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
|
---|---|---|---|---|---|---|---|---|---|
05ecd6101545147495296bb0d57e82f03c0c5d94
|
lualib/mongo.lua
|
lualib/mongo.lua
|
local bson = require "bson"
local socket = require "socket"
local socketchannel = require "socketchannel"
local skynet = require "skynet"
local driver = require "mongo.driver"
local rawget = rawget
local assert = assert
local bson_encode = bson.encode
local bson_encode_order = bson.encode_order
local bson_decode = bson.decode
local empty_bson = bson_encode {}
local mongo = {}
mongo.null = assert(bson.null)
mongo.maxkey = assert(bson.maxkey)
mongo.minkey = assert(bson.minkey)
mongo.type = assert(bson.type)
local mongo_cursor = {}
local cursor_meta = {
__index = mongo_cursor,
}
local mongo_client = {}
local client_meta = {
__index = function(self, key)
return rawget(mongo_client, key) or self:getDB(key)
end,
__tostring = function (self)
local port_string
if self.port then
port_string = ":" .. tostring(self.port)
else
port_string = ""
end
return "[mongo client : " .. self.host .. port_string .."]"
end,
__gc = function(self)
self:disconnect()
end
}
local mongo_db = {}
local db_meta = {
__index = function (self, key)
return rawget(mongo_db, key) or self:getCollection(key)
end,
__tostring = function (self)
return "[mongo db : " .. self.name .. "]"
end
}
local mongo_collection = {}
local collection_meta = {
__index = function(self, key)
return rawget(mongo_collection, key) or self:getCollection(key)
end ,
__tostring = function (self)
return "[mongo collection : " .. self.full_name .. "]"
end
}
local function dispatch_reply(so)
local len_reply = so:read(4)
local reply = so:read(driver.length(len_reply))
local result = {}
local succ, reply_id, document, cursor_id, startfrom = driver.reply(reply, result)
result.document = document
result.cursor_id = cursor_id
result.startfrom = startfrom
result.data = reply
return reply_id, succ, result
end
function mongo.client( obj )
obj.port = obj.port or 27017
obj.__id = 0
obj.__sock = socketchannel.channel {
host = obj.host,
port = obj.port,
response = dispatch_reply,
}
setmetatable(obj, client_meta)
obj.__sock:connect()
return obj
end
function mongo_client:getDB(dbname)
local db = {
connection = self,
name = dbname,
full_name = dbname,
database = false,
__cmd = dbname .. "." .. "$cmd",
}
db.database = db
return setmetatable(db, db_meta)
end
function mongo_client:disconnect()
if self.__sock then
local so = self.__sock
self.__sock = false
so:close()
end
end
function mongo_client:genId()
local id = self.__id + 1
self.__id = id
return id
end
function mongo_client:runCommand(...)
if not self.admin then
self.admin = self:getDB "admin"
end
return self.admin:runCommand(...)
end
function mongo_db:runCommand(cmd,cmd_v,...)
local conn = self.connection
local request_id = conn:genId()
local sock = conn.__sock
local bson_cmd
if not cmd_v then
bson_cmd = bson_encode_order(cmd,1)
else
bson_cmd = bson_encode_order(cmd,cmd_v,...)
end
local pack = driver.query(request_id, 0, self.__cmd, 0, 1, bson_cmd)
local doc = sock:request(pack, request_id).document
return bson_decode(doc)
end
function mongo_db:getCollection(collection)
local col = {
connection = self.connection,
name = collection,
full_name = self.full_name .. "." .. collection,
database = self.database,
}
self[collection] = setmetatable(col, collection_meta)
return col
end
mongo_collection.getCollection = mongo_db.getCollection
function mongo_collection:insert(doc)
if doc._id == nil then
doc._id = bson.objectid()
end
local sock = self.connection.__sock
local pack = driver.insert(0, self.full_name, bson_encode(doc))
-- flags support 1: ContinueOnError
sock:request(pack)
end
function mongo_collection:batch_insert(docs)
for i=1,#docs do
if docs[i]._id == nil then
docs[i]._id = bson.objectid()
end
docs[i] = bson_encode(docs[i])
end
local sock = self.connection.__sock
local pack = driver.insert(0, self.full_name, docs)
sock:request(pack)
end
function mongo_collection:update(selector,update,upsert,multi)
local flags = (upsert and 1 or 0) + (multi and 2 or 0)
local sock = self.connection.__sock
local pack = driver.update(self.full_name, flags, bson_encode(selector), bson_encode(update))
sock:request(pack)
end
function mongo_collection:delete(selector, single)
local sock = self.connection.__sock
local pack = driver.delete(self.full_name, single, bson_encode(selector))
sock:request(pack)
end
function mongo_collection:findOne(query, selector)
local conn = self.connection
local request_id = conn:genId()
local sock = conn.__sock
local pack = driver.query(request_id, 0, self.full_name, 0, 1, query and bson_encode(query) or empty_bson, selector and bson_encode(selector))
local doc = sock:request(pack, request_id).document
return bson_decode(doc)
end
function mongo_collection:find(query, selector)
return setmetatable( {
__collection = self,
__query = query and bson_encode(query) or empty_bson,
__selector = selector and bson_encode(selector),
__ptr = nil,
__data = nil,
__cursor = nil,
__document = {},
__flags = 0,
} , cursor_meta)
end
function mongo_cursor:hasNext()
if self.__ptr == nil then
if self.__document == nil then
return false
end
local conn = self.__collection.connection
local request_id = conn:genId()
local sock = conn.__sock
local pack
if self.__data == nil then
pack = driver.query(request_id, self.__flags, self.__collection.full_name,0,0,self.__query,self.__selector)
else
if self.__cursor then
pack = driver.more(request_id, self.__collection.full_name,0,self.__cursor)
else
-- no more
self.__document = nil
self.__data = nil
return false
end
end
local ok, result = pcall(sock.request,sock,pack, request_id)
local doc = result.document
local cursor = result.cursor_id
if ok then
if doc then
self.__document = doc
self.__data = data
self.__ptr = 1
self.__cursor = cursor
return true
else
self.__document = nil
self.__data = nil
self.__cursor = nil
return false
end
else
self.__document = nil
self.__data = nil
self.__cursor = nil
if doc then
local err = bson_decode(doc)
error(err["$err"])
else
error("Reply from mongod error")
end
end
end
return true
end
function mongo_cursor:next()
if self.__ptr == nil then
error "Call hasNext first"
end
local r = bson_decode(self.__document[self.__ptr])
self.__ptr = self.__ptr + 1
if self.__ptr > #self.__document then
self.__ptr = nil
end
return r
end
function mongo_cursor:close()
-- todo: warning hasNext after close
if self.__cursor then
local sock = self.__collection.connection.__sock
local pack = driver.kill(self.__cursor)
sock:request(pack)
end
end
return mongo
|
local bson = require "bson"
local socket = require "socket"
local socketchannel = require "socketchannel"
local skynet = require "skynet"
local driver = require "mongo.driver"
local rawget = rawget
local assert = assert
local bson_encode = bson.encode
local bson_encode_order = bson.encode_order
local bson_decode = bson.decode
local empty_bson = bson_encode {}
local mongo = {}
mongo.null = assert(bson.null)
mongo.maxkey = assert(bson.maxkey)
mongo.minkey = assert(bson.minkey)
mongo.type = assert(bson.type)
local mongo_cursor = {}
local cursor_meta = {
__index = mongo_cursor,
}
local mongo_client = {}
local client_meta = {
__index = function(self, key)
return rawget(mongo_client, key) or self:getDB(key)
end,
__tostring = function (self)
local port_string
if self.port then
port_string = ":" .. tostring(self.port)
else
port_string = ""
end
return "[mongo client : " .. self.host .. port_string .."]"
end,
__gc = function(self)
self:disconnect()
end
}
local mongo_db = {}
local db_meta = {
__index = function (self, key)
return rawget(mongo_db, key) or self:getCollection(key)
end,
__tostring = function (self)
return "[mongo db : " .. self.name .. "]"
end
}
local mongo_collection = {}
local collection_meta = {
__index = function(self, key)
return rawget(mongo_collection, key) or self:getCollection(key)
end ,
__tostring = function (self)
return "[mongo collection : " .. self.full_name .. "]"
end
}
local function dispatch_reply(so)
local len_reply = so:read(4)
local reply = so:read(driver.length(len_reply))
local result = { result = {} }
local succ, reply_id, document, cursor_id, startfrom = driver.reply(reply, result.result)
result.document = document
result.cursor_id = cursor_id
result.startfrom = startfrom
result.data = reply
return reply_id, succ, result
end
function mongo.client( obj )
obj.port = obj.port or 27017
obj.__id = 0
obj.__sock = socketchannel.channel {
host = obj.host,
port = obj.port,
response = dispatch_reply,
}
setmetatable(obj, client_meta)
obj.__sock:connect()
return obj
end
function mongo_client:getDB(dbname)
local db = {
connection = self,
name = dbname,
full_name = dbname,
database = false,
__cmd = dbname .. "." .. "$cmd",
}
db.database = db
return setmetatable(db, db_meta)
end
function mongo_client:disconnect()
if self.__sock then
local so = self.__sock
self.__sock = false
so:close()
end
end
function mongo_client:genId()
local id = self.__id + 1
self.__id = id
return id
end
function mongo_client:runCommand(...)
if not self.admin then
self.admin = self:getDB "admin"
end
return self.admin:runCommand(...)
end
function mongo_db:runCommand(cmd,cmd_v,...)
local conn = self.connection
local request_id = conn:genId()
local sock = conn.__sock
local bson_cmd
if not cmd_v then
bson_cmd = bson_encode_order(cmd,1)
else
bson_cmd = bson_encode_order(cmd,cmd_v,...)
end
local pack = driver.query(request_id, 0, self.__cmd, 0, 1, bson_cmd)
local doc = sock:request(pack, request_id).document
return bson_decode(doc)
end
function mongo_db:getCollection(collection)
local col = {
connection = self.connection,
name = collection,
full_name = self.full_name .. "." .. collection,
database = self.database,
}
self[collection] = setmetatable(col, collection_meta)
return col
end
mongo_collection.getCollection = mongo_db.getCollection
function mongo_collection:insert(doc)
if doc._id == nil then
doc._id = bson.objectid()
end
local sock = self.connection.__sock
local pack = driver.insert(0, self.full_name, bson_encode(doc))
-- flags support 1: ContinueOnError
sock:request(pack)
end
function mongo_collection:batch_insert(docs)
for i=1,#docs do
if docs[i]._id == nil then
docs[i]._id = bson.objectid()
end
docs[i] = bson_encode(docs[i])
end
local sock = self.connection.__sock
local pack = driver.insert(0, self.full_name, docs)
sock:request(pack)
end
function mongo_collection:update(selector,update,upsert,multi)
local flags = (upsert and 1 or 0) + (multi and 2 or 0)
local sock = self.connection.__sock
local pack = driver.update(self.full_name, flags, bson_encode(selector), bson_encode(update))
sock:request(pack)
end
function mongo_collection:delete(selector, single)
local sock = self.connection.__sock
local pack = driver.delete(self.full_name, single, bson_encode(selector))
sock:request(pack)
end
function mongo_collection:findOne(query, selector)
local conn = self.connection
local request_id = conn:genId()
local sock = conn.__sock
local pack = driver.query(request_id, 0, self.full_name, 0, 1, query and bson_encode(query) or empty_bson, selector and bson_encode(selector))
local doc = sock:request(pack, request_id).document
return bson_decode(doc)
end
function mongo_collection:find(query, selector)
return setmetatable( {
__collection = self,
__query = query and bson_encode(query) or empty_bson,
__selector = selector and bson_encode(selector),
__ptr = nil,
__data = nil,
__cursor = nil,
__document = {},
__flags = 0,
} , cursor_meta)
end
function mongo_cursor:hasNext()
if self.__ptr == nil then
if self.__document == nil then
return false
end
local conn = self.__collection.connection
local request_id = conn:genId()
local sock = conn.__sock
local pack
if self.__data == nil then
pack = driver.query(request_id, self.__flags, self.__collection.full_name,0,0,self.__query,self.__selector)
else
if self.__cursor then
pack = driver.more(request_id, self.__collection.full_name,0,self.__cursor)
else
-- no more
self.__document = nil
self.__data = nil
return false
end
end
local ok, result = pcall(sock.request,sock,pack, request_id)
local doc = result.document
local cursor = result.cursor_id
if ok then
if doc then
self.__document = result.result
self.__data = result.data
self.__ptr = 1
self.__cursor = cursor
return true
else
self.__document = nil
self.__data = nil
self.__cursor = nil
return false
end
else
self.__document = nil
self.__data = nil
self.__cursor = nil
if doc then
local err = bson_decode(doc)
error(err["$err"])
else
error("Reply from mongod error")
end
end
end
return true
end
function mongo_cursor:next()
if self.__ptr == nil then
error "Call hasNext first"
end
local r = bson_decode(self.__document[self.__ptr])
self.__ptr = self.__ptr + 1
if self.__ptr > #self.__document then
self.__ptr = nil
end
return r
end
function mongo_cursor:close()
-- todo: warning hasNext after close
if self.__cursor then
local sock = self.__collection.connection.__sock
local pack = driver.kill(self.__cursor)
sock:request(pack)
end
end
return mongo
|
bugfix: mongo driver, reply result
|
bugfix: mongo driver, reply result
|
Lua
|
mit
|
microcai/skynet,zzh442856860/skynet,lynx-seu/skynet,winglsh/skynet,lynx-seu/skynet,yunGit/skynet,chfg007/skynet,cpascal/skynet,kyle-wang/skynet,qyli/test,jxlczjp77/skynet,Ding8222/skynet,u20024804/skynet,fztcjjl/skynet,LiangMa/skynet,MRunFoss/skynet,xinmingyao/skynet,fztcjjl/skynet,xjdrew/skynet,asanosoyokaze/skynet,zhouxiaoxiaoxujian/skynet,vizewang/skynet,iskygame/skynet,qyli/test,nightcj/mmo,letmefly/skynet,kyle-wang/skynet,enulex/skynet,sundream/skynet,peimin/skynet,longmian/skynet,ilylia/skynet,ypengju/skynet_comment,zzh442856860/skynet-Note,zhangshiqian1214/skynet,letmefly/skynet,rainfiel/skynet,helling34/skynet,lc412/skynet,dymx101/skynet,jxlczjp77/skynet,dymx101/skynet,ludi1991/skynet,codingabc/skynet,Ding8222/skynet,korialuo/skynet,chfg007/skynet,ag6ag/skynet,enulex/skynet,chenjiansnail/skynet,leezhongshan/skynet,xinjuncoding/skynet,cloudwu/skynet,chuenlungwang/skynet,gitfancode/skynet,ypengju/skynet_comment,JiessieDawn/skynet,MRunFoss/skynet,KAndQ/skynet,Markal128/skynet,chuenlungwang/skynet,fztcjjl/skynet,peimin/skynet,zzh442856860/skynet,bigrpg/skynet,LuffyPan/skynet,Markal128/skynet,sdgdsffdsfff/skynet,togolwb/skynet,helling34/skynet,qyli/test,longmian/skynet,leezhongshan/skynet,peimin/skynet_v0.1_with_notes,xinjuncoding/skynet,cmingjian/skynet,czlc/skynet,korialuo/skynet,zhangshiqian1214/skynet,MetSystem/skynet,microcai/skynet,zhoukk/skynet,puXiaoyi/skynet,asanosoyokaze/skynet,jiuaiwo1314/skynet,xinmingyao/skynet,rainfiel/skynet,zzh442856860/skynet-Note,winglsh/skynet,firedtoad/skynet,bigrpg/skynet,great90/skynet,liuxuezhan/skynet,ludi1991/skynet,xcjmine/skynet,peimin/skynet_v0.1_with_notes,enulex/skynet,liuxuezhan/skynet,ruleless/skynet,codingabc/skynet,ilylia/skynet,xjdrew/skynet,microcai/skynet,cuit-zhaxin/skynet,javachengwc/skynet,ruleless/skynet,boyuegame/skynet,cuit-zhaxin/skynet,wangyi0226/skynet,icetoggle/skynet,your-gatsby/skynet,xubigshu/skynet,iskygame/skynet,bingo235/skynet,bttscut/skynet,helling34/skynet,korialuo/skynet,qyli/test,icetoggle/skynet,kyle-wang/skynet,puXiaoyi/skynet,ruleless/skynet,vizewang/skynet,zhoukk/skynet,ludi1991/skynet,LiangMa/skynet,pichina/skynet,boyuegame/skynet,dymx101/skynet,MoZhonghua/skynet,ludi1991/skynet,zhangshiqian1214/skynet,kebo/skynet,felixdae/skynet,leezhongshan/skynet,matinJ/skynet,gitfancode/skynet,firedtoad/skynet,samael65535/skynet,cdd990/skynet,togolwb/skynet,cmingjian/skynet,cloudwu/skynet,bingo235/skynet,jiuaiwo1314/skynet,LuffyPan/skynet,JiessieDawn/skynet,sdgdsffdsfff/skynet,xcjmine/skynet,bttscut/skynet,puXiaoyi/skynet,fhaoquan/skynet,jiuaiwo1314/skynet,asanosoyokaze/skynet,great90/skynet,matinJ/skynet,hongling0/skynet,cuit-zhaxin/skynet,wangyi0226/skynet,pigparadise/skynet,hongling0/skynet,yinjun322/skynet,letmefly/skynet,u20024804/skynet,u20024804/skynet,pichina/skynet,samael65535/skynet,icetoggle/skynet,harryzeng/skynet,fhaoquan/skynet,catinred2/skynet,czlc/skynet,sundream/skynet,liuxuezhan/skynet,zhangshiqian1214/skynet,chuenlungwang/skynet,pigparadise/skynet,Zirpon/skynet,pigparadise/skynet,yinjun322/skynet,pichina/skynet,liuxuezhan/skynet,longmian/skynet,zhouxiaoxiaoxujian/skynet,harryzeng/skynet,plsytj/skynet,lawnight/skynet,letmefly/skynet,sanikoyes/skynet,lawnight/skynet,javachengwc/skynet,KittyCookie/skynet,lc412/skynet,firedtoad/skynet,felixdae/skynet,sundream/skynet,Ding8222/skynet,LuffyPan/skynet,jxlczjp77/skynet,ypengju/skynet_comment,zhangshiqian1214/skynet,KAndQ/skynet,sanikoyes/skynet,zhaijialong/skynet,harryzeng/skynet,hongling0/skynet,chfg007/skynet,MoZhonghua/skynet,wangjunwei01/skynet,xjdrew/skynet,bigrpg/skynet,chenjiansnail/skynet,cdd990/skynet,MRunFoss/skynet,fhaoquan/skynet,boyuegame/skynet,xcjmine/skynet,QuiQiJingFeng/skynet,bttscut/skynet,javachengwc/skynet,JiessieDawn/skynet,kebo/skynet,MoZhonghua/skynet,vizewang/skynet,lc412/skynet,sanikoyes/skynet,lynx-seu/skynet,ilylia/skynet,nightcj/mmo,gitfancode/skynet,zhaijialong/skynet,zhangshiqian1214/skynet,ag6ag/skynet,Markal128/skynet,QuiQiJingFeng/skynet,rainfiel/skynet,Zirpon/skynet,chenjiansnail/skynet,your-gatsby/skynet,bingo235/skynet,KittyCookie/skynet,czlc/skynet,winglsh/skynet,yunGit/skynet,cdd990/skynet,MetSystem/skynet,zhoukk/skynet,MetSystem/skynet,kebo/skynet,KAndQ/skynet,plsytj/skynet,iskygame/skynet,wangyi0226/skynet,lawnight/skynet,xinjuncoding/skynet,catinred2/skynet,zhouxiaoxiaoxujian/skynet,cmingjian/skynet,zzh442856860/skynet-Note,plsytj/skynet,great90/skynet,QuiQiJingFeng/skynet,zhaijialong/skynet,cloudwu/skynet,zzh442856860/skynet-Note,xubigshu/skynet,nightcj/mmo,matinJ/skynet,samael65535/skynet,zzh442856860/skynet,ag6ag/skynet,wangjunwei01/skynet,wangjunwei01/skynet,felixdae/skynet,LiangMa/skynet,catinred2/skynet,togolwb/skynet,sdgdsffdsfff/skynet,yunGit/skynet,codingabc/skynet,yinjun322/skynet,KittyCookie/skynet,your-gatsby/skynet,cpascal/skynet,Zirpon/skynet,lawnight/skynet,cpascal/skynet
|
05027485d2a7140b371a34ad1d647a87fbe38d0a
|
makefiles/premake/RendererModules/OpenGLGUIRenderer/premake.lua
|
makefiles/premake/RendererModules/OpenGLGUIRenderer/premake.lua
|
--
-- OpenGLGUIRenderer premake script
--
cegui_dynamic("OpenGLGUIRenderer")
package.files =
{
matchfiles(pkgdir.."*.cpp"),
matchfiles(pkgdir.."*.h"),
}
include(pkgdir)
include(rootdir)
library("OpenGL32")
library("GLU32")
dependency("CEGUIBase")
if OPENGL_IMAGECODEC == "devil" then
dependency("CEGUIDevILImageCodec")
define("USE_DEVIL_LIBRARY")
elseif OPENGL_IMAGECODEC == "freeimage" then
library("FreeImage", "d")
dependency("CEGUIFreeImageImageCodec")
define("USE_FREEIMAGE_LIBRARY")
elseif OPENGL_IMAGECODEC == "corona" then
library("corona", "_d")
dependency("CEGUICoronaImageCodec")
define("USE_CORONA_LIBRARY")
elseif OPENGL_IMAGECODEC == "silly" then
library("SILLY", "_d")
dependency("CEGUISILLYImageCodec")
define("USE_SILLY_LIBRARY")
else
dependency("CEGUITGAImageCodec")
end
define("OPENGL_GUIRENDERER_EXPORTS")
|
--
-- OpenGLGUIRenderer premake script
--
cegui_dynamic("OpenGLGUIRenderer")
package.files =
{
matchfiles(pkgdir.."*.cpp"),
matchfiles(pkgdir.."*.h"),
}
include(pkgdir)
include(rootdir)
if windows then
library("OpenGL32")
library("GLU32")
define("NOMINMAX")
end
dependency("CEGUIBase")
if OPENGL_IMAGECODEC == "devil" then
dependency("CEGUIDevILImageCodec")
define("USE_DEVIL_LIBRARY")
elseif OPENGL_IMAGECODEC == "freeimage" then
library("FreeImage", "d")
dependency("CEGUIFreeImageImageCodec")
define("USE_FREEIMAGE_LIBRARY")
elseif OPENGL_IMAGECODEC == "corona" then
library("corona", "_d")
dependency("CEGUICoronaImageCodec")
define("USE_CORONA_LIBRARY")
elseif OPENGL_IMAGECODEC == "silly" then
library("SILLY", "_d")
dependency("CEGUISILLYImageCodec")
define("USE_SILLY_LIBRARY")
else
dependency("CEGUITGAImageCodec")
end
define("OPENGL_GUIRENDERER_EXPORTS")
|
Bug fix: Apparently in some cases OpenGLRenderer needs NOMINMAX in Win32 (Mantis #63)
|
Bug fix: Apparently in some cases OpenGLRenderer needs NOMINMAX in Win32 (Mantis #63)
|
Lua
|
mit
|
arkana-fts/cegui,cbeck88/cegui-mirror,arkana-fts/cegui,RealityFactory/CEGUI,RealityFactory/CEGUI,arkana-fts/cegui,RealityFactory/CEGUI,cbeck88/cegui-mirror,cbeck88/cegui-mirror,RealityFactory/CEGUI,arkana-fts/cegui,RealityFactory/CEGUI,arkana-fts/cegui,cbeck88/cegui-mirror,cbeck88/cegui-mirror
|
cf772a9dfc17178dc90fb26c9e5a091f84d00a90
|
src/servicebag/src/Shared/ServiceBag.lua
|
src/servicebag/src/Shared/ServiceBag.lua
|
--[=[
Service bags handle recursive initialization of services, and the
retrieval of services from a given source. This allows the composition
of services without the initialization of those services becoming a pain,
which makes refactoring downstream services very easy.
This also allows multiple copies of a service to exist at once, although
many services right now are not designed for this.
```lua
local serviceBag = ServiceBag.new()
serviceBag:GetService({
Init = function(self)
print("Service initialized")
end;
})
serviceBag:Init()
serviceBag:Start()
```
@class ServiceBag
]=]
local require = require(script.Parent.loader).load(script)
local Signal = require("Signal")
local BaseObject = require("BaseObject")
--[=[
@interface Service
.Init: function?
.Start: function?
.Destroy: function?
@within ServiceBag
]=]
--[=[
@type ServiceType Service | ModuleScript
@within ServiceBag
]=]
local ServiceBag = setmetatable({}, BaseObject)
ServiceBag.ClassName = "ServiceBag"
ServiceBag.__index = ServiceBag
--[=[
Constructs a new ServiceBag
@param parentProvider ServiceBag? -- Optional parent provider to find services in
@return ServiceBag
]=]
function ServiceBag.new(parentProvider)
local self = setmetatable(BaseObject.new(), ServiceBag)
self._services = {}
self._parentProvider = parentProvider
self._serviceTypesToInitializeSet = {}
self._initializedServiceTypeSet = {}
self._initializing = false
self._serviceTypesToStart = {}
self._destroying = Signal.new()
self._maid:GiveTask(self._destroying)
return self
end
--[=[
Returns whether the value is a serviceBag
@param value ServiceBag?
@return boolean
]=]
function ServiceBag.isServiceBag(value)
return type(value) == "table"
and value.ClassName == "ServiceBag"
end
--[=[
Retrieves the service, ensuring initialization if we are in
the initialization phase.
@param serviceType ServiceType
@return any
]=]
function ServiceBag:GetService(serviceType)
if typeof(serviceType) == "Instance" then
serviceType = require(serviceType)
end
assert(type(serviceType) == "table", "Bad serviceType definition")
local service = self._services[serviceType]
if service then
self:_ensureInitialization(serviceType)
return self._services[serviceType]
else
if self._parentProvider then
return self._parentProvider:GetService(serviceType)
end
-- Try to add the service if we're still initializing services
self:_addServiceType(serviceType)
self:_ensureInitialization(serviceType)
return self._services[serviceType]
end
end
--[=[
Returns whether the service bag has the service.
@param serviceType ServiceType
@return boolean
]=]
function ServiceBag:HasService(serviceType)
if self._services[serviceType] then
return true
else
return false
end
end
--[=[
Initializes the service bag and ensures recursive initialization
can occur
]=]
function ServiceBag:Init()
assert(not self._initializing, "Already initializing")
assert(self._serviceTypesToInitializeSet, "Already initialized")
self._initializing = true
while next(self._serviceTypesToInitializeSet) do
local serviceType = next(self._serviceTypesToInitializeSet)
self._serviceTypesToInitializeSet[serviceType] = nil
self:_ensureInitialization(serviceType)
end
self._serviceTypesToInitializeSet = nil
self._initializing = false
end
--[=[
Starts the service bag and all services
]=]
function ServiceBag:Start()
assert(self._serviceTypesToStart, "Already started")
assert(not self._initializing, "Still initializing")
while next(self._serviceTypesToStart) do
local serviceType = table.remove(self._serviceTypesToStart)
local service = assert(self._services[serviceType], "No service")
if service.Start then
local current
task.spawn(function()
current = coroutine.running()
service:Start()
end)
assert(coroutine.status(current) == "dead", "Starting service yielded")
end
end
self._serviceTypesToStart = nil
end
--[=[
Creates a scoped service bag, where services within the scope will not
be accessible outside of the scope.
@return ServiceBag
]=]
function ServiceBag:CreateScope()
local provider = ServiceBag.new(self)
self:_addServiceType(provider)
-- Remove from parent provider
self._maid[provider] = provider._destroying:Connect(function()
self._maid[provider] = nil
self._services[provider] = nil
end)
return provider
end
-- Adds a service to this provider only
function ServiceBag:_addServiceType(serviceType)
if not self._serviceTypesToInitializeSet then
error(("Already finished initializing, cannot add %q"):format(tostring(serviceType)))
return
end
-- Already added
if self._services[serviceType] then
return
end
-- Construct a new version of this service so we're isolated
local service = setmetatable({}, { __index = serviceType })
self._services[serviceType] = service
self:_ensureInitialization(serviceType)
end
function ServiceBag:_ensureInitialization(serviceType)
if self._initializedServiceTypeSet[serviceType] then
return
end
if self._initializing then
self._serviceTypesToInitializeSet[serviceType] = nil
self._initializedServiceTypeSet[serviceType] = true
self:_initService(serviceType)
elseif self._serviceTypesToInitializeSet then
self._serviceTypesToInitializeSet[serviceType] = true
else
error("[ServiceBag._ensureInitialization] - Cannot initialize past initializing phase ")
end
end
function ServiceBag:_initService(serviceType)
local service = assert(self._services[serviceType], "No service")
if service.Init then
local current
task.spawn(function()
current = coroutine.running()
service:Init(self)
end)
assert(coroutine.status(current) == "dead", "Initializing service yielded")
end
table.insert(self._serviceTypesToStart, serviceType)
end
--[=[
Cleans up the service bag and all services that have been
initialized in the service bag.
]=]
function ServiceBag:Destroy()
local super = getmetatable(ServiceBag)
self._destroying:Fire()
local services = self._services
local key, service = next(services)
while service ~= nil do
services[key] = nil
if service.Destroy then
service:Destroy()
end
key, service = next(services)
end
super.Destroy(self)
end
return ServiceBag
|
--[=[
Service bags handle recursive initialization of services, and the
retrieval of services from a given source. This allows the composition
of services without the initialization of those services becoming a pain,
which makes refactoring downstream services very easy.
This also allows multiple copies of a service to exist at once, although
many services right now are not designed for this.
```lua
local serviceBag = ServiceBag.new()
serviceBag:GetService({
Init = function(self)
print("Service initialized")
end;
})
serviceBag:Init()
serviceBag:Start()
```
@class ServiceBag
]=]
local require = require(script.Parent.loader).load(script)
local Signal = require("Signal")
local BaseObject = require("BaseObject")
--[=[
@interface Service
.Init: function?
.Start: function?
.Destroy: function?
@within ServiceBag
]=]
--[=[
@type ServiceType Service | ModuleScript
@within ServiceBag
]=]
local ServiceBag = setmetatable({}, BaseObject)
ServiceBag.ClassName = "ServiceBag"
ServiceBag.__index = ServiceBag
--[=[
Constructs a new ServiceBag
@param parentProvider ServiceBag? -- Optional parent provider to find services in
@return ServiceBag
]=]
function ServiceBag.new(parentProvider)
local self = setmetatable(BaseObject.new(), ServiceBag)
self._services = {}
self._parentProvider = parentProvider
self._serviceTypesToInitializeSet = {}
self._initializedServiceTypeSet = {}
self._initializing = false
self._serviceTypesToStart = {}
self._destroying = Signal.new()
self._maid:GiveTask(self._destroying)
return self
end
--[=[
Returns whether the value is a serviceBag
@param value ServiceBag?
@return boolean
]=]
function ServiceBag.isServiceBag(value)
return type(value) == "table"
and value.ClassName == "ServiceBag"
end
--[=[
Retrieves the service, ensuring initialization if we are in
the initialization phase.
@param serviceType ServiceType
@return any
]=]
function ServiceBag:GetService(serviceType)
if typeof(serviceType) == "Instance" then
serviceType = require(serviceType)
end
assert(type(serviceType) == "table", "Bad serviceType definition")
local service = self._services[serviceType]
if service then
self:_ensureInitialization(serviceType)
return self._services[serviceType]
else
if self._parentProvider then
return self._parentProvider:GetService(serviceType)
end
-- Try to add the service if we're still initializing services
self:_addServiceType(serviceType)
self:_ensureInitialization(serviceType)
return self._services[serviceType]
end
end
--[=[
Returns whether the service bag has the service.
@param serviceType ServiceType
@return boolean
]=]
function ServiceBag:HasService(serviceType)
if typeof(serviceType) == "Instance" then
serviceType = require(serviceType)
end
if self._services[serviceType] then
return true
else
return false
end
end
--[=[
Initializes the service bag and ensures recursive initialization
can occur
]=]
function ServiceBag:Init()
assert(not self._initializing, "Already initializing")
assert(self._serviceTypesToInitializeSet, "Already initialized")
self._initializing = true
while next(self._serviceTypesToInitializeSet) do
local serviceType = next(self._serviceTypesToInitializeSet)
self._serviceTypesToInitializeSet[serviceType] = nil
self:_ensureInitialization(serviceType)
end
self._serviceTypesToInitializeSet = nil
self._initializing = false
end
--[=[
Starts the service bag and all services
]=]
function ServiceBag:Start()
assert(self._serviceTypesToStart, "Already started")
assert(not self._initializing, "Still initializing")
while next(self._serviceTypesToStart) do
local serviceType = table.remove(self._serviceTypesToStart)
local service = assert(self._services[serviceType], "No service")
if service.Start then
local current
task.spawn(function()
current = coroutine.running()
service:Start()
end)
assert(coroutine.status(current) == "dead", "Starting service yielded")
end
end
self._serviceTypesToStart = nil
end
--[=[
Creates a scoped service bag, where services within the scope will not
be accessible outside of the scope.
@return ServiceBag
]=]
function ServiceBag:CreateScope()
local provider = ServiceBag.new(self)
self:_addServiceType(provider)
-- Remove from parent provider
self._maid[provider] = provider._destroying:Connect(function()
self._maid[provider] = nil
self._services[provider] = nil
end)
return provider
end
-- Adds a service to this provider only
function ServiceBag:_addServiceType(serviceType)
if not self._serviceTypesToInitializeSet then
error(("Already finished initializing, cannot add %q"):format(tostring(serviceType)))
return
end
-- Already added
if self._services[serviceType] then
return
end
-- Construct a new version of this service so we're isolated
local service = setmetatable({}, { __index = serviceType })
self._services[serviceType] = service
self:_ensureInitialization(serviceType)
end
function ServiceBag:_ensureInitialization(serviceType)
if self._initializedServiceTypeSet[serviceType] then
return
end
if self._initializing then
self._serviceTypesToInitializeSet[serviceType] = nil
self._initializedServiceTypeSet[serviceType] = true
self:_initService(serviceType)
elseif self._serviceTypesToInitializeSet then
self._serviceTypesToInitializeSet[serviceType] = true
else
error("[ServiceBag._ensureInitialization] - Cannot initialize past initializing phase ")
end
end
function ServiceBag:_initService(serviceType)
local service = assert(self._services[serviceType], "No service")
if service.Init then
local current
task.spawn(function()
current = coroutine.running()
service:Init(self)
end)
assert(coroutine.status(current) == "dead", "Initializing service yielded")
end
table.insert(self._serviceTypesToStart, serviceType)
end
--[=[
Cleans up the service bag and all services that have been
initialized in the service bag.
]=]
function ServiceBag:Destroy()
local super = getmetatable(ServiceBag)
self._destroying:Fire()
local services = self._services
local key, service = next(services)
while service ~= nil do
services[key] = nil
if service.Destroy then
service:Destroy()
end
key, service = next(services)
end
super.Destroy(self)
end
return ServiceBag
|
fix: ServiceBag:HasService allows for serviceType definitions that are instances
|
fix: ServiceBag:HasService allows for serviceType definitions that are instances
|
Lua
|
mit
|
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
|
7ccaba4f7ff0c00412961d03a7f0a03ae812a1f6
|
plugins/hackernews.lua
|
plugins/hackernews.lua
|
--[[
Based on a plugin by topkecleon.
Copyright 2017 wrxck <[email protected]>
This code is licensed under the MIT. See LICENSE for details.
]]--
local hackernews = {}
local mattata = require('mattata')
local https = require('ssl.https')
local json = require('dkjson')
function hackernews:init(configuration)
hackernews.arguments = 'hackernews'
hackernews.commands = mattata.commands(
self.info.username,
configuration.command_prefix
):command('hackernews'):command('hn').table
hackernews.help = configuration.command_prefix .. 'hackernews - Sends the top stories from Hacker News. Alias: ' .. configuration.command_prefix .. 'hn.'
end
function hackernews.get_results(hackernews_topstories, hackernews_result, hackernews_article)
local results = {}
local jstr, res = https.request(hackernews_topstories)
if res ~= 200 then
return false
end
local jdat = json.decode(jstr)
for i = 1, 8 do
local result_jstr, result_res = https.request(hackernews_result:format(jdat[i]))
if result_res ~= 200 then
return false
end
local result_jdat = json.decode(ijstr)
local result = ''
if result_jdat.url then
result = string.format(
'\n• <code>[</code><a href="%s">%s</a><code>]</code> <a href="%s">%s</a>',
mattata.escape_html(hackernews_article:format(result_jdat.id)),
result_jdat.id,
mattata.escape_html(result_jdat.url),
mattata.escape_html(result_jdat.title)
)
else
result = string.format(
'\n• <code>[</code><a href="%s">%s</a><code>]</code> %s',
mattata.escape_html(hackernews_article:format(result_jdat.id)),
result_jdat.id,
mattata.escape_html(result_jdat.title)
)
end
table.insert(
results,
result
)
end
return results
end
function hackernews:on_message(message, configuration, language)
local results = hackernews.get_results('https://hacker-news.firebaseio.com/v0/topstories.json', 'https://hacker-news.firebaseio.com/v0/item/%s.json', 'https://news.ycombinator.com/item?id=%s')
if not results then
return mattata.send_reply(
message,
language.errors.connection
)
end
local result_count = message.chat.id == message.from.id and 8 or 4
local output = '<b>Top Stories from Hacker News:</b>'
for i = 1, result_count do
output = output .. results[i]
end
mattata.send_chat_action(
message.chat.id,
'typing'
)
return mattata.send_message(
message.chat.id,
output,
'html'
)
end
return hackernews
|
--[[
Based on a plugin by topkecleon.
Copyright 2017 wrxck <[email protected]>
This code is licensed under the MIT. See LICENSE for details.
]]--
local hackernews = {}
local mattata = require('mattata')
local https = require('ssl.https')
local json = require('dkjson')
function hackernews:init(configuration)
hackernews.arguments = 'hackernews'
hackernews.commands = mattata.commands(
self.info.username,
configuration.command_prefix
):command('hackernews'):command('hn').table
hackernews.help = configuration.command_prefix .. 'hackernews - Sends the top stories from Hacker News. Alias: ' .. configuration.command_prefix .. 'hn.'
end
function hackernews.get_results(hackernews_topstories, hackernews_result, hackernews_article)
local results = {}
local jstr, res = https.request(hackernews_topstories)
if res ~= 200 then
return false
end
local jdat = json.decode(jstr)
for i = 1, 8 do
hackernews_result = string.format(
hackernews_result,
jdat[i]
)
local result_jstr, result_res = https.request(hackernews_result)
if result_res ~= 200 then
return false
end
local result_jdat = json.decode(result_jstr)
local result
hackernews_article = string.format(
hackernews_article,
result_jdat.id
)
if result_jdat.url then
result = string.format(
'\n• <code>[</code><a href="%s">%s</a><code>]</code> <a href="%s">%s</a>',
mattata.escape_html(hackernews_article),
result_jdat.id,
mattata.escape_html(result_jdat.url),
mattata.escape_html(result_jdat.title)
)
else
result = string.format(
'\n• <code>[</code><a href="%s">%s</a><code>]</code> %s',
mattata.escape_html(hackernews_article),
result_jdat.id,
mattata.escape_html(result_jdat.title)
)
end
table.insert(
results,
result
)
end
return results
end
function hackernews:on_message(message, configuration, language)
local results = hackernews.get_results('https://hacker-news.firebaseio.com/v0/topstories.json', 'https://hacker-news.firebaseio.com/v0/item/%s.json', 'https://news.ycombinator.com/item?id=%s')
if not results then
return mattata.send_reply(
message,
language.errors.connection
)
end
local result_count = message.chat.id == message.from.id and 8 or 4
local output = '<b>Top Stories from Hacker News:</b>'
for i = 1, result_count do
output = output .. results[i]
end
mattata.send_chat_action(
message.chat.id,
'typing'
)
return mattata.send_message(
message.chat.id,
output,
'html'
)
end
return hackernews
|
[v8.1] Bug fix
|
[v8.1] Bug fix
|
Lua
|
mit
|
barreeeiroo/BarrePolice
|
816eb9520e45917607e8e4ac8e4132a19e98ac7e
|
protocols/core/luasrc/model/cbi/admin_network/proto_dhcp.lua
|
protocols/core/luasrc/model/cbi/admin_network/proto_dhcp.lua
|
--[[
LuCI - Lua Configuration Interface
Copyright 2011-2012 Jo-Philipp Wich <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
]]--
local map, section, net = ...
local ifc = net:get_interface()
local hostname, accept_ra, send_rs
local bcast, no_gw, peerdns, dns, metric, clientid, vendorclass
hostname = section:taboption("general", Value, "hostname",
translate("Hostname to send when requesting DHCP"))
hostname.placeholder = luci.sys.hostname()
hostname.datatype = "hostname"
if luci.model.network:has_ipv6() then
accept_ra = s:taboption("general", Flag, "accept_ra", translate("Accept router advertisements"))
accept_ra.default = accept_ra.enabled
send_rs = s:taboption("general", Flag, "send_rs", translate("Send router solicitations"))
send_rs.default = send_rs.disabled
send_rs:depends("accept_ra", "")
end
bcast = section:taboption("advanced", Flag, "broadcast",
translate("Use broadcast flag"),
translate("Required for certain ISPs, e.g. Charter with DOCSIS 3"))
bcast.default = bcast.disabled
no_gw = section:taboption("advanced", Flag, "gateway",
translate("Use default gateway"),
translate("If unchecked, no default route is configured"))
no_gw.default = no_gw.enabled
function no_gw.cfgvalue(...)
return Flag.cfgvalue(...) == "0.0.0.0" and "0" or "1"
end
function no_gw.write(self, section, value)
if value == "1" then
m:set(section, "gateway", nil)
else
m:set(section, "gateway", "0.0.0.0")
end
end
peerdns = section:taboption("advanced", Flag, "peerdns",
translate("Use DNS servers advertised by peer"),
translate("If unchecked, the advertised DNS server addresses are ignored"))
peerdns.default = peerdns.enabled
dns = section:taboption("advanced", DynamicList, "dns",
translate("Use custom DNS servers"))
dns:depends("peerdns", "")
dns.datatype = "ipaddr"
dns.cast = "string"
metric = section:taboption("advanced", Value, "metric",
translate("Use gateway metric"))
metric.placeholder = "0"
metric.datatype = "uinteger"
metric:depends("gateway", "1")
clientid = section:taboption("advanced", Value, "clientid",
translate("Client ID to send when requesting DHCP"))
vendorclass = section:taboption("advanced", Value, "vendorid",
translate("Vendor Class to send when requesting DHCP"))
macaddr = section:taboption("advanced", Value, "macaddr", translate("Override MAC address"))
macaddr.placeholder = ifc and ifc:mac() or "00:00:00:00:00:00"
macaddr.datatype = "macaddr"
mtu = section:taboption("advanced", Value, "mtu", translate("Override MTU"))
mtu.placeholder = "1500"
mtu.datatype = "max(1500)"
|
--[[
LuCI - Lua Configuration Interface
Copyright 2011-2012 Jo-Philipp Wich <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
]]--
local map, section, net = ...
local ifc = net:get_interface()
local hostname, accept_ra, send_rs
local bcast, defaultroute, peerdns, dns, metric, clientid, vendorclass
hostname = section:taboption("general", Value, "hostname",
translate("Hostname to send when requesting DHCP"))
hostname.placeholder = luci.sys.hostname()
hostname.datatype = "hostname"
if luci.model.network:has_ipv6() then
accept_ra = s:taboption("general", Flag, "accept_ra", translate("Accept router advertisements"))
accept_ra.default = accept_ra.enabled
send_rs = s:taboption("general", Flag, "send_rs", translate("Send router solicitations"))
send_rs.default = send_rs.disabled
send_rs:depends("accept_ra", "")
end
bcast = section:taboption("advanced", Flag, "broadcast",
translate("Use broadcast flag"),
translate("Required for certain ISPs, e.g. Charter with DOCSIS 3"))
bcast.default = bcast.disabled
defaultroute = section:taboption("advanced", Flag, "gateway",
translate("Use default gateway"),
translate("If unchecked, no default route is configured"))
defaultroute.default = defaultroute.enabled
peerdns = section:taboption("advanced", Flag, "peerdns",
translate("Use DNS servers advertised by peer"),
translate("If unchecked, the advertised DNS server addresses are ignored"))
peerdns.default = peerdns.enabled
dns = section:taboption("advanced", DynamicList, "dns",
translate("Use custom DNS servers"))
dns:depends("peerdns", "")
dns.datatype = "ipaddr"
dns.cast = "string"
metric = section:taboption("advanced", Value, "metric",
translate("Use gateway metric"))
metric.placeholder = "0"
metric.datatype = "uinteger"
metric:depends("gateway", "1")
clientid = section:taboption("advanced", Value, "clientid",
translate("Client ID to send when requesting DHCP"))
vendorclass = section:taboption("advanced", Value, "vendorid",
translate("Vendor Class to send when requesting DHCP"))
macaddr = section:taboption("advanced", Value, "macaddr", translate("Override MAC address"))
macaddr.placeholder = ifc and ifc:mac() or "00:00:00:00:00:00"
macaddr.datatype = "macaddr"
mtu = section:taboption("advanced", Value, "mtu", translate("Override MTU"))
mtu.placeholder = "1500"
mtu.datatype = "max(1500)"
|
protocols/core: fix defaultroute setting for DHCP interfaces
|
protocols/core: fix defaultroute setting for DHCP interfaces
git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@8702 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
|
Lua
|
apache-2.0
|
zwhfly/openwrt-luci,phi-psi/luci,yeewang/openwrt-luci,eugenesan/openwrt-luci,Canaan-Creative/luci,ch3n2k/luci,saraedum/luci-packages-old,stephank/luci,ReclaimYourPrivacy/cloak-luci,zwhfly/openwrt-luci,vhpham80/luci,ch3n2k/luci,Canaan-Creative/luci,ThingMesh/openwrt-luci,freifunk-gluon/luci,saraedum/luci-packages-old,8devices/carambola2-luci,zwhfly/openwrt-luci,ReclaimYourPrivacy/cloak-luci,jschmidlapp/luci,yeewang/openwrt-luci,jschmidlapp/luci,8devices/carambola2-luci,yeewang/openwrt-luci,phi-psi/luci,ch3n2k/luci,zwhfly/openwrt-luci,ReclaimYourPrivacy/cloak-luci,freifunk-gluon/luci,gwlim/luci,ReclaimYourPrivacy/cloak-luci,Canaan-Creative/luci,saraedum/luci-packages-old,freifunk-gluon/luci,Canaan-Creative/luci,jschmidlapp/luci,zwhfly/openwrt-luci,zwhfly/openwrt-luci,Canaan-Creative/luci,stephank/luci,yeewang/openwrt-luci,eugenesan/openwrt-luci,ThingMesh/openwrt-luci,eugenesan/openwrt-luci,saraedum/luci-packages-old,phi-psi/luci,zwhfly/openwrt-luci,gwlim/luci,eugenesan/openwrt-luci,phi-psi/luci,ReclaimYourPrivacy/cloak-luci,eugenesan/openwrt-luci,ReclaimYourPrivacy/cloak-luci,ThingMesh/openwrt-luci,zwhfly/openwrt-luci,gwlim/luci,ReclaimYourPrivacy/cloak-luci,8devices/carambola2-luci,ThingMesh/openwrt-luci,ThingMesh/openwrt-luci,ch3n2k/luci,jschmidlapp/luci,vhpham80/luci,jschmidlapp/luci,phi-psi/luci,vhpham80/luci,saraedum/luci-packages-old,ch3n2k/luci,yeewang/openwrt-luci,saraedum/luci-packages-old,8devices/carambola2-luci,vhpham80/luci,freifunk-gluon/luci,vhpham80/luci,freifunk-gluon/luci,jschmidlapp/luci,ThingMesh/openwrt-luci,yeewang/openwrt-luci,stephank/luci,gwlim/luci,stephank/luci,phi-psi/luci,stephank/luci,eugenesan/openwrt-luci,Canaan-Creative/luci,freifunk-gluon/luci,8devices/carambola2-luci,8devices/carambola2-luci,saraedum/luci-packages-old,gwlim/luci,8devices/carambola2-luci,jschmidlapp/luci,Canaan-Creative/luci,jschmidlapp/luci,gwlim/luci,freifunk-gluon/luci,eugenesan/openwrt-luci,zwhfly/openwrt-luci,ch3n2k/luci,Canaan-Creative/luci,vhpham80/luci,phi-psi/luci,stephank/luci,freifunk-gluon/luci,ThingMesh/openwrt-luci,ch3n2k/luci,yeewang/openwrt-luci,gwlim/luci,ReclaimYourPrivacy/cloak-luci
|
eb389637184d0c57334d957815b13fbf87d492b4
|
CIFAR10/cifar10_L2.lua
|
CIFAR10/cifar10_L2.lua
|
--[[
Multiple meta-iterations for DrMAD on CIFAR10
]]
require 'torch'
require 'sys'
require 'image'
local root = '../'
local grad = require 'autograd'
local utils = require(root .. 'models/utils.lua')
local optim = require 'optim'
local dl = require 'dataload'
local xlua = require 'xlua'
local c = require 'trepl.colorize'
--local debugger = require 'fb.debugger'
opt = lapp[[
-s,--save (default "logs") subdirectory to save logs
-b,--batchSize (default 64) batch size
-r,--learningRate (default 0.0001) learning rate
--learningRateDecay (default 1e-7) learning rate decay
--weightDecay (default 0.0005) weightDecay
-m,--momentum (default 0.9) momentum
--epoch_step (default 25) epoch step
--model (default vgg) model name
--max_epoch (default 300) maximum number of iterations
--backend (default nn) backend
--mode (default L2) L2/L1/learningrate
--type (default cuda) cuda/float/cl
--numMeta (default 3) #episode
--hLR (default 0.0001) learningrate of hyperparameter
--initHyper (default 0.001) initial value for hyperparameter
]]
print(c.blue "==> " .. "parameter:")
print(opt)
grad.optimize(true)
-- Load in MNIST
print(c.blue '==>' ..' loading data')
local trainset, validset, testset = dl.loadCIFAR10()
local classes = testset.classes
local confusionMatrix = optim.ConfusionMatrix(classes)
print(c.blue ' completed!')
local predict, model, modelf, dfTrain, params, initParams, params_l2
local hyper_params = {}
local function cast(t)
if opt.type == 'cuda' then
require 'cunn'
return t:cuda()
elseif opt.type == 'float' then
return t:float()
elseif opt.type == 'cl' then
require 'clnn'
return t:cl()
else
error('Unknown type '..opt.type)
end
end
local function L2_norm_create(params, initHyper)
local hyper_L2 = {}
for i = 1, #params do
-- dimension = 1 is bias, do not need L2_reg
if (params[i]:nDimension() > 1) then
hyper_L2[i] = params[i]:clone():fill(initHyper)
end
end
return hyper_L2
end
local function L2_norm(params)
-- print(params_l2, params[1])
-- local penalty = torch.sum(torch.cmul(params[1], params_l2[1]))
local penalty = torch.sum(params[1])
-- local penalty = 0
-- for i = 1, #params do
-- -- dimension = 1 is bias, do not need L2_reg
-- if (params[i]:nDimension() > 1) then
-- print(i)
-- penalty = penalty + torch.sum(params[i]) * params_l2[i]
-- end
-- end
return penalty
end
local function init(iter)
----
--- build VGG net.
----
if iter == 1 then
-- load model
print(c.blue '==>' ..' configuring model')
model = cast(dofile(root .. 'models/'..opt.model..'.lua'))
-- cast a model using functionalize
modelf, params = grad.functionalize(model)
params_l2 = L2_norm_create(params, opt.initHyper)
local Lossf = grad.nn.MSECriterion()
local function fTrain(params, x, y)
local prediction = modelf(params, x)
local penalty = L2_norm(params)
return Lossf(prediction, y) + penalty
end
dfTrain = grad(fTrain, { optimize = true })
-- a simple unit test
local X = cast(torch.Tensor(64, 3, 32, 32):fill(0.5))
local Y = cast(torch.Tensor(64, 10):fill(0))
local dparams, l = dfTrain(params, X, Y)
if (l) then
print(c.green ' Auto Diff works!')
end
print(c.blue ' completed!')
end
print(c.blue '==>' ..' initializing model')
utils.MSRinit(model)
print(c.blue ' completed!')
-- copy initial weights for later computation
initParams = utils.deepcopy(params)
end
local function train_meta(iter)
--[[
One meta-iteration to get directives w.r.t. hyperparameters
]]
-----------------------------------
-- [[Meta training]]
-----------------------------------
-- Train a neural network to get final parameters
for epoch = 1, opt.max_epoch do
print(c.blue '==>' ..' Meta episode #' .. iter .. ', Training epoch #' .. epoch)
for i, inputs, targets in trainset:subiter(opt.batchSize) do
local function makesample(inputs, targets)
local t_ = torch.FloatTensor(targets:size(1), 10):zero()
for j = 1, targets:size(1) do
t_[targets[j]] = 1
end
return inputs:cuda(), t_:cuda()
end
local grads, loss = dfTrain(params, makesample(inputs, targets))
for i = 1, #grads do
params[i] = params[i] + opt.learningRate * grads[i]
end
print(c.red 'loss: ', loss)
end
end
-- copy final parameters after convergence
local finalParams = utils.deepcopy(params)
finalParams = nn.utils.recursiveCopy(finalParams, params)
-----------------------
-- [[Reverse mode hyper-parameter training:
-- to get gradient w.r.t. hyper-parameters]]
-----------------------
end
-----------------------------
-- entry point
-----------------------------
local time = sys.clock()
for i = 1, opt.numMeta do
init(i)
-- print("wtf", model)
train_meta(i)
end
time = sys.clock() - time
print(time)
|
--[[
Multiple meta-iterations for DrMAD on CIFAR10
]]
require 'torch'
require 'sys'
require 'image'
local root = '../'
local grad = require 'autograd'
local utils = require(root .. 'models/utils.lua')
local optim = require 'optim'
local dl = require 'dataload'
local xlua = require 'xlua'
local c = require 'trepl.colorize'
--local debugger = require 'fb.debugger'
opt = lapp[[
-s,--save (default "logs") subdirectory to save logs
-b,--batchSize (default 64) batch size
-r,--learningRate (default 0.0001) learning rate
--learningRateDecay (default 1e-7) learning rate decay
--weightDecay (default 0.0005) weightDecay
-m,--momentum (default 0.9) momentum
--epoch_step (default 25) epoch step
--model (default vgg) model name
--max_epoch (default 300) maximum number of iterations
--backend (default nn) backend
--mode (default L2) L2/L1/learningrate
--type (default cuda) cuda/float/cl
--numMeta (default 3) #episode
--hLR (default 0.0001) learningrate of hyperparameter
--initHyper (default 0.001) initial value for hyperparameter
]]
print(c.blue "==> " .. "parameter:")
print(opt)
grad.optimize(true)
-- Load in MNIST
print(c.blue '==>' ..' loading data')
local trainset, validset, testset = dl.loadCIFAR10()
local classes = testset.classes
local confusionMatrix = optim.ConfusionMatrix(classes)
print(c.blue ' completed!')
local predict, model, modelf, dfTrain, params, initParams, params_l2
local hyper_params = {}
local function cast(t)
if opt.type == 'cuda' then
require 'cunn'
return t:cuda()
elseif opt.type == 'float' then
return t:float()
elseif opt.type == 'cl' then
require 'clnn'
return t:cl()
else
error('Unknown type '..opt.type)
end
end
local function L2_norm_create(params, initHyper)
local hyper_L2 = {}
for i = 1, #params do
-- dimension = 1 is bias, do not need L2_reg
if (params[i]:nDimension() > 1) then
hyper_L2[i] = params[i]:clone():fill(initHyper)
end
end
return hyper_L2
end
local function L2_norm(params)
-- print(params_l2, params[1])
local penalty = torch.sum(torch.cmul(params[1], params_l2[1]))
-- local penalty = torch.sum(params[1])
-- local penalty = 0
-- for i = 1, #params do
-- -- dimension = 1 is bias, do not need L2_reg
-- if (params[i]:nDimension() > 1) then
-- print(i)
-- penalty = penalty + torch.sum(params[i]) * params_l2[i]
-- end
-- end
return penalty
end
local function init(iter)
----
--- build VGG net.
----
if iter == 1 then
-- load model
print(c.blue '==>' ..' configuring model')
model = cast(dofile(root .. 'models/'..opt.model..'.lua'))
-- cast a model using functionalize
modelf, params = grad.functionalize(model)
params_l2 = L2_norm_create(params, opt.initHyper)
local Lossf = grad.nn.MSECriterion()
local function fTrain(params, x, y)
-- print(params)
local prediction = modelf(params.p2, x)
local penalty = L2_norm(params.p2)
return Lossf(prediction, y) + penalty
end
dfTrain = grad(fTrain)
-- a simple unit test
local X = cast(torch.Tensor(64, 3, 32, 32):fill(0.5))
local Y = cast(torch.Tensor(64, 10):fill(0))
local p = {
p1 = params_l2,
p2 = params
}
local dparams, l = dfTrain(p, X, Y)
if (l) then
print(c.green ' Auto Diff works!')
end
print(c.blue ' completed!')
end
print(c.blue '==>' ..' initializing model')
utils.MSRinit(model)
print(c.blue ' completed!')
-- copy initial weights for later computation
initParams = utils.deepcopy(params)
end
local function train_meta(iter)
--[[
One meta-iteration to get directives w.r.t. hyperparameters
]]
-----------------------------------
-- [[Meta training]]
-----------------------------------
-- Train a neural network to get final parameters
for epoch = 1, opt.max_epoch do
print(c.blue '==>' ..' Meta episode #' .. iter .. ', Training epoch #' .. epoch)
for i, inputs, targets in trainset:subiter(opt.batchSize) do
local function makesample(inputs, targets)
local t_ = torch.FloatTensor(targets:size(1), 10):zero()
for j = 1, targets:size(1) do
t_[targets[j]] = 1
end
return inputs:cuda(), t_:cuda()
end
local grads, loss = dfTrain(params, makesample(inputs, targets))
for i = 1, #grads do
params[i] = params[i] + opt.learningRate * grads[i]
end
print(c.red 'loss: ', loss)
end
end
-- copy final parameters after convergence
local finalParams = utils.deepcopy(params)
finalParams = nn.utils.recursiveCopy(finalParams, params)
-----------------------
-- [[Reverse mode hyper-parameter training:
-- to get gradient w.r.t. hyper-parameters]]
-----------------------
end
-----------------------------
-- entry point
-----------------------------
local time = sys.clock()
for i = 1, opt.numMeta do
init(i)
-- print("wtf", model)
train_meta(i)
end
time = sys.clock() - time
print(time)
|
fix bug.
|
fix bug.
|
Lua
|
mit
|
bigaidream-projects/drmad
|
99db05a75339907d43f18287d1380b5efa1e0935
|
convert_data.lua
|
convert_data.lua
|
require './lib/portable'
require 'image'
local settings = require './lib/settings'
local image_loader = require './lib/image_loader'
local function count_lines(file)
local fp = io.open(file, "r")
local count = 0
for line in fp:lines() do
count = count + 1
end
fp:close()
return count
end
local function crop_4x(x)
local w = x:size(3) % 4
local h = x:size(2) % 4
return image.crop(x, 0, 0, x:size(3) - w, x:size(2) - h)
end
local function load_images(list)
local count = count_lines(list)
local fp = io.open(list, "r")
local x = {}
local c = 0
for line in fp:lines() do
local im = crop_4x(image_loader.load_byte(line))
if im then
if im:size(2) >= settings.crop_size * 2 and im:size(3) >= settings.crop_size * 2 then
table.insert(x, im)
end
else
print("error:" .. line)
end
c = c + 1
xlua.progress(c, count)
if c % 10 == 0 then
collectgarbage()
end
end
return x
end
print(settings)
local x = load_images(settings.image_list)
torch.save(settings.images, x)
|
require './lib/portable'
require 'image'
local settings = require './lib/settings'
local image_loader = require './lib/image_loader'
local function count_lines(file)
local fp = io.open(file, "r")
local count = 0
for line in fp:lines() do
count = count + 1
end
fp:close()
return count
end
local function crop_4x(x)
local w = x:size(3) % 4
local h = x:size(2) % 4
return image.crop(x, 0, 0, x:size(3) - w, x:size(2) - h)
end
local function load_images(list)
local MARGIN = 32
local count = count_lines(list)
local fp = io.open(list, "r")
local x = {}
local c = 0
for line in fp:lines() do
local im = crop_4x(image_loader.load_byte(line))
if im then
if im:size(2) > (settings.crop_size * 2 + MARGIN) and im:size(3) > (settings.crop_size * 2 + MARGIN) then
table.insert(x, im)
end
else
print("error:" .. line)
end
c = c + 1
xlua.progress(c, count)
if c % 10 == 0 then
collectgarbage()
end
end
return x
end
print(settings)
local x = load_images(settings.image_list)
torch.save(settings.images, x)
|
fix image size validation in convert.lua
|
fix image size validation in convert.lua
|
Lua
|
mit
|
higankanshi/waifu2x,higankanshi/waifu2x,Spitfire1900/upscaler,higankanshi/waifu2x,zyhkz/waifu2x,nagadomi/waifu2x,vitaliylag/waifu2x,zyhkz/waifu2x,vitaliylag/waifu2x,Spitfire1900/upscaler,zyhkz/waifu2x,nagadomi/waifu2x,nagadomi/waifu2x,zyhkz/waifu2x,nagadomi/waifu2x,nagadomi/waifu2x,vitaliylag/waifu2x
|
b99a8acf01f075b617c70d4e206c7573d30da4c2
|
game_view.lua
|
game_view.lua
|
-- imports
grid_state = require 'grid_state'
glitch_gen = require 'glitchGen'
directions = require 'directions'
glider = require 'glider'
background_color = {240, 240, 240}
grid_normal_color = {180, 230, 255}
grid_block_color = {100, 200, 250}
grid_line_width = 0.5
grid_unit_size = 32
grid_big_border = 5
-- mouse variables
mouse_x = 0;
mouse_y = 0;
mouseClicked = false;
lastFrameMouseClicked = false;
-- glider variables
rectanglesToDraw = {}
numberOfGliders = 0
gliderPlaced = false
-- grid state
-- visual glitch state
glitchUpdateTimer = 0.5
function draw_line(grid_num, x1, y1, x2, y2)
local is_main = grid_num % grid_big_border == 0
local color = is_main and grid_block_color or grid_normal_color
local width = grid_line_width
love.graphics.setLineWidth(width)
love.graphics.setColor(color[1], color[2], color[3])
love.graphics.line(x1, y1, x2, y2)
end
function processGoButtonClicked()
gliderPlaced = false;
end
function exports()
local instance = {}
local block_size = grid_unit_size * grid_big_border
local xoffsets = 1280 % block_size
if xoffsets == 0 then
xoffsets = block_size
end
local xoffset = xoffsets / 2
local xcount = (1280 - xoffsets) / grid_unit_size
local yoffsets = 720 % block_size
local yoffset = yoffsets / 2
local ycount = (720 - yoffsets) / grid_unit_size
instance.grid_state = grid_state(xcount, ycount)
instance.goButtonImage = love.graphics.newImage( "placeholders/goButton.png" )
local goButtonX = (xcount - 2) * grid_unit_size + xoffset
local goButtonY = (ycount + 1.4) * grid_unit_size
function instance:draw()
love.graphics.setColor(background_color[1], background_color[2], background_color[3])
love.graphics.rectangle('fill', 0, 0, 1280, 720)
-- Draw Grid
local current_x = xoffset
local grid_num = 0
-- glider
local drawGliderX = -1
local drawGliderY = -1
while grid_num <= xcount do
draw_line(grid_num, current_x, yoffset, current_x, 720 - yoffset)
if mouse_x >= current_x and mouse_x < current_x + grid_unit_size then
drawGliderX = grid_num
end
current_x = current_x + grid_unit_size
grid_num = grid_num + 1
end
local current_y = yoffset
grid_num = 0
while grid_num <= ycount do
draw_line(grid_num, xoffset, current_y, 1280 - xoffset, current_y)
if mouse_y >= current_y and mouse_y < current_y + grid_unit_size then
drawGliderY = grid_num
end
current_y = current_y + grid_unit_size
grid_num = grid_num + 1
end
if mouseClicked and drawGliderX >= 0 and drawGliderY >= 0 and drawGliderX < xcount and drawGliderY < ycount and
not self.grid_state:get_space_at(drawGliderX+1, drawGliderY+1) and not gliderPlaced then
self.grid_state:add_object(glider(drawGliderX + 1, drawGliderY + 1, directions.DOWN))
gliderPlaced = true
end
if glitchUpdateTimer > 0.2 then
glitchUpdate = true
glitchUpdateTimer = glitchUpdateTimer - 0.2
end
for i,rect in ipairs(rectanglesToDraw) do
glitch_gen.drawGlich(rect["x"], rect["y"], xcount, glitchUpdate)
end
glitchUpdate = false
self.grid_state:draw_objects(xoffset, yoffset)
for x = 1, xcount, 1 do
for y = 1, ycount, 1 do
if self.grid_state:get_space_at(x, y) then
love.graphics.setColor(255,0,0)
love.graphics.rectangle('fill', (x-1) * grid_unit_size + xoffset, (y-1) * grid_unit_size + yoffset, grid_unit_size, grid_unit_size)
end
end
end
self.grid_state:update_objects()
-- Button Go to Evolution mode
love.graphics.draw(self.goButtonImage, goButtonX, goButtonY)
end
function instance:update()
mouse_x, mouse_y = love.mouse.getPosition()
lastFrameMouseClicked = mouseClicked
mouseClicked = love.mouse.isDown("l")
if mouseClicked and mouse_x > goButtonX and mouse_x <= goButtonX + 64 and mouse_y > goButtonY and mouse_y <= goButtonY + 32 then
processGoButtonClicked()
end
glitchUpdateTimer = glitchUpdateTimer + 1/60
end
return instance
end
return exports
|
-- imports
grid_state = require 'grid_state'
glitch_gen = require 'glitchGen'
directions = require 'directions'
glider = require 'glider'
background_color = {240, 240, 240}
grid_normal_color = {180, 230, 255}
grid_block_color = {100, 200, 250}
grid_line_width = 0.5
grid_unit_size = 32
grid_big_border = 5
-- mouse variables
mouse_x = 0;
mouse_y = 0;
mouseClicked = false;
lastFrameMouseClicked = false;
-- glider variables
rectanglesToDraw = {}
numberOfGliders = 0
gliderPlaced = false
-- grid state
-- visual glitch state
glitchUpdateTimer = 0.5
function draw_line(grid_num, x1, y1, x2, y2)
local is_main = grid_num % grid_big_border == 0
local color = is_main and grid_block_color or grid_normal_color
local width = grid_line_width
love.graphics.setLineWidth(width)
love.graphics.setColor(color[1], color[2], color[3])
love.graphics.line(x1, y1, x2, y2)
end
function processGoButtonClicked(grid_state)
grid_state:update_objects()
gliderPlaced = false;
end
function exports()
local instance = {}
local block_size = grid_unit_size * grid_big_border
local xoffsets = 1280 % block_size
if xoffsets == 0 then
xoffsets = block_size
end
local xoffset = xoffsets / 2
local xcount = (1280 - xoffsets) / grid_unit_size
local yoffsets = 720 % block_size
local yoffset = yoffsets / 2
local ycount = (720 - yoffsets) / grid_unit_size
instance.grid_state = grid_state(xcount, ycount)
instance.goButtonImage = love.graphics.newImage( "placeholders/goButton.png" )
local goButtonX = (xcount - 2) * grid_unit_size + xoffset
local goButtonY = (ycount + 1.4) * grid_unit_size
local goButtonWidth = 64
local goButtonHeight = 32
function instance:draw()
love.graphics.setColor(background_color[1], background_color[2], background_color[3])
love.graphics.rectangle('fill', 0, 0, 1280, 720)
-- Draw Grid
local current_x = xoffset
local grid_num = 0
-- glider
local drawGliderX = -1
local drawGliderY = -1
while grid_num <= xcount do
draw_line(grid_num, current_x, yoffset, current_x, 720 - yoffset)
if mouse_x >= current_x and mouse_x < current_x + grid_unit_size then
drawGliderX = grid_num
end
current_x = current_x + grid_unit_size
grid_num = grid_num + 1
end
local current_y = yoffset
grid_num = 0
while grid_num <= ycount do
draw_line(grid_num, xoffset, current_y, 1280 - xoffset, current_y)
if mouse_y >= current_y and mouse_y < current_y + grid_unit_size then
drawGliderY = grid_num
end
current_y = current_y + grid_unit_size
grid_num = grid_num + 1
end
if mouseClicked and drawGliderX >= 0 and drawGliderY >= 0 and drawGliderX < xcount and drawGliderY < ycount and
not self.grid_state:get_space_at(drawGliderX+1, drawGliderY+1) and not gliderPlaced then
self.grid_state:add_object(glider(drawGliderX + 1, drawGliderY + 1, directions.DOWN))
gliderPlaced = true
end
if glitchUpdateTimer > 0.2 then
glitchUpdate = true
glitchUpdateTimer = glitchUpdateTimer - 0.2
end
for i,rect in ipairs(rectanglesToDraw) do
glitch_gen.drawGlich(rect["x"], rect["y"], xcount, glitchUpdate)
end
glitchUpdate = false
self.grid_state:draw_objects(xoffset, yoffset)
for x = 1, xcount, 1 do
for y = 1, ycount, 1 do
if self.grid_state:get_space_at(x, y) then
love.graphics.setColor(255,0,0)
love.graphics.rectangle('fill', (x-1) * grid_unit_size + xoffset, (y-1) * grid_unit_size + yoffset, grid_unit_size, grid_unit_size)
end
end
end
-- Button Go to Evolution mode
love.graphics.draw(self.goButtonImage, goButtonX, goButtonY)
end
function instance:update()
mouse_x, mouse_y = love.mouse.getPosition()
lastFrameMouseClicked = mouseClicked
mouseClicked = love.mouse.isDown("l")
if mouseClicked and mouse_x > goButtonX and mouse_x <= goButtonX + goButtonWidth and mouse_y > goButtonY and mouse_y <= goButtonY + goButtonHeight and
not lastFrameMouseClicked then
processGoButtonClicked(self.grid_state)
end
glitchUpdateTimer = glitchUpdateTimer + 1/60
end
return instance
end
return exports
|
some bugs corrected
|
some bugs corrected
|
Lua
|
mit
|
NamefulTeam/PortoGameJam2015
|
033841fd32cbf45d637242da0a5cd9b269b70b57
|
lib/http.lua
|
lib/http.lua
|
local TCP = require('tcp')
local Request = require('request')
local Response = require('response')
local HTTP_Parser = require('http_parser')
local Table = require('table')
local HTTP = {}
function HTTP.request(options, callback)
-- Load options into local variables. Assume defaults
local host = options.host or "127.0.0.1"
local port = options.port or 80
local method = options.method or "GET"
local path = options.path or "/"
local headers = options.headers or {}
if not headers.host then headers.host = host end
local client = TCP.new()
client:connect(host, port)
client:on("complete", function ()
local response = Response.new(client)
local request = {method .. " " .. path .. " HTTP/1.1\r\n"}
for field, value in pairs(headers) do
request[#request + 1] = field .. ": " .. value .. "\r\n"
end
request[#request + 1] = "\r\n"
client:write(Table.concat(request))
client:read_start()
local headers
local current_field
local parser = HTTP_Parser.new("response", {
on_message_begin = function ()
headers = {}
end,
on_url = function (url)
end,
on_header_field = function (field)
current_field = field
end,
on_header_value = function (value)
headers[current_field:lower()] = value
end,
on_headers_complete = function (info)
response.headers = headers
response.status_code = info.status_code
response.version_minor = info.version_minor
response.version_major = info.version_major
callback(response)
end,
on_body = function (chunk)
response:emit('data', chunk)
end,
on_message_complete = function ()
response:emit('end')
end
});
client:on("data", function (chunk, len)
local nparsed = parser:execute(chunk, 0, len)
-- If it wasn't all parsed then there was an error parsing
if nparsed < len then
error("Parse error in server response")
end
end)
client:on("end", function ()
parser:finish()
end)
end)
end
function HTTP.create_server(host, port, on_connection)
local server = TCP.new()
server:bind(host, port)
server:listen(function (err)
if err then
return server:emit("error", err)
end
-- Accept the client and build request and response objects
local client = TCP.new()
server:accept(client)
client:read_start()
local request = Request.new(client)
local response = Response.new(client)
-- Convert TCP stream to HTTP stream
local current_field
local parser
local headers
parser = HTTP_Parser.new("request", {
on_message_begin = function ()
headers = {}
request.headers = headers
end,
on_url = function (url)
request.url = url
end,
on_header_field = function (field)
current_field = field
end,
on_header_value = function (value)
headers[current_field:lower()] = value
end,
on_headers_complete = function (info)
request.method = info.method
request.upgrade = info.upgrade
request.version_major = info.version_major
request.version_minor = info.version_minor
-- Give upgrade requests access to the raw client if they want it
if info.upgrade then
request.client = client
end
-- Handle 100-continue requests
if request.headers.expect and info.version_major == 1 and info.version_minor == 1 and request.headers.expect:lower() == "100-continue" then
if server.handlers and server.handlers.check_continue then
server:emit("check_continue", request, response)
else
response:write_continue()
on_connection(request, response)
end
else
on_connection(request, response)
end
-- We're done with the parser once we hit an upgrade
if request.upgrade then
parser:finish()
end
end,
on_body = function (chunk)
request:emit('data', chunk, #chunk)
end,
on_message_complete = function ()
request:emit('end')
end
})
client:on("data", function (chunk, len)
-- Ignore empty chunks
if len == 0 then return end
-- Once we're in "upgrade" mode, the protocol is no longer HTTP and we
-- shouldn't send data to the HTTP parser
if request.upgrade then
request:emit("data", chunk, len)
return
end
-- Parse the chunk of HTTP, this will syncronously emit several of the
-- above events and return how many bytes were parsed.
local nparsed = parser:execute(chunk, 0, len)
-- If it wasn't all parsed then there was an error parsing
if nparsed < len then
-- If the error was caused by non-http protocol like in websockets
-- then that's ok, just emit the rest directly to the request object
if request.upgrade then
len = len - nparsed
chunk = chunk:sub(nparsed + 1)
request:emit("data", chunk, len)
else
request:emit("error", "parse error")
end
end
end)
client:on("end", function ()
parser:finish()
end)
end)
return server
end
return HTTP
|
local TCP = require('tcp')
local Request = require('request')
local Response = require('response')
local HTTP_Parser = require('http_parser')
local Table = require('table')
local HTTP = {}
function HTTP.request(options, callback)
-- Load options into local variables. Assume defaults
local host = options.host or "127.0.0.1"
local port = options.port or 80
local method = options.method or "GET"
local path = options.path or "/"
local headers = options.headers or {}
if not headers.host then headers.host = host end
local client = TCP.new()
local status, result = pcall(client.connect, client, host, port)
if not status then
callback(result)
client:close()
return
end
client:on("complete", function ()
local response = Response.new(client)
local request = {method .. " " .. path .. " HTTP/1.1\r\n"}
for field, value in pairs(headers) do
request[#request + 1] = field .. ": " .. value .. "\r\n"
end
request[#request + 1] = "\r\n"
client:write(Table.concat(request))
client:read_start()
local headers
local current_field
local parser = HTTP_Parser.new("response", {
on_message_begin = function ()
headers = {}
end,
on_url = function (url)
end,
on_header_field = function (field)
current_field = field
end,
on_header_value = function (value)
headers[current_field:lower()] = value
end,
on_headers_complete = function (info)
response.headers = headers
response.status_code = info.status_code
response.version_minor = info.version_minor
response.version_major = info.version_major
callback(nil, response)
end,
on_body = function (chunk)
response:emit('data', chunk)
end,
on_message_complete = function ()
response:emit('end')
end
});
client:on("data", function (chunk, len)
local nparsed = parser:execute(chunk, 0, len)
-- If it wasn't all parsed then there was an error parsing
if nparsed < len then
error("Parse error in server response")
end
end)
client:on("end", function ()
parser:finish()
end)
end)
end
function HTTP.create_server(host, port, on_connection)
local server = TCP.new()
server:bind(host, port)
server:listen(function (err)
if err then
return server:emit("error", err)
end
-- Accept the client and build request and response objects
local client = TCP.new()
server:accept(client)
client:read_start()
local request = Request.new(client)
local response = Response.new(client)
-- Convert TCP stream to HTTP stream
local current_field
local parser
local headers
parser = HTTP_Parser.new("request", {
on_message_begin = function ()
headers = {}
request.headers = headers
end,
on_url = function (url)
request.url = url
end,
on_header_field = function (field)
current_field = field
end,
on_header_value = function (value)
headers[current_field:lower()] = value
end,
on_headers_complete = function (info)
request.method = info.method
request.upgrade = info.upgrade
request.version_major = info.version_major
request.version_minor = info.version_minor
-- Give upgrade requests access to the raw client if they want it
if info.upgrade then
request.client = client
end
-- Handle 100-continue requests
if request.headers.expect and info.version_major == 1 and info.version_minor == 1 and request.headers.expect:lower() == "100-continue" then
if server.handlers and server.handlers.check_continue then
server:emit("check_continue", request, response)
else
response:write_continue()
on_connection(request, response)
end
else
on_connection(request, response)
end
-- We're done with the parser once we hit an upgrade
if request.upgrade then
parser:finish()
end
end,
on_body = function (chunk)
request:emit('data', chunk, #chunk)
end,
on_message_complete = function ()
request:emit('end')
end
})
client:on("data", function (chunk, len)
-- Ignore empty chunks
if len == 0 then return end
-- Once we're in "upgrade" mode, the protocol is no longer HTTP and we
-- shouldn't send data to the HTTP parser
if request.upgrade then
request:emit("data", chunk, len)
return
end
-- Parse the chunk of HTTP, this will syncronously emit several of the
-- above events and return how many bytes were parsed.
local nparsed = parser:execute(chunk, 0, len)
-- If it wasn't all parsed then there was an error parsing
if nparsed < len then
-- If the error was caused by non-http protocol like in websockets
-- then that's ok, just emit the rest directly to the request object
if request.upgrade then
len = len - nparsed
chunk = chunk:sub(nparsed + 1)
request:emit("data", chunk, len)
else
request:emit("error", "parse error")
end
end
end)
client:on("end", function ()
parser:finish()
end)
end)
return server
end
return HTTP
|
http connect fixed
|
http connect fixed
|
Lua
|
apache-2.0
|
rjeli/luvit,zhaozg/luvit,sousoux/luvit,rjeli/luvit,zhaozg/luvit,AndrewTsao/luvit,GabrielNicolasAvellaneda/luvit-upstream,GabrielNicolasAvellaneda/luvit-upstream,sousoux/luvit,kaustavha/luvit,connectFree/lev,DBarney/luvit,AndrewTsao/luvit,luvit/luvit,boundary/luvit,bsn069/luvit,boundary/luvit,GabrielNicolasAvellaneda/luvit-upstream,AndrewTsao/luvit,sousoux/luvit,sousoux/luvit,rjeli/luvit,sousoux/luvit,boundary/luvit,DBarney/luvit,sousoux/luvit,bsn069/luvit,boundary/luvit,DBarney/luvit,bsn069/luvit,luvit/luvit,boundary/luvit,rjeli/luvit,kaustavha/luvit,GabrielNicolasAvellaneda/luvit-upstream,connectFree/lev,boundary/luvit,kaustavha/luvit,DBarney/luvit
|
94c67002278b5649147444858bd79f8113da453b
|
mods/BeardLib-Editor/Classes/Map/Elements/preplanningelement.lua
|
mods/BeardLib-Editor/Classes/Map/Elements/preplanningelement.lua
|
EditorPrePlanning = EditorPrePlanning or class(MissionScriptEditor)
function EditorPrePlanning:create_element()
self.super.create_element(self)
self._element.class = "ElementPrePlanning"
self._element.values.allowed_types = {}
self._element.values.disables_types = {}
self._element.values.location_group = tweak_data.preplanning.location_groups[1]
self._element.values.upgrade_lock = "none"
self._element.values.dlc_lock = "none"
end
function EditorPrePlanning:_data_updated(value_type, value)
self._element.values[value_type] = value
end
function EditorPrePlanning:_build_panel()
self:_create_panel()
self:ComboCtrl("upgrade_lock", tweak_data.preplanning.upgrade_locks, {help = "Select a upgrade lock from the combobox"})
self:ComboCtrl("dlc_lock", tweak_data.preplanning.dlc_locks, {help = "Select a DLC lock from the combobox"})
self:ComboCtrl("location_group", tweak_data.preplanning.location_groups, {help = "Select a location group from the combobox"})
local allowed_types = {}
for k, v in pairs(managers.preplanning:types()) do
allowed_types[v] = self._element.values.allowed_types[v] == true
end
local disables_types = {}
for k, v in pairs(managers.preplanning:types()) do
disables_types[v] = self._element.values.disables_types[v] == true
end
self:Button("SelectAllowedTypes", function()
BeardLibEditor.managers.SelectDialog:Show({
selected_list = self._element.values.allowed_types,
list = allowed_types,
callback = callback(self, self, "_data_updated", "allowed_types")
})
end)
self:Button("SelectDisablesTypes", function()
BeardLibEditor.managers.SelectDialog:Show({
selected_list = self._element.values.disables_types,
list = disables_types,
callback = callback(self, self, "_data_updated", "disables_types")
})
end)
end
|
EditorPrePlanning = EditorPrePlanning or class(MissionScriptEditor)
function EditorPrePlanning:create_element()
self.super.create_element(self)
self._element.class = "ElementPrePlanning"
self._element.values.allowed_types = {}
self._element.values.disables_types = {}
self._element.values.location_group = tweak_data.preplanning.location_groups[1]
self._element.values.upgrade_lock = "none"
self._element.values.dlc_lock = "none"
end
function EditorPrePlanning:_data_updated(value_type, value)
self._element.values[value_type] = value
end
function EditorPrePlanning:_build_panel()
self:_create_panel()
self:ComboCtrl("upgrade_lock", tweak_data.preplanning.upgrade_locks, {help = "Select a upgrade lock from the combobox"})
self:ComboCtrl("dlc_lock", tweak_data.preplanning.dlc_locks, {help = "Select a DLC lock from the combobox"})
self:ComboCtrl("location_group", tweak_data.preplanning.location_groups, {help = "Select a location group from the combobox"})
local types = managers.preplanning:types()
self:Button("SelectAllowedTypes", function()
BeardLibEditor.managers.SelectDialog:Show({
selected_list = self._element.values.allowed_types,
list = types,
callback = callback(self, self, "_data_updated", "allowed_types")
})
end)
self:Button("SelectDisablesTypes", function()
BeardLibEditor.managers.SelectDialog:Show({
selected_list = self._element.values.disables_types,
list = types,
callback = callback(self, self, "_data_updated", "disables_types")
})
end)
end
|
Fixed PrePlanning element not saving types correctly.
|
Fixed PrePlanning element not saving types correctly.
|
Lua
|
mit
|
simon-wh/PAYDAY-2-BeardLib-Editor
|
55136b77ad6c0cafd75a094cb9c649e39816d8eb
|
service/clusterd.lua
|
service/clusterd.lua
|
local skynet = require "skynet"
local sc = require "skynet.socketchannel"
local socket = require "skynet.socket"
local cluster = require "skynet.cluster.core"
local config_name = skynet.getenv "cluster"
local node_address = {}
local node_session = {}
local command = {}
local function read_response(sock)
local sz = socket.header(sock:read(2))
local msg = sock:read(sz)
return cluster.unpackresponse(msg) -- session, ok, data, padding
end
local function open_channel(t, key)
local host, port = string.match(node_address[key], "([^:]+):(.*)$")
local c = sc.channel {
host = host,
port = tonumber(port),
response = read_response,
nodelay = true,
}
assert(c:connect(true))
t[key] = c
return c
end
local node_channel = setmetatable({}, { __index = open_channel })
local function loadconfig(tmp)
if tmp == nil then
tmp = {}
if config_name then
local f = assert(io.open(config_name))
local source = f:read "*a"
f:close()
assert(load(source, "@"..config_name, "t", tmp))()
end
end
for name,address in pairs(tmp) do
assert(type(address) == "string")
if node_address[name] ~= address then
-- address changed
if rawget(node_channel, name) then
node_channel[name] = nil -- reset connection
end
node_address[name] = address
end
end
end
function command.reload(source, config)
loadconfig(config)
skynet.ret(skynet.pack(nil))
end
function command.listen(source, addr, port)
local gate = skynet.newservice("gate")
if port == nil then
addr, port = string.match(node_address[addr], "([^:]+):(.*)$")
end
skynet.call(gate, "lua", "open", { address = addr, port = port })
skynet.ret(skynet.pack(nil))
end
local function send_request(source, node, addr, msg, sz)
local session = node_session[node] or 1
-- msg is a local pointer, cluster.packrequest will free it
local request, new_session, padding = cluster.packrequest(addr, session, msg, sz)
node_session[node] = new_session
-- node_channel[node] may yield or throw error
local c = node_channel[node]
return c:request(request, session, padding)
end
function command.req(...)
local ok, msg, sz = pcall(send_request, ...)
if ok then
if type(msg) == "table" then
skynet.ret(cluster.concat(msg))
else
skynet.ret(msg)
end
else
skynet.error(msg)
skynet.response()(false)
end
end
function command.push(source, node, addr, msg, sz)
local session = node_session[node] or 1
local request, new_session, padding = cluster.packpush(addr, session, msg, sz)
if padding then -- is multi push
node_session[node] = new_session
end
-- node_channel[node] may yield or throw error
local c = node_channel[node]
c:request(request, nil, padding)
-- notice: push may fail where the channel is disconnected or broken.
end
local proxy = {}
function command.proxy(source, node, name)
local fullname = node .. "." .. name
if proxy[fullname] == nil then
proxy[fullname] = skynet.newservice("clusterproxy", node, name)
end
skynet.ret(skynet.pack(proxy[fullname]))
end
local register_name = {}
function command.register(source, name, addr)
assert(register_name[name] == nil)
addr = addr or source
local old_name = register_name[addr]
if old_name then
register_name[old_name] = nil
end
register_name[addr] = name
register_name[name] = addr
skynet.ret(nil)
skynet.error(string.format("Register [%s] :%08x", name, addr))
end
local large_request = {}
function command.socket(source, subcmd, fd, msg)
if subcmd == "data" then
local sz
local addr, session, msg, padding, is_push = cluster.unpackrequest(msg)
if padding then
local req = large_request[session] or { addr = addr , is_push = is_push }
large_request[session] = req
table.insert(req, msg)
return
else
local req = large_request[session]
if req then
large_request[session] = nil
table.insert(req, msg)
msg,sz = cluster.concat(req)
addr = req.addr
is_push = req.is_push
end
if not msg then
local response = cluster.packresponse(session, false, "Invalid large req")
socket.write(fd, response)
return
end
end
local ok, response
if addr == 0 then
local name = skynet.unpack(msg, sz)
local addr = register_name[name]
if addr then
ok = true
msg, sz = skynet.pack(addr)
else
ok = false
msg = "name not found"
end
elseif is_push then
skynet.rawsend(addr, "lua", msg, sz)
return -- no response
else
ok , msg, sz = pcall(skynet.rawcall, addr, "lua", msg, sz)
end
if ok then
response = cluster.packresponse(session, true, msg, sz)
if type(response) == "table" then
for _, v in ipairs(response) do
socket.lwrite(fd, v)
end
else
socket.write(fd, response)
end
else
response = cluster.packresponse(session, false, msg)
socket.write(fd, response)
end
elseif subcmd == "open" then
skynet.error(string.format("socket accept from %s", msg))
skynet.call(source, "lua", "accept", fd)
else
large_request = {}
skynet.error(string.format("socket %s %d : %s", subcmd, fd, msg))
end
end
skynet.start(function()
loadconfig()
skynet.dispatch("lua", function(session , source, cmd, ...)
local f = assert(command[cmd])
f(source, ...)
end)
end)
|
local skynet = require "skynet"
local sc = require "skynet.socketchannel"
local socket = require "skynet.socket"
local cluster = require "skynet.cluster.core"
local config_name = skynet.getenv "cluster"
local node_address = {}
local node_session = {}
local command = {}
local function read_response(sock)
local sz = socket.header(sock:read(2))
local msg = sock:read(sz)
return cluster.unpackresponse(msg) -- session, ok, data, padding
end
local function open_channel(t, key)
local host, port = string.match(node_address[key], "([^:]+):(.*)$")
local c = sc.channel {
host = host,
port = tonumber(port),
response = read_response,
nodelay = true,
}
assert(c:connect(true))
t[key] = c
return c
end
local node_channel = setmetatable({}, { __index = open_channel })
local function loadconfig(tmp)
if tmp == nil then
tmp = {}
if config_name then
local f = assert(io.open(config_name))
local source = f:read "*a"
f:close()
assert(load(source, "@"..config_name, "t", tmp))()
end
end
for name,address in pairs(tmp) do
assert(type(address) == "string")
if node_address[name] ~= address then
-- address changed
if rawget(node_channel, name) then
node_channel[name] = nil -- reset connection
end
node_address[name] = address
end
end
end
function command.reload(source, config)
loadconfig(config)
skynet.ret(skynet.pack(nil))
end
function command.listen(source, addr, port)
local gate = skynet.newservice("gate")
if port == nil then
addr, port = string.match(node_address[addr], "([^:]+):(.*)$")
end
skynet.call(gate, "lua", "open", { address = addr, port = port })
skynet.ret(skynet.pack(nil))
end
local function send_request(source, node, addr, msg, sz)
local session = node_session[node] or 1
-- msg is a local pointer, cluster.packrequest will free it
local request, new_session, padding = cluster.packrequest(addr, session, msg, sz)
node_session[node] = new_session
-- node_channel[node] may yield or throw error
local c = node_channel[node]
return c:request(request, session, padding)
end
function command.req(...)
local ok, msg, sz = pcall(send_request, ...)
if ok then
if type(msg) == "table" then
skynet.ret(cluster.concat(msg))
else
skynet.ret(msg)
end
else
skynet.error(msg)
skynet.response()(false)
end
end
function command.push(source, node, addr, msg, sz)
local session = node_session[node] or 1
local request, new_session, padding = cluster.packpush(addr, session, msg, sz)
if padding then -- is multi push
node_session[node] = new_session
end
-- node_channel[node] may yield or throw error
local c = node_channel[node]
c:request(request, nil, padding)
-- notice: push may fail where the channel is disconnected or broken.
end
local proxy = {}
function command.proxy(source, node, name)
local fullname = node .. "." .. name
if proxy[fullname] == nil then
proxy[fullname] = skynet.newservice("clusterproxy", node, name)
end
skynet.ret(skynet.pack(proxy[fullname]))
end
local register_name = {}
function command.register(source, name, addr)
assert(register_name[name] == nil)
addr = addr or source
local old_name = register_name[addr]
if old_name then
register_name[old_name] = nil
end
register_name[addr] = name
register_name[name] = addr
skynet.ret(nil)
skynet.error(string.format("Register [%s] :%08x", name, addr))
end
local large_request = {}
function command.socket(source, subcmd, fd, msg)
if subcmd == "data" then
local sz
local addr, session, msg, padding, is_push = cluster.unpackrequest(msg)
if padding then
local requests = large_request[fd]
if requests == nil then
requests = {}
large_request[fd] = requests
end
local req = requests[session] or { addr = addr , is_push = is_push }
requests[session] = req
table.insert(req, msg)
return
else
local requests = large_request[fd]
if requests then
local req = requests[session]
if req then
requests[session] = nil
table.insert(req, msg)
msg,sz = cluster.concat(req)
addr = req.addr
is_push = req.is_push
end
end
if not msg then
local response = cluster.packresponse(session, false, "Invalid large req")
socket.write(fd, response)
return
end
end
local ok, response
if addr == 0 then
local name = skynet.unpack(msg, sz)
local addr = register_name[name]
if addr then
ok = true
msg, sz = skynet.pack(addr)
else
ok = false
msg = "name not found"
end
elseif is_push then
skynet.rawsend(addr, "lua", msg, sz)
return -- no response
else
ok , msg, sz = pcall(skynet.rawcall, addr, "lua", msg, sz)
end
if ok then
response = cluster.packresponse(session, true, msg, sz)
if type(response) == "table" then
for _, v in ipairs(response) do
socket.lwrite(fd, v)
end
else
socket.write(fd, response)
end
else
response = cluster.packresponse(session, false, msg)
socket.write(fd, response)
end
elseif subcmd == "open" then
skynet.error(string.format("socket accept from %s", msg))
skynet.call(source, "lua", "accept", fd)
else
large_request[fd] = nil
skynet.error(string.format("socket %s %d %s", subcmd, fd, msg or ""))
end
end
skynet.start(function()
loadconfig()
skynet.dispatch("lua", function(session , source, cmd, ...)
local f = assert(command[cmd])
f(source, ...)
end)
end)
|
fix issue #741
|
fix issue #741
|
Lua
|
mit
|
xcjmine/skynet,icetoggle/skynet,bttscut/skynet,JiessieDawn/skynet,great90/skynet,korialuo/skynet,hongling0/skynet,pigparadise/skynet,bigrpg/skynet,JiessieDawn/skynet,codingabc/skynet,xcjmine/skynet,korialuo/skynet,kyle-wang/skynet,icetoggle/skynet,pigparadise/skynet,kyle-wang/skynet,zhangshiqian1214/skynet,codingabc/skynet,fztcjjl/skynet,great90/skynet,pigparadise/skynet,firedtoad/skynet,ag6ag/skynet,zhangshiqian1214/skynet,korialuo/skynet,great90/skynet,bigrpg/skynet,ag6ag/skynet,hongling0/skynet,kyle-wang/skynet,sanikoyes/skynet,bttscut/skynet,codingabc/skynet,hongling0/skynet,jxlczjp77/skynet,wangyi0226/skynet,bigrpg/skynet,xcjmine/skynet,czlc/skynet,Ding8222/skynet,JiessieDawn/skynet,wangyi0226/skynet,fztcjjl/skynet,firedtoad/skynet,czlc/skynet,sundream/skynet,cloudwu/skynet,xjdrew/skynet,sanikoyes/skynet,xjdrew/skynet,Ding8222/skynet,xjdrew/skynet,firedtoad/skynet,zhangshiqian1214/skynet,zhangshiqian1214/skynet,czlc/skynet,Ding8222/skynet,zhouxiaoxiaoxujian/skynet,zhouxiaoxiaoxujian/skynet,ag6ag/skynet,jxlczjp77/skynet,wangyi0226/skynet,zhangshiqian1214/skynet,fztcjjl/skynet,sundream/skynet,zhangshiqian1214/skynet,cloudwu/skynet,sanikoyes/skynet,sundream/skynet,zhouxiaoxiaoxujian/skynet,jxlczjp77/skynet,cloudwu/skynet,bttscut/skynet,icetoggle/skynet
|
12e90582ba427b1e4bb5885358f4229382c70de5
|
source/utilities/vector.lua
|
source/utilities/vector.lua
|
--------------------------------------------------------------------------------
-- vector.lua - Defines operations for vector operations
--------------------------------------------------------------------------------
vector = flower.class()
function vector:init(t)
if type(t) == "table" then
for k, v in ipairs(t) do
self[k] = v
end
else
-- Zero out vector
for i=1, t do
self[i] = 0
end
end
end
function vector:add(other)
assert(#other == #self, "Vectors are not the same dimension")
local result = vector()
for i, v in ipairs(self) do
result[i] = v + other[i]
end
return result
end
function vector:sub(other)
return self + other:negate()
end
function vector:negate()
local result = vector()
for i, v in ipairs(self) do
result[i] = -v
end
return result
end
function vector:mul(other)
assert(#other == #self, "Vectors are not the same dimension")
local result = vector()
for i, v in ipairs(self) do
result[i] = v * (type(other) == "number" and other or other[i])
end
return result
end
function vector:equal(other)
if #other ~= #self then
return false
end
for i, v in ipairs(self) do
if v ~= other[i] then
return false
end
end
return true
end
vector.__interface.__add = vector.add
vector.__interface.__sub = vector.sub
vector.__interface.__unm = vector.negate
vector.__interface.__mul = vector.mul
vector.__interface.__eq = vector.equal
|
--------------------------------------------------------------------------------
-- vector.lua - Defines operations for vector operations
--------------------------------------------------------------------------------
vector = flower.class()
function vector:init(t)
if type(t) == "table" then
for k, v in ipairs(t) do
self[k] = v
end
else
t = t or 2 -- default to a 2d vector
-- Zero out vector
for i=1, t do
self[i] = 0
end
end
end
function vector:add(other)
assert(#other == #self, "Vectors are not the same dimension")
local result = vector()
for i, v in ipairs(self) do
result[i] = v + other[i]
end
return result
end
function vector:sub(other)
return self + other:negate()
end
function vector:negate()
local result = vector()
for i, v in ipairs(self) do
result[i] = -v
end
return result
end
function vector:mul(other)
local result = vector()
local iterTable = type(self) == "table" and self or other
for i, v in ipairs(iterTable) do
result[i] = v * (type(self) == "number" and self or (type(other) == "number" and other or other[i]))
end
return result
end
function vector:equal(other)
if #other ~= #self then
return false
end
for i, v in ipairs(self) do
if v ~= other[i] then
return false
end
end
return true
end
vector.__interface.__add = vector.add
vector.__interface.__sub = vector.sub
vector.__interface.__unm = vector.negate
vector.__interface.__mul = vector.mul
vector.__interface.__eq = vector.equal
|
Fixed vector multiplication.
|
Fixed vector multiplication.
|
Lua
|
mit
|
BryceMehring/Hexel
|
c74074db2b9eb54e855a73e0b6301a877cec1867
|
util/array.lua
|
util/array.lua
|
-- Prosody IM
-- Copyright (C) 2008-2009 Matthew Wild
-- Copyright (C) 2008-2009 Waqas Hussain
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
local t_insert, t_sort, t_remove, t_concat
= table.insert, table.sort, table.remove, table.concat;
local array = {};
local array_base = {};
local array_methods = {};
local array_mt = { __index = array_methods, __tostring = function (array) return array:concat(", "); end };
local function new_array(_, t)
return setmetatable(t or {}, array_mt);
end
function array_mt.__add(a1, a2)
local res = new_array();
return res:append(a1):append(a2);
end
setmetatable(array, { __call = new_array });
function array_base.map(outa, ina, func)
for k,v in ipairs(ina) do
outa[k] = func(v);
end
return outa;
end
function array_base.filter(outa, ina, func)
for k,v in ipairs(ina) do
if func(v) then
outa:push(v);
end
end
return outa;
end
function array_base.sort(outa, ina, ...)
if ina ~= outa then
outa:append(ina);
end
t_sort(outa, ...);
return outa;
end
--- These methods only mutate
function array_methods:random()
return self[math.random(1,#self)];
end
function array_methods:shuffle(outa, ina)
local len = #self;
for i=1,#self do
local r = math.random(i,len);
self[i], self[r] = self[r], self[i];
end
return self;
end
function array_methods:reverse()
local len = #self-1;
for i=len,1,-1 do
self:push(self[i]);
self:pop(i);
end
return self;
end
function array_methods:append(array)
local len,len2 = #self, #array;
for i=1,len2 do
self[len+i] = array[i];
end
return self;
end
array_methods.push = table.insert;
array_methods.pop = table.remove;
array_methods.concat = table.concat;
array_methods.length = function (t) return #t; end
--- These methods always create a new array
function array.collect(f, s, var)
local t, var = {};
while true do
var = f(s, var);
if var == nil then break; end
table.insert(t, var);
end
return setmetatable(t, array_mt);
end
---
-- Setup methods from array_base
for method, f in pairs(array_base) do
local method = method; -- Yes, this is necessary :)
local base_method = f;
-- Setup global array method which makes new array
array[method] = function (old_a, ...)
local a = new_array();
return base_method(a, old_a, ...);
end
-- Setup per-array (mutating) method
array_methods[method] = function (self, ...)
return base_method(self, self, ...);
end
end
_G.array = array;
module("array");
return array;
|
-- Prosody IM
-- Copyright (C) 2008-2009 Matthew Wild
-- Copyright (C) 2008-2009 Waqas Hussain
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
local t_insert, t_sort, t_remove, t_concat
= table.insert, table.sort, table.remove, table.concat;
local array = {};
local array_base = {};
local array_methods = {};
local array_mt = { __index = array_methods, __tostring = function (array) return array:concat(", "); end };
local function new_array(_, t)
return setmetatable(t or {}, array_mt);
end
function array_mt.__add(a1, a2)
local res = new_array();
return res:append(a1):append(a2);
end
setmetatable(array, { __call = new_array });
function array_base.map(outa, ina, func)
for k,v in ipairs(ina) do
outa[k] = func(v);
end
return outa;
end
function array_base.filter(outa, ina, func)
local inplace, start_length = ina == outa, #ina;
local write = 1;
for read=1,start_length do
local v = ina[read];
if func(v) then
outa[write] = v;
write = write + 1;
end
end
if inplace and write < start_length then
for i=write,start_length do
outa[i] = nil;
end
end
return outa;
end
function array_base.sort(outa, ina, ...)
if ina ~= outa then
outa:append(ina);
end
t_sort(outa, ...);
return outa;
end
--- These methods only mutate
function array_methods:random()
return self[math.random(1,#self)];
end
function array_methods:shuffle(outa, ina)
local len = #self;
for i=1,#self do
local r = math.random(i,len);
self[i], self[r] = self[r], self[i];
end
return self;
end
function array_methods:reverse()
local len = #self-1;
for i=len,1,-1 do
self:push(self[i]);
self:pop(i);
end
return self;
end
function array_methods:append(array)
local len,len2 = #self, #array;
for i=1,len2 do
self[len+i] = array[i];
end
return self;
end
array_methods.push = table.insert;
array_methods.pop = table.remove;
array_methods.concat = table.concat;
array_methods.length = function (t) return #t; end
--- These methods always create a new array
function array.collect(f, s, var)
local t, var = {};
while true do
var = f(s, var);
if var == nil then break; end
table.insert(t, var);
end
return setmetatable(t, array_mt);
end
---
-- Setup methods from array_base
for method, f in pairs(array_base) do
local method = method; -- Yes, this is necessary :)
local base_method = f;
-- Setup global array method which makes new array
array[method] = function (old_a, ...)
local a = new_array();
return base_method(a, old_a, ...);
end
-- Setup per-array (mutating) method
array_methods[method] = function (self, ...)
return base_method(self, self, ...);
end
end
_G.array = array;
module("array");
return array;
|
util.array: Fix for array:filter() (in-place filtering)
|
util.array: Fix for array:filter() (in-place filtering)
|
Lua
|
mit
|
sarumjanuch/prosody,sarumjanuch/prosody
|
5002dcdce7c9a17a613a7877864ccee5ba18e765
|
MMOCoreORB/bin/scripts/object/tangible/terminal/serverobjects.lua
|
MMOCoreORB/bin/scripts/object/tangible/terminal/serverobjects.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
--Children folder includes
includeFile("tangible/terminal/base/serverobjects.lua")
-- Server Objects
includeFile("tangible/terminal/terminal_ballot_box.lua")
includeFile("tangible/terminal/terminal_bank.lua")
includeFile("tangible/terminal/terminal_bazaar.lua")
includeFile("tangible/terminal/terminal_bestine_quests_01.lua")
includeFile("tangible/terminal/terminal_bestine_quests_02.lua")
includeFile("tangible/terminal/terminal_bestine_quests_03.lua")
includeFile("tangible/terminal/terminal_bounty_droid.lua")
includeFile("tangible/terminal/terminal_character_builder.lua")
includeFile("tangible/terminal/terminal_city.lua")
includeFile("tangible/terminal/terminal_city_vote.lua")
includeFile("tangible/terminal/terminal_cloning.lua")
includeFile("tangible/terminal/terminal_command_console.lua")
includeFile("tangible/terminal/terminal_dark_enclave_challenge.lua")
includeFile("tangible/terminal/terminal_dark_enclave_voting.lua")
includeFile("tangible/terminal/terminal_elevator.lua")
includeFile("tangible/terminal/terminal_elevator_down.lua")
includeFile("tangible/terminal/terminal_elevator_up.lua")
includeFile("tangible/terminal/terminal_elevator_down_guild.lua")
includeFile("tangible/terminal/terminal_elevator_up_guild.lua")
includeFile("tangible/terminal/terminal_geo_bunker.lua")
includeFile("tangible/terminal/terminal_guild.lua")
includeFile("tangible/terminal/terminal_hq.lua")
includeFile("tangible/terminal/terminal_hq_imperial.lua")
includeFile("tangible/terminal/terminal_hq_rebel.lua")
includeFile("tangible/terminal/terminal_hq_turret_control.lua")
includeFile("tangible/terminal/terminal_imagedesign.lua")
includeFile("tangible/terminal/terminal_insurance.lua")
includeFile("tangible/terminal/terminal_jukebox.lua")
includeFile("tangible/terminal/terminal_light_enclave_challenge.lua")
includeFile("tangible/terminal/terminal_light_enclave_voting.lua")
includeFile("tangible/terminal/terminal_mission.lua")
includeFile("tangible/terminal/terminal_mission_artisan.lua")
includeFile("tangible/terminal/terminal_mission_bounty.lua")
includeFile("tangible/terminal/terminal_mission_entertainer.lua")
includeFile("tangible/terminal/terminal_mission_imperial.lua")
includeFile("tangible/terminal/terminal_mission_newbie.lua")
includeFile("tangible/terminal/terminal_mission_rebel.lua")
includeFile("tangible/terminal/terminal_mission_scout.lua")
includeFile("tangible/terminal/terminal_mission_statue.lua")
includeFile("tangible/terminal/terminal_newbie_clothing.lua")
includeFile("tangible/terminal/terminal_newbie_food.lua")
includeFile("tangible/terminal/terminal_newbie_instrument.lua")
includeFile("tangible/terminal/terminal_newbie_medicine.lua")
includeFile("tangible/terminal/terminal_newbie_tool.lua")
includeFile("tangible/terminal/terminal_newsnet.lua")
includeFile("tangible/terminal/terminal_nym_cave.lua")
includeFile("tangible/terminal/terminal_player_structure.lua")
includeFile("tangible/terminal/terminal_player_structure_nosnap.lua")
includeFile("tangible/terminal/terminal_player_structure_nosnap_mini.lua")
includeFile("tangible/terminal/terminal_pm_register.lua")
includeFile("tangible/terminal/terminal_pob_ship.lua")
includeFile("tangible/terminal/terminal_ship_interior_security_1.lua")
includeFile("tangible/terminal/terminal_shipping.lua")
includeFile("tangible/terminal/terminal_skill.lua")
includeFile("tangible/terminal/terminal_space.lua")
includeFile("tangible/terminal/terminal_travel.lua")
includeFile("tangible/terminal/terminal_water_pressure.lua")
includeFile("tangible/terminal/test.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
--Children folder includes
includeFile("tangible/terminal/base/serverobjects.lua")
-- Server Objects
includeFile("tangible/terminal/terminal_ballot_box.lua")
includeFile("tangible/terminal/terminal_bank.lua")
includeFile("tangible/terminal/terminal_bazaar.lua")
includeFile("tangible/terminal/terminal_bestine_quests_01.lua")
includeFile("tangible/terminal/terminal_bestine_quests_02.lua")
includeFile("tangible/terminal/terminal_bestine_quests_03.lua")
includeFile("tangible/terminal/terminal_bounty_droid.lua")
includeFile("tangible/terminal/terminal_character_builder.lua")
includeFile("tangible/terminal/terminal_city.lua")
includeFile("tangible/terminal/terminal_city_vote.lua")
includeFile("tangible/terminal/terminal_cloning.lua")
includeFile("tangible/terminal/terminal_command_console.lua")
includeFile("tangible/terminal/terminal_dark_enclave_challenge.lua")
includeFile("tangible/terminal/terminal_dark_enclave_voting.lua")
includeFile("tangible/terminal/terminal_elevator.lua")
includeFile("tangible/terminal/terminal_elevator_down.lua")
includeFile("tangible/terminal/terminal_elevator_up.lua")
includeFile("tangible/terminal/terminal_geo_bunker.lua")
includeFile("tangible/terminal/terminal_guild.lua")
includeFile("tangible/terminal/terminal_hq.lua")
includeFile("tangible/terminal/terminal_hq_imperial.lua")
includeFile("tangible/terminal/terminal_hq_rebel.lua")
includeFile("tangible/terminal/terminal_hq_turret_control.lua")
includeFile("tangible/terminal/terminal_imagedesign.lua")
includeFile("tangible/terminal/terminal_insurance.lua")
includeFile("tangible/terminal/terminal_jukebox.lua")
includeFile("tangible/terminal/terminal_light_enclave_challenge.lua")
includeFile("tangible/terminal/terminal_light_enclave_voting.lua")
includeFile("tangible/terminal/terminal_mission.lua")
includeFile("tangible/terminal/terminal_mission_artisan.lua")
includeFile("tangible/terminal/terminal_mission_bounty.lua")
includeFile("tangible/terminal/terminal_mission_entertainer.lua")
includeFile("tangible/terminal/terminal_mission_imperial.lua")
includeFile("tangible/terminal/terminal_mission_newbie.lua")
includeFile("tangible/terminal/terminal_mission_rebel.lua")
includeFile("tangible/terminal/terminal_mission_scout.lua")
includeFile("tangible/terminal/terminal_mission_statue.lua")
includeFile("tangible/terminal/terminal_newbie_clothing.lua")
includeFile("tangible/terminal/terminal_newbie_food.lua")
includeFile("tangible/terminal/terminal_newbie_instrument.lua")
includeFile("tangible/terminal/terminal_newbie_medicine.lua")
includeFile("tangible/terminal/terminal_newbie_tool.lua")
includeFile("tangible/terminal/terminal_newsnet.lua")
includeFile("tangible/terminal/terminal_nym_cave.lua")
includeFile("tangible/terminal/terminal_player_structure.lua")
includeFile("tangible/terminal/terminal_player_structure_nosnap.lua")
includeFile("tangible/terminal/terminal_player_structure_nosnap_mini.lua")
includeFile("tangible/terminal/terminal_pm_register.lua")
includeFile("tangible/terminal/terminal_pob_ship.lua")
includeFile("tangible/terminal/terminal_ship_interior_security_1.lua")
includeFile("tangible/terminal/terminal_shipping.lua")
includeFile("tangible/terminal/terminal_skill.lua")
includeFile("tangible/terminal/terminal_space.lua")
includeFile("tangible/terminal/terminal_travel.lua")
includeFile("tangible/terminal/terminal_water_pressure.lua")
includeFile("tangible/terminal/test.lua")
|
[fixed] elevator luas include
|
[fixed] elevator luas include
git-svn-id: c34995188cc7e843f8a799edec2d9d4b36f36456@2718 c3d1530f-68f5-4bd0-87dc-8ef779617e40
|
Lua
|
agpl-3.0
|
lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo
|
d74e442e61b740ae818f3fe9276630256f6b9718
|
share/media/101greatgoals.lua
|
share/media/101greatgoals.lua
|
-- libquvi-scripts
-- Copyright (C) 2013 Toni Gundogdu <[email protected]>
-- Copyright (C) 2012 quvi project
--
-- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>.
--
-- This program is free software: you can redistribute it and/or
-- modify it under the terms of the GNU Affero General Public
-- License as published by the Free Software Foundation, either
-- version 3 of the License, or (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU Affero General Public License for more details.
--
-- You should have received a copy of the GNU Affero General
-- Public License along with this program. If not, see
-- <http://www.gnu.org/licenses/>.
--
-- Hundred and One Great Goals (aggregator)
local HaOgg = {} -- Utility functions specific to this script
-- Identify the media script.
function ident(qargs)
return {
can_parse_url = HaOgg.can_parse_url(qargs),
domains = table.concat({'101greatgoals.com'}, ',')
}
end
-- Parse the media properties.
function parse(qargs)
local p = quvi.http.fetch(qargs.input_url).data
qargs.goto_url = HaOgg.chk_self_hosted(p) or HaOgg.chk_embedded(p)
or error('unable to determine media source')
return qargs
end
--
-- Utility functions
--
function HaOgg.can_parse_url(qargs)
local U = require 'socket.url'
local t = U.parse(qargs.input_url)
if t and t.scheme and t.scheme:lower():match('^http$')
and t.host and t.host:lower():match('101greatgoals%.com$')
and t.path and t.path:lower():match('^/gvideos/.+/$')
then
return true
else
return false
end
end
function HaOgg.chk_self_hosted(p)
--
-- Previously referred to as the "self-hosted" media, although according
-- to the old notes, these were typically hosted by YouTube.
-- http://is.gd/EKKPy2
--
-- 2013-05-05: The contents of the URL no longer seems to contain the
-- "file" value, see chk_embedded for notes; keep this
-- function around for now
--
local d = p:match('%.setup%((.-)%)')
if d then
local s = d:match('"file":"(.-)"') or error('no match: file')
if #s ==0 then
error('empty media URL ("file")')
end
local U = require 'quvi/util'
return (U.slash_unescape(U.unescape(s)))
end
end
function HaOgg.chk_embedded(p)
--
-- 2013-05-05: Most of the content appears to be embedded from elsewhere
--
-- Instead of trying to check for each, parse the likely embedded source
-- and pass it back to libquvi to find a media script that accepts the
-- parsed (embedded) media URL.
--
-- NOTE: This means that those media scripts must unwrangle the embedded
-- media URLs passed from this script
--
local s = p:match('class="post%-type%-gvideos">(.-)</')
or p:match('id="jwplayer%-1">(.-)</>')
or error('unable to determine embedded source')
return s:match('value="(.-)"') or s:match('src="(.-)"')
end
-- vim: set ts=2 sw=2 tw=72 expandtab:
|
-- libquvi-scripts
-- Copyright (C) 2013 Toni Gundogdu <[email protected]>
-- Copyright (C) 2012 quvi project
--
-- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>.
--
-- This program is free software: you can redistribute it and/or
-- modify it under the terms of the GNU Affero General Public
-- License as published by the Free Software Foundation, either
-- version 3 of the License, or (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU Affero General Public License for more details.
--
-- You should have received a copy of the GNU Affero General
-- Public License along with this program. If not, see
-- <http://www.gnu.org/licenses/>.
--
-- Hundred and One Great Goals (aggregator)
local HaOgg = {} -- Utility functions specific to this script
-- Identify the media script.
function ident(qargs)
return {
can_parse_url = HaOgg.can_parse_url(qargs),
domains = table.concat({'101greatgoals.com'}, ',')
}
end
-- Parse the media properties.
function parse(qargs)
local p = quvi.http.fetch(qargs.input_url).data
qargs.goto_url = HaOgg.chk_self_hosted(p) or HaOgg.chk_embedded(p)
or error('unable to determine media source')
return qargs
end
--
-- Utility functions
--
function HaOgg.can_parse_url(qargs)
local U = require 'socket.url'
local t = U.parse(qargs.input_url)
if t and t.scheme and t.scheme:lower():match('^http$')
and t.host and t.host:lower():match('101greatgoals%.com$')
and t.path and t.path:lower():match('^/gvideos/.+/$')
then
return true
else
return false
end
end
function HaOgg.chk_self_hosted(p)
--
-- Previously referred to as the "self-hosted" media, although according
-- to the old notes, these were typically hosted by YouTube.
-- http://is.gd/EKKPy2
--
-- 2013-05-05: The contents of the URL no longer seems to contain the
-- "file" value, see chk_embedded for notes; keep this
-- function around for now
--
local d = p:match('%.setup%((.-)%)')
if d then
local s = d:match('"file":"(.-)"') or error('no match: file')
if #s ==0 then
error('empty media URL ("file")')
end
local U = require 'quvi/util'
return (U.slash_unescape(U.unescape(s)))
end
end
function HaOgg.chk_embedded(p)
--
-- 2013-05-05: Most of the content appears to be embedded from elsewhere
--
-- Instead of trying to check for each, parse the likely embedded source
-- and pass it back to libquvi to find a media script that accepts the
-- parsed (embedded) media URL.
--
local s = p:match('class="post%-type%-gvideos">(.-)</')
or p:match('id="jwplayer%-1">(.-)</>')
or error('unable to determine embedded source')
s = s:match('value="(.-)"') or s:match('src="(.-)"')
local U = require 'socket.url'
local t = U.parse(s)
if not t.scheme then -- Make sure the URL has a scheme.
t.scheme = 'http'
end
return U.build(t)
end
-- vim: set ts=2 sw=2 tw=72 expandtab:
|
FIX: media/101greatgoals: redirect: Add URL scheme
|
FIX: media/101greatgoals: redirect: Add URL scheme
Make sure the redirection URL has a scheme.
Signed-off-by: Toni Gundogdu <[email protected]>
|
Lua
|
agpl-3.0
|
legatvs/libquvi-scripts,alech/libquvi-scripts,legatvs/libquvi-scripts,alech/libquvi-scripts
|
f017ecd721b25a41a3d7dc9f91b95abd16b6ace9
|
mods/es/stair.lua
|
mods/es/stair.lua
|
--Extreme Survival created by maikerumine
-- Minetest 0.4.13 mod: "Extreme Survival"
-- namespace: es
--https://github.com/maikerumine
--License:
--~~~~~~~~
--Code:
--(c) Copyright 2015 maikerumine; modified zlib-License
--see "LICENSE.txt" for details.
--Media(if not stated differently):
--(c) Copyright (2014-2015) maikerumine; CC-BY-SA 3.0
es = {}
function stairs.register_stair_and_slab(subname, recipeitem, groups, images,
desc_stair, desc_slab, sounds)
stairs.register_stair(subname, recipeitem, groups, images, desc_stair, sounds)
stairs.register_slab(subname, recipeitem, groups, images, desc_slab, sounds)
end
--TECHNIC STAIRS
stairs.register_stair_and_slab("granite", "es:granite",
{cracky = 1},
{"technic_granite.png"},
"Granite Block Stair",
"Granite Block Slab",
default.node_sound_stone_defaults())
stairs.register_stair_and_slab("marble", "es:marble",
{cracky = 1},
{"technic_marble.png"},
"Marble Block Stair",
"Marble Block Slab",
default.node_sound_stone_defaults())
stairs.register_stair_and_slab("marble bricks", "es:marble_bricks",
{cracky = 1},
{"technic_marble_bricks.png" },
"Marble Brick Block Stair",
"Marble Brick Block Slab",
default.node_sound_stone_defaults())
--Extreme Survival Stairs
stairs.register_stair_and_slab("Ruby", "es:rubyblock",
{cracky = 1},
{"ruby_block.png"},
"Ruby Block Stair",
"Ruby Block Slab",
default.node_sound_stone_defaults())
stairs.register_stair_and_slab("Emerald", "es:emeraldblock",
{cracky = 1},
{"emerald_block.png"},
"Emerald Block Stair",
"Emerald Block Slab",
default.node_sound_stone_defaults())
stairs.register_stair_and_slab("Aikerum", "es:aikerumblock",
{cracky = 1},
{"aikerum_block.png"},
"Aikerum Block Stair",
"Aikerum Block Slab",
default.node_sound_stone_defaults())
stairs.register_stair_and_slab("Infinium", "es:infiniumblock",
{cracky = 1},
{"infinium_block.png"},
"Infinium Block Stair",
"Infinium Block Slab",
default.node_sound_stone_defaults())
stairs.register_stair_and_slab("Purpellium", "es:purpelliumblock",
{cracky = 1},
{"purpellium_block.png"},
"Purpellium Block Stair",
"Purpellium Block Slab",
default.node_sound_stone_defaults())
stairs.register_stair_and_slab("Dirt", "default:dirt",
{cracky = 3, crumbly = 3,},
{"default_dirt.png"},
"Dirt Block Stair",
"Dirt Block Slab",
default.node_sound_stone_defaults())
|
--Extreme Survival created by maikerumine
-- Minetest 0.4.13 mod: "Extreme Survival"
-- namespace: es
--https://github.com/maikerumine
--License:
--~~~~~~~~
--Code:
--(c) Copyright 2015 maikerumine; modified zlib-License
--see "LICENSE.txt" for details.
--Media(if not stated differently):
--(c) Copyright (2014-2015) maikerumine; CC-BY-SA 3.0
es = {}
function stairs.register_stair_and_slab(subname, recipeitem, groups, images,
desc_stair, desc_slab, sounds)
stairs.register_stair(subname, recipeitem, groups, images, desc_stair, sounds)
stairs.register_slab(subname, recipeitem, groups, images, desc_slab, sounds)
end
--TECHNIC STAIRS
stairs.register_stair_and_slab("granite", "es:granite",
{cracky = 1},
{"technic_granite.png"},
"Granite Block Stair",
"Granite Block Slab",
default.node_sound_stone_defaults())
stairs.register_stair_and_slab("marble", "es:marble",
{cracky = 1},
{"technic_marble.png"},
"Marble Block Stair",
"Marble Block Slab",
default.node_sound_stone_defaults())
stairs.register_stair_and_slab("marblebricks", "es:marble_bricks",
{cracky = 1},
{"technic_marble_bricks.png" },
"Marble Brick Block Stair",
"Marble Brick Block Slab",
default.node_sound_stone_defaults())
stairs.register_stair_and_slab("granitebricks", "es:granite_bricks",
{cracky = 1},
{"technic_granite_bricks.png" },
"Granite Brick Block Stair",
"Granite Brick Block Slab",
default.node_sound_stone_defaults())
--Extreme Survival Stairs
stairs.register_stair_and_slab("Ruby", "es:rubyblock",
{cracky = 1},
{"ruby_block.png"},
"Ruby Block Stair",
"Ruby Block Slab",
default.node_sound_stone_defaults())
stairs.register_stair_and_slab("Emerald", "es:emeraldblock",
{cracky = 1},
{"emerald_block.png"},
"Emerald Block Stair",
"Emerald Block Slab",
default.node_sound_stone_defaults())
stairs.register_stair_and_slab("Aikerum", "es:aikerumblock",
{cracky = 1},
{"aikerum_block.png"},
"Aikerum Block Stair",
"Aikerum Block Slab",
default.node_sound_stone_defaults())
stairs.register_stair_and_slab("Infinium", "es:infiniumblock",
{cracky = 1},
{"infinium_block.png"},
"Infinium Block Stair",
"Infinium Block Slab",
default.node_sound_stone_defaults())
stairs.register_stair_and_slab("Purpellium", "es:purpelliumblock",
{cracky = 1},
{"purpellium_block.png"},
"Purpellium Block Stair",
"Purpellium Block Slab",
default.node_sound_stone_defaults())
stairs.register_stair_and_slab("Dirt", "default:dirt",
{cracky = 3, crumbly = 3,},
{"default_dirt.png"},
"Dirt Block Stair",
"Dirt Block Slab",
default.node_sound_stone_defaults())
|
fix mess up
|
fix mess up
|
Lua
|
lgpl-2.1
|
maikerumine/extreme_survival
|
33a5cba61115e935a57b7a7886abaa2cd77690c9
|
mod_pastebin/mod_pastebin.lua
|
mod_pastebin/mod_pastebin.lua
|
local st = require "util.stanza";
local httpserver = require "net.httpserver";
local uuid_new = require "util.uuid".generate;
local os_time = os.time;
local t_insert, t_remove = table.insert, table.remove;
local add_task = require "util.timer".add_task;
local utf8_pattern = "[\194-\244][\128-\191]*$";
local function drop_invalid_utf8(seq)
local start = seq:byte();
module:log("utf8: %d, %d", start, #seq);
if (start <= 223 and #seq < 2)
or (start >= 224 and start <= 239 and #seq < 3)
or (start >= 240 and start <= 244 and #seq < 4)
or (start > 244) then
return "";
end
return seq;
end
local function utf8_length(str)
local _, count = string.gsub(str, "[^\128-\193]", "");
return count;
end
local pastebin_private_messages = module:get_option_boolean("pastebin_private_messages", hosts[module.host].type ~= "component");
local length_threshold = module:get_option_number("pastebin_threshold", 500);
local line_threshold = module:get_option_number("pastebin_line_threshold", 4);
local max_summary_length = module:get_option_number("pastebin_summary_length", 150);
local html_preview = module:get_option_boolean("pastebin_html_preview", true);
local base_url = module:get_option_string("pastebin_url");
-- Seconds a paste should live for in seconds (config is in hours), default 24 hours
local expire_after = math.floor(module:get_option_number("pastebin_expire_after", 24) * 3600);
local trigger_string = module:get_option_string("pastebin_trigger");
trigger_string = (trigger_string and trigger_string .. " ");
local pastes = {};
local default_headers = { ["Content-Type"] = "text/plain; charset=utf-8" };
local xmlns_xhtmlim = "http://jabber.org/protocol/xhtml-im";
local xmlns_xhtml = "http://www.w3.org/1999/xhtml";
if expire_after == 0 then
local dm = require "util.datamanager";
setmetatable(pastes, {
__index = function (pastes, id)
if type(id) == "string" then
return dm.load(id, module.host, "pastebin");
end
end;
__newindex = function (pastes, id, data)
if type(id) == "string" then
dm.store(id, module.host, "pastebin", data);
end
end;
});
else
setmetatable(pastes, nil);
end
function pastebin_text(text)
local uuid = uuid_new();
pastes[uuid] = { body = text, time = os_time(), headers = default_headers };
pastes[#pastes+1] = uuid;
if not pastes[2] then -- No other pastes, give the timer a kick
add_task(expire_after, expire_pastes);
end
return base_url..uuid;
end
function handle_request(method, body, request)
local pasteid = request.url.path:match("[^/]+$");
if not pasteid or not pastes[pasteid] then
return "Invalid paste id, perhaps it expired?";
end
--module:log("debug", "Received request, replying: %s", pastes[pasteid].text);
return pastes[pasteid];
end
function check_message(data)
local origin, stanza = data.origin, data.stanza;
local body, bodyindex, htmlindex;
for k,v in ipairs(stanza) do
if v.name == "body" then
body, bodyindex = v, k;
elseif v.name == "html" and v.attr.xmlns == xmlns_xhtmlim then
htmlindex = k;
end
end
if not body then return; end
body = body:get_text();
--module:log("debug", "Body(%s) length: %d", type(body), #(body or ""));
if body and (
((#body > length_threshold)
and (utf8_length(body) > length_threshold)) or
(trigger_string and body:find(trigger_string, 1, true) == 1) or
(select(2, body:gsub("\n", "%0")) >= line_threshold)
) then
if trigger_string then
body = body:gsub("^" .. trigger_string, "", 1);
end
local url = pastebin_text(body);
module:log("debug", "Pasted message as %s", url);
--module:log("debug", " stanza[bodyindex] = %q", tostring( stanza[bodyindex]));
local summary = (body:sub(1, max_summary_length):gsub(utf8_pattern, drop_invalid_utf8) or ""):match("[^\n]+") or "";
summary = summary:match("^%s*(.-)%s*$");
local summary_prefixed = summary:match("[,:]$");
stanza[bodyindex][1] = (summary_prefixed and (summary.." ") or "")..url;
if html_preview then
local line_count = select(2, body:gsub("\n", "%0")) + 1;
local link_text = ("[view %spaste (%d line%s)]"):format(summary_prefixed and "" or "rest of ", line_count, line_count == 1 and "" or "s");
local html = st.stanza("html", { xmlns = xmlns_xhtmlim }):tag("body", { xmlns = xmlns_xhtml });
html:tag("p"):text(summary.." "):up();
html:tag("a", { href = url }):text(link_text):up();
stanza[htmlindex or #stanza+1] = html;
end
end
end
module:hook("message/bare", check_message);
if pastebin_private_messages then
module:hook("message/full", check_message);
end
function expire_pastes(time)
time = time or os_time(); -- COMPAT with 0.5
if pastes[1] then
pastes[pastes[1]] = nil;
t_remove(pastes, 1);
if pastes[1] then
return (expire_after - (time - pastes[pastes[1]].time)) + 1;
end
end
end
local ports = module:get_option("pastebin_ports", { 5280 });
for _, options in ipairs(ports) do
local port, base, ssl, interface = 5280, "pastebin", false, nil;
if type(options) == "number" then
port = options;
elseif type(options) == "table" then
port, base, ssl, interface = options.port or 5280, options.path or "pastebin", options.ssl or false, options.interface;
elseif type(options) == "string" then
base = options;
end
base_url = base_url or ("http://"..module:get_host()..(port ~= 80 and (":"..port) or "").."/"..base.."/");
httpserver.new{ port = port, base = base, handler = handle_request, ssl = ssl }
end
function module.save()
return { pastes = pastes };
end
function module.restore(data)
pastes = data.pastes or pastes;
end
|
local st = require "util.stanza";
local httpserver = require "net.httpserver";
local uuid_new = require "util.uuid".generate;
local os_time = os.time;
local t_insert, t_remove = table.insert, table.remove;
local add_task = require "util.timer".add_task;
local utf8_pattern = "[\194-\244][\128-\191]*$";
local function drop_invalid_utf8(seq)
local start = seq:byte();
module:log("utf8: %d, %d", start, #seq);
if (start <= 223 and #seq < 2)
or (start >= 224 and start <= 239 and #seq < 3)
or (start >= 240 and start <= 244 and #seq < 4)
or (start > 244) then
return "";
end
return seq;
end
local function utf8_length(str)
local _, count = string.gsub(str, "[^\128-\193]", "");
return count;
end
local pastebin_private_messages = module:get_option_boolean("pastebin_private_messages", hosts[module.host].type ~= "component");
local length_threshold = module:get_option_number("pastebin_threshold", 500);
local line_threshold = module:get_option_number("pastebin_line_threshold", 4);
local max_summary_length = module:get_option_number("pastebin_summary_length", 150);
local html_preview = module:get_option_boolean("pastebin_html_preview", true);
local base_url = module:get_option_string("pastebin_url");
-- Seconds a paste should live for in seconds (config is in hours), default 24 hours
local expire_after = math.floor(module:get_option_number("pastebin_expire_after", 24) * 3600);
local trigger_string = module:get_option_string("pastebin_trigger");
trigger_string = (trigger_string and trigger_string .. " ");
local pastes = {};
local default_headers = { ["Content-Type"] = "text/plain; charset=utf-8" };
local xmlns_xhtmlim = "http://jabber.org/protocol/xhtml-im";
local xmlns_xhtml = "http://www.w3.org/1999/xhtml";
function pastebin_text(text)
local uuid = uuid_new();
pastes[uuid] = { body = text, time = os_time(), headers = default_headers };
pastes[#pastes+1] = uuid;
if not pastes[2] then -- No other pastes, give the timer a kick
add_task(expire_after, expire_pastes);
end
return base_url..uuid;
end
function handle_request(method, body, request)
local pasteid = request.url.path:match("[^/]+$");
if not pasteid or not pastes[pasteid] then
return "Invalid paste id, perhaps it expired?";
end
--module:log("debug", "Received request, replying: %s", pastes[pasteid].text);
return pastes[pasteid];
end
function check_message(data)
local origin, stanza = data.origin, data.stanza;
local body, bodyindex, htmlindex;
for k,v in ipairs(stanza) do
if v.name == "body" then
body, bodyindex = v, k;
elseif v.name == "html" and v.attr.xmlns == xmlns_xhtmlim then
htmlindex = k;
end
end
if not body then return; end
body = body:get_text();
--module:log("debug", "Body(%s) length: %d", type(body), #(body or ""));
if body and (
((#body > length_threshold)
and (utf8_length(body) > length_threshold)) or
(trigger_string and body:find(trigger_string, 1, true) == 1) or
(select(2, body:gsub("\n", "%0")) >= line_threshold)
) then
if trigger_string then
body = body:gsub("^" .. trigger_string, "", 1);
end
local url = pastebin_text(body);
module:log("debug", "Pasted message as %s", url);
--module:log("debug", " stanza[bodyindex] = %q", tostring( stanza[bodyindex]));
local summary = (body:sub(1, max_summary_length):gsub(utf8_pattern, drop_invalid_utf8) or ""):match("[^\n]+") or "";
summary = summary:match("^%s*(.-)%s*$");
local summary_prefixed = summary:match("[,:]$");
stanza[bodyindex][1] = (summary_prefixed and (summary.." ") or "")..url;
if html_preview then
local line_count = select(2, body:gsub("\n", "%0")) + 1;
local link_text = ("[view %spaste (%d line%s)]"):format(summary_prefixed and "" or "rest of ", line_count, line_count == 1 and "" or "s");
local html = st.stanza("html", { xmlns = xmlns_xhtmlim }):tag("body", { xmlns = xmlns_xhtml });
html:tag("p"):text(summary.." "):up();
html:tag("a", { href = url }):text(link_text):up();
stanza[htmlindex or #stanza+1] = html;
end
end
end
module:hook("message/bare", check_message);
if pastebin_private_messages then
module:hook("message/full", check_message);
end
function expire_pastes(time)
time = time or os_time(); -- COMPAT with 0.5
if pastes[1] then
pastes[pastes[1]] = nil;
t_remove(pastes, 1);
if pastes[1] then
return (expire_after - (time - pastes[pastes[1]].time)) + 1;
end
end
end
local ports = module:get_option("pastebin_ports", { 5280 });
for _, options in ipairs(ports) do
local port, base, ssl, interface = 5280, "pastebin", false, nil;
if type(options) == "number" then
port = options;
elseif type(options) == "table" then
port, base, ssl, interface = options.port or 5280, options.path or "pastebin", options.ssl or false, options.interface;
elseif type(options) == "string" then
base = options;
end
base_url = base_url or ("http://"..module:get_host()..(port ~= 80 and (":"..port) or "").."/"..base.."/");
httpserver.new{ port = port, base = base, handler = handle_request, ssl = ssl }
end
function module.load()
if expire_after == 0 then
local dm = require "util.datamanager";
setmetatable(pastes, {
__index = function (pastes, id)
if type(id) == "string" then
return dm.load(id, module.host, "pastebin");
end
end;
__newindex = function (pastes, id, data)
if type(id) == "string" then
dm.store(id, module.host, "pastebin", data);
end
end;
});
else
setmetatable(pastes, nil);
end
end
function module.save()
return { pastes = pastes };
end
function module.restore(data)
pastes = data.pastes or pastes;
end
|
mod_pastebin: Fix issue with metatable not being set when a reload changes expires_after to 0
|
mod_pastebin: Fix issue with metatable not being set when a reload changes expires_after to 0
|
Lua
|
mit
|
prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2
|
109b36f7ad79f7ec3a04fe586f606d329d60dd0d
|
mod_register_json/mod_register_json.lua
|
mod_register_json/mod_register_json.lua
|
-- Expose a simple servlet to handle user registrations from web pages
-- via JSON.
--
-- A Good chunk of the code is from mod_data_access.lua by Kim Alvefur
-- aka Zash.
local usermanager = require "core.usermanager";
local b64_decode = require "util.encodings".base64.decode;
local json_decode = require "util.json".decode;
module.host = "*" -- HTTP/BOSH Servlets need to be global.
-- Pick up configuration.
local set_realm_name = module:get_option("reg_servlet_realm") or "Restricted";
local throttle_time = module:get_option("reg_servlet_ttime") or false;
local whitelist = module:get_option("reg_servlet_wl") or {};
local blacklist = module:get_option("reg_servlet_bl") or {};
local recent_ips = {};
-- Begin
for _, ip in ipairs(whitelist) do whitelisted_ips[ip] = true; end
for _, ip in ipairs(blacklist) do blacklisted_ips[ip] = true; end
local function http_response(code, message, extra_headers)
local response = {
status = code .. " " .. message;
body = message .. "\n"; }
if extra_headers then response.headers = extra_headers; end
return response
end
local function handle_req(method, body, request)
if request.method ~= "POST" then
return http_response(405, "Bad method...", {["Allow"] = "POST"});
end
if not request.headers["authorization"] then
return http_response(401, "No... No...",
{["WWW-Authenticate"]='Basic realm="'.. set_realm_name ..'"'})
end
local user, password = b64_decode(request.headers.authorization
:match("[^ ]*$") or ""):match("([^:]*):(.*)");
user = jid_prep(user);
if not user or not password then return http_response(400, "What's this..?"); end
local user_node, user_host = jid_split(user)
if not hosts[user_host] then return http_response(401, "Negative."); end
module:log("warn", "%s is authing to submit a new user registration data", user)
if not usermanager.test_password(user_node, user_host, password) then
module:log("warn", "%s failed authentication", user)
return http_response(401, "Who the hell are you?! Guards!");
end
local req_body; pcall(function() req_body = json.decode(body) end);
-- Check if user is an admin of said host
if not usermanager.is_admin(user, req_body["host"]) then
module:log("warn", "%s tried to submit registration data for %s but he's not an admin", user, req_body["host"])
return http_response(401, "I obey only to my masters... Have a nice day.");
else
-- Various sanity checks.
if req_body == nil then module:log("debug", "JSON data submitted for user registration by %s failed to Decode.", user); return http_response(400, "JSON Decoding failed."); end
-- Checks for both Throttling/Whitelist and Blacklist (basically copycatted from prosody's register.lua code)
if blacklist[req_body["ip"]] then module:log("warn", "Attempt of reg. submission to the JSON servlet from blacklisted address: %s", req_body["ip"]); return http_response(403, "The specified address is blacklisted, sorry sorry."); end
if throttle_time and not whitelist[req_body["ip"]] then
if not recent_ips[req_body["ip"]] then
recent_ips[req_body["ip"]] = { time = os_time(), count = 1 };
else
local ip = recent_ips[req_body["ip"]];
ip.count = ip.count + 1;
if os_time() - ip.time < throttle_time then
ip.time = os_time();
module:log("warn", "JSON Registration request from %s has been throttled.", req_body["ip"]);
return http_response(503, "Woah... How many users you want to register..? Request throttled, wait a bit and try again.");
end
ip.time = os_time();
end
end
-- We first check if the supplied username for registration is already there.
if not usermanager.user_exists(req_body["username"], req_body["host"]) then
usermanager.create_user(req_body["username"], req_body["password"], req_body["host"]);
module:log("debug", "%s registration data submission for %s is successful", user, req_body["user"]);
return http_response(200, "Done.");
else
module:log("debug", "%s registration data submission for %s failed (user already exists)", user, req_body["user"]);
return http_response(409, "User already exists.");
end
end
end
-- Set it up!
local function setup()
local ports = module:get_option("reg_servlet_port") or { 9280 };
local base_name = module:get_option("reg_servlet_base") or "register_account";
local ssl_cert = module:get_option("reg_servlet_sslcert") or false;
local ssl_key = module:get_option("reg_servlet_sslkey") or false;
if not ssl_cert or not ssl_key then
require "net.httpserver".new_from_config(ports, handle_req, { base = base_name });
else
if module:get_option("reg_servlet_port") == nil then ports = { 9443 }; end
require "net.httpserver".new_from_config(ports, handle_req, { ssl = { key = ssl_key, certificate = ssl_cert }, base = base_name });
end
end
if prosody.start_time then -- already started
setup();
else
prosody.events.add_handler("server-started", setup);
end
|
-- Expose a simple servlet to handle user registrations from web pages
-- via JSON.
--
-- A Good chunk of the code is from mod_data_access.lua by Kim Alvefur
-- aka Zash.
local jid_prep = require "util.jid".prep;
local jid_split = require "util.jid".split;
local usermanager = require "core.usermanager";
local b64_decode = require "util.encodings".base64.decode;
local json_decode = require "util.json".decode;
module.host = "*" -- HTTP/BOSH Servlets need to be global.
-- Pick up configuration.
local set_realm_name = module:get_option("reg_servlet_realm") or "Restricted";
local throttle_time = module:get_option("reg_servlet_ttime") or false;
local whitelist = module:get_option("reg_servlet_wl") or {};
local blacklist = module:get_option("reg_servlet_bl") or {};
local recent_ips = {};
-- Begin
for _, ip in ipairs(whitelist) do whitelisted_ips[ip] = true; end
for _, ip in ipairs(blacklist) do blacklisted_ips[ip] = true; end
local function http_response(code, message, extra_headers)
local response = {
status = code .. " " .. message;
body = message .. "\n"; }
if extra_headers then response.headers = extra_headers; end
return response
end
local function handle_req(method, body, request)
if request.method ~= "POST" then
return http_response(405, "Bad method...", {["Allow"] = "POST"});
end
if not request.headers["authorization"] then
return http_response(401, "No... No...",
{["WWW-Authenticate"]='Basic realm="'.. set_realm_name ..'"'})
end
local user, password = b64_decode(request.headers.authorization
:match("[^ ]*$") or ""):match("([^:]*):(.*)");
user = jid_prep(user);
if not user or not password then return http_response(400, "What's this..?"); end
local user_node, user_host = jid_split(user)
if not hosts[user_host] then return http_response(401, "Negative."); end
module:log("warn", "%s is authing to submit a new user registration data", user)
if not usermanager.test_password(user_node, user_host, password) then
module:log("warn", "%s failed authentication", user)
return http_response(401, "Who the hell are you?! Guards!");
end
local req_body;
-- We check that what we have is valid JSON wise else we throw an error...
if not pcall(function() req_body = json_decode(body) end) then
module:log("debug", "JSON data submitted for user registration by %s failed to Decode.", user);
return http_response(400, "JSON Decoding failed.");
else
-- Check if user is an admin of said host
if not usermanager.is_admin(user, req_body["host"]) then
module:log("warn", "%s tried to submit registration data for %s but he's not an admin", user, req_body["host"]);
return http_response(401, "I obey only to my masters... Have a nice day.");
else
-- Checks for both Throttling/Whitelist and Blacklist (basically copycatted from prosody's register.lua code)
if blacklist[req_body["ip"]] then then module:log("warn", "Attempt of reg. submission to the JSON servlet from blacklisted address: %s", req_body["ip"]); return http_response(403, "The specified address is blacklisted, sorry sorry."); end
if throttle_time and not whitelist[req_body["ip"]] then
if not recent_ips[req_body["ip"]] then
recent_ips[req_body["ip"]] = { time = os_time(), count = 1 };
else
local ip = recent_ips[req_body["ip"]];
ip.count = ip.count + 1;
if os_time() - ip.time < throttle_time then
ip.time = os_time();
module:log("warn", "JSON Registration request from %s has been throttled.", req_body["ip"]);
return http_response(503, "Woah... How many users you want to register..? Request throttled, wait a bit and try again.");
end
ip.time = os_time();
end
end
-- We first check if the supplied username for registration is already there.
if not usermanager.user_exists(req_body["username"], req_body["host"]) then
usermanager.create_user(req_body["username"], req_body["password"], req_body["host"]);
module:log("debug", "%s registration data submission for %s is successful", user, req_body["user"]);
return http_response(200, "Done.");
else
module:log("debug", "%s registration data submission for %s failed (user already exists)", user, req_body["user"]);
return http_response(409, "User already exists.");
end
end
end
end
-- Set it up!
local function setup()
local ports = module:get_option("reg_servlet_port") or { 9280 };
local base_name = module:get_option("reg_servlet_base") or "register_account";
local ssl_cert = module:get_option("reg_servlet_sslcert") or false;
local ssl_key = module:get_option("reg_servlet_sslkey") or false;
if not ssl_cert or not ssl_key then
require "net.httpserver".new_from_config(ports, handle_req, { base = base_name });
else
if module:get_option("reg_servlet_port") == nil then ports = { 9443 }; end
require "net.httpserver".new_from_config(ports, handle_req, { ssl = { key = ssl_key, certificate = ssl_cert }, base = base_name });
end
end
if prosody.start_time then -- already started
setup();
else
prosody.events.add_handler("server-started", setup);
end
|
mod_register_json: Failed at JSON successful decode check, fixed with a code refactor.
|
mod_register_json: Failed at JSON successful decode check, fixed with a code refactor.
|
Lua
|
mit
|
Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules
|
d04381e5fa15bd9aff02fd3b8cbc441f698b949f
|
lua/nvim/init.lua
|
lua/nvim/init.lua
|
-- luacheck: globals unpack vim
-- local i = vim.inspect
local api = vim.api
-- Took from https://github.com/norcalli/nvim_utils
-- GPL3 apply to the nvim object
local nvim = {
plugins = setmetatable({}, {
__index = function(self, k)
local mt = getmetatable(self)
local x = mt[k]
if x ~= nil then
return x
end
local ok, plugs = pcall(api.nvim_get_var, 'plugs')
if ok then
local plugin = plugs[k]
mt[k] = plugin
return plugin
end
return nil
end
});
has = setmetatable({
cmd = function(cmd)
return api.nvim_call_function('exists', {':'..cmd}) == 1
end;
command = function(command)
return api.nvim_call_function('exists', {'##'..command}) == 1
end;
augroup = function(augroup)
return api.nvim_call_function('exists', {'#'..augroup}) == 1
end;
option = function(option)
return api.nvim_call_function('exists', {'+'..option}) == 1
end;
func = function(func)
return api.nvim_call_function('exists', {'*'..func}) == 1
end;
},{
__call = function(_, feature)
return api.nvim_call_function('has', {feature}) == 1
end;
}
);
exists = setmetatable({
cmd = function(cmd)
return api.nvim_call_function('exists', {':'..cmd}) == 1
end;
command = function(command)
return api.nvim_call_function('exists', {'##'..command}) == 1
end;
augroup = function(augroup)
return api.nvim_call_function('exists', {'#'..augroup}) == 1
end;
option = function(option)
return api.nvim_call_function('exists', {'+'..option}) == 1
end;
func = function(func)
return api.nvim_call_function('exists', {'*'..func}) == 1
end;
},{
__call = function(_, feature)
return api.nvim_call_function('exists', {feature}) == 1
end;
}
);
env = setmetatable({}, {
__index = function(_, k)
local ok, value = pcall(api.nvim_call_function, 'getenv', {k})
if not ok then
value = api.nvim_call_function('expand', {'$'..k})
value = value == k and nil or value
end
return value or nil
end;
__newindex = function(_, k, v)
local ok, _ = pcall(api.nvim_call_function, 'setenv', {k, v})
if not ok then
v = type(v) == 'string' and '"'..v..'"' or v
local _ = api.nvim_eval('let $'..k..' = '..v)
end
end
});
-- TODO: Replace this with vim.cmd
ex = setmetatable({}, {
__index = function(self, k)
local mt = getmetatable(self)
local x = mt[k]
if x ~= nil then
return x
end
local command = k:gsub("_$", "!")
local f = function(...)
return api.nvim_command(table.concat(vim.tbl_flatten {command, ...}, " "))
end
mt[k] = f
return f
end
});
buf = setmetatable({}, {
__index = function(self, k)
local mt = getmetatable(self)
local x = mt[k]
if x ~= nil then
return x
end
local f = api['nvim_buf_'..k]
mt[k] = f
return f
end
});
win = setmetatable({}, {
__index = function(self, k)
local mt = getmetatable(self)
local x = mt[k]
if x ~= nil then
return x
end
local f = api['nvim_win_'..k]
mt[k] = f
return f
end
});
tab = setmetatable({}, {
__index = function(self, k)
local mt = getmetatable(self)
local x = mt[k]
if x ~= nil then
return x
end
local f = api['nvim_tabpage_'..k]
mt[k] = f
return f
end
});
reg = setmetatable({}, {
__index = function(_, k)
local ok, value = pcall(api.nvim_eval, '@'..k)
return ok and value or nil
end;
__newindex = function(_, k, v)
if v == nil then
error("Can't clear registers")
end
api.nvim_command(([[let @%s = '%s']]):format(k, v))
end;
});
}
setmetatable(nvim, {
__index = function(self, k)
local ok
local mt = getmetatable(self)
local x = mt[k]
if x ~= nil then
return x
end
ok, x = pcall(require, 'nvim.'..k)
if not ok then
x = api['nvim_'..k]
if x ~= nil then
mt[k] = x
else
-- Used to access vim's g, b, o, bo, wo, fn, etc interfaces
x = vim[k]
mt[k] = x
end
end
return x
end
})
if api.nvim_call_function('has', {'nvim-0.5'}) == 0 then
local legacy = require'nvim.legacy'
for obj,val in pairs(legacy) do
nvim[obj] = val
end
end
return nvim
|
-- luacheck: globals unpack vim
-- local i = vim.inspect
local api = vim.api
-- Took from https://github.com/norcalli/nvim_utils
-- GPL3 apply to the nvim object
local nvim = {
plugins = setmetatable({}, {
__index = function(self, k)
local mt = getmetatable(self)
local x = mt[k]
if x ~= nil then
return x
end
local ok, plugs = pcall(api.nvim_get_var, 'plugs')
if ok then
local plugin = plugs[k]
mt[k] = plugin
return plugin
end
return nil
end
});
has = setmetatable({
cmd = function(cmd)
return api.nvim_call_function('exists', {':'..cmd}) == 1
end;
command = function(command)
return api.nvim_call_function('exists', {'##'..command}) == 1
end;
augroup = function(augroup)
return api.nvim_call_function('exists', {'#'..augroup}) == 1
end;
option = function(option)
return api.nvim_call_function('exists', {'+'..option}) == 1
end;
func = function(func)
return api.nvim_call_function('exists', {'*'..func}) == 1
end;
},{
__call = function(_, feature)
return api.nvim_call_function('has', {feature}) == 1
end;
}
);
exists = setmetatable({
cmd = function(cmd)
return api.nvim_call_function('exists', {':'..cmd}) == 1
end;
command = function(command)
return api.nvim_call_function('exists', {'##'..command}) == 1
end;
augroup = function(augroup)
return api.nvim_call_function('exists', {'#'..augroup}) == 1
end;
option = function(option)
return api.nvim_call_function('exists', {'+'..option}) == 1
end;
func = function(func)
return api.nvim_call_function('exists', {'*'..func}) == 1
end;
},{
__call = function(_, feature)
return api.nvim_call_function('exists', {feature}) == 1
end;
}
);
env = setmetatable({}, {
__index = function(_, k)
local ok, value = pcall(api.nvim_call_function, 'getenv', {k})
if not ok then
value = api.nvim_call_function('expand', {'$'..k})
value = value == k and nil or value
end
return value or nil
end;
__newindex = function(_, k, v)
local ok, _ = pcall(api.nvim_call_function, 'setenv', {k, v})
if not ok then
v = type(v) == 'string' and '"'..v..'"' or v
local _ = api.nvim_eval('let $'..k..' = '..v)
end
end
});
-- TODO: Replace this with vim.cmd
ex = setmetatable({}, {
__index = function(self, k)
local mt = getmetatable(self)
local x = mt[k]
if x ~= nil then
return x
end
local command = k:gsub("_$", "!")
local f = function(...)
return api.nvim_command(table.concat(vim.tbl_flatten {command, ...}, " "))
end
mt[k] = f
return f
end
});
buf = setmetatable({}, {
__index = function(self, k)
local mt = getmetatable(self)
local x = mt[k]
if x ~= nil then
return x
end
local f = api['nvim_buf_'..k]
mt[k] = f
return f
end
});
win = setmetatable({}, {
__index = function(self, k)
local mt = getmetatable(self)
local x = mt[k]
if x ~= nil then
return x
end
local f = api['nvim_win_'..k]
mt[k] = f
return f
end
});
tab = setmetatable({}, {
__index = function(self, k)
local mt = getmetatable(self)
local x = mt[k]
if x ~= nil then
return x
end
local f = api['nvim_tabpage_'..k]
mt[k] = f
return f
end
});
reg = setmetatable({}, {
__index = function(_, k)
local ok, value = pcall(api.nvim_call_function, 'getreg', {k})
return ok and value or nil
end;
__newindex = function(_, k, v)
if v == nil then
error("Can't clear registers")
end
pcall(api.nvim_call_function, 'setreg', {k, v})
end;
});
}
setmetatable(nvim, {
__index = function(self, k)
local ok
local mt = getmetatable(self)
local x = mt[k]
if x ~= nil then
return x
end
ok, x = pcall(require, 'nvim.'..k)
if not ok then
x = api['nvim_'..k]
if x ~= nil then
mt[k] = x
else
-- Used to access vim's g, b, o, bo, wo, fn, etc interfaces
x = vim[k]
mt[k] = x
end
end
return x
end
})
if api.nvim_call_function('has', {'nvim-0.5'}) == 0 then
local legacy = require'nvim.legacy'
for obj,val in pairs(legacy) do
nvim[obj] = val
end
end
return nvim
|
fix: Avoid evals to set/get registers
|
fix: Avoid evals to set/get registers
Use (set/get)reg to interact with neovim's registers
|
Lua
|
mit
|
Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim
|
a19575867f1335c0c73fd90e14aed0d689cfc42e
|
src/luarocks/command_line.lua
|
src/luarocks/command_line.lua
|
--- Functions for command-line scripts.
local command_line = {}
local unpack = unpack or table.unpack
local util = require("luarocks.util")
local cfg = require("luarocks.core.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")
local function error_handler(err)
return debug.traceback("LuaRocks "..cfg.program_version..
" bug (please report at https://github.com/keplerproject/luarocks/issues).\n"..err, 2)
end
--- 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")
util.printerr("\nError: "..message)
local ok, err = xpcall(util.run_scheduled_functions, error_handler)
if not ok then
util.printerr("\nError: "..err)
exitcode = cfg.errorcodes.CRASH
end
os.exit(exitcode or cfg.errorcodes.UNSPECIFIED)
end
local function replace_tree(flags, tree)
tree = dir.normalize(tree)
flags["tree"] = tree
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"
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"
else
command = table.remove(nonflags, 1)
end
command = command:gsub("-", "_")
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, tree.root)
named = true
break
end
end
if not named then
local root_dir = fs.absolute_name(flags["tree"])
replace_tree(flags, 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, 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 fs.attributes(cfg.local_cache, "owner") ~= fs.current_user() or
fs.attributes(dir.dir_name(cfg.local_cache), "owner") ~= fs.current_user() then
util.warning("The directory '" .. cfg.local_cache .. "' or its parent directory "..
"is not owned by the current user and the cache has been disabled. "..
"Please check the permissions and owner of that directory. "..
"If executing pip with sudo, you may want sudo's -H flag.")
cfg.local_cache = fs.make_temp_dir("local_cache")
util.schedule_function(fs.delete, cfg.local_cache)
end
if commands[command] then
local cmd = require(commands[command])
local call_ok, ok, err, exitcode = xpcall(function() return cmd.command(flags, unpack(nonflags)) end, error_handler)
if not call_ok then
die(ok, cfg.errorcodes.CRASH)
elseif 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.
local command_line = {}
local unpack = unpack or table.unpack
local util = require("luarocks.util")
local cfg = require("luarocks.core.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")
local function error_handler(err)
return debug.traceback("LuaRocks "..cfg.program_version..
" bug (please report at https://github.com/keplerproject/luarocks/issues).\n"..err, 2)
end
--- 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")
util.printerr("\nError: "..message)
local ok, err = xpcall(util.run_scheduled_functions, error_handler)
if not ok then
util.printerr("\nError: "..err)
exitcode = cfg.errorcodes.CRASH
end
os.exit(exitcode or cfg.errorcodes.UNSPECIFIED)
end
local function replace_tree(flags, tree)
tree = dir.normalize(tree)
flags["tree"] = tree
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"
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"
else
command = table.remove(nonflags, 1)
end
command = command:gsub("-", "_")
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, tree.root)
named = true
break
end
end
if not named then
local root_dir = fs.absolute_name(flags["tree"])
replace_tree(flags, 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, 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 fs.attributes(cfg.local_cache, "owner") ~= fs.current_user() or
fs.attributes(dir.dir_name(cfg.local_cache), "owner") ~= fs.current_user() then
util.warning("The directory '" .. cfg.local_cache .. "' or its parent directory "..
"is not owned by the current user and the cache has been disabled. "..
"Please check the permissions and owner of that directory. "..
(cfg.is_platform("unix")
and ("If executing "..util.this_program("luarocks").." with sudo, you may want sudo's -H flag.")
or ""))
cfg.local_cache = fs.make_temp_dir("local_cache")
util.schedule_function(fs.delete, cfg.local_cache)
end
if commands[command] then
local cmd = require(commands[command])
local call_ok, ok, err, exitcode = xpcall(function() return cmd.command(flags, unpack(nonflags)) end, error_handler)
if not call_ok then
die(ok, cfg.errorcodes.CRASH)
elseif not ok then
die(err, exitcode)
end
else
die("Unknown command: "..command)
end
util.run_scheduled_functions()
end
return command_line
|
Oops! Fix warning message.
|
Oops! Fix warning message.
|
Lua
|
mit
|
keplerproject/luarocks,luarocks/luarocks,luarocks/luarocks,keplerproject/luarocks,keplerproject/luarocks,tarantool/luarocks,tarantool/luarocks,keplerproject/luarocks,luarocks/luarocks,tarantool/luarocks
|
ad214ebd079b409f3b172e1f606534960f52dbb8
|
modules/admin-full/luasrc/model/cbi/admin_network/wifi_add.lua
|
modules/admin-full/luasrc/model/cbi/admin_network/wifi_add.lua
|
--[[
LuCI - Lua Configuration Interface
Copyright 2009 Jo-Philipp Wich <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
local fs = require "nixio.fs"
local nw = require "luci.model.network"
local fw = require "luci.model.firewall"
local uci = require "luci.model.uci".cursor()
local http = require "luci.http"
local iw = luci.sys.wifi.getiwinfo(http.formvalue("device"))
local has_firewall = fs.access("/etc/config/firewall")
if not iw then
luci.http.redirect(luci.dispatcher.build_url("admin/network/wireless"))
return
end
m = SimpleForm("network", translate("Join Network: Settings"))
m.cancel = translate("Back to scan results")
m.reset = false
function m.on_cancel()
local dev = http.formvalue("device")
http.redirect(luci.dispatcher.build_url(
dev and "admin/network/wireless_join?device=" .. dev
or "admin/network/wireless"
))
end
nw.init(uci)
fw.init(uci)
m.hidden = {
device = http.formvalue("device"),
join = http.formvalue("join"),
channel = http.formvalue("channel"),
mode = http.formvalue("mode"),
bssid = http.formvalue("bssid"),
wep = http.formvalue("wep"),
wpa_suites = http.formvalue("wpa_suites"),
wpa_version = http.formvalue("wpa_version"),
["cbid.network.1.replace"] = "0"
}
--[[
if iw and iw.mbssid_support then
replace = m:field(Flag, "replace", translate("Replace wireless configuration"),
translate("An additional network will be created if you leave this unchecked."))
function replace.cfgvalue() return "0" end
else
replace = m:field(DummyValue, "replace", translate("Replace wireless configuration"))
replace.default = translate("The hardware is not multi-SSID capable and the existing " ..
"configuration will be replaced if you proceed.")
function replace.formvalue() return "1" end
end
]]--
if http.formvalue("wep") == "1" then
key = m:field(Value, "key", translate("WEP passphrase"),
translate("Specify the secret encryption key here."))
key.password = true
key.datatype = "wepkey"
elseif (tonumber(m.hidden.wpa_version) or 0) > 0 and
(m.hidden.wpa_suites == "PSK" or m.hidden.wpa_suites == "PSK2")
then
key = m:field(Value, "key", translate("WPA passphrase"),
translate("Specify the secret encryption key here."))
key.password = true
key.datatype = "wpakey"
--m.hidden.wpa_suite = (tonumber(http.formvalue("wpa_version")) or 0) >= 2 and "psk2" or "psk"
end
newnet = m:field(Value, "_netname_new", translate("Name of the new network"),
translate("The allowed characters are: <code>A-Z</code>, <code>a-z</code>, " ..
"<code>0-9</code> and <code>_</code>"
))
newnet.default = m.hidden.mode == "Ad-Hoc" and "mesh" or "wwan"
newnet.datatype = "uciname"
if has_firewall then
fwzone = m:field(Value, "_fwzone",
translate("Create / Assign firewall-zone"),
translate("Choose the firewall zone you want to assign to this interface. Select <em>unspecified</em> to remove the interface from the associated zone or fill out the <em>create</em> field to define a new zone and attach the interface to it."))
fwzone.template = "cbi/firewall_zonelist"
fwzone.default = m.hidden.mode == "Ad-Hoc" and "mesh" or "wan"
end
function newnet.parse(self, section)
local net, zone
if has_firewall then
local zval = fwzone:formvalue(section)
zone = fw:get_zone(zval)
if not zone and zval == '-' then
zval = m:formvalue(fwzone:cbid(section) .. ".newzone")
if zval and #zval > 0 then
zone = fw:add_zone(zval)
end
end
end
local wdev = nw:get_wifidev(m.hidden.device)
wdev:set("disabled", false)
wdev:set("channel", m.hidden.channel)
--[[
if replace:formvalue(section) then
local n
for _, n in ipairs(wdev:get_wifinets()) do
wdev:del_wifinet(n)
end
end
]]--
local wconf = {
device = m.hidden.device,
ssid = m.hidden.join,
mode = (m.hidden.mode == "Ad-Hoc" and "adhoc" or "sta")
}
if m.hidden.wep == "1" then
wconf.encryption = "wep-open"
wconf.key = "1"
wconf.key1 = key and key:formvalue(section) or ""
elseif (tonumber(m.hidden.wpa_version) or 0) > 0 then
wconf.encryption = (tonumber(m.hidden.wpa_version) or 0) >= 2 and "psk2" or "psk"
wconf.key = key and key:formvalue(section) or ""
else
wconf.encryption = "none"
end
if wconf.mode == "adhoc" or wconf.mode == "sta" then
wconf.bssid = m.hidden.bssid
end
local value = self:formvalue(section)
net = nw:add_network(value, { proto = "dhcp" })
if not net then
self.error = { [section] = "missing" }
else
wconf.network = net:name()
local wnet = wdev:add_wifinet(wconf)
if wnet then
if zone then
fw:del_network(net:name())
zone:add_network(net:name())
end
uci:save("wireless")
uci:save("network")
uci:save("firewall")
luci.http.redirect(wnet:adminlink())
end
end
end
if has_firewall then
function fwzone.cfgvalue(self, section)
self.iface = section
local z = fw:get_zone_by_network(section)
return z and z:name()
end
end
return m
|
--[[
LuCI - Lua Configuration Interface
Copyright 2009 Jo-Philipp Wich <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
local fs = require "nixio.fs"
local nw = require "luci.model.network"
local fw = require "luci.model.firewall"
local uci = require "luci.model.uci".cursor()
local http = require "luci.http"
local iw = luci.sys.wifi.getiwinfo(http.formvalue("device"))
local has_firewall = fs.access("/etc/config/firewall")
if not iw then
luci.http.redirect(luci.dispatcher.build_url("admin/network/wireless"))
return
end
m = SimpleForm("network", translate("Join Network: Settings"))
m.cancel = translate("Back to scan results")
m.reset = false
function m.on_cancel()
local dev = http.formvalue("device")
http.redirect(luci.dispatcher.build_url(
dev and "admin/network/wireless_join?device=" .. dev
or "admin/network/wireless"
))
end
nw.init(uci)
fw.init(uci)
m.hidden = {
device = http.formvalue("device"),
join = http.formvalue("join"),
channel = http.formvalue("channel"),
mode = http.formvalue("mode"),
bssid = http.formvalue("bssid"),
wep = http.formvalue("wep"),
wpa_suites = http.formvalue("wpa_suites"),
wpa_version = http.formvalue("wpa_version"),
["cbid.network.1.replace"] = "0"
}
--[[
if iw and iw.mbssid_support then
replace = m:field(Flag, "replace", translate("Replace wireless configuration"),
translate("An additional network will be created if you leave this unchecked."))
function replace.cfgvalue() return "0" end
else
replace = m:field(DummyValue, "replace", translate("Replace wireless configuration"))
replace.default = translate("The hardware is not multi-SSID capable and the existing " ..
"configuration will be replaced if you proceed.")
function replace.formvalue() return "1" end
end
]]--
if http.formvalue("wep") == "1" then
key = m:field(Value, "key", translate("WEP passphrase"),
translate("Specify the secret encryption key here."))
key.password = true
key.datatype = "wepkey"
elseif (tonumber(m.hidden.wpa_version) or 0) > 0 and
(m.hidden.wpa_suites == "PSK" or m.hidden.wpa_suites == "PSK2")
then
key = m:field(Value, "key", translate("WPA passphrase"),
translate("Specify the secret encryption key here."))
key.password = true
key.datatype = "wpakey"
--m.hidden.wpa_suite = (tonumber(http.formvalue("wpa_version")) or 0) >= 2 and "psk2" or "psk"
end
newnet = m:field(Value, "_netname_new", translate("Name of the new network"),
translate("The allowed characters are: <code>A-Z</code>, <code>a-z</code>, " ..
"<code>0-9</code> and <code>_</code>"
))
newnet.default = m.hidden.mode == "Ad-Hoc" and "mesh" or "wwan"
newnet.datatype = "uciname"
if has_firewall then
fwzone = m:field(Value, "_fwzone",
translate("Create / Assign firewall-zone"),
translate("Choose the firewall zone you want to assign to this interface. Select <em>unspecified</em> to remove the interface from the associated zone or fill out the <em>create</em> field to define a new zone and attach the interface to it."))
fwzone.template = "cbi/firewall_zonelist"
fwzone.default = m.hidden.mode == "Ad-Hoc" and "mesh" or "wan"
end
function newnet.parse(self, section)
local net, zone
if has_firewall then
local zval = fwzone:formvalue(section)
zone = fw:get_zone(zval)
if not zone and zval == '-' then
zval = m:formvalue(fwzone:cbid(section) .. ".newzone")
if zval and #zval > 0 then
zone = fw:add_zone(zval)
end
end
end
local wdev = nw:get_wifidev(m.hidden.device)
wdev:set("disabled", false)
wdev:set("channel", m.hidden.channel)
--if replace:formvalue(section) then
if iw and iw.mbssid_support then
local n
for _, n in ipairs(wdev:get_wifinets()) do
wdev:del_wifinet(n)
end
end
]]--
local wconf = {
device = m.hidden.device,
ssid = m.hidden.join,
mode = (m.hidden.mode == "Ad-Hoc" and "adhoc" or "sta")
}
if m.hidden.wep == "1" then
wconf.encryption = "wep-open"
wconf.key = "1"
wconf.key1 = key and key:formvalue(section) or ""
elseif (tonumber(m.hidden.wpa_version) or 0) > 0 then
wconf.encryption = (tonumber(m.hidden.wpa_version) or 0) >= 2 and "psk2" or "psk"
wconf.key = key and key:formvalue(section) or ""
else
wconf.encryption = "none"
end
if wconf.mode == "adhoc" or wconf.mode == "sta" then
wconf.bssid = m.hidden.bssid
end
local value = self:formvalue(section)
net = nw:add_network(value, { proto = "dhcp" })
if not net then
self.error = { [section] = "missing" }
else
wconf.network = net:name()
local wnet = wdev:add_wifinet(wconf)
if wnet then
if zone then
fw:del_network(net:name())
zone:add_network(net:name())
end
uci:save("wireless")
uci:save("network")
uci:save("firewall")
luci.http.redirect(wnet:adminlink())
end
end
end
if has_firewall then
function fwzone.cfgvalue(self, section)
self.iface = section
local z = fw:get_zone_by_network(section)
return z and z:name()
end
end
return m
|
fixed hidden input
|
fixed hidden input
|
Lua
|
apache-2.0
|
palmettos/test,palmettos/cnLuCI,palmettos/test,palmettos/test,palmettos/test,palmettos/cnLuCI,palmettos/test,palmettos/cnLuCI,palmettos/cnLuCI,palmettos/test,palmettos/cnLuCI,palmettos/cnLuCI,palmettos/test,palmettos/test,palmettos/cnLuCI,palmettos/cnLuCI
|
adbfdd0dd1df4754330d0a2bd3268431627c5263
|
swig/ft/freetype.lua
|
swig/ft/freetype.lua
|
local ft = require("swig_freetype")
--TODO: is there a way to tell swig not to free() this?
local FT_FaceRec_mt = getmetatable(ft.FT_FaceRec)
FT_FaceRec_mt[".instance"].__gc = function(_) end
local face_metatable = {
__index = {
setCharSize = function(self, size, hdpi, vdpi)
--TODO what is the second param for?
ft.FT_Set_Char_Size(self, 0, size, hdpi, vdpi)
end,
--TODO: returns a status code
setCharMap = function(self, map)
ft.FT_Set_Charmap(self, map)
end,
getCharMapArray = function(self)
local ftf = ft.derefFaceRec(self)
local arr = {
charmaps = ftf.charmaps
}
-- NOTE: swig has same metatable for this and cairo_glyph_t
local mt = {}
mt.__len = function(_) return ftf.num_charmaps end
mt.__index = function(_, i)
return swig_freetype.FT_CharMapArray_getitem(ftf.charmaps, i-1)
end
mt.__newindex = function(_, i, map)
swig_freetype.FT_CharMapArray_setitem(ftf.charmaps, i-1, map)
end
setmetatable(arr, mt)
return arr
end,
--TODO better understanding of swig.
deref = function(self)
return ft.derefFaceRec(self)
end
}
}
local initFreeType = function()
--TODO: check result code
local _,ft_library = ft.FT_Init_FreeType()
local mt = {
__gc = function(_) ft.FT_Done_FreeType(ft_library) end,
__index = {
newFace = function(self, path)
--TODO what is the last param for?
--TODO check error
local _,ft_face = ft.FT_New_Face(self, path, 0)
ft.setmetatable(ft_face, face_metatable)
return ft_face
end,
},
}
ft.setmetatable(ft_library, mt)
return ft_library
end
local dumpChars = function(chars)
ft.dumpChars(chars, #chars)
end
return {
initFreeType = initFreeType,
dumpChars = dumpChars,
}
|
local ft = require("swig_freetype")
local log_console = require"log4l.console"
local logger = log_console()
--TODO: is there a way to tell swig not to free() this?
local FT_FaceRec_mt = getmetatable(ft.FT_FaceRec)
FT_FaceRec_mt[".instance"].__gc = function(_) end
local face_metatable = {
__index = {
setCharSize = function(self, size, hdpi, vdpi)
--TODO what is the second param for?
ft.FT_Set_Char_Size(self, 0, size, hdpi, vdpi)
end,
--TODO: returns a status code
setCharMap = function(self, map)
ft.FT_Set_Charmap(self, map)
end,
getCharMapArray = function(self)
local ftf = ft.derefFaceRec(self)
local arr = {
charmaps = ftf.charmaps
}
-- NOTE: swig has same metatable for this and cairo_glyph_t
local mt = {}
mt.__len = function(_) return ftf.num_charmaps end
mt.__index = function(_, i)
return ft.FT_CharMapArray_getitem(ftf.charmaps, i-1)
end
mt.__newindex = function(_, i, map)
ft.FT_CharMapArray_setitem(ftf.charmaps, i-1, map)
end
setmetatable(arr, mt)
return arr
end,
--TODO better understanding of swig.
deref = function(self)
return ft.derefFaceRec(self)
end
}
}
local initFreeType = function()
--TODO: check result code
local _,ft_library = ft.FT_Init_FreeType()
local mt = {
__gc = function(_)
logger:debug("ft_library __gc called")
ft.FT_Done_FreeType(ft_library)
end,
__index = {
newFace = function(self, path)
--TODO what is the last param for?
--TODO check error
local _,ft_face = ft.FT_New_Face(self, path, 0)
ft.setmetatable(ft_face, face_metatable)
return ft_face
end,
},
}
ft.setmetatable(ft_library, mt)
return ft_library
end
local dumpChars = function(chars)
ft.dumpChars(chars, #chars)
end
return {
initFreeType = initFreeType,
dumpChars = dumpChars,
}
|
some fixes
|
some fixes
|
Lua
|
mit
|
juanchanco/lua-xcb,juanchanco/lua-xcb,juanchanco/lua-xcb
|
bfb08f0df3787266aee5f17a3ea9ef135e26c393
|
helper_classes/22_array.lua
|
helper_classes/22_array.lua
|
require 'torch'
local argcheck = require "argcheck"
local doc = require "argcheck.doc"
doc[[
## Df_Array
The Df_Array is a class that is used to wrap an array table. An array table
no key names, it only uses numbers for indexing and each element has to be
an atomic element, i.e. it may not contain any tables.
]]
-- create class object
local da = torch.class('Df_Array')
function da:__init(...)
arg = {...}
if (#arg == 1 and
(torch.type(arg[1]) == 'table' or
torch.isTensor(arg[1]))) then
arg = arg[1]
end
local array_data = {}
if (torch.isTensor(arg)) then
array_data = arg:totable()
elseif (torch.type(arg) == "Dataseries") then
array_data = arg:to_table()
else
for i=1,#arg do
assert(type(arg[i]) ~= "table",
("The Dataframe array cannot contain tables - see position %d in your input"):format(i))
array_data[i] = arg[i]
end
end
self.data = array_data
end
function da:__index__(index)
if (torch.type(index) == "number") then
return self.data[index], true
end
return false
end
function da:__newindex__(index)
return false
end
da.__len__ = argcheck{
{name="self", type="Df_Array"},
call=function(self)
return #self.data
end}
return da
|
require 'torch'
local argcheck = require "argcheck"
local doc = require "argcheck.doc"
doc[[
## Df_Array
The Df_Array is a class that is used to wrap an array table. An array table
no key names, it only uses numbers for indexing and each element has to be
an atomic element, i.e. it may not contain any tables.
]]
-- create class object
local da = torch.class('Df_Array')
function da:__init(...)
arg = {...}
if (#arg == 1 and
(torch.type(arg[1]) == 'table' or
torch.isTensor(arg[1])) or
torch.type(arg[1]) == "Dataseries") then
-- If this is the case, arg var is set as its single value
arg = arg[1]
end
local array_data = {}
if (torch.isTensor(arg)) then
array_data = arg:totable()
elseif (torch.type(arg) == "Dataseries") then
array_data = arg:to_table()
else
for i=1,#arg do
assert(type(arg[i]) ~= "table",
("The Dataframe array cannot contain tables - see position %d in your input"):format(i))
array_data[i] = arg[i]
end
end
self.data = array_data
end
function da:__index__(index)
if (torch.type(index) == "number") then
return self.data[index], true
end
return false
end
function da:__newindex__(index)
return false
end
da.__len__ = argcheck{
{name="self", type="Df_Array"},
call=function(self)
return #self.data
end}
return da
|
Fix Df_Array init with a Dataseries
|
Fix Df_Array init with a Dataseries
|
Lua
|
mit
|
AlexMili/torch-dataframe
|
35ec0e60d624834dd897868e57eed7081bc219fb
|
sessions.lua
|
sessions.lua
|
require "luv.string"
require "luv.debug"
local math, string, rawset, rawget, tostring, loadstring, type, pairs, debug, getmetatable = math, string, rawset, rawget, tostring, loadstring, type, pairs, debug, getmetatable
local oop, crypt, fs = require "luv.oop", require "luv.crypt", require "luv.fs"
local Object, File, Dir = oop.Object, fs.File, fs.Dir
module(...)
local function serialize (value)
local t = type(value)
if "string" == t then
return "\""..value.."\""
elseif "number" == t or "boolean" == t or "nil" == t then
return tostring(value)
elseif "table" == t then
local res, k, v = "{"
for k, v in pairs(value) do
if type(v) ~= "userdata" and type(v) ~= "function" then
if type(k) == "number" then
res = res..k
else
res = res.."["..serialize(k).."]"
end
res = res.."="..serialize(v)..","
end
end
return res.."}"
end
return "nil"
end
local sessionGet = function (self, key)
local res = self.parent[key]
if res then return res end
return self.data[key]
end
local sessionSet = function (self, key, value)
self.data[key] = value
end
local Session = Object:extend{
__tag = .....".Session",
cookieName = "LUV_SESS_ID",
init = function (self, wsApi, storage)
rawset(self, "wsApi", wsApi)
rawset(self, "storage", storage)
local id = wsApi:getCookie(self:getCookieName())
if not id then
id = tostring(crypt.Md5(math.random(2000000000)))
wsApi:setCookie(self:getCookieName(), id)
end
rawset(self, "id", id)
rawset(self, "data", loadstring(storage:read(id) or "return {}")())
local mt = getmetatable(self)
mt.__index = sessionGet
mt.__newindex = sessionSet
end,
getId = function (self) return self.id end,
getCookieName = function (self) return self.cookieName end,
setCookieName = function (self, name) rawset(self, "cookieName", name) return self end,
getData = function (self) return self.data end,
setData = function (self, data) self.data = data self:save() end,
save = function (self) self.storage:write(self.id, "return "..serialize(self.data)) end
}
local SessionFile = Object:extend{
__tag = .....".SessionFile",
init = function (self, dir)
self:setDir(dir)
end,
getDir = function (self) return self.dir end,
setDir = function (self, dir) self.dir = Dir(dir) return self end,
read = function (self, name)
local f = File(Dir(self.dir:getName()..string.slice(name, 1, 2)):getName()..name)
if not f:isExists() then
return nil
end
return f:openForReading():read"*a"
end,
write = function (self, name, value)
local d = Dir(self.dir:getName()..string.slice(name, 1, 2))
d:create()
local f = File(d:getName()..name)
f:openForWriting():write(value):close()
return true
end,
delete = function (self, name)
File(Dir(self.dir:getName()..string.slice(fileName, 1, 2)):getName()..name):delete()
end
}
return {
Session = Session,
SessionFile = SessionFile
}
|
require "luv.string"
require "luv.debug"
local math, string, rawset, rawget, tostring, loadstring, type, pairs, debug, getmetatable = math, string, rawset, rawget, tostring, loadstring, type, pairs, debug, getmetatable
local oop, crypt, fs = require "luv.oop", require "luv.crypt", require "luv.fs"
local Object, File, Dir = oop.Object, fs.File, fs.Dir
module(...)
local function serialize (value)
local t = type(value)
if "string" == t then
return "\""..value.."\""
elseif "number" == t or "boolean" == t or "nil" == t then
return tostring(value)
elseif "table" == t then
local res, k, v = "{"
for k, v in pairs(value) do
if type(v) ~= "userdata" and type(v) ~= "function" then
if type(k) == "number" then
res = res..k
else
res = res.."["..serialize(k).."]"
end
res = res.."="..serialize(v)..","
end
end
return res.."}"
end
return "nil"
end
local sessionGet = function (self, key)
local res = self.parent[key]
if res then return res end
return self.data[key]
end
local sessionSet = function (self, key, value)
self.data[key] = value
end
local Session = Object:extend{
__tag = .....".Session",
cookieName = "LUV_SESS_ID",
init = function (self, wsApi, storage)
rawset(self, "wsApi", wsApi)
rawset(self, "storage", storage)
local id = wsApi:getCookie(self:getCookieName())
if not id or #id ~= 12 then
id = string.slice(tostring(crypt.Md5(math.random(2000000000))), 1, 12)
wsApi:setCookie(self:getCookieName(), id)
end
rawset(self, "id", id)
rawset(self, "data", loadstring(storage:read(id) or "return {}")())
local mt = getmetatable(self)
mt.__index = sessionGet
mt.__newindex = sessionSet
end,
getId = function (self) return self.id end,
getCookieName = function (self) return self.cookieName end,
setCookieName = function (self, name) rawset(self, "cookieName", name) return self end,
getData = function (self) return self.data end,
setData = function (self, data) self.data = data self:save() end,
save = function (self) self.storage:write(self.id, "return "..serialize(self.data)) end
}
local SessionFile = Object:extend{
__tag = .....".SessionFile",
init = function (self, dir)
self:setDir(dir)
end,
getDir = function (self) return self.dir end,
setDir = function (self, dir) self.dir = Dir(dir) return self end,
read = function (self, name)
local f = File(Dir(self.dir:getName()..string.slice(name, 1, 2)):getName()..string.slice(name, 3))
if not f:isExists() then
return nil
end
return f:openForReading():read"*a"
end,
write = function (self, name, value)
local d = Dir(self.dir:getName()..string.slice(name, 1, 2))
d:create()
local f = File(d:getName()..string.slice(name, 3))
f:openForWriting():write(value):close()
return true
end,
delete = function (self, name)
File(Dir(self.dir:getName()..string.slice(fileName, 1, 2)):getName()..string.slice(name, 3)):delete()
end
}
return {
Session = Session,
SessionFile = SessionFile
}
|
Fixed sessions files long names.
|
Fixed sessions files long names.
|
Lua
|
bsd-3-clause
|
metadeus/luv
|
f152969cdea216f3ce69a575d27f0dee5ee7bca0
|
Chat/src/MY_ChatMosaics.lua
|
Chat/src/MY_ChatMosaics.lua
|
--------------------------------------------
-- @File : MY_ChatMosaics.lua
-- @Desc : һ
-- @Author: һ (tinymins) @ derzh.com
-- @Date : 2015-05-21 10:34:08
-- @Email : [email protected]
-- @Last Modified by: һ @tinymins
-- @Last Modified time: 2015-05-21 15:05:20
-- @Version: 1.0
-- @ChangeLog:
-- + v1.0 File founded. -- viaһ
--------------------------------------------
MY_ChatMosaics = {}
local _C = {}
local _L = MY.LoadLangPack(MY.GetAddonInfo().szRoot .. "Chat/lang/")
local MY_ChatMosaics = MY_ChatMosaics
MY_ChatMosaics.bEnabled = false -- ״̬
MY_ChatMosaics.szMosaics = "*" -- ַ
MY_ChatMosaics.tIgnoreNames = {} --
MY_ChatMosaics.nMosaicsMode = 1 -- ֲģʽ
MY_ChatMosaics.bIgnoreOwnName = false -- Լ
RegisterCustomData("MY_ChatMosaics.tIgnoreNames")
RegisterCustomData("MY_ChatMosaics.nMosaicsMode")
RegisterCustomData("MY_ChatMosaics.bIgnoreOwnName")
MY_ChatMosaics.ResetMosaics = function()
-- re mosaics
_C.bForceUpdate = true
for i = 1, 10 do
_C.Mosaics(Station.Lookup("Lowest2/ChatPanel" .. i .. "/Wnd_Message", "Handle_Message"))
end
_C.bForceUpdate = nil
-- hook chat panel
if MY_ChatMosaics.bEnabled then
MY.HookChatPanel("MY_ChatMosaics", function(h, szChannel, szMsg)
return szMsg, h:GetItemCount()
end, function(h, szChannel, szMsg, i)
_C.Mosaics(h, i)
end)
else
MY.HookChatPanel("MY_ChatMosaics")
end
end
_C.NameLink_GetText = function(h, ...)
return h.__MY_szText or h.__MY_GetText(h, ...)
end
_C.Mosaics = function(h, nPos)
if h then
for i = h:GetItemCount() - 1, nPos or 0, -1 do
local hItem = h:Lookup(i)
if hItem and (hItem:GetName():sub(0, 9)) == "namelink_" then
if MY_ChatMosaics.bEnabled then
-- re mosaics
if _C.bForceUpdate and hItem.__MY_szText then
hItem:SetText(hItem.__MY_szText)
hItem.__MY_szText = nil
end
-- mosaics
if not hItem.__MY_szText and (
not MY_ChatMosaics.bIgnoreOwnName
or hItem:GetText() ~= '[' .. GetClientPlayer().szName .. ']'
) then
local szText = hItem.__MY_szText or hItem:GetText()
hItem.__MY_szText = szText
if not hItem.__MY_GetText then
hItem.__MY_GetText = hItem.GetText
hItem.GetText = _C.NameLink_GetText
end
szText = szText:sub(2, -2) -- ȥ[]
local nLen = wstring.len(szText)
if MY_ChatMosaics.nMosaicsMode == 1 and nLen > 2 then
szText = wstring.sub(szText, 1, 1) .. string.rep(MY_ChatMosaics.szMosaics, nLen - 2) .. wstring.sub(szText, nLen, nLen)
elseif MY_ChatMosaics.nMosaicsMode == 2 and nLen > 1 then
szText = wstring.sub(szText, 1, 1) .. string.rep(MY_ChatMosaics.szMosaics, nLen - 1)
elseif MY_ChatMosaics.nMosaicsMode == 3 and nLen > 1 then
szText = string.rep(MY_ChatMosaics.szMosaics, nLen - 1) .. wstring.sub(szText, nLen, nLen)
else -- if MY_ChatMosaics.nMosaicsMode == 4 then
szText = string.rep(MY_ChatMosaics.szMosaics, nLen)
end
hItem:SetText('[' .. szText .. ']')
hItem:AutoSize()
end
elseif hItem.__MY_szText then
hItem:SetText(hItem.__MY_szText)
hItem.__MY_szText = nil
hItem:AutoSize()
end
end
end
h:FormatAllItemPos()
end
end
MY_ChatMosaics.Mosaics = _C.Mosaics
MY.RegisterPanel("MY_Chat_ChatMosaics", _L["chat mosaics"], _L['Chat'],
"ui/Image/UICommon/yirong3.UITex|63", {255,255,0,200}, {
OnPanelActive = function(wnd)
local ui = MY.UI(wnd)
local w, h = ui:size()
local x, y = 20, 30
ui:append("WndCheckBox", {
text = _L['chat mosaics (mosaics names in chat panel)'],
x = x, y = y, w = 400,
checked = MY_ChatMosaics.bEnabled,
oncheck = function(bCheck)
MY_ChatMosaics.bEnabled = bCheck
MY_ChatMosaics.ResetMosaics()
end,
})
y = y + 30
ui:append("WndCheckBox", {
text = _L['no mosaics on my own name'],
x = x, y = y, w = 400,
checked = MY_ChatMosaics.bIgnoreOwnName,
oncheck = function(bCheck)
MY_ChatMosaics.bIgnoreOwnName = bCheck
MY_ChatMosaics.ResetMosaics()
end,
})
y = y + 30
ui:append("WndRadioBox", {
text = _L['part mosaics A (mosaics except 1st and last character)'],
x = x, y = y, w = 400,
group = "PART_MOSAICS",
checked = MY_ChatMosaics.nMosaicsMode == 1,
oncheck = function(bCheck)
if bCheck then
MY_ChatMosaics.nMosaicsMode = 1
MY_ChatMosaics.ResetMosaics()
end
end,
})
y = y + 30
ui:append("WndRadioBox", {
text = _L['part mosaics B (mosaics except 1st character)'],
x = x, y = y, w = 400,
group = "PART_MOSAICS",
checked = MY_ChatMosaics.nMosaicsMode == 2,
oncheck = function(bCheck)
if bCheck then
MY_ChatMosaics.nMosaicsMode = 2
MY_ChatMosaics.ResetMosaics()
end
end,
})
y = y + 30
ui:append("WndRadioBox", {
text = _L['part mosaics C (mosaics except last character)'],
x = x, y = y, w = 400,
group = "PART_MOSAICS",
checked = MY_ChatMosaics.nMosaicsMode == 3,
oncheck = function(bCheck)
if bCheck then
MY_ChatMosaics.nMosaicsMode = 3
MY_ChatMosaics.ResetMosaics()
end
end,
})
y = y + 30
ui:append("WndRadioBox", {
text = _L['part mosaics D (mosaics all character)'],
x = x, y = y, w = 400,
group = "PART_MOSAICS",
checked = MY_ChatMosaics.nMosaicsMode == 4,
oncheck = function(bCheck)
if bCheck then
MY_ChatMosaics.nMosaicsMode = 4
MY_ChatMosaics.ResetMosaics()
end
end,
})
y = y + 30
ui:append("WndEditBox", {
placeholder = _L['mosaics character'],
x = x, y = y, w = w - 2 * x, h = 25,
text = MY_ChatMosaics.szMosaics,
onchange = function(szText)
if szText == "" then
MY_ChatMosaics.szMosaics = "*"
else
MY_ChatMosaics.szMosaics = szText
end
MY_ChatMosaics.ResetMosaics()
end,
})
y = y + 30
ui:append("WndEditBox", {
placeholder = _L['unmosaics names (split by comma)'],
x = x, y = y, w = w - 2 * x, h = h - y - 50,
text = table.concat(MY_ChatMosaics.tIgnoreNames, ","),
onchange = function(szText)
MY_ChatMosaics.tIgnoreNames = MY.String.Split(szText, ",")
MY_ChatMosaics.ResetMosaics()
end,
})
y = y + 30
end})
|
--------------------------------------------
-- @File : MY_ChatMosaics.lua
-- @Desc : һ
-- @Author: һ (tinymins) @ derzh.com
-- @Date : 2015-05-21 10:34:08
-- @Email : [email protected]
-- @Last Modified by: һ @tinymins
-- @Last Modified time: 2015-05-21 18:57:07
-- @Version: 1.0
-- @ChangeLog:
-- + v1.0 File founded. -- viaһ
--------------------------------------------
MY_ChatMosaics = {}
local _C = {}
local _L = MY.LoadLangPack(MY.GetAddonInfo().szRoot .. "Chat/lang/")
local MY_ChatMosaics = MY_ChatMosaics
MY_ChatMosaics.bEnabled = false -- ״̬
MY_ChatMosaics.szMosaics = "*" -- ַ
MY_ChatMosaics.tIgnoreNames = {} --
MY_ChatMosaics.nMosaicsMode = 1 -- ֲģʽ
MY_ChatMosaics.bIgnoreOwnName = false -- Լ
RegisterCustomData("MY_ChatMosaics.tIgnoreNames")
RegisterCustomData("MY_ChatMosaics.nMosaicsMode")
RegisterCustomData("MY_ChatMosaics.bIgnoreOwnName")
MY_ChatMosaics.ResetMosaics = function()
-- re mosaics
_C.bForceUpdate = true
for i = 1, 10 do
_C.Mosaics(Station.Lookup("Lowest2/ChatPanel" .. i .. "/Wnd_Message", "Handle_Message"))
end
_C.bForceUpdate = nil
-- hook chat panel
if MY_ChatMosaics.bEnabled then
MY.HookChatPanel("MY_ChatMosaics", function(h, szChannel, szMsg)
return szMsg, h:GetItemCount()
end, function(h, szChannel, szMsg, i)
_C.Mosaics(h, i)
end)
else
MY.HookChatPanel("MY_ChatMosaics")
end
end
_C.NameLink_GetText = function(h, ...)
return h.__MY_szText or h.__MY_GetText(h, ...)
end
_C.Mosaics = function(h, nPos)
if h then
for i = h:GetItemCount() - 1, nPos or 0, -1 do
local hItem = h:Lookup(i)
if hItem and (hItem:GetName():sub(0, 9)) == "namelink_" then
if MY_ChatMosaics.bEnabled then
-- re mosaics
if _C.bForceUpdate and hItem.__MY_szText then
hItem:SetText(hItem.__MY_szText)
hItem.__MY_szText = nil
end
-- mosaics
if not hItem.__MY_szText and (
not MY_ChatMosaics.bIgnoreOwnName
or hItem:GetText() ~= '[' .. GetClientPlayer().szName .. ']'
) then
local szText = hItem.__MY_szText or hItem:GetText()
hItem.__MY_szText = szText
if not hItem.__MY_GetText then
hItem.__MY_GetText = hItem.GetText
hItem.GetText = _C.NameLink_GetText
end
szText = szText:sub(2, -2) -- ȥ[]
local nLen = wstring.len(szText)
if MY_ChatMosaics.nMosaicsMode == 1 and nLen > 2 then
szText = wstring.sub(szText, 1, 1) .. string.rep(MY_ChatMosaics.szMosaics, nLen - 2) .. wstring.sub(szText, nLen, nLen)
elseif MY_ChatMosaics.nMosaicsMode == 2 and nLen > 1 then
szText = wstring.sub(szText, 1, 1) .. string.rep(MY_ChatMosaics.szMosaics, nLen - 1)
elseif MY_ChatMosaics.nMosaicsMode == 3 and nLen > 1 then
szText = string.rep(MY_ChatMosaics.szMosaics, nLen - 1) .. wstring.sub(szText, nLen, nLen)
elseif MY_ChatMosaics.nMosaicsMode == 4 or nLen <= 1 then
szText = string.rep(MY_ChatMosaics.szMosaics, nLen)
else
szText = wstring.sub(szText, 1, 1) .. string.rep(MY_ChatMosaics.szMosaics, nLen - 1)
end
hItem:SetText('[' .. szText .. ']')
hItem:AutoSize()
end
elseif hItem.__MY_szText then
hItem:SetText(hItem.__MY_szText)
hItem.__MY_szText = nil
hItem:AutoSize()
end
end
end
h:FormatAllItemPos()
end
end
MY_ChatMosaics.Mosaics = _C.Mosaics
MY.RegisterPanel("MY_Chat_ChatMosaics", _L["chat mosaics"], _L['Chat'],
"ui/Image/UICommon/yirong3.UITex|63", {255,255,0,200}, {
OnPanelActive = function(wnd)
local ui = MY.UI(wnd)
local w, h = ui:size()
local x, y = 20, 30
ui:append("WndCheckBox", {
text = _L['chat mosaics (mosaics names in chat panel)'],
x = x, y = y, w = 400,
checked = MY_ChatMosaics.bEnabled,
oncheck = function(bCheck)
MY_ChatMosaics.bEnabled = bCheck
MY_ChatMosaics.ResetMosaics()
end,
})
y = y + 30
ui:append("WndCheckBox", {
text = _L['no mosaics on my own name'],
x = x, y = y, w = 400,
checked = MY_ChatMosaics.bIgnoreOwnName,
oncheck = function(bCheck)
MY_ChatMosaics.bIgnoreOwnName = bCheck
MY_ChatMosaics.ResetMosaics()
end,
})
y = y + 30
ui:append("WndRadioBox", {
text = _L['part mosaics A (mosaics except 1st and last character)'],
x = x, y = y, w = 400,
group = "PART_MOSAICS",
checked = MY_ChatMosaics.nMosaicsMode == 1,
oncheck = function(bCheck)
if bCheck then
MY_ChatMosaics.nMosaicsMode = 1
MY_ChatMosaics.ResetMosaics()
end
end,
})
y = y + 30
ui:append("WndRadioBox", {
text = _L['part mosaics B (mosaics except 1st character)'],
x = x, y = y, w = 400,
group = "PART_MOSAICS",
checked = MY_ChatMosaics.nMosaicsMode == 2,
oncheck = function(bCheck)
if bCheck then
MY_ChatMosaics.nMosaicsMode = 2
MY_ChatMosaics.ResetMosaics()
end
end,
})
y = y + 30
ui:append("WndRadioBox", {
text = _L['part mosaics C (mosaics except last character)'],
x = x, y = y, w = 400,
group = "PART_MOSAICS",
checked = MY_ChatMosaics.nMosaicsMode == 3,
oncheck = function(bCheck)
if bCheck then
MY_ChatMosaics.nMosaicsMode = 3
MY_ChatMosaics.ResetMosaics()
end
end,
})
y = y + 30
ui:append("WndRadioBox", {
text = _L['part mosaics D (mosaics all character)'],
x = x, y = y, w = 400,
group = "PART_MOSAICS",
checked = MY_ChatMosaics.nMosaicsMode == 4,
oncheck = function(bCheck)
if bCheck then
MY_ChatMosaics.nMosaicsMode = 4
MY_ChatMosaics.ResetMosaics()
end
end,
})
y = y + 30
ui:append("WndEditBox", {
placeholder = _L['mosaics character'],
x = x, y = y, w = w - 2 * x, h = 25,
text = MY_ChatMosaics.szMosaics,
onchange = function(szText)
if szText == "" then
MY_ChatMosaics.szMosaics = "*"
else
MY_ChatMosaics.szMosaics = szText
end
MY_ChatMosaics.ResetMosaics()
end,
})
y = y + 30
ui:append("WndEditBox", {
placeholder = _L['unmosaics names (split by comma)'],
x = x, y = y, w = w - 2 * x, h = h - y - 50,
text = table.concat(MY_ChatMosaics.tIgnoreNames, ","),
onchange = function(szText)
MY_ChatMosaics.tIgnoreNames = MY.String.Split(szText, ",")
MY_ChatMosaics.ResetMosaics()
end,
})
y = y + 30
end})
|
聊天打码:一处逻辑BUG
|
聊天打码:一处逻辑BUG
|
Lua
|
bsd-3-clause
|
tinymins/MY
|
fed33e050f736145a7a08d88bb231bce035c82f7
|
src/plugins/core/console/applications.lua
|
src/plugins/core/console/applications.lua
|
--- === plugins.core.console.applications ===
---
--- Adds all installed applications to the Search Console.
local require = require
local hs = hs
local log = require "hs.logger".new "applications"
local image = require "hs.image"
local fs = require "hs.fs"
local config = require "cp.config"
local spotlight = require "hs.spotlight"
local displayName = fs.displayName
local execute = hs.execute
local iconForFile = image.iconForFile
local imageFromAppBundle = image.imageFromAppBundle
local imageFromPath = image.imageFromPath
local mod = {}
mod.appCache = {}
local function modifyNameMap(info, add)
for _, item in ipairs(info) do
local icon = nil
local displayname = item.kMDItemDisplayName or displayName(item.kMDItemPath)
displayname = displayname:gsub("%.app$", "", 1)
--------------------------------------------------------------------------------
-- Preferences Panel:
--------------------------------------------------------------------------------
if string.find(item.kMDItemPath, "%.prefPane$") then
displayname = displayname .. " preferences"
if add then
icon = iconForFile(item.kMDItemPath)
end
end
--------------------------------------------------------------------------------
-- Add to the cache:
--------------------------------------------------------------------------------
if add then
local bundleID = item.kMDItemCFBundleIdentifier
if (not icon) and (bundleID) then
icon = imageFromAppBundle(bundleID)
end
--------------------------------------------------------------------------------
-- Add application to cache:
--------------------------------------------------------------------------------
mod.appCache[displayname] = {
path = item.kMDItemPath,
bundleID = bundleID,
icon = icon
}
--------------------------------------------------------------------------------
-- Remove from the cache:
--------------------------------------------------------------------------------
else
mod.appCache[displayname] = nil
end
end
mod._handler:reset()
end
local function updateNameMap(_, msg, info)
if info then
--------------------------------------------------------------------------------
-- All three can occur in either message, so check them all:
--------------------------------------------------------------------------------
if info.kMDQueryUpdateAddedItems then modifyNameMap(info.kMDQueryUpdateAddedItems, true) end
if info.kMDQueryUpdateChangedItems then modifyNameMap(info.kMDQueryUpdateChangedItems, true) end
if info.kMDQueryUpdateRemovedItems then modifyNameMap(info.kMDQueryUpdateRemovedItems, false) end
else
--------------------------------------------------------------------------------
-- This shouldn't happen for didUpdate or inProgress:
--------------------------------------------------------------------------------
log.df("userInfo from SpotLight was empty for " .. msg)
end
end
function mod.startSpotlightSearch()
local searchPaths = {
"/Applications",
"/System/Applications",
"~/Applications",
"/Developer/Applications",
"/Applications/Xcode.app/Contents/Applications",
"/System/Library/PreferencePanes",
"/Library/PreferencePanes",
"~/Library/PreferencePanes",
"/System/Library/CoreServices/Applications",
"/System/Library/CoreServices/",
"/usr/local/Cellar",
"/Library/Scripts",
"~/Library/Scripts"
}
mod.spotlight = spotlight.new():queryString([[ (kMDItemContentType = "com.apple.application-bundle") || (kMDItemContentType = "com.apple.systempreference.prefpane") ]])
:callbackMessages("didUpdate", "inProgress")
:setCallback(updateNameMap)
:searchScopes(searchPaths)
:start()
end
local plugin = {
id = "core.console.applications",
group = "core",
dependencies = {
["core.action.manager"] = "actionmanager",
}
}
function plugin.init(deps)
--------------------------------------------------------------------------------
-- Start Spotlight Search:
--------------------------------------------------------------------------------
mod.startSpotlightSearch()
--------------------------------------------------------------------------------
-- Setup Handler:
--------------------------------------------------------------------------------
mod._handler = deps.actionmanager.addHandler("global_applications", "global")
:onChoices(function(choices)
for name, app in pairs(mod.appCache) do
choices:add(name)
:subText(app["path"])
:params({
["path"] = app["path"],
})
:image(app["icon"])
:id("global_applications_" .. name)
end
end)
:onExecute(function(action)
execute(string.format("/usr/bin/open '%s'", action["path"]))
end)
:onActionId(function() return "global_applications" end)
return mod
end
return plugin
|
--- === plugins.core.console.applications ===
---
--- Adds all installed applications to the Search Console.
local require = require
local hs = hs
local log = require "hs.logger".new "applications"
local image = require "hs.image"
local fs = require "hs.fs"
local config = require "cp.config"
local spotlight = require "hs.spotlight"
local displayName = fs.displayName
local execute = hs.execute
local iconForFile = image.iconForFile
local imageFromAppBundle = image.imageFromAppBundle
local imageFromPath = image.imageFromPath
local mod = {}
mod.appCache = {}
local function modifyNameMap(info, add)
for _, item in ipairs(info) do
local icon = nil
local displayname = item.kMDItemDisplayName or (item.kMDItemPath and displayName(item.kMDItemPath))
if displayname then
displayname = displayname:gsub("%.app$", "", 1)
--------------------------------------------------------------------------------
-- Preferences Panel:
--------------------------------------------------------------------------------
if string.find(item.kMDItemPath, "%.prefPane$") then
displayname = displayname .. " preferences"
if add then
icon = iconForFile(item.kMDItemPath)
end
end
--------------------------------------------------------------------------------
-- Add to the cache:
--------------------------------------------------------------------------------
if add then
local bundleID = item.kMDItemCFBundleIdentifier
if (not icon) and (bundleID) then
icon = imageFromAppBundle(bundleID)
end
--------------------------------------------------------------------------------
-- Add application to cache:
--------------------------------------------------------------------------------
mod.appCache[displayname] = {
path = item.kMDItemPath,
bundleID = bundleID,
icon = icon
}
--------------------------------------------------------------------------------
-- Remove from the cache:
--------------------------------------------------------------------------------
else
mod.appCache[displayname] = nil
end
end
end
mod._handler:reset()
end
local function updateNameMap(_, msg, info)
if info then
--------------------------------------------------------------------------------
-- All three can occur in either message, so check them all:
--------------------------------------------------------------------------------
if info.kMDQueryUpdateAddedItems then modifyNameMap(info.kMDQueryUpdateAddedItems, true) end
if info.kMDQueryUpdateChangedItems then modifyNameMap(info.kMDQueryUpdateChangedItems, true) end
if info.kMDQueryUpdateRemovedItems then modifyNameMap(info.kMDQueryUpdateRemovedItems, false) end
else
--------------------------------------------------------------------------------
-- This shouldn't happen for didUpdate or inProgress:
--------------------------------------------------------------------------------
log.df("userInfo from SpotLight was empty for " .. msg)
end
end
function mod.startSpotlightSearch()
local searchPaths = {
"/Applications",
"/System/Applications",
"~/Applications",
"/Developer/Applications",
"/Applications/Xcode.app/Contents/Applications",
"/System/Library/PreferencePanes",
"/Library/PreferencePanes",
"~/Library/PreferencePanes",
"/System/Library/CoreServices/Applications",
"/System/Library/CoreServices/",
"/usr/local/Cellar",
"/Library/Scripts",
"~/Library/Scripts"
}
mod.spotlight = spotlight.new():queryString([[ (kMDItemContentType = "com.apple.application-bundle") || (kMDItemContentType = "com.apple.systempreference.prefpane") ]])
:callbackMessages("didUpdate", "inProgress")
:setCallback(updateNameMap)
:searchScopes(searchPaths)
:start()
end
local plugin = {
id = "core.console.applications",
group = "core",
dependencies = {
["core.action.manager"] = "actionmanager",
}
}
function plugin.init(deps)
--------------------------------------------------------------------------------
-- Start Spotlight Search:
--------------------------------------------------------------------------------
mod.startSpotlightSearch()
--------------------------------------------------------------------------------
-- Setup Handler:
--------------------------------------------------------------------------------
mod._handler = deps.actionmanager.addHandler("global_applications", "global")
:onChoices(function(choices)
for name, app in pairs(mod.appCache) do
choices:add(name)
:subText(app["path"])
:params({
["path"] = app["path"],
})
:image(app["icon"])
:id("global_applications_" .. name)
end
end)
:onExecute(function(action)
execute(string.format("/usr/bin/open '%s'", action["path"]))
end)
:onActionId(function() return "global_applications" end)
return mod
end
return plugin
|
Fixed potential nil error in Search Console Applications Handler
|
Fixed potential nil error in Search Console Applications Handler
- Closes #2085
|
Lua
|
mit
|
fcpxhacks/fcpxhacks,CommandPost/CommandPost,CommandPost/CommandPost,fcpxhacks/fcpxhacks,CommandPost/CommandPost
|
32a5206c288189c4d2d827ec6723d3bbb08a9d11
|
tools/ejabberdsql2prosody.lua
|
tools/ejabberdsql2prosody.lua
|
#!/usr/bin/env lua
-- Prosody IM
-- Copyright (C) 2008-2009 Matthew Wild
-- Copyright (C) 2008-2009 Waqas Hussain
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
package.path = package.path ..";../?.lua";
local serialize = require "util.serialization".serialize;
local st = require "util.stanza";
package.loaded["util.logger"] = {init = function() return function() end; end}
local dm = require "util.datamanager"
dm.set_data_path("data");
function parseFile(filename)
------
local file = nil;
local last = nil;
local function read(expected)
local ch;
if last then
ch = last; last = nil;
else ch = file:read(1); end
if expected and ch ~= expected then error("expected: "..expected.."; got: "..(ch or "nil")); end
return ch;
end
local function pushback(ch)
if last then error(); end
last = ch;
end
local function peek()
if not last then last = read(); end
return last;
end
local escapes = {
["\\0"] = "\0";
["\\'"] = "'";
["\\\""] = "\"";
["\\b"] = "\b";
["\\n"] = "\n";
["\\r"] = "\r";
["\\t"] = "\t";
["\\Z"] = "\26";
["\\\\"] = "\\";
["\\%"] = "%";
["\\_"] = "_";
}
local function unescape(s)
return escapes[s] or error("Unknown escape sequence: "..s);
end
local function readString()
read("'");
local s = "";
while true do
local ch = peek();
if ch == "\\" then
s = s..unescape(read()..read());
elseif ch == "'" then
break;
else
s = s..read();
end
end
read("'");
return s;
end
local function readNonString()
local s = "";
while true do
if peek() == "," or peek() == ")" then
break;
else
s = s..read();
end
end
return tonumber(s);
end
local function readItem()
if peek() == "'" then
return readString();
else
return readNonString();
end
end
local function readTuple()
local items = {}
read("(");
while peek() ~= ")" do
table.insert(items, readItem());
if peek() == ")" then break; end
read(",");
end
read(")");
return items;
end
local function readTuples()
if peek() ~= "(" then read("("); end
local tuples = {};
while true do
table.insert(tuples, readTuple());
if peek() == "," then read() end
if peek() == ";" then break; end
end
return tuples;
end
local function readTableName()
local tname = "";
while peek() ~= "`" do tname = tname..read(); end
return tname;
end
local function readInsert()
if peek() == nil then return nil; end
for ch in ("INSERT INTO `"):gmatch(".") do -- find line starting with this
if peek() == ch then
read(); -- found
else -- match failed, skip line
while peek() and read() ~= "\n" do end
return nil;
end
end
local tname = readTableName();
for ch in ("` VALUES "):gmatch(".") do read(ch); end -- expect this
local tuples = readTuples();
read(";"); read("\n");
return tname, tuples;
end
local function readFile(filename)
file = io.open(filename);
if not file then error("File not found: "..filename); os.exit(0); end
local t = {};
while true do
local tname, tuples = readInsert();
if tname then
t[tname] = tuples;
elseif peek() == nil then
break;
end
end
return t;
end
return readFile(filename);
------
end
local arg, host = ...;
local help = "/? -? ? /h -h /help -help --help";
if not(arg and host) or help:find(arg, 1, true) then
print([[ejabberd SQL DB dump importer for Prosody
Usage: ejabberdsql2prosody.lua filename.txt hostname
The file can be generated using mysqldump:
mysqldump db_name > filename.txt]]);
os.exit(1);
end
local map = {
["last"] = {"username", "seconds", "state"};
["privacy_default_list"] = {"username", "name"};
["privacy_list"] = {"username", "name", "id"};
["privacy_list_data"] = {"id", "t", "value", "action", "ord", "match_all", "match_iq", "match_message", "match_presence_in", "match_presence_out"};
["private_storage"] = {"username", "namespace", "data"};
["rostergroups"] = {"username", "jid", "grp"};
["rosterusers"] = {"username", "jid", "nick", "subscription", "ask", "askmessage", "server", "subscribe", "type"};
["spool"] = {"username", "xml", "seq"};
["users"] = {"username", "password"};
["vcard"] = {"username", "vcard"};
--["vcard_search"] = {};
}
local NULL = {};
local t = parseFile(arg);
for name, data in pairs(t) do
local m = map[name];
if m then
for i=1,#data do
local row = data[i];
for j=1,#row do
local n = m[j];
if n then
row[n] = row[j];
row[j] = nil;
else print("[warning] expected "..#n.." columns for table `"..name.."`, found "..#row); break; end
end
end
end
end
--print(serialize(t));
for i, row in ipairs(t["users"] or NULL) do
local node, password = row.username, row.password;
local ret, err = dm.store(node, host, "accounts", {password = password});
print("["..(err or "success").."] accounts: "..node.."@"..host.." = "..password);
end
function roster(node, host, jid, item)
local roster = dm.load(node, host, "roster") or {};
roster[jid] = item;
local ret, err = dm.store(node, host, "roster", roster);
print("["..(err or "success").."] roster: " ..node.."@"..host.." - "..jid);
end
function roster_pending(node, host, jid)
local roster = dm.load(node, host, "roster") or {};
roster.pending = roster.pending or {};
roster.pending[jid] = true;
local ret, err = dm.store(node, host, "roster", roster);
print("["..(err or "success").."] roster-pending: " ..node.."@"..host.." - "..jid);
end
function roster_group(node, host, jid, group)
local roster = dm.load(node, host, "roster") or {};
local item = roster[jid];
if not item then print("Warning: No roster item "..jid.." for user "..user..", can't put in group "..group); return; end
item.groups[group] = true;
local ret, err = dm.store(node, host, "roster", roster);
print("["..(err or "success").."] roster-group: " ..node.."@"..host.." - "..jid.." - "..group);
end
for i, row in ipairs(t["rosterusers"] or NULL) do
local node, contact = row.username, row.jid;
local name = row.nick;
if name == "" then name = nil; end
local subscription = row.subscription;
if subscription == "N" then
subscription = "none"
elseif subscription == "B" then
subscription = "both"
elseif subscription == "F" then
subscription = "from"
elseif subscription == "T" then
subscription = "to"
else error("Unknown subscription type: "..subscription) end;
local ask = row.ask;
if ask == "N" then
ask = nil;
elseif ask == "O" then
ask = "subscribe";
elseif ask == "I" then
roster_pending(node, host, contact);
ask = nil;
else error("Unknown ask type: "..ask); end
local item = {name = name, ask = ask, subscription = subscription, groups = {}};
roster(node, host, contact, item);
end
for i, row in ipairs(t["rostergroups"] or NULL) do
roster_group(row.username, host, row.jid, row.grp);
end
|
#!/usr/bin/env lua
-- Prosody IM
-- Copyright (C) 2008-2009 Matthew Wild
-- Copyright (C) 2008-2009 Waqas Hussain
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
package.path = package.path ..";../?.lua";
local serialize = require "util.serialization".serialize;
local st = require "util.stanza";
package.loaded["util.logger"] = {init = function() return function() end; end}
local dm = require "util.datamanager"
dm.set_data_path("data");
function parseFile(filename)
------
local file = nil;
local last = nil;
local function read(expected)
local ch;
if last then
ch = last; last = nil;
else ch = file:read(1); end
if expected and ch ~= expected then error("expected: "..expected.."; got: "..(ch or "nil")); end
return ch;
end
local function pushback(ch)
if last then error(); end
last = ch;
end
local function peek()
if not last then last = read(); end
return last;
end
local escapes = {
["\\0"] = "\0";
["\\'"] = "'";
["\\\""] = "\"";
["\\b"] = "\b";
["\\n"] = "\n";
["\\r"] = "\r";
["\\t"] = "\t";
["\\Z"] = "\26";
["\\\\"] = "\\";
["\\%"] = "%";
["\\_"] = "_";
}
local function unescape(s)
return escapes[s] or error("Unknown escape sequence: "..s);
end
local function readString()
read("'");
local s = "";
while true do
local ch = peek();
if ch == "\\" then
s = s..unescape(read()..read());
elseif ch == "'" then
break;
else
s = s..read();
end
end
read("'");
return s;
end
local function readNonString()
local s = "";
while true do
if peek() == "," or peek() == ")" then
break;
else
s = s..read();
end
end
return tonumber(s);
end
local function readItem()
if peek() == "'" then
return readString();
else
return readNonString();
end
end
local function readTuple()
local items = {}
read("(");
while peek() ~= ")" do
table.insert(items, readItem());
if peek() == ")" then break; end
read(",");
end
read(")");
return items;
end
local function readTuples()
if peek() ~= "(" then read("("); end
local tuples = {};
while true do
table.insert(tuples, readTuple());
if peek() == "," then read() end
if peek() == ";" then break; end
end
return tuples;
end
local function readTableName()
local tname = "";
while peek() ~= "`" do tname = tname..read(); end
return tname;
end
local function readInsert()
if peek() == nil then return nil; end
for ch in ("INSERT INTO `"):gmatch(".") do -- find line starting with this
if peek() == ch then
read(); -- found
else -- match failed, skip line
while peek() and read() ~= "\n" do end
return nil;
end
end
local tname = readTableName();
for ch in ("` VALUES "):gmatch(".") do read(ch); end -- expect this
local tuples = readTuples();
read(";"); read("\n");
return tname, tuples;
end
local function readFile(filename)
file = io.open(filename);
if not file then error("File not found: "..filename); os.exit(0); end
local t = {};
while true do
local tname, tuples = readInsert();
if tname then
t[tname] = tuples;
elseif peek() == nil then
break;
end
end
return t;
end
return readFile(filename);
------
end
local arg, host = ...;
local help = "/? -? ? /h -h /help -help --help";
if not(arg and host) or help:find(arg, 1, true) then
print([[ejabberd SQL DB dump importer for Prosody
Usage: ejabberdsql2prosody.lua filename.txt hostname
The file can be generated using mysqldump:
mysqldump db_name > filename.txt]]);
os.exit(1);
end
local map = {
["last"] = {"username", "seconds", "state"};
["privacy_default_list"] = {"username", "name"};
["privacy_list"] = {"username", "name", "id"};
["privacy_list_data"] = {"id", "t", "value", "action", "ord", "match_all", "match_iq", "match_message", "match_presence_in", "match_presence_out"};
["private_storage"] = {"username", "namespace", "data"};
["rostergroups"] = {"username", "jid", "grp"};
["rosterusers"] = {"username", "jid", "nick", "subscription", "ask", "askmessage", "server", "subscribe", "type"};
["spool"] = {"username", "xml", "seq"};
["users"] = {"username", "password"};
["vcard"] = {"username", "vcard"};
--["vcard_search"] = {};
}
local NULL = {};
local t = parseFile(arg);
for name, data in pairs(t) do
local m = map[name];
if m then
if #data > 0 and #data[1] ~= #m then
print("[warning] expected "..#m.." columns for table `"..name.."`, found "..#data[1]);
end
for i=1,#data do
local row = data[i];
for j=1,#m do
row[m[j]] = row[j];
row[j] = nil;
end
end
end
end
--print(serialize(t));
for i, row in ipairs(t["users"] or NULL) do
local node, password = row.username, row.password;
local ret, err = dm.store(node, host, "accounts", {password = password});
print("["..(err or "success").."] accounts: "..node.."@"..host.." = "..password);
end
function roster(node, host, jid, item)
local roster = dm.load(node, host, "roster") or {};
roster[jid] = item;
local ret, err = dm.store(node, host, "roster", roster);
print("["..(err or "success").."] roster: " ..node.."@"..host.." - "..jid);
end
function roster_pending(node, host, jid)
local roster = dm.load(node, host, "roster") or {};
roster.pending = roster.pending or {};
roster.pending[jid] = true;
local ret, err = dm.store(node, host, "roster", roster);
print("["..(err or "success").."] roster-pending: " ..node.."@"..host.." - "..jid);
end
function roster_group(node, host, jid, group)
local roster = dm.load(node, host, "roster") or {};
local item = roster[jid];
if not item then print("Warning: No roster item "..jid.." for user "..user..", can't put in group "..group); return; end
item.groups[group] = true;
local ret, err = dm.store(node, host, "roster", roster);
print("["..(err or "success").."] roster-group: " ..node.."@"..host.." - "..jid.." - "..group);
end
for i, row in ipairs(t["rosterusers"] or NULL) do
local node, contact = row.username, row.jid;
local name = row.nick;
if name == "" then name = nil; end
local subscription = row.subscription;
if subscription == "N" then
subscription = "none"
elseif subscription == "B" then
subscription = "both"
elseif subscription == "F" then
subscription = "from"
elseif subscription == "T" then
subscription = "to"
else error("Unknown subscription type: "..subscription) end;
local ask = row.ask;
if ask == "N" then
ask = nil;
elseif ask == "O" then
ask = "subscribe";
elseif ask == "I" then
roster_pending(node, host, contact);
ask = nil;
else error("Unknown ask type: "..ask); end
local item = {name = name, ask = ask, subscription = subscription, groups = {}};
roster(node, host, contact, item);
end
for i, row in ipairs(t["rostergroups"] or NULL) do
roster_group(row.username, host, row.jid, row.grp);
end
|
ejabberdsql2prosody: Fix typo, and improve the warning message
|
ejabberdsql2prosody: Fix typo, and improve the warning message
|
Lua
|
mit
|
sarumjanuch/prosody,sarumjanuch/prosody
|
a61ce7a29da03a50655ba5e47e2366737b433ba5
|
_build/cibuild.lua
|
_build/cibuild.lua
|
local TERRA_OS, ARCHIVE_EXT
local TERRA_RELEASE = "https://github.com/terralang/terra/releases/download/release-1.0.6"
local TERRA_HASH = "6184586"
local OUTSCRIPT = "_build/build_generated.sh"
local TRUSSFS_URL = "https://github.com/PyryM/trussfs/releases/download/v0.1.1/"
if jit.os == "Windows" then
-- https://github.com/terralang/terra/releases/download/release-1.0.6/terra-Windows-x86_64-6184586.7z
TERRA_OS = "Windows-x86_64"
ARCHIVE_EXT = "7z"
TRUSSFS_URL = TRUSSFS_URL .. "trussfs_windows-latest.zip"
elseif jit.os == "Linux" and jit.arch == "x64" then
-- https://github.com/terralang/terra/releases/download/release-1.0.6/terra-Linux-x86_64-6184586.tar.xz
TERRA_OS = "Linux-x86_64"
ARCHIVE_EXT = "tar.xz"
TRUSSFS_URL = TRUSSFS_URL .. "trussfs_ubuntu-latest.zip"
else
error("No Terra release for " .. jit.os .. " / " .. jit.arch)
end
local TERRA_NAME = ("terra-%s-%s"):format(TERRA_OS, TERRA_HASH)
local TERRA_URL = ("%s/%s.%s"):format(TERRA_RELEASE, TERRA_NAME, ARCHIVE_EXT)
print("Terra url:", TERRA_URL)
local outfile = io.open(OUTSCRIPT, "wt")
local function cmd(...)
local str = table.concat({...}, " ")
outfile:write(str .. "\n")
end
local function cd(path)
cmd('cd', path)
end
local function mkdir(path)
cmd('mkdir', path)
end
local function cp(src, dest)
cmd('cp -r', src, dest)
end
local function run(bin, ...)
-- if jit.os == 'Windows' then
-- cmd(bin, ...)
-- else
cmd("./" .. bin, ...)
-- end
end
cmd 'sudo apt-get update -qq -y'
cmd 'sudo apt-get install -qq -y libtinfo-dev'
mkdir '_deps'
cd '_deps'
cmd(('curl -o terra.%s -L %s'):format(ARCHIVE_EXT, TERRA_URL))
cmd(('curl -o trussfs.zip -L %s'):format(TRUSSFS_URL))
if jit.os == "Windows" then
cmd("7z e terra." .. ARCHIVE_EXT)
cmd("7z e trussfs.zip")
else
cmd("tar -xvf terra." .. ARCHIVE_EXT)
cmd("unzip trussfs.zip")
end
cd '..'
mkdir 'include/terra'
cp('_deps/' .. TERRA_NAME .. '/include/*', 'include/')
cp('_deps/' .. TERRA_NAME .. '/lib', 'lib')
cp('_deps/' .. TERRA_NAME .. '/bin', 'bin')
cp('_deps/include/*', 'include/')
cp('_deps/lib/*', 'lib/')
if jit.os == 'Windows' then
cp('_deps/trussfs/target/release/*.dll', 'lib/')
cp('_deps/trussfs/target/release/*.lib', 'lib/')
-- unsure whether exp and pdb are actually useful in windows
--[[
cp('_deps/trussfs/target/release/*.exp', 'lib/')
cp('_deps/trussfs/target/release/*.pdb', 'lib/')
]]
cmd('mv bin/terra.exe', '.')
cp('lib/terra.dll', '.')
cp('lib/lua51.dll', '.')
elseif jit.os == 'Linux' then
cp('_deps/trussfs/target/release/*.so', 'lib/')
cmd('mv bin/terra', '.')
else
-- OSX?
end
run('terra', 'src/build/selfbuild.t')
run('truss', 'dev/downloadlibs.t')
outfile:close()
os.execute("chmod +x " .. OUTSCRIPT)
os.execute("./" .. OUTSCRIPT)
|
local TERRA_OS, ARCHIVE_EXT
local TERRA_RELEASE = "https://github.com/terralang/terra/releases/download/release-1.0.6"
local TERRA_HASH = "6184586"
local OUTSCRIPT = "_build/build_generated.sh"
local TRUSSFS_URL = "https://github.com/PyryM/trussfs/releases/download/v0.1.1/"
if jit.os == "Windows" then
-- https://github.com/terralang/terra/releases/download/release-1.0.6/terra-Windows-x86_64-6184586.7z
TERRA_OS = "Windows-x86_64"
ARCHIVE_EXT = "7z"
TRUSSFS_URL = TRUSSFS_URL .. "trussfs_windows-latest.zip"
elseif jit.os == "Linux" and jit.arch == "x64" then
-- https://github.com/terralang/terra/releases/download/release-1.0.6/terra-Linux-x86_64-6184586.tar.xz
TERRA_OS = "Linux-x86_64"
ARCHIVE_EXT = "tar.xz"
TRUSSFS_URL = TRUSSFS_URL .. "trussfs_ubuntu-latest.zip"
else
error("No Terra release for " .. jit.os .. " / " .. jit.arch)
end
local TERRA_NAME = ("terra-%s-%s"):format(TERRA_OS, TERRA_HASH)
local TERRA_URL = ("%s/%s.%s"):format(TERRA_RELEASE, TERRA_NAME, ARCHIVE_EXT)
print("Terra url:", TERRA_URL)
local outfile = io.open(OUTSCRIPT, "wt")
local function cmd(...)
local str = table.concat({...}, " ")
outfile:write(str .. "\n")
end
local function cd(path)
cmd('cd', path)
end
local function mkdir(path)
cmd('mkdir', path)
end
local function cp(src, dest)
cmd('cp -r', src, dest)
end
local function run(bin, ...)
-- if jit.os == 'Windows' then
-- cmd(bin, ...)
-- else
cmd("./" .. bin, ...)
-- end
end
cmd 'sudo apt-get update -qq -y'
cmd 'sudo apt-get install -qq -y libtinfo-dev'
mkdir '_deps'
cd '_deps'
cmd(('curl -o terra.%s -L %s'):format(ARCHIVE_EXT, TERRA_URL))
cmd(('curl -o trussfs.zip -L %s'):format(TRUSSFS_URL))
if jit.os == "Windows" then
cmd("7z e terra." .. ARCHIVE_EXT)
cmd("7z e trussfs.zip")
else
cmd("tar -xvf terra." .. ARCHIVE_EXT)
cmd("unzip trussfs.zip")
end
cd '..'
mkdir 'include/terra'
cp('_deps/' .. TERRA_NAME .. '/include/*', 'include/')
cp('_deps/' .. TERRA_NAME .. '/lib', 'lib')
cp('_deps/' .. TERRA_NAME .. '/bin', 'bin')
cp('_deps/include/*', 'include/')
cp('_deps/lib/*', 'lib/')
if jit.os == 'Windows' then
cmd('mv bin/terra.exe', '.')
cp('lib/terra.dll', '.')
cp('lib/lua51.dll', '.')
elseif jit.os == 'Linux' then
cmd('mv bin/terra', '.')
else
-- OSX?
end
run('terra', 'src/build/selfbuild.t')
run('truss', 'dev/downloadlibs.t')
outfile:close()
os.execute("chmod +x " .. OUTSCRIPT)
os.execute("./" .. OUTSCRIPT)
|
this time it's fixed for sure
|
this time it's fixed for sure
|
Lua
|
mit
|
PyryM/truss,PyryM/truss,PyryM/truss,PyryM/truss
|
6f49d33f832bb308ea86bd34c5a5d4a7e983f1f2
|
qwiki.lua
|
qwiki.lua
|
dofile("urlcode.lua")
dofile("table_show.lua")
JSON = (loadfile "JSON.lua")()
local url_count = 0
local tries = 0
local item_type = os.getenv('item_type')
local item_value = os.getenv('item_value')
local downloaded = {}
load_json_file = function(file)
if file then
local f = io.open(file)
local data = f:read("*all")
f:close()
return JSON:decode(data)
else
return nil
end
end
read_file = function(file)
if file then
local f = assert(io.open(file))
local data = f:read("*all")
f:close()
return data
else
return ""
end
end
wget.callbacks.download_child_p = function(urlpos, parent, depth, start_url_parsed, iri, verdict, reason)
local url = urlpos["url"]["url"]
local html = urlpos["link_expect_html"]
local parenturl = parent["url"]
local html = nil
if item_type == "page" then
if string.match(customurl, "/v/"..item_value)
or string.match(customurl, "cdn[0-9]+%.qwiki%.com")
or string.match(customurl, "p%.typekit%.com")
or string.match(customurl, "use%.typekit%.com")
or string.match(customurl, "[^%.]+%.cloudfront%.net")
or string.match(customurl, "[^%.]+%.amazonaws.com")
or string.match(customurl, "%.json")
or string.match(customurl, "%.m3u8")
or string.match(customurl, "ikiwq%.com")
or string.match(customurl, "/api/")
or string.match(customurl, "/assets/") then
return true
else
return false
end
end
end
wget.callbacks.get_urls = function(file, url, is_css, iri)
local urls = {}
local html = nil
if item_type == "page" then
if string.match(url, item_value)
or string.match(url, "%.json")
or string.match(url, "%.m3u8") then
html = read_file(file)
for customurl in string.match(html, '"(http[s]?://[^"]+)"') do
if string.match(customurl, "/v/"..item_value)
or string.match(customurl, "cdn[0-9]+%.qwiki%.com")
or string.match(customurl, "p%.typekit%.com")
or string.match(customurl, "use%.typekit%.com")
or string.match(customurl, "[^%.]+%.cloudfront%.net")
or string.match(customurl, "[^%.]+%.amazonaws.com")
or string.match(customurl, "%.json")
or string.match(customurl, "%.m3u8")
or string.match(customurl, "ikiwq%.com")
or string.match(customurl, "/api/")
or string.match(customurl, "/assets/") then
if downloaded[customurl] ~= true then
table.insert(urls, { url=customurl })
end
end
end
for customurlnf in string.match(html, '"(/[^"]+)"') do
if string.match(customurlnf, "/v/"..item_value)
or string.match(customurlnf, "cdn[0-9]+%.qwiki%.com")
or string.match(customurlnf, "p%.typekit%.com")
or string.match(customurlnf, "use%.typekit%.com")
or string.match(customurlnf, "[^%.]+%.cloudfront%.net")
or string.match(customurlnf, "[^%.]+%.amazonaws.com")
or string.match(customurlnf, "ikiwq%.com")
or string.match(customurlnf, "/api/")
or string.match(customurlnf, "/assets/") then
local base = "http://www.qwiki.com"
local customurl = base..customurlnf
if downloaded[customurl] ~= true then
table.insert(urls, { url=customurl })
end
end
end
for tsurl in string.match(html, "#EXTINF:[0-9]+,[^0123456789abcdefghijklmnopqrstuvwxyz]+([^%.]+%.ts)") do
local base = string.match(url, "(http://[^/]+/[^/]+/[^/]+/[^/]+/)")
local fulltsurl = base..tsurl
if downloaded[fulltsurl] ~= true then
table.insert(urls, { url=fulltsurl })
end
end
end
end
return urls
end
wget.callbacks.httploop_result = function(url, err, http_stat)
-- NEW for 2014: Slightly more verbose messages because people keep
-- complaining that it's not moving or not working
url_count = url_count + 1
io.stdout:write(url_count .. "=" .. status_code .. " " .. url["url"] .. ". \n")
io.stdout:flush()
if (status_code >= 200 and status_code <= 399) or status_code == 403 then
downloaded[url.url] = true
end
if status_code >= 500 or
(status_code >= 400 and status_code ~= 404 and status_code ~= 403) then
io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n")
io.stdout:flush()
os.execute("sleep 1")
tries = tries + 1
if tries >= 20 then
io.stdout:write("\nI give up...\n")
io.stdout:flush()
return wget.actions.ABORT
else
return wget.actions.CONTINUE
end
elseif status_code == 0 then
io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n")
io.stdout:flush()
os.execute("sleep 10")
tries = tries + 1
if tries >= 10 then
io.stdout:write("\nI give up...\n")
io.stdout:flush()
return wget.actions.ABORT
else
return wget.actions.CONTINUE
end
end
tries = 0
-- We're okay; sleep a bit (if we have to) and continue
-- local sleep_time = 0.1 * (math.random(75, 1000) / 100.0)
local sleep_time = 0
-- if string.match(url["host"], "cdn") or string.match(url["host"], "media") then
-- -- We should be able to go fast on images since that's what a web browser does
-- sleep_time = 0
-- end
if sleep_time > 0.001 then
os.execute("sleep " .. sleep_time)
end
return wget.actions.NOTHING
end
|
dofile("urlcode.lua")
dofile("table_show.lua")
JSON = (loadfile "JSON.lua")()
local url_count = 0
local tries = 0
local item_type = os.getenv('item_type')
local item_value = os.getenv('item_value')
local downloaded = {}
load_json_file = function(file)
if file then
local f = io.open(file)
local data = f:read("*all")
f:close()
return JSON:decode(data)
else
return nil
end
end
read_file = function(file)
if file then
local f = assert(io.open(file))
local data = f:read("*all")
f:close()
return data
else
return ""
end
end
wget.callbacks.download_child_p = function(urlpos, parent, depth, start_url_parsed, iri, verdict, reason)
local url = urlpos["url"]["url"]
local html = urlpos["link_expect_html"]
local parenturl = parent["url"]
local html = nil
if item_type == "page" then
if string.match(url, "/v/"..item_value)
or string.match(url, "cdn[0-9]+%.qwiki%.com")
or string.match(url, "p%.typekit%.com")
or string.match(url, "use%.typekit%.com")
or string.match(url, "[^%.]+%.cloudfront%.net")
or string.match(url, "[^%.]+%.amazonaws.com")
or string.match(url, "%.json")
or string.match(url, "%.m3u8")
or string.match(url, "ikiwq%.com")
or string.match(url, "/api/")
or string.match(url, "/assets/") then
return true
else
return false
end
end
end
wget.callbacks.get_urls = function(file, url, is_css, iri)
local urls = {}
local html = nil
if item_type == "page" then
if string.match(url, item_value)
or string.match(url, "%.json")
or string.match(url, "%.m3u8") then
html = read_file(file)
for customurl in string.match(html, '"(http[s]?://[^"]+)"') do
if string.match(customurl, "/v/"..item_value)
or string.match(customurl, "cdn[0-9]+%.qwiki%.com")
or string.match(customurl, "p%.typekit%.com")
or string.match(customurl, "use%.typekit%.com")
or string.match(customurl, "[^%.]+%.cloudfront%.net")
or string.match(customurl, "[^%.]+%.amazonaws.com")
or string.match(customurl, "%.json")
or string.match(customurl, "%.m3u8")
or string.match(customurl, "ikiwq%.com")
or string.match(customurl, "/api/")
or string.match(customurl, "/assets/") then
if downloaded[customurl] ~= true then
table.insert(urls, { url=customurl })
end
end
end
for customurlnf in string.match(html, '"(/[^"]+)"') do
if string.match(customurlnf, "/v/"..item_value)
or string.match(customurlnf, "cdn[0-9]+%.qwiki%.com")
or string.match(customurlnf, "p%.typekit%.com")
or string.match(customurlnf, "use%.typekit%.com")
or string.match(customurlnf, "[^%.]+%.cloudfront%.net")
or string.match(customurlnf, "[^%.]+%.amazonaws.com")
or string.match(customurlnf, "ikiwq%.com")
or string.match(customurlnf, "/api/")
or string.match(customurlnf, "/assets/") then
local base = "http://www.qwiki.com"
local customurl = base..customurlnf
if downloaded[customurl] ~= true then
table.insert(urls, { url=customurl })
end
end
end
for tsurl in string.match(html, "#EXTINF:[0-9]+,[^0123456789abcdefghijklmnopqrstuvwxyz]+([^%.]+%.ts)") do
local base = string.match(url, "(http://[^/]+/[^/]+/[^/]+/[^/]+/)")
local fulltsurl = base..tsurl
if downloaded[fulltsurl] ~= true then
table.insert(urls, { url=fulltsurl })
end
end
end
end
return urls
end
wget.callbacks.httploop_result = function(url, err, http_stat)
-- NEW for 2014: Slightly more verbose messages because people keep
-- complaining that it's not moving or not working
url_count = url_count + 1
io.stdout:write(url_count .. "=" .. status_code .. " " .. url["url"] .. ". \n")
io.stdout:flush()
if (status_code >= 200 and status_code <= 399) or status_code == 403 then
downloaded[url.url] = true
end
if status_code >= 500 or
(status_code >= 400 and status_code ~= 404 and status_code ~= 403) then
io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n")
io.stdout:flush()
os.execute("sleep 1")
tries = tries + 1
if tries >= 20 then
io.stdout:write("\nI give up...\n")
io.stdout:flush()
return wget.actions.ABORT
else
return wget.actions.CONTINUE
end
elseif status_code == 0 then
io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n")
io.stdout:flush()
os.execute("sleep 10")
tries = tries + 1
if tries >= 10 then
io.stdout:write("\nI give up...\n")
io.stdout:flush()
return wget.actions.ABORT
else
return wget.actions.CONTINUE
end
end
tries = 0
-- We're okay; sleep a bit (if we have to) and continue
-- local sleep_time = 0.1 * (math.random(75, 1000) / 100.0)
local sleep_time = 0
-- if string.match(url["host"], "cdn") or string.match(url["host"], "media") then
-- -- We should be able to go fast on images since that's what a web browser does
-- sleep_time = 0
-- end
if sleep_time > 0.001 then
os.execute("sleep " .. sleep_time)
end
return wget.actions.NOTHING
end
|
quizilla.lua: fix
|
quizilla.lua: fix
|
Lua
|
unlicense
|
ArchiveTeam/qwiki-grab,ArchiveTeam/qwiki-grab
|
92d5a4a7bd18cade95e7cabd103d17655628609c
|
resources/[race]/race_random/duel_s.lua
|
resources/[race]/race_random/duel_s.lua
|
local maps = {
"duel.map",
}
local function getAlivePlayers()
local players = {}
for _, player in ipairs(getElementsByType('player')) do
if getElementData(player, 'state') == 'alive' then
table.insert(players, player)
end
end
return players
end
local mapname, maproot
function startDuel(p, c, a)
local players = getAlivePlayers()
if exports.race:getRaceMode() ~= "Destruction derby" then return outputChatBox("Not a DD map", p) end
if #players ~= 2 then return outputChatBox(#players .. " != 2 players for duel", p) end
-- Load in random map
mapname = maps[math.random(#maps)]
local node = getResourceConfig ( mapname )
if not node then return outputChatBox("Couldn't load xml", p) end
maproot = loadMapData ( node, resourceRoot )
xmlUnloadFile ( node )
if not maproot then return outputChatBox("Couldn't load map", p) end
-- Find spawns
local spawns = getElementsByType('spawnpoint', maproot)
for k, p in ipairs(players) do
local veh = getPedOccupiedVehicle(p)
local s = spawns[k]
setElementPosition(veh, getElementPosition(s))
setElementRotation(veh, 0, 0, getElementData(s, 'rotZ'))
setElementFrozen(veh, true)
setTimer(setElementFrozen, 100, 1, veh, false)
end
triggerClientEvent('its_time_to_duel.mp3', resourceRoot)
outputChatBox("[DUEL] " .. getPlayerName(p) .. " #00FF00started a duel!", root, 0,255,0, true)
end
addCommandHandler('duel', startDuel, true)
function stopDuel()
if maproot then
destroyElement(maproot)
maproot = nil
end
end
addEvent('stopDuel')
addEventHandler('onPostFinish', root, stopDuel)
|
local maps = {
"duel.map",
}
local function getAlivePlayers()
local players = {}
for _, player in ipairs(getElementsByType('player')) do
if getElementData(player, 'player state') == 'alive' then
table.insert(players, player)
end
end
return players
end
local mapname, maproot, initiator
function startDuel(p, c, a)
if maproot then return end
local players = getAlivePlayers()
if exports.race:getRaceMode() ~= "Destruction derby" then return outputChatBox("Not a DD map", p) end
if #players ~= 2 then return outputChatBox(#players .. " != 2 players for duel", p) end
if getElementData(p, 'player state') ~= 'alive' then return outputChatBox("Only the last two players can start duels", p, 255,0,0) end
if not initiator then
outputChatBox(getPlayerStrippedName(p) .. " has requested to duel! /duel to accept", root, 0, 255, 0)
initiator = p
return
elseif p == initiator then
return
end
-- Load in random map
mapname = maps[math.random(#maps)]
local node = getResourceConfig ( mapname )
if not node then return outputChatBox("Couldn't load xml", p) end
maproot = loadMapData ( node, resourceRoot )
xmlUnloadFile ( node )
if not maproot then return outputChatBox("Couldn't load map", p) end
-- Find spawns
local spawns = getElementsByType('spawnpoint', maproot)
for k, p in ipairs(players) do
local veh = getPedOccupiedVehicle(p)
local s = spawns[k]
setElementPosition(veh, getElementPosition(s))
setElementRotation(veh, 0, 0, getElementData(s, 'rotZ'))
setElementFrozen(veh, true)
setTimer(setElementFrozen, 100, 1, veh, false)
end
triggerClientEvent('its_time_to_duel.mp3', resourceRoot)
outputChatBox("[DUEL] " .. getPlayerName(p) .. " #00FF00accepted a duel!", root, 0,255,0, true)
end
addCommandHandler('duel', startDuel)
function stopDuel()
if maproot then
destroyElement(maproot)
maproot = nil
initiator = nil
end
end
addEvent('stopDuel')
addEventHandler('onPostFinish', root, stopDuel)
function removeHEXFromString(str)
return str:gsub("#%x%x%x%x%x%x", "")
end
function getPlayerStrippedName(player)
if not isElement(player) then error('getPlayerStrippedName error', 2) end
return removeHEXFromString(getPlayerName(player))
end
|
Made /duel so it can be used by players
|
Made /duel so it can be used by players
Fixed a fps bug
|
Lua
|
mit
|
JarnoVgr/Mr.Green-MTA-Resources,Bierbuikje/Mr.Green-MTA-Resources,Bierbuikje/Mr.Green-MTA-Resources,Bierbuikje/Mr.Green-MTA-Resources,AleksCore/Mr.Green-MTA-Resources,AleksCore/Mr.Green-MTA-Resources,JarnoVgr/Mr.Green-MTA-Resources,AleksCore/Mr.Green-MTA-Resources,JarnoVgr/Mr.Green-MTA-Resources
|
3bc9d5cdb145283f78f51595403647b7879532ab
|
modules/loot.lua
|
modules/loot.lua
|
local mod = EPGP:NewModule("loot", "AceEvent-3.0")
local L = LibStub("AceLocale-3.0"):GetLocale("EPGP")
local LLN = LibStub("LibLootNotify-1.0")
local Coroutine = LibStub("LibCoroutine-1.0")
local ignored_items = {
[20725] = true, -- Nexus Crystal
[22450] = true, -- Void Crystal
[34057] = true, -- Abyss Crystal
[29434] = true, -- Badge of Justice
[40752] = true, -- Emblem of Heroism
[40753] = true, -- Emblem of Valor
[45624] = true, -- Emblem of Conquest
[47241] = true, -- Emblem of Triumph
[49426] = true, -- Emblem of Frost
[30311] = true, -- Warp Slicer
[30312] = true, -- Infinity Blade
[30313] = true, -- Staff of Disintegration
[30314] = true, -- Phaseshift Bulwark
[30316] = true, -- Devastation
[30317] = true, -- Cosmic Infuser
[30318] = true, -- Netherstrand Longbow
[30319] = true, -- Nether Spikes
[30320] = true, -- Bundle of Nether Spikes
}
local in_combat = false
local function IsRLorML()
if UnitInRaid("player") then
local loot_method, ml_party_id, ml_raid_id = GetLootMethod()
if loot_method == "master" and ml_party_id == 0 then return true end
if loot_method ~= "master" and IsRaidLeader() then return true end
end
return false
end
local function ShowPopup(player, item, quantity)
while in_combat or StaticPopup_Visible("EPGP_CONFIRM_GP_CREDIT") do
Coroutine:Sleep(0.1)
end
local itemName, itemLink, itemRarity, _, _, _, _, _, _, itemTexture = GetItemInfo(item)
local r, g, b = GetItemQualityColor(itemRarity)
if EPGP:GetEPGP(player) then
local dialog = StaticPopup_Show("EPGP_CONFIRM_GP_CREDIT", player, "", {
texture = itemTexture,
name = itemName,
color = {r, g, b, 1},
link = itemLink
})
if dialog then
dialog.name = player
end
end
end
local function LootReceived(event_name, player, itemLink, quantity)
if IsRLorML() and CanEditOfficerNote() then
local itemID = tonumber(itemLink:match("item:(%d+)") or 0)
if not itemID then return end
local itemRarity = select(3, GetItemInfo(itemID))
if itemRarity < mod.db.profile.threshold then return end
if ignored_items[itemID] then return end
Coroutine:RunAsync(ShowPopup, player, itemLink, quantity)
end
end
function mod:PLAYER_REGEN_DISABLED()
in_combat = true
end
function mod:PLAYER_REGEN_ENABLED()
in_combat = false
end
mod.dbDefaults = {
profile = {
enabled = true,
threshold = 4, -- Epic quality items
}
}
function mod:OnInitialize()
self.db = EPGP.db:RegisterNamespace("loot", mod.dbDefaults)
end
mod.optionsName = L["Loot"]
mod.optionsDesc = L["Automatic loot tracking"]
mod.optionsArgs = {
help = {
order = 1,
type = "description",
name = L["Automatic loot tracking by means of a popup to assign GP to the toon that received loot. This option only has effect if you are in a raid and you are either the Raid Leader or the Master Looter."]
},
threshold = {
order = 10,
type = "select",
name = L["Loot tracking threshold"],
desc = L["Sets loot tracking threshold, to disable the popup on loot below this threshold quality."],
values = {
[2] = ITEM_QUALITY2_DESC,
[3] = ITEM_QUALITY3_DESC,
[4] = ITEM_QUALITY4_DESC,
[5] = ITEM_QUALITY5_DESC,
},
},
}
function mod:OnEnable()
self:RegisterEvent("PLAYER_REGEN_DISABLED")
self:RegisterEvent("PLAYER_REGEN_ENABLED")
LLN.RegisterCallback(self, "LootReceived", LootReceived)
end
function mod:OnDisable()
LLN.UnregisterAllCallbacks(self)
end
|
local mod = EPGP:NewModule("loot", "AceEvent-3.0")
local L = LibStub("AceLocale-3.0"):GetLocale("EPGP")
local LLN = LibStub("LibLootNotify-1.0")
local Coroutine = LibStub("LibCoroutine-1.0")
local ignored_items = {
[20725] = true, -- Nexus Crystal
[22450] = true, -- Void Crystal
[34057] = true, -- Abyss Crystal
[29434] = true, -- Badge of Justice
[40752] = true, -- Emblem of Heroism
[40753] = true, -- Emblem of Valor
[45624] = true, -- Emblem of Conquest
[47241] = true, -- Emblem of Triumph
[49426] = true, -- Emblem of Frost
[30311] = true, -- Warp Slicer
[30312] = true, -- Infinity Blade
[30313] = true, -- Staff of Disintegration
[30314] = true, -- Phaseshift Bulwark
[30316] = true, -- Devastation
[30317] = true, -- Cosmic Infuser
[30318] = true, -- Netherstrand Longbow
[30319] = true, -- Nether Spikes
[30320] = true, -- Bundle of Nether Spikes
}
local in_combat = false
local function IsRLorML()
if UnitInRaid("player") then
local loot_method, ml_party_id, ml_raid_id = GetLootMethod()
if loot_method == "master" and ml_party_id == 0 then return true end
if loot_method ~= "master" and and IsInRaid() and UnitIsGroupLeader("player") then return true end
end
return false
end
local function ShowPopup(player, item, quantity)
while in_combat or StaticPopup_Visible("EPGP_CONFIRM_GP_CREDIT") do
Coroutine:Sleep(0.1)
end
local itemName, itemLink, itemRarity, _, _, _, _, _, _, itemTexture = GetItemInfo(item)
local r, g, b = GetItemQualityColor(itemRarity)
if EPGP:GetEPGP(player) then
local dialog = StaticPopup_Show("EPGP_CONFIRM_GP_CREDIT", player, "", {
texture = itemTexture,
name = itemName,
color = {r, g, b, 1},
link = itemLink
})
if dialog then
dialog.name = player
end
end
end
local function LootReceived(event_name, player, itemLink, quantity)
if IsRLorML() and CanEditOfficerNote() then
local itemID = tonumber(itemLink:match("item:(%d+)") or 0)
if not itemID then return end
local itemRarity = select(3, GetItemInfo(itemID))
if itemRarity < mod.db.profile.threshold then return end
if ignored_items[itemID] then return end
Coroutine:RunAsync(ShowPopup, player, itemLink, quantity)
end
end
function mod:PLAYER_REGEN_DISABLED()
in_combat = true
end
function mod:PLAYER_REGEN_ENABLED()
in_combat = false
end
mod.dbDefaults = {
profile = {
enabled = true,
threshold = 4, -- Epic quality items
}
}
function mod:OnInitialize()
self.db = EPGP.db:RegisterNamespace("loot", mod.dbDefaults)
end
mod.optionsName = L["Loot"]
mod.optionsDesc = L["Automatic loot tracking"]
mod.optionsArgs = {
help = {
order = 1,
type = "description",
name = L["Automatic loot tracking by means of a popup to assign GP to the toon that received loot. This option only has effect if you are in a raid and you are either the Raid Leader or the Master Looter."]
},
threshold = {
order = 10,
type = "select",
name = L["Loot tracking threshold"],
desc = L["Sets loot tracking threshold, to disable the popup on loot below this threshold quality."],
values = {
[2] = ITEM_QUALITY2_DESC,
[3] = ITEM_QUALITY3_DESC,
[4] = ITEM_QUALITY4_DESC,
[5] = ITEM_QUALITY5_DESC,
},
},
}
function mod:OnEnable()
self:RegisterEvent("PLAYER_REGEN_DISABLED")
self:RegisterEvent("PLAYER_REGEN_ENABLED")
LLN.RegisterCallback(self, "LootReceived", LootReceived)
end
function mod:OnDisable()
LLN.UnregisterAllCallbacks(self)
end
|
fix traceback from task 723
|
fix traceback from task 723
|
Lua
|
bsd-3-clause
|
ceason/epgp-tfatf,protomech/epgp-dkp-reloaded,hayword/tfatf_epgp,sheldon/epgp,protomech/epgp-dkp-reloaded,hayword/tfatf_epgp,ceason/epgp-tfatf,sheldon/epgp
|
d3396be99c657c74966eefa7e634102341f12c15
|
tests/actions/make/cpp/test_objects.lua
|
tests/actions/make/cpp/test_objects.lua
|
--
-- tests/actions/make/cpp/test_objects.lua
-- Validate the list of objects for a makefile.
-- Copyright (c) 2009-2014 Jason Perkins and the Premake project
--
local suite = test.declare("make_cpp_objects")
local make = premake.make
local project = premake.project
--
-- Setup
--
local sln, prj
function suite.setup()
sln = test.createsolution()
end
local function prepare()
prj = premake.solution.getproject(sln, 1)
make.cppObjects(prj)
end
--
-- If a file is listed at the project level, it should get listed in
-- the project level objects list.
--
function suite.listFileInProjectObjects()
files { "src/hello.cpp" }
prepare()
test.capture [[
OBJECTS := \
$(OBJDIR)/hello.o \
]]
end
--
-- Only buildable files should be listed.
--
function suite.onlyListBuildableFiles()
files { "include/gl.h", "src/hello.cpp" }
prepare()
test.capture [[
OBJECTS := \
$(OBJDIR)/hello.o \
]]
end
--
-- A file should only be listed in the configurations to which it belongs.
--
function suite.configFilesAreConditioned()
filter "Debug"
files { "src/hello_debug.cpp" }
filter "Release"
files { "src/hello_release.cpp" }
prepare()
test.capture [[
OBJECTS := \
RESOURCES := \
ifeq ($(config),debug)
OBJECTS += \
$(OBJDIR)/hello_debug.o \
endif
ifeq ($(config),release)
OBJECTS += \
$(OBJDIR)/hello_release.o \
endif
]]
end
--
-- Two files with the same base name should have different object files.
--
function suite.uniqueObjNames_onBaseNameCollision()
files { "src/hello.cpp", "src/greetings/hello.cpp" }
prepare()
test.capture [[
OBJECTS := \
$(OBJDIR)/hello.o \
$(OBJDIR)/hello1.o \
]]
end
--
-- If a custom rule builds to an object file, include it in the
-- link automatically to match the behavior of Visual Studio
--
function suite.customBuildRule()
files { "hello.x" }
filter "files:**.x"
buildmessage "Compiling %{file.name}"
buildcommands {
'cxc -c "%{file.path}" -o "%{cfg.objdir}/%{file.basename}.xo"',
'c2o -c "%{cfg.objdir}/%{file.basename}.xo" -o "%{cfg.objdir}/%{file.basename}.obj"'
}
buildoutputs { "%{cfg.objdir}/%{file.basename}.obj" }
prepare()
test.capture [[
OBJECTS := \
RESOURCES := \
ifeq ($(config),debug)
OBJECTS += \
obj/Debug/hello.obj \
endif
]]
end
--
-- If a file is excluded from a configuration, it should not be listed.
--
function suite.excludedFromBuild_onExcludedFile()
files { "hello.cpp" }
filter "Debug"
removefiles { "hello.cpp" }
prepare()
test.capture [[
OBJECTS := \
RESOURCES := \
ifeq ($(config),release)
OBJECTS += \
$(OBJDIR)/hello.o \
endif
]]
end
function suite.excludedFromBuild_onExcludeFlag()
files { "hello.cpp" }
filter { "Debug", "files:hello.cpp" }
flags { "ExcludeFromBuild" }
prepare()
test.capture [[
OBJECTS := \
RESOURCES := \
ifeq ($(config),release)
OBJECTS += \
$(OBJDIR)/hello.o \
endif
]]
end
|
--
-- tests/actions/make/cpp/test_objects.lua
-- Validate the list of objects for a makefile.
-- Copyright (c) 2009-2014 Jason Perkins and the Premake project
--
local suite = test.declare("make_cpp_objects")
local make = premake.make
local project = premake.project
--
-- Setup
--
local sln, prj
function suite.setup()
sln = test.createsolution()
end
local function prepare()
prj = premake.solution.getproject(sln, 1)
make.cppObjects(prj)
end
--
-- If a file is listed at the project level, it should get listed in
-- the project level objects list.
--
function suite.listFileInProjectObjects()
files { "src/hello.cpp" }
prepare()
test.capture [[
OBJECTS := \
$(OBJDIR)/hello.o \
]]
end
--
-- Only buildable files should be listed.
--
function suite.onlyListBuildableFiles()
files { "include/gl.h", "src/hello.cpp" }
prepare()
test.capture [[
OBJECTS := \
$(OBJDIR)/hello.o \
]]
end
--
-- A file should only be listed in the configurations to which it belongs.
--
function suite.configFilesAreConditioned()
filter "Debug"
files { "src/hello_debug.cpp" }
filter "Release"
files { "src/hello_release.cpp" }
prepare()
test.capture [[
OBJECTS := \
RESOURCES := \
CUSTOMFILES := \
ifeq ($(config),debug)
OBJECTS += \
$(OBJDIR)/hello_debug.o \
endif
ifeq ($(config),release)
OBJECTS += \
$(OBJDIR)/hello_release.o \
endif
]]
end
--
-- Two files with the same base name should have different object files.
--
function suite.uniqueObjNames_onBaseNameCollision()
files { "src/hello.cpp", "src/greetings/hello.cpp" }
prepare()
test.capture [[
OBJECTS := \
$(OBJDIR)/hello.o \
$(OBJDIR)/hello1.o \
]]
end
--
-- If a custom rule builds to an object file, include it in the
-- link automatically to match the behavior of Visual Studio
--
function suite.customBuildRule()
files { "hello.x" }
filter "files:**.x"
buildmessage "Compiling %{file.name}"
buildcommands {
'cxc -c "%{file.path}" -o "%{cfg.objdir}/%{file.basename}.xo"',
'c2o -c "%{cfg.objdir}/%{file.basename}.xo" -o "%{cfg.objdir}/%{file.basename}.obj"'
}
buildoutputs { "%{cfg.objdir}/%{file.basename}.obj" }
prepare()
test.capture [[
OBJECTS := \
RESOURCES := \
CUSTOMFILES := \
ifeq ($(config),debug)
OBJECTS += \
obj/Debug/hello.obj \
endif
]]
end
--
-- If a file is excluded from a configuration, it should not be listed.
--
function suite.excludedFromBuild_onExcludedFile()
files { "hello.cpp" }
filter "Debug"
removefiles { "hello.cpp" }
prepare()
test.capture [[
OBJECTS := \
RESOURCES := \
CUSTOMFILES := \
ifeq ($(config),release)
OBJECTS += \
$(OBJDIR)/hello.o \
endif
]]
end
function suite.excludedFromBuild_onExcludeFlag()
files { "hello.cpp" }
filter { "Debug", "files:hello.cpp" }
flags { "ExcludeFromBuild" }
prepare()
test.capture [[
OBJECTS := \
RESOURCES := \
CUSTOMFILES := \
ifeq ($(config),release)
OBJECTS += \
$(OBJDIR)/hello.o \
endif
]]
end
|
Fix unit tests broken by previous commit
|
Fix unit tests broken by previous commit
|
Lua
|
bsd-3-clause
|
starkos/premake-core,saberhawk/premake-core,aleksijuvani/premake-core,Zefiros-Software/premake-core,bravnsgaard/premake-core,lizh06/premake-core,kankaristo/premake-core,Meoo/premake-core,jstewart-amd/premake-core,jstewart-amd/premake-core,mandersan/premake-core,grbd/premake-core,mandersan/premake-core,Tiger66639/premake-core,Meoo/premake-core,Blizzard/premake-core,akaStiX/premake-core,sleepingwit/premake-core,tvandijck/premake-core,premake/premake-core,soundsrc/premake-core,sleepingwit/premake-core,aleksijuvani/premake-core,grbd/premake-core,Blizzard/premake-core,dcourtois/premake-core,Yhgenomics/premake-core,mendsley/premake-core,CodeAnxiety/premake-core,tvandijck/premake-core,noresources/premake-core,noresources/premake-core,mendsley/premake-core,Zefiros-Software/premake-core,PlexChat/premake-core,Yhgenomics/premake-core,jstewart-amd/premake-core,starkos/premake-core,aleksijuvani/premake-core,PlexChat/premake-core,starkos/premake-core,kankaristo/premake-core,jsfdez/premake-core,jstewart-amd/premake-core,starkos/premake-core,Blizzard/premake-core,saberhawk/premake-core,dcourtois/premake-core,starkos/premake-core,prapin/premake-core,alarouche/premake-core,saberhawk/premake-core,felipeprov/premake-core,akaStiX/premake-core,dcourtois/premake-core,tvandijck/premake-core,Zefiros-Software/premake-core,grbd/premake-core,mandersan/premake-core,resetnow/premake-core,xriss/premake-core,tritao/premake-core,jsfdez/premake-core,xriss/premake-core,dcourtois/premake-core,prapin/premake-core,martin-traverse/premake-core,noresources/premake-core,Meoo/premake-core,TurkeyMan/premake-core,TurkeyMan/premake-core,CodeAnxiety/premake-core,Zefiros-Software/premake-core,premake/premake-core,dcourtois/premake-core,tvandijck/premake-core,Tiger66639/premake-core,alarouche/premake-core,felipeprov/premake-core,tritao/premake-core,Blizzard/premake-core,Zefiros-Software/premake-core,noresources/premake-core,premake/premake-core,felipeprov/premake-core,Tiger66639/premake-core,CodeAnxiety/premake-core,akaStiX/premake-core,martin-traverse/premake-core,jsfdez/premake-core,Blizzard/premake-core,LORgames/premake-core,soundsrc/premake-core,Yhgenomics/premake-core,noresources/premake-core,tritao/premake-core,noresources/premake-core,dcourtois/premake-core,mandersan/premake-core,Yhgenomics/premake-core,bravnsgaard/premake-core,soundsrc/premake-core,TurkeyMan/premake-core,mendsley/premake-core,kankaristo/premake-core,sleepingwit/premake-core,LORgames/premake-core,mendsley/premake-core,tritao/premake-core,xriss/premake-core,mendsley/premake-core,xriss/premake-core,LORgames/premake-core,soundsrc/premake-core,lizh06/premake-core,TurkeyMan/premake-core,resetnow/premake-core,premake/premake-core,CodeAnxiety/premake-core,aleksijuvani/premake-core,tvandijck/premake-core,xriss/premake-core,starkos/premake-core,prapin/premake-core,Blizzard/premake-core,alarouche/premake-core,lizh06/premake-core,soundsrc/premake-core,starkos/premake-core,saberhawk/premake-core,dcourtois/premake-core,alarouche/premake-core,lizh06/premake-core,Tiger66639/premake-core,bravnsgaard/premake-core,aleksijuvani/premake-core,mandersan/premake-core,CodeAnxiety/premake-core,sleepingwit/premake-core,sleepingwit/premake-core,premake/premake-core,prapin/premake-core,premake/premake-core,LORgames/premake-core,TurkeyMan/premake-core,PlexChat/premake-core,jstewart-amd/premake-core,martin-traverse/premake-core,resetnow/premake-core,resetnow/premake-core,felipeprov/premake-core,PlexChat/premake-core,Meoo/premake-core,martin-traverse/premake-core,grbd/premake-core,noresources/premake-core,bravnsgaard/premake-core,premake/premake-core,kankaristo/premake-core,resetnow/premake-core,LORgames/premake-core,jsfdez/premake-core,bravnsgaard/premake-core,akaStiX/premake-core
|
fb19e26d155bd6a41e9f562b9928d61c03963297
|
resource-count_0.0.1/control.lua
|
resource-count_0.0.1/control.lua
|
require "defines"
script.on_init(function()
initPlayers()
end)
script.on_event(defines.events.on_player_created, function(event)
playerCreated(event)
end)
script.on_event(defines.events.on_tick, function(event)
if event.tick % 10 ~= 0 then
return
end
for index, player in ipairs(game.players) do
showResourceCount(player)
end
end)
function showResourceCount(player)
if (not player.valid) or (not player.connected) then
return
end
if (player.selected == nil) or (player.selected.prototype.type ~= "resource") then
player.gui.top.resource_total.caption = ""
return
end
local resources = floodFindResources(player.selected)
local count = sumResources(resources)
player.gui.top.resource_total.caption = player.selected.name .. ": " .. count.total .. " in " .. count.count .. " tiles"
end
function keyFor(entity)
return entity.position.x .. "," .. entity.position.y
end
function initPlayers()
for _, player in ipairs(game.players) do
initPlayer(player)
end
end
function playerCreated(event)
local player = game.players[event.player_index]
initPlayer(player)
end
function initPlayer(player)
player.gui.top.add{type="label", name="resource_total", caption=""}
end
function sumResources(resources)
local total = 0
local count = 0
for key, resource in pairs(resources) do
total = total + resource.amount
count = count + 1
end
return {total = total, count = count}
end
function floodFindResources(entity)
local found = {}
floodCount(found, entity)
return found
end
function floodCount(found, entity)
local name = entity.name
local key = keyFor(entity)
if found[key] then
return
end
found[key] = entity
local RANGE = 2.2
local surface = entity.surface
local pos = entity.position
local area = {{pos.x - RANGE, pos.y - RANGE}, {pos.x + RANGE, pos.y + RANGE}}
for _, res in pairs(surface.find_entities_filtered { area = area, name = entity.name}) do
local key2 = keyFor(res)
if not found[key2] then
floodCount(found, res)
end
end
end
|
require "defines"
script.on_init(function()
initPlayers()
end)
script.on_event(defines.events.on_player_created, function(event)
playerCreated(event)
end)
script.on_event(defines.events.on_tick, function(event)
if event.tick % 10 ~= 0 then
return
end
for index, player in ipairs(game.players) do
showResourceCount(player)
end
end)
function showResourceCount(player)
if (not player.valid) or (not player.connected) then
return
end
if (player.selected == nil) or (player.selected.prototype.type ~= "resource") then
player.gui.top.resource_total.caption = ""
return
end
global.selects = global.selects or {}
global.selects[player.index] = global.selects[player.index] or {}
local previousSelected = global.selects[player.index]
local key = keyFor(player.selected)
if previousSelected[key] then
showForResources(player, previousSelected)
else
local resources = floodFindResources(player.selected)
global.selects[player.index] = resources
showForResources(player, resources)
end
end
function showForResources(player, resources)
local count = sumResources(resources)
player.gui.top.resource_total.caption = player.selected.name .. ": " .. count.total .. " in " .. count.count .. " tiles"
end
function keyFor(entity)
return entity.position.x .. "," .. entity.position.y
end
function initPlayers()
for _, player in ipairs(game.players) do
initPlayer(player)
end
end
function playerCreated(event)
local player = game.players[event.player_index]
initPlayer(player)
end
function initPlayer(player)
player.gui.top.add{type="label", name="resource_total", caption=""}
end
function sumResources(resources)
local total = 0
local count = 0
for key, resource in pairs(resources) do
total = total + resource.amount
count = count + 1
end
return {total = total, count = count}
end
function floodFindResources(entity)
local found = {}
floodCount(found, entity)
return found
end
function floodCount(found, entity)
local name = entity.name
local key = keyFor(entity)
if found[key] then
return
end
found[key] = entity
local RANGE = 2.2
local surface = entity.surface
local pos = entity.position
local area = {{pos.x - RANGE, pos.y - RANGE}, {pos.x + RANGE, pos.y + RANGE}}
for _, res in pairs(surface.find_entities_filtered { area = area, name = entity.name}) do
local key2 = keyFor(res)
if not found[key2] then
floodCount(found, res)
end
end
end
|
Fix #9 Store the previous resource entities to speed up resource count
|
Fix #9 Store the previous resource entities to speed up resource count
|
Lua
|
mit
|
Zomis/FactorioMods
|
06d59df81b6d387aaf109a42fad0d1b4dfd4bb61
|
src/core/app.lua
|
src/core/app.lua
|
module(...,package.seeall)
local buffer = require("core.buffer")
local packet = require("core.packet")
local lib = require("core.lib")
local link = require("core.link")
local config = require("core.config")
local timer = require("core.timer")
require("core.packet_h")
-- The set of all active apps and links in the system.
-- Indexed both by name (in a table) and by number (in an array).
app_table, app_array = {}, {}
link_table, link_array = {}, {}
configuration = config.new()
-- Configure the running app network to match new_configuration.
--
-- Successive calls to configure() will migrate from the old to the
-- new app network by making the changes needed.
function configure (new_config)
local actions = compute_config_actions(configuration, new_config)
apply_config_actions(actions, new_config)
end
-- Return the configuration actions needed to migrate from old config to new.
-- The return value is a table:
-- app_name -> stop | start | keep | restart | reconfig
function compute_config_actions (old, new)
local actions = {}
for appname, info in pairs(new.apps) do
local class, config = unpack(info)
local action = nil
if not old.apps[appname] then action = 'start'
elseif old.apps[appname].class ~= class then action = 'restart'
elseif old.apps[appname].config ~= config then action = 'reconfig'
else action = 'keep' end
actions[appname] = action
end
for appname in pairs(old.apps) do
if not new.apps[appname] then actions[appname] = 'stop' end
end
return actions
end
-- Update the active app network by applying the necessary actions.
function apply_config_actions (actions, conf)
-- The purpose of this function is to populate these tables:
local new_app_table, new_app_array = {}, {}, {}
local new_link_table, new_link_array = {}, {}, {}
-- Temporary name->index table for use in link renumbering
local app_name_to_index = {}
-- Table of functions that execute config actions
local ops = {}
function ops.stop (name)
if app_table[name].stop then app_table[name]:stop() end
end
function ops.keep (name)
new_app_table[name] = app_table[name]
table.insert(new_app_array, app_table[name])
app_name_to_index[name] = #new_app_array
end
function ops.start (name)
local class = conf.apps[name].class
local arg = conf.apps[name].arg
local app = class:new(arg)
app.output = {}
app.input = {}
new_app_table[name] = app
table.insert(new_app_array, app)
app_name_to_index[name] = #new_app_array
end
function ops.restart (name)
ops.stop(name)
ops.start(name)
end
function ops.reconfig (name)
if app_table[name].reconfig then
app_table[name]:reconfig(config)
else
ops.restart(name)
end
end
-- dispatch all actions
for name, action in pairs(actions) do
ops[action](name)
end
-- Setup links: create (or reuse) and renumber.
for linkspec in pairs(conf.links) do
local fa, fl, ta, tl = config.parse_link(linkspec)
if not new_app_table[fa] then error("no such app: " .. fa) end
if not new_app_table[ta] then error("no such app: " .. ta) end
-- Create or reuse a link and assign/update receiving app index
local link = link_table[linkspec] or link.new()
link.receiving_app = app_name_to_index[ta]
-- Add link to apps
new_app_table[fa].output[fl] = link
new_app_table[ta].input[tl] = link
-- Remember link
new_link_table[linkspec] = link
table.insert(new_link_array, link)
end
for _, app in ipairs(new_app_array) do
if app.relink then app:relink() end
end
-- commit changes
app_table, link_table = new_app_table, new_link_table
app_array, link_array = new_app_array, new_link_array
end
-- Call this to "run snabb switch".
function main (options)
local done = nil
options = options or {}
local no_timers = options.no_timers
if options.duration then done = lib.timer(options.duration * 1e9) end
repeat
breathe()
if not no_timers then timer.run() end
until done and done()
report()
end
function breathe ()
-- Inhale: pull work into the app network
for _, app in ipairs(app_array) do
if app.pull then app:pull() end
end
-- Exhale: push work out through the app network
local firstloop = true
repeat
local progress = false
-- For each link that has new data, run the receiving app
for _, link in ipairs(link_array) do
if firstloop or link.has_new_data then
link.has_new_data = false
local receiver = app_array[link.receiving_app]
if receiver.push then
receiver:push()
progress = true
end
end
end
firstloop = false
until not progress -- Stop after no link had new data
end
function report ()
print("link report")
for name, l in pairs(link_table) do
print(lib.comma_value(tostring(tonumber(l.stats.txpackets))), "sent on", name)
end
end
-- XXX add graphviz() function back.
function module_init ()
-- XXX Find a better place for this.
require("lib.hardware.bus").scan_devices()
end
module_init()
|
module(...,package.seeall)
local buffer = require("core.buffer")
local packet = require("core.packet")
local lib = require("core.lib")
local link = require("core.link")
local config = require("core.config")
local timer = require("core.timer")
require("core.packet_h")
-- The set of all active apps and links in the system.
-- Indexed both by name (in a table) and by number (in an array).
app_table, app_array = {}, {}
link_table, link_array = {}, {}
configuration = config.new()
-- Configure the running app network to match new_configuration.
--
-- Successive calls to configure() will migrate from the old to the
-- new app network by making the changes needed.
function configure (new_config)
local actions = compute_config_actions(configuration, new_config)
apply_config_actions(actions, new_config)
configuration = new_config
end
-- Return the configuration actions needed to migrate from old config to new.
-- The return value is a table:
-- app_name -> stop | start | keep | restart | reconfig
function compute_config_actions (old, new)
local actions = {}
for appname, info in pairs(new.apps) do
local class, arg = info.class, info.arg
local action = nil
if not old.apps[appname] then action = 'start'
elseif old.apps[appname].class ~= class then action = 'restart'
elseif old.apps[appname].arg ~= arg then action = 'reconfig'
else action = 'keep' end
actions[appname] = action
end
for appname in pairs(old.apps) do
if not new.apps[appname] then actions[appname] = 'stop' end
end
return actions
end
-- Update the active app network by applying the necessary actions.
function apply_config_actions (actions, conf)
-- The purpose of this function is to populate these tables:
local new_app_table, new_app_array = {}, {}, {}
local new_link_table, new_link_array = {}, {}, {}
-- Temporary name->index table for use in link renumbering
local app_name_to_index = {}
-- Table of functions that execute config actions
local ops = {}
function ops.stop (name)
if app_table[name].stop then app_table[name]:stop() end
end
function ops.keep (name)
new_app_table[name] = app_table[name]
table.insert(new_app_array, app_table[name])
app_name_to_index[name] = #new_app_array
end
function ops.start (name)
local class = conf.apps[name].class
local arg = conf.apps[name].arg
local app = class:new(arg)
app.output = {}
app.input = {}
new_app_table[name] = app
table.insert(new_app_array, app)
app_name_to_index[name] = #new_app_array
end
function ops.restart (name)
ops.stop(name)
ops.start(name)
end
function ops.reconfig (name)
if app_table[name].reconfig then
app_table[name]:reconfig(config)
else
ops.restart(name)
end
end
-- dispatch all actions
for name, action in pairs(actions) do
ops[action](name)
end
-- Setup links: create (or reuse) and renumber.
for linkspec in pairs(conf.links) do
local fa, fl, ta, tl = config.parse_link(linkspec)
if not new_app_table[fa] then error("no such app: " .. fa) end
if not new_app_table[ta] then error("no such app: " .. ta) end
-- Create or reuse a link and assign/update receiving app index
local link = link_table[linkspec] or link.new()
link.receiving_app = app_name_to_index[ta]
-- Add link to apps
new_app_table[fa].output[fl] = link
new_app_table[ta].input[tl] = link
-- Remember link
new_link_table[linkspec] = link
table.insert(new_link_array, link)
end
for _, app in ipairs(new_app_array) do
if app.relink then app:relink() end
end
-- commit changes
app_table, link_table = new_app_table, new_link_table
app_array, link_array = new_app_array, new_link_array
end
-- Call this to "run snabb switch".
function main (options)
local done = nil
options = options or {}
local no_timers = options.no_timers
if options.duration then done = lib.timer(options.duration * 1e9) end
repeat
breathe()
if not no_timers then timer.run() end
until done and done()
report()
end
function breathe ()
-- Inhale: pull work into the app network
for _, app in ipairs(app_array) do
if app.pull then app:pull() end
end
-- Exhale: push work out through the app network
local firstloop = true
repeat
local progress = false
-- For each link that has new data, run the receiving app
for _, link in ipairs(link_array) do
if firstloop or link.has_new_data then
link.has_new_data = false
local receiver = app_array[link.receiving_app]
if receiver.push then
receiver:push()
progress = true
end
end
end
firstloop = false
until not progress -- Stop after no link had new data
end
function report ()
print("link report")
for name, l in pairs(link_table) do
print(lib.comma_value(tostring(tonumber(l.stats.txpackets))), "sent on", name)
end
end
function selftest ()
print("selftest: app")
local App = {}
function App:new () return setmetatable({}, {__index = App}) end
local c1 = config.new()
config.app(c1, "app1", App)
config.app(c1, "app2", App)
config.link(c1, "app1.x -> app2.x")
print("empty -> c1")
configure(c1)
assert(#app_array == 2)
assert(#link_array == 1)
assert(app_table.app1 and app_table.app2)
local orig_app1 = app_table.app1
local orig_app2 = app_table.app2
local orig_link = link_array[1]
print("c1 -> c1")
configure(c1)
assert(app_table.app1 == orig_app1)
assert(app_table.app2 == orig_app2)
local c2 = config.new()
config.app(c2, "app1", App, "config")
config.app(c2, "app2", App)
config.link(c2, "app1.x -> app2.x")
config.link(c2, "app2.x -> app1.x")
print("c1 -> c2")
configure(c2)
assert(#app_array == 2)
assert(#link_array == 2)
assert(app_table.app1 ~= orig_app1) -- should be restarted
assert(app_table.app2 == orig_app2) -- should be the same
-- tostring() because == does not work on FFI structs?
assert(tostring(orig_link) == tostring(link_table['app1.x -> app2.x']))
print("c2 -> c1")
configure(c1) -- c2 -> c1
assert(app_table.app1 ~= orig_app1) -- should be restarted
assert(app_table.app2 == orig_app2) -- should be the same
assert(#app_array == 2)
assert(#link_array == 1)
print("c1 -> empty")
configure(config.new())
assert(#app_array == 0)
assert(#link_array == 0)
print("OK")
end
-- XXX add graphviz() function back.
function module_init ()
-- XXX Find a better place for this.
require("lib.hardware.bus").scan_devices()
end
module_init()
|
app.lua: Added selftest() and fixed bugs in configure().
|
app.lua: Added selftest() and fixed bugs in configure().
|
Lua
|
apache-2.0
|
snabbnfv-goodies/snabbswitch,snabbco/snabb,hb9cwp/snabbswitch,lukego/snabbswitch,lukego/snabbswitch,snabbco/snabb,mixflowtech/logsensor,Igalia/snabbswitch,SnabbCo/snabbswitch,Igalia/snabb,snabbnfv-goodies/snabbswitch,snabbnfv-goodies/snabbswitch,fhanik/snabbswitch,Igalia/snabb,pirate/snabbswitch,pirate/snabbswitch,Igalia/snabb,wingo/snabb,wingo/snabb,eugeneia/snabb,Igalia/snabb,plajjan/snabbswitch,wingo/snabbswitch,eugeneia/snabbswitch,eugeneia/snabb,eugeneia/snabb,justincormack/snabbswitch,snabbco/snabb,plajjan/snabbswitch,snabbco/snabb,lukego/snabb,heryii/snabb,javierguerragiraldez/snabbswitch,wingo/snabb,dpino/snabb,SnabbCo/snabbswitch,xdel/snabbswitch,eugeneia/snabb,Igalia/snabbswitch,heryii/snabb,snabbco/snabb,dwdm/snabbswitch,aperezdc/snabbswitch,snabbco/snabb,dpino/snabb,eugeneia/snabb,hb9cwp/snabbswitch,virtualopensystems/snabbswitch,fhanik/snabbswitch,SnabbCo/snabbswitch,alexandergall/snabbswitch,pavel-odintsov/snabbswitch,heryii/snabb,eugeneia/snabbswitch,heryii/snabb,alexandergall/snabbswitch,andywingo/snabbswitch,alexandergall/snabbswitch,dpino/snabb,eugeneia/snabb,dpino/snabbswitch,mixflowtech/logsensor,kbara/snabb,Igalia/snabbswitch,fhanik/snabbswitch,virtualopensystems/snabbswitch,wingo/snabb,mixflowtech/logsensor,plajjan/snabbswitch,wingo/snabb,alexandergall/snabbswitch,dpino/snabb,pirate/snabbswitch,aperezdc/snabbswitch,eugeneia/snabbswitch,eugeneia/snabbswitch,hb9cwp/snabbswitch,Igalia/snabb,Igalia/snabbswitch,SnabbCo/snabbswitch,kbara/snabb,Igalia/snabb,Igalia/snabb,pavel-odintsov/snabbswitch,alexandergall/snabbswitch,wingo/snabbswitch,lukego/snabb,lukego/snabbswitch,eugeneia/snabb,aperezdc/snabbswitch,heryii/snabb,dwdm/snabbswitch,dwdm/snabbswitch,xdel/snabbswitch,dpino/snabbswitch,mixflowtech/logsensor,pavel-odintsov/snabbswitch,dpino/snabbswitch,lukego/snabb,alexandergall/snabbswitch,wingo/snabbswitch,wingo/snabb,kbara/snabb,andywingo/snabbswitch,alexandergall/snabbswitch,snabbco/snabb,kbara/snabb,Igalia/snabb,snabbnfv-goodies/snabbswitch,xdel/snabbswitch,alexandergall/snabbswitch,kellabyte/snabbswitch,kbara/snabb,snabbco/snabb,justincormack/snabbswitch,justincormack/snabbswitch,dpino/snabb,andywingo/snabbswitch,kellabyte/snabbswitch,kbara/snabb,justincormack/snabbswitch,Igalia/snabbswitch,andywingo/snabbswitch,dpino/snabbswitch,dpino/snabb,mixflowtech/logsensor,lukego/snabbswitch,kellabyte/snabbswitch,heryii/snabb,dpino/snabb,virtualopensystems/snabbswitch,aperezdc/snabbswitch,hb9cwp/snabbswitch,wingo/snabbswitch,javierguerragiraldez/snabbswitch,lukego/snabb,eugeneia/snabb,javierguerragiraldez/snabbswitch,plajjan/snabbswitch
|
ec0a64707b06c48c44ac6787ccab5c93284060f7
|
BtCommandScripts/moveOptim.lua
|
BtCommandScripts/moveOptim.lua
|
function getInfo()
return {
onNoUnits = SUCCESS,
parameterDefs = {
{
name = "x",
variableType = "number",
componentType = "editBox",
defaultValue = "0",
},
{
name = "y",
variableType = "number",
componentType = "editBox",
defaultValue = "0",
}
}
}
end
local giveOrderToUnit = Spring.GiveOrderToUnit
--local getUnitDir = Spring.GetUnitDirection
local unitIsDead = Spring.GetUnitIsDead
local SHORT_PATH_LEN = 100
local SUBTARGET_TOLEARANCE_SQ = 30*30
local TOLERANCE_SQ = 30*30
local MOST_DISTANT_UNIT_DIST_SQ = 50*50
local LEADER_TOLERANCE_SQ = 50 * 50
local function wrapResVect(f, id)
local x, y, z = f(id)
return { x, y, z}
end
local function getUnitPos(unitID)
return wrapResVect(Spring.GetUnitPosition, unitID)
end
local function getUnitDir(unitID)
return wrapResVect(Spring.GetUnitDirection, unitID)
end
local function direction(from, to)
local dir = {to[1] - from[1], to[2] - from[2], to[3] - from[3]}
local len = math.sqrt(dir[1] * dir[1] + dir[2] * dir[2] + dir[3] * dir[3])
return {dir[1] / len, dir[2] / len, dir[3] / len }
end
local function dirsEqual(v1, v2)
local ratioX = v1[1] / v2[1]
local ratioZ = v1[3] / v2[3]
local tolerance = 0.05
return math.abs(ratioZ - ratioX) < tolerance
end
local function distanceSq(pos1, pos2)
local dist = 0
for i = 1,3 do
local d = pos1[i] - pos2[i]
dist = dist + d * d
end
return dist
end
local function UnitMoved(self, unitID, x, _, z)
local lastPos = self.lastPositions[unitID]
if not lastPos then
lastPos = {x = x, z = z}
self.lastPositions[unitID] = lastPos
Logger.log("move-command","unit:", unitID, "x: ", x ,", z: ", z)
return true
end
Logger.log("move-command", "unit:", unitID, " x: ", x ,", lastX: ", lastPos.x, ", z: ", z, ", lastZ: ", lastPos.z)
moved = x ~= lastPos.x or z ~= lastPos.z
self.lastPositions[unitID] = {x = x, z = z}
return moved
end
function New(self)
Logger.log("command", "Running New in move")
self.lastPositions = {}
self.subTargets = {}
self.finalTargets = {}
end
local function EnsureLeader(self, unitIds)
if self.leaderId and not unitIsDead(self.leaderId) and distanceSq(getUnitPos(self.leaderId), self.finalTargets[self.leaderId]) > TOLERANCE_SQ then
return self.leaderId
end
self.leaderId = nil
for i = 1, #unitIds do
if not unitIsDead(unitIds[i]) then
self.leaderId = unitIds[i]
break
end
end
--Logger.log("move-command", "=== finalTargets: ", self.finalTargets)
local tar = self.finalTargets[self.leaderId]
--Logger.log("move-command", "=== tar: ", tar)
giveOrderToUnit(self.leaderId, CMD.MOVE, tar, {})
return self.leaderId
end
local function InitTargetLocations(self, unitIds, parameter)
self.finalTargets = {}
for i = 1, #unitIds do
local id = unitIds[i]
local pos = getUnitPos(id)
--Logger.log("move-command", "=== pos: ", pos)
local tarPos = { pos[1] + parameter.x, pos[2], pos[3] + parameter.y }
--Logger.log("move-command", "=== tarPos: ", tarPos)
self.finalTargets[id] = tarPos
end
end
function Run(self, unitIds, parameter)
Logger.log("move-command", "Lua MOVE command run, unitIds: ", unitIds, ", parameter.x: " .. parameter.x .. ", parameter.y: " .. parameter.y)
local firstTick = false
if not self.finalTargets then
InitTargetLocations(self, unitIds, parameter)
firstTick = true
end
local leader = EnsureLeader(self, unitIds)
if not leader then
return FAILURE
end
local leaderDir = getUnitDir(leader)
local leaderDone = distanceSq(getUnitPos(leader), self.finalTargets[leader]) < LEADER_TOLERANCE_SQ
Logger.log("move-command", "Leader done - ", leaderDone, " dist - ", distanceSq(getUnitPos(leader), self.finalTargets[leader]))
local done = leaderDone
local issueFinalOrder = false
if leaderDone and not self.finalOrderIssued then
self.finalOrderIssued = true
issueFinalOrder = true
end
local unitsSize = #unitIds
local distSum = 0
local distMax = 0
for i=1, unitsSize do
local unitID = unitIds[i]
if unitID ~= leader then
local curPos = getUnitPos(unitID)
local curSubTar = self.subTargets[unitID]
local curDir = direction(getUnitPos(unitID), curSubTar or {0,0,0})
local dist = distanceSq(curPos, self.finalTargets[unitID])
--Logger.log("move-command", " ------ dist ", dist)
if dist > distMax then
distMax = dist
end
distSum = distSum + dist
if leaderDone then
-- go to the target location when leader reaches the target location
if issueFinalOrder then
Logger.log("move-command", "=== Final order ", unitID)
giveOrderToUnit(unitID, CMD.MOVE, self.finalTargets[unitID], {})
end
elseif not curSubTar or distanceSq(curPos, curSubTar) < SUBTARGET_TOLEARANCE_SQ or not dirsEqual(leaderDir, curDir) then
-- otherwise move a small distance in the direction the leader is facing
if firstTick then -- the leader needs to turn first, so send the unit in the direction of the target instead of following the leaders direction, which may be left over from the previous move command.
leaderDir = direction(curPos, self.finalTargets[unitID])
end
curSubTar = {curPos[1] + leaderDir[1] * SHORT_PATH_LEN, curPos[2], curPos[3] + leaderDir[3] * SHORT_PATH_LEN}
self.subTargets[unitID] = curSubTar
giveOrderToUnit(unitID, CMD.MOVE, curSubTar, {})
end
end
end
-- Logger.log("move-command", "dist sum - ", distSum, ", max sum - ", (unitsSize - 1) * TOLERANCE_SQ)
if distSum < (unitsSize - 1) * TOLERANCE_SQ and distMax < MOST_DISTANT_UNIT_DIST_SQ then
return SUCCESS
--elseif noneMoved then
-- return FAILURE
else
return RUNNING
end
end
function Reset(self)
Logger.log("move-command", "Lua command reset")
self.leaderTarget = nil
self.lastPositions = {}
self.leaderId = nil
self.subTargets = {}
self.finalTargets = nil
self.finalOrderIssued = false
end
|
function getInfo()
return {
onNoUnits = SUCCESS,
parameterDefs = {
{
name = "x",
variableType = "number",
componentType = "editBox",
defaultValue = "0",
},
{
name = "y",
variableType = "number",
componentType = "editBox",
defaultValue = "0",
}
}
}
end
local giveOrderToUnit = Spring.GiveOrderToUnit
--local getUnitDir = Spring.GetUnitDirection
local unitIsDead = Spring.GetUnitIsDead
local SHORT_PATH_LEN = 100
local SUBTARGET_TOLEARANCE_SQ = 30*30
local TOLERANCE_SQ = 30*30
local MOST_DISTANT_UNIT_DIST_SQ = 50*50
local LEADER_TOLERANCE_SQ = 50 * 50
local WAYPOINTS_DIST_SQ = 20 * 20
local function wrapResVect(f, id)
local x, y, z = f(id)
return { x, y, z}
end
local function getUnitPos(unitID)
return wrapResVect(Spring.GetUnitPosition, unitID)
end
local function getUnitDir(unitID)
return wrapResVect(Spring.GetUnitDirection, unitID)
end
local function makeVector(from, to)
return{to[1] - from[1], to[2] - from[2], to[3] - from[3]}
end
local function direction(from, to)
local dir = makeVector(from, to)
local len = math.sqrt(dir[1] * dir[1] + dir[2] * dir[2] + dir[3] * dir[3])
-- normalize vector
return {dir[1] / len, dir[2] / len, dir[3] / len }
end
local function dirsEqual(v1, v2)
local ratioX = v1[1] / v2[1]
local ratioZ = v1[3] / v2[3]
local tolerance = 0.05
return math.abs(ratioZ - ratioX) < tolerance
end
local function distanceSq(pos1, pos2)
local dist = 0
for i = 1,3 do
local d = pos1[i] - pos2[i]
dist = dist + d * d
end
return dist
end
local function addToList(list, item)
list[#list + 1] = item
end
local function vectSum(...)
local sum = {0, 0, 0}
for _,vect in ipairs(arg) do
sum = {sum[1] + vect[1], sum[2] + vect[2], sum[3] + vect[3]}
end
return sum
end
local function UnitMoved(self, unitID, x, _, z)
local lastPos = self.lastPositions[unitID]
if not lastPos then
lastPos = {x = x, z = z}
self.lastPositions[unitID] = lastPos
Logger.log("move-command","unit:", unitID, "x: ", x ,", z: ", z)
return true
end
Logger.log("move-command", "unit:", unitID, " x: ", x ,", lastX: ", lastPos.x, ", z: ", z, ", lastZ: ", lastPos.z)
moved = x ~= lastPos.x or z ~= lastPos.z
self.lastPositions[unitID] = {x = x, z = z}
return moved
end
function New(self)
Logger.log("command", "Running New in move")
self.lastPositions = {}
self.subTargets = {}
self.finalTargets = {}
self.formationDiffs = {}
self.leaderWaypoints = {}
end
local lastLeaderPos
local function EnsureLeader(self, unitIds)
if self.leaderId and not unitIsDead(self.leaderId) and distanceSq(getUnitPos(self.leaderId), self.finalTargets[self.leaderId]) > TOLERANCE_SQ then
return self.leaderId
end
self.leaderId = nil
for i = 1, #unitIds do
if not unitIsDead(unitIds[i]) then
self.leaderId = unitIds[i]
break
end
end
--Logger.log("move-command", "=== finalTargets: ", self.finalTargets)
local tar = self.finalTargets[self.leaderId]
--Logger.log("move-command", "=== tar: ", tar)
giveOrderToUnit(self.leaderId, CMD.MOVE, tar, {})
return self.leaderId
end
local function InitTargetLocations(self, unitIds, parameter)
self.finalTargets = {}
local leaderPos = getUnitPos(self.leaderId)
for i = 1, #unitIds do
local id = unitIds[i]
local pos = getUnitPos(id)
--Logger.log("move-command", "=== pos: ", pos)
local tarPos = { pos[1] + parameter.x, pos[2], pos[3] + parameter.y }
--Logger.log("move-command", "=== tarPos: ", tarPos)
self.finalTargets[id] = tarPos
self.formationDiffs[id] = math.sqrt(distanceSq(leaderPos, pos))
end
end
function Run(self, unitIds, parameter)
Logger.log("move-command", "Lua MOVE command run, unitIds: ", unitIds, ", parameter.x: " .. parameter.x .. ", parameter.y: " .. parameter.y)
local leader = EnsureLeader(self, unitIds)
if not leader then
return FAILURE
end
local firstTick = false
if not self.finalTargets then
InitTargetLocations(self, unitIds, parameter)
firstTick = true
end
local leaderPos = getUnitPos(leader)
local waypoints = self.leaderWaypoints
if (#waypoints == 0 or distanceSq(leaderPos, waypoints[#waypoints]) > WAYPOINTS_DIST_SQ) then
addToList(waypoints, leaderPos)
end
local leaderDir
if (firstTick) then
leaderDir = direction(leaderPos, self.finalTargets[leader])
else
leaderDir = direction(waypoints[#waypoints - 3] or waypoints[1], leaderPos)
end
local leaderDone = distanceSq(getUnitPos(leader), self.finalTargets[leader]) < LEADER_TOLERANCE_SQ
-- Logger.log("move-command", "Leader done - ", leaderDone, " dist - ", distanceSq(getUnitPos(leader), self.finalTargets[leader]))
local done = leaderDone
local issueFinalOrder = false
if leaderDone and not self.finalOrderIssued then
self.finalOrderIssued = true
issueFinalOrder = true
end
local unitsSize = #unitIds
local distSum = 0
local distMax = 0
for i=1, unitsSize do
local unitID = unitIds[i]
if unitID ~= leader then
local curPos = getUnitPos(unitID)
local curSubTar = self.subTargets[unitID]
local curDir = direction(getUnitPos(unitID), curSubTar or {0,0,0})
local dist = distanceSq(curPos, self.finalTargets[unitID])
--Logger.log("move-command", " ------ dist ", dist)
if dist > distMax then
distMax = dist
end
distSum = distSum + dist
if leaderDone then
-- go to the target location when leader reaches the target location
if issueFinalOrder then
--Logger.log("move-command", "=== Final order ", unitID)
giveOrderToUnit(unitID, CMD.MOVE, self.finalTargets[unitID], {})
end
elseif not curSubTar or distanceSq(curPos, curSubTar) < SUBTARGET_TOLEARANCE_SQ or not dirsEqual(leaderDir, curDir) then
-- otherwise move a small distance in the direction the leader is facing
local toLeader = makeVector(curPos, leaderPos)
curSubTar = vectSum(curPos, toLeader, leaderDir, formationDiffs[unitID])
-- curSubTar = {curPos[1] + leaderDir[1] * SHORT_PATH_LEN, curPos[2], curPos[3] + leaderDir[3] * SHORT_PATH_LEN}
self.subTargets[unitID] = curSubTar
giveOrderToUnit(unitID, CMD.MOVE, curSubTar, {})
end
end
end
-- Logger.log("move-command", "dist sum - ", distSum, ", max sum - ", (unitsSize - 1) * TOLERANCE_SQ)
if distSum < (unitsSize - 1) * TOLERANCE_SQ and distMax < MOST_DISTANT_UNIT_DIST_SQ then
return SUCCESS
--elseif noneMoved then
-- return FAILURE
else
return RUNNING
end
end
function Reset(self)
Logger.log("move-command", "Lua command reset")
self.leaderTarget = nil
self.lastPositions = {}
self.leaderId = nil
self.subTargets = {}
self.finalTargets = nil
self.finalOrderIssued = false
self.formationDiffs = {}
end
|
Attempt at fix of optimized move command.
|
Attempt at fix of optimized move command.
|
Lua
|
mit
|
MartinFrancu/BETS
|
520f4830430433e75ce23aa8d8537df9c4fd7043
|
lua/autorun/mediaplayer_spawnables.lua
|
lua/autorun/mediaplayer_spawnables.lua
|
local MediaPlayerClass = "mediaplayer_tv"
local function AddMediaPlayerModel( spawnName, name, model, playerConfig )
list.Set( "SpawnableEntities", spawnName, {
PrintName = name,
ClassName = MediaPlayerClass,
Category = "Media Player",
DropToFloor = true,
KeyValues = {
model = model
}
} )
list.Set( "MediaPlayerModelConfigs", model, playerConfig )
end
AddMediaPlayerModel(
"../spawnicons/models/hunter/plates/plate5x8",
"Huge Billboard",
"models/hunter/plates/plate5x8.mdl",
{
angle = Angle(0, 90, 0),
offset = Vector(-118.8, 189.8, 2.5),
width = 380,
height = 238
}
)
if SERVER or IsMounted( "cstrike" ) then
AddMediaPlayerModel(
"../spawnicons/models/props/cs_office/tv_plasma",
"Small TV",
"models/props/cs_office/tv_plasma.mdl",
{
angle = Angle(-90, 90, 0),
offset = Vector(6.5, 27.9, 35.3),
width = 56,
height = 33
}
)
end
|
local MediaPlayerClass = "mediaplayer_tv"
local function AddMediaPlayerModel( spawnName, name, model, playerConfig )
list.Set( "SpawnableEntities", spawnName, {
PrintName = name,
ClassName = MediaPlayerClass,
Category = "Media Player",
DropToFloor = true,
KeyValues = {
model = model
}
} )
list.Set( "MediaPlayerModelConfigs", model, playerConfig )
end
AddMediaPlayerModel(
"../spawnicons/models/hunter/plates/plate5x8",
"Huge Billboard",
"models/hunter/plates/plate5x8.mdl",
{
angle = Angle(0, 90, 0),
offset = Vector(-118.8, 189.8, 2.5),
width = 380,
height = 238
}
)
if SERVER or IsMounted( "cstrike" ) then
AddMediaPlayerModel(
"../spawnicons/models/props/cs_office/tv_plasma",
"Small TV",
"models/props/cs_office/tv_plasma.mdl",
{
angle = Angle(-90, 90, 0),
offset = Vector(6.5, 27.9, 35.3),
width = 56,
height = 33
}
)
end
if SERVER then
-- fix for media player owner not getting set on alternate model spawn
hook.Add( "PlayerSpawnedSENT", "MediaPlayer.SetOwner", function(ply, ent)
if not ent.IsMediaPlayerEntity then return end
ent:SetCreator(ply)
local mp = ent:GetMediaPlayer()
mp:SetOwner(ply)
end )
end
|
Fixed alternate media player models not properly setting the owner.
|
Fixed alternate media player models not properly setting the owner.
|
Lua
|
mit
|
pixeltailgames/gm-mediaplayer,pixeltailgames/gm-mediaplayer
|
cd80a9c296877f4f6d3b86e1c3633f369b0dce9f
|
scene/result.lua
|
scene/result.lua
|
--
-- Ekran wyświetlający wyniki.
--
-- Wymagane moduły
local app = require( 'lib.app' )
local preference = require( 'preference' )
local composer = require( 'composer' )
local fx = require( 'com.ponywolf.ponyfx' )
local tiled = require( 'com.ponywolf.ponytiled' )
local json = require( 'json' )
local translations = require( 'translations' )
-- Lokalne zmienne
local scene = composer.newScene()
local info, ui
function scene:create( event )
local sceneGroup = self.view
-- Wczytanie mapy
local uiData = json.decodeFile( system.pathForFile( 'scene/menu/ui/result.json', system.ResourceDirectory ) )
info = tiled.new( uiData, 'scene/menu/ui' )
info.x, info.y = _CX - info.designedWidth * 0.5, _CY - info.designedHeight * 0.5
-- Obsługa przycisków
info.extensions = 'scene.menu.lib.'
info:extend( 'button', 'label' )
function ui( event )
local phase = event.phase
local name = event.buttonName
if phase == 'released' then
app.playSound( 'button' )
if ( name == 'restart' ) then
fx.fadeOut( function()
composer.hideOverlay( 'crossFade' )
composer.gotoScene( 'scene.refresh', { params = {} } )
end )
elseif ( name == 'menu' ) then
fx.fadeOut( function()
composer.hideOverlay( 'crossFade' )
composer.gotoScene( 'scene.menu', { params = {} } )
end )
end
end
return true
end
sceneGroup:insert( info )
end
function scene:show( event )
local phase = event.phase
local textId = event.params.textId
local newScore = event.params.newScore
local totalPoints = preference:get( 'totalPoints' )
local lang = preference:get( 'language' )
if ( phase == 'will' ) then
print( totalPoints )
totalPoints = totalPoints + newScore
local message = {
win = translations[lang]['winMessage'] .. totalPoints,
lost = translations[lang]['loseMessage'] .. totalPoints,
}
info:findObject('message').text = message[textId]
-- zlicza wszystkie zdobyte punkty
preference:set('totalPoints', totalPoints )
elseif ( phase == 'did' ) then
app.addRuntimeEvents( {'ui', ui} )
end
end
function scene:hide( event )
local phase = event.phase
local previousScene = event.parent
if ( phase == 'will' ) then
app.removeAllRuntimeEvents()
previousScene:resumeGame()
elseif ( phase == 'did' ) then
end
end
function scene:destroy( event )
--collectgarbage()
end
scene:addEventListener( 'create' )
scene:addEventListener( 'show' )
scene:addEventListener( 'hide' )
scene:addEventListener( 'destroy' )
return scene
|
--
-- Ekran wyświetlający wyniki.
--
-- Wymagane moduły
local app = require( 'lib.app' )
local preference = require( 'preference' )
local composer = require( 'composer' )
local fx = require( 'com.ponywolf.ponyfx' )
local tiled = require( 'com.ponywolf.ponytiled' )
local json = require( 'json' )
local translations = require( 'translations' )
-- Lokalne zmienne
local scene = composer.newScene()
local info, ui
function scene:create( event )
local sceneGroup = self.view
-- Wczytanie mapy
local uiData = json.decodeFile( system.pathForFile( 'scene/menu/ui/result.json', system.ResourceDirectory ) )
info = tiled.new( uiData, 'scene/menu/ui' )
info.x, info.y = _CX - info.designedWidth * 0.5, _CY - info.designedHeight * 0.5
-- Obsługa przycisków
info.extensions = 'scene.menu.lib.'
info:extend( 'button', 'label' )
function ui( event )
local phase = event.phase
local name = event.buttonName
if phase == 'released' then
app.playSound( 'button' )
if ( name == 'restart' ) then
fx.fadeOut( function()
composer.hideOverlay()
composer.gotoScene( 'scene.refresh', { params = {} } )
end )
elseif ( name == 'menu' ) then
fx.fadeOut( function()
composer.hideOverlay()
composer.gotoScene( 'scene.menu', { params = {} } )
end )
end
end
return true
end
sceneGroup:insert( info )
end
function scene:show( event )
local phase = event.phase
local textId = event.params.textId
local newScore = event.params.newScore
local totalPoints = preference:get( 'totalPoints' )
local lang = preference:get( 'language' )
if ( phase == 'will' ) then
print( totalPoints )
totalPoints = totalPoints + newScore
local message = {
win = translations[lang]['winMessage'] .. totalPoints,
lost = translations[lang]['loseMessage'] .. totalPoints,
}
info:findObject('message').text = message[textId]
-- zlicza wszystkie zdobyte punkty
preference:set('totalPoints', totalPoints )
elseif ( phase == 'did' ) then
app.addRuntimeEvents( {'ui', ui} )
end
end
function scene:hide( event )
local phase = event.phase
if ( phase == 'will' ) then
app.removeAllRuntimeEvents()
elseif ( phase == 'did' ) then
end
end
function scene:destroy( event )
--collectgarbage()
end
scene:addEventListener( 'create' )
scene:addEventListener( 'show' )
scene:addEventListener( 'hide' )
scene:addEventListener( 'destroy' )
return scene
|
Bug fix
|
Bug fix
|
Lua
|
mit
|
ldurniat/The-Great-Pong,ldurniat/My-Pong-Game
|
f0b6267c6a02e4db1f1bda6a1f02f5842beb2fb8
|
spec/ev_spec.lua
|
spec/ev_spec.lua
|
-- Runs internally an ev async test and checks the returned statuses.
if not pcall(require, "ev") then
describe("Testing ev loop", function()
pending("The 'ev' loop was not tested because 'ev' isn't installed")
end)
else
local generic_async = require 'generic_async_test'
local ev = require 'ev'
local loop = ev.Loop.default
local statuses = busted.run_internal_test(function()
local eps = 0.000000000001
local yield = function(done)
ev.Timer.new(
function()
done()
end,eps):start(loop)
end
setloop('ev')
generic_async.setup_tests(yield,'ev')
end)
generic_async.describe_statuses(statuses)
local statuses = busted.run_internal_test(function()
setloop('ev')
it('this should timeout',function(done)
settimeout(0.01)
ev.Timer.new(async(done),0.1):start(loop)
end)
it('this should not timeout',function(done)
settimeout(0.1)
ev.Timer.new(async(done),0.01):start(loop)
end)
end)
it('first test is timeout',function()
local status = statuses[1]
assert.is_equal(status.type,'failure')
assert.is_equal(status.err,'test timeout elapsed (0.01s)')
assert.is_equal(status.trace,'')
end)
it('second test is not timeout',function()
local status = statuses[2]
assert.is_equal(status.type,'success')
end)
end
|
-- Runs internally an ev async test and checks the returned statuses.
if not pcall(require, "ev") then
describe("Testing ev loop", function()
pending("The 'ev' loop was not tested because 'ev' isn't installed")
end)
else
local generic_async = require 'generic_async_test'
local ev = require 'ev'
local loop = ev.Loop.default
local statuses = busted.run_internal_test(function()
local eps = 0.000000000001
local yield = function(done)
ev.Timer.new(
function()
done()
end,eps):start(loop)
end
setloop('ev')
generic_async.setup_tests(yield,'ev')
end)
generic_async.describe_statuses(statuses)
local statuses = busted.run_internal_test(function()
setloop('ev')
it('this should timeout',function(done)
settimeout(0.01)
ev.Timer.new(async(function() done() end),0.1):start(loop)
end)
it('this should not timeout',function(done)
settimeout(0.1)
ev.Timer.new(async(function() done() end),0.01):start(loop)
end)
end)
it('first test is timeout',function()
local status = statuses[1]
assert.is_equal(status.type,'failure')
assert.is_equal(status.err,'test timeout elapsed (0.01s)')
assert.is_equal(status.trace,'')
end)
it('second test is not timeout',function()
local status = statuses[2]
assert.is_equal(status.type,'success')
end)
end
|
fix 2 tests
|
fix 2 tests
|
Lua
|
mit
|
nehz/busted,leafo/busted,ryanplusplus/busted,sobrinho/busted,DorianGray/busted,o-lim/busted,mpeterv/busted,istr/busted,xyliuke/busted,Olivine-Labs/busted
|
475947283539f2badc47a078adec379a14d6a3db
|
MMOCoreORB/bin/conf/config.lua
|
MMOCoreORB/bin/conf/config.lua
|
--Copyright (C) 2007 <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
--which carries forward this exception.
-- Core3 Config File
-- 0 = false, 1 = true
MakeLogin = 1
MakeZone = 1
MakePing = 1
MakeStatus = 1
ORB = ""
DBHost = "127.0.0.1"
DBPort = 3306
DBName = "swgemu"
DBUser = "swgemu"
DBPass = "123456"
LoginPort = 44453
LoginProcessingThreads = 1
LoginAllowedConnections = 3000
LoginRequiredVersion = "20050408-18:00"
MantisHost = "127.0.0.1"
MantisPort = 3306
MantisName = "swgemu"
MantisUser = "swgemu"
MantisPass = "123456"
MantisPrfx = "mantis_" -- The prefix for your mantis tables.
AutoReg = 1
PingPort = 44462
PingAllowedConnections = 3000
ZoneProcessingThreads = 10
ZoneAllowedConnections = 30000
ZoneGalaxyID = 2 --The actual zone server's galaxyID. Should coordinate with your login server.
ZoneOnlineCharactersPerAccount = 2 --How many characters are allowed online from a single account.
-- directory of tres with live.cfg
TrePath = "/Applications/SWGEmu.app/Contents/Resources/transgaming/c_drive/SWGEMU"
--Status Server Config
StatusPort = 44455
StatusAllowedConnections = 500
StatusInterval = 30 -- interval to check if zone is locked up (in seconds)
TreFiles = {
"default_patch.tre",
"hotfix_13_1_00.tre",
"patch_sku1_13_00.tre",
"patch_13_00.tre",
"patch_sku1_12_00.tre",
"patch_12_00.tre",
"patch_11_03.tre",
"data_sku1_07.tre",
"patch_11_02.tre",
"data_sku1_06.tre",
"patch_11_01.tre",
"patch_11_00.tre",
"data_sku1_05.tre",
"data_sku1_04.tre",
"data_sku1_03.tre",
"data_sku1_02.tre",
"data_sku1_01.tre",
"data_sku1_00.tre",
"patch_10.tre",
"patch_09.tre",
"patch_08.tre",
"patch_07.tre",
"patch_06.tre",
"patch_05.tre",
"patch_04.tre",
"patch_03.tre",
"patch_02.tre",
"patch_01.tre",
"patch_00.tre",
"data_other_00.tre",
"data_static_mesh_01.tre",
"data_static_mesh_00.tre",
"data_texture_07.tre",
"data_texture_06.tre",
"data_texture_05.tre",
"data_texture_04.tre",
"data_texture_03.tre",
"data_texture_02.tre",
"data_texture_01.tre",
"data_texture_00.tre",
"data_skeletal_mesh_01.tre",
"data_skeletal_mesh_00.tre",
"data_animation_00.tre",
"data_sample_04.tre",
"data_sample_03.tre",
"data_sample_02.tre",
"data_sample_01.tre",
"data_sample_00.tre",
"data_music_00.tre",
"bottom.tre"
}
|
--Copyright (C) 2007 <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
--which carries forward this exception.
-- Core3 Config File
-- 0 = false, 1 = true
MakeLogin = 1
MakeZone = 1
MakePing = 1
MakeStatus = 1
ORB = ""
DBHost = "172.26.0.2"
DBPort = 3306
DBName = "swgemu"
DBUser = "root"
DBPass = "swgemu"
LoginPort = 44453
LoginProcessingThreads = 1
LoginAllowedConnections = 3000
LoginRequiredVersion = "20050408-18:00"
MantisHost = "172.26.0.2"
MantisPort = 3306
MantisName = "swgemu"
MantisUser = "root"
MantisPass = "swgemu"
MantisPrfx = "mantis_" -- The prefix for your mantis tables.
AutoReg = 1
PingPort = 44462
PingAllowedConnections = 3000
ZoneProcessingThreads = 10
ZoneAllowedConnections = 30000
ZoneGalaxyID = 2 --The actual zone server's galaxyID. Should coordinate with your login server.
ZoneOnlineCharactersPerAccount = 2 --How many characters are allowed online from a single account.
-- directory of tres with live.cfg
TrePath = "/Applications/SWGEmu.app/Contents/Resources/transgaming/c_drive/SWGEMU"
TreFiles = {
"default_patch.tre",
"patch_sku1_14_00.tre",
"patch_14_00.tre",
"hotfix_13_1_00.tre",
"patch_sku1_13_00.tre",
"patch_13_00.tre",
"patch_sku1_12_00.tre",
"patch_12_00.tre",
"patch_11_03.tre",
"data_sku1_07.tre",
"patch_11_02.tre",
"data_sku1_06.tre",
"patch_11_01.tre",
"patch_11_00.tre",
"data_sku1_05.tre",
"data_sku1_04.tre",
"data_sku1_03.tre",
"data_sku1_02.tre",
"data_sku1_01.tre",
"data_sku1_00.tre",
"patch_10.tre",
"patch_09.tre",
"patch_08.tre",
"patch_07.tre",
"patch_06.tre",
"patch_05.tre",
"patch_04.tre",
"patch_03.tre",
"patch_02.tre",
"patch_01.tre",
"patch_00.tre",
"data_other_00.tre",
"data_static_mesh_01.tre",
"data_static_mesh_00.tre",
"data_texture_07.tre",
"data_texture_06.tre",
"data_texture_05.tre",
"data_texture_04.tre",
"data_texture_03.tre",
"data_texture_02.tre",
"data_texture_01.tre",
"data_texture_00.tre",
"data_skeletal_mesh_01.tre",
"data_skeletal_mesh_00.tre",
"data_animation_00.tre",
"data_sample_04.tre",
"data_sample_03.tre",
"data_sample_02.tre",
"data_sample_01.tre",
"data_sample_00.tre",
"data_music_00.tre",
"bottom.tre"
}
--Status Server Config
StatusPort = 44455
StatusAllowedConnections = 500
StatusInterval = 30 -- interval to check if zone is locked up (in seconds)
|
[fixed] added patch_14.tre loading
|
[fixed] added patch_14.tre loading
git-svn-id: c34995188cc7e843f8a799edec2d9d4b36f36456@3013 c3d1530f-68f5-4bd0-87dc-8ef779617e40
|
Lua
|
agpl-3.0
|
lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,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,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo
|
fdb5e65fb4895ed99de65e098768daa2ee6f738c
|
sample/standard/proto/tcp/security.lua
|
sample/standard/proto/tcp/security.lua
|
------------------------------------
-- TCP attacks
------------------------------------
haka.rule {
hooks = { "tcp-up" },
eval = function (self, pkt)
--Xmas scan, as made by nmap -sX <IP>
if pkt.flags.psh and pkt.flags.fin and pkt.flags.urg then
haka.log.error("filter", "Xmas attack detected !!!")
pkt:drop()
end
end
}
haka.rule {
hooks = { "tcp-up" },
eval = function (self, pkt)
local bindshell = "\xeb\x1f\x5e\x89\x76\x08\x31\xc0\x88\x46\x07\x89\x46\x0c\xb0\x0b" ..
"\x89\xf3\x8d\x4e\x08\x8d\x56\x0c\xcd\x80\x31\xdb\x89\xd8\x40\xcd" ..
"\x80\xe8\xdc\xff\xff\xff/bin/sh"
if #pkt.payload > 0 then
-- reconstruct payload
payload = getpayload(pkt.payload)
-- test if shellcode is present in data
if string.find(payload, bindshell) then
haka.log.error("filter", "/bin/sh shellcode detected !!!")
pkt:drop()
end
end
end
}
|
------------------------------------
-- TCP attacks
------------------------------------
haka.rule {
hooks = { "tcp-up" },
eval = function (self, pkt)
--Xmas scan, as made by nmap -sX <IP>
if pkt.flags.psh and pkt.flags.fin and pkt.flags.urg then
haka.log.error("filter", "Xmas attack detected !!!")
pkt:drop()
end
end
}
local function string_convert(t)
for i=1,#t do
if type(t[i]) == "number" then t[i] = string.char(t[i]) end
end
return table.concat(t)
end
local bindshell = string_convert({0xeb, 0x1f, 0x5e, 0x89, 0x76, 0x08, 0x31, 0xc0,
0x88, 0x46, 0x07, 0x89, 0x46, 0x0c, 0xb0, 0x0b, 0x89, 0xf3, 0x8d, 0x4e, 0x08,
0x8d, 0x56, 0x0c, 0xcd, 0x80, 0x31, 0xdb, 0x89, 0xd8, 0x40, 0xcd, 0x80, 0xe8,
0xdc, 0xff, 0xff, 0xff, "/bin/sh"})
haka.rule {
hooks = { "tcp-up" },
eval = function (self, pkt)
if #pkt.payload > 0 then
-- reconstruct payload
payload = getpayload(pkt.payload)
-- test if shellcode is present in data
if string.find(payload, bindshell) then
haka.log.error("filter", "/bin/sh shellcode detected !!!")
pkt:drop()
end
end
end
}
|
Fix sample with Lua51
|
Fix sample with Lua51
In Lua51, the notation \x* is not supported.
|
Lua
|
mpl-2.0
|
Wingless-Archangel/haka,Wingless-Archangel/haka,nabilbendafi/haka,haka-security/haka,haka-security/haka,LubyRuffy/haka,lcheylus/haka,nabilbendafi/haka,lcheylus/haka,nabilbendafi/haka,LubyRuffy/haka,lcheylus/haka,haka-security/haka
|
d33665e7d2aedaa8bb293c21f8dba6afa8b27e18
|
deps/secure-socket/context.lua
|
deps/secure-socket/context.lua
|
--[[
Copyright 2016 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 openssl = require('openssl')
local loadResource
if type(module) == "table" then
function loadResource(path)
return module:load(path)
end
else
loadResource = require('resource').load
end
local bit = require('bit')
local DEFAULT_CIPHERS = 'ECDHE-RSA-AES128-SHA256:AES128-GCM-SHA256:' .. -- TLS 1.2
'!RC4:HIGH:!MD5:!aNULL:!EDH' -- TLS 1.0
local DEFAULT_CA_STORE
do
local data = assert(loadResource("./root_ca.dat"))
DEFAULT_CA_STORE = openssl.x509.store:new()
local index = 1
local dataLength = #data
while index < dataLength do
local len = bit.bor(bit.lshift(data:byte(index), 8), data:byte(index + 1))
index = index + 2
local cert = assert(openssl.x509.read(data:sub(index, index + len)))
index = index + len
assert(DEFAULT_CA_STORE:add(cert))
end
end
local function returnOne()
return 1
end
return function (options)
local ctx = openssl.ssl.ctx_new(
options.protocol or 'TLSv1_2',
options.ciphers or DEFAULT_CIPHERS)
local key, cert, ca
if options.key then
key = assert(openssl.pkey.read(options.key, true, 'pem'))
end
if options.cert then
cert = {}
for chunk in options.cert:gmatch("%-+BEGIN[^-]+%-+[^-]+%-+END[^-]+%-+") do
cert[#cert + 1] = assert(openssl.x509.read(chunk))
end
end
if options.ca then
if type(options.ca) == "string" then
ca = { assert(openssl.x509.read(options.ca)) }
elseif type(options.ca) == "table" then
ca = {}
for i = 1, #options.ca do
ca[i] = assert(openssl.x509.read(options.ca[i]))
end
else
error("options.ca must be string or table of strings")
end
end
if key and cert then
local first = table.remove(cert, 1)
assert(ctx:use(key, first))
if #cert > 0 then
-- TODO: find out if there is a way to not need to duplicate the last cert here
-- as a dummy fill for the root CA cert
assert(ctx:add(cert[#cert], cert))
end
end
if ca then
local store = openssl.x509.store:new()
for i = 1, #ca do
assert(store:add(ca[i]))
end
ctx:cert_store(store)
elseif DEFAULT_CA_STORE then
ctx:cert_store(DEFAULT_CA_STORE)
end
if not (options.insecure or options.key) then
ctx:verify_mode(openssl.ssl.peer, returnOne)
end
ctx:options(bit.bor(
openssl.ssl.no_sslv2,
openssl.ssl.no_sslv3,
openssl.ssl.no_compression))
return ctx
end
|
--[[
Copyright 2016 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 openssl = require('openssl')
local loadResource
if type(module) == "table" then
function loadResource(path)
return module:load(path)
end
else
loadResource = require('resource').load
end
local bit = require('bit')
local DEFAULT_SECUREPROTOCOL
do
local _, _, V = openssl.version()
local isLibreSSL = V:find('^LibreSSL')
_, _, V = openssl.version(true)
local isTLSv1_3 = not isLibreSSL and V > 0x10100000
if isTLSv1_3 then
DEFAULT_SECUREPROTOCOL = 'TLS'
else
DEFAULT_SECUREPROTOCOL = 'SSLv23'
end
end
local DEFAULT_CIPHERS = 'TLS_AES_128_GCM_SHA256:TLS_AES_128_CCM_SHA256:' .. --TLS 1.3
'ECDHE-RSA-AES128-SHA256:AES128-GCM-SHA256:' .. --TLS 1.2
'RC4:HIGH:!MD5:!aNULL:!EDH' --TLS 1.0
local DEFAULT_CA_STORE
do
local data = assert(loadResource("./root_ca.dat"))
DEFAULT_CA_STORE = openssl.x509.store:new()
local index = 1
local dataLength = #data
while index < dataLength do
local len = bit.bor(bit.lshift(data:byte(index), 8), data:byte(index + 1))
index = index + 2
local cert = assert(openssl.x509.read(data:sub(index, index + len)))
index = index + len
assert(DEFAULT_CA_STORE:add(cert))
end
end
local function returnOne()
return 1
end
return function (options)
local ctx = openssl.ssl.ctx_new(
options.protocol or DEFAULT_SECUREPROTOCOL,
options.ciphers or DEFAULT_CIPHERS)
local key, cert, ca
if options.key then
key = assert(openssl.pkey.read(options.key, true, 'pem'))
end
if options.cert then
cert = {}
for chunk in options.cert:gmatch("%-+BEGIN[^-]+%-+[^-]+%-+END[^-]+%-+") do
cert[#cert + 1] = assert(openssl.x509.read(chunk))
end
end
if options.ca then
if type(options.ca) == "string" then
ca = { assert(openssl.x509.read(options.ca)) }
elseif type(options.ca) == "table" then
ca = {}
for i = 1, #options.ca do
ca[i] = assert(openssl.x509.read(options.ca[i]))
end
else
error("options.ca must be string or table of strings")
end
end
if key and cert then
local first = table.remove(cert, 1)
assert(ctx:use(key, first))
if #cert > 0 then
-- TODO: find out if there is a way to not need to duplicate the last cert here
-- as a dummy fill for the root CA cert
assert(ctx:add(cert[#cert], cert))
end
end
if ca then
local store = openssl.x509.store:new()
for i = 1, #ca do
assert(store:add(ca[i]))
end
ctx:cert_store(store)
elseif DEFAULT_CA_STORE then
ctx:cert_store(DEFAULT_CA_STORE)
end
if not (options.insecure or options.key) then
ctx:verify_mode(openssl.ssl.peer, returnOne)
end
ctx:options(bit.bor(
openssl.ssl.no_sslv2,
openssl.ssl.no_sslv3,
openssl.ssl.no_compression))
return ctx
end
|
Fix secure-socket for OpenSSL > 1.1.0 (#257)
|
Fix secure-socket for OpenSSL > 1.1.0 (#257)
Fixes #256
Lit version of https://github.com/luvit/luvit/pull/1062
|
Lua
|
apache-2.0
|
luvit/lit,zhaozg/lit
|
75c904fead5b20505c57dfc9601184adb6b3ed16
|
exercises/102/palindrome-rewrite-nospaces.lua
|
exercises/102/palindrome-rewrite-nospaces.lua
|
function isPalindrome(input)
original = input -- saved for the final message
-- remove spaces
withoutSpaces = ""
for i = 1,#input do
letter = string.sub(input, i, i)
if letter ~= " " then
withoutSpaces = withoutSpaces .. letter
end
end
-- reverse
reverse = ""
for i = #withoutSpaces,1,-1 do
reverse = reverse .. string.sub(withoutSpaces, i, i)
end
-- check if they are the same
return withoutSpaces == reverse
end
input = "a man a plan a canal panama"
if isPalindrome(input) then
print("'" .. input .. "' is a palindrome!")
else
print("'" .. input .. "' is not a palindrome!")
end
|
function isPalindrome(input)
-- remove spaces
withoutSpaces = ""
for i = 1,#input do
letter = string.sub(input, i, i)
if letter ~= " " then
withoutSpaces = withoutSpaces .. letter
end
end
-- reverse
reverse = ""
for i = #withoutSpaces,1,-1 do
reverse = reverse .. string.sub(withoutSpaces, i, i)
end
-- check if they are the same
return withoutSpaces == reverse
end
input = "a man a plan a canal panama"
if isPalindrome(input) then
print("'" .. input .. "' is a palindrome!")
else
print("'" .. input .. "' is not a palindrome!")
end
|
Fixed palindrome exercise
|
Fixed palindrome exercise
|
Lua
|
mit
|
Castux/devtut,Castux/devtut
|
9067cba27b1cf23356693e1ee1c027879c289e11
|
lib/acid/unittest.lua
|
lib/acid/unittest.lua
|
local _M = { _VERSION='0.1' }
local function tostr(x)
return '[' .. tostring( x ) .. ']'
end
local function dd(...)
local args = {...}
local s = ''
for _, mes in ipairs(args) do
s = s .. tostring(mes)
end
_M.output( s )
end
function _M.output(s)
print( s )
end
local function is_test_file( fn )
return fn:sub( 1, 5 ) == 'test_' and fn:sub( -4, -1 ) == '.lua'
end
local function scandir(directory)
local t = {}
for filename in io.popen('ls "'..directory..'"'):lines() do
table.insert( t, filename )
end
return t
end
local function keys(tbl)
local n = 0
local ks = {}
for k, v in pairs( tbl ) do
table.insert( ks, k )
n = n + 1
end
table.sort( ks, function(a, b) return tostring(a)<tostring(b) end )
return ks, n
end
local testfuncs = {
ass= function (self, expr, expection, mes)
mes = mes or ''
local thisfile = debug.getinfo(1).short_src
local info
for i = 2, 10 do
info = debug.getinfo(i)
if info.short_src ~= thisfile then
break
end
end
local pos = 'Failure: \n'
pos = pos .. ' in ' .. info.short_src .. '\n'
pos = pos .. ' ' .. self._name .. '():' .. info.currentline .. '\n'
assert( expr, pos .. ' expect ' .. expection .. ' (' .. mes .. ')' )
self._suite.n_assert = self._suite.n_assert + 1
end,
eq= function( self, a, b, mes )
self:ass( a==b, 'to be ' .. tostr(a) .. ' but is ' .. tostr(b), mes )
end,
neq= function( self, a, b, mes )
self:ass( a~=b, 'not to be' .. tostr(a) .. ' but the same: ' .. tostr(b), mes )
end,
err= function ( self, func, mes )
local ok, rst = pcall( func )
self:eq( false, ok, mes )
end,
eqlist= function( self, a, b, mes )
self:neq( nil, a, "left list is not nil " .. (mes or '') )
self:neq( nil, b, "right list is not nil " .. (mes or '') )
for i, e in ipairs(a) do
self:ass( e==b[i], i .. 'th elt to be ' .. tostr(e) .. ' but is ' .. tostr(b[i]), mes )
end
-- check if b has more elements
for i, e in ipairs(b) do
self:ass( nil~=a[i], i .. 'th elt to be nil but is ' .. tostr(e), mes )
end
end,
eqdict= function( self, a, b, mes )
mes = mes or ''
if a == b then
return
end
self:neq( nil, a, "left table is not nil" .. mes )
self:neq( nil, b, "right table is not nil" .. mes )
local akeys, an = keys( a )
local bkeys, bn = keys( b )
for _, k in ipairs( akeys ) do
self:ass( b[k] ~= nil, '["' .. k .. '"] in right but not. '.. mes )
end
for _, k in ipairs( bkeys ) do
self:ass( a[k] ~= nil, '["' .. k .. '"] in left but not. '.. mes )
end
for _, k in ipairs( akeys ) do
local av, bv = a[k], b[k]
if type( av ) == 'table' and type( bv ) == 'table' then
self:eqdict( av, bv, k .. '<' .. mes )
else
self:ass( a[k] == b[k],
'["' .. k .. '"] to be ' .. tostr(a[k]) .. ' but is ' .. tostr(b[k]), mes )
end
end
end,
contain= function( self, a, b, mes )
self:neq( nil, a, "left table is not nil" )
self:neq( nil, b, "right table is not nil" )
for k, e in pairs(a) do
self:ass( e==b[k], '["' .. k .. '"] to be ' .. tostr(e) .. ' but is ' .. tostr(b[k]), mes )
end
end,
}
local _mt = { __index= testfuncs }
local function find_tests(tbl)
local tests = {}
for k, v in pairs(tbl) do
if k:sub( 1, 5 ) == 'test_' and type( v ) == 'function' then
tests[ k ] = v
end
end
return tests
end
function _M.test_one( suite, name, func )
dd( "* testing ", name, ' ...' )
local tfuncs = {}
setmetatable( tfuncs, _mt )
tfuncs._name = name
tfuncs._suite = suite
local co = coroutine.create( func )
local ok, rst = coroutine.resume( co, tfuncs )
if not ok then
dd( rst )
dd( debug.traceback(co) )
os.exit(1)
end
suite.n = suite.n + 1
end
function _M.testall( suite )
local names = {}
local tests = find_tests( _G )
for k, v in pairs(tests) do
table.insert( names, { k, v } )
end
table.sort( names, function(x, y) return x[ 1 ]<y[ 1 ] end )
for _, t in ipairs( names ) do
local funcname, func = t[ 1 ], t[ 2 ]
_M.test_one( suite, funcname, func )
end
end
function _M.testdir( dir )
package.path = package.path .. ';'..dir..'/?.lua'
local suite = { n=0, n_assert=0 }
local fns = scandir( dir )
for _, fn in ipairs(fns) do
if is_test_file( fn ) then
dd( "---- ", fn, ' ----' )
local tests0 = find_tests( _G )
require( fn:sub( 1, -5 ) )
local tests1 = find_tests( _G )
_M.testall( suite )
for k, v in pairs(tests1) do
if tests0[ k ] == nil then
_G[ k ] = nil
end
end
end
end
dd( suite.n, ' tests all passed. nr of assert: ', suite.n_assert )
return true
end
function _M.t()
if arg == nil then
-- lua -l unittest
_M.testdir( '.' )
os.exit()
else
-- require( "unittest" )
end
end
_M.t()
return _M
|
local _M = { _VERSION='0.1' }
local function tostr(x)
return '[' .. tostring( x ) .. ']'
end
local function dd(...)
local args = {...}
local s = ''
for _, mes in ipairs(args) do
s = s .. tostring(mes)
end
_M.output( s )
end
function _M.output(s)
print( s )
end
local function is_test_file( fn )
return fn:sub( 1, 5 ) == 'test_' and fn:sub( -4, -1 ) == '.lua'
end
local function scandir(directory)
local t = {}
for filename in io.popen('ls "'..directory..'"'):lines() do
table.insert( t, filename )
end
return t
end
local function keys(tbl)
local n = 0
local ks = {}
for k, v in pairs( tbl ) do
table.insert( ks, k )
n = n + 1
end
table.sort( ks, function(a, b) return tostring(a)<tostring(b) end )
return ks, n
end
local testfuncs = {
ass= function (self, expr, expection, mes)
mes = mes or ''
local thisfile = debug.getinfo(1).short_src
local info
for i = 2, 10 do
info = debug.getinfo(i)
if info.short_src ~= thisfile then
break
end
end
local pos = 'Failure: \n'
pos = pos .. ' in ' .. info.short_src .. '\n'
pos = pos .. ' ' .. self._name .. '():' .. info.currentline .. '\n'
assert( expr, pos .. ' expect ' .. expection .. ' (' .. mes .. ')' )
self._suite.n_assert = self._suite.n_assert + 1
end,
eq= function( self, a, b, mes )
self:ass( a==b, 'to be ' .. tostr(a) .. ' but is ' .. tostr(b), mes )
end,
neq= function( self, a, b, mes )
self:ass( a~=b, 'not to be' .. tostr(a) .. ' but the same: ' .. tostr(b), mes )
end,
err= function ( self, func, mes )
local ok, rst = pcall( func )
self:eq( false, ok, mes )
end,
eqlist= function( self, a, b, mes )
if a == b then
return
end
self:neq( nil, a, "left list is not nil " .. (mes or '') )
self:neq( nil, b, "right list is not nil " .. (mes or '') )
for i, e in ipairs(a) do
self:ass( e==b[i], i .. 'th elt to be ' .. tostr(e) .. ' but is ' .. tostr(b[i]), mes )
end
-- check if b has more elements
for i, e in ipairs(b) do
self:ass( nil~=a[i], i .. 'th elt to be nil but is ' .. tostr(e), mes )
end
end,
eqdict= function( self, a, b, mes )
mes = mes or ''
if a == b then
return
end
self:neq( nil, a, "left table is not nil " .. mes )
self:neq( nil, b, "right table is not nil " .. mes )
local akeys, an = keys( a )
local bkeys, bn = keys( b )
for _, k in ipairs( akeys ) do
self:ass( b[k] ~= nil, '["' .. k .. '"] in right but not. '.. mes )
end
for _, k in ipairs( bkeys ) do
self:ass( a[k] ~= nil, '["' .. k .. '"] in left but not. '.. mes )
end
for _, k in ipairs( akeys ) do
local av, bv = a[k], b[k]
if type( av ) == 'table' and type( bv ) == 'table' then
self:eqdict( av, bv, k .. '<' .. mes )
else
self:ass( a[k] == b[k],
'["' .. k .. '"] to be ' .. tostr(a[k]) .. ' but is ' .. tostr(b[k]), mes )
end
end
end,
contain= function( self, a, b, mes )
self:neq( nil, a, "left table is not nil" )
self:neq( nil, b, "right table is not nil" )
for k, e in pairs(a) do
self:ass( e==b[k], '["' .. k .. '"] to be ' .. tostr(e) .. ' but is ' .. tostr(b[k]), mes )
end
end,
}
local _mt = { __index= testfuncs }
local function find_tests(tbl)
local tests = {}
for k, v in pairs(tbl) do
if k:sub( 1, 5 ) == 'test_' and type( v ) == 'function' then
tests[ k ] = v
end
end
return tests
end
function _M.test_one( suite, name, func )
dd( "* testing ", name, ' ...' )
local tfuncs = {}
setmetatable( tfuncs, _mt )
tfuncs._name = name
tfuncs._suite = suite
local co = coroutine.create( func )
local ok, rst = coroutine.resume( co, tfuncs )
if not ok then
dd( rst )
dd( debug.traceback(co) )
os.exit(1)
end
suite.n = suite.n + 1
end
function _M.testall( suite )
local names = {}
local tests = find_tests( _G )
for k, v in pairs(tests) do
table.insert( names, { k, v } )
end
table.sort( names, function(x, y) return x[ 1 ]<y[ 1 ] end )
for _, t in ipairs( names ) do
local funcname, func = t[ 1 ], t[ 2 ]
_M.test_one( suite, funcname, func )
end
end
function _M.testdir( dir )
package.path = package.path .. ';'..dir..'/?.lua'
local suite = { n=0, n_assert=0 }
local fns = scandir( dir )
for _, fn in ipairs(fns) do
if is_test_file( fn ) then
dd( "---- ", fn, ' ----' )
local tests0 = find_tests( _G )
require( fn:sub( 1, -5 ) )
local tests1 = find_tests( _G )
_M.testall( suite )
for k, v in pairs(tests1) do
if tests0[ k ] == nil then
_G[ k ] = nil
end
end
end
end
dd( suite.n, ' tests all passed. nr of assert: ', suite.n_assert )
return true
end
function _M.t()
if arg == nil then
-- lua -l unittest
_M.testdir( '.' )
os.exit()
else
-- require( "unittest" )
end
end
_M.t()
return _M
|
fix unittest: eqdict add space between expectation and mes
|
fix unittest: eqdict add space between expectation and mes
|
Lua
|
mit
|
drmingdrmer/lua-paxos,drmingdrmer/lua-paxos
|
5c98f1edc2f521fd882d1796bdb043492ce138fe
|
xmake/plugins/macro/macros/package.lua
|
xmake/plugins/macro/macros/package.lua
|
--!The Make-like Build Utility based on Lua
--
-- XMake 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.1 of the License, or
-- (at your option) any later version.
--
-- XMake 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 XMake;
-- If not, see <a href="http://www.gnu.org/licenses/"> http://www.gnu.org/licenses/</a>
--
-- Copyright (C) 2015 - 2016, ruki All rights reserved.
--
-- @author ruki
-- @file package.lua
--
-- imports
import("core.base.option")
import("core.project.config")
import("core.project.project")
import("core.platform.platform")
-- the options
local options =
{
{'p', "plat", "kv", os.host(), "Set the platform." }
, {'f', "config", "kv", nil, "Pass the config arguments to \"xmake config\" .." }
, {'o', "outputdir", "kv", nil, "Set the output directory of the package." }
}
-- package all
--
-- .e.g
-- xmake m package
-- xmake m package -f "-m debug"
-- xmake m package -p linux
-- xmake m package -p iphoneos -f "-m debug --xxx ..." -o /tmp/xxx
-- xmake m package -f \"--mode=debug\"
--
function main(argv)
-- parse arguments
local args = option.parse(argv, options, "Package all architectures for the given the platform."
, ""
, "Usage: xmake macro package [options]")
-- package all archs
local plat = args.plat
for _, arch in ipairs(platform.archs(plat)) do
-- config it
os.exec("xmake f -p %s -a %s %s -c %s", plat, arch, args.config or "", ifelse(option.get("verbose"), "-v", ""))
-- package it
if args.outputdir then
os.exec("xmake p -o %s %s", args.outputdir, ifelse(option.get("verbose"), "-v", ""))
else
os.exec("xmake p %s", ifelse(option.get("verbose"), "-v", ""))
end
end
-- package universal for iphoneos, watchos ...
if plat == "iphoneos" or plat == "watchos" then
-- load configure
config.load()
-- load project
project.load()
-- the outputdir directory
local outputdir = args.outputdir or config.get("buildir")
-- package all targets
for _, target in pairs(project.targets()) do
-- get all modes
local modedirs = os.match(format("%s/%s.pkg/lib/*", outputdir, target:name()), true)
for _, modedir in ipairs(modedirs) do
-- get mode
local mode = path.basename(modedir)
-- make lipo arguments
local lipoargs = nil
for _, arch in ipairs(platform.archs(plat)) do
local archfile = format("%s/%s.pkg/lib/%s/%s/%s/%s", outputdir, target:name(), mode, plat, arch, path.filename(target:targetfile()))
if os.isfile(archfile) then
lipoargs = format("%s -arch %s %s", lipoargs or "", arch, archfile)
end
end
if lipoargs then
-- make full lipo arguments
lipoargs = format("-create %s -output %s/%s.pkg/lib/%s/%s/universal/%s", lipoargs, outputdir, target:name(), mode, plat, path.filename(target:targetfile()))
-- make universal directory
os.mkdir(format("%s/%s.pkg/lib/%s/%s/universal", outputdir, target:name(), mode, plat))
-- package all archs
os.execv("xmake", {"l", "lipo", lipoargs})
end
end
end
end
end
|
--!The Make-like Build Utility based on Lua
--
-- XMake 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.1 of the License, or
-- (at your option) any later version.
--
-- XMake 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 XMake;
-- If not, see <a href="http://www.gnu.org/licenses/"> http://www.gnu.org/licenses/</a>
--
-- Copyright (C) 2015 - 2016, ruki All rights reserved.
--
-- @author ruki
-- @file package.lua
--
-- imports
import("core.base.option")
import("core.project.config")
import("core.project.project")
import("core.platform.platform")
-- the options
local options =
{
{'p', "plat", "kv", os.host(), "Set the platform." }
, {'f', "config", "kv", nil, "Pass the config arguments to \"xmake config\" .." }
, {'o', "outputdir", "kv", nil, "Set the output directory of the package." }
}
-- package all
--
-- .e.g
-- xmake m package
-- xmake m package -f "-m debug"
-- xmake m package -p linux
-- xmake m package -p iphoneos -f "-m debug --xxx ..." -o /tmp/xxx
-- xmake m package -f \"--mode=debug\"
--
function main(argv)
-- parse arguments
local args = option.parse(argv, options, "Package all architectures for the given the platform."
, ""
, "Usage: xmake macro package [options]")
-- package all archs
local plat = args.plat
for _, arch in ipairs(platform.archs(plat)) do
-- config it
os.exec("xmake f -p %s -a %s %s -c %s", plat, arch, args.config or "", ifelse(option.get("verbose"), "-v", ""))
-- package it
if args.outputdir then
os.exec("xmake p -o %s %s", args.outputdir, ifelse(option.get("verbose"), "-v", ""))
else
os.exec("xmake p %s", ifelse(option.get("verbose"), "-v", ""))
end
end
-- package universal for iphoneos, watchos ...
if plat == "iphoneos" or plat == "watchos" then
-- load configure
config.load()
-- load project
project.load()
-- enter the project directory
os.cd(project.directory())
-- the outputdir directory
local outputdir = args.outputdir or config.get("buildir")
-- package all targets
for _, target in pairs(project.targets()) do
-- get all modes
local modedirs = os.match(format("%s/%s.pkg/lib/*", outputdir, target:name()), true)
for _, modedir in ipairs(modedirs) do
-- get mode
local mode = path.basename(modedir)
-- make lipo arguments
local lipoargs = nil
for _, arch in ipairs(platform.archs(plat)) do
local archfile = format("%s/%s.pkg/lib/%s/%s/%s/%s", outputdir, target:name(), mode, plat, arch, path.filename(target:targetfile()))
if os.isfile(archfile) then
lipoargs = format("%s -arch %s %s", lipoargs or "", arch, archfile)
end
end
if lipoargs then
-- make full lipo arguments
lipoargs = format("-create %s -output %s/%s.pkg/lib/%s/%s/universal/%s", lipoargs, outputdir, target:name(), mode, plat, path.filename(target:targetfile()))
-- make universal directory
os.mkdir(format("%s/%s.pkg/lib/%s/%s/universal", outputdir, target:name(), mode, plat))
-- package all archs
os.execv("xmake", {"l", "lipo", lipoargs})
end
end
end
end
end
|
fix the packge macro
|
fix the packge macro
|
Lua
|
apache-2.0
|
tboox/xmake,tboox/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,tboox/xmake,waruqi/xmake,tboox/xmake,tboox/xmake,tboox/xmake,waruqi/xmake,tboox/xmake
|
8c7d0f53041af5b5e5b4e42902e6ac49abbd5bd7
|
MCServer/Plugins/InfoReg.lua
|
MCServer/Plugins/InfoReg.lua
|
-- InfoReg.lua
-- Implements registration functions that process g_PluginInfo
--- Lists all the subcommands that the player has permissions for
local function ListSubcommands(a_Player, a_Subcommands, a_CmdString)
if (a_Player == nil) then
LOGINFO("The " .. a_CmdString .. " command requires another verb:")
else
a_Player:SendMessage("The " .. a_CmdString .. " command requires another verb:")
end
-- Enum all the subcommands:
local Verbs = {};
for cmd, info in pairs(a_Subcommands) do
if (a_Player:HasPermission(info.Permission or "")) then
table.insert(Verbs, " " .. a_CmdString .. " " .. cmd);
end
end
table.sort(Verbs);
-- Send the list:
if (a_Player == nil) then
for idx, verb in ipairs(Verbs) do
LOGINFO(verb);
end
else
for idx, verb in ipairs(Verbs) do
a_Player:SendMessage(verb);
end
end
end
--- This is a generic command callback used for handling multicommands' parent commands
-- For example, if there are "/gal save" and "/gal load" commands, this callback handles the "/gal" command
-- It is used for both console and in-game commands; the console version has a_Player set to nil
local function MultiCommandHandler(a_Split, a_Player, a_CmdString, a_CmdInfo, a_Level)
local Verb = a_Split[a_Level + 1];
if (Verb == nil) then
-- No verb was specified. If there is a handler for the upper level command, call it:
if (a_CmdInfo.Handler ~= nil) then
return a_CmdInfo.Handler(a_Split, a_Player);
end
-- Let the player know they need to give a subcommand:
ListSubcommands(a_Player, a_CmdInfo.Subcommands, a_CmdString);
return true;
end
-- A verb was specified, look it up in the subcommands table:
local Subcommand = a_CmdInfo.Subcommands[Verb];
if (Subcommand == nil) then
if (a_Level > 1) then
-- This is a true subcommand, display the message and make MCS think the command was handled
-- Otherwise we get weird behavior: for "/cmd verb" we get "unknown command /cmd" although "/cmd" is valid
if (a_Player == nil) then
LOGWARNING("The " .. a_CmdString .. " command doesn't support verb " .. Verb)
else
a_Player:SendMessage("The " .. a_CmdString .. " command doesn't support verb " .. Verb)
end
return true;
end
-- This is a top-level command, let MCS handle the unknown message
return false;
end
-- Check the permission:
if (a_Player ~= nil) then
if not(a_Player:HasPermission(Subcommand.Permission or "")) then
a_Player:SendMessage("You don't have permission to execute this command");
return true;
end
end
-- If the handler is not valid, check the next sublevel:
if (Subcommand.Handler == nil) then
if (Subcommand.Subcommands == nil) then
LOG("Cannot find handler for command " .. a_CmdString .. " " .. Verb);
return false;
end
MultiCommandHandler(a_Split, a_Player, a_CmdString .. " " .. Verb, Subcommand, a_Level + 1);
return true;
end
-- Execute:
return Subcommand.Handler(a_Split, a_Player);
end
--- Registers all commands specified in the g_PluginInfo.Commands
function RegisterPluginInfoCommands()
-- A sub-function that registers all subcommands of a single command, using the command's Subcommands table
-- The a_Prefix param already contains the space after the previous command
-- a_Level is the depth of the subcommands being registered, with 1 being the top level command
local function RegisterSubcommands(a_Prefix, a_Subcommands, a_Level)
assert(a_Subcommands ~= nil);
-- A table that will hold aliases to subcommands temporarily, during subcommand iteration
local AliasTable = {}
-- Iterate through the subcommands, register them, and accumulate aliases:
for cmd, info in pairs(a_Subcommands) do
local CmdName = a_Prefix .. cmd;
local Handler = info.Handler;
-- Provide a special handler for multicommands:
if (info.Subcommands ~= nil) then
Handler = function(a_Split, a_Player)
return MultiCommandHandler(a_Split, a_Player, CmdName, info, a_Level);
end
end
if (Handler == nil) then
LOGWARNING(g_PluginInfo.Name .. ": Invalid handler for command " .. CmdName .. ", command will not be registered.");
else
local HelpString;
if (info.HelpString ~= nil) then
HelpString = " - " .. info.HelpString;
else
HelpString = "";
end
cPluginManager.BindCommand(CmdName, info.Permission or "", Handler, HelpString);
-- Register all aliases for the command:
if (info.Alias ~= nil) then
if (type(info.Alias) == "string") then
info.Alias = {info.Alias};
end
for idx, alias in ipairs(info.Alias) do
cPluginManager.BindCommand(a_Prefix .. alias, info.Permission or "", Handler, HelpString);
-- Also copy the alias's info table as a separate subcommand,
-- so that MultiCommandHandler() handles it properly. Need to off-load into a separate table
-- than the one we're currently iterating and join after the iterating.
AliasTable[alias] = info
end
end
end -- else (if Handler == nil)
-- Recursively register any subcommands:
if (info.Subcommands ~= nil) then
RegisterSubcommands(a_Prefix .. cmd .. " ", info.Subcommands, a_Level + 1);
end
end -- for cmd, info - a_Subcommands[]
-- Add the subcommand aliases that were off-loaded during registration:
for alias, info in pairs(AliasTable) do
a_Subcommands[alias] = info
end
AliasTable = {}
end
-- Loop through all commands in the plugin info, register each:
RegisterSubcommands("", g_PluginInfo.Commands, 1);
end
--- Registers all console commands specified in the g_PluginInfo.ConsoleCommands
function RegisterPluginInfoConsoleCommands()
-- A sub-function that registers all subcommands of a single command, using the command's Subcommands table
-- The a_Prefix param already contains the space after the previous command
local function RegisterSubcommands(a_Prefix, a_Subcommands, a_Level)
assert(a_Subcommands ~= nil);
for cmd, info in pairs(a_Subcommands) do
local CmdName = a_Prefix .. cmd;
local Handler = info.Handler
if (Handler == nil) then
Handler = function(a_Split)
return MultiCommandHandler(a_Split, nil, CmdName, info, a_Level);
end
end
cPluginManager.BindConsoleCommand(CmdName, Handler, info.HelpString or "");
-- Recursively register any subcommands:
if (info.Subcommands ~= nil) then
RegisterSubcommands(a_Prefix .. cmd .. " ", info.Subcommands, a_Level + 1);
end
end
end
-- Loop through all commands in the plugin info, register each:
RegisterSubcommands("", g_PluginInfo.ConsoleCommands, 1);
end
|
-- InfoReg.lua
-- Implements registration functions that process g_PluginInfo
--- Lists all the subcommands that the player has permissions for
local function ListSubcommands(a_Player, a_Subcommands, a_CmdString)
if (a_Player == nil) then
LOGINFO("The " .. a_CmdString .. " command requires another verb:")
else
a_Player:SendMessage("The " .. a_CmdString .. " command requires another verb:")
end
-- Enum all the subcommands:
local Verbs = {}
for cmd, info in pairs(a_Subcommands) do
if ((a_Player == nil) or (a_Player:HasPermission(info.Permission or ""))) then
table.insert(Verbs, a_CmdString .. " " .. cmd)
end
end
table.sort(Verbs)
-- Send the list:
if (a_Player == nil) then
for idx, verb in ipairs(Verbs) do
LOGINFO(" " .. verb)
end
else
for idx, verb in ipairs(Verbs) do
a_Player:SendMessage(cCompositeChat(" ", mtInfo):AddSuggestCommandPart(verb, verb))
end
end
end
--- This is a generic command callback used for handling multicommands' parent commands
-- For example, if there are "/gal save" and "/gal load" commands, this callback handles the "/gal" command
-- It is used for both console and in-game commands; the console version has a_Player set to nil
local function MultiCommandHandler(a_Split, a_Player, a_CmdString, a_CmdInfo, a_Level)
local Verb = a_Split[a_Level + 1];
if (Verb == nil) then
-- No verb was specified. If there is a handler for the upper level command, call it:
if (a_CmdInfo.Handler ~= nil) then
return a_CmdInfo.Handler(a_Split, a_Player);
end
-- Let the player know they need to give a subcommand:
ListSubcommands(a_Player, a_CmdInfo.Subcommands, a_CmdString);
return true;
end
-- A verb was specified, look it up in the subcommands table:
local Subcommand = a_CmdInfo.Subcommands[Verb];
if (Subcommand == nil) then
if (a_Level > 1) then
-- This is a true subcommand, display the message and make MCS think the command was handled
-- Otherwise we get weird behavior: for "/cmd verb" we get "unknown command /cmd" although "/cmd" is valid
if (a_Player == nil) then
LOGWARNING("The " .. a_CmdString .. " command doesn't support verb " .. Verb)
else
a_Player:SendMessage("The " .. a_CmdString .. " command doesn't support verb " .. Verb)
end
return true;
end
-- This is a top-level command, let MCS handle the unknown message
return false;
end
-- Check the permission:
if (a_Player ~= nil) then
if not(a_Player:HasPermission(Subcommand.Permission or "")) then
a_Player:SendMessage("You don't have permission to execute this command");
return true;
end
end
-- If the handler is not valid, check the next sublevel:
if (Subcommand.Handler == nil) then
if (Subcommand.Subcommands == nil) then
LOG("Cannot find handler for command " .. a_CmdString .. " " .. Verb);
return false;
end
MultiCommandHandler(a_Split, a_Player, a_CmdString .. " " .. Verb, Subcommand, a_Level + 1);
return true;
end
-- Execute:
return Subcommand.Handler(a_Split, a_Player);
end
--- Registers all commands specified in the g_PluginInfo.Commands
function RegisterPluginInfoCommands()
-- A sub-function that registers all subcommands of a single command, using the command's Subcommands table
-- The a_Prefix param already contains the space after the previous command
-- a_Level is the depth of the subcommands being registered, with 1 being the top level command
local function RegisterSubcommands(a_Prefix, a_Subcommands, a_Level)
assert(a_Subcommands ~= nil);
-- A table that will hold aliases to subcommands temporarily, during subcommand iteration
local AliasTable = {}
-- Iterate through the subcommands, register them, and accumulate aliases:
for cmd, info in pairs(a_Subcommands) do
local CmdName = a_Prefix .. cmd;
local Handler = info.Handler;
-- Provide a special handler for multicommands:
if (info.Subcommands ~= nil) then
Handler = function(a_Split, a_Player)
return MultiCommandHandler(a_Split, a_Player, CmdName, info, a_Level);
end
end
if (Handler == nil) then
LOGWARNING(g_PluginInfo.Name .. ": Invalid handler for command " .. CmdName .. ", command will not be registered.");
else
local HelpString;
if (info.HelpString ~= nil) then
HelpString = " - " .. info.HelpString;
else
HelpString = "";
end
cPluginManager.BindCommand(CmdName, info.Permission or "", Handler, HelpString);
-- Register all aliases for the command:
if (info.Alias ~= nil) then
if (type(info.Alias) == "string") then
info.Alias = {info.Alias};
end
for idx, alias in ipairs(info.Alias) do
cPluginManager.BindCommand(a_Prefix .. alias, info.Permission or "", Handler, HelpString);
-- Also copy the alias's info table as a separate subcommand,
-- so that MultiCommandHandler() handles it properly. Need to off-load into a separate table
-- than the one we're currently iterating and join after the iterating.
AliasTable[alias] = info
end
end
end -- else (if Handler == nil)
-- Recursively register any subcommands:
if (info.Subcommands ~= nil) then
RegisterSubcommands(a_Prefix .. cmd .. " ", info.Subcommands, a_Level + 1);
end
end -- for cmd, info - a_Subcommands[]
-- Add the subcommand aliases that were off-loaded during registration:
for alias, info in pairs(AliasTable) do
a_Subcommands[alias] = info
end
AliasTable = {}
end
-- Loop through all commands in the plugin info, register each:
RegisterSubcommands("", g_PluginInfo.Commands, 1);
end
--- Registers all console commands specified in the g_PluginInfo.ConsoleCommands
function RegisterPluginInfoConsoleCommands()
-- A sub-function that registers all subcommands of a single command, using the command's Subcommands table
-- The a_Prefix param already contains the space after the previous command
local function RegisterSubcommands(a_Prefix, a_Subcommands, a_Level)
assert(a_Subcommands ~= nil);
for cmd, info in pairs(a_Subcommands) do
local CmdName = a_Prefix .. cmd;
local Handler = info.Handler
if (Handler == nil) then
Handler = function(a_Split)
return MultiCommandHandler(a_Split, nil, CmdName, info, a_Level);
end
end
cPluginManager.BindConsoleCommand(CmdName, Handler, info.HelpString or "");
-- Recursively register any subcommands:
if (info.Subcommands ~= nil) then
RegisterSubcommands(a_Prefix .. cmd .. " ", info.Subcommands, a_Level + 1);
end
end
end
-- Loop through all commands in the plugin info, register each:
RegisterSubcommands("", g_PluginInfo.ConsoleCommands, 1);
end
|
InfoReg uses cCompositeChat for subcommand lists.
|
InfoReg uses cCompositeChat for subcommand lists.
Also fixed an issue with console commands.
|
Lua
|
apache-2.0
|
QUSpilPrgm/cuberite,Fighter19/cuberite,Altenius/cuberite,tonibm19/cuberite,Schwertspize/cuberite,Tri125/MCServer,Fighter19/cuberite,nevercast/cuberite,nichwall/cuberite,jammet/MCServer,mjssw/cuberite,kevinr/cuberite,ionux/MCServer,SamOatesPlugins/cuberite,guijun/MCServer,Howaner/MCServer,HelenaKitty/EbooMC,linnemannr/MCServer,mjssw/cuberite,mmdk95/cuberite,Fighter19/cuberite,Howaner/MCServer,guijun/MCServer,nevercast/cuberite,nicodinh/cuberite,electromatter/cuberite,linnemannr/MCServer,nicodinh/cuberite,Tri125/MCServer,nounoursheureux/MCServer,Haxi52/cuberite,nicodinh/cuberite,marvinkopf/cuberite,birkett/cuberite,johnsoch/cuberite,Haxi52/cuberite,Altenius/cuberite,Fighter19/cuberite,tonibm19/cuberite,electromatter/cuberite,Schwertspize/cuberite,Haxi52/cuberite,mjssw/cuberite,ionux/MCServer,marvinkopf/cuberite,guijun/MCServer,marvinkopf/cuberite,SamOatesPlugins/cuberite,nicodinh/cuberite,Altenius/cuberite,MuhammadWang/MCServer,Howaner/MCServer,zackp30/cuberite,nounoursheureux/MCServer,mmdk95/cuberite,nounoursheureux/MCServer,nevercast/cuberite,guijun/MCServer,jammet/MCServer,zackp30/cuberite,QUSpilPrgm/cuberite,birkett/cuberite,kevinr/cuberite,ionux/MCServer,nichwall/cuberite,MuhammadWang/MCServer,nevercast/cuberite,mjssw/cuberite,SamOatesPlugins/cuberite,linnemannr/MCServer,thetaeo/cuberite,nichwall/cuberite,johnsoch/cuberite,guijun/MCServer,Frownigami1/cuberite,bendl/cuberite,Schwertspize/cuberite,bendl/cuberite,mc-server/MCServer,johnsoch/cuberite,Tri125/MCServer,mmdk95/cuberite,Haxi52/cuberite,nicodinh/cuberite,Fighter19/cuberite,birkett/MCServer,nounoursheureux/MCServer,birkett/cuberite,Tri125/MCServer,HelenaKitty/EbooMC,electromatter/cuberite,Altenius/cuberite,thetaeo/cuberite,nicodinh/cuberite,Tri125/MCServer,linnemannr/MCServer,Altenius/cuberite,nichwall/cuberite,mc-server/MCServer,electromatter/cuberite,Frownigami1/cuberite,nounoursheureux/MCServer,ionux/MCServer,jammet/MCServer,mmdk95/cuberite,marvinkopf/cuberite,SamOatesPlugins/cuberite,thetaeo/cuberite,marvinkopf/cuberite,Fighter19/cuberite,HelenaKitty/EbooMC,HelenaKitty/EbooMC,zackp30/cuberite,tonibm19/cuberite,johnsoch/cuberite,birkett/cuberite,mc-server/MCServer,jammet/MCServer,nevercast/cuberite,kevinr/cuberite,MuhammadWang/MCServer,Howaner/MCServer,mmdk95/cuberite,birkett/MCServer,HelenaKitty/EbooMC,Frownigami1/cuberite,QUSpilPrgm/cuberite,birkett/MCServer,jammet/MCServer,Schwertspize/cuberite,birkett/MCServer,birkett/MCServer,tonibm19/cuberite,mmdk95/cuberite,nichwall/cuberite,thetaeo/cuberite,ionux/MCServer,Tri125/MCServer,tonibm19/cuberite,thetaeo/cuberite,electromatter/cuberite,marvinkopf/cuberite,guijun/MCServer,electromatter/cuberite,kevinr/cuberite,bendl/cuberite,Frownigami1/cuberite,Haxi52/cuberite,jammet/MCServer,zackp30/cuberite,QUSpilPrgm/cuberite,bendl/cuberite,Haxi52/cuberite,linnemannr/MCServer,thetaeo/cuberite,nevercast/cuberite,kevinr/cuberite,bendl/cuberite,QUSpilPrgm/cuberite,birkett/cuberite,zackp30/cuberite,ionux/MCServer,SamOatesPlugins/cuberite,linnemannr/MCServer,kevinr/cuberite,Howaner/MCServer,mc-server/MCServer,Schwertspize/cuberite,nichwall/cuberite,birkett/cuberite,nounoursheureux/MCServer,tonibm19/cuberite,Frownigami1/cuberite,mjssw/cuberite,zackp30/cuberite,QUSpilPrgm/cuberite,Howaner/MCServer,mc-server/MCServer,johnsoch/cuberite,mjssw/cuberite,MuhammadWang/MCServer,MuhammadWang/MCServer,mc-server/MCServer,birkett/MCServer
|
2db8884c27bc432a09dbe3a86d92ef928c8b9c8a
|
build/Helpers.lua
|
build/Helpers.lua
|
-- This module checks for the all the project dependencies.
action = _ACTION or ""
depsdir = path.getabsolute("../deps");
srcdir = path.getabsolute("../src");
incdir = path.getabsolute("../include");
bindir = path.getabsolute("../bin");
examplesdir = path.getabsolute("../examples");
testsdir = path.getabsolute("../tests");
builddir = path.getabsolute("./" .. action);
if _ARGS[1] then
builddir = path.getabsolute("./" .. _ARGS[1]);
end
libdir = path.join(builddir, "lib", "%{cfg.buildcfg}_%{cfg.platform}");
gendir = path.join(builddir, "gen");
common_flags = { "Unicode", "Symbols" }
msvc_buildflags = { "/wd4267" }
gcc_buildflags = { "-std=c++11" }
msvc_cpp_defines = { }
function os.is_osx()
local version = os.getversion()
return string.find(version.description, "Mac OS X") ~= nil
end
function os.is_windows()
local version = os.getversion()
return string.find(version.description, "Windows") ~= nil
end
function string.starts(str, start)
return string.sub(str, 1, string.len(start)) == start
end
function SafePath(path)
return "\"" .. path .. "\""
end
function SetupNativeProject()
location (path.join(builddir, "projects"))
local c = configuration "Debug"
defines { "DEBUG" }
configuration "Release"
defines { "NDEBUG" }
optimize "On"
-- Compiler-specific options
configuration "vs*"
buildoptions { msvc_buildflags }
defines { msvc_cpp_defines }
configuration { "gmake" }
buildoptions { gcc_buildflags }
configuration { "macosx" }
buildoptions { gcc_buildflags, "-stdlib=libc++" }
links { "c++" }
-- OS-specific options
configuration "Windows"
defines { "WIN32", "_WINDOWS" }
configuration(c)
end
function SetupManagedProject()
language "C#"
location (path.join(builddir, "projects"))
if not os.is_osx() then
local c = configuration { "vs*" }
location "."
configuration(c)
end
end
function IncludeDir(dir)
local deps = os.matchdirs(dir .. "/*")
for i,dep in ipairs(deps) do
local fp = path.join(dep, "premake4.lua")
fp = path.join(os.getcwd(), fp)
if os.isfile(fp) then
print(string.format(" including %s", dep))
include(dep)
end
end
end
|
-- This module checks for the all the project dependencies.
action = _ACTION or ""
depsdir = path.getabsolute("../deps");
srcdir = path.getabsolute("../src");
incdir = path.getabsolute("../include");
bindir = path.getabsolute("../bin");
examplesdir = path.getabsolute("../examples");
testsdir = path.getabsolute("../tests");
builddir = path.getabsolute("./" .. action);
if _ARGS[1] then
builddir = path.getabsolute("./" .. _ARGS[1]);
end
libdir = path.join(builddir, "lib", "%{cfg.buildcfg}_%{cfg.platform}");
gendir = path.join(builddir, "gen");
common_flags = { "Unicode", "Symbols" }
msvc_buildflags = { "/wd4267" }
gcc_buildflags = { "-std=c++11" }
msvc_cpp_defines = { }
function os.is_osx()
return os.is("macosx")
end
function os.is_windows()
return os.is("windows")
end
function string.starts(str, start)
return string.sub(str, 1, string.len(start)) == start
end
function SafePath(path)
return "\"" .. path .. "\""
end
function SetupNativeProject()
location (path.join(builddir, "projects"))
local c = configuration "Debug"
defines { "DEBUG" }
configuration "Release"
defines { "NDEBUG" }
optimize "On"
-- Compiler-specific options
configuration "vs*"
buildoptions { msvc_buildflags }
defines { msvc_cpp_defines }
configuration { "gmake" }
buildoptions { gcc_buildflags }
configuration { "macosx" }
buildoptions { gcc_buildflags, "-stdlib=libc++" }
links { "c++" }
-- OS-specific options
configuration "Windows"
defines { "WIN32", "_WINDOWS" }
configuration(c)
end
function SetupManagedProject()
language "C#"
location (path.join(builddir, "projects"))
if not os.is_osx() then
local c = configuration { "vs*" }
location "."
configuration(c)
end
end
function IncludeDir(dir)
local deps = os.matchdirs(dir .. "/*")
for i,dep in ipairs(deps) do
local fp = path.join(dep, "premake4.lua")
fp = path.join(os.getcwd(), fp)
if os.isfile(fp) then
print(string.format(" including %s", dep))
include(dep)
end
end
end
|
Fix osx detection, we do not parse result of os.getversion() in premake (seems it return something strange). Instead use internal os detection in premake.
|
Fix osx detection, we do not parse result of os.getversion() in premake (seems it return something strange). Instead use internal os detection in premake.
|
Lua
|
mit
|
Samana/CppSharp,u255436/CppSharp,xistoso/CppSharp,ddobrev/CppSharp,zillemarco/CppSharp,mohtamohit/CppSharp,mohtamohit/CppSharp,mydogisbox/CppSharp,mydogisbox/CppSharp,nalkaro/CppSharp,mono/CppSharp,u255436/CppSharp,ddobrev/CppSharp,txdv/CppSharp,KonajuGames/CppSharp,Samana/CppSharp,zillemarco/CppSharp,KonajuGames/CppSharp,genuinelucifer/CppSharp,zillemarco/CppSharp,txdv/CppSharp,mohtamohit/CppSharp,Samana/CppSharp,imazen/CppSharp,KonajuGames/CppSharp,nalkaro/CppSharp,mono/CppSharp,xistoso/CppSharp,u255436/CppSharp,zillemarco/CppSharp,ddobrev/CppSharp,inordertotest/CppSharp,Samana/CppSharp,mydogisbox/CppSharp,inordertotest/CppSharp,Samana/CppSharp,SonyaSa/CppSharp,mono/CppSharp,ddobrev/CppSharp,xistoso/CppSharp,ktopouzi/CppSharp,inordertotest/CppSharp,ddobrev/CppSharp,txdv/CppSharp,genuinelucifer/CppSharp,SonyaSa/CppSharp,ktopouzi/CppSharp,nalkaro/CppSharp,SonyaSa/CppSharp,genuinelucifer/CppSharp,imazen/CppSharp,mono/CppSharp,SonyaSa/CppSharp,KonajuGames/CppSharp,txdv/CppSharp,imazen/CppSharp,mono/CppSharp,txdv/CppSharp,SonyaSa/CppSharp,ktopouzi/CppSharp,mydogisbox/CppSharp,xistoso/CppSharp,mydogisbox/CppSharp,u255436/CppSharp,xistoso/CppSharp,mohtamohit/CppSharp,genuinelucifer/CppSharp,u255436/CppSharp,KonajuGames/CppSharp,inordertotest/CppSharp,mohtamohit/CppSharp,zillemarco/CppSharp,genuinelucifer/CppSharp,nalkaro/CppSharp,nalkaro/CppSharp,ktopouzi/CppSharp,imazen/CppSharp,inordertotest/CppSharp,mono/CppSharp,ktopouzi/CppSharp,imazen/CppSharp
|
5ce93d98c21d010e6a61a0a72518ac72abd27171
|
rootfs/etc/nginx/lua/test/monitor_test.lua
|
rootfs/etc/nginx/lua/test/monitor_test.lua
|
_G._TEST = true
local original_ngx = ngx
local function reset_ngx()
_G.ngx = original_ngx
end
local function mock_ngx(mock)
local _ngx = mock
setmetatable(_ngx, { __index = ngx })
_G.ngx = _ngx
end
local function mock_ngx_socket_tcp()
local tcp_mock = {}
stub(tcp_mock, "connect", true)
stub(tcp_mock, "send", true)
stub(tcp_mock, "close", true)
local socket_mock = {}
stub(socket_mock, "tcp", tcp_mock)
mock_ngx({ socket = socket_mock })
return tcp_mock
end
describe("Monitor", function()
after_each(function()
reset_ngx()
package.loaded["monitor"] = nil
end)
it("batches metrics", function()
local monitor = require("monitor")
mock_ngx({ var = {} })
for i = 1,10,1 do
monitor.call()
end
assert.equal(10, #monitor.get_metrics_batch())
end)
describe("flush", function()
it("short circuits when premmature is true (when worker is shutting down)", function()
local tcp_mock = mock_ngx_socket_tcp()
local monitor = require("monitor")
mock_ngx({ var = {} })
for i = 1,10,1 do
monitor.call()
end
monitor.flush(true)
assert.stub(tcp_mock.connect).was_not_called()
end)
it("short circuits when there's no metrics batched", function()
local tcp_mock = mock_ngx_socket_tcp()
local monitor = require("monitor")
monitor.flush()
assert.stub(tcp_mock.connect).was_not_called()
end)
it("JSON encodes and sends the batched metrics", function()
local tcp_mock = mock_ngx_socket_tcp()
local monitor = require("monitor")
local ngx_var_mock = {
host = "example.com",
namespace = "default",
ingress_name = "example",
service_name = "http-svc",
location_path = "/",
request_method = "GET",
status = "200",
request_length = "256",
request_time = "0.04",
bytes_sent = "512",
upstream_addr = "10.10.0.1",
upstream_connect_time = "0.01",
upstream_response_time = "0.02",
upstream_response_length = "456",
upstream_status = "200",
}
mock_ngx({ var = ngx_var_mock })
monitor.call()
local ngx_var_mock1 = ngx_var_mock
ngx_var_mock1.status = "201"
ngx_var_mock1.request_method = "POST"
mock_ngx({ var = ngx_var_mock })
monitor.call()
monitor.flush()
local expected_payload = '[{"host":"example.com","method":"GET","requestLength":256,"status":"200","upstreamResponseLength":456,"upstreamLatency":0.01,"upstreamResponseTime":0.02,"path":"\\/","requestTime":0.04,"ingress":"example","namespace":"default","service":"http-svc","responseLength":512},{"host":"example.com","method":"POST","requestLength":256,"status":"201","upstreamResponseLength":456,"upstreamLatency":0.01,"upstreamResponseTime":0.02,"path":"\\/","requestTime":0.04,"ingress":"example","namespace":"default","service":"http-svc","responseLength":512}]'
assert.stub(tcp_mock.connect).was_called_with(tcp_mock, "unix:/tmp/prometheus-nginx.socket")
assert.stub(tcp_mock.send).was_called_with(tcp_mock, expected_payload)
assert.stub(tcp_mock.close).was_called_with(tcp_mock)
end)
end)
end)
|
_G._TEST = true
local original_ngx = ngx
local function reset_ngx()
_G.ngx = original_ngx
end
local function mock_ngx(mock)
local _ngx = mock
setmetatable(_ngx, { __index = ngx })
_G.ngx = _ngx
end
local function mock_ngx_socket_tcp()
local tcp_mock = {}
stub(tcp_mock, "connect", true)
stub(tcp_mock, "send", true)
stub(tcp_mock, "close", true)
local socket_mock = {}
stub(socket_mock, "tcp", tcp_mock)
mock_ngx({ socket = socket_mock })
return tcp_mock
end
describe("Monitor", function()
after_each(function()
reset_ngx()
package.loaded["monitor"] = nil
end)
it("batches metrics", function()
local monitor = require("monitor")
mock_ngx({ var = {} })
for i = 1,10,1 do
monitor.call()
end
assert.equal(10, #monitor.get_metrics_batch())
end)
describe("flush", function()
it("short circuits when premmature is true (when worker is shutting down)", function()
local tcp_mock = mock_ngx_socket_tcp()
local monitor = require("monitor")
mock_ngx({ var = {} })
for i = 1,10,1 do
monitor.call()
end
monitor.flush(true)
assert.stub(tcp_mock.connect).was_not_called()
end)
it("short circuits when there's no metrics batched", function()
local tcp_mock = mock_ngx_socket_tcp()
local monitor = require("monitor")
monitor.flush()
assert.stub(tcp_mock.connect).was_not_called()
end)
it("JSON encodes and sends the batched metrics", function()
local tcp_mock = mock_ngx_socket_tcp()
local monitor = require("monitor")
local ngx_var_mock = {
host = "example.com",
namespace = "default",
ingress_name = "example",
service_name = "http-svc",
location_path = "/",
request_method = "GET",
status = "200",
request_length = "256",
request_time = "0.04",
bytes_sent = "512",
upstream_addr = "10.10.0.1",
upstream_connect_time = "0.01",
upstream_response_time = "0.02",
upstream_response_length = "456",
upstream_status = "200",
}
mock_ngx({ var = ngx_var_mock })
monitor.call()
local ngx_var_mock1 = ngx_var_mock
ngx_var_mock1.status = "201"
ngx_var_mock1.request_method = "POST"
mock_ngx({ var = ngx_var_mock })
monitor.call()
monitor.flush()
local expected_payload = '[{"requestLength":256,"ingress":"example","status":"200","service":"http-svc","requestTime":0.04,"namespace":"default","host":"example.com","method":"GET","upstreamResponseTime":0.02,"upstreamResponseLength":456,"upstreamLatency":0.01,"path":"\\/","responseLength":512},{"requestLength":256,"ingress":"example","status":"201","service":"http-svc","requestTime":0.04,"namespace":"default","host":"example.com","method":"POST","upstreamResponseTime":0.02,"upstreamResponseLength":456,"upstreamLatency":0.01,"path":"\\/","responseLength":512}]'
assert.stub(tcp_mock.connect).was_called_with(tcp_mock, "unix:/tmp/prometheus-nginx.socket")
assert.stub(tcp_mock.send).was_called_with(tcp_mock, expected_payload)
assert.stub(tcp_mock.close).was_called_with(tcp_mock)
end)
end)
end)
|
Fix lua test
|
Lua
|
apache-2.0
|
kubernetes/ingress-nginx,kubernetes/ingress-nginx,caicloud/ingress,aledbf/ingress-nginx,aledbf/ingress-nginx,caicloud/ingress,canhnt/ingress,aledbf/ingress-nginx,canhnt/ingress,caicloud/ingress,kubernetes/ingress-nginx,canhnt/ingress,aledbf/ingress-nginx,kubernetes/ingress-nginx,caicloud/ingress,kubernetes/ingress-nginx,canhnt/ingress
|
|
3f95e0b0271a7f52b87a8c55f74e0f65c2ddd3ce
|
docker/notelauncher.lua
|
docker/notelauncher.lua
|
--
-- Module for managing notebook container instances running with the docker module
--
-- author: Steve Chan [email protected]
--
-- Copyright 2013 The Regents of the University of California,
-- Lawrence Berkeley National Laboratory
-- United States Department of Energy
-- The DOE Systems Biology Knowledgebase (KBase)
-- Made available under the KBase Open Source License
--
local M = {}
local locklib = require("resty.lock")
local docker = require('docker')
local json = require('json')
local p = require('pl.pretty')
local lfs = require('lfs')
-- This is the repository name, can be set by whoever instantiates a notelauncher
M.repository_image = 'kbase/narrative'
-- This is the tag to use, defaults to latest
M.repository_version = 'latest'
-- This is the port that should be exposed from the container, the service in the container
-- should have a listener on here configured
M.private_port = 8888
-- This is the path to the syslog Unix socket listener in the host environment
-- it is imported into the container via a Volumes argument
M.syslog_src = '/dev/log'
-- simple function to split string by whitespace and return table
local function split(self, s)
t = {}
for x in string.gmatch(s, "%S+") do
table.insert(t, x)
end
return t
end
--
-- Query the docker container for a list of containers and
-- return a list of the container ids that have listeners on
-- port 8888. Keyed on container name, value is IP:Port that can
-- be fed into an nginx proxy target
local function get_notebooks(self)
local ok, res = pcall(docker.client.containers, docker.client)
local portmap = {}
ngx.log(ngx.DEBUG, string.format("list containers result: %s", p.write(res.body)))
if ok then
for index, container in pairs(res.body) do
-- we only care about containers matching repository_image and listening on the proper port
first, last = string.find(container.Image, M.repository_image)
if first == 1 then
for i, v in pairs(container.Ports) do
if v.PrivatePort == M.private_port then
portmap[container.Id] = string.format("127.0.0.1:%u", v.PublicPort)
end
end
end
end
else
ngx.log(ngx.ERR, string.format("Failed to fetch list of containers: %s", p.write(res.body)))
end
return portmap
end
--
-- Actually launch a new docker container.
-- Return docker ID and table of info: { state, ip:port, session, last_time, last_ip }
--
local function launch_notebook(self)
-- don't wrap this in a pcall, if it fails let it propagate to
-- the caller
local conf = docker.config()
local bind_syslog = nil
conf.Image = string.format("%s:%s", M.repository_image, M.repository_version)
conf.PortSpecs = {tostring(M.private_port)}
ngx.log(ngx.INFO, string.format("Spinning up instance of %s on port %d", conf.Image, M.private_port))
-- we wrap the next call in pcall because we want to trap the case where we get an
-- error and try deleting the old container and creating a new one again
local ok, res = pcall(docker.client.create_container, docker.client, {payload = conf})
if not ok and res.response.status == "connection refused" then
ngx.log(ngx.ERR, "Unable to connect to docker API: "..p.write(res))
return nil, res
end
if not ok and res.response.status >= 409 and res.body.Id then
-- conflict, try to delete it and then create it again
local id = res.body.Id
ngx.log(ngx.ERR, string.format("conflicting notebook, removing container: %s", id))
ok, res = pcall(docker.client.remove_container, docker.client, {id = id})
ngx.log(ngx.ERR, string.format("response from remove_container: %s", p.write(res.response)))
-- ignore the response and retry the create, and if it still errors, let that propagate
ok, res = pcall(docker.client.create_container, docker.client, {payload = conf})
end
if ok then
assert(res.status == 201, "Failed to create container: "..json.encode(res.body))
local id = res.body.Id
if M.syslog_src then
-- Make sure it exists and is writeable
local stat = lfs.attributes(M.syslog_src)
if stat ~= nil and stat.mode == 'socket' then
bind_syslog = { string.format("%s:%s",M.syslog_src,"/dev/log") }
ngx.log(ngx.INFO, string.format("Binding %s in container %s", bind_syslog[1], id))
else
ngx.log(ngx.ERR, string.format("%s is not writeable, not mounting in container %s", M.syslog_src, id))
end
end
if bind_syslog ~= nil then
res = docker.client:start_container{id = id, payload = {PublishAllPorts = true, Binds = bind_syslog}}
else
res = docker.client:start_container{id = id, payload = {PublishAllPorts = true}}
end
assert(res.status == 204, "Failed to start container "..id.." : "..json.encode(res.body))
-- get back the container info to pull out the port mapping
res = docker.client:inspect_container{id=id}
assert(res.status == 200, "Could not inspect new container: "..id)
local ports = res.body.NetworkSettings.Ports
local ThePort = string.format("%d/tcp", M.private_port)
assert(ports[ThePort] ~= nil, string.format("Port binding for port %s not found!", ThePort))
local ip_port = string.format("%s:%d", "127.0.0.1", ports[ThePort][1].HostPort)
-- info = { state, ip:port, session, last_time, last_ip }
local info = {"queued", ip_port, "*", os.time(), "127.0.0.1"} -- default values except for ip_port
return id, info
else
ngx.log(ngx.ERR, "Failed to create container: "..p.write(res))
return nil, res
end
end
--
-- Kill and remove an existing docker container.
--
local function remove_notebook(self, id)
ngx.log(ngx.INFO, string.format("removing container: %s",id))
local res = docker.client:stop_container{id = id}
--ngx.log(ngx.INFO,string.format("response from stop_container: %d : %s",res.status,res.body))
assert(res.status == 204, "Failed to stop container: "..json.encode(res.body))
res = docker.client:remove_container{id = id}
--ngx.log(ngx.INFO,string.format("response from remove_container: %d : %s",res.status,res.body))
assert(res.status == 204, "Failed to remove container "..id.." : "..json.encode(res.body))
return true
end
M.docker = docker
M.split = split
M.get_notebooks = get_notebooks
M.launch_notebook = launch_notebook
M.remove_notebook = remove_notebook
return M
|
--
-- Module for managing notebook container instances running with the docker module
--
-- author: Steve Chan [email protected]
--
-- Copyright 2013 The Regents of the University of California,
-- Lawrence Berkeley National Laboratory
-- United States Department of Energy
-- The DOE Systems Biology Knowledgebase (KBase)
-- Made available under the KBase Open Source License
--
local M = {}
local docker = require('docker')
local json = require('json')
local p = require('pl.pretty')
local lfs = require('lfs')
-- This is the repository name, can be set by whoever instantiates a notelauncher
M.repository_image = 'kbase/narrative'
-- This is the tag to use, defaults to latest
M.repository_version = 'latest'
-- This is the port that should be exposed from the container, the service in the container
-- should have a listener on here configured
M.private_port = 8888
-- This is the path to the syslog Unix socket listener in the host environment
-- it is imported into the container via a Volumes argument
M.syslog_src = '/dev/log'
-- simple function to split string by whitespace and return table
local function split(self, s)
t = {}
for x in string.gmatch(s, "%S+") do
table.insert(t, x)
end
return t
end
--
-- Query the docker container for a list of containers and
-- return a list of the container ids that have listeners on
-- port 8888. Keyed on container name, value is IP:Port that can
-- be fed into an nginx proxy target
local function get_notebooks(self)
local ok, res = pcall(docker.client.containers, docker.client)
local portmap = {}
ngx.log(ngx.DEBUG, string.format("list containers result: %s", p.write(res.body)))
if ok then
for index, container in pairs(res.body) do
-- we only care about containers matching repository_image and listening on the proper port
first, last = string.find(container.Image, M.repository_image)
if first == 1 then
for i, v in pairs(container.Ports) do
if v.PrivatePort == M.private_port then
portmap[container.Id] = string.format("127.0.0.1:%u", v.PublicPort)
end
end
end
end
else
ngx.log(ngx.ERR, string.format("Failed to fetch list of containers: %s", p.write(res.body)))
end
return portmap
end
--
-- Actually launch a new docker container.
-- Return docker ID and table of info: { state, ip:port, session, last_time, last_ip }
--
local function launch_notebook(self)
-- don't wrap this in a pcall, if it fails let it propagate to
-- the caller
local conf = docker.config()
local bind_syslog = nil
conf.Image = string.format("%s:%s", M.repository_image, M.repository_version)
conf.PortSpecs = {tostring(M.private_port)}
ngx.log(ngx.INFO, string.format("Spinning up instance of %s on port %d", conf.Image, M.private_port))
-- we wrap the next call in pcall because we want to trap the case where we get an
-- error and try deleting the old container and creating a new one again
local ok, res = pcall(docker.client.create_container, docker.client, {payload = conf})
if not ok and res.response.status == "connection refused" then
ngx.log(ngx.ERR, "Unable to connect to docker API: "..p.write(res))
return nil, res
end
if not ok and res.response.status >= 409 and res.body.Id then
-- conflict, try to delete it and then create it again
local id = res.body.Id
ngx.log(ngx.ERR, string.format("conflicting notebook, removing container: %s", id))
ok, res = pcall(docker.client.remove_container, docker.client, {id = id})
ngx.log(ngx.ERR, string.format("response from remove_container: %s", p.write(res.response)))
-- ignore the response and retry the create, and if it still errors, let that propagate
ok, res = pcall(docker.client.create_container, docker.client, {payload = conf})
end
if ok then
assert(res.status == 201, "Failed to create container: "..json.encode(res.body))
local id = res.body.Id
if M.syslog_src then
-- Make sure it exists and is writeable
local stat = lfs.attributes(M.syslog_src)
if stat ~= nil and stat.mode == 'socket' then
bind_syslog = { string.format("%s:%s",M.syslog_src,"/dev/log") }
ngx.log(ngx.INFO, string.format("Binding %s in container %s", bind_syslog[1], id))
else
ngx.log(ngx.ERR, string.format("%s is not writeable, not mounting in container %s", M.syslog_src, id))
end
end
if bind_syslog ~= nil then
res = docker.client:start_container{id = id, payload = {PublishAllPorts = true, Binds = bind_syslog}}
else
res = docker.client:start_container{id = id, payload = {PublishAllPorts = true}}
end
assert(res.status == 204, "Failed to start container "..id.." : "..json.encode(res.body))
-- get back the container info to pull out the port mapping
res = docker.client:inspect_container{id=id}
assert(res.status == 200, "Could not inspect new container: "..id)
local ports = res.body.NetworkSettings.Ports
local ThePort = string.format("%d/tcp", M.private_port)
assert(ports[ThePort] ~= nil, string.format("Port binding for port %s not found!", ThePort))
local ip_port = string.format("%s:%d", "127.0.0.1", ports[ThePort][1].HostPort)
-- info = { state, ip:port, session, last_time, last_ip }
local info = {"queued", ip_port, "*", os.time(), "127.0.0.1"} -- default values except for ip_port
return id, info
else
ngx.log(ngx.ERR, "Failed to create container: "..p.write(res))
return nil, res
end
end
--
-- Kill and remove an existing docker container.
--
local function remove_notebook(id)
ngx.log(ngx.INFO, "Removing container: "..id)
local res = docker.client:stop_container{id = id}
--ngx.log(ngx.INFO,string.format("response from stop_container: %d : %s",res.status,res.body))
assert(res.status == 204, "Failed to stop container: "..json.encode(res.body))
res = docker.client:remove_container{id = id}
--ngx.log(ngx.INFO,string.format("response from remove_container: %d : %s",res.status,res.body))
assert(res.status == 204, "Failed to remove container "..id.." : "..json.encode(res.body))
return true
end
M.docker = docker
M.split = split
M.get_notebooks = get_notebooks
M.launch_notebook = launch_notebook
M.remove_notebook = remove_notebook
return M
|
fix function call
|
fix function call
|
Lua
|
mit
|
rsutormin/narrative,msneddon/narrative,nlharris/narrative,aekazakov/narrative,pranjan77/narrative,briehl/narrative,kbase/narrative,briehl/narrative,pranjan77/narrative,pranjan77/narrative,psnovichkov/narrative,briehl/narrative,jmchandonia/narrative,pranjan77/narrative,msneddon/narrative,scanon/narrative,psnovichkov/narrative,msneddon/narrative,rsutormin/narrative,scanon/narrative,aekazakov/narrative,jmchandonia/narrative,psnovichkov/narrative,mlhenderson/narrative,rsutormin/narrative,psnovichkov/narrative,scanon/narrative,kbase/narrative,mlhenderson/narrative,pranjan77/narrative,psnovichkov/narrative,aekazakov/narrative,pranjan77/narrative,kbase/narrative,nlharris/narrative,pranjan77/narrative,scanon/narrative,nlharris/narrative,rsutormin/narrative,mlhenderson/narrative,jmchandonia/narrative,nlharris/narrative,jmchandonia/narrative,kbase/narrative,nlharris/narrative,mlhenderson/narrative,rsutormin/narrative,kbase/narrative,msneddon/narrative,jmchandonia/narrative,msneddon/narrative,kbase/narrative,briehl/narrative,aekazakov/narrative,rsutormin/narrative,aekazakov/narrative,jmchandonia/narrative,scanon/narrative,msneddon/narrative,psnovichkov/narrative,aekazakov/narrative,msneddon/narrative,briehl/narrative,mlhenderson/narrative,scanon/narrative,nlharris/narrative,nlharris/narrative,mlhenderson/narrative,briehl/narrative,briehl/narrative,jmchandonia/narrative,psnovichkov/narrative
|
d98b855b4feea0c5640182de4ca2ebefb01aa068
|
lgi/override/GObject-Value.lua
|
lgi/override/GObject-Value.lua
|
------------------------------------------------------------------------------
--
-- LGI GObject.Value support.
--
-- Copyright (c) 2010, 2011 Pavel Holejsovsky
-- Licensed under the MIT license:
-- http://www.opensource.org/licenses/mit-license.php
--
------------------------------------------------------------------------------
local assert, pairs, select, type, tostring, error =
assert, pairs, select, type, tostring, error
local lgi = require 'lgi'
local core = require 'lgi.core'
local repo = core.repo
local gi = core.gi
local Type = repo.GObject.Type
-- Value is constructible from any kind of source Lua value, and the
-- type of the value can be hinted by type name.
local Value = repo.GObject.Value
local value_info = gi.GObject.Value
local log = lgi.log.domain('Lgi')
-- Workaround for incorrect annotations - g_value_set_xxx are missing
-- (allow-none) annotations in glib < 2.30.
for _, name in pairs { 'set_object', 'set_variant', 'set_string' } do
if not value_info.methods[name].args[1].optional then
log.message("g_value_%s() is missing (allow-none)", name)
local setter = Value[name]
Value._method[name] =
function(value, val)
if not val then Value.reset(value) else setter(value, val) end
end
end
end
-- Do not allow direct access to fields.
local value_field_gtype = Value._field.g_type
Value._field = nil
-- 'type' property controls gtype of the property.
Value._attribute = { gtype = {} }
function Value._attribute.gtype.get(value)
return core.record.field(value, value_field_gtype)
end
function Value._attribute.gtype.set(value, newtype)
local gtype = core.record.field(value, value_field_gtype)
if gtype then
if newtype then
-- Try converting old value to new one.
local dest = core.record.new(value_info)
Value.init(dest, newtype)
if not Value.transform(value, dest) then
error(("GObject.Value: cannot convert `%s' to `%s'"):format(
gtype, core.record.field(dest, value_field_gtype)))
end
Value.unset(value)
Value.init(value, newtype)
Value.copy(dest, value)
else
Value.unset(value)
end
elseif newtype then
-- No value was set and some is requested, so set it.
Value.init(value, newtype)
end
end
local value_marshallers = {}
for name, gtype in pairs(Type) do
local get = Value._method['get_' .. name:lower()]
local set = Value._method['set_' .. name:lower()]
if get and set then
value_marshallers[gtype] =
function(value, params, ...)
return (select('#', ...) > 0 and set or get)(value, ...)
end
end
end
-- Interface marshaller is the same as object marshallers.
value_marshallers[Type.INTERFACE] = value_marshallers[Type.OBJECT]
-- Override 'boxed' marshaller, default one marshalls to gpointer
-- instead of target boxed type.
value_marshallers[Type.BOXED] =
function(value, params, ...)
local gtype = core.record.field(value, value_field_gtype)
if select('#', ...) > 0 then
Value.set_boxed(value, core.record.query((...), 'addr', gtype))
else
return core.record.new(gi[core.gtype(gtype)], Value.get_boxed(value))
end
end
-- Create GStrv marshaller, implement it using typeinfo marshaller
-- with proper null-terminated-array-of-utf8 typeinfo 'stolen' from
-- g_shell_parse_argv().
value_marshallers[Type.STRV] = core.marshal.container(
gi.GLib.shell_parse_argv.args[3].typeinfo)
-- Finds marshaller closure which can marshal type described either by
-- gtype or typeinfo/transfer combo.
function Value._method.find_marshaller(gtype, typeinfo, transfer)
-- Check whether we can have marshaller for typeinfo, if the
-- typeinfo is container.
local marshaller
if typeinfo then
marshaller = core.marshal.container(typeinfo, transfer)
if marshaller then return marshaller end
end
-- Special case for non-gtype records.
if not gtype and typeinfo and typeinfo.tag == 'interface' then
-- Workaround for GoI < 1.30; it does not know that GLib structs are
-- boxed, so it does not assign them GType; moreover it incorrectly
-- considers GParamSpec as GType-less struct instead of the class.
local function marshal_record_no_gtype(value, params, ...)
-- Check actual gtype of the real value.
local gtype = core.record.field(value, value_field_gtype)
if Type.is_a(gtype, Type.PARAM) then
return value_marshallers[Type.PARAM](value, ...)
end
-- Find out proper getter/setter method for the value.
local get, set
if Type.is_a(gtype, Type.BOXED) then
get, set = Value.get_boxed, Value.set_boxed
else
get, set = Value.get_pointer, Value.set_pointer
end
-- Do GValue<->record transfer.
local record_info = typeinfo.interface
if select('#', ...) > 0 then
set(value, core.record.query((...), 'addr', record_info))
else
return core.record.new(record_info, get(value))
end
end
return marshal_record_no_gtype
end
local gt = gtype
if type(gt) == 'number' then gt = Type.name(gt) end
-- Special marshaller, allowing only 'nil'.
if not gt then return function() end end
-- Find marshaller according to gtype of the value.
while gt do
-- Check simple and/or fundamental marshallers.
marshaller = value_marshallers[gt] or core.marshal.fundamental(gt)
if marshaller then return marshaller end
gt = Type.parent(gt)
end
error(("GValue marshaller for `%s' not found"):format(tostring(gtype)))
end
-- Value 'value' property provides access to GValue's embedded data.
function Value._attribute:value(...)
local marshaller = Value._method.find_marshaller(
core.record.field(self, value_field_gtype))
return marshaller(self, nil, ...)
end
-- Implement custom 'constructor', taking optionally two values (type
-- and value). The reason why it is overriden is that the order of
-- initialization is important, and standard record intializer cannot
-- enforce the order.
function Value:_new(gtype, value)
local v = core.record.new(value_info)
if gtype then v.gtype = gtype end
if value then v.value = value end
return v
end
|
------------------------------------------------------------------------------
--
-- LGI GObject.Value support.
--
-- Copyright (c) 2010, 2011 Pavel Holejsovsky
-- Licensed under the MIT license:
-- http://www.opensource.org/licenses/mit-license.php
--
------------------------------------------------------------------------------
local assert, pairs, select, type, tostring, error =
assert, pairs, select, type, tostring, error
local lgi = require 'lgi'
local core = require 'lgi.core'
local repo = core.repo
local gi = core.gi
local Type = repo.GObject.Type
-- Value is constructible from any kind of source Lua value, and the
-- type of the value can be hinted by type name.
local Value = repo.GObject.Value
local value_info = gi.GObject.Value
local log = lgi.log.domain('Lgi')
-- Workaround for incorrect annotations - g_value_set_xxx are missing
-- (allow-none) annotations in glib < 2.30.
for _, name in pairs { 'set_object', 'set_variant', 'set_string' } do
if not value_info.methods[name].args[1].optional then
log.message("g_value_%s() is missing (allow-none)", name)
local setter = Value[name]
Value._method[name] =
function(value, val)
if not val then Value.reset(value) else setter(value, val) end
end
end
end
-- Do not allow direct access to fields.
local value_field_gtype = Value._field.g_type
Value._field = nil
-- 'type' property controls gtype of the property.
Value._attribute = { gtype = {} }
function Value._attribute.gtype.get(value)
return core.record.field(value, value_field_gtype)
end
function Value._attribute.gtype.set(value, newtype)
local gtype = core.record.field(value, value_field_gtype)
if gtype then
if newtype then
-- Try converting old value to new one.
local dest = core.record.new(value_info)
Value.init(dest, newtype)
if not Value.transform(value, dest) then
error(("GObject.Value: cannot convert `%s' to `%s'"):format(
gtype, core.record.field(dest, value_field_gtype)))
end
Value.unset(value)
Value.init(value, newtype)
Value.copy(dest, value)
else
Value.unset(value)
end
elseif newtype then
-- No value was set and some is requested, so set it.
Value.init(value, newtype)
end
end
local value_marshallers = {}
for name, gtype in pairs(Type) do
local get = Value._method['get_' .. name:lower()]
local set = Value._method['set_' .. name:lower()]
if get and set then
value_marshallers[gtype] =
function(value, params, ...)
return (select('#', ...) > 0 and set or get)(value, ...)
end
end
end
-- Interface marshaller is the same as object marshaller.
value_marshallers[Type.INTERFACE] = value_marshallers[Type.OBJECT]
-- Override 'boxed' marshaller, default one marshalls to gpointer
-- instead of target boxed type.
value_marshallers[Type.BOXED] =
function(value, params, ...)
local gtype = core.record.field(value, value_field_gtype)
if select('#', ...) > 0 then
Value.set_boxed(value, core.record.query((...), 'addr', gtype))
else
return core.record.new(gi[core.gtype(gtype)], Value.get_boxed(value))
end
end
-- Override marshallers for enums and bitmaps, marshal them as strings
-- or sets of string flags.
for name, gtype in pairs { ENUM = Type.ENUM, FLAGS = Type.FLAGS } do
local get = Value._method['get_' .. name:lower()]
local set = Value._method['set_' .. name:lower()]
value_marshallers[gtype] = function(value, params, ...)
local rtype
if select('#', ...) > 0 then
local param = ...
if type(param) ~= 'number' then
rtype = core.repotype(core.record.field(value, value_field_gtype))
param = rtype(param)
end
set(value, param)
else
rtype = core.repotype(core.record.field(value, value_field_gtype))
return rtype[get(value)]
end
end
end
-- Create GStrv marshaller, implement it using typeinfo marshaller
-- with proper null-terminated-array-of-utf8 typeinfo 'stolen' from
-- g_shell_parse_argv().
value_marshallers[Type.STRV] = core.marshal.container(
gi.GLib.shell_parse_argv.args[3].typeinfo)
-- Finds marshaller closure which can marshal type described either by
-- gtype or typeinfo/transfer combo.
function Value._method.find_marshaller(gtype, typeinfo, transfer)
-- Check whether we can have marshaller for typeinfo, if the
-- typeinfo is container.
local marshaller
if typeinfo then
marshaller = core.marshal.container(typeinfo, transfer)
if marshaller then return marshaller end
end
-- Special case for non-gtype records.
if not gtype and typeinfo and typeinfo.tag == 'interface' then
-- Workaround for GoI < 1.30; it does not know that GLib structs are
-- boxed, so it does not assign them GType; moreover it incorrectly
-- considers GParamSpec as GType-less struct instead of the class.
local function marshal_record_no_gtype(value, params, ...)
-- Check actual gtype of the real value.
local gtype = core.record.field(value, value_field_gtype)
if Type.is_a(gtype, Type.PARAM) then
return value_marshallers[Type.PARAM](value, ...)
end
-- Find out proper getter/setter method for the value.
local get, set
if Type.is_a(gtype, Type.BOXED) then
get, set = Value.get_boxed, Value.set_boxed
else
get, set = Value.get_pointer, Value.set_pointer
end
-- Do GValue<->record transfer.
local record_info = typeinfo.interface
if select('#', ...) > 0 then
set(value, core.record.query((...), 'addr', record_info))
else
return core.record.new(record_info, get(value))
end
end
return marshal_record_no_gtype
end
local gt = gtype
if type(gt) == 'number' then gt = Type.name(gt) end
-- Special marshaller, allowing only 'nil'.
if not gt then return function() end end
-- Find marshaller according to gtype of the value.
while gt do
-- Check simple and/or fundamental marshallers.
marshaller = value_marshallers[gt] or core.marshal.fundamental(gt)
if marshaller then return marshaller end
gt = Type.parent(gt)
end
error(("GValue marshaller for `%s' not found"):format(tostring(gtype)))
end
-- Value 'value' property provides access to GValue's embedded data.
function Value._attribute:value(...)
local marshaller = Value._method.find_marshaller(
core.record.field(self, value_field_gtype))
return marshaller(self, nil, ...)
end
-- Implement custom 'constructor', taking optionally two values (type
-- and value). The reason why it is overriden is that the order of
-- initialization is important, and standard record intializer cannot
-- enforce the order.
function Value:_new(gtype, value)
local v = core.record.new(value_info)
if gtype then v.gtype = gtype end
if value then v.value = value end
return v
end
|
Marshal properly enums and bitflags also from/to GValue
|
Marshal properly enums and bitflags also from/to GValue
Recent changes in enum/flags marshaling did not touch custom value
marshaling, so fix it now, add implementation translating numeric
values into natural enum/flags types.
|
Lua
|
mit
|
psychon/lgi,zevv/lgi,pavouk/lgi
|
d22424ff930a8e70ae03bfb93cc5df6e5f76bce1
|
modules/path/path.lua
|
modules/path/path.lua
|
-- NOTICE:
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-- ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
-- LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-- CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-- SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-- INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-- CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-- POSSIBILITY OF SUCH DAMAGE.
--
-- read COPYRIGHT.md for more informations.
local path = {}
--current = fbmakelib.getcwd()
local curdir = "."
local pardir = ".."
local sep = "/"
local isWindows
local impl
do
if (jit.os=="Windows") then
isWindows = true
impl = require("path.impl_win")
else
impl = require("path.impl_posix")
end
end
local current = impl.current
path.current = current
if (isWindows) then
sep = "\\"
function path.isabs(str)
return str:find("%a%:") == 1 or str:find("[%/%\\]") == 1
end
function path.splitdrive(str)
local p1, p2 = str:match("(%a%:)(.+)")
if (p1) then
return p1, p2
end
return '', str
end
assert(path.isabs(current()))
assert(path.isabs("c:\\index.html"))
assert(path.isabs("h:"))
assert(path.isabs("/test/"))
assert(not path.isabs("test"))
else
function path.splitdrive(str)
return '', str
end
function path.isabs(str)
return str:find("%/") == 1
end
assert(path.isabs(current))
assert(path.isabs("/usr/home"))
assert(not path.isabs(".src"))
assert(not path.isabs("ppp/asdf/asdf"))
end
path.sep = sep
local isabs = path.isabs
local splitdrive = path.splitdrive
function path.join(...)
local t={...}
local p="."
for i,v in ipairs(t) do
if (isabs(v)) then
p = v
else
p = p .. sep .. v
end
end
return p
end
local join = path.join
function path.normalize(path, sep)
local orgpath = path
if (path == "") then
return '.'
end
if (isWindows and path:find("%\\%\\[^%/%\\]+%\\") ==1) then
return path
end
local prefix = ""
local p1, p2 = splitdrive(path)
if (p1) then
prefix = p1
local p3, p4 = p2:match("([%/%\\]+)(.+)")
prefix = p1..p3
path = p4
else
prefix, path = path:match("([%/%\\]+)(.+)")
end
local comps = {}
for k in path:gmatch("[^%/%\\]+") do
table.insert(comps, k)
end
local outt = {}
local j = 0
for i=1, #comps do
if (comps[i] =='.' or comps[i] == '') then
elseif (comps[i] == '..') then
if (j > 0 and outt[j] ~= "..") then
outt[j] = nil
j = j-1
elseif (j == 0 and prefix~= "") then
else
j = j+1
outt[j] = comps[i]
end
else
j = j+1
outt[j] = comps[i]
end
end
if (prefix=='' and j == 0) then
return '.'
end
if (isWindows) then
sep = sep or '\\'
else
sep = sep or '/'
end
return prefix .. table.concat(outt, sep)
end
local normalize = path.normalize
function path.split(p)
local p1, p2 = p:match("(.+[%/%\\])[%/%\\]*([^%/%\\]+)")
if p1 then
return p1, p2
end
return "", p
end
local split = path.split
function path.splitext(p)
local p1, p2 = p:match("(.+)(%.[^.]*)")
if (p1) then
if (p2:match("[%/%\\]")) then
return p, ''
end
return p1, p2
end
return p, ''
end
function path.basename(p)
local b, t = split(p)
return t
end
function path.dirname(p)
local b, t = split(p)
return b
end
function path.normjoin(...)
return normalize(join(...))
end
function path.abspath(path)
return normalize(join(current, path))
end
local function _abspath_split(path)
path = abspath(path)
local prefix, rest = splitdrive(path)
local restsplit = {}
--rest:split("[%/%\\]", false, true)
for k in rest:gmatch("[%/%\\]") do
table.insert(restsplit, k)
end
return prefix, restsplit
end
function path.relpath(path, start)
start = start or current
local start_prefix, start_list = _abspath_split(start)
local path_prefix, path_list = _abspath_split(path)
if (start_prefix:lower() ~= path_prefix:lower()) then
return path
end
i = 1
while (i<=#start_list and i<=#path_list and start_list[i] == path_list[i]) do
i = i + 1
end
local rel_list = {}
for j = i, #start_list do
table.insert(rel_list, pardir)
end
for j = i, #path_list do
table.insert(rel_list, path_list[j])
end
if (#path_list == 0) then
return curdir
end
return table.concat(rel_list, sep)
end
path.stat = impl.stat
path.isdir = impl.isdir
path.exists = impl.exists
path.listAll = impl.listAll
path.listFiles = impl.listFiles
path.listSubdirs = impl.listSubdirs
--[[
function path.modifiedTime(path)
return fbmakelib.modifiedTime(path)
end
function createdTime(path)
return fbmakelib.createdTime(path)
end
function mkdir(path, mode) --mode = 777
mode = mode or 0x1FF
local head, tail = split(path)
if (tail == "") then
head, tail = split(head)
end
if (head~="" and tail~="" and not exist(head)) then
mkdir(head, mode)
end
if (not exist(path)) then
fbmakelib.mkdir(path, mode)
end
end
function rmdir(path, func)
for i,v in ipairs(listfile(path)) do
local p = normjoin(path, v)
if func then
func(p)
end
os.remove(p)
end
for i,v in ipairs(listsubdir(path)) do
rmdir(join(path, v))
end
local p = normpath(path)
if func then
func(p)
end
if (isWindows) then
os.execute("rmdir ".. p)
else
os.remove(p)
end
end
]]
return path
|
-- NOTICE:
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-- ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
-- LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-- CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-- SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-- INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-- CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-- POSSIBILITY OF SUCH DAMAGE.
--
-- read COPYRIGHT.md for more informations.
local path = {}
--current = fbmakelib.getcwd()
local curdir = "."
local pardir = ".."
local sep = "/"
local isWindows
local impl
do
if (jit.os=="Windows") then
isWindows = true
impl = require("path.impl_win")
else
impl = require("path.impl_posix")
end
end
local current = impl.current
path.current = current
if (isWindows) then
sep = "\\"
function path.isabs(str)
return str:find("%a%:") == 1 or str:find("[%/%\\]") == 1
end
function path.splitdrive(str)
local p0, p1, p2 = str:match("()(%a%:)(.+)")
if (p0==1) then
return p1, p2
end
return '', str
end
assert(path.isabs(current()))
assert(path.isabs("c:\\index.html"))
assert(path.isabs("h:"))
assert(path.isabs("/test/"))
assert(not path.isabs("test"))
else
function path.splitdrive(str)
return '', str
end
function path.isabs(str)
return str:find("%/") == 1
end
assert(path.isabs(current))
assert(path.isabs("/usr/home"))
assert(not path.isabs(".src"))
assert(not path.isabs("ppp/asdf/asdf"))
end
path.sep = sep
local isabs = path.isabs
local splitdrive = path.splitdrive
function path.join(...)
local t={...}
local p="."
for i,v in ipairs(t) do
if (isabs(v)) then
p = v
else
p = p .. sep .. v
end
end
return p
end
local join = path.join
function path.normalize(path, sep)
local orgpath = path
if (path == "") then
return '.'
end
if (isWindows and path:find("%\\%\\[^%/%\\]+%\\") ==1) then
return path
end
local prefix = ""
local p1, p2 = splitdrive(path)
if (p1) then
prefix = p1
local p0, p3, p4 = p2:match("()([%/%\\]+)(.+)")
if (p0 == 1) then
prefix = p1..p3
path = p4
else
prefix = p1
path = p2
end
else
local p0, p3, p4 = path:match("()([%/%\\]+)(.+)")
if (p0 == 1) then
prefix = p3
path = p4
else
prefix = ""
path = path
end
end
local comps = {}
for k in path:gmatch("[^%/%\\]+") do
table.insert(comps, k)
end
local outt = {}
local j = 0
for i=1, #comps do
if (comps[i] =='.' or comps[i] == '') then
elseif (comps[i] == '..') then
if (j > 0 and outt[j] ~= "..") then
outt[j] = nil
j = j-1
elseif (j == 0 and prefix~= "") then
else
j = j+1
outt[j] = comps[i]
end
else
j = j+1
outt[j] = comps[i]
end
end
if (prefix=='' and j == 0) then
return '.'
end
if (isWindows) then
sep = sep or '\\'
else
sep = sep or '/'
end
return prefix .. table.concat(outt, sep)
end
local normalize = path.normalize
function path.split(p)
local p1, p2 = p:match("(.+[%/%\\])[%/%\\]*([^%/%\\]+)")
if p1 then
return p1, p2
end
return "", p
end
local split = path.split
function path.splitext(p)
local p1, p2 = p:match("(.+)(%.[^.]*)")
if (p1) then
if (p2:match("[%/%\\]")) then
return p, ''
end
return p1, p2
end
return p, ''
end
function path.basename(p)
local b, t = split(p)
return t
end
function path.dirname(p)
local b, t = split(p)
return b
end
function path.normjoin(...)
return normalize(join(...))
end
function path.abspath(path)
return normalize(join(current, path))
end
local function _abspath_split(path)
path = abspath(path)
local prefix, rest = splitdrive(path)
local restsplit = {}
--rest:split("[%/%\\]", false, true)
for k in rest:gmatch("[%/%\\]") do
table.insert(restsplit, k)
end
return prefix, restsplit
end
function path.relpath(path, start)
start = start or current
local start_prefix, start_list = _abspath_split(start)
local path_prefix, path_list = _abspath_split(path)
if (start_prefix:lower() ~= path_prefix:lower()) then
return path
end
i = 1
while (i<=#start_list and i<=#path_list and start_list[i] == path_list[i]) do
i = i + 1
end
local rel_list = {}
for j = i, #start_list do
table.insert(rel_list, pardir)
end
for j = i, #path_list do
table.insert(rel_list, path_list[j])
end
if (#path_list == 0) then
return curdir
end
return table.concat(rel_list, sep)
end
path.stat = impl.stat
path.isdir = impl.isdir
path.exists = impl.exists
path.listAll = impl.listAll
path.listFiles = impl.listFiles
path.listSubdirs = impl.listSubdirs
--[[
function path.modifiedTime(path)
return fbmakelib.modifiedTime(path)
end
function createdTime(path)
return fbmakelib.createdTime(path)
end
function mkdir(path, mode) --mode = 777
mode = mode or 0x1FF
local head, tail = split(path)
if (tail == "") then
head, tail = split(head)
end
if (head~="" and tail~="" and not exist(head)) then
mkdir(head, mode)
end
if (not exist(path)) then
fbmakelib.mkdir(path, mode)
end
end
function rmdir(path, func)
for i,v in ipairs(listfile(path)) do
local p = normjoin(path, v)
if func then
func(p)
end
os.remove(p)
end
for i,v in ipairs(listsubdir(path)) do
rmdir(join(path, v))
end
local p = normpath(path)
if func then
func(p)
end
if (isWindows) then
os.execute("rmdir ".. p)
else
os.remove(p)
end
end
]]
return path
|
bugfix in path.normalize
|
bugfix in path.normalize
|
Lua
|
bsd-3-clause
|
tdzl2003/luaqt,tdzl2003/luaqt,tdzl2003/luaqt
|
96e91bb0483948a698b1ebd224bfdf8971f8a18d
|
face-detector/run.lua
|
face-detector/run.lua
|
#!/usr/bin/env qlua
------------------------------------------------------------
-- a face detector, based on a simple convolutional network,
-- trained end-to-end for that task.
--
-- Clement Farabet
--
require 'xlua'
require 'torch'
require 'qt'
require 'qtwidget'
require 'qtuiloader'
xrequire('inline',true)
xrequire('camera',true)
xrequire('nnx',true)
-- parse args
op = xlua.OptionParser('%prog [options]')
op:option{'-c', '--camera', action='store', dest='camidx',
help='if source=camera, you can specify the camera index: /dev/videoIDX',
default=0}
op:option{'-n', '--network', action='store', dest='network',
help='path to existing [trained] network',
default='face.net'}
opt,args = op:parse()
-- blob parser
parse = inline.load [[
// get args
const void* id = luaT_checktypename2id(L, "torch.DoubleTensor");
THDoubleTensor *tensor = luaT_checkudata(L, 1, id);
double threshold = lua_tonumber(L, 2);
int table_blobs = 3;
int idx = lua_objlen(L, 3) + 1;
double scale = lua_tonumber(L, 4);
// loop over pixels
int x,y;
for (y=0; y<tensor->size[0]; y++) {
for (x=0; x<tensor->size[1]; x++) {
double val = THDoubleTensor_get2d(tensor, y, x);
if (val > threshold) {
// entry = {}
lua_newtable(L);
int entry = lua_gettop(L);
// entry[1] = x
lua_pushnumber(L, x);
lua_rawseti(L, entry, 1);
// entry[2] = y
lua_pushnumber(L, y);
lua_rawseti(L, entry, 2);
// entry[3] = scale
lua_pushnumber(L, scale);
lua_rawseti(L, entry, 3);
// blobs[idx] = entry; idx = idx + 1
lua_rawseti(L, table_blobs, idx++);
}
}
}
return 0;
]]
-- load pre-trained network from disk
network = nn.Sequential()
network = torch.load(opt.network)
network_fov = 32
network_sub = 4
-- setup camera
camera = image.Camera{}
-- process input at multiple scales
scales = {0.3, 0.24, 0.192, 0.15, 0.12, 0.1}
-- use a pyramid packer/unpacker
require 'PyramidPacker'
require 'PyramidUnPacker'
packer = nn.PyramidPacker(network, scales)
unpacker = nn.PyramidUnPacker(network)
-- setup GUI (external UI file)
if not win or not widget then
widget = qtuiloader.load('g.ui')
win = qt.QtLuaPainter(widget.frame)
end
-- a gaussian for smoothing the distributions
gaussian = image.gaussian(3,0.15)
-- process function
function process()
-- (1) grab frame
frame = camera:forward()
-- (2) transform it into Y space
frameY = image.rgb2y(frame)
-- (3) create multiscale pyramid
pyramid, coordinates = packer:forward(frameY)
-- (4) run pre-trained network on it
multiscale = network:forward(pyramid)
-- (5) unpack pyramid
distributions = unpacker:forward(multiscale, coordinates)
-- (6) parse distributions to extract blob centroids
threshold = widget.verticalSlider.value/100
rawresults = {}
for i,distribution in ipairs(distributions) do
local smoothed = image.convolve(distribution[1]:add(1):mul(0.5), gaussian)
parse(smoothed, threshold, rawresults, scales[i])
end
-- (7) clean up results
detections = {}
for i,res in ipairs(rawresults) do
local scale = res[3]
local x = res[1]*network_sub/scale
local y = res[2]*network_sub/scale
local w = network_fov/scale
local h = network_fov/scale
detections[i] = {x=x, y=y, w=w, h=h}
end
end
-- display function
function display()
win:gbegin()
win:showpage()
-- (1) display input image + pyramid
image.display{image=frame, win=win}
-- (2) overlay bounding boxes for each detection
for i,detect in ipairs(detections) do
win:setcolor(1,0,0)
win:rectangle(detect.x, detect.y, detect.w, detect.h)
win:stroke()
win:setfont(qt.QFont{serif=false,italic=false,size=16})
win:moveto(detect.x, detect.y-1)
win:show('face')
end
-- (3) display distributions
local prevx = 0
for i,distribution in ipairs(distributions) do
local prev = distributions[i-1]
if prev then prevx = prevx + prev:size(3) end
image.display{image=distribution[1], win=win, x=prevx, min=0, max=1}
end
win:gend()
end
-- setup gui
timer = qt.QTimer()
timer.interval = 10
timer.singleShot = true
qt.connect(timer,
'timeout()',
function()
process()
display()
timer:start()
end)
widget.windowTitle = 'Face Detector'
widget:show()
timer:start()
|
#!/usr/bin/env qlua
------------------------------------------------------------
-- a face detector, based on a simple convolutional network,
-- trained end-to-end for that task.
--
-- Clement Farabet
--
require 'xlua'
require 'torch'
require 'qt'
require 'qtwidget'
require 'qtuiloader'
xrequire('inline',true)
xrequire('camera',true)
xrequire('nnx',true)
-- parse args
op = xlua.OptionParser('%prog [options]')
op:option{'-c', '--camera', action='store', dest='camidx',
help='if source=camera, you can specify the camera index: /dev/videoIDX',
default=0}
op:option{'-n', '--network', action='store', dest='network',
help='path to existing [trained] network',
default='face.net'}
opt,args = op:parse()
-- blob parser
parse = inline.load [[
// get args
const void* id = luaT_checktypename2id(L, "torch.DoubleTensor");
THDoubleTensor *tensor = luaT_checkudata(L, 1, id);
double threshold = lua_tonumber(L, 2);
int table_blobs = 3;
int idx = lua_objlen(L, 3) + 1;
double scale = lua_tonumber(L, 4);
// loop over pixels
int x,y;
for (y=0; y<tensor->size[0]; y++) {
for (x=0; x<tensor->size[1]; x++) {
double val = THDoubleTensor_get2d(tensor, y, x);
if (val > threshold) {
// entry = {}
lua_newtable(L);
int entry = lua_gettop(L);
// entry[1] = x
lua_pushnumber(L, x);
lua_rawseti(L, entry, 1);
// entry[2] = y
lua_pushnumber(L, y);
lua_rawseti(L, entry, 2);
// entry[3] = scale
lua_pushnumber(L, scale);
lua_rawseti(L, entry, 3);
// blobs[idx] = entry; idx = idx + 1
lua_rawseti(L, table_blobs, idx++);
}
}
}
return 0;
]]
-- load pre-trained network from disk
network = nn.Sequential()
network = torch.load(opt.network)
network_fov = 32
network_sub = 4
-- setup camera
camera = image.Camera{}
-- process input at multiple scales
scales = {0.3, 0.24, 0.192, 0.15, 0.12, 0.1}
-- use a pyramid packer/unpacker
require 'PyramidPacker'
require 'PyramidUnPacker'
packer = nn.PyramidPacker(network, scales)
unpacker = nn.PyramidUnPacker(network)
-- setup GUI (external UI file)
if not win or not widget then
widget = qtuiloader.load('g.ui')
win = qt.QtLuaPainter(widget.frame)
end
-- a gaussian for smoothing the distributions
gaussian = image.gaussian(3,0.15)
-- profiler
p = xlua.Profiler()
-- process function
function process()
-- (1) grab frame
frame = camera:forward()
-- (2) transform it into Y space
frameY = image.rgb2y(frame)
-- (3) create multiscale pyramid
pyramid, coordinates = packer:forward(frameY)
-- (4) run pre-trained network on it
multiscale = network:forward(pyramid)
-- (5) unpack pyramid
distributions = unpacker:forward(multiscale, coordinates)
-- (6) parse distributions to extract blob centroids
threshold = widget.verticalSlider.value/100
rawresults = {}
for i,distribution in ipairs(distributions) do
local smoothed = image.convolve(distribution[1]:add(1):mul(0.5), gaussian)
parse(smoothed, threshold, rawresults, scales[i])
end
-- (7) clean up results
detections = {}
for i,res in ipairs(rawresults) do
local scale = res[3]
local x = res[1]*network_sub/scale
local y = res[2]*network_sub/scale
local w = network_fov/scale
local h = network_fov/scale
detections[i] = {x=x, y=y, w=w, h=h}
end
end
-- display function
function display()
win:gbegin()
win:showpage()
-- (1) display input image + pyramid
image.display{image=frame, win=win}
-- (2) overlay bounding boxes for each detection
for i,detect in ipairs(detections) do
win:setcolor(1,0,0)
win:rectangle(detect.x, detect.y, detect.w, detect.h)
win:stroke()
win:setfont(qt.QFont{serif=false,italic=false,size=16})
win:moveto(detect.x, detect.y-1)
win:show('face')
end
-- (3) display distributions
local prevx = 0
for i,distribution in ipairs(distributions) do
local prev = distributions[i-1]
if prev then prevx = prevx + prev:size(3) end
image.display{image=distribution[1], win=win, x=prevx, min=0, max=1}
end
win:gend()
end
-- setup gui
timer = qt.QTimer()
timer.interval = 10
timer.singleShot = true
qt.connect(timer,
'timeout()',
function()
p:start('prediction')
process()
p:lap('prediction')
p:start('display')
display()
p:lap('display')
require 'openmp'
timer:start()
p:printAll()
end)
widget.windowTitle = 'Face Detector'
widget:show()
timer:start()
|
fixed openmp?
|
fixed openmp?
|
Lua
|
bsd-3-clause
|
e-lab/torch7-demos,e-lab/torch7-demos
|
90385c968247f64e766df4093dd29c54ec859a08
|
extensions/hid/init.lua
|
extensions/hid/init.lua
|
--- === hs.hid ===
---
--- HID interface for Hammerspoon, controls and queries caps lock state
---
--- Portions sourced from (https://discussions.apple.com/thread/7094207).
local module = require("hs.hid.internal")
-- private variables and methods -----------------------------------------
-- Public interface ------------------------------------------------------
module.capslock = {}
--- hs.hid.capslock.get() -> bool
--- Function
--- Checks the state of the caps lock via HID
---
--- Returns:
--- * true if on, false if off
module.capslock.get = function()
return module._capslock_query()
end
--- hs.hid.capslock.toggle() -> bool
--- Function
--- Toggles the state of caps lock via HID
---
--- Returns:
--- * true if on, false if off
module.capslock.toggle = function()
return module._capslock_toggle()
end
--- hs.hid.capslock.set(state) -> bool
--- Function
--- Assigns capslock to the desired state
---
--- Parameters:
--- * state - A boolean indicating desired state
---
--- Returns:
--- * true if on, false if off
module.capslock.set = function(state)
if state then
return module._capslock_on()
else
return module._capslock_off()
end
end
module.led = {}
--- hs.hid.led.set(name, state) -> bool
--- Function
--- Assigns HID LED to the desired state
--- Note that this function controls the LED state only,
--- to modify capslock state, use hs.hid.capslock.set
---
--- Parameters:
--- * name - LED name: "caps", "scroll" or "num"
--- * state - A boolean indicating desired state
---
--- Returns:
--- * true if success, false if error
module.led.set = function(name, state)
return module._led_set(name, state)
end
-- Return Module Object --------------------------------------------------
return module
|
--- === hs.hid ===
---
--- HID interface for Hammerspoon, controls and queries caps lock state
---
--- Portions sourced from (https://discussions.apple.com/thread/7094207).
local module = require("hs.hid.internal")
-- private variables and methods -----------------------------------------
-- Public interface ------------------------------------------------------
module.capslock = {}
--- hs.hid.capslock.get() -> bool
--- Function
--- Checks the state of the caps lock via HID
---
--- Returns:
--- * true if on, false if off
module.capslock.get = function()
return module._capslock_query()
end
--- hs.hid.capslock.toggle() -> bool
--- Function
--- Toggles the state of caps lock via HID
---
--- Returns:
--- * true if on, false if off
module.capslock.toggle = function()
return module._capslock_toggle()
end
--- hs.hid.capslock.set(state) -> bool
--- Function
--- Assigns capslock to the desired state
---
--- Parameters:
--- * state - A boolean indicating desired state
---
--- Returns:
--- * true if on, false if off
module.capslock.set = function(state)
if state then
return module._capslock_on()
else
return module._capslock_off()
end
end
--- === hs.hid.led ===
---
--- HID LED interface for Hammerspoon, controls the state of keyboard LEDs
module.led = {}
--- hs.hid.led.set(name, state) -> bool
--- Function
--- Assigns HID LED to the desired state
--- Note that this function controls the LED state only,
--- to modify capslock state, use hs.hid.capslock.set
---
--- Parameters:
--- * name - LED name: "caps", "scroll" or "num"
--- * state - A boolean indicating desired state
---
--- Returns:
--- * true if success, false if error
module.led.set = function(name, state)
return module._led_set(name, state)
end
-- Return Module Object --------------------------------------------------
return module
|
Fix docs for hs.hid.led
|
Fix docs for hs.hid.led
|
Lua
|
mit
|
CommandPost/CommandPost-App,Hammerspoon/hammerspoon,CommandPost/CommandPost-App,CommandPost/CommandPost-App,latenitefilms/hammerspoon,CommandPost/CommandPost-App,asmagill/hammerspoon,Hammerspoon/hammerspoon,latenitefilms/hammerspoon,cmsj/hammerspoon,asmagill/hammerspoon,Habbie/hammerspoon,cmsj/hammerspoon,Hammerspoon/hammerspoon,cmsj/hammerspoon,Hammerspoon/hammerspoon,latenitefilms/hammerspoon,Habbie/hammerspoon,Habbie/hammerspoon,CommandPost/CommandPost-App,CommandPost/CommandPost-App,latenitefilms/hammerspoon,asmagill/hammerspoon,asmagill/hammerspoon,cmsj/hammerspoon,cmsj/hammerspoon,asmagill/hammerspoon,Hammerspoon/hammerspoon,Habbie/hammerspoon,latenitefilms/hammerspoon,Habbie/hammerspoon,cmsj/hammerspoon,latenitefilms/hammerspoon,Hammerspoon/hammerspoon,Habbie/hammerspoon,asmagill/hammerspoon
|
2eecf3b9e14eeefdc299aea0b4de6e5cc0486cf2
|
openLuup/userdata.lua
|
openLuup/userdata.lua
|
local version = "openLuup.user_data 2016.04.28 @akbooer"
-- user_data
-- saving and loading, plus utility functions used by HTTP requests id=user_data, etc.
local json = require "openLuup.json"
--
-- Here a complete list of top-level (scalar) attributes taken from an actual Vera user_data2 request
-- the commented out items are either vital tables, or useless parameters.
local attributes = {
-- AltEventServer = "127.0.0.1",
-- AutomationDevices = 0,
BuildVersion = "*1.7.0*",
City_description = "Greenwich",
Country_description = "UNITED KINGDOM",
-- DataVersion = 563952001,
-- DataVersion_Static = "32",
-- DeviceSync = "1426564006",
Device_Num_Next = "1",
-- ExtraLuaFiles = {},
-- InstalledPlugins = {},
-- InstalledPlugins2 = {},
KwhPrice = "0.15",
LoadTime = os.time(),
Mode = "1", -- House Mode
ModeSetting = "1:DC*;2:DC*;3:DC*;4:DC*", -- see: http://wiki.micasaverde.com/index.php/House_Modes
PK_AccessPoint = "88800000", -- TODO: pick up machine serial number from EPROM or such like,
-- PluginSettings = {},
-- PluginsSynced = "0",
-- RA_Server = "vera-us-oem-relay41.mios.com",
-- RA_Server_Back = "vera-us-oem-relay11.mios.com",
Region_description = "England",
-- ServerBackup = "1",
-- Server_Device = "vera-us-oem-device12.mios.com",
-- Server_Device_Alt = "vera-us-oem-device11.mios.com",
-- SetupDevices = {},
-- ShowIndividualJobs = 0,
StartupCode = "",
-- SvnVersion = "*13875*",
TemperatureFormat = "C",
-- UnassignedDevices = 0,
-- Using_2G = 0,
-- breach_delay = "30",
-- category_filter = {},
currency = "£",
date_format = "dd/mm/yy",
-- device_sync = "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,18,19,20,21",
-- devices = {},
-- energy_dev_log = "41,",
-- firmware_version = "1",
gmt_offset = "0",
-- ip_requests = {},
-- ir = 0,
latitude = "51.48",
-- local_udn = "uuid:4d494342-5342-5645-0000-000002b03069",
longitude = "0.0",
mode_change_delay = "30",
model = "Not a Vera",
-- net_pnp = "0",
-- overview_tabs = {},
-- rooms = {},
-- scenes = {},
-- sections = {},
-- setup_wizard_finished = "1",
-- shouldHelpOverlayBeHidden = true,
-- skin = "mios",
-- static_data = {},
-- sync_kit = "0000-00-00 00:00:00",
timeFormat = "24hr",
timezone = "0",
-- users = {},
-- weatherSettings = {
-- weatherCountry = "UNITED KINGDOM",
-- weatherCity = "Oxford England",
-- tempFormat = "C" },
-- zwave_heal = "1426331082",
-- openLuup specials
GitHubVersion = "unknown",
GitHubLatest = "unknown",
ShutdownCode = '',
}
local function parse_user_data (user_data_json)
return json.decode (user_data_json)
end
local function load_user_data (filename)
local user_data, message, err
local f = io.open (filename or "user_data.json", 'r')
if f then
local user_data_json = f:read "*a"
f:close ()
user_data, err = parse_user_data (user_data_json)
if not user_data then
message = "error in user_data: " .. err
end
else
user_data = {}
message = "cannot open user_data file" -- not an error, _per se_, there may just be no file
end
return user_data, message
end
--
-- user_data devices table
local function devices_table (device_list)
local info = {}
local serviceNo = 0
for _,d in pairs (device_list) do
local states = {}
for i,item in ipairs(d.variables) do
states[i] = {
id = item.id,
service = item.srv,
variable = item.name,
value = item.value,
}
end
local curls
if d.serviceList then -- add the ControlURLs
curls = {}
for _,x in ipairs (d.serviceList) do
serviceNo = serviceNo + 1
curls["service_" .. serviceNo] = {
service = x.serviceId,
serviceType = x.serviceType,
ControlURL = "upnp/control/dev_" .. serviceNo,
EventURL = "/upnp/event/dev_" .. serviceNo,
}
end
end
local tbl = {
ControlURLs = curls,
states = states,
}
for a,b in pairs (d.attributes) do tbl[a] = b end
info[#info+1] = tbl
end
return info
end
-- save ()
-- top-level attributes and key tables: devices, rooms, scenes
-- TODO: [, sections, users, weatherSettings]
local function save_user_data (luup, filename)
local result, message
local f = io.open (filename or "user_data.json", 'w')
if not f then
message = "error writing user_data"
else
local data = {rooms = {}, scenes = {}}
-- scalar attributes
for a,b in pairs (attributes) do
if type(b) ~= "table" then data[a] = b end
end
-- devices
data.devices = devices_table (luup.devices or {})
-- plugins
data.InstalledPlugins2 = {} -- TODO: replace with plugins.installed()
-- rooms
local rooms = data.rooms
for i, name in pairs (luup.rooms or {}) do
rooms[#rooms+1] = {id = i, name = name}
end
-- scenes
local scenes = data.scenes
for _, s in pairs (luup.scenes or {}) do
scenes[#scenes+1] = s: user_table ()
end
--
local j, msg = json.encode (data)
if j then
f:write (j)
f:write '\n'
result = true
else
message = "syntax error in user_data: " .. (msg or '?')
end
f:close ()
end
return result, message
end
return {
attributes = attributes,
devices_table = devices_table,
-- load = load_user_data,
parse = parse_user_data,
save = save_user_data,
version = version,
}
|
ABOUT = {
NAME = "openLuup.userdata",
VERSION = "2016.04.30",
DESCRIPTION = "user_data saving and loading, plus utility functions used by HTTP requests",
AUTHOR = "@akbooer",
DOCUMENTATION = "https://github.com/akbooer/openLuup/tree/master/Documentation",
}
-- user_data
-- saving and loading, plus utility functions used by HTTP requests id=user_data, etc.
local json = require "openLuup.json"
--
-- Here a complete list of top-level (scalar) attributes taken from an actual Vera user_data2 request
-- the commented out items are either vital tables, or useless parameters.
local attributes = {
-- AltEventServer = "127.0.0.1",
-- AutomationDevices = 0,
BuildVersion = "*1.7.0*",
City_description = "Greenwich",
Country_description = "UNITED KINGDOM",
-- DataVersion = 563952001,
-- DataVersion_Static = "32",
-- DeviceSync = "1426564006",
Device_Num_Next = "1",
-- ExtraLuaFiles = {},
-- InstalledPlugins = {},
-- InstalledPlugins2 = {},
KwhPrice = "0.15",
LoadTime = os.time(),
Mode = "1", -- House Mode
ModeSetting = "1:DC*;2:DC*;3:DC*;4:DC*", -- see: http://wiki.micasaverde.com/index.php/House_Modes
PK_AccessPoint = "88800000", -- TODO: pick up machine serial number from EPROM or such like,
-- PluginSettings = {},
-- PluginsSynced = "0",
-- RA_Server = "vera-us-oem-relay41.mios.com",
-- RA_Server_Back = "vera-us-oem-relay11.mios.com",
Region_description = "England",
-- ServerBackup = "1",
-- Server_Device = "vera-us-oem-device12.mios.com",
-- Server_Device_Alt = "vera-us-oem-device11.mios.com",
-- SetupDevices = {},
-- ShowIndividualJobs = 0,
StartupCode = "",
-- SvnVersion = "*13875*",
TemperatureFormat = "C",
-- UnassignedDevices = 0,
-- Using_2G = 0,
-- breach_delay = "30",
-- category_filter = {},
currency = "£",
date_format = "dd/mm/yy",
-- device_sync = "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,18,19,20,21",
-- devices = {},
-- energy_dev_log = "41,",
-- firmware_version = "1",
gmt_offset = "0",
-- ip_requests = {},
-- ir = 0,
latitude = "51.48",
-- local_udn = "uuid:4d494342-5342-5645-0000-000002b03069",
longitude = "0.0",
mode_change_delay = "30",
model = "Not a Vera",
-- net_pnp = "0",
-- overview_tabs = {},
-- rooms = {},
-- scenes = {},
-- sections = {},
-- setup_wizard_finished = "1",
-- shouldHelpOverlayBeHidden = true,
-- skin = "mios",
-- static_data = {},
-- sync_kit = "0000-00-00 00:00:00",
timeFormat = "24hr",
timezone = "0",
-- users = {},
-- weatherSettings = {
-- weatherCountry = "UNITED KINGDOM",
-- weatherCity = "Oxford England",
-- tempFormat = "C" },
-- zwave_heal = "1426331082",
-- openLuup specials
GitHubVersion = "unknown",
GitHubLatest = "unknown",
ShutdownCode = '',
}
local function parse_user_data (user_data_json)
return json.decode (user_data_json)
end
local function load_user_data (filename)
local user_data, message, err
local f = io.open (filename or "user_data.json", 'r')
if f then
local user_data_json = f:read "*a"
f:close ()
user_data, err = parse_user_data (user_data_json)
if not user_data then
message = "error in user_data: " .. err
end
else
user_data = {}
message = "cannot open user_data file" -- not an error, _per se_, there may just be no file
end
return user_data, message
end
--
-- user_data devices table
local function devices_table (device_list)
local info = {}
local serviceNo = 0
for _,d in pairs (device_list) do
local states = {}
for i,item in ipairs(d.variables) do
states[i] = {
id = item.id,
service = item.srv,
variable = item.name,
value = item.value,
}
end
local curls
if d.serviceList then -- add the ControlURLs
curls = {}
for _,x in ipairs (d.serviceList) do
serviceNo = serviceNo + 1
curls["service_" .. serviceNo] = {
service = x.serviceId,
serviceType = x.serviceType,
ControlURL = "upnp/control/dev_" .. serviceNo,
EventURL = "/upnp/event/dev_" .. serviceNo,
}
end
end
local status = d:status_get() or -1 -- 2016.04.29
-- if status == -1 then status = nil end -- don't report 'normal' status ???
local tbl = {
ControlURLs = curls,
states = states,
status = status,
}
for a,b in pairs (d.attributes) do tbl[a] = b end
info[#info+1] = tbl
end
return info
end
-- save ()
-- top-level attributes and key tables: devices, rooms, scenes
-- TODO: [, sections, users, weatherSettings]
local function save_user_data (localLuup, filename)
local luup = localLuup or luup
local result, message
local f = io.open (filename or "user_data.json", 'w')
if not f then
message = "error writing user_data"
else
local data = {rooms = {}, scenes = {}}
-- scalar attributes
for a,b in pairs (attributes) do
if type(b) ~= "table" then data[a] = b end
end
-- devices
data.devices = devices_table (luup.devices or {})
-- plugins
data.InstalledPlugins2 = {} -- TODO: replace with plugins.installed()
-- rooms
local rooms = data.rooms
for i, name in pairs (luup.rooms or {}) do
rooms[#rooms+1] = {id = i, name = name}
end
-- scenes
local scenes = data.scenes
for _, s in pairs (luup.scenes or {}) do
scenes[#scenes+1] = s: user_table ()
end
--
local j, msg = json.encode (data)
if j then
f:write (j)
f:write '\n'
result = true
else
message = "syntax error in user_data: " .. (msg or '?')
end
f:close ()
end
return result, message
end
return {
ABOUT = ABOUT,
attributes = attributes,
devices_table = devices_table,
-- load = load_user_data,
parse = parse_user_data,
save = save_user_data,
}
|
hot-fix-user_data-backup
|
hot-fix-user_data-backup
- to allow backup WSAPI CGI script to work
|
Lua
|
apache-2.0
|
akbooer/openLuup
|
116f119655bbcce232ec0d0f777a260b29f5df64
|
whisper.lua
|
whisper.lua
|
local mod = EPGP:NewModule("whisper", "AceEvent-3.0")
local L = LibStub("AceLocale-3.0"):GetLocale("EPGP")
local senderMap = {}
function mod:CHAT_MSG_WHISPER(event_name, msg, sender)
if not UnitInRaid("player") then return end
if msg:sub(1, 12):lower() ~= 'epgp standby' then return end
local member = msg:sub(13):match("([^ ]+)")
if member then
-- http://lua-users.org/wiki/LuaUnicode
local firstChar, offset = member:match("([%z\1-\127\194-\244][\128-\191]*)()")
member = firstChar:upper()..member:sub(offset):lower()
else
member = sender
end
senderMap[member] = sender
if not EPGP:GetEPGP(member) then
SendChatMessage(L["%s is not eligible for EP awards"]:format(member),
"WHISPER", nil, sender)
elseif EPGP:IsMemberInAwardList(member) then
SendChatMessage(L["%s is already in the award list"]:format(member),
"WHISPER", nil, sender)
else
EPGP:SelectMember(member)
SendChatMessage(L["%s is added to the award list"]:format(member),
"WHISPER", nil, sender)
end
end
local function SendNotifiesAndClearExtras(
event_name, names, reason, amount,
extras_awarded, extras_reason, extras_amount)
EPGP:GetModule("announce"):AnnounceTo(
"GUILD",
L["If you want to be on the award list but you are not in the raid, you need to whisper me: 'epgp standby' or 'epgp standby <name>' where <name> is the toon that should receive awards"])
if extras_awarded then
for member,_ in pairs(extras_awarded) do
local sender = senderMap[member]
if sender then
SendChatMessage(L["%+d EP (%s) to %s"]:format(
extras_amount, extras_reason, member),
"WHISPER", nil, sender)
EPGP:DeSelectMember(member)
SendChatMessage(
L["%s is now removed from the award list"]:format(member),
"WHISPER", nil, sender)
end
senderMap[member] = nil
end
end
end
mod.dbDefaults = {
profile = {
enable = false,
}
}
mod.optionsName = L["Whisper"]
mod.optionsDesc = L["Standby whispers in raid"]
mod.optionsArgs = {
help = {
order = 1,
type = "description",
name = L["Automatic handling of the standby list through whispers when in raid. When this is enabled, the standby list is cleared after each reward."],
},
}
function mod:OnEnable()
self:RegisterEvent("CHAT_MSG_WHISPER")
EPGP.RegisterCallback(self, "MassEPAward", SendNotifiesAndClearExtras)
EPGP.RegisterCallback(self, "StartRecurringAward", SendNotifiesAndClearExtras)
end
function mod:OnDisable()
EPGP.UnregisterAllCallbacks(self)
end
|
local mod = EPGP:NewModule("whisper", "AceEvent-3.0")
local L = LibStub("AceLocale-3.0"):GetLocale("EPGP")
local senderMap = {}
function mod:CHAT_MSG_WHISPER(event_name, msg, sender)
if not UnitInRaid("player") then return end
if msg:sub(1, 12):lower() ~= 'epgp standby' then return end
local member = msg:sub(13):match("([^ ]+)")
if member then
-- http://lua-users.org/wiki/LuaUnicode
local firstChar, offset = member:match("([%z\1-\127\194-\244][\128-\191]*)()")
member = firstChar:upper()..member:sub(offset):lower()
else
member = sender
end
senderMap[member] = sender
if not EPGP:GetEPGP(member) then
SendChatMessage(L["%s is not eligible for EP awards"]:format(member),
"WHISPER", nil, sender)
elseif EPGP:IsMemberInAwardList(member) then
SendChatMessage(L["%s is already in the award list"]:format(member),
"WHISPER", nil, sender)
else
EPGP:SelectMember(member)
SendChatMessage(L["%s is added to the award list"]:format(member),
"WHISPER", nil, sender)
end
end
local function AnnounceMedium()
local medium = mod.db.profile.medium
if medium ~= "NONE" then
return medium
end
end
local function SendNotifiesAndClearExtras(
event_name, names, reason, amount,
extras_awarded, extras_reason, extras_amount)
local medium = AnnounceMedium()
if medium then
EPGP:GetModule("announce"):AnnounceTo(
medium,
L["If you want to be on the award list but you are not in the raid, you need to whisper me: 'epgp standby' or 'epgp standby <name>' where <name> is the toon that should receive awards"])
end
if extras_awarded then
for member,_ in pairs(extras_awarded) do
local sender = senderMap[member]
if sender then
SendChatMessage(L["%+d EP (%s) to %s"]:format(
extras_amount, extras_reason, member),
"WHISPER", nil, sender)
EPGP:DeSelectMember(member)
SendChatMessage(
L["%s is now removed from the award list"]:format(member),
"WHISPER", nil, sender)
end
senderMap[member] = nil
end
end
end
mod.dbDefaults = {
profile = {
enable = false,
memdium = "GUILD",
}
}
mod.optionsName = L["Whisper"]
mod.optionsDesc = L["Standby whispers in raid"]
mod.optionsArgs = {
help = {
order = 1,
type = "description",
name = L["Automatic handling of the standby list through whispers when in raid. When this is enabled, the standby list is cleared after each reward."],
},
medium = {
order = 10,
type = "select",
name = L["Announce medium"],
desc = L["Sets the announce medium EPGP will use to announce EPGP actions."],
values = {
["GUILD"] = CHAT_MSG_GUILD,
["CHANNEL"] = CUSTOM,
["NONE"] = NONE,
},
},
}
function mod:OnEnable()
self:RegisterEvent("CHAT_MSG_WHISPER")
EPGP.RegisterCallback(self, "MassEPAward", SendNotifiesAndClearExtras)
EPGP.RegisterCallback(self, "StartRecurringAward", SendNotifiesAndClearExtras)
end
function mod:OnDisable()
EPGP.UnregisterAllCallbacks(self)
end
|
Let the user select the announce medium the whisper module should use. This fixes issue 475.
|
Let the user select the announce medium the whisper module should use. This fixes issue 475.
|
Lua
|
bsd-3-clause
|
hayword/tfatf_epgp,sheldon/epgp,ceason/epgp-tfatf,sheldon/epgp,protomech/epgp-dkp-reloaded,hayword/tfatf_epgp,ceason/epgp-tfatf,protomech/epgp-dkp-reloaded
|
2c4d3d5db65dc87a297ce9d2b2753a9be4ef1143
|
core/debug-output.lua
|
core/debug-output.lua
|
if (not SILE.outputters) then SILE.outputters = {} end
local cursorX = 0
local cursorY = 0
local lastFont
local outfile
local writeline = function (...)
local args = table.pack(...)
for i = 1, #args do
outfile:write(args[i])
if i < #args then outfile:write("\t") end
end
outfile:write("\n")
end
local _deprecationCheck = function (caller)
if type(caller) ~= "table" or type(caller.debugHbox) ~= "function" then
SU.deprecated("SILE.outputter.*", "SILE.outputter:*", "0.10.9", "0.10.10")
end
end
local function _round (input)
-- LuaJIT 2.1 betas (and inheritors such as OpenResty and Moonjit) are biased
-- towards rounding 0.5 up to 1, all other Lua interpreters are biased
-- towards rounding such floating point numbers down. This hack shaves off
-- just enough to fix the bias so our test suite works across interpreters.
-- Note that even a true rounding function here will fail because the bias is
-- inherent to the floating point type. Also note we are erroring in favor of
-- the *less* common option beacuse the LuaJIT VMS are hopelessly broken
-- whereas normal LUA VMs can be cooerced.
if input > 0 then input = input + .00000000000001 end
if input < 0 then input = input - .00000000000001 end
return string.format("%.4f", input)
end
SILE.outputters.debug = {
init = function (self)
_deprecationCheck(self)
outfile = io.open(SILE.outputFilename, "w+")
writeline("Set paper size ", SILE.documentState.paperSize[1], SILE.documentState.paperSize[2])
writeline("Begin page")
end,
newPage = function (self)
_deprecationCheck(self)
writeline("New page")
end,
finish = function (self)
_deprecationCheck(self)
if SILE.status.unsupported then writeline("UNSUPPORTED") end
writeline("End page")
writeline("Finish")
outfile:close()
end,
cursor = function (_)
SU.deprecated("SILE.outputter:cursor", "SILE.outputter:getCursor", "0.10.10", "0.11.0")
end,
getCursor = function (self)
_deprecationCheck(self)
return cursorX, cursorY
end,
moveTo = function (_, _, _)
SU.deprecated("SILE.outputter:moveTo", "SILE.outputter:setCursor", "0.10.10", "0.11.0")
end,
setCursor = function (self, x, y, relative)
_deprecationCheck(self)
x = SU.cast("number", x)
y = SU.cast("number", y)
local oldx, oldy = self:getCursor()
local offset = relative and { x = cursorX, y = cursorY } or { x = 0, y = 0 }
cursorX = offset.x + x
cursorY = offset.y - y
if _round(oldx) ~= _round(cursorX) then writeline("Mx ", _round(x)) end
if _round(oldy) ~= _round(cursorY) then writeline("My ", _round(y)) end
end,
setColor = function (self, color)
_deprecationCheck(self)
writeline("Set color", color.r, color.g, color.b)
end,
pushColor = function (self, color)
_deprecationCheck(self)
if color.r then
writeline("Push color", _round(color.r), _round(color.g), _round(color.b))
elseif color.c then
writeline("Push color (CMYK)", _round(color.c), _round(color.m), _round(color.y), _round(color.k))
elseif color.l then
writeline("Push color (grayscale)", _round(color.l))
end
end,
popColor = function (self)
_deprecationCheck(self)
writeline("Pop color")
end,
outputHbox = function (_, _, _)
SU.deprecated("SILE.outputter:outputHbox", "SILE.outputter:drawHbox", "0.10.10", "0.11.0")
end,
drawHbox = function (self, value, width)
_deprecationCheck(self)
if not value.glyphString then return end
width = SU.cast("number", width)
local buf
if value.complex then
local cluster = {}
for i = 1, #value.items do
local item = value.items[i]
cluster[#cluster+1] = item.gid
-- For the sake of terseness we're only dumping non-zero values
if item.glyphAdvance ~= 0 then cluster[#cluster+1] = "a=".._round(item.glyphAdvance) end
if item.x_offset then cluster[#cluster+1] = "x=".._round(item.x_offset) end
if item.y_offset then cluster[#cluster+1] = "y=".._round(item.y_offset) end
self:setCursor(item.width, 0, true)
end
buf = table.concat(cluster, " ")
else
buf = table.concat(value.glyphString, " ") .. " w=" .. _round(width)
end
writeline("T", buf, "(" .. tostring(value.text) .. ")")
end,
setFont = function (self, options)
_deprecationCheck(self)
local font = SILE.font._key(options)
if lastFont ~= font then
writeline("Set font ", font)
lastFont = font
end
end,
drawImage = function (self, src, x, y, width, height)
_deprecationCheck(self)
x = SU.cast("number", x)
y = SU.cast("number", y)
width = SU.cast("number", width)
height = SU.cast("number", height)
writeline("Draw image", src, _round(x), _round(y), _round(width), _round(height))
end,
imageSize = function (_, _)
SU.deprecated("SILE.outputter:imageSize", "SILE.outputter:getImageSize", "0.10.10", "0.11.0")
end,
getImageSize = function (self, src)
_deprecationCheck(self)
local pdf = require("justenoughlibtexpdf")
local llx, lly, urx, ury = pdf.imagebbox(src)
return (urx-llx), (ury-lly)
end,
drawSVG = function (self, figure, _, x, y, width, height, scalefactor)
_deprecationCheck(self)
x = SU.cast("number", x)
y = SU.cast("number", y)
width = SU.cast("number", width)
height = SU.cast("number", height)
writeline("Draw SVG", _round(x), _round(y), _round(width), _round(height), figure, scalefactor)
end,
rule = function (_, _, _, _, _)
SU.deprecated("SILE.outputter:rule", "SILE.outputter:drawRule", "0.10.10", "0.11.0")
end,
drawRule = function (self, x, y, width, depth)
_deprecationCheck(self)
x = SU.cast("number", x)
y = SU.cast("number", y)
width = SU.cast("number", width)
depth = SU.cast("number", depth)
writeline("Draw line", _round(x), _round(y), _round(width), _round(depth))
end,
debugFrame = function (self, _, _)
_deprecationCheck(self)
end,
debugHbox = function (self, _, _, _)
_deprecationCheck(self)
end
}
SILE.outputter = SILE.outputters.debug
if not SILE.outputFilename and SILE.masterFilename then
SILE.outputFilename = SILE.masterFilename..".debug"
end
|
if (not SILE.outputters) then SILE.outputters = {} end
local cursorX = 0
local cursorY = 0
local lastFont
local outfile
local writeline = function (...)
local args = table.pack(...)
for i = 1, #args do
outfile:write(args[i])
if i < #args then outfile:write("\t") end
end
outfile:write("\n")
end
local _deprecationCheck = function (caller)
if type(caller) ~= "table" or type(caller.debugHbox) ~= "function" then
SU.deprecated("SILE.outputter.*", "SILE.outputter:*", "0.10.9", "0.10.10")
end
end
local function _round (input)
-- LuaJIT 2.1 betas (and inheritors such as OpenResty and Moonjit) are biased
-- towards rounding 0.5 up to 1, all other Lua interpreters are biased
-- towards rounding such floating point numbers down. This hack shaves off
-- just enough to fix the bias so our test suite works across interpreters.
-- Note that even a true rounding function here will fail because the bias is
-- inherent to the floating point type. Also note we are erroring in favor of
-- the *less* common option beacuse the LuaJIT VMS are hopelessly broken
-- whereas normal LUA VMs can be cooerced.
if input > 0 then input = input + .00000000000001 end
if input < 0 then input = input - .00000000000001 end
return string.format("%.4f", input)
end
SILE.outputters.debug = {
init = function (self)
_deprecationCheck(self)
outfile = io.open(SILE.outputFilename, "w+")
writeline("Set paper size ", SILE.documentState.paperSize[1], SILE.documentState.paperSize[2])
writeline("Begin page")
end,
newPage = function (self)
_deprecationCheck(self)
writeline("New page")
end,
finish = function (self)
_deprecationCheck(self)
if SILE.status.unsupported then writeline("UNSUPPORTED") end
writeline("End page")
writeline("Finish")
outfile:close()
end,
cursor = function (_)
SU.deprecated("SILE.outputter:cursor", "SILE.outputter:getCursor", "0.10.10", "0.11.0")
end,
getCursor = function (self)
_deprecationCheck(self)
return cursorX, cursorY
end,
moveTo = function (_, _, _)
SU.deprecated("SILE.outputter:moveTo", "SILE.outputter:setCursor", "0.10.10", "0.11.0")
end,
setCursor = function (self, x, y, relative)
_deprecationCheck(self)
x = SU.cast("number", x)
y = SU.cast("number", y)
local oldx, oldy = self:getCursor()
local offset = relative and { x = cursorX, y = cursorY } or { x = 0, y = 0 }
cursorX = offset.x + x
cursorY = offset.y - y
if _round(oldx) ~= _round(cursorX) then writeline("Mx ", _round(x)) end
if _round(oldy) ~= _round(cursorY) then writeline("My ", _round(y)) end
end,
setColor = function (self, color)
_deprecationCheck(self)
if color.r then
writeline("Set color", _round(color.r), _round(color.g), _round(color.b))
elseif color.c then
writeline("Set color (CMYK)", _round(color.c), _round(color.m), _round(color.y), _round(color.k))
elseif color.l then
writeline("Set color (grayscale)", _round(color.l))
end
end,
pushColor = function (self, color)
_deprecationCheck(self)
if color.r then
writeline("Push color", _round(color.r), _round(color.g), _round(color.b))
elseif color.c then
writeline("Push color (CMYK)", _round(color.c), _round(color.m), _round(color.y), _round(color.k))
elseif color.l then
writeline("Push color (grayscale)", _round(color.l))
end
end,
popColor = function (self)
_deprecationCheck(self)
writeline("Pop color")
end,
outputHbox = function (_, _, _)
SU.deprecated("SILE.outputter:outputHbox", "SILE.outputter:drawHbox", "0.10.10", "0.11.0")
end,
drawHbox = function (self, value, width)
_deprecationCheck(self)
if not value.glyphString then return end
width = SU.cast("number", width)
local buf
if value.complex then
local cluster = {}
for i = 1, #value.items do
local item = value.items[i]
cluster[#cluster+1] = item.gid
-- For the sake of terseness we're only dumping non-zero values
if item.glyphAdvance ~= 0 then cluster[#cluster+1] = "a=".._round(item.glyphAdvance) end
if item.x_offset then cluster[#cluster+1] = "x=".._round(item.x_offset) end
if item.y_offset then cluster[#cluster+1] = "y=".._round(item.y_offset) end
self:setCursor(item.width, 0, true)
end
buf = table.concat(cluster, " ")
else
buf = table.concat(value.glyphString, " ") .. " w=" .. _round(width)
end
writeline("T", buf, "(" .. tostring(value.text) .. ")")
end,
setFont = function (self, options)
_deprecationCheck(self)
local font = SILE.font._key(options)
if lastFont ~= font then
writeline("Set font ", font)
lastFont = font
end
end,
drawImage = function (self, src, x, y, width, height)
_deprecationCheck(self)
x = SU.cast("number", x)
y = SU.cast("number", y)
width = SU.cast("number", width)
height = SU.cast("number", height)
writeline("Draw image", src, _round(x), _round(y), _round(width), _round(height))
end,
imageSize = function (_, _)
SU.deprecated("SILE.outputter:imageSize", "SILE.outputter:getImageSize", "0.10.10", "0.11.0")
end,
getImageSize = function (self, src)
_deprecationCheck(self)
local pdf = require("justenoughlibtexpdf")
local llx, lly, urx, ury = pdf.imagebbox(src)
return (urx-llx), (ury-lly)
end,
drawSVG = function (self, figure, _, x, y, width, height, scalefactor)
_deprecationCheck(self)
x = SU.cast("number", x)
y = SU.cast("number", y)
width = SU.cast("number", width)
height = SU.cast("number", height)
writeline("Draw SVG", _round(x), _round(y), _round(width), _round(height), figure, scalefactor)
end,
rule = function (_, _, _, _, _)
SU.deprecated("SILE.outputter:rule", "SILE.outputter:drawRule", "0.10.10", "0.11.0")
end,
drawRule = function (self, x, y, width, depth)
_deprecationCheck(self)
x = SU.cast("number", x)
y = SU.cast("number", y)
width = SU.cast("number", width)
depth = SU.cast("number", depth)
writeline("Draw line", _round(x), _round(y), _round(width), _round(depth))
end,
debugFrame = function (self, _, _)
_deprecationCheck(self)
end,
debugHbox = function (self, _, _, _)
_deprecationCheck(self)
end
}
SILE.outputter = SILE.outputters.debug
if not SILE.outputFilename and SILE.masterFilename then
SILE.outputFilename = SILE.masterFilename..".debug"
end
|
chore(outputter): Fixup debug outputter for non-RGB
|
chore(outputter): Fixup debug outputter for non-RGB
|
Lua
|
mit
|
alerque/sile,alerque/sile,alerque/sile,alerque/sile
|
edee7571afda1b4ab073e324151b2bc0892cfc7d
|
nvim/.config/nvim/lua/gb/test.lua
|
nvim/.config/nvim/lua/gb/test.lua
|
-- Testing helpers
local jester = require('jester');
jester.setup({
path_to_jest_run = 'node_modules/.bin/jest',
terminal_cmd = ':below split | terminal'
})
vim.keymap.set("n", "<leader>tt", function () jester.run() end)
vim.keymap.set("n", "<leader>tf", function () jester.run_file() end)
vim.keymap.set("n", "<leader>td", function () jester.debug() end)
function _G.go_to_test_file(typeOfSplit)
local current_path = vim.fn.expand("%")
if string.find(current_path, ".ts$") == nil then
print "Only TS files are supported"
return
end
local is_test_file = string.find(current_path, ".test.ts$") ~= nil
local test_file_path = string.gsub(current_path, ".ts$", ".test.ts")
local vsplit_command = "vsplit "
local split_command = "below split "
if is_test_file then
test_file_path = string.gsub(current_path, ".test.ts$", ".ts")
vsplit_command = "vsplit "
split_command = "below "
end
if typeOfSplit == "v" then
return vim.api.nvim_command(":" .. vsplit_command .. test_file_path)
else
return vim.api.nvim_command(":" .. split_command .. test_file_path)
end
end
vim.keymap.set("n", "<leader>ts", ":lua go_to_test_file()<CR>", {silent = true})
vim.keymap.set("n", "<leader>tw", ':lua go_to_test_file("v")<CR>', {silent = true})
|
-- Testing helpers
local jester = require('jester');
jester.setup({
path_to_jest_run = 'node_modules/.bin/jest',
terminal_cmd = ':below split | terminal'
})
vim.keymap.set("n", "<leader>tt", function () jester.run() end)
vim.keymap.set("n", "<leader>tf", function () jester.run_file() end)
vim.keymap.set("n", "<leader>td", function () jester.debug() end)
function _G.go_to_test_file()
local current_path = vim.fn.expand("%")
if string.find(current_path, ".ts$") == nil then
print "Only TS files are supported"
return
end
local is_test_file = string.find(current_path, ".test.ts$") ~= nil
local test_file_path = string.gsub(current_path, ".ts$", ".test.ts")
local vsplit_command = ":vsplit "
if is_test_file then
test_file_path = string.gsub(current_path, ".test.ts$", ".ts")
vsplit_command = ":lefta " .. vsplit_command
end
return vim.api.nvim_command(vsplit_command .. test_file_path)
end
vim.keymap.set("n", "<leader>tw", ':lua go_to_test_file()<CR>', {silent = true})
|
Fix splitting test files
|
Fix splitting test files
|
Lua
|
mit
|
gblock0/dotfiles
|
d2abbe73657b4ea5dd68180f552a97c322f7101a
|
mod_carbons/mod_carbons.lua
|
mod_carbons/mod_carbons.lua
|
-- XEP-0280: Message Carbons implementation for Prosody
-- Copyright (C) 2011 Kim Alvefur
--
-- This file is MIT/X11 licensed.
local st = require "util.stanza";
local jid_bare = require "util.jid".bare;
local xmlns_carbons = "urn:xmpp:carbons:2";
local xmlns_carbons_old = "urn:xmpp:carbons:1";
local xmlns_carbons_really_old = "urn:xmpp:carbons:0";
local xmlns_forward = "urn:xmpp:forward:0";
local full_sessions, bare_sessions = full_sessions, bare_sessions;
local function toggle_carbons(event)
local origin, stanza = event.origin, event.stanza;
if stanza.attr.type == "set" then
local state = stanza.tags[1].name;
module:log("debug", "%s %sd carbons", origin.full_jid, state);
origin.want_carbons = state == "enable" and stanza.tags[1].attr.xmlns;
origin.send(st.reply(stanza));
return true
end
end
module:hook("iq/self/"..xmlns_carbons..":disable", toggle_carbons);
module:hook("iq/self/"..xmlns_carbons..":enable", toggle_carbons);
-- COMPAT
module:hook("iq/self/"..xmlns_carbons_old..":disable", toggle_carbons);
module:hook("iq/self/"..xmlns_carbons_old..":enable", toggle_carbons);
-- COMPAT :(
if module:get_option_boolean("carbons_v0") then
module:hook("iq/self/"..xmlns_carbons_really_old..":carbons", function(event)
local origin, stanza = event.origin, event.stanza;
if stanza.attr.type == "set" then
local state = stanza.tags[1].attr.mode;
origin.want_carbons = state == "enable" and xmlns_carbons_really_old;
origin.send(st.reply(stanza));
return true;
end
end);
end
local function message_handler(event, c2s)
local origin, stanza = event.origin, event.stanza;
local orig_type = stanza.attr.type;
local orig_from = stanza.attr.from;
local orig_to = stanza.attr.to;
if not (orig_type == nil
or orig_type == "normal"
or orig_type == "chat") then
return -- No carbons for messages of type error or headline
end
-- Stanza sent by a local client
local bare_jid = jid_bare(orig_from);
local target_session = origin;
local top_priority = false;
local user_sessions = bare_sessions[bare_jid];
-- Stanza about to be delivered to a local client
if not c2s then
bare_jid = jid_bare(orig_to);
target_session = full_sessions[orig_to];
user_sessions = bare_sessions[bare_jid];
if not target_session and user_sessions then
-- The top resources will already receive this message per normal routing rules,
-- so we are going to skip them in order to avoid sending duplicated messages.
local top_resources = user_sessions.top_resources;
top_priority = top_resources and top_resources[1].priority
end
end
if not user_sessions then
module:log("debug", "Skip carbons for offline user");
return -- No use in sending carbons to an offline user
end
if not c2s and stanza:get_child("private", xmlns_carbons) then
stanza:maptags(function(tag)
return tag.attr.xmlns == xmlns_carbons
and tag.name == "private" and tag or nil;
end);
module:log("debug", "Message tagged private, ignoring");
return
elseif stanza:get_child("no-copy", "urn:xmpp:hints") then
module:log("debug", "Message has no-copy hint, ignoring");
return
end
-- Create the carbon copy and wrap it as per the Stanza Forwarding XEP
local copy = st.clone(stanza);
copy.attr.xmlns = "jabber:client";
local carbon = st.message{ from = bare_jid, type = orig_type, }
:tag(c2s and "sent" or "received", { xmlns = xmlns_carbons })
:tag("forwarded", { xmlns = xmlns_forward })
:add_child(copy):reset();
-- COMPAT
local carbon_old = st.message{ from = bare_jid, type = orig_type, }
:tag(c2s and "sent" or "received", { xmlns = xmlns_carbons_old }):up()
:tag("forwarded", { xmlns = xmlns_forward })
:add_child(copy):reset();
-- COMPAT
local carbon_really_old = st.clone(stanza)
:tag(c2s and "sent" or "received", { xmlns = xmlns_carbons_really_old }):up()
user_sessions = user_sessions and user_sessions.sessions;
for _, session in pairs(user_sessions) do
-- Carbons are sent to resources that have enabled it
if session.want_carbons
-- but not the resource that sent the message, or the one that it's directed to
and session ~= target_session
-- and isn't among the top resources that would receive the message per standard routing rules
and (c2s or session.priority ~= top_priority)
-- don't send v0 carbons (or copies) for c2s
and (not c2s or session.want_carbons ~= xmlns_carbons_really_old) then
carbon.attr.to = session.full_jid;
module:log("debug", "Sending carbon to %s", session.full_jid);
local carbon = session.want_carbons == xmlns_carbons_old and carbon_old -- COMPAT
or session.want_carbons == xmlns_carbons_really_old and carbon_really_old -- COMPAT
or carbon;
session.send(carbon);
end
end
end
local function c2s_message_handler(event)
return message_handler(event, true)
end
-- Stanzas sent by local clients
module:hook("pre-message/host", c2s_message_handler, 1);
module:hook("pre-message/bare", c2s_message_handler, 1);
module:hook("pre-message/full", c2s_message_handler, 1);
-- Stanzas to local clients
module:hook("message/bare", message_handler, 1);
module:hook("message/full", message_handler, 1);
module:add_feature(xmlns_carbons);
module:add_feature(xmlns_carbons_old);
if module:get_option_boolean("carbons_v0") then
module:add_feature(xmlns_carbons_really_old);
end
|
-- XEP-0280: Message Carbons implementation for Prosody
-- Copyright (C) 2011 Kim Alvefur
--
-- This file is MIT/X11 licensed.
local st = require "util.stanza";
local jid_bare = require "util.jid".bare;
local xmlns_carbons = "urn:xmpp:carbons:2";
local xmlns_carbons_old = "urn:xmpp:carbons:1";
local xmlns_carbons_really_old = "urn:xmpp:carbons:0";
local xmlns_forward = "urn:xmpp:forward:0";
local full_sessions, bare_sessions = full_sessions, bare_sessions;
local function toggle_carbons(event)
local origin, stanza = event.origin, event.stanza;
if stanza.attr.type == "set" then
local state = stanza.tags[1].name;
module:log("debug", "%s %sd carbons", origin.full_jid, state);
origin.want_carbons = state == "enable" and stanza.tags[1].attr.xmlns;
origin.send(st.reply(stanza));
return true
end
end
module:hook("iq/self/"..xmlns_carbons..":disable", toggle_carbons);
module:hook("iq/self/"..xmlns_carbons..":enable", toggle_carbons);
-- COMPAT
module:hook("iq/self/"..xmlns_carbons_old..":disable", toggle_carbons);
module:hook("iq/self/"..xmlns_carbons_old..":enable", toggle_carbons);
-- COMPAT :(
if module:get_option_boolean("carbons_v0") then
module:hook("iq/self/"..xmlns_carbons_really_old..":carbons", function(event)
local origin, stanza = event.origin, event.stanza;
if stanza.attr.type == "set" then
local state = stanza.tags[1].attr.mode;
origin.want_carbons = state == "enable" and xmlns_carbons_really_old;
origin.send(st.reply(stanza));
return true;
end
end);
end
local function message_handler(event, c2s)
local origin, stanza = event.origin, event.stanza;
local orig_type = stanza.attr.type;
local orig_from = stanza.attr.from;
local orig_to = stanza.attr.to;
if not (orig_type == nil
or orig_type == "normal"
or orig_type == "chat") then
return -- No carbons for messages of type error or headline
end
-- Stanza sent by a local client
local bare_jid = jid_bare(orig_from);
local target_session = origin;
local top_priority = false;
local user_sessions = bare_sessions[bare_jid];
-- Stanza about to be delivered to a local client
if not c2s then
bare_jid = jid_bare(orig_to);
target_session = full_sessions[orig_to];
user_sessions = bare_sessions[bare_jid];
if not target_session and user_sessions then
-- The top resources will already receive this message per normal routing rules,
-- so we are going to skip them in order to avoid sending duplicated messages.
local top_resources = user_sessions.top_resources;
top_priority = top_resources and top_resources[1].priority
end
end
if not user_sessions then
module:log("debug", "Skip carbons for offline user");
return -- No use in sending carbons to an offline user
end
if not c2s and stanza:get_child("private", xmlns_carbons) then
stanza:maptags(function(tag)
if not ( tag.attr.xmlns == xmlns_carbons and tag.name == "private" ) then
return tag;
end
end);
module:log("debug", "Message tagged private, ignoring");
return
elseif stanza:get_child("no-copy", "urn:xmpp:hints") then
module:log("debug", "Message has no-copy hint, ignoring");
return
end
-- Create the carbon copy and wrap it as per the Stanza Forwarding XEP
local copy = st.clone(stanza);
copy.attr.xmlns = "jabber:client";
local carbon = st.message{ from = bare_jid, type = orig_type, }
:tag(c2s and "sent" or "received", { xmlns = xmlns_carbons })
:tag("forwarded", { xmlns = xmlns_forward })
:add_child(copy):reset();
-- COMPAT
local carbon_old = st.message{ from = bare_jid, type = orig_type, }
:tag(c2s and "sent" or "received", { xmlns = xmlns_carbons_old }):up()
:tag("forwarded", { xmlns = xmlns_forward })
:add_child(copy):reset();
-- COMPAT
local carbon_really_old = st.clone(stanza)
:tag(c2s and "sent" or "received", { xmlns = xmlns_carbons_really_old }):up()
user_sessions = user_sessions and user_sessions.sessions;
for _, session in pairs(user_sessions) do
-- Carbons are sent to resources that have enabled it
if session.want_carbons
-- but not the resource that sent the message, or the one that it's directed to
and session ~= target_session
-- and isn't among the top resources that would receive the message per standard routing rules
and (c2s or session.priority ~= top_priority)
-- don't send v0 carbons (or copies) for c2s
and (not c2s or session.want_carbons ~= xmlns_carbons_really_old) then
carbon.attr.to = session.full_jid;
module:log("debug", "Sending carbon to %s", session.full_jid);
local carbon = session.want_carbons == xmlns_carbons_old and carbon_old -- COMPAT
or session.want_carbons == xmlns_carbons_really_old and carbon_really_old -- COMPAT
or carbon;
session.send(carbon);
end
end
end
local function c2s_message_handler(event)
return message_handler(event, true)
end
-- Stanzas sent by local clients
module:hook("pre-message/host", c2s_message_handler, 1);
module:hook("pre-message/bare", c2s_message_handler, 1);
module:hook("pre-message/full", c2s_message_handler, 1);
-- Stanzas to local clients
module:hook("message/bare", message_handler, 1);
module:hook("message/full", message_handler, 1);
module:add_feature(xmlns_carbons);
module:add_feature(xmlns_carbons_old);
if module:get_option_boolean("carbons_v0") then
module:add_feature(xmlns_carbons_really_old);
end
|
mod_carbons: Fix <private/> handling
|
mod_carbons: Fix <private/> handling
|
Lua
|
mit
|
prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2
|
4015c7949fa72b7c4ed9073abf861b355ee4a514
|
lua/framework/mouse.lua
|
lua/framework/mouse.lua
|
--=========== Copyright © 2018, Planimeter, All rights reserved. =============--
--
-- Purpose:
--
--============================================================================--
local ffi = require( "ffi" )
local SDL = require( "sdl" )
module( "framework.mouse" )
function getPosition()
local x = ffi.new( "int[1]" )
local y = ffi.new( "int[1]" )
SDL.SDL_GetMouseState( x, y )
return x[0], y[0]
end
function getSystemCursor( id )
if ( id == "arrow" ) then
id = ffi.C.SDL_SYSTEM_CURSOR_ARROW
elseif ( id == "ibeam" ) then
id = ffi.C.SDL_SYSTEM_CURSOR_IBEAM
elseif ( id == "wait" ) then
id = ffi.C.SDL_SYSTEM_CURSOR_WAIT
elseif ( id == "crosshair" ) then
id = ffi.C.SDL_SYSTEM_CURSOR_CROSSHAIR
elseif ( id == "waitarrow" ) then
id = ffi.C.SDL_SYSTEM_CURSOR_WAITARROW
elseif ( id == "sizenwse" ) then
id = ffi.C.SDL_SYSTEM_CURSOR_SIZENWSE
elseif ( id == "sizenesw" ) then
id = ffi.C.SDL_SYSTEM_CURSOR_SIZENESW
elseif ( id == "sizewe" ) then
id = ffi.C.SDL_SYSTEM_CURSOR_SIZEWE
elseif ( id == "sizens" ) then
id = ffi.C.SDL_SYSTEM_CURSOR_SIZENS
elseif ( id == "sizeall" ) then
id = ffi.C.SDL_SYSTEM_CURSOR_SIZEALL
elseif ( id == "no" ) then
id = ffi.C.SDL_SYSTEM_CURSOR_NO
elseif ( id == "hand" ) then
id = ffi.C.SDL_SYSTEM_CURSOR_HAND
end
return SDL.SDL_CreateSystemCursor( id )
end
function setCursor( cursor )
SDL.SDL_SetCursor( cursor )
if ( cursor ) then
else
SDL.SDL_SetCursor( SDL.SDL_GetDefaultCursor() )
end
end
function setVisible( visible )
SDL.SDL_ShowCursor( visible and SDL.SDL_ENABLE or SDL.SDL_DISABLE )
end
|
--=========== Copyright © 2018, Planimeter, All rights reserved. =============--
--
-- Purpose:
--
--============================================================================--
local ffi = require( "ffi" )
local SDL = require( "sdl" )
local framework = framework
module( "framework.mouse" )
function getPosition()
local x = ffi.new( "int[1]" )
local y = ffi.new( "int[1]" )
SDL.SDL_GetMouseState( x, y )
return x[0], y[0]
end
function getSystemCursor( id )
if ( id == "arrow" ) then
id = ffi.C.SDL_SYSTEM_CURSOR_ARROW
elseif ( id == "ibeam" ) then
id = ffi.C.SDL_SYSTEM_CURSOR_IBEAM
elseif ( id == "wait" ) then
id = ffi.C.SDL_SYSTEM_CURSOR_WAIT
elseif ( id == "crosshair" ) then
id = ffi.C.SDL_SYSTEM_CURSOR_CROSSHAIR
elseif ( id == "waitarrow" ) then
id = ffi.C.SDL_SYSTEM_CURSOR_WAITARROW
elseif ( id == "sizenwse" ) then
id = ffi.C.SDL_SYSTEM_CURSOR_SIZENWSE
elseif ( id == "sizenesw" ) then
id = ffi.C.SDL_SYSTEM_CURSOR_SIZENESW
elseif ( id == "sizewe" ) then
id = ffi.C.SDL_SYSTEM_CURSOR_SIZEWE
elseif ( id == "sizens" ) then
id = ffi.C.SDL_SYSTEM_CURSOR_SIZENS
elseif ( id == "sizeall" ) then
id = ffi.C.SDL_SYSTEM_CURSOR_SIZEALL
elseif ( id == "no" ) then
id = ffi.C.SDL_SYSTEM_CURSOR_NO
elseif ( id == "hand" ) then
id = ffi.C.SDL_SYSTEM_CURSOR_HAND
end
return SDL.SDL_CreateSystemCursor( id )
end
function setCursor( cursor )
SDL.SDL_SetCursor( cursor )
if ( cursor ) then
else
SDL.SDL_SetCursor( SDL.SDL_GetDefaultCursor() )
end
end
function setPosition( x, y )
SDL.SDL_WarpMouseInWindow( framework.window._window, x, y )
end
function setVisible( visible )
SDL.SDL_ShowCursor( visible and 1 or 0 )
end
|
Update `framework.mouse`
|
Update `framework.mouse`
Add `setPosition`
Fix error in `setVisible`
|
Lua
|
mit
|
Planimeter/lgameframework,Planimeter/lgameframework,Planimeter/lgameframework
|
44c31afe62afaf99c2c3d5f71c02993e038633c6
|
frontend/ui/reader/readercopt.lua
|
frontend/ui/reader/readercopt.lua
|
ReaderCoptListener = EventListener:new{}
function ReaderCoptListener:onReadSettings(config)
local embedded_css = config:readSetting("copt_embedded_css")
if embedded_css == 0 then
table.insert(self.ui.postInitCallback, function()
self.ui:handleEvent(Event:new("ToggleEmbeddedStyleSheet", false))
end)
end
local view_mode = config:readSetting("copt_view_mode")
if view_mode == 0 then
table.insert(self.ui.postInitCallback, function()
self.ui:handleEvent(Event:new("SetViewMode", "page"))
end)
elseif view_mode == 1 then
table.insert(self.ui.postInitCallback, function()
self.ui:handleEvent(Event:new("SetViewMode", "scroll"))
end)
end
local copt_font_size = config:readSetting("copt_font_size")
if copt_font_size then
table.insert(self.ui.postInitCallback, function()
self.ui:handleEvent(Event:new("SetFontSize", copt_font_size))
end)
end
local copt_margins = config:readSetting("copt_page_margins")
if copt_margins then
table.insert(self.ui.postInitCallback, function()
self.ui:handleEvent(Event:new("SetPageMargins", copt_margins))
end)
end
end
|
ReaderCoptListener = EventListener:new{}
function ReaderCoptListener:onReadSettings(config)
local embedded_css = config:readSetting("copt_embedded_css")
if embedded_css == 0 then
table.insert(self.ui.postInitCallback, function()
self.ui:handleEvent(Event:new("ToggleEmbeddedStyleSheet", false))
end)
end
local view_mode = config:readSetting("copt_view_mode")
if view_mode == 0 then
table.insert(self.ui.postInitCallback, function()
self.ui:handleEvent(Event:new("SetViewMode", "page"))
end)
elseif view_mode == 1 then
table.insert(self.ui.postInitCallback, function()
self.ui:handleEvent(Event:new("SetViewMode", "scroll"))
end)
end
local copt_font_size = config:readSetting("copt_font_size") or 22
if copt_font_size then
table.insert(self.ui.postInitCallback, function()
self.ui.document:setFontSize(copt_font_size)
self.ui:handleEvent(Event:new("UpdatePos"))
end)
end
local copt_margins = config:readSetting("copt_page_margins")
if copt_margins then
table.insert(self.ui.postInitCallback, function()
-- FIXME: SetPageMargins will mess up current reading position
-- for now we simply disable this feature.
--self.ui:handleEvent(Event:new("SetPageMargins", copt_margins))
end)
end
end
|
fix bug #179 It seems that the setPageMargins method will mess up XPointer of current view. This bugfix simply disables page margin restoring in readercopt.lua so that reading position is restorable.
|
fix bug #179
It seems that the setPageMargins method will mess up XPointer of current view.
This bugfix simply disables page margin restoring in readercopt.lua so that
reading position is restorable.
|
Lua
|
agpl-3.0
|
NiLuJe/koreader,apletnev/koreader,houqp/koreader,frankyifei/koreader,Frenzie/koreader,chihyang/koreader,robert00s/koreader,ashhher3/koreader,poire-z/koreader,noname007/koreader,mwoz123/koreader,Hzj-jie/koreader,NiLuJe/koreader,mihailim/koreader,ashang/koreader,koreader/koreader,poire-z/koreader,Markismus/koreader,Frenzie/koreader,pazos/koreader,koreader/koreader,chrox/koreader,lgeek/koreader,NickSavage/koreader
|
50062279a86648fc8f00646157727c1ae64dade2
|
MMOCoreORB/bin/scripts/object/tangible/fishing/fish/fish.lua
|
MMOCoreORB/bin/scripts/object/tangible/fishing/fish/fish.lua
|
--Copyright (C) 2009 <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
--which carries forward this exception.
object_tangible_fishing_fish_blackfish = object_tangible_fishing_fish_shared_blackfish:new {
gameObjectType = 8234
}
ObjectTemplates:addTemplate(object_tangible_fishing_fish_blackfish, "object/tangible/fishing/fish/blackfish.iff")
object_tangible_fishing_fish_blowfish = object_tangible_fishing_fish_shared_blowfish:new {
gameObjectType = 8234
}
ObjectTemplates:addTemplate(object_tangible_fishing_fish_blowfish, "object/tangible/fishing/fish/blowfish.iff")
object_tangible_fishing_fish_bluefish = object_tangible_fishing_fish_shared_bluefish:new {
gameObjectType = 8234
}
ObjectTemplates:addTemplate(object_tangible_fishing_fish_bluefish, "object/tangible/fishing/fish/bluefish.iff")
object_tangible_fishing_fish_faa = object_tangible_fishing_fish_shared_faa:new {
gameObjectType = 8234
}
ObjectTemplates:addTemplate(object_tangible_fishing_fish_faa, "object/tangible/fishing/fish/faa.iff")
object_tangible_fishing_fish_fish_generic = SharedTangibleObjectTemplate:new {
gameObjectType = 8234
}
ObjectTemplates:addTemplate(object_tangible_fishing_fish_fish_generic, "object/tangible/fishing/fish/fish_generic.iff")
object_tangible_fishing_fish_laa = object_tangible_fishing_fish_shared_laa:new {
gameObjectType = 8234
}
ObjectTemplates:addTemplate(object_tangible_fishing_fish_laa, "object/tangible/fishing/fish/laa.iff")
object_tangible_fishing_fish_ray = object_tangible_fishing_fish_shared_ray:new {
gameObjectType = 8234
}
ObjectTemplates:addTemplate(object_tangible_fishing_fish_ray, "object/tangible/fishing/fish/ray.iff")
object_tangible_fishing_fish_striped = object_tangible_fishing_fish_shared_striped:new {
gameObjectType = 8234
}
ObjectTemplates:addTemplate(object_tangible_fishing_fish_striped, "object/tangible/fishing/fish/striped.iff")
|
--Copyright (C) 2009 <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
--which carries forward this exception.
object_tangible_fishing_fish_blackfish = object_tangible_fishing_fish_shared_blackfish:new {
gameObjectType = 8234
}
ObjectTemplates:addTemplate(object_tangible_fishing_fish_blackfish, "object/tangible/fishing/fish/blackfish.iff")
object_tangible_fishing_fish_blowfish = object_tangible_fishing_fish_shared_blowfish:new {
gameObjectType = 8234
}
ObjectTemplates:addTemplate(object_tangible_fishing_fish_blowfish, "object/tangible/fishing/fish/blowfish.iff")
object_tangible_fishing_fish_bluefish = object_tangible_fishing_fish_shared_bluefish:new {
gameObjectType = 8234
}
ObjectTemplates:addTemplate(object_tangible_fishing_fish_bluefish, "object/tangible/fishing/fish/bluefish.iff")
object_tangible_fishing_fish_faa = object_tangible_fishing_fish_shared_faa:new {
gameObjectType = 8234
}
ObjectTemplates:addTemplate(object_tangible_fishing_fish_faa, "object/tangible/fishing/fish/faa.iff")
object_tangible_fishing_fish_fish_generic = object_tangible_fishing_fish_shared_fish_generic:new {
gameObjectType = 8234
}
ObjectTemplates:addTemplate(object_tangible_fishing_fish_fish_generic, "object/tangible/fishing/fish/fish_generic.iff")
object_tangible_fishing_fish_laa = object_tangible_fishing_fish_shared_laa:new {
gameObjectType = 8234
}
ObjectTemplates:addTemplate(object_tangible_fishing_fish_laa, "object/tangible/fishing/fish/laa.iff")
object_tangible_fishing_fish_ray = object_tangible_fishing_fish_shared_ray:new {
gameObjectType = 8234
}
ObjectTemplates:addTemplate(object_tangible_fishing_fish_ray, "object/tangible/fishing/fish/ray.iff")
object_tangible_fishing_fish_striped = object_tangible_fishing_fish_shared_striped:new {
gameObjectType = 8234
}
ObjectTemplates:addTemplate(object_tangible_fishing_fish_striped, "object/tangible/fishing/fish/striped.iff")
|
[Fixed] Generic Fish
|
[Fixed] Generic Fish
git-svn-id: c34995188cc7e843f8a799edec2d9d4b36f36456@2015 c3d1530f-68f5-4bd0-87dc-8ef779617e40
|
Lua
|
agpl-3.0
|
lasko2112/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,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,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo
|
2cc195d5c9781677123d98f5dd3d43c36321503b
|
lua_examples/webap_toggle_pin.lua
|
lua_examples/webap_toggle_pin.lua
|
wifi.setmode(wifi.SOFTAP)
wifi.ap.config({ssid="test",pwd="12345678"})
gpio.mode(1, gpio.OUTPUT)
srv=net.createServer(net.TCP)
srv:listen(80,function(conn)
conn:on("receive", function(client,request)
local buf = ""
local _, _, method, path, vars = string.find(request, "([A-Z]+) (.+)?(.+) HTTP")
if(method == nil)then
_, _, method, path = string.find(request, "([A-Z]+) (.+) HTTP")
end
local _GET = {}
if (vars ~= nil)then
for k, v in string.gmatch(vars, "(%w+)=(%w+)&*") do
_GET[k] = v
end
end
buf = buf.."<h1> Hello, NodeMcu.</h1><form src=\"/\">Turn PIN1 <select name=\"pin\" onchange=\"form.submit()\">"
local _on,_off = "",""
if(_GET.pin == "ON")then
_on = " selected=true"
gpio.write(1, gpio.HIGH)
elseif(_GET.pin == "OFF")then
_off = " selected=\"true\""
gpio.write(1, gpio.LOW)
end
buf = buf.."<option".._on..">ON</opton><option".._off..">OFF</option></select></form>"
client:send(buf)
end)
conn:on("sent", function (c) c:close() end)
end)
|
wifi.setmode(wifi.SOFTAP)
wifi.ap.config({ ssid = "test", pwd = "12345678" })
gpio.mode(1, gpio.OUTPUT)
srv = net.createServer(net.TCP)
srv:listen(80, function(conn)
conn:on("receive", function(client, request)
local buf = ""
local _, _, method, path, vars = string.find(request, "([A-Z]+) (.+)?(.+) HTTP")
if (method == nil) then
_, _, method, path = string.find(request, "([A-Z]+) (.+) HTTP")
end
local _GET = {}
if (vars ~= nil) then
for k, v in string.gmatch(vars, "(%w+)=(%w+)&*") do
_GET[k] = v
end
end
buf = buf .. "<!DOCTYPE html><html><body><h1>Hello, this is NodeMCU.</h1><form src=\"/\">Turn PIN1 <select name=\"pin\" onchange=\"form.submit()\">"
local _on, _off = "", ""
if (_GET.pin == "ON") then
_on = " selected=true"
gpio.write(1, gpio.HIGH)
elseif (_GET.pin == "OFF") then
_off = " selected=\"true\""
gpio.write(1, gpio.LOW)
end
buf = buf .. "<option" .. _on .. ">ON</option><option" .. _off .. ">OFF</option></select></form></body></html>"
client:send(buf)
end)
conn:on("sent", function(c) c:close() end)
end)
|
webap_toggle_pin.lua HTML warnings and typos fixed (#2394)
|
webap_toggle_pin.lua HTML warnings and typos fixed (#2394)
|
Lua
|
mit
|
TerryE/nodemcu-firmware,TerryE/nodemcu-firmware,nwf/nodemcu-firmware,HEYAHONG/nodemcu-firmware,nwf/nodemcu-firmware,nodemcu/nodemcu-firmware,FelixPe/nodemcu-firmware,eku/nodemcu-firmware,marcelstoer/nodemcu-firmware,FelixPe/nodemcu-firmware,HEYAHONG/nodemcu-firmware,FelixPe/nodemcu-firmware,nwf/nodemcu-firmware,eku/nodemcu-firmware,vsky279/nodemcu-firmware,vsky279/nodemcu-firmware,TerryE/nodemcu-firmware,marcelstoer/nodemcu-firmware,devsaurus/nodemcu-firmware,vsky279/nodemcu-firmware,nwf/nodemcu-firmware,devsaurus/nodemcu-firmware,eku/nodemcu-firmware,marcelstoer/nodemcu-firmware,devsaurus/nodemcu-firmware,marcelstoer/nodemcu-firmware,marcelstoer/nodemcu-firmware,nodemcu/nodemcu-firmware,HEYAHONG/nodemcu-firmware,vsky279/nodemcu-firmware,TerryE/nodemcu-firmware,nodemcu/nodemcu-firmware,nodemcu/nodemcu-firmware,devsaurus/nodemcu-firmware,vsky279/nodemcu-firmware,nwf/nodemcu-firmware,HEYAHONG/nodemcu-firmware,nodemcu/nodemcu-firmware,eku/nodemcu-firmware,HEYAHONG/nodemcu-firmware,FelixPe/nodemcu-firmware,FelixPe/nodemcu-firmware,devsaurus/nodemcu-firmware,TerryE/nodemcu-firmware
|
2f265bbf95d34bbc42105942a18196c951f4e4c1
|
scen_edit/command/load_map.lua
|
scen_edit/command/load_map.lua
|
LoadMap = AbstractCommand:extends{}
LoadMap.className = "LoadMap"
local floatSize = 4
function LoadMap:init(deltaMap)
self.className = "LoadMap"
self.deltaMap = deltaMap
end
function LoadMap:execute()
Spring.RevertHeightMap(0, 0, Game.mapSizeX, Game.mapSizeZ, 1)
Spring.SetHeightMapFunc(function()
--Spring.Echo("HEIGHTMAP LOAD")
local x = 0
local z = 0
local lastChanged = false
if #self.deltaMap == 0 then
return
end
local bufferSize = 1000 * floatSize
local segmentNum = 0
local totalSegments = math.ceil(#self.deltaMap / bufferSize)
local dataSize = #self.deltaMap / floatSize
--Spring.Echo("Segments : " .. totalSegments .. " Floats: " .. dataSize)
local fetchSegment = function()
if segmentNum >= totalSegments then
return {}
end
local startIndx = 1 + segmentNum * bufferSize
segmentNum = segmentNum + 1
local str = self.deltaMap:sub(startIndx, startIndx + bufferSize)
return VFS.UnpackF32(str, 1, bufferSize / floatSize) or {}
-- return VFS.UnpackF32(self.deltaMap, startIndx, bufferSize / floatSize) or {}
end
local data = fetchSegment()
local i = 1
local getData = function()
local chunk = data[i]
i = i + 1
if i > #data then
data = fetchSegment()
i = 1
end
return chunk
end
for chunk in getData do
if z == 0 then
lastChanged = false
end
----Spring.Echo(chunk, i)
if lastChanged then
if chunk == 0 then
--Spring.Echo(0)
lastChanged = false
else
local deltaHeight = chunk
--Spring.Echo(x, z)
--Spring.Echo(deltaHeight)
z = z + Game.squareSize
Spring.AddHeightMap(x, z, deltaHeight)
if z >= Game.mapSizeZ then
z = 0
x = x + Game.squareSize
end
end
else
x, z, deltaHeight = chunk, getData(), getData()
lastChanged = true
Spring.AddHeightMap(x, z, deltaHeight)
--Spring.Echo(x, z, deltaHeight)
end
end
--Spring.Echo("HEIGHTMAP LOAD DONE")
end)
end
|
LoadMap = AbstractCommand:extends{}
LoadMap.className = "LoadMap"
local floatSize = 4
function LoadMap:init(deltaMap)
self.className = "LoadMap"
self.deltaMap = deltaMap
end
function LoadMap:execute()
Spring.RevertHeightMap(0, 0, Game.mapSizeX, Game.mapSizeZ, 1)
Spring.SetHeightMapFunc(function()
--Spring.Echo("HEIGHTMAP LOAD")
local x = 0
local z = 0
if #self.deltaMap == 0 then
return
end
local bufferSize = 1000 * floatSize
local segmentNum = 0
local totalSegments = math.ceil(#self.deltaMap / bufferSize)
local dataSize = #self.deltaMap / floatSize
--Spring.Echo("Segments : " .. totalSegments .. " Floats: " .. dataSize)
local fetchSegment = function()
if segmentNum >= totalSegments then
return {}
end
local startIndx = 1 + segmentNum * bufferSize
segmentNum = segmentNum + 1
local str = self.deltaMap:sub(startIndx, startIndx + bufferSize)
return VFS.UnpackF32(str, 1, bufferSize / floatSize) or {}
-- return VFS.UnpackF32(self.deltaMap, startIndx, bufferSize / floatSize) or {}
end
local data = fetchSegment()
local i = 1
local getData = function()
local chunk = data[i]
i = i + 1
if i > #data then
data = fetchSegment()
i = 1
end
return chunk
end
local lastChanged = false
for chunk in getData do
----Spring.Echo(chunk, i)
if lastChanged then
if chunk == 0 then
--Spring.Echo(0)
lastChanged = false
else
local deltaHeight = chunk
z = z + Game.squareSize
if z >= Game.mapSizeZ then
z = 0
x = x + Game.squareSize
lastChanged = false
end
Spring.AddHeightMap(x, z, deltaHeight)
end
else
x, z, deltaHeight = chunk, getData(), getData()
lastChanged = true
Spring.AddHeightMap(x, z, deltaHeight)
--Spring.Echo(x, z, deltaHeight)
end
end
--Spring.Echo("HEIGHTMAP LOAD DONE")
end)
end
|
fixed heightmap loading
|
fixed heightmap loading
|
Lua
|
mit
|
Spring-SpringBoard/SpringBoard-Core,Spring-SpringBoard/SpringBoard-Core
|
ab9bc3485327f81d69aa7881edb6bc594f90a712
|
lua/arduino/telescope.lua
|
lua/arduino/telescope.lua
|
local themes = require('telescope.themes')
local actions = require('telescope.actions')
local pickers = require('telescope.pickers')
local finders = require('telescope.finders')
local conf = require('telescope.config').values
local M = {}
local entry_maker = function(item)
return {
display = item.label or item.value,
ordinal = item.label or item.value,
value = item.value,
}
end
M.choose = function(title, items, callback)
local opts = themes.get_dropdown{
previewer = false,
}
pickers.new(opts, {
prompt_title = title,
finder = finders.new_table {
results = items,
entry_maker = entry_maker,
},
sorter = conf.generic_sorter(opts),
attach_mappings = function(prompt_bufnr)
actions.select_default:replace(function()
local selection = actions.get_selected_entry()
actions.close(prompt_bufnr)
if type(callback) == "string" then
vim.call(callback, selection.value)
else
callback(selection.value)
end
end)
return true
end
}):find()
end
return M
|
local themes = require('telescope.themes')
local actions = require('telescope.actions')
local state = require('telescope.actions.state')
local pickers = require('telescope.pickers')
local finders = require('telescope.finders')
local conf = require('telescope.config').values
local M = {}
local entry_maker = function(item)
return {
display = item.label or item.value,
ordinal = item.label or item.value,
value = item.value,
}
end
M.choose = function(title, items, callback)
local opts = themes.get_dropdown{
previewer = false,
}
pickers.new(opts, {
prompt_title = title,
finder = finders.new_table {
results = items,
entry_maker = entry_maker,
},
sorter = conf.generic_sorter(opts),
attach_mappings = function(prompt_bufnr)
actions.select_default:replace(function()
local selection = state.get_selected_entry()
actions.close(prompt_bufnr)
if type(callback) == "string" then
vim.call(callback, selection.value)
else
callback(selection.value)
end
end)
return true
end
}):find()
end
return M
|
fix: update deprecated telescope API method
|
fix: update deprecated telescope API method
|
Lua
|
mit
|
stevearc/vim-arduino
|
096d41c6279d5822eefce35608883cda45784493
|
pud/level/TileLevelView.lua
|
pud/level/TileLevelView.lua
|
local Class = require 'lib.hump.class'
local LevelView = require 'pud.level.LevelView'
local MapUpdateFinishedEvent = require 'pud.event.MapUpdateFinishedEvent'
-- TileLevelView
-- draws tiles for each node in the level map to a framebuffer, which is then
-- drawn to screen
local TileLevelView = Class{name='TileLevelView',
inherits=LevelView,
function(self, mapW, mapH)
LevelView.construct(self)
verify('number', mapW, mapH)
self._tileW, self._tileH = 32, 32
self._set = Image.dungeon
local w, h = nearestPO2(mapW*self._tileW), nearestPO2(mapH*self._tileH)
self._fb = love.graphics.newFramebuffer(w, h)
self:_setupQuads()
end
}
-- destructor
function TileLevelView:destroy()
self:_clearQuads()
self._set = nil
LevelView.destroy(self)
end
-- make a quad from the given tile position
function TileLevelView:_makeQuad(mapType, variation, x, y)
variation = tostring(variation)
self._quads[mapType] = self._quads[mapType] or {}
self._quads[mapType][variation] = love.graphics.newQuad(
self._tileW*(x-1),
self._tileH*(y-1),
self._tileW,
self._tileH,
self._set:getWidth(),
self._set:getHeight())
end
function TileLevelView:_getQuad(node)
if self._quads then
local mapType = node:getMapType()
if not mapType:isType('empty') then
local mtype, variation = mapType:get()
if not variation then
if mapType:isType('wall') then
mtype = 'wall'
variation = 'V1'
elseif mapType:isType('floor') then
mtype = 'floor'
variation = '1'
elseif mapType:isType('torch') then
mtype = 'torch'
variation = 'A'
elseif mapType:isType('trap') then
mtype = 'trap'
variation = 'A'
elseif mapType:isType('stairUp')
or mapType:isType('stairDown')
or mapType:isType('doorOpen')
or mapType:isType('doorClosed')
then
variation = 1
end
end
if self._quads[mtype] then
return self._quads[mtype][variation]
end
end
end
return nil
end
-- clear the quads table
function TileLevelView:_clearQuads()
if self._quads then
for k,v in pairs(self._quads) do self._quads[k] = nil end
self._quads = nil
end
end
-- set up the quads
function TileLevelView:_setupQuads()
self:_clearQuads()
self._quads = {}
for i=1,4 do
self:_makeQuad('wall', 'H'..i, 1, i)
self:_makeQuad('wall', 'HWorn'..i, 2, i)
self:_makeQuad('wall', 'V'..i, 3, i)
self:_makeQuad('torch', 'A'..i, 4, i)
self:_makeQuad('torch', 'B'..i, 5, i)
self:_makeQuad('floor', i, 6, i)
self:_makeQuad('floor', 'Worn'..i, 7, i)
self:_makeQuad('floor', 'X'..i, 8, i)
self:_makeQuad('floor', 'Rug'..i, 9, i)
self:_makeQuad('stairUp', i, 10, i)
self:_makeQuad('stairDown', i, 11, i)
end
for i=1,5 do
self:_makeQuad('doorClosed', i, 12, i+(i-1))
self:_makeQuad('doorOpen', i, 12, i*2)
end
for i=1,6 do
self:_makeQuad('trap', 'A'..i, 13, i+(i-1))
self:_makeQuad('trap', 'B'..i, 13, i*2)
end
end
-- register for events that will cause this view to redraw
function TileLevelView:registerEvents()
local events = {
MapUpdateFinishedEvent,
}
GameEvent:register(self, events)
end
-- handle registered events as they are fired
function TileLevelView:onEvent(e, ...)
if e:is_a(MapUpdateFinishedEvent) then
self:drawToFB(e:getMap())
end
end
-- draw to the framebuffer
function TileLevelView:drawToFB(map)
if self._fb and self._set and map then
self._isDrawing = true
love.graphics.setRenderTarget(self._fb)
love.graphics.setColor(1,1,1)
for y=1,map:getHeight() do
local drawY = (y-1)*self._tileH
for x=1,map:getWidth() do
local node = map:getLocation(x, y)
local quad = self:_getQuad(node)
if quad then
local drawX = (x-1)*self._tileW
love.graphics.drawq(self._set, quad, drawX, drawY)
end
end
end
love.graphics.setRenderTarget()
self._isDrawing = false
end
end
-- draw the framebuffer to the screen
function TileLevelView:draw()
if self._fb and self._isDrawing == false then
love.graphics.setColor(1,1,1)
love.graphics.draw(self._fb)
end
end
-- the class
return TileLevelView
|
local Class = require 'lib.hump.class'
local LevelView = require 'pud.level.LevelView'
local MapUpdateFinishedEvent = require 'pud.event.MapUpdateFinishedEvent'
-- TileLevelView
-- draws tiles for each node in the level map to a framebuffer, which is then
-- drawn to screen
local TileLevelView = Class{name='TileLevelView',
inherits=LevelView,
function(self, mapW, mapH)
LevelView.construct(self)
verify('number', mapW, mapH)
self._tileW, self._tileH = 32, 32
self._set = Image.dungeon
local w, h = nearestPO2(mapW*self._tileW), nearestPO2(mapH*self._tileH)
self._fb = love.graphics.newFramebuffer(w, h)
self:_setupQuads()
end
}
-- destructor
function TileLevelView:destroy()
self:_clearQuads()
self._set = nil
LevelView.destroy(self)
end
-- make a quad from the given tile position
function TileLevelView:_makeQuad(mapType, variation, x, y)
variation = tostring(variation)
self._quads[mapType] = self._quads[mapType] or {}
self._quads[mapType][variation] = love.graphics.newQuad(
self._tileW*(x-1),
self._tileH*(y-1),
self._tileW,
self._tileH,
self._set:getWidth(),
self._set:getHeight())
end
function TileLevelView:_getQuad(node)
if self._quads then
local mapType = node:getMapType()
if not mapType:isType('empty') then
local mtype, variation = mapType:get()
if not variation then
if mapType:isType('wall') then
mtype = 'wall'
variation = 'V1'
elseif mapType:isType('floor') then
mtype = 'floor'
variation = '1'
elseif mapType:isType('torch') then
mtype = 'torch'
variation = 'A1'
elseif mapType:isType('trap') then
mtype = 'trap'
variation = 'A1'
elseif mapType:isType('stairUp')
or mapType:isType('stairDown')
or mapType:isType('doorOpen')
or mapType:isType('doorClosed')
then
variation = '1'
end
end
if self._quads[mtype] then
return self._quads[mtype][variation]
end
end
end
return nil
end
-- clear the quads table
function TileLevelView:_clearQuads()
if self._quads then
for k,v in pairs(self._quads) do self._quads[k] = nil end
self._quads = nil
end
end
-- set up the quads
function TileLevelView:_setupQuads()
self:_clearQuads()
self._quads = {}
for i=1,4 do
self:_makeQuad('wall', 'H'..i, 1, i)
self:_makeQuad('wall', 'HWorn'..i, 2, i)
self:_makeQuad('wall', 'V'..i, 3, i)
self:_makeQuad('torch', 'A'..i, 4, i)
self:_makeQuad('torch', 'B'..i, 5, i)
self:_makeQuad('floor', i, 6, i)
self:_makeQuad('floor', 'Worn'..i, 7, i)
self:_makeQuad('floor', 'X'..i, 8, i)
self:_makeQuad('floor', 'Rug'..i, 9, i)
self:_makeQuad('stairUp', i, 10, i)
self:_makeQuad('stairDown', i, 11, i)
end
for i=1,5 do
self:_makeQuad('doorClosed', i, i+(i-1), 5)
self:_makeQuad('doorOpen', i, i*2, 5)
end
for i=1,6 do
self:_makeQuad('trap', 'A'..i, i+(i-1), 6)
self:_makeQuad('trap', 'B'..i, i*2, 6)
end
end
-- register for events that will cause this view to redraw
function TileLevelView:registerEvents()
local events = {
MapUpdateFinishedEvent,
}
GameEvent:register(self, events)
end
-- handle registered events as they are fired
function TileLevelView:onEvent(e, ...)
if e:is_a(MapUpdateFinishedEvent) then
self:drawToFB(e:getMap())
end
end
-- draw to the framebuffer
function TileLevelView:drawToFB(map)
if self._fb and self._set and map then
self._isDrawing = true
love.graphics.setRenderTarget(self._fb)
love.graphics.setColor(1,1,1)
for y=1,map:getHeight() do
local drawY = (y-1)*self._tileH
for x=1,map:getWidth() do
local node = map:getLocation(x, y)
local quad = self:_getQuad(node)
if quad then
local drawX = (x-1)*self._tileW
love.graphics.drawq(self._set, quad, drawX, drawY)
elseif not node:getMapType():isType('empty') then
warning('no quad found for %s', tostring(node:getMapType()))
end
end
end
love.graphics.setRenderTarget()
self._isDrawing = false
end
end
-- draw the framebuffer to the screen
function TileLevelView:draw()
if self._fb and self._isDrawing == false then
love.graphics.setColor(1,1,1)
love.graphics.draw(self._fb)
end
end
-- the class
return TileLevelView
|
fix some maptypes not showing up
|
fix some maptypes not showing up
|
Lua
|
mit
|
scottcs/wyx
|
e5521dc82b65137dca21eacc1e4cfca0b06415bf
|
mods/mobs/mese_dragon.lua
|
mods/mobs/mese_dragon.lua
|
mobs:register_mob("mobs:mese_dragon", {
type = "monster",
-- agressive, deals 13 damage to player when hit
passive = false,
damage = 13,
attack_type = "dogshoot",
reach = 3,
shoot_interval = 2,
arrow = "mobs:mese_dragon_fireball",
shoot_offset = 2,
-- health & armor
hp_min = 175,
hp_max = 225,
armor = 70,
-- textures and model
collisionbox = {-0.6, 0, -0.6, 0.6, 5, 0.6},
visual = "mesh",
mesh = "mese_dragon.b3d",
textures = {
{"mese_dragon.png"},
},
visual_size = {x=3, y=3},
blood_texture = "default_mese_crystal_fragment.png",
-- sounds
makes_footstep_sound = true,
sounds = {
shoot_attack = "mesed",
attack = "mese_dragon",
distance = 60,
},
-- speed and jump
view_range = 20,
knock_back = 0,
walk_velocity = 1.5,
run_velocity = 3.5,
pathfinding = false,
jump = true,
jump_height = 4,
fall_damage = 0,
fall_speed = -6,
stepheight = 1.5,
-- drops returnmirror & mese & class items when dead
drops = {
-- Ressource & Decoration drops
{name = "default:mese", chance = 2, min = 2, max = 4},
{name = "returnmirror:mirror_inactive", chance = 10, min = 1, max = 1},
-- Tools drops
{name = "default:pick_mese", chance = 33, min = 1, max = 1},
{name = "default:shovel_mese", chance = 33, min = 1, max = 1},
{name = "default:axe_mese", chance = 33, min = 1, max = 1},
{name = "farming:hoe_mese", chance = 33, min = 1, max = 1},
-- Hunter drops
{name = "3d_armor:leggings_hardenedleather", chance = 10, min = 1, max = 1},
{name = "3d_armor:boots_hardenedleather", chance = 10, min = 1, max = 1},
{name = "throwing:arbalest", chance = 33, min = 1, max = 1},
-- Warrior drops
{name = "3d_armor:leggings_mithril", chance = 10, min = 1, max = 1},
{name = "3d_armor:boots_mithril", chance = 10, min = 1, max = 1},
{name = "default:sword_mese", chance = 33, min = 1, max = 1},
},
-- damaged by
water_damage = 0,
lava_damage = 0,
light_damage = 0,
-- model animation
animation = {
speed_normal = 15,
speed_run = 15,
stand_start = 0,
stand_end = 80,
walk_start = 180,
walk_end = 200,
run_start = 180,
run_end = 200,
punch_start = 140,
punch_end = 170,
},
})
-- mese_dragon_fireball (weapon)
mobs:register_arrow("mobs:mese_dragon_fireball", {
visual = "sprite",
visual_size = {x = 1, y = 1},
textures = {"mobs_mese_dragon_fireball.png"},
velocity = 8,
-- direct hit, no fire... just plenty of pain
hit_player = function(self, player)
player:punch(self.object, 1.0, { -- Mettre à 2.0 aussi ?
full_punch_interval = 2.0, -- Modif MFF
damage_groups = {fleshy = 13}, -- Modif MFF
}, nil)
end,
hit_mob = function(self, player)
player:punch(self.object, 1.0, { -- Mettre à 2.0 aussi ?
full_punch_interval = 2.0, -- Modif MFF
damage_groups = {fleshy = 13}, -- Modif MFF
}, nil)
end,
-- node hit, bursts into flame
hit_node = function(self, pos, node)
mobs:explosion(pos, 1, 1, 0)
end
})
minetest.register_node("mobs:mese_dragon_spawner", {
description = "Mese Dragon Spawner",
tiles = {"default_mese_block.png"},
is_ground_content = false,
groups = {unbreakable = 1, mob_spawner=1},
sounds = default.node_sound_stone_defaults({
dug = {name="mobs_boom", gain=0.25} -- to be changed
})
})
--(name, nodes, neighbors, min_light, max_light, interval, chance, active_object_count, min_height, max_height, spawn_in_area)
-- spawn on mobs:mese_dragon_spawner between 1 and 20 light, interval 300, 1 chance, 1 mese_dragon_spawner in area up to 31000 in height
mobs:spawn_specific("mobs:mese_dragon", {"mobs:mese_dragon_spawner"}, {"air"}, 1, 20, 300, 1, 100, -31000, 31000, true)
mobs:register_egg("mobs:mese_dragon", "Mese Dragon", "mobs_mese_dragon_inv.png", 1)
|
mobs:register_mob("mobs:mese_dragon", {
type = "monster",
-- agressive, deals 13 damage to player when hit
passive = false,
damage = 13,
attack_type = "dogshoot",
reach = 4,
shoot_interval = 2,
arrow = "mobs:mese_dragon_fireball",
shoot_offset = 2,
-- health & armor
hp_min = 175,
hp_max = 225,
armor = 70,
-- textures and model
collisionbox = {-0.6, 0, -0.6, 0.6, 5, 0.6},
visual = "mesh",
mesh = "mese_dragon.b3d",
textures = {
{"mese_dragon.png"},
},
visual_size = {x=3, y=3},
blood_texture = "default_mese_crystal_fragment.png",
-- sounds
makes_footstep_sound = true,
sounds = {
shoot_attack = "mesed",
attack = "mese_dragon",
distance = 60,
},
-- speed and jump
view_range = 20,
knock_back = 0,
walk_velocity = 1.5,
run_velocity = 3.5,
pathfinding = false,
jump = true,
jump_height = 4,
fall_damage = 0,
fall_speed = -6,
stepheight = 1.5,
-- drops returnmirror & mese & class items when dead
drops = {
-- Ressource & Decoration drops
{name = "default:mese", chance = 2, min = 2, max = 4},
{name = "returnmirror:mirror_inactive", chance = 10, min = 1, max = 1},
-- Tools drops
{name = "default:pick_mese", chance = 33, min = 1, max = 1},
{name = "default:shovel_mese", chance = 33, min = 1, max = 1},
{name = "default:axe_mese", chance = 33, min = 1, max = 1},
{name = "farming:hoe_mese", chance = 33, min = 1, max = 1},
-- Hunter drops
{name = "3d_armor:leggings_hardenedleather", chance = 10, min = 1, max = 1},
{name = "3d_armor:boots_hardenedleather", chance = 10, min = 1, max = 1},
{name = "throwing:arbalest", chance = 33, min = 1, max = 1},
-- Warrior drops
{name = "3d_armor:leggings_mithril", chance = 10, min = 1, max = 1},
{name = "3d_armor:boots_mithril", chance = 10, min = 1, max = 1},
{name = "default:sword_mese", chance = 33, min = 1, max = 1},
},
-- damaged by
water_damage = 0,
lava_damage = 0,
light_damage = 0,
-- model animation
animation = {
speed_normal = 15,
speed_run = 15,
stand_start = 0,
stand_end = 80,
walk_start = 180,
walk_end = 200,
run_start = 180,
run_end = 200,
punch_start = 140,
punch_end = 170,
},
})
-- mese_dragon_fireball (weapon)
mobs:register_arrow("mobs:mese_dragon_fireball", {
visual = "sprite",
visual_size = {x = 1, y = 1},
textures = {"mobs_mese_dragon_fireball.png"},
velocity = 8,
-- direct hit, no fire... just plenty of pain
hit_player = function(self, player)
player:punch(self.object, 2.0, { -- Modif MFF
full_punch_interval = 2.0, -- Modif MFF
damage_groups = {fleshy = 13}, -- Modif MFF
}, nil)
end,
hit_mob = function(self, player)
player:punch(self.object, 2.0, { -- Modif MFF
full_punch_interval = 2.0, -- Modif MFF
damage_groups = {fleshy = 13}, -- Modif MFF
}, nil)
end,
-- node hit, bursts into flame
hit_node = function(self, pos, node)
mobs:explosion(pos, 1, 1, 0)
end
})
minetest.register_node("mobs:mese_dragon_spawner", {
description = "Mese Dragon Spawner",
tiles = {"default_mese_block.png"},
is_ground_content = false,
groups = {unbreakable = 1, mob_spawner=1},
sounds = default.node_sound_stone_defaults({
dug = {name="mobs_boom", gain=0.25} -- to be changed
})
})
--(name, nodes, neighbors, min_light, max_light, interval, chance, active_object_count, min_height, max_height, spawn_in_area)
-- spawn on mobs:mese_dragon_spawner between 1 and 20 light, interval 300, 1 chance, 1 mese_dragon_spawner in area up to 31000 in height
mobs:spawn_specific("mobs:mese_dragon", {"mobs:mese_dragon_spawner"}, {"air"}, 1, 20, 300, 1, 100, -31000, 31000, true)
mobs:register_egg("mobs:mese_dragon", "Mese Dragon", "mobs_mese_dragon_inv.png", 1)
|
Mese dragon fixes
|
Mese dragon fixes
Ok, last bug with the mese dragon : the fireball don't hit the player, there are too y+1 or y+2 to the player colisionbox, need to add a offset
|
Lua
|
unlicense
|
MinetestForFun/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,Ombridride/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,Coethium/server-minetestforfun,crabman77/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,MinetestForFun/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,sys4-fr/server-minetestforfun,Ombridride/minetest-minetestforfun-server,Coethium/server-minetestforfun,Gael-de-Sailly/minetest-minetestforfun-server,Coethium/server-minetestforfun,LeMagnesium/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,Gael-de-Sailly/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun
|
d2f793a9813bf0a6095fbfdcf2767c72b3d50e53
|
libs/web/luasrc/dispatcher.lua
|
libs/web/luasrc/dispatcher.lua
|
--[[
LuCI - Dispatcher
Description:
The request dispatcher and module dispatcher generators
FileId:
$Id$
License:
Copyright 2008 Steven Barth <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
module("luci.dispatcher", package.seeall)
require("luci.http")
require("luci.sys")
require("luci.fs")
-- Local dispatch database
local tree = {nodes={}}
-- Index table
local index = {}
-- Indexdump
local indexcache = "/tmp/.luciindex"
-- Global request object
request = {}
-- Active dispatched node
dispatched = nil
-- Status fields
built_index = false
built_tree = false
-- Builds a URL
function build_url(...)
return luci.http.dispatcher() .. "/" .. table.concat(arg, "/")
end
-- Sends a 404 error code and renders the "error404" template if available
function error404(message)
luci.http.status(404, "Not Found")
message = message or "Not Found"
require("luci.template")
if not pcall(luci.template.render, "error404") then
luci.http.prepare_content("text/plain")
print(message)
end
return false
end
-- Sends a 500 error code and renders the "error500" template if available
function error500(message)
luci.http.status(500, "Internal Server Error")
require("luci.template")
if not pcall(luci.template.render, "error500", {message=message}) then
luci.http.prepare_content("text/plain")
print(message)
end
return false
end
-- Creates a request object for dispatching
function httpdispatch()
local pathinfo = luci.http.env.PATH_INFO or ""
local c = tree
for s in pathinfo:gmatch("([%w_]+)") do
table.insert(request, s)
end
dispatch()
end
-- Dispatches a request
function dispatch()
if not built_tree then
createtree()
end
local c = tree
local track = {}
for i, s in ipairs(request) do
c = c.nodes[s]
if not c then
break
end
for k, v in pairs(c) do
track[k] = v
end
end
if track.i18n then
require("luci.i18n").loadc(track.i18n)
end
if track.setgroup then
luci.sys.process.setgroup(track.setgroup)
end
if track.setuser then
luci.sys.process.setuser(track.setuser)
end
-- Init template engine
local tpl = require("luci.template")
tpl.viewns.translate = function(...) return require("luci.i18n").translate(...) end
tpl.viewns.controller = luci.http.dispatcher()
tpl.viewns.uploadctrl = luci.http.dispatcher_upload()
tpl.viewns.media = luci.config.main.mediaurlbase
tpl.viewns.resource = luci.config.main.resourcebase
-- Load default translation
require("luci.i18n").loadc("default")
if c and type(c.target) == "function" then
dispatched = c
stat, err = pcall(c.target)
if not stat then
error500(err)
end
else
error404()
end
end
-- Generates the dispatching tree
function createindex()
index = {}
local path = luci.sys.libpath() .. "/controller/"
local suff = ".lua"
if pcall(require, "fastindex") then
createindex_fastindex(path, suff)
else
createindex_plain(path, suff)
end
built_index = true
end
-- Uses fastindex to create the dispatching tree
function createindex_fastindex(path, suffix)
local fi = fastindex.new("index")
fi.add(path .. "*" .. suffix)
fi.add(path .. "*/*" .. suffix)
fi.scan()
for k, v in pairs(fi.indexes) do
index[v[2]] = v[1]
end
end
-- Calls the index function of all available controllers
function createindex_plain(path, suffix)
local cachetime = nil
local controllers = luci.util.combine(
luci.fs.glob(path .. "*" .. suffix) or {},
luci.fs.glob(path .. "*/*" .. suffix) or {}
)
if indexcache then
cachetime = luci.fs.mtime(indexcache)
if not cachetime then
luci.fs.mkdir(indexcache)
luci.fs.chmod(indexcache, "a=,u=rwx")
end
end
if not cachetime or luci.fs.mtime(path) > cachetime then
for i,c in ipairs(controllers) do
c = "luci.controller." .. c:sub(#path+1, #c-#suffix):gsub("/", ".")
stat, mod = pcall(require, c)
if stat and mod and type(mod.index) == "function" then
index[c] = mod.index
if indexcache then
luci.fs.writefile(indexcache .. "/" .. c, string.dump(mod.index))
end
end
end
if indexcache then
luci.fs.unlink(indexcache .. "/.index")
luci.fs.writefile(indexcache .. "/.index", "")
end
else
for i,c in ipairs(luci.fs.dir(indexcache)) do
if c:sub(1) ~= "." then
index[c] = loadfile(indexcache .. "/" .. c)
end
end
end
end
-- Creates the dispatching tree from the index
function createtree()
if not built_index then
createindex()
end
for k, v in pairs(index) do
luci.util.updfenv(v, _M)
local stat, mod = pcall(require, k)
if stat then
luci.util.updfenv(v, mod)
end
pcall(v)
end
built_tree = true
end
-- Shortcut for creating a dispatching node
function entry(path, target, title, order, add)
add = add or {}
local c = node(path)
c.target = target
c.title = title
c.order = order
for k,v in pairs(add) do
c[k] = v
end
return c
end
-- Fetch a dispatching node
function node(...)
local c = tree
if arg[1] and type(arg[1]) == "table" then
arg = arg[1]
end
for k,v in ipairs(arg) do
if not c.nodes[v] then
c.nodes[v] = {nodes={}}
end
c = c.nodes[v]
end
return c
end
-- Subdispatchers --
function alias(...)
local req = arg
return function()
request = req
dispatch()
end
end
function template(name)
require("luci.template")
return function() luci.template.render(name) end
end
function cbi(model)
require("luci.cbi")
require("luci.template")
return function()
local stat, res = pcall(luci.cbi.load, model)
if not stat then
error500(res)
return true
end
local stat, err = pcall(res.parse, res)
if not stat then
error500(err)
return true
end
luci.template.render("cbi/header")
res:render()
luci.template.render("cbi/footer")
end
end
|
--[[
LuCI - Dispatcher
Description:
The request dispatcher and module dispatcher generators
FileId:
$Id$
License:
Copyright 2008 Steven Barth <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
module("luci.dispatcher", package.seeall)
require("luci.http")
require("luci.sys")
require("luci.fs")
-- Local dispatch database
local tree = {nodes={}}
-- Index table
local index = {}
-- Indexdump
local indexcache = "/tmp/.luciindex"
-- Global request object
request = {}
-- Active dispatched node
dispatched = nil
-- Status fields
built_index = false
built_tree = false
-- Builds a URL
function build_url(...)
return luci.http.dispatcher() .. "/" .. table.concat(arg, "/")
end
-- Sends a 404 error code and renders the "error404" template if available
function error404(message)
luci.http.status(404, "Not Found")
message = message or "Not Found"
require("luci.template")
if not pcall(luci.template.render, "error404") then
luci.http.prepare_content("text/plain")
print(message)
end
return false
end
-- Sends a 500 error code and renders the "error500" template if available
function error500(message)
luci.http.status(500, "Internal Server Error")
require("luci.template")
if not pcall(luci.template.render, "error500", {message=message}) then
luci.http.prepare_content("text/plain")
print(message)
end
return false
end
-- Creates a request object for dispatching
function httpdispatch()
local pathinfo = luci.http.env.PATH_INFO or ""
local c = tree
for s in pathinfo:gmatch("([%w_]+)") do
table.insert(request, s)
end
dispatch()
end
-- Dispatches a request
function dispatch()
if not built_tree then
createtree()
end
local c = tree
local track = {}
for i, s in ipairs(request) do
c = c.nodes[s]
if not c then
break
end
for k, v in pairs(c) do
track[k] = v
end
end
if track.i18n then
require("luci.i18n").loadc(track.i18n)
end
if track.setgroup then
luci.sys.process.setgroup(track.setgroup)
end
if track.setuser then
luci.sys.process.setuser(track.setuser)
end
-- Init template engine
local tpl = require("luci.template")
tpl.viewns.translate = function(...) return require("luci.i18n").translate(...) end
tpl.viewns.controller = luci.http.dispatcher()
tpl.viewns.uploadctrl = luci.http.dispatcher_upload()
tpl.viewns.media = luci.config.main.mediaurlbase
tpl.viewns.resource = luci.config.main.resourcebase
-- Load default translation
require("luci.i18n").loadc("default")
if c and type(c.target) == "function" then
dispatched = c
stat, err = pcall(c.target)
if not stat then
error500(err)
end
else
error404()
end
end
-- Generates the dispatching tree
function createindex()
index = {}
local path = luci.sys.libpath() .. "/controller/"
local suff = ".lua"
if pcall(require, "fastindex") then
createindex_fastindex(path, suff)
else
createindex_plain(path, suff)
end
built_index = true
end
-- Uses fastindex to create the dispatching tree
function createindex_fastindex(path, suffix)
local fi = fastindex.new("index")
fi.add(path .. "*" .. suffix)
fi.add(path .. "*/*" .. suffix)
fi.scan()
for k, v in pairs(fi.indexes) do
index[v[2]] = v[1]
end
end
-- Calls the index function of all available controllers
function createindex_plain(path, suffix)
local cachetime = nil
local controllers = luci.util.combine(
luci.fs.glob(path .. "*" .. suffix) or {},
luci.fs.glob(path .. "*/*" .. suffix) or {}
)
if indexcache then
cachetime = luci.fs.mtime(indexcache)
if not cachetime then
luci.fs.mkdir(indexcache)
luci.fs.chmod(indexcache, "a=,u=rwx")
end
end
if not cachetime then
for i,c in ipairs(controllers) do
c = "luci.controller." .. c:sub(#path+1, #c-#suffix):gsub("/", ".")
stat, mod = pcall(require, c)
if stat and mod and type(mod.index) == "function" then
index[c] = mod.index
if indexcache then
luci.fs.writefile(indexcache .. "/" .. c, string.dump(mod.index))
end
end
end
else
for i,c in ipairs(luci.fs.dir(indexcache)) do
if c:sub(1) ~= "." then
index[c] = loadfile(indexcache .. "/" .. c)
end
end
end
end
-- Creates the dispatching tree from the index
function createtree()
if not built_index then
createindex()
end
for k, v in pairs(index) do
luci.util.updfenv(v, _M)
local stat, mod = pcall(require, k)
if stat then
luci.util.updfenv(v, mod)
end
pcall(v)
end
built_tree = true
end
-- Shortcut for creating a dispatching node
function entry(path, target, title, order, add)
add = add or {}
local c = node(path)
c.target = target
c.title = title
c.order = order
for k,v in pairs(add) do
c[k] = v
end
return c
end
-- Fetch a dispatching node
function node(...)
local c = tree
if arg[1] and type(arg[1]) == "table" then
arg = arg[1]
end
for k,v in ipairs(arg) do
if not c.nodes[v] then
c.nodes[v] = {nodes={}}
end
c = c.nodes[v]
end
return c
end
-- Subdispatchers --
function alias(...)
local req = arg
return function()
request = req
dispatch()
end
end
function template(name)
require("luci.template")
return function() luci.template.render(name) end
end
function cbi(model)
require("luci.cbi")
require("luci.template")
return function()
local stat, res = pcall(luci.cbi.load, model)
if not stat then
error500(res)
return true
end
local stat, err = pcall(res.parse, res)
if not stat then
error500(err)
return true
end
luci.template.render("cbi/header")
res:render()
luci.template.render("cbi/footer")
end
end
|
* Fixed caching mechanism
|
* Fixed caching mechanism
|
Lua
|
apache-2.0
|
deepak78/luci,deepak78/luci,deepak78/luci,8devices/luci,8devices/luci,deepak78/luci,8devices/luci,8devices/luci,deepak78/luci,8devices/luci,deepak78/luci,deepak78/luci,8devices/luci,deepak78/luci
|
f54b7fb3d3457d8f9369fd5766b70b92e81515de
|
gui.lua
|
gui.lua
|
--[[#########################################
-- GUI and main menu are in here
--#########################################
-- elements for the main menu:
-- *start new game
--- -> go to first mission
-- * continue/load game
--- -> choose save file
-- *settings
--- -> sound, resolution, ...
-- *Quit -> stops the game
--]]
gui={}
gui.current = nil
buttonDetected=0
guiScale = 2.0
-- GameStates:0=MainMenu, 1=inGame, 2=Load, 3=Settings, 4=Game Over
font = love.graphics.newFont(32)
love.graphics.setFont(font)
local screenWidth = love.window.getWidth()
local screenHeight = love.window.getHeight()
local buttonsizeh = 200
local buttonsizev = 100
local buttons = {}
buttonNames = {"Start", "Load", "Settings", "Quit"}
gui.imgLogo = love.graphics.newImage("resources/sprites/ui/logo.png")
gui.imgBackground = love.graphics.newImage("resources/sprites/ui/menu_background.png")
gui.imgMiddleground = love.graphics.newImage("resources/sprites/ui/menu_middleground.png")
local activemenu = {
start = false,
load = false,
settings = false,
quit = false
}
function love.mousepressed(x, y, key)
if(key=="l") then
buttonDetected=1
love.turris.checkleftclick(x,y)
end
if(key=="r") then
buttonDetected=2
love.turris.checkrightclick(x,y)
end
end
--Function to look if Mousbutton is over an button
function gui.mouseMove()
local mouseXPos = love.mouse.getX()
local mouseYPos = love.mouse.getX()
--Check if Mouse is over an button
for i = 1, #buttons do
--Check if mouse is over Button
if buttons[i].isOverButton(mouseXPos,mouseYPos) then
buttons[i].hover = true
else
buttons[i].hover = false
end
end
end
--Updates Everything in the GUI --TODO-- PLZ ADD ALL OTHER METHODS
function gui.update()
gui.mouseMove()
end
function gui.isinbutton(clickx,clicky)
for i = 1, #buttons do
if buttons[i].isOverButton(clickx, clicky) == true then
if buttons[i].name == "Start" then
activemenu.start = true
elseif buttons[i].name == "Load" then
activemenu.load = true
elseif buttons[i].name == "Settings" then
activemenu.settings = true
elseif buttons[i].name == "Quit" then
activemenu.quit = true
end
end
end
end
--Button class
-- This Class is a Button with all its Attributes
-- @param xPos
-- @param yPos
-- @param width
-- @param height
-- @param name The Name of the button
function gui.button(xPos, yPos, width, height, name)
local o = {}
--Attribute
o.xPos = xPos
o.yPos = yPos
o.width = width
o.height = height
o.name = name
o.status = false
o.hover = false
--Returns true if the Position is inside an Button
function o.isOverButton(mouseX, mouseY)
if mouseX > xPos and mouseX < xPos + width and mouseY > yPos and mouseY < yPos + height then
return true
else
return false
end
end
return o
end
--Function to Create Buttons
-- Usses The Array buttonNames to Crate The buttons
function gui.createButtons()
local startx = screenWidth / 2 - (buttonsizeh / 2)
local starty = 128
local buttonDistance = screenHeight / 5 - (buttonsizev)
--Creates the buttons and pushes it into the buttons array
for i = 1, #buttonNames do
buttons[#buttons +1] = gui.button(startx,starty,buttonsizeh,buttonsizev,buttonNames[i])
starty = starty + (buttonDistance + buttonsizev)
buttons[#buttons +1] = gui.button(startx, starty, buttonsizeh, buttonsizev, buttonNames[i])
starty = starty + 80
end
end
function love.turris.checkleftclick(clickx,clicky)
currentgstate=love.getgamestate()
if currentgstate == 0 then--MainMenu
gui.isinbutton(clickx,clicky)
love.turris.mainmenubuttonpushed()
elseif currentgstate == 1 then --ingame
--love.setgamestate(0)
local clickedfieldx,clickedfieldy=getclickedfield(clickx,clicky)
print(clickedfield)
turGame.addTower(clickedfieldx,clickedfieldy,1)
elseif currentgstate == 4 then --game over
love.turris.gameoverstate()
end
end
function getclickedfield(clickx,clicky)
local x=((clickx-turGame.offsetX)-((clickx-turGame.offsetX)%turMap.tileWidth))/turMap.tileWidth+1
local y=((clicky-turGame.offsetY)-((clicky-turGame.offsetY)%turMap.tileHeight))/turMap.tileHeight+1
print("clicked field "..x..", "..y)
return x,y
end
function love.turris.checkrightclick(clickx,clicky)
currentgstate=love.getgamestate()
if currentgamestate==1 then --ingame
local clickedfieldx,clickedfieldy=getclickedfield(clickx,clicky)
turGame.removeTower(clickedfieldx,clickedfieldy)
--turMap.setState(clickedfieldx,clickedfieldy,0)
--turrets will be removed
end
end
function gui.drawMainMenu()
local buttonDistance = 30
love.graphics.setColor(255, 255, 255)
--love.graphics.setColor(0, 0, 0, 91)
--love.graphics.rectangle("fill", buttons[1].xPos - 16, buttons[1].yPos - 16, buttons[1].width + 32, buttons[1].height * 4 + 92)
local timer = math.sin(love.timer.getTime())
G.draw(gui.imgBackground)
G.draw(gui.imgMiddleground)
G.draw(gui.imgLogo, gui.imgLogo:getWidth() * 0.5, gui.imgLogo:getHeight() * 0.5, timer * 0.1, 1, 1, gui.imgLogo:getWidth() * 0.5, gui.imgLogo:getHeight() * 0.5)
for i = 1, #buttons do
--G.setBlendMode("alpha")
--love.graphics.setColor(0, 0, 0, 91)
--love.graphics.setLineWidth(8)
--love.graphics.rectangle("line", buttons[i].xPos, buttons[i].yPos, buttons[i].width, buttons[i].height)
--G.setBlendMode("additive")
--love.graphics.setColor(0, 127, 255)
--love.graphics.setLineWidth(4)
--love.graphics.rectangle("line", buttons[i].xPos, buttons[i].yPos, buttons[i].width, buttons[i].height)
--startText
G.setBlendMode("alpha")
love.graphics.setColor(0, 0, 0, 91)
love.graphics.printf(buttons[i].name, buttons[i].xPos + 2,buttons[i].yPos + buttons[i].height / 3 + 2, buttons[i].width, "center")
G.setBlendMode("additive")
love.graphics.setColor(255, 127, 0)
love.graphics.printf(buttons[i].name, buttons[i].xPos,buttons[i].yPos + buttons[i].height / 3, buttons[i].width, "center")
end
end
function love.turris.mainmenubuttonpushed()
if(activemenu.start==true) then
love.sounds.playSound("sounds/button_pressed.wav")
love.turris.startGame()
elseif(activemenu.load==true) then
love.sounds.playSound("sounds/button_deactivated.wav")
love.turris.showLoadWindow()
elseif(activemenu.settings) then
love.sounds.playSound("sounds/button_deactivated.wav")
love.turris.openSettings()
elseif(activemenu.quit) then
love.sounds.playSound("sounds/button_pressed.wav")
love.turris.quitGame()
end
activemenu.start = false
activemenu.load = false
activemenu.settings = false
activemenu.quit = false
end
function love.turris.startGame()
love.setgamestate(1)
end
function love.turris.showLoadWindow() -- show list with all savestates or save files
print("Saving and loading the game is not yet implemented")
local savestates = {
save1 = "save 1",
save2 = "save 2",
save3 = "save 3"
}
end
function love.turris.openSettings()
print("settings are not yet implemented")
--reload main screen, recalculate button positions!!
end
function love.turris.quitGame()
love.event.quit()
end
|
--[[#########################################
-- GUI and main menu are in here
--#########################################
-- elements for the main menu:
-- *start new game
--- -> go to first mission
-- * continue/load game
--- -> choose save file
-- *settings
--- -> sound, resolution, ...
-- *Quit -> stops the game
--]]
gui={}
gui.current = nil
buttonDetected=0
guiScale = 2.0
-- GameStates:0=MainMenu, 1=inGame, 2=Load, 3=Settings, 4=Game Over
font = love.graphics.newFont(32)
love.graphics.setFont(font)
local screenWidth = love.window.getWidth()
local screenHeight = love.window.getHeight()
local buttonsizeh = 200
local buttonsizev = 100
local buttons = {}
buttonNames = {"Start", "Load", "Settings", "Quit"}
gui.imgLogo = love.graphics.newImage("resources/sprites/ui/logo.png")
gui.imgBackground = love.graphics.newImage("resources/sprites/ui/menu_background.png")
gui.imgMiddleground = love.graphics.newImage("resources/sprites/ui/menu_middleground.png")
local activemenu = {
start = false,
load = false,
settings = false,
quit = false
}
function love.mousepressed(x, y, key)
if(key=="l") then
buttonDetected=1
love.turris.checkleftclick(x,y)
end
if(key=="r") then
buttonDetected=2
love.turris.checkrightclick(x,y)
end
end
--Function to look if Mousbutton is over an button
function gui.mouseMove()
local mouseXPos = love.mouse.getX()
local mouseYPos = love.mouse.getX()
--Check if Mouse is over an button
for i = 1, #buttons do
--Check if mouse is over Button
if buttons[i].isOverButton(mouseXPos,mouseYPos) then
buttons[i].hover = true
else
buttons[i].hover = false
end
end
end
--Updates Everything in the GUI --TODO-- PLZ ADD ALL OTHER METHODS
function gui.update()
gui.mouseMove()
end
function gui.isinbutton(clickx,clicky)
for i = 1, #buttons do
if buttons[i].isOverButton(clickx, clicky) == true then
if buttons[i].name == "Start" then
activemenu.start = true
elseif buttons[i].name == "Load" then
activemenu.load = true
elseif buttons[i].name == "Settings" then
activemenu.settings = true
elseif buttons[i].name == "Quit" then
activemenu.quit = true
end
end
end
end
--Button class
-- This Class is a Button with all its Attributes
-- @param xPos
-- @param yPos
-- @param width
-- @param height
-- @param name The Name of the button
function gui.button(xPos, yPos, width, height, name)
local o = {}
--Attribute
o.xPos = xPos
o.yPos = yPos
o.width = width
o.height = height
o.name = name
o.status = false
o.hover = false
--Returns true if the Position is inside an Button
function o.isOverButton(mouseX, mouseY)
if mouseX > xPos and mouseX < xPos + width and mouseY > yPos and mouseY < yPos + height then
return true
else
return false
end
end
return o
end
--Function to Create Buttons
-- Usses The Array buttonNames to Crate The buttons
function gui.createButtons()
local startx = screenWidth / 2 - (buttonsizeh / 2)
local starty = 128
local buttonDistance = screenHeight / 5 - (buttonsizev)
--Creates the buttons and pushes it into the buttons array
for i = 1, #buttonNames do
buttons[#buttons + 1] = gui.button(startx, starty, buttonsizeh, buttonsizev, buttonNames[i])
starty = starty + 80
end
end
function love.turris.checkleftclick(clickx,clicky)
currentgstate=love.getgamestate()
if currentgstate == 0 then--MainMenu
gui.isinbutton(clickx,clicky)
love.turris.mainmenubuttonpushed()
elseif currentgstate == 1 then --ingame
--love.setgamestate(0)
local clickedfieldx,clickedfieldy=getclickedfield(clickx,clicky)
print(clickedfield)
turGame.addTower(clickedfieldx,clickedfieldy,1)
elseif currentgstate == 4 then --game over
love.turris.gameoverstate()
end
end
function getclickedfield(clickx,clicky)
local x=((clickx-turGame.offsetX)-((clickx-turGame.offsetX)%turMap.tileWidth))/turMap.tileWidth+1
local y=((clicky-turGame.offsetY)-((clicky-turGame.offsetY)%turMap.tileHeight))/turMap.tileHeight+1
print("clicked field "..x..", "..y)
return x,y
end
function love.turris.checkrightclick(clickx,clicky)
currentgstate=love.getgamestate()
if currentgamestate==1 then --ingame
local clickedfieldx,clickedfieldy=getclickedfield(clickx,clicky)
turGame.removeTower(clickedfieldx,clickedfieldy)
--turMap.setState(clickedfieldx,clickedfieldy,0)
--turrets will be removed
end
end
function gui.drawMainMenu()
local buttonDistance = 30
love.graphics.setColor(255, 255, 255)
--love.graphics.setColor(0, 0, 0, 91)
--love.graphics.rectangle("fill", buttons[1].xPos - 16, buttons[1].yPos - 16, buttons[1].width + 32, buttons[1].height * 4 + 92)
local timer = math.sin(love.timer.getTime())
G.draw(gui.imgBackground)
G.draw(gui.imgMiddleground)
G.draw(gui.imgLogo, gui.imgLogo:getWidth() * 0.5, gui.imgLogo:getHeight() * 0.5, timer * 0.1, 1, 1, gui.imgLogo:getWidth() * 0.5, gui.imgLogo:getHeight() * 0.5)
for i = 1, #buttons do
--G.setBlendMode("alpha")
--love.graphics.setColor(0, 0, 0, 91)
--love.graphics.setLineWidth(8)
--love.graphics.rectangle("line", buttons[i].xPos, buttons[i].yPos, buttons[i].width, buttons[i].height)
--G.setBlendMode("additive")
--love.graphics.setColor(0, 127, 255)
--love.graphics.setLineWidth(4)
--love.graphics.rectangle("line", buttons[i].xPos, buttons[i].yPos, buttons[i].width, buttons[i].height)
--startText
G.setBlendMode("alpha")
love.graphics.setColor(0, 0, 0, 91)
love.graphics.printf(buttons[i].name, buttons[i].xPos + 2,buttons[i].yPos + buttons[i].height / 3 + 2, buttons[i].width, "center")
G.setBlendMode("additive")
love.graphics.setColor(255, 127, 0)
love.graphics.printf(buttons[i].name, buttons[i].xPos,buttons[i].yPos + buttons[i].height / 3, buttons[i].width, "center")
end
end
function love.turris.mainmenubuttonpushed()
if(activemenu.start==true) then
love.sounds.playSound("sounds/button_pressed.wav")
love.turris.startGame()
elseif(activemenu.load==true) then
love.sounds.playSound("sounds/button_deactivated.wav")
love.turris.showLoadWindow()
elseif(activemenu.settings) then
love.sounds.playSound("sounds/button_deactivated.wav")
love.turris.openSettings()
elseif(activemenu.quit) then
love.sounds.playSound("sounds/button_pressed.wav")
love.turris.quitGame()
end
activemenu.start = false
activemenu.load = false
activemenu.settings = false
activemenu.quit = false
end
function love.turris.startGame()
love.setgamestate(1)
end
function love.turris.showLoadWindow() -- show list with all savestates or save files
print("Saving and loading the game is not yet implemented")
local savestates = {
save1 = "save 1",
save2 = "save 2",
save3 = "save 3"
}
end
function love.turris.openSettings()
print("settings are not yet implemented")
--reload main screen, recalculate button positions!!
end
function love.turris.quitGame()
love.event.quit()
end
|
fixes
|
fixes
|
Lua
|
mit
|
sam1i/Turres-Monacorum,sam1i/Turres-Monacorum
|
c89289d13fbe3586a88c254756ec94202967b013
|
src/apps/ipfix/maps.lua
|
src/apps/ipfix/maps.lua
|
module(..., package.seeall)
local ffi = require("ffi")
local lib = require("core.lib")
local ctable = require("lib.ctable")
local ethernet = require("lib.protocol.ethernet")
local ipv4 = require("lib.protocol.ipv4")
local poptrie = require("lib.poptrie")
local logger = require("lib.logger")
-- Map MAC addresses to peer AS number
--
-- Used to determine bgpPrevAdjacentAsNumber, bgpNextAdjacentAsNumber
-- from the packet's MAC addresses. File format:
-- <AS>-<MAC>
local mac_to_as_key_t = ffi.typeof("uint8_t[6]")
local mac_to_as_value_t = ffi.typeof("uint32_t")
local function make_mac_to_as_map(name)
local table = ctable.new({ key_type = mac_to_as_key_t,
value_type = mac_to_as_value_t,
initial_size = 15000,
max_displacement_limit = 30 })
local key = mac_to_as_key_t()
local value = mac_to_as_value_t()
for line in assert(io.lines(name)) do
local as, mac = line:match("^%s*(%d*)-([0-9a-fA-F:]*)")
assert(as and mac, "MAC-to-AS map: invalid line: "..line)
local key, value = ethernet:pton(mac), tonumber(as)
local result = table:lookup_ptr(key)
if result then
if result.value ~= value then
print("MAC-to-AS map: amibguous mapping: "
..ethernet:ntop(key)..": "..result.value..", "..value)
end
end
table:add(key, value, true)
end
return table
end
-- Map VLAN tag to interface Index
--
-- Used to set ingressInterface, egressInterface based on the VLAN
-- tag. This is useful if packets from multiple sources are
-- multiplexed on the input interface by a device between the metering
-- process and the port mirrors/optical taps of the monitored links.
-- The multiplexer adds a VLAN tag to uniquely identify the original
-- monitored link. The tag is then translated into an interface
-- index. Only one of the ingressInterface and egressInterface
-- elements is relevant, depending on the direction of the flow. File
-- format:
-- <TAG>-<ingress>-<egress>
local function make_vlan_to_ifindex_map(name)
local table = {}
for line in assert(io.lines(name)) do
local vlan, ingress, egress = line:match("^(%d+)-(%d+)-(%d+)$")
assert(vlan and ingress and egress,
"VLAN-to-IFIndex map: invalid line: "..line)
table[tonumber(vlan)] = {
ingress = tonumber(ingress),
egress = tonumber(egress)
}
end
return table
end
-- Map IP address to AS number
--
-- Used to set bgpSourceAsNumber, bgpDestinationAsNumber from the IP
-- source and destination address, respectively. The file contains a
-- list of prefixes and their proper source AS number based on
-- authoritative data from the RIRs. This parser supports the format
-- used by the Geo2Lite database provided by MaxMind:
-- http://geolite.maxmind.com/download/geoip/database/GeoLite2-ASN-CSV.zip
local function make_pfx_to_as_map(name, proto)
local table = { pt = poptrie.new{direct_pointing=true}, asn = {} }
if proto == ipv4 then
function table:search_bytes (a)
return self.asn[self.pt:lookup32(a)]
end
elseif proto == ipv6 then
function table:search_bytes (a)
return self.asn[self.pt:lookup128(a)]
end
else
error("Proto must be ipv4 or ipv6")
end
for line in assert(io.lines(name)) do
if not line:match("^network") then
local cidr, asn = line:match("([^,]*),(%d+),")
asn = tonumber(asn)
assert(cidr and asn, "Prefix-to-AS map: invalid line: "..line)
local id = #asn+1
assert(id < 2^16, "Prefix-to-AS map: poptrie overflow")
table.asn[id] = asn
local pfx, len = proto:pton_cidr(cidr)
table:add(pfx, len, id)
end
end
table:build()
return table
end
local map_info = {
mac_to_as = {
create_fn = make_mac_to_as_map,
logger_module = 'MAC to AS mapper'
},
vlan_to_ifindex = {
create_fn = make_vlan_to_ifindex_map,
logger_module = 'VLAN to ifIndex mapper'
},
pfx4_to_as = {
create_fn = function (name) return make_pfx_to_as_map(name, ipv4) end,
logger_module = 'IPv4 prefix to AS mapper'
},
pfx6_to_as = {
create_fn = function (name) return make_pfx_to_as_map(name, ipv6) end,
logger_module = 'IPv6 prefix to AS mapper'
}
}
local maps = {}
function mk_map(name, file, log_rate, log_fh)
local info = assert(map_info[name])
local map = maps[name]
if not map then
map = info.create_fn(file)
maps[name] = map
end
local map = { map = map }
if log_fh then
map.logger = logger.new({ rate = log_rate or 0.05,
fh = log_fh,
module = info.logger_module })
end
return map
end
|
module(..., package.seeall)
local ffi = require("ffi")
local lib = require("core.lib")
local ctable = require("lib.ctable")
local ethernet = require("lib.protocol.ethernet")
local ipv4 = require("lib.protocol.ipv4")
local ipv6 = require("lib.protocol.ipv6")
local poptrie = require("lib.poptrie")
local logger = require("lib.logger")
-- Map MAC addresses to peer AS number
--
-- Used to determine bgpPrevAdjacentAsNumber, bgpNextAdjacentAsNumber
-- from the packet's MAC addresses. File format:
-- <AS>-<MAC>
local mac_to_as_key_t = ffi.typeof("uint8_t[6]")
local mac_to_as_value_t = ffi.typeof("uint32_t")
local function make_mac_to_as_map(name)
local table = ctable.new({ key_type = mac_to_as_key_t,
value_type = mac_to_as_value_t,
initial_size = 15000,
max_displacement_limit = 30 })
local key = mac_to_as_key_t()
local value = mac_to_as_value_t()
for line in assert(io.lines(name)) do
local as, mac = line:match("^%s*(%d*)-([0-9a-fA-F:]*)")
assert(as and mac, "MAC-to-AS map: invalid line: "..line)
local key, value = ethernet:pton(mac), tonumber(as)
local result = table:lookup_ptr(key)
if result then
if result.value ~= value then
print("MAC-to-AS map: amibguous mapping: "
..ethernet:ntop(key)..": "..result.value..", "..value)
end
end
table:add(key, value, true)
end
return table
end
-- Map VLAN tag to interface Index
--
-- Used to set ingressInterface, egressInterface based on the VLAN
-- tag. This is useful if packets from multiple sources are
-- multiplexed on the input interface by a device between the metering
-- process and the port mirrors/optical taps of the monitored links.
-- The multiplexer adds a VLAN tag to uniquely identify the original
-- monitored link. The tag is then translated into an interface
-- index. Only one of the ingressInterface and egressInterface
-- elements is relevant, depending on the direction of the flow. File
-- format:
-- <TAG>-<ingress>-<egress>
local function make_vlan_to_ifindex_map(name)
local table = {}
for line in assert(io.lines(name)) do
local vlan, ingress, egress = line:match("^(%d+)-(%d+)-(%d+)$")
assert(vlan and ingress and egress,
"VLAN-to-IFIndex map: invalid line: "..line)
table[tonumber(vlan)] = {
ingress = tonumber(ingress),
egress = tonumber(egress)
}
end
return table
end
-- Map IP address to AS number
--
-- Used to set bgpSourceAsNumber, bgpDestinationAsNumber from the IP
-- source and destination address, respectively. The file contains a
-- list of prefixes and their proper source AS number based on
-- authoritative data from the RIRs. This parser supports the format
-- used by the Geo2Lite database provided by MaxMind:
-- http://geolite.maxmind.com/download/geoip/database/GeoLite2-ASN-CSV.zip
local function make_pfx_to_as_map(name, proto)
local table = { pt = poptrie.new{direct_pointing=true,
leaf_t=ffi.typeof("uint32_t")} }
if proto == ipv4 then
function table:search_bytes (a)
return self.pt:lookup32(a)
end
elseif proto == ipv6 then
function table:search_bytes (a)
return self.pt:lookup128(a)
end
else
error("Proto must be ipv4 or ipv6")
end
for line in assert(io.lines(name)) do
if not line:match("^network") then
local cidr, asn = line:match("([^,]*),(%d+),")
asn = tonumber(asn)
assert(cidr and asn, "Prefix-to-AS map: invalid line: "..line)
assert(asn > 0 and asn < 2^32, "Prefix-to-AS map: asn out of range: "..asn)
local pfx, len = proto:pton_cidr(cidr)
table.pt:add(pfx, len, asn)
end
end
table.pt:build()
return table
end
local map_info = {
mac_to_as = {
create_fn = make_mac_to_as_map,
logger_module = 'MAC to AS mapper'
},
vlan_to_ifindex = {
create_fn = make_vlan_to_ifindex_map,
logger_module = 'VLAN to ifIndex mapper'
},
pfx4_to_as = {
create_fn = function (name) return make_pfx_to_as_map(name, ipv4) end,
logger_module = 'IPv4 prefix to AS mapper'
},
pfx6_to_as = {
create_fn = function (name) return make_pfx_to_as_map(name, ipv6) end,
logger_module = 'IPv6 prefix to AS mapper'
}
}
local maps = {}
function mk_map(name, file, log_rate, log_fh)
local info = assert(map_info[name])
local map = maps[name]
if not map then
map = info.create_fn(file)
maps[name] = map
end
local map = { map = map }
if log_fh then
map.logger = logger.new({ rate = log_rate or 0.05,
fh = log_fh,
module = info.logger_module })
end
return map
end
|
apps.ipfix: fix up previous commits
|
apps.ipfix: fix up previous commits
|
Lua
|
apache-2.0
|
snabbco/snabb,eugeneia/snabb,snabbco/snabb,eugeneia/snabb,snabbco/snabb,snabbco/snabb,eugeneia/snabb,eugeneia/snabb,snabbco/snabb,eugeneia/snabb,snabbco/snabb,eugeneia/snabb,eugeneia/snabb,snabbco/snabb,eugeneia/snabb,snabbco/snabb
|
6ad7269e5a56c5041d5a19a427c69bc4168ce656
|
modules/gamelib/creature.lua
|
modules/gamelib/creature.lua
|
-- @docclass Creature
-- @docconsts @{
SkullNone = 0
SkullYellow = 1
SkullGreen = 2
SkullWhite = 3
SkullRed = 4
SkullBlack = 5
SkullOrange = 6
ShieldNone = 0
ShieldWhiteYellow = 1
ShieldWhiteBlue = 2
ShieldBlue = 3
ShieldYellow = 4
ShieldBlueSharedExp = 5
ShieldYellowSharedExp = 6
ShieldBlueNoSharedExpBlink = 7
ShieldYellowNoSharedExpBlink = 8
ShieldBlueNoSharedExp = 9
ShieldYellowNoSharedExp = 10
EmblemNone = 0
EmblemGreen = 1
EmblemRed = 2
EmblemBlue = 3
-- @}
function getSkullImagePath(skullId)
local path
if skullId == SkullYellow then
path = 'icons/skull_yellow.png'
elseif skullId == SkullGreen then
path = 'icons/skull_green.png'
elseif skullId == SkullWhite then
path = 'icons/skull_white.png'
elseif skullId == SkullRed then
path = 'icons/skull_red.png'
elseif skullId == SkullBlack then
path = 'icons/skull_black.png'
elseif skullId == SkullOrange then
path = 'icons/skull_orange.png'
end
path = resolvepath(path)
return path
end
function getShieldImagePathAndBlink(shieldId)
local path
if shieldId == ShieldWhiteYellow then
path = 'icons/shield_yellow_white.png', false
elseif shieldId == ShieldWhiteBlue then
path = 'icons/shield_blue_white.png', false
elseif shieldId == ShieldBlue then
path = 'icons/shield_blue.png', false
elseif shieldId == ShieldYellow then
path = 'icons/shield_yellow.png', false
elseif shieldId == ShieldBlueSharedExp then
path = 'icons/shield_blue_shared.png', false
elseif shieldId == ShieldYellowSharedExp then
path = 'icons/shield_yellow_shared.png', false
elseif shieldId == ShieldBlueNoSharedExpBlink then
path = 'icons/shield_blue_not_shared.png', true
elseif shieldId == ShieldYellowNoSharedExpBlink then
path = 'icons/shield_yellow_not_shared.png', true
elseif shieldId == ShieldBlueNoSharedExp then
path = 'icons/shield_blue_not_shared.png', false
elseif shieldId == ShieldYellowNoSharedExp then
path = 'icons/shield_yellow_not_shared.png', false
end
path = resolvepath(path)
return path
end
function getEmblemImagePath(emblemId)
local path
if emblemId == EmblemGreen then
path = 'icons/emblem_green.png'
elseif emblemId == EmblemRed then
path = 'icons/emblem_red.png'
elseif emblemId == EmblemBlue then
path = 'icons/emblem_blue.png'
end
path = resolvepath(path)
return path
end
function Creature:onSkullChange(skullId)
local imagePath = getSkullImagePath(skullId)
if imagePath then
self:setSkullTexture(imagePath)
end
end
function Creature:onShieldChange(shieldId)
local imagePath, blink = getShieldImagePathAndBlink(shieldId)
if imagePath then
self:setShieldTexture(imagePath, blink)
end
end
function Creature:onEmblemChange(emblemId)
local imagePath = getEmblemImagePath(emblemId)
if imagePath then
self:setEmblemTexture(imagePath)
end
end
|
-- @docclass Creature
-- @docconsts @{
SkullNone = 0
SkullYellow = 1
SkullGreen = 2
SkullWhite = 3
SkullRed = 4
SkullBlack = 5
SkullOrange = 6
ShieldNone = 0
ShieldWhiteYellow = 1
ShieldWhiteBlue = 2
ShieldBlue = 3
ShieldYellow = 4
ShieldBlueSharedExp = 5
ShieldYellowSharedExp = 6
ShieldBlueNoSharedExpBlink = 7
ShieldYellowNoSharedExpBlink = 8
ShieldBlueNoSharedExp = 9
ShieldYellowNoSharedExp = 10
EmblemNone = 0
EmblemGreen = 1
EmblemRed = 2
EmblemBlue = 3
-- @}
function getSkullImagePath(skullId)
local path
if skullId == SkullYellow then
path = 'icons/skull_yellow.png'
elseif skullId == SkullGreen then
path = 'icons/skull_green.png'
elseif skullId == SkullWhite then
path = 'icons/skull_white.png'
elseif skullId == SkullRed then
path = 'icons/skull_red.png'
elseif skullId == SkullBlack then
path = 'icons/skull_black.png'
elseif skullId == SkullOrange then
path = 'icons/skull_orange.png'
end
path = resolvepath(path)
return path
end
function getShieldImagePathAndBlink(shieldId)
local path, blink
if shieldId == ShieldWhiteYellow then
path, blink = 'icons/shield_yellow_white.png', false
elseif shieldId == ShieldWhiteBlue then
path, blink = 'icons/shield_blue_white.png', false
elseif shieldId == ShieldBlue then
path, blink = 'icons/shield_blue.png', false
elseif shieldId == ShieldYellow then
path, blink = 'icons/shield_yellow.png', false
elseif shieldId == ShieldBlueSharedExp then
path, blink = 'icons/shield_blue_shared.png', false
elseif shieldId == ShieldYellowSharedExp then
path, blink = 'icons/shield_yellow_shared.png', false
elseif shieldId == ShieldBlueNoSharedExpBlink then
path, blink = 'icons/shield_blue_not_shared.png', true
elseif shieldId == ShieldYellowNoSharedExpBlink then
path, blink = 'icons/shield_yellow_not_shared.png', true
elseif shieldId == ShieldBlueNoSharedExp then
path, blink = 'icons/shield_blue_not_shared.png', false
elseif shieldId == ShieldYellowNoSharedExp then
path, blink = 'icons/shield_yellow_not_shared.png', false
end
path = resolvepath(path)
return path, blink
end
function getEmblemImagePath(emblemId)
local path
if emblemId == EmblemGreen then
path = 'icons/emblem_green.png'
elseif emblemId == EmblemRed then
path = 'icons/emblem_red.png'
elseif emblemId == EmblemBlue then
path = 'icons/emblem_blue.png'
end
path = resolvepath(path)
return path
end
function Creature:onSkullChange(skullId)
local imagePath = getSkullImagePath(skullId)
if imagePath then
self:setSkullTexture(imagePath)
end
end
function Creature:onShieldChange(shieldId)
local imagePath, blink = getShieldImagePathAndBlink(shieldId)
if imagePath then
self:setShieldTexture(imagePath, blink)
end
end
function Creature:onEmblemChange(emblemId)
local imagePath = getEmblemImagePath(emblemId)
if imagePath then
self:setEmblemTexture(imagePath)
end
end
|
Fix skull blink
|
Fix skull blink
|
Lua
|
mit
|
Cavitt/otclient_mapgen,kwketh/otclient,gpedro/otclient,Radseq/otclient,dreamsxin/otclient,Radseq/otclient,gpedro/otclient,gpedro/otclient,EvilHero90/otclient,dreamsxin/otclient,kwketh/otclient,dreamsxin/otclient,Cavitt/otclient_mapgen,EvilHero90/otclient
|
9c0abf065c9365888fb9212fb40f64346c1fdd8c
|
mods/plantlife_modpack/3dmushrooms/init.lua
|
mods/plantlife_modpack/3dmushrooms/init.lua
|
-- 3D Mushroom mod by VanessaE
--
-- License: WTFPL for everything.
mushroom = {}
minetest.override_item("flowers:mushroom_fertile_brown", {
drawtype = "mesh",
mesh = "3dmushrooms.obj",
tiles = {"3dmushrooms_brown.png"},
selection_box = {
type = "fixed",
fixed = {-0.3, -0.5, -0.3, 0.3, 0, 0.3}
},
inventory_image = "3dmushrooms_brown_inv.png"
})
minetest.override_item("flowers:mushroom_brown", {
drawtype = "mesh",
mesh = "3dmushrooms.obj",
tiles = {"3dmushrooms_brown.png"},
selection_box = {
type = "fixed",
fixed = {-0.3, -0.5, -0.3, 0.3, 0, 0.3}
},
inventory_image = "3dmushrooms_brown_inv.png"
})
minetest.override_item("flowers:mushroom_fertile_red", {
drawtype = "mesh",
mesh = "3dmushrooms.obj",
tiles = {"3dmushrooms_red.png"},
selection_box = {
type = "fixed",
fixed = {-0.3, -0.5, -0.3, 0.3, 0, 0.3}
},
inventory_image = "3dmushrooms_red_inv.png"
})
minetest.override_item("flowers:mushroom_red", {
drawtype = "mesh",
mesh = "3dmushrooms.obj",
tiles = {"3dmushrooms_red.png"},
selection_box = {
type = "fixed",
fixed = {-0.3, -0.5, -0.3, 0.3, 0, 0.3}
},
inventory_image = "3dmushrooms_red_inv.png"
})
-- aliases to the default mushrooms
minetest.register_alias("mushroom:brown", "flowers:mushroom_brown")
minetest.register_alias("mushroom:brown_natural", "flowers:mushroom_fertile_brown")
minetest.register_alias("mushroom:spore_brown", "flowers:mushroom_spores_brown")
minetest.register_alias("mushroom:spore2", "flowers:mushroom_spores_brown")
minetest.register_alias("mushroom:brown_essence", "flowers:mushroom_brown")
minetest.register_alias("mushroom:red", "flowers:mushroom_red")
minetest.register_alias("mushroom:red_natural", "flowers:mushroom_fertile_red")
minetest.register_alias("mushroom:spore_red", "flowers:mushroom_spores_red")
minetest.register_alias("mushroom:spore1", "flowers:mushroom_spores_red")
minetest.register_alias("mushroom:poison", "flowers:mushroom_red")
minetest.register_alias("mushroom:identifier", "default:mese_crystal_fragment")
minetest.log("action", "[3D Mushrooms] loaded.")
|
-- 3D Mushroom mod by VanessaE
--
-- License: WTFPL for everything.
mushroom = {}
minetest.override_item("flowers:mushroom_brown", {
drawtype = "mesh",
mesh = "3dmushrooms.obj",
tiles = {"3dmushrooms_brown.png"},
selection_box = {
type = "fixed",
fixed = {-0.3, -0.5, -0.3, 0.3, 0, 0.3}
},
inventory_image = "3dmushrooms_brown_inv.png"
})
minetest.override_item("flowers:mushroom_red", {
drawtype = "mesh",
mesh = "3dmushrooms.obj",
tiles = {"3dmushrooms_red.png"},
selection_box = {
type = "fixed",
fixed = {-0.3, -0.5, -0.3, 0.3, 0, 0.3}
},
inventory_image = "3dmushrooms_red_inv.png"
})
-- aliases to the default mushrooms
minetest.register_alias("mushroom:brown", "flowers:mushroom_brown")
minetest.register_alias("mushroom:brown_natural", "flowers:mushroom_brown")
minetest.register_alias("mushroom:spore_brown", "flowers:mushroom_brown")
minetest.register_alias("mushroom:spore2", "flowers:mushroom_brown")
minetest.register_alias("mushroom:brown_essence", "flowers:mushroom_brown")
minetest.register_alias("mushroom:red", "flowers:mushroom_red")
minetest.register_alias("mushroom:red_natural", "flowers:mushroom_red")
minetest.register_alias("mushroom:spore_red", "flowers:mushroom_red")
minetest.register_alias("mushroom:spore1", "flowers:mushroom_red")
minetest.register_alias("mushroom:poison", "flowers:mushroom_red")
minetest.register_alias("mushroom:identifier", "default:mese_crystal_fragment")
minetest.log("action", "[3D Mushrooms] loaded.")
|
[3dmushrooms] Redirect aliases to the new itemstrings
|
[3dmushrooms] Redirect aliases to the new itemstrings
- Fix #390
|
Lua
|
unlicense
|
sys4-fr/server-minetestforfun,crabman77/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,MinetestForFun/server-minetestforfun,Coethium/server-minetestforfun,MinetestForFun/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,Coethium/server-minetestforfun,MinetestForFun/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,Coethium/server-minetestforfun,LeMagnesium/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,MinetestForFun/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,sys4-fr/server-minetestforfun
|
692d4ec5beabe1d518775102c82bf0ecabc34cda
|
src/highlight/src/Client/AnimatedHighlight.lua
|
src/highlight/src/Client/AnimatedHighlight.lua
|
--[=[
@class AnimatedHighlight
]=]
local require = require(script.Parent.loader).load(script)
local BasicPane = require("BasicPane")
local BasicPaneUtils = require("BasicPaneUtils")
local Blend = require("Blend")
local SpringObject = require("SpringObject")
local Math = require("Math")
local ValueObject = require("ValueObject")
local EnumUtils = require("EnumUtils")
local Maid = require("Maid")
local Signal = require("Signal")
local AnimatedHighlight = setmetatable({}, BasicPane)
AnimatedHighlight.ClassName = "AnimatedHighlight"
AnimatedHighlight.__index = AnimatedHighlight
function AnimatedHighlight.new()
local self = setmetatable(BasicPane.new(), AnimatedHighlight)
self._adornee = Instance.new("ObjectValue")
self._adornee.Value = nil
self._maid:GiveTask(self._adornee)
self._highlightDepthMode = ValueObject.new(Enum.HighlightDepthMode.AlwaysOnTop)
self._maid:GiveTask(self._highlightDepthMode)
self._fillColor = Instance.new("Color3Value")
self._fillColor.Value = Color3.new(1, 1, 1)
self._maid:GiveTask(self._fillColor)
self._outlineColor = Instance.new("Color3Value")
self._outlineColor.Value = Color3.new(1, 1, 1)
self._maid:GiveTask(self._outlineColor)
self._fillTransparencySpring = SpringObject.new(0.5, 40)
self._maid:GiveTask(self._fillTransparencySpring)
self._outlineTransparencySpring = SpringObject.new(0, 40)
self._maid:GiveTask(self._outlineTransparencySpring)
self._percentVisible = SpringObject.new(BasicPaneUtils.observePercentVisible(self), 20)
self._maid:GiveTask(self._percentVisible)
self.Destroying = Signal.new()
self._maid:GiveTask(function()
self.Destroying:Fire()
self.Destroying:Destroy()
end)
self._maid:GiveTask(self:_render():Subscribe(function(highlight)
self.Gui = highlight
end))
return self
end
function AnimatedHighlight.isAnimatedHighlight(value)
return type(value) == "table" and
getmetatable(value) == AnimatedHighlight
end
--[=[
Sets the depth mode. Either can be:
* Enum.HighlightDepthMode.AlwaysOnTop
* Enum.HighlightDepthMode.Occluded
@param depthMode Enum.HighlightDepthMode
]=]
function AnimatedHighlight:SetHighlightDepthMode(depthMode)
assert(EnumUtils.isOfType(Enum.HighlightDepthMode, depthMode))
self._highlightDepthMode.Value = depthMode
end
function AnimatedHighlight:SetPropertiesFrom(sourceHighlight)
assert(AnimatedHighlight.isAnimatedHighlight(sourceHighlight), "Bad AnimatedHighlight")
self._highlightDepthMode.Value = sourceHighlight._highlightDepthMode.Value
self._fillColor.Value = sourceHighlight._fillColor.Value
self._outlineColor.Value = sourceHighlight._outlineColor.Value
-- well, this can't be very fast...
local function transferSpringValue(target, source)
target.Speed = source.Speed
target.Damper = source.Damper
target.Target = source.Target
target.Position = source.Position
target.Velocity = source.Velocity
end
transferSpringValue(self._fillTransparencySpring, sourceHighlight._fillTransparencySpring)
transferSpringValue(self._outlineTransparencySpring, sourceHighlight._outlineTransparencySpring)
transferSpringValue(self._percentVisible, sourceHighlight._percentVisible)
end
function AnimatedHighlight:SetTransparencySpeed(speed)
assert(type(speed) == "number", "Bad speed")
self._fillTransparencySpring.Speed = speed
self._outlineTransparencySpring.Speed = speed
end
function AnimatedHighlight:SetSpeed(speed)
assert(type(speed) == "number", "Bad speed")
self._percentVisible.Speed = speed
end
function AnimatedHighlight:Finish(doNotAnimate, callback)
if self._percentVisible.p == 0 and self._percentVisible.v == 0 then
callback()
return
end
local maid = Maid.new()
local done = false
maid:GiveTask(self._percentVisible:ObserveRenderStepped():Subscribe(function(position)
if position == 0 then
done = true
callback()
end
end))
self:Hide(doNotAnimate)
maid:GiveTask(function()
self._maid[maid] = nil
end)
self._maid[maid] = maid
if not done then
maid:GiveTask(self.VisibleChanged:Connect(function(isVisible)
if isVisible then
-- cancel
self._maid[maid]:DoCleaning()
end
end))
end
end
function AnimatedHighlight:SetFillColor(color)
assert(typeof(color) == "Color3", "Bad color")
self._fillColor.Value = color
end
function AnimatedHighlight:SetOutlineColor(color)
assert(typeof(color) == "Color3", "Bad color")
self._outlineColor.Value = color
end
function AnimatedHighlight:SetAdornee(adornee)
assert(typeof(adornee) == "Instance" or adornee == nil, "Bad adornee")
self._adornee.Value = adornee
end
function AnimatedHighlight:GetAdornee()
return self._adornee.Value
end
function AnimatedHighlight:SetOutlineTransparency(outlineTransparency, doNotAnimate)
assert(type(outlineTransparency) == "number", "Bad outlineTransparency")
self._outlineTransparencySpring.Target = outlineTransparency
if doNotAnimate then
self._outlineTransparencySpring.Position = outlineTransparency
self._outlineTransparencySpring.Velocity = 0
end
end
function AnimatedHighlight:SetFillTransparency(fillTransparency, doNotAnimate)
assert(type(fillTransparency) == "number", "Bad fillTransparency")
self._fillTransparencySpring.Target = fillTransparency
if doNotAnimate then
self._fillTransparencySpring.Position = fillTransparency
self._fillTransparencySpring.Velocity = 0
end
end
function AnimatedHighlight:_render()
return Blend.New "Highlight" {
Name = "AnimatedHighlight";
Archivable = false;
DepthMode = self._highlightDepthMode;
FillColor = self._fillColor;
OutlineColor = self._outlineColor;
FillTransparency = Blend.Computed(
self._fillTransparencySpring:ObserveRenderStepped(),
self._percentVisible:ObserveRenderStepped(),
function(transparency, visible)
return Math.map(visible, 0, 1, 1, transparency);
end);
OutlineTransparency = Blend.Computed(
self._outlineTransparencySpring:ObserveRenderStepped(),
self._percentVisible:ObserveRenderStepped(),
function(transparency, visible)
return Math.map(visible, 0, 1, 1, transparency);
end);
Adornee = self._adornee;
Parent = self._adornee;
}
end
return AnimatedHighlight
|
--[=[
@class AnimatedHighlight
]=]
local require = require(script.Parent.loader).load(script)
local BasicPane = require("BasicPane")
local Blend = require("Blend")
local SpringObject = require("SpringObject")
local Math = require("Math")
local ValueObject = require("ValueObject")
local EnumUtils = require("EnumUtils")
local Maid = require("Maid")
local Signal = require("Signal")
local AnimatedHighlight = setmetatable({}, BasicPane)
AnimatedHighlight.ClassName = "AnimatedHighlight"
AnimatedHighlight.__index = AnimatedHighlight
function AnimatedHighlight.new()
local self = setmetatable(BasicPane.new(), AnimatedHighlight)
self._adornee = Instance.new("ObjectValue")
self._adornee.Value = nil
self._maid:GiveTask(self._adornee)
self._highlightDepthMode = ValueObject.new(Enum.HighlightDepthMode.AlwaysOnTop)
self._maid:GiveTask(self._highlightDepthMode)
self._fillColor = Instance.new("Color3Value")
self._fillColor.Value = Color3.new(1, 1, 1)
self._maid:GiveTask(self._fillColor)
self._outlineColor = Instance.new("Color3Value")
self._outlineColor.Value = Color3.new(1, 1, 1)
self._maid:GiveTask(self._outlineColor)
self._fillTransparencySpring = SpringObject.new(0.5, 40)
self._maid:GiveTask(self._fillTransparencySpring)
self._outlineTransparencySpring = SpringObject.new(0, 40)
self._maid:GiveTask(self._outlineTransparencySpring)
self._percentVisible = SpringObject.new(0, 20)
self._maid:GiveTask(self._percentVisible)
self._maid:GiveTask(self.VisibleChanged:Connect(function(isVisible, doNotAnimate)
self._percentVisible.t = isVisible and 1 or 0
if doNotAnimate then
self._percentVisible.p = self._percentVisible.t
self._percentVisible.v = 0
end
end))
self.Destroying = Signal.new()
self._maid:GiveTask(function()
self.Destroying:Fire()
self.Destroying:Destroy()
end)
self._maid:GiveTask(self:_render():Subscribe(function(highlight)
self.Gui = highlight
end))
return self
end
function AnimatedHighlight.isAnimatedHighlight(value)
return type(value) == "table" and
getmetatable(value) == AnimatedHighlight
end
--[=[
Sets the depth mode. Either can be:
* Enum.HighlightDepthMode.AlwaysOnTop
* Enum.HighlightDepthMode.Occluded
@param depthMode Enum.HighlightDepthMode
]=]
function AnimatedHighlight:SetHighlightDepthMode(depthMode)
assert(EnumUtils.isOfType(Enum.HighlightDepthMode, depthMode))
self._highlightDepthMode.Value = depthMode
end
function AnimatedHighlight:SetPropertiesFrom(sourceHighlight)
assert(AnimatedHighlight.isAnimatedHighlight(sourceHighlight), "Bad AnimatedHighlight")
self._highlightDepthMode.Value = sourceHighlight._highlightDepthMode.Value
self._fillColor.Value = sourceHighlight._fillColor.Value
self._outlineColor.Value = sourceHighlight._outlineColor.Value
-- well, this can't be very fast...
local function transferSpringValue(target, source)
target.Speed = source.Speed
target.Damper = source.Damper
target.Target = source.Target
target.Position = source.Position
target.Velocity = source.Velocity
end
-- Transfer state before we set spring values
self:SetVisible(sourceHighlight:IsVisible(), true)
transferSpringValue(self._fillTransparencySpring, sourceHighlight._fillTransparencySpring)
transferSpringValue(self._outlineTransparencySpring, sourceHighlight._outlineTransparencySpring)
transferSpringValue(self._percentVisible, sourceHighlight._percentVisible)
end
function AnimatedHighlight:SetTransparencySpeed(speed)
assert(type(speed) == "number", "Bad speed")
self._fillTransparencySpring.Speed = speed
self._outlineTransparencySpring.Speed = speed
end
function AnimatedHighlight:SetSpeed(speed)
assert(type(speed) == "number", "Bad speed")
self._percentVisible.Speed = speed
end
function AnimatedHighlight:Finish(doNotAnimate, callback)
if self._percentVisible.p == 0 and self._percentVisible.v == 0 then
callback()
return
end
local maid = Maid.new()
local done = false
self:Hide(doNotAnimate)
maid:GiveTask(function()
self._maid[maid] = nil
end)
self._maid[maid] = maid
maid:GiveTask(self._percentVisible:ObserveRenderStepped():Subscribe(function(position)
if position == 0 and not done then
done = true
callback()
end
end))
if not done then
maid:GiveTask(self.VisibleChanged:Connect(function(isVisible)
if isVisible then
-- cancel
self._maid[maid] = nil
end
end))
end
end
function AnimatedHighlight:SetFillColor(color)
assert(typeof(color) == "Color3", "Bad color")
self._fillColor.Value = color
end
function AnimatedHighlight:SetOutlineColor(color)
assert(typeof(color) == "Color3", "Bad color")
self._outlineColor.Value = color
end
function AnimatedHighlight:SetAdornee(adornee)
assert(typeof(adornee) == "Instance" or adornee == nil, "Bad adornee")
self._adornee.Value = adornee
end
function AnimatedHighlight:GetAdornee()
return self._adornee.Value
end
function AnimatedHighlight:SetOutlineTransparency(outlineTransparency, doNotAnimate)
assert(type(outlineTransparency) == "number", "Bad outlineTransparency")
self._outlineTransparencySpring.Target = outlineTransparency
if doNotAnimate then
self._outlineTransparencySpring.Position = outlineTransparency
self._outlineTransparencySpring.Velocity = 0
end
end
function AnimatedHighlight:SetFillTransparency(fillTransparency, doNotAnimate)
assert(type(fillTransparency) == "number", "Bad fillTransparency")
self._fillTransparencySpring.Target = fillTransparency
if doNotAnimate then
self._fillTransparencySpring.Position = fillTransparency
self._fillTransparencySpring.Velocity = 0
end
end
function AnimatedHighlight:_render()
return Blend.New "Highlight" {
Name = "AnimatedHighlight";
Archivable = false;
DepthMode = self._highlightDepthMode;
FillColor = self._fillColor;
OutlineColor = self._outlineColor;
FillTransparency = Blend.Computed(
self._fillTransparencySpring:ObserveRenderStepped(),
self._percentVisible:ObserveRenderStepped(),
function(transparency, visible)
return Math.map(visible, 0, 1, 1, transparency);
end);
OutlineTransparency = Blend.Computed(
self._outlineTransparencySpring:ObserveRenderStepped(),
self._percentVisible:ObserveRenderStepped(),
function(transparency, visible)
return Math.map(visible, 0, 1, 1, transparency);
end);
Adornee = self._adornee;
Parent = self._adornee;
}
end
return AnimatedHighlight
|
fix: Fix visiblity not transferring from animated highlight (and more specifically, the event binding between visibility and the spring)
|
fix: Fix visiblity not transferring from animated highlight (and more specifically, the event binding between visibility and the spring)
|
Lua
|
mit
|
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
|
d7ea70549ceafaf577c862edb9672d8fb6c332a9
|
Modules/Client/Gui/MultipleClickUtils.lua
|
Modules/Client/Gui/MultipleClickUtils.lua
|
--- Utility library for detecting multiple clicks or taps. Not good UX, but good for opening up a debug
-- menus
-- @module MultipleClickUtils
local require = require(game:GetService("ReplicatedStorage"):WaitForChild("Nevermore"))
local Signal = require("Signal")
local InputObjectUtils = require("InputObjectUtils")
local MultipleClickUtils = {}
local TIME_TO_CLICK_AGAIN = 0.5 -- Based upon windows default
local VALID_TYPES = {
[Enum.UserInputType.MouseButton1] = true;
[Enum.UserInputType.Touch] = true;
}
function MultipleClickUtils.getDoubleClickSignal(maid, gui)
return MultipleClickUtils.getDoubleClickSignal(maid, gui, 2)
end
function MultipleClickUtils.getMultipleClickSignal(maid, gui, requiredCount)
assert(maid)
assert(typeof(gui) == "Instance")
local signal = Signal.new()
maid:GiveTask(signal)
local lastInputTime = 0
local lastInputObject = nil
local inputCount = 0
maid:GiveTask(gui.InputBegan:Connect(function(inputObject)
if not VALID_TYPES[inputObject.UserInputType] then
return
end
if lastInputObject
and InputObjectUtils.isSameInputObject(inputObject, lastInputObject)
and (tick() - lastInputTime) <= TIME_TO_CLICK_AGAIN then
inputCount = inputCount + 1
if inputCount >= requiredCount then
inputCount = 0
lastInputTime = 0
lastInputObject = nil
signal:Fire(lastInputObject)
end
else
inputCount = 1
lastInputTime = tick()
lastInputObject = inputObject
end
end))
return signal
end
return MultipleClickUtils
|
--- Utility library for detecting multiple clicks or taps. Not good UX, but good for opening up a debug
-- menus
-- @module MultipleClickUtils
local require = require(game:GetService("ReplicatedStorage"):WaitForChild("Nevermore"))
local Signal = require("Signal")
local MultipleClickUtils = {}
local TIME_TO_CLICK_AGAIN = 0.5 -- Based upon windows default
local VALID_TYPES = {
[Enum.UserInputType.MouseButton1] = true;
[Enum.UserInputType.Touch] = true;
}
function MultipleClickUtils.getDoubleClickSignal(maid, gui)
return MultipleClickUtils.getDoubleClickSignal(maid, gui, 2)
end
function MultipleClickUtils.getMultipleClickSignal(maid, gui, requiredCount)
assert(maid)
assert(typeof(gui) == "Instance")
local signal = Signal.new()
maid:GiveTask(signal)
local lastInputTime = 0
local lastInputObject = nil
local inputCount = 0
maid:GiveTask(gui.InputBegan:Connect(function(inputObject)
if not VALID_TYPES[inputObject.UserInputType] then
return
end
if lastInputObject
and inputObject.UserInputType == lastInputObject.UserInputType
and (tick() - lastInputTime) <= TIME_TO_CLICK_AGAIN then
inputCount = inputCount + 1
if inputCount >= requiredCount then
inputCount = 0
lastInputTime = 0
lastInputObject = nil
signal:Fire(lastInputObject)
end
else
inputCount = 1
lastInputTime = tick()
lastInputObject = inputObject
end
end))
return signal
end
return MultipleClickUtils
|
Fix mobile UX
|
Fix mobile UX
|
Lua
|
mit
|
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
|
4b9073ce0735f4b705d9f007479536cd91dac16b
|
src/pegasus/request.lua
|
src/pegasus/request.lua
|
local Request = {}
function Request:new(port, client)
local newObj = {}
self.__index = self
newObj.client = client
newObj.port = port
newObj.ip = client:getpeername()
newObj.firstLine = nil
newObj._method = nil
newObj._path = nil
newObj._params = {}
newObj._headers_parsed = false
newObj._headers = {}
newObj._form = {}
newObj._is_valid = false
newObj._body = ''
newObj._content_done = 0
return setmetatable(newObj, self)
end
Request.PATTERN_METHOD = '^(.+)%s'
Request.PATTERN_PATH = '(.*)%s'
Request.PATTERN_PROTOCOL = '(HTTP%/%d%.%d)'
Request.PATTERN_REQUEST = (Request.PATTERN_METHOD ..
Request.PATTERN_PATH ..Request.PATTERN_PROTOCOL)
function Request:parseFirstLine()
if (self.firstLine ~= nil) then
return
end
local status, partial
self.firstLine, status, partial = self.client:receive()
if (self.firstLine == nil or status == 'timeout' or partial == '' or status == 'closed') then
return
end
-- Parse firstline http: METHOD PATH PROTOCOL,
-- GET Makefile HTTP/1.1
local method, path, protocol = string.match(self.firstLine,
Request.PATTERN_REQUEST)
local filename, querystring = string.match(path, '^([^#?]+)[#|?]?(.*)')
self._path = filename
self._query_string = querystring
self._method = method
end
Request.PATTERN_QUERY_STRING = '([^=]*)=([^&]*)&?'
function Request:parseURLEncoded(value, _table)
--value exists and _table is empty
if value and next(_table) == nil then
for k, v in string.gmatch(value, Request.PATTERN_QUERY_STRING) do
_table[k] = v
end
end
return _table
end
function Request:params()
self:parseFirstLine()
return self:parseURLEncoded(self._query_string, self._params)
end
function Request:post()
if self:method() ~= 'POST' then return nil end
local data = self:receiveBody()
return self:parseURLEncoded(data, {})
end
function Request:path()
self:parseFirstLine()
return self._path
end
function Request:method()
self:parseFirstLine()
return self._method
end
Request.PATTERN_HEADER = '([%w-]+): ([%w %p]+=?)'
function Request:headers()
if self._headers_parsed then
return self._headers
end
self:parseFirstLine()
local data = self.client:receive()
while (data ~= nil) and (data:len() > 0) do
local key, value = string.match(data, Request.PATTERN_HEADER)
if key and value then
self._headers[key] = value
end
data = self.client:receive()
end
self._headers_parsed = true
self._content_length = tonumber(self._headers["Content-Length"] or 0)
return self._headers
end
function Request:receiveBody(size)
size = size or self._content_length
-- do we have content?
if self._content_done >= self._content_length then return false end
-- fetch in chunks
local fetch = math.min(self._content_length-self._content_done, size)
local data, err, partial = self.client:receive(fetch)
if err =='timeout' then
err = nil
data = partial
end
self._content_done = self._content_done + #data
return data
end
return Request
|
local Request = {}
function Request:new(port, client)
local newObj = {}
self.__index = self
newObj.client = client
newObj.port = port
newObj.ip = client:getpeername()
newObj.firstLine = nil
newObj._method = nil
newObj._path = nil
newObj._params = {}
newObj._headers_parsed = false
newObj._headers = {}
newObj._form = {}
newObj._is_valid = false
newObj._body = ''
newObj._content_done = 0
return setmetatable(newObj, self)
end
Request.PATTERN_METHOD = '^(.+)%s'
Request.PATTERN_PATH = '(.*)%s'
Request.PATTERN_PROTOCOL = '(HTTP%/%d%.%d)'
Request.PATTERN_REQUEST = (Request.PATTERN_METHOD ..
Request.PATTERN_PATH ..Request.PATTERN_PROTOCOL)
function Request:parseFirstLine()
if (self.firstLine ~= nil) then
return
end
local status, partial
self.firstLine, status, partial = self.client:receive()
if (self.firstLine == nil or status == 'timeout' or partial == '' or status == 'closed') then
return
end
-- Parse firstline http: METHOD PATH PROTOCOL,
-- GET Makefile HTTP/1.1
local method, path, protocol = string.match(self.firstLine,
Request.PATTERN_REQUEST)
local filename, querystring = string.match(path, '^([^#?]+)[#|?]?(.*)')
self._path = filename
self._query_string = querystring
self._method = method
end
Request.PATTERN_QUERY_STRING = '([^=]*)=([^&]*)&?'
function Request:parseURLEncoded(value, _table)
--value exists and _table is empty
if value and next(_table) == nil then
for k, v in string.gmatch(value, Request.PATTERN_QUERY_STRING) do
_table[k] = v
end
end
return _table
end
function Request:params()
self:parseFirstLine()
return self:parseURLEncoded(self._query_string, self._params)
end
function Request:post()
if self:method() ~= 'POST' then return nil end
local data = self:receiveBody()
return self:parseURLEncoded(data, {})
end
function Request:path()
self:parseFirstLine()
return self._path
end
function Request:method()
self:parseFirstLine()
return self._method
end
Request.PATTERN_HEADER = '([%w-]+): ([%w %p]+=?)'
function Request:headers()
if self._headers_parsed then
return self._headers
end
self:parseFirstLine()
local data = self.client:receive()
while (data ~= nil) and (data:len() > 0) do
local key, value = string.match(data, Request.PATTERN_HEADER)
if key and value then
self._headers[key] = value
end
data = self.client:receive()
end
self._headers_parsed = true
self._content_length = tonumber(self._headers["Content-Length"] or 0)
return self._headers
end
function Request:receiveBody(size)
size = size or self._content_length
-- do we have content?
if (self._content_length == nil) or (self._content_done >= self._content_length) then return false end
-- fetch in chunks
local fetch = math.min(self._content_length-self._content_done, size)
local data, err, partial = self.client:receive(fetch)
if err =='timeout' then
err = nil
data = partial
end
self._content_done = self._content_done + #data
return data
end
return Request
|
Fix. Do not raise error when calls receiveBody and there no content-length.
|
Fix. Do not raise error when calls receiveBody and there no content-length.
|
Lua
|
mit
|
EvandroLG/pegasus.lua
|
16e097b0aa4682d60a528bd07d2bb11e8ef0ecb9
|
lib/switchboard_modules/lua_script_debugger/premade_scripts/advanced_scripts/lua-stream-and-log-v3.lua
|
lib/switchboard_modules/lua_script_debugger/premade_scripts/advanced_scripts/lua-stream-and-log-v3.lua
|
--[[
Name: lua-stream-and-log-v3.lua
Desc: This example shows how to stream data to AIN0 and log to file
Note: Streams at 4KS/s, using nominal cal constants
This example requires firmware 1.0282 (T7) or 1.0023 (T4)
T-Series datasheet on streaming:
https://labjack.com/support/datasheets/t7/communication/stream-mode/low-level-streaming
--]]
-- Function that applies nominal cal constants (+-10V range)
function applycal(b)
local v = 0
local pslope = 0.000315805780
local nslope = -0.000315805800
local bincenter = 33523.0
local offset = -10.586956522
if b < bincenter then
v = (bincenter - b) * nslope
else
v = (b - bincenter) * pslope
end
return v
end
print("Stream and log AIN0 at 4kS/s to file, nominal cal constants")
strdate = ""
-- Check what hardware is installed
local hardware = MB.readName("HARDWARE_INSTALLED")
local passed = 1
if(bit.band(hardware, 8) ~= 8) then
print("uSD card not detected")
passed = 0
end
if(bit.band(hardware, 4) ~= 4) then
print("RTC module not detected")
passed = 0
end
if(passed == 0) then
print("This Lua script requires an RTC module and a microSD card, but one or both are not detected. These features are only preinstalled on the T7-Pro. Script Stopping")
-- Writing 0 to LUA_RUN stops the script
MB.writeName("LUA_RUN", 0)
end
local table = {}
table[1] = 0
table[2] = 0
table[3] = 0
table[4] = 0
table[5] = 0
table[6] = 0
local table, error = MB.RA(61510, 0, 6)
local strdate = string.format("%04d-%02d-%02d %02d-%02d-%02d",table[1],table[2],table[3],table[4],table[5],table[6])
local filecount = 0
local numfiles = 10
local extension = ".csv"
local filename = strdate .. extension
local strnewdata = ""
local datawritten = 0
local dataperfile = 100
local data = {}
-- Create or open and overwrite the file
local file = io.open(filename, "w")
-- Make sure that the file was opened properly.
if file then
print("Opened File on uSD Card", filename)
else
-- If the file was not opened properly we probably have a bad SD card.
print("!! Failed to open file on uSD Card !!", filename)
MB.writeName("LUA_RUN", 0)
end
local streamread = 0
local maxreads = 1000
local interval = 100
-- Configure FIO0 and FIO1 as low
MB.writeName("FIO0", 0)
MB.writeName("FIO1", 0)
-- Make sure analog is on
MB.writeName("POWER_AIN", 1)
-- Make sure streaming is not enabled
local streamrunning = MB.readName("STREAM_ENABLE")
if streamrunning == 1 then
MB.writeName("STREAM_ENABLE", 0)
end
-- Use +-10V for the AIN range
MB.writeName("AIN_ALL_RANGE", 10)
-- Use a 4000Hz scanrate
MB.writeName("STREAM_SCANRATE_HZ", 4000)
print(string.format("Scanrate %.8f",MB.readName("STREAM_SCANRATE_HZ")))
-- Use 1 channel for streaming
MB.writeName("STREAM_NUM_ADDRESSES", 1)
-- Enforce a 1uS settling time
MB.writeName("STREAM_SETTLING_US", 1)
-- Use the default stream resolution
MB.writeName("STREAM_RESOLUTION_INDEX", 0)
-- Use a 1024 byte buffer size (must be a power of 2)
MB.writeName("STREAM_BUFFER_SIZE_BYTES", 2^11)
-- Use command-response mode (0b10000=16)
MB.W("STREAM_AUTO_TARGET", 16)
-- Run continuously (can be limited)
MB.writeName("STREAM_NUM_SCANS", 0)
-- Scan AIN0
MB.writeName("STREAM_SCANLIST_ADDRESS0", 0)
-- Start the stream
MB.writeName("STREAM_ENABLE", 1)
-- configure a 5ms interval
LJ.IntervalConfig(0, 5)
local running = true
local numinbuffer = 1
while running do
-- If an interval is done
if LJ.CheckInterval(0) then
MB.writeName("FIO1", 1)
-- 4 (header) + 1 (num channels)
local numtoread = 4 + numinbuffer
data = MB.RA(4500, 0, numtoread)
-- Calculate the number of samples remaining in the buffer
numinbuffer = data[2]
-- numinbuffer = bit.rshift(data[2],0) -- num/2 (num bytes in uint) /1 (num channels)
-- Make sure the number of samples read the next iteration is a manageable amount.
if numinbuffer > 100 then
numinbuffer = 100
end
-- Save read data to the open file.
for i=5,numtoread do
-- Notify user of a stream error.
if data[i] == 0xFFFF then
print("Bad Val", data[3],data[4])
end
file:write(string.format("%.4f\n",applycal(data[i])))
end
MB.writeName("FIO0", 0)
MB.writeName("FIO1", 1)
streamread = streamread + 1
if streamread%interval == 0 then
print(streamread/maxreads, numinbuffer, data[2])
end
MB.writeName("FIO0", 0)
end
if (streamread > maxreads) then
-- Stop the stream
MB.writeName("STREAM_ENABLE", 0)
running = false
end
end
-- Configure FIO0 and FIO1 as low
MB.writeName("FIO0", 0)
MB.writeName("FIO1", 0)
file:close()
print("Finishing Script", datawritten, filecount, filename)
MB.writeName("LUA_RUN", 0)
|
--[[
Name: lua-stream-and-log-v3.lua
Desc: This example shows how to stream data to AIN0 and log to file
Note: Streams at 4KS/s, using nominal cal constants
This example requires firmware 1.0282 (T7) or 1.0023 (T4)
T-Series datasheet on streaming:
https://labjack.com/support/datasheets/t7/communication/stream-mode/low-level-streaming
--]]
-- Function that applies nominal cal constants (+-10V range)
function applycal(b)
local v = 0
local pslope = 0.000315805780
local nslope = -0.000315805800
local bincenter = 33523.0
local offset = -10.586956522
if b < bincenter then
v = (bincenter - b) * nslope
else
v = (b - bincenter) * pslope
end
return v
end
print("Stream and log AIN0 at 4kS/s to file, nominal cal constants")
strdate = ""
-- Check what hardware is installed
local hardware = MB.readName("HARDWARE_INSTALLED")
local passed = 1
if(bit.band(hardware, 8) ~= 8) then
print("uSD card not detected")
passed = 0
end
if(bit.band(hardware, 4) ~= 4) then
print("RTC module not detected")
passed = 0
end
if(passed == 0) then
print("This Lua script requires an RTC module and a microSD card, but one or both are not detected. These features are only preinstalled on the T7-Pro. Script Stopping")
-- Writing 0 to LUA_RUN stops the script
MB.writeName("LUA_RUN", 0)
end
local table = {}
table[1] = 0
table[2] = 0
table[3] = 0
table[4] = 0
table[5] = 0
table[6] = 0
local table, error = MB.RA(61510, 0, 6)
local strdate = string.format("%04d-%02d-%02d %02d-%02d-%02d",table[1],table[2],table[3],table[4],table[5],table[6])
local filecount = 0
local numfiles = 10
local extension = ".csv"
local filename = strdate .. extension
local datawritten = 0
local dataperfile = 100
local data = {}
-- Create or open and overwrite the file
local file = io.open(filename, "w")
-- Make sure that the file was opened properly.
if file then
print("Opened File on uSD Card", filename)
else
-- If the file was not opened properly we probably have a bad SD card.
print("!! Failed to open file on uSD Card !!", filename)
MB.writeName("LUA_RUN", 0)
end
local streamread = 0
local maxreads = 1000
local interval = 100
-- Configure FIO0 and FIO1 as low
MB.writeName("FIO0", 0)
MB.writeName("FIO1", 0)
-- Make sure analog is on
MB.writeName("POWER_AIN", 1)
-- Make sure streaming is not enabled
local streamrunning = MB.readName("STREAM_ENABLE")
if streamrunning == 1 then
MB.writeName("STREAM_ENABLE", 0)
end
-- Use +-10V for the AIN range
MB.writeName("AIN_ALL_RANGE", 10)
-- Use a 4000Hz scanrate
MB.writeName("STREAM_SCANRATE_HZ", 4000)
print(string.format("Scanrate %.8f",MB.readName("STREAM_SCANRATE_HZ")))
-- Use 1 channel for streaming
MB.writeName("STREAM_NUM_ADDRESSES", 1)
-- Enforce a 1uS settling time
MB.writeName("STREAM_SETTLING_US", 1)
-- Use the default stream resolution
MB.writeName("STREAM_RESOLUTION_INDEX", 0)
-- Use a 1024 byte buffer size (must be a power of 2)
MB.writeName("STREAM_BUFFER_SIZE_BYTES", 2^11)
-- Use command-response mode (0b10000=16)
MB.writeName("STREAM_AUTO_TARGET", 16)
-- Run continuously (can be limited)
MB.writeName("STREAM_NUM_SCANS", 0)
-- Scan AIN0
MB.writeName("STREAM_SCANLIST_ADDRESS0", 0)
-- Start the stream
MB.writeName("STREAM_ENABLE", 1)
-- configure a 5ms interval
LJ.IntervalConfig(0, 5)
local running = true
local numinbuffer = 1
while running do
-- If an interval is done
if LJ.CheckInterval(0) then
MB.writeName("FIO1", 1)
-- 4 (header) + 1 (num channels)
local numtoread = 4 + numinbuffer
data = MB.RA(4500, 0, numtoread)
-- Calculate the number of samples remaining in the buffer
numinbuffer = data[2]
-- numinbuffer = bit.rshift(data[2],0) -- num/2 (num bytes in uint) /1 (num channels)
-- Make sure the number of samples read the next iteration is a manageable amount.
if numinbuffer > 100 then
numinbuffer = 100
end
-- Save read data to the open file.
for i=5,numtoread do
-- Notify user of a stream error.
if data[i] == 0xFFFF then
print("Bad Val", data[3],data[4])
end
file:write(string.format("%.4f\n",applycal(data[i])))
end
MB.writeName("FIO0", 0)
MB.writeName("FIO1", 1)
streamread = streamread + 1
if streamread%interval == 0 then
print(streamread/maxreads, numinbuffer, data[2])
end
MB.writeName("FIO0", 0)
end
if (streamread > maxreads) then
-- Stop the stream
MB.writeName("STREAM_ENABLE", 0)
running = false
end
end
-- Configure FIO0 and FIO1 as low
MB.writeName("FIO0", 0)
MB.writeName("FIO1", 0)
file:close()
print("Finishing Script", datawritten, filecount, filename)
MB.writeName("LUA_RUN", 0)
|
Fixed the stream and log example
|
Fixed the stream and log example
|
Lua
|
mit
|
chrisJohn404/ljswitchboard-module_manager,chrisJohn404/ljswitchboard-module_manager,chrisJohn404/ljswitchboard-module_manager
|
ec03c5ec57abb0bf5ba4de196892eb363f697179
|
lua/wire/flir.lua
|
lua/wire/flir.lua
|
--[[
Simulation of FLIR (forward-looking infrared) vision.
Possible future ideas:
* Different materials have different emissivities:
aluminium is about 20%, wherease asphalt is 95%.
maybe we could use the physical properties to simulate this?
* the luminance of a texture contributes *negatively* to its emissivity
* IR sensors often have auto gain control that we might simulate with auto-exposure
* players are drawn fullbright but NPCs aren't.
--]]
if not FLIR then FLIR = { enabled = false } end
if CLIENT then
FLIR.normal = CreateMaterial("flir_normal", "VertexLitGeneric", {
["$basetexture"] = "color/white",
["$model"] = 1,
["$halflambert"] = 1, -- causes the diffuse lighting to 'wrap around' more
["$color2"] = "[10.0 10.0 10.0]"
})
FLIR.entcol = {
["$pp_colour_colour" ] = 0,
["$pp_colour_brightness"] = -0.00,
["$pp_colour_contrast"] = 4
}
FLIR.mapcol = {
[ "$pp_colour_brightness" ] = 0,
[ "$pp_colour_contrast" ] = 0.2
}
FLIR.skycol = {
[ "$pp_colour_contrast" ] = 0.2,
[ "$pp_colour_brightness" ] = 1
}
local function SetFLIRMat(ent)
if not IsValid(ent) then return end
if ent:GetMoveType() == MOVETYPE_VPHYSICS or IsValid(ent:GetParent()) or ent:IsPlayer() or ent:IsNPC() or ent:IsRagdoll() then
ent.FLIRMat = ent:GetMaterial()
ent:SetMaterial("!flir_normal")
end
end
function FLIR.start()
if FLIR.enabled then return else FLIR.enabled = true end
bright = false
hook.Add("PreRender", "wire_flir", function() --lighting mode 1 = fullbright
render.SetLightingMode(1)
end)
hook.Add("PostDraw2DSkyBox", "wire_flir", function() --overrides 2d skybox to be gray, as it normally becomes white
DrawColorModify(FLIR.skycol)
end)
hook.Add("PostDrawTranslucentRenderables", "wire_flir", function(_a, _b, sky)
if not sky then
render.SetLightingMode(0)
DrawColorModify(FLIR.mapcol)
end
end)
hook.Add("RenderScreenspaceEffects", "wire_flir", function()
DrawColorModify(FLIR.entcol)
DrawBloom(0.5,1.0,2,2,2,1, 1, 1, 1)
DrawBokehDOF(1, 0.1, 0.1)
end)
hook.Add("OnEntityCreated", "wire_flir", function(ent)
if FLIR.enabled then
SetFLIRMat(ent)
end
end)
hook.Add("CreateClientsideRagdoll", "wire_flir", function(ent, rag)
if FLIR.enabled then
SetFLIRMat(rag)
end
end)
for k, v in pairs(ents.GetAll()) do
SetFLIRMat(v)
end
end
function FLIR.stop()
if FLIR.enabled then FLIR.enabled = false else return end
render.SetLightingMode(0)
hook.Remove("PostDrawTranslucentRenderables", "wire_flir")
hook.Remove("RenderScreenspaceEffects", "wire_flir")
hook.Remove("PostDraw2DSkyBox", "wire_flir")
hook.Remove("PreRender", "wire_flir")
hook.Remove("OnEntityCreated", "wire_flir")
hook.Remove("CreateClientsideRagdoll", "wire_flir")
render.MaterialOverride(nil)
for k, v in pairs(ents.GetAll()) do
if v.FLIRMat then
v:SetMaterial(v.FLIRMat)
v.FLIRMat = nil
end
end
end
function FLIR.enable(enabled)
if enabled then FLIR.start() else FLIR.stop() end
end
usermessage.Hook("flir.enable",function(um)
FLIR.enable(um:ReadBool())
end)
concommand.Add("flir_enable", function(player, command, args)
FLIR.enable(tobool(args[1]))
end)
else
function FLIR.start(player) FLIR.enable(player, true) end
function FLIR.stop(player) FLIR.enable(player, false) end
function FLIR.enable(player, enabled)
umsg.Start( "flir.enable", player)
umsg.Bool( enabled )
umsg.End()
end
end
|
--[[
Simulation of FLIR (forward-looking infrared) vision.
Possible future ideas:
* Different materials have different emissivities:
aluminium is about 20%, wherease asphalt is 95%.
maybe we could use the physical properties to simulate this?
* the luminance of a texture contributes *negatively* to its emissivity
* IR sensors often have auto gain control that we might simulate with auto-exposure
* players are drawn fullbright but NPCs aren't.
--]]
if not FLIR then FLIR = { enabled = false } end
if CLIENT then
FLIR.RenderStack = {}
FLIR.Render = 0
FLIR.bright = CreateMaterial("flir_bright", "UnlitGeneric", {
["$basetexture"] = "color/white",
["$model"] = 1
})
FLIR.mapcol = {
[ "$pp_colour_brightness" ] = 0.4,
[ "$pp_colour_contrast" ] = 0.4
}
FLIR.skycol = {
[ "$pp_colour_contrast" ] = 0.2,
[ "$pp_colour_brightness" ] = 1
}
FLIR.desat = {
["$pp_colour_colour"] = 0,
["$pp_colour_contrast"] = 1,
["$pp_colour_brightness"] = 0
}
local function SetFLIRMat(ent)
if not IsValid(ent) then return end
if ent:GetMoveType() == MOVETYPE_VPHYSICS or ent:IsPlayer() or ent:IsNPC() or ent:IsRagdoll() or ent:GetClass() == "gmod_wire_hologram" then
ent.FLIRCol = ent:GetColor()
ent.RenderOverride = FLIR.Render
table.insert(FLIR.RenderStack, ent) --add entity to the FLIR renderstack and remove it from regular opaque rendering
end
end
local function RemoveFLIRMat(ent)
ent.RenderOverride = nil
if ent.FLIRCol then
ent:SetColor(ent.FLIRCol)
end
table.RemoveByValue(FLIR.RenderStack, ent)
end
function FLIR.Render(self)
if FLIR.Render == 1 then self:DrawModel() end
end
function FLIR.start()
if FLIR.enabled then return else FLIR.enabled = true end
bright = false
hook.Add("PreRender", "wire_flir", function() --lighting mode 1 = fullbright
render.SetLightingMode(1)
FLIR.Render = 0
end)
hook.Add("PostDraw2DSkyBox", "wire_flir", function() --overrides 2d skybox to be gray, as it normally becomes white or black
DrawColorModify(FLIR.skycol)
end)
hook.Add("PreDrawTranslucentRenderables", "wire_flir", function(a, b, sky)
if not sky then
DrawColorModify(FLIR.mapcol)
end
end)
hook.Add("PostDrawTranslucentRenderables", "wire_flir", function(_a, _b, sky)
if sky then return end
render.SetLightingMode(0)
FLIR.Render = 1
render.MaterialOverride(FLIR.bright)
for k, v in pairs(FLIR.RenderStack) do --draw all the FLIR highlighted enemies after the opaque render
if v:IsValid() then v:DrawModel() end --to separate then from the rest of the map
end
FLIR.Render = 0
render.MaterialOverride(nil)
render.SetLightingMode(1)
end)
hook.Add("RenderScreenspaceEffects", "wire_flir", function()
render.SetLightingMode(0)
DrawColorModify(FLIR.desat)
DrawBloom(0.5,1.0,2,2,2,1, 1, 1, 1)
DrawBokehDOF(1, 0.1, 0.1)
end)
hook.Add("OnEntityCreated", "wire_flir", function(ent)
if FLIR.enabled then
SetFLIRMat(ent)
end
end)
hook.Add("CreateClientsideRagdoll", "wire_flir", function(ent, rag)
if FLIR.enabled then
SetFLIRMat(rag)
end
end)
for k, v in pairs(ents.GetAll()) do
SetFLIRMat(v)
end
end
function FLIR.stop()
if FLIR.enabled then FLIR.enabled = false else return end
render.SetLightingMode(0)
hook.Remove("PreDrawTranslucentRenderables", "wire_flir")
hook.Remove("PostDrawTranslucentRenderables", "wire_flir")
hook.Remove("RenderScreenspaceEffects", "wire_flir")
hook.Remove("PostDraw2DSkyBox", "wire_flir")
hook.Remove("PreRender", "wire_flir")
hook.Remove("OnEntityCreated", "wire_flir")
hook.Remove("CreateClientsideRagdoll", "wire_flir")
render.MaterialOverride(nil)
for k, v in pairs(ents.GetAll()) do
RemoveFLIRMat(v)
end
end
function FLIR.enable(enabled)
if enabled then FLIR.start() else FLIR.stop() end
end
usermessage.Hook("flir.enable",function(um)
FLIR.enable(um:ReadBool())
end)
concommand.Add("flir_enable", function(player, command, args)
FLIR.enable(tobool(args[1]))
end)
else
function FLIR.start(player) FLIR.enable(player, true) end
function FLIR.stop(player) FLIR.enable(player, false) end
function FLIR.enable(player, enabled)
umsg.Start( "flir.enable", player)
umsg.Bool( enabled )
umsg.End()
end
end
|
Better FLIR (Again!) (#2249)
|
Better FLIR (Again!) (#2249)
* Reworked FLIR visual behaviour
* added hook removals, fixed 3d skybox color
* adjusted color modifies, streamlined hooks, removed old material system
* client ragdoll hook -> flir.Start() to fix no heat on bodies
* removed print(test) from function
* removed flir.living material, renamed hooks flir -> wire_flir
* FLIR entities put in separate renderstack
* removed old calls to rendermode
* brightened up a bit
Co-authored-by: thegrb93 <[email protected]>
|
Lua
|
apache-2.0
|
dvdvideo1234/wire,Grocel/wire,wiremod/wire
|
eec41e9f7cb3df2e69cdc494412b723f5b3d2375
|
examples/sanitizer.lua
|
examples/sanitizer.lua
|
-- This example implements the HTML sanitization rules used by GitHub
-- https://github.com/github/markup#html-sanitization
local gumbo = require "gumbo"
local Set = require "gumbo.Set"
local input = arg[1] or io.stdin
local write, assert = io.write, assert
local _ENV = nil
local allowedHrefSchemes = Set{"http://", "https://", "mailto:"}
local allowedImgSrcSchemes = Set{"http://", "https://"}
local allowedDivAttributes = Set{"itemscope", "itemtype"}
local allowedElements = Set [[
a b blockquote br code dd del div dl dt em h1 h2 h3 h4 h5 h6 hr i
img ins kbd li ol p pre q rp rt ruby s samp strike strong sub sup
table tbody td tfoot th thead tr tt ul var
]]
local allowedAttributes = Set [[
abbr accept accept-charset accesskey action align alt axis border
cellpadding cellspacing char charoff charset checked cite clear
color cols colspan compact coords datetime dir disabled enctype for
frame headers height hreflang hspace ismap itemprop label lang
longdesc maxlength media method multiple name nohref noshade nowrap
prompt readonly rel rev rows rowspan rules scope selected shape size
span start summary tabindex target title type usemap valign value
vspace width
]]
local function isAllowedHref(url)
local scheme = url:match("^[a-z]+:/?/?")
return (scheme and allowedHrefSchemes[scheme]) and true or false
end
local function isAllowedImgSrc(url)
local scheme = url:match("^[a-z]+://")
return (scheme and allowedImgSrcSchemes[scheme]) and true or false
end
-- TODO: Allow relative URLs for a[href] and img[src]
local function isAllowedAttribute(tag, attr)
local name = assert(attr.name)
if allowedAttributes[name] then
return true
elseif tag == "div" and allowedDivAttributes[name] then
return true
else
local value = assert(attr.value)
if tag == "a" and name == "href" and isAllowedHref(value) then
return true
elseif tag == "img" and name == "src" and isAllowedImgSrc(value) then
return true
end
end
return false
end
local function sanitize(root)
for node in root:reverseWalk() do
if node.type == "element" then
local tag = node.localName
if allowedElements[tag] then
local attributes = node.attributes
for i = #attributes, 1, -1 do
local attr = attributes[i]
if not isAllowedAttribute(tag, attr) then
node:removeAttribute(attr.name)
end
end
else
node:remove()
end
end
end
return root
end
local document = assert(gumbo.parseFile(input))
local body = assert(sanitize(document.body))
write(body.outerHTML, "\n")
|
-- This example implements the HTML sanitization rules used by GitHub
-- https://github.com/github/markup#html-sanitization
local gumbo = require "gumbo"
local Set = require "gumbo.Set"
local input = arg[1] or io.stdin
local write, assert = io.write, assert
local _ENV = nil
local urlSchemePattern = "^[\0-\32]*([a-zA-Z][a-zA-Z0-9+.-]*:)"
local allowedHrefSchemes = Set{"http:", "https:", "mailto:"}
local allowedImgSrcSchemes = Set{"http:", "https:"}
local allowedDivAttributes = Set{"itemscope", "itemtype"}
local allowedElements = Set [[
a b blockquote br code dd del div dl dt em h1 h2 h3 h4 h5 h6 hr i
img ins kbd li ol p pre q rp rt ruby s samp strike strong sub sup
table tbody td tfoot th thead tr tt ul var
]]
local allowedAttributes = Set [[
abbr accept accept-charset accesskey action align alt axis border
cellpadding cellspacing char charoff charset checked cite clear
color cols colspan compact coords datetime dir disabled enctype for
frame headers height hreflang hspace ismap itemprop label lang
longdesc maxlength media method multiple name nohref noshade nowrap
prompt readonly rel rev rows rowspan rules scope selected shape size
span start summary tabindex target title type usemap valign value
vspace width
]]
local function isAllowedHref(url)
local scheme = url:match(urlSchemePattern)
return scheme == nil or allowedHrefSchemes[scheme:lower()] == true
end
local function isAllowedImgSrc(url)
local scheme = url:match(urlSchemePattern)
return scheme == nil or allowedImgSrcSchemes[scheme:lower()] == true
end
local function isAllowedAttribute(tag, attr)
local name = assert(attr.name)
if allowedAttributes[name] then
return true
elseif tag == "div" and allowedDivAttributes[name] then
return true
else
local value = assert(attr.value)
if tag == "a" and name == "href" and isAllowedHref(value) then
return true
elseif tag == "area" and name == "href" and isAllowedHref(value) then
return true
elseif tag == "img" and name == "src" and isAllowedImgSrc(value) then
return true
end
end
return false
end
local function sanitize(root)
for node in root:reverseWalk() do
if node.type == "element" then
local tag = node.localName
if allowedElements[tag] then
local attributes = node.attributes
for i = #attributes, 1, -1 do
local attr = attributes[i]
if not isAllowedAttribute(tag, attr) then
node:removeAttribute(attr.name)
end
end
else
node:remove()
end
end
end
return root
end
local document = assert(gumbo.parseFile(input))
local body = assert(sanitize(document.body))
write(body.outerHTML, "\n")
|
Fix URL sanitization in examples/sanitizer.lua...
|
Fix URL sanitization in examples/sanitizer.lua...
Only absolute URLs with a non-whitelisted scheme (e.g. "javascript:")
are rejected now. All relative URLs are allowed.
|
Lua
|
apache-2.0
|
craigbarnes/lua-gumbo,craigbarnes/lua-gumbo,craigbarnes/lua-gumbo
|
2aab618f2b5deaa85245907a9a420c077bc5f923
|
site/email.lua
|
site/email.lua
|
--[[
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
-- This is email.lua - a script for fetching a document (email)
local JSON = require 'cjson'
local elastic = require 'lib/elastic'
local aaa = require 'lib/aaa'
local user = require 'lib/user'
function handle(r)
r.content_type = "application/json"
local get = r:parseargs()
local doc = elastic.get("mbox", get.id or "hmm")
if doc then
local canAccess = false
if doc.private then
local account = user.get(r)
if account then
local lid = doc.list_raw:match("<[^.]+%.(.-)>")
for k, v in pairs(aaa.rights(account.credentials.uid or account.credentials.email)) do
if v == "*" or v == lid then
canAccess = true
break
end
end
else
r:puts(JSON.encode{
error = "You must be logged in to view this email"
})
end
else
canAccess = true
end
if canAccess then
r:puts(JSON.encode(doc))
else
r:puts(JSON.encode{
error = "You do not have access to view this email, sorry."
})
end
else
r:puts[[{}]]
end
return apache2.OK
end
|
--[[
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
-- This is email.lua - a script for fetching a document (email)
local JSON = require 'cjson'
local elastic = require 'lib/elastic'
local aaa = require 'lib/aaa'
local user = require 'lib/user'
function handle(r)
r.content_type = "application/json"
local get = r:parseargs()
local doc = elastic.get("mbox", get.id or "hmm")
if doc then
local canAccess = false
if doc.private then
local account = user.get(r)
if account then
local lid = doc.list_raw:match("<[^.]+%.(.-)>")
for k, v in pairs(aaa.rights(account.credentials.uid or account.credentials.email)) do
if v == "*" or v == lid then
canAccess = true
break
end
end
else
r:puts(JSON.encode{
error = "You must be logged in to view this email"
})
return apache2.OK
end
else
canAccess = true
end
if canAccess then
r:puts(JSON.encode(doc))
else
r:puts(JSON.encode{
error = "You do not have access to view this email, sorry."
})
return apache2.OK
end
else
r:puts[[{}]]
end
return apache2.OK
end
|
fix returns
|
fix returns
|
Lua
|
apache-2.0
|
Humbedooh/ponymail,rbowen/ponymail,jimjag/ponymail,Humbedooh/ponymail,Humbedooh/ponymail,quenda/ponymail,quenda/ponymail,quenda/ponymail,jimjag/ponymail,rbowen/ponymail,rbowen/ponymail,jimjag/ponymail,jimjag/ponymail
|
ee4ef0967a03c05f56cd8bc7a5c780b31b41b0a3
|
lib/lua/virgo-time.lua
|
lib/lua/virgo-time.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 logging = require('logging')
local Error = require('core').Error
local math = require('math')
local delta = 0
local delay = 0
local function now()
return math.floor(virgo.gmtnow() + delta)
end
local function raw()
return math.floor(virgo.gmtnow())
end
local function setDelta(_delta)
delta = _delta
end
local function getDelta()
return delta
end
--[[
This algorithm follows the NTP algorithm found here:
http://www.eecis.udel.edu/~mills/ntp/html/warp.html
T1 = agent departure timestamp
T2 = server receieved timestamp
T3 = server transmit timestamp
T4 = agent destination timestamp
]]--
local function timesync(T1, T2, T3, T4)
if not T1 or not T2 or not T3 or not T4 then
return Error:new('T1, T2, T3, or T4 was null. Failed to sync time.')
end
logging.debug('T1 = %i', T1)
logging.debug('T2 = %i', T2)
logging.debug('T3 = %i', T3)
logging.debug('T4 = %i', T4)
delta = ((T2 - T1) + (T3 - T4)) / 2
delay = ((T4 - T1) + (T3 - T2))
logging.infof('Setting time delta to %i', delta)
return
end
local exports = {}
exports.setDelta = setDelta
exports.getDelta = getDelta
exports.now = now
exports.raw = raw
exports.timesync = timesync
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 logging = require('logging')
local Error = require('core').Error
local math = require('math')
local delta = 0
local delay = 0
local function now()
return math.floor(virgo.gmtnow() + delta)
end
local function raw()
return math.floor(virgo.gmtnow())
end
local function setDelta(_delta)
delta = _delta
end
local function getDelta()
return delta
end
--[[
This algorithm follows the NTP algorithm found here:
http://www.eecis.udel.edu/~mills/ntp/html/warp.html
T1 = agent departure timestamp
T2 = server receieved timestamp
T3 = server transmit timestamp
T4 = agent destination timestamp
]]--
local function timesync(T1, T2, T3, T4)
if not T1 or not T2 or not T3 or not T4 then
return Error:new('T1, T2, T3, or T4 was null. Failed to sync time.')
end
logging.debugf('time_sync data: T1 = %.0f T2 = %.0f T3 = %.0f T4 = %.0f', T1, T2, T3, T4)
delta = ((T2 - T1) + (T3 - T4)) / 2
delay = ((T4 - T1) + (T3 - T2))
logging.infof('Setting time delta to %.0fms based on server time %.0fms', delta, T2)
return
end
local exports = {}
exports.setDelta = setDelta
exports.getDelta = getDelta
exports.now = now
exports.raw = raw
exports.timesync = timesync
return exports
|
lib: virgo-time: improve debug statement
|
lib: virgo-time: improve debug statement
the debug statement had two problems:
1) it didn't use debugf so the timestamps weren't printed
2) it printed in 4 lines what could be said in 1
Fix both these issues.
|
Lua
|
apache-2.0
|
cp16net/virgo-base,cp16net/virgo-base,AlphaStaxLLC/rackspace-monitoring-agent,virgo-agent-toolkit/rackspace-monitoring-agent,cp16net/virgo-base,cp16net/virgo-base,cp16net/virgo-base,christopherjwang/rackspace-monitoring-agent,kaustavha/rackspace-monitoring-agent,virgo-agent-toolkit/rackspace-monitoring-agent,kaustavha/rackspace-monitoring-agent,christopherjwang/rackspace-monitoring-agent,AlphaStaxLLC/rackspace-monitoring-agent
|
0a066396bdc112e03def431b03781ec1b9ff4db9
|
framework/sound.lua
|
framework/sound.lua
|
--=========== Copyright © 2017, Planimeter, All rights reserved. =============--
--
-- Purpose:
--
--============================================================================--
local AL = require( "openal" )
local SDL = require( "sdl" )
local SDL_sound = require( "sdl_sound" )
require( "class" )
local ffi = require( "ffi" )
SDL_sound.Sound_Init()
class( "framework.sound" )
local sound = framework.sound
function sound.getFormat( channels, type )
local format = AL.AL_NONE
if ( type == SDL.AUDIO_U8 ) then
if ( channels == 1 ) then
format = AL.AL_FORMAT_MONO8
elseif ( channels == 2 ) then
format = AL.AL_FORMAT_STEREO8
end
elseif ( type == SDL.AUDIO_S16LSB or type == SDL.AUDIO_S16MSB ) then
if ( channels == 1 ) then
format = AL.AL_FORMAT_MONO16
elseif ( channels == 2 ) then
format = AL.AL_FORMAT_STEREO16
end
end
return format
end
function sound:sound( filename )
self.source = ffi.new( "ALuint[1]" )
AL.alGenSources( 1, self.source )
self.buffer = ffi.new( "ALuint[1]" )
AL.alGenBuffers( 1, self.buffer )
local sample = SDL_sound.Sound_NewSampleFromFile( filename, nil, 0 )
if ( sample == nil ) then
error( "Could not load sound '" .. filename .. "'", 3 )
end
self.sample = sample
local info = sample.actual
local format = framework.sound.getFormat( info.channels, info.format )
local size = SDL_sound.Sound_DecodeAll( sample )
local data = sample.buffer
local freq = info.rate
AL.alBufferData( self.buffer[0], format, data, size, freq )
setproxy( self )
end
function sound:play()
AL.alSourcePlay( self.source[0] )
end
function sound:__gc()
SDL_sound.Sound_FreeSample( self.sample )
AL.alDeleteBuffers( 1, self.buffer )
AL.alDeleteSources( 1, self.source )
end
|
--=========== Copyright © 2017, Planimeter, All rights reserved. =============--
--
-- Purpose:
--
--============================================================================--
local AL = require( "openal" )
local SDL = require( "sdl" )
local SDL_sound = require( "sdl_sound" )
require( "class" )
local ffi = require( "ffi" )
SDL_sound.Sound_Init()
class( "framework.sound" )
local sound = framework.sound
function sound.getFormat( channels, type )
local format = AL.AL_NONE
if ( type == SDL.AUDIO_U8 ) then
if ( channels == 1 ) then
format = AL.AL_FORMAT_MONO8
elseif ( channels == 2 ) then
format = AL.AL_FORMAT_STEREO8
end
elseif ( type == SDL.AUDIO_S16LSB or type == SDL.AUDIO_S16MSB ) then
if ( channels == 1 ) then
format = AL.AL_FORMAT_MONO16
elseif ( channels == 2 ) then
format = AL.AL_FORMAT_STEREO16
end
end
return format
end
function sound:sound( filename )
self.source = ffi.new( "ALuint[1]" )
AL.alGenSources( 1, self.source )
self.buffer = ffi.new( "ALuint[1]" )
AL.alGenBuffers( 1, self.buffer )
local sample = SDL_sound.Sound_NewSampleFromFile( filename, nil, 10240 )
if ( sample == nil ) then
error( "Could not load sound '" .. filename .. "'", 3 )
end
self.sample = sample
local info = sample.actual
local format = framework.sound.getFormat( info.channels, info.format )
local size = SDL_sound.Sound_DecodeAll( sample )
local data = sample.buffer
local freq = info.rate
print( info, format, size, data, freq )
AL.alBufferData( self.buffer[0], format, data, size, freq )
setproxy( self )
end
function sound:play()
AL.alSourcei( self.source[0], AL.AL_BUFFER, self.buffer[0] )
AL.alSourcePlay( self.source[0] )
end
function sound:stop()
AL.alSourcei( self.source[0], AL.AL_BUFFER, self.buffer[0] )
AL.alSourceStop( self.source[0] )
end
function sound:__gc()
SDL_sound.Sound_FreeSample( self.sample )
AL.alDeleteBuffers( 1, self.buffer )
AL.alDeleteSources( 1, self.source )
end
|
Fix initial buffer in sound.lua
|
Fix initial buffer in sound.lua
|
Lua
|
mit
|
Planimeter/lgameframework,Planimeter/lgameframework,Planimeter/lgameframework
|
db66c8c55e10c88ed37ba17fce347fdb4662ba43
|
site/code/triggers.lua
|
site/code/triggers.lua
|
-- Manage the SNMP package
pkg = resource.package.new("net-snmp")
pkg.state = "present"
-- Manage the config file for SNMP daemon
config = resource.file.new("/etc/snmp/snmpd.conf")
config.state = "present"
config.content = "rocommunity public"
config.require = { pkg:ID() }
-- Manage the SNMP service
svc = resource.service.new("snmpd")
svc.state = "running"
svc.enable = true
svc.require = { pkg:ID(), config:ID() }
-- Subscribe for changes in the config file resource.
-- Reload the SNMP daemon service if the config file has changed.
svc.subscribe[pkg:ID()] = function()
os.execute("systemctl reload snmpd")
end
-- Subscribe for changes in the package resource.
-- Restart the SNMP daemon service if the package has changed.
svc.subscribe[config:ID()] = function()
os.execute("systemctl restart snmpd")
end
-- Add resources to the catalog
catalog:add(pkg, config, svc)
|
--
-- Example code for using triggers in resources
--
-- Manage the SNMP package
pkg = resource.package.new("net-snmp")
pkg.state = "present"
-- Manage the config file for SNMP daemon
config = resource.file.new("/etc/snmp/snmpd.conf")
config.state = "present"
config.content = "rocommunity public"
config.require = { pkg:ID() }
-- Manage the SNMP service
svc = resource.service.new("snmpd")
svc.state = "running"
svc.enable = true
svc.require = { pkg:ID(), config:ID() }
-- Subscribe for changes in the config file resource.
-- Reload the SNMP daemon service if the config file has changed.
svc.subscribe[config:ID()] = function()
os.execute("systemctl reload snmpd")
end
-- Subscribe for changes in the package resource.
-- Restart the SNMP daemon service if the package has changed.
svc.subscribe[pkg:ID()] = function()
os.execute("systemctl restart snmpd")
end
-- Add resources to the catalog
catalog:add(pkg, config, svc)
|
site: typo fixes in trigger example code
|
site: typo fixes in trigger example code
|
Lua
|
mit
|
ranjithamca/gru
|
dc61170366c925db8ae7a2e3575d4f2e9d216a1e
|
scripts/slate.lua
|
scripts/slate.lua
|
-- run and gather slate v1.0 by Dunagain
dofile("common.inc");
numSlates = 0
function doit()
local done = false
askForWindow("Whenever possible, your avatar will collect a slate. You can perform other tasks while the macro is running. You can also minimize VT windows after the macro is started to let it run discreetly.") ;
while not done
do
sleepWithStatus(100, "Slates collected: " .. tostring(numSlates)) ;
srReadScreen();
local xyWindowSize = srGetWindowSize();
local midX = xyWindowSize[0] / 2;
local pos = srFindImageInRange("slate.png",0,0,midX,100,1000);
if (pos) then
safeClick(pos[0] + 3, pos[1] + 3);
numSlates = numSlates + 1;
end
end
end
|
-- run and gather slate v1.0 by Dunagain
dofile("common.inc");
numSlates = 0
function doit()
local done = false
askForWindow("Whenever possible, your avatar will collect a slate. You can perform other tasks while the macro is running. You can also minimize VT windows after the macro is started to let it run discreetly.") ;
while not done
do
sleepWithStatus(5, "Slates collected: " .. tostring(numSlates)) ;
srReadScreen();
local pos = srFindImage("slate.png");
if (pos) then
safeClick(pos[0] + 3, pos[1] + 3);
numSlates = numSlates + 1;
end
end
end
|
Fixing slate macro so it gathers slate while running
|
Fixing slate macro so it gathers slate while running
|
Lua
|
mit
|
DashingStrike/Automato-ATITD,DashingStrike/Automato-ATITD
|
f2cee5c109c4bd35eb06148a8c7436ecb346ac24
|
lib/specl/util.lua
|
lib/specl/util.lua
|
-- Miscellaneous utility functions.
-- Written by Gary V. Vaughan, 2013
--
-- Copyright (c) 2013-2014 Gary V. Vaughan
--
-- 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, 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; see the file COPYING. If not, write to the
-- Free Software Foundation, Fifth Floor, 51 Franklin Street, Boston,
-- MA 02111-1301, USA.
local std = require "specl.std"
local have_posix, posix = pcall (require, "posix")
local object = std.object
-- A null operation function.
local function nop () end
local files, timersub -- forward declarations
if have_posix then
files = function (root, t)
t = t or {}
for _, file in ipairs (posix.dir (root) or {}) do
if file ~= "." and file ~= ".." then
local path = std.io.catfile (root, file)
if posix.stat (path).type == "directory" then
t = files (path, t)
else
t[#t + 1] = path
end
end
end
return t
end
timersub = posix.sys and posix.sys.timersub or posix.timersub
else
files = nop
end
-- Use higher resolution timers from luaposix if available.
local function gettimeofday ()
if not (have_posix and timersub) then
return os.time ()
end
return posix.gettimeofday ()
end
local function timesince (earlier)
if not (have_posix and timersub) then
return os.time () - earlier
end
local elapsed = timersub (posix.gettimeofday (), earlier)
return (elapsed.usec / 1000000) + elapsed.sec
end
-- Return a complete copy of T, along with copied metatables.
local function deepcopy (t)
local copied = {} -- references to tables already copied
local function tablecopy (orig)
local mt = getmetatable (orig)
local copy = mt and setmetatable ({}, copied[mt] or tablecopy (mt)) or {}
copied[orig] = copy
for k, v in next, orig, nil do -- don't trigger __pairs metamethod
if type (k) == "table" then k = copied[k] or tablecopy (k) end
if type (v) == "table" then v = copied[v] or tablecopy (v) end
rawset (copy, k, v)
end
return copy
end
return tablecopy (t)
end
-- Map function F over elements of T and return a table of results.
local function map (f, t)
local r = {}
for _, v in pairs (t) do
local o = f (v)
if o then
table.insert (r, o)
end
end
return r
end
-- Concatenate elements of table ALTERNATIVES much like `table.concat`
-- except the separator is always ", ". If INFIX is provided, the
-- final separotor uses that instead of ", ". If QUOTED is not nil or
-- false, then any elements of ALTERNATIVES with type "string" will be
-- quoted using `string.format ("%q")` before concatenation.
local function concat (alternatives, infix, quoted)
infix = infix or ", "
if quoted ~= nil then
alternatives = map (function (v)
if object.type (v) ~= "string" then
return std.string.tostring (v)
else
return ("%q"):format (v)
end
end, alternatives)
end
return table.concat (alternatives, ", "):gsub (", ([^,]+)$", infix .. "%1")
end
-- Simplified object.type, that just returns "object" for non-primitive
-- types, or else the primitive type name.
local function xtype (x)
if type (x) == "table" and object.type (x) ~= "table" then
return "object"
end
return type (x)
end
-- Write a function call type error similar to how Lua core does it.
local function type_error (name, i, arglist, typelist)
local actual = "no value"
if arglist[i] then actual = object.type (arglist[i]) end
local expected = typelist[i]
if object.type (expected) ~= "table" then expected = {expected} end
expected = concat (expected, " or "):gsub ("#table", "non-empty table")
error ("bad argument #" .. tostring (i) .. " to '" .. name ..
"' (" .. expected .. " expected, got " .. actual .. ")\n" ..
"received: '" .. tostring (arglist[i]) .. "'", 3)
end
-- Check that every parameter in <arglist> matches one of the types
-- from the corresponding slot in <typelist>. Raise a parameter type
-- error if there are any mismatches.
-- There are a few additional strings you can use in <typelist> to
-- match special types in <arglist>:
--
-- #table accept any non-empty table
-- object accept any std.Object derived type
-- any accept any type
local function type_check (name, arglist, typelist)
for i, v in ipairs (typelist) do
if v ~= "any" then
if object.type (v) ~= "table" then v = {v} end
if i > #arglist then
type_error (name, i, arglist, typelist)
end
local a = object.type (arglist[i])
-- check that argument at `i` has one of the types at typelist[i].
local ok = false
for _, check in ipairs (v) do
if check == "#table" then
if a == "table" and #arglist[i] > 0 then
ok = true
break
end
elseif check == "object" then
if type (arglist[i]) == "table" and object.type (arglist[i]) ~= "table" then
ok = true
break
end
elseif a == check then
ok = true
break
end
end
if not ok then
type_error (name, i, arglist, typelist)
end
end
end
end
-- Return an appropriate indent for last element of DESCRIPTIONS.
local function indent (descriptions)
return string.rep (" ", #descriptions - 1)
end
-- Return S with the first word and following whitespace stripped,
-- where S contains some whitespace initially (i.e single words are
-- returned unchanged).
local function strip1st (s)
return s:gsub ("^%s*%w+%s+", "")
end
--[[ ----------------- ]]--
--[[ Public Interface. ]]--
--[[ ----------------- ]]--
-- Don't prevent examples from loading a different luaposix.
for _, reload in pairs {"posix", "posix_c", "posix.sys"} do
package.loaded[reload] = nil
end
local M = {
-- Functions
concat = concat,
deepcopy = deepcopy,
files = files,
gettimeofday = gettimeofday,
have_posix = have_posix,
indent = indent,
nop = nop,
map = map,
strip1st = strip1st,
timesince = timesince,
type = xtype,
type_check = type_check,
}
return M
|
-- Miscellaneous utility functions.
-- Written by Gary V. Vaughan, 2013
--
-- Copyright (c) 2013-2014 Gary V. Vaughan
--
-- 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, 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; see the file COPYING. If not, write to the
-- Free Software Foundation, Fifth Floor, 51 Franklin Street, Boston,
-- MA 02111-1301, USA.
local std = require "specl.std"
local have_posix, posix = pcall (require, "posix")
local object = std.object
-- A null operation function.
local function nop () end
local files, timersub -- forward declarations
if have_posix then
files = function (root, t)
t = t or {}
for _, file in ipairs (posix.dir (root) or {}) do
if file ~= "." and file ~= ".." then
local path = std.io.catfile (root, file)
if posix.stat (path).type == "directory" then
t = files (path, t)
else
t[#t + 1] = path
end
end
end
return t
end
timersub = posix.sys and posix.sys.timersub or posix.timersub
else
files = nop
end
-- Use higher resolution timers from luaposix if available.
local function gettimeofday ()
if not (have_posix and timersub) then
return os.time ()
end
return posix.gettimeofday ()
end
local function timesince (earlier)
if not (have_posix and timersub) then
return os.time () - earlier
end
local elapsed = timersub (posix.gettimeofday (), earlier)
return (elapsed.usec / 1000000) + elapsed.sec
end
-- Return a complete copy of T, along with copied metatables.
local function deepcopy (t)
local copied = {} -- references to tables already copied
local function tablecopy (orig)
local mt = getmetatable (orig)
local copy = mt and setmetatable ({}, copied[mt] or tablecopy (mt)) or {}
copied[orig] = copy
for k, v in next, orig, nil do -- don't trigger __pairs metamethod
if type (k) == "table" then k = copied[k] or tablecopy (k) end
if type (v) == "table" then v = copied[v] or tablecopy (v) end
rawset (copy, k, v)
end
return copy
end
return tablecopy (t)
end
-- Map function F over elements of T and return a table of results.
local function map (f, t)
local r = {}
for _, v in pairs (t) do
local o = f (v)
if o then
table.insert (r, o)
end
end
return r
end
-- Concatenate elements of table ALTERNATIVES much like `table.concat`
-- except the separator is always ", ". If INFIX is provided, the
-- final separotor uses that instead of ", ". If QUOTED is not nil or
-- false, then any elements of ALTERNATIVES with type "string" will be
-- quoted using `string.format ("%q")` before concatenation.
local function concat (alternatives, infix, quoted)
infix = infix or ", "
if quoted ~= nil then
alternatives = map (function (v)
if object.type (v) ~= "string" then
return std.string.tostring (v)
else
return ("%q"):format (v)
end
end, alternatives)
end
return table.concat (alternatives, ", "):gsub (", ([^,]+)$", infix .. "%1")
end
-- Simplified object.type, that just returns "object" for non-primitive
-- types, or else the primitive type name.
local function xtype (x)
if type (x) == "table" and object.type (x) ~= "table" then
return "object"
end
return type (x)
end
-- Write a function call type error similar to how Lua core does it.
local function type_error (name, i, arglist, typelist)
local actual = "no value"
if arglist[i] then actual = object.type (arglist[i]) end
local expected = typelist[i]
if object.type (expected) ~= "table" then expected = {expected} end
expected = concat (expected, " or "):gsub ("#table", "non-empty table")
error ("bad argument #" .. tostring (i) .. " to '" .. name ..
"' (" .. expected .. " expected, got " .. actual .. ")\n" ..
"received: '" .. tostring (arglist[i]) .. "'", 3)
end
-- Check that every parameter in <arglist> matches one of the types
-- from the corresponding slot in <typelist>. Raise a parameter type
-- error if there are any mismatches.
-- There are a few additional strings you can use in <typelist> to
-- match special types in <arglist>:
--
-- #table accept any non-empty table
-- object accept any std.Object derived type
-- any accept any type
local function type_check (name, arglist, typelist)
for i, v in ipairs (typelist) do
if v ~= "any" then
if object.type (v) ~= "table" then v = {v} end
if i > #arglist then
type_error (name, i, arglist, typelist)
end
local a = object.type (arglist[i])
-- check that argument at `i` has one of the types at typelist[i].
local ok = false
for _, check in ipairs (v) do
if check == "#table" then
if a == "table" and #arglist[i] > 0 then
ok = true
break
end
elseif check == "object" then
if type (arglist[i]) == "table" and object.type (arglist[i]) ~= "table" then
ok = true
break
end
elseif a == check then
ok = true
break
end
end
if not ok then
type_error (name, i, arglist, typelist)
end
end
end
end
-- Return an appropriate indent for last element of DESCRIPTIONS.
local function indent (descriptions)
return string.rep (" ", #descriptions - 1)
end
-- Return S with the first word and following whitespace stripped,
-- where S contains some whitespace initially (i.e single words are
-- returned unchanged).
local function strip1st (s)
return s:gsub ("^%s*%w+%s+", "")
end
--[[ ----------------- ]]--
--[[ Public Interface. ]]--
--[[ ----------------- ]]--
-- Don't prevent examples from loading a different luaposix.
for k in pairs (package.loaded) do
if k == "posix" or k == "posix_c" or k:match "^posix%." then
package.loaded[k] = nil
end
end
local M = {
-- Functions
concat = concat,
deepcopy = deepcopy,
files = files,
gettimeofday = gettimeofday,
have_posix = have_posix,
indent = indent,
nop = nop,
map = map,
strip1st = strip1st,
timesince = timesince,
type = xtype,
type_check = type_check,
}
return M
|
maint: unload luaposix > v32 correctly.
|
maint: unload luaposix > v32 correctly.
* lib/specl/util.lua: Unload any module with a name prefixed by
"posix", in order that autoloaded submodules for an installed
recent luaposix are dropped in favour of test versions as
necessary.
Signed-off-by: Gary V. Vaughan <[email protected]>
|
Lua
|
mit
|
gvvaughan/specl
|
8c11f5ae917a0f81b4bcf604c76b3967430ba111
|
misc/freeswitch/scripts/common/object.lua
|
misc/freeswitch/scripts/common/object.lua
|
-- Gemeinschaft 5 module: object class
-- (c) AMOOMA GmbH 2013
--
module(...,package.seeall)
Object = {}
-- create object object ;)
function Object.new(self, arg)
arg = arg or {}
object = arg.object or {}
setmetatable(object, self);
self.__index = self;
self.class = 'object';
self.log = arg.log;
self.database = arg.database;
return object;
end
-- find object
function Object.find(self, attributes)
if not attributes.class then
return nil;
end
local object = nil;
require 'common.str';
local class = common.str.downcase(attributes.class);
if class == 'user' then
require 'dialplan.user';
if tonumber(attributes.id) then
object = dialplan.user.User:new{ log = self.log, database = self.database }:find_by_id(attributes.id);
elseif not common.str.blank(attributes.uuid) then
object = dialplan.user.User:new{ log = self.log, database = self.database }:find_by_uuid(attributes.uuid);
end
if object then
object.user_groups = object:list_groups();
end
elseif class == 'tenant' then
require 'dialplan.tenant';
if tonumber(attributes.id) then
object = dialplan.tenant.Tenant:new{ log = self.log, database = self.database }:find_by_id(attributes.id);
elseif not common.str.blank(attributes.uuid) then
object = dialplan.tenant.Tenant:new{ log = self.log, database = self.database }:find_by_uuid(attributes.uuid);
end
elseif class == 'sipaccount' then
require 'common.sip_account';
if not common.str.blank(attributes.auth_name) then
object = common.sip_account.SipAccount:new{ log = self.log, database = self.database }:find_by_auth_name(attributes.auth_name, attributes.domain);
elseif tonumber(attributes.id) then
object = common.sip_account.SipAccount:new{ log = self.log, database = self.database }:find_by_id(attributes.id);
elseif not common.str.blank(attributes.uuid) then
object = common.sip_account.SipAccount:new{ log = self.log, database = self.database }:find_by_uuid(attributes.uuid);
end
if object then
object.owner = self:find{class = object.record.sip_accountable_type, id = tonumber(object.record.sip_accountable_id)};
end
elseif class == 'huntgroup' then
require 'dialplan.hunt_group';
if tonumber(attributes.id) then
object = dialplan.hunt_group.HuntGroup:new{ log = self.log, database = self.database }:find_by_id(attributes.id);
elseif not common.str.blank(attributes.uuid) then
object = dialplan.hunt_group.HuntGroup:new{ log = self.log, database = self.database }:find_by_uuid(attributes.uuid);
end
if object then
object.owner = self:find{class = 'tenant', id = tonumber(object.record.tenant_id)};
end
elseif class == 'automaticcalldistributor' then
require 'dialplan.acd';
if tonumber(attributes.id) then
object = dialplan.acd.AutomaticCallDistributor:new{ log = self.log, database = self.database, domain = self.domain }:find_by_id(attributes.id);
elseif not common.str.blank(attributes.uuid) then
object = dialplan.acd.AutomaticCallDistributor:new{ log = self.log, database = self.database, domain = self.domain }:find_by_uuid(attributes.uuid);
end
if object then
object.owner = self:find{class = object.record.automatic_call_distributorable_type, id = tonumber(object.record.automatic_call_distributorable_id)};
end
elseif class == 'faxaccount' then
require 'dialplan.fax';
if tonumber(attributes.id) then
fax_account = dialplan.fax.Fax:new{ log = self.log, database = self.database }:find_by_id(attributes.id);
elseif not common.str.blank(attributes.uuid) then
fax_account = dialplan.fax.Fax:new{ log = self.log, database = self.database }:find_by_uuid(attributes.uuid);
end
if object then
object.owner = self:find{class = fax_account.record.fax_accountable_type, id = tonumber(fax_account.record.fax_accountable_id)};
end
end
if object then
require 'common.group';
object.groups, object.group_ids = common.group.Group:new{ log = self.log, database = self.database }:name_id_by_member(object.id, object.class);
end
return object;
end
|
-- Gemeinschaft 5 module: object class
-- (c) AMOOMA GmbH 2013
--
module(...,package.seeall)
Object = {}
-- create object object ;)
function Object.new(self, arg)
arg = arg or {}
object = arg.object or {}
setmetatable(object, self);
self.__index = self;
self.class = 'object';
self.log = arg.log;
self.database = arg.database;
return object;
end
-- find object
function Object.find(self, attributes)
if not attributes.class then
return nil;
end
local object = nil;
require 'common.str';
local class = common.str.downcase(attributes.class);
if class == 'user' then
require 'dialplan.user';
if tonumber(attributes.id) then
object = dialplan.user.User:new{ log = self.log, database = self.database }:find_by_id(attributes.id);
elseif not common.str.blank(attributes.uuid) then
object = dialplan.user.User:new{ log = self.log, database = self.database }:find_by_uuid(attributes.uuid);
end
if object then
object.user_groups = object:list_groups();
end
elseif class == 'tenant' then
require 'dialplan.tenant';
if tonumber(attributes.id) then
object = dialplan.tenant.Tenant:new{ log = self.log, database = self.database }:find_by_id(attributes.id);
elseif not common.str.blank(attributes.uuid) then
object = dialplan.tenant.Tenant:new{ log = self.log, database = self.database }:find_by_uuid(attributes.uuid);
end
elseif class == 'sipaccount' then
require 'common.sip_account';
if not common.str.blank(attributes.auth_name) then
object = common.sip_account.SipAccount:new{ log = self.log, database = self.database }:find_by_auth_name(attributes.auth_name, attributes.domain);
elseif tonumber(attributes.id) then
object = common.sip_account.SipAccount:new{ log = self.log, database = self.database }:find_by_id(attributes.id);
elseif not common.str.blank(attributes.uuid) then
object = common.sip_account.SipAccount:new{ log = self.log, database = self.database }:find_by_uuid(attributes.uuid);
end
if object then
object.owner = self:find{class = object.record.sip_accountable_type, id = tonumber(object.record.sip_accountable_id)};
end
elseif class == 'huntgroup' then
require 'dialplan.hunt_group';
if tonumber(attributes.id) then
object = dialplan.hunt_group.HuntGroup:new{ log = self.log, database = self.database }:find_by_id(attributes.id);
elseif not common.str.blank(attributes.uuid) then
object = dialplan.hunt_group.HuntGroup:new{ log = self.log, database = self.database }:find_by_uuid(attributes.uuid);
end
if object then
object.owner = self:find{class = 'tenant', id = tonumber(object.record.tenant_id)};
end
elseif class == 'automaticcalldistributor' then
require 'dialplan.acd';
if tonumber(attributes.id) then
object = dialplan.acd.AutomaticCallDistributor:new{ log = self.log, database = self.database, domain = self.domain }:find_by_id(attributes.id);
elseif not common.str.blank(attributes.uuid) then
object = dialplan.acd.AutomaticCallDistributor:new{ log = self.log, database = self.database, domain = self.domain }:find_by_uuid(attributes.uuid);
end
if object then
object.owner = self:find{class = object.record.automatic_call_distributorable_type, id = tonumber(object.record.automatic_call_distributorable_id)};
end
elseif class == 'faxaccount' then
require 'dialplan.fax';
if tonumber(attributes.id) then
object = dialplan.fax.Fax:new{ log = self.log, database = self.database }:find_by_id(attributes.id);
elseif not common.str.blank(attributes.uuid) then
object = dialplan.fax.Fax:new{ log = self.log, database = self.database }:find_by_uuid(attributes.uuid);
end
if object then
object.owner = self:find{class = object.record.fax_accountable_type, id = tonumber(object.record.fax_accountable_id)};
end
end
if object then
require 'common.group';
object.groups, object.group_ids = common.group.Group:new{ log = self.log, database = self.database }:name_id_by_member(object.id, object.class);
end
return object;
end
|
retrieving fax objects fixed
|
retrieving fax objects fixed
|
Lua
|
mit
|
amooma/GS5,funkring/gs5,amooma/GS5,amooma/GS5,funkring/gs5,amooma/GS5,funkring/gs5,funkring/gs5
|
3314a2f000a210fa6bd6b4e6e568d096b9b43e14
|
mod_watchuntrusted/mod_watchuntrusted.lua
|
mod_watchuntrusted/mod_watchuntrusted.lua
|
local jid_prep = require "util.jid".prep;
local secure_auth = module:get_option_boolean("s2s_secure_auth", false);
local secure_domains, insecure_domains =
module:get_option_set("s2s_secure_domains", {})._items, module:get_option_set("s2s_insecure_domains", {})._items;
local untrusted_fail_watchers = module:get_option_set("untrusted_fail_watchers", module:get_option("admins", {})) / jid_prep;
local untrusted_fail_notification = module:get_option("untrusted_fail_notification", "Establishing a secure connection from $from_host to $to_host failed. Certificate hash: $sha1. $errors");
local st = require "util.stanza";
local notified_about_already = { };
module:hook_global("s2s-check-certificate", function (event)
local session, host = event.session, event.host;
local conn = session.conn:socket();
local local_host = session.direction == "outgoing" and session.from_host or session.to_host;
if not (local_host == module:get_host()) then return end
module:log("debug", "Checking certificate...");
local must_secure = secure_auth;
if not must_secure and secure_domains[host] then
must_secure = true;
elseif must_secure and insecure_domains[host] then
must_secure = false;
end
if must_secure and (session.cert_chain_status ~= "valid" or session.cert_identity_status ~= "valid") and not notified_about_already[host] then
notified_about_already[host] = os.time();
local _, errors = conn:getpeerverification();
local error_message = "";
for depth, t in pairs(errors or {}) do
if #t > 0 then
error_message = error_message .. "Error with certificate " .. (depth - 1) .. ": " .. table.concat(t, ", ") .. ". ";
end
end
if session.cert_identity_status then
error_message = error_message .. "This certificate is " .. session.cert_identity_status .. " for " .. host .. ".";
end
local replacements = { sha1 = event.cert and event.cert:digest("sha1"), errors = error_message };
local message = st.message{ type = "chat", from = local_host }
:tag("body")
:text(untrusted_fail_notification:gsub("%$([%w_]+)", function (v)
return event[v] or session and session[v] or replacements and replacements[v] or nil;
end));
for jid in untrusted_fail_watchers do
module:log("debug", "Notifying %s", jid);
message.attr.to = jid;
module:send(message);
end
end
end, -0.5);
module:add_timer(14400, function (now)
for host, time in pairs(notified_about_already) do
if time + 86400 > now then
notified_about_already[host] = nil;
end
end
end)
|
local jid_prep = require "util.jid".prep;
local secure_auth = module:get_option_boolean("s2s_secure_auth", false);
local secure_domains, insecure_domains =
module:get_option_set("s2s_secure_domains", {})._items, module:get_option_set("s2s_insecure_domains", {})._items;
local untrusted_fail_watchers = module:get_option_set("untrusted_fail_watchers", module:get_option("admins", {})) / jid_prep;
local untrusted_fail_notification = module:get_option("untrusted_fail_notification", "Establishing a secure connection from $from_host to $to_host failed. Certificate hash: $sha1. $errors");
local st = require "util.stanza";
local notified_about_already = { };
module:hook_global("s2s-check-certificate", function (event)
local session, host = event.session, event.host;
if not host then return end
local conn = session.conn:socket();
local local_host = session.direction == "outgoing" and session.from_host or session.to_host;
if not (local_host == module:get_host()) then return end
module:log("debug", "Checking certificate...");
local must_secure = secure_auth;
if not must_secure and secure_domains[host] then
must_secure = true;
elseif must_secure and insecure_domains[host] then
must_secure = false;
end
if must_secure and (session.cert_chain_status ~= "valid" or session.cert_identity_status ~= "valid") and not notified_about_already[host] then
notified_about_already[host] = os.time();
local _, errors = conn:getpeerverification();
local error_message = "";
for depth, t in pairs(errors or {}) do
if #t > 0 then
error_message = error_message .. "Error with certificate " .. (depth - 1) .. ": " .. table.concat(t, ", ") .. ". ";
end
end
if session.cert_identity_status then
error_message = error_message .. "This certificate is " .. session.cert_identity_status .. " for " .. host .. ".";
end
local replacements = { sha1 = event.cert and event.cert:digest("sha1"), errors = error_message };
local message = st.message{ type = "chat", from = local_host }
:tag("body")
:text(untrusted_fail_notification:gsub("%$([%w_]+)", function (v)
return event[v] or session and session[v] or replacements and replacements[v] or nil;
end));
for jid in untrusted_fail_watchers do
module:log("debug", "Notifying %s", jid);
message.attr.to = jid;
module:send(message);
end
end
end, -0.5);
module:add_timer(14400, function (now)
for host, time in pairs(notified_about_already) do
if time + 86400 > now then
notified_about_already[host] = nil;
end
end
end)
|
mod_watchuntrusted: Skip connections to/from unknown hosts (fixes possible traceback)
|
mod_watchuntrusted: Skip connections to/from unknown hosts (fixes possible traceback)
|
Lua
|
mit
|
Craige/prosody-modules,amenophis1er/prosody-modules,mardraze/prosody-modules,dhotson/prosody-modules,vfedoroff/prosody-modules,vfedoroff/prosody-modules,1st8/prosody-modules,syntafin/prosody-modules,guilhem/prosody-modules,apung/prosody-modules,prosody-modules/import,amenophis1er/prosody-modules,jkprg/prosody-modules,asdofindia/prosody-modules,asdofindia/prosody-modules,vince06fr/prosody-modules,olax/prosody-modules,Craige/prosody-modules,1st8/prosody-modules,mmusial/prosody-modules,olax/prosody-modules,mardraze/prosody-modules,jkprg/prosody-modules,obelisk21/prosody-modules,mmusial/prosody-modules,guilhem/prosody-modules,mardraze/prosody-modules,LanceJenkinZA/prosody-modules,obelisk21/prosody-modules,guilhem/prosody-modules,iamliqiang/prosody-modules,dhotson/prosody-modules,syntafin/prosody-modules,mmusial/prosody-modules,iamliqiang/prosody-modules,heysion/prosody-modules,dhotson/prosody-modules,syntafin/prosody-modules,LanceJenkinZA/prosody-modules,prosody-modules/import,vince06fr/prosody-modules,1st8/prosody-modules,mmusial/prosody-modules,vince06fr/prosody-modules,syntafin/prosody-modules,amenophis1er/prosody-modules,mmusial/prosody-modules,apung/prosody-modules,LanceJenkinZA/prosody-modules,mardraze/prosody-modules,vfedoroff/prosody-modules,Craige/prosody-modules,asdofindia/prosody-modules,olax/prosody-modules,apung/prosody-modules,heysion/prosody-modules,heysion/prosody-modules,mardraze/prosody-modules,amenophis1er/prosody-modules,iamliqiang/prosody-modules,iamliqiang/prosody-modules,amenophis1er/prosody-modules,prosody-modules/import,dhotson/prosody-modules,olax/prosody-modules,apung/prosody-modules,1st8/prosody-modules,syntafin/prosody-modules,jkprg/prosody-modules,dhotson/prosody-modules,guilhem/prosody-modules,vfedoroff/prosody-modules,prosody-modules/import,vfedoroff/prosody-modules,Craige/prosody-modules,guilhem/prosody-modules,jkprg/prosody-modules,heysion/prosody-modules,asdofindia/prosody-modules,olax/prosody-modules,LanceJenkinZA/prosody-modules,asdofindia/prosody-modules,jkprg/prosody-modules,vince06fr/prosody-modules,1st8/prosody-modules,prosody-modules/import,vince06fr/prosody-modules,obelisk21/prosody-modules,apung/prosody-modules,obelisk21/prosody-modules,LanceJenkinZA/prosody-modules,heysion/prosody-modules,iamliqiang/prosody-modules,obelisk21/prosody-modules,Craige/prosody-modules
|
25dc8b68ccc495e3de3fc5b0975491fbe36b7d17
|
himan-scripts/pressure-code.lua
|
himan-scripts/pressure-code.lua
|
-- Find low/high pressure centers
-- https://wiki.fmi.fi/display/PROJEKTIT/Painekeskukset
-- partio 20161219
local MISS = missing
-- Create area masks used later
-- This mask is for ECMWF; for other models with different
-- horizontal grid size it would need to be adjusted
local mask1 = matrix(3, 3, 1, MISS)
mask1:SetValues({MISS, 1, MISS, 1, 1, 1, MISS, 1, MISS})
local mask2 = matrix(21, 21, 1, MISS)
mask2:SetValues({
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
})
local p = luatool:FetchInfo(current_time, current_level, param("P-PA"))
if not p then
return
end
-- Get 'matrix'
local pdata = p:GetData()
local pMin1 = Min2D(pdata, mask1):GetValues()
local pMin2 = Min2D(pdata, mask2):GetValues()
local pMax1 = Max2D(pdata, mask1):GetValues()
local pMax2 = Max2D(pdata, mask2):GetValues()
pressureCode = {}
for i=1,#pMax1 do
pressureCode[i] = MISS
if pMin1[i] == pMin1[i] and pMin2[i] == pMin2[i] and pMin1[i] == pMin2[i] then
-- Mirri font code 53 = "M"
pressureCode[i] = 53
end
if pMax1[i] == pMax1[i] and pMax2[i] == pMax2[i] and pMax1[i] == pMax2[i] then
-- Mirri font code 49 = "K"
pressureCode[i] = 49
end
end
result:SetParam(param("P-N"))
result:SetValues(pressureCode)
luatool:WriteToFile(result)
|
-- Find low/high pressure centers
-- https://wiki.fmi.fi/display/PROJEKTIT/Painekeskukset
-- partio 20161219
local MISS = missing
-- Create area masks used later
-- This mask is for ECMWF; for other models with different
-- horizontal grid size it would need to be adjusted
local mask1 = matrix(3, 3, 1, MISS)
mask1:SetValues({MISS, 1, MISS, 1, 1, 1, MISS, 1, MISS})
local mask2 = matrix(21, 21, 1, MISS)
mask2:SetValues({
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
})
local p = luatool:FetchInfo(current_time, current_level, param("P-PA"))
if not p then
return
end
-- Get 'matrix'
local pdata = p:GetData()
local pMin1 = Min2D(pdata, mask1, configuration:GetUseCuda()):GetValues()
local pMin2 = Min2D(pdata, mask2, configuration:GetUseCuda()):GetValues()
local pMax1 = Max2D(pdata, mask1, configuration:GetUseCuda()):GetValues()
local pMax2 = Max2D(pdata, mask2, configuration:GetUseCuda()):GetValues()
pressureCode = {}
for i=1,#pMax1 do
pressureCode[i] = MISS
if pMin1[i] == pMin1[i] and pMin2[i] == pMin2[i] and pMin1[i] == pMin2[i] then
-- Mirri font code 53 = "M"
pressureCode[i] = 53
end
if pMax1[i] == pMax1[i] and pMax2[i] == pMax2[i] and pMax1[i] == pMax2[i] then
-- Mirri font code 49 = "K"
pressureCode[i] = 49
end
end
result:SetParam(param("P-N"))
result:SetValues(pressureCode)
luatool:WriteToFile(result)
|
Bugfix: Min2D/Max2D require a third argument as well
|
Bugfix: Min2D/Max2D require a third argument as well
|
Lua
|
mit
|
fmidev/himan,fmidev/himan,fmidev/himan
|
1a4a5f70d46831a312735bc6762a8505dbce8983
|
VeggieTales/luaScripts/chem_extract_auto.lua
|
VeggieTales/luaScripts/chem_extract_auto.lua
|
assert(loadfile("luaScripts/chem_notepad.lua"))();
cheapRecipes = nil;
allRecipes = nil;
local types = {"Ra", "Thoth", "Osiris", "Set", "Maat", "Geb"};
local typePlus = {"+++++", "++++", "++++", "+++", "+++", "++"};
local typeMinus = {"-----", "----", "----", "---", "---", "--"};
local typeEnabled = {true, true, true, true, true, true};
local properties = {"Aromatic", "Astringent", "Bitter", "Salty",
"Sour", "Spicy", "Sweet", "Toxic"};
local props = {"Ar", "As", "Bi", "Sa", "So", "Sp", "Sw", "To"};
function doit()
cheapRecipes = loadNotes("luascripts/chem-cheap.txt");
allRecipes = loadNotes("luascripts/chem-all.txt");
askForWindow("Magical Chemistry Vibes of Doom!!!!!!\n \n To view detailed instructions:\n \nClick Exit button, Open Folder button\nDouble click 'chem_extract_auto.txt' to view detailed instructions!\n \nClick Shift over ATITD window to continue.");
while true do
tryAllTypes();
sleepWithStatus(2000, "Making more magic");
end
end
function tryAllTypes()
for i=1,#types do
local done = false;
if typeEnabled[i] then
statusScreen("Trying type " .. types[i]);
srReadScreen();
clickAllText(types[i] .. "'s Compound");
local anchor = waitForText("Required:");
if anchor then
local tags = {types[i]};
local window = getWindowBorders(anchor[0], anchor[1]);
addRequirements(tags, findAllText(typePlus[i], window), typePlus[i]);
addRequirements(tags, findAllText(typeMinus[i], window), typeMinus[i]);
local recipe = lookupData(cheapRecipes, tags);
if not recipe and i <= 2 then
recipe = lookupData(allRecipes, tags);
end
if recipe then
lsPrintln("tags: " .. table.concat(tags, ", "));
-- if not recipe then
-- lsPrintln("Boohoo");
-- end
-- if recipe then
-- lsPrintln("Impossible");
-- else
-- lsPrintln("else");
-- end
-- lsPrintln("Recipe: " .. table.concat(recipe, "---"));
local recipeList = csplit(recipe, ",");
lsPrintln("After csplit");
done = true;
local done = makeRecipe(recipeList, window);
if done then
break;
end
else
lsPrintln("No recipe for " .. table.concat(tags, ","));
end
end
while clickAllImages("Cancel.png") == 1 do
sleepWithStatus(200, types[i] .. " not found: Cancel");
end
end
end
end
function addRequirements(tags, lines, sign)
for i=1,#lines do
for j=1,#properties do
if string.match(lines[i][2], properties[j]) then
table.insert(tags, props[j] .. sign);
break;
end
end
end
end
function makeRecipe(recipe, window)
statusScreen("Checking ingredients: " .. table.concat(recipe, ", "));
local ingredients = findIngredients(recipe);
if #ingredients < 5 then
askForWindow("Not enough essences for recipe "
.. table.concat(recipe, ", "));
return false;
end
local t = nil;
for i=1,#ingredients do
statusScreen("Adding Essence of " .. recipe[i]);
safeClick(ingredients[i][0]+10, ingredients[i][1]+5);
waitForText("many?", 5000, "", nil, NOPIN);
srKeyEvent("7\n");
local ingredientWindow = getWindowBorders(ingredients[i][0]+10,
ingredients[i][1]+5);
safeClick(ingredientWindow.x + 2, ingredientWindow.y + 2);
t = waitForText("Manufacture");
safeClick(t[0]+10, t[1]+5);
t = waitForText("Essential Mixture");
safeClick(t[0]+10, t[1]+5);
t = waitForText("Add Essence");
safeClick(t[0]+10, t[1]+5);
local done = false;
while not done do
local spot = findWithoutParen(recipe[i]);
if spot then
safeClick(spot[0]+10, spot[1]+5);
done = true;
end
checkBreak();
end
end
statusScreen("Mixing Compound");
t = waitForText("Manufacture");
safeClick(t[0]+10, t[1]+5);
t = waitForText("Essential Mixture");
safeClick(t[0]+10, t[1]+5);
t = waitForText("Mix Comp");
safeClick(t[0]+10, t[1]+5);
waitForText("do you wish to name it?");
srKeyEvent("autocompound\n");
sleepWithStatus(300, "Updating");
clickAllText("This is a Chemistry Lab");
sleepWithStatus(300, "Updating");
t = waitForText("Take...");
safeClick(t[0]+10, t[1]+5);
t = waitForText("Everything");
safeClick(t[0]+10, t[1]+5);
statusScreen("Creating extract");
t = waitForText("Essential Comp", nil, "Waiting for autocompound",
makeBox(window.x + 10, window.y,
window.width - 10, window.height));
safeClick(t[0]+10, t[1]+5);
sleepWithStatus(200);
clickAllImages("Okb.png");
sleepWithStatus(200);
return true;
end
function findIngredients(names)
local result = {};
for i=1,#names do
local current = findTextPrefix(names[i]);
if current then
local window = getWindowBorders(current[0], current[1]);
safeClick(window.x+2, window.y+2);
lsSleep(100);
current = findTextPrefix(names[i], window);
if current then
local first, len, match = string.find(current[2], "%(([0-9]+)");
local count = tonumber(match);
if count and count >= 7 then
table.insert(result, current);
elseif count then
lsPrintln("No essences for: " .. names[i] .. " (" .. count .. ")");
else
lsPrintln("No count for: " .. names[i]);
end
end
end
end
return result;
end
function findTextPrefix(text, window)
local result = nil;
local matches = findAllText(text, window);
for i=1,#matches do
local first = string.find(matches[i][2], text);
if first == 1 then
result = matches[i];
break;
end
end
return result;
end
function findWithoutParen(text)
local result = nil;
local matches = findAllText(text);
for i=1,#matches do
local found = string.match(matches[i][2], "%(");
if not found then
result = matches[i];
break;
end
end
return result;
end
|
assert(loadfile("luaScripts/chem_notepad.lua"))();
cheapRecipes = nil;
allRecipes = nil;
local types = {"Ra", "Thoth", "Osiris", "Set", "Maat", "Geb"};
local typePlus = {"+++++", "++++", "++++", "+++", "+++", "++"};
local typeMinus = {"-----", "----", "----", "---", "---", "--"};
local typeEnabled = {true, true, true, true, true, true};
local properties = {"Aromatic", "Astringent", "Bitter", "Salty",
"Sour", "Spicy", "Sweet", "Toxic"};
local props = {"Ar", "As", "Bi", "Sa", "So", "Sp", "Sw", "To"};
function doit()
cheapRecipes = loadNotes("luascripts/chem-cheap.txt");
allRecipes = loadNotes("luascripts/chem-all.txt");
askForWindow("Setup for this macro is complicated. To view detailed instructions:\n \nClick Exit button, Open Folder button\nDouble click 'chem_extract_auto.txt'.\n \nClick Shift over ATITD window to continue.");
while true do
tryAllTypes();
sleepWithStatus(2000, "Making more magic");
end
end
function tryAllTypes()
for i=1,#types do
local done = false;
if typeEnabled[i] then
statusScreen("Trying type " .. types[i]);
srReadScreen();
clickAllText(types[i] .. "'s Compound");
local anchor = waitForText("Required:");
if anchor then
local tags = {types[i]};
local window = getWindowBorders(anchor[0], anchor[1]);
addRequirements(tags, findAllText(typePlus[i], window), typePlus[i]);
addRequirements(tags, findAllText(typeMinus[i], window), typeMinus[i]);
local recipe = lookupData(cheapRecipes, tags);
if not recipe and i <= 2 then
recipe = lookupData(allRecipes, tags);
end
if recipe then
lsPrintln("tags: " .. table.concat(tags, ", "));
-- if not recipe then
-- lsPrintln("Boohoo");
-- end
-- if recipe then
-- lsPrintln("Impossible");
-- else
-- lsPrintln("else");
-- end
-- lsPrintln("Recipe: " .. table.concat(recipe, "---"));
local recipeList = csplit(recipe, ",");
lsPrintln("After csplit");
done = true;
local done = makeRecipe(recipeList, window);
if done then
break;
end
else
lsPrintln("No recipe for " .. table.concat(tags, ","));
end
end
while clickAllImages("Cancel.png") == 1 do
sleepWithStatus(200, types[i] .. " not found: Cancel");
end
end
end
end
function addRequirements(tags, lines, sign)
for i=1,#lines do
lsPrintln("Line: " .. lines[i][2]);
for j=1,#properties do
if string.match(lines[i][2], properties[j]) or
(properties[j] == "Toxic" and string.match(lines[i][2], "Txic"))
then
table.insert(tags, props[j] .. sign);
break;
end
end
end
end
function makeRecipe(recipe, window)
statusScreen("Checking ingredients: " .. table.concat(recipe, ", "));
local ingredients = findIngredients(recipe);
if #ingredients < 5 then
askForWindow("Not enough essences for recipe "
.. table.concat(recipe, ", "));
return false;
end
local t = nil;
for i=1,#ingredients do
local status = "Recipe: " .. table.concat(recipe, ", ") .. "\n\n\n" ..
"Adding Essence of " .. recipe[i];
-- statusScreen("Adding Essence of " .. recipe[i]);
safeClick(ingredients[i][0]+10, ingredients[i][1]+5);
waitForText("many?", 5000, status, nil, NOPIN);
srKeyEvent("7\n");
local ingredientWindow = getWindowBorders(ingredients[i][0]+10,
ingredients[i][1]+5);
safeClick(ingredientWindow.x + 2, ingredientWindow.y + 2);
t = waitForText("Manufacture", nil, status);
safeClick(t[0]+10, t[1]+5);
t = waitForText("Essential Mixture", nil, status);
safeClick(t[0]+10, t[1]+5);
t = waitForText("Add Essence", nil, status);
safeClick(t[0]+10, t[1]+5);
local done = false;
while not done do
local spot = findWithoutParen(recipe[i]);
if spot then
safeClick(spot[0]+10, spot[1]+5);
done = true;
end
checkBreak();
end
end
local status = "Mixing Compound";
t = waitForText("Manufacture", nil, status);
safeClick(t[0]+10, t[1]+5);
t = waitForText("Essential Mixture", nil, status);
safeClick(t[0]+10, t[1]+5);
t = waitForText("Mix Comp", nil, status);
safeClick(t[0]+10, t[1]+5);
waitForText("do you wish to name it?", nil, status);
srKeyEvent("autocompound\n");
sleepWithStatus(300, status);
clickAllText("This is a Chemistry Lab");
sleepWithStatus(300, status);
t = waitForText("Take...", nil, status);
safeClick(t[0]+10, t[1]+5);
t = waitForText("Everything", nil, status);
safeClick(t[0]+10, t[1]+5);
statusScreen("Creating extract", nil, status);
t = waitForText("Essential Comp", nil, status .. "\n\nWaiting for autocompound",
makeBox(window.x + 10, window.y,
window.width - 10, window.height));
safeClick(t[0]+10, t[1]+5);
sleepWithStatus(200, status);
clickAllImages("Okb.png");
sleepWithStatus(200, status);
return true;
end
function findIngredients(names)
local result = {};
for i=1,#names do
local current = findTextPrefix(names[i]);
if current then
local window = getWindowBorders(current[0], current[1]);
safeClick(window.x+2, window.y+2);
lsSleep(100);
current = findTextPrefix(names[i], window);
if current then
local first, len, match = string.find(current[2], "%(([0-9]+)");
local count = tonumber(match);
if count and count >= 7 then
table.insert(result, current);
elseif count then
lsPrintln("No essences for: " .. names[i] .. " (" .. count .. ")");
else
lsPrintln("No count for: " .. names[i]);
end
end
end
end
return result;
end
function findTextPrefix(text, window)
local result = nil;
local matches = findAllText(text, window);
for i=1,#matches do
local first = string.find(matches[i][2], text);
if first == 1 then
result = matches[i];
break;
end
end
return result;
end
function findWithoutParen(text)
local result = nil;
local matches = findAllText(text);
for i=1,#matches do
local found = string.match(matches[i][2], "%(");
if not found then
result = matches[i];
break;
end
end
return result;
end
|
Workaround for bug in OCR which sometimes reads 'Toxic' as 'Txic'.
|
Workaround for bug in OCR which sometimes reads 'Toxic' as 'Txic'.
|
Lua
|
mit
|
TheRealMaxion/Automato-ATITD,wzydhek/Automato-ATITD,MHoroszowski/Automato-ATITD,DashingStrike/Automato-ATITD,DashingStrike/Automato-ATITD,wzydhek/Automato-ATITD,TheRealMaxion/Automato-ATITD,MHoroszowski/Automato-ATITD
|
c3c5462e8fd07093151686394396a265eb0a355a
|
src/lua-factory/sources/grl-metrolyrics.lua
|
src/lua-factory/sources/grl-metrolyrics.lua
|
--[[
* Copyright (C) 2014 Victor Toso.
*
* Contact: Victor Toso <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; version 2.1 of
* the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
--]]
---------------------------
-- Source initialization --
---------------------------
source = {
id = "grl-metrolyrics",
name = "Metrolyrics",
description = "a source for lyrics",
supported_keys = { "lyrics" },
supported_media = { 'audio', 'video' },
resolve_keys = {
["type"] = "audio",
required = { "artist", "title" },
},
tags = { 'music', 'net:internet', 'net:plaintext' },
}
netopts = {
user_agent = "Grilo Source Metrolyrics/0.2.8",
}
------------------
-- Source utils --
------------------
METROLYRICS_INVALID_URL_CHARS = "[" .. "%(%)%[%]%$%&" .. "]"
METROLYRICS_DEFAULT_QUERY = "http://www.metrolyrics.com/%s-lyrics-%s.html"
---------------------------------
-- Handlers of Grilo functions --
---------------------------------
function grl_source_resolve(media, options, callback)
local url
local artist, title
if not media or not media.artist or not media.title
or #media.artist == 0 or #media.title == 0 then
callback()
return
end
-- Prepare artist and title strings to the url
artist = media.artist:gsub(METROLYRICS_INVALID_URL_CHARS, "")
artist = artist:gsub("%s+", "-")
title = media.title:gsub(METROLYRICS_INVALID_URL_CHARS, "")
title = title:gsub("%s+", "-")
url = string.format(METROLYRICS_DEFAULT_QUERY, title, artist)
local userdata = {callback = callback, media = media}
grl.fetch(url, netopts, fetch_page_cb, userdata)
end
---------------
-- Utilities --
---------------
function fetch_page_cb(feed, userdata)
if feed and not feed:find("notfound") then
local lyrics = metrolyrics_get_lyrics(feed)
if not lyrics then
userdata.callback()
return
end
userdata.media.lyrics = lyrics
end
userdata.callback(userdata.media, 0)
end
function metrolyrics_get_lyrics(feed)
local lyrics_body = '<div id="lyrics%-body%-text".->(.-)</div>'
local noise_array = {
{ noise = "</p>", sub = "\n\n" },
{ noise = "<p class='verse'><p class='verse'>", sub = "\n\n" },
{ noise = "<p class='verse'>", sub = "" },
{ noise = "<br/>", sub = "" },
{ noise = "<br>", sub = "" },
}
-- remove html noise
feed = feed:match(lyrics_body)
if not feed then
grl.warning ("This Lyrics do not match our parser! Please file a bug!")
return nil
end
for _, it in ipairs (noise_array) do
feed = feed:gsub(it.noise, it.sub)
end
-- strip the lyrics
feed = feed:gsub("^[%s%W]*(.-)[%s%W]*$", "%1")
return feed
end
|
--[[
* Copyright (C) 2014 Victor Toso.
*
* Contact: Victor Toso <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; version 2.1 of
* the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
--]]
---------------------------
-- Source initialization --
---------------------------
source = {
id = "grl-metrolyrics",
name = "Metrolyrics",
description = "a source for lyrics",
supported_keys = { "lyrics" },
supported_media = { 'audio', 'video' },
resolve_keys = {
["type"] = "audio",
required = { "artist", "title" },
},
tags = { 'music', 'net:internet', 'net:plaintext' },
}
netopts = {
user_agent = "Grilo Source Metrolyrics/0.2.8",
}
------------------
-- Source utils --
------------------
METROLYRICS_INVALID_URL_CHARS = "[" .. "%(%)%[%]%$%&" .. "]"
METROLYRICS_DEFAULT_QUERY = "http://www.metrolyrics.com/%s-lyrics-%s.html"
---------------------------------
-- Handlers of Grilo functions --
---------------------------------
function grl_source_resolve()
local url, req
local artist, title
req = grl.get_media_keys()
if not req or not req.artist or not req.title
or #req.artist == 0 or #req.title == 0 then
grl.callback()
return
end
-- Prepare artist and title strings to the url
artist = req.artist:gsub(METROLYRICS_INVALID_URL_CHARS, "")
artist = artist:gsub("%s+", "-")
title = req.title:gsub(METROLYRICS_INVALID_URL_CHARS, "")
title = title:gsub("%s+", "-")
url = string.format(METROLYRICS_DEFAULT_QUERY, title, artist)
grl.fetch(url, fetch_page_cb, netopts)
end
---------------
-- Utilities --
---------------
function fetch_page_cb(feed)
local media = nil
if feed and not feed:find("notfound") then
media = metrolyrics_get_lyrics(feed)
end
grl.callback(media, 0)
end
function metrolyrics_get_lyrics(feed)
local media = {}
local lyrics_body = '<div id="lyrics%-body%-text".->(.-)</div>'
local noise_array = {
{ noise = "</p>", sub = "\n\n" },
{ noise = "<p class='verse'><p class='verse'>", sub = "\n\n" },
{ noise = "<p class='verse'>", sub = "" },
{ noise = "<br/>", sub = "" },
{ noise = "<br>", sub = "" },
}
-- remove html noise
feed = feed:match(lyrics_body)
if not feed then
grl.warning ("This Lyrics do not match our parser! Please file a bug!")
return nil
end
for _, it in ipairs (noise_array) do
feed = feed:gsub(it.noise, it.sub)
end
-- strip the lyrics
feed = feed:gsub("^[%s%W]*(.-)[%s%W]*$", "%1")
-- switch table to string
media.lyrics = feed
return media
end
|
Revert "lua-factory: port grl-metrolyrics.lua to the new lua system"
|
Revert "lua-factory: port grl-metrolyrics.lua to the new lua system"
This reverts commit 0e71278f1616a55e4e0a3b719abbe978a4ad71af.
But keeps grl.fetch callback as function instead of string
https://bugzilla.gnome.org/show_bug.cgi?id=763046
|
Lua
|
lgpl-2.1
|
jasuarez/grilo-plugins,MikePetullo/grilo-plugins,grilofw/grilo-plugins,MikePetullo/grilo-plugins,MikePetullo/grilo-plugins,GNOME/grilo-plugins,grilofw/grilo-plugins,jasuarez/grilo-plugins,GNOME/grilo-plugins
|
eb25c21db86bf77d4edac85f7b204fddda387ff4
|
lua/tests/values/function_v.lua
|
lua/tests/values/function_v.lua
|
-- Copyright (c) 2009 Incremental IP Limited
-- see license.txt for license information
local series = require("test.series")
local object = require("rima.object")
local scope = require("rima.scope")
local expression = require("rima.expression")
local function_v = require("rima.values.function_v")
require("rima.public")
local rima = rima
module(...)
-- Tests -----------------------------------------------------------------------
function test(show_passes)
local T = series:new(_M, show_passes)
local D = expression.dump
local B = expression.bind
local E = expression.eval
T:test(object.isa(function_v:new({"a"}, 3), function_v), "isa(function_v:new(), function_v)")
T:check_equal(object.type(function_v:new({"a"}, 3)), "function_v", "type(function_v:new()) == 'function_v'")
T:expect_error(function() function_v:new({1}, 1) end,
"expected string or simple reference, got '1' %(number%)")
do
local a = rima.R"a"
T:expect_error(function() function_v:new({a[1]}, 1) end,
"expected string or simple reference, got 'a%[1%]' %(index%)")
local S = scope.create{ b=rima.free() }
T:expect_error(function() function_v:new({S.b}, 1) end,
"expected string or simple reference, got 'b' %(ref%)")
end
local a, b, c, x = rima.R"a, b, c, x"
do
local f = rima.R"f"
local S = scope.create{ f = function_v:new({a}, 3) }
T:expect_error(function() rima.E(f(), S) end,
"the function needs to be called with at least 1 arguments, got 0")
T:expect_error(function() rima.E(f(1, 2), S) end,
"the function needs to be called with 1 arguments, got 2")
T:expect_error(function() rima.E(f(1, 2, 3), S) end,
"the function needs to be called with 1 arguments, got 3")
end
do
local f = function_v:new({a}, 3)
local S = scope.new()
T:check_equal(f, "function(a) return 3", "function description")
T:check_equal(f:call({5}, S, E), 3)
end
do
local f = function_v:new({"a"}, 3 + a)
local S = scope.create{ x = rima.free() }
T:check_equal(f, "function(a) return 3 + a", "function description")
T:check_equal(f:call({x}, S, B), "3 + x")
T:check_equal(f:call({x}, S, E), "3 + x")
T:check_equal(f:call({5}, S, B), "3 + a")
T:check_equal(f:call({5}, S, E), 8)
T:check_equal(f:call({x}, scope.spawn(S, {x=10}), B), "3 + x")
T:check_equal(f:call({x}, scope.spawn(S, {x=10}), E), 13)
end
do
local f = function_v:new({a}, b + a)
local S = scope.create{ ["a, b"] = rima.free() }
T:check_equal(f, "function(a) return b + a", "function description")
T:check_equal(f:call({x}, S, E), "b + x")
T:check_equal(f:call({5}, S, E), "5 + b")
T:check_equal(f:call({1 + a}, S, E), "1 + a + b")
T:check_equal(f:call({1 + b}, S, E), "1 + 2*b")
local S2 = scope.spawn(S, {b=20})
T:check_equal(f:call({x}, S2, E), "20 + x")
T:check_equal(f:call({5}, S2, E), 25)
S2.x = 100
T:check_equal(f:call({x}, S2, E), 120)
S2.a = 1000
T:check_equal(f:call({x}, S2, E), 120)
end
do
local f = function_v:new({a, "b"}, 1 + a, nil, b^2)
local S = scope.create{ ["a, b"] = rima.free() }
T:check_equal(f, "function(a, b) return 1 + a", "function description")
T:check_equal(f:call({2 + x, 5, {x}}, S, B), "3 + b^2")
T:check_equal(f:call({2 + x, 5, {x}}, S, E), 28)
T:check_equal(f:call({5 * x, b, {x}}, S, E), "1 + 5*b^2")
end
do
local f = rima.R"f"
local S = scope.create{ f = function_v:new({"a", b}, 1 + a, nil, b^2) }
local e = 1 + f(1 + x, 3, {x})
T:check_equal(rima.E(e, S), 12)
end
do
local f, x, y = rima.R"f, x, y"
T:check_equal(rima.E(f(x), { f=rima.F({y}, rima.sin(y)) }), "sin(x)")
end
do
local y = rima.R"y"
T:check_equal(rima.F({y}, y^2)(5), 25)
end
do
local a, b, c, t, s, u = rima.R"a, b, c, t, s, u"
local S = scope.create{
a={w={{x=10,y={z=100}},{x=20,y={z=200}}}},
t=rima.F({b}, a.w[b].x),
s=rima.F({b}, a.w[b].y),
u=rima.F({b}, a.q[b].y) }
T:check_equal(D(t(1)), "call(ref(t), number(1))")
T:check_equal(t(1), "t(1)")
T:expect_ok(function() B(t(1), S) end, "binding")
T:check_equal(B(t(1), S), "a.w[1].x")
T:expect_ok(function() E(t(1), S) end, "eval")
T:check_equal(E(t(1), S), 10)
T:check_equal(E(t(2), S), 20)
local e = B(t(1), S)
T:check_equal(E(e, S), 10)
T:check_equal(D(s(1).z), "index(call(ref(s), number(1)), address(string(z)))")
T:check_equal(s(1).z, "s(1).z")
T:expect_ok(function() B(s(1).z, S) end, "binding")
T:check_equal(B(s(1).z, S), "a.w[1].y.z")
T:expect_ok(function() E(s(1).z, S) end, "eval")
T:check_equal(E(s(1).z, S), 100)
T:check_equal(E(s(2).z, S), 200)
local e = B(s(1).z, S)
T:check_equal(E(e, S), 100)
T:check_equal(s(1).q, "s(1).q")
T:expect_ok(function() B(s(1).q, S) end, "binding")
T:check_equal(B(s(1).q, S), "a.w[1].y.q")
T:expect_ok(function() E(s(1).q, S) end, "eval")
T:check_equal(E(s(1).q, S), "a.w[1].y.q")
T:check_equal(E(s(2).q, S), "a.w[2].y.q")
local e = B(s(1).q, S)
T:check_equal(E(e, S), "a.w[1].y.q")
T:check_equal(u(1).z, "u(1).z")
T:expect_ok(function() B(u(1).z, S) end, "binding")
T:check_equal(B(u(1).z, S), "a.q[1].y.z")
T:expect_ok(function() E(u(1).z, S) end, "eval")
T:check_equal(E(u(1).z, S), "a.q[1].y.z")
T:check_equal(E(u(2).z, S), "a.q[2].y.z")
local e = B(u(1).z, S)
T:check_equal(E(e, S), "a.q[1].y.z")
end
do
local a, b, i = rima.R"a, b, i"
local S = rima.scope.create{ a = { { 5 } }, b = rima.F({i}, a[1][i]) }
T:check_equal(E(a[1][1], S), 5)
T:check_equal(E(b(1), S), 5)
T:expect_error(function() E(b(1)[1], S) end, "error evaluating 'b%(1%)%[1%]' as 'a%[1, 1, 1%]':.*address: error resolving 'a%[1, 1, 1%]': 'a%[1, 1%]' is not indexable %(got '5' number%)")
end
-- more tests in expression
return T:close()
end
-- EOF -------------------------------------------------------------------------
|
-- Copyright (c) 2009 Incremental IP Limited
-- see license.txt for license information
local series = require("test.series")
local object = require("rima.object")
local scope = require("rima.scope")
local expression = require("rima.expression")
local function_v = require("rima.values.function_v")
require("rima.public")
local rima = rima
module(...)
-- Tests -----------------------------------------------------------------------
function test(show_passes)
local T = series:new(_M, show_passes)
local D = expression.dump
local B = expression.bind
local E = expression.eval
T:test(object.isa(function_v:new({"a"}, 3), function_v), "isa(function_v:new(), function_v)")
T:check_equal(object.type(function_v:new({"a"}, 3)), "function_v", "type(function_v:new()) == 'function_v'")
T:expect_error(function() function_v:new({1}, 1) end,
"expected string or simple reference, got '1' %(number%)")
do
local a = rima.R"a"
T:expect_error(function() function_v:new({a[1]}, 1) end,
"expected string or simple reference, got 'a%[1%]' %(index%)")
local S = scope.create{ b=rima.free() }
T:expect_error(function() function_v:new({S.b}, 1) end,
"expected string or simple reference, got 'b' %(ref%)")
end
local a, b, c, x = rima.R"a, b, c, x"
do
local f = rima.R"f"
local S = scope.create{ f = function_v:new({a}, 3) }
T:expect_error(function() rima.E(f(), S) end,
"the function needs to be called with at least 1 arguments, got 0")
T:expect_error(function() rima.E(f(1, 2), S) end,
"the function needs to be called with 1 arguments, got 2")
T:expect_error(function() rima.E(f(1, 2, 3), S) end,
"the function needs to be called with 1 arguments, got 3")
end
do
local f = function_v:new({a}, 3)
local S = scope.new()
T:check_equal(f, "function(a) return 3", "function description")
T:check_equal(f:call({5}, S, E), 3)
end
do
local f = function_v:new({"a"}, 3 + a)
local S = scope.create{ x = rima.free() }
T:check_equal(f, "function(a) return 3 + a", "function description")
T:check_equal(f:call({x}, S, B), "3 + x")
T:check_equal(f:call({x}, S, E), "3 + x")
T:check_equal(f:call({5}, S, B), "3 + a")
T:check_equal(f:call({5}, S, E), 8)
T:check_equal(f:call({x}, scope.spawn(S, {x=10}), B), "3 + x")
T:check_equal(f:call({x}, scope.spawn(S, {x=10}), E), 13)
end
do
local f = function_v:new({a}, b + a)
local S = scope.create{ ["a, b"] = rima.free() }
T:check_equal(f, "function(a) return b + a", "function description")
T:check_equal(f:call({x}, S, E), "b + x")
T:check_equal(f:call({5}, S, E), "5 + b")
T:check_equal(f:call({1 + a}, S, E), "1 + a + b")
T:check_equal(f:call({1 + b}, S, E), "1 + 2*b")
local S2 = scope.spawn(S, {b=20})
T:check_equal(f:call({x}, S2, E), "20 + x")
T:check_equal(f:call({5}, S2, E), 25)
S2.x = 100
T:check_equal(f:call({x}, S2, E), 120)
S2.a = 1000
T:check_equal(f:call({x}, S2, E), 120)
end
do
local f = function_v:new({a, "b"}, 1 + a, nil, b^2)
local S = scope.create{ ["a, b"] = rima.free() }
T:check_equal(f, "function(a, b) return 1 + a", "function description")
T:check_equal(f:call({2 + x, 5, {x}}, S, B), "3 + b^2")
T:check_equal(f:call({2 + x, 5, {x}}, S, E), 28)
T:check_equal(f:call({5 * x, b, {x}}, S, E), "1 + 5*b^2")
end
do
local f = rima.R"f"
local S = scope.create{ f = function_v:new({"a", b}, 1 + a, nil, b^2) }
local e = 1 + f(1 + x, 3, {x})
T:check_equal(rima.E(e, S), 12)
end
do
local f, x, y = rima.R"f, x, y"
T:check_equal(rima.E(f(x), { f=rima.F({y}, rima.sin(y)) }), "sin(x)")
end
do
local y = rima.R"y"
T:check_equal(rima.F({y}, y^2)(5), 25)
end
do
local a, b, c, t, s, u = rima.R"a, b, c, t, s, u"
local S = scope.create{
a={w={{x=10,y={z=100}},{x=20,y={z=200}}}},
t=rima.F({b}, a.w[b].x),
s=rima.F({b}, a.w[b].y),
u=rima.F({b}, a.q[b].y) }
T:check_equal(D(t(1)), "call(ref(t), number(1))")
T:check_equal(t(1), "t(1)")
T:expect_ok(function() B(t(1), S) end, "binding")
T:check_equal(B(t(1), S), "a.w[1].x")
T:expect_ok(function() E(t(1), S) end, "eval")
T:check_equal(E(t(1), S), 10)
T:check_equal(E(t(2), S), 20)
local e = B(t(1), S)
T:check_equal(E(e, S), 10)
T:check_equal(D(s(1).z), "index(call(ref(s), number(1)), address(string(z)))")
T:check_equal(s(1).z, "s(1).z")
T:expect_ok(function() B(s(1).z, S) end, "binding")
T:check_equal(B(s(1).z, S), "a.w[1].y.z")
T:expect_ok(function() E(s(1).z, S) end, "eval")
T:check_equal(E(s(1).z, S), 100)
T:check_equal(E(s(2).z, S), 200)
local e = B(s(1).z, S)
T:check_equal(E(e, S), 100)
T:check_equal(s(1).q, "s(1).q")
T:expect_ok(function() B(s(1).q, S) end, "binding")
T:check_equal(B(s(1).q, S), "a.w[1].y.q")
T:expect_ok(function() E(s(1).q, S) end, "eval")
T:check_equal(E(s(1).q, S), "a.w[1].y.q")
T:check_equal(E(s(2).q, S), "a.w[2].y.q")
local e = B(s(1).q, S)
T:check_equal(E(e, S), "a.w[1].y.q")
T:check_equal(u(1).z, "u(1).z")
T:expect_ok(function() B(u(1).z, S) end, "binding")
T:check_equal(B(u(1).z, S), "a.q[1].y.z")
T:expect_ok(function() E(u(1).z, S) end, "eval")
T:check_equal(E(u(1).z, S), "a.q[1].y.z")
T:check_equal(E(u(2).z, S), "a.q[2].y.z")
local e = B(u(1).z, S)
T:check_equal(E(e, S), "a.q[1].y.z")
end
do
local a, b, i = rima.R"a, b, i"
local S = rima.scope.create{ a = { { 5 } }, b = rima.F({i}, a[1][i]) }
T:check_equal(E(a[1][1], S), 5)
T:check_equal(E(b(1), S), 5)
T:expect_error(function() E(b(1)[1], S) end, "error evaluating 'b%(1%)%[1%]' as 'a%[1, 1, 1%]':.*address: error resolving 'a%[1, 1, 1%]': 'a%[1, 1%]' is not indexable %(got '5' number%)")
end
do
local f, x, y = rima.R"f, x, y"
local S = rima.scope.create{ f = rima.F({y}, y + x, { x=5 }) }
T:check_equal(E(f(x), S), "5 + x")
S.x = 100
T:check_equal(E(f(x), S), 105)
end
do
local f, x, y = rima.R"f, x, y"
local S = rima.scope.create{ f = rima.F({y}, y + x, { x=5 }) }
local e = E(f(x), S)
local S2 = rima.scope.spawn(S)
S2.x = 200
T:check_equal(E(e, S2), 205)
end
-- more tests in expression
return T:close()
end
-- EOF -------------------------------------------------------------------------
|
rima: added some tests to function_v that are related to the earlier fix to ref.
|
rima: added some tests to function_v that are related to the earlier fix to ref.
|
Lua
|
mit
|
geoffleyland/rima,geoffleyland/rima,geoffleyland/rima
|
ab6f0944eb6f04d8af9c44f65e66919d263d300e
|
elb/slow_elb.lua
|
elb/slow_elb.lua
|
#!/usr/local/bin/lua
--
-- Parses ELB log files to find slow responses for ELB int processing time, backend processing time or upstream processing time.
--
-- Download ELB logs from S3 bucket:
-- aws s3 sync s3://pub-ext-elb/AWSLogs/719728721003/elasticloadbalancing/eu-west-1/2015/08/28 .
-- 2015-08-28T08:08:11.042771Z publishing-external-elb-https 93.15.210.26:26023 11.240.54.67:80 0.000023 1.069548 0.00003 200 200 0 3372 "GET https://mot-testing.i-env.net:443/ HTTP/1.1" "Mozilla/5.0 (Linux; Android 4.4.2; V919 3G Air Core8 Build/KOT49H) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.133 Safari/537.36" ECDHE-RSA-AES128-GCM-SHA256 TLSv1.2
--
-- PC 30/01/16 lua version
-- PC 15/01/16 ruby version
-- PC 12/10/15 perl 6 version
-- PC 29/08/15 perl 5 version
--
require "lapp/lapp"
version = "0.3"
--scriptname = args[0]
alltheargs = args
opt_debug = nil
function string:split2 (separator)
local tokens = {}
local pattern = string.format("([^%s]+)", separator)
local i = 0
for token in self:gmatch(pattern) do
tokens[i] = token
i = i + 1
end
return tokens
end
--
-- Read an ELB logfile line-by-line for efficiency and parse for slow response times.
--
function parseElblogfile (fh, filename)
--local fh = assert(io.open(filename, "r"), "unable to open file " .. filename)
print ("=========" .. filename .. "=========")
while true do
local line = fh:read()
if line == nil then break end
parseLine(line)
end
fh:close()
end
--
-- Parse an ELB logfile line to identify which of the 3 responses times are slower than the threshold.
--
function parseLine (line)
local time1, time2, time3 = "-", "-", "-"
local items = line:split2(' ')
local date, elb, clientip, referrer, request_processing_time, backend_processing_time, response_processing_time, elbstatus, backendstatus, rbytes, sbytes, verb, url = items[1], items[2], items[3], items[4], items[5], items[6], items[7], items[8], items[9], items[10], items[11], items[12], items[13]
if argv.e1 and tonumber(request_processing_time) > argv.threshold then time1 = request_processing_time end
if argv.e2 and tonumber(backend_processing_time) > argv.threshold then time2 = backend_processing_time end
if argv.e3 and tonumber(response_processing_time) > argv.threshold then time3 = response_processing_time end
if (time1 ~= "-") or (time2 ~= "-") or (time3 ~= "-") then
if argv.verbose then print(line) end
if argv.short then print(date.." "..time1.." "..time2.." "..time3.." "..url.." ("..backendstatus..")") end
end
end
argv = lapp [[
scriptname: alltheargs (version)
scriptname logfiles
-u,--e1 Compare time of elb internal processing time (sec). Defaults if none specified.
-e,--e2 Compare time of backend processing time (sec). Defaults if none specified.
-d,--e3 Compare time of response processing time (sec). Defaults if none specified.
-t,--threshold (default 1) n in seconds of time threshold to compare against. Default is 1 sec.
-s,--short (default true) Display time and 3 responses times only in results. Default.
-v,--verbose Display whole log statement in results.
<files...> (file-in) Log files
To easily download elb logs from S3 bucket use this with your bucket name:
$ aws s3 sync s3://pub-ext-elb/AWSLogs/719728721003/elasticloadbalancing/eu-west-1/2015/08/28 .
]]
argv.short = not argv.verbose
argv.verbose = not argv.short
if argv.e1 == nil then argv.e1 = false end
if argv.e2 == nil then argv.e2 = false end
if argv.e3 == nil then argv.e3 = false end
if not argv.e1 and not argv.e2 and not argv.e3 then argv.e1, argv.e2, argv.e3 = true, true, true end
if opt_debug then
print("Processing files:")
for i = 1,#argv.files do
print (argv.files[i])
end
end
for i = 1,#argv.files do
parseElblogfile(argv.files[i], argv.files_name[i])
end
|
#!/usr/local/bin/lua
--
-- Parses ELB log files to find slow responses for ELB int processing time, backend processing time or upstream processing time.
--
-- Download ELB logs from S3 bucket:
-- aws s3 sync s3://pub-ext-elb/AWSLogs/719728721003/elasticloadbalancing/eu-west-1/2015/08/28 .
-- 2015-08-28T08:08:11.042771Z publishing-external-elb-https 93.15.210.26:26023 11.240.54.67:80 0.000023 1.069548 0.00003 200 200 0 3372 "GET https://mot-testing.i-env.net:443/ HTTP/1.1" "Mozilla/5.0 (Linux; Android 4.4.2; V919 3G Air Core8 Build/KOT49H) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.133 Safari/537.36" ECDHE-RSA-AES128-GCM-SHA256 TLSv1.2
--
-- PC 30/01/16 lua version
-- PC 15/01/16 ruby version
-- PC 12/10/15 perl 6 version
-- PC 29/08/15 perl 5 version
--
require "lapp/lapp"
version = "0.3"
--scriptname = args[0]
alltheargs = args
opt_debug = nil
--
-- Split a string
-- credit: http://lua-users.org/wiki/SplitJoin
--
function string:split (separator)
local separator, fields = separator or ",", {}
local pattern = string.format("([^%s]+)", separator)
self:gsub(pattern, function(c) fields[#fields+1] = c end)
return fields
end
function string:split2 (separator)
local tokens = {}
local pattern = string.format("([^%s]+)", separator)
local i = 1
for token in self:gmatch(pattern) do
tokens[i] = token
i = i + 1
end
return tokens
end
--
-- Read an ELB logfile line-by-line for efficiency and parse for slow response times.
--
function parseElblogfile (fh, filename)
--local fh = assert(io.open(filename, "r"), "unable to open file " .. filename)
print ("=========" .. filename .. "=========")
while true do
local line = fh:read()
if line == nil then break end
parseLine(line)
end
fh:close()
end
--
-- Parse an ELB logfile line to identify which of the 3 responses times are slower than the threshold.
--
function parseLine (line)
local time1, time2, time3 = "-", "-", "-"
local items = line:split2(' ')
local date, elb, clientip, referrer, request_processing_time, backend_processing_time, response_processing_time, elbstatus, backendstatus, rbytes, sbytes, verb, url = items[1], items[2], items[3], items[4], items[5], items[6], items[7], items[8], items[9], items[10], items[11], items[12], items[13]
if argv.e1 and tonumber(request_processing_time) > argv.threshold then time1 = request_processing_time end
if argv.e2 and tonumber(backend_processing_time) > argv.threshold then time2 = backend_processing_time end
if argv.e3 and tonumber(response_processing_time) > argv.threshold then time3 = response_processing_time end
if (time1 ~= "-") or (time2 ~= "-") or (time3 ~= "-") then
if argv.verbose then print(line) end
if argv.short then print(date.." "..time1.." "..time2.." "..time3.." "..url.." ("..backendstatus..")") end
end
end
argv = lapp [[
scriptname: alltheargs (version)
scriptname logfiles
-u,--e1 Compare time of elb internal processing time (sec). Defaults if none specified.
-e,--e2 Compare time of backend processing time (sec). Defaults if none specified.
-d,--e3 Compare time of response processing time (sec). Defaults if none specified.
-t,--threshold (default 1) n in seconds of time threshold to compare against. Default is 1 sec.
-s,--short (default true) Display time and 3 responses times only in results. Default.
-v,--verbose Display whole log statement in results.
<files...> (file-in) Log files
To easily download elb logs from S3 bucket use this with your bucket name:
$ aws s3 sync s3://pub-ext-elb/AWSLogs/719728721003/elasticloadbalancing/eu-west-1/2015/08/28 .
]]
argv.short = not argv.verbose
argv.verbose = not argv.short
if argv.e1 == nil then argv.e1 = false end
if argv.e2 == nil then argv.e2 = false end
if argv.e3 == nil then argv.e3 = false end
if not argv.e1 and not argv.e2 and not argv.e3 then argv.e1, argv.e2, argv.e3 = true, true, true end
if opt_debug then
print("Processing files:")
for i = 1,#argv.files do
print (argv.files[i])
end
end
for i = 1,#argv.files do
parseElblogfile(argv.files[i], argv.files_name[i])
end
|
fixed split function bug
|
fixed split function bug
|
Lua
|
mit
|
KainosSoftwareLtd/dig-scriptogram,KainosSoftwareLtd/dig-scriptogram,KainosSoftwareLtd/dig-scriptogram,KainosSoftwareLtd/dig-scriptogram,KainosSoftwareLtd/dig-scriptogram,KainosSoftwareLtd/dig-scriptogram
|
8216fe2441aeda108f59c2ba358f10b78ebb36b9
|
specl-rockspec.lua
|
specl-rockspec.lua
|
-- Specl rockspec data
-- Variables to be interpolated:
--
-- package
-- version
local default = {
package = package_name,
version = version.."-1",
source = {
url = "http://github.com/gvvaughan/"..package_name.."/archive/release-v"..version..".zip",
dir = package_name.."-release-v"..version,
},
description = {
summary = "Behaviour Driven Development for Lua",
detailed = [[
Develop and run BDD specs written in Lua for RSpec style workflow.
]],
homepage = "http://github.com/gvvaughan/"..package_name.."/",
license = "GPLv3+",
},
dependencies = {
"ansicolor",
"lua >= 5.1",
"lyaml",
},
build = {
type = "command",
build_command = "LUA=$(LUA) LUA_INCLUDE=-I$(LUA_INCDIR) " ..
"./configure CPPFLAGS=-I$(YAML_INCDIR) LDFLAGS='-L$(YAML_LIBDIR)' " ..
"--prefix=$(PREFIX) --libdir=$(LIBDIR) --datadir=$(LUADIR) " ..
"&& make clean && make",
install_command = "make install",
copy_directories = {},
},
}
if version == "git" then
default.build.build_command = "./bootstrap && " .. default.build.build_command
end
return {default=default, [""]={}}
|
-- Specl rockspec data
-- Variables to be interpolated:
--
-- package
-- version
local default = {
package = package_name,
version = version.."-1",
source = {
url = "http://github.com/gvvaughan/"..package_name.."/archive/release-v"..version..".zip",
dir = package_name.."-release-v"..version,
},
description = {
summary = "Behaviour Driven Development for Lua",
detailed = [[
Develop and run BDD specs written in Lua for RSpec style workflow.
]],
homepage = "http://github.com/gvvaughan/"..package_name.."/",
license = "GPLv3+",
},
dependencies = {
"ansicolors",
"lua >= 5.1",
"lyaml",
},
build = {
type = "command",
build_command = "LUA=$(LUA) LUA_INCLUDE=-I$(LUA_INCDIR) " ..
"./configure --prefix=$(PREFIX) --libdir=$(LIBDIR) --datadir=$(LUADIR) " ..
"&& make clean && make",
install_command = "make install",
copy_directories = {},
},
}
if version == "git" then
default.build.build_command = "./bootstrap && " .. default.build.build_command
end
return {default=default, [""]={}}
|
rockspecs: fix a typo, and remove unused configure flags.
|
rockspecs: fix a typo, and remove unused configure flags.
* specl-rockspec.lua (dependencies): spell ansicolors correctly.
(build.build_command): Remove unused YAML flags.
Signed-off-by: Gary V. Vaughan <[email protected]>
|
Lua
|
mit
|
gvvaughan/specl
|
20cf05cf66b6b6a72b6b388d57b35edf16c06b89
|
applications/luci-ahcp/luasrc/model/cbi/ahcp.lua
|
applications/luci-ahcp/luasrc/model/cbi/ahcp.lua
|
--[[
LuCI - Lua Configuration Interface
Copyright 2011 Jo-Philipp Wich <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id: init.lua 5764 2010-03-08 19:05:34Z jow $
]]--
m = Map("ahcpd", translate("AHCP Server"), translate("AHCP is an autoconfiguration protocol " ..
"for IPv6 and dual-stack IPv6/IPv4 networks designed to be used in place of router " ..
"discovery and DHCP on networks where it is difficult or impossible to configure a " ..
"server within every link-layer broadcast domain, for example mobile ad-hoc networks."))
m:section(SimpleSection).template = "ahcp_status"
s = m:section(TypedSection, "ahcpd")
s:tab("general", translate("General Setup"))
s:tab("advanced", translate("Advanced Settings"))
s.addremove = false
s.anonymous = true
mode = s:taboption("general", ListValue, "mode", translate("Operation mode"))
mode:value("server", translate("Server"))
mode:value("forwarder", translate("Forwarder"))
net = s:taboption("general", Value, "interface", translate("Served interfaces"))
net.template = "cbi/network_netlist"
net.widget = "checkbox"
net.nocreate = true
function net.cfgvalue(self, section)
return m.uci:get("ahcpd", section, "interface")
end
pfx = s:taboption("general", DynamicList, "prefix", translate("Announced prefixes"),
translate("Specifies the announced IPv4 and IPv6 network prefixes in CIDR notation"))
pfx.optional = true
pfx.datatype = "ipaddr"
pfx:depends("mode", "server")
nss = s:taboption("general", DynamicList, "name_server", translate("Announced DNS servers"),
translate("Specifies the announced IPv4 and IPv6 name servers"))
nss.optional = true
nss.datatype = "ipaddr"
nss:depends("mode", "server")
ntp = s:taboption("general", DynamicList, "ntp_server", translate("Announced NTP servers"),
translate("Specifies the announced IPv4 and IPv6 NTP servers"))
ntp.optional = true
ntp.datatype = "ipaddr"
ntp:depends("mode", "server")
mca = s:taboption("general", Value, "multicast_address", translate("Multicast address"))
mca.optional = true
mca.placeholder = "ff02::cca6:c0f9:e182:5359"
mca.datatype = "ip6addr"
port = s:taboption("general", Value, "port", translate("Port"))
port.optional = true
port.placeholder = 5359
port.datatype = "port"
fam = s:taboption("general", ListValue, "_family", translate("Protocol family"))
fam:value("", translate("IPv4 and IPv6"))
fam:value("ipv4", translate("IPv4 only"))
fam:value("ipv6", translate("IPv6 only"))
function fam.cfgvalue(self, section)
local v4 = m.uci:get_bool("ahcpd", section, "ipv4_only")
local v6 = m.uci:get_bool("ahcpd", section, "ipv6_only")
if v4 then
return "ipv4"
elseif v6 then
return "ipv6"
end
return ""
end
function fam.write(self, section, value)
if value == "ipv4" then
m.uci:set("ahcpd", section, "ipv4_only", "true")
m.uci:delete("ahcpd", section, "ipv6_only")
elseif value == "ipv6" then
m.uci:set("ahcpd", section, "ipv6_only", "true")
m.uci:delete("ahcpd", section, "ipv4_only")
end
end
function fam.remove(self, section)
m.uci:delete("ahcpd", section, "ipv4_only")
m.uci:delete("ahcpd", section, "ipv6_only")
end
ltime = s:taboption("general", Value, "lease_time", translate("Lease validity time"))
ltime.optional = true
ltime.placeholder = 3666
ltime.datatype = "uinteger"
ld = s:taboption("advanced", Value, "lease_dir", translate("Lease directory"))
ld.datatype = "directory"
ld.placeholder = "/var/lib/leases"
id = s:taboption("advanced", Value, "id_file", translate("Unique ID file"))
--id.datatype = "file"
id.placeholder = "/var/lib/ahcpd-unique-id"
log = s:taboption("advanced", Value, "log_file", translate("Log file"))
--log.datatype = "file"
log.placeholder = "/var/log/ahcpd.log"
return m
|
--[[
LuCI - Lua Configuration Interface
Copyright 2011 Jo-Philipp Wich <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id: init.lua 5764 2010-03-08 19:05:34Z jow $
]]--
m = Map("ahcpd", translate("AHCP Server"), translate("AHCP is an autoconfiguration protocol " ..
"for IPv6 and dual-stack IPv6/IPv4 networks designed to be used in place of router " ..
"discovery and DHCP on networks where it is difficult or impossible to configure a " ..
"server within every link-layer broadcast domain, for example mobile ad-hoc networks."))
m:section(SimpleSection).template = "ahcp_status"
s = m:section(TypedSection, "ahcpd")
s:tab("general", translate("General Setup"))
s:tab("advanced", translate("Advanced Settings"))
s.addremove = false
s.anonymous = true
mode = s:taboption("general", ListValue, "mode", translate("Operation mode"))
mode:value("client", translate("Client"))
mode:value("server", translate("Server"))
mode:value("forwarder", translate("Forwarder"))
net = s:taboption("general", Value, "interface", translate("Served interfaces"))
net.template = "cbi/network_netlist"
net.widget = "checkbox"
net.nocreate = true
function net.cfgvalue(self, section)
return m.uci:get("ahcpd", section, "interface")
end
pfx = s:taboption("general", DynamicList, "prefix", translate("Announced prefixes"),
translate("Specifies the announced IPv4 and IPv6 network prefixes in CIDR notation"))
pfx.optional = true
pfx.datatype = "ipaddr"
pfx:depends("mode", "server")
nss = s:taboption("general", DynamicList, "name_server", translate("Announced DNS servers"),
translate("Specifies the announced IPv4 and IPv6 name servers"))
nss.optional = true
nss.datatype = "ipaddr"
nss:depends("mode", "server")
ntp = s:taboption("general", DynamicList, "ntp_server", translate("Announced NTP servers"),
translate("Specifies the announced IPv4 and IPv6 NTP servers"))
ntp.optional = true
ntp.datatype = "ipaddr"
ntp:depends("mode", "server")
mca = s:taboption("general", Value, "multicast_address", translate("Multicast address"))
mca.optional = true
mca.placeholder = "ff02::cca6:c0f9:e182:5359"
mca.datatype = "ip6addr"
port = s:taboption("general", Value, "port", translate("Port"))
port.optional = true
port.placeholder = 5359
port.datatype = "port"
fam = s:taboption("general", ListValue, "_family", translate("Protocol family"))
fam:value("", translate("IPv4 and IPv6"))
fam:value("ipv4", translate("IPv4 only"))
fam:value("ipv6", translate("IPv6 only"))
function fam.cfgvalue(self, section)
local v4 = m.uci:get_bool("ahcpd", section, "ipv4_only")
local v6 = m.uci:get_bool("ahcpd", section, "ipv6_only")
if v4 then
return "ipv4"
elseif v6 then
return "ipv6"
end
return ""
end
function fam.write(self, section, value)
if value == "ipv4" then
m.uci:set("ahcpd", section, "ipv4_only", "true")
m.uci:delete("ahcpd", section, "ipv6_only")
elseif value == "ipv6" then
m.uci:set("ahcpd", section, "ipv6_only", "true")
m.uci:delete("ahcpd", section, "ipv4_only")
end
end
function fam.remove(self, section)
m.uci:delete("ahcpd", section, "ipv4_only")
m.uci:delete("ahcpd", section, "ipv6_only")
end
ltime = s:taboption("general", Value, "lease_time", translate("Lease validity time"))
ltime.optional = true
ltime.placeholder = 3666
ltime.datatype = "uinteger"
ld = s:taboption("advanced", Value, "lease_dir", translate("Lease directory"))
ld.datatype = "directory"
ld.placeholder = "/var/lib/leases"
id = s:taboption("advanced", Value, "id_file", translate("Unique ID file"))
--id.datatype = "file"
id.placeholder = "/var/lib/ahcpd-unique-id"
log = s:taboption("advanced", Value, "log_file", translate("Log file"))
--log.datatype = "file"
log.placeholder = "/var/log/ahcpd.log"
return m
|
Fixed ahcp support in lua for client mode
|
Fixed ahcp support in lua for client mode
|
Lua
|
apache-2.0
|
dtaht/cerowrt-luci-3.3,dtaht/cerowrt-luci-3.3,dtaht/cerowrt-luci-3.3,dtaht/cerowrt-luci-3.3,dtaht/cerowrt-luci-3.3,dtaht/cerowrt-luci-3.3
|
f014b1e779e5121d2900b908a8e76dd3379c048e
|
zpm.lua
|
zpm.lua
|
--[[ @cond ___LICENSE___
-- Copyright (c) 2017 Zefiros Software
--
-- Permission is hereby granted, free of charge, to any person obtaining a copy
-- of this software and associated documentation files (the "Software"), to deal
-- in the Software without restriction, including without limitation the rights
-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-- copies of the Software, and to permit persons to whom the Software is
-- furnished to do so, subject to the following conditions:
--
-- The above copyright notice and this permission notice shall be included in
-- all copies or substantial portions of the Software.
--
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-- THE SOFTWARE.
--
-- @endcond
--]]
workspace "SerLib"
cppdialect "C++14"
zefiros.setDefaults("serialisation")
-- use another path in case of a coverage build
if os.getenv('BUILD_CONFIGURATION') == 'coverage' then
project "serialisation-test"
defines {
"TEST_FILES_DIR=\"test/test-files/\""
}
end
|
--[[ @cond ___LICENSE___
-- Copyright (c) 2017 Zefiros Software
--
-- Permission is hereby granted, free of charge, to any person obtaining a copy
-- of this software and associated documentation files (the "Software"), to deal
-- in the Software without restriction, including without limitation the rights
-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-- copies of the Software, and to permit persons to whom the Software is
-- furnished to do so, subject to the following conditions:
--
-- The above copyright notice and this permission notice shall be included in
-- all copies or substantial portions of the Software.
--
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-- THE SOFTWARE.
--
-- @endcond
--]]
workspace "SerLib"
cppdialect "C++14"
zefiros.setDefaults("serialisation")
project "serialisation-test"
-- use another path in case of a coverage build
filter "Coverage"
defines {
"TEST_FILES_DIR=\"test/test-files/\""
}
filter{}
|
Fix coverage paths
|
Fix coverage paths
|
Lua
|
mit
|
Zefiros-Software/SerLib2
|
b548a8684a5866f6162b02dae5d62b0593ca6a81
|
Josephus_Problem/Lua/Yonaba/josephus.lua
|
Josephus_Problem/Lua/Yonaba/josephus.lua
|
-- Josephus problem implementation
-- See: http://en.wikipedia.org/wiki/Josephus_problem
-- Returns the survivor
-- n : the initial number of people
-- k : the count for each step
-- returns : the survivor's number
local function josephus_recursive(n, k)
if n == 1 then return 1
else
return ((josephus_recursive(n-1,k)+k-1)%n)+1
end
end
-- Returns the survivor
-- n : the initial number of people
-- k : the count for each step
-- returns : the survivor's number
local function josephus_loop(n, k)
local r, i = 0, 1
while i <= n do
r = (r + k) % i
i = i + 1
end
return r + 1
end
-- Private wrapper
local function j(n, k, s)
if n == 1 then return 1 end
local new_s = ((s or 1) + k - 2) % n + 1
local survivor = j(n - 1, k, new_s)
return survivor < new_s and survivor or survivor + 1
end
-- Returns the survivor
-- n : the initial number of people
-- k : the count for each step
-- returns : the survivor's number
local function josephus_elaborated(n, k)
return j(n, k, 1)
end
-- Returns the survivor (assumes the count is k = 2)
-- n : the initial number of people
-- returns : the survivor's number
local function josephus_2(n)
return josephus_iterative(n, 2)
end
-- Returns the survivor (assumes the count is k = 2)
-- Alternate implementation using logarithm.
-- n : the initial number of people
-- returns : the survivor's number
local function josephus_log_2(n)
return 2*(n - 2 ^ math.floor(math.log(n, 2)))+1
end
return {
recursive = josephus_recursive,
loop = josephus_loop,
elaborated = josephus_elaborated,
standard = josephus_2,
standard_log = josephus_log_2,
}
|
-- Josephus problem implementation
-- See: http://en.wikipedia.org/wiki/Josephus_problem
-- Returns the survivor
-- n : the initial number of people
-- k : the count for each step
-- returns : the survivor's number
local function josephus_recursive(n, k)
if n == 1 then return 1
else
return ((josephus_recursive(n-1,k)+k-1)%n)+1
end
end
-- Returns the survivor
-- n : the initial number of people
-- k : the count for each step
-- returns : the survivor's number
local function josephus_loop(n, k)
local r, i = 0, 1
while i <= n do
r = (r + k) % i
i = i + 1
end
return r + 1
end
-- Private wrapper
local function j(n, k, s)
if n == 1 then return 1 end
local new_s = ((s or 1) + k - 2) % n + 1
local survivor = j(n - 1, k, new_s)
return survivor < new_s and survivor or survivor + 1
end
-- Returns the survivor
-- n : the initial number of people
-- k : the count for each step
-- returns : the survivor's number
local function josephus_elaborated(n, k)
return j(n, k, 1)
end
-- Returns the survivor (assumes the count is k = 2)
-- n : the initial number of people
-- returns : the survivor's number
local function josephus_2(n)
return josephus_loop(n, 2)
end
-- Returns the survivor (assumes the count is k = 2)
-- Alternate implementation using logarithm.
-- n : the initial number of people
-- returns : the survivor's number
local function josephus_log_2(n)
return 2*(n - 2 ^ math.floor(math.log(n, 2)))+1
end
return {
recursive = josephus_recursive,
loop = josephus_loop,
elaborated = josephus_elaborated,
standard = josephus_2,
standard_log = josephus_log_2,
}
|
Fixed implentation Code prettification
|
Fixed implentation
Code prettification
|
Lua
|
mit
|
vikas17a/Algorithm-Implementations,pravsingh/Algorithm-Implementations,sugiartocokrowibowo/Algorithm-Implementations,imanmafi/Algorithm-Implementations,Etiene/Algorithm-Implementations,rohanp/Algorithm-Implementations,girishramnani/Algorithm-Implementations,isalnikov/Algorithm-Implementations,rohanp/Algorithm-Implementations,Etiene/Algorithm-Implementations,Yonaba/Algorithm-Implementations,pravsingh/Algorithm-Implementations,pravsingh/Algorithm-Implementations,pravsingh/Algorithm-Implementations,Etiene/Algorithm-Implementations,sugiartocokrowibowo/Algorithm-Implementations,jiang42/Algorithm-Implementations,vikas17a/Algorithm-Implementations,kennyledet/Algorithm-Implementations,jb1717/Algorithm-Implementations,Sweet-kid/Algorithm-Implementations,warreee/Algorithm-Implementations,jiang42/Algorithm-Implementations,varunparkhe/Algorithm-Implementations,movb/Algorithm-Implementations,jb1717/Algorithm-Implementations,imrandomizer/Algorithm-Implementations,mishin/Algorithm-Implementations,kennyledet/Algorithm-Implementations,mishin/Algorithm-Implementations,varunparkhe/Algorithm-Implementations,rohanp/Algorithm-Implementations,AntonioModer/Algorithm-Implementations,mishin/Algorithm-Implementations,AntonioModer/Algorithm-Implementations,kennyledet/Algorithm-Implementations,movb/Algorithm-Implementations,Etiene/Algorithm-Implementations,Yonaba/Algorithm-Implementations,imrandomizer/Algorithm-Implementations,Etiene/Algorithm-Implementations,jiang42/Algorithm-Implementations,kennyledet/Algorithm-Implementations,girishramnani/Algorithm-Implementations,isalnikov/Algorithm-Implementations,sugiartocokrowibowo/Algorithm-Implementations,imrandomizer/Algorithm-Implementations,girishramnani/Algorithm-Implementations,sugiartocokrowibowo/Algorithm-Implementations,jiang42/Algorithm-Implementations,movb/Algorithm-Implementations,praveenjha527/Algorithm-Implementations,isalnikov/Algorithm-Implementations,pravsingh/Algorithm-Implementations,jiang42/Algorithm-Implementations,jiang42/Algorithm-Implementations,Etiene/Algorithm-Implementations,n1ghtmare/Algorithm-Implementations,Yonaba/Algorithm-Implementations,imanmafi/Algorithm-Implementations,aayushKumarJarvis/Algorithm-Implementations,Endika/Algorithm-Implementations,girishramnani/Algorithm-Implementations,jiang42/Algorithm-Implementations,Yonaba/Algorithm-Implementations,aayushKumarJarvis/Algorithm-Implementations,varunparkhe/Algorithm-Implementations,imanmafi/Algorithm-Implementations,pravsingh/Algorithm-Implementations,girishramnani/Algorithm-Implementations,isalnikov/Algorithm-Implementations,jiang42/Algorithm-Implementations,warreee/Algorithm-Implementations,joshimoo/Algorithm-Implementations,n1ghtmare/Algorithm-Implementations,rohanp/Algorithm-Implementations,kennyledet/Algorithm-Implementations,praveenjha527/Algorithm-Implementations,praveenjha527/Algorithm-Implementations,kidaa/Algorithm-Implementations,warreee/Algorithm-Implementations,imanmafi/Algorithm-Implementations,imanmafi/Algorithm-Implementations,joshimoo/Algorithm-Implementations,Sweet-kid/Algorithm-Implementations,Sweet-kid/Algorithm-Implementations,vikas17a/Algorithm-Implementations,jiang42/Algorithm-Implementations,imrandomizer/Algorithm-Implementations,warreee/Algorithm-Implementations,jb1717/Algorithm-Implementations,praveenjha527/Algorithm-Implementations,imanmafi/Algorithm-Implementations,girishramnani/Algorithm-Implementations,mishin/Algorithm-Implementations,mishin/Algorithm-Implementations,Etiene/Algorithm-Implementations,isalnikov/Algorithm-Implementations,warreee/Algorithm-Implementations,imrandomizer/Algorithm-Implementations,praveenjha527/Algorithm-Implementations,sugiartocokrowibowo/Algorithm-Implementations,Endika/Algorithm-Implementations,imanmafi/Algorithm-Implementations,kidaa/Algorithm-Implementations,rohanp/Algorithm-Implementations,imanmafi/Algorithm-Implementations,girishramnani/Algorithm-Implementations,aayushKumarJarvis/Algorithm-Implementations,pravsingh/Algorithm-Implementations,kidaa/Algorithm-Implementations,warreee/Algorithm-Implementations,jb1717/Algorithm-Implementations,Sweet-kid/Algorithm-Implementations,mishin/Algorithm-Implementations,varunparkhe/Algorithm-Implementations,jb1717/Algorithm-Implementations,mishin/Algorithm-Implementations,Etiene/Algorithm-Implementations,isalnikov/Algorithm-Implementations,rohanp/Algorithm-Implementations,imanmafi/Algorithm-Implementations,girishramnani/Algorithm-Implementations,n1ghtmare/Algorithm-Implementations,Endika/Algorithm-Implementations,AntonioModer/Algorithm-Implementations,AntonioModer/Algorithm-Implementations,praveenjha527/Algorithm-Implementations,varunparkhe/Algorithm-Implementations,joshimoo/Algorithm-Implementations,jb1717/Algorithm-Implementations,Yonaba/Algorithm-Implementations,kidaa/Algorithm-Implementations,movb/Algorithm-Implementations,kennyledet/Algorithm-Implementations,kidaa/Algorithm-Implementations,isalnikov/Algorithm-Implementations,imanmafi/Algorithm-Implementations,kennyledet/Algorithm-Implementations,sugiartocokrowibowo/Algorithm-Implementations,sugiartocokrowibowo/Algorithm-Implementations,praveenjha527/Algorithm-Implementations,imrandomizer/Algorithm-Implementations,AntonioModer/Algorithm-Implementations,n1ghtmare/Algorithm-Implementations,joshimoo/Algorithm-Implementations,aayushKumarJarvis/Algorithm-Implementations,vikas17a/Algorithm-Implementations,Endika/Algorithm-Implementations,vikas17a/Algorithm-Implementations,isalnikov/Algorithm-Implementations,joshimoo/Algorithm-Implementations,Sweet-kid/Algorithm-Implementations,n1ghtmare/Algorithm-Implementations,kennyledet/Algorithm-Implementations,vikas17a/Algorithm-Implementations,movb/Algorithm-Implementations,varunparkhe/Algorithm-Implementations,jiang42/Algorithm-Implementations,Yonaba/Algorithm-Implementations,pravsingh/Algorithm-Implementations,varunparkhe/Algorithm-Implementations,warreee/Algorithm-Implementations,Etiene/Algorithm-Implementations,vikas17a/Algorithm-Implementations,mishin/Algorithm-Implementations,kennyledet/Algorithm-Implementations,warreee/Algorithm-Implementations,n1ghtmare/Algorithm-Implementations,imrandomizer/Algorithm-Implementations,imrandomizer/Algorithm-Implementations,Sweet-kid/Algorithm-Implementations,Endika/Algorithm-Implementations,imanmafi/Algorithm-Implementations,sugiartocokrowibowo/Algorithm-Implementations,mishin/Algorithm-Implementations,AntonioModer/Algorithm-Implementations,girishramnani/Algorithm-Implementations,Endika/Algorithm-Implementations,joshimoo/Algorithm-Implementations,girishramnani/Algorithm-Implementations,isalnikov/Algorithm-Implementations,AntonioModer/Algorithm-Implementations,imrandomizer/Algorithm-Implementations,jb1717/Algorithm-Implementations,kennyledet/Algorithm-Implementations,aayushKumarJarvis/Algorithm-Implementations,joshimoo/Algorithm-Implementations,aayushKumarJarvis/Algorithm-Implementations,Etiene/Algorithm-Implementations,movb/Algorithm-Implementations,varunparkhe/Algorithm-Implementations,isalnikov/Algorithm-Implementations,vikas17a/Algorithm-Implementations,Endika/Algorithm-Implementations,kennyledet/Algorithm-Implementations,n1ghtmare/Algorithm-Implementations,Endika/Algorithm-Implementations,rohanp/Algorithm-Implementations,Endika/Algorithm-Implementations,varunparkhe/Algorithm-Implementations,rohanp/Algorithm-Implementations,imrandomizer/Algorithm-Implementations,sugiartocokrowibowo/Algorithm-Implementations,warreee/Algorithm-Implementations,vikas17a/Algorithm-Implementations,isalnikov/Algorithm-Implementations,Endika/Algorithm-Implementations,pravsingh/Algorithm-Implementations,warreee/Algorithm-Implementations,pravsingh/Algorithm-Implementations,Yonaba/Algorithm-Implementations,pravsingh/Algorithm-Implementations,kidaa/Algorithm-Implementations,Yonaba/Algorithm-Implementations,warreee/Algorithm-Implementations,movb/Algorithm-Implementations,vikas17a/Algorithm-Implementations,jb1717/Algorithm-Implementations,joshimoo/Algorithm-Implementations,jb1717/Algorithm-Implementations,AntonioModer/Algorithm-Implementations,AntonioModer/Algorithm-Implementations,Sweet-kid/Algorithm-Implementations,kidaa/Algorithm-Implementations,mishin/Algorithm-Implementations,n1ghtmare/Algorithm-Implementations,rohanp/Algorithm-Implementations,Yonaba/Algorithm-Implementations,pravsingh/Algorithm-Implementations,rohanp/Algorithm-Implementations,jb1717/Algorithm-Implementations,n1ghtmare/Algorithm-Implementations,Endika/Algorithm-Implementations,Sweet-kid/Algorithm-Implementations,AntonioModer/Algorithm-Implementations,jiang42/Algorithm-Implementations,mishin/Algorithm-Implementations,imanmafi/Algorithm-Implementations,Endika/Algorithm-Implementations,varunparkhe/Algorithm-Implementations,praveenjha527/Algorithm-Implementations,rohanp/Algorithm-Implementations,Sweet-kid/Algorithm-Implementations,girishramnani/Algorithm-Implementations,warreee/Algorithm-Implementations,praveenjha527/Algorithm-Implementations,joshimoo/Algorithm-Implementations,Endika/Algorithm-Implementations,n1ghtmare/Algorithm-Implementations,praveenjha527/Algorithm-Implementations,aayushKumarJarvis/Algorithm-Implementations,Etiene/Algorithm-Implementations,jiang42/Algorithm-Implementations,kidaa/Algorithm-Implementations,sugiartocokrowibowo/Algorithm-Implementations,kennyledet/Algorithm-Implementations,n1ghtmare/Algorithm-Implementations,rohanp/Algorithm-Implementations,praveenjha527/Algorithm-Implementations,Sweet-kid/Algorithm-Implementations,jb1717/Algorithm-Implementations,sugiartocokrowibowo/Algorithm-Implementations,joshimoo/Algorithm-Implementations,kennyledet/Algorithm-Implementations,AntonioModer/Algorithm-Implementations,imanmafi/Algorithm-Implementations,sugiartocokrowibowo/Algorithm-Implementations,Sweet-kid/Algorithm-Implementations,joshimoo/Algorithm-Implementations,Yonaba/Algorithm-Implementations,imrandomizer/Algorithm-Implementations,sugiartocokrowibowo/Algorithm-Implementations,kidaa/Algorithm-Implementations,jiang42/Algorithm-Implementations,Sweet-kid/Algorithm-Implementations,mishin/Algorithm-Implementations,isalnikov/Algorithm-Implementations,movb/Algorithm-Implementations,vikas17a/Algorithm-Implementations,sugiartocokrowibowo/Algorithm-Implementations,AntonioModer/Algorithm-Implementations,Sweet-kid/Algorithm-Implementations,warreee/Algorithm-Implementations,pravsingh/Algorithm-Implementations,mishin/Algorithm-Implementations,Sweet-kid/Algorithm-Implementations,movb/Algorithm-Implementations,pravsingh/Algorithm-Implementations,aayushKumarJarvis/Algorithm-Implementations,kidaa/Algorithm-Implementations,joshimoo/Algorithm-Implementations,kidaa/Algorithm-Implementations,Etiene/Algorithm-Implementations,joshimoo/Algorithm-Implementations,aayushKumarJarvis/Algorithm-Implementations,Yonaba/Algorithm-Implementations,Endika/Algorithm-Implementations,girishramnani/Algorithm-Implementations,varunparkhe/Algorithm-Implementations,Yonaba/Algorithm-Implementations,movb/Algorithm-Implementations,rohanp/Algorithm-Implementations,kidaa/Algorithm-Implementations,rohanp/Algorithm-Implementations,Endika/Algorithm-Implementations,kennyledet/Algorithm-Implementations,movb/Algorithm-Implementations,imrandomizer/Algorithm-Implementations,n1ghtmare/Algorithm-Implementations,jb1717/Algorithm-Implementations,AntonioModer/Algorithm-Implementations,praveenjha527/Algorithm-Implementations,kidaa/Algorithm-Implementations,kidaa/Algorithm-Implementations,isalnikov/Algorithm-Implementations,mishin/Algorithm-Implementations,Sweet-kid/Algorithm-Implementations,isalnikov/Algorithm-Implementations,joshimoo/Algorithm-Implementations,imanmafi/Algorithm-Implementations,vikas17a/Algorithm-Implementations,sugiartocokrowibowo/Algorithm-Implementations,kennyledet/Algorithm-Implementations,varunparkhe/Algorithm-Implementations,jb1717/Algorithm-Implementations,Etiene/Algorithm-Implementations,imrandomizer/Algorithm-Implementations,pravsingh/Algorithm-Implementations,Yonaba/Algorithm-Implementations,movb/Algorithm-Implementations,movb/Algorithm-Implementations,praveenjha527/Algorithm-Implementations,imrandomizer/Algorithm-Implementations,varunparkhe/Algorithm-Implementations,joshimoo/Algorithm-Implementations,jb1717/Algorithm-Implementations,warreee/Algorithm-Implementations,n1ghtmare/Algorithm-Implementations,aayushKumarJarvis/Algorithm-Implementations,vikas17a/Algorithm-Implementations,warreee/Algorithm-Implementations,imrandomizer/Algorithm-Implementations,vikas17a/Algorithm-Implementations,mishin/Algorithm-Implementations,jiang42/Algorithm-Implementations,imanmafi/Algorithm-Implementations,isalnikov/Algorithm-Implementations,aayushKumarJarvis/Algorithm-Implementations,movb/Algorithm-Implementations,varunparkhe/Algorithm-Implementations,Etiene/Algorithm-Implementations,jb1717/Algorithm-Implementations,kidaa/Algorithm-Implementations,movb/Algorithm-Implementations,n1ghtmare/Algorithm-Implementations,vikas17a/Algorithm-Implementations,warreee/Algorithm-Implementations,Yonaba/Algorithm-Implementations,jiang42/Algorithm-Implementations,Yonaba/Algorithm-Implementations,rohanp/Algorithm-Implementations,aayushKumarJarvis/Algorithm-Implementations
|
95f9bb97ba1d247819e66bced6988ec39301d2e5
|
libs/httpd/luasrc/httpd/handler/luci.lua
|
libs/httpd/luasrc/httpd/handler/luci.lua
|
--[[
HTTP server implementation for LuCI - luci handler
(c) 2008 Steven Barth <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
module("luci.httpd.handler.luci", package.seeall)
require("luci.dispatcher")
require("luci.http")
require("luci.http.protocol.date")
local ltn12 = require("luci.ltn12")
Luci = luci.util.class(luci.httpd.module.Handler)
Response = luci.httpd.module.Response
function Luci.__init__(self, limit)
luci.httpd.module.Handler.__init__(self)
self.limit = limit or 5
self.running = {}
setmetatable(self.running, {__mode = "v"})
end
function Luci.handle_head(self, ...)
local response, sourceout = self:handle_get(...)
return response
end
function Luci.handle_post(self, ...)
return self:handle_get(...)
end
function Luci.handle_get(self, request, sourcein, sinkerr)
if self.limit and #self.running >= self.limit then
return self:failure(503, "Overload")
end
table.insert(self.running, coroutine.running())
local r = luci.http.Request(
request.env,
sourcein,
sinkerr
)
local res, id, data1, data2 = true, 0, nil, nil
local headers = {}
local status = 200
local active = true
local x = coroutine.create(luci.dispatcher.httpdispatch)
while not id or id < 3 do
coroutine.yield()
res, id, data1, data2 = coroutine.resume(x, r)
if not res then
status = 500
headers["Content-Type"] = "text/plain"
local err = {id}
return Response( status, headers ), function() return table.remove(err) end
end
if id == 1 then
status = data1
elseif id == 2 then
headers[data1] = data2
end
end
local function iter()
local res, id, data = coroutine.resume(x)
if not res then
return nil, id
elseif not id or not active then
return true
elseif id == 5 then
active = false
return nil
elseif id == 4 then
return data
end
if coroutine.status(x) == "dead" then
return nil
end
end
return Response(status, headers), iter
end
|
--[[
HTTP server implementation for LuCI - luci handler
(c) 2008 Steven Barth <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
module("luci.httpd.handler.luci", package.seeall)
require("luci.dispatcher")
require("luci.http")
require("luci.http.protocol.date")
local ltn12 = require("luci.ltn12")
Luci = luci.util.class(luci.httpd.module.Handler)
Response = luci.httpd.module.Response
function Luci.__init__(self, limit)
luci.httpd.module.Handler.__init__(self)
self.limit = limit or 5
self.running = {}
setmetatable(self.running, {__mode = "v"})
end
function Luci.handle_head(self, ...)
local response, sourceout = self:handle_get(...)
return response
end
function Luci.handle_post(self, ...)
return self:handle_get(...)
end
function Luci.handle_get(self, request, sourcein, sinkerr)
if self.limit and #self.running >= self.limit then
for k, v in ipairs(self.running) do
if coroutine.status(v) == "dead" then
collectgarbage()
break
end
end
if #self.running >= self.limit then
return self:failure(503, "Overload")
end
end
table.insert(self.running, coroutine.running())
local r = luci.http.Request(
request.env,
sourcein,
sinkerr
)
local res, id, data1, data2 = true, 0, nil, nil
local headers = {}
local status = 200
local active = true
local x = coroutine.create(luci.dispatcher.httpdispatch)
while not id or id < 3 do
coroutine.yield()
res, id, data1, data2 = coroutine.resume(x, r)
if not res then
status = 500
headers["Content-Type"] = "text/plain"
local err = {id}
return Response( status, headers ), function() return table.remove(err) end
end
if id == 1 then
status = data1
elseif id == 2 then
headers[data1] = data2
end
end
local function iter()
local res, id, data = coroutine.resume(x)
if not res then
return nil, id
elseif not id or not active then
return true
elseif id == 5 then
active = false
while (coroutine.resume(x)) do
end
return nil
elseif id == 4 then
return data
end
if coroutine.status(x) == "dead" then
return nil
end
end
return Response(status, headers), iter
end
|
Fixed occasionally occuring "Overload"-problems with luci-httpd
|
Fixed occasionally occuring "Overload"-problems with luci-httpd
|
Lua
|
apache-2.0
|
maxrio/luci981213,artynet/luci,taiha/luci,male-puppies/luci,tcatm/luci,male-puppies/luci,jorgifumi/luci,rogerpueyo/luci,LazyZhu/openwrt-luci-trunk-mod,palmettos/test,tcatm/luci,Kyklas/luci-proto-hso,nmav/luci,oyido/luci,openwrt-es/openwrt-luci,thesabbir/luci,981213/luci-1,bright-things/ionic-luci,slayerrensky/luci,Kyklas/luci-proto-hso,aa65535/luci,oneru/luci,Wedmer/luci,rogerpueyo/luci,jlopenwrtluci/luci,jlopenwrtluci/luci,openwrt/luci,david-xiao/luci,jorgifumi/luci,Noltari/luci,bittorf/luci,jlopenwrtluci/luci,oyido/luci,lcf258/openwrtcn,RuiChen1113/luci,urueedi/luci,opentechinstitute/luci,daofeng2015/luci,male-puppies/luci,artynet/luci,deepak78/new-luci,slayerrensky/luci,remakeelectric/luci,nmav/luci,david-xiao/luci,Kyklas/luci-proto-hso,taiha/luci,cappiewu/luci,db260179/openwrt-bpi-r1-luci,kuoruan/lede-luci,david-xiao/luci,MinFu/luci,Noltari/luci,wongsyrone/luci-1,obsy/luci,LuttyYang/luci,jchuang1977/luci-1,dwmw2/luci,thess/OpenWrt-luci,wongsyrone/luci-1,RedSnake64/openwrt-luci-packages,palmettos/cnLuCI,joaofvieira/luci,Hostle/luci,shangjiyu/luci-with-extra,ollie27/openwrt_luci,Hostle/openwrt-luci-multi-user,harveyhu2012/luci,schidler/ionic-luci,RedSnake64/openwrt-luci-packages,cshore-firmware/openwrt-luci,nwf/openwrt-luci,sujeet14108/luci,shangjiyu/luci-with-extra,nwf/openwrt-luci,keyidadi/luci,opentechinstitute/luci,lbthomsen/openwrt-luci,keyidadi/luci,palmettos/test,Kyklas/luci-proto-hso,cshore/luci,981213/luci-1,thesabbir/luci,MinFu/luci,rogerpueyo/luci,keyidadi/luci,MinFu/luci,tobiaswaldvogel/luci,taiha/luci,obsy/luci,slayerrensky/luci,urueedi/luci,palmettos/cnLuCI,lcf258/openwrtcn,jchuang1977/luci-1,ollie27/openwrt_luci,mumuqz/luci,palmettos/test,zhaoxx063/luci,LuttyYang/luci,dwmw2/luci,jchuang1977/luci-1,Hostle/openwrt-luci-multi-user,openwrt-es/openwrt-luci,oneru/luci,openwrt-es/openwrt-luci,jlopenwrtluci/luci,deepak78/new-luci,hnyman/luci,maxrio/luci981213,rogerpueyo/luci,ollie27/openwrt_luci,RuiChen1113/luci,RedSnake64/openwrt-luci-packages,kuoruan/luci,remakeelectric/luci,shangjiyu/luci-with-extra,chris5560/openwrt-luci,obsy/luci,schidler/ionic-luci,fkooman/luci,palmettos/cnLuCI,remakeelectric/luci,981213/luci-1,lcf258/openwrtcn,zhaoxx063/luci,harveyhu2012/luci,981213/luci-1,dwmw2/luci,slayerrensky/luci,urueedi/luci,obsy/luci,lcf258/openwrtcn,Hostle/openwrt-luci-multi-user,bright-things/ionic-luci,remakeelectric/luci,taiha/luci,cshore/luci,kuoruan/luci,teslamint/luci,aa65535/luci,tobiaswaldvogel/luci,Noltari/luci,teslamint/luci,tobiaswaldvogel/luci,zhaoxx063/luci,ff94315/luci-1,ReclaimYourPrivacy/cloak-luci,dwmw2/luci,palmettos/test,zhaoxx063/luci,urueedi/luci,opentechinstitute/luci,kuoruan/luci,joaofvieira/luci,kuoruan/luci,dismantl/luci-0.12,sujeet14108/luci,hnyman/luci,remakeelectric/luci,db260179/openwrt-bpi-r1-luci,NeoRaider/luci,ReclaimYourPrivacy/cloak-luci,ReclaimYourPrivacy/cloak-luci,cappiewu/luci,oneru/luci,palmettos/test,Wedmer/luci,thesabbir/luci,opentechinstitute/luci,daofeng2015/luci,Sakura-Winkey/LuCI,artynet/luci,marcel-sch/luci,cshore/luci,marcel-sch/luci,hnyman/luci,forward619/luci,rogerpueyo/luci,bright-things/ionic-luci,openwrt/luci,oyido/luci,ollie27/openwrt_luci,cshore-firmware/openwrt-luci,shangjiyu/luci-with-extra,Wedmer/luci,dwmw2/luci,wongsyrone/luci-1,slayerrensky/luci,openwrt/luci,cshore/luci,hnyman/luci,LazyZhu/openwrt-luci-trunk-mod,deepak78/new-luci,aircross/OpenWrt-Firefly-LuCI,cappiewu/luci,chris5560/openwrt-luci,shangjiyu/luci-with-extra,RuiChen1113/luci,kuoruan/luci,thesabbir/luci,shangjiyu/luci-with-extra,nwf/openwrt-luci,jlopenwrtluci/luci,deepak78/new-luci,jlopenwrtluci/luci,ff94315/luci-1,openwrt-es/openwrt-luci,sujeet14108/luci,chris5560/openwrt-luci,aircross/OpenWrt-Firefly-LuCI,tcatm/luci,david-xiao/luci,artynet/luci,Sakura-Winkey/LuCI,981213/luci-1,palmettos/test,daofeng2015/luci,Kyklas/luci-proto-hso,Wedmer/luci,kuoruan/luci,rogerpueyo/luci,harveyhu2012/luci,aa65535/luci,obsy/luci,Hostle/luci,RuiChen1113/luci,tcatm/luci,keyidadi/luci,hnyman/luci,LazyZhu/openwrt-luci-trunk-mod,tobiaswaldvogel/luci,florian-shellfire/luci,bittorf/luci,aa65535/luci,obsy/luci,opentechinstitute/luci,kuoruan/luci,dismantl/luci-0.12,palmettos/test,zhaoxx063/luci,urueedi/luci,jlopenwrtluci/luci,opentechinstitute/luci,Wedmer/luci,openwrt/luci,lcf258/openwrtcn,nmav/luci,nmav/luci,joaofvieira/luci,thess/OpenWrt-luci,ReclaimYourPrivacy/cloak-luci,marcel-sch/luci,zhaoxx063/luci,NeoRaider/luci,ollie27/openwrt_luci,remakeelectric/luci,Kyklas/luci-proto-hso,jorgifumi/luci,shangjiyu/luci-with-extra,aircross/OpenWrt-Firefly-LuCI,zhaoxx063/luci,LazyZhu/openwrt-luci-trunk-mod,fkooman/luci,remakeelectric/luci,oneru/luci,mumuqz/luci,lcf258/openwrtcn,thess/OpenWrt-luci,tcatm/luci,schidler/ionic-luci,forward619/luci,joaofvieira/luci,Noltari/luci,LazyZhu/openwrt-luci-trunk-mod,ff94315/luci-1,jchuang1977/luci-1,palmettos/cnLuCI,nwf/openwrt-luci,teslamint/luci,NeoRaider/luci,jorgifumi/luci,nmav/luci,lbthomsen/openwrt-luci,NeoRaider/luci,RedSnake64/openwrt-luci-packages,jorgifumi/luci,tobiaswaldvogel/luci,harveyhu2012/luci,Hostle/luci,RuiChen1113/luci,teslamint/luci,NeoRaider/luci,Wedmer/luci,artynet/luci,oyido/luci,urueedi/luci,ff94315/luci-1,Hostle/luci,bittorf/luci,nmav/luci,Hostle/openwrt-luci-multi-user,lbthomsen/openwrt-luci,bittorf/luci,palmettos/cnLuCI,dismantl/luci-0.12,schidler/ionic-luci,LuttyYang/luci,wongsyrone/luci-1,nwf/openwrt-luci,MinFu/luci,oneru/luci,jchuang1977/luci-1,mumuqz/luci,LazyZhu/openwrt-luci-trunk-mod,dwmw2/luci,nwf/openwrt-luci,aircross/OpenWrt-Firefly-LuCI,marcel-sch/luci,hnyman/luci,david-xiao/luci,urueedi/luci,urueedi/luci,bright-things/ionic-luci,Noltari/luci,RedSnake64/openwrt-luci-packages,db260179/openwrt-bpi-r1-luci,RedSnake64/openwrt-luci-packages,maxrio/luci981213,aa65535/luci,aircross/OpenWrt-Firefly-LuCI,ollie27/openwrt_luci,forward619/luci,cappiewu/luci,Noltari/luci,lbthomsen/openwrt-luci,981213/luci-1,kuoruan/lede-luci,cshore/luci,schidler/ionic-luci,schidler/ionic-luci,cshore-firmware/openwrt-luci,tcatm/luci,LazyZhu/openwrt-luci-trunk-mod,thesabbir/luci,aircross/OpenWrt-Firefly-LuCI,keyidadi/luci,deepak78/new-luci,fkooman/luci,NeoRaider/luci,Wedmer/luci,Sakura-Winkey/LuCI,RuiChen1113/luci,nmav/luci,aa65535/luci,daofeng2015/luci,lbthomsen/openwrt-luci,ReclaimYourPrivacy/cloak-luci,teslamint/luci,Hostle/luci,openwrt-es/openwrt-luci,openwrt/luci,ff94315/luci-1,dismantl/luci-0.12,joaofvieira/luci,dismantl/luci-0.12,thess/OpenWrt-luci,sujeet14108/luci,dismantl/luci-0.12,slayerrensky/luci,ff94315/luci-1,Sakura-Winkey/LuCI,LuttyYang/luci,oneru/luci,fkooman/luci,marcel-sch/luci,cshore/luci,rogerpueyo/luci,slayerrensky/luci,thesabbir/luci,cshore-firmware/openwrt-luci,LuttyYang/luci,oneru/luci,teslamint/luci,dismantl/luci-0.12,joaofvieira/luci,mumuqz/luci,thess/OpenWrt-luci,palmettos/cnLuCI,openwrt-es/openwrt-luci,wongsyrone/luci-1,kuoruan/lede-luci,male-puppies/luci,Hostle/openwrt-luci-multi-user,LazyZhu/openwrt-luci-trunk-mod,tobiaswaldvogel/luci,db260179/openwrt-bpi-r1-luci,openwrt/luci,Hostle/openwrt-luci-multi-user,keyidadi/luci,male-puppies/luci,lbthomsen/openwrt-luci,cshore-firmware/openwrt-luci,ff94315/luci-1,kuoruan/lede-luci,fkooman/luci,db260179/openwrt-bpi-r1-luci,tobiaswaldvogel/luci,teslamint/luci,thesabbir/luci,cshore-firmware/openwrt-luci,NeoRaider/luci,florian-shellfire/luci,thess/OpenWrt-luci,Wedmer/luci,lcf258/openwrtcn,openwrt/luci,oyido/luci,db260179/openwrt-bpi-r1-luci,bittorf/luci,ollie27/openwrt_luci,teslamint/luci,Hostle/luci,forward619/luci,cshore/luci,thesabbir/luci,LuttyYang/luci,kuoruan/lede-luci,jorgifumi/luci,Noltari/luci,tcatm/luci,db260179/openwrt-bpi-r1-luci,dwmw2/luci,male-puppies/luci,mumuqz/luci,deepak78/new-luci,Hostle/luci,nmav/luci,fkooman/luci,opentechinstitute/luci,Sakura-Winkey/LuCI,kuoruan/luci,maxrio/luci981213,harveyhu2012/luci,opentechinstitute/luci,981213/luci-1,forward619/luci,Noltari/luci,jchuang1977/luci-1,david-xiao/luci,jorgifumi/luci,lcf258/openwrtcn,deepak78/new-luci,Hostle/luci,RuiChen1113/luci,keyidadi/luci,MinFu/luci,daofeng2015/luci,marcel-sch/luci,Noltari/luci,chris5560/openwrt-luci,chris5560/openwrt-luci,LuttyYang/luci,hnyman/luci,zhaoxx063/luci,openwrt-es/openwrt-luci,chris5560/openwrt-luci,bright-things/ionic-luci,schidler/ionic-luci,RuiChen1113/luci,florian-shellfire/luci,NeoRaider/luci,aa65535/luci,ReclaimYourPrivacy/cloak-luci,Hostle/openwrt-luci-multi-user,oneru/luci,lbthomsen/openwrt-luci,male-puppies/luci,florian-shellfire/luci,keyidadi/luci,forward619/luci,wongsyrone/luci-1,male-puppies/luci,openwrt/luci,obsy/luci,taiha/luci,bittorf/luci,daofeng2015/luci,cappiewu/luci,artynet/luci,nwf/openwrt-luci,chris5560/openwrt-luci,ollie27/openwrt_luci,deepak78/new-luci,MinFu/luci,rogerpueyo/luci,db260179/openwrt-bpi-r1-luci,cappiewu/luci,joaofvieira/luci,marcel-sch/luci,cshore/luci,sujeet14108/luci,sujeet14108/luci,kuoruan/lede-luci,slayerrensky/luci,schidler/ionic-luci,david-xiao/luci,kuoruan/lede-luci,bright-things/ionic-luci,shangjiyu/luci-with-extra,harveyhu2012/luci,maxrio/luci981213,taiha/luci,joaofvieira/luci,cshore-firmware/openwrt-luci,palmettos/test,bittorf/luci,florian-shellfire/luci,Hostle/openwrt-luci-multi-user,remakeelectric/luci,maxrio/luci981213,ReclaimYourPrivacy/cloak-luci,Sakura-Winkey/LuCI,kuoruan/lede-luci,jorgifumi/luci,sujeet14108/luci,mumuqz/luci,chris5560/openwrt-luci,wongsyrone/luci-1,RedSnake64/openwrt-luci-packages,MinFu/luci,aircross/OpenWrt-Firefly-LuCI,jchuang1977/luci-1,harveyhu2012/luci,marcel-sch/luci,aa65535/luci,oyido/luci,fkooman/luci,maxrio/luci981213,maxrio/luci981213,tobiaswaldvogel/luci,wongsyrone/luci-1,palmettos/cnLuCI,jlopenwrtluci/luci,nmav/luci,ff94315/luci-1,florian-shellfire/luci,nwf/openwrt-luci,Kyklas/luci-proto-hso,forward619/luci,Sakura-Winkey/LuCI,lcf258/openwrtcn,artynet/luci,taiha/luci,sujeet14108/luci,mumuqz/luci,florian-shellfire/luci,cshore-firmware/openwrt-luci,thess/OpenWrt-luci,bittorf/luci,daofeng2015/luci,bright-things/ionic-luci,jchuang1977/luci-1,florian-shellfire/luci,lcf258/openwrtcn,oyido/luci,dwmw2/luci,forward619/luci,cappiewu/luci,daofeng2015/luci,openwrt-es/openwrt-luci,LuttyYang/luci,mumuqz/luci,bright-things/ionic-luci,artynet/luci,palmettos/cnLuCI,hnyman/luci,fkooman/luci,thess/OpenWrt-luci,lbthomsen/openwrt-luci,oyido/luci,taiha/luci,cappiewu/luci,Sakura-Winkey/LuCI,artynet/luci,ReclaimYourPrivacy/cloak-luci,tcatm/luci,david-xiao/luci,MinFu/luci,obsy/luci
|
2e8e0c4ac7efc8e58bd59921541966b55e3d1613
|
lua/timer.lua
|
lua/timer.lua
|
--- Simple timer class.
local mod = {}
local dpdk = require "dpdk"
local timer = {}
timer.__index = timer
function mod:new(time)
return setmetatable({
time = time or 0,
stop = dpdk.getTime() + (time or 0)
}, timer)
end
function timer:running()
return self.stop > dpdk.getTime()
end
function timer:expired()
return self.stop <= dpdk.getTime()
end
function timer:timeLeft()
return self.stop - dpdk.getTime()
end
function timer:reset(time)
self.stop = dpdk.getTime() + (time or self.time)
end
--- Perform a busy wait on the timer.
-- Returns early if Phobos is stopped (phobos.running() == false).
function timer:busyWait()
while not self:expired() and phobos.running() do
end
return phobos.running()
end
--- Perform a non-busy wait on the timer.
--- Might be less accurate than busyWait()
function timer:wait()
-- TODO: implement
return self:busyWait()
end
return mod
|
--- Simple timer class.
local mod = {}
local phobos = require "phobos"
local timer = {}
timer.__index = timer
function mod:new(time)
return setmetatable({
time = time or 0,
stop = phobos.getTime() + (time or 0)
}, timer)
end
function timer:running()
return self.stop > phobos.getTime()
end
function timer:expired()
return self.stop <= phobos.getTime()
end
function timer:timeLeft()
return self.stop - phobos.getTime()
end
function timer:reset(time)
self.stop = phobos.getTime() + (time or self.time)
end
--- Perform a busy wait on the timer.
-- Returns early if Phobos is stopped (phobos.running() == false).
function timer:busyWait()
while not self:expired() and phobos.running() do
end
return phobos.running()
end
--- Perform a non-busy wait on the timer.
--- Might be less accurate than busyWait()
function timer:wait()
-- TODO: implement
return self:busyWait()
end
return mod
|
fix timer
|
fix timer
|
Lua
|
mit
|
emmericp/libmoon,libmoon/libmoon,scholzd/libmoon,scholzd/libmoon,libmoon/libmoon,scholzd/libmoon,libmoon/libmoon,emmericp/libmoon,emmericp/libmoon
|
60ad7b46e883a3e0ed49853c8fd515a2c579257c
|
hash.lua
|
hash.lua
|
local ffi = require 'ffi'
local tds = require 'tds.env'
local C = tds.C
local hash = {}
function hash.new()
local self = C.tds_hash_new()
if self == nil then
error('unable to allocate hash')
end
ffi.gc(self, C.tds_hash_free)
return self
end
local function setelem(elem, lelem)
if type(lelem) == 'string' then
C.tds_elem_set_string(elem, lelem, #lelem)
elseif type(lelem) == 'number' then
C.tds_elem_set_number(elem, lelem)
else
error('string or number key/value expected')
end
end
local function findkey(self, lkey)
local obj
if type(lkey) == 'string' then
obj = C.tds_hash_search_string(self, lkey, #lkey)
elseif type(lkey) == 'number' then
obj = C.tds_hash_search_number(self, lkey)
else
error('string or number key expected')
end
return obj
end
function hash:__newindex(lkey, lval)
assert(self)
local obj = findkey(self, lkey)
if obj ~= nil then
if lval then
local val = C.tds_hash_object_value(obj)
setelem(val, lval)
else
C.tds_hash_remove(self, obj)
C.tds_hash_object_free(obj)
end
else
local obj = C.tds_hash_object_new()
local key = C.tds_hash_object_key(obj)
local val = C.tds_hash_object_value(obj)
setelem(val, lval)
setelem(key, lkey)
C.tds_hash_insert(self, obj)
end
end
local function getelem(elem)
assert(elem)
local value
local elemtype = C.tds_elem_type(elem)
if elemtype == 110 then--string.byte('n') then
value = C.tds_elem_get_number(elem)
elseif elemtype == 115 then--string.byte('s') then
value = ffi.string(C.tds_elem_get_string(elem), C.tds_elem_get_string_size(elem))
else
error(string.format('value type <%s> not supported yet', elemtype))
end
return value
end
function hash:__index(lkey)
assert(self)
local obj = findkey(self, lkey)
if obj ~= nil then
local val = getelem(C.tds_hash_object_value(obj))
return val
end
end
function hash:__len()
assert(self)
return tonumber(C.tds_hash_size(self))
end
function hash:__pairs()
assert(self)
local iterator = C.tds_hash_iterator_new(self)
ffi.gc(iterator, C.tds_hash_iterator_free)
return function()
local obj = C.tds_hash_iterator_next(iterator)
if obj ~= nil then
local key = getelem(C.tds_hash_object_key(obj))
local val = getelem(C.tds_hash_object_value(obj))
return key, val
end
end
end
hash.pairs = hash.__pairs
ffi.metatype('tds_hash', hash)
-- table constructor
local hash_ctr = {}
setmetatable(
hash_ctr,
{
__index = hash,
__newindex = hash,
__call = hash.new
}
)
tds.hash = hash_ctr
return hash_ctr
|
local ffi = require 'ffi'
local tds = require 'tds.env'
local C = tds.C
local hash = {}
function hash.new()
local self = C.tds_hash_new()
if self == nil then
error('unable to allocate hash')
end
ffi.gc(self, C.tds_hash_free)
return self
end
local function setelem(elem, lelem)
if type(lelem) == 'string' then
C.tds_elem_set_string(elem, lelem, #lelem)
elseif type(lelem) == 'number' then
C.tds_elem_set_number(elem, lelem)
else
error('string or number key/value expected')
end
end
local function findkey(self, lkey)
local obj
if type(lkey) == 'string' then
obj = C.tds_hash_search_string(self, lkey, #lkey)
elseif type(lkey) == 'number' then
obj = C.tds_hash_search_number(self, lkey)
else
error('string or number key expected')
end
return obj
end
function hash:__newindex(lkey, lval)
assert(self)
local obj = findkey(self, lkey)
if obj ~= nil then
if lval then
local val = C.tds_hash_object_value(obj)
C.tds_elem_free(val)
setelem(val, lval)
else
C.tds_hash_remove(self, obj)
C.tds_hash_object_free(obj)
end
else
local obj = C.tds_hash_object_new()
local key = C.tds_hash_object_key(obj)
local val = C.tds_hash_object_value(obj)
setelem(val, lval)
setelem(key, lkey)
C.tds_hash_insert(self, obj)
end
end
local function getelem(elem)
assert(elem)
local value
local elemtype = C.tds_elem_type(elem)
if elemtype == 110 then--string.byte('n') then
value = C.tds_elem_get_number(elem)
elseif elemtype == 115 then--string.byte('s') then
value = ffi.string(C.tds_elem_get_string(elem), C.tds_elem_get_string_size(elem))
else
error(string.format('value type <%s> not supported yet', elemtype))
end
return value
end
function hash:__index(lkey)
assert(self)
local obj = findkey(self, lkey)
if obj ~= nil then
local val = getelem(C.tds_hash_object_value(obj))
return val
end
end
function hash:__len()
assert(self)
return tonumber(C.tds_hash_size(self))
end
function hash:__pairs()
assert(self)
local iterator = C.tds_hash_iterator_new(self)
ffi.gc(iterator, C.tds_hash_iterator_free)
return function()
local obj = C.tds_hash_iterator_next(iterator)
if obj ~= nil then
local key = getelem(C.tds_hash_object_key(obj))
local val = getelem(C.tds_hash_object_value(obj))
return key, val
end
end
end
hash.pairs = hash.__pairs
ffi.metatype('tds_hash', hash)
-- table constructor
local hash_ctr = {}
setmetatable(
hash_ctr,
{
__index = hash,
__newindex = hash,
__call = hash.new
}
)
tds.hash = hash_ctr
return hash_ctr
|
hash: fix leak
|
hash: fix leak
|
Lua
|
bsd-3-clause
|
jakezhaojb/tds,jakezhaojb/tds,jakezhaojb/tds,torch/tds,jakezhaojb/tds,Moodstocks/tds
|
e5854ab93a07c67531fbe2ffb8da549211ca4804
|
Quadtastic/QuadList.lua
|
Quadtastic/QuadList.lua
|
local current_folder = ... and (...):match '(.-%.?)[^%.]+$' or ''
local Frame = require(current_folder .. ".Frame")
local Layout = require(current_folder .. ".Layout")
local Text = require(current_folder .. ".Text")
local Scrollpane = require(current_folder .. ".Scrollpane")
local imgui = require(current_folder .. ".imgui")
local libquadtastic = require(current_folder .. ".libquadtastic")
local Button = require(current_folder .. ".Button")
local QuadList = {}
local function draw_elements(gui_state, state, elements, last_hovered, quad_bounds)
local clicked_element, hovered_element, double_clicked_element
for name,element in pairs(elements) do
if name ~= "_META" then
local row_height = 16
-- check if this quad will be visible, and only draw it if it is visible.
local visible = gui_state.layout.next_y + row_height >= state.quad_scrollpane_state.y and
gui_state.layout.next_y < state.quad_scrollpane_state.y + (state.quad_scrollpane_state.h or 0)
local input_consumed
if visible then
local background_quads
if state.selection:is_selected(element) then
background_quads = gui_state.style.quads.rowbackground.selected
elseif last_hovered == element then
background_quads = gui_state.style.quads.rowbackground.hovered
else
background_quads = gui_state.style.quads.rowbackground.default
end
love.graphics.setColor(255, 255, 255)
-- Draw row background
love.graphics.draw( -- top
gui_state.style.stylesheet, background_quads.top,
gui_state.layout.next_x, gui_state.layout.next_y,
0, gui_state.layout.max_w, 1)
love.graphics.draw( -- center
gui_state.style.stylesheet, background_quads.center,
gui_state.layout.next_x, gui_state.layout.next_y + 2,
0, gui_state.layout.max_w, 12)
love.graphics.draw( -- bottom
gui_state.style.stylesheet, background_quads.bottom,
gui_state.layout.next_x, gui_state.layout.next_y + 14,
0, gui_state.layout.max_w, 1)
if libquadtastic.is_quad(element) then
Text.draw(gui_state, 2, nil, gui_state.layout.max_w, nil,
string.format("%s: x%d y%d %dx%d", tostring(name), element.x, element.y, element.w, element.h))
else
local raw_quads, quads
if state.collapsed_groups[element] then
raw_quads = gui_state.style.raw_quads.rowbackground.collapsed
quads = gui_state.style.quads.rowbackground.collapsed
else
raw_quads = gui_state.style.raw_quads.rowbackground.expanded
quads = gui_state.style.quads.rowbackground.expanded
end
assert(raw_quads.default.w == raw_quads.default.h)
local quad_size = raw_quads.default.w
local x, y = gui_state.layout.next_x + 1, gui_state.layout.next_y + 5
local w, h = quad_size, quad_size
local clicked, pressed, hovered = Button.draw_flat(gui_state, x, y, w, h, nil, quads)
if clicked then
if state.collapsed_groups[element] then
state.collapsed_groups[element] = false
else
state.collapsed_groups[element] = true
end
end
input_consumed = clicked or pressed or hovered
Text.draw(gui_state, quad_size + 3, nil, gui_state.layout.max_w, nil,
string.format("%s", tostring(name)))
end
end
gui_state.layout.adv_x = gui_state.layout.max_w
gui_state.layout.adv_y = row_height
quad_bounds[element] = {x = gui_state.layout.next_x, y = gui_state.layout.next_y,
w = gui_state.layout.adv_x, h = gui_state.layout.adv_y}
-- Check if the mouse was clicked on this list entry
local x, y = gui_state.layout.next_x, gui_state.layout.next_y
local w, h = gui_state.layout.adv_x, gui_state.layout.adv_y
if not input_consumed and imgui.was_mouse_pressed(gui_state, x, y, w, h) then
clicked_element = element
if gui_state.input.mouse.buttons[1].double_clicked then
double_clicked_element = element
end
end
hovered_element = not input_consumed and
imgui.is_mouse_in_rect(gui_state, x, y, w, h) and
element or hovered_element
Layout.next(gui_state, "|")
-- If we are drawing a group, we now need to recursively draw its
-- children
if not libquadtastic.is_quad(element) and not state.collapsed_groups[element] then
-- Use translate to add some indentation
love.graphics.translate(9, 0)
local rec_clicked, rec_hovered = draw_elements(gui_state, state, element, last_hovered, quad_bounds)
clicked_element = clicked_element or rec_clicked
hovered_element = hovered_element or rec_hovered
love.graphics.translate(-9, 0)
end
end
end
return clicked_element, hovered_element, double_clicked_element
end
-- Draw the quads in the current state.
-- active is a table that contains for each quad whether it is active.
-- hovered is nil, or a single quad that the mouse hovers over.
QuadList.draw = function(gui_state, state, x, y, w, h, last_hovered)
-- The quad that the user clicked on
local clicked
local hovered
local double_clicked
local quad_bounds = {}
do Frame.start(gui_state, x, y, w, h)
imgui.push_style(gui_state, "font", gui_state.style.small_font)
imgui.push_style(gui_state, "font_color", gui_state.style.palette.shades.brightest)
do state.quad_scrollpane_state = Scrollpane.start(gui_state, nil, nil, nil, nil, state.quad_scrollpane_state)
do Layout.start(gui_state, nil, nil, nil, nil, {noscissor = true})
clicked, hovered, double_clicked = draw_elements(gui_state, state, state.quads, last_hovered, quad_bounds)
end Layout.finish(gui_state, "|")
-- Restrict the viewport's position to the visible content as good as
-- possible
state.quad_scrollpane_state.min_x = 0
state.quad_scrollpane_state.min_y = 0
state.quad_scrollpane_state.max_x = gui_state.layout.adv_x
state.quad_scrollpane_state.max_y = math.max(gui_state.layout.adv_y, gui_state.layout.max_h)
end Scrollpane.finish(gui_state, state.quad_scrollpane_state)
imgui.pop_style(gui_state, "font")
imgui.pop_style(gui_state, "font_color")
end Frame.finish(gui_state)
-- Move viewport to focus quad if necessary
if state.quad_scrollpane_state.focus_quad and
quad_bounds[state.quad_scrollpane_state.focus_quad]
then
Scrollpane.move_into_view(
state.quad_scrollpane_state,
quad_bounds[state.quad_scrollpane_state.focus_quad])
-- Clear focus quad
state.quad_scrollpane_state.focus_quad = nil
end
return clicked, hovered, double_clicked
end
QuadList.move_quad_into_view = function(scrollpane_state, quad)
scrollpane_state.focus_quad = quad
end
return QuadList
|
local current_folder = ... and (...):match '(.-%.?)[^%.]+$' or ''
local Frame = require(current_folder .. ".Frame")
local Layout = require(current_folder .. ".Layout")
local Text = require(current_folder .. ".Text")
local Scrollpane = require(current_folder .. ".Scrollpane")
local imgui = require(current_folder .. ".imgui")
local libquadtastic = require(current_folder .. ".libquadtastic")
local Button = require(current_folder .. ".Button")
local QuadList = {}
local function draw_elements(gui_state, state, elements, last_hovered, quad_bounds)
local clicked_element, hovered_element, double_clicked_element
for name,element in pairs(elements) do
if name ~= "_META" then
local row_height = 16
-- check if this quad will be visible, and only draw it if it is visible.
local visible = gui_state.layout.next_y + row_height >= state.quad_scrollpane_state.y and
gui_state.layout.next_y < state.quad_scrollpane_state.y + (state.quad_scrollpane_state.h or 0)
local input_consumed
if visible then
local background_quads
if state.selection:is_selected(element) then
background_quads = gui_state.style.quads.rowbackground.selected
elseif last_hovered == element then
background_quads = gui_state.style.quads.rowbackground.hovered
else
background_quads = gui_state.style.quads.rowbackground.default
end
love.graphics.setColor(255, 255, 255)
-- Draw row background
love.graphics.draw( -- top
gui_state.style.stylesheet, background_quads.top,
gui_state.layout.next_x, gui_state.layout.next_y,
0, gui_state.layout.max_w, 1)
love.graphics.draw( -- center
gui_state.style.stylesheet, background_quads.center,
gui_state.layout.next_x, gui_state.layout.next_y + 2,
0, gui_state.layout.max_w, 12)
love.graphics.draw( -- bottom
gui_state.style.stylesheet, background_quads.bottom,
gui_state.layout.next_x, gui_state.layout.next_y + 14,
0, gui_state.layout.max_w, 1)
if libquadtastic.is_quad(element) then
Text.draw(gui_state, 2, nil, gui_state.layout.max_w, nil,
string.format("%s: x%d y%d %dx%d", tostring(name), element.x, element.y, element.w, element.h))
else
local raw_quads, quads
if state.collapsed_groups[element] then
raw_quads = gui_state.style.raw_quads.rowbackground.collapsed
quads = gui_state.style.quads.rowbackground.collapsed
else
raw_quads = gui_state.style.raw_quads.rowbackground.expanded
quads = gui_state.style.quads.rowbackground.expanded
end
assert(raw_quads.default.w == raw_quads.default.h)
local quad_size = raw_quads.default.w
local x, y = gui_state.layout.next_x + 1, gui_state.layout.next_y + 5
local w, h = quad_size, quad_size
local clicked, pressed, hovered = Button.draw_flat(gui_state, x, y, w, h, nil, quads)
if clicked then
if state.collapsed_groups[element] then
state.collapsed_groups[element] = false
else
state.collapsed_groups[element] = true
end
end
input_consumed = clicked or pressed or hovered
Text.draw(gui_state, quad_size + 3, nil, gui_state.layout.max_w, nil,
string.format("%s", tostring(name)))
end
end
gui_state.layout.adv_x = gui_state.layout.max_w
gui_state.layout.adv_y = row_height
quad_bounds[element] = {x = gui_state.layout.next_x, y = gui_state.layout.next_y,
w = gui_state.layout.adv_x, h = gui_state.layout.adv_y}
-- Check if the mouse was clicked on this list entry
local x, y = gui_state.layout.next_x, gui_state.layout.next_y
local w, h = gui_state.layout.adv_x, gui_state.layout.adv_y
if not input_consumed and imgui.was_mouse_pressed(gui_state, x, y, w, h) then
clicked_element = element
if gui_state.input.mouse.buttons[1].double_clicked then
double_clicked_element = element
end
end
hovered_element = not input_consumed and
imgui.is_mouse_in_rect(gui_state, x, y, w, h) and
element or hovered_element
Layout.next(gui_state, "|")
-- If we are drawing a group, we now need to recursively draw its
-- children
if not libquadtastic.is_quad(element) and not state.collapsed_groups[element] then
-- Use translate to add some indentation
love.graphics.translate(9, 0)
local rec_clicked, rec_hovered, rec_double_clicked = draw_elements(gui_state, state, element, last_hovered, quad_bounds)
clicked_element = clicked_element or rec_clicked
hovered_element = hovered_element or rec_hovered
double_clicked_element = double_clicked_element or rec_double_clicked
love.graphics.translate(-9, 0)
end
end
end
return clicked_element, hovered_element, double_clicked_element
end
-- Draw the quads in the current state.
-- active is a table that contains for each quad whether it is active.
-- hovered is nil, or a single quad that the mouse hovers over.
QuadList.draw = function(gui_state, state, x, y, w, h, last_hovered)
-- The quad that the user clicked on
local clicked
local hovered
local double_clicked
local quad_bounds = {}
do Frame.start(gui_state, x, y, w, h)
imgui.push_style(gui_state, "font", gui_state.style.small_font)
imgui.push_style(gui_state, "font_color", gui_state.style.palette.shades.brightest)
do state.quad_scrollpane_state = Scrollpane.start(gui_state, nil, nil, nil, nil, state.quad_scrollpane_state)
do Layout.start(gui_state, nil, nil, nil, nil, {noscissor = true})
clicked, hovered, double_clicked = draw_elements(gui_state, state, state.quads, last_hovered, quad_bounds)
end Layout.finish(gui_state, "|")
-- Restrict the viewport's position to the visible content as good as
-- possible
state.quad_scrollpane_state.min_x = 0
state.quad_scrollpane_state.min_y = 0
state.quad_scrollpane_state.max_x = gui_state.layout.adv_x
state.quad_scrollpane_state.max_y = math.max(gui_state.layout.adv_y, gui_state.layout.max_h)
end Scrollpane.finish(gui_state, state.quad_scrollpane_state)
imgui.pop_style(gui_state, "font")
imgui.pop_style(gui_state, "font_color")
end Frame.finish(gui_state)
-- Move viewport to focus quad if necessary
if state.quad_scrollpane_state.focus_quad and
quad_bounds[state.quad_scrollpane_state.focus_quad]
then
Scrollpane.move_into_view(
state.quad_scrollpane_state,
quad_bounds[state.quad_scrollpane_state.focus_quad])
-- Clear focus quad
state.quad_scrollpane_state.focus_quad = nil
end
return clicked, hovered, double_clicked
end
QuadList.move_quad_into_view = function(scrollpane_state, quad)
scrollpane_state.focus_quad = quad
end
return QuadList
|
Fix double-click to rename not working
|
Fix double-click to rename not working
The quad list draws elements of a group recursively, but ignored
the double-clicked element that was returned by the recursive call.
That was the reason why double-clicking on non-top-level quads or
groups did not open the rename dialog.
This commit fixes that.
Resolves #29
|
Lua
|
mit
|
25A0/Quadtastic,25A0/Quadtastic
|
022283296067013c812a0ec87e852d35172027c2
|
premakeUtils.lua
|
premakeUtils.lua
|
baseAbsPath = os.getcwd()
srcAbsPath = baseAbsPath .. "/src"
externalAbsPath = baseAbsPath .. "/external"
buildPath = "build/" .. _ACTION
genAbsPath = baseAbsPath .. "/build/gen"
buildAbsPath = baseAbsPath .. "/" .. buildPath
versionMajor = 0
versionMinor = 0
versionBuild = 0
function coSetWorkspaceDefaults()
configurations {"debug", "release", "prebuildDebug", "prebuildRelease"}
location(buildPath)
objdir(buildPath .. "/obj")
libdirs { buildPath .. "/bin" }
targetdir(buildPath .. "/bin")
defines { "coVERSION_MAJOR="..versionMajor, "coVERSION_MINOR="..versionMinor, "coVERSION_BUILD="..versionBuild }
includedirs { "src", "build/gen" }
end
function coSetPCH(_dir, _projectName, _fileName)
pchheader(_projectName .. "/".. _fileName .. '.h')
pchsource(_fileName .. '.cpp')
--[[
filter { "action:vs*" }
pchheader(_fileName .. '.h')
pchsource(_fileName .. '.cpp')
filter { "action:not vs*" }
pchheader(_dir .. '/' .. _fileName .. '.h')
filter {}
--]]
end
function coSetProjectDefaults(_name, _options)
print("Generating project ".._name.."...")
project(_name)
architecture "x86_64"
warnings "Extra"
kind "StaticLib"
location (buildAbsPath.."/projects")
projectDir = "src/".._name
defines { "coPROJECT_NAME=".._name }
debugdir "$(OutDir)"
if not (_options and _options.prebuildDependency) then
--removeconfigurations {"prebuild*"}
configurations { "debug", "release" }
end
filter{"configurations:debug or release"}
defines {"coREFLECT_ENABLED"}
filter { "configurations:debug or prebuildDebug" }
targetsuffix "_d"
filter { "configurations:release or prebuildRelease" }
optimize "On"
filter {}
end
function coSetCppProjectDefaults(_name)
coSetProjectDefaults(_name)
rtti "Off"
language "C++"
exceptionhandling "Off"
vectorextensions "SSE2"
floatingpoint "Fast"
editandcontinue "Off"
flags { "Symbols", "NoMinimalRebuild", "FatalWarnings", "C++14", "MultiProcessorCompile" }
files { "**.cpp", "**.h"}
if os.isfile("pch.h") then
coSetPCH(projectDir, _name, "pch")
end
filter { "gmake" }
buildoptions { "-Wno-reorder", "-Wno-deprecated" }
includedirs { gmakeIncludeDir }
filter { "vs*" }
defines { "_HAS_EXCEPTIONS=0" }
--flags { "StaticRuntime" }
linkoptions { "/ENTRY:mainCRTStartup" }
filter { "configurations:release or prebuildRelease" }
flags { "OptimizeSpeed", "NoFramePointer"}
filter {"configurations:debug or release"}
if os.isfile("reflect.cpp") then
prebuildcommands{"$(OutputPath)prebuild_dist.exe '" .. srcAbsPath .. "' '" .. genAbsPath .. "' '" .. _name .. "' '".. _name .."/pch.h''"}
end
filter {}
end
function coSetShaderProjectDefaults(_name)
coSetProjectDefaults(_name)
kind "Utility"
-- Defaults
files { "**.vert", "**.frag"}
--language "C++" -- We don't have better here
---[[
shaderOutPath = "$(OutDir)/shaders/%{file.name}.spv"
filter {'files:**.vert or **.frag'}
buildmessage 'Compiling %{file.relpath}'
buildcommands
{
'$(VULKAN_SDK)/Bin/glslangValidator.exe -V -o "'..shaderOutPath ..'" %{file.relpath}'
}
buildoutputs { shaderOutPath }
filter {}
--]]
end
function coSetProjectDependencies(_deps)
if not co_dependencies then
co_dependencies = {}
end
for _,v in pairs(_deps) do table.insert(co_dependencies, v) end
links(_deps)
end
function coGenerateProjectWorkspace(_params)
print("Generating workspace ".._params.name.."...")
workspace(_params.name)
coSetWorkspaceDefaults()
startproject(_params.projects[0])
for _, p in pairs(_params.projects) do
include("src/"..p)
end
if co_dependencies then
for _, d in pairs(co_dependencies) do
include("src/"..d)
end
end
end
|
baseAbsPath = os.getcwd()
srcAbsPath = baseAbsPath .. "/src"
externalAbsPath = baseAbsPath .. "/external"
buildPath = "build/" .. _ACTION
genAbsPath = baseAbsPath .. "/build/gen"
buildAbsPath = baseAbsPath .. "/" .. buildPath
versionMajor = 0
versionMinor = 0
versionBuild = 0
function coSetWorkspaceDefaults()
configurations {"debug", "release", "prebuildDebug", "prebuildRelease"}
location(buildPath)
objdir(buildPath .. "/obj")
libdirs { buildPath .. "/bin" }
targetdir(buildPath .. "/bin")
defines { "coVERSION_MAJOR="..versionMajor, "coVERSION_MINOR="..versionMinor, "coVERSION_BUILD="..versionBuild }
includedirs { "src", "build/gen" }
end
function coSetPCH(_dir, _projectName, _fileName)
pchheader(_projectName .. "/".. _fileName .. '.h')
pchsource(_fileName .. '.cpp')
--[[
filter { "action:vs*" }
pchheader(_fileName .. '.h')
pchsource(_fileName .. '.cpp')
filter { "action:not vs*" }
pchheader(_dir .. '/' .. _fileName .. '.h')
filter {}
--]]
end
function coSetProjectDefaults(_name, _options)
print("Generating project ".._name.."...")
project(_name)
architecture "x86_64"
warnings "Extra"
kind "StaticLib"
location (buildAbsPath.."/projects")
projectDir = "src/".._name
defines { "coPROJECT_NAME=".._name }
debugdir "$(OutDir)"
if not (_options and _options.prebuildDependency) then
--removeconfigurations {"prebuild*"}
configurations { "debug", "release" }
end
filter{"configurations:debug or release"}
defines {"coREFLECT_ENABLED"}
filter { "configurations:debug or prebuildDebug" }
targetsuffix "_d"
filter { "configurations:release or prebuildRelease" }
optimize "On"
filter {}
end
function coSetCppProjectDefaults(_name)
coSetProjectDefaults(_name)
rtti "Off"
language "C++"
exceptionhandling "Off"
vectorextensions "SSE2"
floatingpoint "Fast"
editandcontinue "Off"
flags { "Symbols", "NoMinimalRebuild", "FatalWarnings", "C++14", "MultiProcessorCompile" }
files { "**.cpp", "**.h"}
if os.isfile("pch.h") then
coSetPCH(projectDir, _name, "pch")
end
filter { "gmake" }
buildoptions { "-Wno-reorder", "-Wno-deprecated" }
includedirs { gmakeIncludeDir }
filter { "vs*" }
defines { "_HAS_EXCEPTIONS=0" }
--flags { "StaticRuntime" }
linkoptions { "/ENTRY:mainCRTStartup" }
filter { "configurations:release or prebuildRelease" }
flags { "OptimizeSpeed", "NoFramePointer"}
filter {"configurations:debug or release"}
if os.isfile("reflect.cpp") then
local command = '$(OutputPath)prebuild_dist.exe "' .. srcAbsPath .. '" "' .. genAbsPath .. '" "' .. _name .. '" "'.. _name ..'/pch.h"'
command = command .. ' -I="$(UniversalCRT_IncludePath)"'
prebuildcommands{command}
end
filter {}
end
function coSetShaderProjectDefaults(_name)
coSetProjectDefaults(_name)
kind "Utility"
-- Defaults
files { "**.vert", "**.frag"}
--language "C++" -- We don't have better here
---[[
shaderOutPath = "$(OutDir)/shaders/%{file.name}.spv"
filter {'files:**.vert or **.frag'}
buildmessage 'Compiling %{file.relpath}'
buildcommands
{
'$(VULKAN_SDK)/Bin/glslangValidator.exe -V -o "'..shaderOutPath ..'" %{file.relpath}'
}
buildoutputs { shaderOutPath }
filter {}
--]]
end
function coSetProjectDependencies(_deps)
if not co_dependencies then
co_dependencies = {}
end
for _,v in pairs(_deps) do table.insert(co_dependencies, v) end
links(_deps)
end
function coGenerateProjectWorkspace(_params)
print("Generating workspace ".._params.name.."...")
workspace(_params.name)
coSetWorkspaceDefaults()
startproject(_params.projects[0])
for _, p in pairs(_params.projects) do
include("src/"..p)
end
if co_dependencies then
for _, d in pairs(co_dependencies) do
include("src/"..d)
end
end
end
|
Fixed prebuild errors.
|
Fixed prebuild errors.
|
Lua
|
mit
|
smogpill/core,smogpill/core
|
6a4a785e68f9d8318e3f0eb0203c8c5853a345b6
|
SpatialReSamplingEx.lua
|
SpatialReSamplingEx.lua
|
local SpatialReSamplingEx, parent = torch.class('nn.SpatialReSamplingEx', 'nn.Module')
local help_desc = [[
Extended spatial resampling.
]]
function SpatialReSamplingEx:__init(...)
parent.__init(self)
-- get args
xlua.unpack_class(
self, {...}, 'nn.SpatialReSampling', help_desc,
{arg='rwidth', type='number', help='ratio: owidth/iwidth'},
{arg='rheight', type='number', help='ratio: oheight/iheight'},
{arg='owidth', type='number', help='output width'},
{arg='oheight', type='number', help='output height'},
{arg='mode', type='string', help='Mode : simple | average (only for downsampling) | bilinear', default = 'simple'},
{arg='yDim', type='number', help='image y dimension', default=2},
{arg='xDim', type='number', help='image x dimension', default=3}
)
if self.yDim+1 ~= self.xDim then
error('nn.SpatialReSamplingEx: yDim must be equals to xDim-1')
end
self.outputSize = torch.LongStorage(4)
self.inputSize = torch.LongStorage(4)
if self.mode == 'simple' then self.mode_c = 0 end
if self.mode == 'average' then self.mode_c = 1 end
if self.mode == 'bilinear' then self.mode_c = 2 end
if not self.mode_c then
error('SpatialReSampling: mode must be simple | average | bilinear')
end
end
local function round(a)
return math.floor(a+0.5)
end
function SpatialReSamplingEx:updateOutput(input)
-- compute iheight, iwidth, oheight and owidth
self.iheight = input:size(self.yDim)
self.iwidth = input:size(self.xDim)
self.oheight = self.oheight or round(self.rheight*self.iheight)
self.owidth = self.owidth or round(self.rwidth*self.iwidth)
if not ((self.oheight>=self.iheight) == (self.owidth>=self.iwidth)) then
error('SpatialReSamplingEx: Cannot upsample one dimension while downsampling the other')
end
-- resize input into K1 x iheight x iwidth x K2 tensor
self.inputSize:fill(1)
for i = 1,self.yDim-1 do
self.inputSize[1] = self.inputSize[1] * input:size(i)
end
self.inputSize[2] = self.iheight
self.inputSize[3] = self.iwidth
for i = self.xDim+1,input:nDimension() do
self.inputSize[4] = self.inputSize[4] * input:size(i)
end
local reshapedInput = input:reshape(self.inputSize)
-- prepare output of size K1 x oheight x owidth x K2
self.outputSize[1] = self.inputSize[1]
self.outputSize[2] = self.oheight
self.outputSize[3] = self.owidth
self.outputSize[4] = self.inputSize[4]
self.output:resize(self.outputSize)
-- resample over dims 2 and 3
input.nn.SpatialReSamplingEx_updateOutput(self, input:reshape(self.inputSize))
--resize output into the same shape as input
local outputSize2 = input:size()
outputSize2[self.yDim] = self.oheight
outputSize2[self.xDim] = self.owidth
self.output = self.output:reshape(outputSize2)
return self.output
end
function SpatialReSamplingEx:updateGradInput(input, gradOutput)
self.gradInput:resize(self.inputSize)
input.nn.SpatialReSamplingEx_updateGradInput(self, gradOutput:reshape(self.outputSize))
self.gradInput = self.gradInput:reshape(input:size())
return self.gradInput
end
|
local SpatialReSamplingEx, parent = torch.class('nn.SpatialReSamplingEx', 'nn.Module')
local help_desc = [[
Extended spatial resampling.
]]
function SpatialReSamplingEx:__init(...)
parent.__init(self)
-- get args
xlua.unpack_class(
self, {...}, 'nn.SpatialReSampling', help_desc,
{arg='rwidth', type='number', help='ratio: owidth/iwidth'},
{arg='rheight', type='number', help='ratio: oheight/iheight'},
{arg='owidth', type='number', help='output width'},
{arg='oheight', type='number', help='output height'},
{arg='mode', type='string', help='Mode : simple | average (only for downsampling) | bilinear', default = 'simple'},
{arg='yDim', type='number', help='image y dimension', default=2},
{arg='xDim', type='number', help='image x dimension', default=3}
)
if self.yDim+1 ~= self.xDim then
error('nn.SpatialReSamplingEx: yDim must be equals to xDim-1')
end
self.outputSize = torch.LongStorage(4)
self.inputSize = torch.LongStorage(4)
if self.mode == 'simple' then self.mode_c = 0 end
if self.mode == 'average' then self.mode_c = 1 end
if self.mode == 'bilinear' then self.mode_c = 2 end
if not self.mode_c then
error('SpatialReSampling: mode must be simple | average | bilinear')
end
end
local function round(a)
return math.floor(a+0.5)
end
function SpatialReSamplingEx:updateOutput(input)
-- compute iheight, iwidth, oheight and owidth
self.iheight = input:size(self.yDim)
self.iwidth = input:size(self.xDim)
self.oheightCurrent = self.oheight or round(self.rheight*self.iheight)
self.owidthCurrent = self.owidth or round(self.rwidth*self.iwidth)
if not ((self.oheightCurrent>=self.iheight) == (self.owidthCurrent>=self.iwidth)) then
error('SpatialReSamplingEx: Cannot upsample one dimension while downsampling the other')
end
-- resize input into K1 x iheight x iwidth x K2 tensor
self.inputSize:fill(1)
for i = 1,self.yDim-1 do
self.inputSize[1] = self.inputSize[1] * input:size(i)
end
self.inputSize[2] = self.iheight
self.inputSize[3] = self.iwidth
for i = self.xDim+1,input:nDimension() do
self.inputSize[4] = self.inputSize[4] * input:size(i)
end
local reshapedInput = input:reshape(self.inputSize)
-- prepare output of size K1 x oheight x owidth x K2
self.outputSize[1] = self.inputSize[1]
self.outputSize[2] = self.oheightCurrent
self.outputSize[3] = self.owidthCurrent
self.outputSize[4] = self.inputSize[4]
self.output:resize(self.outputSize)
-- resample over dims 2 and 3
input.nn.SpatialReSamplingEx_updateOutput(self, input:reshape(self.inputSize))
--resize output into the same shape as input
local outputSize2 = input:size()
outputSize2[self.yDim] = self.oheightCurrent
outputSize2[self.xDim] = self.owidthCurrent
self.output = self.output:reshape(outputSize2)
return self.output
end
function SpatialReSamplingEx:updateGradInput(input, gradOutput)
self.gradInput:resize(self.inputSize)
input.nn.SpatialReSamplingEx_updateGradInput(self, gradOutput:reshape(self.outputSize))
self.gradInput = self.gradInput:reshape(input:size())
return self.gradInput
end
|
fix a bug where the module is locked in to a particular oheight/width
|
fix a bug where the module is locked in to a particular oheight/width
|
Lua
|
mit
|
clementfarabet/lua---nnx
|
7449fde35f1d4e5aef2d2f4d2556a201d2ed1099
|
xmake/tools/ml.lua
|
xmake/tools/ml.lua
|
--!The Make-like Build Utility based on Lua
--
-- XMake 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.1 of the License, or
-- (at your option) any later version.
--
-- XMake 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 XMake;
-- If not, see <a href="http://www.gnu.org/licenses/"> http://www.gnu.org/licenses/</a>
--
-- Copyright (C) 2015 - 2016, ruki All rights reserved.
--
-- @author ruki
-- @file ml.lua
--
-- init it
function init(shellname)
-- save name
_g.shellname = shellname or "ml.exe"
-- init asflags
_g.asflags = { "-nologo", "-Gd", "-MP4", "-D_MBCS", "-D_CRT_SECURE_NO_WARNINGS"}
-- init flags map
_g.mapflags =
{
-- optimize
["-O0"] = "-Od"
, ["-O3"] = "-Ot"
, ["-Ofast"] = "-Ox"
, ["-fomit-frame-pointer"] = "-Oy"
-- symbols
, ["-g"] = "-Z7"
, ["-fvisibility=.*"] = ""
-- warnings
, ["-Wall"] = "-W3" -- = "-Wall" will enable too more warnings
, ["-W1"] = "-W1"
, ["-W2"] = "-W2"
, ["-W3"] = "-W3"
, ["-Werror"] = "-WX"
, ["%-Wno%-error=.*"] = ""
-- vectorexts
, ["-mmmx"] = "-arch:MMX"
, ["-msse"] = "-arch:SSE"
, ["-msse2"] = "-arch:SSE2"
, ["-msse3"] = "-arch:SSE3"
, ["-mssse3"] = "-arch:SSSE3"
, ["-mavx"] = "-arch:AVX"
, ["-mavx2"] = "-arch:AVX2"
, ["-mfpu=.*"] = ""
-- others
, ["-ftrapv"] = ""
, ["-fsanitize=address"] = ""
}
end
-- get the property
function get(name)
-- get it
return _g[name]
end
-- make the symbol flag
function symbol(level, symbolfile)
-- check -FS flags
if _g._FS == nil then
local ok = try
{
function ()
check("-ZI -FS -Fd" .. os.tmpfile() .. ".pdb")
return true
end
}
if ok then
_g._FS = true
end
end
-- debug? generate *.pdb file
local flags = ""
if level == "debug" then
if symbolfile then
flags = "-ZI -Fd" .. symbolfile
if _g._FS then
flags = "-FS " .. flags
end
else
flags = "-ZI"
end
end
-- none
return flags
end
-- make the warning flag
function warning(level)
-- the maps
local maps =
{
none = "-w"
, less = "-W1"
, more = "-W3"
, all = "-W3"
, error = "-WX"
}
-- make it
return maps[level] or ""
end
-- make the optimize flag
function optimize(level)
-- the maps
local maps =
{
none = "-Od"
, fast = "-O1"
, faster = "-O2"
, fastest = "-Ot"
, smallest = "-Os"
, aggressive = "-Ox"
}
-- make it
return maps[level] or ""
end
-- make the vector extension flag
function vectorext(extension)
-- the maps
local maps =
{
sse = "-arch:SSE"
, sse2 = "-arch:SSE2"
, avx = "-arch:AVX"
, avx2 = "-arch:AVX2"
}
-- make it
return maps[extension] or ""
end
-- make the language flag
function language(stdname)
return ""
end
-- make the define flag
function define(macro)
-- make it
return "-D" .. macro:gsub("\"", "\\\"")
end
-- make the undefine flag
function undefine(macro)
-- make it
return "-U" .. macro
end
-- make the includedir flag
function includedir(dir)
-- make it
return "-I" .. dir
end
-- make the complie command
function compcmd(sourcefile, objectfile, flags)
-- make it
return format("%s -c %s -Fo%s %s", _g.shellname, flags, objectfile, sourcefile)
end
-- complie the source file
function compile(sourcefile, objectfile, incdepfile, flags)
-- ensure the object directory
os.mkdir(path.directory(objectfile))
-- compile it
os.run(compcmd(sourcefile, objectfile, flags))
end
-- check the given flags
function check(flags)
-- make an stub source file
local objectfile = os.tmpfile() .. ".obj"
local sourcefile = os.tmpfile() .. ".asm"
io.write(sourcefile, "end")
-- check it
os.run("%s -c %s -Fo%s %s", _g.shellname, ifelse(flags, flags, ""), objectfile, sourcefile)
-- remove files
os.rm(objectfile)
os.rm(sourcefile)
end
|
--!The Make-like Build Utility based on Lua
--
-- XMake 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.1 of the License, or
-- (at your option) any later version.
--
-- XMake 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 XMake;
-- If not, see <a href="http://www.gnu.org/licenses/"> http://www.gnu.org/licenses/</a>
--
-- Copyright (C) 2015 - 2016, ruki All rights reserved.
--
-- @author ruki
-- @file ml.lua
--
-- init it
function init(shellname)
-- save name
_g.shellname = shellname or "ml.exe"
-- init asflags
_g.asflags = { "-nologo", "-Gd"}
-- init flags map
_g.mapflags =
{
-- optimize
["-O0"] = "-Od"
, ["-O3"] = "-Ot"
, ["-Ofast"] = "-Ox"
, ["-fomit-frame-pointer"] = "-Oy"
-- symbols
, ["-g"] = "-Z7"
, ["-fvisibility=.*"] = ""
-- warnings
, ["-Wall"] = "-W3" -- = "-Wall" will enable too more warnings
, ["-W1"] = "-W1"
, ["-W2"] = "-W2"
, ["-W3"] = "-W3"
, ["-Werror"] = "-WX"
, ["%-Wno%-error=.*"] = ""
-- vectorexts
, ["-mmmx"] = "-arch:MMX"
, ["-msse"] = "-arch:SSE"
, ["-msse2"] = "-arch:SSE2"
, ["-msse3"] = "-arch:SSE3"
, ["-mssse3"] = "-arch:SSSE3"
, ["-mavx"] = "-arch:AVX"
, ["-mavx2"] = "-arch:AVX2"
, ["-mfpu=.*"] = ""
-- others
, ["-ftrapv"] = ""
, ["-fsanitize=address"] = ""
}
end
-- get the property
function get(name)
-- get it
return _g[name]
end
-- make the symbol flag
function symbol(level, symbolfile)
-- check -FS flags
if _g._FS == nil then
local ok = try
{
function ()
check("-ZI -FS -Fd" .. os.tmpfile() .. ".pdb")
return true
end
}
if ok then
_g._FS = true
end
end
-- debug? generate *.pdb file
local flags = ""
if level == "debug" then
if symbolfile then
flags = "-ZI -Fd" .. symbolfile
if _g._FS then
flags = "-FS " .. flags
end
else
flags = "-ZI"
end
end
-- none
return flags
end
-- make the warning flag
function warning(level)
-- the maps
local maps =
{
none = "-w"
, less = "-W1"
, more = "-W3"
, all = "-W3"
, error = "-WX"
}
-- make it
return maps[level] or ""
end
-- make the optimize flag
function optimize(level)
return ""
end
-- make the vector extension flag
function vectorext(extension)
return ""
end
-- make the language flag
function language(stdname)
return ""
end
-- make the define flag
function define(macro)
-- make it
return "-D" .. macro:gsub("\"", "\\\"")
end
-- make the undefine flag
function undefine(macro)
-- make it
return "-U" .. macro
end
-- make the includedir flag
function includedir(dir)
-- make it
return "-I" .. dir
end
-- make the complie command
function compcmd(sourcefile, objectfile, flags)
-- make it
return format("%s -c %s -Fo%s %s", _g.shellname, flags, objectfile, sourcefile)
end
-- complie the source file
function compile(sourcefile, objectfile, incdepfile, flags)
-- ensure the object directory
os.mkdir(path.directory(objectfile))
-- compile it
os.run(compcmd(sourcefile, objectfile, flags))
end
-- check the given flags
function check(flags)
-- make an stub source file
local objectfile = os.tmpfile() .. ".obj"
local sourcefile = os.tmpfile() .. ".asm"
io.write(sourcefile, "end")
-- check it
os.run("%s -c %s -Fo%s %s", _g.shellname, ifelse(flags, flags, ""), objectfile, sourcefile)
-- remove files
os.rm(objectfile)
os.rm(sourcefile)
end
|
fix ml compile error
|
fix ml compile error
|
Lua
|
apache-2.0
|
waruqi/xmake,tboox/xmake,tboox/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,tboox/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,tboox/xmake,tboox/xmake,tboox/xmake,tboox/xmake
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.