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
|
---|---|---|---|---|---|---|---|---|---|
b570e0f3142cb9ba4e1612d6ab7782347bcfb377
|
main.lua
|
main.lua
|
emufun = {
config = {};
}
package.cpath = package.cpath..";/usr/lib64/lua/5.1/?.so"
require "lfs"
require "util"
require "logging"
require "input"
require "settings"
require "window"
flags.register("library-paths", "L") {
help = "Comma-separated paths to the media library or libraries";
type = flags.list;
default = {};
}
local init = {}
function state(name)
return function(...)
return love.filesystem.load("state/" .. name .. ".lua")(...)
end
end
function love.load()
init.init()
end
function init.init()
flags.register("help", "h", "?") { help = "This text." }
-- Then we parse the command line the first time around.
flags.parse(unpack(arg))
init.argv()
-- If the user asked for help, we bail here.
if emufun.config.help then
flags.help()
os.exit(0)
end
-- Then we initialize the settings library (which writes default configuration
-- files, if they don't already exist and this behaviour hasn't been suppressed
-- with command line options) and then load the user configuration.
emufun.initConfig()
emufun.loadConfig "emufun" (emufun.config)
-- Loading the user configuration may have overwritten the command line flags,
-- so we parse the command line *again*, giving command line flags precedence
-- over the user configuration file.
init.argv()
-- At this point we finally know what the log file is named, if anything, so
-- we open it.
log.init()
window.init()
for k,v in pairs(flags.parsed) do
log.debug("FLAG\t%s\t%s", tostring(k), tostring(v))
end
-- Now we are done processing the main user config and the command line flags
-- and can continue with initialization.
for k,v in pairs(emufun.config) do
log.debug("CFG\t%s\t%s", tostring(k), tostring(v))
end
-- Load user control settings.
emufun.loadConfig "controls" (setmetatable({ emufun = emufun, love = love }, { __index = input }))
-- Load top-level library configuration (file types, etc).
emufun.config._library_config_fn = emufun.loadConfig "library"
return state "load-libraries" ()
end
function love.draw() end
function love.update(dt)
-- cap framerate at 30fps
love.timer.sleep(1/30 - dt)
end
local _errhand = love.errhand
function love.errhand(...)
log.error("Error: %s", debug.traceback((...)))
return _errhand(...)
end
function emufun.quit()
os.exit(0)
end
function init.argv()
-- Parse command line flags. Flags from argv overwrite anything already present.
table.merge(emufun.config, flags.parsed)
-- Flags from the default settings are only taken if nothing has overridden them.
table.merge(emufun.config, flags.defaults, "ignore")
end
|
emufun = {
config = {};
}
package.cpath = package.cpath..";/usr/lib64/lua/5.1/?.so"
function love.update(dt)
-- cap framerate at 30fps
love.timer.sleep(1/30 - dt)
end
require "lfs"
require "util"
require "logging"
require "input"
require "settings"
require "window"
flags.register("library-paths", "L") {
help = "Comma-separated paths to the media library or libraries";
type = flags.list;
default = {};
}
local init = {}
function state(name)
return function(...)
return love.filesystem.load("state/" .. name .. ".lua")(...)
end
end
function love.load()
init.init()
end
function init.init()
flags.register("help", "h", "?") { help = "This text." }
-- Then we parse the command line the first time around.
flags.parse(unpack(arg))
init.argv()
-- If the user asked for help, we bail here.
if emufun.config.help then
flags.help()
os.exit(0)
end
-- Then we initialize the settings library (which writes default configuration
-- files, if they don't already exist and this behaviour hasn't been suppressed
-- with command line options) and then load the user configuration.
emufun.initConfig()
emufun.loadConfig "emufun" (emufun.config)
-- Loading the user configuration may have overwritten the command line flags,
-- so we parse the command line *again*, giving command line flags precedence
-- over the user configuration file.
init.argv()
-- At this point we finally know what the log file is named, if anything, so
-- we open it.
log.init()
window.init()
for k,v in pairs(flags.parsed) do
log.debug("FLAG\t%s\t%s", tostring(k), tostring(v))
end
-- Now we are done processing the main user config and the command line flags
-- and can continue with initialization.
for k,v in pairs(emufun.config) do
log.debug("CFG\t%s\t%s", tostring(k), tostring(v))
end
-- Load user control settings.
emufun.loadConfig "controls" (setmetatable({ emufun = emufun, love = love }, { __index = input }))
-- Load top-level library configuration (file types, etc).
emufun.config._library_config_fn = emufun.loadConfig "library"
return state "load-libraries" ()
end
function love.draw() end
local _errhand = love.errhand
function love.errhand(...)
log.error("Error: %s", debug.traceback((...)))
return _errhand(...)
end
function emufun.quit()
os.exit(0)
end
function init.argv()
-- Parse command line flags. Flags from argv overwrite anything already present.
table.merge(emufun.config, flags.parsed)
-- Flags from the default settings are only taken if nothing has overridden them.
table.merge(emufun.config, flags.defaults, "ignore")
end
|
Fix breakage of love.update function.
|
Fix breakage of love.update function.
|
Lua
|
mit
|
ToxicFrog/EmuFun
|
dfda26bb05bdb3a55c2dec00f6e7509c181d5b53
|
feedback/confusion.lua
|
feedback/confusion.lua
|
------------------------------------------------------------------------
--[[ Confusion ]]--
-- Feedback
-- Adapter for optim.ConfusionMatrix
-- requires 'optim' package
------------------------------------------------------------------------
local Confusion, parent = torch.class("dp.Confusion", "dp.Feedback")
Confusion.isConfusion = true
function Confusion:__init(config)
config = config or {}
assert(torch.type(config) == 'table' and not config[1],
"Constructor requires key-value arguments")
local args, name = xlua.unpack(
{config},
'Confusion',
'Adapter for optim.ConfusionMatrix',
{arg='name', type='string', default='confusion',
help='name identifying Feedback in reports'}
)
config.name = name
parent.__init(self, config)
end
function Confusion:setup(config)
parent.setup(self, config)
self._mediator:subscribe("doneEpoch", self, "doneEpoch")
end
function Confusion:doneEpoch(report)
if self._cm then
print(self._id:toString().." accuracy = "..self._cm.totalValid)
end
end
function Confusion:_add(batch, output, carry, report)
if not self._cm then
require 'optim'
self._cm = optim.ConfusionMatrix(batch:targets():classes())
end
local act = output:forward('bf')
if act ~= 'torch.DoubleTensor' and act ~= 'torch.FloatTensor' then
act = output:forward('bf', 'torch.FloatTensor')
end
self._cm:batchAdd(act, batch:targets():forward('b'))
end
function Confusion:_reset()
if self._cm then
self._cm:zero()
end
end
function Confusion:report()
local cm = self._cm or {}
if self._cm then
cm:updateValids()
end
--valid means accuracy
--union means divide valid classification by sum of rows and cols
-- (as opposed to just cols.) minus valid classificaiton
-- (which is included in each sum)
return {
[self:name()] = {
matrix = cm.mat,
per_class = {
accuracy = cm.valids,
union_accuracy = cm.unionvalids,
avg = {
accuracy = cm.averageValid,
union_accuracy = cm.averageUnionValid
}
},
accuracy = cm.totalValid,
avg_per_class_accuracy = cm.averageValid,
classes = cm.classes
},
n_sample = self._n_sample
}
end
|
------------------------------------------------------------------------
--[[ Confusion ]]--
-- Feedback
-- Adapter for optim.ConfusionMatrix
-- requires 'optim' package
------------------------------------------------------------------------
local Confusion, parent = torch.class("dp.Confusion", "dp.Feedback")
Confusion.isConfusion = true
function Confusion:__init(config)
config = config or {}
assert(torch.type(config) == 'table' and not config[1],
"Constructor requires key-value arguments")
local args, name = xlua.unpack(
{config},
'Confusion',
'Adapter for optim.ConfusionMatrix',
{arg='name', type='string', default='confusion',
help='name identifying Feedback in reports'}
)
config.name = name
parent.__init(self, config)
end
function Confusion:setup(config)
parent.setup(self, config)
self._mediator:subscribe("doneEpoch", self, "doneEpoch")
end
function Confusion:doneEpoch(report)
if self._cm then
print(self._id:toString().." accuracy = "..self._cm.totalValid)
end
end
function Confusion:_add(batch, output, carry, report)
if not self._cm then
require 'optim'
self._cm = optim.ConfusionMatrix(batch:targets():classes())
end
local act = output:forward('bf')
local act_type = torch.type(act)
if act_type ~= 'torch.DoubleTensor' and act_type ~= 'torch.FloatTensor' then
act = output:forward('bf', 'torch.FloatTensor')
end
self._cm:batchAdd(act, batch:targets():forward('b'))
end
function Confusion:_reset()
if self._cm then
self._cm:zero()
end
end
function Confusion:report()
local cm = self._cm or {}
if self._cm then
cm:updateValids()
end
--valid means accuracy
--union means divide valid classification by sum of rows and cols
-- (as opposed to just cols.) minus valid classificaiton
-- (which is included in each sum)
return {
[self:name()] = {
matrix = cm.mat,
per_class = {
accuracy = cm.valids,
union_accuracy = cm.unionvalids,
avg = {
accuracy = cm.averageValid,
union_accuracy = cm.averageUnionValid
}
},
accuracy = cm.totalValid,
avg_per_class_accuracy = cm.averageValid,
classes = cm.classes
},
n_sample = self._n_sample
}
end
|
fixed small bug in Confusion
|
fixed small bug in Confusion
|
Lua
|
bsd-3-clause
|
eulerreich/dp,sagarwaghmare69/dp,kracwarlock/dp,fiskio/dp,rickyHong/dptorchLib,nicholas-leonard/dp,jnhwkim/dp
|
037662a3f9dd0468bd1af6a1c9a67c8dc5579327
|
nyagos.d/suffix.lua
|
nyagos.d/suffix.lua
|
if not nyagos then
print("This is a script for nyagos not lua.exe")
os.exit()
end
share._suffixes={}
share._setsuffix = function(suffix,cmdline)
suffix=string.gsub(string.lower(suffix),"^%.","")
if not share._suffixes[suffix] then
local newext="."..suffix
local orgpathext = nyagos.env.PATHEXT
if orgpathext then
if not string.find(";"..orgpathext..";",";"..newext..";",1,true) then
nyagos.env.PATHEXT = orgpathext..";"..newext
end
else
nyagos.env.PATHEXT = newext
end
end
share._suffixes[suffix]=cmdline
end
suffix = setmetatable({},{
__call = function(t,k,v) share._setsuffix(k,v) return end,
__newindex = function(t,k,v) share._setsuffix(k,v) return end,
__index = function(t,k) return share._suffixes[k] end
})
share._org_suffix_argsfilter=nyagos.argsfilter
nyagos.argsfilter = function(args)
if share._org_suffix_argsfilter then
local args_ = share._org_suffix_argsfilter(args)
if args_ then
args = args_
end
end
local m = string.match(args[0],"%.(%w+)$")
if not m then
return
end
local cmdline = share._suffixes[ string.lower(m) ]
if not cmdline then
return
end
local path=nyagos.which(args[0])
if not path then
return
end
local newargs={}
if type(cmdline) == 'table' then
for i=1,#cmdline do
newargs[i-1]=cmdline[i]
end
elseif type(cmdline) == 'string' then
newargs[0] = cmdline
end
newargs[#newargs+1] = path
for i=1,#args do
newargs[#newargs+1] = args[i]
end
return newargs
end
nyagos.alias.suffix = function(args)
if #args < 1 then
for key,val in pairs(share._suffixes) do
local right=val
if type(val) == "table" then
right = table.concat(val," ")
end
print(key .. "=" .. right)
end
return
end
for i=1,#args do
local left,right=string.match(args[i],"^%.?([^=]+)%=(.+)$")
if right then
local args={}
for m in string.gmatch(right,"%S+") do
args[#args+1] = m
end
share._setsuffix(left,args)
else
local val = share._suffixes[args[i]]
if not val then
val = ""
elseif type(val) == "table" then
val = table.concat(val," ")
end
print(args[i].."="..val)
end
end
end
for key,val in pairs{
awk={"gawk","-f"},
js={"cscript","//nologo"},
lua={"nyagos.exe","--norc","--lua-file"},
pl={"perl"},
ps1={"powershell","-ExecutionPolicy","RemoteSigned","-file"},
rb={"ruby"},
vbs={"cscript","//nologo"},
wsf={"cscript","//nologo"},
py={"python"},
} do
share._setsuffix( key , val )
end
|
if not nyagos then
print("This is a script for nyagos not lua.exe")
os.exit()
end
share._suffixes={}
share._setsuffix = function(suffix,cmdline)
suffix=string.gsub(string.lower(suffix),"^%.","")
share._suffixes[suffix]=cmdline
end
suffix = setmetatable({},{
__call = function(t,k,v) share._setsuffix(k,v) return end,
__newindex = function(t,k,v) share._setsuffix(k,v) return end,
__index = function(t,k) return share._suffixes[k] end
})
share._org_suffix_argsfilter=nyagos.argsfilter
nyagos.argsfilter = function(args)
if share._org_suffix_argsfilter then
local args_ = share._org_suffix_argsfilter(args)
if args_ then
args = args_
end
end
local m = string.match(args[0],"%.(%w+)$")
if not m then
return
end
local cmdline = share._suffixes[ string.lower(m) ]
if not cmdline then
return
end
local path=nyagos.which(args[0])
if not path then
return
end
local newargs={}
if type(cmdline) == 'table' then
for i=1,#cmdline do
newargs[i-1]=cmdline[i]
end
elseif type(cmdline) == 'string' then
newargs[0] = cmdline
end
newargs[#newargs+1] = path
for i=1,#args do
newargs[#newargs+1] = args[i]
end
return newargs
end
nyagos.alias.suffix = function(args)
if #args < 1 then
for key,val in pairs(share._suffixes) do
local right=val
if type(val) == "table" then
right = table.concat(val," ")
end
print(key .. "=" .. right)
end
return
end
for i=1,#args do
local left,right=string.match(args[i],"^%.?([^=]+)%=(.+)$")
if right then
local args={}
for m in string.gmatch(right,"%S+") do
args[#args+1] = m
end
share._setsuffix(left,args)
else
local val = share._suffixes[args[i]]
if not val then
val = ""
elseif type(val) == "table" then
val = table.concat(val," ")
end
print(args[i].."="..val)
end
end
end
for key,val in pairs{
awk={"gawk","-f"},
js={"cscript","//nologo"},
lua={"nyagos.exe","--norc","--lua-file"},
pl={"perl"},
ps1={"powershell","-ExecutionPolicy","RemoteSigned","-file"},
rb={"ruby"},
vbs={"cscript","//nologo"},
wsf={"cscript","//nologo"},
py={"python"},
} do
share._setsuffix( key , val )
end
|
(#425) Do not append extensions defined suffix function to %PATHEXT%
|
(#425) Do not append extensions defined suffix function to %PATHEXT%
|
Lua
|
bsd-3-clause
|
tsuyoshicho/nyagos
|
808494bf724c30d50cc90034c6b976687824a7c6
|
share/media/clipfish.lua
|
share/media/clipfish.lua
|
-- libquvi-scripts
-- Copyright (C) 2010-2013 Toni Gundogdu <[email protected]>
--
-- 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/>.
--
local ClipFish = {} -- Utility functions unique to this script.
-- Identify the media script.
function ident(qargs)
return {
can_parse_url = ClipFish.can_parse_url(qargs),
domains = table.concat({'clipfish.de'}, ',')
}
end
-- Parse the media properties.
function parse(qargs)
-- Make mandatory: the ID is required to fetch the media info
qargs.id = qargs.input_url:match('/video/(%d+)/.-/$')
or error("no match: media ID")
local t = {'http://www.clipfish.de/devxml/videoinfo/', qargs.id}
local c = quvi.http.fetch(table.concat(t,'')).data
local L = require 'quvi/lxph'
local P = require 'lxp.lom'
x = P.parse(c)
qargs.thumb_url = L.find_first_tag(x, 'imageurl')[1]
qargs.title = L.find_first_tag(x, 'title')[1]
local d = L.find_first_tag(x, 'duration')[1]
local T = require 'quvi/time'
qargs.duration_ms = T.timecode_str_to_s(d)*1000
qargs.streams = ClipFish.iter_streams(L, x)
return qargs
end
--
-- Utility functions
--
function ClipFish.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('clipfish%.de$')
and t.path and t.path:lower():match('/video/%d+/.-/$')
then
return true
else
return false
end
end
function ClipFish.iter_streams(L, x)
local u = L.find_first_tag(x, 'filename')[1]
local S = require 'quvi/stream'
return {S.stream_new(u)}
end
-- vim: set ts=2 sw=2 tw=72 expandtab:
|
-- libquvi-scripts
-- Copyright (C) 2010-2013 Toni Gundogdu <[email protected]>
--
-- 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/>.
--
local ClipFish = {} -- Utility functions unique to this script.
-- Identify the media script.
function ident(qargs)
return {
can_parse_url = ClipFish.can_parse_url(qargs),
domains = table.concat({'clipfish.de'}, ',')
}
end
-- Parse the media properties.
function parse(qargs)
-- Make mandatory: the ID is required to fetch the media info
qargs.id = qargs.input_url:match('/video/(%d+)/.-/$')
or error("no match: media ID")
local t = {'http://www.clipfish.de/devxml/videoinfo/', qargs.id}
local c = quvi.http.fetch(table.concat(t,'')).data
local L = require 'quvi/lxph'
local P = require 'lxp.lom'
x = P.parse(c)
qargs.thumb_url = L.find_first_tag(x, 'imageurl')[1]
qargs.title = L.find_first_tag(x, 'title')[1]
local d = L.find_first_tag(x, 'duration')[1]
local T = require 'quvi/time'
qargs.duration_ms = T.timecode_str_to_s(d)*1000
qargs.streams = ClipFish.iter_streams(L, x)
return qargs
end
--
-- Utility functions
--
function ClipFish.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('clipfish%.de$')
and t.path and t.path:lower():match('/video/%d+/.-/$')
then
return true
else
return false
end
end
function ClipFish.iter_streams(L, x)
local u = L.find_first_tag(x, 'filename')[1]
or error('no match: media stream URL')
local S = require 'quvi/stream'
return {S.stream_new(u)}
end
-- vim: set ts=2 sw=2 tw=72 expandtab:
|
FIX: media/clipfish.lua: Raise "no match: media stream URL"
|
FIX: media/clipfish.lua: Raise "no match: media stream URL"
Signed-off-by: Toni Gundogdu <[email protected]>
|
Lua
|
agpl-3.0
|
legatvs/libquvi-scripts,legatvs/libquvi-scripts,alech/libquvi-scripts,alech/libquvi-scripts
|
6a132e6f804764a53cc71f9a58e62bf67422a3ef
|
misc.lua
|
misc.lua
|
-- new global functions, either replacing existing ones or providing new
-- ones for convenience
-- replacements: pairs, ipairs, type
-- new: printf, fprintf, eprintf, sprintf, srequire, L
-- new version of type() that supports the __type metamethod
local _type = type
function type(obj)
local mt = getmetatable(obj)
if mt and rawget(mt, "__type") then
return rawget(mt, "__type")(obj)
end
return _type(obj)
end
-- update file metatable
getmetatable(io.stdout).__type = function() return "file" end
-- printf(format, ...)
function printf(...)
return fprintf(io.stdout,...)
end
-- printf to standard error
function eprintf(...)
return fprintf(io.stderr, ...)
end
-- fprintf(file, format, ...)
function fprintf(fout, ...)
return fout:write(string.format(...))
end
-- string sprintf(format, ...)
function sprintf(...)
return string.format(...)
end
-- bind to io tables, so that file:printf(...) becomes legal
getmetatable(io.stdout).__index.printf = fprintf
-- "safe require", returns nil,error if require fails rather than
-- throwing an error
function srequire(...)
local s,r = pcall(require, ...)
if s then
return r
end
return nil,r
end
-- fast one-liner lambda creation
function f(src)
return assert(loadstring(
"return function(" .. src:gsub(" => ", ") return ") .. " end"
))()
end
-- bind args into function
function partial(f, arg1, ...)
if arg1 == nil then
return f
end
return curry(function(...) return f(arg1, ...) end, ...)
end
|
-- new global functions, either replacing existing ones or providing new
-- ones for convenience
-- replacements: pairs, ipairs, type
-- new: printf, fprintf, eprintf, sprintf, srequire, L
-- new version of type() that supports the __type metamethod
rawtype = type
function type(obj)
local mt = getmetatable(obj)
if mt and rawget(mt, "__type") then
return rawget(mt, "__type")(obj)
end
return rawtype(obj)
end
-- update file metatable
getmetatable(io.stdout).__type = function() return "file" end
-- printf(format, ...)
function printf(...)
return fprintf(io.stdout,...)
end
-- printf to standard error
function eprintf(...)
return fprintf(io.stderr, ...)
end
-- fprintf(file, format, ...)
function fprintf(fout, ...)
return fout:write(string.format(...))
end
-- string sprintf(format, ...)
function sprintf(...)
return string.format(...)
end
-- bind to io tables, so that file:printf(...) becomes legal
getmetatable(io.stdout).__index.printf = fprintf
-- "safe require", returns nil,error if require fails rather than
-- throwing an error
function srequire(...)
local s,r = pcall(require, ...)
if s then
return r
end
return nil,r
end
-- fast one-liner lambda creation
function f(src)
return assert(loadstring(
"return function(" .. src:gsub(" => ", ") return ") .. " end"
))()
end
-- bind args into function
function partial(f, ...)
if select('#', ...) == 0 then
return f
end
local arg = (...)
return partial(function(...) return f(arg, ...) end, select(2, ...))
end
|
Fix partial, and make original type available as rawtype
|
Fix partial, and make original type available as rawtype
|
Lua
|
mit
|
ToxicFrog/luautil
|
226bd84da0df884d23c5e98f82ce1842629f86f2
|
module/admin-core/src/controller/admin/index.lua
|
module/admin-core/src/controller/admin/index.lua
|
module("ffluci.controller.admin.index", package.seeall)
function action_wizard()
if ffluci.http.formvalue("ip") then
return configure_freifunk()
end
local ifaces = {}
local wldevs = ffluci.model.uci.show("wireless")
if wldevs then
for k, v in pairs(wldevs.wireless) do
if v[".type"] == "wifi-device" then
table.insert(ifaces, k)
end
end
end
ffluci.template.render("admin_index/wizard", {ifaces=ifaces})
end
function configure_freifunk()
local ip = ffluci.http.formvalue("ip")
local uci = ffluci.model.uci.Session()
-- Configure FF-Interface
uci:del("network", "ff")
uci:del("network", "ffdhcp")
uci:set("network", "ff", nil, "interface")
uci:set("network", "ff", "type", "bridge")
uci:set("network", "ff", "proto", "static")
uci:set("network", "ff", "ipaddr", ip)
uci:set("network", "ff", "netmask", uci:get("freifunk", "community", "mask"))
uci:set("network", "ff", "dns", uci:get("freifunk", "community", "dns"))
-- Enable internal routing
uci:set("freifunk", "routing", "internal", "1")
-- Enable internet routing
if ffluci.http.formvalue("shareinet") then
uci:set("freifunk", "routing", "internet", "1")
else
uci:set("freifunk", "routing", "internet", "0")
end
-- Configure DHCP
if ffluci.http.formvalue("dhcp") then
local dhcpnet = uci:get("freifunk", "community", "dhcp"):match("^([0-9]+)")
local dhcpip = ip:gsub("^[0-9]+", dhcpnet)
uci:set("network", "ffdhcp", nil, "interface")
uci:set("network", "ffdhcp", "proto", "static")
uci:set("network", "ffdhcp", "ifname", "br-ff:dhcp")
uci:set("network", "ffdhcp", "ipaddr", dhcpip)
uci:set("network", "ffdhcp", "netmask", uci:get("freifunk", "community", "dhcpmask"))
end
-- Configure OLSR
if ffluci.http.formvalue("olsr") and uci:show("olsr") then
for k, v in pairs(uci:show("olsr").olsr) do
if v[".type"] == "Interface" or v[".type"] == "LoadPlugin" then
uci:del("olsr", "k")
end
end
if ffluci.http.formvalue("shareinet") then
uci:set("olsr", "dyn_gw", nil, "LoadPlugin")
uci:set("olsr", "dyn_gw", "Library", "olsrd_dyn_gw.so.0.4")
end
uci:set("olsr", "nameservice", nil, "LoadPlugin")
uci:set("olsr", "nameservice", "Library", "olsrd_nameservice.so.0.3")
uci:set("olsr", "nameservice", "name", ip:gsub("%.", "-"))
uci:set("olsr", "nameservice", "hosts_file", "/var/etc/hosts")
uci:set("olsr", "nameservice", "suffix", ".olsr")
uci:set("olsr", "nameservice", "latlon_infile", "/tmp/latlon.txt")
uci:set("olsr", "txtinfo", nil, "LoadPlugin")
uci:set("olsr", "txtinfo", "Library", "olsrd_txtinfo.so.0.1")
uci:set("olsr", "txtinfo", "Accept", "127.0.0.1")
local oif = uci:add("olsr", "Interface")
uci:set("olsr", oif, "Interface", "ff")
uci:set("olsr", oif, "HelloInterval", "6.0")
uci:set("olsr", oif, "HelloValidityTime", "108.0")
uci:set("olsr", oif, "TcInterval", "4.0")
uci:set("olsr", oif, "TcValidityTime", "324.0")
uci:set("olsr", oif, "MidInterval", "18.0")
uci:set("olsr", oif, "MidValidityTime", "324.0")
uci:set("olsr", oif, "HnaInterval", "18.0")
uci:set("olsr", oif, "HnaValidityTime", "108.0")
end
-- Configure Wifi
local wifi = ffluci.http.formvalue("wifi")
local wcfg = uci:show("wireless")
if type(wifi) == "table" and wcfg then
for iface, v in pairs(wifi) do
if wcfg[iface] then
-- Cleanup
for k, v in pairs(wcfg.wireless) do
if v[".type"] == "wifi-iface" and v.device == iface then
uci:del("wireless", k)
end
end
uci:set("wireless", iface, "disabled", "0")
uci:set("wireless", iface, "mode", "11g")
uci:set("wireless", iface, "txantenna", 1)
uci:set("wireless", iface, "rxantenna", 1)
uci:set("wireless", iface, "channel", uci:get("freifunk", "community", "channel"))
local wif = uci:add("wireless", "wifi-iface")
uci:set("wireless", wif, "device", iface)
uci:set("wireless", wif, "network", "ff")
uci:set("wireless", wif, "mode", "adhoc")
uci:set("wireless", wif, "ssid", uci:get("freifunk", "community", "essid"))
uci:set("wireless", wif, "bssid", uci:get("freifunk", "community", "bssid"))
uci:set("wireless", wif, "txpower", 13)
end
end
end
ffluci.http.request_redirect("admin", "uci", "changes")
end
|
module("ffluci.controller.admin.index", package.seeall)
function action_wizard()
if ffluci.http.formvalue("ip") then
return configure_freifunk()
end
local ifaces = {}
local wldevs = ffluci.model.uci.show("wireless")
if wldevs then
for k, v in pairs(wldevs.wireless) do
if v[".type"] == "wifi-device" then
table.insert(ifaces, k)
end
end
end
ffluci.template.render("admin_index/wizard", {ifaces=ifaces})
end
function configure_freifunk()
local ip = ffluci.http.formvalue("ip")
local uci = ffluci.model.uci.Session()
-- Configure FF-Interface
uci:del("network", "ff")
uci:del("network", "ffdhcp")
uci:set("network", "ff", nil, "interface")
uci:set("network", "ff", "type", "bridge")
uci:set("network", "ff", "proto", "static")
uci:set("network", "ff", "ipaddr", ip)
uci:set("network", "ff", "netmask", uci:get("freifunk", "community", "mask"))
uci:set("network", "ff", "dns", uci:get("freifunk", "community", "dns"))
-- Enable internal routing
uci:set("freifunk", "routing", "internal", "1")
-- Enable internet routing
if ffluci.http.formvalue("shareinet") then
uci:set("freifunk", "routing", "internet", "1")
else
uci:set("freifunk", "routing", "internet", "0")
end
-- Configure DHCP
if ffluci.http.formvalue("dhcp") then
local dhcpnet = uci:get("freifunk", "community", "dhcp"):match("^([0-9]+)")
local dhcpip = ip:gsub("^[0-9]+", dhcpnet)
uci:set("network", "ffdhcp", nil, "interface")
uci:set("network", "ffdhcp", "proto", "static")
uci:set("network", "ffdhcp", "ifname", "br-ff:dhcp")
uci:set("network", "ffdhcp", "ipaddr", dhcpip)
uci:set("network", "ffdhcp", "netmask", uci:get("freifunk", "community", "dhcpmask"))
local splash = uci:show("luci_splash")
if splash then
for k, v in pairs(splash.luci_splash) do
if v[".type"] == "iface" then
uci:del("luci_splash", k)
end
end
local sk = uci:add("luci_splash", "iface")
uci:set("luci_splash", sk, "network", "ffdhcp")
end
end
-- Configure OLSR
if ffluci.http.formvalue("olsr") and uci:show("olsr") then
for k, v in pairs(uci:show("olsr").olsr) do
if v[".type"] == "Interface" or v[".type"] == "LoadPlugin" then
uci:del("olsr", k)
end
end
if ffluci.http.formvalue("shareinet") then
uci:set("olsr", "dyn_gw", nil, "LoadPlugin")
uci:set("olsr", "dyn_gw", "Library", "olsrd_dyn_gw.so.0.4")
end
uci:set("olsr", "nameservice", nil, "LoadPlugin")
uci:set("olsr", "nameservice", "Library", "olsrd_nameservice.so.0.3")
uci:set("olsr", "nameservice", "name", ip:gsub("%.", "-"))
uci:set("olsr", "nameservice", "hosts_file", "/var/etc/hosts")
uci:set("olsr", "nameservice", "suffix", ".olsr")
uci:set("olsr", "nameservice", "latlon_infile", "/tmp/latlon.txt")
uci:set("olsr", "txtinfo", nil, "LoadPlugin")
uci:set("olsr", "txtinfo", "Library", "olsrd_txtinfo.so.0.1")
uci:set("olsr", "txtinfo", "Accept", "127.0.0.1")
local oif = uci:add("olsr", "Interface")
uci:set("olsr", oif, "Interface", "ff")
uci:set("olsr", oif, "HelloInterval", "6.0")
uci:set("olsr", oif, "HelloValidityTime", "108.0")
uci:set("olsr", oif, "TcInterval", "4.0")
uci:set("olsr", oif, "TcValidityTime", "324.0")
uci:set("olsr", oif, "MidInterval", "18.0")
uci:set("olsr", oif, "MidValidityTime", "324.0")
uci:set("olsr", oif, "HnaInterval", "18.0")
uci:set("olsr", oif, "HnaValidityTime", "108.0")
end
-- Configure Wifi
local wifi = ffluci.http.formvalue("wifi")
local wcfg = uci:show("wireless")
if type(wifi) == "table" and wcfg then
for iface, v in pairs(wifi) do
if wcfg[iface] then
-- Cleanup
for k, v in pairs(wcfg.wireless) do
if v[".type"] == "wifi-iface" and v.device == iface then
uci:del("wireless", k)
end
end
uci:set("wireless", iface, "disabled", "0")
uci:set("wireless", iface, "mode", "11g")
uci:set("wireless", iface, "txantenna", 1)
uci:set("wireless", iface, "rxantenna", 1)
uci:set("wireless", iface, "channel", uci:get("freifunk", "community", "channel"))
local wif = uci:add("wireless", "wifi-iface")
uci:set("wireless", wif, "device", iface)
uci:set("wireless", wif, "network", "ff")
uci:set("wireless", wif, "mode", "adhoc")
uci:set("wireless", wif, "ssid", uci:get("freifunk", "community", "essid"))
uci:set("wireless", wif, "bssid", uci:get("freifunk", "community", "bssid"))
uci:set("wireless", wif, "txpower", 13)
end
end
end
ffluci.http.request_redirect("admin", "uci", "changes")
end
|
* Fixed Freifunk wizard
|
* Fixed Freifunk wizard
|
Lua
|
apache-2.0
|
deepak78/luci,deepak78/luci,8devices/luci,deepak78/luci,deepak78/luci,8devices/luci,8devices/luci,deepak78/luci,deepak78/luci,8devices/luci,deepak78/luci,8devices/luci,8devices/luci,deepak78/luci
|
4f70b29b82730640f67ec08f6871b0f0d2fe8c52
|
kong/vaults/env/init.lua
|
kong/vaults/env/init.lua
|
local type = type
local gsub = string.gsub
local upper = string.upper
local kong = kong
local ENV = {}
local function init()
local ffi = require "ffi"
ffi.cdef("extern char **environ;")
local e = ffi.C.environ
if not e then
kong.log.warn("could not access environment variables")
return
end
local find = string.find
local sub = string.sub
local str = ffi.string
local i = 0
while e[i] ~= nil do
local var = str(e[i])
local p = find(var, "=", nil, true)
if p then
ENV[sub(var, 1, p - 1)] = sub(var, p + 1)
end
i = i + 1
end
end
local function get(conf, resource, version)
local prefix = conf.prefix
if type(prefix) == "string" then
resource = prefix .. resource
end
resource = upper(gsub(resource, "-", "_"))
if version == 2 then
resource = resource .. "_PREVIOUS"
end
return ENV[resource]
end
return {
VERSION = "1.0.0",
init = init,
get = get,
}
|
local ffi = require "ffi"
local type = type
local gsub = string.gsub
local upper = string.upper
local find = string.find
local sub = string.sub
local str = ffi.string
local kong = kong
local ENV = {}
ffi.cdef [[
extern char **environ;
]]
local function init()
local e = ffi.C.environ
if not e then
kong.log.warn("could not access environment variables")
return
end
local i = 0
while e[i] ~= nil do
local var = str(e[i])
local p = find(var, "=", nil, true)
if p then
ENV[sub(var, 1, p - 1)] = sub(var, p + 1)
end
i = i + 1
end
end
local function get(conf, resource, version)
local prefix = conf.prefix
if type(prefix) == "string" then
resource = prefix .. resource
end
resource = upper(gsub(resource, "-", "_"))
if version == 2 then
resource = resource .. "_PREVIOUS"
end
return ENV[resource]
end
return {
VERSION = "1.0.0",
init = init,
get = get,
}
|
fix(env) luajit table overflow error when using ffi.cdef (#8945)
|
fix(env) luajit table overflow error when using ffi.cdef (#8945)
|
Lua
|
apache-2.0
|
Kong/kong,Kong/kong,Kong/kong
|
b23cc68d4459e96338c030e9aa812950bdf1e2c1
|
scripts/tundra/tools/gcc.lua
|
scripts/tundra/tools/gcc.lua
|
-- Copyright 2010 Andreas Fredriksson
--
-- This file is part of Tundra.
--
-- Tundra is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- Tundra 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 Tundra. If not, see <http://www.gnu.org/licenses/>.
module(..., package.seeall)
local native = require "tundra.native"
function apply(env, options)
-- load the generic C toolset first
tundra.boot.load_toolset("generic-cpp", env)
env:set_many {
["NATIVE_SUFFIXES"] = { ".c", ".cpp", ".cc", ".cxx", ".a", ".o" },
["OBJECTSUFFIX"] = ".o",
["LIBPREFIX"] = "lib",
["LIBSUFFIX"] = ".a",
["_GCC_BINPREFIX"] = "",
["CC"] = "$(_GCC_BINPREFIX)gcc",
["CXX"] = "$(_GCC_BINPREFIX)g++",
["LIB"] = "$(_GCC_BINPREFIX)ar",
["LD"] = "$(_GCC_BINPREFIX)gcc",
["_OS_CCOPTS"] = "",
["_OS_CXXOPTS"] = "",
["CCCOM"] = "$(CC) $(_OS_CCOPTS) -c $(CPPDEFS:p-D) $(CPPPATH:f:p-I) $(CCOPTS) $(CCOPTS_$(CURRENT_VARIANT:u)) -o $(@) $(<)",
["CXXCOM"] = "$(CXX) $(_OS_CXXOPTS) -c $(CPPDEFS:p-D) $(CPPPATH:f:p-I) $(CXXOPTS) $(CXXOPTS_$(CURRENT_VARIANT:u)) -o $(@) $(<)",
["PROGOPTS"] = "",
["PROGCOM"] = "$(LD) $(PROGOPTS) $(LIBPATH:p-L) $(LIBS:p-l) -o $(@) $(<)",
["PROGPREFIX"] = "",
["LIBOPTS"] = "",
["LIBCOM"] = "$(LIB) -rs $(LIBOPTS) $(@) $(<)",
["SHLIBPREFIX"] = "lib",
["SHLIBOPTS"] = "-shared",
["SHLIBCOM"] = "$(LD) $(SHLIBOPTS) $(LIBPATH:p-L) $(LIBS:p-l) -o $(@) $(<)",
}
end
|
-- Copyright 2010 Andreas Fredriksson
--
-- This file is part of Tundra.
--
-- Tundra is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- Tundra 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 Tundra. If not, see <http://www.gnu.org/licenses/>.
module(..., package.seeall)
local native = require "tundra.native"
function apply(env, options)
-- load the generic C toolset first
tundra.boot.load_toolset("generic-cpp", env)
env:set_many {
["NATIVE_SUFFIXES"] = { ".c", ".cpp", ".cc", ".cxx", ".a", ".o" },
["OBJECTSUFFIX"] = ".o",
["LIBPREFIX"] = "lib",
["LIBSUFFIX"] = ".a",
["_GCC_BINPREFIX"] = "",
["CC"] = "$(_GCC_BINPREFIX)gcc",
["CXX"] = "$(_GCC_BINPREFIX)g++",
["LIB"] = "$(_GCC_BINPREFIX)ar",
["LD"] = "$(_GCC_BINPREFIX)gcc",
["_OS_CCOPTS"] = "",
["_OS_CXXOPTS"] = "",
["CCCOM"] = "$(CC) $(_OS_CCOPTS) -c $(CPPDEFS:p-D) $(CPPPATH:f:p-I) $(CCOPTS) $(CCOPTS_$(CURRENT_VARIANT:u)) -o $(@) $(<)",
["CXXCOM"] = "$(CXX) $(_OS_CXXOPTS) -c $(CPPDEFS:p-D) $(CPPPATH:f:p-I) $(CXXOPTS) $(CXXOPTS_$(CURRENT_VARIANT:u)) -o $(@) $(<)",
["PROGOPTS"] = "",
["PROGCOM"] = "$(LD) $(PROGOPTS) $(LIBPATH:p-L) -o $(@) $(<) $(LIBS:p-l)",
["PROGPREFIX"] = "",
["LIBOPTS"] = "",
["LIBCOM"] = "$(LIB) -rs $(LIBOPTS) $(@) $(<)",
["SHLIBPREFIX"] = "lib",
["SHLIBOPTS"] = "-shared",
["SHLIBCOM"] = "$(LD) $(SHLIBOPTS) $(LIBPATH:p-L) -o $(@) $(<) $(LIBS:p-l)",
}
end
|
Put libraries after objects on GCC link command line.
|
Put libraries after objects on GCC link command line.
Fixes GH-86.
|
Lua
|
mit
|
deplinenoise/tundra,bmharper/tundra,bmharper/tundra,deplinenoise/tundra,bmharper/tundra,bmharper/tundra,deplinenoise/tundra
|
5762889ed90e82eefa16ce59f898d4005ece8066
|
inventory.lua
|
inventory.lua
|
local component = require("component")
local ic = component.inventory_controller
local robot = require("robot")
local sides = require("sides")
local util = require("util")
local inventory = {}
function inventory.isOneOf(item, checkList)
for _,chk in ipairs(checkList) do
if chk == "!tool" then
if item.maxDamage > 0 then
return true
end
elseif string.match(item.name, chk) then
return true
end
end
return false
end
function inventory.dropAll(side, fromSlotNumber, exceptFor)
-- tries to drop all the robot's inventory into the storage on the given side
-- returns true if all if it could be unloaded, false if none or only some could
--robot.drop([number]) -- Returns true if at least one item was dropped, false otherwise.
local couldDropAll = true
exceptFor = exceptFor or {}
fromSlotNumber = fromSlotNumber or 1
for i=fromSlotNumber,robot.inventorySize() do
local c = robot.count(i)
if c > 0 then
local stack = ic.getStackInInternalSlot(i)
if not inventory.isOneOf(stack, exceptFor) then
robot.select(i)
if side == nil or side == sides.front then
robot.drop()
elseif side == sides.bottom then
robot.dropDown()
elseif side == sides.top then
robot.dropUp()
end
-- see if all the items were successfully dropped
c = robot.count(i)
if c > 0 then
-- at least one item couldn't be dropped.
-- but we keep trying to drop all so we still drop as much as we can.
couldDropAll = false
end
end --isOneOf
end
end
return couldDropAll
end
function inventory.isIdealTorchSpot(x, z)
local isZ = (z % 7)
local isX = (x % 12)
if isZ ~= 0 or (isX ~= 0 and isX ~= 6) then
return false
end
-- we skip every other x torch in the first row,
-- and the 'other' every other torch in the next row
local zRow = math.floor(z / 7) % 2
if (zRow == 0 and isX == 6) or (zRow == 1 and isX == 0) then
return false
end
return true
end
function inventory.selectItem(pattern)
for i=1,robot.inventorySize() do
local stack = ic.getStackInInternalSlot(i)
if stack ~= nil and string.find(stack.name, pattern) ~= nil then
robot.select(i)
return true
end
end
return false
end
function inventory.placeTorch(sideOfRobot, sideOfBlock)
if inventory.selectItem("torch$") then
local success
if sideOfRobot == nil or sideOfRobot == sides.down then
success = robot.placeDown(sideOfBlock or sides.bottom)
elseif sideOfRobot == sides.front then
success = robot.place(sideOfBlock or sides.bottom)
end
if success then
return true
end
end
return false
end
function inventory.isLocalFull()
-- backwards cuz the later slots fill up last
for i=robot.inventorySize(),1,-1 do
local stack = ic.getStackInInternalSlot(i)
if stack == nil then
return false
end
end
return true
end
function inventory.toolIsBroken()
local d = robot.durability()
d = util.trunc(d or 0, 2)
return d <= 0
end
function inventory.pickUpFreshTools(sideOfRobot, toolName)
sideOfRobot = sideOfRobot or sides.bottom
local size = ic.getInventorySize()
if size == nil then
return false
end
local count = 0
for i=1,size do
local stack = ic.getStackInSlot(sideOfRobot, i)
-- is this the tool we want and fully repaired?
if stack ~= nil and
(stack.name == toolName or string.match(stack.name, toolName))
and stack.damage == stack.maxDamage then
-- found one, get it!
robot.select(1) -- select 1 cuz it will fill into an empty slot at or after that
if not ic.suckFromSlot(sideOfRobot, i) then
return false
end
count = count + 1
end
end
return true, count
end
function inventory.dropBrokenTools(sideOfRobot, toolName)
sideOfRobot = sideOfRobot or sides.bottom
local brokenToolsCount = 0
for i=1,robot.inventorySize() do
local stack = ic.getStackInInternalSlot(i)
if stack ~= nil and (stack.name == toolName or string.match(stack.name, toolName)) then
-- is this a broken tool?
local isBroken = util.trunc(stack.damage / stack.maxDamage, 2) <= 0
if isBroken then
brokenToolsCount = brokenToolsCount + 1
-- drop it
robot.select(i)
local result = (sideOfRobot == sides.bottom and robot.dropDown(1)) or
(sideOfRobot == sides.front and robot.drop(1))
if not result then
return false, brokenToolsCount
end
end
end
end
-- finally we need to see if the tool we are holding is broken
robot.select(1)
ic.equip()
local stack = ic.getStackInInternalSlot(1)
if stack ~= nil and stack.name == toolName then
-- is this a broken tool?
local isBroken = util.trunc(stack.damage / stack.maxDamage, 2) <= 0
if isBroken then
brokenToolsCount = brokenToolsCount + 1
if not robot.dropDown(1) then
ic.equip()
return false, brokenToolsCount
end
end
end
ic.equip()
return true, brokenToolsCount
end
function inventory.equipFreshTool(itemName)
if itemName == nil then
-- use the currently selected tool as the pattern.
-- first we must see what tool it is we currently have
-- swap it with slot 1
robot.select(1)
ic.equip()
local currentTool = ic.getStackInInternalSlot()
-- equip it back since whatever was in slot 1 might be important
ic.equip()
if currentTool == nil then
-- no current tool, sorry
return false
end
itemName = currentTool.name
end
for i=1,robot.inventorySize() do
local stack = ic.getStackInInternalSlot(i)
if itemName == "!empty" then
if stack == nil or (stack.maxDamage == nil or stack.maxDamage == 0) then
-- found an empty slot or at least something that doesn't use durability
robot.select(i)
ic.equip()
return true
end
elseif stack ~= nil and (stack.name == itemName or string.match(stack.name, itemName)) then
robot.select(i)
ic.equip()
-- found one but we need to check if it's got durability
if not inventory.toolIsBroken() then
return true
end
-- not durable enough, so put it back and keep looking
ic.equip()
end
end
return false
end
return inventory
|
local component = require("component")
local ic = component.inventory_controller
local robot = require("robot")
local sides = require("sides")
local util = require("util")
local inventory = {}
function inventory.isOneOf(item, checkList)
for _,chk in ipairs(checkList) do
if chk == "!tool" then
if item.maxDamage > 0 then
return true
end
elseif string.match(item.name, chk) then
return true
end
end
return false
end
function inventory.dropAll(side, fromSlotNumber, exceptFor)
-- tries to drop all the robot's inventory into the storage on the given side
-- returns true if all if it could be unloaded, false if none or only some could
--robot.drop([number]) -- Returns true if at least one item was dropped, false otherwise.
local couldDropAll = true
exceptFor = exceptFor or {}
fromSlotNumber = fromSlotNumber or 1
for i=fromSlotNumber,robot.inventorySize() do
local c = robot.count(i)
if c > 0 then
local stack = ic.getStackInInternalSlot(i)
if not inventory.isOneOf(stack, exceptFor) then
robot.select(i)
if side == nil or side == sides.front then
robot.drop()
elseif side == sides.bottom then
robot.dropDown()
elseif side == sides.top then
robot.dropUp()
end
-- see if all the items were successfully dropped
c = robot.count(i)
if c > 0 then
-- at least one item couldn't be dropped.
-- but we keep trying to drop all so we still drop as much as we can.
couldDropAll = false
end
end --isOneOf
end
end
return couldDropAll
end
function inventory.isIdealTorchSpot(x, z)
local isZ = (z % 7)
local isX = (x % 12)
if isZ ~= 0 or (isX ~= 0 and isX ~= 6) then
return false
end
-- we skip every other x torch in the first row,
-- and the 'other' every other torch in the next row
local zRow = math.floor(z / 7) % 2
if (zRow == 0 and isX == 6) or (zRow == 1 and isX == 0) then
return false
end
return true
end
function inventory.selectItem(pattern)
for i=1,robot.inventorySize() do
local stack = ic.getStackInInternalSlot(i)
if stack ~= nil and string.find(stack.name, pattern) ~= nil then
robot.select(i)
return true
end
end
return false
end
function inventory.placeTorch(sideOfRobot, sideOfBlock)
if inventory.selectItem("torch$") then
local success
if sideOfRobot == nil or sideOfRobot == sides.down then
success = robot.placeDown(sideOfBlock or sides.bottom)
elseif sideOfRobot == sides.front then
success = robot.place(sideOfBlock or sides.bottom)
end
if success then
return true
end
end
return false
end
function inventory.isLocalFull()
-- backwards cuz the later slots fill up last
for i=robot.inventorySize(),1,-1 do
local stack = ic.getStackInInternalSlot(i)
if stack == nil then
return false
end
end
return true
end
function inventory.toolIsBroken()
local d = robot.durability()
d = util.trunc(d or 0, 2)
return d <= 0
end
function inventory.pickUpFreshTools(sideOfRobot, toolName)
sideOfRobot = sideOfRobot or sides.bottom
local size = ic.getInventorySize()
if size == nil then
return false
end
local count = 0
for i=1,size do
local stack = ic.getStackInSlot(sideOfRobot, i)
-- is this the tool we want and fully repaired?
if stack ~= nil and
(stack.name == toolName or string.match(stack.name, toolName))
and stack.damage == stack.maxDamage then
-- found one, get it!
robot.select(1) -- select 1 cuz it will fill into an empty slot at or after that
if not ic.suckFromSlot(sideOfRobot, i) then
return false
end
count = count + 1
end
end
return true, count
end
function inventory.dropBrokenTools(sideOfRobot, toolName)
sideOfRobot = sideOfRobot or sides.bottom
local brokenToolsCount = 0
for i=1,robot.inventorySize() do
local stack = ic.getStackInInternalSlot(i)
if stack ~= nil and (stack.name == toolName or string.match(stack.name, toolName)) then
-- is this a broken tool?
local isBroken = util.trunc((stack.maxDamage-stack.damage) / stack.maxDamage, 2) <= 0
if isBroken then
brokenToolsCount = brokenToolsCount + 1
-- drop it
robot.select(i)
local result = (sideOfRobot == sides.bottom and robot.dropDown(1)) or
(sideOfRobot == sides.front and robot.drop(1))
if not result then
return false, brokenToolsCount
end
end
end
end
-- finally we need to see if the tool we are holding is broken
robot.select(1)
ic.equip()
local stack = ic.getStackInInternalSlot(1)
if stack ~= nil and stack.name == toolName then
-- is this a broken tool?
local isBroken = util.trunc((stack.maxDamage-stack.damage) / stack.maxDamage, 2) <= 0
if isBroken then
brokenToolsCount = brokenToolsCount + 1
if not robot.dropDown(1) then
ic.equip()
return false, brokenToolsCount
end
end
end
ic.equip()
return true, brokenToolsCount
end
function inventory.equipFreshTool(itemName)
if itemName == nil then
-- use the currently selected tool as the pattern.
-- first we must see what tool it is we currently have
-- swap it with slot 1
robot.select(1)
ic.equip()
local currentTool = ic.getStackInInternalSlot()
-- equip it back since whatever was in slot 1 might be important
ic.equip()
if currentTool == nil then
-- no current tool, sorry
return false
end
itemName = currentTool.name
end
for i=1,robot.inventorySize() do
local stack = ic.getStackInInternalSlot(i)
if itemName == "!empty" then
if stack == nil or (stack.maxDamage == nil or stack.maxDamage == 0) then
-- found an empty slot or at least something that doesn't use durability
robot.select(i)
ic.equip()
return true
end
elseif stack ~= nil and (stack.name == itemName or string.match(stack.name, itemName)) then
robot.select(i)
ic.equip()
-- found one but we need to check if it's got durability
if not inventory.toolIsBroken() then
return true
end
-- not durable enough, so put it back and keep looking
ic.equip()
end
end
return false
end
return inventory
|
fixes reverse issue with damage/maxDamage
|
fixes reverse issue with damage/maxDamage
|
Lua
|
apache-2.0
|
InfinitiesLoop/oclib
|
aee96dc67811cce904bb08f1d66b1616a4d7cb15
|
spec/cl_test.lua
|
spec/cl_test.lua
|
-- Tests the commandline options by executing busted through
-- os.execute(). It can be run through the following command:
--
-- busted --pattern=cl_test.lua --defer-print
local error_started
local error_start = function()
print("================================================")
print("== Error block follows ==")
print("================================================")
error_started = true
end
local error_end = function()
print("================================================")
print("== Error block ended, all according to plan ==")
print("================================================")
error_started = false
end
-- if exitcode >256, then take MSB as exit code
local modexit = function(exitcode)
if exitcode>255 then
return math.floor(exitcode/256), exitcode - math.floor(exitcode/256)*256
else
return exitcode
end
end
describe("Tests the busted command-line options", function()
setup(function()
require("pl")
end)
after_each(function()
if error_started then
print("================================================")
print("== Error block ended, something was wrong ==")
print("================================================")
error_started = false
end
end)
it("tests running with --tags specified", function()
local success, exitcode
error_start()
success, exitcode = utils.execute("busted --pattern=_tags.lua$")
assert.is_false(success)
assert.is_equal(modexit(exitcode), 3)
success, exitcode = utils.execute("busted --pattern=_tags.lua$ --tags=tag1")
assert.is_false(success)
assert.is_equal(modexit(exitcode), 2)
success, exitcode = utils.execute("busted --pattern=_tags.lua$ --tags=tag1,tag2")
assert.is_false(success)
assert.is_equal(modexit(exitcode), 3)
error_end()
end)
it("tests running with --lang specified", function()
local success, exitcode
error_start()
success, exitcode = utils.execute("busted --pattern=cl_success.lua$ --lang=en")
assert.is_true(success)
assert.is_equal(modexit(exitcode), 0)
success, exitcode = utils.execute("busted --pattern=cl_success --lang=not_found_here")
assert.is_false(success)
assert.is_equal(modexit(exitcode), 1) -- busted errors out on non-available language
error_end()
end)
it("tests running with --version specified", function()
local success, exitcode
success, exitcode = utils.execute("busted --version")
assert.is_true(success)
assert.is_equal(modexit(exitcode), 0)
end)
it("tests running with --help specified", function()
local success, exitcode
success, exitcode = utils.execute("busted --help")
assert.is_true(success)
assert.is_equal(modexit(exitcode), 0)
end)
it("tests running a non-compiling testfile", function()
local success, exitcode
error_start()
success, exitcode = utils.execute("busted --pattern=cl_compile_fail.lua$")
assert.is_false(success)
assert.is_equal(modexit(exitcode), 1)
error_end()
end)
it("tests running a testfile throwing errors when being run", function()
local success, exitcode
error_start()
success, exitcode = utils.execute("busted --pattern=cl_execute_fail.lua$")
assert.is_false(success)
assert.is_equal(modexit(exitcode), 1)
error_end()
end)
it("tests running with --output specified", function()
local success, exitcode
error_start()
success, exitcode = utils.execute("busted --pattern=cl_success.lua$ --output=TAP")
assert.is_true(success)
assert.is_equal(modexit(exitcode), 0)
success, exitcode = utils.execute("busted --pattern=cl_two_failures.lua$ --output=not_found_here")
assert.is_false(success)
assert.is_equal(modexit(exitcode), 1) -- 1 for outputter missing
error_end()
end)
end)
|
-- Tests the commandline options by executing busted through
-- os.execute(). It can be run through the following command:
--
-- busted --pattern=cl_test.lua --defer-print
local ditch
local error_started
local error_start = function()
if ditch == "" then return end
print("================================================")
print("== Error block follows ==")
print("================================================")
error_started = true
end
local error_end = function()
if ditch == "" then return end
print("================================================")
print("== Error block ended, all according to plan ==")
print("================================================")
error_started = false
end
-- if exitcode >256, then take MSB as exit code
local modexit = function(exitcode)
if exitcode>255 then
return math.floor(exitcode/256), exitcode - math.floor(exitcode/256)*256
else
return exitcode
end
end
local path = require("pl.path")
local = " > /dev/null 2>&1"
if path.is_windows then
ditch = " 1> NUL 2>NUL"
end
--ditch = "" -- uncomment this line, to show output of failing commands, for debugging
describe("Tests the busted command-line options", function()
setup(function()
require("pl")
end)
after_each(function()
if error_started then
print("================================================")
print("== Error block ended, something was wrong ==")
print("================================================")
error_started = false
end
end)
it("tests running with --tags specified", function()
local success, exitcode
error_start()
success, exitcode = utils.execute("busted --pattern=_tags.lua$"..ditch)
assert.is_false(success)
assert.is_equal(modexit(exitcode), 3)
success, exitcode = utils.execute("busted --pattern=_tags.lua$ --tags=tag1"..ditch)
assert.is_false(success)
assert.is_equal(modexit(exitcode), 2)
success, exitcode = utils.execute("busted --pattern=_tags.lua$ --tags=tag1,tag2"..ditch)
assert.is_false(success)
assert.is_equal(modexit(exitcode), 3)
error_end()
end)
it("tests running with --lang specified", function()
local success, exitcode
error_start()
success, exitcode = utils.execute("busted --pattern=cl_success.lua$ --lang=en"..ditch)
assert.is_true(success)
assert.is_equal(modexit(exitcode), 0)
success, exitcode = utils.execute("busted --pattern=cl_success --lang=not_found_here"..ditch)
assert.is_false(success)
assert.is_equal(modexit(exitcode), 1) -- busted errors out on non-available language
error_end()
end)
it("tests running with --version specified", function()
local success, exitcode
success, exitcode = utils.execute("busted --version"..ditch)
assert.is_true(success)
assert.is_equal(modexit(exitcode), 0)
end)
it("tests running with --help specified", function()
local success, exitcode
success, exitcode = utils.execute("busted --help"..ditch)
assert.is_true(success)
assert.is_equal(modexit(exitcode), 0)
end)
it("tests running a non-compiling testfile", function()
local success, exitcode
error_start()
success, exitcode = utils.execute("busted --pattern=cl_compile_fail.lua$"..ditch)
assert.is_false(success)
assert.is_equal(modexit(exitcode), 1)
error_end()
end)
it("tests running a testfile throwing errors when being run", function()
local success, exitcode
error_start()
success, exitcode = utils.execute("busted --pattern=cl_execute_fail.lua$"..ditch)
assert.is_false(success)
assert.is_equal(modexit(exitcode), 1)
error_end()
end)
it("tests running with --output specified", function()
local success, exitcode
error_start()
success, exitcode = utils.execute("busted --pattern=cl_success.lua$ --output=TAP"..ditch)
assert.is_true(success)
assert.is_equal(modexit(exitcode), 0)
success, exitcode = utils.execute("busted --pattern=cl_two_failures.lua$ --output=not_found_here"..ditch)
assert.is_false(success)
assert.is_equal(modexit(exitcode), 1) -- 1 for outputter missing
error_end()
end)
end)
|
fixed cl spec to run on other platforms
|
fixed cl spec to run on other platforms
|
Lua
|
mit
|
sobrinho/busted,ryanplusplus/busted,mpeterv/busted,DorianGray/busted,xyliuke/busted,istr/busted,leafo/busted,Olivine-Labs/busted,o-lim/busted,nehz/busted
|
dc95f2b487928f0a839e1b47d86e25b26579355f
|
util/DataLoader.lua
|
util/DataLoader.lua
|
require 'torch'
require 'hdf5'
local utils = require 'util.utils'
local DataLoader = torch.class('DataLoader')
function DataLoader:__init(kwargs)
local h5_file = utils.get_kwarg(kwargs, 'input_h5')
self.batch_size = utils.get_kwarg(kwargs, 'batch_size')
self.seq_length = utils.get_kwarg(kwargs, 'seq_length')
local N, T = self.batch_size, self.seq_length
-- Just slurp all the data into memory
local splits = {}
local f = hdf5.open(h5_file, 'r')
splits.train = f:read('/train'):all()
splits.val = f:read('/val'):all()
splits.test = f:read('/test'):all()
self.x_splits = {}
self.y_splits = {}
self.split_sizes = {}
for split, v in pairs(splits) do
local num = v:nElement()
local extra = num % (N * T)
-- Chop out the extra bits at the end to make it evenly divide
local vx = v[{{1, num - extra}}]:view(N, -1, T):transpose(1, 2):clone()
local vy = v[{{2, num - extra + 1}}]:view(N, -1, T):transpose(1, 2):clone()
self.x_splits[split] = vx
self.y_splits[split] = vy
self.split_sizes[split] = vx:size(1)
end
self.split_idxs = {train=1, val=1, test=1}
end
function DataLoader:nextBatch(split)
local idx = self.split_idxs[split]
assert(idx, 'invalid split ' .. split)
local x = self.x_splits[split][idx]
local y = self.y_splits[split][idx]
if idx == self.split_sizes[split] then
self.split_idxs[split] = 1
else
self.split_idxs[split] = idx + 1
end
return x, y
end
|
require 'torch'
require 'hdf5'
local utils = require 'util.utils'
local DataLoader = torch.class('DataLoader')
function DataLoader:__init(kwargs)
local h5_file = utils.get_kwarg(kwargs, 'input_h5')
self.batch_size = utils.get_kwarg(kwargs, 'batch_size')
self.seq_length = utils.get_kwarg(kwargs, 'seq_length')
local N, T = self.batch_size, self.seq_length
-- Just slurp all the data into memory
local splits = {}
local f = hdf5.open(h5_file, 'r')
splits.train = f:read('/train'):all()
splits.val = f:read('/val'):all()
splits.test = f:read('/test'):all()
self.x_splits = {}
self.y_splits = {}
self.split_sizes = {}
for split, v in pairs(splits) do
local num = v:nElement()
local extra = num % (N * T)
-- Ensure that `vy` is non-empty
if extra == 0 then
extra = N * T
end
-- Chop out the extra bits at the end to make it evenly divide
local vx = v[{{1, num - extra}}]:view(N, -1, T):transpose(1, 2):clone()
local vy = v[{{2, num - extra + 1}}]:view(N, -1, T):transpose(1, 2):clone()
self.x_splits[split] = vx
self.y_splits[split] = vy
self.split_sizes[split] = vx:size(1)
end
self.split_idxs = {train=1, val=1, test=1}
end
function DataLoader:nextBatch(split)
local idx = self.split_idxs[split]
assert(idx, 'invalid split ' .. split)
local x = self.x_splits[split][idx]
local y = self.y_splits[split][idx]
if idx == self.split_sizes[split] then
self.split_idxs[split] = 1
else
self.split_idxs[split] = idx + 1
end
return x, y
end
|
Fix bug when extra=0
|
Fix bug when extra=0
|
Lua
|
mit
|
dgcrouse/torch-rnn,oneyanshi/transcend-exe,gabrielegiannini/torch-rnn-repo,tmp6154/torch-rnn,phanhuy1502/FYP,jcjohnson/torch-rnn,spaceraccoon/bilabot,phanhuy1502/FYP,antihutka/torch-rnn
|
ab089caf5dedec2f66ff4941a27684a2cdc3a1b0
|
src/lua/main.lua
|
src/lua/main.lua
|
-- © 2008 David Given.
-- WordGrinder is licensed under the BSD open source license. See the COPYING
-- file in this distribution for the full text.
--
-- $Id$
-- $URL$
local int = math.floor
local Write = wg.write
local SetNormal = wg.setnormal
local SetBold = wg.setbold
local SetUnderline = wg.setunderline
local SetReverse = wg.setreverse
local GetStringWidth = wg.getstringwidth
local redrawpending = true
function QueueRedraw()
redrawpending = true
if not Document.wrapwidth then
ResizeScreen()
end
end
function ResetDocumentSet()
DocumentSet = CreateDocumentSet()
DocumentSet:addDocument(CreateDocument(), "main")
DocumentSet:setCurrent("main")
DocumentSet.menu = CreateMenu()
RebuildParagraphStylesMenu(DocumentSet.styles)
RebuildDocumentsMenu(DocumentSet.documents)
DocumentSet:purge()
DocumentSet:clean()
FireEvent(Event.DocumentCreated)
FireEvent(Event.RegisterAddons)
end
-- This function contains the word processor proper, including the main event
-- loop.
function WordProcessor(filename)
ResetDocumentSet()
wg.initscreen()
ResizeScreen()
RedrawScreen()
if filename then
Cmd.LoadDocumentSet(filename)
end
--ModalMessage("Welcome!", "Welcome to WordGrinder! While editing, you may press ESC for the menu, or ESC, F, X to exit (or ALT+F, X if your terminal supports it).")
local masterkeymap = {
["KEY_RESIZE"] = function() -- resize
ResizeScreen()
RedrawScreen()
end,
[" "] = Cmd.SplitCurrentWord,
["KEY_RETURN"] = Cmd.SplitCurrentParagraph,
["KEY_ESCAPE"] = Cmd.ActivateMenu,
}
local nl = string.char(13)
while true do
if DocumentSet.justchanged then
FireEvent(Event.Changed)
DocumentSet.justchanged = false
end
FireEvent(Event.WaitingForUser)
local c = "KEY_TIMEOUT"
while (c == "KEY_TIMEOUT") do
if redrawpending then
RedrawScreen()
redrawpending = false
end
c = wg.getchar(DocumentSet.idletime)
if (c == "KEY_TIMEOUT") then
FireEvent(Event.Idle)
end
end
ResetNonmodalMessages()
-- Anything in masterkeymap overrides everything else.
local f = masterkeymap[c]
if f then
f()
else
-- It's not in masterkeymap. If it's printable, insert it; if it's
-- not, look it up in the menu hierarchy.
if not c:match("^KEY_") then
Cmd.InsertStringIntoWord(c)
else
f = DocumentSet.menu:lookupAccelerator(c)
if f then
if (type(f) == "function") then
f()
else
Cmd.ActivateMenu(f)
end
else
NonmodalMessage(c:gsub("^KEY_", "").." is not bound --- try ESCAPE for a menu")
end
end
end
end
end
-- Program entry point. Parses command line arguments and executes.
function Main(...)
local filename = nil
do
local stdout = io.stdout
local stderr = io.stderr
local function message(...)
stderr:write("wordgrinder: ", ...)
stderr:write("\n")
end
local function usererror(...)
message(...)
os.exit(1)
end
local function do_help(opt)
stdout:write("WordGrinder version ", VERSION, " © 2007-2008 David Given\n")
if DEBUG then
stdout:write("(This version has been compiled with debugging enabled.)\n")
end
stdout:write([[
Syntax: wordgrinder [<options...>] [<filename>]
Options:
-h --help Displays this message.
--lua file.lua Loads and executes file.lua before startup
Only one filename may be specified, which is the name of a WordGrinder
file to load on startup. If not given, you get a blank document instead.
]])
if DEBUG then
-- List debugging options here.
end
os.exit(0)
end
local function do_lua(opt)
if not opt then
usererror("--lua must have an argument")
end
local f, e = loadfile(opt)
if e then
usererror("user script compilation error: "..e)
end
f()
return 1
end
local function do_profile(opt)
profiler.start()
return 0
end
local function needarg(opt)
if not opt then
usererror("missing option parameter")
end
end
local argmap = {
["h"] = do_help,
["help"] = do_help,
["lua"] = do_lua,
}
if DEBUG then
-- argmap["p"] = do_profile
-- argmap["profile"] = do_profile
end
-- Called on an unrecognised option.
local function unrecognisedarg(arg)
usererror("unrecognised option '", arg, "' --- try --help for help")
end
-- Do the actual argument parsing.
local arg = {...}
for i = 2, #arg do
local o = arg[i]
local op
if (o:byte(1) == 45) then
-- This is an option.
if (o:byte(2) == 45) then
-- ...with a -- prefix.
o = o:sub(3)
local fn = argmap[o]
if not fn then
unrecognisedarg("--"..o)
end
local op = arg[i+1]
i = i + fn(op)
else
-- ...without a -- prefix.
local od = o:sub(2, 2)
local fn = argmap[od]
if not fn then
unrecognisedarg("-"..od)
end
op = o:sub(3)
if (op == "") then
op = arg[i+1]
i = i + fn(op)
else
fn(op)
end
end
else
if filename then
usererror("you may only specify one filename")
end
filename = o
end
end
end
if filename and
not filename:find("^/") and
not filename:find("^[a-zA-Z]:[/\\]") then
filename = lfs.currentdir() .. "/" .. filename
end
WordProcessor(filename)
end
|
-- © 2008 David Given.
-- WordGrinder is licensed under the BSD open source license. See the COPYING
-- file in this distribution for the full text.
--
-- $Id$
-- $URL$
local int = math.floor
local Write = wg.write
local SetNormal = wg.setnormal
local SetBold = wg.setbold
local SetUnderline = wg.setunderline
local SetReverse = wg.setreverse
local GetStringWidth = wg.getstringwidth
local redrawpending = true
function QueueRedraw()
redrawpending = true
if not Document.wrapwidth then
ResizeScreen()
end
end
function ResetDocumentSet()
DocumentSet = CreateDocumentSet()
DocumentSet.menu = CreateMenu()
DocumentSet:addDocument(CreateDocument(), "main")
DocumentSet:setCurrent("main")
RebuildParagraphStylesMenu(DocumentSet.styles)
RebuildDocumentsMenu(DocumentSet.documents)
DocumentSet:purge()
DocumentSet:clean()
FireEvent(Event.DocumentCreated)
FireEvent(Event.RegisterAddons)
end
-- This function contains the word processor proper, including the main event
-- loop.
function WordProcessor(filename)
ResetDocumentSet()
wg.initscreen()
ResizeScreen()
RedrawScreen()
if filename then
Cmd.LoadDocumentSet(filename)
end
--ModalMessage("Welcome!", "Welcome to WordGrinder! While editing, you may press ESC for the menu, or ESC, F, X to exit (or ALT+F, X if your terminal supports it).")
local masterkeymap = {
["KEY_RESIZE"] = function() -- resize
ResizeScreen()
RedrawScreen()
end,
[" "] = Cmd.SplitCurrentWord,
["KEY_RETURN"] = Cmd.SplitCurrentParagraph,
["KEY_ESCAPE"] = Cmd.ActivateMenu,
}
local nl = string.char(13)
while true do
if DocumentSet.justchanged then
FireEvent(Event.Changed)
DocumentSet.justchanged = false
end
FireEvent(Event.WaitingForUser)
local c = "KEY_TIMEOUT"
while (c == "KEY_TIMEOUT") do
if redrawpending then
RedrawScreen()
redrawpending = false
end
c = wg.getchar(DocumentSet.idletime)
if (c == "KEY_TIMEOUT") then
FireEvent(Event.Idle)
end
end
ResetNonmodalMessages()
-- Anything in masterkeymap overrides everything else.
local f = masterkeymap[c]
if f then
f()
else
-- It's not in masterkeymap. If it's printable, insert it; if it's
-- not, look it up in the menu hierarchy.
if not c:match("^KEY_") then
Cmd.InsertStringIntoWord(c)
else
f = DocumentSet.menu:lookupAccelerator(c)
if f then
if (type(f) == "function") then
f()
else
Cmd.ActivateMenu(f)
end
else
NonmodalMessage(c:gsub("^KEY_", "").." is not bound --- try ESCAPE for a menu")
end
end
end
end
end
-- Program entry point. Parses command line arguments and executes.
function Main(...)
local filename = nil
do
local stdout = io.stdout
local stderr = io.stderr
local function message(...)
stderr:write("wordgrinder: ", ...)
stderr:write("\n")
end
local function usererror(...)
message(...)
os.exit(1)
end
local function do_help(opt)
stdout:write("WordGrinder version ", VERSION, " © 2007-2008 David Given\n")
if DEBUG then
stdout:write("(This version has been compiled with debugging enabled.)\n")
end
stdout:write([[
Syntax: wordgrinder [<options...>] [<filename>]
Options:
-h --help Displays this message.
--lua file.lua Loads and executes file.lua before startup
Only one filename may be specified, which is the name of a WordGrinder
file to load on startup. If not given, you get a blank document instead.
]])
if DEBUG then
-- List debugging options here.
end
os.exit(0)
end
local function do_lua(opt)
if not opt then
usererror("--lua must have an argument")
end
local f, e = loadfile(opt)
if e then
usererror("user script compilation error: "..e)
end
f()
return 1
end
local function do_profile(opt)
profiler.start()
return 0
end
local function needarg(opt)
if not opt then
usererror("missing option parameter")
end
end
local argmap = {
["h"] = do_help,
["help"] = do_help,
["lua"] = do_lua,
}
if DEBUG then
-- argmap["p"] = do_profile
-- argmap["profile"] = do_profile
end
-- Called on an unrecognised option.
local function unrecognisedarg(arg)
usererror("unrecognised option '", arg, "' --- try --help for help")
end
-- Do the actual argument parsing.
local arg = {...}
for i = 2, #arg do
local o = arg[i]
local op
if (o:byte(1) == 45) then
-- This is an option.
if (o:byte(2) == 45) then
-- ...with a -- prefix.
o = o:sub(3)
local fn = argmap[o]
if not fn then
unrecognisedarg("--"..o)
end
local op = arg[i+1]
i = i + fn(op)
else
-- ...without a -- prefix.
local od = o:sub(2, 2)
local fn = argmap[od]
if not fn then
unrecognisedarg("-"..od)
end
op = o:sub(3)
if (op == "") then
op = arg[i+1]
i = i + fn(op)
else
fn(op)
end
end
else
if filename then
usererror("you may only specify one filename")
end
filename = o
end
end
end
if filename and
not filename:find("^/") and
not filename:find("^[a-zA-Z]:[/\\]") then
filename = lfs.currentdir() .. "/" .. filename
end
WordProcessor(filename)
end
|
Fixed crash on File->New caused by the menu not being created at the right point.
|
Fixed crash on File->New caused by the menu not being created at the right point.
|
Lua
|
mit
|
rodoviario/wordgrinder,Munchotaur/wordgrinder,NRauh/wordgrinder,NRauh/wordgrinder,rodoviario/wordgrinder,Munchotaur/wordgrinder
|
90ca7152241450472ceb745b108b64afd7bdfd6e
|
mogamett/mixins/PhysicsBody.lua
|
mogamett/mixins/PhysicsBody.lua
|
local Class = require (mogamett_path .. '/libraries/classic/classic')
local PhysicsBody = Class:extend()
function PhysicsBody:physicsBodyNew(world, x, y, settings)
self.bodies = {}
self.shapes = {}
self.fixtures = {}
self.sensors = {}
self.joints = {}
self:addBody(world, x, y, settings)
end
function PhysicsBody:addBody(world, x, y, settings)
settings = settings or {}
local body = love.physics.newBody(world.world, x, y, settings.body_type or 'dynamic')
body:setFixedRotation(true)
settings.shape = settings.shape or 'rectangle'
local shape = nil
local shape_name = string.lower(settings.shape)
self.shape_name = shape_name
local body_w, body_h, body_r = 0, 0, 0
if shape_name == 'bsgrectangle' then
local w, h, s = settings.w or 32, settings.h or 32, settings.s or 4
body_w, body_h = w, h
shape = love.physics.newPolygonShape(
-w/2, -h/2 + s, -w/2 + s, -h/2,
w/2 - s, -h/2, w/2, -h/2 + s,
w/2, h/2 - s, w/2 - s, h/2,
-w/2 + s, h/2, -w/2, h/2 - s
)
elseif shape_name == 'rectangle' then
body_w, body_h = settings.w or 32, settings.h or 32
shape = love.physics.newRectangleShape(settings.w or 32, settings.h or 32)
elseif shape_name == 'polygon' then
shape = love.physics.newPolygonShape(unpack(settings.vertices))
elseif shape_name == 'chain' then
shape = love.physics.newChainShape(settings.loop or false, unpack(settings.vertices))
elseif shape_name == 'circle' then
body_r = settings.r or 16
body_w, body_h = settings.r or 32, settings.r or 32
shape = love.physics.newCircleShape(settings.r or 16)
end
local mask_name = settings.collision_class or self.class_name
local fixture = love.physics.newFixture(body, shape)
fixture:setCategory(unpack(self.world.mg.Collision.masks[mask_name].categories))
fixture:setMask(unpack(self.world.mg.Collision.masks[mask_name].masks))
fixture:setUserData({object = self, tag = mask_name})
local sensor = love.physics.newFixture(body, shape)
sensor:setSensor(true)
sensor:setUserData({object = self, tag = mask_name})
table.insert(self.bodies, body)
table.insert(self.shapes, shape)
table.insert(self.fixtures, fixture)
table.insert(self.sensors, sensor)
-- Set self.---- to the first added ----
if #self.bodies == 1 then
self.w, self.h, self.r = body_w, body_h, body_r
self.body = self.bodies[1]
self.shape = self.shapes[1]
self.fixture = self.fixtures[1]
self.sensor = self.sensors[1]
end
end
function PhysicsBody:removeBody(n)
self.fixtures[n]:setUserData(nil)
self.sensors[n]:setUserData(nil)
self.bodies[n]:destroy()
table.remove(self.fixtures, n)
table.remove(self.sensors, n)
table.remove(self.bodies, n)
end
function PhysicsBody:addJoint(type, ...)
local args = {...}
local joint_name = string.lower(type)
local joint = nil
local joint_name_to_function_name = {
distance = 'newDistanceJoint', friction = 'newFrictionJoint', gear = 'newGearJoint',
mouse = 'newMouseJoint', prismatic = 'newPrismaticJoint', pulley = 'newPulleyJoint',
revolute = 'newRevoluteJoint', rope = 'newRopeJoint', weld = 'newWeldJoint', wheel = 'newWheelJoint',
}
joint = love.physics[joint_name_to_function_name[joint_name]](unpack(args))
table.insert(self.joints, joint)
end
function PhysicsBody:removeJoint(n)
self.joints[n]:destroy()
table.remove(self.joints, n)
end
function PhysicsBody:removeShape(n)
table.remove(self.shapes, n)
end
function PhysicsBody:changeCollisionClass(n, collision_class)
self.fixtures[n]:setCategory(unpack(self.world.mg.Collision.masks[collision_class].categories))
self.fixtures[n]:setMask(unpack(self.world.mg.Collision.masks[collision_class].masks))
self.fixtures[n]:setUserData({object = self, tag = collision_class})
self.sensors[n]:setSensor(true)
self.sensors[n]:setUserData({object = self, tag = collision_class})
end
function PhysicsBody:physicsBodyUpdate(dt)
self.x, self.y = self.body:getPosition()
end
function PhysicsBody:physicsBodyDraw()
self.x, self.y = self.body:getPosition()
if not self.world.mg.debug_draw then return end
for i = 1, #self.bodies do
if self.shapes[i]:type() == 'PolygonShape' then
love.graphics.setColor(64, 128, 244)
love.graphics.polygon('line', self.bodies[i]:getWorldPoints(self.shapes[i]:getPoints()))
love.graphics.setColor(255, 255, 255)
elseif self.shapes[i]:type() == 'EdgeShape' then
love.graphics.setColor(64, 128, 244)
local points = {self.bodies[i]:getWorldPoints(self.shapes[i]:getPoints())}
for i = 1, #points, 2 do
if i < #points-2 then love.graphics.line(points[i], points[i+1], points[i+2], points[i+3]) end
end
love.graphics.setColor(255, 255, 255)
elseif self.shapes[i]:type() == 'CircleShape' then
love.graphics.setColor(64, 128, 244)
local x, y = self.bodies[i]:getPosition()
love.graphics.circle('line', x, y, self.r, 360)
love.graphics.setColor(255, 255, 255)
end
end
for i = 1, #self.joints do
local x1, y1, x2, y2 = self.joints[i]:getAnchors()
love.graphics.setPointSize(8)
love.graphics.setColor(244, 128, 64)
love.graphics.point(x1, y1)
love.graphics.setColor(128, 244, 64)
love.graphics.point(x2, y2)
love.graphics.setColor(255, 255, 255)
love.graphics.setPointSize(1)
end
end
function PhysicsBody:handleCollisions(type, object, contact, ni1, ti1, ni2, ti2)
if type == 'pre' then
if self.preSolve then
self:preSolve(object, contact)
end
elseif type == 'post' then
if self.postSolve then
self:postSolve(object, contact, ni1, ti1, ni2, ti2)
end
elseif type == 'enter' then
if self.onCollisionEnter then
self:onCollisionEnter(object, contact)
end
elseif type == 'exit' then
if self.onCollisionExit then
self:onCollisionExit(object, contact)
end
end
end
return PhysicsBody
|
local Class = require (mogamett_path .. '/libraries/classic/classic')
local PhysicsBody = Class:extend()
function PhysicsBody:physicsBodyNew(world, x, y, settings)
self.bodies = {}
self.shapes = {}
self.fixtures = {}
self.sensors = {}
self.joints = {}
self:addBody(world, x, y, settings)
end
function PhysicsBody:addBody(world, x, y, settings)
-- Set name to main if there isn't one and/or remove previous physics names if they already exist
local settings = settings or {}
settings.physics_name = settings.physics_name or 'main'
local name = settings.physics_name
if self.bodies[name] then self:removeBody(name) end
-- Define body
local body = love.physics.newBody(world.world, x, y, settings.body_type or 'dynamic')
body:setFixedRotation(true)
-- Define shape
settings.shape = settings.shape or 'rectangle'
local shape = nil
local shape_name = string.lower(settings.shape)
self.shape_name = shape_name
local body_w, body_h, body_r = 0, 0, 0
if shape_name == 'bsgrectangle' then
local w, h, s = settings.w or 32, settings.h or 32, settings.s or 4
body_w, body_h = w, h
shape = love.physics.newPolygonShape(
-w/2, -h/2 + s, -w/2 + s, -h/2,
w/2 - s, -h/2, w/2, -h/2 + s,
w/2, h/2 - s, w/2 - s, h/2,
-w/2 + s, h/2, -w/2, h/2 - s
)
elseif shape_name == 'rectangle' then
body_w, body_h = settings.w or 32, settings.h or 32
shape = love.physics.newRectangleShape(settings.w or 32, settings.h or 32)
elseif shape_name == 'polygon' then
shape = love.physics.newPolygonShape(unpack(settings.vertices))
elseif shape_name == 'chain' then
shape = love.physics.newChainShape(settings.loop or false, unpack(settings.vertices))
elseif shape_name == 'circle' then
body_r = settings.r or 16
body_w, body_h = settings.r or 32, settings.r or 32
shape = love.physics.newCircleShape(settings.r or 16)
end
-- Define collision classes and attach them to fixture and sensor
local mask_name = settings.collision_class or self.class_name
local fixture = love.physics.newFixture(body, shape)
fixture:setCategory(unpack(self.world.mg.Collision.masks[mask_name].categories))
fixture:setMask(unpack(self.world.mg.Collision.masks[mask_name].masks))
fixture:setUserData({object = self, tag = mask_name})
local sensor = love.physics.newFixture(body, shape)
sensor:setSensor(true)
sensor:setUserData({object = self, tag = mask_name})
self.bodies[name] = body
self.shapes[name] = shape
self.fixtures[name] = fixture
self.sensors[name] = sensor
-- self.body, shape, fixture, sensor = the main body, shape, fixture, sensor
if name == 'main' then
self.w, self.h, self.r = body_w, body_h, body_r
self.body = self.bodies['main']
self.shape = self.shapes['main']
self.fixture = self.fixtures['main']
self.sensor = self.sensors['main']
end
end
function PhysicsBody:removeBody(name)
if not self.bodies[name] then return end
self.fixtures[name]:setUserData(nil)
self.sensors[name]:setUserData(nil)
self.bodies[name]:destroy()
self.fixtures[name] = nil
self.sensors[name] = nil
self.shapes[name] = nil
self.bodies[name] = nil
end
function PhysicsBody:removeJoint(name)
if not self.joints[name] then return end
self.joints[name]:destroy()
self.joints[name] = nil
end
function PhysicsBody:removeShape(name)
if not self.shapes[name] then return end
self.shapes[name] = nil
end
function PhysicsBody:addJoint(name, type, ...)
if self.joints[name] then self:removeJoint(name) end
local args = {...}
local joint_name = string.lower(type)
local joint = nil
local joint_name_to_function_name = {
distance = 'newDistanceJoint', friction = 'newFrictionJoint', gear = 'newGearJoint',
mouse = 'newMouseJoint', prismatic = 'newPrismaticJoint', pulley = 'newPulleyJoint',
revolute = 'newRevoluteJoint', rope = 'newRopeJoint', weld = 'newWeldJoint', wheel = 'newWheelJoint',
}
joint = love.physics[joint_name_to_function_name[joint_name]](unpack(args))
self.joints[name] = joint
end
function PhysicsBody:changeCollisionClass(name, collision_class)
if not self.fixtures[name] then return end -- fail silently or not? Same question for add/remove calls
self.fixtures[name]:setCategory(unpack(self.world.mg.Collision.masks[collision_class].categories))
self.fixtures[name]:setMask(unpack(self.world.mg.Collision.masks[collision_class].masks))
self.fixtures[name]:setUserData({object = self, tag = collision_class})
self.sensors[name]:setSensor(true)
self.sensors[name]:setUserData({object = self, tag = collision_class})
end
function PhysicsBody:physicsBodyUpdate(dt)
self.x, self.y = self.body:getPosition()
end
function PhysicsBody:physicsBodyDraw()
self.x, self.y = self.body:getPosition()
if not self.world.mg.debug_draw then return end
for name, body in pairs(self.bodies) do
if self.shapes[name]:type() == 'PolygonShape' then
love.graphics.setColor(64, 128, 244)
love.graphics.polygon('line', self.bodies[name]:getWorldPoints(self.shapes[name]:getPoints()))
love.graphics.setColor(255, 255, 255)
elseif self.shapes[name]:type() == 'EdgeShape' then
love.graphics.setColor(64, 128, 244)
local points = {self.bodies[name]:getWorldPoints(self.shapes[name]:getPoints())}
for i = 1, #points, 2 do
if i < #points-2 then love.graphics.line(points[i], points[i+1], points[i+2], points[i+3]) end
end
love.graphics.setColor(255, 255, 255)
elseif self.shapes[name]:type() == 'CircleShape' then
love.graphics.setColor(64, 128, 244)
local x, y = self.bodies[name]:getPosition()
love.graphics.circle('line', x, y, self.r, 360)
love.graphics.setColor(255, 255, 255)
end
end
for name, joint in pairs(self.joints) do
local x1, y1, x2, y2 = self.joints[name]:getAnchors()
love.graphics.setPointSize(8)
love.graphics.setColor(244, 128, 64)
love.graphics.point(x1, y1)
love.graphics.setColor(128, 244, 64)
love.graphics.point(x2, y2)
love.graphics.setColor(255, 255, 255)
love.graphics.setPointSize(1)
end
end
function PhysicsBody:handleCollisions(type, object, contact, ni1, ti1, ni2, ti2)
if type == 'pre' then
if self.preSolve then
self:preSolve(object, contact)
end
elseif type == 'post' then
if self.postSolve then
self:postSolve(object, contact, ni1, ti1, ni2, ti2)
end
elseif type == 'enter' then
if self.onCollisionEnter then
self:onCollisionEnter(object, contact)
end
elseif type == 'exit' then
if self.onCollisionExit then
self:onCollisionExit(object, contact)
end
end
end
return PhysicsBody
|
Add body/shape/fixture/sensor naming for proper retrieval/removal
|
Add body/shape/fixture/sensor naming for proper retrieval/removal
|
Lua
|
mit
|
AntonioModer/fuccboiGDX,AntonioModer/fuccboiGDX
|
413904bb40d3ed3b82518c2d82201bceae27b555
|
premake4.lua
|
premake4.lua
|
----------------------------------------------------------------------------------------------------
if _ACTION == "clean" then
os.rmdir("build")
end
----------------------------------------------------------------------------------------------------
solution "Support"
configurations { "Debug", "Release" }
platforms { "x64", "x32" }
location ("build/" .. _ACTION)
objdir ("build/" .. _ACTION .. "/obj")
configuration { "Debug" }
targetsuffix "d"
defines { "_DEBUG" }
flags { "ExtraWarnings", "Symbols" }
configuration { "Release" }
defines { "NDEBUG" }
flags { "ExtraWarnings", "Optimize" }
configuration { "Debug", "x64" }
targetdir ("build/" .. _ACTION .. "/bin/x64/Debug")
configuration { "Release", "x64" }
targetdir ("build/" .. _ACTION .. "/bin/x64/Release")
configuration { "Debug", "x32" }
targetdir ("build/" .. _ACTION .. "/bin/x32/Debug")
configuration { "Release", "x32" }
targetdir ("build/" .. _ACTION .. "/bin/x32/Release")
configuration { "gmake" }
buildoptions {
"-std=c++11",
"-pedantic",
-- "-save-temps",
}
configuration { "windows" }
flags { "Unicode" }
----------------------------------------------------------------------------------------------------
local have_gtest = os.isdir("test/gtest")
----------------------------------------------------------------------------------------------------
project "CmdLine"
kind "StaticLib"
language "C++"
includedirs { "include/" }
files {
"include/**.*",
"src/**.*",
}
----------------------------------------------------------------------------------------------------
project "Test"
kind "ConsoleApp"
language "C++"
links { "CmdLine" }
includedirs { "include/" }
files {
"test/Test.cpp",
"test/CmdLineQt.h",
}
----------------------------------------------------------------------------------------------------
project "CmdLineTest"
kind "ConsoleApp"
language "C++"
links { "CmdLine", "gtest", "gtest_main" }
includedirs { "include/" }
if have_gtest then
includedirs { "test/gtest/include" }
end
files {
"test/CmdLineTest.cpp",
}
----------------------------------------------------------------------------------------------------
project "CmdLineToArgvTest"
kind "ConsoleApp"
language "C++"
links { "CmdLine", "gtest", "gtest_main" }
includedirs { "include/" }
if have_gtest then
includedirs { "test/gtest/include" }
end
files {
"test/CmdLineToArgvTest.cpp",
}
----------------------------------------------------------------------------------------------------
project "ConvertUTFTest"
kind "ConsoleApp"
language "C++"
links { "CmdLine", "gtest", "gtest_main" }
includedirs { "include/" }
if have_gtest then
includedirs { "test/gtest/include" }
end
files {
"test/ConvertUTFTest.cpp",
"test/ConvertUTF.h",
}
----------------------------------------------------------------------------------------------------
project "StringRefTest"
kind "ConsoleApp"
language "C++"
links { "CmdLine", "gtest", "gtest_main" }
includedirs { "include/" }
if have_gtest then
includedirs { "test/gtest/include" }
end
files {
"test/StringRefTest.cpp",
}
----------------------------------------------------------------------------------------------------
project "StringSplitTest"
kind "ConsoleApp"
language "C++"
links { "CmdLine", "gtest", "gtest_main" }
includedirs { "include/" }
if have_gtest then
includedirs { "test/gtest/include" }
end
files {
"test/StringSplitTest.cpp",
}
----------------------------------------------------------------------------------------------------
if have_gtest then
project "gtest"
kind "StaticLib"
language "C++"
includedirs {
"test/gtest/include",
"test/gtest",
}
files {
"test/gtest/src/gtest-all.cc",
}
project "gtest_main"
kind "StaticLib"
language "C++"
includedirs {
"test/gtest/include",
"test/gtest",
}
files {
"test/gtest/src/gtest_main.cc",
}
end
|
----------------------------------------------------------------------------------------------------
if _ACTION == "clean" then
os.rmdir("build")
end
----------------------------------------------------------------------------------------------------
local have_gtest = os.isdir("test/gtest")
----------------------------------------------------------------------------------------------------
solution "Support"
configurations { "Debug", "Release" }
platforms { "x64", "x32" }
location ("build/" .. _ACTION)
objdir ("build/" .. _ACTION .. "/obj")
if have_gtest then
-- all tests are single threaded.
-- compiling with "-pthread" doesn't help... avoid linker errors...
-- FIXME!
defines { "GTEST_HAS_PTHREAD=0" }
end
configuration { "Debug" }
targetsuffix "d"
defines { "_DEBUG" }
flags { "ExtraWarnings", "Symbols" }
configuration { "Release" }
defines { "NDEBUG" }
flags { "ExtraWarnings", "Optimize" }
configuration { "Debug", "x64" }
targetdir ("build/" .. _ACTION .. "/bin/x64/Debug")
configuration { "Release", "x64" }
targetdir ("build/" .. _ACTION .. "/bin/x64/Release")
configuration { "Debug", "x32" }
targetdir ("build/" .. _ACTION .. "/bin/x32/Debug")
configuration { "Release", "x32" }
targetdir ("build/" .. _ACTION .. "/bin/x32/Release")
configuration { "gmake" }
buildoptions {
"-std=c++11",
"-pedantic",
}
configuration { "windows" }
flags { "Unicode" }
----------------------------------------------------------------------------------------------------
project "CmdLine"
kind "StaticLib"
language "C++"
includedirs { "include/" }
files {
"include/**.*",
"src/**.*",
}
----------------------------------------------------------------------------------------------------
project "Test"
kind "ConsoleApp"
language "C++"
links { "CmdLine" }
includedirs { "include/" }
files {
"test/Test.cpp",
"test/CmdLineQt.h",
}
----------------------------------------------------------------------------------------------------
project "CmdLineTest"
kind "ConsoleApp"
language "C++"
links { "CmdLine", "gtest", "gtest_main" }
includedirs { "include/" }
if have_gtest then
includedirs { "test/gtest/include" }
end
files {
"test/CmdLineTest.cpp",
}
----------------------------------------------------------------------------------------------------
project "CmdLineToArgvTest"
kind "ConsoleApp"
language "C++"
links { "CmdLine", "gtest", "gtest_main" }
includedirs { "include/" }
if have_gtest then
includedirs { "test/gtest/include" }
end
files {
"test/CmdLineToArgvTest.cpp",
}
----------------------------------------------------------------------------------------------------
project "ConvertUTFTest"
kind "ConsoleApp"
language "C++"
links { "CmdLine", "gtest", "gtest_main" }
includedirs { "include/" }
if have_gtest then
includedirs { "test/gtest/include" }
end
files {
"test/ConvertUTFTest.cpp",
"test/ConvertUTF.h",
}
----------------------------------------------------------------------------------------------------
project "StringRefTest"
kind "ConsoleApp"
language "C++"
links { "CmdLine", "gtest", "gtest_main" }
includedirs { "include/" }
if have_gtest then
includedirs { "test/gtest/include" }
end
files {
"test/StringRefTest.cpp",
}
----------------------------------------------------------------------------------------------------
project "StringSplitTest"
kind "ConsoleApp"
language "C++"
links { "CmdLine", "gtest", "gtest_main" }
includedirs { "include/" }
if have_gtest then
includedirs { "test/gtest/include" }
end
files {
"test/StringSplitTest.cpp",
}
----------------------------------------------------------------------------------------------------
if have_gtest then
project "gtest"
kind "StaticLib"
language "C++"
includedirs {
"test/gtest/include",
"test/gtest",
}
files {
"test/gtest/src/gtest-all.cc",
}
project "gtest_main"
kind "StaticLib"
language "C++"
includedirs {
"test/gtest/include",
"test/gtest",
}
files {
"test/gtest/src/gtest_main.cc",
}
end
|
Fix linker errors with gtest
|
Fix linker errors with gtest
|
Lua
|
mit
|
abolz/CmdLine
|
84a971b27db6361ff5444060a7432b111c10a7de
|
premake4.lua
|
premake4.lua
|
--
-- Premake4 build script (http://industriousone.com/premake/download)
--
solution 'cpp-bench'
configurations {'Debug', 'Release'}
language 'C++'
flags {'ExtraWarnings'}
targetdir 'bin'
platforms {'x32','x64'}
configuration 'Debug'
defines { 'DEBUG' }
flags { 'Symbols' }
configuration 'Release'
defines { 'NDEBUG' }
flags { 'Symbols', 'Optimize' }
project 'benchmark'
location 'build'
kind 'ConsoleApp'
uuid '31BC2F58-F374-4984-B490-F1F08ED02DD3'
files
{
'src/*.h',
'src/*.cpp',
'test/*.cpp',
}
includedirs
{
'src',
}
if os.get() == 'windows' then
defines
{
'WIN32',
'WIN32_LEAN_AND_MEAN',
'_WIN32_WINNT=0x0600',
'_CRT_SECURE_NO_WARNINGS',
'_SCL_SECURE_NO_WARNINGS',
'NOMINMAX',
}
end
if os.get() == 'linux' then
buildoptions { '-std=c++11' }
defines
{
'__STDC_LIMIT_MACROS',
}
end
|
--
-- Premake4 build script (http://industriousone.com/premake/download)
--
solution 'cpp-bench'
configurations {'Debug', 'Release'}
language 'C++'
flags {'ExtraWarnings'}
targetdir 'bin'
platforms {'x32','x64'}
configuration 'Debug'
defines { 'DEBUG' }
flags { 'Symbols' }
configuration 'Release'
defines { 'NDEBUG' }
flags { 'Symbols', 'Optimize' }
project 'benchmark'
location 'build'
kind 'ConsoleApp'
uuid '31BC2F58-F374-4984-B490-F1F08ED02DD3'
files
{
'src/*.h',
'src/*.cpp',
'test/*.cpp',
}
includedirs
{
'src',
}
if os.get() == 'windows' then
defines
{
'WIN32',
'WIN32_LEAN_AND_MEAN',
'_WIN32_WINNT=0x0600',
'_CRT_SECURE_NO_WARNINGS',
'_SCL_SECURE_NO_WARNINGS',
'NOMINMAX',
}
end
if os.get() == 'linux' then
buildoptions { '-std=c++11' }
defines
{
'__STDC_LIMIT_MACROS',
}
links
{
'rt',
}
end
|
fix linux linkage clock_gettime() need lib 'rt'
|
fix linux linkage
clock_gettime() need lib 'rt'
|
Lua
|
apache-2.0
|
ichenq/cpp-bench,ichenq/cpp-bench
|
425cba468999e6d9a0636f0c4a40a6949abb08f3
|
lib/switchboard_modules/lua_script_debugger/premade_scripts/counter_examples/107_counters.lua
|
lib/switchboard_modules/lua_script_debugger/premade_scripts/counter_examples/107_counters.lua
|
--The loop runs at about 130 Hz, meaning that frequencies up to about 65 Hz can
-- be accurately counted.
--The index of each counter within an array is 1 more than its
-- associated counter. E.g. counter 10 (AIN113) corresponds with an array
-- index of 11.
--Counters 0-3 correspond with AIN0-AIN3
--Counters 4-13 correspond with AIN107-116 as the following:
--Counter: 4 Channel: AIN107
--Counter: 5 Channel: AIN108
--Counter: 6 Channel: AIN109
--Counter: 7 Channel: AIN110
--Counter: 8 Channel: AIN111
--Counter: 9 Channel: AIN112
--Counter: 10 Channel: AIN113
--Counter: 11 Channel: AIN114
--Counter: 12 Channel: AIN115
--Counter: 13 Channel: AIN116
--Counters 14-36 correspond with DIO0-22 as the following:
--Counter: 14 Channel: FIO0 (DIO0)
--Counter: 15 Channel: FIO1 (DIO1)
--Counter: 16 Channel: FIO2 (DIO2)
--Counter: 17 Channel: FIO3 (DIO3)
--Counter: 18 Channel: FIO4 (DIO4)
--Counter: 19 Channel: FIO5 (DIO5)
--Counter: 20 Channel: FIO6 (DIO6)
--Counter: 21 Channel: FIO7 (DIO7)
--Counter: 22 Channel: EIO0 (DIO8)
--Counter: 23 Channel: EIO1 (DIO9)
--Counter: 24 Channel: EIO2 (DIO10)
--Counter: 25 Channel: EIO3 (DIO11)
--Counter: 26 Channel: EIO4 (DIO12)
--Counter: 27 Channel: EIO5 (DIO13)
--Counter: 28 Channel: EIO6 (DIO14)
--Counter: 29 Channel: EIO7 (DIO15)
--Counter: 30 Channel: CIO0 (DIO16)
--Counter: 31 Channel: CIO1 (DIO17)
--Counter: 32 Channel: CIO2 (DIO18)
--Counter: 33 Channel: CIO3 (DIO19)
--Counter: 34 Channel: MIO0 (DIO20)
--Counter: 35 Channel: MIO1 (DIO21)
--Counter: 36 Channel: MIO2 (DIO22)
--Counters 37-47 correspond with AIN117-AIN127 as the following:
--Counter: 37 Channel: AIN117
--Counter: 38 Channel: AIN118
--Counter: 39 Channel: AIN119
--Counter: 40 Channel: AIN120
--Counter: 41 Channel: AIN121
--Counter: 42 Channel: AIN122
--Counter: 43 Channel: AIN123
--Counter: 44 Channel: AIN124
--Counter: 45 Channel: AIN125
--Counter: 46 Channel: AIN126
--Counter: 47 Channel: AIN127
--Counters 48-106 correspond with AIN48-106
print("Create and read 107 counters.")
local mbRead=MB.R --Local functions for faster processing
local mbWrite=MB.W
if (mbRead(60000, 3) ~= 7) then
print("This example is only for the T7. Exiting Lua Script.")
mbWrite(6000, 1, 0)
end
local threshold = {}
for i=1, 107 do
--Thresholds can be changed to be specific to each analog input
threshold[i] = 1.4
end
--1 = Rising edge, 0 = falling
local edge = {}
for i=1, 107 do
edge[i] = 0 --sets all 107 counters to increment on falling edges
end
local bits = {}
local bits_new = {}
local count = {}
--The throttle setting can correspond roughly with the length of the Lua
--script. A rule of thumb for deciding a throttle setting is
--throttle = (3*NumLinesCode) + 20
local throttleSetting = 100 --Default throttle setting is 10 instructions
LJ.setLuaThrottle(throttleSetting)
ThrottleSetting = LJ.getLuaThrottle()
print ("Current Lua Throttle Setting: ", throttleSetting)
mbWrite(2600, 0, 0) --FIO to input
mbWrite(2601, 0, 0) --EIO to input
mbWrite(2602, 0, 0) --COI to input
mbWrite(2603, 0, 0) --MIO to input
mbWrite(43903, 0, 1) --AIN_ALL_RESOLUTION_INDEX to 1
mbWrite(6006, 1, 37)
for i=1, 107 do
bits[i] = 0
bits_new[i] = 99
count[i] = 0
end
while true do
--Analog channels AIN0-AIN3
for i=1, 4 do
if mbRead((i-1)*2, 3) > threshold[i] then
bits_new[i]=1
else
bits_new[i]=0
end
end
--Analog channels AIN107-AIN116
for i=5, 14 do
if mbRead((i+102)*2, 3) > threshold[i] then
bits_new[i]=1
else
bits_new[i]=0
end
end
--Digital channels DIO0-22
for i=15, 37 do
bits_new[i] = mbRead((i-15)+2000, 0)
end
--Analog channels AIN117-AIN127
for i=38, 48 do
if mbRead((i+79)*2, 3) > threshold[i] then
bits_new[i]=1
else
bits_new[i]=0
end
end
--Analog channels AIN48-AIN106
for i=49, 107 do
if mbRead((i-1)*2, 3) > threshold[i] then
bits_new[i]=1
else
bits_new[i]=0
end
end
--Compare bits_new to bits
for i=1, 107 do
if bits[i] ~= bits_new[i] then
if edge[i] == 1 then
if bits[i] == 0 then
count[i] = count[i] + 1
print ("Counter: ", i-1, " Rising: ", count[i])
end -- ==0
else
if bits[i] == 1 then
count[i] = count[i] + 1
print ("Counter: ", i-1, " Falling: ", count[i])
end
end
bits[i] = bits_new[i]
if i<100 then --Only the first 100 counters can be saved in User RAM
mbWrite(((i-1)*2)+46000, 3, count[i])
end
end
end
end
|
--[[
Name: 107_counters.lua
Desc: Sets up and reads 107 counters
Note: The loop runs at about 130 Hz, meaning that frequencies up to about
65 Hz can be accurately counted.
The index of each counter within an array is 1 more than its
associated counter. E.g. counter 10 (AIN113) corresponds with an
array index of 11.
--]]
--Counters 0-3 correspond with AIN0-AIN3
--Counters 4-13 correspond with AIN107-116 as the following:
--Counter: 4 Channel: AIN107
--Counter: 5 Channel: AIN108
--Counter: 6 Channel: AIN109
--Counter: 7 Channel: AIN110
--Counter: 8 Channel: AIN111
--Counter: 9 Channel: AIN112
--Counter: 10 Channel: AIN113
--Counter: 11 Channel: AIN114
--Counter: 12 Channel: AIN115
--Counter: 13 Channel: AIN116
--Counters 14-36 correspond with DIO0-22 as the following:
--Counter: 14 Channel: FIO0 (DIO0)
--Counter: 15 Channel: FIO1 (DIO1)
--Counter: 16 Channel: FIO2 (DIO2)
--Counter: 17 Channel: FIO3 (DIO3)
--Counter: 18 Channel: FIO4 (DIO4)
--Counter: 19 Channel: FIO5 (DIO5)
--Counter: 20 Channel: FIO6 (DIO6)
--Counter: 21 Channel: FIO7 (DIO7)
--Counter: 22 Channel: EIO0 (DIO8)
--Counter: 23 Channel: EIO1 (DIO9)
--Counter: 24 Channel: EIO2 (DIO10)
--Counter: 25 Channel: EIO3 (DIO11)
--Counter: 26 Channel: EIO4 (DIO12)
--Counter: 27 Channel: EIO5 (DIO13)
--Counter: 28 Channel: EIO6 (DIO14)
--Counter: 29 Channel: EIO7 (DIO15)
--Counter: 30 Channel: CIO0 (DIO16)
--Counter: 31 Channel: CIO1 (DIO17)
--Counter: 32 Channel: CIO2 (DIO18)
--Counter: 33 Channel: CIO3 (DIO19)
--Counter: 34 Channel: MIO0 (DIO20)
--Counter: 35 Channel: MIO1 (DIO21)
--Counter: 36 Channel: MIO2 (DIO22)
--Counters 37-47 correspond with AIN117-AIN127 as the following:
--Counter: 37 Channel: AIN117
--Counter: 38 Channel: AIN118
--Counter: 39 Channel: AIN119
--Counter: 40 Channel: AIN120
--Counter: 41 Channel: AIN121
--Counter: 42 Channel: AIN122
--Counter: 43 Channel: AIN123
--Counter: 44 Channel: AIN124
--Counter: 45 Channel: AIN125
--Counter: 46 Channel: AIN126
--Counter: 47 Channel: AIN127
--Counters 48-106 correspond with AIN48-106
print("Create and read 107 counters.")
-- Assign global functions locally for faster processing
local modbus_read = MB.R
local modbus_write = MB.W
local set_lua_throttle = LJ.setLuaThrottle
local get_lua_throttle = LJ.getLuaThrottle
-- Read the PRODUCT_ID register to get the device type. This script will not
-- run correctly on devices other than the T7
if (modbus_read(60000, 3) ~= 7) then
print("This example is only for the T7. Exiting Lua Script.")
-- Write a 0 to LUA_RUN to stop the script
modbus_write(6000, 1, 0)
end
local threshold = {}
for i=1, 107 do
-- Thresholds can be changed to be specific to each analog input
threshold[i] = 1.4
end
-- 1 = Rising edge, 0 = falling
local edge = {}
for i=1, 107 do
-- Sets all 107 counters to increment on falling edges
edge[i] = 0
end
local bits = {}
local newbits = {}
local count = {}
-- The throttle setting can correspond roughly with the length of the Lua
-- script. A rule of thumb for deciding a throttle setting is
-- Throttle = (3*NumLinesCode)+20. The default throttle setting is 10 instructions
local throttle = 40
set_lua_throttle(throttle)
throttle = get_lua_throttle()
print ("Current Lua Throttle Setting: ", throttle)
-- Set FIO registers to input
modbus_write(2600, 0, 0)
-- Set EIO registers to input
modbus_write(2601, 0, 0)
-- Set COI registers to input
modbus_write(2602, 0, 0)
-- Set MIO registers to input
modbus_write(2603, 0, 0)
-- Set AIN_ALL_RESOLUTION_INDEX to 1 (fastest setting)
modbus_write(43903, 0, 1)
for i=1, 107 do
bits[i] = 0
newbits[i] = 99
count[i] = 0
end
while true do
-- Analog channels AIN0-AIN3
for i=1, 4 do
-- If the channels value is above the threshold
if modbus_read((i-1)*2, 3) > threshold[i] then
newbits[i]=1
else
newbits[i]=0
end
end
-- Analog channels AIN107-AIN116
for i=5, 14 do
-- If the channels value is above the threshold
if modbus_read((i+102)*2, 3) > threshold[i] then
newbits[i]=1
else
newbits[i]=0
end
end
-- Digital channels DIO0-22
for i=15, 37 do
newbits[i] = modbus_read((i-15)+2000, 0)
end
-- Analog channels AIN117-AIN127
for i=38, 48 do
-- If the channels value is above the threshold
if modbus_read((i+79)*2, 3) > threshold[i] then
newbits[i]=1
else
newbits[i]=0
end
end
--Analog channels AIN48-AIN106
for i=49, 107 do
-- If the channels value is above the threshold
if modbus_read((i-1)*2, 3) > threshold[i] then
newbits[i]=1
else
newbits[i]=0
end
end
--Compare newbits to bits for each counter
for i=1, 107 do
-- If bits are different from newbits the counter state changed
if bits[i] ~= newbits[i] then
-- If the counter should increase on a rising edge
if edge[i] == 1 then
-- If the last counter state was 0 then there was a rising edge, increment
-- the counter
if bits[i] == 0 then
count[i] = count[i] + 1
print ("Counter: ", i-1, " Rising: ", count[i])
end
-- If the counter should increase on a falling edge
else
-- If the last counter state was 1 then there was a falling edge,
-- increment the counter
if bits[i] == 1 then
count[i] = count[i] + 1
print ("Counter: ", i-1, " Falling: ", count[i])
end
end
-- Adjust bits to reflect the new counter state
bits[i] = newbits[i]
-- Write the counter values to USER_RAM
-- Only the first 100 counters can be saved in User RAM
if i<100 then
modbus_write(((i-1)*2)+46000, 3, count[i])
end
end
end
end
|
Fixed up the formatting of the 107 counter example
|
Fixed up the formatting of the 107 counter example
|
Lua
|
mit
|
chrisJohn404/ljswitchboard-module_manager,chrisJohn404/ljswitchboard-module_manager,chrisJohn404/ljswitchboard-module_manager
|
38a6ea96d73d0e9a187983d90b85791d7d0c27dd
|
frontend/ui/widget/touchmenu.lua
|
frontend/ui/widget/touchmenu.lua
|
require "ui/widget/container"
require "ui/widget/group"
require "ui/widget/line"
require "ui/widget/iconbutton"
--[[
TouchMenuItem widget
--]]
TouchMenuItem = InputContainer:new{
menu = nil,
vertical_align = "center",
item = nil,
dimen = nil,
face = Font:getFace("cfont", 22),
}
function TouchMenuItem:init()
self.ges_events = {
TapSelect = {
GestureRange:new{
ges = "tap",
range = self.dimen,
},
doc = "Select Menu Item",
},
}
self.item_frame = FrameContainer:new{
width = self.dimen.w,
bordersize = 0,
color = 15,
HorizontalGroup:new {
align = "center",
HorizontalSpan:new{ width = 10 },
TextWidget:new{
text = self.item.text,
face = self.face,
},
},
}
self[1] = self.item_frame
end
function TouchMenuItem:onTapSelect(arg, ges)
self.item_frame.invert = true
UIManager:setDirty(self.menu, "partial")
UIManager:scheduleIn(0.5, function()
self.item_frame.invert = false
UIManager:setDirty(self.menu, "partial")
end)
self.menu:onMenuSelect(self.item)
return true
end
--[[
TouchMenuBar widget
--]]
TouchMenuBar = InputContainer:new{
height = 70,
width = Screen:getWidth(),
icon = {},
-- touch menu that holds the bar, used for trigger repaint on icons
parent = nil,
menu = nil,
}
function TouchMenuBar:init()
self.parent = self.parent or self
self.dimen = Geom:new{
w = self.width,
h = self.height,
}
local icon_sep = LineWidget:new{
dimen = Geom:new{
w = 2,
h = self.height,
}
}
local icon_span = HorizontalSpan:new{ width = 20 }
-- build up image widget for menu icon bar
self.icon_widgets = {}
-- the start_seg for first icon_widget should be 0
-- we asign negative here to offset it in the loop
start_seg = -icon_sep:getSize().w
end_seg = start_seg
for k, v in ipairs(self.icons) do
local ib = IconButton:new{
parent = self.parent,
icon_file = v,
callback = nil,
}
table.insert(self.icon_widgets, HorizontalGroup:new{
icon_span,
ib,
icon_span,
})
-- we have to use local variable here for closure callback
local _start_seg = end_seg + icon_sep:getSize().w
local _end_seg = _start_seg + self.icon_widgets[k]:getSize().w
if k == 1 then
self.bar_sep = LineWidget:new{
dimen = Geom:new{
w = self.width,
h = 2,
},
empty_segments = {
{
s = _start_seg, e = _end_seg
}
},
}
end
ib.callback = function()
self.bar_sep.empty_segments = {
{
s = _start_seg, e = _end_seg
}
}
self.menu:switchMenuTab(k)
end
start_seg = _start_seg
end_seg = _end_seg
end
self.bar_icon_group = HorizontalGroup:new{
self.icon_widgets[1],
icon_sep,
self.icon_widgets[2],
icon_sep,
}
self[1] = FrameContainer:new{
bordersize = 0,
padding = 0,
VerticalGroup:new{
align = "left",
-- bar icons
self.bar_icon_group,
-- separate line
self.bar_sep
},
}
end
--[[
TouchMenu widget
--]]
TouchMenu = InputContainer:new{
title = "Untitled",
item_table = {},
item_height = 50,
bordersize = 2,
padding = 5,
width = Screen:getWidth(),
height = nil,
page = 1,
max_per_page = 10,
-- for UIManager:setDirty
parent = nil,
cur_tab = 1,
close_callback = nil,
}
function TouchMenu:init()
self.parent = self.parent or self
if not self.close_callback then
self.close_callback = function()
UIManager:close(self.parent)
end
end
self.ges_events.TapCloseAllMenus = {
GestureRange:new{
ges = "tap",
range = Geom:new{
x = 0, y = 0,
w = Screen:getWidth(),
h = Screen:getHeight(),
}
}
}
local icons = {}
for _,v in ipairs(self.item_table) do
table.insert(icons, v.icon)
end
self.bar = TouchMenuBar:new{
width = self.width - self.padding * 2 - self.bordersize * 2,
icons = icons,
parent = self.parent,
menu = self,
}
self.item_group = VerticalGroup:new{}
self[1] = FrameContainer:new{
padding = self.padding,
bordersize = self.bordersize,
background = 0,
self.item_group
}
self:updateItems()
end
function TouchMenu:_recalculateDimen()
self.dimen.w = self.width
-- if height not given, dynamically calculate it
if not self.height then
self.dimen.h = (#self.item_table[self.cur_tab] + 2) * self.item_height
+ self.bar:getSize().h
else
self.dimen.h = self.height
end
if self.dimen.h > Screen:getHeight() then
self.dimen.h = Screen:getHeight()
end
self.perpage = math.floor(self.dimen.h / self.item_height) - 2
if self.perpage > self.max_per_page then
self.perpage = self.max_per_page
end
self.page_num = math.ceil(#self.item_table / self.perpage)
end
function TouchMenu:updateItems()
self:_recalculateDimen()
self.item_group:clear()
table.insert(self.item_group, self.bar)
local item_width = self.dimen.w - self.padding*2 - self.bordersize*2
local item_table = self.item_table[self.cur_tab]
for c = 1, self.perpage do
-- calculate index in item_table
local i = (self.page - 1) * self.perpage + c
if i <= #item_table then
local item_tmp = TouchMenuItem:new{
item = item_table[i],
menu = self,
dimen = Geom:new{
w = item_width,
h = self.item_height,
},
}
table.insert(self.item_group, item_tmp)
-- insert split line
if c ~= self.perpage then
table.insert(self.item_group, LineWidget:new{
style = "dashed",
dimen = Geom:new{
w = item_width - 20,
h = 1,
}
})
end
else
-- item not enough to fill the whole page, break out of loop
table.insert(self.item_group,
VerticalSpan:new{
width = self.item_height
})
break
end -- if i <= self.items
end -- for c=1, self.perpage
-- FIXME: this is a dirty hack to clear previous menus
-- refert to issue #664
UIManager.repaint_all = true
end
function TouchMenu:switchMenuTab(tab_num)
if self.cur_tab ~= tab_num then
self.cur_tab = tab_num
self:updateItems()
end
return true
end
function TouchMenu:closeMenu()
self.close_callback()
end
function TouchMenu:onMenuSelect(item)
if item.sub_item_table == nil then
self:closeMenu()
if item.callback then
item.callback()
end
end
return true
end
function TouchMenu:onTapCloseAllMenus(arg, ges_ev)
if ges_ev.pos:notIntersectWith(self.dimen) then
self:closeMenu()
return true
end
end
|
require "ui/widget/container"
require "ui/widget/group"
require "ui/widget/line"
require "ui/widget/iconbutton"
--[[
TouchMenuItem widget
--]]
TouchMenuItem = InputContainer:new{
menu = nil,
vertical_align = "center",
item = nil,
dimen = nil,
face = Font:getFace("cfont", 22),
parent = nil,
}
function TouchMenuItem:init()
self.ges_events = {
TapSelect = {
GestureRange:new{
ges = "tap",
range = self.dimen,
},
doc = "Select Menu Item",
},
}
self.item_frame = FrameContainer:new{
width = self.dimen.w,
bordersize = 0,
color = 15,
HorizontalGroup:new {
align = "center",
HorizontalSpan:new{ width = 10 },
TextWidget:new{
text = self.item.text,
face = self.face,
},
},
}
self[1] = self.item_frame
end
function TouchMenuItem:onTapSelect(arg, ges)
self.item_frame.invert = true
UIManager:setDirty(self.parent, "partial")
UIManager:scheduleIn(0.5, function()
self.item_frame.invert = false
UIManager:setDirty(self.parent, "partial")
end)
self.menu:onMenuSelect(self.item)
return true
end
--[[
TouchMenuBar widget
--]]
TouchMenuBar = InputContainer:new{
height = 70,
width = Screen:getWidth(),
icons = {},
-- touch menu that holds the bar, used for trigger repaint on icons
parent = nil,
menu = nil,
}
function TouchMenuBar:init()
self.parent = self.parent or self
self.dimen = Geom:new{
w = self.width,
h = self.height,
}
self.bar_icon_group = HorizontalGroup:new{}
local icon_sep = LineWidget:new{
dimen = Geom:new{
w = 2,
h = self.height,
}
}
local icon_span = HorizontalSpan:new{ width = 20 }
-- build up image widget for menu icon bar
self.icon_widgets = {}
-- the start_seg for first icon_widget should be 0
-- we asign negative here to offset it in the loop
start_seg = -icon_sep:getSize().w
end_seg = start_seg
for k, v in ipairs(self.icons) do
local ib = IconButton:new{
parent = self.parent,
icon_file = v,
callback = nil,
}
table.insert(self.icon_widgets, HorizontalGroup:new{
icon_span,
ib,
icon_span,
})
-- we have to use local variable here for closure callback
local _start_seg = end_seg + icon_sep:getSize().w
local _end_seg = _start_seg + self.icon_widgets[k]:getSize().w
if k == 1 then
self.bar_sep = LineWidget:new{
dimen = Geom:new{
w = self.width,
h = 2,
},
empty_segments = {
{
s = _start_seg, e = _end_seg
}
},
}
end
ib.callback = function()
self.bar_sep.empty_segments = {
{
s = _start_seg, e = _end_seg
}
}
self.menu:switchMenuTab(k)
end
table.insert(self.bar_icon_group, self.icon_widgets[k])
table.insert(self.bar_icon_group, icon_sep)
start_seg = _start_seg
end_seg = _end_seg
end
self[1] = FrameContainer:new{
bordersize = 0,
padding = 0,
VerticalGroup:new{
align = "left",
-- bar icons
self.bar_icon_group,
-- separate line
self.bar_sep
},
}
end
--[[
TouchMenu widget
--]]
TouchMenu = InputContainer:new{
item_table = {},
item_height = 50,
bordersize = 2,
padding = 5,
width = Screen:getWidth(),
height = nil,
page = 1,
max_per_page = 10,
-- for UIManager:setDirty
parent = nil,
cur_tab = 1,
close_callback = nil,
}
function TouchMenu:init()
self.parent = self.parent or self
if not self.close_callback then
self.close_callback = function()
UIManager:close(self.parent)
end
end
self.ges_events.TapCloseAllMenus = {
GestureRange:new{
ges = "tap",
range = Geom:new{
x = 0, y = 0,
w = Screen:getWidth(),
h = Screen:getHeight(),
}
}
}
local icons = {}
for _,v in ipairs(self.item_table) do
table.insert(icons, v.icon)
end
self.bar = TouchMenuBar:new{
width = self.width - self.padding * 2 - self.bordersize * 2,
icons = icons,
parent = self.parent,
menu = self,
}
self.item_group = VerticalGroup:new{}
self[1] = FrameContainer:new{
padding = self.padding,
bordersize = self.bordersize,
background = 0,
self.item_group
}
self:updateItems()
end
function TouchMenu:_recalculateDimen()
self.dimen.w = self.width
-- if height not given, dynamically calculate it
if not self.height then
self.dimen.h = (#self.item_table[self.cur_tab] + 2) * self.item_height
+ self.bar:getSize().h
else
self.dimen.h = self.height
end
if self.dimen.h > Screen:getHeight() then
self.dimen.h = Screen:getHeight()
end
self.perpage = math.floor(self.dimen.h / self.item_height) - 2
if self.perpage > self.max_per_page then
self.perpage = self.max_per_page
end
self.page_num = math.ceil(#self.item_table / self.perpage)
end
function TouchMenu:updateItems()
self:_recalculateDimen()
self.item_group:clear()
table.insert(self.item_group, self.bar)
local item_width = self.dimen.w - self.padding*2 - self.bordersize*2
local item_table = self.item_table[self.cur_tab]
for c = 1, self.perpage do
-- calculate index in item_table
local i = (self.page - 1) * self.perpage + c
if i <= #item_table then
local item_tmp = TouchMenuItem:new{
item = item_table[i],
menu = self,
dimen = Geom:new{
w = item_width,
h = self.item_height,
},
parent = self.parent,
}
table.insert(self.item_group, item_tmp)
-- insert split line
if c ~= self.perpage then
table.insert(self.item_group, LineWidget:new{
style = "dashed",
dimen = Geom:new{
w = item_width - 20,
h = 1,
}
})
end
else
-- item not enough to fill the whole page, break out of loop
table.insert(self.item_group,
VerticalSpan:new{
width = self.item_height
})
break
end -- if i <= self.items
end -- for c=1, self.perpage
-- FIXME: this is a dirty hack to clear previous menus
-- refert to issue #664
UIManager.repaint_all = true
end
function TouchMenu:switchMenuTab(tab_num)
if self.cur_tab ~= tab_num then
self.cur_tab = tab_num
self:updateItems()
end
return true
end
function TouchMenu:closeMenu()
self.close_callback()
end
function TouchMenu:onMenuSelect(item)
if item.sub_item_table == nil then
self:closeMenu()
if item.callback then
item.callback()
end
end
return true
end
function TouchMenu:onTapCloseAllMenus(arg, ges_ev)
if ges_ev.pos:notIntersectWith(self.dimen) then
self:closeMenu()
return true
end
end
|
fix: set parent on TouchMenuItem
|
fix: set parent on TouchMenuItem
|
Lua
|
agpl-3.0
|
koreader/koreader,apletnev/koreader-base,Hzj-jie/koreader,frankyifei/koreader-base,Hzj-jie/koreader-base,pazos/koreader,mihailim/koreader,apletnev/koreader-base,NiLuJe/koreader,Frenzie/koreader,frankyifei/koreader-base,NiLuJe/koreader,Frenzie/koreader-base,koreader/koreader,chihyang/koreader,poire-z/koreader,koreader/koreader-base,NiLuJe/koreader-base,apletnev/koreader-base,houqp/koreader-base,NiLuJe/koreader-base,apletnev/koreader-base,koreader/koreader-base,NickSavage/koreader,Hzj-jie/koreader-base,ashhher3/koreader,houqp/koreader,lgeek/koreader,Frenzie/koreader-base,Markismus/koreader,houqp/koreader-base,robert00s/koreader,poire-z/koreader,apletnev/koreader,noname007/koreader,Hzj-jie/koreader-base,NiLuJe/koreader-base,Hzj-jie/koreader-base,houqp/koreader-base,houqp/koreader-base,mwoz123/koreader,Frenzie/koreader-base,ashang/koreader,Frenzie/koreader-base,koreader/koreader-base,NiLuJe/koreader-base,frankyifei/koreader-base,koreader/koreader-base,frankyifei/koreader,Frenzie/koreader,chrox/koreader,frankyifei/koreader-base
|
761a00ae3e526bd54d2be649086dc7f9540c2be8
|
MMOCoreORB/bin/scripts/object/draft_schematic/furniture/furniture_tatooine_tapestry.lua
|
MMOCoreORB/bin/scripts/object/draft_schematic/furniture/furniture_tatooine_tapestry.lua
|
--Copyright (C) 2010 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 2 of the License,
--or (at your option) any later version.
--This program is distributed in the hope that it will be useful,
--but WITHOUT ANY WARRANTY; without even the implied warranty of
--MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
--See the GNU Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
object_draft_schematic_furniture_furniture_tatooine_tapestry = object_draft_schematic_furniture_shared_furniture_tatooine_tapestry:new {
templateType = DRAFTSCHEMATIC,
customObjectName = "Tapestry (Tatooine) Draft Schematic",
craftingToolTab = 512, -- (See DraftSchemticImplementation.h)
complexity = 18,
size = 1,
xpType = "crafting_clothing_general",
xp = 340,
assemblySkill = "clothing_assembly",
experimentingSkill = "clothing_experimentation",
customizationSkill = "clothing_customization",
customizationOptions = {},
customizationStringNames = {},
customizationDefaults = {},
ingredientTemplateNames = {"craft_furniture_ingredients_n", "craft_furniture_ingredients_n", "craft_item_ingredients_n"},
ingredientTitleNames = {"flag_base", "flag", "paints"},
ingredientSlotType = {0, 0, 0},
resourceTypes = {"metal", "fiberplast", "petrochem_inert_polymer"},
resourceQuantities = {30, 80, 25},
contribution = {100, 100, 100},
targetTemplate = "object/tangible/furniture/decorative/tatooine_tapestry.iff",
additionalTemplates = {
}
}
ObjectTemplates:addTemplate(object_draft_schematic_furniture_furniture_tatooine_tapestry, "object/draft_schematic/furniture/furniture_tatooine_tapestry.iff")
|
--Copyright (C) 2010 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 2 of the License,
--or (at your option) any later version.
--This program is distributed in the hope that it will be useful,
--but WITHOUT ANY WARRANTY; without even the implied warranty of
--MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
--See the GNU Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
object_draft_schematic_furniture_furniture_tatooine_tapestry = object_draft_schematic_furniture_shared_furniture_tatooine_tapestry:new {
templateType = DRAFTSCHEMATIC,
customObjectName = "Tapestry (Tatooine) Draft Schematic",
craftingToolTab = 512, -- (See DraftSchemticImplementation.h)
complexity = 18,
size = 1,
xpType = "crafting_clothing_general",
xp = 340,
disableFactoryRun = true,
assemblySkill = "clothing_assembly",
experimentingSkill = "clothing_experimentation",
customizationSkill = "clothing_customization",
customizationOptions = {},
customizationStringNames = {},
customizationDefaults = {},
ingredientTemplateNames = {"craft_furniture_ingredients_n", "craft_furniture_ingredients_n", "craft_item_ingredients_n"},
ingredientTitleNames = {"flag_base", "flag", "paints"},
ingredientSlotType = {0, 0, 0},
resourceTypes = {"metal", "fiberplast", "petrochem_inert_polymer"},
resourceQuantities = {30, 80, 25},
contribution = {100, 100, 100},
targetTemplate = "object/tangible/furniture/decorative/tatooine_tapestry.iff",
additionalTemplates = {
}
}
ObjectTemplates:addTemplate(object_draft_schematic_furniture_furniture_tatooine_tapestry, "object/draft_schematic/furniture/furniture_tatooine_tapestry.iff")
|
[fixed] disabled factory runs on tatooine tapestry loot schem
|
[fixed] disabled factory runs on tatooine tapestry loot schem
Change-Id: I4560c96e9b18bc6e509797bb37a2434eb8e1a111
|
Lua
|
agpl-3.0
|
lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/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
|
530f6547b7ac51047f9b8bfa29e8e49bd2baed66
|
test/dump.lua
|
test/dump.lua
|
local ipairs = ipairs
local pairs = pairs
local tostring = tostring
local type = type
local format = string.format
local huge = 1/0
local tiny = -1/0
local function dump(v)
local builder = {}
local i = 1
local depth = 0
local depth8 = 1
local view = 1
local usestack
local vars = {'v1', 'v2', 'v3', 'v4', 'v5', 'v6', 'v7', 'v8'}
local vars2 = {'v1[', 'v2[', 'v3[', 'v4[', 'v5[', 'v6[', 'v7[', 'v8['}
local var = 'v1'
local var2 = 'v1['
local function incdepth()
depth = depth+1
if depth > 1 then
depth8 = depth8+1
if depth8 > 8 then
depth8 = 1
end
var = vars[depth8]
var2 = vars2[depth8]
if depth >= view+8 then
usestack = true
view = view+1
builder[i] = 'stack['
builder[i+1] = depth-8
builder[i+2] = ']='
builder[i+3] = var
builder[i+4] = '\n'
i = i+5
end
end
end
local function decdepth()
depth = depth-1
if depth > 0 then
depth8 = depth8-1
if depth8 < 1 then
depth8 = 8
end
var = vars[depth8]
var2 = vars2[depth8]
if depth < view then
view = view-1
builder[i] = var
builder[i+1] = '=stack['
builder[i+2] = depth
builder[i+3] = ']\n'
i = i+4
end
end
end
local visited = {}
local tablefun, tbl
local function tableelem(k, v, kt)
do
local vt = type(v)
if vt ~= 'table' then
local e = tbl[vt](v)
builder[i] = var2
builder[i+1] = k
builder[i+2] = ']='
builder[i+3] = e
builder[i+4] = '\n'
i = i+5
return
end
end
do
local olddepth = visited[o]
if olddepth then
builder[i] = var
builder[i+1] = '='
if olddepth >= view then
builder[i+2] = vars[olddepth%8]
else
builder[i+2] = 'stack['..olddepth..']'
end
builder[i+3] = '\n'
i = i+4
return
end
end
if kt == 'table' then
builder[i] = 'vtmp={}\n'
builder[i+1] = var2
builder[i+2] = k
builder[i+3] = ']=vtmp\n'
incdepth()
builder[i+4] = var
builder[i+5] = '=vtmp\n'
i = i+6
else
local oldvar2 = var2
incdepth()
builder[i] = var
builder[i+1] = '={}\n'
builder[i+2] = oldvar2
builder[i+3] = k
builder[i+4] = ']='
builder[i+5] = var
builder[i+6] = '\n'
i = i+7
end
tablefun(v)
decdepth()
end
function tablefun(o)
local l = 0
for j, v in ipairs(o) do
l = j
tableelem(j, v, 'number')
end
for k, v in pairs(o) do
local kt = type(k)
if kt ~= 'number' or k < 1 or k > l then
local kt = type(k)
k = tbl[kt](k)
tableelem(k, v, kt)
end
end
end
tbl = {
boolean = tostring,
table = function(o)
do
local olddepth = visited[o]
if olddepth then
if olddepth >= view then
return vars[olddepth%8]
else
return 'stack['..olddepth..']'
end
end
end
incdepth()
visited[o] = depth
builder[i] = var
builder[i+1] = '={}\n'
i = i+2
tablefun(o)
local oldvar = var
visited[o] = nil
decdepth()
return oldvar
end,
string = function(s)
return format('%q', s)
end,
number = function(n)
if tiny < n and n < huge then
return format('%.17g', n)
elseif n == huge then
return '1/0'
elseif n == tiny then
return '-1/0'
else
return '0/0'
end
end,
__index = function(_)
error("illegal val")
end
}
setmetatable(tbl, tbl)
builder[i] = 'local '
i = i+1
for j = 1, 8 do
builder[i] = vars[j]
builder[i+1] = ','
i = i+2
end
builder[i] = 'vtmp\n'
i = i+1
local stackdecl = i
builder[i] = ""
i = i+1
local e = tbl[type(v)](v)
builder[i] = 'return '
builder[i+1] = e
i = i+2
if usestack then
builder[stackdecl] = 'local stack={}\n'
i = i+1
end
return table.concat(builder)
end
return dump
|
local ipairs = ipairs
local pairs = pairs
local tostring = tostring
local type = type
local format = string.format
local huge = 1/0
local tiny = -1/0
local function dump(v)
local builder = {}
local i = 1
local depth = 0
local depth8 = 1
local view = 1
local usestack
local vars = {'v1', 'v2', 'v3', 'v4', 'v5', 'v6', 'v7', 'v8', 'v1'}
local vars2 = {'v1[', 'v2[', 'v3[', 'v4[', 'v5[', 'v6[', 'v7[', 'v8['}
local var = 'v1'
local nextvar = 'v2'
local var2 = 'v1['
local nextvar2 = 'v2['
local function incdepth()
depth = depth+1
if depth > 1 then
depth8 = depth8+1
if depth8 > 8 then
depth8 = 0
end
var = nextvar
nextvar = vars[depth8+1]
var2 = vars2[depth8]
if depth >= view+8 then
usestack = true
view = view+1
builder[i] = 'stack['
builder[i+1] = depth-8
builder[i+2] = ']='
builder[i+3] = var
builder[i+4] = '\n'
i = i+5
end
end
end
local function decdepth()
depth = depth-1
if depth > 0 then
depth8 = depth8-1
if depth8 < 1 then
depth8 = 8
end
nextvar = var
var = vars[depth8]
nextvar2 = var2
var2 = vars2[depth8]
if depth < view then
view = view-1
builder[i] = var
builder[i+1] = '=stack['
builder[i+2] = depth
builder[i+3] = ']\n'
i = i+4
end
end
end
local visited = {}
local tablefun, tbl
local function tableelem(k, v)
do
local vt = type(v)
if vt ~= 'table' then
local e = tbl[vt](v)
builder[i] = var2
builder[i+1] = k
builder[i+2] = ']='
builder[i+3] = e
builder[i+4] = '\n'
i = i+5
return
end
end
do
local olddepth = visited[v]
if olddepth then
builder[i] = var2
builder[i+1] = k
builder[i+2] = ']='
if olddepth >= view then
builder[i+3] = vars[olddepth%8]
else
builder[i+3] = 'stack['..olddepth..']'
end
builder[i+4] = '\n'
i = i+5
return
end
end
do
local oldvar2 = var2
incdepth()
visited[v] = depth
if kt == nextvar then
builder[i] = 'vtmp={}\n'
builder[i+1] = oldvar2
builder[i+2] = k
builder[i+3] = ']=vtmp\n'
builder[i+4] = var
builder[i+5] = '=vtmp\n'
i = i+6
else
builder[i] = var
builder[i+1] = '={}\n'
builder[i+2] = oldvar2
builder[i+3] = k
builder[i+4] = ']='
builder[i+5] = var
builder[i+6] = '\n'
i = i+7
end
end
tablefun(v)
visited[v] = nil
decdepth()
end
function tablefun(o)
local l = 0
for j, v in ipairs(o) do
l = j
tableelem(j, v)
end
for k, v in pairs(o) do
local kt = type(k)
if kt ~= 'number' or k < 1 or k > l then
k = tbl[kt](k)
tableelem(k, v)
end
end
end
tbl = {
boolean = tostring,
table = function(o)
do
local olddepth = visited[o]
if olddepth then
if olddepth >= view then
return vars[olddepth%8]
else
return 'stack['..olddepth..']'
end
end
end
incdepth()
visited[o] = depth
builder[i] = var
builder[i+1] = '={}\n'
i = i+2
tablefun(o)
visited[o] = nil
decdepth()
return nextvar
end,
string = function(s)
return format('%q', s)
end,
number = function(n)
if tiny < n and n < huge then
return format('%.17g', n)
elseif n == huge then
return '1/0'
elseif n == tiny then
return '-1/0'
else
return '0/0'
end
end,
__index = function(_)
error("illegal val")
end
}
setmetatable(tbl, tbl)
builder[i] = 'local '
i = i+1
for j = 1, 8 do
builder[i] = vars[j]
builder[i+1] = ','
i = i+2
end
builder[i] = 'vtmp\n'
i = i+1
local stackdecl = i
builder[i] = ""
i = i+1
local e = tbl[type(v)](v)
builder[i] = 'return '
builder[i+1] = e
i = i+2
if usestack then
builder[stackdecl] = 'local stack={}\n'
i = i+1
end
return table.concat(builder)
end
return dump
|
fix loop detection of dump.lua
|
fix loop detection of dump.lua
|
Lua
|
mit
|
grafi-tt/lunajson,bigcrush/lunajson,tst2005/lunajson,csteddy/lunajson,bigcrush/lunajson,grafi-tt/lunajson,grafi-tt/lunajson,tst2005/lunajson,csteddy/lunajson
|
aa8567aac171d30261ecd0ec925773d7c170d86f
|
xmake/repository/packages/a/automake/xmake.lua
|
xmake/repository/packages/a/automake/xmake.lua
|
package("automake")
set_kind("binary")
set_homepage("https://www.gnu.org/software/automake/")
set_description("A tool for automatically generating Makefile.in files compliant with the GNU Coding Standards.")
if is_host("macosx", "linux") then
add_urls("http://ftp.gnu.org/gnu/automake/automake-$(version).tar.gz",
"https://mirrors.ustc.edu.cn/gnu/automake/automake-$(version).tar.gz")
add_versions("1.16.1", "608a97523f97db32f1f5d5615c98ca69326ced2054c9f82e65bade7fc4c9dea8")
add_versions("1.15.1", "988e32527abe052307d21c8ca000aa238b914df363a617e38f4fb89f5abf6260")
add_versions("1.9.6", "e6d3030dd3f7a07ee2075da5f77864a3cc3e78c5bf76bb48df23dbe3d6ba13b9")
add_versions("1.9.5", "68712753fcb756f3707b7da554917afb348450eb8530cae3b623a067078596fd")
end
on_install("macosx", "linux", function (package)
import("package.tools.autoconf").install(package)
end)
on_test(function (package)
os.vrun("automake --version")
end)
|
package("automake")
set_kind("binary")
set_homepage("https://www.gnu.org/software/automake/")
set_description("A tool for automatically generating Makefile.in files compliant with the GNU Coding Standards.")
if is_host("macosx", "linux") then
add_urls("http://ftp.gnu.org/gnu/automake/automake-$(version).tar.gz",
"https://mirrors.ustc.edu.cn/gnu/automake/automake-$(version).tar.gz")
add_versions("1.16.1", "608a97523f97db32f1f5d5615c98ca69326ced2054c9f82e65bade7fc4c9dea8")
add_versions("1.15.1", "988e32527abe052307d21c8ca000aa238b914df363a617e38f4fb89f5abf6260")
add_versions("1.9.6", "e6d3030dd3f7a07ee2075da5f77864a3cc3e78c5bf76bb48df23dbe3d6ba13b9")
add_versions("1.9.5", "68712753fcb756f3707b7da554917afb348450eb8530cae3b623a067078596fd")
end
on_install("macosx", "linux", function (package)
import("package.tools.autoconf").install(package)
io.writefile(path.join(package:installdir("share", "aclocal"), "dirlist"), [[
/usr/local/share/aclocal
/usr/share/aclocal
]])
end)
on_test(function (package)
os.vrun("automake --version")
end)
|
fix automake install script
|
fix automake install script
|
Lua
|
apache-2.0
|
tboox/xmake,tboox/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,tboox/xmake,tboox/xmake,tboox/xmake,waruqi/xmake,tboox/xmake,tboox/xmake,waruqi/xmake
|
305daf860b11f36a51a943594c637b39f79efa87
|
trovebox.lua
|
trovebox.lua
|
dofile("urlcode.lua")
dofile("table_show.lua")
local url_count = 0
local tries = 0
local item_type = os.getenv('item_type')
local item_value = os.getenv('item_value')
local downloaded = {}
local addedtolist = {}
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 downloaded[url] == true or addedtolist[url] == true then
return false
end
if item_type == "site" and (downloaded[url] ~= true and addedtolist[url] ~= true) then
if string.match(url, item_value) then
return verdict
elseif html == 0 then
return verdict
else
return false
end
end
end
wget.callbacks.get_urls = function(file, url, is_css, iri)
local urls = {}
local html = nil
local function check(url)
if (downloaded[url] ~= true and addedtolist[url] ~= true) then
table.insert(urls, { url=url })
addedtolist[url] = true
end
end
if item_type == "site" then
if string.match(url, "%?") then
newurl = string.match(url, "(https://[^%?]+)%?")
check(newurl)
end
if string.match(url, item_value.."%.trovebox%.com") and not string.match(url, "%.jpg") then
html = read_file(file)
for newurl in string.gmatch(html, '"(https?://[^"]+)"') do
if string.match(newurl, "\/") then
newnewurl = string.gsub(newurl, "\/", "/")
check(newnewurl)
elseif string.match(newurl, item_value) or string.match(newurl, "%.jpg") or string.match(newurl, "%.png") or string.match(url, "%.cloudfront%.com") then
check(newurl)
end
end
for newurl2 in string.gmatch(html, '"(%?[^"]+)"') then
newurl1 = string.match(url, "(https?://[^%?]+)%?")
newurl = newurl1..newurl2
check(newurl)
end
for newurl2 in string.gmatch(html, '"(/[^"]+)"') do
if not string.match(newurl2, "%%") then
newurl1 = string.match(url, "(https?://[^/]+)/")
newurl = newurl1..newurl2
check(newurl)
end
end
if string.match(url, "%.trovebox%.com/p/[0-9a-zA-Z][0-9a-zA-Z][0-9a-zA-Z]") then
photoid = string.match(url, "%.trovebox%.com/p/([0-9a-zA-Z][0-9a-zA-Z][0-9a-zA-Z])")
for newphotoid in string.gmatch(html, '"id":"([0-9a-zA-Z][0-9a-zA-Z][0-9a-zA-Z])"') do
newurl = string.gsub(url, "/p/"..photoid, "/p/"..newphotoid)
check(newurl)
end
end
if string.match(url, "%.trovebox%.com/albums/") then
for newalbum in string.gmatch(html, '"id":"([0-9a-zA-Z][0-9a-zA-Z])"') do
https://opensourceecology.trovebox.com/photos/album-23/list
newurl = string.gsub(url, "/albums/", "/photos/album%-"..newalbum.."/list")
check(newurl)
end
end
if string.match(url, "%.trovebox%.com/photos/album%-[0-9a-zA-Z][0-9a-zA-Z]/list") then
albumid = string.match(url, "%.trovebox%.com/photos/album%-([0-9a-zA-Z][0-9a-zA-Z])")
for photoid in string.gmatch(html, '"id":"([0-9a-zA-Z][0-9a-zA-Z][0-9a-zA-Z])"')
newurl = "https://"..item_value..".trovebox.com/p/"..photoid.."/album-"..albumid
newurl0 = "https://"..item_value..".trovebox.com/p/"..photoid
newurl1 = "https://"..item_value..".trovebox.com/p/"..photoid.."/album-"..albumid.."?sortBy=dateTaken,asc"
newurl2 = "https://"..item_value..".trovebox.com/p/"..photoid.."/album-"..albumid.."?sortBy=dateTaken,desc"
newurl3 = "https://"..item_value..".trovebox.com/p/"..photoid.."/album-"..albumid.."?sortBy=dateUploaded,asc"
newurl4 = "https://"..item_value..".trovebox.com/p/"..photoid.."/album-"..albumid.."?sortBy=dateUploaded,desc"
check(newurl)
check(newurl0)
check(newurl1)
check(newurl2)
check(newurl3)
check(newurl4)
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
local status_code = http_stat["statcode"]
last_http_statcode = status_code
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) then
if string.match(url["url"], "https://") then
local newurl = string.gsub(url["url"], "https://", "http://")
downloaded[newurl] = true
else
downloaded[url["url"]] = true
end
end
if status_code >= 500 or
(status_code >= 400 and status_code ~= 404) then
io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n")
io.stdout:flush()
os.execute("sleep 5")
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(500, 5000) / 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")
local url_count = 0
local tries = 0
local item_type = os.getenv('item_type')
local item_value = os.getenv('item_value')
local downloaded = {}
local addedtolist = {}
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"]
if downloaded[url] == true or addedtolist[url] == true then
return false
end
if item_type == "site" and (downloaded[url] ~= true and addedtolist[url] ~= true) then
if string.match(url, item_value) then
return verdict
elseif html == 0 then
return verdict
else
return false
end
end
end
wget.callbacks.get_urls = function(file, url, is_css, iri)
local urls = {}
local html = nil
local function check(url)
if (downloaded[url] ~= true and addedtolist[url] ~= true) then
table.insert(urls, { url=url })
addedtolist[url] = true
end
end
if item_type == "site" then
if string.match(url, "%?") then
local newurl = string.match(url, "(https://[^%?]+)%?")
check(newurl)
end
if string.match(url, "https?://[^%.]+%.trovebox%.com") and not string.match(url, "%.jpg") then
html = read_file(file)
for newurl in string.gmatch(html, '"(https?://[^"]+)"') do
if string.match(newurl, "\/") then
local newnewurl = string.gsub(newurl, "\/", "/")
check(newnewurl)
elseif string.match(newurl, item_value) or string.match(newurl, "%.jpg") or string.match(newurl, "%.png") or string.match(url, "%.cloudfront%.com") then
check(newurl)
end
end
for newurl2 in string.gmatch(html, '"(%?[^"]+)"') then
local newurl1 = string.match(url, "(https?://[^%?]+)%?")
local newurl = newurl1..newurl2
check(newurl)
end
for newurl2 in string.gmatch(html, '"(/[^"]+)"') do
if not string.match(newurl2, "%%") then
local newurl1 = string.match(url, "(https?://[^/]+)/")
local newurl = newurl1..newurl2
check(newurl)
end
end
if string.match(url, "%.trovebox%.com/p/[0-9a-zA-Z][0-9a-zA-Z][0-9a-zA-Z]") then
local photoid = string.match(url, "%.trovebox%.com/p/([0-9a-zA-Z][0-9a-zA-Z][0-9a-zA-Z])")
for newphotoid in string.gmatch(html, '"id":"([0-9a-zA-Z][0-9a-zA-Z][0-9a-zA-Z])"') do
local newurl = string.gsub(url, "/p/"..photoid, "/p/"..newphotoid)
check(newurl)
end
end
if string.match(url, "%.trovebox%.com/albums/") then
for newalbum in string.gmatch(html, '"id":"([0-9a-zA-Z][0-9a-zA-Z])"') do
local newurl = string.gsub(url, "/albums/", "/photos/album%-"..newalbum.."/list")
check(newurl)
end
end
if string.match(url, "%.trovebox%.com/photos/album%-[0-9a-zA-Z][0-9a-zA-Z]/list") then
local albumid = string.match(url, "%.trovebox%.com/photos/album%-([0-9a-zA-Z][0-9a-zA-Z])")
for photoid in string.gmatch(html, '"id":"([0-9a-zA-Z][0-9a-zA-Z][0-9a-zA-Z])"')
local newurl = "https://"..item_value..".trovebox.com/p/"..photoid.."/album-"..albumid
local newurl0 = "https://"..item_value..".trovebox.com/p/"..photoid
local newurl1 = "https://"..item_value..".trovebox.com/p/"..photoid.."/album-"..albumid.."?sortBy=dateTaken,asc"
local newurl2 = "https://"..item_value..".trovebox.com/p/"..photoid.."/album-"..albumid.."?sortBy=dateTaken,desc"
local newurl3 = "https://"..item_value..".trovebox.com/p/"..photoid.."/album-"..albumid.."?sortBy=dateUploaded,asc"
local newurl4 = "https://"..item_value..".trovebox.com/p/"..photoid.."/album-"..albumid.."?sortBy=dateUploaded,desc"
check(newurl)
check(newurl0)
check(newurl1)
check(newurl2)
check(newurl3)
check(newurl4)
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
local status_code = http_stat["statcode"]
last_http_statcode = status_code
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) then
if string.match(url["url"], "https://") then
local newurl = string.gsub(url["url"], "https://", "http://")
downloaded[newurl] = true
else
downloaded[url["url"]] = true
end
end
if status_code >= 500 or
(status_code >= 400 and status_code ~= 404) then
io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n")
io.stdout:flush()
os.execute("sleep 5")
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(500, 5000) / 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
|
trovebox.lua: fixes
|
trovebox.lua: fixes
|
Lua
|
unlicense
|
ArchiveTeam/trovebox-grab,ArchiveTeam/trovebox-grab
|
85c82ce1a63eec639fa8a24fa7b6d46e6c44ee1d
|
lunamark/writer/man.lua
|
lunamark/writer/man.lua
|
-- (c) 2009-2011 John MacFarlane. Released under MIT license.
-- See the file LICENSE in the source for details.
--- Groff man writer for lunamark.
-- Extends [lunamark.writer.groff].
--
-- Note: continuation paragraphs in lists are not
-- handled properly.
local M = {}
local groff = require("lunamark.writer.groff")
local util = require("lunamark.util")
local gsub = string.gsub
local format = string.format
--- Returns a new groff writer.
-- For a list of fields, see [lunamark.writer.generic].
function M.new(options)
local options = options or {}
local Man = groff.new(options)
local endnotes = {}
function Man.link(lab,src,tit)
return {lab," (",src,")"}
end
function Man.image(lab,src,tit)
return {"[IMAGE (",lab,")]"}
end
-- TODO handle continuations properly.
-- pandoc does this:
-- .IP \[bu] 2
-- one
-- .RS 2
-- .PP
-- cont
-- .RE
function Man.paragraph(contents)
return {".PP\n",contents}
end
function Man.bulletlist(items,tight)
local buffer = {}
for _,item in ipairs(items) do
buffer[#buffer + 1] = {".IP \\[bu] 2\n",item}
end
return util.intersperse(buffer, Man.containersep)
end
function Man.orderedlist(items,tight,startnum)
local buffer = {}
local num = startnum or 1
for _,item in ipairs(items) do
buffer[#buffer + 1] = {format(".IP \"%d.\" 4\n",num),item}
num = num + 1
end
return util.intersperse(buffer, Man.containersep)
end
function Man.blockquote(s)
return {".RS\n",s,"\n.RE"}
end
function Man.verbatim(s)
return {".IP\n.nf\n\\f[C]\n",s,".fi"}
end
function Man.header(s,level)
local hcode = ".SS"
if level == 1 then hcode = ".SH" end
return {hcode," ",s}
end
Man.hrule = ".PP\n * * * * *"
function Man.note(contents)
local num = #endnotes + 1
endnotes[num] = {format(".SS [%d]\n",num),contents}
return format('[%d]', num)
end
function Man.definitionlist(items,tight)
local buffer = {}
local ds
for _,item in ipairs(items) do
if tight then
ds = util.intersperse(item.definitions,"\n.RS\n.RE\n")
buffer[#buffer + 1] = {".TP\n.B ",item.term,"\n",ds,"\n.RS\n.RE"}
else
ds = util.intersperse(item.definitions,"\n.RS\n.RE\n")
buffer[#buffer + 1] = {".TP\n.B ",item.term,"\n.RS\n",ds,"\n.RE"}
end
end
local contents = util.intersperse(buffer,"\n")
return contents
end
function Man.start_document()
endnotes = {}
return ""
end
function Man.stop_document()
if #endnotes == 0 then
return ""
else
return {"\n.SH NOTES\n", util.intersperse(endnotes, "\n")}
end
end
Man.template = [===[
.TH "$title" "$section" "$date" "$left_footer" "$center_header"
$body
]===]
return Man
end
return M
|
-- (c) 2009-2011 John MacFarlane. Released under MIT license.
-- See the file LICENSE in the source for details.
--- Groff man writer for lunamark.
-- Extends [lunamark.writer.groff].
--
-- Note: continuation paragraphs in lists are not
-- handled properly.
local M = {}
local groff = require("lunamark.writer.groff")
local util = require("lunamark.util")
local gsub = string.gsub
local format = string.format
--- Returns a new groff writer.
-- For a list of fields, see [lunamark.writer.generic].
function M.new(options)
local options = options or {}
local Man = groff.new(options)
local endnotes = {}
function Man.link(lab,src,tit)
return {lab," (",src,")"}
end
function Man.image(lab,src,tit)
return {"[IMAGE (",lab,")]"}
end
-- TODO handle continuations properly.
-- pandoc does this:
-- .IP \[bu] 2
-- one
-- .RS 2
-- .PP
-- cont
-- .RE
function Man.paragraph(contents)
return {".PP\n",contents}
end
function Man.bulletlist(items,tight)
local buffer = {}
for _,item in ipairs(items) do
local revitem = item
-- we don't want to have .IP then .PP
if revitem[1][1] == ".PP\n" then revitem[1][1] = "" end
buffer[#buffer + 1] = {".IP \\[bu] 2\n",item}
end
return util.intersperse(buffer, Man.containersep)
end
function Man.orderedlist(items,tight,startnum)
local buffer = {}
local num = startnum or 1
for _,item in ipairs(items) do
local revitem = item
-- we don't want to have .IP then .PP
if revitem[1][1] == ".PP\n" then revitem[1][1] = "" end
buffer[#buffer + 1] = {format(".IP \"%d.\" 4\n",num),item}
num = num + 1
end
return util.intersperse(buffer, Man.containersep)
end
function Man.blockquote(s)
return {".RS\n",s,"\n.RE"}
end
function Man.verbatim(s)
return {".IP\n.nf\n\\f[C]\n",s,".fi"}
end
function Man.header(s,level)
local hcode = ".SS"
if level == 1 then hcode = ".SH" end
return {hcode," ",s}
end
Man.hrule = ".PP\n * * * * *"
function Man.note(contents)
local num = #endnotes + 1
endnotes[num] = {format(".SS [%d]\n",num),contents}
return format('[%d]', num)
end
function Man.definitionlist(items,tight)
local buffer = {}
local ds
for _,item in ipairs(items) do
if tight then
ds = util.intersperse(item.definitions,"\n.RS\n.RE\n")
buffer[#buffer + 1] = {".TP\n.B ",item.term,"\n",ds,"\n.RS\n.RE"}
else
ds = util.intersperse(item.definitions,"\n.RS\n.RE\n")
buffer[#buffer + 1] = {".TP\n.B ",item.term,"\n.RS\n",ds,"\n.RE"}
end
end
local contents = util.intersperse(buffer,"\n")
return contents
end
function Man.start_document()
endnotes = {}
return ""
end
function Man.stop_document()
if #endnotes == 0 then
return ""
else
return {"\n.SH NOTES\n", util.intersperse(endnotes, "\n")}
end
end
Man.template = [===[
.TH "$title" "$section" "$date" "$left_footer" "$center_header"
$body
]===]
return Man
end
return M
|
man writer: Fixed lists so we don't get .PP after .IP.
|
man writer: Fixed lists so we don't get .PP after .IP.
|
Lua
|
mit
|
jgm/lunamark,tst2005/lunamark,simoncozens/lunamark,simoncozens/lunamark,tst2005/lunamark,tst2005/lunamark,jgm/lunamark,jgm/lunamark,simoncozens/lunamark
|
18b327504885c7c139d791d5c735ce22f1220cde
|
webpaste.lua
|
webpaste.lua
|
args = {}
settings = args[1]
return doctype()(
tag"head"(
tag"title" "CPaste WebPaste",
tag"script"[{src="//code.jquery.com/jquery-1.11.3.min.js"}](),
tag"script"[{src="//code.jquery.com/jquery-migrate-1.2.1.min.js"}](),
tag"script"([[
$(document).ready(function() {
$('#submit').click(function() {
var sentType = "plain";
var pasteTypes = document.getElementsByName("pasteType");
for (var i = 0; i < pasteTypes.length; i++) {
if (pasteTypes[i].checked) {
var val = pasteTypes[i].id;
if (val == "radio1") sentType = "plain";
if (val == "radio2") sentType = "raw";
if (val == "radio3") sentType = "html";
break;
}
}
$.ajax({
data: {
c: $('textarea').val(),
type: sentType
},
type: "POST",
url: $('#submit').attr('action'),
success: function(response) {
$('#resultholder').css({
display: "block"
});
$('#result').html(response);
$('#result').attr("href", response);
console.log( response )
}
});
return false
});
});
]]),
tag"style"[{type="text/css"}]([[
html, body, form {
overflow: hidden;
margin: 0px;
width: 100%;
height: 100%;
background-color: #010101;
}
button {
padding: 5px;
background-color: #111;
border: 2px solid #dcdcdc;
color: #dcdcdc;
text-decoration: none;
position: absolute;
left: 3px;
bottom: 3px;
transition: 0.2s;
-webkit-transition: 0.2s;
-moz-transition: 0.2s;
-o-transition: 0.2s;
}
button:hover {
background-color: #010101;
}
div.pasteTypeHolder {
padding: 5px;
background-color: #010101;
color: #dcdcdc;
position: absolute;
bottom: 3px;
left: 60px;
}
textarea {
background-color: #010101;
border: 0px;
color: #fff;
width: 100%;
top: 0px;
bottom: 40px;
resize: none;
position: absolute;
outline: 0;
}
div#resultholder {
padding: 5px;
background-color: #010101;
border: 2px solid #dcdcdc;
position: fixed;
left: 50%;
top: 50%;
-webkit-transform: translate( -50%, -50% );
-moz-transform: translate( -50%, -50% );
-ms-transform: translate( -50%, -50% );
transform: translate( -50%, -50% );
display: none;
transition: 0.2s;
-webkit-transition: 0.2s;
-moz-transition: 0.2s;
-o-transition: 0.2s;
}
a#result {
color: #dcdcdc;
}
]])
),
tag"body"(
tag"textarea"[{name="c", placeholder="Hello World!"}](),
tag"button"[{id="submit",action=ret.url}]("Paste!"),
tag"div"[{class="pasteTypeHolder"}](
tag"input"[{type="radio",class="pasteType",name="pasteType",id="radio1",checked=""}]("Normal"),
tag"input"[{type="radio",class="pasteType",name="pasteType",id="radio2"}]("Raw"),
tag"input"[{type="radio",class="pasteType",name="pasteType",id="radio3"}]("HTML")
),
tag"div"[{id="resultholder"}](
tag"a"[{id="result"}]
)
)
):render()
|
args = {}
settings = args[1]
return doctype()(
tag"head"(
tag"title" "CPaste WebPaste",
tag"script"[{src="//code.jquery.com/jquery-1.11.3.min.js"}](),
tag"script"[{src="//code.jquery.com/jquery-migrate-1.2.1.min.js"}](),
tag"script"([[
$(document).ready(function() {
$('#submit').click(function() {
var sentType = "plain";
var pasteTypes = document.getElementsByName("pasteType");
var i = 0;
while (true) {
if (i >= pasteTypes.length) break;
if (pasteTypes[i].checked) {
var val = pasteTypes[i].id;
if (val == "radio1") sentType = "plain";
if (val == "radio2") sentType = "raw";
if (val == "radio3") sentType = "html";
break;
}
}
$.ajax({
data: {
c: $('textarea').val(),
type: sentType
},
type: "POST",
url: $('#submit').attr('action'),
success: function(response) {
$('#resultholder').css({
display: "block"
});
$('#result').html(response);
$('#result').attr("href", response);
console.log( response )
}
});
return false
});
});
]]),
tag"style"[{type="text/css"}]([[
html, body, form {
overflow: hidden;
margin: 0px;
width: 100%;
height: 100%;
background-color: #010101;
}
button {
padding: 5px;
background-color: #111;
border: 2px solid #dcdcdc;
color: #dcdcdc;
text-decoration: none;
position: absolute;
left: 3px;
bottom: 3px;
transition: 0.2s;
-webkit-transition: 0.2s;
-moz-transition: 0.2s;
-o-transition: 0.2s;
}
button:hover {
background-color: #010101;
}
div.pasteTypeHolder {
padding: 5px;
background-color: #010101;
color: #dcdcdc;
position: absolute;
bottom: 3px;
left: 60px;
}
textarea {
background-color: #010101;
border: 0px;
color: #fff;
width: 100%;
top: 0px;
bottom: 40px;
resize: none;
position: absolute;
outline: 0;
}
div#resultholder {
padding: 5px;
background-color: #010101;
border: 2px solid #dcdcdc;
position: fixed;
left: 50%;
top: 50%;
-webkit-transform: translate( -50%, -50% );
-moz-transform: translate( -50%, -50% );
-ms-transform: translate( -50%, -50% );
transform: translate( -50%, -50% );
display: none;
transition: 0.2s;
-webkit-transition: 0.2s;
-moz-transition: 0.2s;
-o-transition: 0.2s;
}
a#result {
color: #dcdcdc;
}
]])
),
tag"body"(
tag"textarea"[{name="c", placeholder="Hello World!"}](),
tag"button"[{id="submit",action=ret.url}]("Paste!"),
tag"div"[{class="pasteTypeHolder"}](
tag"input"[{type="radio",class="pasteType",name="pasteType",id="radio1",checked=""}]("Normal"),
tag"input"[{type="radio",class="pasteType",name="pasteType",id="radio2"}]("Raw"),
tag"input"[{type="radio",class="pasteType",name="pasteType",id="radio3"}]("HTML")
),
tag"div"[{id="resultholder"}](
tag"a"[{id="result"}]
)
)
):render()
|
Fixed formatting and changed loop style
|
Fixed formatting and changed loop style
|
Lua
|
mit
|
vifino/cpaste,carbonsrv/cpaste
|
0528b8648d9829b9e3385665748889ee382b1745
|
src/hs/finalcutpro/ui/Table.lua
|
src/hs/finalcutpro/ui/Table.lua
|
local log = require("hs.logger").new("Table")
local inspect = require("hs.inspect")
local axutils = require("hs.finalcutpro.axutils")
local tools = require("hs.fcpxhacks.modules.tools")
local geometry = require("hs.geometry")
local Table = {}
--- hs.finalcutpro.ui.Table:new(axuielement, table) -> Table
--- Function:
--- Creates a new Table
function Table:new(parent, finder)
o = {_parent = parent, _finder = finder}
setmetatable(o, self)
self.__index = self
return o
end
function Table:parent()
return self._parent
end
function Table:UI()
return axutils.cache(self, "_ui", function()
return self._finder()
end)
end
function Table:outlineUI()
return axutils.cache(self, "_outline", function()
local ui = self:UI()
return ui and axutils.childWithRole(ui, "AXOutline")
end)
end
function Table:verticalScrollBarUI()
local ui = self:UI()
return ui and ui:attributeValue("AXVerticalScrollBar")
end
function Table:horizontalScrollBarUI()
local ui = self:UI()
return ui and ui:attributeValue("AXHorizontalScrollBar")
end
function Table:isShowing()
return self:UI() ~= nil
end
function Table:isFocused()
local ui = self:rowsUI()
return ui and axutils.childWith(ui, "AXFocused", true) ~= nil
end
-- Returns the list of rows in the table
function Table:rowsUI()
local ui = self:outlineUI()
if ui then
local rows = {}
for i,child in ipairs(ui) do
if child:attributeValue("AXRole") == "AXRow" then
rows[#rows + 1] = child
end
end
return rows
end
return nil
end
function Table:columnsUI()
local ui = self:outlineUI()
if ui then
local columns = {}
for i,child in ipairs(ui) do
if child:attributeValue("AXRole") == "AXColumn" then
columns[#columns + 1] = child
end
end
return columns
end
return nil
end
function Table:findColumnNumber(id)
local cols = self:columnsUI()
if cols then
for i=1,#cols do
if cols[i]:attributeValue("AXIdentifier") == id then
return i
end
end
end
return nil
end
function Table:findCellUI(rowNumber, columnId)
local rows = self:rowsUI()
if rows and rowNumber >= 1 and rowNumber < #rows then
local colNumber = self:findColumnNumber(columnId)
return colNumber and rows[rowNumber][colNumber]
end
return nil
end
function Table:selectedRowsUI()
local rows = self:rowsUI()
if rows then
local selected = {}
for i,row in ipairs(rows) do
if row:attributeValue("AXSelected") then
selected[#selected + 1] = row
end
end
return selected
end
return nil
end
function Table:viewFrame()
local ui = self:UI()
if ui then
local vFrame = ui:frame()
local vScroll = self:verticalScrollBarUI()
if vScroll then
local vsFrame = vScroll:frame()
vFrame.w = vFrame.w - vsFrame.w
vFrame.h = vsFrame.h
else
local hScroll = self:horizontalScrollBarUI()
if hScroll then
local hsFrame = hScroll:frame()
vFrame.w = hsFrame.w
vFrame.h = vFrame.h - hsFrame.h
end
end
return vFrame
end
return nil
end
function Table:showRow(rowUI)
local ui = self:UI()
if ui then
local vFrame = self:viewFrame()
local rowFrame = rowUI:frame()
local top = vFrame.y
local bottom = vFrame.y + vFrame.h
local rowTop = rowFrame.y
local rowBottom = rowFrame.y + rowFrame.h
if rowTop < top or rowBottom > bottom then
-- we need to scroll
local oFrame = self:outlineUI():frame()
local scrollHeight = oFrame.h - vFrame.h
local vValue = nil
if rowTop < top or rowFrame.h > scrollHeight then
vValue = (rowTop-oFrame.y)/scrollHeight
else
vValue = 1.0 - (oFrame.y + oFrame.h - rowBottom)/scrollHeight
end
vScroll:setAttributeValue("AXValue", vValue)
end
end
return self
end
function Table:showRowAt(index)
local rows = self:rowsUI()
if rows then
if index > 0 and index <= #rows then
self:showRow(rows[index])
end
end
return self
end
function Table:selectRow(rowUI)
self:showRow(rowUI)
tools.ninjaMouseClick(geometry.rect(rowUI[1]:frame()).center)
end
function Table:selectRowAt(index)
local ui = self:rowsUI()
if ui and #ui >= index then
self:selectRow(ui[index])
end
end
return Table
|
local log = require("hs.logger").new("Table")
local inspect = require("hs.inspect")
local axutils = require("hs.finalcutpro.axutils")
local tools = require("hs.fcpxhacks.modules.tools")
local geometry = require("hs.geometry")
local Table = {}
--- hs.finalcutpro.ui.Table:new(axuielement, table) -> Table
--- Function:
--- Creates a new Table
function Table:new(parent, finder)
o = {_parent = parent, _finder = finder}
setmetatable(o, self)
self.__index = self
return o
end
function Table:parent()
return self._parent
end
function Table:UI()
return axutils.cache(self, "_ui", function()
return self._finder()
end)
end
function Table:outlineUI()
return axutils.cache(self, "_outline", function()
local ui = self:UI()
return ui and axutils.childWithRole(ui, "AXOutline")
end)
end
function Table:verticalScrollBarUI()
local ui = self:UI()
return ui and ui:attributeValue("AXVerticalScrollBar")
end
function Table:horizontalScrollBarUI()
local ui = self:UI()
return ui and ui:attributeValue("AXHorizontalScrollBar")
end
function Table:isShowing()
return self:UI() ~= nil
end
function Table:isFocused()
local ui = self:rowsUI()
return ui and axutils.childWith(ui, "AXFocused", true) ~= nil
end
-- Returns the list of rows in the table
function Table:rowsUI()
local ui = self:outlineUI()
if ui then
local rows = {}
for i,child in ipairs(ui) do
if child:attributeValue("AXRole") == "AXRow" then
rows[#rows + 1] = child
end
end
return rows
end
return nil
end
function Table:columnsUI()
local ui = self:outlineUI()
if ui then
local columns = {}
for i,child in ipairs(ui) do
if child:attributeValue("AXRole") == "AXColumn" then
columns[#columns + 1] = child
end
end
return columns
end
return nil
end
function Table:findColumnNumber(id)
local cols = self:columnsUI()
if cols then
for i=1,#cols do
if cols[i]:attributeValue("AXIdentifier") == id then
return i
end
end
end
return nil
end
function Table:findCellUI(rowNumber, columnId)
local rows = self:rowsUI()
if rows and rowNumber >= 1 and rowNumber < #rows then
local colNumber = self:findColumnNumber(columnId)
return colNumber and rows[rowNumber][colNumber]
end
return nil
end
function Table:selectedRowsUI()
local rows = self:rowsUI()
if rows then
local selected = {}
for i,row in ipairs(rows) do
if row:attributeValue("AXSelected") then
selected[#selected + 1] = row
end
end
return selected
end
return nil
end
function Table:viewFrame()
local ui = self:UI()
if ui then
local vFrame = ui:frame()
local vScroll = self:verticalScrollBarUI()
if vScroll then
local vsFrame = vScroll:frame()
vFrame.w = vFrame.w - vsFrame.w
vFrame.h = vsFrame.h
else
local hScroll = self:horizontalScrollBarUI()
if hScroll then
local hsFrame = hScroll:frame()
vFrame.w = hsFrame.w
vFrame.h = vFrame.h - hsFrame.h
end
end
return vFrame
end
return nil
end
function Table:showRow(rowUI)
local ui = self:UI()
if ui then
local vFrame = self:viewFrame()
local rowFrame = rowUI:frame()
local top = vFrame.y
local bottom = vFrame.y + vFrame.h
local rowTop = rowFrame.y
local rowBottom = rowFrame.y + rowFrame.h
if rowTop < top or rowBottom > bottom then
-- we need to scroll
local oFrame = self:outlineUI():frame()
local scrollHeight = oFrame.h - vFrame.h
local vValue = nil
if rowTop < top or rowFrame.h > scrollHeight then
vValue = (rowTop-oFrame.y)/scrollHeight
else
vValue = 1.0 - (oFrame.y + oFrame.h - rowBottom)/scrollHeight
end
local vScroll = self:verticalScrollBarUI()
if vScroll then
vScroll:setAttributeValue("AXValue", vValue)
end
end
end
return self
end
function Table:showRowAt(index)
local rows = self:rowsUI()
if rows then
if index > 0 and index <= #rows then
self:showRow(rows[index])
end
end
return self
end
function Table:selectRow(rowUI)
self:showRow(rowUI)
tools.ninjaMouseClick(geometry.rect(rowUI[1]:frame()).center)
end
function Table:selectRowAt(index)
local ui = self:rowsUI()
if ui and #ui >= index then
self:selectRow(ui[index])
end
end
return Table
|
#110 * Fixed bug in Table
|
#110
* Fixed bug in Table
|
Lua
|
mit
|
cailyoung/CommandPost,fcpxhacks/fcpxhacks,cailyoung/CommandPost,CommandPost/CommandPost,fcpxhacks/fcpxhacks,CommandPost/CommandPost,CommandPost/CommandPost,cailyoung/CommandPost
|
776bb03740a8f89a6182bccc8a47ea5035347009
|
src/main/resources/std/utf8.lua
|
src/main/resources/std/utf8.lua
|
-- Copyright (c) 2018. tangzx([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License"); you may not
-- use this file except in compliance with the License. You may obtain a copy of
-- the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-- WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-- License for the specific language governing permissions and limitations under
-- the License.
utf8 = {}
---
--- Receives zero or more integers, converts each one to its corresponding
--- UTF-8 byte sequence and returns a string with the concatenation of all
--- these sequences.
---@return string
function utf8.char(···) end
---
--- The pattern (a string, not a function) "`[\0-\x7F\xC2-\xF4][\x80-\xBF]*`",
--- which matches exactly one UTF-8 byte sequence, assuming that the subject
--- is a valid UTF-8 string.
utf8.charpattern = ""
---
--- Returns values so that the construction
---
--- `for p, c in utf8.codes(s) do *body* end`
--- will iterate over all characters in string `s`, with `p` being the position
--- (in bytes) and `c` the code point of each character. It raises an error if
--- it meets any invalid byte sequence.
---@param s string
---@return fun(p:number, c:number):number
function utf8.codes(s) end
---
--- Returns the codepoints (as integers) from all characters in s that start
--- between byte position `i` and `j` (both included). The default for `i` is
--- 1 and for `j` is `i`. It raises an error if it meets any invalid byte
--- sequence.
---@param s string
---@param i number
---@param j number
---@return number
function utf8.codepoint (s, i, j) end
---
--- Returns the number of UTF-8 characters in string s that start between
--- positions `i` and `j` (both inclusive). The default for `i` is 1 and for
--- `j` is -1. If it finds any invalid byte sequence, returns a false value
--- plus the position of the first invalid byte.
---@param s string
---@param i number
---@param j number
---@return number|number
function utf8.len(s, i, j) end
---
--- Returns the position (in bytes) where the encoding of the `n`-th character
--- of `s` (counting from position `i`) starts. A negative `n` gets
--- characters before position `i`. The default for `i` is 1 when `n` is
--- non-negative and `#s + 1` otherwise, so that `utf8.offset(s, -n)` gets the
--- offset of the `n`-th character from the end of the string. If the
--- specified character is neither in the subject nor right after its end,
--- the function returns nil. As a special case, when `n` is 0 the function
--- returns the start of the encoding of the character that contains the `i`-th
--- byte of `s`.
---
--- This function assumes that `s` is a valid UTF-8 string.
---@param s string
---@param n number
---@param i number
---@return number
function utf8.offset (s, n, i) end
|
-- Copyright (c) 2018. tangzx([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License"); you may not
-- use this file except in compliance with the License. You may obtain a copy of
-- the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-- WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-- License for the specific language governing permissions and limitations under
-- the License.
utf8 = {}
---
--- Receives zero or more integers, converts each one to its corresponding
--- UTF-8 byte sequence and returns a string with the concatenation of all
--- these sequences.
---@return string
function utf8.char(...) end
---
--- The pattern (a string, not a function) "`[\0-\x7F\xC2-\xF4][\x80-\xBF]*`",
--- which matches exactly one UTF-8 byte sequence, assuming that the subject
--- is a valid UTF-8 string.
---@type string
utf8.charpattern = ""
---
--- Returns values so that the construction
--- `for p, c in utf8.codes(s) do body end`
--- will iterate over all characters in string `s`, with `p` being the position
--- (in bytes) and `c` the code point of each character. It raises an error if
--- it meets any invalid byte sequence.
---@param s string
---@return string
function utf8.codes(s) end
---
--- Returns the codepoints (as integers) from all characters in `s` that start
--- between byte position `i` and `j` (both included). The default for `i` is
--- 1 and for `j` is `i`. It raises an error if it meets any invalid byte
--- sequence.
---@overload fun(s:string):number
---@param s string
---@param i number
---@param j number
---@return number
function utf8.codepoint (s, i, j) end
---
--- Returns the number of UTF-8 characters in string `s` that start between
--- positions `i` and `j` (both inclusive). The default for `i` is 1 and for
--- `j` is -1. If it finds any invalid byte sequence, returns a false value
--- plus the position of the first invalid byte.
---@overload fun(s:string):number
---@param s string
---@param i number
---@param j number
---@return number
function utf8.len(s, i, j) end
---
--- Returns the position (in bytes) where the encoding of the `n`-th character
--- of `s` (counting from position `i`) starts. A negative `n` gets
--- characters before position `i`. The default for `i` is 1 when `n` is
--- non-negative and `#s + 1` otherwise, so that `utf8.offset(s, -n)` gets the
--- offset of the `n`-th character from the end of the string. If the
--- specified character is neither in the subject nor right after its end,
--- the function returns nil. As a special case, when `n` is 0 the function
--- returns the start of the encoding of the character that contains the `i`-th
--- byte of `s`.
---
--- This function assumes that `s` is a valid UTF-8 string.
---@overload fun(s:string):number
---@param s string
---@param n number
---@param i number
---@return number
function utf8.offset (s, n, i) end
|
fix optional params
|
fix optional params
|
Lua
|
apache-2.0
|
tangzx/IntelliJ-EmmyLua,tangzx/IntelliJ-EmmyLua,tangzx/IntelliJ-EmmyLua,tangzx/IntelliJ-EmmyLua,EmmyLua/IntelliJ-EmmyLua,EmmyLua/IntelliJ-EmmyLua,EmmyLua/IntelliJ-EmmyLua,EmmyLua/IntelliJ-EmmyLua
|
aa7e58f06c79d5f93ebcce8245c9c2fae0138f4a
|
extension/script/backend/worker/eval/repl.lua
|
extension/script/backend/worker/eval/repl.lua
|
local source, level = ...
level = (level or 0) + 2
if _VERSION == "Lua 5.1" then
load = loadstring
function table.pack(...)
local t = {...}
t.n = select("#", ...)
return t
end
table.unpack = unpack
end
local f = assert(debug.getinfo(level,"f").func, "can't find function")
local args = {}
local locals = {}
local local_id = {}
local local_value = {}
local upvalue_id = {}
local i = 1
while true do
local name, value = debug.getlocal(level, i)
if name == nil then
break
end
if name:byte() ~= 40 then -- '('
args[#args+1] = name
locals[#locals+1] = ("[%d]=%s,"):format(i,name)
local_id[name] = i
local_value[name] = value
end
i = i + 1
end
local i = 1
while true do
local name = debug.getupvalue(f, i)
if name == nil then
break
end
if #name > 0 then
upvalue_id[name] = i
args[#args+1] = name
end
i = i + 1
end
local full_source
if #args > 0 then
full_source = ([[
local $ARGS
return function(...)
$SOURCE
end,
function()
return {$LOCALS}
end
]]):gsub("%$(%w+)", {
ARGS = table.concat(args, ","),
SOURCE = source,
LOCALS = table.concat(locals),
})
else
full_source = ([[
return function(...)
$SOURCE
end,
function()
return {$LOCALS}
end
]]):gsub("%$(%w+)", {
SOURCE = source,
LOCALS = table.concat(locals),
})
end
local func, update = assert(load(full_source, '=(EVAL)'))()
local i = 1
while true do
local name = debug.getupvalue(func, i)
if name == nil then
break
end
local uvid = upvalue_id[name]
if uvid then
debug.upvaluejoin(func, i, f, uvid)
end
if local_id[name] then
debug.setupvalue(func, i, local_value[name])
end
i = i + 1
end
local rets
local vararg, v = debug.getlocal(level, -1)
if vararg then
local vargs = { v }
local i = 2
while true do
vararg, v = debug.getlocal(level, -i)
if vararg then
vargs[i] = v
else
break
end
i=i+1
end
rets = table.pack(func(table.unpack(vargs)))
else
rets = table.pack(func())
end
local needupdate = update()
for k,v in pairs(needupdate) do
debug.setlocal(level,k,v)
end
return table.unpack(rets)
|
local source, level = ...
level = (level or 0) + 2
if _VERSION == "Lua 5.1" then
load = loadstring
function table.pack(...)
local t = {...}
t.n = select("#", ...)
return t
end
table.unpack = unpack
end
local f = assert(debug.getinfo(level,"f").func, "can't find function")
local args_name = {}
local args_value = {}
local locals = {}
do
local i = 1
while true do
local name, value = debug.getupvalue(f, i)
if name == nil then
break
end
if #name > 0 then
args_name[#args_name+1] = name
args_value[name] = value
end
i = i + 1
end
end
do
local i = 1
while true do
local name, value = debug.getlocal(level, i)
if name == nil then
break
end
if name:byte() ~= 40 then -- '('
args_name[#args_name+1] = name
args_value[name] = value
locals[#locals+1] = ("[%d]={%s},"):format(i,name)
end
i = i + 1
end
end
local full_source
if #args_name > 0 then
full_source = ([[
local $ARGS
return function(...)
$SOURCE
end,
function()
return {$LOCALS}
end
]]):gsub("%$(%w+)", {
ARGS = table.concat(args_name, ","),
SOURCE = source,
LOCALS = table.concat(locals),
})
else
full_source = ([[
return function(...)
$SOURCE
end,
function()
return {$LOCALS}
end
]]):gsub("%$(%w+)", {
SOURCE = source,
LOCALS = table.concat(locals),
})
end
local func, update = assert(load(full_source, '=(EVAL)'))()
do
local i = 1
while true do
local name = debug.getupvalue(func, i)
if name == nil then
break
end
debug.setupvalue(func, i, args_value[name])
i = i + 1
end
end
local rets
do
local vararg, v = debug.getlocal(level, -1)
if vararg then
local vargs = { v }
local i = 2
while true do
vararg, v = debug.getlocal(level, -i)
if vararg then
vargs[i] = v
else
break
end
i = i + 1
end
rets = table.pack(func(table.unpack(vargs)))
else
rets = table.pack(func())
end
end
for k,v in pairs(update()) do
debug.setlocal(level,k,v[1])
end
return table.unpack(rets)
|
Fixes #118
|
Fixes #118
|
Lua
|
mit
|
actboy168/vscode-lua-debug,actboy168/vscode-lua-debug,actboy168/vscode-lua-debug
|
1453d200d965c3a30c6103a12ebc1ee36777cf15
|
fimbul/eh/character.lua
|
fimbul/eh/character.lua
|
---@module fimbul.eh.character
local character = {}
local base = _G
local ability = require('fimbul.eh.ability')
local rules = require('fimbul.eh.rules')
local skill_check = require('fimbul.eh.skill_check')
local util = require('fimbul.util')
function character:new(y)
local neu = y or {}
setmetatable(neu, self)
self.__index = self
-- Initialise abilities
neu.abilities = {}
for _, a in base.pairs(rules.abilities.names) do
local lower = string.lower(a)
neu[lower] = ability:new(a)
table.insert(neu.abilities, neu[lower])
end
neu.skills = {}
neu._equipment = {}
neu._credits = 0
neu._weight = 0
neu._hp = 0
neu._stance = rules.combat.stance.STANDING
neu._movement = rules.combat.movement.SUBTLE
neu._name = ''
return neu
end
function character:spawn(r, t)
local neu = self:new()
if not t.name then
error('Character must have a name!')
end
neu._name = t.name
neu.template = t
-- Load race.
if t.race == nil then
error('Character does not have a race.')
end
local race = r:find_spawn_first(r.eh.races, t.race)
if race == nil then
error('No such race: ' .. t.race)
end
neu._race = race
neu._weight = t.weight or 0
neu._height = t.height or 0
neu._credits = t.credits or 0
for _, a in base.pairs(rules.abilities.names) do
local at
local name = string.lower(a)
local ans = rules.short_ability_name(a)
at = util.findfirst(t, a, name, ans, string.lower(ans))
if at then
neu[name] = ability:new(name, at)
end
end
if t.skills then
for skill, rank in base.pairs(t.skills) do
local s = r:find(r.eh.skills, skill)
if #s == 0 then
error('No such skill: ' .. skill)
end
local sk = r:spawn(s[1])
sk:rank(rank)
-- Insert skill to list
table.insert(neu.skills, sk)
end
end
if t.equipment then
for _, item in base.pairs(t.equipment) do
local it = r:parse_item(item)
if it == nil then
error('No such item: ' .. item)
end
table.insert(neu._equipment, it)
end
end
neu._hp = neu:max_hp()
return neu
end
function character:name()
return self._name
end
function character:weight()
return self._weight
end
function character:height()
return self._height
end
function character:race()
return self._race
end
function character:max_hp()
return rules.character.BASE_HP
+ self.strength:rank()
+ self.constitution:rank()
end
function character:damage(dmg, source)
local d
local z = self:race():hitzone():roll_zone()
-- TODO: Armor
z:modify_damage(dmg)
d = dmg:value()
self._hp = self._hp - d
-- TODO: Roll wounds
return dmg, z
end
function character:perform(r, t)
local s = t:skill()
local skill = r:find_spawn_first(r.eh.skills, s)
local sk = util.find_name(self.skills, s)
local mod = skill_check:new()
-- Handle ability modifiers
--
for _, a in base.pairs(skill:uses()) do
local m = self:ability(a):modifier()
if (m < 0 and sk == nil) or
(m >= 0 and sk ~= nil) then
mod:add(m, a)
end
end
-- Do we have a skill modifier?
--
if sk ~= nil then
local rk = sk:rank()
mod:add(rk, sk:name())
end
-- Roll
mod:roll()
if mod:value() >= t:value() then
return true, mod
end
return false, mod
end
function character:ability(a)
local n = string.lower(a)
return self[n]
end
function character:hp()
return self._hp
end
function character:is_dead()
return self:hp() <= (self:max_hp() * -1)
end
function character:equipment()
return self._equipment
end
function character:max_carry_weight()
return rules.character.BASE_CARRY_WEIGHT
+ self.constitution:rank()
+ self.constitution:rank()
end
function character:equipment_weight()
local w = 0
for _, i in base.pairs(self._equipment) do
w = w + i:weight()
end
return w
end
function character:equipment_cost()
local c = 0
for _, i in base.pairs(self._equipment) do
c = c + i:cost()
end
return c
end
function character:total_weight()
return self:weight() + self:equipment_weight()
end
function character:cost()
local c = 0
-- TODO: Performance
for _, a in base.pairs(self.abilities) do
c = c + a:cost()
end
for _, s in base.pairs(self.skills) do
c = c + s:cost()
end
return c
end
function character:stance(v)
if v == nil then
return self._stance
else
if not util.contains(rules.combat.stance, v) then
error('Invalid stance.')
end
self._stance = v
end
end
function character:movement(v)
if v == nil then
return self._movement
else
if not util.contains(rules.combat.movement, v) then
error('Invalid stance.')
end
self._movement = v
end
end
function character:roll_initiative()
return rules.combat.initiative_dice:roll()
+ self.dexterity:modifier()
end
function character:size()
return rules.combat.size_by_stance[self:stance()]
end
function character:string(e)
if not e then
return self:name()
end
local s = ''
s = s .. 'Character: ' .. self:name() .. "\n"
s = s .. 'CCP Spent: ' .. self:cost() .. "\n"
s = s .. "\n"
s = s .. 'Strength: ' .. self.strength:rank() .. "\n"
s = s .. 'Dexterity: ' .. self.dexterity:rank() .. "\n"
s = s .. 'Constitution: ' .. self.constitution:rank() .. "\n"
s = s .. 'Intelligence: ' .. self.intelligence:rank() .. "\n"
s = s .. 'Perception: ' .. self.perception:rank() .. "\n"
s = s .. 'Charisma: ' .. self.charisma:rank() .. "\n"
s = s .. "\n"
s = s .. 'Max HP: ' .. self:max_hp() .. "\n"
s = s .. 'Height: ' .. self:height() .. " cm\n"
s = s .. 'Weight: ' .. self:weight() .. " kg\n"
s = s .. 'Total weight: ' .. self:total_weight() .. " kg\n"
s = s .. 'Max carry weight: ' .. self:max_carry_weight() .. " kg\n"
s = s .. 'Equipment: ' .. "\n"
for _, i in base.pairs(self:equipment()) do
s = s .. ' - ' .. i:string() .. "\n"
end
s = s .. ' Weight: ' .. self:equipment_weight() .. " kg\n"
s = s .. ' Cost: ' .. self:equipment_cost() .. " C"
return s
end
return character
|
---@module fimbul.eh.character
local character = {}
local base = _G
local ability = require('fimbul.eh.ability')
local rules = require('fimbul.eh.rules')
local skill_check = require('fimbul.eh.skill_check')
local util = require('fimbul.util')
function character:new(y)
local neu = y or {}
setmetatable(neu, self)
self.__index = self
-- Initialise abilities
for _, a in base.pairs(rules.abilities.names) do
local lower = string.lower(a)
neu[lower] = ability:new(a)
end
neu.skills = {}
neu._equipment = {}
neu._credits = 0
neu._weight = 0
neu._hp = 0
neu._stance = rules.combat.stance.STANDING
neu._movement = rules.combat.movement.SUBTLE
neu._name = ''
return neu
end
function character:spawn(r, t)
local neu = self:new()
if not t.name then
error('Character must have a name!')
end
neu._name = t.name
neu.template = t
-- Load race.
if t.race == nil then
error('Character does not have a race.')
end
local race = r:find_spawn_first(r.eh.races, t.race)
if race == nil then
error('No such race: ' .. t.race)
end
neu._race = race
neu._weight = t.weight or 0
neu._height = t.height or 0
neu._credits = t.credits or 0
for _, a in base.pairs(rules.abilities.names) do
local at
local name = string.lower(a)
local ans = rules.short_ability_name(a)
at = util.findfirst(t, a, name, ans, string.lower(ans))
if at then
neu[name] = ability:new(name, at)
end
end
if t.skills then
for skill, rank in base.pairs(t.skills) do
local s = r:find(r.eh.skills, skill)
if #s == 0 then
error('No such skill: ' .. skill)
end
local sk = r:spawn(s[1])
sk:rank(rank)
-- Insert skill to list
table.insert(neu.skills, sk)
end
end
if t.equipment then
for _, item in base.pairs(t.equipment) do
local it = r:parse_item(item)
if it == nil then
error('No such item: ' .. item)
end
table.insert(neu._equipment, it)
end
end
neu._hp = neu:max_hp()
return neu
end
function character:name()
return self._name
end
function character:weight()
return self._weight
end
function character:height()
return self._height
end
function character:race()
return self._race
end
function character:max_hp()
return rules.character.BASE_HP
+ self.strength:rank()
+ self.constitution:rank()
end
function character:damage(dmg, source)
local d
local z = self:race():hitzone():roll_zone()
-- TODO: Armor
z:modify_damage(dmg)
d = dmg:value()
self._hp = self._hp - d
-- TODO: Roll wounds
return dmg, z
end
function character:perform(r, t)
local s = t:skill()
local skill = r:find_spawn_first(r.eh.skills, s)
local sk = util.find_name(self.skills, s)
local mod = skill_check:new()
-- Handle ability modifiers
--
for _, a in base.pairs(skill:uses()) do
local m = self:ability(a):modifier()
if (m < 0 and sk == nil) or
(m >= 0 and sk ~= nil) then
mod:add(m, a)
end
end
-- Do we have a skill modifier?
--
if sk ~= nil then
local rk = sk:rank()
mod:add(rk, sk:name())
end
-- Roll
mod:roll()
if mod:value() >= t:value() then
return true, mod
end
return false, mod
end
function character:ability(a)
local n = string.lower(a)
return self[n]
end
function character:hp()
return self._hp
end
function character:is_dead()
return self:hp() <= (self:max_hp() * -1)
end
function character:equipment()
return self._equipment
end
function character:max_carry_weight()
return rules.character.BASE_CARRY_WEIGHT
+ self.constitution:rank()
+ self.constitution:rank()
end
function character:equipment_weight()
local w = 0
for _, i in base.pairs(self._equipment) do
w = w + i:weight()
end
return w
end
function character:equipment_cost()
local c = 0
for _, i in base.pairs(self._equipment) do
c = c + i:cost()
end
return c
end
function character:total_weight()
return self:weight() + self:equipment_weight()
end
function character:cost()
local c = 0
-- TODO: Performance
for _, a in base.pairs(rules.abilities.names) do
local ab = self[string.lower(a)]
if ab then
c = c + ab:cost()
end
end
for _, s in base.pairs(self.skills) do
c = c + s:cost()
end
return c
end
function character:stance(v)
if v == nil then
return self._stance
else
if not util.contains(rules.combat.stance, v) then
error('Invalid stance.')
end
self._stance = v
end
end
function character:movement(v)
if v == nil then
return self._movement
else
if not util.contains(rules.combat.movement, v) then
error('Invalid stance.')
end
self._movement = v
end
end
function character:roll_initiative()
return rules.combat.initiative_dice:roll()
+ self.dexterity:modifier()
end
function character:size()
return rules.combat.size_by_stance[self:stance()]
end
function character:string(e)
if not e then
return self:name()
end
local s = ''
s = s .. 'Character: ' .. self:name() .. "\n"
s = s .. 'CCP Spent: ' .. self:cost() .. "\n"
s = s .. "\n"
s = s .. 'Strength: ' .. self.strength:rank() .. "\n"
s = s .. 'Dexterity: ' .. self.dexterity:rank() .. "\n"
s = s .. 'Constitution: ' .. self.constitution:rank() .. "\n"
s = s .. 'Intelligence: ' .. self.intelligence:rank() .. "\n"
s = s .. 'Perception: ' .. self.perception:rank() .. "\n"
s = s .. 'Charisma: ' .. self.charisma:rank() .. "\n"
s = s .. "\n"
s = s .. 'Max HP: ' .. self:max_hp() .. "\n"
s = s .. 'Height: ' .. self:height() .. " cm\n"
s = s .. 'Weight: ' .. self:weight() .. " kg\n"
s = s .. 'Total weight: ' .. self:total_weight() .. " kg\n"
s = s .. 'Max carry weight: ' .. self:max_carry_weight() .. " kg\n"
s = s .. 'Equipment: ' .. "\n"
for _, i in base.pairs(self:equipment()) do
s = s .. ' - ' .. i:string() .. "\n"
end
s = s .. ' Weight: ' .. self:equipment_weight() .. " kg\n"
s = s .. ' Cost: ' .. self:equipment_cost() .. " C"
return s
end
return character
|
Fix CCP calculation for abilities
|
Fix CCP calculation for abilities
|
Lua
|
bsd-2-clause
|
n0la/fimbul
|
a908ed67e182b8f44299d639381575d91a113447
|
site/api/lib/elastic.lua
|
site/api/lib/elastic.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 elastic.lua - ElasticSearch library
local http = require 'socket.http'
local JSON = require 'cjson'
local config = require 'lib/config'
local default_doc = "mbox"
-- http code return check
function checkReturn(code)
if not code or code ~= 200 then
if not code or code == "closed" then
error("Could not contact database backend!")
else
error("Backend Database returned code " .. code .. "!")
end
return nil
end
end
-- Standard ES query, returns $size results of any doc of type $doc, sorting by $sitem
function getHits(query, size, doc, sitem)
doc = doc or "mbox"
sitem = sitem or "epoch"
size = size or 10
query = query:gsub(" ", "+")
local url = config.es_url .. doc .. "/_search?q="..query.."&sort=" .. sitem .. ":desc&size=" .. size
local result, hc = http.request(url)
local out = {}
checkReturn(hc)
local json = JSON.decode(result)
local out = {}
if json and json.hits and json.hits.hits then
for k, v in pairs(json.hits.hits) do
v._source.request_id = v._id
table.insert(out, v._source)
end
end
return out
end
-- Get a single document
function getDoc (ty, id)
local url = config.es_url .. ty .. "/" .. id
local result, hc = http.request(url)
local out = {}
checkReturn(hc)
local json = JSON.decode(result)
if json and json._source then
json._source.request_id = json._id
end
return (json and json._source) and json._source or {}
end
-- Get results (a'la getHits), but only return email headers, not the body
-- provides faster transport when we don't need everything
function getHeaders(query, size, doc)
doc = doc or "mbox"
size = size or 10
query = query:gsub(" ", "+")
local url = config.es_url .. doc .. "/_search?_source_exclude=body&q="..query.."&sort=date:desc&size=" .. size
local result, hc = http.request(url)
local out = {}
checkReturn(hc)
local json = JSON.decode(result)
local out = {}
if json and json.hits and json.hits.hits then
for k, v in pairs(json.hits.hits) do
v._source.request_id = v._id
table.insert(out, v._source)
end
end
return out
end
-- Same as above, but reverse return order
function getHeadersReverse(query, size, doc)
doc = doc or "mbox"
size = size or 10
query = query:gsub(" ", "+")
local url = config.es_url .. doc .. "/_search?_source_exclude=body&q="..query.."&sort=epoch:desc&size=" .. size
local result, hc = http.request(url)
local out = {}
local json = JSON.decode(result)
local out = {}
checkReturn(hc)
if json and json.hits and json.hits.hits then
for k, v in pairs(json.hits.hits) do
v._source.request_id = v._id
table.insert(out, 1, v._source)
end
end
return out
end
-- Do a raw ES query with a JSON query
function raw(query, doctype)
local js = JSON.encode(query)
doctype = doctype or default_doc
local url = config.es_url .. doctype .. "/_search"
local result, hc = http.request(url, js)
local out = {}
checkReturn(hc)
local json = JSON.decode(result)
return json or {}, url
end
-- Raw query with scroll/scan
function scan(query, doctype)
local js = JSON.encode(query)
doctype = doctype or default_doc
local url = config.es_url .. doctype .. "/_search?search_type=scan&scroll=1m"
local result, hc = http.request(url, js)
local out = {}
checkReturn(hc)
local json = JSON.decode(result)
if json and json._scroll_id then
return json._scroll_id
end
return nil
end
function scroll(sid)
doctype = doctype or default_doc
-- We have to do some gsubbing here, as ES expects us to be at the root of the ES URL
-- But in case we're being proxied, let's just cut off the last part of the URL
local url = config.es_url:gsub("[^/]+/?$", "") .. "/_search/scroll?scroll=1m&scroll_id=" .. sid
local result, hc = http.request(url)
checkReturn(hc)
local json = JSON.decode(result)
if json and json._scroll_id then
return json, json._scroll_id
end
return nil
end
-- Update a document
function update(doctype, id, query, consistency)
local js = JSON.encode({doc = query })
doctype = doctype or default_doc
local url = config.es_url .. doctype .. "/" .. id .. "/_update"
if consistency then
url = url .. "?write_consistency=" .. consistency
end
local result, hc = http.request(url, js)
local out = {}
local json = JSON.decode(result)
return json or {}, url
end
-- Put a new document somewhere
function index(r, id, ty, body, consistency)
local js = JSON.encode(query)
if not id then
id = r:sha1(ty .. (math.random(1,99999999)*os.time()) .. ':' .. r:clock())
end
local url = config.es_url .. ty .. "/" .. id
if consistency then
url = url .. "?write_consistency=" .. consistency
end
local result, hc = http.request(url, body)
local out = {}
local json = JSON.decode(result)
return json or {}
end
function setDefault(typ)
default_doc = typ
end
-- module defs
return {
find = getHits,
findFast = getHeaders,
findFastReverse = getHeadersReverse,
get = getDoc,
raw = raw,
index = index,
default = setDefault,
update = update,
scan = scan,
scroll = scroll
}
|
--[[
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 elastic.lua - ElasticSearch library
local http = require 'socket.http'
local JSON = require 'cjson'
local config = require 'lib/config'
local default_doc = "mbox"
-- http code return check
function checkReturn(code)
if not code or code ~= 200 then
if not code or code == "closed" then
error("Could not contact database backend!")
else
error("Backend Database returned code " .. code .. "!")
end
end
end
-- Standard ES query, returns $size results of any doc of type $doc, sorting by $sitem
function getHits(query, size, doc, sitem)
doc = doc or "mbox"
sitem = sitem or "epoch"
size = size or 10
query = query:gsub(" ", "+")
local url = config.es_url .. doc .. "/_search?q="..query.."&sort=" .. sitem .. ":desc&size=" .. size
local result, hc = http.request(url)
checkReturn(hc)
local json = JSON.decode(result)
local out = {}
if json and json.hits and json.hits.hits then
for k, v in pairs(json.hits.hits) do
v._source.request_id = v._id
table.insert(out, v._source)
end
end
return out
end
-- Get a single document
function getDoc (ty, id)
local url = config.es_url .. ty .. "/" .. id
local result, hc = http.request(url)
checkReturn(hc)
local json = JSON.decode(result)
if json and json._source then
json._source.request_id = json._id
end
return (json and json._source) and json._source or {}
end
-- Get results (a'la getHits), but only return email headers, not the body
-- provides faster transport when we don't need everything
function getHeaders(query, size, doc)
doc = doc or "mbox"
size = size or 10
query = query:gsub(" ", "+")
local url = config.es_url .. doc .. "/_search?_source_exclude=body&q="..query.."&sort=date:desc&size=" .. size
local result, hc = http.request(url)
checkReturn(hc)
local json = JSON.decode(result)
local out = {}
if json and json.hits and json.hits.hits then
for k, v in pairs(json.hits.hits) do
v._source.request_id = v._id
table.insert(out, v._source)
end
end
return out
end
-- Same as above, but reverse return order
function getHeadersReverse(query, size, doc)
doc = doc or "mbox"
size = size or 10
query = query:gsub(" ", "+")
local url = config.es_url .. doc .. "/_search?_source_exclude=body&q="..query.."&sort=epoch:desc&size=" .. size
local result, hc = http.request(url)
checkReturn(hc)
local json = JSON.decode(result)
local out = {}
if json and json.hits and json.hits.hits then
for k, v in pairs(json.hits.hits) do
v._source.request_id = v._id
table.insert(out, 1, v._source)
end
end
return out
end
-- Do a raw ES query with a JSON query
function raw(query, doctype)
local js = JSON.encode(query)
doctype = doctype or default_doc
local url = config.es_url .. doctype .. "/_search"
local result, hc = http.request(url, js)
checkReturn(hc)
local json = JSON.decode(result)
return json or {}, url
end
-- Raw query with scroll/scan
function scan(query, doctype)
local js = JSON.encode(query)
doctype = doctype or default_doc
local url = config.es_url .. doctype .. "/_search?search_type=scan&scroll=1m"
local result, hc = http.request(url, js)
checkReturn(hc)
local json = JSON.decode(result)
if json and json._scroll_id then
return json._scroll_id
end
return nil
end
function scroll(sid)
-- We have to do some gsubbing here, as ES expects us to be at the root of the ES URL
-- But in case we're being proxied, let's just cut off the last part of the URL
local url = config.es_url:gsub("[^/]+/?$", "") .. "/_search/scroll?scroll=1m&scroll_id=" .. sid
local result, hc = http.request(url)
checkReturn(hc)
local json = JSON.decode(result)
if json and json._scroll_id then
return json, json._scroll_id
end
return nil
end
-- Update a document
function update(doctype, id, query, consistency)
local js = JSON.encode({doc = query })
doctype = doctype or default_doc
local url = config.es_url .. doctype .. "/" .. id .. "/_update"
if consistency then
url = url .. "?write_consistency=" .. consistency
end
local result, hc = http.request(url, js)
local json = JSON.decode(result)
return json or {}, url
end
-- Put a new document somewhere
function index(r, id, ty, body, consistency)
if not id then
id = r:sha1(ty .. (math.random(1,99999999)*os.time()) .. ':' .. r:clock())
end
local url = config.es_url .. ty .. "/" .. id
if consistency then
url = url .. "?write_consistency=" .. consistency
end
local result, hc = http.request(url, body)
local json = JSON.decode(result)
return json or {}
end
function setDefault(typ)
default_doc = typ
end
-- module defs
return {
find = getHits,
findFast = getHeaders,
findFastReverse = getHeadersReverse,
get = getDoc,
raw = raw,
index = index,
default = setDefault,
update = update,
scan = scan,
scroll = scroll
}
|
Fix for https://github.com/apache/incubator-ponymail/issues/139
|
Fix for https://github.com/apache/incubator-ponymail/issues/139
|
Lua
|
apache-2.0
|
Humbedooh/ponymail,jimjag/ponymail,jimjag/ponymail,jimjag/ponymail,Humbedooh/ponymail,quenda/ponymail,quenda/ponymail,jimjag/ponymail,Humbedooh/ponymail,quenda/ponymail
|
e558401e090c5f2cb0e06a9681f15579374a4e51
|
core/inputs-xml.lua
|
core/inputs-xml.lua
|
SILE.inputs.XML = {
order = 1,
appropriate = function(fn, sniff)
return (fn:match("xml$") or sniff:match("<"))
end,
process = function (fn)
local lom = require("lomwithpos")
local fh = io.open(fn)
local t = lom.parse(fh:read("*all"))
local root = SILE.documentState.documentClass == nil
if root then
if not(t.tag == "sile") then
SU.error("This isn't a SILE document!")
end
SILE.inputs.common.init(fn, t)
end
SILE.currentCommand = t
if SILE.Commands[t.tag] then
SILE.Commands[t.tag](t.attr,t)
else
SILE.process(t)
end
if root and not SILE.preamble then
SILE.documentState.documentClass:finish()
end
end,
}
|
SILE.inputs.XML = {
order = 1,
appropriate = function(fn, sniff)
return (fn:match("xml$") or sniff:match("<"))
end,
process = function (fn)
local lom = require("lomwithpos")
local fh = io.open(fn)
local t, err = lom.parse(fh:read("*all"))
if t == nil then
error(err)
end
local root = SILE.documentState.documentClass == nil
if root then
if not(t.tag == "sile") then
SU.error("This isn't a SILE document!")
end
SILE.inputs.common.init(fn, t)
end
SILE.currentCommand = t
if SILE.Commands[t.tag] then
SILE.Commands[t.tag](t.attr,t)
else
SILE.process(t)
end
if root and not SILE.preamble then
SILE.documentState.documentClass:finish()
end
end,
}
|
Fix #330
|
Fix #330
|
Lua
|
mit
|
simoncozens/sile,alerque/sile,alerque/sile,neofob/sile,simoncozens/sile,simoncozens/sile,simoncozens/sile,neofob/sile,neofob/sile,neofob/sile,alerque/sile,alerque/sile
|
e6a9deaf3a04164ae1099b3c1321c4234f938034
|
plugins/botinteract.lua
|
plugins/botinteract.lua
|
local function callback_setbot(extra, success, result)
if success == 0 then
send_large_msg('chat#id' .. extra.chatid, lang_text('noUsernameFound'))
send_large_msg('channel#id' .. extra.chatid, lang_text('noUsernameFound'))
return
end
local hash = 'botinteract'
redis:sadd(hash, extra.chatid .. ':' .. result.peer_id)
send_large_msg('chat#id' .. extra.chatid, result.first_name .. ' - ' .. result.username .. lang_text('botSet'))
send_large_msg('channel#id' .. extra.chatid, result.first_name .. ' - ' .. result.username .. lang_text('botSet'))
end
local function callback_unsetbot(extra, success, result)
if success == 0 then
send_large_msg('chat#id' .. extra.chatid, lang_text('noUsernameFound'))
send_large_msg('channel#id' .. extra.chatid, lang_text('noUsernameFound'))
return
end
local hash = 'botinteract'
redis:srem(hash, extra.chatid .. ':' .. result.peer_id)
send_large_msg('chat#id' .. extra.chatid, result.first_name .. ' - ' .. result.username .. lang_text('botUnset'))
send_large_msg('channel#id' .. extra.chatid, result.first_name .. ' - ' .. result.username .. lang_text('botUnset'))
end
local function list_botinteract(msg)
local list = redis:smembers('botinteract')
local text = ''
for k, v in pairs(list) do
text = text .. v .. "\n"
end
return text
end
local function run(msg, matches)
if matches[1]:lower() == "setbot" or matches[1]:lower() == "sasha imposta bot" and string.sub(matches[2]:lower(), -3) == 'bot' then
if is_admin1(msg) then
resolve_username(matches[2]:gsub("@", ""), callback_setbot, { chatid = msg.to.id })
return
else
return lang_text('require_admin')
end
end
if matches[1]:lower() == "unsetbot" or matches[1]:lower() == "sasha rimuovi bot" and string.sub(matches[2]:lower(), -3) == 'bot' then
if is_momod(msg) then
resolve_username(matches[2]:gsub("@", ""), callback_unsetbot, { chatid = msg.to.id })
return
else
return lang_text('require_owner')
end
end
if matches[1] == '$' then
local chat = ''
local bot = ''
local t = list_botinteract(msg):split('\n')
for i, v in pairs(t) do
chat, bot = v:match("(%d+):(%d+)")
if tonumber(msg.to.id) == tonumber(chat) then
msg.text = msg.text:gsub('§§', '')
send_large_msg('user#id' .. bot, msg.text)
end
end
end
if matches[1] == 'getchar' then
return '$'
end
if matches[1] == 'sendmedia' then
redis:set(msg.to.id, 'waiting')
return lang_text('sendMeMedia')
end
if matches[1]:lower() == 'undo' then
redis:del(msg.to.id)
return lang_text('cancelled')
end
if (matches[1] == '[photo]' or matches[1] == '[document]' or matches[1] == '[video]' or matches[1] == '[audio]' or matches[1] == '[contact]' or matches[1] == '[geo]') and redis:get(msg.to.id) then
local chat = ''
local bot = ''
local t = list_botinteract(msg):split('\n')
for i, v in pairs(t) do
chat, bot = v:match("(%d+):(%d+)")
if tonumber(msg.to.id) == tonumber(chat) then
fwd_msg('user#id' .. bot, msg.id, ok_cb, false)
end
end
redis:del(msg.to.id)
return lang_text('mediaForwarded')
end
end
local function pre_process(msg)
if not msg.text and msg.media then
msg.text = '[' .. msg.media.type .. ']'
end
if msg.to.type == 'user' then
local chat = ''
local bot = ''
local t = list_botinteract(msg):split('\n')
for i, v in pairs(t) do
chat, bot = v:match("(%d+):(%d+)")
if tonumber(msg.from.id) == tonumber(bot) then
if not msg.media then
send_large_msg('chat#id' .. chat, msg.text)
send_large_msg('channel#id' .. chat, msg.text)
else
fwd_msg('chat#id' .. chat, msg.id, ok_cb, false)
fwd_msg('channel#id' .. chat, msg.id, ok_cb, false)
end
end
end
end
return msg
end
return {
description = "BOTINTERACT",
patterns =
{
"^(%$).*$",
"^[#!/]([Gg][Ee][Tt][Cc][Hh][Aa][Rr])$",
"^[#!/]([Ss][Ee][Nn][Dd][Mm][Ee][Dd][Ii][Aa])$",
"^[#!/]([Ss][Ee][Tt][Bb][Oo][Tt]) (.*)$",
"^[#!/]([Uu][Nn][Ss][Ee][Tt][Bb][Oo][Tt]) (.*)$",
"^[#!/]([Uu][Nn][Dd][Oo])$",
"(%[(document)%])",
"(%[(photo)%])",
"(%[(video)%])",
"(%[(audio)%])",
"(%[(contact)%])",
"(%[(geo)%])",
},
run = run,
pre_process = pre_process,
min_rank = 0
-- usage
-- #getchar
-- $<text>
-- #sendmedia
-- MOD
-- (#unsetbot|sasha rimuovi bot)
-- ADMIN
-- (#setbot|sasha imposta bot)
}
|
local function callback_setbot(extra, success, result)
if success == 0 then
send_large_msg('chat#id' .. extra.chatid, lang_text('noUsernameFound'))
send_large_msg('channel#id' .. extra.chatid, lang_text('noUsernameFound'))
return
end
local hash = 'botinteract'
redis:sadd(hash, extra.chatid .. ':' .. result.peer_id)
send_large_msg('chat#id' .. extra.chatid, result.first_name .. ' - ' .. result.username .. lang_text('botSet'))
send_large_msg('channel#id' .. extra.chatid, result.first_name .. ' - ' .. result.username .. lang_text('botSet'))
end
local function callback_unsetbot(extra, success, result)
if success == 0 then
send_large_msg('chat#id' .. extra.chatid, lang_text('noUsernameFound'))
send_large_msg('channel#id' .. extra.chatid, lang_text('noUsernameFound'))
return
end
local hash = 'botinteract'
redis:srem(hash, extra.chatid .. ':' .. result.peer_id)
send_large_msg('chat#id' .. extra.chatid, result.first_name .. ' - ' .. result.username .. lang_text('botUnset'))
send_large_msg('channel#id' .. extra.chatid, result.first_name .. ' - ' .. result.username .. lang_text('botUnset'))
end
local function list_botinteract(msg)
local list = redis:smembers('botinteract')
local text = ''
for k, v in pairs(list) do
text = text .. v .. "\n"
end
return text
end
local function run(msg, matches)
if matches[1]:lower() == "setbot" or matches[1]:lower() == "sasha imposta bot" and string.sub(matches[2]:lower(), -3) == 'bot' then
if is_admin1(msg) then
resolve_username(matches[2]:gsub("@", ""), callback_setbot, { chatid = msg.to.id })
return
else
return lang_text('require_admin')
end
end
if matches[1]:lower() == "unsetbot" or matches[1]:lower() == "sasha rimuovi bot" and string.sub(matches[2]:lower(), -3) == 'bot' then
if is_momod(msg) then
resolve_username(matches[2]:gsub("@", ""), callback_unsetbot, { chatid = msg.to.id })
return
else
return lang_text('require_owner')
end
end
if matches[1] == '$' then
local chat = ''
local bot = ''
local t = list_botinteract(msg):split('\n')
for i, v in pairs(t) do
chat, bot = v:match("(%d+):(%d+)")
if tonumber(msg.to.id) == tonumber(chat) then
msg.text = msg.text:gsub('$', '')
send_large_msg('user#id' .. bot, msg.text)
end
end
end
if matches[1] == 'getchar' then
return '$'
end
if matches[1] == 'sendmedia' then
redis:set(msg.to.id, 'waiting')
return lang_text('sendMeMedia')
end
if matches[1]:lower() == 'undo' then
redis:del(msg.to.id)
return lang_text('cancelled')
end
if (matches[1] == '[photo]' or matches[1] == '[document]' or matches[1] == '[video]' or matches[1] == '[audio]' or matches[1] == '[contact]' or matches[1] == '[geo]') and redis:get(msg.to.id) then
local chat = ''
local bot = ''
local t = list_botinteract(msg):split('\n')
for i, v in pairs(t) do
chat, bot = v:match("(%d+):(%d+)")
if tonumber(msg.to.id) == tonumber(chat) then
fwd_msg('user#id' .. bot, msg.id, ok_cb, false)
end
end
redis:del(msg.to.id)
return lang_text('mediaForwarded')
end
end
local function pre_process(msg)
if not msg.text and msg.media then
msg.text = '[' .. msg.media.type .. ']'
end
if msg.to.type == 'user' then
local chat = ''
local bot = ''
local t = list_botinteract(msg):split('\n')
for i, v in pairs(t) do
chat, bot = v:match("(%d+):(%d+)")
if tonumber(msg.from.id) == tonumber(bot) then
if not msg.media then
fwd_msg('chat#id' .. chat, msg.id, ok_cb, false)
fwd_msg('channel#id' .. chat, msg.id, ok_cb, false)
else
fwd_msg('chat#id' .. chat, msg.id, ok_cb, false)
fwd_msg('channel#id' .. chat, msg.id, ok_cb, false)
end
end
end
end
return msg
end
return {
description = "BOTINTERACT",
patterns =
{
"^(%$).*$",
"^[#!/]([Gg][Ee][Tt][Cc][Hh][Aa][Rr])$",
"^[#!/]([Ss][Ee][Nn][Dd][Mm][Ee][Dd][Ii][Aa])$",
"^[#!/]([Ss][Ee][Tt][Bb][Oo][Tt]) (.*)$",
"^[#!/]([Uu][Nn][Ss][Ee][Tt][Bb][Oo][Tt]) (.*)$",
"^[#!/]([Uu][Nn][Dd][Oo])$",
"(%[(document)%])",
"(%[(photo)%])",
"(%[(video)%])",
"(%[(audio)%])",
"(%[(contact)%])",
"(%[(geo)%])",
},
run = run,
pre_process = pre_process,
min_rank = 0
-- usage
-- #getchar
-- $<text>
-- #sendmedia
-- MOD
-- (#unsetbot|sasha rimuovi bot)
-- ADMIN
-- (#setbot|sasha imposta bot)
}
|
fix botinteract
|
fix botinteract
|
Lua
|
agpl-3.0
|
xsolinsx/AISasha
|
c4244d392988177a4d542f84d7fa720476cda252
|
Sequential.lua
|
Sequential.lua
|
local Sequential, _ = torch.class('nn.Sequential', 'nn.Container')
function Sequential:__len()
return #self.modules
end
function Sequential:add(module)
if #self.modules == 0 then
self.gradInput = module.gradInput
end
table.insert(self.modules, module)
self.output = module.output
return self
end
function Sequential:insert(module, index)
index = index or (#self.modules + 1)
if index > (#self.modules + 1) or index < 1 then
error"index should be contiguous to existing modules"
end
table.insert(self.modules, index, module)
self.output = self.modules[#self.modules].output
self.gradInput = self.modules[1].gradInput
end
function Sequential:remove(index)
index = index or #self.modules
if index > #self.modules or index < 1 then
error"index out of range"
end
table.remove(self.modules, index)
self.output = self.modules[#self.modules].output
self.gradInput = self.modules[1].gradInput
end
function Sequential:updateOutput(input)
local currentOutput = input
for i=1,#self.modules do
currentOutput = self.modules[i]:updateOutput(currentOutput)
end
self.output = currentOutput
return currentOutput
end
function Sequential:updateGradInput(input, gradOutput)
local currentGradOutput = gradOutput
local currentModule = self.modules[#self.modules]
for i=#self.modules-1,1,-1 do
local previousModule = self.modules[i]
currentGradOutput = currentModule:updateGradInput(previousModule.output, currentGradOutput)
currentModule = previousModule
end
currentGradOutput = currentModule:updateGradInput(input, currentGradOutput)
self.gradInput = currentGradOutput
return currentGradOutput
end
function Sequential:accGradParameters(input, gradOutput, scale)
scale = scale or 1
local currentGradOutput = gradOutput
local currentModule = self.modules[#self.modules]
for i=#self.modules-1,1,-1 do
local previousModule = self.modules[i]
currentModule:accGradParameters(previousModule.output, currentGradOutput, scale)
currentGradOutput = currentModule.gradInput
currentModule = previousModule
end
currentModule:accGradParameters(input, currentGradOutput, scale)
end
function Sequential:backward(input, gradOutput, scale)
scale = scale or 1
local currentGradOutput = gradOutput
local currentModule = self.modules[#self.modules]
for i=#self.modules-1,1,-1 do
local previousModule = self.modules[i]
currentGradOutput = currentModule:backward(previousModule.output, currentGradOutput, scale)
currentModule.gradInput = currentGradOutput
currentModule = previousModule
end
currentGradOutput = currentModule:backward(input, currentGradOutput, scale)
self.gradInput = currentGradOutput
return currentGradOutput
end
function Sequential:accUpdateGradParameters(input, gradOutput, lr)
local currentGradOutput = gradOutput
local currentModule = self.modules[#self.modules]
for i=#self.modules-1,1,-1 do
local previousModule = self.modules[i]
currentModule:accUpdateGradParameters(previousModule.output, currentGradOutput, lr)
currentGradOutput = currentModule.gradInput
currentModule = previousModule
end
currentModule:accUpdateGradParameters(input, currentGradOutput, lr)
end
function Sequential:__tostring__()
local tab = ' '
local line = '\n'
local next = ' -> '
local str = 'nn.Sequential'
str = str .. ' {' .. line .. tab .. '[input'
for i=1,#self.modules do
str = str .. next .. '(' .. i .. ')'
end
str = str .. next .. 'output]'
for i=1,#self.modules do
str = str .. line .. tab .. '(' .. i .. '): ' .. tostring(self.modules[i]):gsub(line, line .. tab)
end
str = str .. line .. '}'
return str
end
|
local Sequential, _ = torch.class('nn.Sequential', 'nn.Container')
function Sequential:__len()
return #self.modules
end
function Sequential:add(module)
if #self.modules == 0 then
self.gradInput = module.gradInput
end
table.insert(self.modules, module)
self.output = module.output
return self
end
function Sequential:insert(module, index)
index = index or (#self.modules + 1)
if index > (#self.modules + 1) or index < 1 then
error"index should be contiguous to existing modules"
end
table.insert(self.modules, index, module)
self.output = self.modules[#self.modules].output
self.gradInput = self.modules[1].gradInput
end
function Sequential:remove(index)
index = index or #self.modules
if index > #self.modules or index < 1 then
error"index out of range"
end
table.remove(self.modules, index)
if #self.modules > 0 then
self.output = self.modules[#self.modules].output
self.gradInput = self.modules[1].gradInput
else
self.output = torch.Tensor()
self.gradInput = torch.Tensor()
end
end
function Sequential:updateOutput(input)
local currentOutput = input
for i=1,#self.modules do
currentOutput = self.modules[i]:updateOutput(currentOutput)
end
self.output = currentOutput
return currentOutput
end
function Sequential:updateGradInput(input, gradOutput)
local currentGradOutput = gradOutput
local currentModule = self.modules[#self.modules]
for i=#self.modules-1,1,-1 do
local previousModule = self.modules[i]
currentGradOutput = currentModule:updateGradInput(previousModule.output, currentGradOutput)
currentModule = previousModule
end
currentGradOutput = currentModule:updateGradInput(input, currentGradOutput)
self.gradInput = currentGradOutput
return currentGradOutput
end
function Sequential:accGradParameters(input, gradOutput, scale)
scale = scale or 1
local currentGradOutput = gradOutput
local currentModule = self.modules[#self.modules]
for i=#self.modules-1,1,-1 do
local previousModule = self.modules[i]
currentModule:accGradParameters(previousModule.output, currentGradOutput, scale)
currentGradOutput = currentModule.gradInput
currentModule = previousModule
end
currentModule:accGradParameters(input, currentGradOutput, scale)
end
function Sequential:backward(input, gradOutput, scale)
scale = scale or 1
local currentGradOutput = gradOutput
local currentModule = self.modules[#self.modules]
for i=#self.modules-1,1,-1 do
local previousModule = self.modules[i]
currentGradOutput = currentModule:backward(previousModule.output, currentGradOutput, scale)
currentModule.gradInput = currentGradOutput
currentModule = previousModule
end
currentGradOutput = currentModule:backward(input, currentGradOutput, scale)
self.gradInput = currentGradOutput
return currentGradOutput
end
function Sequential:accUpdateGradParameters(input, gradOutput, lr)
local currentGradOutput = gradOutput
local currentModule = self.modules[#self.modules]
for i=#self.modules-1,1,-1 do
local previousModule = self.modules[i]
currentModule:accUpdateGradParameters(previousModule.output, currentGradOutput, lr)
currentGradOutput = currentModule.gradInput
currentModule = previousModule
end
currentModule:accUpdateGradParameters(input, currentGradOutput, lr)
end
function Sequential:__tostring__()
local tab = ' '
local line = '\n'
local next = ' -> '
local str = 'nn.Sequential'
str = str .. ' {' .. line .. tab .. '[input'
for i=1,#self.modules do
str = str .. next .. '(' .. i .. ')'
end
str = str .. next .. 'output]'
for i=1,#self.modules do
str = str .. line .. tab .. '(' .. i .. '): ' .. tostring(self.modules[i]):gsub(line, line .. tab)
end
str = str .. line .. '}'
return str
end
|
fixing Sequential.remove corner case
|
fixing Sequential.remove corner case
|
Lua
|
bsd-3-clause
|
andreaskoepf/nn,eulerreich/nn,sbodenstein/nn,lukasc-ch/nn,lvdmaaten/nn,adamlerer/nn,Jeffyrao/nn,ominux/nn,diz-vara/nn,PierrotLC/nn,ivendrov/nn,douwekiela/nn,joeyhng/nn,abeschneider/nn,vgire/nn,kmul00/nn,davidBelanger/nn,LinusU/nn,hughperkins/nn,bartvm/nn,jhjin/nn,EnjoyHacking/nn,clementfarabet/nn,GregSatre/nn,Moodstocks/nn,aaiijmrtt/nn,PraveerSINGH/nn,colesbury/nn,elbamos/nn,jonathantompson/nn,mlosch/nn,zhangxiangxiao/nn,sagarwaghmare69/nn,noa/nn,jzbontar/nn,caldweln/nn,apaszke/nn,rotmanmi/nn,witgo/nn,nicholas-leonard/nn,xianjiec/nn,Djabbz/nn,eriche2016/nn,Aysegul/nn,forty-2/nn
|
4fad635aa45f4de4bb97f748f3d3cc23e23f9763
|
training/main.lua
|
training/main.lua
|
#!/usr/bin/env th
require 'torch'
require 'optim'
require 'paths'
require 'xlua'
local opts = paths.dofile('opts.lua')
opt = opts.parse(arg)
print(opt)
if opt.cuda then
require 'cutorch'
cutorch.setDevice(opt.device)
end
torch.save(paths.concat(opt.save, 'opts.t7'), opt, 'ascii')
print('Saving everything to: ' .. opt.save)
torch.setdefaulttensortype('torch.FloatTensor')
torch.manualSeed(opt.manualSeed)
paths.dofile('data.lua')
paths.dofile('util.lua')
model = nil
criterion = nil
paths.dofile('train.lua')
paths.dofile('test.lua')
if opt.peoplePerBatch > nClasses then
print('\n\nError: opt.peoplePerBatch > number of classes. Please decrease this value.')
print(' + opt.peoplePerBatch: ', opt.peoplePerBatch)
print(' + number of classes: ', nClasses)
os.exit(-1)
end
epoch = opt.epochNumber
for _=1,opt.nEpochs do
train()
if opt.testing then
test()
end
model = saveModel(model)
epoch = epoch + 1
end
|
#!/usr/bin/env th
require 'torch'
require 'optim'
require 'paths'
require 'xlua'
local opts = paths.dofile('opts.lua')
opt = opts.parse(arg)
print(opt)
if opt.cuda then
require 'cutorch'
cutorch.setDevice(opt.device)
end
torch.save(paths.concat(opt.save, 'opts.t7'), opt, 'ascii')
print('Saving everything to: ' .. opt.save)
torch.setdefaulttensortype('torch.FloatTensor')
torch.manualSeed(opt.manualSeed)
paths.dofile('data.lua')
paths.dofile('util.lua')
model = nil
criterion = nil
paths.dofile('train.lua')
paths.dofile('test.lua')
if opt.peoplePerBatch > nClasses then
print('\n\nError: opt.peoplePerBatch > number of classes. Please decrease this value.')
print(' + opt.peoplePerBatch: ', opt.peoplePerBatch)
print(' + number of classes: ', nClasses)
os.exit(-1)
end
epoch = opt.epochNumber
for _=1,opt.nEpochs do
train()
model = saveModel(model)
if opt.testing then
test()
end
epoch = epoch + 1
end
|
Fix testing
|
Fix testing
|
Lua
|
apache-2.0
|
Alexx-G/openface,Alexx-G/openface,nmabhi/Webface,cmusatyalab/openface,Alexx-G/openface,francisleunggie/openface,cmusatyalab/openface,xinfang/face-recognize,francisleunggie/openface,nmabhi/Webface,nmabhi/Webface,Alexx-G/openface,xinfang/face-recognize,cmusatyalab/openface,nmabhi/Webface,francisleunggie/openface,xinfang/face-recognize
|
4e6c7dc7f979a1dc4651170e614b98f03631a5d1
|
src/luacheck/cache.lua
|
src/luacheck/cache.lua
|
local serializer = require "luacheck.serializer"
local utils = require "luacheck.utils"
local cache = {}
-- Cache file contains check results for n unique filenames.
-- Cache file consists of 3n+2 lines, the first line is empty and the second is cache format version.
-- The rest are contain file records, 3 lines per file.
-- For each file, first line is the filename, second is modification time,
-- third is check result in lua table format.
-- Event fields are compressed into array indexes.
cache.format_version = 34
-- Returns array of triplets of lines from cache fh.
local function read_triplets(fh)
local res = {}
while true do
local filename = fh:read()
if filename then
local mtime = fh:read() or ""
local cached = fh:read() or ""
table.insert(res, {filename, mtime, cached})
else
break
end
end
return res
end
-- Writes cache triplets into fh.
local function write_triplets(fh, triplets)
for _, triplet in ipairs(triplets) do
fh:write(triplet[1], "\n")
fh:write(triplet[2], "\n")
fh:write(triplet[3], "\n")
end
end
local function check_version_header(fh)
local first_line = fh:read()
return (first_line == "" or first_line == "\r") and tonumber(fh:read()) == cache.format_version
end
local function write_version_header(fh)
fh:write("\n", tostring(cache.format_version), "\n")
end
-- Loads cache for filenames given mtimes from cache cache_filename.
-- Returns table mapping filenames to cached check results.
-- On corrupted cache returns nil, on version mismatch returns {}.
function cache.load(cache_filename, filenames, mtimes)
local fh = io.open(cache_filename, "rb")
if not fh then
return {}
end
if not check_version_header(fh) then
fh:close()
return {}
end
local result = {}
local not_yet_found = utils.array_to_set(filenames)
while next(not_yet_found) do
local filename = fh:read()
if not filename then
fh:close()
return result
end
if filename:sub(-1) == "\r" then
filename = filename:sub(1, -2)
end
local mtime = fh:read()
local cached = fh:read()
if not mtime or not cached then
fh:close()
return
end
mtime = tonumber(mtime)
if not mtime then
fh:close()
return
end
if not_yet_found[filename] then
if mtimes[not_yet_found[filename]] == mtime then
result[filename] = serializer.load_check_result(cached)
if result[filename] == nil then
fh:close()
return
end
end
not_yet_found[filename] = nil
end
end
fh:close()
return result
end
-- Updates cache at cache_filename with results for filenames.
-- Returns success flag + whether update was append-only.
function cache.update(cache_filename, filenames, mtimes, results)
local old_triplets = {}
local can_append = false
local fh = io.open(cache_filename, "rb")
if fh then
if check_version_header(fh) then
old_triplets = read_triplets(fh)
can_append = true
end
fh:close()
end
local filename_set = utils.array_to_set(filenames)
local old_filename_set = {}
-- Update old cache for files which got a new result.
for i, triplet in ipairs(old_triplets) do
old_filename_set[triplet[1]] = true
local file_index = filename_set[triplet[1]]
if file_index then
can_append = false
old_triplets[i][2] = mtimes[file_index]
old_triplets[i][3] = serializer.dump_check_result(results[file_index])
end
end
local new_triplets = {}
for _, filename in ipairs(filenames) do
-- Use unique index (there could be duplicate filenames).
local file_index = filename_set[filename]
if file_index and not old_filename_set[filename] then
table.insert(new_triplets, {
filename,
mtimes[file_index],
serializer.dump_check_result(results[file_index])
})
-- Do not save result for this filename again.
filename_set[filename] = nil
end
end
if can_append then
if #new_triplets > 0 then
fh = io.open(cache_filename, "ab")
if not fh then
return false
end
write_triplets(fh, new_triplets)
fh:close()
end
else
fh = io.open(cache_filename, "wb")
if not fh then
return false
end
write_version_header(fh)
write_triplets(fh, old_triplets)
write_triplets(fh, new_triplets)
fh:close()
end
return true, can_append
end
return cache
|
local serializer = require "luacheck.serializer"
local utils = require "luacheck.utils"
local cache = {}
-- Cache file contains check results for n unique filenames.
-- Cache file consists of 3n+2 lines, the first line is empty and the second is cache format version.
-- The rest are contain file records, 3 lines per file.
-- For each file, first line is the filename, second is modification time,
-- third is check result in lua table format.
-- Event fields are compressed into array indexes.
cache.format_version = 34
-- Returns array of triplets of lines from cache fh.
local function read_triplets(fh)
local res = {}
while true do
local filename = fh:read()
if filename then
local mtime = fh:read() or ""
local cached = fh:read() or ""
table.insert(res, {filename, mtime, cached})
else
break
end
end
return res
end
-- Writes cache triplets into fh.
local function write_triplets(fh, triplets)
for _, triplet in ipairs(triplets) do
fh:write(triplet[1], "\n")
fh:write(triplet[2], "\n")
fh:write(triplet[3], "\n")
end
end
local function check_version_header(fh)
local first_line = fh:read()
if first_line ~= "" and first_line ~= "\r" then
return false
end
local second_line = fh:read()
return tonumber(second_line) == cache.format_version
end
local function write_version_header(fh)
fh:write("\n", tostring(cache.format_version), "\n")
end
-- Loads cache for filenames given mtimes from cache cache_filename.
-- Returns table mapping filenames to cached check results.
-- On corrupted cache returns nil, on version mismatch returns {}.
function cache.load(cache_filename, filenames, mtimes)
local fh = io.open(cache_filename, "rb")
if not fh then
return {}
end
if not check_version_header(fh) then
fh:close()
return {}
end
local result = {}
local not_yet_found = utils.array_to_set(filenames)
while next(not_yet_found) do
local filename = fh:read()
if not filename then
fh:close()
return result
end
if filename:sub(-1) == "\r" then
filename = filename:sub(1, -2)
end
local mtime = fh:read()
local cached = fh:read()
if not mtime or not cached then
fh:close()
return
end
mtime = tonumber(mtime)
if not mtime then
fh:close()
return
end
if not_yet_found[filename] then
if mtimes[not_yet_found[filename]] == mtime then
result[filename] = serializer.load_check_result(cached)
if result[filename] == nil then
fh:close()
return
end
end
not_yet_found[filename] = nil
end
end
fh:close()
return result
end
-- Updates cache at cache_filename with results for filenames.
-- Returns success flag + whether update was append-only.
function cache.update(cache_filename, filenames, mtimes, results)
local old_triplets = {}
local can_append = false
local fh = io.open(cache_filename, "rb")
if fh then
if check_version_header(fh) then
old_triplets = read_triplets(fh)
can_append = true
end
fh:close()
end
local filename_set = utils.array_to_set(filenames)
local old_filename_set = {}
-- Update old cache for files which got a new result.
for i, triplet in ipairs(old_triplets) do
old_filename_set[triplet[1]] = true
local file_index = filename_set[triplet[1]]
if file_index then
can_append = false
old_triplets[i][2] = mtimes[file_index]
old_triplets[i][3] = serializer.dump_check_result(results[file_index])
end
end
local new_triplets = {}
for _, filename in ipairs(filenames) do
-- Use unique index (there could be duplicate filenames).
local file_index = filename_set[filename]
if file_index and not old_filename_set[filename] then
table.insert(new_triplets, {
filename,
mtimes[file_index],
serializer.dump_check_result(results[file_index])
})
-- Do not save result for this filename again.
filename_set[filename] = nil
end
end
if can_append then
if #new_triplets > 0 then
fh = io.open(cache_filename, "ab")
if not fh then
return false
end
write_triplets(fh, new_triplets)
fh:close()
end
else
fh = io.open(cache_filename, "wb")
if not fh then
return false
end
write_version_header(fh)
write_triplets(fh, old_triplets)
write_triplets(fh, new_triplets)
fh:close()
end
return true, can_append
end
return cache
|
Fix potential error on cache loading with an error reading the second line
|
Fix potential error on cache loading with an error reading the second line
tonumber expects a number as the second argument,
therefore `tonumber(fh:read())` is unsafe.
|
Lua
|
mit
|
xpol/luacheck,mpeterv/luacheck,mpeterv/luacheck,mpeterv/luacheck,xpol/luacheck,xpol/luacheck
|
76568bbb02430dda6689a97edc3c079a7b954e67
|
tests/test-http-parse-error.lua
|
tests/test-http-parse-error.lua
|
--[[
Copyright 2012 The Luvit Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
require('helper')
local net = require('net')
local http = require('http')
local PORT = process.env.PORT or 10081
local HOST = '127.0.0.1'
local running = false
local caughtErrors = 0
local gotParseError = false
local server = net.createServer(function(client)
client:write('test')
client:destroy()
end)
server:listen(PORT, HOST, function()
running = true
local req = http.request({
host = HOST,
port = PORT,
path = '/'
}, function (res)
end)
req:on("error", function(err)
msg = tostring(err)
caughtErrors = caughtErrors + 1
if msg:find('parse error') then
gotParseError = true
end
if running then
running = false
req:destroy()
server:close()
end
end)
req:done()
end)
process:on('exit', function()
assert(caughtErrors == 2)
assert(gotParseError)
end)
|
--[[
Copyright 2012 The Luvit Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
require('helper')
local net = require('net')
local http = require('http')
local PORT = process.env.PORT or 10081
local HOST = '127.0.0.1'
local running = false
local caughtErrors = 0
local gotParseError = false
local server = net.createServer(function(client)
client:write('test')
client:on("end", function()
client:destroy()
end)
end)
server:listen(PORT, HOST, function()
running = true
local req = http.request({
host = HOST,
port = PORT,
path = '/'
}, function (res)
end)
req:on("error", function(err)
msg = tostring(err)
caughtErrors = caughtErrors + 1
if msg:find('parse error') then
gotParseError = true
end
if running then
running = false
req:destroy()
server:close()
end
end)
req:done()
end)
process:on('exit', function()
assert(caughtErrors == 2)
assert(gotParseError)
end)
|
fix test-http-parse-error.lua to be a little more concise
|
fix test-http-parse-error.lua to be a little more concise
* fixes the test on windows
|
Lua
|
apache-2.0
|
sousoux/luvit,bsn069/luvit,GabrielNicolasAvellaneda/luvit-upstream,bsn069/luvit,luvit/luvit,kaustavha/luvit,rjeli/luvit,DBarney/luvit,boundary/luvit,bsn069/luvit,kaustavha/luvit,boundary/luvit,sousoux/luvit,rjeli/luvit,kaustavha/luvit,DBarney/luvit,DBarney/luvit,sousoux/luvit,zhaozg/luvit,DBarney/luvit,boundary/luvit,GabrielNicolasAvellaneda/luvit-upstream,luvit/luvit,rjeli/luvit,sousoux/luvit,boundary/luvit,boundary/luvit,boundary/luvit,GabrielNicolasAvellaneda/luvit-upstream,zhaozg/luvit,sousoux/luvit,sousoux/luvit,rjeli/luvit,GabrielNicolasAvellaneda/luvit-upstream
|
ba62c8cc315beb8e9075b34397acb763c3d34950
|
nodemcu/webz/server.lua
|
nodemcu/webz/server.lua
|
redled = 1
whiteled = 2
gpio.mode(redled, gpio.OUTPUT)
gpio.mode(whiteled, 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>ESP8266 Web Server</h1>";
buf = buf.."<p>White led <a href=\"?pin=ONRED\"><button>ON</button></a> <a href=\"?pin=OFFRED\"><button>OFF</button></a></p>";
buf = buf.."<p>Red led <a href=\"?pin=ONWHITE\"><button>ON</button></a> <a href=\"?pin=OFFWHITE\"><button>OFF</button></a></p>";
local _on,_off = "",""
if(_GET.pin == "ONRED")then
gpio.write(redled, gpio.HIGH);
elseif(_GET.pin == "OFFRED")then
gpio.write(redled, gpio.LOW);
elseif(_GET.pin == "ONWHITE")then
gpio.write(whiteled, gpio.HIGH);
elseif(_GET.pin == "OFFWHITE")then
gpio.write(whiteled, gpio.LOW);
end
client:send(buf);
client:close();
collectgarbage();
end)
end)
|
whiteled = 1
redled = 2
gpio.mode(whiteled, gpio.OUTPUT)
gpio.mode(redled, 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>ESP8266 light switch</h1>";
buf = buf.."<p>White led <a href=\"?pin=ONWHITE\"><button>ON</button></a> ";
buf = buf.."<a href=\"?pin=OFFWHITE\"><button>OFF</button></a></p>";
buf = buf.."<p>Red led <a href=\"?pin=ONRED\"><button>ON</button></a> ";
buf = buf.."<a href=\"?pin=OFFRED\"><button>OFF</button></a></p>";
local _on,_off = "",""
if(_GET.pin == "ONWHITE")then
gpio.write(whiteled, gpio.HIGH);
elseif(_GET.pin == "OFFWHITE")then
gpio.write(whiteled, gpio.LOW);
elseif(_GET.pin == "ONRED")then
gpio.write(redled, gpio.HIGH);
elseif(_GET.pin == "OFFRED")then
gpio.write(redled, gpio.LOW);
end
client:send(buf);
client:close();
collectgarbage();
end)
end)
|
fixed wrong avrable assignments for colors
|
fixed wrong avrable assignments for colors
|
Lua
|
mit
|
tuvokki/pistuff,tuvokki/pistuff,tuvokki/pistuff
|
bac92c34172ad70802d56487c368d4a4da69efc8
|
src/jet/daemon/radix.lua
|
src/jet/daemon/radix.lua
|
-- Implements a radix tree for the jet-daemon
local pairs = pairs
local next = next
local tinsert = table.insert
local tremove = table.remove
local new = function()
local j = {}
-- the table that holds the radix_tree
j.radix_tree = {}
-- elments that can be filled by several functions
-- and be returned as set of possible hits
j.radix_elements = {}
-- internal tree instance or table of tree instances
-- used to hold parts of the tree that may be interesting afterwards
j.return_tree = {}
-- this FSM is used for string comparison
-- can evaluate if the radix tree contains or ends with a specific string
local lookup_fsm = function (wordpart,next_state,next_letter)
if wordpart:sub(next_state,next_state) ~= next_letter then
if wordpart:sub(1,1) ~= next_letter then
return false,0
else
return false,1
end
end
if #wordpart == next_state then
return true,next_state
else
return false,next_state
end
end
-- evaluate if the radix tree starts with a specific string
-- returns pointer to subtree
local root_lookup
root_lookup = function(tree_instance,part)
if #part == 0 then
j.return_tree = tree_instance
else
local s = part:sub(1,1)
if tree_instance[s] ~= true then
root_lookup(tree_instance[s], part:sub(2))
end
end
end
-- evaluate if the radix tree contains or ends with a specific string
-- returns list of pointers to subtrees
local leaf_lookup
leaf_lookup = function(tree_instance,word,state)
local next_state = state + 1
for k,v in pairs(tree_instance) do
if v ~= true then
local hit,next_state = lookup_fsm(word,next_state,k)
if hit == true then
tinsert(j.return_tree,v)
else
leaf_lookup(v,word,next_state)
end
end
end
end
-- takes a single tree or a list of trees
-- traverses the trees and adds all elements to j.radix_elements
local radix_traverse
radix_traverse = function(tree_instance)
for k,v in pairs(tree_instance) do
if v == true then
j.radix_elements[k] = true
elseif v ~= true then
radix_traverse(v)
end
end
end
-- adds a new element to the tree
local add_to_tree = function(word)
local t = j.radix_tree
for char in word:gfind('.') do
if t[char] == true or t[char] == nil then
t[char] = {}
end
t = t[char]
end
t[word] = true
end
-- removes an element from the tree
local remove_from_tree = function(word)
local t = j.radix_tree
for char in word:gfind('.') do
if t[char] == true then
return
end
t = t[char]
end
t[word] = nil
end
-- performs the respective actions for the parts of a fetcher
-- that can be handled by a radix tree
-- fills j.radix_elements with all hits that were found
local match_parts = function(tree_instance,parts)
j.radix_elements = {}
if parts['equals'] then
j.return_tree = {}
root_lookup(tree_instance,parts['equals'])
if j.return_tree[parts['equals']] == true then
j.radix_elements[parts['equals']] = true
end
else
local temp_tree = tree_instance
if parts['startsWith'] then
j.return_tree = {}
root_lookup(temp_tree,parts['startsWith'])
temp_tree = j.return_tree
end
if parts['contains'] then
j.return_tree = {}
leaf_lookup(temp_tree,parts['contains'],0)
temp_tree = j.return_tree
end
if parts['endsWith'] then
j.return_tree = {}
leaf_lookup(temp_tree,parts['endsWith'],0)
for k,t in pairs(j.return_tree) do
for _,v in pairs(t) do
if v ~= true then
j.return_tree[k] = nil
break
end
end
end
temp_tree = j.return_tree
end
if temp_tree then
radix_traverse(temp_tree)
end
end
end
-- evaluates if the fetch operation can be handled
-- completely or partially by the radix tree
-- returns elements from the j.radix_tree if it can be handled
-- and nil otherwise
local get_possible_matches = function(peer,params,fetch_id,is_case_insensitive)
local involves_path_match = params.path
local involves_value_match = params.value or params.valueField
local level = 'impossible'
local radix_expressions = {}
if involves_path_match and not is_case_insensitive then
for name,value in pairs(params.path) do
if name == 'equals' or name == 'startsWith' or name == 'endsWith' or name == 'contains' then
if radix_expressions[name] then
level = 'impossible'
break
end
radix_expressions[name] = value
if level == 'partial_pending' or involves_value_match then
level = 'partial'
elseif level ~= 'partial' then
level = 'all'
end
else
if level == 'easy' or level == 'partial' then
level = 'partial'
else
level = 'partial_pending'
end
end
end
if level == 'partial_pending' then
level = 'impossible'
end
end
if level ~= 'impossible' then
match_parts(j.radix_tree,radix_expressions)
return j.radix_elements
else
return nil
end
end
j.add = function(word)
add_to_tree(word)
end
j.remove = function(word)
remove_from_tree(word)
end
j.get_possible_matches = get_possible_matches
-- for unit testing
j.match_parts = function(parts,xxx)
match_parts(j.radix_tree,parts,xxx)
end
j.found_elements = function()
return j.radix_elements
end
return j
end
return {
new = new
}
|
-- Implements a radix tree for the jet-daemon
local pairs = pairs
local next = next
local tinsert = table.insert
local tremove = table.remove
local new = function()
local j = {}
-- the table that holds the radix_tree
j.radix_tree = {}
-- elments that can be filled by several functions
-- and be returned as set of possible hits
j.radix_elements = {}
-- internal tree instance or table of tree instances
-- used to hold parts of the tree that may be interesting afterwards
j.return_tree = {}
-- this FSM is used for string comparison
-- can evaluate if the radix tree contains or ends with a specific string
local lookup_fsm = function (wordpart,next_state,next_letter)
if wordpart:sub(next_state,next_state) ~= next_letter then
if wordpart:sub(1,1) ~= next_letter then
return false,0
else
return false,1
end
end
if #wordpart == next_state then
return true,next_state
else
return false,next_state
end
end
-- evaluate if the radix tree starts with a specific string
-- returns pointer to subtree
local root_lookup
root_lookup = function(tree_instance,part)
if #part == 0 then
j.return_tree = tree_instance
else
local s = part:sub(1,1)
if tree_instance and tree_instance[s] ~= true then
root_lookup(tree_instance[s], part:sub(2))
end
end
end
-- evaluate if the radix tree contains or ends with a specific string
-- returns list of pointers to subtrees
local leaf_lookup
leaf_lookup = function(tree_instance,word,state)
local next_state = state + 1
if tree_instance then
for k,v in pairs(tree_instance) do
if v ~= true then
local hit,next_state = lookup_fsm(word,next_state,k)
if hit == true then
tinsert(j.return_tree,v)
else
leaf_lookup(v,word,next_state)
end
end
end
end
end
-- takes a single tree or a list of trees
-- traverses the trees and adds all elements to j.radix_elements
local radix_traverse
radix_traverse = function(tree_instance)
for k,v in pairs(tree_instance) do
if v == true then
j.radix_elements[k] = true
elseif v ~= true then
radix_traverse(v)
end
end
end
-- adds a new element to the tree
local add_to_tree = function(word)
local t = j.radix_tree
for char in word:gfind('.') do
if t[char] == true or t[char] == nil then
t[char] = {}
end
t = t[char]
end
t[word] = true
end
-- removes an element from the tree
local remove_from_tree = function(word)
local t = j.radix_tree
for char in word:gfind('.') do
if t[char] == true then
return
end
t = t[char]
end
t[word] = nil
end
-- performs the respective actions for the parts of a fetcher
-- that can be handled by a radix tree
-- fills j.radix_elements with all hits that were found
local match_parts = function(tree_instance,parts)
j.radix_elements = {}
if parts['equals'] then
j.return_tree = {}
root_lookup(tree_instance,parts['equals'])
if j.return_tree[parts['equals']] == true then
j.radix_elements[parts['equals']] = true
end
else
local temp_tree = tree_instance
if parts['startsWith'] then
j.return_tree = {}
root_lookup(temp_tree,parts['startsWith'])
temp_tree = j.return_tree
end
if parts['contains'] then
j.return_tree = {}
leaf_lookup(temp_tree,parts['contains'],0)
temp_tree = j.return_tree
end
if parts['endsWith'] then
j.return_tree = {}
leaf_lookup(temp_tree,parts['endsWith'],0)
for k,t in pairs(j.return_tree) do
for _,v in pairs(t) do
if v ~= true then
j.return_tree[k] = nil
break
end
end
end
temp_tree = j.return_tree
end
if temp_tree then
radix_traverse(temp_tree)
end
end
end
-- evaluates if the fetch operation can be handled
-- completely or partially by the radix tree
-- returns elements from the j.radix_tree if it can be handled
-- and nil otherwise
local get_possible_matches = function(peer,params,fetch_id,is_case_insensitive)
local involves_path_match = params.path
local involves_value_match = params.value or params.valueField
local level = 'impossible'
local radix_expressions = {}
if involves_path_match and not is_case_insensitive then
for name,value in pairs(params.path) do
if name == 'equals' or name == 'startsWith' or name == 'endsWith' or name == 'contains' then
if radix_expressions[name] then
level = 'impossible'
break
end
radix_expressions[name] = value
if level == 'partial_pending' or involves_value_match then
level = 'partial'
elseif level ~= 'partial' then
level = 'all'
end
else
if level == 'easy' or level == 'partial' then
level = 'partial'
else
level = 'partial_pending'
end
end
end
if level == 'partial_pending' then
level = 'impossible'
end
end
if level ~= 'impossible' then
match_parts(j.radix_tree,radix_expressions)
return j.radix_elements
else
return nil
end
end
j.add = function(word)
add_to_tree(word)
end
j.remove = function(word)
remove_from_tree(word)
end
j.get_possible_matches = get_possible_matches
-- for unit testing
j.match_parts = function(parts,xxx)
match_parts(j.radix_tree,parts,xxx)
end
j.found_elements = function()
return j.radix_elements
end
return j
end
return {
new = new
}
|
fixed nil error
|
fixed nil error
|
Lua
|
mit
|
lipp/lua-jet
|
71c404e39cbbf9f5970a3c2caa07bbda71c64f0f
|
plugins/botinteract.lua
|
plugins/botinteract.lua
|
local function callback_setbot(extra, success, result)
if success == 0 then
send_large_msg('chat#id' .. extra.chatid, lang_text('noUsernameFound'))
send_large_msg('channel#id' .. extra.chatid, lang_text('noUsernameFound'))
return
end
local hash = 'botinteract'
redis:sadd(hash, extra.chatid .. ':' .. result.peer_id)
send_large_msg('chat#id' .. extra.chatid, result.first_name .. ' - ' .. result.username .. lang_text('botSet'))
send_large_msg('channel#id' .. extra.chatid, result.first_name .. ' - ' .. result.username .. lang_text('botSet'))
end
local function callback_unsetbot(extra, success, result)
if success == 0 then
send_large_msg('chat#id' .. extra.chatid, lang_text('noUsernameFound'))
send_large_msg('channel#id' .. extra.chatid, lang_text('noUsernameFound'))
return
end
local hash = 'botinteract'
redis:srem(hash, extra.chatid .. ':' .. result.peer_id)
send_large_msg('chat#id' .. extra.chatid, result.first_name .. ' - ' .. result.username .. lang_text('botUnset'))
send_large_msg('channel#id' .. extra.chatid, result.first_name .. ' - ' .. result.username .. lang_text('botUnset'))
end
local function list_botinteract(msg)
local list = redis:smembers('botinteract')
local text = ''
for k, v in pairs(list) do
text = text .. v .. "\n"
end
return text
end
local function run(msg, matches)
if matches[1]:lower() == "setbot" or matches[1]:lower() == "sasha imposta bot" and string.sub(matches[2]:lower(), -3) == 'bot' then
if is_admin1(msg) then
resolve_username(matches[2]:gsub("@", ""), callback_setbot, { chatid = msg.to.id })
return
else
return lang_text('require_admin')
end
end
if matches[1]:lower() == "unsetbot" or matches[1]:lower() == "sasha rimuovi bot" and string.sub(matches[2]:lower(), -3) == 'bot' then
if is_owner(msg) then
resolve_username(matches[2]:gsub("@", ""), callback_unsetbot, { chatid = msg.to.id })
return
else
return lang_text('require_owner')
end
end
if matches[1] == '§§' then
if is_momod(msg) then
local chat = ''
local bot = ''
local t = list_botinteract(msg):split('\n')
for i, v in pairs(t) do
chat, bot = v:match("(%d+):(%d+)")
if tonumber(msg.to.id) == tonumber(chat) then
msg.text = msg.text:gsub('§§', '')
send_large_msg('user#id' .. bot, msg.text)
end
end
else
return lang_text('require_mod')
end
end
end
local function pre_process(msg)
if msg.to.type == 'user' then
local chat = ''
local bot = ''
local t = list_botinteract(msg):split('\n')
for i, v in pairs(t) do
chat, bot = v:match("(%d+):(%d+)")
if tonumber(msg.from.id) == tonumber(bot) then
send_large_msg('chat#id' .. chat, msg.text)
send_large_msg('channel#id' .. chat, msg.text)
end
end
end
return msg
end
return {
description = "BOTINTERACT",
patterns =
{
-- MOD
"^(§§).*$",
"^[#!/]([Ss][Ee][Nn][Dd][Mm][Ee][Dd][Ii][Aa])$",
-- ADMIN
"^[#!/]([Ss][Ee][Tt][Bb][Oo][Tt]) (.*)$",
},
run = run,
pre_process = pre_process,
min_rank = 1
-- usage
-- MOD
-- §§<text>
-- OWNER
-- (#unsetbot|sasha rimuovi bot)
-- ADMIN
-- (#setbot|sasha imposta bot)
}
|
local function callback_setbot(extra, success, result)
if success == 0 then
send_large_msg('chat#id' .. extra.chatid, lang_text('noUsernameFound'))
send_large_msg('channel#id' .. extra.chatid, lang_text('noUsernameFound'))
return
end
local hash = 'botinteract'
redis:sadd(hash, extra.chatid .. ':' .. result.peer_id)
send_large_msg('chat#id' .. extra.chatid, result.first_name .. ' - ' .. result.username .. lang_text('botSet'))
send_large_msg('channel#id' .. extra.chatid, result.first_name .. ' - ' .. result.username .. lang_text('botSet'))
end
local function callback_unsetbot(extra, success, result)
if success == 0 then
send_large_msg('chat#id' .. extra.chatid, lang_text('noUsernameFound'))
send_large_msg('channel#id' .. extra.chatid, lang_text('noUsernameFound'))
return
end
local hash = 'botinteract'
redis:srem(hash, extra.chatid .. ':' .. result.peer_id)
send_large_msg('chat#id' .. extra.chatid, result.first_name .. ' - ' .. result.username .. lang_text('botUnset'))
send_large_msg('channel#id' .. extra.chatid, result.first_name .. ' - ' .. result.username .. lang_text('botUnset'))
end
local function list_botinteract(msg)
local list = redis:smembers('botinteract')
local text = ''
for k, v in pairs(list) do
text = text .. v .. "\n"
end
return text
end
local function run(msg, matches)
if matches[1]:lower() == "setbot" or matches[1]:lower() == "sasha imposta bot" and string.sub(matches[2]:lower(), -3) == 'bot' then
if is_admin1(msg) then
resolve_username(matches[2]:gsub("@", ""), callback_setbot, { chatid = msg.to.id })
return
else
return lang_text('require_admin')
end
end
if matches[1]:lower() == "unsetbot" or matches[1]:lower() == "sasha rimuovi bot" and string.sub(matches[2]:lower(), -3) == 'bot' then
if is_owner(msg) then
resolve_username(matches[2]:gsub("@", ""), callback_unsetbot, { chatid = msg.to.id })
return
else
return lang_text('require_owner')
end
end
if matches[1] == '§§' then
if is_momod(msg) then
local chat = ''
local bot = ''
local t = list_botinteract(msg):split('\n')
for i, v in pairs(t) do
chat, bot = v:match("(%d+):(%d+)")
if tonumber(msg.to.id) == tonumber(chat) then
msg.text = msg.text:gsub('§§', '')
send_large_msg('user#id' .. bot, msg.text)
end
end
else
return lang_text('require_mod')
end
end
end
local function pre_process(msg)
if msg.to.type == 'user' then
local chat = ''
local bot = ''
local t = list_botinteract(msg):split('\n')
for i, v in pairs(t) do
chat, bot = v:match("(%d+):(%d+)")
if tonumber(msg.from.id) == tonumber(bot) then
send_large_msg('chat#id' .. chat, msg.text)
send_large_msg('channel#id' .. chat, msg.text)
end
end
end
return msg
end
return {
description = "BOTINTERACT",
patterns =
{
"^(§§).*$",
"^[#!/]([Ss][Ee][Nn][Dd][Mm][Ee][Dd][Ii][Aa])$",
"^[#!/]([Ss][Ee][Tt][Bb][Oo][Tt]) (.*)$",
"^[#!/]([Uu][Nn][Ss][Ee][Tt][Bb][Oo][Tt]) (.*)$",
},
run = run,
pre_process = pre_process,
min_rank = 1
-- usage
-- MOD
-- §§<text>
-- OWNER
-- (#unsetbot|sasha rimuovi bot)
-- ADMIN
-- (#setbot|sasha imposta bot)
}
|
fix missing pattern
|
fix missing pattern
|
Lua
|
agpl-3.0
|
xsolinsx/AISasha
|
8bc1c56f9ca20a052b22592149d66158330a3605
|
build/LLVM.lua
|
build/LLVM.lua
|
-- Setup the LLVM dependency directories
LLVMRootDir = depsdir .. "/llvm/"
local LLVMDirPerConfiguration = false
local LLVMRootDirDebug = ""
local LLVMRootDirRelease = ""
require "scripts/LLVM"
function SearchLLVM()
LLVMRootDirDebug = basedir .. "/scripts/" .. get_llvm_package_name(nil, "Debug")
LLVMRootDirRelease = basedir .. "/scripts/" .. get_llvm_package_name()
if os.isdir(LLVMRootDirDebug) or os.isdir(LLVMRootDirRelease) then
LLVMDirPerConfiguration = true
print("Using debug LLVM build: " .. LLVMRootDirDebug)
print("Using release LLVM build: " .. LLVMRootDirRelease)
elseif os.isdir(LLVMRootDir) then
print("Using LLVM build: " .. LLVMRootDir)
else
error("Error finding an LLVM build")
end
end
function get_llvm_build_dir()
return path.join(LLVMRootDir, get_llvm_package_name())
end
function SetupLLVMIncludes()
local c = filter()
if LLVMDirPerConfiguration then
filter { "configurations:Debug" }
includedirs
{
path.join(LLVMRootDirDebug, "include"),
path.join(LLVMRootDirDebug, "tools/clang/include"),
path.join(LLVMRootDirDebug, "tools/clang/lib"),
path.join(LLVMRootDirDebug, "build/include"),
path.join(LLVMRootDirDebug, "build/tools/clang/include"),
}
filter { "configurations:Release" }
includedirs
{
path.join(LLVMRootDirRelease, "include"),
path.join(LLVMRootDirRelease, "tools/clang/include"),
path.join(LLVMRootDirRelease, "tools/clang/lib"),
path.join(LLVMRootDirRelease, "build/include"),
path.join(LLVMRootDirRelease, "build/tools/clang/include"),
}
else
local LLVMBuildDir = get_llvm_build_dir()
includedirs
{
path.join(LLVMRootDir, "include"),
path.join(LLVMRootDir, "tools/clang/include"),
path.join(LLVMRootDir, "tools/clang/lib"),
path.join(LLVMBuildDir, "include"),
path.join(LLVMBuildDir, "tools/clang/include"),
}
end
filter(c)
end
function CopyClangIncludes()
local clangBuiltinIncludeDir = path.join(LLVMRootDir, "lib")
if LLVMDirPerConfiguration then
local clangBuiltinDebug = path.join(LLVMRootDirDebug, "lib")
local clangBuiltinRelease = path.join(LLVMRootDirRelease, "lib")
if os.isdir(path.join(clangBuiltinDebug, "clang")) then
clangBuiltinIncludeDir = clangBuiltinDebug
end
if os.isdir(path.join(clangBuiltinRelease, "clang")) then
clangBuiltinIncludeDir = clangBuiltinRelease
end
end
if os.isdir(clangBuiltinIncludeDir) then
postbuildcommands { string.format("{COPY} %s %%{cfg.buildtarget.directory}", clangBuiltinIncludeDir) }
end
end
function SetupLLVMLibs()
local c = filter()
filter { "action:not vs*" }
defines { "__STDC_CONSTANT_MACROS", "__STDC_LIMIT_MACROS" }
filter { "system:macosx" }
links { "c++", "curses", "pthread", "z" }
filter { "action:vs*" }
links { "version" }
filter {}
if LLVMDirPerConfiguration then
filter { "configurations:Debug" }
libdirs { path.join(LLVMRootDirDebug, "build/lib") }
filter { "configurations:Release" }
libdirs { path.join(LLVMRootDirRelease, "build/lib") }
else
local LLVMBuildDir = get_llvm_build_dir()
libdirs { path.join(LLVMBuildDir, "lib") }
filter { "configurations:Debug", "action:vs*" }
libdirs { path.join(LLVMBuildDir, "Debug/lib") }
filter { "configurations:Release", "action:vs*" }
libdirs { path.join(LLVMBuildDir, "RelWithDebInfo/lib") }
end
filter {}
links
{
"clangFrontend",
"clangDriver",
"clangSerialization",
"clangCodeGen",
"clangParse",
"clangSema",
"clangAnalysis",
"clangEdit",
"clangAST",
"clangLex",
"clangBasic",
"clangIndex",
"LLVMLinker",
"LLVMipo",
"LLVMVectorize",
"LLVMBitWriter",
"LLVMIRReader",
"LLVMAsmParser",
"LLVMOption",
"LLVMInstrumentation",
"LLVMProfileData",
"LLVMX86AsmParser",
"LLVMX86Desc",
"LLVMObject",
"LLVMMCParser",
"LLVMBitReader",
"LLVMX86Info",
"LLVMX86AsmPrinter",
"LLVMX86Utils",
"LLVMX86CodeGen",
"LLVMX86Disassembler",
"LLVMCodeGen",
"LLVMSelectionDAG",
"LLVMGlobalISel",
"LLVMDebugInfoCodeView",
"LLVMScalarOpts",
"LLVMInstCombine",
"LLVMTransformUtils",
"LLVMAnalysis",
"LLVMTarget",
"LLVMMCDisassembler",
"LLVMMC",
"LLVMCoverage",
"LLVMCore",
"LLVMSupport",
"LLVMBinaryFormat",
"LLVMDemangle"
}
filter(c)
end
|
-- Setup the LLVM dependency directories
LLVMRootDir = depsdir .. "/llvm/"
local LLVMDirPerConfiguration = false
local LLVMRootDirDebug = ""
local LLVMRootDirRelease = ""
require "scripts/LLVM"
function SearchLLVM()
LLVMRootDirDebug = basedir .. "/scripts/" .. get_llvm_package_name(nil, "Debug")
LLVMRootDirRelease = basedir .. "/scripts/" .. get_llvm_package_name()
if os.isdir(LLVMRootDirDebug) or os.isdir(LLVMRootDirRelease) then
LLVMDirPerConfiguration = true
print("Using debug LLVM build: " .. LLVMRootDirDebug)
print("Using release LLVM build: " .. LLVMRootDirRelease)
elseif os.isdir(LLVMRootDir) then
print("Using LLVM build: " .. LLVMRootDir)
else
error("Error finding an LLVM build")
end
end
function get_llvm_build_dir()
return path.join(LLVMRootDir, get_llvm_package_name())
end
function SetupLLVMIncludes()
local c = filter()
if LLVMDirPerConfiguration then
filter { "configurations:Debug" }
includedirs
{
path.join(LLVMRootDirDebug, "include"),
path.join(LLVMRootDirDebug, "tools/clang/include"),
path.join(LLVMRootDirDebug, "tools/clang/lib"),
path.join(LLVMRootDirDebug, "build/include"),
path.join(LLVMRootDirDebug, "build/tools/clang/include"),
}
filter { "configurations:Release" }
includedirs
{
path.join(LLVMRootDirRelease, "include"),
path.join(LLVMRootDirRelease, "tools/clang/include"),
path.join(LLVMRootDirRelease, "tools/clang/lib"),
path.join(LLVMRootDirRelease, "build/include"),
path.join(LLVMRootDirRelease, "build/tools/clang/include"),
}
else
local LLVMBuildDir = get_llvm_build_dir()
includedirs
{
path.join(LLVMRootDir, "include"),
path.join(LLVMRootDir, "tools/clang/include"),
path.join(LLVMRootDir, "tools/clang/lib"),
path.join(LLVMBuildDir, "include"),
path.join(LLVMBuildDir, "tools/clang/include"),
}
end
filter(c)
end
function CopyClangIncludes()
local clangBuiltinIncludeDir = path.join(LLVMRootDir, "lib")
if LLVMDirPerConfiguration then
local clangBuiltinDebug = path.join(LLVMRootDirDebug, "lib")
local clangBuiltinRelease = path.join(LLVMRootDirRelease, "lib")
if os.isdir(path.join(clangBuiltinDebug, "clang")) then
clangBuiltinIncludeDir = clangBuiltinDebug
end
if os.isdir(path.join(clangBuiltinRelease, "clang")) then
clangBuiltinIncludeDir = clangBuiltinRelease
end
end
if os.isdir(clangBuiltinIncludeDir) then
postbuildcommands { string.format("{COPY} %s %%{cfg.buildtarget.directory}", clangBuiltinIncludeDir) }
end
end
function SetupLLVMLibs()
local c = filter()
filter { "action:not vs*" }
defines { "__STDC_CONSTANT_MACROS", "__STDC_LIMIT_MACROS" }
filter { "system:macosx" }
links { "c++", "curses" }
filter { "system:macosx or system:linux" }
links { "pthread", "z" }
filter { "action:vs*" }
links { "version" }
filter {}
if os.ishost("linux") and os.isfile("/usr/lib/libtinfo.so") then
links { "tinfo" }
end
if LLVMDirPerConfiguration then
filter { "configurations:Debug" }
libdirs { path.join(LLVMRootDirDebug, "build/lib") }
filter { "configurations:Release" }
libdirs { path.join(LLVMRootDirRelease, "build/lib") }
else
local LLVMBuildDir = get_llvm_build_dir()
libdirs { path.join(LLVMBuildDir, "lib") }
filter { "configurations:Debug", "action:vs*" }
libdirs { path.join(LLVMBuildDir, "Debug/lib") }
filter { "configurations:Release", "action:vs*" }
libdirs { path.join(LLVMBuildDir, "RelWithDebInfo/lib") }
end
filter {}
links
{
"clangFrontend",
"clangDriver",
"clangSerialization",
"clangCodeGen",
"clangParse",
"clangSema",
"clangAnalysis",
"clangEdit",
"clangAST",
"clangLex",
"clangBasic",
"clangIndex",
"LLVMLinker",
"LLVMipo",
"LLVMVectorize",
"LLVMBitWriter",
"LLVMIRReader",
"LLVMAsmParser",
"LLVMOption",
"LLVMInstrumentation",
"LLVMProfileData",
"LLVMX86AsmParser",
"LLVMX86Desc",
"LLVMObject",
"LLVMMCParser",
"LLVMBitReader",
"LLVMX86Info",
"LLVMX86AsmPrinter",
"LLVMX86Utils",
"LLVMX86CodeGen",
"LLVMX86Disassembler",
"LLVMCodeGen",
"LLVMSelectionDAG",
"LLVMGlobalISel",
"LLVMDebugInfoCodeView",
"LLVMScalarOpts",
"LLVMInstCombine",
"LLVMTransformUtils",
"LLVMAnalysis",
"LLVMTarget",
"LLVMMCDisassembler",
"LLVMMC",
"LLVMCoverage",
"LLVMCore",
"LLVMSupport",
"LLVMBinaryFormat",
"LLVMDemangle"
}
filter(c)
end
|
Fix linked libs for linux
|
Fix linked libs for linux
Link `pthread` and `z` on linux as well. Link `tinfo` if `/usr/lib/libtinfo.so` file exists. This is required because despite explicitly disabling these libs in LLVM build config they still somehow get pulled in on some systems. `pthread` and `z` are standard components of every linux distribution therefore linking them unconditionally is OK. `tinfo` may not exist on some systems therefore it's existence is checked first. With this patch finally builds produced on Archlinux no longer result in `DllNotFoundException`.
|
Lua
|
mit
|
mono/CppSharp,mono/CppSharp,zillemarco/CppSharp,ddobrev/CppSharp,mono/CppSharp,ddobrev/CppSharp,mono/CppSharp,mohtamohit/CppSharp,zillemarco/CppSharp,mohtamohit/CppSharp,zillemarco/CppSharp,mono/CppSharp,mohtamohit/CppSharp,zillemarco/CppSharp,ddobrev/CppSharp,zillemarco/CppSharp,mohtamohit/CppSharp,ddobrev/CppSharp,mono/CppSharp,ddobrev/CppSharp,mohtamohit/CppSharp
|
849d2ccc07c4c2c3ee6ef5ed0cbc9e3936910526
|
BothForms-data.lua
|
BothForms-data.lua
|
--[[
This module holds datas for those Pokémon that has both Alt and Useless forms.
When possible, takes datas from the other alternative forms modules.
--]]
local t = {}
local txt = require('Wikilib-strings') -- luacheck: no unused
local tab = require('Wikilib-tables') -- luacheck: no unused
local alt = require("AltForms-data")
local useless = require("UselessForms-data")
--[[
Automatically merges alt and useless forms data of a certain Pokémon.
Merges names, links, blacklinks, ext, since and (if needed) until. Doesn't
merge gamesOrder because it can't know how to sort it.
--]]
local function mergeByName(poke)
local res = {}
-- Table.copy is needed because table.merge doesn't work on
-- mw.loadDataed tables.
res.names = table.merge(table.copy(alt[poke].names),
table.copy(useless[poke].names))
res.links = table.merge(table.copy(alt[poke].links),
table.copy(useless[poke].links))
res.blacklinks = table.merge(table.copy(alt[poke].blacklinks),
table.copy(useless[poke].blacklinks))
res.ext = table.merge(table.copy(alt[poke].ext),
table.copy(useless[poke].ext))
res.since = table.merge(table.copy(alt[poke].since),
table.copy(useless[poke].since))
-- Only merged when present
if alt[poke]['until'] or useless[poke]['until'] then
res['until'] = table.merge(table.copy(alt[poke]['until'] or {}),
table.copy(useless[poke]['until'] or {}))
end
return res
end
--[[
There's a table for each Pokémon. Some are missing because they would be equal
to others, thus there's aliasing at the end of the module.
--]]
t.pikachu = mergeByName("pikachu")
t.alcremie = mergeByName("alcremie")
t.alcremie.names.base = useless.alcremie.names.base
-- The copy is needed to remove metatable that mw.loadData doesn't like
t.minior = table.copy(useless.minior)
-- gamesOrder can't be merged automatically because there's no way to sort
-- abbrs
-- Minor isn't here because the AltForms is a subset of UselesForms
t.pikachu.gamesOrder = {'base', 'Cs', 'R', 'D', 'Cn', 'S', 'W',
'O', 'H', 'Si', 'U', 'K', 'A', 'Co', 'Cm', 'G', 'Gi'}
t.alcremie.gamesOrder = table.copy(useless.alcremie.gamesOrder)
table.insert(t.alcremie.gamesOrder, "Gi")
-- Aliasing, put here to avoid needless repetitions of previous cycles.
t[25] = t.pikachu
t[774] = t.minior
t[869] = t.alcremie
return t
|
--[[
This module holds datas for those Pokémon that has both Alt and Useless forms.
When possible, takes datas from the other alternative forms modules.
--]]
local t = {}
local txt = require('Wikilib-strings') -- luacheck: no unused
local tab = require('Wikilib-tables') -- luacheck: no unused
local alt = require("AltForms-data")
local useless = require("UselessForms-data")
--[[
Automatically merges alt and useless forms data of a certain Pokémon.
Merges names, links, blacklinks, ext, since and (if needed) until. Doesn't
merge gamesOrder because it can't know how to sort it.
--]]
local function mergeByName(poke)
local res = {}
-- Table.copy is needed because table.merge doesn't work on
-- mw.loadDataed tables.
res.names = table.merge(table.copy(alt[poke].names),
table.copy(useless[poke].names))
res.links = table.merge(table.copy(alt[poke].links),
table.copy(useless[poke].links))
res.blacklinks = table.merge(table.copy(alt[poke].blacklinks),
table.copy(useless[poke].blacklinks))
res.plainlinks = table.merge(table.copy(alt[poke].plainlinks),
table.copy(useless[poke].plainlinks))
res.ext = table.merge(table.copy(alt[poke].ext),
table.copy(useless[poke].ext))
res.since = table.merge(table.copy(alt[poke].since),
table.copy(useless[poke].since))
-- Only merged when present
if alt[poke]['until'] or useless[poke]['until'] then
res['until'] = table.merge(table.copy(alt[poke]['until'] or {}),
table.copy(useless[poke]['until'] or {}))
end
return res
end
--[[
There's a table for each Pokémon. Some are missing because they would be equal
to others, thus there's aliasing at the end of the module.
--]]
t.pikachu = mergeByName("pikachu")
t.alcremie = mergeByName("alcremie")
t.alcremie.names.base = useless.alcremie.names.base
-- The copy is needed to remove metatable that mw.loadData doesn't like
t.minior = table.copy(useless.minior)
-- gamesOrder can't be merged automatically because there's no way to sort
-- abbrs
-- Minor isn't here because the AltForms is a subset of UselesForms
t.pikachu.gamesOrder = {'base', 'Cs', 'R', 'D', 'Cn', 'S', 'W',
'O', 'H', 'Si', 'U', 'K', 'A', 'Co', 'Cm', 'G', 'Gi'}
t.alcremie.gamesOrder = table.copy(useless.alcremie.gamesOrder)
table.insert(t.alcremie.gamesOrder, "Gi")
-- Aliasing, put here to avoid needless repetitions of previous cycles.
t[25] = t.pikachu
t[774] = t.minior
t[869] = t.alcremie
return t
|
fixup! Adding plain links to AltForms-data and PokémonData
|
fixup! Adding plain links to AltForms-data and PokémonData
|
Lua
|
cc0-1.0
|
pokemoncentral/wiki-lua-modules
|
dd9b87e8a04434138c33dea0c8d3f600e347bf38
|
love2d/ambientsound.lua
|
love2d/ambientsound.lua
|
require "mapGenerator"
-- world map: lizGame.world.map.*
-- THIS IS ONLY THE SOUND PRODUCED BY THE AMBIENT (TODO the ambient consists of everything that is on the normal world map right now)
-- for sound produced by objects (e.g. the player or a door or an enemy) look at objectsound.lua (NYI)
--[[ possible sound sources:
1. player/selected character <- only this works for now
2. map center <- will be added later
--]]
--[[ possible values for the SoundMap:
0: no sound at all -- other tile or out of map
greater than 0: see MAP_OBJ_... constants in mapGenerator.lua
--]]
function getAmbientSoundGenerator() --not nice but this cannot be part of the namespace "love.sounds.*"
local o = {}
o.soundActive = false
o.listeningRadius = 3 -- this will be used for determining how far a tile may be for the player to hear a sound
o.origX = 0
o.origY = 0
o.soundMap = {}
-- call this method once at initialization and every time the listening radius is changed
o.resetSoundMap = function()
local tempSoundMap = {}
for i = 1,2*o.listeningRadius+1 do
tempSoundMap[i] = {}
for j = 1, 2*o.listeningRadius+1 do
tempSoundMap[i][j] = 0
end
end
o.soundMap = tempSoundMap
end
o.updateSoundMap = function()
o.resetSoundMap()
for i = 1,2*o.listeningRadius+1 do
if i+o.origX-o.listeningRadius < 1 or i+o.origX-o.listeningRadius>lizGame.world.mapWidth then
for j = 1, 2*o.listeningRadius+1 do
o.soundMap[i][j] = 0
end
else
for j = 1, o.listeningRadius+o.origY do
if j+o.origY-o.listeningRadius < 1 or j+o.origY-o.listeningRadius>lizGame.world.mapHeight then
o.soundMap[i][j] = 0
else
local t = MapGenerator.getObject(lizGame.world.mapG,i+o.origX-o.listeningRadius,j+o.origY-o.listeningRadius)
--print ("tile to add:"..t)
--TODO change this when 3D world is implemented
o.soundMap[i][j] = t
--print ("tile added? "..o.soundMap[i][j])
end
end
end
end
end
o.setOrigin = function()
--TODO, default for now: look at pawn #1
local tempx,tempy = lizGame.world.pawns[1].getPosition()
o.origX = math.floor(tempx+0.5)
o.origY = math.floor(tempy+0.5)
end
o.playAmbient = function()
print "."
if o.soundActive and lizGame.state == states.GAMEPLAY then
o.setOrigin()
o.updateSoundMap()
local tileAmount = {}
for i=0,9 do
tileAmount[i]=0
end
for i = 1,2*o.listeningRadius+1 do
for j = 1, 2*o.listeningRadius+1 do
--tileAmount[o.soundMap[i][j]] and
local soundMapValue = o.soundMap[i][j]
if i+j>=o.listeningRadius and soundMapValue>0 then
if soundMapValue == 4 then
--print("fire might be at "..i+o.origX-o.listeningRadius..", "..j+o.origY-o.listeningRadius)
for k=1,#lizGame.world.fires do
if lizGame.world.fires[k].y == j+o.origY-o.listeningRadius and lizGame.world.fires[k].x == i+o.origX-o.listeningRadius then
--print ("found fire")
if lizGame.world.fires[k].state ~= 0 then
tileAmount[soundMapValue] = tileAmount[soundMapValue] + 1
--print("burning fire added")
end
break
end
end
else
tileAmount[soundMapValue] = tileAmount[soundMapValue] + 1
end
end
end
end
-- quick algorithm to find the most used tile within listener range
local mostUsed = 0
local mostUsedAmount = 0
local secondMostUsed = 0
for i=1,#tileAmount do
if tileAmount[i]>mostUsedAmount then
secondMostUsed = mostUsed
mostUsedAmount = tileAmount[i]
mostUsed = i
end
--print("Amount of "..i..":"..tileAmount[i])
end
--print("Most used: "..mostUsed..", "..secondMostUsed)
-- play the right music file
if mostUsed == 1 or secondMostUsed == 1 then
love.sounds.playSound("riverLoop1")
else
love.sounds.stopSound("riverLoop1")
end
if mostUsed == 2 or secondMostUsed == 2 then
if love.sounds.soundRandomizer:random(1,100) > 85 then
love.sounds.playSound("birds",nil,love.sounds.soundRandomizer:random(1,3)*0.5)
end
else
love.sounds.stopSound("birds")
end
if mostUsed == 4 or secondMostUsed == 4 then
love.sounds.playSound("fireplace")
-- elseif mostUsed == 5 then
else
love.sounds.stopSound("fireplace")
end
if mostUsed >= 5 or secondMostUsed >=5 then
if love.sounds.soundRandomizer:random(1,100) > 80 then
love.sounds.playSound("bird",nil,love.sounds.soundRandomizer:random(1,3)*0.5)
end
else
love.sounds.stopSound("bird")
end
end
end
return o
end
|
require "mapGenerator"
-- world map: lizGame.world.map.*
-- THIS IS ONLY THE SOUND PRODUCED BY THE AMBIENT (TODO the ambient consists of everything that is on the normal world map right now)
-- for sound produced by objects (e.g. the player or a door or an enemy) look at objectsound.lua (NYI)
--[[ possible sound sources:
1. player/selected character <- only this works for now
2. map center <- will be added later
--]]
--[[ possible values for the SoundMap:
0: no sound at all -- other tile or out of map
greater than 0: see MAP_OBJ_... constants in mapGenerator.lua
--]]
function getAmbientSoundGenerator() --not nice but this cannot be part of the namespace "love.sounds.*"
local o = {}
o.soundActive = false
o.listeningRadius = 3 -- this will be used for determining how far a tile may be for the player to hear a sound
o.origX = 0
o.origY = 0
o.soundMap = {}
-- call this method once at initialization and every time the listening radius is changed
o.resetSoundMap = function()
local tempSoundMap = {}
for i = 1,2*o.listeningRadius+1 do
tempSoundMap[i] = {}
for j = 1, 2*o.listeningRadius+1 do
tempSoundMap[i][j] = 0
end
end
o.soundMap = tempSoundMap
end
o.updateSoundMap = function()
o.resetSoundMap()
for i = 1,2*o.listeningRadius+1 do
if i+o.origX-o.listeningRadius < 1 or i+o.origX-o.listeningRadius>lizGame.world.mapWidth then
for j = 1, 2*o.listeningRadius+1 do
o.soundMap[i][j] = 0
end
else
for j = 1, o.listeningRadius+o.origY do
if j+o.origY-o.listeningRadius < 1 or j+o.origY-o.listeningRadius>lizGame.world.mapHeight then
o.soundMap[i][j] = 0
else
local t = MapGenerator.getObject(lizGame.world.mapG,i+o.origX-o.listeningRadius,j+o.origY-o.listeningRadius)
--print ("tile to add:"..t)
--TODO change this when 3D world is implemented
o.soundMap[i][j] = t
--print ("tile added? "..o.soundMap[i][j])
end
end
end
end
end
o.setOrigin = function()
--TODO, default for now: look at pawn #1
local tempx,tempy = lizGame.world.pawns[1].getPosition()
o.origX = math.floor(tempx+0.5)
o.origY = math.floor(tempy+0.5)
end
o.playAmbient = function()
--print "."
if o.soundActive and lizGame.state == states.GAMEPLAY then
o.setOrigin()
o.updateSoundMap()
local tileAmount = {}
for i=0,9 do
tileAmount[i]=0
end
for i = 1,2*o.listeningRadius+1 do
for j = 1, 2*o.listeningRadius+1 do
--tileAmount[o.soundMap[i][j]] and
local soundMapValue = o.soundMap[i][j]
if i+j>=o.listeningRadius and soundMapValue>0 then
if soundMapValue == 4 then
for k=1,#lizGame.world.fires do
if lizGame.world.fires[k].y == j+o.origY-o.listeningRadius-1 and lizGame.world.fires[k].x == i+o.origX-o.listeningRadius-1 then
if lizGame.world.fires[k].state ~= 0 then
tileAmount[soundMapValue] = tileAmount[soundMapValue] + 1
end
break
end
end
else
tileAmount[soundMapValue] = tileAmount[soundMapValue] + 1
end
end
end
end
-- quick algorithm to find the most used tile within listener range
local mostUsed = 0
local mostUsedAmount = 0
local secondMostUsed = 0
for i=1,#tileAmount do
if tileAmount[i]>mostUsedAmount then
secondMostUsed = mostUsed
mostUsedAmount = tileAmount[i]
mostUsed = i
end
--print("Amount of "..i..":"..tileAmount[i])
end
--print("Most used: "..mostUsed..", "..secondMostUsed)
-- play the right music file
if mostUsed == 1 or secondMostUsed == 1 then
love.sounds.playSound("riverLoop1")
else
love.sounds.stopSound("riverLoop1")
end
if mostUsed == 2 or secondMostUsed == 2 then
if love.sounds.soundRandomizer:random(1,100) > 85 then
love.sounds.playSound("birds",nil,love.sounds.soundRandomizer:random(1,3)*0.5)
end
else
love.sounds.stopSound("birds")
end
if mostUsed == 4 or secondMostUsed == 4 then
love.sounds.playSound("fireplace")
-- elseif mostUsed == 5 then
else
love.sounds.stopSound("fireplace")
end
if mostUsed >= 5 or secondMostUsed >=5 then
if love.sounds.soundRandomizer:random(1,100) > 80 then
love.sounds.playSound("bird",nil,love.sounds.soundRandomizer:random(1,3)*0.5)
end
else
love.sounds.stopSound("bird")
end
end
end
return o
end
|
fix for issue #8 is fixed now and all the comments in the sound file are disabled
|
fix for issue #8 is fixed now and all the comments in the sound file are disabled
|
Lua
|
mit
|
nczempin/lizard-journey
|
0120745cd6257b3c7b6b30075223b3a7956ad317
|
tests/lua/tests/gl.lua
|
tests/lua/tests/gl.lua
|
local gl = require 'engine.gl'
local ffi = require 'ffi'
local fileutil = require 'engine.fileutil'
local render_test = nil
local program, posAttrib = nil, nil
function _render()
gl.glUseProgram(program)
gl.glVertexAttribPointer(posAttrib, 2, gl.GL_FLOAT, gl.GL_FALSE, 0, nil)
gl.glEnableVertexAttribArray(posAttrib)
gl.glDrawArrays(gl.GL_TRIANGLES, 0, 3)
end
function _init()
local vertexSource = [[
#version 330
in vec2 position;
void main()
{
gl_Position = vec4(position, 0.0, 1.0);
}
]]
local fragmentSource = [[
#version 330
out vec4 outColor;
void main()
{
outColor = vec4(1.0, 1.0, 1.0, 1.0);
}
]]
local vertices = ffi.new('float[6]', { 0.0, 0.5, 0.5, -0.5, -0.5, -0.5} )
local vbo = ffi.new 'GLuint[1]'
gl.glGenBuffers(1, vbo)
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, vbo[1])
gl.glBufferData(gl.GL_ARRAY_BUFFER, ffi.sizeof(vertices), vertices, gl.GL_STATIC_DRAW);
program = gl.createProgram(vertexSource, fragmentSource)
posAttrib = gl.glGetAttribLocation(program, 'position')
local vao = ffi.new 'GLuint[1]'
gl.glGenVertexArrays(1, vao);
gl.glBindVertexArray(vao[1]);
render_test = _render
end
render_test = _init
return {
process = function(dt)
end,
render = function()
render_test()
end
}
|
local gl = require 'engine.gl'
local ffi = require 'ffi'
local fileutil = require 'engine.fileutil'
local render_test = nil
local program, posAttrib = nil, nil
function _render()
gl.glUseProgram(program)
gl.glDrawArrays(gl.GL_TRIANGLES, 0, 3)
end
function _init()
local vertexSource = [[
#version 330
in vec2 position;
void main()
{
gl_Position = vec4(position, 0.0, 1.0);
}
]]
local fragmentSource = [[
#version 330
out vec4 outColor;
void main()
{
outColor = vec4(1.0, 1.0, 1.0, 1.0);
}
]]
local vao = ffi.new 'GLuint[1]'
local vbo = ffi.new 'GLuint[1]'
local vertices = ffi.new('float[6]', { 0.0, 0.5, 0.5, -0.5, -0.5, -0.5} )
gl.glGenBuffers(1, vbo)
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, vbo[0])
gl.glBufferData(gl.GL_ARRAY_BUFFER, ffi.sizeof(vertices), vertices, gl.GL_STATIC_DRAW);
program = gl.createProgram(vertexSource, fragmentSource)
gl.glGenVertexArrays(1, vao);
gl.glBindVertexArray(vao[0]);
posAttrib = gl.glGetAttribLocation(program, 'position')
gl.glVertexAttribPointer(posAttrib, 2, gl.GL_FLOAT, gl.GL_FALSE, 0, nil)
gl.glEnableVertexAttribArray(posAttrib)
render_test = _render
end
render_test = _init
return {
process = function(dt)
end,
render = function()
render_test()
end
}
|
Fix wrong vao and vbo number
|
Fix wrong vao and vbo number
|
Lua
|
mit
|
lzubiaur/woot,lzubiaur/woot,lzubiaur/woot,lzubiaur/woot,lzubiaur/woot,lzubiaur/woot,lzubiaur/woot
|
ee7837873f27e30d65de8cae113e302eb454b106
|
premake4.lua
|
premake4.lua
|
#!lua
-- clang || gcc
-- compiler = "clang"
if not _OPTIONS["compiler"] then
_OPTIONS["compiler"] = "gcc"
end
if _OPTIONS["compiler"] == "clang" then
print("clang")
toolset = "clang"
else
if os.execute("gcc-6 -v") == 0 then
print("gcc")
premake.gcc.cc = 'gcc-6'
premake.gcc.cxx = 'g++-6'
else
error("gcc version 6 required. Aborting.")
end
end
solution "Opossum"
configurations { "Debug", "Release" }
platforms "x64"
flags { "FatalWarnings", "ExtraWarnings" }
project "Opossum"
kind "ConsoleApp"
language "C++"
targetdir "build/"
buildoptions { "-std=c++1z" }
files { "**.hpp", "**.cpp" }
includedirs { "src/lib/", "/usr/local/include" }
configuration "Debug"
defines { "DEBUG" }
flags { "Symbols" }
configuration "Release"
defines { "NDEBUG" }
flags { "OptimizeSpeed" }
newoption {
trigger = "compiler",
value = "clang||gcc",
description = "Choose a compiler",
allowed = {
{ "gcc", "gcc of version 6 or higher" },
{ "clang", "clang llvm frontend" }
}
}
|
#!lua
-- clang || gcc
-- compiler = "clang"
if not _OPTIONS["compiler"] then
_OPTIONS["compiler"] = "gcc"
end
if _OPTIONS["compiler"] == "clang" then
toolset = "clang"
else
if os.execute("gcc-6 -v") == 0 then
premake.gcc.cc = 'gcc-6'
premake.gcc.cxx = 'g++-6'
else
error("gcc version 6 required. Aborting.")
end
end
solution "Opossum"
configurations { "Debug", "Release" }
platforms "x64"
flags { "FatalWarnings", "ExtraWarnings" }
project "Opossum"
kind "ConsoleApp"
language "C++"
targetdir "build/"
buildoptions { "-std=c++1z" }
files { "**.hpp", "**.cpp" }
includedirs { "src/lib/", "/usr/local/include" }
configuration "Debug"
defines { "DEBUG" }
flags { "Symbols" }
configuration "Release"
defines { "NDEBUG" }
flags { "OptimizeSpeed" }
newoption {
trigger = "compiler",
value = "clang||gcc",
description = "Choose a compiler",
allowed = {
{ "gcc", "gcc of version 6 or higher" },
{ "clang", "clang llvm frontend" }
}
}
|
Minor premake fix
|
Minor premake fix
|
Lua
|
mit
|
hyrise/hyrise,hyrise/hyrise,hyrise/hyrise
|
6c1d04b7cab2cbbcddeb3f5da4bfd78e97cb0445
|
cache.lua
|
cache.lua
|
local cache = {}
local _cache = {}
local CACHE_PATH = love.filesystem.getSaveDirectory().."/cache"
-- cache format
-- TS\tFLAGS\tPATH\n
function cache.load()
LOG.INFO("Loading cache...")
for line in io.lines(CACHE_PATH) do
local ts,flags,path = line:match("(%d+)\t(%w*)\t(.*)")
_cache[path] = { ts = tonumber(ts), flags = {} }
for flag in flags:gmatch("[^:]+") do
_cache[path].flags[flag] = true
end
end
end
function cache.save()
LOG.INFO("Saving cache...")
local fd = io.open(CACHE_PATH..".tmp", "wb")
for path,data in pairs(_cache) do
local flags = {}
for flag in pairs(data.flags) do
table.insert(flags, flag)
end
fd:write("%d\t%s\t%s\n" % { data.ts, table.concat(flags, ":"), path })
end
fd:close()
local res,err = os.rename(CACHE_PATH..".tmp", CACHE_PATH)
if not res then
LOG.ERROR("Cache save failed: %s", tostring(err))
end
end
function cache.get(path)
if not _cache[path] then
_cache[path] = { ts = 0, flags = {} }
end
return _cache[path]
end
function cache.set(path, data)
_cache[path] = data
end
io.open(CACHE_PATH, "a"):close() -- create cache file if it doesn't already exist
cache.load()
return cache
|
local cache = {}
local _cache = {}
local CACHE_PATH = love.filesystem.getSaveDirectory().."/cache"
-- cache format
-- TS\tFLAGS\tPATH\n
function cache.load()
LOG.INFO("Loading cache...")
for line in io.lines(CACHE_PATH) do
local ts,flags,path = line:match("(%d+)\t(%w*)\t(.*)")
_cache[path] = { ts = tonumber(ts), flags = {} }
for flag in flags:gmatch("[^:]+") do
_cache[path].flags[flag] = true
end
end
end
function cache.save()
LOG.INFO("Saving cache...")
local fd = io.open(CACHE_PATH..".tmp", "wb")
for path,data in pairs(_cache) do
local flags = {}
for flag in pairs(data.flags) do
table.insert(flags, flag)
end
fd:write("%d\t%s\t%s\n" % { data.ts, table.concat(flags, ":"), path })
end
fd:close()
local res,err = os.remove(CACHE_PATH)
if res then
res,err = os.rename(CACHE_PATH..".tmp", CACHE_PATH)
end
if not res then
LOG.ERROR("Cache save failed: %s", tostring(err))
end
end
function cache.get(path)
if not _cache[path] then
_cache[path] = { ts = 0, flags = {} }
end
return _cache[path]
end
function cache.set(path, data)
_cache[path] = data
end
io.open(CACHE_PATH, "a"):close() -- create cache file if it doesn't already exist
cache.load()
return cache
|
Remove cache before renaming new one into place to work around weird bug on windows. NOT SAFE. DO NOT KEEP.
|
Remove cache before renaming new one into place to work around weird bug on windows. NOT SAFE. DO NOT KEEP.
|
Lua
|
mit
|
ToxicFrog/EmuFun
|
292be5786a83f8f975d55ad7320c8b955e678430
|
src/plugins/lua/mid.lua
|
src/plugins/lua/mid.lua
|
--[[
Copyright (c) 2016, Alexander Moisseev <[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.
]]--
--[[
MID plugin - suppress INVALID_MSGID and MISSING_MID for messages originating
from listed valid DKIM domains with missed or known proprietary Message-IDs
]]--
local rspamd_logger = require "rspamd_logger"
local rspamd_regexp = require "rspamd_regexp"
local settings = {
url = '',
symbol_known_mid = 'KNOWN_MID',
symbol_known_no_mid = 'KNOWN_NO_MID',
symbol_invalid_msgid = 'INVALID_MSGID',
symbol_missing_mid = 'MISSING_MID',
symbol_dkim_allow = 'R_DKIM_ALLOW',
csymbol_invalid_msgid_allowed = 'INVALID_MSGID_ALLOWED',
csymbol_missing_mid_allowed = 'MISSING_MID_ALLOWED',
}
local map = {}
local function known_mid_cb(task)
local re = {}
local header = task:get_header('Message-Id')
local das = task:get_symbol(settings['symbol_dkim_allow'])
if das and das[1] and das[1]['options'] then
for _,dkim_domain in ipairs(das[1]['options']) do
local v = map:get_key(dkim_domain)
if v then
if v == '' then
if not header then
task:insert_result(settings['symbol_known_no_mid'], 1, dkim_domain)
return
end
else
re[dkim_domain] = rspamd_regexp.create_cached(v)
if header then
if re[dkim_domain]:match(header) then
task:insert_result(settings['symbol_known_mid'], 1, dkim_domain)
return
end
end
end
end
end
end
end
local opts = rspamd_config:get_all_opt('mid')
if opts then
for k,v in pairs(opts) do
settings[k] = v
end
if settings['url'] and #settings['url'] > 0 then
map = rspamd_config:add_map ({
url = settings['url'],
type = 'map',
description = 'Message-IDs map'
})
local id = rspamd_config:register_symbol({
name = 'KNOWN_MID_CALLBACK',
type = 'callback',
callback = known_mid_cb
})
rspamd_config:register_symbol({
name = settings['symbol_known_mid'],
parent = id,
type = 'virtual'
})
rspamd_config:register_symbol({
name = settings['symbol_known_no_mid'],
parent = id,
type = 'virtual'
})
rspamd_config:add_composite(settings['csymbol_invalid_msgid_allowed'],
settings['symbol_known_mid'] .. ' & ' .. settings['symbol_invalid_msgid'])
rspamd_config:add_composite(settings['csymbol_missing_mid_allowed'],
settings['symbol_known_no_mid'] .. ' & ' .. settings['symbol_missing_mid'])
rspamd_config:register_dependency(id, settings['symbol_dkim_allow'])
else
rspamd_logger.infox(rspamd_config, 'url is not specified, disabling module')
end
end
|
--[[
Copyright (c) 2016, Alexander Moisseev <[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.
]]--
--[[
MID plugin - suppress INVALID_MSGID and MISSING_MID for messages originating
from listed valid DKIM domains with missed or known proprietary Message-IDs
]]--
local rspamd_logger = require "rspamd_logger"
local rspamd_regexp = require "rspamd_regexp"
local settings = {
url = '',
symbol_known_mid = 'KNOWN_MID',
symbol_known_no_mid = 'KNOWN_NO_MID',
symbol_invalid_msgid = 'INVALID_MSGID',
symbol_missing_mid = 'MISSING_MID',
symbol_dkim_allow = 'R_DKIM_ALLOW',
csymbol_invalid_msgid_allowed = 'INVALID_MSGID_ALLOWED',
csymbol_missing_mid_allowed = 'MISSING_MID_ALLOWED',
}
local map = {}
local function known_mid_cb(task)
local re = {}
local header = task:get_header('Message-Id')
local das = task:get_symbol(settings['symbol_dkim_allow'])
if das and das[1] and das[1]['options'] then
for _,dkim_domain in ipairs(das[1]['options']) do
local v = map:get_key(dkim_domain)
if v then
if v == '' then
if not header then
task:insert_result(settings['symbol_known_no_mid'], 1, dkim_domain)
return
end
else
re[dkim_domain] = rspamd_regexp.create_cached(v)
if header and re[dkim_domain] and re[dkim_domain]:match(header) then
task:insert_result(settings['symbol_known_mid'], 1, dkim_domain)
return
end
end
end
end
end
end
local opts = rspamd_config:get_all_opt('mid')
if opts then
for k,v in pairs(opts) do
settings[k] = v
end
if settings['url'] and #settings['url'] > 0 then
map = rspamd_config:add_map ({
url = settings['url'],
type = 'map',
description = 'Message-IDs map'
})
local id = rspamd_config:register_symbol({
name = 'KNOWN_MID_CALLBACK',
type = 'callback',
callback = known_mid_cb
})
rspamd_config:register_symbol({
name = settings['symbol_known_mid'],
parent = id,
type = 'virtual'
})
rspamd_config:register_symbol({
name = settings['symbol_known_no_mid'],
parent = id,
type = 'virtual'
})
rspamd_config:add_composite(settings['csymbol_invalid_msgid_allowed'],
settings['symbol_known_mid'] .. ' & ' .. settings['symbol_invalid_msgid'])
rspamd_config:add_composite(settings['csymbol_missing_mid_allowed'],
settings['symbol_known_no_mid'] .. ' & ' .. settings['symbol_missing_mid'])
rspamd_config:register_dependency(id, settings['symbol_dkim_allow'])
else
rspamd_logger.infox(rspamd_config, 'url is not specified, disabling module')
end
end
|
[Fix] mid: handle incorrect rgexps in the map
|
[Fix] mid: handle incorrect rgexps in the map
|
Lua
|
bsd-2-clause
|
AlexeySa/rspamd,AlexeySa/rspamd,minaevmike/rspamd,minaevmike/rspamd,AlexeySa/rspamd,minaevmike/rspamd,minaevmike/rspamd,minaevmike/rspamd,AlexeySa/rspamd,minaevmike/rspamd,minaevmike/rspamd,AlexeySa/rspamd,AlexeySa/rspamd,minaevmike/rspamd,minaevmike/rspamd,AlexeySa/rspamd,AlexeySa/rspamd,AlexeySa/rspamd
|
888a2ee3262a838967970f47c5901e5c1460eb04
|
src/commands/exec.lua
|
src/commands/exec.lua
|
local utils = require("utils")
local exec = {
func = function(msg)
if msg.from.username == config.master then
local t = {pcall(load(string.match(msg.text, "/exec(.*)")))}
local ts = string.format("[status] %s\n", tostring(t[1]))
for i = 2, #t do
ts = ts .. string.format("[return %d] %s\n", i-1, tostring(t[i]))
end
bot.sendMessage(msg.chat.id, ts .. "[END]")
elseif config.dolua then
if msg.text:find("for") or msg.text:find("while") or msg.text:find("until") or msg.text:find("goto") or msg.text:find("function") then
bot.sendMessage(msg.chat.id, "Sorry, but no looping.")
else
local t = {pcall(load("_ENV = utils.sandbox{'math', 'string', 'pairs', 'cjson', 'table', 'message', 'base64', 'md5'}; string.dump = nil; " .. string.match(msg.text, "/exec(.*)")))}
local ts = string.format("[status] %s\n", tostring(t[1]))
for i = 2, #t do
ts = ts .. string.format("[return %d] %s\n", i-1, tostring(t[i]))
end
if #ts > 4096 then
ts = "[status] false\n"
end
bot.sendMessage(msg.chat.id, ts .. "[END]")
end
end
end,
form = "/exec <code>",
desc = "Execute code in lua.",
help = "`string`, `math`, `table`, `base64` and `md5` are available.\ne.g.\n `/exec return 1+1`\n `/exec return string.rep(\"233\\n\", 5)`\n `/exec return table.encode(base64)`",
limit = {
match = "/exec%s*(%S.+)"
}
}
return exec
|
local utils = require("utils")
local exec = {
func = function(msg)
if msg.from.username == config.master then
local t = {pcall(load(string.match(msg.text, "/exec(.*)")))}
local ts = string.format("[status] %s\n", tostring(t[1]))
for i = 2, #t do
ts = ts .. string.format("[return %d] %s\n", i-1, tostring(t[i]))
end
bot.sendMessage(msg.chat.id, ts .. "[END]")
elseif config.dolua then
if msg.text:find("for") or msg.text:find("while") or msg.text:find("until") or msg.text:find("goto") or msg.text:find("function") then
bot.sendMessage(msg.chat.id, "Sorry, but no looping.")
else
local t = {pcall(load("local utils = require('utils'); _ENV = utils.sandbox{'math', 'string', 'pairs', 'cjson', 'table', 'message', 'base64', 'md5'}; string.dump = nil; " .. string.match(msg.text, "/exec(.*)")))}
local ts = string.format("[status] %s\n", tostring(t[1]))
for i = 2, #t do
ts = ts .. string.format("[return %d] %s\n", i-1, tostring(t[i]))
end
if #ts > 4096 then
ts = "[status] false\n"
end
bot.sendMessage(msg.chat.id, ts .. "[END]")
end
end
end,
form = "/exec <code>",
desc = "Execute code in lua.",
help = "`string`, `math`, `table`, `base64` and `md5` are available.\ne.g.\n `/exec return 1+1`\n `/exec return string.rep(\"233\\n\", 5)`\n `/exec return table.encode(base64)`",
limit = {
match = "/exec%s*(%S.+)"
}
}
return exec
|
fix: no utils in sandbox
|
fix: no utils in sandbox
|
Lua
|
apache-2.0
|
SJoshua/Project-Small-R
|
9f7187804f03d027a75b1052a264135772bfb64b
|
lor/lib/request.lua
|
lor/lib/request.lua
|
local error = error
local pairs = pairs
local setmetatable = setmetatable
local Request = {}
-- new request: init args/params/body etc from http request
function Request:new()
ngx.req.read_body()
local body = {} -- body params
for k,v in pairs(ngx.req.get_post_args()) do
body[k] = v
end
local instance = {
path = ngx.var.uri, -- uri
method = ngx.req.get_method(),
query = ngx.req.get_uri_args(),
params = {},
body = body,
body_raw = ngx.req.get_body_data(),
url = ngx.var.request_uri,
uri = ngx.var.request_uri,
headers = ngx.req.get_headers(), -- request headers
req_args = ngx.var.args,
found = false --标识404错误
}
setmetatable(instance, { __index = self })
return instance
end
function Request:mock()
local query = {} -- uri params
local body = {} -- body params
local params = {}
local instance = {
method = "get",
query = {},
params = {},
body = {},
path = "",
uri = "",
baseUrl = "",
}
setmetatable(instance, { __index = self })
return instance
end
function Request:isFound()
return self.found
end
function Request:setFound(isFound)
self.found = isFound
end
return Request
|
local error = error
local pairs = pairs
local setmetatable = setmetatable
local Request = {}
-- new request: init args/params/body etc from http request
function Request:new()
ngx.req.read_body()
local body = {} -- body params
local post_args = ngx.req.get_post_args()
if post_args and type(post_args) == "table" then
for k,v in pairs(post_args) do
body[k] = v
end
end
local instance = {
path = ngx.var.uri, -- uri
method = ngx.req.get_method(),
query = ngx.req.get_uri_args(),
params = {},
body = body,
body_raw = ngx.req.get_body_data(),
url = ngx.var.request_uri,
uri = ngx.var.request_uri,
headers = ngx.req.get_headers(), -- request headers
req_args = ngx.var.args,
found = false --标识404错误
}
setmetatable(instance, { __index = self })
return instance
end
function Request:mock()
local query = {} -- uri params
local body = {} -- body params
local params = {}
local instance = {
method = "get",
query = {},
params = {},
body = {},
path = "",
uri = "",
baseUrl = "",
}
setmetatable(instance, { __index = self })
return instance
end
function Request:isFound()
return self.found
end
function Request:setFound(isFound)
self.found = isFound
end
return Request
|
fixbug: request body init
|
fixbug: request body init
|
Lua
|
mit
|
269724033/lor,ms2008/lor,sumory/lor
|
1bc5615d55ae05df270fae3793053805a3efc16c
|
levent/socket.lua
|
levent/socket.lua
|
--[[
-- author: xjdrew
-- date: 2014-07-17
--]]
local c = require "levent.socket.c"
local errno = require "levent.errno.c"
local class = require "levent.class"
local hub = require "levent.hub"
local timeout = require "levent.timeout"
local closed_socket = setmetatable({}, {__index = function(t, key)
if key == "send" or key == "recv" or key=="sendto" or key == "recvfrom" or key == "accept" then
return function(...)
return nil, errno.EBADF
end
end
end})
local function _wait(watcher, sec)
local t
if sec and sec > 0 then
t = timeout.start_new(sec)
end
local ok, excepiton = xpcall(hub.wait, debug.traceback, hub, watcher)
if not ok then
print(ok, excepiton)
end
if t then
t:cancel()
end
return ok, excepiton
end
local Socket = class("Socket")
function Socket:_init(cobj)
assert(type(cobj.fileno) == "function", cobj)
self.cobj = cobj
self.cobj:setblocking(false)
local loop = hub.loop
self._read_event = loop:io(self.cobj:fileno(), loop.EV_READ)
self._write_event = loop:io(self.cobj:fileno(), loop.EV_WRITE)
-- timeout
self.timeout = nil
end
function Socket:setblocking(flag)
if flag then
self.timeout = nil
else
self.timeout = 0.0
end
end
function Socket:set_timeout(sec)
self.timeout = sec
end
function Socket:get_timeout()
return self.timeout
end
function Socket:bind(ip, port)
self.cobj:setsockopt(c.SOL_SOCKET, c.SO_REUSEADDR, 1)
local ok, code = self.cobj:bind(ip, port)
if not ok then
return false, errno.strerror(code)
end
return true
end
function Socket:listen(backlog)
local ok, code = self.cobj:listen(backlog)
if not ok then
return false, errno.strerror(code)
end
return true
end
function Socket:_need_block(err)
if self.timeout == 0 then
return false
end
if err ~= errno.EWOULDBLOCK and err ~= errno.EAGAIN then
return false
end
return true
end
function Socket:accept()
local csock, err
while true do
csock, err = self.cobj:accept()
if csock then
break
end
if not self:_need_block(err) then
return nil, errno.strerror(err)
end
local ok, exception = _wait(self._read_event, self.timeout)
if not ok then
return nil, exception
end
end
return Socket.new(csock)
end
function Socket:_recv(func, ...)
while true do
local data, err = func(self.cobj, ...)
if data then
return data
end
if not self:_need_block(err) then
return nil, err
end
local ok, exception = _wait(self._read_event, self.timeout)
if not ok then
return nil, exception
end
end
end
-- args:len
function Socket:recvfrom(len)
return self:_recv(self.cobj.recvfrom, len)
end
-- args: len
function Socket:recv(len)
return self:_recv(self.cobj.recv, len)
end
function Socket:_send(func, ...)
while true do
local nwrite, err = func(self.cobj, ...)
if nwrite then
return nwrite
end
if not self:_need_block(err) then
return nil, err
end
local ok, exception = _wait(self._write_event, self.timeout)
if not ok then
return nil, exception
end
end
end
-- args: data, from
-- from: count from 0
function Socket:send(data, from)
return self:_send(self.cobj.send, data, from)
end
-- args:
function Socket:sendto(ip, port, data, from)
return self:_send(self.cobj.sendto, ip, port, data, from)
end
-- from: count from 0
function Socket:sendall(data, from)
local from = from or 0
local total = #data - from
local sent = 0
while sent < total do
local nwrite, err = self:send(data, from + sent)
if not nwrite then
return sent, err
end
sent = sent + nwrite
end
return sent
end
function Socket:connect(ip, port)
while true do
local ok, err = self.cobj:connect(ip, port)
if ok then
return ok
end
if self.timeout == 0.0 or (err ~= errno.EINPROGRESS and err ~= errno.EWOULDBLOCK) then
return ok, err
end
local ok, exception = _wait(self._write_event, self.timeout)
if not ok then
return nil, exception
end
end
end
function Socket:fileno()
return self.cobj:fileno()
end
function Socket:getpeername()
return self.cobj:getpeername()
end
function Socket:getsockname()
return self.cobj:getsockname()
end
function Socket:getsockopt(level, optname, buflen)
return self.cobj:getsockopt(level, optname, buflen)
end
function Socket:setsockopt(level, optname, value)
return self.cobj:setsockopt(level, optname, value)
end
function Socket:close()
if self.cobj ~= closed_socket then
hub:cancel_wait(self._read_event)
hub:cancel_wait(self._write_event)
self.cobj:close()
self.cobj = closed_socket
end
end
local socket = {}
function socket.socket(family, _type, protocol)
local cobj, err = c.socket(family, _type, protocol)
if not cobj then
return nil, errno.strerror(err)
end
return Socket.new(cobj)
end
return setmetatable(socket, {__index = c} )
|
--[[
-- author: xjdrew
-- date: 2014-07-17
--]]
local c = require "levent.socket.c"
local errno = require "levent.errno.c"
local class = require "levent.class"
local hub = require "levent.hub"
local timeout = require "levent.timeout"
local closed_socket = setmetatable({}, {__index = function(t, key)
if key == "send" or key == "recv" or key=="sendto" or key == "recvfrom" or key == "accept" then
return function(...)
return nil, errno.EBADF
end
end
end})
local function _wait(watcher, sec)
local t
if sec and sec > 0 then
t = timeout.start_new(sec)
end
local ok, excepiton = xpcall(hub.wait, debug.traceback, hub, watcher)
if not ok then
print(ok, excepiton)
end
if t then
t:cancel()
end
return ok, excepiton
end
local Socket = class("Socket")
function Socket:_init(cobj)
assert(type(cobj.fileno) == "function", cobj)
self.cobj = cobj
self.cobj:setblocking(false)
local loop = hub.loop
self._read_event = loop:io(self.cobj:fileno(), loop.EV_READ)
self._write_event = loop:io(self.cobj:fileno(), loop.EV_WRITE)
-- timeout
self.timeout = nil
end
function Socket:setblocking(flag)
if flag then
self.timeout = nil
else
self.timeout = 0.0
end
end
function Socket:set_timeout(sec)
self.timeout = sec
end
function Socket:get_timeout()
return self.timeout
end
function Socket:bind(ip, port)
self.cobj:setsockopt(c.SOL_SOCKET, c.SO_REUSEADDR, 1)
local ok, code = self.cobj:bind(ip, port)
if not ok then
return false, errno.strerror(code)
end
return true
end
function Socket:listen(backlog)
local ok, code = self.cobj:listen(backlog)
if not ok then
return false, errno.strerror(code)
end
return true
end
function Socket:_need_block(err)
if self.timeout == 0 then
return false
end
if err ~= errno.EWOULDBLOCK and err ~= errno.EAGAIN then
return false
end
return true
end
function Socket:accept()
local csock, err
while true do
csock, err = self.cobj:accept()
if csock then
break
end
if not self:_need_block(err) then
return nil, errno.strerror(err)
end
local ok, exception = _wait(self._read_event, self.timeout)
if not ok then
return nil, exception
end
end
return Socket.new(csock)
end
function Socket:_recv(func, ...)
local cobj = self.cobj
while true do
local data, err = func(cobj, ...)
if data then
return data
end
if not self:_need_block(err) then
return nil, err
end
local ok, exception = _wait(self._read_event, self.timeout)
if not ok then
return nil, exception
end
end
end
-- args:len
function Socket:recvfrom(len)
return self:_recv(self.cobj.recvfrom, len)
end
-- args: len
function Socket:recv(len)
return self:_recv(self.cobj.recv, len)
end
function Socket:_send(func, ...)
local cobj = self.cobj
while true do
local nwrite, err = func(cobj, ...)
if nwrite then
return nwrite
end
if not self:_need_block(err) then
return nil, err
end
local ok, exception = _wait(self._write_event, self.timeout)
if not ok then
return nil, exception
end
end
end
-- args: data, from
-- from: count from 0
function Socket:send(data, from)
return self:_send(self.cobj.send, data, from)
end
-- args:
function Socket:sendto(ip, port, data, from)
return self:_send(self.cobj.sendto, ip, port, data, from)
end
-- from: count from 0
function Socket:sendall(data, from)
local from = from or 0
local total = #data - from
local sent = 0
while sent < total do
local nwrite, err = self:send(data, from + sent)
if not nwrite then
return sent, err
end
sent = sent + nwrite
end
return sent
end
function Socket:connect(ip, port)
while true do
local ok, err = self.cobj:connect(ip, port)
if ok then
return ok
end
if self.timeout == 0.0 or (err ~= errno.EINPROGRESS and err ~= errno.EWOULDBLOCK) then
return ok, err
end
local ok, exception = _wait(self._write_event, self.timeout)
if not ok then
return nil, exception
end
end
end
function Socket:fileno()
return self.cobj:fileno()
end
function Socket:getpeername()
return self.cobj:getpeername()
end
function Socket:getsockname()
return self.cobj:getsockname()
end
function Socket:getsockopt(level, optname, buflen)
return self.cobj:getsockopt(level, optname, buflen)
end
function Socket:setsockopt(level, optname, value)
return self.cobj:setsockopt(level, optname, value)
end
function Socket:close()
if self.cobj ~= closed_socket then
hub:cancel_wait(self._read_event)
hub:cancel_wait(self._write_event)
self.cobj:close()
self.cobj = closed_socket
end
end
local socket = {}
function socket.socket(family, _type, protocol)
local cobj, err = c.socket(family, _type, protocol)
if not cobj then
return nil, errno.strerror(err)
end
return Socket.new(cobj)
end
return setmetatable(socket, {__index = c} )
|
bugfix: bad argument #1 to 'func' (socket_metatable expected, got table)
|
bugfix: bad argument #1 to 'func' (socket_metatable expected, got table)
|
Lua
|
mit
|
xjdrew/levent
|
01eb2e89b6177dc37496cff04a3dba8d0526055d
|
mod_mam/rsm.lib.lua
|
mod_mam/rsm.lib.lua
|
local stanza = require"util.stanza".stanza;
local tostring, tonumber = tostring, tonumber;
local type = type;
local pairs = pairs;
local xmlns_rsm = 'http://jabber.org/protocol/rsm';
local element_parsers;
do
local function xs_int(st)
return tonumber((st:get_text()));
end
local function xs_string(st)
return st:get_text();
end
element_parsers = {
after = xs_string;
before = function(st)
return st:get_text() or true;
end;
max = xs_int;
index = xs_int;
first = function(st)
return { index = tonumber(st.attr.index); st:get_text() };
end;
last = xs_string;
count = xs_int;
}
end
local element_generators = setmetatable({
first = function(st, data)
if type(data) == "table" then
st:tag("first", { index = data.index }):text(data[1]):up();
else
st:tag("first"):text(tostring(data)):up();
end
end;
}, {
__index = function(_, name)
return function(st, data)
st:tag(name):text(tostring(data)):up();
end
end;
});
local function parse(stanza)
local rs = {};
for tag in stanza:childtags() do
local name = tag.name;
local parser = name and element_parsers[name];
if parser then
rs[name] = parser(tag);
end
end
return rs;
end
local function generate(t)
local st = stanza("set", { xmlns = xmlns_rsm });
for k,v in pairs(t) do
if element_parsers[k] then
element_generators[k](st, v);
end
end
return st;
end
local function get(st)
local set = st:get_child("set", xmlns_rsm);
if set and #set.tags > 0 then
return parse(set);
end
end
return { parse = parse, generate = generate, get = get };
|
local stanza = require"util.stanza".stanza;
local tostring, tonumber = tostring, tonumber;
local type = type;
local pairs = pairs;
local xmlns_rsm = 'http://jabber.org/protocol/rsm';
local element_parsers;
do
local function xs_int(st)
return tonumber((st:get_text()));
end
local function xs_string(st)
return st:get_text();
end
element_parsers = {
after = xs_string;
before = function(st)
return st:get_text() or true;
end;
max = xs_int;
index = xs_int;
first = function(st)
return { index = tonumber(st.attr.index); st:get_text() };
end;
last = xs_string;
count = xs_int;
}
end
local element_generators = setmetatable({
first = function(st, data)
if type(data) == "table" then
st:tag("first", { index = data.index }):text(data[1]):up();
else
st:tag("first"):text(tostring(data)):up();
end
end;
before = function(st, data)
if data == true then
st:tag("before"):up();
else
st:tag("before"):text(tostring(data)):up();
end
end
}, {
__index = function(_, name)
return function(st, data)
st:tag(name):text(tostring(data)):up();
end
end;
});
local function parse(stanza)
local rs = {};
for tag in stanza:childtags() do
local name = tag.name;
local parser = name and element_parsers[name];
if parser then
rs[name] = parser(tag);
end
end
return rs;
end
local function generate(t)
local st = stanza("set", { xmlns = xmlns_rsm });
for k,v in pairs(t) do
if element_parsers[k] then
element_generators[k](st, v);
end
end
return st;
end
local function get(st)
local set = st:get_child("set", xmlns_rsm);
if set and #set.tags > 0 then
return parse(set);
end
end
return { parse = parse, generate = generate, get = get };
|
mod_mam/rsm.lib: Fix serialization of before = true
|
mod_mam/rsm.lib: Fix serialization of before = true
|
Lua
|
mit
|
Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules
|
e2542e5d7174100924e2e453bd29fb422e83e8f9
|
layout-a4.lua
|
layout-a4.lua
|
local class = SILE.documentState.documentClass
class:declareFrame("content", { left = "32mm", right = "100%pw-32mm", top = "36mm", bottom = "top(footnotes)" })
class:declareFrame("runningHead", { left = "left(content)", right = "right(content)", top = "top(content)-12mm", bottom = "top(content)-2mm" })
class:declareFrame("footnotes", { left = "left(content)", right = "right(content)", height = "0", bottom = "100%ph-24mm"})
SILE.registerCommand("meta:distribution", function (options, content)
SILE.call("font", { weight = 600, style = "Bold" }, { "Yayın: " })
SILE.typesetter:typeset("Bu PDF biçimi, özellikle yerel kiliselerin kendi cemaatları için basmalarına uygun hazırlanmıştır ve Via Christus’un internet sitesinde üçretsiz yayılmaktadır.")
end)
-- We have a bound A4 format too, but this one doesn't need double-page openers
SILE.registerCommand("open-double-page", function ()
SILE.typesetter:leaveHmode();
SILE.Commands["supereject"]();
SILE.typesetter:leaveHmode();
end)
|
local class = SILE.documentState.documentClass
class:defineMaster({
id = "right",
firstContentFrame = "content",
frames = {
content = {
left = "32mm",
right = "100%pw-32mm",
top = "bottom(runningHead)+4mm",
bottom = "top(footnotes)-4mm"
},
runningHead = {
left = "left(content)",
right = "right(content)",
top = "24mm",
bottom = "30mm"
},
footnotes = {
left = "left(content)",
right = "right(content)",
height = "0",
bottom = "top(folio)-4mm"
},
folio = {
left = "left(content)",
right = "right(content)",
top = "100%ph-30mm",
bottom = "100%ph-24mm"
}
}
})
class:mirrorMaster("right", "left")
SILE.call("switch-master-one-page", { id = "right" })
SILE.registerCommand("meta:distribution", function (options, content)
SILE.call("font", { weight = 600, style = "Bold" }, { "Yayın: " })
SILE.typesetter:typeset("Bu PDF biçimi, özellikle yerel kiliselerin kendi cemaatları için basmalarına uygun hazırlanmıştır ve Via Christus’un internet sitesinde üçretsiz yayılmaktadır.")
end)
-- We have a bound A4 format too, but this one doesn't need double-page openers
SILE.registerCommand("open-double-page", function ()
SILE.typesetter:leaveHmode();
SILE.Commands["supereject"]();
SILE.typesetter:leaveHmode();
end)
|
Fix frames layout to 'undo' masters layouts
|
Fix frames layout to 'undo' masters layouts
Even though _this_ layout isn't a dual sided masters, this is the
exception and our class has already loaded that stuff up. Unless we port
the class to not be based on book, we need to undo the masters layout
stuff rather that just setting up the single page template.
|
Lua
|
agpl-3.0
|
alerque/casile,alerque/casile,alerque/casile,alerque/casile,alerque/casile
|
7cd5b23ff4048c7fd1bf44a299369325669bcfcf
|
src/pcap.lua
|
src/pcap.lua
|
-- pcap.lua -- simple pcap file export
-- Copyright 2012 Snabb GmbH. See the file LICENSE.
module(...,package.seeall)
local ffi = require("ffi")
local c = require("c")
-- PCAP file format: http://wiki.wireshark.org/Development/LibpcapFileFormat/
ffi.cdef[[
struct pcap_file {
/* file header */
uint32_t magic_number; /* magic number */
uint16_t version_major; /* major version number */
uint16_t version_minor; /* minor version number */
int32_t thiszone; /* GMT to local correction */
uint32_t sigfigs; /* accuracy of timestamps */
uint32_t snaplen; /* max length of captured packets, in octets */
uint32_t network; /* data link type */
}
struct pcap_record {
/* record header */
uint32_t ts_sec; /* timestamp seconds */
uint32_t ts_usec; /* timestamp microseconds */
uint32_t incl_len; /* number of octets of packet saved in file */
uint32_t orig_len; /* actual length of packet */
}
struct pcap_record_extra {
/* Extra metadata that we append to the pcap record, after the payload. */
uint32_t port_id; /* port the packet is captured on */
uint32_t flags; /* bit 0 set means input, bit 0 clear means output */
uint64_t reserved0, reserved1, reserved2, reserved3;
}
]]
function write_file_header(file)
local pcap_file = ffi.new("struct pcap_file")
pcap_file.magic_number = 0xa1b2c3d4
pcap_file.version_major = 2
pcap_file.version_minor = 4
pcap_file.snaplen = 65535
pcap_file.network = 1
file:write(ffi.string(pcap_file, ffi.sizeof(pcap_file)))
file:flush()
end
local pcap_extra = ffi.new("struct pcap_record_extra")
ffi.C.memset(pcap_extra, 0, ffi.sizeof(pcap_extra))
function write_record(file, ffi_buffer, length, port, input)
local pcap_record = ffi.new("struct pcap_record")
local incl_len = length;
if port ~= nil then
incl_len = incl_len + ffi.sizeof(pcap_extra)
pcap_extra.port_id = port
pcap_extra.flags = (input and 0) or 1
end
pcap_record.incl_len = incl_len
pcap_record.orig_len = length
file:write(ffi.string(pcap_record, ffi.sizeof(pcap_record)))
file:write(ffi.string(ffi_buffer, length))
if port ~= nil then
-- print 'write extra bytes...'
file:write(ffi.string(pcap_extra, ffi.sizeof(pcap_extra)))
end
file:flush()
end
-- Return an iterator for pcap records in FILENAME.
function records (filename)
local file = io.open(filename, "r")
local pcap_file = readc(file, "struct pcap_file")
if pcap_file.magic_number == 0xD4C3B2A1 then
error("Endian mismatch in " .. filename)
elseif pcap_file.magic_number ~= 0xA1B2C3D4 then
error("Bad PCAP magic number in " .. filename)
end
local function pcap_records_it (t, i)
local record = readc(file, "struct pcap_record")
if record == nil then return nil end
local datalen = math.min(record.orig_len, record.incl_len)
local packet = file:read(datalen)
local extra = nil
if record.incl_len == #packet + ffi.sizeof("struct pcap_record_extra") then
extra = readc(file, "struct pcap_record_extra")
end
return packet, record, extra
end
return pcap_records_it, true, true
end
-- Read a C object of TYPE from FILE. Return a pointer to the result.
function readc(file, type)
local string = file:read(ffi.sizeof(type))
if string == nil then return nil end
if #string ~= ffi.sizeof(type) then
error("short read of " .. type .. " from " .. tostring(file))
end
return ffi.cast(type.."*", string)
end
|
-- pcap.lua -- simple pcap file export
-- Copyright 2012 Snabb GmbH. See the file LICENSE.
module(...,package.seeall)
local ffi = require("ffi")
-- PCAP file format: http://wiki.wireshark.org/Development/LibpcapFileFormat/
ffi.cdef[[
struct pcap_file {
/* file header */
uint32_t magic_number; /* magic number */
uint16_t version_major; /* major version number */
uint16_t version_minor; /* minor version number */
int32_t thiszone; /* GMT to local correction */
uint32_t sigfigs; /* accuracy of timestamps */
uint32_t snaplen; /* max length of captured packets, in octets */
uint32_t network; /* data link type */
}
struct pcap_record {
/* record header */
uint32_t ts_sec; /* timestamp seconds */
uint32_t ts_usec; /* timestamp microseconds */
uint32_t incl_len; /* number of octets of packet saved in file */
uint32_t orig_len; /* actual length of packet */
}
struct pcap_record_extra {
/* Extra metadata that we append to the pcap record, after the payload. */
uint32_t port_id; /* port the packet is captured on */
uint32_t flags; /* bit 0 set means input, bit 0 clear means output */
uint64_t reserved0, reserved1, reserved2, reserved3;
}
]]
function write_file_header(file)
local pcap_file = ffi.new("struct pcap_file")
pcap_file.magic_number = 0xa1b2c3d4
pcap_file.version_major = 2
pcap_file.version_minor = 4
pcap_file.snaplen = 65535
pcap_file.network = 1
file:write(ffi.string(pcap_file, ffi.sizeof(pcap_file)))
file:flush()
end
local pcap_extra = ffi.new("struct pcap_record_extra")
ffi.fill(pcap_extra, ffi.sizeof(pcap_extra), 0)
function write_record(file, ffi_buffer, length, port, input)
local pcap_record = ffi.new("struct pcap_record")
local incl_len = length;
if port ~= nil then
incl_len = incl_len + ffi.sizeof(pcap_extra)
pcap_extra.port_id = port
pcap_extra.flags = (input and 0) or 1
end
pcap_record.incl_len = incl_len
pcap_record.orig_len = length
file:write(ffi.string(pcap_record, ffi.sizeof(pcap_record)))
file:write(ffi.string(ffi_buffer, length))
if port ~= nil then
-- print 'write extra bytes...'
file:write(ffi.string(pcap_extra, ffi.sizeof(pcap_extra)))
end
file:flush()
end
-- Return an iterator for pcap records in FILENAME.
function records (filename)
local file = io.open(filename, "r")
if file == nil then error("Unable to open file: " .. filename) end
local pcap_file = readc(file, "struct pcap_file")
if pcap_file.magic_number == 0xD4C3B2A1 then
error("Endian mismatch in " .. filename)
elseif pcap_file.magic_number ~= 0xA1B2C3D4 then
error("Bad PCAP magic number in " .. filename)
end
local function pcap_records_it (t, i)
local record = readc(file, "struct pcap_record")
if record == nil then return nil end
local datalen = math.min(record.orig_len, record.incl_len)
local packet = file:read(datalen)
local extra = nil
if record.incl_len == #packet + ffi.sizeof("struct pcap_record_extra") then
extra = readc(file, "struct pcap_record_extra")
end
return packet, record, extra
end
return pcap_records_it, true, true
end
-- Read a C object of TYPE from FILE. Return a pointer to the result.
function readc(file, type)
local string = file:read(ffi.sizeof(type))
if string == nil then return nil end
if #string ~= ffi.sizeof(type) then
error("short read of " .. type .. " from " .. tostring(file))
end
return ffi.cast(type.."*", string)
end
|
pcap.lua: Minor fixes.
|
pcap.lua: Minor fixes.
|
Lua
|
apache-2.0
|
dpino/snabbswitch,kellabyte/snabbswitch,SnabbCo/snabbswitch,lukego/snabb,plajjan/snabbswitch,hb9cwp/snabbswitch,snabbco/snabb,xdel/snabbswitch,alexandergall/snabbswitch,SnabbCo/snabbswitch,andywingo/snabbswitch,Igalia/snabbswitch,eugeneia/snabbswitch,kellabyte/snabbswitch,lukego/snabbswitch,mixflowtech/logsensor,plajjan/snabbswitch,Igalia/snabb,kbara/snabb,alexandergall/snabbswitch,alexandergall/snabbswitch,mixflowtech/logsensor,wingo/snabbswitch,eugeneia/snabb,dwdm/snabbswitch,alexandergall/snabbswitch,Igalia/snabbswitch,Igalia/snabb,SnabbCo/snabbswitch,snabbco/snabb,eugeneia/snabb,dpino/snabb,snabbco/snabb,alexandergall/snabbswitch,pavel-odintsov/snabbswitch,fhanik/snabbswitch,kbara/snabb,Igalia/snabb,hb9cwp/snabbswitch,virtualopensystems/snabbswitch,Igalia/snabb,SnabbCo/snabbswitch,andywingo/snabbswitch,eugeneia/snabbswitch,lukego/snabbswitch,snabbco/snabb,eugeneia/snabbswitch,wingo/snabb,eugeneia/snabb,snabbnfv-goodies/snabbswitch,mixflowtech/logsensor,pavel-odintsov/snabbswitch,dpino/snabb,dpino/snabb,xdel/snabbswitch,dwdm/snabbswitch,fhanik/snabbswitch,xdel/snabbswitch,heryii/snabb,javierguerragiraldez/snabbswitch,snabbnfv-goodies/snabbswitch,heryii/snabb,javierguerragiraldez/snabbswitch,Igalia/snabb,virtualopensystems/snabbswitch,javierguerragiraldez/snabbswitch,snabbco/snabb,alexandergall/snabbswitch,heryii/snabb,wingo/snabbswitch,eugeneia/snabb,pavel-odintsov/snabbswitch,kellabyte/snabbswitch,wingo/snabb,eugeneia/snabb,eugeneia/snabbswitch,wingo/snabb,kbara/snabb,lukego/snabbswitch,kbara/snabb,andywingo/snabbswitch,eugeneia/snabb,dwdm/snabbswitch,Igalia/snabb,wingo/snabbswitch,eugeneia/snabb,mixflowtech/logsensor,wingo/snabb,heryii/snabb,snabbco/snabb,kbara/snabb,Igalia/snabbswitch,virtualopensystems/snabbswitch,dpino/snabbswitch,alexandergall/snabbswitch,justincormack/snabbswitch,justincormack/snabbswitch,plajjan/snabbswitch,aperezdc/snabbswitch,pirate/snabbswitch,heryii/snabb,lukego/snabbswitch,wingo/snabbswitch,lukego/snabb,andywingo/snabbswitch,heryii/snabb,dpino/snabb,Igalia/snabbswitch,dpino/snabb,lukego/snabb,alexandergall/snabbswitch,eugeneia/snabb,snabbnfv-goodies/snabbswitch,hb9cwp/snabbswitch,aperezdc/snabbswitch,fhanik/snabbswitch,snabbco/snabb,dpino/snabbswitch,justincormack/snabbswitch,Igalia/snabb,pirate/snabbswitch,dpino/snabbswitch,snabbnfv-goodies/snabbswitch,wingo/snabb,aperezdc/snabbswitch,Igalia/snabb,wingo/snabb,lukego/snabb,justincormack/snabbswitch,dpino/snabb,kbara/snabb,hb9cwp/snabbswitch,aperezdc/snabbswitch,plajjan/snabbswitch,mixflowtech/logsensor,dpino/snabb,Igalia/snabbswitch,pirate/snabbswitch,snabbco/snabb
|
8e8d81d27c35ce966b22bf819faeae0bb7982eca
|
src/pegasus/handler.lua
|
src/pegasus/handler.lua
|
local Request = require 'pegasus.request'
local Response = require 'pegasus.response'
local mimetypes = require 'mimetypes'
local lfs = require 'lfs'
local Handler = {}
Handler.__index = Handler
function Handler:new(callback, location, plugins)
local handler = {}
handler.callback = callback
handler.location = location or ''
handler.plugins = plugins or {}
local result = setmetatable(handler, self)
result:pluginsAlterRequestResponseMetatable()
return result
end
function Handler:pluginsAlterRequestResponseMetatable()
for _, plugin in ipairs(self.plugins) do
if plugin.alterRequestResponseMetaTable then
local stop = plugin:alterRequestResponseMetaTable(Request, Response)
if stop then
return stop
end
end
end
end
function Handler:pluginsNewRequestResponse(request, response)
for _, plugin in ipairs(self.plugins) do
if plugin.newRequestResponse then
local stop = plugin:newRequestResponse(request, response)
if stop then
return stop
end
end
end
end
function Handler:pluginsBeforeProcess(request, response)
for _, plugin in ipairs(self.plugins) do
if plugin.beforeProcess then
local stop = plugin:beforeProcess(request, response)
if stop then
return stop
end
end
end
end
function Handler:pluginsAfterProcess(request, response)
for _, plugin in ipairs(self.plugins) do
if plugin.afterProcess then
local stop = plugin:afterProcess(request, response)
if stop then
return stop
end
end
end
end
function Handler:pluginsProcessFile(request, response, filename)
for _, plugin in ipairs(self.plugins) do
if plugin.processFile then
local stop = plugin:processFile(request, response, filename)
if stop then
return stop
end
end
end
end
function Handler:processBodyData(data, stayOpen, response)
local localData = data
for _, plugin in ipairs(self.plugins or {}) do
if plugin.processBodyData then
localData = plugin:processBodyData(
localData,
stayOpen,
response.request,
response
)
end
end
return localData
end
function Handler:processRequest(port, client, server)
local request = Request:new(port, client, server)
-- if we get some invalid request just close it
-- do not try handle or response
if not request:method() then
server:close()
client:close()
return
end
local response = Response:new(client, self)
response.request = request
local stop = self:pluginsNewRequestResponse(request, response)
if stop then
return
end
if request:path() and self.location ~= '' then
local path = (request:path() == '/' or request:path() == '') and 'index.html' or request:path()
local filename = '.' .. self.location .. path
if not lfs.attributes(filename) then
response:statusCode(404)
end
stop = self:pluginsProcessFile(request, response, filename)
if stop then
return
end
local file = io.open(filename, 'rb')
if file then
response:writeFile(file, mimetypes.guess(filename or '') or 'text/html')
else
response:statusCode(404)
end
end
if self.callback then
response:statusCode(200)
response.headers = {}
response:addHeader('Content-Type', 'text/html')
self.callback(request, response)
end
if response.status == 404 then
response:writeDefaultErrorMessage(404)
end
end
return Handler
|
local Request = require 'pegasus.request'
local Response = require 'pegasus.response'
local mimetypes = require 'mimetypes'
local lfs = require 'lfs'
local function ternary(condition, t, f)
if condition then return t else return f end
end
local Handler = {}
Handler.__index = Handler
function Handler:new(callback, location, plugins)
local handler = {}
handler.callback = callback
handler.location = location or ''
handler.plugins = plugins or {}
local result = setmetatable(handler, self)
result:pluginsAlterRequestResponseMetatable()
return result
end
function Handler:pluginsAlterRequestResponseMetatable()
for _, plugin in ipairs(self.plugins) do
if plugin.alterRequestResponseMetaTable then
local stop = plugin:alterRequestResponseMetaTable(Request, Response)
if stop then
return stop
end
end
end
end
function Handler:pluginsNewRequestResponse(request, response)
for _, plugin in ipairs(self.plugins) do
if plugin.newRequestResponse then
local stop = plugin:newRequestResponse(request, response)
if stop then
return stop
end
end
end
end
function Handler:pluginsBeforeProcess(request, response)
for _, plugin in ipairs(self.plugins) do
if plugin.beforeProcess then
local stop = plugin:beforeProcess(request, response)
if stop then
return stop
end
end
end
end
function Handler:pluginsAfterProcess(request, response)
for _, plugin in ipairs(self.plugins) do
if plugin.afterProcess then
local stop = plugin:afterProcess(request, response)
if stop then
return stop
end
end
end
end
function Handler:pluginsProcessFile(request, response, filename)
for _, plugin in ipairs(self.plugins) do
if plugin.processFile then
local stop = plugin:processFile(request, response, filename)
if stop then
return stop
end
end
end
end
function Handler:processBodyData(data, stayOpen, response)
local localData = data
for _, plugin in ipairs(self.plugins or {}) do
if plugin.processBodyData then
localData = plugin:processBodyData(
localData,
stayOpen,
response.request,
response
)
end
end
return localData
end
function Handler:processRequest(port, client, server)
local request = Request:new(port, client, server)
if not request:method() then
client:close()
return
end
local response = Response:new(client, self)
response.request = request
local stop = self:pluginsNewRequestResponse(request, response)
if stop then
return
end
if request:path() and self.location ~= '' then
local path = ternary(request:path() == '/' or request:path() == '', 'index.html', request:path())
local filename = '.' .. self.location .. path
if not lfs.attributes(filename) then
response:statusCode(404)
end
stop = self:pluginsProcessFile(request, response, filename)
if stop then
return
end
local file = io.open(filename, 'rb')
if file then
response:writeFile(file, mimetypes.guess(filename or '') or 'text/html')
else
response:statusCode(404)
end
end
if self.callback then
response:statusCode(200)
response.headers = {}
response:addHeader('Content-Type', 'text/html')
self.callback(request, response)
end
if response.status == 404 then
response:writeDefaultErrorMessage(404)
end
end
return Handler
|
fix issue in processRequest method
|
fix issue in processRequest method
|
Lua
|
mit
|
EvandroLG/pegasus.lua
|
32713a3dcb7ee5850eadf6183f73fdac815931a1
|
config/nvim/lua/settings/gitsigns.lua
|
config/nvim/lua/settings/gitsigns.lua
|
require("gitsigns").setup {
signs = {
add = {hl = "GitSignsAdd", text = "│", numhl = "GitSignsAddNr", linehl = "GitSignsAddLn"},
change = {hl = "GitSignsChange", text = "│", numhl = "GitSignsChangeNr", linehl = "GitSignsChangeLn"},
delete = {hl = "GitSignsDelete", text = "_", numhl = "GitSignsDeleteNr", linehl = "GitSignsDeleteLn"},
topdelete = {hl = "GitSignsDelete", text = "‾", numhl = "GitSignsDeleteNr", linehl = "GitSignsDeleteLn"},
changedelete = {hl = "GitSignsChange", text = "~", numhl = "GitSignsChangeNr", linehl = "GitSignsChangeLn"}
},
numhl = false,
linehl = false,
keymaps = {
-- Default keymap options
noremap = true,
["n ]c"] = {expr = true, '&diff ? \']c\' : \'<cmd>lua require"gitsigns.actions".next_hunk()<CR>\''},
["n [c"] = {expr = true, '&diff ? \'[c\' : \'<cmd>lua require"gitsigns.actions".prev_hunk()<CR>\''},
["n <leader>hs"] = '<cmd>lua require"gitsigns".stage_hunk()<CR>',
["v <leader>hs"] = '<cmd>lua require"gitsigns".stage_hunk({vim.fn.line("."), vim.fn.line("v")})<CR>',
["n <leader>hu"] = '<cmd>lua require"gitsigns".undo_stage_hunk()<CR>',
["n <leader>hr"] = '<cmd>lua require"gitsigns".reset_hunk()<CR>',
["v <leader>hr"] = '<cmd>lua require"gitsigns".reset_hunk({vim.fn.line("."), vim.fn.line("v")})<CR>',
["n <leader>hR"] = '<cmd>lua require"gitsigns".reset_buffer()<CR>',
["n <leader>hp"] = '<cmd>lua require"gitsigns".preview_hunk()<CR>',
["n <leader>hb"] = '<cmd>lua require"gitsigns".blame_line(true)<CR>',
-- Text objects
["o ih"] = ':<C-U>lua require"gitsigns.actions".select_hunk()<CR>',
["x ih"] = ':<C-U>lua require"gitsigns.actions".select_hunk()<CR>'
},
watch_index = {
interval = 1000,
follow_files = true
},
current_line_blame = false,
current_line_blame_delay = 1000,
current_line_blame_position = "eol",
sign_priority = 6,
update_debounce = 100,
status_formatter = nil, -- Use default
word_diff = true,
use_internal_diff = true -- If luajit is present
}
|
require("gitsigns").setup {
signs = {
add = {hl = "GitSignsAdd", text = "│", numhl = "GitSignsAddNr", linehl = "GitSignsAddLn"},
change = {hl = "GitSignsChange", text = "│", numhl = "GitSignsChangeNr", linehl = "GitSignsChangeLn"},
delete = {hl = "GitSignsDelete", text = "_", numhl = "GitSignsDeleteNr", linehl = "GitSignsDeleteLn"},
topdelete = {hl = "GitSignsDelete", text = "‾", numhl = "GitSignsDeleteNr", linehl = "GitSignsDeleteLn"},
changedelete = {hl = "GitSignsChange", text = "~", numhl = "GitSignsChangeNr", linehl = "GitSignsChangeLn"}
},
numhl = false,
linehl = false,
keymaps = {
-- Default keymap options
noremap = true,
["n ]c"] = {expr = true, '&diff ? \']c\' : \'<cmd>lua require"gitsigns.actions".next_hunk()<CR>\''},
["n [c"] = {expr = true, '&diff ? \'[c\' : \'<cmd>lua require"gitsigns.actions".prev_hunk()<CR>\''},
["n <leader>hs"] = '<cmd>lua require"gitsigns".stage_hunk()<CR>',
["v <leader>hs"] = '<cmd>lua require"gitsigns".stage_hunk({vim.fn.line("."), vim.fn.line("v")})<CR>',
["n <leader>hu"] = '<cmd>lua require"gitsigns".undo_stage_hunk()<CR>',
["n <leader>hr"] = '<cmd>lua require"gitsigns".reset_hunk()<CR>',
["v <leader>hr"] = '<cmd>lua require"gitsigns".reset_hunk({vim.fn.line("."), vim.fn.line("v")})<CR>',
["n <leader>hR"] = '<cmd>lua require"gitsigns".reset_buffer()<CR>',
["n <leader>hp"] = '<cmd>lua require"gitsigns".preview_hunk()<CR>',
["n <leader>hb"] = '<cmd>lua require"gitsigns".blame_line(true)<CR>',
-- Text objects
["o ih"] = ':<C-U>lua require"gitsigns.actions".select_hunk()<CR>',
["x ih"] = ':<C-U>lua require"gitsigns.actions".select_hunk()<CR>'
},
watch_index = {
interval = 1000,
follow_files = true
},
current_line_blame_opts = {
delay = 1000,
virtual_text_pos = "eol"
},
current_line_blame = false,
sign_priority = 6,
update_debounce = 100,
status_formatter = nil, -- Use default
word_diff = true,
use_internal_diff = true -- If luajit is present
}
|
fix(vim): remove deprecated gitsigns opts
|
fix(vim): remove deprecated gitsigns opts
|
Lua
|
mit
|
nicknisi/dotfiles,nicknisi/dotfiles,nicknisi/dotfiles
|
ba7c37d212db8a466f13e9e896f37d61f898ead2
|
base/explosion.lua
|
base/explosion.lua
|
--[[
Illarion Server
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License as published by the Free
Software Foundation, either version 3 of the License, or (at your option) any
later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU Affero General Public License for more
details.
You should have received a copy of the GNU Affero General Public License along
with this program. If not, see <http://www.gnu.org/licenses/>.
]]
require("base.common")
module("base.explosion", package.seeall)
function CreateExplosion(CenterPos)
function CreateOuterCircle(HitPos)
CreateExplosionCircle(HitPos, 1,250,CenterPos,false);
return true;
end
function CreateMiddleCircle(HitPos)
CreateExplosionCircle(HitPos,9,750,CenterPos,true);
return true;
end
function CreateInnerCircle(HitPos)
CreateExplosionCircle(HitPos, 44,1000,CenterPos,true);
return true;
end
base.common.CreateCircle(CenterPos, 3, CreateouterCircle);
base.common.CreateCircle(CenterPos, 2, CreateMiddleCircle);
base.common.CreateCircle(CenterPos, 1, CreateInnerCircle);
world:gfx(36,CenterPos);
world:makeSound(5,CenterPos);
end
function CreateExplosionCircle(HitPos,gfxid,Damage,CenterPos,setFlames)
world:gfx(gfxid,HitPos);
HitChar(HitPos,Damage,CenterPos);
if setFlames then
if (math.random(1,5)==1) then
world:createItemFromId(359,1,HitPos,true,math.random(200,600),nil);
end
end
end;
function HitChar(Posi,Hitpoints,CenterPos)
if world:isCharacterOnField(Posi) then
local Character = world:getCharacterOnField(Posi);
if (Character:getType() == 2) then --dont touch npcs
return;
end
local posX;
local posY;
if (Posi == CenterPos) then
posX = Character.pos.x+math.random(-9,9)
posY = Character.pos.y+math.random(-9,9)
else
local Distance = Character:distanceMetricToPosition(CenterPos);
local Diffx = CenterPos.x - Character.pos.x;
local Diffy = CenterPos.y - Character.pos.y;
if (Distance == 1) then
Diffx = 6*Diffx;
Diffy = 6*Diffy;
elseif (Distance == 2) then
Diffx = 2*Diffx;
Diffy = 2*Diffy;
end
posX = Character.pos.x-Diffx
posY = Character.pos.y-Diffy
end
local listOfStuff = world:LoS(Character.pos, position(posX,posY,Character.pos.z))
if listOfStuff ~= nil then
local minDistance = Character:distanceMetricToPosition(position(posX,posY,Character.pos.z));
for i, listEntry in pairs(listOfStuff) do
local itemPos = listEntry.OBJECT.pos
local field = world:getField(itemPos)
local tempX = posX;
local tempY = posY;
-- something not passable is in the way, recalculate position
if not field:isPassable() then
local phi = base.common.GetPhi(Character.pos, itemPos);
if (phi < math.pi / 8) then
tempX = itemPos.x - 1
elseif (phi < 3 * math.pi / 8) then
tempX = itemPos.x - 1
tempY = itemPos.y - 1
elseif (phi < 5 * math.pi / 8) then
tempY = itemPos.y - 1
elseif (phi < 7 * math.pi / 8) then
tempX = itemPos.x + 1
tempY = itemPos.y - 1
elseif (phi < 9 * math.pi / 8) then
tempX = itemPos.x + 1
elseif (phi < 11 * math.pi / 8) then
tempX = itemPos.x + 1
tempY = itemPos.y + 1
elseif (phi < 13 * math.pi / 8) then
tempY = itemPos.y + 1
elseif (phi < 15 * math.pi / 8) then
tempX = itemPos.x - 1
tempY = itemPos.y + 1
else
tempX = itemPos.x - 1
end;
local tempDistance = Character:distanceMetricToPosition(position(tempX,tempY,Character.pos.z));
if ( tempDistance < minDistance) then
minDistance = tempDistance;
posX = tempX;
posY = tempY;
end
end
end
end
Character:warp(position(posX,posY,Character.pos.z));
base.common.InformNLS(Character,
"Getroffen von der Detonation wirst du davon geschleudert.",
"Hit by the detonation, you get thrown away.");
Character:increaseAttrib("hitpoints",-Hitpoints);
end;
end;
|
--[[
Illarion Server
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License as published by the Free
Software Foundation, either version 3 of the License, or (at your option) any
later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU Affero General Public License for more
details.
You should have received a copy of the GNU Affero General Public License along
with this program. If not, see <http://www.gnu.org/licenses/>.
]]
require("base.common")
module("base.explosion", package.seeall)
--[[
CreateExplosion
Provide an explosion that also throws characters away, in a radios of 3 fields
@param integer - Center of the explosion
]]
function CreateExplosion(CenterPos)
function CreateOuterCircle(HitPos)
CreateExplosionCircle(HitPos, 1,250,CenterPos,false);
return true;
end
function CreateMiddleCircle(HitPos)
CreateExplosionCircle(HitPos,9,750,CenterPos,true);
return true;
end
function CreateInnerCircle(HitPos)
CreateExplosionCircle(HitPos, 44,1000,CenterPos,true);
return true;
end
base.common.CreateCircle(CenterPos, 3, CreateOuterCircle);
base.common.CreateCircle(CenterPos, 2, CreateMiddleCircle);
base.common.CreateCircle(CenterPos, 1, CreateInnerCircle);
world:gfx(36,CenterPos);
world:makeSound(5,CenterPos);
end
function CreateExplosionCircle(HitPos,gfxid,Damage,CenterPos,setFlames)
world:gfx(gfxid,HitPos);
HitChar(HitPos,Damage,CenterPos);
if setFlames then
if (math.random(1,5)==1) then
world:createItemFromId(359,1,HitPos,true,math.random(200,600),nil);
end
end
end;
function HitChar(Posi,Hitpoints,CenterPos)
if world:isCharacterOnField(Posi) then
local Character = world:getCharacterOnField(Posi);
if (Character:getType() == 2) then --dont touch npcs
return;
end
local posX;
local posY;
if (Posi == CenterPos) then -- code path not reached
posX = Character.pos.x+math.random(-9,9)
posY = Character.pos.y+math.random(-9,9)
else
local Distance = Character:distanceMetricToPosition(CenterPos);
local Diffx = CenterPos.x - Character.pos.x;
local Diffy = CenterPos.y - Character.pos.y;
if (Distance == 1) then
Diffx = 6*Diffx;
Diffy = 6*Diffy;
elseif (Distance == 2) then
Diffx = 2*Diffx;
Diffy = 2*Diffy;
end
posX = Character.pos.x-Diffx
posY = Character.pos.y-Diffy
end
local listOfStuff = world:LoS(Character.pos, position(posX,posY,Character.pos.z))
if listOfStuff ~= nil then
local minDistance = Character:distanceMetricToPosition(position(posX,posY,Character.pos.z));
for i, listEntry in pairs(listOfStuff) do
local itemPos = listEntry.OBJECT.pos
local field = world:getField(itemPos)
local tempX = posX;
local tempY = posY;
-- something not passable is in the way, recalculate position
if not field:isPassable() then
local phi = base.common.GetPhi(Character.pos, itemPos);
if (phi < math.pi / 8) then
tempX = itemPos.x - 1
elseif (phi < 3 * math.pi / 8) then
tempX = itemPos.x - 1
tempY = itemPos.y - 1
elseif (phi < 5 * math.pi / 8) then
tempY = itemPos.y - 1
elseif (phi < 7 * math.pi / 8) then
tempX = itemPos.x + 1
tempY = itemPos.y - 1
elseif (phi < 9 * math.pi / 8) then
tempX = itemPos.x + 1
elseif (phi < 11 * math.pi / 8) then
tempX = itemPos.x + 1
tempY = itemPos.y + 1
elseif (phi < 13 * math.pi / 8) then
tempY = itemPos.y + 1
elseif (phi < 15 * math.pi / 8) then
tempX = itemPos.x - 1
tempY = itemPos.y + 1
else
tempX = itemPos.x - 1
end;
local tempDistance = Character:distanceMetricToPosition(position(tempX,tempY,Character.pos.z));
if ( tempDistance < minDistance) then
minDistance = tempDistance;
posX = tempX;
posY = tempY;
end
end
end
end
Character:warp(position(posX,posY,Character.pos.z));
base.common.InformNLS(Character,
"Getroffen von der Detonation wirst du davon geschleudert.",
"Hit by the detonation, you get thrown away.");
Character:increaseAttrib("hitpoints",-Hitpoints);
end;
end;
|
fix typo
|
fix typo
|
Lua
|
agpl-3.0
|
vilarion/Illarion-Content,KayMD/Illarion-Content,Baylamon/Illarion-Content,LaFamiglia/Illarion-Content,Illarion-eV/Illarion-Content
|
1bbe5c99b40fb66e436d34b892fead702d4b8923
|
src/lua/sancus/web/dispatcher.lua
|
src/lua/sancus/web/dispatcher.lua
|
--
local utils = require"sancus.utils"
local object = require"sancus.object"
local urltemplate = require"sancus.web.urltemplate"
--
--
local function wsapi_logger(env, status, message)
local h = env.headers
local script_name = h["SCRIPT_NAME"]
local path_info = h["PATH_INFO"]
local method = h["REQUEST_METHOD"]
local logged = false
local prefix = "PathMapper: %s %s%s: %s"
if script_name == "" then
script_name = path_info
path_info = ""
elseif path_info ~= "" then
path_info = " (PATH_INFO:"..path_info..")"
end
prefix = prefix:format(method, script_name, path_info, status)
if message ~= nil and message ~= "" then
for l in message:gmatch("[^\r\n]+") do
logged = true
utils.stderr("%s: %s\n", prefix, l)
end
end
if not logged then
utils.stderr("%s\n", prefix)
end
end
local function wsapi_silent_logger(env, status, message)
if status == 500 then
return wsapi_logger(env, status, message)
end
end
local function wsapi_traceback(env, logger, e)
logger(env, 500, e)
logger(env, 500, debug.traceback())
logger(env, 500, "-- END TRACEBACK --")
return e
end
--
--
local M = object.Class{
compile = urltemplate.URLTemplateCompiler
}
function M:__call(wsapi_env)
local h = self:find_handler(wsapi_env)
if h == nil then
self.logger(wsapi_env, 404, "Handler not found")
return 404
else
local handler = function() return h(wsapi_env) end
local traceback = function(e) return wsapi_traceback(wsapi_env, self.logger, e) end
local success, status, headers, iter = xpcall(handler, traceback)
if success then
self.logger(wsapi_env, status)
return status, headers, iter
else
-- already logged by traceback
return 500
end
end
end
function M:find_handler(env)
local script_name = env.headers["SCRIPT_NAME"] or ""
local path_info = env.headers["PATH_INFO"] or ""
for _, t in ipairs(self.patterns) do
local regex, h, kw = unpack(t)
local c, p = regex:match(path_info)
if p then
local matched_path_info = path_info:sub(1, p-1)
local extra_path_info = path_info:sub(p)
if #extra_path_info == 0 or
(#extra_path_info > 0 and extra_path_info:sub(1,1) == "/") then
-- good match
local routing_args = env.headers["sancus.routing_args"] or {}
-- import captures
for k,v in pairs(c) do
routing_args[k] = v
end
-- and import extra add() args
if kw then
for k,v in pairs(kw) do
routing_args[k] = v
end
end
env.headers["sancus.routing_args"] = routing_args
env.headers["SCRIPT_NAME"] = script_name .. matched_path_info
env.headers["PATH_INFO"] = extra_path_info
return h
end
end
end
end
function M:add(expr, h, kw)
local p = assert(self.compile(expr))
self.patterns[#self.patterns + 1] = {p, h, kw}
end
return {
PathMapper = function (o)
o = M(o)
o.patterns = o.patterns or {}
if o.logger == false then
o.logger = wsapi_silent_logger
elseif o.logger == true or type(o.logger) ~= "function" then
o.logger = wsapi_logger
end
return o
end
}
|
--
local utils = require"sancus.utils"
local object = require"sancus.object"
local urltemplate = require"sancus.web.urltemplate"
--
--
local function wsapi_logger(env, status, message)
local h = env.headers
local script_name = h["SCRIPT_NAME"]
local path_info = h["PATH_INFO"]
local method = h["REQUEST_METHOD"]
local logged = false
local prefix = "PathMapper: %s %s%s: %s"
if script_name == "" then
script_name = path_info
path_info = ""
elseif path_info ~= "" then
path_info = " (PATH_INFO:"..path_info..")"
end
prefix = prefix:format(method, script_name, path_info, status)
utils.stderr_prefixed_lines(prefix, message)
end
local function wsapi_silent_logger(env, status, message)
if status == 500 then
return wsapi_logger(env, status, message)
end
end
local function wsapi_traceback(env, logger, e)
logger(env, 500, e)
logger(env, 500, debug.traceback())
logger(env, 500, "-- END TRACEBACK --")
return e
end
--
--
local M = object.Class{
compile = urltemplate.URLTemplateCompiler
}
function M:__call(wsapi_env)
local h = self:find_handler(wsapi_env)
if h == nil then
self.logger(wsapi_env, 404, "Handler not found")
return 404
else
local handler = function() return h(wsapi_env) end
local traceback = function(e) return wsapi_traceback(wsapi_env, self.logger, e) end
local success, status, headers, iter = xpcall(handler, traceback)
if success then
self.logger(wsapi_env, status)
return status, headers, iter
else
-- already logged by traceback
return 500
end
end
end
function M:find_handler(env)
local script_name = env.headers["SCRIPT_NAME"] or ""
local path_info = env.headers["PATH_INFO"] or ""
for _, t in ipairs(self.patterns) do
local regex, h, kw = unpack(t)
local c, p = regex:match(path_info)
if p then
local matched_path_info = path_info:sub(1, p-1)
local extra_path_info = path_info:sub(p)
if #extra_path_info == 0 or
(#extra_path_info > 0 and extra_path_info:sub(1,1) == "/") then
-- good match
local routing_args = env.headers["sancus.routing_args"] or {}
-- import captures
for k,v in pairs(c) do
routing_args[k] = v
end
-- and import extra add() args
if kw then
for k,v in pairs(kw) do
routing_args[k] = v
end
end
env.headers["sancus.routing_args"] = routing_args
env.headers["SCRIPT_NAME"] = script_name .. matched_path_info
env.headers["PATH_INFO"] = extra_path_info
return h
end
end
end
end
function M:add(expr, h, kw)
local p = assert(self.compile(expr))
self.patterns[#self.patterns + 1] = {p, h, kw}
end
return {
PathMapper = function (o)
o = M(o)
o.patterns = o.patterns or {}
if o.logger == false then
o.logger = wsapi_silent_logger
elseif o.logger == true or type(o.logger) ~= "function" then
o.logger = wsapi_logger
end
return o
end
}
|
sancus.web.dispatcher: clean wsapi_logger() by using utils.stderr_prefixed_lines()
|
sancus.web.dispatcher: clean wsapi_logger() by using utils.stderr_prefixed_lines()
|
Lua
|
bsd-2-clause
|
sancus-project/sancus-lua-web
|
656bf612346c79d0f15be1762de2bc264d80e0d5
|
loot.lua
|
loot.lua
|
local mod = EPGP:NewModule("loot", "AceEvent-3.0", "AceTimer-3.0")
local L = LibStub("AceLocale-3.0"):GetLocale("EPGP")
local pattern_cache = {}
local function deformat(str, format)
local pattern = pattern_cache[format]
if not pattern then
-- print(string.format("Format: %s", format))
-- Escape special characters
pattern = format:gsub("[%^%$%(%)%%%.%[%]%*%+%-%?]",
function(c) return "%"..c end)
-- print(string.format("Escaped pattern: %s", pattern))
-- Substitute formatting elements with captures (only s and d
-- supported now). Obviously now a formatting element will look
-- like %%s because we escaped the %.
pattern = pattern:gsub("%%%%([sd])", {
["s"] = "(.-)",
["d"] = "(%d+)",
})
--print(string.format("Final pattern: %s", pattern))
pattern_cache[format] = pattern
end
return str:match(pattern)
end
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
[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 loot_queue = {}
local timer
local function IsRLorML()
if UnitInRaid("player") then
local loot_method, ml_party_id, ml_raid_id = GetLootMethod()
if loot_method == "master" and ml_party_id == 0 then return true end
if loot_method ~= "master" and IsRaidLeader() then return true end
end
return false
end
local function ParseLootMessage(msg)
local player = UnitName("player")
local item, quantity = deformat(msg, LOOT_ITEM_SELF_MULTIPLE)
if item and quantity then
return player, item, tonumber(quantity)
end
quantity = 1
item = deformat(msg, LOOT_ITEM_SELF)
if item then
return player, item, tonumber(quantity)
end
player, item, quantity = deformat(msg, LOOT_ITEM_MULTIPLE)
if player and item and quantity then
return player, item, tonumber(quantity)
end
quantity = 1
player, item = deformat(msg, LOOT_ITEM)
return player, item, tonumber(quantity)
end
function mod:CHAT_MSG_LOOT(event_type, msg)
if not EPGP.db.profile.auto_loot or not IsRLorML() then return end
local player, item, quantity = ParseLootMessage(msg)
if not player or not item then return end
local item_name, item_link, item_rarity = GetItemInfo(item)
if item_rarity < EPGP.db.profile.auto_loot_threshold then return end
local item_id = select(3, item_link:find("item:(%d+):"))
if not item_id then return end
item_id = tonumber(item_id:trim())
if not item_id then return end
if ignored_items[item_id] then return end
self:SendMessage("LootReceived", player, item_link, quantity)
end
function mod:PopLootQueue()
if in_combat then return end
if #loot_queue == 0 then
if timer then
self:CancelTimer(timer, true)
timer = nil
end
return
end
local player, itemLink = unpack(loot_queue[1])
-- In theory this should never happen.
if not player or not itemLink then
tremove(loot_queue, 1)
return
end
-- User is busy with other popup.
if StaticPopup_Visible("EPGP_CONFIRM_GP_CREDIT") then
return
end
tremove(loot_queue, 1)
local itemName, itemLink, itemRarity, _, _, _, _, _, _, itemTexture = GetItemInfo(itemLink)
local r, g, b = GetItemQualityColor(itemRarity)
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
local function LootReceived(event_name, player, itemLink, quantity)
if CanEditOfficerNote() then
tinsert(loot_queue, {player, itemLink, quantity})
if not timer then
timer = mod:ScheduleRepeatingTimer("PopLootQueue", 1)
end
end
end
function mod:PLAYER_REGEN_DISABLED()
in_combat = true
end
function mod:PLAYER_REGEN_ENABLED()
in_combat = false
end
function mod:Debug()
LootReceived("LootReceived", UnitName("player"), "\124cffa335ee|Hitem:39235:0:0:0:0:0:0:531162426:8\124h[Bone-Framed Bracers]\124h\124r")
end
function mod:OnEnable()
self:RegisterEvent("CHAT_MSG_LOOT")
self:RegisterEvent("PLAYER_REGEN_DISABLED")
self:RegisterEvent("PLAYER_REGEN_ENABLED")
self:RegisterMessage("LootReceived", LootReceived)
end
|
local mod = EPGP:NewModule("loot", "AceEvent-3.0", "AceTimer-3.0")
local L = LibStub("AceLocale-3.0"):GetLocale("EPGP")
local pattern_cache = {}
local function deformat(str, format)
local pattern = pattern_cache[format]
if not pattern then
-- print(string.format("Format: %s", format))
-- Escape special characters
pattern = format:gsub("[%^%$%(%)%%%.%[%]%*%+%-%?]",
function(c) return "%"..c end)
-- print(string.format("Escaped pattern: %s", pattern))
-- Substitute formatting elements with captures (only s and d
-- supported now). Obviously now a formatting element will look
-- like %%s because we escaped the %.
pattern = pattern:gsub("%%%%([sd])", {
["s"] = "(.-)",
["d"] = "(%d+)",
})
--print(string.format("Final pattern: %s", pattern))
pattern_cache[format] = pattern
end
return str:match(pattern)
end
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
[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 loot_queue = {}
local timer
local function IsRLorML()
if UnitInRaid("player") then
local loot_method, ml_party_id, ml_raid_id = GetLootMethod()
if loot_method == "master" and ml_party_id == 0 then return true end
if loot_method ~= "master" and IsRaidLeader() then return true end
end
return false
end
local function ParseLootMessage(msg)
local player = UnitName("player")
local item, quantity = deformat(msg, LOOT_ITEM_SELF_MULTIPLE)
if item and quantity then
return player, item, tonumber(quantity)
end
quantity = 1
item = deformat(msg, LOOT_ITEM_SELF)
if item then
return player, item, tonumber(quantity)
end
player, item, quantity = deformat(msg, LOOT_ITEM_MULTIPLE)
if player and item and quantity then
return player, item, tonumber(quantity)
end
quantity = 1
player, item = deformat(msg, LOOT_ITEM)
return player, item, tonumber(quantity)
end
function mod:CHAT_MSG_LOOT(event_type, msg)
if not IsRLorML() then return end
local player, item, quantity = ParseLootMessage(msg)
if not player or not item then return end
local item_name, item_link, item_rarity = GetItemInfo(item)
if item_rarity < EPGP.db.profile.auto_loot_threshold then return end
local item_id = select(3, item_link:find("item:(%d+):"))
if not item_id then return end
item_id = tonumber(item_id:trim())
if not item_id then return end
if ignored_items[item_id] then return end
self:SendMessage("LootReceived", player, item_link, quantity)
end
function mod:PopLootQueue()
if in_combat then return end
if #loot_queue == 0 then
if timer then
self:CancelTimer(timer, true)
timer = nil
end
return
end
local player, itemLink = unpack(loot_queue[1])
-- In theory this should never happen.
if not player or not itemLink then
tremove(loot_queue, 1)
return
end
-- User is busy with other popup.
if StaticPopup_Visible("EPGP_CONFIRM_GP_CREDIT") then
return
end
tremove(loot_queue, 1)
local itemName, itemLink, itemRarity, _, _, _, _, _, _, itemTexture = GetItemInfo(itemLink)
local r, g, b = GetItemQualityColor(itemRarity)
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
local function LootReceived(event_name, player, itemLink, quantity)
if CanEditOfficerNote() then
tinsert(loot_queue, {player, itemLink, quantity})
if not timer then
timer = mod:ScheduleRepeatingTimer("PopLootQueue", 1)
end
end
end
function mod:PLAYER_REGEN_DISABLED()
in_combat = true
end
function mod:PLAYER_REGEN_ENABLED()
in_combat = false
end
function mod:Debug()
LootReceived("LootReceived", UnitName("player"), "\124cffa335ee|Hitem:39235:0:0:0:0:0:0:531162426:8\124h[Bone-Framed Bracers]\124h\124r")
end
function mod:OnEnable()
self:RegisterEvent("CHAT_MSG_LOOT")
self:RegisterEvent("PLAYER_REGEN_DISABLED")
self:RegisterEvent("PLAYER_REGEN_ENABLED")
self:RegisterMessage("LootReceived", LootReceived)
end
|
Do not check non-existing variables to ignore loot events. This fixes issue 326.
|
Do not check non-existing variables to ignore loot events. This fixes issue 326.
|
Lua
|
bsd-3-clause
|
hayword/tfatf_epgp,hayword/tfatf_epgp,ceason/epgp-tfatf,sheldon/epgp,protomech/epgp-dkp-reloaded,ceason/epgp-tfatf,sheldon/epgp,protomech/epgp-dkp-reloaded
|
0fc705c1ccd5cbea6256238bc613eaa97afbf4b9
|
src/nodes/baseball.lua
|
src/nodes/baseball.lua
|
local anim8 = require 'vendor/anim8'
local Helper = require 'helper'
local Baseball = {}
Baseball.__index = Baseball
Baseball.baseball = true
local BaseballImage = love.graphics.newImage('images/baseball.png')
local g = anim8.newGrid(9, 9, BaseballImage:getWidth(), BaseballImage:getHeight())
local game = {}
game.step = 10000
game.friction = 0.0146875 * game.step
game.accel = 0.046875 * game.step
game.deccel = 0.5 * game.step
game.gravity = 0.21875 * game.step
game.airaccel = 0.09375 * game.step
game.airdrag = 0.96875 * game.step
game.max_x = 300
game.max_y= 600
function Baseball.new(node, collider)
local baseball = {}
setmetatable(baseball, Baseball)
baseball.image = BaseballImage
baseball.foreground = node.properties.foreground
baseball.bb = collider:addRectangle(node.x, node.y, node.width, node.height)
baseball.bb.node = baseball
baseball.collider = collider
baseball.spinning = anim8.newAnimation('loop', g('1-2,1'), .10)
baseball.position = { x = node.x, y = node.y }
baseball.velocity = { x = -230, y = -200 }
baseball.floor = node.layer.map.objectLayers.floor.objects[1].y - node.height
baseball.thrown = true
baseball.held = false
baseball.rebounded = false
baseball.width = node.width
baseball.height = node.height
return baseball
end
function Baseball:draw()
if self.thrown then
self.spinning:draw(BaseballImage, self.position.x, self.position.y)
else
love.graphics.drawq(self.image, love.graphics.newQuad( 0, 0, 9, 9, 18, 9 ), self.position.x, self.position.y)
end
end
function Baseball:collide(node, dt, mtv_x, mtv_y)
if node and node.character then
node:registerHoldable(self)
end
end
function Baseball:collide_end(node, dt)
if node and node.character then
node:cancelHoldable(self)
end
end
function Baseball:update(dt, player)
if self.held then
self.position.x = math.floor(player.position.x) + (self.width / 2) + 15
self.position.y = math.floor(player.position.y) + player.hand_offset - self.height + 2
self:moveBoundingBox()
end
if not self.thrown then
return
end
self.spinning:update(dt)
if self.velocity.x < 0 then
self.velocity.x = math.min(self.velocity.x + game.friction * dt, 0)
else
self.velocity.x = math.max(self.velocity.x - game.friction * dt, 0)
end
self.velocity.y = self.velocity.y + game.gravity * dt
if self.velocity.y > game.max_y then
self.velocity.y = game.max_y
end
self.position.x = self.position.x + self.velocity.x * dt
self.position.y = self.position.y + self.velocity.y * dt
self:moveBoundingBox()
if self.position.x < 0 then
self.rebounded = false
self.velocity.x = -self.velocity.x
end
if self.position.x > 450 then
self.rebounded = false
self.velocity.x = -self.velocity.x
end
current_y_velocity = self.velocity.y
if self.thrown and self.position.y > self.floor then
self.rebounded = false
if current_y_velocity < 5 then
--stop bounce
self.velocity.y = 0
self.position.y = self.floor
self.thrown = false
else
--bounce
self.velocity.y = -1 * math.abs( current_y_velocity )
end
end
end
function Baseball:moveBoundingBox()
Helper.moveBoundingBox(self)
end
function Baseball:keypressed(key, player)
if (key == "rshift" or key == "lshift") and player.holdable == self then
if player.holding == nil then
player.walk_state = 'holdwalk'
player.gaze_state = 'holdwalk'
player.crouch_state = 'holdwalk'
player.holding = true
self.held = true
self.thrown = false
self.velocity.y = 0
self.velocity.x = 0
else
player.holding = nil
player.walk_state = 'walk'
player.crouch_state = 'crouch'
player.gaze_state = 'gaze'
self.held = false
self.thrown = true
self.velocity.x = ( ( ( player.direction == "left" ) and -1 or 1 ) * 500 ) + player.velocity.x
self.velocity.y = -800
end
end
end
---
-- Gets the current acceleration speed
-- @return Number the acceleration to apply
function Baseball:accel()
if self.velocity.y < 0 then
return game.airaccel
else
return game.accel
end
end
---
-- Gets the current deceleration speed
-- @return Number the deceleration to apply
function Baseball:deccel()
if self.velocity.y < 0 then
return game.airaccel
else
return game.deccel
end
end
function Baseball:rebound( x_change, y_change )
if not self.rebounded then
if x_change then
self.velocity.x = -( self.velocity.x / 2 )
end
if y_change then
self.velocity.y = -self.velocity.y
end
self.rebounded = true
end
end
return Baseball
|
local anim8 = require 'vendor/anim8'
local Helper = require 'helper'
local window = require 'window'
local Baseball = {}
Baseball.__index = Baseball
Baseball.baseball = true
local BaseballImage = love.graphics.newImage('images/baseball.png')
local g = anim8.newGrid(9, 9, BaseballImage:getWidth(), BaseballImage:getHeight())
local game = {}
game.step = 10000
game.friction = 0.0146875 * game.step
game.accel = 0.046875 * game.step
game.deccel = 0.5 * game.step
game.gravity = 0.21875 * game.step
game.airaccel = 0.09375 * game.step
game.airdrag = 0.96875 * game.step
game.max_x = 300
game.max_y= 600
function Baseball.new(node, collider)
local baseball = {}
setmetatable(baseball, Baseball)
baseball.image = BaseballImage
baseball.foreground = node.properties.foreground
baseball.bb = collider:addRectangle(node.x, node.y, node.width, node.height)
baseball.bb.node = baseball
baseball.collider = collider
baseball.spinning = anim8.newAnimation('loop', g('1-2,1'), .10)
baseball.position = { x = node.x, y = node.y }
baseball.velocity = { x = -230, y = -200 }
baseball.floor = node.layer.map.objectLayers.floor.objects[1].y - node.height
baseball.thrown = true
baseball.held = false
baseball.rebounded = false
baseball.width = node.width
baseball.height = node.height
return baseball
end
function Baseball:draw()
if self.thrown then
self.spinning:draw(BaseballImage, self.position.x, self.position.y)
else
love.graphics.drawq(self.image, love.graphics.newQuad( 0, 0, 9, 9, 18, 9 ), self.position.x, self.position.y)
end
end
function Baseball:collide(node, dt, mtv_x, mtv_y)
if node and node.character then
node:registerHoldable(self)
end
end
function Baseball:collide_end(node, dt)
if node and node.character then
node:cancelHoldable(self)
end
end
function Baseball:update(dt, player)
if self.held then
self.position.x = math.floor(player.position.x) + (self.width / 2) + 15
self.position.y = math.floor(player.position.y) + player.hand_offset - self.height + 2
self:moveBoundingBox()
end
if self.thrown then
self.spinning:update(dt)
if self.velocity.x < 0 then
self.velocity.x = math.min(self.velocity.x + game.friction * dt, 0)
else
self.velocity.x = math.max(self.velocity.x - game.friction * dt, 0)
end
self.velocity.y = self.velocity.y + game.gravity * dt
if self.velocity.y > game.max_y then
self.velocity.y = game.max_y
end
self.position.x = self.position.x + self.velocity.x * dt
self.position.y = self.position.y + self.velocity.y * dt
if self.position.x < 0 then
self.position.x = 0
self.rebounded = false
self.velocity.x = -self.velocity.x
end
if self.position.x + self.width > window.width then
self.position.x = window.width - self.width
self.rebounded = false
self.velocity.x = -self.velocity.x
end
current_y_velocity = self.velocity.y
if self.thrown and self.position.y > self.floor then
self.rebounded = false
if current_y_velocity < 5 then
--stop bounce
self.velocity.y = 0
self.position.y = self.floor
self.thrown = false
else
--bounce
self.velocity.y = -1 * math.abs( current_y_velocity )
end
end
end
self:moveBoundingBox()
end
function Baseball:moveBoundingBox()
Helper.moveBoundingBox(self)
end
function Baseball:keypressed(key, player)
if (key == "rshift" or key == "lshift") then
if player.holdable == self then
if player.holding == nil then
player.walk_state = 'holdwalk'
player.gaze_state = 'holdwalk'
player.crouch_state = 'holdwalk'
player.holding = true
self.held = true
self.thrown = false
self.velocity.y = 0
self.velocity.x = 0
else
player.holding = nil
player.walk_state = 'walk'
player.crouch_state = 'crouch'
player.gaze_state = 'gaze'
self.held = false
self.thrown = true
self.velocity.x = ( ( ( player.direction == "left" ) and -1 or 1 ) * 500 ) + player.velocity.x
self.velocity.y = -800
end
end
end
end
---
-- Gets the current acceleration speed
-- @return Number the acceleration to apply
function Baseball:accel()
if self.velocity.y < 0 then
return game.airaccel
else
return game.accel
end
end
---
-- Gets the current deceleration speed
-- @return Number the deceleration to apply
function Baseball:deccel()
if self.velocity.y < 0 then
return game.airaccel
else
return game.deccel
end
end
function Baseball:rebound( x_change, y_change )
if not self.rebounded then
if x_change then
self.velocity.x = -( self.velocity.x / 2 )
end
if y_change then
self.velocity.y = -self.velocity.y
end
self.rebounded = true
end
end
return Baseball
|
Bugfixes for baseball
|
Bugfixes for baseball
|
Lua
|
mit
|
hawkthorne/hawkthorne-server-lua,hawkthorne/hawkthorne-client-lua,hawkthorne/hawkthorne-server-lua,hawkthorne/hawkthorne-client-lua
|
2db471328e60378ae602cd745ec76697c13900f0
|
onmt/modules/WordEmbedding.lua
|
onmt/modules/WordEmbedding.lua
|
--[[ nn unit. Maps from word ids to embeddings. Slim wrapper around
nn.LookupTable to allow fixed and pretrained embeddings.
--]]
local WordEmbedding, parent = torch.class('onmt.WordEmbedding', 'onmt.Network')
--[[
Parameters:
* `vocabSize` - size of the vocabulary
* `vecSize` - size of the embedding
* `preTrainined` - path to a pretrained vector file
* `fix` - keep the weights of the embeddings fixed.
--]]
function WordEmbedding:__init(vocabSize, vecSize, preTrained, fix)
self.vocabSize = vocabSize
parent.__init(self, nn.LookupTable(vocabSize, vecSize, onmt.Constants.PAD))
-- If embeddings are given. Initialize them.
if preTrained and preTrained:len() > 0 then
local vecs = torch.load(preTrained)
self.net.weight:copy(vecs)
end
self.fix = fix
if self.fix then
self.net.gradWeight = nil
end
end
function WordEmbedding:postParametersInitialization()
self.net.weight[onmt.Constants.PAD]:zero()
end
function WordEmbedding:accGradParameters(input, gradOutput, scale)
if not self.fix then
self.net:accGradParameters(input, gradOutput, scale)
self.net.gradWeight[onmt.Constants.PAD]:zero()
end
end
function WordEmbedding:parameters()
if not self.fix then
return parent.parameters(self)
end
end
|
--[[ nn unit. Maps from word ids to embeddings. Slim wrapper around
nn.LookupTable to allow fixed and pretrained embeddings.
--]]
local WordEmbedding, parent = torch.class('onmt.WordEmbedding', 'onmt.Network')
--[[
Parameters:
* `vocabSize` - size of the vocabulary
* `vecSize` - size of the embedding
* `preTrainined` - path to a pretrained vector file
* `fix` - keep the weights of the embeddings fixed.
--]]
function WordEmbedding:__init(vocabSize, vecSize, preTrained, fix)
self.vocabSize = vocabSize
parent.__init(self, nn.LookupTable(vocabSize, vecSize, onmt.Constants.PAD))
-- If embeddings are given. Initialize them.
if preTrained and preTrained:len() > 0 then
local vecs = torch.load(preTrained)
self.net.weight:copy(vecs)
end
self.fix = fix
if self.fix then
self.net.gradWeight = nil
end
end
function WordEmbedding:postParametersInitialization()
self.net.weight[onmt.Constants.PAD]:zero()
end
function WordEmbedding:accGradParameters(input, gradOutput, scale)
if self.net.gradWeight then
self.net:accGradParameters(input, gradOutput, scale)
self.net.gradWeight[onmt.Constants.PAD]:zero()
end
end
function WordEmbedding:parameters()
if self.net.gradWeight then
return parent.parameters(self)
end
end
|
Fix fixed word embeddings condition
|
Fix fixed word embeddings condition
|
Lua
|
mit
|
da03/OpenNMT,jungikim/OpenNMT,monsieurzhang/OpenNMT,jsenellart-systran/OpenNMT,da03/OpenNMT,OpenNMT/OpenNMT,monsieurzhang/OpenNMT,OpenNMT/OpenNMT,jsenellart-systran/OpenNMT,jungikim/OpenNMT,jsenellart/OpenNMT,da03/OpenNMT,jsenellart/OpenNMT,jungikim/OpenNMT,monsieurzhang/OpenNMT,jsenellart/OpenNMT,jsenellart-systran/OpenNMT,OpenNMT/OpenNMT
|
5279b8b4622cc2fe87b1596b879c04f79b3161bc
|
zpm.lua
|
zpm.lua
|
local zefiros = require( "Zefiros-Software/Zefiros-Defaults", "@head" )
function useCore()
zpm.uses {
"Zefiros-Software/MathLib",
"Zefiros-Software/Boost",
"Zefiros-Software/Date",
"Zefiros-Software/Fmt"
}
end
workspace "CoreLib"
flags "C++14"
pic "On"
filter "system:linux"
links {
"pthread",
"dl"
}
filter {}
zefiros.setDefaults( "core" )
--DEBUG
filter "system:macosx"
buildoptions{"-fsanitize=address", "-fsanitize-memory-track-origins", "-fno-omit-frame-pointer", "-fsanitize-memory-use-after-dtor ", "-fno-optimize-sibling-calls", "-g", "-O1"}
project "core"
useCore()
project "core-test"
useCore()
zpm.uses {
"Zefiros-Software/GoogleTest",
}
links {
"core",
"core-plugin-test4"
}
includedirs {
"plugin/test4/include/"
}
group( "Plugins/" )
project "core-plugin-test"
targetname "Test"
kind "SharedLib"
targetsuffix ""
links "core"
useCore()
zpm.uses {
"Zefiros-Software/GoogleTest",
}
includedirs {
"core/include/"
}
files {
"plugin/include/**.hpp",
"plugin/include/**.h",
"plugin/test/src/**.cpp"
}
filter "platforms:x86"
targetdir "bin/x86/plugins/"
filter "platforms:x86_64"
targetdir "bin/x86_64/plugins/"
filter {}
group( "Plugins/Test2" )
project "core-plugin-test2"
targetname "Test2"
kind "SharedLib"
targetsuffix ""
links {
"core",
"core-plugin-test2-lib"
}
useCore()
includedirs {
"core/include/",
"plugin/test2/include/"
}
files {
"plugin/test2/src/plugin.cpp"
}
filter "platforms:x86"
targetdir "bin/x86/plugins/"
filter "platforms:x86_64"
targetdir "bin/x86_64/plugins/"
filter {}
project "core-plugin-test2-lib"
targetname "Test2"
kind "StaticLib"
links "core"
useCore()
includedirs {
"core/include/",
"plugin/test2/include/"
}
files {
"plugin/include/**.hpp",
"plugin/include/**.h",
"plugin/test2/src/test2.cpp"
}
group( "Plugins/Test3" )
project "core-plugin-test3"
targetname "Test3"
kind "SharedLib"
targetsuffix ""
links {
"core",
"core-plugin-test3-lib",
"core-plugin-test2-lib"
}
useCore()
includedirs {
"core/include/",
"plugin/test3/include/",
"plugin/test2/include/"
}
files {
"plugin/test3/src/plugin.cpp"
}
filter "platforms:x86"
targetdir "bin/x86/plugins/"
filter "platforms:x86_64"
targetdir "bin/x86_64/plugins/"
filter {}
project "core-plugin-test3-lib"
targetname "Test3"
kind "StaticLib"
links {
"core",
"core-plugin-test2-lib"
}
useCore()
includedirs {
"core/include/",
"plugin/test3/include/",
"plugin/test2/include/"
}
files {
"plugin/include/**.hpp",
"plugin/include/**.h",
"plugin/test3/src/test3.cpp"
}
group( "Plugins/Test4" )
project "core-plugin-test4"
targetname "Test4"
kind "StaticLib"
links "core"
useCore()
includedirs {
"core/include/",
"plugin/test4/include/"
}
files {
"plugin/include/**.hpp",
"plugin/include/**.h",
"plugin/test4/src/**.cpp"
}
|
local zefiros = require( "Zefiros-Software/Zefiros-Defaults", "@head" )
function useCore()
zpm.uses {
"Zefiros-Software/MathLib",
"Zefiros-Software/Boost",
"Zefiros-Software/Date",
"Zefiros-Software/Fmt"
}
end
workspace "CoreLib"
flags "C++14"
pic "On"
filter "system:linux"
links {
"pthread",
"dl"
}
filter {}
zefiros.setDefaults( "core" )
--DEBUG
filter "system:macosx"
buildoptions{"-fsanitize=address", "-fsanitize-memory-track-origins", "-fno-omit-frame-pointer", "-fsanitize-memory-use-after-dtor ", "-fno-optimize-sibling-calls", "-g", "-O1"}
linkoptions{"-fsanitize=address", "-fsanitize-memory-track-origins", "-fno-omit-frame-pointer", "-fsanitize-memory-use-after-dtor ", "-fno-optimize-sibling-calls", "-g", "-O1"}
project "core"
useCore()
project "core-test"
useCore()
zpm.uses {
"Zefiros-Software/GoogleTest",
}
links {
"core",
"core-plugin-test4"
}
includedirs {
"plugin/test4/include/"
}
group( "Plugins/" )
project "core-plugin-test"
targetname "Test"
kind "SharedLib"
targetsuffix ""
links "core"
useCore()
zpm.uses {
"Zefiros-Software/GoogleTest",
}
includedirs {
"core/include/"
}
files {
"plugin/include/**.hpp",
"plugin/include/**.h",
"plugin/test/src/**.cpp"
}
filter "platforms:x86"
targetdir "bin/x86/plugins/"
filter "platforms:x86_64"
targetdir "bin/x86_64/plugins/"
filter {}
group( "Plugins/Test2" )
project "core-plugin-test2"
targetname "Test2"
kind "SharedLib"
targetsuffix ""
links {
"core",
"core-plugin-test2-lib"
}
useCore()
includedirs {
"core/include/",
"plugin/test2/include/"
}
files {
"plugin/test2/src/plugin.cpp"
}
filter "platforms:x86"
targetdir "bin/x86/plugins/"
filter "platforms:x86_64"
targetdir "bin/x86_64/plugins/"
filter {}
project "core-plugin-test2-lib"
targetname "Test2"
kind "StaticLib"
links "core"
useCore()
includedirs {
"core/include/",
"plugin/test2/include/"
}
files {
"plugin/include/**.hpp",
"plugin/include/**.h",
"plugin/test2/src/test2.cpp"
}
group( "Plugins/Test3" )
project "core-plugin-test3"
targetname "Test3"
kind "SharedLib"
targetsuffix ""
links {
"core",
"core-plugin-test3-lib",
"core-plugin-test2-lib"
}
useCore()
includedirs {
"core/include/",
"plugin/test3/include/",
"plugin/test2/include/"
}
files {
"plugin/test3/src/plugin.cpp"
}
filter "platforms:x86"
targetdir "bin/x86/plugins/"
filter "platforms:x86_64"
targetdir "bin/x86_64/plugins/"
filter {}
project "core-plugin-test3-lib"
targetname "Test3"
kind "StaticLib"
links {
"core",
"core-plugin-test2-lib"
}
useCore()
includedirs {
"core/include/",
"plugin/test3/include/",
"plugin/test2/include/"
}
files {
"plugin/include/**.hpp",
"plugin/include/**.h",
"plugin/test3/src/test3.cpp"
}
group( "Plugins/Test4" )
project "core-plugin-test4"
targetname "Test4"
kind "StaticLib"
links "core"
useCore()
includedirs {
"core/include/",
"plugin/test4/include/"
}
files {
"plugin/include/**.hpp",
"plugin/include/**.h",
"plugin/test4/src/**.cpp"
}
|
fixed link options of the debug build
|
fixed link options of the debug build
|
Lua
|
mit
|
Zefiros-Software/CoreLib,Zefiros-Software/CoreLib
|
bef58703aaedf24f1e1e7b5a9b0343b0d2dbaf49
|
kong/plugins/mashape-analytics/handler.lua
|
kong/plugins/mashape-analytics/handler.lua
|
-- Analytics plugin handler.
--
-- How it works:
-- Keep track of calls made to configured APIs on a per-worker basis, using the ALF format
-- (alf_serializer.lua) and per-API buffers. `:access()` and `:body_filter()` are implemented to record some properties
-- required for the ALF entry.
--
-- When an API buffer is full (it reaches the `batch_size` configuration value or the maximum payload size), send the batch to the server.
--
-- In order to keep Analytics as real-time as possible, we also start a 'delayed timer' running in background.
-- If no requests are made during a certain period of time (the `delay` configuration value), the
-- delayed timer will fire and send the batch + flush the data, not waiting for the buffer to be full.
--
-- @see alf_serializer.lua
-- @see buffer.lua
local ALFBuffer = require "kong.plugins.mashape-analytics.buffer"
local BasePlugin = require "kong.plugins.base_plugin"
local ALFSerializer = require "kong.plugins.log-serializers.alf"
local ngx_now = ngx.now
local ngx_log = ngx.log
local ngx_log_ERR = ngx.ERR
local ALF_BUFFERS = {} -- buffers per-api
local AnalyticsHandler = BasePlugin:extend()
function AnalyticsHandler:new()
AnalyticsHandler.super.new(self, "mashape-analytics")
end
function AnalyticsHandler:access(conf)
AnalyticsHandler.super.access(self)
-- Retrieve and keep in memory the bodies for this request
ngx.ctx.analytics = {
req_body = "",
res_body = "",
req_post_args = {}
}
ngx.req.read_body()
local status, res = pcall(ngx.req.get_post_args)
if not status then
if res == "requesty body in temp file not supported" then
ngx_log(ngx_log_ERR, "[mashape-analytics] cannot read request body from temporary file. Try increasing the client_body_buffer_size directive.")
else
ngx_log(ngx_log_ERR, res)
end
else
ngx.ctx.analytics.req_post_args = res
end
if conf.log_body then
ngx.ctx.analytics.req_body = ngx.req.get_body_data()
end
end
function AnalyticsHandler:body_filter(conf)
AnalyticsHandler.super.body_filter(self)
local chunk, eof = ngx.arg[1], ngx.arg[2]
-- concatenate response chunks for ALF's `response.content.text`
if conf.log_body then
ngx.ctx.analytics.res_body = ngx.ctx.analytics.res_body..chunk
end
if eof then -- latest chunk
ngx.ctx.analytics.response_received = ngx_now() * 1000
end
end
function AnalyticsHandler:log(conf)
AnalyticsHandler.super.log(self)
local api_id = ngx.ctx.api.id
-- Create the ALF buffer if not existing for this API
if not ALF_BUFFERS[api_id] then
ALF_BUFFERS[api_id] = ALFBuffer.new(conf)
end
local buffer = ALF_BUFFERS[api_id]
-- Creating the ALF
local alf = ALFSerializer.new_alf(ngx, conf.service_token, conf.environment)
if alf then
-- Simply adding the ALF to the buffer, it will decide if it is necessary to flush itself
buffer:add_alf(alf)
end
end
return AnalyticsHandler
|
-- Analytics plugin handler.
--
-- How it works:
-- Keep track of calls made to configured APIs on a per-worker basis, using the ALF format
-- (alf_serializer.lua) and per-API buffers. `:access()` and `:body_filter()` are implemented to record some properties
-- required for the ALF entry.
--
-- When an API buffer is full (it reaches the `batch_size` configuration value or the maximum payload size), send the batch to the server.
--
-- In order to keep Analytics as real-time as possible, we also start a 'delayed timer' running in background.
-- If no requests are made during a certain period of time (the `delay` configuration value), the
-- delayed timer will fire and send the batch + flush the data, not waiting for the buffer to be full.
--
-- @see alf_serializer.lua
-- @see buffer.lua
local ALFBuffer = require "kong.plugins.mashape-analytics.buffer"
local BasePlugin = require "kong.plugins.base_plugin"
local ALFSerializer = require "kong.plugins.log-serializers.alf"
local ngx_now = ngx.now
local ngx_log = ngx.log
local ngx_log_ERR = ngx.ERR
local string_find = string.find
local pcall = pcall
local ALF_BUFFERS = {} -- buffers per-api
local AnalyticsHandler = BasePlugin:extend()
function AnalyticsHandler:new()
AnalyticsHandler.super.new(self, "mashape-analytics")
end
function AnalyticsHandler:access(conf)
AnalyticsHandler.super.access(self)
local req_body = ""
local res_body = ""
local req_post_args = {}
if conf.log_body then
ngx.req.read_body()
req_body = ngx.req.get_body_data()
local headers = ngx.req.get_headers()
local content_type = headers["content-type"]
if content_type and string_find(content_type:lower(), "application/x-www-form-urlencoded", nil, true) then
local status, res = pcall(ngx.req.get_post_args)
if not status then
if res == "requesty body in temp file not supported" then
ngx_log(ngx_log_ERR, "[mashape-analytics] cannot read request body from temporary file. Try increasing the client_body_buffer_size directive.")
else
ngx_log(ngx_log_ERR, res)
end
else
req_post_args = res
end
end
end
-- keep in memory the bodies for this request
ngx.ctx.analytics = {
req_body = req_body,
res_body = res_body,
req_post_args = req_post_args
}
end
function AnalyticsHandler:body_filter(conf)
AnalyticsHandler.super.body_filter(self)
local chunk, eof = ngx.arg[1], ngx.arg[2]
-- concatenate response chunks for ALF's `response.content.text`
if conf.log_body then
ngx.ctx.analytics.res_body = ngx.ctx.analytics.res_body..chunk
end
if eof then -- latest chunk
ngx.ctx.analytics.response_received = ngx_now() * 1000
end
end
function AnalyticsHandler:log(conf)
AnalyticsHandler.super.log(self)
local api_id = ngx.ctx.api.id
-- Create the ALF buffer if not existing for this API
if not ALF_BUFFERS[api_id] then
ALF_BUFFERS[api_id] = ALFBuffer.new(conf)
end
local buffer = ALF_BUFFERS[api_id]
-- Creating the ALF
local alf = ALFSerializer.new_alf(ngx, conf.service_token, conf.environment)
if alf then
-- Simply adding the ALF to the buffer, it will decide if it is necessary to flush itself
buffer:add_alf(alf)
end
end
return AnalyticsHandler
|
hotfix(alf_serializer) do not include JSON body in params
|
hotfix(alf_serializer) do not include JSON body in params
JSON bodies need to be present in the text field but not included in
`postData.params`.
This also avoids reading the request body if not configured so in the
plugin.
Sadly there is no unit test for this part of the ALF serializer.
Fix #762
|
Lua
|
apache-2.0
|
shiprabehera/kong,icyxp/kong,Mashape/kong,Kong/kong,li-wl/kong,ajayk/kong,akh00/kong,Kong/kong,jerizm/kong,salazar/kong,xvaara/kong,beauli/kong,Vermeille/kong,smanolache/kong,jebenexer/kong,ccyphers/kong,Kong/kong
|
a0e60fb86af953a15b7022f53f3d9ccbf7427cc7
|
nonsence/deque.lua
|
nonsence/deque.lua
|
--[[ Double ended queue for Lua
Copyright John Abrahamsen 2011, 2012, 2013 < [email protected] >
"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." ]]
require('middleclass')
local log = require "log"
local ffi = require "ffi"
--[[ Double ended queue class. ]]
local deque = class('Deque')
function deque:init()
self.head = nil
self.tail = nil
end
--[[ Append elements to tail. ]]
function deque:append(item)
if (not self.tail) then
self.tail = {next = nil, prev = nil, value = item}
self.head = self.tail
else
local old_tail = self.tail
local new_tail = {next = nil, prev = old_tail, value = item}
old_tail.next = new_tail
self.tail = new_tail
end
end
--[[ Append element to head. ]]
function deque:appendleft(item)
if (not self.head) then
self.head = {next = nil, value = item}
self.tail = self.tail
else
local new_head = {next = self.head, prev = nil, value = item}
self.head = new_head
end
end
--[[ Removes element at tail and returns it. ]]
function deque:pop()
if (not self.tail) then
return nil
end
local value = self.tail.value
local new_tail = self.tail.prev
if not new_tail then
self.tail = nil
self.head = nil
else
self.tail = new_tail
new_tail.next = nil
end
return value
end
--[[ Removes element at head and returns it. ]]
function deque:popleft()
if (not self.head) then
return nil
end
local value = self.head.value
local new_head = self.head.next
if (not new_head) then
self.head = nil
self.tail = nil
else
new_head.prev = nil
self.head = new_head
end
return value
end
function deque:size()
if (self.head == nil) then
return 0
end
local l = self.head
local i = 0
while (l) do
i = i + 1
l = l.next
end
return i
end
--[[ Find length of all elements in deque combined. Slow.]]
function deque:strlen()
local l = self.head
if (not l) then
return 0
else
local sz = 0
while (l) do
sz = l.value:len() + sz
l = l.next
end
return sz
end
end
--[[ Concat all elements in deque. Slow.]]
function deque:concat()
local l = self.head
if (not l) then
return ""
else
local sz = 0
while (l) do
sz = l.value:len() + sz
l = l.next
end
local buf = ffi.new("char[?]", sz)
l = self.head
local i = 0
while (l) do
local len = l.value:len()
ffi.copy(buf + i, l.value, len)
i = i + len
l = l.next
end
return ffi.string(buf, sz) or ""
end
end
function deque:getn(pos)
local l = self.head
if not l then
return nil
end
while pos ~= 0 do
l = l.next
if not l then
return nil
end
pos = pos - 1
end
return l.value
end
--[[ Returns element at tail. ]]
function deque:peeklast() return self.tail.value end
--[[ Returns element at head. ]]
function deque:peekfirst() return self.head.value end
function deque:not_empty()
return self.head ~= nil
end
return deque
|
--[[ Nonsence Async HTTP client example
Copyright 2013 John Abrahamsen
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. ]]
_G.NW_CONSOLE = 1
local nonsence = require "nonsence"
local TwitterFeedHandler = class("TwitterFeed", nonsence.web.RequestHandler)
function TwitterFeedHandler:get(path)
self:set_auto_finish(false)
nonsence.async.HTTPClient:new():fetch("http://search.twitter.com/search.json?q=Twitter&result_type=mixed",
"GET",
function(headers, data)
if headers:get_status_code() == 200 then
local res = nonsence.escape.json_decode(data)
local top_search_result = res.results[1]
local text = top_search_result.text
local pic = top_search_result.profile_image_url
self:write(string.format([[
<h1>Search for Twitter on Twitter gave this tweet:</h1>
<img src="%s">
<p>%s</p>
]], pic, text))
else
error(nonsence.web.HTTPError(500), "Twitter did not respond with 200?!")
end
self:finish()
end, function(err)
-- Could not connect?
error(nonsence.web.HTTPError(500), "Could not load data from Twitter API")
end)
end
local application = nonsence.web.Application:new({
{"(.+)", TwitterFeedHandler}
})
application:listen(8888)
nonsence.ioloop.instance():start()
|
Fixed bug and added size in object.
|
Fixed bug and added size in object.
|
Lua
|
apache-2.0
|
mniestroj/turbo,YuanPeir-Chen/turbo-support-mipsel,zcsteele/turbo,luastoned/turbo,luastoned/turbo,YuanPeir-Chen/turbo-support-mipsel,ddysher/turbo,zcsteele/turbo,ddysher/turbo,kernelsauce/turbo
|
88178c25d759a063db074762732f730dc8addad6
|
xmake.lua
|
xmake.lua
|
set_project("UBWindow")
if is_mode("debug") then
set_symbols("debug")
set_optimize("none")
end
if is_mode("release") then
set_symbols("hidden")
set_optimize("fastest")
set_strip("all")
end
add_includedirs("include")
target("ubwindow")
set_kind("static")
set_targetdir("lib")
add_includedirs("src")
add_files("src/*.c")
if is_plat("macosx") then
add_files("src/*.m")
end
target("demo_blank")
add_deps("ubwindow")
set_kind("binary")
set_targetdir("bin")
add_linkdirs("lib")
add_files("demo/*.c")
add_links("ubwindow")
if is_plat("windows") then
add_links("user32")
end
if is_plat("mingw") then
add_ldflags("-static")
end
if is_plat("linux") then
add_links("X11")
end
if is_plat("macosx") then
add_ldflags("-framework Cocoa")
end
|
set_project("UBWindow")
if is_mode("debug") then
add_defines("DEBUG")
set_symbols("debug")
set_optimize("none")
end
if is_mode("release") then
add_defines("NDEBUG")
set_symbols("hidden")
set_optimize("fastest")
set_strip("all")
end
add_includedirs("include")
target("ubwindow")
set_kind("static")
set_targetdir("lib")
add_includedirs("src")
add_files("src/*.c")
if is_plat("macosx") then
add_files("src/*.m")
end
target("demo_blank")
add_deps("ubwindow")
set_kind("binary")
set_targetdir("bin")
add_linkdirs("lib")
add_files("demo/*.c")
add_links("ubwindow")
if is_plat("windows") then
add_links("user32")
end
if is_plat("mingw") then
add_ldflags("-static")
end
if is_plat("linux") then
add_links("X11")
end
if is_plat("macosx") then
add_ldflags("-framework Cocoa")
end
|
Fixed xmake.lua
|
Fixed xmake.lua
|
Lua
|
mit
|
yulon/pwre
|
e6305ef83d305fe12317939a6b4f6fb2d46a477b
|
exploding-trees_0.0.1/control.lua
|
exploding-trees_0.0.1/control.lua
|
local random = math.random
-- Explosions = { "explosion", "explosion-hit", "ground-explosion", "massive-explosion", "medium-explosion", "nuke-explosion", "crash-site-explosion-smoke"
local exploding_trees = {
["tree-01"] = true,
["tree-02"] = true,
["tree-03"] = true,
["tree-04"] = true,
["tree-05"] = true,
["tree-09"] = true,
["tree-02-red"] = true,
["tree-07"] = true,
["tree-06"] = true,
["tree-06-brown"] = true,
["tree-09-brown"] = true,
["tree-09-red"] = true,
["tree-08"] = true,
["tree-08-brown"] = true,
["tree-08-red"] = true,
["dead-dry-hairy-tree"] = true,
["dead-grey-trunk"] = true,
["dead-tree-desert"] = true,
["dry-hairy-tree"] = true,
["dry-tree"] = true,
["tree-01-stump"] = true,
["tree-02-stump"] = true,
["tree-03-stump"] = true,
["tree-04-stump"] = true,
["tree-05-stump"] = true,
["tree-06-stump"] = true,
["tree-07-stump"] = true,
["tree-08-stump"] = true,
["tree-09-stump"] = true
}
local function get_random_position(box, x_scale, y_scale)
local x_scale = x_scale or 1
local y_scale = y_scale or 1
local x1 = box.left_top.x
local y1 = box.left_top.y
local x2 = box.right_bottom.x
local y2 = box.right_bottom.y
local x = ((x2 - x1) * x_scale * (random() - 0.5)) + ((x1 + x2) / 2)
local y = ((y2 - y1) * y_scale * (random() - 0.5)) + ((y1 + y2) / 2)
return {x, y}
end
local function explode(entity)
local surface = entity.surface
local effects = 1
local box = entity.bounding_box
for k = 1, effects do
local position = get_random_position(box, 0.8, 0.5)
local effect = surface.create_entity {
name = "explosion",
position = position
}
surface.create_entity {
name = "crash-site-fire-smoke",
position = position
}
end
end
script.on_event(defines.events.on_player_mined_entity, function(event)
if not exploding_trees[event.entity.name] then
return
end
if global.random == nil then
global.random = game.create_random_generator()
end
local probability = settings.global["exploding-trees-probability"].value
if global.random(1, 100) <= probability then
explode(event.entity)
end
end)
|
local random = math.random
-- Explosions = {
-- "explosion", "explosion-hit", "ground-explosion", "massive-explosion",
-- "medium-explosion", "nuke-explosion", "crash-site-explosion-smoke"
-- }
local exploding_trees = {
["tree-01"] = true,
["tree-02"] = true,
["tree-03"] = true,
["tree-04"] = true,
["tree-05"] = true,
["tree-09"] = true,
["tree-02-red"] = true,
["tree-07"] = true,
["tree-06"] = true,
["tree-06-brown"] = true,
["tree-09-brown"] = true,
["tree-09-red"] = true,
["tree-08"] = true,
["tree-08-brown"] = true,
["tree-08-red"] = true,
["dead-dry-hairy-tree"] = true,
["dead-grey-trunk"] = true,
["dead-tree-desert"] = true,
["dry-hairy-tree"] = true,
["dry-tree"] = true,
["tree-01-stump"] = true,
["tree-02-stump"] = true,
["tree-03-stump"] = true,
["tree-04-stump"] = true,
["tree-05-stump"] = true,
["tree-06-stump"] = true,
["tree-07-stump"] = true,
["tree-08-stump"] = true,
["tree-09-stump"] = true
}
local function get_random_position(box)
local x1 = box.left_top.x
local y1 = box.left_top.y
local x2 = box.right_bottom.x
local y2 = box.right_bottom.y
local x = ((x2 - x1) * (random() - 0.5)) + ((x1 + x2) / 2)
local y = ((y2 - y1) * (random() - 0.5)) + ((y1 + y2) / 2)
return {x, y}
end
local function explode(entity)
local surface = entity.surface
local effects = 1
local box = entity.bounding_box
for _ = 1, effects do
local position = get_random_position(box, 0.8, 0.5)
surface.create_entity {
name = "explosion",
position = position
}
surface.create_entity {
name = "crash-site-fire-smoke",
position = position
}
end
end
script.on_event(defines.events.on_player_mined_entity, function(event)
if not exploding_trees[event.entity.name] then
return
end
if global.random == nil then
global.random = game.create_random_generator()
end
local probability = settings.global["exploding-trees-probability"].value
if global.random(1, 100) <= probability then
explode(event.entity)
end
end)
|
Fix Exploding Trees warnings
|
Fix Exploding Trees warnings
We don't want things other than trees to explode, after all
|
Lua
|
mit
|
Zomis/FactorioMods
|
dfda42b8153b33aadbc7279ef929b3ab6133d5ed
|
plugins/database.lua
|
plugins/database.lua
|
local function callback_group_database(extra, success, result)
local database = extra.database
local chat_id = result.peer_id
-- save group info
if database["groups"][tostring(chat_id)] then
database["groups"][tostring(chat_id)] = {
print_name = result.print_name:gsub("_"," "),
lang = get_lang(result.peer_id),
old_print_names = database["groups"][tostring(chat_id)].old_print_names .. ' ### ' .. result.print_name:gsub("_"," "),
long_id = result.id
}
else
database["groups"][tostring(chat_id)] = {
print_name = result.print_name:gsub("_"," "),
lang = get_lang(result.peer_id),
old_print_names = result.print_name:gsub("_"," "),
long_id = result.id
}
end
-- save users info
for k, v in pairs(result.members) do
if database["users"][tostring(v.peer_id)] then
table.insert(database["users"][tostring(v.peer_id)].groups, chat_id)
database["users"][tostring(v.peer_id)] = {
print_name = v.print_name:gsub("_"," "),
username = v.username or 'NOUSER',
old_print_names = database["users"][tostring(v.peer_id)].old_print_names .. ' ### ' .. v.print_name:gsub("_"," "),
old_usernames = database["users"][tostring(v.peer_id)].old_usernames .. ' ### ' ..(v.username or 'NOUSER'),
long_id = v.id
}
else
database["users"][tostring(v.peer_id)] = {
print_name = v.print_name:gsub("_"," "),
username = v.username or 'NOUSER',
groups = { chat_id },
old_print_names = v.print_name:gsub("_"," "),
old_usernames = v.username or 'NOUSER',
long_id = v.id
}
end
end
save_data(_config.database.db, database)
send_large_msg(extra.receiver, langs[get_lang(result.peer_id)].dataLeaked)
end
local function callback_supergroup_database(extra, success, result)
local database = extra.database
local chat_id = string.match(extra.receiver, '%d+')
-- save supergroup info
if database["groups"][tostring(chat_id)] then
database["groups"][tostring(chat_id)] = {
print_name = extra.print_name:gsub("_"," "),
username = extra.username or 'NOUSER',
lang = get_lang(string.match(extra.receiver,'%d+')),
old_print_names = database["groups"][tostring(chat_id)].old_print_names .. ' ### ' .. extra.print_name:gsub("_"," "),
old_usernames = database["groups"][tostring(chat_id)].old_usernames .. ' ### ' ..(extra.username or 'NOUSER'),
long_id = extra.id
}
else
database["groups"][tostring(chat_id)] = {
print_name = extra.print_name:gsub("_"," "),
username = extra.username or 'NOUSER',
lang = get_lang(string.match(extra.receiver,'%d+')),
old_print_names = extra.print_name:gsub("_"," "),
old_usernames = extra.username or 'NOUSER',
long_id = extra.id
}
end
-- save users info
for k, v in pairsByKeys(result) do
if database["users"][tostring(v.peer_id)] then
table.insert(database["users"][tostring(v.peer_id)].groups, chat_id)
database["users"][tostring(v.peer_id)] = {
print_name = v.print_name:gsub("_"," "),
username = v.username or 'NOUSER',
old_print_names = database["users"][tostring(v.peer_id)].old_print_names .. ' ### ' .. v.print_name:gsub("_"," "),
old_usernames = database["users"][tostring(v.peer_id)].old_usernames .. ' ### ' ..(v.username or 'NOUSER'),
long_id = v.id
}
else
database["users"][tostring(v.peer_id)] = {
print_name = v.print_name:gsub("_"," "),
username = v.username or 'NOUSER',
groups = { chat_id },
old_print_names = v.print_name:gsub("_"," "),
old_usernames = v.username or 'NOUSER',
long_id = v.id
}
end
end
save_data(_config.database.db, database)
send_large_msg(extra.receiver, langs[get_lang(string.match(extra.receiver, '%d+'))].dataLeaked)
end
local function run(msg, matches)
if is_sudo(msg) then
if matches[1]:lower() == 'createdatabase' then
local f = io.open(_config.database.db, 'w+')
f:write('{"groups":{},"users":{}}')
f:close()
reply_msg(msg.id, langs[msg.lang].dbCreated, ok_cb, false)
return
end
local database = load_data(_config.database.db)
if matches[1]:lower() == 'database' or matches[1]:lower() == 'sasha database' then
local receiver = get_receiver(msg)
if msg.to.type == 'channel' then
channel_get_users(receiver, callback_supergroup_database, { receiver = receiver, database = database, print_name = msg.to.print_name, username = (msg.to.username or nil), id = msg.to.peer_id })
elseif msg.to.type == 'chat' then
chat_info(receiver, callback_group_database, { receiver = receiver, database = database })
else
return
end
end
else
return langs[msg.lang].require_sudo
end
end
return {
description = "DATABASE",
patterns =
{
"^[#!/]([Cc][Rr][Ee][Aa][Tt][Ee][Dd][Aa][Tt][Aa][Bb][Aa][Ss][Ee])$",
"^[#!/]([Dd][Aa][Tt][Aa][Bb][Aa][Ss][Ee])$",
-- database
"^([Ss][Aa][Ss][Hh][Aa] [Dd][Aa][Tt][Aa][Bb][Aa][Ss][Ee])$",
},
run = run,
min_rank = 5
-- usage
-- SUDO
-- #createdatabase
-- (#database|[sasha] database)
}
|
local function callback_group_database(extra, success, result)
local database = extra.database
local chat_id = result.peer_id
-- save group info
if database["groups"][tostring(chat_id)] then
database["groups"][tostring(chat_id)] = {
print_name = result.print_name:gsub("_"," "),
lang = get_lang(result.peer_id),
old_print_names = database["groups"][tostring(chat_id)].old_print_names .. ' ### ' .. result.print_name:gsub("_"," "),
long_id = result.id
}
else
database["groups"][tostring(chat_id)] = {
print_name = result.print_name:gsub("_"," "),
lang = get_lang(result.peer_id),
old_print_names = result.print_name:gsub("_"," "),
long_id = result.id
}
end
-- save users info
for k, v in pairs(result.members) do
if database["users"][tostring(v.peer_id)] then
if not database["users"][tostring(v.peer_id)].groups[tostring(chat_id)] then
database["users"][tostring(v.peer_id)].groups[tostring(chat_id)] = tonumber(chat_id)
end
database["users"][tostring(v.peer_id)] = {
print_name = v.print_name:gsub("_"," "),
username = v.username or 'NOUSER',
old_print_names = database["users"][tostring(v.peer_id)].old_print_names .. ' ### ' .. v.print_name:gsub("_"," "),
old_usernames = database["users"][tostring(v.peer_id)].old_usernames .. ' ### ' ..(v.username or 'NOUSER'),
long_id = v.id
}
else
database["users"][tostring(v.peer_id)] = {
print_name = v.print_name:gsub("_"," "),
username = v.username or 'NOUSER',
old_print_names = v.print_name:gsub("_"," "),
old_usernames = v.username or 'NOUSER',
long_id = v.id
}
database["users"][tostring(v.peer_id)].groups = { }
database["users"][tostring(v.peer_id)].groups[tostring(chat_id)] = tonumber(chat_id)
end
end
save_data(_config.database.db, database)
send_large_msg(extra.receiver, langs[get_lang(result.peer_id)].dataLeaked)
end
local function callback_supergroup_database(extra, success, result)
local database = extra.database
local chat_id = string.match(extra.receiver, '%d+')
-- save supergroup info
if database["groups"][tostring(chat_id)] then
database["groups"][tostring(chat_id)] = {
print_name = extra.print_name:gsub("_"," "),
username = extra.username or 'NOUSER',
lang = get_lang(string.match(extra.receiver,'%d+')),
old_print_names = database["groups"][tostring(chat_id)].old_print_names .. ' ### ' .. extra.print_name:gsub("_"," "),
old_usernames = database["groups"][tostring(chat_id)].old_usernames .. ' ### ' ..(extra.username or 'NOUSER'),
long_id = extra.id
}
else
database["groups"][tostring(chat_id)] = {
print_name = extra.print_name:gsub("_"," "),
username = extra.username or 'NOUSER',
lang = get_lang(string.match(extra.receiver,'%d+')),
old_print_names = extra.print_name:gsub("_"," "),
old_usernames = extra.username or 'NOUSER',
long_id = extra.id
}
end
-- save users info
for k, v in pairsByKeys(result) do
if database["users"][tostring(v.peer_id)] then
if not database["users"][tostring(v.peer_id)].groups[tostring(chat_id)] then
database["users"][tostring(v.peer_id)].groups[tostring(chat_id)] = tonumber(chat_id)
end
database["users"][tostring(v.peer_id)] = {
print_name = v.print_name:gsub("_"," "),
username = v.username or 'NOUSER',
old_print_names = database["users"][tostring(v.peer_id)].old_print_names .. ' ### ' .. v.print_name:gsub("_"," "),
old_usernames = database["users"][tostring(v.peer_id)].old_usernames .. ' ### ' ..(v.username or 'NOUSER'),
long_id = v.id
}
else
database["users"][tostring(v.peer_id)] = {
print_name = v.print_name:gsub("_"," "),
username = v.username or 'NOUSER',
old_print_names = v.print_name:gsub("_"," "),
old_usernames = v.username or 'NOUSER',
long_id = v.id
}
database["users"][tostring(v.peer_id)].groups = { }
database["users"][tostring(v.peer_id)].groups[tostring(chat_id)] = tonumber(chat_id)
end
end
save_data(_config.database.db, database)
send_large_msg(extra.receiver, langs[get_lang(string.match(extra.receiver, '%d+'))].dataLeaked)
end
local function run(msg, matches)
if is_sudo(msg) then
if matches[1]:lower() == 'createdatabase' then
local f = io.open(_config.database.db, 'w+')
f:write('{"groups":{},"users":{}}')
f:close()
reply_msg(msg.id, langs[msg.lang].dbCreated, ok_cb, false)
return
end
local database = load_data(_config.database.db)
if matches[1]:lower() == 'database' or matches[1]:lower() == 'sasha database' then
local receiver = get_receiver(msg)
if msg.to.type == 'channel' then
channel_get_users(receiver, callback_supergroup_database, { receiver = receiver, database = database, print_name = msg.to.print_name, username = (msg.to.username or nil), id = msg.to.peer_id })
elseif msg.to.type == 'chat' then
chat_info(receiver, callback_group_database, { receiver = receiver, database = database })
else
return
end
end
else
return langs[msg.lang].require_sudo
end
end
return {
description = "DATABASE",
patterns =
{
"^[#!/]([Cc][Rr][Ee][Aa][Tt][Ee][Dd][Aa][Tt][Aa][Bb][Aa][Ss][Ee])$",
"^[#!/]([Dd][Aa][Tt][Aa][Bb][Aa][Ss][Ee])$",
-- database
"^([Ss][Aa][Ss][Hh][Aa] [Dd][Aa][Tt][Aa][Bb][Aa][Ss][Ee])$",
},
run = run,
min_rank = 5
-- usage
-- SUDO
-- #createdatabase
-- (#database|[sasha] database)
}
|
fix database
|
fix database
|
Lua
|
agpl-3.0
|
xsolinsx/AISasha
|
7ec10d155d12bc118e0b57a017299b88ef5a583d
|
generate/lua/ParseDescription.lua
|
generate/lua/ParseDescription.lua
|
--[[
ParseDescription ( file )
Retrieves descriptions for a class from a given markdown dile.
The file is divided into sections, delimited by level-1 headers. The following
header names are detected (case-insensitive):
- summary: A short and simple description of the class.
- details: A long description of the class.
- members: Descriptions of each member.
The members section is further divided into subsections; one for each member
of the class. Each subsection is delimited by a level-2 header, with the name
of the member as the header name (case-sensitive).
Returns a table with the following fields:
- `summary`: The content of the summary section, parsed into HTML.
- `details`: The content of the details section, parsed into HTML.
- `members`: A set of member names paired with their corresponsing section
content, parsed into HTML.
The order of sections does not matter.
All sections and subsections are optional. If a section is omitted, its
returned value will simply be nil. Note that sections that are empty may not
be detected.
]]
-- find a header and return it's start and end position, and its level and name
local function findHeader(source,init)
-- find atx-style header at beginning
-- this could probably be better
local a,b = source:find('^#+[ \t]*[^\n][^\n]-[ \t]*#*[ \t]*\n',init)
if not a then
-- find on a new line instead
a,b = source:find('\n#+[ \t]*[^\n][^\n]-[ \t]*#*[ \t]*\n',init)
end
-- find setext-style header
local c,d = source:find('^[ \t]*([^\n][^\n]-)[ \t]*\n[-=]+\n',init)
if not c then
c,d = source:find('\n[ \t]*[^\n][^\n]-[ \t]*\n[-=]+\n',init)
end
-- both may have matched, so select the first
if a and c then
if c < a then
a = nil
else
c = nil
end
end
-- extract the level and name out of the matched header
if a then
local level,name = source:sub(a,b):match('(#+)[ \t]*([^\n][^\n]-)[ \t]*#*[ \t]*\n')
return a,b,#level,name
elseif c then
local name,level = source:sub(c,d):match('[ \t]*([^\n][^\n]-)[ \t]*\n([-=]+)\n')
-- make sure each character matches
if level:match('^=+$') then
-- level 1 header
return c,d,1,name
elseif level:match('^-+$') then
-- level 2 header
return c,d,2,name
end
end
return nil
end
-- trim leading and trailing whitespace
local function trim(s)
return s:gsub('^%s+',''):gsub('%s+$','')
end
local function getHeader(sections,name)
local markdown = require 'markdown'
local section = trim(markdown(sections[name] or ''))
if #section > 0 then
return section
end
end
local function getSubheader(sections,name)
local section = sections.members
if section and #section > 0 then
local markdown = require 'markdown'
local subs = {}
local subName
local subStart,subEnd
local init = 0
while true do
local headStart,headEnd,level,name = findHeader(section,init + 1)
if not headStart then
break
end
if level == 2 then
if subName then
subEnd = headStart - 1
local content = trim(markdown(section:sub(subStart,subEnd)))
if #content > 0 then
subs[subName] = content
end
end
subName = name
subStart = headEnd + 1
end
init = headEnd
end
if subName then
local content = trim(markdown(section:sub(subStart,#section)))
if #content > 0 then
subs[subName] = content
end
end
return subs
end
end
return function(type,name)
local file = utl.path('..','data',type,format.url.file(name) .. '.md')
local source do
local f,err = io.open(file)
if not f then
return {}
end
source = f:read('*a')
f:close()
end
-- convert DOS and Mac newlines to UNIX, for convenience
-- markdown parser already does it anyway
source = source:gsub('\r\n','\n'):gsub('\r','\n')
-- find sections, delimited by headers
local sections = {}
local low = source:lower()
local secName
local secStart,secEnd
local init = 0
while true do
-- header names are case-insensitive
local headStart,headEnd,level,name = findHeader(low,init + 1)
if not headStart then
break
end
-- only find level 1 headers; skip over other ones
if level == 1 then
if secName then
secEnd = headStart - 1
sections[secName] = source:sub(secStart,secEnd)
end
secName = name
secStart = headEnd + 1
end
init = headEnd
end
if secName then
sections[secName] = source:sub(secStart,#source)
end
-- extract the sections we want and convert them to HTML
local description = {
Summary = getHeader(sections,'summary');
Details = getHeader(sections,'details');
}
if type == 'class' then
description.Members = getSubheader(sections,'members')
elseif type == 'enum' then
description.Items = getSubheader(sections,'items')
end
return description
end
|
--[[
ParseDescription ( file )
Retrieves descriptions for a class from a given markdown dile.
The file is divided into sections, delimited by level-1 headers. The following
header names are detected (case-insensitive):
- summary: A short and simple description of the class.
- details: A long description of the class.
- members: Descriptions of each member.
The members section is further divided into subsections; one for each member
of the class. Each subsection is delimited by a level-2 header, with the name
of the member as the header name (case-sensitive).
Returns a table with the following fields:
- `summary`: The content of the summary section, parsed into HTML.
- `details`: The content of the details section, parsed into HTML.
- `members`: A set of member names paired with their corresponsing section
content, parsed into HTML.
The order of sections does not matter.
All sections and subsections are optional. If a section is omitted, its
returned value will simply be nil. Note that sections that are empty may not
be detected.
]]
local utl = require'utl'
local format = require'format'
-- find a header and return it's start and end position, and its level and name
local function findHeader(source,init)
-- find atx-style header at beginning
-- this could probably be better
local a,b = source:find('^#+[ \t]*[^\n][^\n]-[ \t]*#*[ \t]*\n',init)
if not a then
-- find on a new line instead
a,b = source:find('\n#+[ \t]*[^\n][^\n]-[ \t]*#*[ \t]*\n',init)
end
-- find setext-style header
local c,d = source:find('^[ \t]*([^\n][^\n]-)[ \t]*\n[-=]+\n',init)
if not c then
c,d = source:find('\n[ \t]*[^\n][^\n]-[ \t]*\n[-=]+\n',init)
end
-- both may have matched, so select the first
if a and c then
if c < a then
a = nil
else
c = nil
end
end
-- extract the level and name out of the matched header
if a then
local level,name = source:sub(a,b):match('(#+)[ \t]*([^\n][^\n]-)[ \t]*#*[ \t]*\n')
return a,b,#level,name
elseif c then
local name,level = source:sub(c,d):match('[ \t]*([^\n][^\n]-)[ \t]*\n([-=]+)\n')
-- make sure each character matches
if level:match('^=+$') then
-- level 1 header
return c,d,1,name
elseif level:match('^-+$') then
-- level 2 header
return c,d,2,name
end
end
return nil
end
-- trim leading and trailing whitespace
local function trim(s)
return s:gsub('^%s+',''):gsub('%s+$','')
end
local function getHeader(sections,name)
local markdown = require 'markdown'
local section = trim(markdown(sections[name] or ''))
if #section > 0 then
return section
end
end
local function getSubheader(sections,name)
local section = sections.members
if section and #section > 0 then
local markdown = require 'markdown'
local subs = {}
local subName
local subStart,subEnd
local init = 0
while true do
local headStart,headEnd,level,name = findHeader(section,init + 1)
if not headStart then
break
end
if level == 2 then
if subName then
subEnd = headStart - 1
local content = trim(markdown(section:sub(subStart,subEnd)))
if #content > 0 then
subs[subName] = content
end
end
subName = name
subStart = headEnd + 1
end
init = headEnd
end
if subName then
local content = trim(markdown(section:sub(subStart,#section)))
if #content > 0 then
subs[subName] = content
end
end
return subs
end
end
return function(type,name)
local file = utl.path('..','data',type,format.url.file(name) .. '.md')
local source do
local f,err = io.open(file)
if not f then
return {}
end
source = f:read('*a')
f:close()
end
-- convert DOS and Mac newlines to UNIX, for convenience
-- markdown parser already does it anyway
source = source:gsub('\r\n','\n'):gsub('\r','\n')
-- find sections, delimited by headers
local sections = {}
local low = source:lower()
local secName
local secStart,secEnd
local init = 0
while true do
-- header names are case-insensitive
local headStart,headEnd,level,name = findHeader(low,init + 1)
if not headStart then
break
end
-- only find level 1 headers; skip over other ones
if level == 1 then
if secName then
secEnd = headStart - 1
sections[secName] = source:sub(secStart,secEnd)
end
secName = name
secStart = headEnd + 1
end
init = headEnd
end
if secName then
sections[secName] = source:sub(secStart,#source)
end
-- extract the sections we want and convert them to HTML
local description = {
Summary = getHeader(sections,'summary');
Details = getHeader(sections,'details');
}
if type == 'class' then
description.Members = getSubheader(sections,'members')
elseif type == 'enum' then
description.Items = getSubheader(sections,'items')
end
return description
end
|
fixed missing dependencies
|
fixed missing dependencies
|
Lua
|
unlicense
|
Anaminus/roblox-api-ref,Anaminus/roblox-api-ref
|
185fc8f1a4c1b3754ff877c2b4a3a7e73da2c096
|
src_trunk/resources/anticheat-system/c_anticheat.lua
|
src_trunk/resources/anticheat-system/c_anticheat.lua
|
local cooldown = false
local localPlayer = getLocalPlayer()
function checkSpeedHacks()
local vehicle = getPedOccupiedVehicle(localPlayer)
if (vehicle) and not (cooldown) then
local speedx, speedy, speedz = getElementVelocity(vehicle)
local actualspeed = math.ceil(((speedx^2 + speedy^2 + speedz^2)^(0.5)*100))
if (actualspeed>151) then
cooldown = true
setTimer(resetCD, 5000, 1)
triggerServerEvent("alertAdminsOfSpeedHacks", localPlayer, actualspeed)
end
end
end
addEventHandler("onClientRender", getRootElement(), checkSpeedHacks)
function resetCD()
cooldown = false
end
local timer = false
local kills = 0
function checkDM(killer)
if (killer==localPlayer) then
kills = kills + 1
if (kills>=3) then
triggerServerEvent("alertAdminsOfDM", localPlayer, kills)
end
if not (timer) then
timer = true
setTimer(resetDMCD, 120000, 1)
end
end
end
addEventHandler("onClientPlayerWasted", getRootElement(), checkDM)
function resetDMCD()
kills = 0
timer = false
end
-- [WEAPON HACKS]
local strikes = 0
function resetWeaponTimer()
if weapontimer then
killTimer(weapontimer)
end
weapontimer = setTimer(checkWeapons, 15000, 0)
end
function checkWeapons()
for i = 1, 47 do
local onslot = getSlotFromWeapon(i)
if getPedWeapon(localPlayer, onslot) == i then
local ammo = getElementData(localPlayer, "ACweapon" .. i) or 0
local totalAmmo = getPedTotalAmmo(localPlayer, onslot)
if totalAmmo >= 60000 and (i <= 15 or i >= 44) then -- fix for melee with 60k+ ammo
totalAmmo = 1
end
if totalAmmo > ammo then
strikes = strikes + 1
triggerServerEvent("notifyWeaponHacks", localPlayer, i, totalAmmo, ammo, strikes)
elseif totalAmmo < ammo then
-- update the new ammo count
setElementData(localPlayer, "ACweapon" .. i, totalAmmo, false)
end
else -- weapon on that slot, but not the current one
setElementData(localPlayer, "ACweapon" .. i, nil, false)
end
end
end
addCommandHandler("fwc", checkWeapons)
function giveSafeWeapon(weapon, ammo)
resetWeaponTimer()
setElementData(localPlayer, "ACweapon" .. weapon, (getElementData(localPlayer, "ACweapon" .. weapon) or 0) + ammo, false)
end
addEvent("giveSafeWeapon", true)
addEventHandler("giveSafeWeapon", getLocalPlayer(), giveSafeWeapon)
function setSafeWeaponAmmo(weapon, ammo)
resetWeaponTimer()
setElementData(localPlayer, "ACweapon" .. weapon, ammo, false)
end
addEvent("setSafeWeaponAmmo", true)
addEventHandler("setSafeWeaponAmmo", getLocalPlayer(), setSafeWeaponAmmo)
function takeAllWeaponsSafe()
resetWeaponTimer()
for weapon = 0, 47 do
setElementData(localPlayer, "ACweapon" .. weapon, nil, false)
end
end
addEvent("takeAllWeaponsSafe", true)
addEventHandler("takeAllWeaponsSafe", getLocalPlayer(), takeAllWeaponsSafe)
function takeWeaponSafe(weapon)
resetWeaponTimer()
setElementData(localPlayer, "ACweapon" .. weapon, nil, false)
end
addEvent("takeWeaponSafe", true)
addEventHandler("takeWeaponSafe", getLocalPlayer(), takeWeaponSafe)
addEventHandler("onClientResourceStart", getResourceRootElement(), resetWeaponTimer)
function updateWeaponOnFire(weapon, ammo)
setElementData(localPlayer, "ACweapon" .. weapon, (getElementData(localPlayer, "ACweapon" .. weapon) or 0) - 1, false)
end
addEventHandler("onClientPlayerWeaponFire", localPlayer, updateWeaponOnFire)
|
local cooldown = false
local localPlayer = getLocalPlayer()
function checkSpeedHacks()
local vehicle = getPedOccupiedVehicle(localPlayer)
if (vehicle) and not (cooldown) then
local speedx, speedy, speedz = getElementVelocity(vehicle)
local actualspeed = math.ceil(((speedx^2 + speedy^2 + speedz^2)^(0.5)*100))
if (actualspeed>151) then
cooldown = true
setTimer(resetCD, 5000, 1)
triggerServerEvent("alertAdminsOfSpeedHacks", localPlayer, actualspeed)
end
end
end
addEventHandler("onClientRender", getRootElement(), checkSpeedHacks)
function resetCD()
cooldown = false
end
local timer = false
local kills = 0
function checkDM(killer)
if (killer==localPlayer) then
kills = kills + 1
if (kills>=3) then
triggerServerEvent("alertAdminsOfDM", localPlayer, kills)
end
if not (timer) then
timer = true
setTimer(resetDMCD, 120000, 1)
end
end
end
addEventHandler("onClientPlayerWasted", getRootElement(), checkDM)
function resetDMCD()
kills = 0
timer = false
end
-- [WEAPON HACKS]
local strikes = 0
function resetWeaponTimer()
if weapontimer then
killTimer(weapontimer)
end
weapontimer = setTimer(checkWeapons, 15000, 0)
end
function checkWeapons()
for i = 1, 47 do
local onslot = getSlotFromWeapon(i)
if getPedWeapon(localPlayer, onslot) == i then
local ammo = getElementData(localPlayer, "ACweapon" .. i) or 0
if ammo < 0 then
ammo = 0
setElementData(localPlayer, "ACweapon" .. i, 0, false)
end
local totalAmmo = getPedTotalAmmo(localPlayer, onslot)
if totalAmmo >= 60000 and (i <= 15 or i >= 44) then -- fix for melee with 60k+ ammo
totalAmmo = 1
end
if totalAmmo > ammo then
strikes = strikes + 1
triggerServerEvent("notifyWeaponHacks", localPlayer, i, totalAmmo, ammo, strikes)
elseif totalAmmo < ammo then
-- update the new ammo count
setElementData(localPlayer, "ACweapon" .. i, totalAmmo, false)
end
else -- weapon on that slot, but not the current one
setElementData(localPlayer, "ACweapon" .. i, nil, false)
end
end
end
addCommandHandler("fwc", checkWeapons)
function giveSafeWeapon(weapon, ammo)
resetWeaponTimer()
setElementData(localPlayer, "ACweapon" .. weapon, (getElementData(localPlayer, "ACweapon" .. weapon) or 0) + ammo, false)
end
addEvent("giveSafeWeapon", true)
addEventHandler("giveSafeWeapon", getLocalPlayer(), giveSafeWeapon)
function setSafeWeaponAmmo(weapon, ammo)
resetWeaponTimer()
setElementData(localPlayer, "ACweapon" .. weapon, ammo, false)
end
addEvent("setSafeWeaponAmmo", true)
addEventHandler("setSafeWeaponAmmo", getLocalPlayer(), setSafeWeaponAmmo)
function takeAllWeaponsSafe()
resetWeaponTimer()
for weapon = 0, 47 do
setElementData(localPlayer, "ACweapon" .. weapon, nil, false)
end
end
addEvent("takeAllWeaponsSafe", true)
addEventHandler("takeAllWeaponsSafe", getLocalPlayer(), takeAllWeaponsSafe)
function takeWeaponSafe(weapon)
resetWeaponTimer()
setElementData(localPlayer, "ACweapon" .. weapon, nil, false)
end
addEvent("takeWeaponSafe", true)
addEventHandler("takeWeaponSafe", getLocalPlayer(), takeWeaponSafe)
addEventHandler("onClientResourceStart", getResourceRootElement(), resetWeaponTimer)
function updateWeaponOnFire(weapon, ammo)
setElementData(localPlayer, "ACweapon" .. weapon, (getElementData(localPlayer, "ACweapon" .. weapon) or 0) - 1, false)
end
addEventHandler("onClientPlayerWeaponFire", localPlayer, updateWeaponOnFire)
|
ac fix
|
ac fix
git-svn-id: 8769cb08482c9977c94b72b8e184ec7d2197f4f7@1271 64450a49-1f69-0410-a0a2-f5ebb52c4f5b
|
Lua
|
bsd-3-clause
|
valhallaGaming/uno,valhallaGaming/uno,valhallaGaming/uno
|
c676980f8b16415504fced711d1a36547317f124
|
src/apps/pcap/tap.lua
|
src/apps/pcap/tap.lua
|
-- Use of this source code is governed by the Apache 2.0 license; see COPYING.
module(...,package.seeall)
local ffi = require("ffi")
local app = require("core.app")
local lib = require("core.lib")
local link = require("core.link")
local pcap = require("lib.pcap.pcap")
local pf = require("pf")
Tap = {}
local tap_config_params = {
-- Name of file to which to write packets.
filename = { required=true },
-- "truncate" to truncate the file, or "append" to add to the file.
mode = { default = "truncate" },
-- Only packets that match this pflang filter will be captured.
filter = { },
-- Only write every Nth packet that matches the filter.
sample = { default=1 },
}
function Tap:new(conf)
local o = lib.parse(conf, tap_config_params)
local mode = assert(({truncate='w+b', append='a+b'})[o.mode])
o.file = assert(io.open(o.filename, mode))
if o.file:seek() == 0 then pcap.write_file_header(o.file) end
if o.filter then o.filter = pf.compile_filter(o.filter) end
o.n = o.sample - 1
return setmetatable(o, {__index = Tap})
end
function Tap:push ()
local n = self.n
while not link.empty(self.input.input) do
local p = link.receive(self.input.input)
if not self.filter or self.filter(p.data, p.length) then
n = n + 1
if n == self.sample then
n = 0
pcap.write_record(self.file, p.data, p.length)
end
end
link.transmit(self.output.output, p)
end
self.n = n
end
function selftest ()
print('selftest: apps.pcap.tap')
local config = require("core.config")
local Sink = require("apps.basic.basic_apps").Sink
local PcapReader = require("apps.pcap.pcap").PcapReader
local function run(filter, sample)
local tmp = os.tmpname()
local c = config.new()
-- Re-use example from packet filter test.
config.app(c, "source", PcapReader, "apps/packet_filter/samples/v6.pcap")
config.app(c, "tap", Tap, {filename=tmp, filter=filter, sample=sample})
config.app(c, "sink", Sink )
config.link(c, "source.output -> tap.input")
config.link(c, "tap.output -> sink.input")
app.configure(c)
while not app.app_table.source.done do app.breathe() end
local n = 0
for packet, record in pcap.records(tmp) do n = n + 1 end
os.remove(tmp)
app.configure(config.new())
return n
end
assert(run() == 161)
assert(run("icmp6") == 49)
assert(run(nil, 2) == 81)
assert(run("icmp6", 2) == 25)
print('selftest: ok')
end
|
-- Use of this source code is governed by the Apache 2.0 license; see COPYING.
module(...,package.seeall)
local ffi = require("ffi")
local app = require("core.app")
local lib = require("core.lib")
local link = require("core.link")
local pcap = require("lib.pcap.pcap")
local pf = require("pf")
Tap = {}
local tap_config_params = {
-- Name of file to which to write packets.
filename = { required=true },
-- "truncate" to truncate the file, or "append" to add to the file.
mode = { default = "truncate" },
-- Only packets that match this pflang filter will be captured.
filter = { },
-- Only write every Nth packet that matches the filter.
sample = { default=1 },
}
function Tap:new(conf)
local o = lib.parse(conf, tap_config_params)
local mode = assert(({truncate='w+b', append='a+b'})[o.mode])
o.file = assert(io.open(o.filename, mode))
if o.file:seek() == 0 then pcap.write_file_header(o.file) end
if o.filter then o.filter = pf.compile_filter(o.filter) end
o.n = o.sample - 1
return setmetatable(o, {__index = Tap})
end
function Tap:push ()
local n = self.n
while not link.empty(self.input.input) do
local p = link.receive(self.input.input)
if not self.filter or self.filter(p.data, p.length) then
n = n + 1
if n == self.sample then
n = 0
pcap.write_record(self.file, p.data, p.length)
end
end
link.transmit(self.output.output, p)
end
self.n = n
end
function selftest ()
print('selftest: apps.pcap.tap')
local config = require("core.config")
local Sink = require("apps.basic.basic_apps").Sink
local PcapReader = require("apps.pcap.pcap").PcapReader
local function run(filter, sample)
local tmp = os.tmpname()
local c = config.new()
-- Re-use example from packet filter test.
config.app(c, "source", PcapReader, "apps/packet_filter/samples/v6.pcap")
config.app(c, "tap", Tap, {filename=tmp, filter=filter, sample=sample})
config.app(c, "sink", Sink )
config.link(c, "source.output -> tap.input")
config.link(c, "tap.output -> sink.input")
app.configure(c)
app.main{done=function () return app.app_table.source.done end}
local n = 0
for packet, record in pcap.records(tmp) do n = n + 1 end
os.remove(tmp)
app.configure(config.new())
return n
end
assert(run() == 161)
assert(run("icmp6") == 49)
assert(run(nil, 2) == 81)
assert(run("icmp6", 2) == 25)
print('selftest: ok')
end
|
apps.pcap.tap: fix selftest
|
apps.pcap.tap: fix selftest
|
Lua
|
apache-2.0
|
snabbco/snabb,eugeneia/snabb,eugeneia/snabb,eugeneia/snabb,snabbco/snabb,eugeneia/snabb,snabbco/snabb,eugeneia/snabb,snabbco/snabb,eugeneia/snabb,snabbco/snabb,snabbco/snabb,snabbco/snabb,eugeneia/snabb,snabbco/snabb,eugeneia/snabb
|
3048eed2aaaf3595d7e22ac792a41f60214a8b87
|
lualib/skynet/cluster.lua
|
lualib/skynet/cluster.lua
|
local skynet = require "skynet"
local clusterd
local cluster = {}
local sender = {}
local function get_sender(t, node)
local c = skynet.call(clusterd, "lua", "sender", node)
t[node] = c
return c
end
setmetatable(sender, { __index = get_sender } )
function cluster.call(node, address, ...)
-- skynet.pack(...) will free by cluster.core.packrequest
return skynet.call(sender[node], "lua", "req", address, skynet.pack(...))
end
function cluster.send(node, address, ...)
-- push is the same with req, but no response
skynet.send(sender[node], "lua", "push", address, skynet.pack(...))
end
function cluster.open(port)
if type(port) == "string" then
skynet.call(clusterd, "lua", "listen", port)
else
skynet.call(clusterd, "lua", "listen", "0.0.0.0", port)
end
end
function cluster.reload(config)
skynet.call(clusterd, "lua", "reload", config)
end
function cluster.proxy(node, name)
return skynet.call(clusterd, "lua", "proxy", node, name)
end
function cluster.snax(node, name, address)
local snax = require "skynet.snax"
if not address then
address = cluster.call(node, ".service", "QUERY", "snaxd" , name)
end
local handle = skynet.call(clusterd, "lua", "proxy", node, address)
return snax.bind(handle, name)
end
function cluster.register(name, addr)
assert(type(name) == "string")
assert(addr == nil or type(addr) == "number")
return skynet.call(clusterd, "lua", "register", name, addr)
end
function cluster.query(node, name)
return skynet.call(sender[node], "lua", "req", 0, skynet.pack(name))
end
skynet.init(function()
clusterd = skynet.uniqueservice("clusterd")
end)
return cluster
|
local skynet = require "skynet"
local clusterd
local cluster = {}
local sender = {}
local task_queue = {}
local function request_sender(q, node)
local ok, c = pcall(skynet.call, clusterd, "lua", "sender", node)
if not ok then
skynet.error(c)
c = nil
end
-- run tasks in queue
local confirm = coroutine.running()
q.confirm = confirm
q.sender = c
for _, task in ipairs(q) do
if type(task) == "table" then
if c then
skynet.send(c, "lua", "push", table.unpack(task,1,task.n))
end
else
skynet.wakeup(task)
skynet.wait(confirm)
end
end
task_queue[node] = nil
sender[node] = c
end
local function get_queue(t, node)
local q = {}
t[node] = q
skynet.fork(request_sender, q, node)
return q
end
setmetatable(task_queue, { __index = get_queue } )
local function get_sender(node)
local s = sender[node]
if not s then
local q = task_queue[node]
local task = coroutine.running()
table.insert(q, task)
skynet.wait(task)
skynet.wakeup(q.confirm)
return q.sender
end
return s
end
function cluster.call(node, address, ...)
-- skynet.pack(...) will free by cluster.core.packrequest
return skynet.call(get_sender(node), "lua", "req", address, skynet.pack(...))
end
function cluster.send(node, address, ...)
-- push is the same with req, but no response
local s = sender[node]
if not s then
table.insert(task_queue[node], table.pack(address, ...))
else
skynet.send(sender[node], "lua", "push", address, skynet.pack(...))
end
end
function cluster.open(port)
if type(port) == "string" then
skynet.call(clusterd, "lua", "listen", port)
else
skynet.call(clusterd, "lua", "listen", "0.0.0.0", port)
end
end
function cluster.reload(config)
skynet.call(clusterd, "lua", "reload", config)
end
function cluster.proxy(node, name)
return skynet.call(clusterd, "lua", "proxy", node, name)
end
function cluster.snax(node, name, address)
local snax = require "skynet.snax"
if not address then
address = cluster.call(node, ".service", "QUERY", "snaxd" , name)
end
local handle = skynet.call(clusterd, "lua", "proxy", node, address)
return snax.bind(handle, name)
end
function cluster.register(name, addr)
assert(type(name) == "string")
assert(addr == nil or type(addr) == "number")
return skynet.call(clusterd, "lua", "register", name, addr)
end
function cluster.query(node, name)
return skynet.call(get_sender(node), "lua", "req", 0, skynet.pack(name))
end
skynet.init(function()
clusterd = skynet.uniqueservice("clusterd")
end)
return cluster
|
try to fix #988
|
try to fix #988
|
Lua
|
mit
|
xjdrew/skynet,sanikoyes/skynet,xcjmine/skynet,ag6ag/skynet,bigrpg/skynet,cloudwu/skynet,wangyi0226/skynet,icetoggle/skynet,wangyi0226/skynet,wangyi0226/skynet,korialuo/skynet,jxlczjp77/skynet,JiessieDawn/skynet,cloudwu/skynet,JiessieDawn/skynet,JiessieDawn/skynet,hongling0/skynet,cloudwu/skynet,icetoggle/skynet,hongling0/skynet,xcjmine/skynet,jxlczjp77/skynet,sanikoyes/skynet,sanikoyes/skynet,icetoggle/skynet,pigparadise/skynet,xcjmine/skynet,xjdrew/skynet,ag6ag/skynet,korialuo/skynet,pigparadise/skynet,hongling0/skynet,pigparadise/skynet,jxlczjp77/skynet,bigrpg/skynet,ag6ag/skynet,korialuo/skynet,bigrpg/skynet,xjdrew/skynet
|
8216a7548560ec6e17048a53abeca94e6f7fe0b2
|
net/xmppserver_listener.lua
|
net/xmppserver_listener.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 logger = require "logger";
local log = logger.init("xmppserver_listener");
local lxp = require "lxp"
local init_xmlhandlers = require "core.xmlhandlers"
local s2s_new_incoming = require "core.s2smanager".new_incoming;
local s2s_streamopened = require "core.s2smanager".streamopened;
local s2s_streamclosed = require "core.s2smanager".streamclosed;
local s2s_destroy_session = require "core.s2smanager".destroy_session;
local s2s_attempt_connect = require "core.s2smanager".attempt_connection;
local stream_callbacks = { stream_tag = "http://etherx.jabber.org/streams|stream",
default_ns = "jabber:server",
streamopened = s2s_streamopened, streamclosed = s2s_streamclosed, handlestanza = core_process_stanza };
function stream_callbacks.error(session, error, data)
if error == "no-stream" then
session:close("invalid-namespace");
else
session.log("debug", "Server-to-server XML parse error: %s", tostring(error));
session:close("xml-not-well-formed");
end
end
local function handleerr(err) log("error", "Traceback[s2s]: %s: %s", tostring(err), debug.traceback()); end
function stream_callbacks.handlestanza(a, b)
xpcall(function () core_process_stanza(a, b) end, handleerr);
end
local connlisteners_register = require "net.connlisteners".register;
local t_insert = table.insert;
local t_concat = table.concat;
local t_concatall = function (t, sep) local tt = {}; for _, s in ipairs(t) do t_insert(tt, tostring(s)); end return t_concat(tt, sep); end
local m_random = math.random;
local format = string.format;
local sessionmanager = require "core.sessionmanager";
local sm_new_session, sm_destroy_session = sessionmanager.new_session, sessionmanager.destroy_session;
local st = require "util.stanza";
local sessions = {};
local xmppserver = { default_port = 5269, default_mode = "*a" };
-- These are session methods --
local function session_reset_stream(session)
-- Reset stream
local parser = lxp.new(init_xmlhandlers(session, stream_callbacks), "|");
session.parser = parser;
session.notopen = true;
function session.data(conn, data)
local ok, err = parser:parse(data);
if ok then return; end
session.log("warn", "Received invalid XML: %s", data);
session.log("warn", "Problem was: %s", err);
session:close("xml-not-well-formed");
end
return true;
end
local stream_xmlns_attr = {xmlns='urn:ietf:params:xml:ns:xmpp-streams'};
local default_stream_attr = { ["xmlns:stream"] = stream_callbacks.stream_tag:gsub("%|[^|]+$", ""), xmlns = stream_callbacks.default_ns, version = "1.0", id = "" };
local function session_close(session, reason)
local log = session.log or log;
if session.conn then
if session.notopen then
session.sends2s("<?xml version='1.0'?>");
session.sends2s(st.stanza("stream:stream", default_stream_attr):top_tag());
end
if reason then
if type(reason) == "string" then -- assume stream error
log("info", "Disconnecting %s[%s], <stream:error> is: %s", session.host or "(unknown host)", session.type, reason);
session.sends2s(st.stanza("stream:error"):tag(reason, {xmlns = 'urn:ietf:params:xml:ns:xmpp-streams' }));
elseif type(reason) == "table" then
if reason.condition then
local stanza = st.stanza("stream:error"):tag(reason.condition, stream_xmlns_attr):up();
if reason.text then
stanza:tag("text", stream_xmlns_attr):text(reason.text):up();
end
if reason.extra then
stanza:add_child(reason.extra);
end
log("info", "Disconnecting %s[%s], <stream:error> is: %s", session.host or "(unknown host)", session.type, tostring(stanza));
session.sends2s(stanza);
elseif reason.name then -- a stanza
log("info", "Disconnecting %s->%s[%s], <stream:error> is: %s", session.from_host or "(unknown host)", session.to_host or "(unknown host)", session.type, tostring(reason));
session.sends2s(reason);
end
end
end
session.sends2s("</stream:stream>");
if sesson.notopen or not session.conn.close() then
session.conn.close(true); -- Force FIXME: timer?
end
session.conn.close();
xmppserver.disconnect(session.conn, "stream error");
end
end
-- End of session methods --
function xmppserver.listener(conn, data)
local session = sessions[conn];
if not session then
session = s2s_new_incoming(conn);
sessions[conn] = session;
-- Logging functions --
local conn_name = "s2sin"..tostring(conn):match("[a-f0-9]+$");
session.log = logger.init(conn_name);
session.log("info", "Incoming s2s connection");
session.reset_stream = session_reset_stream;
session.close = session_close;
session_reset_stream(session); -- Initialise, ready for use
session.dispatch_stanza = stream_callbacks.handlestanza;
end
if data then
session.data(conn, data);
end
end
function xmppserver.status(conn, status)
if status == "ssl-handshake-complete" then
local session = sessions[conn];
if session and session.direction == "outgoing" then
local format, to_host, from_host = string.format, session.to_host, session.from_host;
session.log("debug", "Sending stream header...");
session.sends2s(format([[<stream:stream xmlns='jabber:server' xmlns:db='jabber:server:dialback' xmlns:stream='http://etherx.jabber.org/streams' from='%s' to='%s' version='1.0'>]], from_host, to_host));
end
end
end
function xmppserver.disconnect(conn, err)
local session = sessions[conn];
if session then
if err and err ~= "closed" and session.srv_hosts then
(session.log or log)("debug", "s2s connection closed unexpectedly");
if s2s_attempt_connect(session, err) then
(session.log or log)("debug", "...so we're going to try again");
return; -- Session lives for now
end
end
(session.log or log)("info", "s2s disconnected: %s->%s (%s)", tostring(session.from_host), tostring(session.to_host), tostring(err));
s2s_destroy_session(session);
sessions[conn] = nil;
session = nil;
collectgarbage("collect");
end
end
function xmppserver.register_outgoing(conn, session)
session.direction = "outgoing";
sessions[conn] = session;
session.reset_stream = session_reset_stream;
session.close = session_close;
session_reset_stream(session); -- Initialise, ready for use
--local function handleerr(err) print("Traceback:", err, debug.traceback()); end
--session.stanza_dispatch = function (stanza) return select(2, xpcall(function () return core_process_stanza(session, stanza); end, handleerr)); end
end
connlisteners_register("xmppserver", xmppserver);
-- We need to perform some initialisation when a connection is created
-- We also need to perform that same initialisation at other points (SASL, TLS, ...)
-- ...and we need to handle data
-- ...and record all sessions associated with connections
|
-- 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 logger = require "logger";
local log = logger.init("xmppserver_listener");
local lxp = require "lxp"
local init_xmlhandlers = require "core.xmlhandlers"
local s2s_new_incoming = require "core.s2smanager".new_incoming;
local s2s_streamopened = require "core.s2smanager".streamopened;
local s2s_streamclosed = require "core.s2smanager".streamclosed;
local s2s_destroy_session = require "core.s2smanager".destroy_session;
local s2s_attempt_connect = require "core.s2smanager".attempt_connection;
local stream_callbacks = { stream_tag = "http://etherx.jabber.org/streams|stream",
default_ns = "jabber:server",
streamopened = s2s_streamopened, streamclosed = s2s_streamclosed, handlestanza = core_process_stanza };
function stream_callbacks.error(session, error, data)
if error == "no-stream" then
session:close("invalid-namespace");
else
session.log("debug", "Server-to-server XML parse error: %s", tostring(error));
session:close("xml-not-well-formed");
end
end
local function handleerr(err) log("error", "Traceback[s2s]: %s: %s", tostring(err), debug.traceback()); end
function stream_callbacks.handlestanza(a, b)
xpcall(function () core_process_stanza(a, b) end, handleerr);
end
local connlisteners_register = require "net.connlisteners".register;
local t_insert = table.insert;
local t_concat = table.concat;
local t_concatall = function (t, sep) local tt = {}; for _, s in ipairs(t) do t_insert(tt, tostring(s)); end return t_concat(tt, sep); end
local m_random = math.random;
local format = string.format;
local sessionmanager = require "core.sessionmanager";
local sm_new_session, sm_destroy_session = sessionmanager.new_session, sessionmanager.destroy_session;
local st = require "util.stanza";
local sessions = {};
local xmppserver = { default_port = 5269, default_mode = "*a" };
-- These are session methods --
local function session_reset_stream(session)
-- Reset stream
local parser = lxp.new(init_xmlhandlers(session, stream_callbacks), "|");
session.parser = parser;
session.notopen = true;
function session.data(conn, data)
local ok, err = parser:parse(data);
if ok then return; end
session:close("xml-not-well-formed");
end
return true;
end
local stream_xmlns_attr = {xmlns='urn:ietf:params:xml:ns:xmpp-streams'};
local default_stream_attr = { ["xmlns:stream"] = stream_callbacks.stream_tag:gsub("%|[^|]+$", ""), xmlns = stream_callbacks.default_ns, version = "1.0", id = "" };
local function session_close(session, reason)
local log = session.log or log;
if session.conn then
if session.notopen then
session.sends2s("<?xml version='1.0'?>");
session.sends2s(st.stanza("stream:stream", default_stream_attr):top_tag());
end
if reason then
if type(reason) == "string" then -- assume stream error
log("info", "Disconnecting %s[%s], <stream:error> is: %s", session.host or "(unknown host)", session.type, reason);
session.sends2s(st.stanza("stream:error"):tag(reason, {xmlns = 'urn:ietf:params:xml:ns:xmpp-streams' }));
elseif type(reason) == "table" then
if reason.condition then
local stanza = st.stanza("stream:error"):tag(reason.condition, stream_xmlns_attr):up();
if reason.text then
stanza:tag("text", stream_xmlns_attr):text(reason.text):up();
end
if reason.extra then
stanza:add_child(reason.extra);
end
log("info", "Disconnecting %s[%s], <stream:error> is: %s", session.host or "(unknown host)", session.type, tostring(stanza));
session.sends2s(stanza);
elseif reason.name then -- a stanza
log("info", "Disconnecting %s->%s[%s], <stream:error> is: %s", session.from_host or "(unknown host)", session.to_host or "(unknown host)", session.type, tostring(reason));
session.sends2s(reason);
end
end
end
session.sends2s("</stream:stream>");
if session.notopen or not session.conn.close() then
session.conn.close(true); -- Force FIXME: timer?
end
session.conn.close();
xmppserver.disconnect(session.conn, "stream error");
end
end
-- End of session methods --
function xmppserver.listener(conn, data)
local session = sessions[conn];
if not session then
session = s2s_new_incoming(conn);
sessions[conn] = session;
-- Logging functions --
local conn_name = "s2sin"..tostring(conn):match("[a-f0-9]+$");
session.log = logger.init(conn_name);
session.log("info", "Incoming s2s connection");
session.reset_stream = session_reset_stream;
session.close = session_close;
session_reset_stream(session); -- Initialise, ready for use
session.dispatch_stanza = stream_callbacks.handlestanza;
end
if data then
session.data(conn, data);
end
end
function xmppserver.disconnect(conn, err)
local session = sessions[conn];
if session then
if err and err ~= "closed" and session.srv_hosts then
(session.log or log)("debug", "s2s connection closed unexpectedly");
if s2s_attempt_connect(session, err) then
(session.log or log)("debug", "...so we're going to try again");
return; -- Session lives for now
end
end
(session.log or log)("info", "s2s disconnected: %s->%s (%s)", tostring(session.from_host), tostring(session.to_host), tostring(err));
s2s_destroy_session(session);
sessions[conn] = nil;
session = nil;
collectgarbage("collect");
end
end
function xmppserver.register_outgoing(conn, session)
session.direction = "outgoing";
sessions[conn] = session;
session.reset_stream = session_reset_stream;
session.close = session_close;
session_reset_stream(session); -- Initialise, ready for use
--local function handleerr(err) print("Traceback:", err, debug.traceback()); end
--session.stanza_dispatch = function (stanza) return select(2, xpcall(function () return core_process_stanza(session, stanza); end, handleerr)); end
end
connlisteners_register("xmppserver", xmppserver);
-- We need to perform some initialisation when a connection is created
-- We also need to perform that same initialisation at other points (SASL, TLS, ...)
-- ...and we need to handle data
-- ...and record all sessions associated with connections
|
xmppserver_listener: Fix typo (thanks Jorj)
|
xmppserver_listener: Fix typo (thanks Jorj)
|
Lua
|
mit
|
sarumjanuch/prosody,sarumjanuch/prosody
|
2ff0784f882f5d666c0a9c6502fb34765b8f66ba
|
entities/ui/wheel.lua
|
entities/ui/wheel.lua
|
local Wheel = Class('Wheel')
function Wheel:initialize(parent, props)
self.parent = parent
self.radius = 90
self.inactiveColor = {255, 255, 255}
self.pressColor = {127, 127, 127}
self.position = Vector(0, 0)
self.angle = 0
self.onClicked = function(rotDir) end
for k, prop in pairs(props) do
self[k] = prop
end
self.isPressed = false
self.beganPress = false
self.rotationAccumulator = 0
self.startAngle = self.angle
self.activeRotDirection = "cw"
self.spinMultiplier = .5
end
function Wheel:activate()
self.activated = true
local randDir = love.math.random(0, 1)
if randDir == 0 then
self.activeRotDirection = "cw"
elseif randDir == 1 then
self.activeRotDirection = "ccw"
else
error("Unexpected var for randDir: " .. randDir)
end
end
function Wheel:getPressed(x, y)
return Lume.distance(self.position.x, self.position.y, x, y) <= self.radius
end
function Wheel:update(dt)
end
function Wheel:mousepressed(x, y, mbutton)
self.isPressed = false
if mbutton == 1 and self:getPressed(x, y) then
self.isPressed = true
self.beganPress = true
--self.rotationAccumulator = 0
--self.startAngle = self.angle
end
end
function Wheel:mousemoved(x, y, dx, dy, istouch)
if self.isPressed then
-- makes a good spinning behavior regardless of how far inside or outside of the wheel the mouse is
local dist = Lume.distance(self.position.x, self.position.y, x, y)
local currentAngle = Lume.angle(self.position.x, self.position.y, x, y)
local extrapLength = math.max(self.radius, dist)
local extrapOffset = Vector(math.cos(currentAngle)*extrapLength, math.sin(currentAngle)*extrapLength)
extrapOffset = extrapOffset - Vector(dx, dy)
local prevAngle = Lume.angle(0, 0, extrapOffset.x, extrapOffset.y)
local deltaAngle = (currentAngle - prevAngle)
self:solveAngle(theta)
end
end
function Wheel:solveAngle(deltaAngle)
-- idea: be able to treat the skip from 180deg to -180deg as no big deal
-- fairly hacky
if deltaAngle >= math.pi then
deltaAngle = 2*math.pi - deltaAngle
elseif deltaAngle <= -math.pi then
deltaAngle = -2*math.pi - deltaAngle
end
self.angle = self.angle + deltaAngle
self.rotationAccumulator = self.rotationAccumulator + deltaAngle
if self.rotationAccumulator >= 2*math.pi then
self.rotationAccumulator = self.rotationAccumulator - 2*math.pi
if self.activated and self.activeRotDirection == "cw" then
self.activated = false
self.onClicked("cw")
end
elseif self.rotationAccumulator <= -2*math.pi then
self.rotationAccumulator = self.rotationAccumulator + 2*math.pi
if self.activated and self.activeRotDirection == "ccw" then
self.activated = false
self.onClicked("ccw")
end
end
if self.angle >= 2*math.pi then
self.angle = self.angle - 2*math.pi
elseif self.angle <= -2*math.pi then
self.angle = self.angle + 2*math.pi
end
end
function Wheel:mousereleased(x, y, mbutton)
if mbutton == 1 then
self.isPressed = false
self.beganPress = false
--self.rotationAccumulator = 0
end
end
function Wheel:wheelmoved(x, y)
self:solveAngle(-y * self.spinMultiplier)
end
function Wheel:draw()
love.graphics.setColor(self.inactiveColor)
if self.activated then
love.graphics.setColor(self.pressColor)
end
local angle1Raw, angle2Raw = self.startAngle, self.startAngle + self.rotationAccumulator
local angle1, angle2 = math.min(angle1Raw, angle2Raw), math.max(angle1Raw, angle2Raw)
love.graphics.arc('line', self.position.x, self.position.y, self.radius + 5, angle1, angle2)
love.graphics.circle('line', self.position.x, self.position.y, self.radius)
love.graphics.setColor(self.inactiveColor)
if self.isPressed then
love.graphics.setColor(self.pressColor)
end
local handleX, handleY = self.position.x + math.cos(self.angle)*self.radius, self.position.y + math.sin(self.angle)*self.radius
love.graphics.circle('fill', handleX, handleY , 6)
if self.activated then
local deltaRad
if self.activeRotDirection == "cw" then
deltaRad = math.pi/4
elseif self.activeRotDirection == "ccw" then
deltaRad = -math.pi/4
end
love.graphics.line(handleX, handleY, handleX + math.cos(self.angle+deltaRad)*20, handleY + math.sin(self.angle+deltaRad)*20)
end
--love.graphics.print(math.deg(self.rotationAccumulator), self.position.x, self.position.y)
end
return Wheel
|
local Wheel = Class('Wheel')
function Wheel:initialize(parent, props)
self.parent = parent
self.radius = 90
self.inactiveColor = {255, 255, 255}
self.pressColor = {127, 127, 127}
self.position = Vector(0, 0)
self.angle = 0
self.onClicked = function(rotDir) end
for k, prop in pairs(props) do
self[k] = prop
end
self.isPressed = false
self.beganPress = false
self.rotationAccumulator = 0
self.startAngle = self.angle
self.activeRotDirection = "cw"
self.bindingSpinMultiplier = .5
self.mouseSpinMultiplier = 1
end
function Wheel:activate()
self.activated = true
local randDir = love.math.random(0, 1)
if randDir == 0 then
self.activeRotDirection = "cw"
elseif randDir == 1 then
self.activeRotDirection = "ccw"
else
error("Unexpected var for randDir: " .. randDir)
end
end
function Wheel:getPressed(x, y)
return Lume.distance(self.position.x, self.position.y, x, y) <= self.radius
end
function Wheel:update(dt)
end
function Wheel:mousepressed(x, y, mbutton)
self.isPressed = false
if mbutton == 1 and self:getPressed(x, y) then
self.isPressed = true
self.beganPress = true
--self.rotationAccumulator = 0
--self.startAngle = self.angle
end
end
function Wheel:mousemoved(x, y, dx, dy, istouch)
if self.isPressed then
-- makes a good spinning behavior regardless of how far inside or outside of the wheel the mouse is
local dist = Lume.distance(self.position.x, self.position.y, x, y)
local currentAngle = Lume.angle(self.position.x, self.position.y, x, y)
local extrapLength = math.max(self.radius, dist)
local extrapOffset = Vector(math.cos(currentAngle)*extrapLength, math.sin(currentAngle)*extrapLength)
extrapOffset = extrapOffset - Vector(dx, dy)
local prevAngle = Lume.angle(0, 0, extrapOffset.x, extrapOffset.y)
local deltaAngle = (currentAngle - prevAngle) * self.mouseSpinMultiplier
self:solveAngle(deltaAngle)
end
end
function Wheel:solveAngle(deltaAngle)
-- idea: be able to treat the skip from 180deg to -180deg as no big deal
-- fairly hacky
if deltaAngle >= math.pi then
deltaAngle = 2*math.pi - deltaAngle
elseif deltaAngle <= -math.pi then
deltaAngle = -2*math.pi - deltaAngle
end
self.angle = self.angle + deltaAngle
self.rotationAccumulator = self.rotationAccumulator + deltaAngle
if self.rotationAccumulator >= 2*math.pi then
self.rotationAccumulator = self.rotationAccumulator - 2*math.pi
if self.activated and self.activeRotDirection == "cw" then
self.activated = false
self.onClicked("cw")
end
elseif self.rotationAccumulator <= -2*math.pi then
self.rotationAccumulator = self.rotationAccumulator + 2*math.pi
if self.activated and self.activeRotDirection == "ccw" then
self.activated = false
self.onClicked("ccw")
end
end
if self.angle >= 2*math.pi then
self.angle = self.angle - 2*math.pi
elseif self.angle <= -2*math.pi then
self.angle = self.angle + 2*math.pi
end
end
function Wheel:mousereleased(x, y, mbutton)
if mbutton == 1 then
self.isPressed = false
self.beganPress = false
--self.rotationAccumulator = 0
end
end
function Wheel:wheelmoved(x, y)
self:solveAngle(-y * self.bindingSpinMultiplier)
end
function Wheel:draw()
love.graphics.setColor(self.inactiveColor)
if self.activated then
love.graphics.setColor(self.pressColor)
end
local angle1Raw, angle2Raw = self.startAngle, self.startAngle + self.rotationAccumulator
local angle1, angle2 = math.min(angle1Raw, angle2Raw), math.max(angle1Raw, angle2Raw)
love.graphics.arc('line', self.position.x, self.position.y, self.radius + 5, angle1, angle2)
love.graphics.circle('line', self.position.x, self.position.y, self.radius)
love.graphics.setColor(self.inactiveColor)
if self.isPressed then
love.graphics.setColor(self.pressColor)
end
local handleX, handleY = self.position.x + math.cos(self.angle)*self.radius, self.position.y + math.sin(self.angle)*self.radius
love.graphics.circle('fill', handleX, handleY , 6)
if self.activated then
local deltaRad
if self.activeRotDirection == "cw" then
deltaRad = math.pi/4
elseif self.activeRotDirection == "ccw" then
deltaRad = -math.pi/4
end
love.graphics.line(handleX, handleY, handleX + math.cos(self.angle+deltaRad)*20, handleY + math.sin(self.angle+deltaRad)*20)
end
--love.graphics.print(math.deg(self.rotationAccumulator), self.position.x, self.position.y)
end
return Wheel
|
fixed crash from moving the wheel with mouse
|
fixed crash from moving the wheel with mouse
|
Lua
|
mit
|
Nuthen/ludum-dare-39
|
db34128b952504c0830e47b6a1c3a432378590b8
|
src/xenia/gpu/vulkan/premake5.lua
|
src/xenia/gpu/vulkan/premake5.lua
|
project_root = "../../../.."
include(project_root.."/tools/build")
group("src")
project("xenia-gpu-vulkan")
uuid("717590b4-f579-4162-8f23-0624e87d6cca")
kind("StaticLib")
language("C++")
links({
"vulkan-loader",
"xenia-base",
"xenia-gpu",
"xenia-ui",
"xenia-ui-spirv",
"xenia-ui-vulkan",
"xxhash",
})
defines({
})
includedirs({
project_root.."/third_party/gflags/src",
})
local_platform_files()
files({
"shaders/bin/*.h",
})
-- TODO(benvanik): kill this and move to the debugger UI.
group("src")
project("xenia-gpu-vulkan-trace-viewer")
uuid("86a1dddc-a26a-4885-8c55-cf745225d93e")
kind("WindowedApp")
language("C++")
links({
"gflags",
"imgui",
"vulkan-loader",
"xenia-apu",
"xenia-apu-nop",
"xenia-apu-xaudio2",
"xenia-base",
"xenia-core",
"xenia-cpu",
"xenia-cpu-backend-x64",
"xenia-gpu",
"xenia-gpu-vulkan",
"xenia-hid-nop",
"xenia-hid-winkey",
"xenia-hid-xinput",
"xenia-kernel",
"xenia-ui",
"xenia-ui-spirv",
"xenia-ui-vulkan",
"xenia-vfs",
})
flags({
"WinMain", -- Use WinMain instead of main.
})
defines({
})
includedirs({
project_root.."/third_party/gflags/src",
})
files({
"vulkan_trace_viewer_main.cc",
"../../base/main_"..platform_suffix..".cc",
})
filter("platforms:Windows")
-- Only create the .user file if it doesn't already exist.
local user_file = project_root.."/build/xenia-gpu-vulkan-trace-viewer.vcxproj.user"
if not os.isfile(user_file) then
debugdir(project_root)
debugargs({
"--flagfile=scratch/flags.txt",
"2>&1",
"1>scratch/stdout-trace-viewer.txt",
})
end
group("src")
project("xenia-gpu-vulkan-trace-dump")
uuid("0dd0dd1c-b321-494d-ab9a-6c062f0c65cc")
kind("ConsoleApp")
language("C++")
links({
"gflags",
"imgui",
"vulkan-loader",
"xenia-apu",
"xenia-apu-nop",
"xenia-apu-xaudio2",
"xenia-base",
"xenia-core",
"xenia-cpu",
"xenia-cpu-backend-x64",
"xenia-gpu",
"xenia-gpu-vulkan",
"xenia-hid-nop",
"xenia-hid-winkey",
"xenia-hid-xinput",
"xenia-kernel",
"xenia-ui",
"xenia-ui-spirv",
"xenia-ui-vulkan",
"xenia-vfs",
})
defines({
})
includedirs({
project_root.."/third_party/gflags/src",
})
files({
"vulkan_trace_dump_main.cc",
"../../base/main_"..platform_suffix..".cc",
})
filter("platforms:Windows")
-- Only create the .user file if it doesn't already exist.
local user_file = project_root.."/build/xenia-gpu-vulkan-trace-dump.vcxproj.user"
if not os.isfile(user_file) then
debugdir(project_root)
debugargs({
"--flagfile=scratch/flags.txt",
"2>&1",
"1>scratch/stdout-trace-dump.txt",
})
end
|
project_root = "../../../.."
include(project_root.."/tools/build")
group("src")
project("xenia-gpu-vulkan")
uuid("717590b4-f579-4162-8f23-0624e87d6cca")
kind("StaticLib")
language("C++")
links({
"vulkan-loader",
"xenia-base",
"xenia-gpu",
"xenia-ui",
"xenia-ui-spirv",
"xenia-ui-vulkan",
"xxhash",
})
defines({
})
includedirs({
project_root.."/third_party/gflags/src",
})
local_platform_files()
files({
"shaders/bin/*.h",
})
-- TODO(benvanik): kill this and move to the debugger UI.
group("src")
project("xenia-gpu-vulkan-trace-viewer")
uuid("86a1dddc-a26a-4885-8c55-cf745225d93e")
kind("WindowedApp")
language("C++")
links({
"gflags",
"imgui",
"vulkan-loader",
"xenia-apu",
"xenia-apu-nop",
"xenia-apu-xaudio2",
"xenia-base",
"xenia-core",
"xenia-cpu",
"xenia-cpu-backend-x64",
"xenia-gpu",
"xenia-gpu-vulkan",
"xenia-hid-nop",
"xenia-hid-winkey",
"xenia-hid-xinput",
"xenia-kernel",
"xenia-ui",
"xenia-ui-spirv",
"xenia-ui-vulkan",
"xenia-vfs",
})
flags({
"WinMain", -- Use WinMain instead of main.
})
defines({
})
includedirs({
project_root.."/third_party/gflags/src",
})
files({
"vulkan_trace_viewer_main.cc",
"../../base/main_"..platform_suffix..".cc",
})
filter("platforms:Windows")
-- Only create the .user file if it doesn't already exist.
local user_file = project_root.."/build/xenia-gpu-vulkan-trace-viewer.vcxproj.user"
if not os.isfile(user_file) then
debugdir(project_root)
debugargs({
"--flagfile=scratch/flags.txt",
"2>&1",
"1>scratch/stdout-trace-viewer.txt",
})
end
group("src")
project("xenia-gpu-vulkan-trace-dump")
uuid("0dd0dd1c-b321-494d-ab9a-6c062f0c65cc")
kind("ConsoleApp")
language("C++")
links({
"capstone",
"gflags",
"glslang-spirv",
"imgui",
"libavcodec",
"libavutil",
"snappy",
"spirv-tools",
"vulkan-loader",
"xenia-apu",
"xenia-apu-nop",
"xenia-base",
"xenia-core",
"xenia-cpu",
"xenia-cpu-backend-x64",
"xenia-gpu",
"xenia-gpu-vulkan",
"xenia-hid",
"xenia-hid-nop",
"xenia-kernel",
"xenia-ui",
"xenia-ui-spirv",
"xenia-ui-vulkan",
"xenia-vfs",
"xxhash",
})
defines({
})
includedirs({
project_root.."/third_party/gflags/src",
})
files({
"vulkan_trace_dump_main.cc",
"../../base/main_"..platform_suffix..".cc",
})
filter("platforms:Windows")
-- Only create the .user file if it doesn't already exist.
local user_file = project_root.."/build/xenia-gpu-vulkan-trace-dump.vcxproj.user"
if not os.isfile(user_file) then
debugdir(project_root)
debugargs({
"--flagfile=scratch/flags.txt",
"2>&1",
"1>scratch/stdout-trace-dump.txt",
})
end
|
Fix linux build of the vulkan trace dumper
|
Fix linux build of the vulkan trace dumper
|
Lua
|
bsd-3-clause
|
sephiroth99/xenia,sephiroth99/xenia,sephiroth99/xenia
|
5675e2156ce1ed930817bbd1d114fa7c53404b9a
|
LuaAndCparticipants.lua
|
LuaAndCparticipants.lua
|
-- http://kodomo.fbb.msu.ru/wiki/Main/LuaAndC/Participants
local participants = {
{'Александра Галицина', 'agalicina', 'agalitsyna', },
{'Анна Колупаева', 'kolupaeva', 'AnyaKol', },
{'Александра Бойко', 'boyko.s', 'boykos', },
{'Андрей Сигорских', 'crescent8547', 'CarolusRex8547', },
{'Иван Русинов', 'is_rusinov', 'isrusin', },
{'Игорь Поляков', 'ranhummer', 'RanHum', },
{'Борис Нагаев', 'bnagaev', 'starius',
'https://github.com/LuaAndC/LuaAndC', 'LuaAndC'},
{'Татьяна Шугаева', 'talianash', 'Talianash', 'GlobinDetector-2015' },
{'Дарья Диброва', 'udavdasha', 'udavdasha', },
{'Павел Долгов', '', 'zer0main',
'https://github.com/zer0main/battleship',
'battleship'},
{'Роман Кудрин', 'explover', 'explover', },
{'Анастасия Князева', 'nknjasewa', 'nknjasewa', },
{'Иван Ильницкий', 'ilnitsky', 'ilnitsky', },
{'Наталия Кашко', 'nataliya.kashko', 'natilika', },
{'Дмитрий Пензар', 'darkvampirewolf', 'dmitrypenzar1996'},
{'Злобин Александр', 'alexander.zlobin', 'AlxTheEvil'},
{'Просвиров Кирилл', 'prosvirov.k', 'Akado2009'},
{'Михаил Молдован', 'mikemoldovan', 'mikemoldovan'},
{'Андрей Демкив', 'andrei-demkiv', 'Andrei-demkiv'},
}
local unpack = unpack or table.unpack
print("||Имя, тесты||Github||Учебный проект||")
for _, participant in ipairs(participants) do
local name, kodomo, github, projecturl, projectname =
unpack(participant)
local kodomolink, quizlink
if kodomo then
kodomolink = ('[[http://kodomo.fbb.msu.ru/~%s|%s]]')
:format(kodomo, name)
quizlink = ('[[http://kodomoquiz.tk/admin/user/%s|#]]')
:format(kodomo)
else
kodomolink = name
quizlink = ''
end
local githublink = ('[[https://github.com/%s|%s]]')
:format(github, github)
local projectlink = ''
if projecturl and projectname then
projectlink = ('[[%s|%s]]')
:format(projecturl, projectname)
end
print(("||%s %s||%s||%s||"):format(kodomolink,
quizlink, githublink, projectlink))
end
|
-- http://kodomo.fbb.msu.ru/wiki/Main/LuaAndC/Participants
local participants = {
{'Александра Галицина', 'agalicina', 'agalitsyna', },
{'Анна Колупаева', 'kolupaeva', 'AnyaKol', },
{'Александра Бойко', 'boyko.s', 'boykos', },
{'Андрей Сигорских', 'crescent8547', 'CarolusRex8547', },
{'Иван Русинов', 'is_rusinov', 'isrusin', },
{'Игорь Поляков', 'ranhummer', 'RanHum', },
{'Борис Нагаев', 'bnagaev', 'starius',
'https://github.com/LuaAndC/LuaAndC', 'LuaAndC'},
{'Татьяна Шугаева', 'talianash', 'Talianash',
'https://github.com/Talianash/GlobinDetector-2015',
'GlobinDetector-2015'},
{'Дарья Диброва', 'udavdasha', 'udavdasha', },
{'Павел Долгов', '', 'zer0main',
'https://github.com/zer0main/battleship',
'battleship'},
{'Роман Кудрин', 'explover', 'explover', },
{'Анастасия Князева', 'nknjasewa', 'nknjasewa', },
{'Иван Ильницкий', 'ilnitsky', 'ilnitsky', },
{'Наталия Кашко', 'nataliya.kashko', 'natilika', },
{'Дмитрий Пензар', 'darkvampirewolf', 'dmitrypenzar1996'},
{'Злобин Александр', 'alexander.zlobin', 'AlxTheEvil'},
{'Просвиров Кирилл', 'prosvirov.k', 'Akado2009'},
{'Михаил Молдован', 'mikemoldovan', 'mikemoldovan'},
{'Андрей Демкив', 'andrei-demkiv', 'Andrei-demkiv'},
}
local unpack = unpack or table.unpack
print("||Имя, тесты||Github||Учебный проект||")
for _, participant in ipairs(participants) do
local name, kodomo, github, projecturl, projectname =
unpack(participant)
local kodomolink, quizlink
if kodomo then
kodomolink = ('[[http://kodomo.fbb.msu.ru/~%s|%s]]')
:format(kodomo, name)
quizlink = ('[[http://kodomoquiz.tk/admin/user/%s|#]]')
:format(kodomo)
else
kodomolink = name
quizlink = ''
end
local githublink = ('[[https://github.com/%s|%s]]')
:format(github, github)
local projectlink = ''
if projecturl and projectname then
projectlink = ('[[%s|%s]]')
:format(projecturl, projectname)
end
print(("||%s %s||%s||%s||"):format(kodomolink,
quizlink, githublink, projectlink))
end
|
fix project URL & name (GlobinDetector-2015)
|
fix project URL & name (GlobinDetector-2015)
|
Lua
|
mit
|
LuaAndC/LuaAndC,hbucius/LuaAndC
|
27cccd8d89271e9ba59c1e95560f567b20d67f43
|
deps/base64.lua
|
deps/base64.lua
|
--[[lit-meta
name = "creationix/base64"
description = "A pure lua implemention of base64 using bitop"
tags = {"crypto", "base64", "bitop"}
version = "1.0.0"
license = "MIT"
author = { name = "Tim Caswell" }
]]
local bit = require 'bit'
local rshift = bit.rshift
local lshift = bit.lshift
local bor = bit.bor
local band = bit.band
local char = string.char
local byte = string.byte
local concat = table.concat
local ceil = math.ceil
local codes = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
return function (str)
local parts = {}
local l = ceil(#str / 3)
for i = 1, l do
local o = i * 3
local a, b, c = byte(str, o - 2, o)
parts[i] = char(
-- Higher 6 bits of a
byte(codes, rshift(a, 2) + 1),
-- Lower 2 bits of a + high 4 bits of b
byte(codes, bor(
lshift(band(a, 3), 4),
b and rshift(b, 4) or 0
) + 1),
-- High 4 bits of b + low 2 bits of c
b and byte(codes, bor(
lshift(band(b, 15), 2),
c and rshift(c, 6) or 0
) + 1) or 61, -- 61 is '='
-- Lower 4 bits of c
c and byte(band(c, 63) + 1) or 61 -- 61 is '='
)
end
return concat(parts)
end
|
--[[lit-meta
name = "creationix/base64"
description = "A pure lua implemention of base64 using bitop"
tags = {"crypto", "base64", "bitop"}
version = "1.0.1"
license = "MIT"
author = { name = "Tim Caswell" }
]]
local bit = require 'bit'
local rshift = bit.rshift
local lshift = bit.lshift
local bor = bit.bor
local band = bit.band
local char = string.char
local byte = string.byte
local concat = table.concat
local ceil = math.ceil
local codes = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
local function base64(str)
local parts = {}
local l = ceil(#str / 3)
for i = 1, l do
local o = i * 3
local a, b, c = byte(str, o - 2, o)
parts[i] = char(
-- Higher 6 bits of a
byte(codes, rshift(a, 2) + 1),
-- Lower 2 bits of a + high 4 bits of b
byte(codes, bor(
lshift(band(a, 3), 4),
b and rshift(b, 4) or 0
) + 1),
-- High 4 bits of b + low 2 bits of c
b and byte(codes, bor(
lshift(band(b, 15), 2),
c and rshift(c, 6) or 0
) + 1) or 61, -- 61 is '='
-- Lower 4 bits of c
c and byte(codes, band(c, 63) + 1) or 61 -- 61 is '='
)
end
return concat(parts)
end
assert(base64("") == "")
assert(base64("f") == "Zg==")
assert(base64("fo") == "Zm8=")
assert(base64("foo") == "Zm9v")
assert(base64("foob") == "Zm9vYg==")
assert(base64("fooba") == "Zm9vYmE=")
assert(base64("foobar") == "Zm9vYmFy")
return base64
|
Fix typo in base64 library
|
Fix typo in base64 library
|
Lua
|
apache-2.0
|
luvit/lit,james2doyle/lit,squeek502/lit,zhaozg/lit
|
97511074b234ab00594507d1bf339c56f7787e9a
|
OS/DiskOS/Editors/sfx.lua
|
OS/DiskOS/Editors/sfx.lua
|
--SFX Editor
local sfxobj = require("Libraries.sfx") --The sfx object
local eapi = select(1,...) --The editors api
local sw, sh = screenSize() --The screensize
local volColors = {1,2,13,6,12,14,15,7}
local se = {} --sfx editor
local sfxSlots = 64 --The amount of sfx slots
local sfxNotes = 32 --The number of notes in each sfx
local defaultSpeed = 0.25 --The default speed
local speed = defaultSpeed --The current sfx speed
local selectedSlot = 0
local selectedWave = 0
local playingNote = -1
local pitchGrid = {0,9, sfxNotes*4,12*7, sfxNotes,12*7}
local volumeGrid = {0,sh-8-8*2-1, sfxNotes*4,8*2, sfxNotes,8}
--The SFXes datas.
local sfxdata = {}
for i=0,sfxSlots-1 do
local sfx = sfxobj(sfxNotes, defaultSpeed)
for i=0,sfxNotes-1 do
sfx:setNote(i,1,1,0,0) --Octave 0 is hidden...
end
sfxdata[i] = sfx
end
local patternImage = imagedata("LK12;GPUIMG;2x6;770007700077;")
local pattern2Image = imagedata("LK12;GPUIMG;4x2;00070070;")
local function drawGraph()
local x,y = pitchGrid[1], pitchGrid[2]-1
local x2,y2 = volumeGrid[1], volumeGrid[2]
local sfx = sfxdata[selectedSlot]
--Pitch Rectangle
rect(x,y,pitchGrid[3]+1,pitchGrid[4]+4,false,0)
--Volume Rectangle
rect(x2,y2-1,volumeGrid[3]+1,volumeGrid[4]+2,false,0)
--Horizental Box (Style)
rect(x,y+pitchGrid[4]+4, pitchGrid[3]+1+1, y2-1-y-pitchGrid[4]-4, false, 9)
patternFill(patternImage)
rect(x,y+pitchGrid[4]+4, pitchGrid[3]+1+1, y2-1-y-pitchGrid[4]-4, false, 4)
patternFill()
--Vertical Line (Style)
rect(x+pitchGrid[3]+1,8, 4,sh-16, false, 9)
patternFill(pattern2Image)
rect(x+pitchGrid[3]+1,8, 4,sh-16, false, 4)
patternFill()
local playingNote = math.floor(playingNote)
--Notes lines
for i=0, sfxNotes-1 do
local note,oct,wave,amp = sfx:getNote(i); note = note-1
if wave >= 0 and amp > 0 then
rect(x+1+i*4, y+12*8-(note+oct*12), 2, note+oct*12-9, false, (playingNote == i and 6 or 1))
rect(x+1+i*4, y+12*8-(note+oct*12), 2, 2, false, 8+wave)
end
local vol = math.floor(amp*7)
if wave < 0 then vol = 0 end
rect(x2+1+i*4, y2+(7-vol)*2, 3,2, false, volColors[vol+1])
end
end
local slotLeft, slotLeftDown = {sw-27,15,4,7}, false
local slotRight, slotRightDown = {sw-10,15,4,7}, false
function se:drawSlot()
color(12)
print("SLOT:",sw-54,16)
if slotLeftDown then pal(9,4) end
eapi.editorsheet:draw(164,slotLeft[1],slotLeft[2])
pal()
color(13)
rect(sw-22,15,fontWidth()*2+3,fontHeight()+2, false, 6)
print(selectedSlot, sw-21,16, fontWidth()*2+2, "right")
if slotRightDown then pal(9,4) end
eapi.editorsheet:draw(165,slotRight[1],slotRight[2])
pal()
end
local speedLeft, speedLeftDown = {sw-26,27,4,7}, false
local speedRight, speedRightDown = {sw-9,27,4,7}, false
function se:drawSpeed()
color(7)
print("SPEED:",sw-56,28)
if speedLeftDown then pal(9,4) end
eapi.editorsheet:draw(164,speedLeft[1],speedLeft[2])
pal()
color(13)
rect(sw-21,27,fontWidth()*2+3,fontHeight()+2, false, 6)
print(speed/0.25, sw-20,28, fontWidth()*2+2, "right")
if speedRightDown then pal(9,4) end
eapi.editorsheet:draw(165,speedRight[1],speedRight[2])
pal()
end
function se:entered()
eapi:drawUI()
drawGraph()
self:drawSlot()
self:drawSpeed()
end
function se:leaved()
end
function se:pitchMouse(state,x,y,button,istouch)
local cx,cy = whereInGrid(x,y,pitchGrid)
if cx and isMDown(1) then
local sfx = sfxdata[selectedSlot]
cx, cy = cx-1, 12*8-cy+1
local note = cy%12
local oct = math.floor(cy/12)
local _,_,_,amp = sfx:getNote(cx)
sfx:setNote(cx,note,oct,selectedWave,amp == 0 and 5/7 or amp)
drawGraph()
end
end
function se:volumeMouse(state,x,y,button,istouch)
local cx,cy = whereInGrid(x,y,volumeGrid)
if cx and isMDown(1) then
local sfx = sfxdata[selectedSlot]
local note, oct, wave = sfx:getNote(cx-1)
if wave < 0 and cy < 8 then wave = selectedWave end
sfx:setNote(cx-1,false,false,wave,(8-cy)/7)
drawGraph()
end
end
function se:slotMouse(state,x,y,button,istouch)
if state == "pressed" then
if isInRect(x,y,slotLeft) then
slotLeftDown = true
self:drawSlot()
end
if isInRect(x,y,slotRight) then
slotRightDown = true
self:drawSlot()
end
elseif state == "moved" then
if not isInRect(x,y,slotLeft) and slotLeftDown then
slotLeftDown = false
self:drawSlot()
end
if not isInRect(x,y,slotRight) and slotRightDown then
slotRightDown = false
self:drawSlot()
end
else
if isInRect(x,y,slotLeft) and slotLeftDown then
selectedSlot = math.max(selectedSlot-1,0)
speed = sfxdata[selectedSlot]:getSpeed()
end
slotLeftDown = false
if isInRect(x,y,slotRight) and slotRightDown then
selectedSlot = math.min(selectedSlot+1,sfxSlots-1)
speed = sfxdata[selectedSlot]:getSpeed()
end
slotRightDown = false
drawGraph() self:drawSlot() self:drawSpeed()
end
end
function se:speedMouse(state,x,y,button,istouch)
if state == "pressed" then
if isInRect(x,y,speedLeft) then
speedLeftDown = true
self:drawSpeed()
end
if isInRect(x,y,speedRight) then
speedRightDown = true
self:drawSpeed()
end
elseif state == "moved" then
if not isInRect(x,y,speedLeft) and speedLeftDown then
speedLeftDown = false
self:drawSpeed()
end
if not isInRect(x,y,speedRight) and speedRightDown then
speedRightDown = false
self:drawSpeed()
end
else
if isInRect(x,y,speedLeft) then
speed = math.max(speed-0.25,0.25)
sfxdata[selectedSlot]:setSpeed(speed)
end
speedLeftDown = false
if isInRect(x,y,speedRight) then
speed = math.min(speed+0.25,255*0.25)
sfxdata[selectedSlot]:setSpeed(speed)
end
speedRightDown = false
drawGraph() self:drawSlot() self:drawSpeed()
end
end
se.keymap = {
["space"] = function()
sfxdata[selectedSlot]:play()
playingNote = 0
end
}
function se:update(dt)
if playingNote >= 0 then
playingNote = playingNote + (dt*sfxNotes)/speed
if playingNote >= sfxNotes then
playingNote = -1
end
drawGraph()
end
end
function se:mousepressed(x,y,button,istouch)
self:pitchMouse("pressed",x,y,button,istouch)
self:volumeMouse("pressed",x,y,button,istouch)
self:slotMouse("pressed",x,y,button,istouch)
self:speedMouse("pressed",x,y,button,istouch)
end
function se:mousemoved(x,y,button,istouch)
self:pitchMouse("moved",x,y,dx,dy,istouch)
self:volumeMouse("moved",x,y,dx,dy,istouch)
self:slotMouse("moved",x,y,dx,dy,istouch)
self:speedMouse("moved",x,y,dx,dy,istouch)
end
function se:mousereleased(x,y,button,istouch)
self:pitchMouse("released",x,y,button,istouch)
self:volumeMouse("released",x,y,button,istouch)
self:slotMouse("released",x,y,button,istouch)
self:speedMouse("released",x,y,button,istouch)
end
return se
|
--SFX Editor
local sfxobj = require("Libraries.sfx") --The sfx object
local eapi = select(1,...) --The editors api
local sw, sh = screenSize() --The screensize
local volColors = {1,2,13,6,12,14,15,7}
local se = {} --sfx editor
local sfxSlots = 64 --The amount of sfx slots
local sfxNotes = 32 --The number of notes in each sfx
local defaultSpeed = 0.25 --The default speed
local speed = defaultSpeed --The current sfx speed
local selectedSlot = 0
local selectedWave = 0
local playingNote = -1
local pitchGrid = {0,9, sfxNotes*4,12*7, sfxNotes,12*7}
local volumeGrid = {0,sh-8-8*2-1, sfxNotes*4,8*2, sfxNotes,8}
--The SFXes datas.
local sfxdata = {}
for i=0,sfxSlots-1 do
local sfx = sfxobj(sfxNotes, defaultSpeed)
for i=0,sfxNotes-1 do
sfx:setNote(i,1,1,0,0) --Octave 0 is hidden...
end
sfxdata[i] = sfx
end
local patternImage = imagedata("LK12;GPUIMG;2x6;770007700077;")
local pattern2Image = imagedata("LK12;GPUIMG;4x2;00070070;")
local function drawGraph()
local x,y = pitchGrid[1], pitchGrid[2]-1
local x2,y2 = volumeGrid[1], volumeGrid[2]
local sfx = sfxdata[selectedSlot]
--Pitch Rectangle
rect(x,y,pitchGrid[3]+1,pitchGrid[4]+4,false,0)
--Volume Rectangle
rect(x2,y2-1,volumeGrid[3]+1,volumeGrid[4]+2,false,0)
--Horizental Box (Style)
rect(x,y+pitchGrid[4]+4, pitchGrid[3]+1+1, y2-1-y-pitchGrid[4]-4, false, 9)
patternFill(patternImage)
rect(x,y+pitchGrid[4]+4, pitchGrid[3]+1+1, y2-1-y-pitchGrid[4]-4, false, 4)
patternFill()
--Vertical Line (Style)
rect(x+pitchGrid[3]+1,8, 4,sh-16, false, 9)
patternFill(pattern2Image)
rect(x+pitchGrid[3]+1,8, 4,sh-16, false, 4)
patternFill()
local playingNote = math.floor(playingNote)
--Notes lines
for i=0, sfxNotes-1 do
local note,oct,wave,amp = sfx:getNote(i); note = note-1
if wave >= 0 and amp > 0 then
rect(x+1+i*4, y+12*8-(note+oct*12), 2, note+oct*12-9, false, (playingNote == i and 6 or 1))
rect(x+1+i*4, y+12*8-(note+oct*12), 2, 2, false, 8+wave)
end
local vol = math.floor(amp*7)
if wave < 0 then vol = 0 end
rect(x2+1+i*4, y2+(7-vol)*2, 3,2, false, volColors[vol+1])
end
end
local slotLeft, slotLeftDown = {sw-27,15,4,7}, false
local slotRight, slotRightDown = {sw-10,15,4,7}, false
function se:drawSlot()
color(12)
print("SLOT:",sw-54,16)
if slotLeftDown then pal(9,4) end
eapi.editorsheet:draw(164,slotLeft[1],slotLeft[2])
pal()
color(13)
rect(sw-22,15,fontWidth()*2+3,fontHeight()+2, false, 6)
print(selectedSlot, sw-21,16, fontWidth()*2+2, "right")
if slotRightDown then pal(9,4) end
eapi.editorsheet:draw(165,slotRight[1],slotRight[2])
pal()
end
local speedLeft, speedLeftDown = {sw-26,27,4,7}, false
local speedRight, speedRightDown = {sw-9,27,4,7}, false
function se:drawSpeed()
color(7)
print("SPEED:",sw-56,28)
if speedLeftDown then pal(9,4) end
eapi.editorsheet:draw(164,speedLeft[1],speedLeft[2])
pal()
color(13)
rect(sw-21,27,fontWidth()*2+3,fontHeight()+2, false, 6)
print(speed/0.25, sw-20,28, fontWidth()*2+2, "right")
if speedRightDown then pal(9,4) end
eapi.editorsheet:draw(165,speedRight[1],speedRight[2])
pal()
end
function se:entered()
eapi:drawUI()
drawGraph()
self:drawSlot()
self:drawSpeed()
end
function se:leaved()
end
function se:pitchMouse(state,x,y,button,istouch)
local cx,cy = whereInGrid(x,y,pitchGrid)
if cx and isMDown(1) then
local sfx = sfxdata[selectedSlot]
cx, cy = cx-1, 12*8-cy+1
local note = cy%12
local oct = math.floor(cy/12)
local _,_,_,amp = sfx:getNote(cx)
sfx:setNote(cx,note,oct,selectedWave,amp == 0 and 5/7 or amp)
drawGraph()
end
end
function se:volumeMouse(state,x,y,button,istouch)
local cx,cy = whereInGrid(x,y,volumeGrid)
if cx and isMDown(1) then
local sfx = sfxdata[selectedSlot]
local note, oct, wave = sfx:getNote(cx-1)
if wave < 0 and cy < 8 then wave = selectedWave end
sfx:setNote(cx-1,false,false,wave,(8-cy)/7)
drawGraph()
end
end
function se:slotMouse(state,x,y,button,istouch)
if state == "pressed" then
if isInRect(x,y,slotLeft) then
slotLeftDown = true
self:drawSlot()
end
if isInRect(x,y,slotRight) then
slotRightDown = true
self:drawSlot()
end
elseif state == "moved" then
if not isInRect(x,y,slotLeft) and slotLeftDown then
slotLeftDown = false
self:drawSlot()
end
if not isInRect(x,y,slotRight) and slotRightDown then
slotRightDown = false
self:drawSlot()
end
else
if isInRect(x,y,slotLeft) and slotLeftDown then
selectedSlot = math.max(selectedSlot-1,0)
speed = sfxdata[selectedSlot]:getSpeed()
end
slotLeftDown = false
if isInRect(x,y,slotRight) and slotRightDown then
selectedSlot = math.min(selectedSlot+1,sfxSlots-1)
speed = sfxdata[selectedSlot]:getSpeed()
end
slotRightDown = false
drawGraph() self:drawSlot() self:drawSpeed()
end
end
function se:speedMouse(state,x,y,button,istouch)
if state == "pressed" then
if isInRect(x,y,speedLeft) then
speedLeftDown = true
self:drawSpeed()
end
if isInRect(x,y,speedRight) then
speedRightDown = true
self:drawSpeed()
end
elseif state == "moved" then
if not isInRect(x,y,speedLeft) and speedLeftDown then
speedLeftDown = false
self:drawSpeed()
end
if not isInRect(x,y,speedRight) and speedRightDown then
speedRightDown = false
self:drawSpeed()
end
else
if isInRect(x,y,speedLeft) and speedLeftDown then
speed = math.max(speed-0.25,0.25)
sfxdata[selectedSlot]:setSpeed(speed)
end
speedLeftDown = false
if isInRect(x,y,speedRight) and speedRightDown then
speed = math.min(speed+0.25,255*0.25)
sfxdata[selectedSlot]:setSpeed(speed)
end
speedRightDown = false
drawGraph() self:drawSlot() self:drawSpeed()
end
end
se.keymap = {
["space"] = function()
sfxdata[selectedSlot]:play()
playingNote = 0
end
}
function se:update(dt)
if playingNote >= 0 then
playingNote = playingNote + (dt*sfxNotes)/speed
if playingNote >= sfxNotes then
playingNote = -1
end
drawGraph()
end
end
function se:mousepressed(x,y,button,istouch)
self:pitchMouse("pressed",x,y,button,istouch)
self:volumeMouse("pressed",x,y,button,istouch)
self:slotMouse("pressed",x,y,button,istouch)
self:speedMouse("pressed",x,y,button,istouch)
end
function se:mousemoved(x,y,button,istouch)
self:pitchMouse("moved",x,y,dx,dy,istouch)
self:volumeMouse("moved",x,y,dx,dy,istouch)
self:slotMouse("moved",x,y,dx,dy,istouch)
self:speedMouse("moved",x,y,dx,dy,istouch)
end
function se:mousereleased(x,y,button,istouch)
self:pitchMouse("released",x,y,button,istouch)
self:volumeMouse("released",x,y,button,istouch)
self:slotMouse("released",x,y,button,istouch)
self:speedMouse("released",x,y,button,istouch)
end
return se
|
Bugfix
|
Bugfix
Former-commit-id: 378f4359e983cbad222aa92db6bf9b67385190f9
|
Lua
|
mit
|
RamiLego4Game/LIKO-12
|
acf3d9bbd6e09254116383e899e06e126c4cebeb
|
item/id_258_flail.lua
|
item/id_258_flail.lua
|
-- Dreschflegel ( 258 )
-- Getreidebndel --> Getreidekrner
-- UPDATE common SET com_script='item.id_258_flail' WHERE com_itemid IN (258);
require("item.general.wood")
require("base.common")
require("content.gathering")
module("item.id_258_flail", package.seeall, package.seeall(item.general.wood))
function UseItem( User, SourceItem, TargetItem, Counter, Param, ltstate )
content.gathering.InitGathering();
local farming = content.gathering.farming;
base.common.ResetInterruption( User, ltstate );
if ( ltstate == Action.abort ) then -- Arbeit unterbrochen
if (User:increaseAttrib("sex",0) == 0) then
gText = "seine";
eText = "his";
else
gText = "ihre";
eText = "her";
end
User:talkLanguage(Character.say, Player.german, "#me unterbricht "..gText.." Arbeit.");
User:talkLanguage(Character.say, Player.english,"#me interrupts "..eText.." work.");
return
end
if not base.common.CheckItem( User, SourceItem ) then -- Sicherheitscheck
return
end
if base.common.Encumbrence(User) then -- Durch Steife Rstung behindert
base.common.InformNLS( User,
"Deine Rstung behindert Dich beim Getreide dreschen.",
"Your armour disturbes you when flailing grain" );
return
end
if (SourceItem:getType() ~= 4) then -- Dreschflegel in der Hand
base.common.InformNLS( User,
"Du musst den Dreschflegel in der Hand haben!",
"You need to hold the flail in your hand!" );
return
end
if not base.common.FitForWork( User ) then -- Nicht erschpft
return
end
if not base.common.IsLookingAt( User, TargetItem.pos ) then -- Blickrichtung prfen
base.common.TurnTo( User, TargetItem.pos ); -- notfalls drehen
end
if ( ltstate == Action.none ) then -- Arbeit noch nicht begonnen -> Los gehts
if (User:countItemAt("all",249)==0) then -- Getreidebndel im Grtel
base.common.InformNLS( User,
"Was willst du mit dem Dreschflegel bearbeiten? Dich selbst?",
"What do you want to flail? Yourself?" );
return;
end
farming.SavedWorkTime[User.id] = farming:GenWorkTime(User,nil,true);
User:startAction( farming.SavedWorkTime[User.id], 0, 0, 0, 0);
User:talkLanguage( Character.say, Player.german, "#me beginnt Getreide zu dreschen");
User:talkLanguage( Character.say, Player.english, "#me starts to flail grain");
return
end
if not farming:FindRandomItem(User) then
return
end
if base.common.IsInterrupted( User ) then
local selectMessage = math.random(1,5);
if ( selectMessage == 1 ) then
base.common.InformNLS(User,
"Du wischst dir den Schwei von der Stirn.",
"You wipe sweat off your forehead.");
elseif ( selectMessage == 2 ) then
base.common.InformNLS(User,
"Die Dreschstange des Flegels lst sich und du musst sie erneut festbinden.",
"The flail's chain appears to be stuck, it takes you some time to fix it.");
elseif ( selectMessage == 3 ) then
base.common.InformNLS(User,
"Du schaffst das Stroh weg um wieder mehr Platz zu haben.",
"You tie a few straw bundles together.");
elseif ( selectMessage == 4 ) then
base.common.InformNLS(User,
"Du kehrst kurz die Spreu zusammen und bringst sie weg.",
"You sweep the husk into a pile and carry it away.");
else
base.common.InformNLS(User,
"Deine Hnde brennen wie Feuer, deshalb machst du eine kurze Pause. Hoffentlich gibt das keine Blase...",
"Your arms appear to be getting very tired, you decide on a short break.");
end
return
end
User:learn( farming.LeadSkill, farming.LeadSkillGroup, farming.SavedWorkTime[User.id], 100, User:increaseAttrib(farming.LeadAttribute,0) );
User:eraseItem( 249, 1 ); -- Getreidebndel wegnehmen
amount = GenAmount(User);
local notCreated = User:createItem( 259, amount, 333 ,0); -- Getreidekrner erstellen
if ( amount==0) then
base.common.InformNLS(User,
"Du verschttest etwas Getreide.",
"You spill some grain.");
else
if ( notCreated > 0 ) then -- Zu viele Items erstellt --> Char berladen
world:createItemFromId( 259, notCreated, User.pos, true, 333 ,0);
base.common.InformNLS(User,
"Du kannst nichts mehr halten.",
"You can't carry any more.");
else -- Nicht berladen -> Neue aktion Starten
farming.SavedWorkTime[User.id] = farming:GenWorkTime(User,nil,true);
User:startAction( farming.SavedWorkTime[User.id], 0, 0, 0, 0);
end
end
base.common.GetHungry( User, 200 ); -- Hungrig werden
if base.common.ToolBreaks( User, SourceItem, true ) then -- Dreschflegen beschdigen
base.common.InformNLS(User,
"Dein alter Dreschflegel zerbricht.",
"Your old flail breaks.");
return
end
end
-- Menge der Items die erstellt werden festlegen
function GenAmount(User)
local Skill = User:getSkill( content.gathering.farming.LeadSkill );
local Attrib = User:increaseAttrib( content.gathering.farming.LeadAttribute, 0 );
local chance = math.random( 100 );
if ( chance < (Skill+Attrib) - 10 ) then return 4;
elseif ( chance < (Skill+Attrib) ) then return 3;
elseif ( chance < (Skill+Attrib) + 25 ) then return 2;
elseif ( chance < (Skill+Attrib) + 50 ) then return 1;
end
end
|
-- Dreschflegel ( 258 )
-- Getreidebndel --> Getreidekrner
-- UPDATE common SET com_script='item.id_258_flail' WHERE com_itemid IN (258);
require("item.general.wood")
require("base.common")
require("content.gathering")
module("item.id_258_flail", package.seeall, package.seeall(item.general.wood))
function UseItem( User, SourceItem, TargetItem, Counter, Param, ltstate )
content.gathering.InitGathering();
local farming = content.gathering.farming;
base.common.ResetInterruption( User, ltstate );
if ( ltstate == Action.abort ) then -- Arbeit unterbrochen
if (User:increaseAttrib("sex",0) == 0) then
gText = "seine";
eText = "his";
else
gText = "ihre";
eText = "her";
end
User:talkLanguage(Character.say, Player.german, "#me unterbricht "..gText.." Arbeit.");
User:talkLanguage(Character.say, Player.english,"#me interrupts "..eText.." work.");
return
end
if not base.common.CheckItem( User, SourceItem ) then -- Sicherheitscheck
return
end
if base.common.Encumbrence(User) then -- Durch Steife Rstung behindert
base.common.InformNLS( User,
"Deine Rstung behindert Dich beim Getreide dreschen.",
"Your armour disturbes you when flailing grain" );
return
end
if (SourceItem:getType() ~= 4) then -- Dreschflegel in der Hand
base.common.InformNLS( User,
"Du musst den Dreschflegel in der Hand haben!",
"You need to hold the flail in your hand!" );
return
end
if not base.common.FitForWork( User ) then -- Nicht erschpft
return
end
if not base.common.IsLookingAt( User, TargetItem.pos ) then -- Blickrichtung prfen
base.common.TurnTo( User, TargetItem.pos ); -- notfalls drehen
end
if ( ltstate == Action.none ) then -- Arbeit noch nicht begonnen -> Los gehts
if (User:countItemAt("all",249)==0) then -- Getreidebndel im Grtel
base.common.InformNLS( User,
"Was willst du mit dem Dreschflegel bearbeiten? Dich selbst?",
"What do you want to flail? Yourself?" );
return;
end
farming.SavedWorkTime[User.id] = farming:GenWorkTime(User,nil,true);
User:startAction( farming.SavedWorkTime[User.id], 0, 0, 0, 0);
User:talkLanguage( Character.say, Player.german, "#me beginnt Getreide zu dreschen");
User:talkLanguage( Character.say, Player.english, "#me starts to flail grain");
return
end
if not farming:FindRandomItem(User) then
return
end
if base.common.IsInterrupted( User ) then
local selectMessage = math.random(1,5);
if ( selectMessage == 1 ) then
base.common.InformNLS(User,
"Du wischst dir den Schwei von der Stirn.",
"You wipe sweat off your forehead.");
elseif ( selectMessage == 2 ) then
base.common.InformNLS(User,
"Die Dreschstange des Flegels lst sich und du musst sie erneut festbinden.",
"The flail's chain appears to be stuck, it takes you some time to fix it.");
elseif ( selectMessage == 3 ) then
base.common.InformNLS(User,
"Du schaffst das Stroh weg um wieder mehr Platz zu haben.",
"You tie a few straw bundles together.");
elseif ( selectMessage == 4 ) then
base.common.InformNLS(User,
"Du kehrst kurz die Spreu zusammen und bringst sie weg.",
"You sweep the husk into a pile and carry it away.");
else
base.common.InformNLS(User,
"Deine Hnde brennen wie Feuer, deshalb machst du eine kurze Pause. Hoffentlich gibt das keine Blase...",
"Your arms appear to be getting very tired, you decide on a short break.");
end
return
end
User:learn( farming.LeadSkill, farming.LeadSkillGroup, farming.SavedWorkTime[User.id], 100, User:increaseAttrib(farming.LeadAttribute,0) );
User:eraseItem( 249, 1 ); -- Getreidebndel wegnehmen
amount = GenAmount(User);
local notCreated = User:createItem( 259, amount, 333 ,0); -- Getreidekrner erstellen
if ( amount==0) then
base.common.InformNLS(User,
"Du verschttest etwas Getreide.",
"You spill some grain.");
else
if ( notCreated > 0 ) then -- Zu viele Items erstellt --> Char berladen
world:createItemFromId( 259, notCreated, User.pos, true, 333 ,0);
base.common.InformNLS(User,
"Du kannst nichts mehr halten.",
"You can't carry any more.");
elseif (User:countItemAt("all",249)==0) then -- Nicht berladen -> Neue aktion Starten
farming.SavedWorkTime[User.id] = farming:GenWorkTime(User,nil,true);
User:startAction( farming.SavedWorkTime[User.id], 0, 0, 0, 0);
else
base.common.InformNLS(User,
"Du hast kein Getreidebndel mehr.",
"You have no bundle of grain anymore.");
end
end
base.common.GetHungry( User, 200 ); -- Hungrig werden
if base.common.ToolBreaks( User, SourceItem, true ) then -- Dreschflegen beschdigen
base.common.InformNLS(User,
"Dein alter Dreschflegel zerbricht.",
"Your old flail breaks.");
return
end
end
-- Menge der Items die erstellt werden festlegen
function GenAmount(User)
local Skill = User:getSkill( content.gathering.farming.LeadSkill );
local Attrib = User:increaseAttrib( content.gathering.farming.LeadAttribute, 0 );
local chance = math.random( 100 );
if ( chance < (Skill+Attrib) - 10 ) then return 4;
elseif ( chance < (Skill+Attrib) ) then return 3;
elseif ( chance < (Skill+Attrib) + 25 ) then return 2;
elseif ( chance < (Skill+Attrib) + 50 ) then return 1;
end
return 0;
end
|
fix flailing
|
fix flailing
|
Lua
|
agpl-3.0
|
KayMD/Illarion-Content,LaFamiglia/Illarion-Content,vilarion/Illarion-Content,Baylamon/Illarion-Content,Illarion-eV/Illarion-Content
|
2935d85c0f43bc4abe6b92f90970b0b1ee873366
|
tools/premake/app_template.lua
|
tools/premake/app_template.lua
|
local function add_pmtech_links()
configuration "Debug"
links { "put", "pen" }
configuration "Release"
links { "put", "pen" }
configuration {}
end
local function copy_shared_libs()
configuration "Debug"
postbuildcommands
{
("{COPY} " .. shared_libs_dir .. " %{cfg.targetdir}")
}
configuration "Release"
postbuildcommands
{
("{COPY} " .. shared_libs_dir .. " %{cfg.targetdir}")
}
configuration {}
end
local function setup_osx()
links
{
"Cocoa.framework",
"GameController.framework",
"iconv",
"fmod",
"IOKit.framework"
}
if renderer_dir == "metal" then
links
{
"MetalKit.framework",
"Metal.framework"
}
elseif renderer_dir == "opengl" then
links
{
"OpenGL.framework"
}
end
add_pmtech_links()
copy_shared_libs()
end
local function setup_linux()
--linux must be linked in order
add_pmtech_links()
links
{
"pthread",
"GLEW",
"GLU",
"GL",
"X11",
"fmod"
}
end
local function setup_win32()
if renderer_dir == "vulkan" then
libdirs
{
"$(VK_SDK_PATH)/Lib"
}
links
{
"vulkan-1.lib"
}
elseif renderer_dir == "opengl" then
includedirs
{
pmtech_dir .. "/third_party/glew/include"
}
libdirs
{
pmtech_dir .. "/third_party/glew/lib/win64"
}
links
{
"OpenGL32.lib"
}
else
links
{
"d3d11.lib"
}
end
links
{
"dxguid.lib",
"winmm.lib",
"comctl32.lib",
"fmod64_vc.lib",
"Shlwapi.lib"
}
add_pmtech_links()
systemversion(windows_sdk_version())
disablewarnings { "4800", "4305", "4018", "4244", "4267", "4996" }
end
local function setup_ios()
links
{
"Foundation.framework",
"UIKit.framework",
"QuartzCore.framework",
}
if renderer_dir == "metal" then
links
{
"MetalKit.framework",
"Metal.framework"
}
elseif renderer_dir == "opengl" then
links
{
"OpenGLES.framework",
"GLKit.framework",
}
end
files
{
(pmtech_dir .. "/template/ios/**.*"),
"bin/ios/data"
}
excludes
{
("**.DS_Store")
}
xcodebuildresources
{
"bin/ios/data"
}
end
local function setup_android()
files
{
pmtech_dir .. "/template/android/manifest/**.*",
pmtech_dir .. "/template/android/activity/**.*"
}
androidabis
{
"armeabi-v7a", "x86"
}
end
local function setup_platform()
if platform_dir == "win32" then
setup_win32()
elseif platform_dir == "osx" then
setup_osx()
elseif platform_dir == "ios" then
setup_ios()
elseif platform_dir == "linux" then
setup_linux()
elseif platform_dir == "android" then
setup_android()
end
end
local function setup_bullet()
bullet_lib = "bullet_monolithic"
bullet_lib_debug = "bullet_monolithic_d"
bullet_lib_dir = platform_dir
if _ACTION == "vs2017" or _ACTION == "vs2015" then
bullet_lib_dir = _ACTION
bullet_lib = (bullet_lib)
bullet_lib_debug = (bullet_lib_debug)
end
libdirs
{
(pmtech_dir .. "third_party/bullet/lib/" .. bullet_lib_dir)
}
configuration "Debug"
links { bullet_lib_debug }
configuration "Release"
links { bullet_lib }
configuration {}
end
local function setup_fmod()
libdirs
{
(pmtech_dir .. "third_party/fmod/lib/" .. platform_dir)
}
end
function setup_modules()
setup_bullet()
setup_fmod()
end
function create_app(project_name, source_directory, root_directory)
project ( project_name )
setup_product( project_name )
kind "WindowedApp"
language "C++"
dependson{ "pen", "put" }
includedirs
{
-- core
pmtech_dir .. "source/pen/include",
pmtech_dir .. "source/pen/include/common",
pmtech_dir .. "source/pen/include/" .. platform_dir,
pmtech_dir .. "source/pen/include/" .. renderer_dir,
--utility
pmtech_dir .. "source/put/source/",
-- third party
pmtech_dir .. "third_party/",
"include/",
}
files
{
(root_directory .. "code/" .. source_directory .. "/**.cpp"),
(root_directory .. "code/" .. source_directory .. "/**.c"),
(root_directory .. "code/" .. source_directory .. "/**.h"),
(root_directory .. "code/" .. source_directory .. "/**.m"),
(root_directory .. "code/" .. source_directory .. "/**.mm")
}
setup_env()
setup_platform()
setup_modules()
location (root_directory .. "/build/" .. platform_dir)
targetdir (root_directory .. "/bin/" .. platform_dir)
debugdir (root_directory .. "/bin/" .. platform_dir)
configuration "Release"
defines { "NDEBUG" }
entrypoint "WinMainCRTStartup"
optimize "Speed"
targetname (project_name)
architecture "x64"
libdirs
{
pmtech_dir .. "source/pen/lib/" .. platform_dir .. "/release",
pmtech_dir .. "source/put/lib/" .. platform_dir .. "/release",
}
configuration "Debug"
defines { "DEBUG" }
entrypoint "WinMainCRTStartup"
symbols "On"
targetname (project_name .. "_d")
architecture "x64"
libdirs
{
pmtech_dir .. "source/pen/lib/" .. platform_dir .. "/debug",
pmtech_dir .. "source/put/lib/" .. platform_dir .. "/debug",
}
end
function create_app_example( project_name, root_directory )
create_app( project_name, project_name, root_directory )
end
|
local function add_pmtech_links()
configuration "Debug"
links { "put", "pen" }
configuration "Release"
links { "put", "pen" }
configuration {}
end
local function copy_shared_libs()
configuration "Debug"
postbuildcommands
{
("{COPY} " .. shared_libs_dir .. " %{cfg.targetdir}")
}
configuration "Release"
postbuildcommands
{
("{COPY} " .. shared_libs_dir .. " %{cfg.targetdir}")
}
configuration {}
end
local function setup_osx()
links
{
"Cocoa.framework",
"GameController.framework",
"iconv",
"fmod",
"IOKit.framework"
}
if renderer_dir == "metal" then
links
{
"MetalKit.framework",
"Metal.framework"
}
elseif renderer_dir == "opengl" then
links
{
"OpenGL.framework"
}
end
add_pmtech_links()
copy_shared_libs()
end
local function setup_linux()
--linux must be linked in order
add_pmtech_links()
links
{
"pthread",
"GLEW",
"GLU",
"GL",
"X11",
"fmod"
}
end
local function setup_win32()
if renderer_dir == "vulkan" then
libdirs
{
"$(VK_SDK_PATH)/Lib"
}
links
{
"vulkan-1.lib"
}
elseif renderer_dir == "opengl" then
includedirs
{
pmtech_dir .. "/third_party/glew/include"
}
libdirs
{
pmtech_dir .. "/third_party/glew/lib/win64"
}
links
{
"OpenGL32.lib"
}
else
links
{
"d3d11.lib"
}
end
links
{
"dxguid.lib",
"winmm.lib",
"comctl32.lib",
"fmod64_vc.lib",
"Shlwapi.lib"
}
add_pmtech_links()
systemversion(windows_sdk_version())
disablewarnings { "4800", "4305", "4018", "4244", "4267", "4996" }
end
local function setup_ios()
links
{
"Foundation.framework",
"UIKit.framework",
"QuartzCore.framework",
}
if renderer_dir == "metal" then
links
{
"MetalKit.framework",
"Metal.framework"
}
elseif renderer_dir == "opengl" then
links
{
"OpenGLES.framework",
"GLKit.framework",
}
end
files
{
(pmtech_dir .. "/template/ios/**.*"),
"bin/ios/data"
}
excludes
{
("**.DS_Store")
}
xcodebuildresources
{
"bin/ios/data"
}
end
local function setup_android()
files
{
pmtech_dir .. "/template/android/manifest/**.*",
pmtech_dir .. "/template/android/activity/**.*"
}
androidabis
{
"armeabi-v7a", "x86"
}
end
local function setup_platform()
if platform_dir == "win32" then
setup_win32()
elseif platform_dir == "osx" then
setup_osx()
elseif platform_dir == "ios" then
setup_ios()
elseif platform_dir == "linux" then
setup_linux()
elseif platform_dir == "android" then
setup_android()
end
end
local function setup_bullet()
bullet_lib = "bullet_monolithic"
bullet_lib_debug = "bullet_monolithic_d"
bullet_lib_dir = platform_dir
libdirs
{
(pmtech_dir .. "third_party/bullet/lib/" .. bullet_lib_dir)
}
configuration "Debug"
links { bullet_lib_debug }
configuration "Release"
links { bullet_lib }
configuration {}
end
local function setup_fmod()
libdirs
{
(pmtech_dir .. "third_party/fmod/lib/" .. platform_dir)
}
end
function setup_modules()
setup_bullet()
setup_fmod()
end
function create_app(project_name, source_directory, root_directory)
project ( project_name )
setup_product( project_name )
kind "WindowedApp"
language "C++"
dependson{ "pen", "put" }
includedirs
{
-- core
pmtech_dir .. "source/pen/include",
pmtech_dir .. "source/pen/include/common",
pmtech_dir .. "source/pen/include/" .. platform_dir,
pmtech_dir .. "source/pen/include/" .. renderer_dir,
--utility
pmtech_dir .. "source/put/source/",
-- third party
pmtech_dir .. "third_party/",
"include/",
}
files
{
(root_directory .. "code/" .. source_directory .. "/**.cpp"),
(root_directory .. "code/" .. source_directory .. "/**.c"),
(root_directory .. "code/" .. source_directory .. "/**.h"),
(root_directory .. "code/" .. source_directory .. "/**.m"),
(root_directory .. "code/" .. source_directory .. "/**.mm")
}
setup_env()
setup_platform()
setup_modules()
location (root_directory .. "/build/" .. platform_dir)
targetdir (root_directory .. "/bin/" .. platform_dir)
debugdir (root_directory .. "/bin/" .. platform_dir)
configuration "Release"
defines { "NDEBUG" }
entrypoint "WinMainCRTStartup"
optimize "Speed"
targetname (project_name)
architecture "x64"
libdirs
{
pmtech_dir .. "source/pen/lib/" .. platform_dir .. "/release",
pmtech_dir .. "source/put/lib/" .. platform_dir .. "/release",
}
configuration "Debug"
defines { "DEBUG" }
entrypoint "WinMainCRTStartup"
symbols "On"
targetname (project_name .. "_d")
architecture "x64"
libdirs
{
pmtech_dir .. "source/pen/lib/" .. platform_dir .. "/debug",
pmtech_dir .. "source/put/lib/" .. platform_dir .. "/debug",
}
end
function create_app_example( project_name, root_directory )
create_app( project_name, project_name, root_directory )
end
|
- fix bullet lib dir
|
- fix bullet lib dir
|
Lua
|
mit
|
polymonster/pmtech,polymonster/pmtech,polymonster/pmtech,polymonster/pmtech,polymonster/pmtech,polymonster/pmtech
|
afa1f31486a2f0ed18c900c30bf29698f55ad12a
|
spec/pomelo_spec.lua
|
spec/pomelo_spec.lua
|
require('busted.runner')()
local sleep = require('system').sleep
local pomelo = require('pomelo')
describe('pomelo', function()
describe('.configure()', function()
it('configure library without args', function()
--pomelo.configure()
end)
it('configure library with options', function()
pomelo.configure({log='DISABLE', cafile='cafile', capath='.'})
end)
end)
describe('.version()', function()
it('returns the libpomelo2 version string', function()
local v = pomelo.version()
assert.are.equal('string', type(v))
assert.is.truthy(v:match('^(%d+)%.(%d+)%.(%d+)%-(.+)$'))
end)
end)
describe('.newClient()', function()
it('construct a new client instance with default options', function()
local c = pomelo.newClient({enable_reconn = false})
assert.are.equal('userdata', type(c))
assert.is.truthy(tostring(c):match('Client %(0x[%da-f]+%)'))
end)
it('construct a new client instance with options', function()
local c = pomelo.newClient({
conn_timeout = 30, -- optional, default 30 seconds
enable_reconn = true, -- optional, default true
reconn_max_retry = 3, -- optional, 'ALWAYS' or a positive integer. default 'ALWAYS'
reconn_delay = 2, -- integer, optional, default to 2
reconn_delay_max = 30, -- integer, optional, default to 30
reconn_exp_backoff = true,-- boolean, optional, default to true
transport_name = "TLS" -- 'TCP', 'TLS', 'DUMMY', or an integer id of you customized transport
})
assert.are.equal('userdata', type(c))
assert.is.truthy(tostring(c):match('Client %(0x[%da-f]+%)'))
end)
end)
describe('Client', function()
local c
before_each(function()
c = pomelo.newClient()
end)
after_each(function()
c:close()
sleep(1)
c:poll()
c = nil
end)
describe(':connect()', function()
it('connect to a pomelo server', function()
assert.are.equal('INITED', c:state())
assert.is_true(c:connect('127.0.0.1', 3010))
assert.are.equal('CONNECTING', c:state())
sleep(1)
c:poll()
assert.are.equal('CONNECTED', c:state())
end)
end)
describe(':disconnect() #try', function()
it('connect to a pomelo server', function()
c:connect('127.0.0.5', 3011)
sleep(1)
c:poll()
assert.is_true(c:disconnect())
end)
end)
describe(':request() #req', function()
it('send request to pomelo server', function()
c:connect('127.0.0.1', 3010)
sleep(1)
c:poll()
local callback = spy.new(function()end)
c:request('connector.entryHandler.entry', '{"name": "test"}', 10, callback)
sleep(2)
c:poll()
assert.spy(callback).was.called(1)
assert.spy(callback).was.called_with(
nil,
{route='connector.entryHandler.entry', msg='{"name": "test"}', timeout=10},
'{"code":200,"msg":"game server is ok."}'
)
c:close()
sleep(1)
c:poll()
end)
end)
describe(':notify()', function()
it('send notify to pomelo server', function()
c:connect('127.0.0.1', 3010)
sleep(1)
c:poll()
local s = spy.new(function() end)
c:notify('test.testHandler.notify', '{"content": "test content"}', 10, s)
sleep(2)
c:poll()
assert.spy(s).was.called(1)
end)
end)
describe(':on()', function()
it('adds event listener to client', function()
local s = spy.new(function() end)
c:on('connected', s)
c:connect('127.0.0.1', 3010)
sleep(1)
c:poll()
assert.spy(s).was.called(1)
end)
end)
describe(':addListener()', function()
end)
describe(':once()', function()
end)
describe(':off()', function()
it('removes event listener', function()
local s = spy.new(function() end)
c:on('connected', s)
c:off('connected', s)
sleep(1)
c:poll()
assert.spy(s).was.called(0)
end)
end)
describe(':removeListener()', function()
end)
describe(':listeners()', function()
end)
describe(':config()', function()
it('returns the config of the client', function()
assert.are.same({
reconn_delay = 2,
reconn_delay_max = 30,
reconn_exp_backoff = true,
reconn_max_retry = 'ALWAYS',
transport_name = 'TCP',
conn_timeout = 30,
enable_reconn = true
}, c:config())
local conf = {
reconn_delay = 3,
reconn_delay_max = 15,
reconn_exp_backoff = false,
reconn_max_retry = 4,
transport_name = 'TLS',
conn_timeout = 15,
enable_reconn = true
}
local c2 = pomelo.newClient(conf)
assert.are.same(conf, c2:config())
end)
end)
describe(':state()', function()
it('new created client are in `INITED` state', function()
assert.are.equal('INITED', c:state())
end)
it('new created client are in `INITED` state', function()
c:connect('127.0.0.1', 1234)
assert.are.equal('CONNECTING', c:state())
end)
end)
describe(':conn_quality()', function()
end)
describe(':connQuality()', function()
end)
describe(':poll()', function()
end)
describe(':close()', function()
end)
end)
end)
|
require('busted.runner')()
local sleep = require('system').sleep
local pomelo = require('pomelo')
describe('pomelo', function()
describe('.configure()', function()
it('configure library without args', function()
--pomelo.configure()
end)
it('configure library with options', function()
pomelo.configure({log='DISABLE', cafile='cafile', capath='.'})
end)
end)
describe('.version()', function()
it('returns the libpomelo2 version string', function()
local v = pomelo.version()
assert.are.equal('string', type(v))
assert.is.truthy(v:match('^(%d+)%.(%d+)%.(%d+)%-(.+)$'))
end)
end)
describe('.newClient()', function()
it('construct a new client instance with default options', function()
local c = pomelo.newClient({enable_reconn = false})
assert.are.equal('userdata', type(c))
assert.is.truthy(tostring(c):match('Client %(0x[%da-f]+%)'))
end)
it('construct a new client instance with options', function()
local c = pomelo.newClient({
conn_timeout = 30, -- optional, default 30 seconds
enable_reconn = true, -- optional, default true
reconn_max_retry = 3, -- optional, 'ALWAYS' or a positive integer. default 'ALWAYS'
reconn_delay = 2, -- integer, optional, default to 2
reconn_delay_max = 30, -- integer, optional, default to 30
reconn_exp_backoff = true,-- boolean, optional, default to true
transport_name = "TLS" -- 'TCP', 'TLS', 'DUMMY', or an integer id of you customized transport
})
assert.are.equal('userdata', type(c))
assert.is.truthy(tostring(c):match('Client %(0x[%da-f]+%)'))
end)
end)
describe('Client', function()
local c
before_each(function()
c = pomelo.newClient()
end)
after_each(function()
c:close()
c = nil
end)
describe(':connect()', function()
it('connect to a pomelo server', function()
assert.are.equal('INITED', c:state())
assert.is_true(c:connect('127.0.0.1', 3010))
assert.are.equal('CONNECTING', c:state())
sleep(1)
c:poll()
assert.are.equal('CONNECTED', c:state())
end)
end)
describe(':disconnect() #try', function()
it('connect to a pomelo server', function()
c:connect('127.0.0.5', 3011)
sleep(1)
c:poll()
assert.is_true(c:disconnect())
end)
end)
describe(':request()', function()
it('send request to pomelo server', function()
c:connect('127.0.0.1', 3010)
sleep(1)
c:poll()
local callback = spy.new(function()end)
c:request('connector.entryHandler.entry', '{"name": "test"}', 10, callback)
sleep(2)
c:poll()
assert.spy(callback).was.called(1)
assert.spy(callback).was.called_with(
nil,
{route='connector.entryHandler.entry', msg='{"name": "test"}', timeout=10},
'{"code":200,"msg":"game server is ok."}'
)
end)
end)
describe(':notify()', function()
it('send notify to pomelo server', function()
c:connect('127.0.0.1', 3010)
sleep(1)
c:poll()
local s = spy.new(function() end)
c:notify('test.testHandler.notify', '{"content": "test content"}', 10, s)
sleep(2)
c:poll()
assert.spy(s).was.called(1)
end)
end)
describe(':on()', function()
it('adds event listener to client', function()
local s = spy.new(function() end)
c:on('connected', s)
c:connect('127.0.0.1', 3010)
sleep(1)
c:poll()
c:disconnect()
sleep(1)
c:poll()
c:connect('127.0.0.1', 3010)
sleep(1)
c:poll()
assert.spy(s).was.called(2)
end)
end)
describe(':once()', function()
it('adds event listener to client', function()
local s = spy.new(function() end)
c:once('connected', s)
c:connect('127.0.0.1', 3010)
sleep(1)
c:poll()
c:disconnect()
sleep(1)
c:poll()
c:connect('127.0.0.1', 3010)
sleep(1)
c:poll()
assert.spy(s).was.called(1)
end)
end)
describe(':off()', function()
it('removes event listener', function()
local s = spy.new(function() end)
c:on('connected', s)
c:off('connected', s)
c:connect('127.0.0.1', 3010)
sleep(1)
c:poll()
assert.spy(s).was.called(0)
end)
end)
describe(':listeners()', function()
it('returns emtpy when no listeners registered', function()
assert.are.same({}, c:listeners('connected'))
end)
it('return the array of listeners registered', function()
local function f() end
c:on('connected', f)
assert.are.same({f}, c:listeners('connected'))
end)
it('return the array of listeners registered', function()
local function f() end
c:on('connected', f)
assert.are.same({f}, c:listeners('connected'))
end)
end)
describe(':config()', function()
it('returns the config of the client', function()
assert.are.same({
reconn_delay = 2,
reconn_delay_max = 30,
reconn_exp_backoff = true,
reconn_max_retry = 'ALWAYS',
transport_name = 'TCP',
conn_timeout = 30,
enable_reconn = true
}, c:config())
local conf = {
reconn_delay = 3,
reconn_delay_max = 15,
reconn_exp_backoff = false,
reconn_max_retry = 4,
transport_name = 'TLS',
conn_timeout = 15,
enable_reconn = true
}
local c2 = pomelo.newClient(conf)
assert.are.same(conf, c2:config())
end)
end)
describe(':state()', function()
it('new created client are in `INITED` state', function()
assert.are.equal('INITED', c:state())
end)
it('new created client are in `INITED` state', function()
c:connect('127.0.0.1', 1234)
assert.are.equal('CONNECTING', c:state())
end)
end)
describe(':conn_quality()', function()
end)
describe(':connQuality()', function()
end)
describe(':poll()', function()
end)
describe(':close()', function()
end)
end)
end)
|
Fixes and add more tests.
|
Fixes and add more tests.
|
Lua
|
mit
|
xpol/lua-pomelo
|
0060125b03ceb5c31d57a4bed4cadeaf98140785
|
src/FileManager.lua
|
src/FileManager.lua
|
--==================================================================================================
-- Copyright (C) 2014 - 2015 by Robert Machmer =
-- =
-- Permission is hereby granted, free of charge, to any person obtaining a copy =
-- of this software and associated documentation files (the "Software"), to deal =
-- in the Software without restriction, including without limitation the rights =
-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell =
-- copies of the Software, and to permit persons to whom the Software is =
-- furnished to do so, subject to the following conditions: =
-- =
-- The above copyright notice and this permission notice shall be included in =
-- all copies or substantial portions of the Software. =
-- =
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR =
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, =
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE =
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER =
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, =
-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN =
-- THE SOFTWARE. =
--==================================================================================================
local FileManager = {};
-- ------------------------------------------------
-- Local Variables
-- ------------------------------------------------
local extensions = {};
-- ------------------------------------------------
-- Local Functions
-- ------------------------------------------------
---
-- Splits the extension from a file.
-- @param fileName
--
local function splitExtension(fileName)
local pos = fileName:find('%.');
if pos then
return fileName:sub(pos);
else
-- Prevents issues with files sans extension.
return '.?';
end
end
-- ------------------------------------------------
-- Public Functions
-- ------------------------------------------------
---
-- Draws a list of all authors working on the project.
--
function FileManager.draw()
local count = 0;
for ext, tbl in pairs(extensions) do
count = count + 1;
love.graphics.setColor(tbl.color);
love.graphics.print(ext, love.graphics.getWidth() - 80, 100 + count * 20);
love.graphics.print(tbl.amount, love.graphics.getWidth() - 120, 100 + count * 20);
love.graphics.setColor(255, 255, 255);
end
end
---
-- Adds a new file extension to the list.
-- @param fileName
--
function FileManager.add(fileName)
local ext = splitExtension(fileName);
if not extensions[ext] then
extensions[ext] = {};
extensions[ext].amount = 0;
extensions[ext].color = { love.math.random(0, 255), love.math.random(0, 255), love.math.random(0, 255) };
end
extensions[ext].amount = extensions[ext].amount + 1;
return extensions[ext].color;
end
---
-- Reduce the amount of counted files of the
-- same extension. If there are no more files
-- of that extension, it will remove it from
-- the list.
--
function FileManager.remove(fileName)
local ext = splitExtension(fileName);
if not extensions[ext] then
error('Tried to remove the non existing file extension "' .. ext .. '".');
end
extensions[ext].amount = extensions[ext].amount - 1;
if extensions[ext].amount == 0 then
extensions[ext] = nil;
end
end
-- ------------------------------------------------
-- Getters
-- ------------------------------------------------
---
-- @param ext
--
function FileManager.getColor(ext)
return extensions[ext].color;
end
-- ------------------------------------------------
-- Return Module
-- ------------------------------------------------
return FileManager;
|
--==================================================================================================
-- Copyright (C) 2014 - 2015 by Robert Machmer =
-- =
-- Permission is hereby granted, free of charge, to any person obtaining a copy =
-- of this software and associated documentation files (the "Software"), to deal =
-- in the Software without restriction, including without limitation the rights =
-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell =
-- copies of the Software, and to permit persons to whom the Software is =
-- furnished to do so, subject to the following conditions: =
-- =
-- The above copyright notice and this permission notice shall be included in =
-- all copies or substantial portions of the Software. =
-- =
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR =
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, =
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE =
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER =
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, =
-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN =
-- THE SOFTWARE. =
--==================================================================================================
local FileManager = {};
-- ------------------------------------------------
-- Local Variables
-- ------------------------------------------------
local extensions = {};
-- ------------------------------------------------
-- Local Functions
-- ------------------------------------------------
---
-- Splits the extension from a file.
-- @param fileName
--
local function splitExtension(fileName)
local tmp = fileName:reverse();
local pos = tmp:find('%.');
if pos then
return tmp:sub(1, pos):reverse();
else
-- Prevents issues with files sans extension.
return '.?';
end
end
-- ------------------------------------------------
-- Public Functions
-- ------------------------------------------------
---
-- Draws a list of all authors working on the project.
--
function FileManager.draw()
local count = 0;
for ext, tbl in pairs(extensions) do
count = count + 1;
love.graphics.setColor(tbl.color);
love.graphics.print(ext, love.graphics.getWidth() - 80, 100 + count * 20);
love.graphics.print(tbl.amount, love.graphics.getWidth() - 120, 100 + count * 20);
love.graphics.setColor(255, 255, 255);
end
end
---
-- Adds a new file extension to the list.
-- @param fileName
--
function FileManager.add(fileName)
local ext = splitExtension(fileName);
if not extensions[ext] then
extensions[ext] = {};
extensions[ext].amount = 0;
extensions[ext].color = { love.math.random(0, 255), love.math.random(0, 255), love.math.random(0, 255) };
end
extensions[ext].amount = extensions[ext].amount + 1;
return extensions[ext].color;
end
---
-- Reduce the amount of counted files of the
-- same extension. If there are no more files
-- of that extension, it will remove it from
-- the list.
--
function FileManager.remove(fileName)
local ext = splitExtension(fileName);
if not extensions[ext] then
error('Tried to remove the non existing file extension "' .. ext .. '".');
end
extensions[ext].amount = extensions[ext].amount - 1;
if extensions[ext].amount == 0 then
extensions[ext] = nil;
end
end
-- ------------------------------------------------
-- Getters
-- ------------------------------------------------
---
-- @param ext
--
function FileManager.getColor(ext)
return extensions[ext].color;
end
-- ------------------------------------------------
-- Return Module
-- ------------------------------------------------
return FileManager;
|
Fix #3 - Only use the end of a filename as an extension.
|
Fix #3 - Only use the end of a filename as an extension.
We simply reverse the filename and find the first full stop from behind.
Since we can assume this to be the file's extension, we cut it off
and re-reverse it.
|
Lua
|
mit
|
rm-code/logivi
|
e27e98705619b45b32d026f64b80562442e97378
|
build/scripts/Torque6.lua
|
build/scripts/Torque6.lua
|
project "Torque6"
targetname "Torque6"
language "C++"
kind "SharedLib"
includedirs {
"../../engine/lib/assimp/include",
"../../engine/lib/bgfx/include",
"../../engine/lib/bgfx/3rdparty",
"../../engine/lib/bgfx/common",
"../../engine/Lib/LeapSDK/include",
"../../engine/Lib/zlib",
"../../engine/Lib/lpng",
"../../engine/Lib/ljpeg",
"../../engine/Lib/openal/win32",
"../../engine/source",
"../../engine/source/persistence/rapidjson/include",
"../../engine/source/persistence/libjson",
"../../engine/source/testing/googleTest",
"../../engine/source/testing/googleTest/include",
"../../engine/source/spine",
}
files {
"../../engine/source/**.h",
"../../engine/source/**.cc",
"../../engine/source/**.cpp",
"../../engine/source/**.asm",
"../../engine/source/**.c",
}
removefiles {
"../../engine/source/exe/**",
"../../engine/source/graphics/bitmapPvr.cc",
"../../engine/source/persistence/rapidjson/example/**",
"../../engine/source/persistence/rapidjson/test/**",
"../../engine/source/persistence/rapidjson/thirdparty/**",
"../../engine/source/platform/**.unix.cc",
"../../engine/source/platformAndroid/**",
"../../engine/source/platformEmscripten/**",
"../../engine/source/platformiOS/**",
"../../engine/source/platformOSX/**",
"../../engine/source/platformWin32/**",
"../../engine/source/testing/googleTest/**",
"../../engine/source/console/runtimeClassRep.cc",
}
libdirs { "$(DXSDK_DIR)/Lib/x86",
"../../engine/lib/LeapSDK/lib/x86" }
links {
"assimp",
"bgfx",
"ljpeg",
"lpng",
"zlib",
}
configuration "Debug"
targetname "Torque6_DEBUG"
defines { "TORQUE_DEBUG",
"TORQUE_ENABLE_PROFILER",
"TORQUE_DEBUG_GUARD",
}
flags { "Symbols" }
configuration "Release"
defines { }
configuration "vs*"
defines { "_CRT_SECURE_NO_WARNINGS", "UNICODE" }
flags { "NoNativeWChar" }
buildoptions { "/wd4100", "/wd4800" }
includedirs { "../../engine/lib/bgfx/include/compat/msvc", }
configuration "windows"
targetdir "../bin/windows"
links { "Leapd",
"COMCTL32",
"COMDLG32",
"USER32",
"ADVAPI32",
"GDI32",
"RPCRT4",
"WINMM",
"WSOCK32",
"vfw32",
"Imm32",
"unicows",
"shell32",
"shlwapi",
"ole32",
}
configuration "linux"
targetdir "../bin/linux"
links { "dl" }
removefiles {
"../../engine/source/input/leapMotion/**",
"../../engine/source/platformX86UNIX/x86UNIXDedicatedStub.cc"
}
configuration "bsd"
targetdir "../bin/bsd"
configuration "linux or bsd"
defines { }
links { "m" }
linkoptions { "-rdynamic" }
buildoptions { "-fpermissive" }
configuration "macosx"
targetdir "../bin/darwin"
defines { }
links { "CoreServices.framework" }
configuration { "macosx", "gmake" }
buildoptions { "-mmacosx-version-min=10.4" }
linkoptions { "-mmacosx-version-min=10.4" }
|
project "Torque6"
targetname "Torque6"
language "C++"
kind "SharedLib"
includedirs {
"../../engine/lib/assimp/include",
"../../engine/lib/bgfx/include",
"../../engine/lib/bgfx/3rdparty",
"../../engine/lib/bgfx/common",
"../../engine/Lib/LeapSDK/include",
"../../engine/Lib/zlib",
"../../engine/Lib/lpng",
"../../engine/Lib/ljpeg",
"../../engine/Lib/openal/win32",
"../../engine/source",
"../../engine/source/persistence/rapidjson/include",
"../../engine/source/persistence/libjson",
"../../engine/source/testing/googleTest",
"../../engine/source/testing/googleTest/include",
"../../engine/source/spine",
}
files {
"../../engine/source/**.h",
"../../engine/source/**.cc",
"../../engine/source/**.cpp",
"../../engine/source/**.asm",
"../../engine/source/**.c",
}
removefiles {
"../../engine/source/exe/**",
"../../engine/source/graphics/bitmapPvr.cc",
"../../engine/source/persistence/rapidjson/example/**",
"../../engine/source/persistence/rapidjson/test/**",
"../../engine/source/persistence/rapidjson/thirdparty/**",
"../../engine/source/platform/**.unix.cc",
"../../engine/source/testing/googleTest/**",
"../../engine/source/console/runtimeClassRep.cc",
}
libdirs { "$(DXSDK_DIR)/Lib/x86",
"../../engine/lib/LeapSDK/lib/x86" }
links {
"assimp",
"bgfx",
"ljpeg",
"lpng",
"zlib",
}
configuration "Debug"
targetname "Torque6_DEBUG"
defines { "TORQUE_DEBUG",
"TORQUE_ENABLE_PROFILER",
"TORQUE_DEBUG_GUARD",
}
flags { "Symbols" }
configuration "Release"
defines { }
configuration "vs*"
defines { "_CRT_SECURE_NO_WARNINGS", "UNICODE" }
flags { "NoNativeWChar" }
buildoptions { "/wd4100", "/wd4800" }
includedirs { "../../engine/lib/bgfx/include/compat/msvc", }
configuration "windows"
targetdir "../bin/windows"
links { "Leapd",
"COMCTL32",
"COMDLG32",
"USER32",
"ADVAPI32",
"GDI32",
"RPCRT4",
"WINMM",
"WSOCK32",
"vfw32",
"Imm32",
"unicows",
"shell32",
"shlwapi",
"ole32",
}
removefiles {
"../../engine/source/platform/**.unix.cc",
"../../engine/source/platformAndroid/**",
"../../engine/source/platformEmscripten/**",
"../../engine/source/platformiOS/**",
"../../engine/source/platformOSX/**",
"../../engine/source/platformX86UNIX/**",
}
configuration "linux"
targetdir "../bin/linux"
links { "dl" }
removefiles {
"../../engine/source/input/leapMotion/**",
"../../engine/source/platformX86UNIX/x86UNIXDedicatedStub.cc"
"../../engine/source/platform/**.unix.cc",
"../../engine/source/platformAndroid/**",
"../../engine/source/platformEmscripten/**",
"../../engine/source/platformiOS/**",
"../../engine/source/platformOSX/**",
"../../engine/source/platformWin32/**",
}
configuration "bsd"
targetdir "../bin/bsd"
configuration "linux or bsd"
defines { }
links { "m" }
linkoptions { "-rdynamic" }
buildoptions { "-fpermissive" }
configuration "macosx"
targetdir "../bin/darwin"
defines { }
links { "CoreServices.framework" }
configuration { "macosx", "gmake" }
buildoptions { "-mmacosx-version-min=10.4" }
linkoptions { "-mmacosx-version-min=10.4" }
|
Fix windows builds from previous commit.
|
Fix windows builds from previous commit.
|
Lua
|
mit
|
lukaspj/Torque6,ktotheoz/Torque6,andr3wmac/Torque6,andr3wmac/Torque6,ktotheoz/Torque6,lukaspj/Torque6,JeffProgrammer/Torque6,ktotheoz/Torque6,ktotheoz/Torque6,RichardRanft/Torque6,RichardRanft/Torque6,RichardRanft/Torque6,lukaspj/Torque6,andr3wmac/Torque6,ktotheoz/Torque6,RichardRanft/Torque6,RichardRanft/Torque6,JeffProgrammer/Torque6,lukaspj/Torque6,JeffProgrammer/Torque6,lukaspj/Torque6,JeffProgrammer/Torque6,JeffProgrammer/Torque6,JeffProgrammer/Torque6,JeffProgrammer/Torque6,andr3wmac/Torque6,andr3wmac/Torque6,lukaspj/Torque6,lukaspj/Torque6,andr3wmac/Torque6,RichardRanft/Torque6,RichardRanft/Torque6,JeffProgrammer/Torque6,andr3wmac/Torque6,lukaspj/Torque6,ktotheoz/Torque6,ktotheoz/Torque6,RichardRanft/Torque6,andr3wmac/Torque6,ktotheoz/Torque6,ktotheoz/Torque6
|
8795bbfb1709c532d7827301a5124275a8c373f0
|
loadcaffe_wrapper.lua
|
loadcaffe_wrapper.lua
|
local ffi = require 'ffi'
require 'loadcaffe'
local C = loadcaffe.C
--[[
Most of this function is copied from
https://github.com/szagoruyko/loadcaffe/blob/master/loadcaffe.lua
with some horrible horrible hacks added by Justin Johnson to
make it possible to load VGG-19 without any CUDA dependency.
--]]
local function loadcaffe_load(prototxt_name, binary_name, backend)
local backend = backend or 'nn'
local handle = ffi.new('void*[1]')
-- loads caffe model in memory and keeps handle to it in ffi
local old_val = handle[1]
C.loadBinary(handle, prototxt_name, binary_name)
if old_val == handle[1] then return end
-- transforms caffe prototxt to torch lua file model description and
-- writes to a script file
local lua_name = prototxt_name..'.lua'
-- C.loadBinary creates a .lua source file that builds up a table
-- containing the layers of the network. As a horrible dirty hack,
-- we'll modify this file when backend "nn-cpu" is requested by
-- doing the following:
--
-- (1) Delete the lines that import cunn and inn, which are always
-- at lines 2 and 4
local model = nil
if backend == 'nn-cpu' then
C.convertProtoToLua(handle, lua_name, 'nn')
local lua_name_cpu = prototxt_name..'.cpu.lua'
local fin = assert(io.open(lua_name), 'r')
local fout = assert(io.open(lua_name_cpu, 'w'))
local line_num = 1
while true do
local line = fin:read('*line')
if line == nil then break end
if line_num ~= 2 and line_num ~= 4 then
fout:write(line, '\n')
end
line_num = line_num + 1
end
fin:close()
fout:close()
model = dofile(lua_name_cpu)
else
C.convertProtoToLua(handle, lua_name, backend)
model = dofile(lua_name)
end
-- goes over the list, copying weights from caffe blobs to torch tensor
local net = nn.Sequential()
local list_modules = model
for i,item in ipairs(list_modules) do
item[2].name = item[1]
if item[2].weight then
local w = torch.FloatTensor()
local bias = torch.FloatTensor()
C.loadModule(handle, item[1], w:cdata(), bias:cdata())
if backend == 'ccn2' then
w = w:permute(2,3,4,1)
end
item[2].weight:copy(w)
item[2].bias:copy(bias)
end
net:add(item[2])
end
C.destroyBinary(handle)
if backend == 'cudnn' or backend == 'ccn2' then
net:cuda()
end
return net
end
return {
load = loadcaffe_load
}
|
local ffi = require 'ffi'
require 'loadcaffe'
local C = loadcaffe.C
--[[
Most of this function is copied from
https://github.com/szagoruyko/loadcaffe/blob/master/loadcaffe.lua
with some horrible horrible hacks added by Justin Johnson to
make it possible to load VGG-19 without any CUDA dependency.
--]]
local function loadcaffe_load(prototxt_name, binary_name, backend)
local backend = backend or 'nn'
local handle = ffi.new('void*[1]')
-- loads caffe model in memory and keeps handle to it in ffi
local old_val = handle[1]
C.loadBinary(handle, prototxt_name, binary_name)
if old_val == handle[1] then return end
-- transforms caffe prototxt to torch lua file model description and
-- writes to a script file
local lua_name = prototxt_name..'.lua'
-- C.loadBinary creates a .lua source file that builds up a table
-- containing the layers of the network. As a horrible dirty hack,
-- we'll modify this file when backend "nn-cpu" is requested by
-- doing the following:
--
-- (1) Delete the lines that import cunn and inn, which are always
-- at lines 2 and 4
local model = nil
if backend == 'nn-cpu' then
C.convertProtoToLua(handle, lua_name, 'nn')
local lua_name_cpu = prototxt_name..'.cpu.lua'
local fin = assert(io.open(lua_name), 'r')
local fout = assert(io.open(lua_name_cpu, 'w'))
local line_num = 1
while true do
local line = fin:read('*line')
if line == nil then break end
fout:write(line, '\n')
line_num = line_num + 1
end
fin:close()
fout:close()
model = dofile(lua_name_cpu)
else
C.convertProtoToLua(handle, lua_name, backend)
model = dofile(lua_name)
end
-- goes over the list, copying weights from caffe blobs to torch tensor
local net = nn.Sequential()
local list_modules = model
for i,item in ipairs(list_modules) do
item[2].name = item[1]
if item[2].weight then
local w = torch.FloatTensor()
local bias = torch.FloatTensor()
C.loadModule(handle, item[1], w:cdata(), bias:cdata())
if backend == 'ccn2' then
w = w:permute(2,3,4,1)
end
item[2].weight:copy(w)
item[2].bias:copy(bias)
end
net:add(item[2])
end
C.destroyBinary(handle)
if backend == 'cudnn' or backend == 'ccn2' then
net:cuda()
end
return net
end
return {
load = loadcaffe_load
}
|
fix loadcaffe_wrapper to work again in CPU mode
|
fix loadcaffe_wrapper to work again in CPU mode
|
Lua
|
mit
|
neilpanchal/neural-style,PaniniGelato/neural-style,zerolocker/neural-style,jcjohnson/neural-style,napsternxg/neural-style,VaKonS/neural-style,ksemianov/neural-style,shenyunhang/neural-style,n1ckfg/neural-style,waythe/neural-style,zerolocker/neural-style
|
2abf3edb10320fe9353b43620137536ab51eb315
|
core/hyphenator-liang.lua
|
core/hyphenator-liang.lua
|
local function addPattern(h, p)
local t = h.trie;
bits = SU.splitUtf8(p)
for i = 1,#bits do char = bits[i]
if not char:find("%d") then
if not(t[char]) then t[char] = {} end
t = t[char]
end
end
t["_"] = {};
local lastWasDigit = 0
for i = 1,#bits do char = bits[i]
if char:find("%d") then
lastWasDigit = 1
table.insert(t["_"], tonumber(char))
elseif lastWasDigit == 1 then
lastWasDigit = 0
else
table.insert(t["_"], 0)
end
end
end
local function registerException(h, exc)
local k = exc:gsub("-", "")
h.exceptions[k] = { }
j = 1
for i=1,#exc do
j = j + 1
if exc[i] == "-" then
j = j - 1
h.exceptions[k][j] = 1
else
h.exceptions[k][j] = 0
end
end
end
function loadPatterns(h, language)
SILE.languageSupport.loadLanguage(language)
local languageset = SILE.hyphenator.languages[language];
if not (languageset) then
print("No patterns for language "..language)
return
end
for _,pat in pairs(languageset.patterns) do addPattern(h, pat) end
if not languageset.exceptions then languageset.exceptions = {} end
for _,exc in pairs(languageset.exceptions) do
registerException(h, exc)
end
end
function _hyphenate(self, w)
if string.len(w) < self.minWord then return {w} end
local points = self.exceptions[w:lower()]
local word = SU.splitUtf8(w)
if not points then
points = SU.map(function()return 0 end, word)
local work = SU.map(string.lower, word)
table.insert(work, ".")
table.insert(work, 1, ".")
table.insert(points, 1, 0)
for i = 1, #work do
local t = self.trie
for j = i, #work do
if not t[work[j]] then break end
t = t[work[j]]
local p = t["_"]
if p then
for k = 1, #p do
if points[i+k - 2] and points[i+k -2] < p[k] then
points[i+k -2] = p[k]
end
end
end
end
end
-- Still inside the no-exceptions case
for i = 1,self.leftmin do points[i] = 0 end
for i = #points-self.rightmin,#points do points[i] = 0 end
end
local pieces = {""}
for i = 1,#word do
pieces[#pieces] = pieces[#pieces] .. word[i]
if points[1+i] and 1 == (points[1+i] % 2) then table.insert(pieces, "") end
end
return pieces
end
SILE.hyphenator = {}
SILE.hyphenator.languages = {};
_hyphenators = {};
local initHyphenator = function (lang)
if not _hyphenators[lang] then
_hyphenators[lang] = {minWord = 5, leftmin = 2, rightmin = 2, trie = {}, exceptions = {} };
loadPatterns(_hyphenators[lang], lang)
end
end
local hyphenateNode = function(n)
if not n:isNnode() or not n.text then return {n} end
initHyphenator(n.language)
local breaks = _hyphenate(_hyphenators[n.language],n.text);
if #breaks > 1 then
local newnodes = {}
for j, b in ipairs(breaks) do
if not(b=="") then
for _,nn in pairs(SILE.shaper:createNnodes(b, n.options)) do
if nn:isNnode() then
nn.parent = n
table.insert(newnodes, nn)
end
end
if not (j == #breaks) then
d = SILE.nodefactory.newDiscretionary({ prebreak = SILE.shaper:createNnodes(SILE.settings.get("font.hyphenchar"), n.options) })
d.parent = n
table.insert(newnodes, d)
--table.insert(newnodes, SILE.nodefactory.newPenalty({ value = SILE.settings.get("typesetter.hyphenpenalty") }))
end
end
end
n.children = newnodes
n.hyphenated = false
n.done = false
return newnodes
end
return {n}
end
showHyphenationPoints = function (word, language)
language = language or "en"
initHyphenator(language)
return SU.concat(_hyphenate(_hyphenators[language], word), SILE.settings.get("font.hyphenchar"))
end
SILE.hyphenate = function (nodelist)
local newlist = {}
for i = 1,#nodelist do
local n = nodelist[i]
local newnodes = hyphenateNode(n)
for j=1,#newnodes do newlist[#newlist+1] = newnodes[j] end
end
return newlist
end
SILE.registerCommand("hyphenator:add-exceptions", function (o,c)
local language = o.lang or SILE.settings.get("document.language")
SILE.languageSupport.loadLanguage(language)
initHyphenator(language)
for token in SU.gtoke(c[1]) do
if token.string then
registerException(_hyphenators[language],token.string)
end
end
end)
|
local function addPattern(h, p)
local t = h.trie;
bits = SU.splitUtf8(p)
for i = 1,#bits do char = bits[i]
if not char:find("%d") then
if not(t[char]) then t[char] = {} end
t = t[char]
end
end
t["_"] = {};
local lastWasDigit = 0
for i = 1,#bits do char = bits[i]
if char:find("%d") then
lastWasDigit = 1
table.insert(t["_"], tonumber(char))
elseif lastWasDigit == 1 then
lastWasDigit = 0
else
table.insert(t["_"], 0)
end
end
end
local function registerException(h, exc)
local a = SU.splitUtf8(exc)
local k = exc:gsub("-", "")
h.exceptions[k] = { }
j = 1
for i=1,#a do
j = j + 1
if a[i] == "-" then
j = j - 1
h.exceptions[k][j] = 1
else
h.exceptions[k][j] = 0
end
end
end
function loadPatterns(h, language)
SILE.languageSupport.loadLanguage(language)
local languageset = SILE.hyphenator.languages[language];
if not (languageset) then
print("No patterns for language "..language)
return
end
for _,pat in pairs(languageset.patterns) do addPattern(h, pat) end
if not languageset.exceptions then languageset.exceptions = {} end
for _,exc in pairs(languageset.exceptions) do
registerException(h, exc)
end
end
function _hyphenate(self, w)
if string.len(w) < self.minWord then return {w} end
local points = self.exceptions[w:lower()]
local word = SU.splitUtf8(w)
if not points then
points = SU.map(function()return 0 end, word)
local work = SU.map(string.lower, word)
table.insert(work, ".")
table.insert(work, 1, ".")
table.insert(points, 1, 0)
for i = 1, #work do
local t = self.trie
for j = i, #work do
if not t[work[j]] then break end
t = t[work[j]]
local p = t["_"]
if p then
for k = 1, #p do
if points[i+k - 2] and points[i+k -2] < p[k] then
points[i+k -2] = p[k]
end
end
end
end
end
-- Still inside the no-exceptions case
for i = 1,self.leftmin do points[i] = 0 end
for i = #points-self.rightmin,#points do points[i] = 0 end
end
local pieces = {""}
for i = 1,#word do
pieces[#pieces] = pieces[#pieces] .. word[i]
if points[1+i] and 1 == (points[1+i] % 2) then table.insert(pieces, "") end
end
return pieces
end
SILE.hyphenator = {}
SILE.hyphenator.languages = {};
_hyphenators = {};
local initHyphenator = function (lang)
if not _hyphenators[lang] then
_hyphenators[lang] = {minWord = 5, leftmin = 2, rightmin = 2, trie = {}, exceptions = {} };
loadPatterns(_hyphenators[lang], lang)
end
end
local hyphenateNode = function(n)
if not n:isNnode() or not n.text then return {n} end
initHyphenator(n.language)
local breaks = _hyphenate(_hyphenators[n.language],n.text);
if #breaks > 1 then
local newnodes = {}
for j, b in ipairs(breaks) do
if not(b=="") then
for _,nn in pairs(SILE.shaper:createNnodes(b, n.options)) do
if nn:isNnode() then
nn.parent = n
table.insert(newnodes, nn)
end
end
if not (j == #breaks) then
d = SILE.nodefactory.newDiscretionary({ prebreak = SILE.shaper:createNnodes(SILE.settings.get("font.hyphenchar"), n.options) })
d.parent = n
table.insert(newnodes, d)
--table.insert(newnodes, SILE.nodefactory.newPenalty({ value = SILE.settings.get("typesetter.hyphenpenalty") }))
end
end
end
n.children = newnodes
n.hyphenated = false
n.done = false
return newnodes
end
return {n}
end
showHyphenationPoints = function (word, language)
language = language or "en"
initHyphenator(language)
return SU.concat(_hyphenate(_hyphenators[language], word), SILE.settings.get("font.hyphenchar"))
end
SILE.hyphenate = function (nodelist)
local newlist = {}
for i = 1,#nodelist do
local n = nodelist[i]
local newnodes = hyphenateNode(n)
for j=1,#newnodes do newlist[#newlist+1] = newnodes[j] end
end
return newlist
end
SILE.registerCommand("hyphenator:add-exceptions", function (o,c)
local language = o.lang or SILE.settings.get("document.language")
SILE.languageSupport.loadLanguage(language)
initHyphenator(language)
for token in SU.gtoke(c[1]) do
if token.string then
registerException(_hyphenators[language],token.string)
end
end
end)
|
Use Unicode aware function when splitting string
|
Use Unicode aware function when splitting string
Fixes #346
|
Lua
|
mit
|
simoncozens/sile,neofob/sile,alerque/sile,neofob/sile,simoncozens/sile,simoncozens/sile,neofob/sile,alerque/sile,alerque/sile,simoncozens/sile,alerque/sile,neofob/sile
|
d6a4d7103e42e54671ee603f497f3027ed62fae1
|
mods/mobs_mc/wolf.lua
|
mods/mobs_mc/wolf.lua
|
--MCmobs v0.2
--maikerumine
--made for MC like Survival game
--License for code WTFPL and otherwise stated in readmes
--dofile(minetest.get_modpath("mobs").."/api.lua")
--###################
--################### WOLF
--###################
--[[
mobs:register_mob("mobs_mc:33wolf", {
type = "animal",
passive = true,
runaway = true,
stepheight = 1.2,
hp_min = 30,
hp_max = 60,
armor = 150,
collisionbox = {-0.35, -0.01, -0.35, 0.35, 2, 0.35},
rotate = -180,
visual = "mesh",
mesh = "wolf.b3d",
textures = {
{"wolf.png"},
},
visual_size = {x=3, y=3},
walk_velocity = 2,
run_velocity = 4,
jump = true,
animation = {
speed_normal = 50, speed_run = 100,
stand_start = 40, stand_end = 45,
walk_start = 0, walk_end = 40,
run_start = 0, run_end = 40,
},
})
mobs:register_egg("mobs_mc:33wolf", "Wolf", "wolf_inv.png", 0)
]]
-- Dog
mobs:register_mob("mobs_mc:dog", {
type = "npc",
passive = true,
hp_min = 55,
hp_max = 75,
collisionbox = {-0.4, -0.01, -0.4, 0.4, 1, 0.4},
rotate = -180,
visual = "mesh",
mesh = "wolf.b3d",
textures = {
{"mobs_dog.png"},
},
makes_footstep_sound = true,
sounds = {
war_cry = "mobs_wolf_attack",
},
view_range = 15,
stepheight = 1.1,
owner = "",
order = "follow",
floats = {x=0,y=0,z=0},
walk_velocity = 4,
run_velocity = 4,
stepheight = 1.1,
damage = 3,
group_attack = true,
armor = 100,
attacks_monsters = true,
attack_type = "dogfight",
drops = {
{name = "mobs:meat_raw",
chance = 1,
min = 2,
max = 3,},
},
drawtype = "front",
water_damage = 0,
lava_damage = 5,
light_damage = 0,
on_rightclick = function(self, clicker)
local item = clicker:get_wielded_item()
if item:get_name() == "mobs:meat_raw" then
local hp = self.object:get_hp()
if hp + 4 > self.hp_max then return end
if not minetest.setting_getbool("creative_mode") then
item:take_item()
clicker:set_wielded_item(item)
end
self.object:set_hp(hp+4)
else
if self.owner == "" then
self.owner = clicker:get_player_name()
else
local formspec = "size[8,4]"
formspec = formspec .. "textlist[2.85,0;2.1,0.5;dialog;What can I do for you?]"
formspec = formspec .. "button_exit[1,1;2,2;dfollow;follow]"
formspec = formspec .. "button_exit[5,1;2,2;dstand;stand]"
formspec = formspec .. "button_exit[0,2;4,4;dfandp;follow and protect]"
formspec = formspec .. "button_exit[4,2;4,4;dsandp;stand and protect]"
formspec = formspec .. "button_exit[1,2;2,2;dgohome; go home]"
formspec = formspec .. "button_exit[5,2;2,2;dsethome; sethome]"
minetest.show_formspec(clicker:get_player_name(), "order", formspec)
minetest.register_on_player_receive_fields(function(clicker, formname, fields)
if fields.dfollow then
self.order = "follow"
self.attacks_monsters = false
end
if fields.dstand then
self.order = "stand"
self.attacks_monsters = false
end
if fields.dfandp then
self.order = "follow"
self.attacks_monsters = true
end
if fields.dsandp then
self.order = "stand"
self.attacks_monsters = true
end
if fields.dsethome then
self.floats = self.object:getpos()
end
if fields.dgohome then
if self.floats then
self.order = "stand"
self.object:setpos(self.floats)
end
end
end)
end
end
end,
animation = {
speed_normal = 20,
speed_run = 30,
stand_start = 10,
stand_end = 20,
walk_start = 75,
walk_end = 100,
run_start = 100,
run_end = 130,
punch_start = 135,
punch_end = 155,
},
jump = true,
step = 1,
blood_texture = "mobs_blood.png",
})
-- Wolf by KrupnoPavel
mobs:register_mob("mobs_mc:wolf", {
type = "npc",
hp_min = 55,
hp_max = 75,
passive = false,
group_attack = true,
collisionbox = {-0.4, -0.01, -0.4, 0.4, 1, 0.4},
rotate = -180,
visual = "mesh",
mesh = "wolf.b3d",
textures = {
{"wolf.png"},
},
makes_footstep_sound = true,
sounds = {
war_cry = "mobs_wolf_attack",
},
view_range = 7,
walk_velocity = 2,
run_velocity = 3,
stepheight = 1.1,
damage = 3,
armor = 200,
attack_type = "dogfight",
drops = {
{name = "mobs:meat_raw",
chance = 1,
min = 2,
max = 3,},
},
drawtype = "front",
water_damage = 0,
lava_damage = 5,
light_damage = 0,
on_rightclick = function(self, clicker)
tool = clicker:get_wielded_item()
local dog
local ent
if tool:get_name() == "mobs:meat_raw" then
clicker:get_inventory():remove_item("main", "mobs:meat_raw")
dog = minetest.add_entity(self.object:getpos(), "mobs_mc:dog")
ent = dog:get_luaentity()
ent.owner = clicker:get_player_name()
self.object:remove()
end
end,
animation = {
speed_normal = 20,
speed_run = 30,
stand_start = 10,
stand_end = 20,
walk_start = 75,
walk_end = 100,
run_start = 100,
run_end = 130,
punch_start = 135,
punch_end = 155,
},
jump = true,
attacks_monsters = true,
step = 0.5,
blood_texture = "mobs_blood.png",
})
mobs:register_spawn("mobs_mc:wolf", {"default:dirt_with_grass","default:dirt","default:snow", "default:snowblock"}, 20, 0, 19000, 1, 31000)
-- compatibility
mobs:alias_mob("mobs:wolf", "mobs_mc:wolf")
mobs:alias_mob("mobs:dog", "mobs_mc:dog")
mobs:alias_mob("esmobs:wolf", "mobs_mc:wolf")
mobs:alias_mob("esmobs:dog", "mobs_mc:dog")
-- spawn eggs
--mobs:register_egg("mobs_mc:wolf", "Wolf", "wool_grey.png", 1)
--mobs:register_egg("mobs_mc:dog", "Dog", "wool_brown.png", 1)
mobs:register_egg("mobs_mc:wolf", "Wolf", "wolf_inv.png", 0)
if minetest.setting_get("log_mods") then
minetest.log("action", "MC Wolf loaded")
end
|
--MCmobs v0.4
--maikerumine
--made for MC like Survival game
--License for code WTFPL and otherwise stated in readmes
--dofile(minetest.get_modpath("mobs").."/api.lua")
--###################
--################### WOLF
--###################
--[[
mobs:register_mob("mobs_mc:33wolf", {
type = "animal",
passive = true,
runaway = true,
stepheight = 1.2,
hp_min = 30,
hp_max = 60,
armor = 150,
collisionbox = {-0.35, -0.01, -0.35, 0.35, 2, 0.35},
rotate = -180,
visual = "mesh",
mesh = "wolf.b3d",
textures = {
{"wolf.png"},
},
visual_size = {x=3, y=3},
walk_velocity = 2,
run_velocity = 4,
jump = true,
animation = {
speed_normal = 50, speed_run = 100,
stand_start = 40, stand_end = 45,
walk_start = 0, walk_end = 40,
run_start = 0, run_end = 40,
},
})
mobs:register_egg("mobs_mc:33wolf", "Wolf", "wolf_inv.png", 0)
]]
-- Dog
mobs:register_mob("mobs_mc:dog", {
type = "npc",
passive = true,
hp_min = 55,
hp_max = 75,
collisionbox = {-0.4, -0.01, -0.4, 0.4, 1, 0.4},
rotate = -180,
visual = "mesh",
mesh = "wolf.b3d",
textures = {
{"mobs_dog.png"},
},
visual_size = {x=3, y=3},
makes_footstep_sound = true,
sounds = {
war_cry = "mobs_wolf_attack",
},
view_range = 15,
stepheight = 1.1,
owner = "",
order = "follow",
floats = {x=0,y=0,z=0},
walk_velocity = 4,
run_velocity = 4,
stepheight = 1.1,
damage = 3,
group_attack = true,
armor = 100,
attacks_monsters = true,
attack_type = "dogfight",
drops = {
{name = "mobs:meat_raw",
chance = 1,
min = 2,
max = 3,},
},
drawtype = "front",
water_damage = 0,
lava_damage = 5,
light_damage = 0,
on_rightclick = function(self, clicker)
local item = clicker:get_wielded_item()
if item:get_name() == "mobs:meat_raw" then
local hp = self.object:get_hp()
if hp + 4 > self.hp_max then return end
if not minetest.setting_getbool("creative_mode") then
item:take_item()
clicker:set_wielded_item(item)
end
self.object:set_hp(hp+4)
else
if self.owner == "" then
self.owner = clicker:get_player_name()
else
local formspec = "size[8,4]"
formspec = formspec .. "textlist[2.85,0;2.1,0.5;dialog;What can I do for you?]"
formspec = formspec .. "button_exit[1,1;2,2;dfollow;follow]"
formspec = formspec .. "button_exit[5,1;2,2;dstand;stand]"
formspec = formspec .. "button_exit[0,2;4,4;dfandp;follow and protect]"
formspec = formspec .. "button_exit[4,2;4,4;dsandp;stand and protect]"
formspec = formspec .. "button_exit[1,2;2,2;dgohome; go home]"
formspec = formspec .. "button_exit[5,2;2,2;dsethome; sethome]"
minetest.show_formspec(clicker:get_player_name(), "order", formspec)
minetest.register_on_player_receive_fields(function(clicker, formname, fields)
if fields.dfollow then
self.order = "follow"
self.attacks_monsters = false
end
if fields.dstand then
self.order = "stand"
self.attacks_monsters = false
end
if fields.dfandp then
self.order = "follow"
self.attacks_monsters = true
end
if fields.dsandp then
self.order = "stand"
self.attacks_monsters = true
end
if fields.dsethome then
self.floats = self.object:getpos()
end
if fields.dgohome then
if self.floats then
self.order = "stand"
self.object:setpos(self.floats)
end
end
end)
end
end
end,
animation = {
speed_normal = 20,
speed_run = 30,
stand_start = 10,
stand_end = 20,
walk_start = 75,
walk_end = 100,
run_start = 100,
run_end = 130,
punch_start = 135,
punch_end = 155,
},
jump = true,
step = 1,
blood_texture = "mobs_blood.png",
})
-- Wolf by KrupnoPavel
mobs:register_mob("mobs_mc:wolf", {
type = "npc",
hp_min = 55,
hp_max = 75,
passive = false,
group_attack = true,
collisionbox = {-0.4, -0.01, -0.4, 0.4, 1, 0.4},
rotate = -180,
visual = "mesh",
mesh = "wolf.b3d",
textures = {
{"wolf.png"},
},
visual_size = {x=3, y=3},
makes_footstep_sound = true,
sounds = {
war_cry = "mobs_wolf_attack",
},
view_range = 7,
walk_velocity = 2,
run_velocity = 3,
stepheight = 1.1,
damage = 3,
armor = 200,
attack_type = "dogfight",
drops = {
{name = "mobs:meat_raw",
chance = 1,
min = 2,
max = 3,},
},
drawtype = "front",
water_damage = 0,
lava_damage = 5,
light_damage = 0,
on_rightclick = function(self, clicker)
tool = clicker:get_wielded_item()
local dog
local ent
if tool:get_name() == "mobs:meat_raw" then
clicker:get_inventory():remove_item("main", "mobs:meat_raw")
dog = minetest.add_entity(self.object:getpos(), "mobs_mc:dog")
ent = dog:get_luaentity()
ent.owner = clicker:get_player_name()
self.object:remove()
end
end,
animation = {
speed_normal = 20,
speed_run = 30,
stand_start = 10,
stand_end = 20,
walk_start = 75,
walk_end = 100,
run_start = 100,
run_end = 130,
punch_start = 135,
punch_end = 155,
},
jump = true,
attacks_monsters = true,
step = 0.5,
blood_texture = "mobs_blood.png",
})
mobs:register_spawn("mobs_mc:wolf", {"default:dirt_with_grass","default:dirt","default:snow", "default:snowblock"}, 20, 0, 19000, 1, 31000)
-- compatibility
mobs:alias_mob("mobs:wolf", "mobs_mc:wolf")
mobs:alias_mob("mobs:dog", "mobs_mc:dog")
mobs:alias_mob("esmobs:wolf", "mobs_mc:wolf")
mobs:alias_mob("esmobs:dog", "mobs_mc:dog")
-- spawn eggs
--mobs:register_egg("mobs_mc:wolf", "Wolf", "wool_grey.png", 1)
--mobs:register_egg("mobs_mc:dog", "Dog", "wool_brown.png", 1)
mobs:register_egg("mobs_mc:wolf", "Wolf", "wolf_inv.png", 0)
if minetest.setting_get("log_mods") then
minetest.log("action", "MC Wolf loaded")
end
|
fix size
|
fix size
|
Lua
|
lgpl-2.1
|
maikerumine/grieftest
|
3fa18d019a2b8ac34cbd6483e62e6f76c9aa7c62
|
src/lua/lluv/poll_zmq.lua
|
src/lua/lluv/poll_zmq.lua
|
local uv = require "lluv"
local ut = require "lluv.utils"
-- This allows do not load zmq library
-- and we can use only OO interface of socket object
local ZMQ_POLLIN = 1
local uv_poll_zmq = ut.class() do
function uv_poll_zmq:__init(s)
self._s = s
self._h = uv.poll_socket(s:fd())
return self
end
local function on_poll(self, err, cb, events)
if err then cb(self, err, self._s) else
while self._h:active() and not self._s:closed() do
local ok, err = self._s:has_event(events)
if ok == nil then cb(self, err, self._s) break end
if ok then cb(self, nil, self._s) else break end
end
end
if self._s:closed() then self._h:close() end
end
function uv_poll_zmq:start(events, cb)
if not cb then cb, events = events end
events = events or ZMQ_POLLIN
self._h:start(function(handle, err) on_poll(self, err, cb, events) end)
-- For `inproc` socket without this call socket never get in signal state.
local ok, err = self._s:has_event(events)
if ok == nil then
-- context already terminated
uv.defer(on_poll, self, err, cb, events)
elseif ok then
-- socket already has events
uv.defer(on_poll, self, nil, cb, events)
end
return self
end
function uv_poll_zmq:stop()
self._h:stop()
return self
end
function uv_poll_zmq:close(...)
self._h:close(...)
return self
end
end
return setmetatable({},{
__call = function(_, ...)
return uv_poll_zmq.new(...)
end;
})
|
local uv = require "lluv"
local ut = require "lluv.utils"
-- This allows do not load zmq library
-- and we can use only OO interface of socket object
local ZMQ_POLLIN = 1
local uv_poll_zmq = ut.class() do
function uv_poll_zmq:__init(s)
self._s = s
self._h = uv.poll_socket(s:fd())
return self
end
local function on_poll(self, err, events)
if err then cb(self, err, self._s) else
while self._read_cb and self._h:active() and not self._s:closed() do
local ok, err = self._s:has_event(events)
if ok == nil then self._read_cb(self, err, self._s) break end
if ok then self._read_cb(self, nil, self._s) else break end
end
end
if self._s:closed() then self._h:close() end
end
function uv_poll_zmq:start(events, cb)
if not cb then cb, events = events end
events = events or ZMQ_POLLIN
self._read_cb = cb
self._h:start(function(handle, err) on_poll(self, err, events) end)
-- For `inproc` socket without this call socket never get in signal state.
local ok, err = self._s:has_event(events)
if ok == nil then
-- context already terminated
uv.defer(on_poll, self, err, events)
elseif ok then
-- socket already has events
uv.defer(on_poll, self, nil, events)
end
return self
end
function uv_poll_zmq:stop()
self._h:stop()
self._read_cb = nil
return self
end
function uv_poll_zmq:close(...)
self._h:close(...)
return self
end
end
return setmetatable({},{
__call = function(_, ...)
return uv_poll_zmq.new(...)
end;
})
|
Fix. Allow restart poll from callback with different poll cb
|
Fix. Allow restart poll from callback with different poll cb
```Lua
poller:start(function()
poller:start(function()
end)
end)
```
|
Lua
|
mit
|
moteus/lua-lluv-poll-zmq
|
0a711097eddab99648e2f5f360619b6452a5e397
|
packages/verbatim.lua
|
packages/verbatim.lua
|
SILE.registerCommand("verbatim:font", function(options, content)
SILE.settings.set("font.family", "Monaco")
SILE.settings.set("font.size", SILE.settings.get("font.size") - 3)
end, "The font chosen for the verbatim environment")
SILE.registerCommand("verbatim", function(options, content)
SILE.typesetter:pushVglue({ height = SILE.length.new({ length = 6 }) })
SILE.typesetter:leaveHmode()
SILE.settings.temporarily(function()
SILE.settings.set("typesetter.parseppattern", "\n")
SILE.settings.set("document.rskip", SILE.nodefactory.newGlue("0 plus 10000pt"))
SILE.settings.set("document.parindent", SILE.nodefactory.newGlue("0"))
SILE.settings.set("current.parindent", SILE.nodefactory.newGlue("0"))
SILE.settings.set("document.baselineskip", SILE.nodefactory.newVglue("0"))
SILE.settings.set("document.lineskip", SILE.nodefactory.newVglue("2pt"))
SILE.settings.set("document.spaceskip", SILE.length.parse("1en"))
SILE.call("verbatim:font")
SILE.settings.set("document.language", "xx")
SILE.settings.set("shaper.spacepattern", '%s')
SILE.process(content)
end)
SILE.typesetter:pushVglue({ height = SILE.length.new({ length = 6 }) })
end, "Typesets its contents in a monospaced font.")
return [[\begin{document}
The \code{verbatim} package is useful when quoting pieces of computer code and
other text for which formatting is significant. It changes SILE’s settings
so that text is set ragged right, with no hyphenation, no indentation and
regular spacing. It tells SILE to honor multiple spaces, and sets a monospaced
font.
\note{Despite the name, \code{verbatim} does not alter the way that SILE
sees special characters. You still need to escape backslashes and braces:
to produce a backslash, you need to write \code{\\\\}.}
Here is some text set in the verbatim environment:
\begin{verbatim}
function SILE.repl()
if not SILE._repl then SILE.initRepl() end
SILE._repl:run()
end
\end{verbatim}
If you want to specify what font the verbatim environment should use, you
can redefine the \code{verbatim:font} command. The current document says:
\begin{verbatim}
<define command="verbatim:font">
<font family="DejaVu Sans Mono" size="9pt"/>
</define>
\end{verbatim}
\end{document}]]
|
SILE.registerCommand("verbatim:font", function(options, content)
SILE.settings.set("font.family", "Monaco")
SILE.settings.set("font.size", SILE.settings.get("font.size") - 3)
end, "The font chosen for the verbatim environment")
SILE.registerCommand("verbatim", function(options, content)
SILE.typesetter:pushVglue({ height = SILE.length.new({ length = 6 }) })
SILE.typesetter:leaveHmode()
SILE.settings.temporarily(function()
SILE.settings.set("typesetter.parseppattern", "\n")
SILE.settings.set("document.rskip", SILE.nodefactory.newGlue("0 plus 10000pt"))
SILE.settings.set("document.parindent", SILE.nodefactory.newGlue("0"))
SILE.settings.set("current.parindent", SILE.nodefactory.newGlue("0"))
SILE.settings.set("document.baselineskip", SILE.nodefactory.newVglue("0"))
SILE.settings.set("document.lineskip", SILE.nodefactory.newVglue("2pt"))
SILE.call("verbatim:font")
SILE.settings.set("document.spaceskip", SILE.length.parse("1en"))
SILE.settings.set("document.language", "xx")
SILE.settings.set("shaper.spacepattern", '%s')
SILE.process(content)
end)
SILE.typesetter:pushVglue({ height = SILE.length.new({ length = 6 }) })
end, "Typesets its contents in a monospaced font.")
return [[\begin{document}
The \code{verbatim} package is useful when quoting pieces of computer code and
other text for which formatting is significant. It changes SILE’s settings
so that text is set ragged right, with no hyphenation, no indentation and
regular spacing. It tells SILE to honor multiple spaces, and sets a monospaced
font.
\note{Despite the name, \code{verbatim} does not alter the way that SILE
sees special characters. You still need to escape backslashes and braces:
to produce a backslash, you need to write \code{\\\\}.}
Here is some text set in the verbatim environment:
\begin{verbatim}
function SILE.repl()
if not SILE._repl then SILE.initRepl() end
SILE._repl:run()
end
\end{verbatim}
If you want to specify what font the verbatim environment should use, you
can redefine the \code{verbatim:font} command. The current document says:
\begin{verbatim}
<define command="verbatim:font">
<font family="DejaVu Sans Mono" size="9pt"/>
</define>
\end{verbatim}
\end{document}]]
|
Fixes #132.
|
Fixes #132.
|
Lua
|
mit
|
neofob/sile,anthrotype/sile,simoncozens/sile,alerque/sile,simoncozens/sile,simoncozens/sile,neofob/sile,alerque/sile,neofob/sile,anthrotype/sile,neofob/sile,alerque/sile,anthrotype/sile,simoncozens/sile,anthrotype/sile,alerque/sile
|
3629e97d1a293ea0b3db39188b61e4c8691a70ec
|
init.lua
|
init.lua
|
local init = {}
function init.getfiles()
print("initializing files...")
local repo = nil
for line in io.lines(os.getenv("PWD") .. "/init.files") do
if repo == nil then
repo = line
print("repo " .. repo)
else
print("getting " .. line)
os.execute("wget -f https://raw.githubusercontent.com/" .. repo .. "/master/" .. line .. " " .. line)
end
end
print("done")
end
function init.clone(repo)
os.execute("wget -f https://raw.githubusercontent.com/" .. repo .. "/master/init.files init.files")
init.getfiles()
end
if arg[1] ~= nil then
init.clone(arg[1])
end
return init
|
local init = {}
local shell = require("shell")
function init.getfiles()
print("initializing files...")
local repo = nil
for line in io.lines(os.getenv("PWD") .. "/init.files") do
if repo == nil then
repo = line
print("repo " .. repo)
else
print("getting " .. line)
os.execute("wget -f https://raw.githubusercontent.com/" .. repo .. "/master/" .. line .. " " .. line)
end
end
print("done")
end
function init.clone(repo)
os.execute("wget -f https://raw.githubusercontent.com/" .. repo .. "/master/init.files init.files")
init.getfiles()
end
local args = shell.parse( ... )
if args[1] ~= nil then
init.clone(args[1])
end
return init
|
fixes init
|
fixes init
|
Lua
|
apache-2.0
|
InfinitiesLoop/oclib
|
8fb1c174847eb4502c429145e3317230051070e4
|
json.lua
|
json.lua
|
--source
--http://www.computercraft.info/forums2/index.php?/topic/5854-json-api-v201-for-computercraft/
-------------------------------------------------------------------- utils
local controls = {["\n"]="\\n", ["\r"]="\\r", ["\t"]="\\t", ["\b"]="\\b", ["\f"]="\\f", ["\""]="\\\"", ["\\"]="\\\\"}
local function isArray(t)
local max = 0
for k,v in pairs(t) do
if type(k) ~= "number" then
return false
elseif k > max then
max = k
end
end
return max == #t
end
local whites = {['\n']=true; ['r']=true; ['\t']=true; [' ']=true; [',']=true; [':']=true}
function removeWhite(str)
while whites[str:sub(1, 1)] do
str = str:sub(2)
end
return str
end
------------------------------------------------------------------ encoding
local function encodeCommon(val, pretty, tabLevel, tTracking)
local str = ""
-- Tabbing util
local function tab(s)
str = str .. ("\t"):rep(tabLevel) .. s
end
local function arrEncoding(val, bracket, closeBracket, iterator, loopFunc)
str = str .. bracket
if pretty then
str = str .. "\n"
tabLevel = tabLevel + 1
end
for k,v in iterator(val) do
tab("")
loopFunc(k,v)
str = str .. ","
if pretty then str = str .. "\n" end
end
if pretty then
tabLevel = tabLevel - 1
end
if str:sub(-2) == ",\n" then
str = str:sub(1, -3) .. "\n"
elseif str:sub(-1) == "," then
str = str:sub(1, -2)
end
tab(closeBracket)
end
-- Table encoding
if type(val) == "table" then
assert(not tTracking[val], "Cannot encode a table holding itself recursively")
tTracking[val] = true
if isArray(val) then
arrEncoding(val, "[", "]", ipairs, function(k,v)
str = str .. encodeCommon(v, pretty, tabLevel, tTracking)
end)
else
arrEncoding(val, "{", "}", pairs, function(k,v)
assert(type(k) == "string", "JSON object keys must be strings", 2)
str = str .. encodeCommon(k, pretty, tabLevel, tTracking)
str = str .. (pretty and ": " or ":") .. encodeCommon(v, pretty, tabLevel, tTracking)
end)
end
-- String encoding
elseif type(val) == "string" then
str = '"' .. val:gsub("[%c\"\\]", controls) .. '"'
-- Number encoding
elseif type(val) == "number" or type(val) == "boolean" then
str = tostring(val)
else
error("JSON only supports arrays, objects, numbers, booleans, and strings", 2)
end
return str
end
function encode(val)
return encodeCommon(val, false, 0, {})
end
function encodePretty(val)
return encodeCommon(val, true, 0, {})
end
------------------------------------------------------------------ decoding
function parseBoolean(str)
if str:sub(1, 4) == "true" then
return true, removeWhite(str:sub(5))
else
return false, removeWhite(str:sub(6))
end
end
function parseNull(str)
return nil, removeWhite(str:sub(5))
end
local numChars = {['e']=true; ['E']=true; ['+']=true; ['-']=true; ['.']=true}
function parseNumber(str)
local i = 1
while numChars[str:sub(i, i)] or tonumber(str:sub(i, i)) do
i = i + 1
end
local val = tonumber(str:sub(1, i - 1))
str = removeWhite(str:sub(i))
return val, str
end
function parseString(str)
local i,j = str:find('^".-[^\\]?"')
local s = str:sub(i + 1,j - 1)
for k,v in pairs(controls) do
s = s:gsub(v, k)
end
str = removeWhite(str:sub(j + 1))
return s, str
end
function parseArray(str)
str = removeWhite(str:sub(2))
local val = {}
local i = 1
while str:sub(1, 1) ~= "]" do
local v = nil
v, str = parseValue(str)
val[i] = v
i = i + 1
str = removeWhite(str)
end
str = removeWhite(str:sub(2))
return val, str
end
function parseObject(str)
str = removeWhite(str:sub(2))
local val = {}
while str:sub(1, 1) ~= "}" do
local k, v = nil, nil
k, v, str = parseMember(str)
val[k] = v
str = removeWhite(str)
end
str = removeWhite(str:sub(2))
return val, str
end
function parseMember(str)
local k = nil
k, str = parseValue(str)
local val = nil
val, str = parseValue(str)
return k, val, str
end
function parseValue(str)
local fchar = str:sub(1, 1)
if fchar == "{" then
return parseObject(str)
elseif fchar == "[" then
return parseArray(str)
elseif tonumber(fchar) ~= nil or numChars[fchar] then
return parseNumber(str)
elseif str:sub(1, 4) == "true" or str:sub(1, 5) == "false" then
return parseBoolean(str)
elseif fchar == "\"" then
return parseString(str)
elseif str:sub(1, 4) == "null" then
return parseNull(str)
end
return nil
end
function decode(str)
str = removeWhite(str)
t = parseValue(str)
return t
end
function decodeFromFile(path)
local file = assert(fs.open(path, "r"))
return decode(file.readAll())
end
|
--source
--http://www.computercraft.info/forums2/index.php?/topic/5854-json-api-v201-for-computercraft/
-------------------------------------------------------------------- utils
local controls = {["\n"]="\\n", ["\r"]="\\r", ["\t"]="\\t", ["\b"]="\\b", ["\f"]="\\f", ["\""]="\\\"", ["\\"]="\\\\"}
local function isArray(t)
local max = 0
for k,v in pairs(t) do
if type(k) ~= "number" then
return false
elseif k > max then
max = k
end
end
return max == #t
end
local whites = {['\n']=true; ['r']=true; ['\t']=true; [' ']=true; [',']=true; [':']=true}
function removeWhite(str)
while whites[str:sub(1, 1)] do
str = str:sub(2)
end
return str
end
------------------------------------------------------------------ encoding
local function encodeCommon(val, pretty, tabLevel, tTracking)
local str = ""
-- Tabbing util
local function tab(s)
str = str .. ("\t"):rep(tabLevel) .. s
end
local function arrEncoding(val, bracket, closeBracket, iterator, loopFunc)
str = str .. bracket
if pretty then
str = str .. "\n"
tabLevel = tabLevel + 1
end
for k,v in iterator(val) do
tab("")
loopFunc(k,v)
str = str .. ","
if pretty then str = str .. "\n" end
end
if pretty then
tabLevel = tabLevel - 1
end
if str:sub(-2) == ",\n" then
str = str:sub(1, -3) .. "\n"
elseif str:sub(-1) == "," then
str = str:sub(1, -2)
end
tab(closeBracket)
end
-- Table encoding
if type(val) == "table" then
assert(not tTracking[val], "Cannot encode a table holding itself recursively")
tTracking[val] = true
if isArray(val) then
arrEncoding(val, "[", "]", ipairs, function(k,v)
str = str .. encodeCommon(v, pretty, tabLevel, tTracking)
end)
else
arrEncoding(val, "{", "}", pairs, function(k,v)
assert(type(k) == "string", "JSON object keys must be strings", 2)
str = str .. encodeCommon(k, pretty, tabLevel, tTracking)
str = str .. (pretty and ": " or ":") .. encodeCommon(v, pretty, tabLevel, tTracking)
end)
end
-- String encoding
elseif type(val) == "string" then
str = '"' .. val:gsub("[%c\"\\]", controls) .. '"'
-- Number encoding
elseif type(val) == "number" or type(val) == "boolean" then
str = tostring(val)
else
error("JSON only supports arrays, objects, numbers, booleans, and strings", 2)
end
return str
end
function encode(val)
return encodeCommon(val, false, 0, {})
end
function encodePretty(val)
return encodeCommon(val, true, 0, {})
end
------------------------------------------------------------------ decoding
function parseBoolean(str)
if str:sub(1, 4) == "true" then
return true, removeWhite(str:sub(5))
else
return false, removeWhite(str:sub(6))
end
end
function parseNull(str)
return nil, removeWhite(str:sub(5))
end
local numChars = {['e']=true; ['E']=true; ['+']=true; ['-']=true; ['.']=true}
function parseNumber(str)
local i = 1
while numChars[str:sub(i, i)] or tonumber(str:sub(i, i)) do
i = i + 1
end
local val = tonumber(str:sub(1, i - 1))
str = removeWhite(str:sub(i))
return val, str
end
function parseString(str)
local i,j
if str:sub(1,2) == '""' then
i,j = 1,2
else
i,j = str:find('^".-[^\\]"')
end
local s = str:sub(i + 1,j - 1)
for k,v in pairs(controls) do
s = s:gsub(v, k)
end
str = removeWhite(str:sub(j + 1))
return s, str
end
function parseArray(str)
str = removeWhite(str:sub(2))
local val = {}
local i = 1
while str:sub(1, 1) ~= "]" do
local v = nil
v, str = parseValue(str)
val[i] = v
i = i + 1
str = removeWhite(str)
end
str = removeWhite(str:sub(2))
return val, str
end
function parseObject(str)
str = removeWhite(str:sub(2))
local val = {}
while str:sub(1, 1) ~= "}" do
local k, v = nil, nil
k, v, str = parseMember(str)
val[k] = v
str = removeWhite(str)
end
str = removeWhite(str:sub(2))
return val, str
end
function parseMember(str)
local k = nil
k, str = parseValue(str)
local val = nil
val, str = parseValue(str)
return k, val, str
end
function parseValue(str)
local fchar = str:sub(1, 1)
if fchar == "{" then
return parseObject(str)
elseif fchar == "[" then
return parseArray(str)
elseif tonumber(fchar) ~= nil or numChars[fchar] then
return parseNumber(str)
elseif str:sub(1, 4) == "true" or str:sub(1, 5) == "false" then
return parseBoolean(str)
elseif fchar == "\"" then
return parseString(str)
elseif str:sub(1, 4) == "null" then
return parseNull(str)
end
return nil
end
function decode(str)
str = removeWhite(str)
t = parseValue(str)
return t
end
function decodeFromFile(path)
local file = assert(fs.open(path, "r"))
return decode(file.readAll())
end
|
Fix still broken json parsing
|
Fix still broken json parsing
The previous fix caused bugs by crashing when parsing some values
with quotation marks. This fix replaces it with a more careful
approach that is unlikely to cause any new problems.
|
Lua
|
mit
|
tmerr/computercraftIRC
|
c899b850b8dcc0b711109840a5cebc350bb73f78
|
main.lua
|
main.lua
|
io.stdout:setvbuf("no")
local reboot, events = false
--==Contribution Guide==--
--[[
I did create an events system for liko12, making my work more modular.
Below there is a modified love.run function which implements 4 things:
- Instead of calling love callbacks, it triggers the events with name "love:callback", for ex: "love:mousepressed".
- It contains a small and a nice trick which reloads all the code files (expect main.lua & conf.lua) and reboots liko12 without haveing to restart love.
- When the love.graphics is active (usable) it triggers "love:graphics" event.
- If any "love:quit" event returned true, the quit will be canceled.
About the soft restart:
* To do a soft restart trigger the "love:reboot" event.
* This works by clearing package.loaded expect bit library, then calling love.graphics.reset(), and reseting the events library, and finally restarts love.run from the top (there's an extra while loop you can see).
* In case you changed something in main.lua or conf.lua then you can do a hard restart by calling love.event.quit("restart")
* In DiskOS you can run 'reboot' command to do a soft reboot, or 'reboot hard' to do a hard one (by restarting love).
I don't think anyone would want to edit anything in this file.
==Contributers to this file==
(Add your name when contributing to this file)
- Rami Sabbagh (RamiLego4Game)
]]
love.filesystem.load("Engine/errhand.lua")() --Apply the custom error handler.
--Internal Callbacks--
function love.load(args)
love.filesystem.load("BIOS/init.lua")() --Initialize the BIOS.
events:trigger("love:load")
end
function love.run(arg)
while true do
events = require("Engine.events")
events:register("love:reboot",function(args) --Code can trigger this event to do a soft restart.
reboot = args or {}
end)
if love.math then
love.math.setRandomSeed(os.time())
end
if love.load then love.load(reboot or arg) end reboot = false
-- We don't want the first frame's dt to include time taken by love.load.
if love.timer then love.timer.step() end
local dt = 0
-- Main loop time.
while true do
-- Process events.
if love.event then
love.event.pump()
for name, a,b,c,d,e,f in love.event.poll() do
if name == "quit" then
local r = events:trigger("love:quit") --If any event returns true the quit will be cancelled
for k,v in pairs(r) do
if v and v[1] then r = nil break end
end
if r then return a end
else
events:trigger("love:"..name,a,b,c,d,e,f)
end
end
end
-- Update dt, as we'll be passing it to update
if love.timer then
love.timer.step()
dt = love.timer.getDelta()
end
-- Call update and draw
events:trigger("love:update",dt) -- will pass 0 if love.timer is disabled
if love.graphics and love.graphics.isActive() then
events:trigger("love:graphics")
end
if love.timer then love.timer.sleep(0.001) end
if reboot then
for k,v in pairs(package.loaded) do
if k ~= "bit" and k ~= "ffi" then package.loaded[k] = nil end
end--Reset the required packages
love.graphics.reset() --Reset the GPU
events = nil --Must undefine this.
break --Break our game loop
end
end
end
end
|
io.stdout:setvbuf("no")
local reboot, events = false
--==Contribution Guide==--
--[[
I did create an events system for liko12, making my work more modular.
Below there is a modified love.run function which implements 4 things:
- Instead of calling love callbacks, it triggers the events with name "love:callback", for ex: "love:mousepressed".
- It contains a small and a nice trick which reloads all the code files (expect main.lua & conf.lua) and reboots liko12 without haveing to restart love.
- When the love.graphics is active (usable) it triggers "love:graphics" event.
- If any "love:quit" event returned true, the quit will be canceled.
About the soft restart:
* To do a soft restart trigger the "love:reboot" event.
* This works by clearing package.loaded expect bit library, then calling love.graphics.reset(), and reseting the events library, and finally restarts love.run from the top (there's an extra while loop you can see).
* In case you changed something in main.lua or conf.lua then you can do a hard restart by calling love.event.quit("restart")
* In DiskOS you can run 'reboot' command to do a soft reboot, or 'reboot hard' to do a hard one (by restarting love).
I don't think anyone would want to edit anything in this file.
==Contributers to this file==
(Add your name when contributing to this file)
- Rami Sabbagh (RamiLego4Game)
]]
local package_exceptions = {
"bit", "ffi", "ssl.core", "ssl.context", "ssl.x209", "ssl", "https", "socket.http", "ltn12", "mime", "socket.smtp", "socket", "socket.url"
}
for k,v in ipairs(package_exceptions) do package_exceptions[v] = k end
love.filesystem.load("Engine/errhand.lua")() --Apply the custom error handler.
--Internal Callbacks--
function love.load(args)
love.filesystem.load("BIOS/init.lua")() --Initialize the BIOS.
events:trigger("love:load")
end
function love.run(arg)
while true do
events = require("Engine.events")
events:register("love:reboot",function(args) --Code can trigger this event to do a soft restart.
reboot = args or {}
end)
if love.math then
love.math.setRandomSeed(os.time())
end
if love.load then love.load(reboot or arg) end reboot = false
-- We don't want the first frame's dt to include time taken by love.load.
if love.timer then love.timer.step() end
local dt = 0
-- Main loop time.
while true do
-- Process events.
if love.event then
love.event.pump()
for name, a,b,c,d,e,f in love.event.poll() do
if name == "quit" then
local r = events:trigger("love:quit") --If any event returns true the quit will be cancelled
for k,v in pairs(r) do
if v and v[1] then r = nil break end
end
if r then return a end
else
events:trigger("love:"..name,a,b,c,d,e,f)
end
end
end
-- Update dt, as we'll be passing it to update
if love.timer then
love.timer.step()
dt = love.timer.getDelta()
end
-- Call update and draw
events:trigger("love:update",dt) -- will pass 0 if love.timer is disabled
if love.graphics and love.graphics.isActive() then
events:trigger("love:graphics")
end
if love.timer then love.timer.sleep(0.001) end
if reboot then
for k,v in pairs(package.loaded) do
if not package_exceptions[k] then package.loaded[k] = nil end
end--Reset the required packages
love.graphics.reset() --Reset the GPU
events = nil --Must undefine this.
break --Break our game loop
end
end
end
end
|
Fix soft reboot crash
|
Fix soft reboot crash
Former-commit-id: 8930a551138f9875bdee8a81d527728b5af58ad8
|
Lua
|
mit
|
RamiLego4Game/LIKO-12
|
f1f9e3a7c4f3d988173d3fba799d906ea9fe5c40
|
main.lua
|
main.lua
|
--=========== Copyright © 2018, Planimeter, All rights reserved. =============--
--
-- Purpose:
--
--============================================================================--
function framework.load( arg )
-- Set glTF 2.0 physically-based rendering shader
framework.graphics.setGlTFPBRShader()
-- Light
local rotation = math.rad( 75 )
local pitch = math.rad( 40 )
framework.graphics.setLightDirection( {
math.sin( rotation ) * math.cos( pitch ),
math.sin( pitch ),
math.cos( rotation ) * math.cos( pitch )
} )
-- Camera
framework.graphics.setCameraPosition( {
-1 * math.sin( rotation ) * math.cos( -pitch ),
-1 * math.sin( -pitch ),
1 * math.cos( rotation ) * math.cos( -pitch )
} )
-- Load scene
helmet = framework.graphics.newModel(
"models/DamagedHelmet/gltf/DamagedHelmet.gltf"
)
-- Set background color
framework.graphics.setBackgroundColor( { 51, 51, 51, 1 } )
end
function framework.update( dt )
end
function framework.draw()
local width, height = framework.graphics.getSize()
framework.graphics.setPerspectiveProjection( 45, width / height, 0.01, 100 )
framework.graphics.push()
framework.graphics.lookAt(
0, 0, 4,
0, 0, 0,
0, 1, 0
)
framework.graphics.rotateY( math.rad( 180 ) )
framework.graphics.draw( helmet )
framework.graphics.pop()
end
|
--=========== Copyright © 2018, Planimeter, All rights reserved. =============--
--
-- Purpose:
--
--============================================================================--
local kazmath = require( "kazmath" )
local ffi = require( "ffi" )
function framework.load( arg )
-- Set glTF 2.0 physically-based rendering shader
framework.graphics.setGlTFPBRShader()
-- View matrix
framework.graphics.lookAt(
0, 0, 4,
0, 0, 0,
0, 1, 0
)
-- Load scene
helmet = framework.graphics.newModel(
"models/DamagedHelmet/gltf/DamagedHelmet.gltf"
)
-- Set background color
framework.graphics.setBackgroundColor( { 51, 51, 51, 1 } )
-- Light
local rotation = math.rad( 75 )
local pitch = math.rad( 40 )
framework.graphics.setLightDirection( {
math.sin( rotation ) * math.cos( pitch ),
math.sin( pitch ),
math.cos( rotation ) * math.cos( pitch )
} )
end
function framework.update( dt )
end
--[[ ***** Mouse Controls ***** ]]
local mouseDown = false
local roll = math.pi
local pitch = 0
local translate = 4
function framework.draw()
local width, height = framework.graphics.getSize()
framework.graphics.setPerspectiveProjection( 45, width / height, 0.01, 100 )
-- set up the camera position and view matrix
framework.graphics.setCameraPosition( {
-1 * math.sin( roll ) * math.cos( -pitch ),
-1 * math.sin( -pitch ),
1 * math.cos( roll ) * math.cos( -pitch )
} )
-- Update view matrix
-- roll, pitch and translate are all globals.
local xRotation = ffi.new( "kmMat4" )
kazmath.kmMat4RotationY( xRotation, roll )
local yRotation = ffi.new( "kmMat4" )
kazmath.kmMat4RotationX( yRotation, pitch )
local mode = framework.graphics.getMatrixMode()
framework.graphics.setMatrixMode( "view" )
framework.graphics.push()
local mat4 = framework.graphics.getTransformation()
kazmath.kmMat4Multiply( mat4, yRotation, xRotation )
mat4.mat[14] = -translate
framework.graphics.draw( helmet )
framework.graphics.pop()
framework.graphics.setMatrixMode( mode )
end
function framework.mousepressed( x, y, button, istouch )
mouseDown = true
end
function framework.mousereleased( x, y, button, istouch )
mouseDown = false
end
function framework.mousemoved( x, y, dx, dy, istouch )
if ( not mouseDown ) then
return
end
roll = roll + ( dx / 100 )
pitch = pitch + ( dy / 100 )
end
local wheelSpeed = 1.04
function framework.wheelmoved( x, y )
if ( y > 0 ) then
translate = translate * wheelSpeed
else
translate = translate / wheelSpeed
end
end
|
Fix reference camera
|
Fix reference camera
|
Lua
|
mit
|
Planimeter/lgameframework,Planimeter/lgameframework,Planimeter/lgameframework
|
8a9ff4fffa7538bb7f22d4ccff48e456172f1005
|
hammerspoon/hammerspoon.symlink/modules/keyboard.lua
|
hammerspoon/hammerspoon.symlink/modules/keyboard.lua
|
local hyper = { "shift", "cmd", "alt", "ctrl" }
local mash = { "ctrl", "alt", "cmd" }
-- Global shortcut to reload Hammerspoon
hs.hotkey.bind(hyper, "r", hs.reload)
hs.hotkey.bind(hyper, "c", hs.toggleConsole)
-- Move windows around current screen
hs.hotkey.bind(mash, "left", function() window:leftHalf() end);
hs.hotkey.bind(mash, "right", function() window:rightHalf() end);
hs.hotkey.bind(mash, "up", function() window:topHalf() end);
hs.hotkey.bind(mash, "down", function() window:bottomHalf() end);
hs.hotkey.bind(hyper, "f", function() window:maximize() end)
-- Move between screens
hs.hotkey.bind(hyper, "left", function() hs.window.focusedWindow():moveOneScreenWest() end)
hs.hotkey.bind(hyper, "right", function() hs.window.focusedWindow():moveOneScreenEast() end)
window = {}
local function currentFrame()
return hs.window.focusedWindow():frame()
end
local function currentScreenFrame()
return hs.window.focusedWindow():screen():frame()
end
function window:maximize ()
hs.window.focusedWindow():maximize()
end
function window:move (f, window)
if window == nil then
window = hs.window.focusedWindow()
end
local oldFrame = window:frame()
if oldFrame ~= f then
window:move(hs.geometry(f.x, f.y, f.w, f.h))
end
end
function window:leftHalf ()
local s = currentScreenFrame()
self:move({ x = 0, y = 0, w = (s.w / 2), h = s.h })
end
function window:rightHalf ()
local s = currentScreenFrame()
self:move({ x = (s.w / 2), y = 0, w = (s.w / 2), h = s.h })
end
function window:topHalf ()
local s = currentScreenFrame()
self:move({ x = 0, y = 0, w = s.w, h = (s.h / 2) })
end
function window:bottomHalf ()
local s = currentScreenFrame()
self:move({ x = 0, y = (s.h / 2), w = s.w, h = (s.h / 2) })
end
|
local hyper = { "shift", "cmd", "alt", "ctrl" }
local mash = { "ctrl", "alt", "cmd" }
-- Global shortcut to reload Hammerspoon
hs.hotkey.bind(hyper, "r", hs.reload)
hs.hotkey.bind(hyper, "c", hs.toggleConsole)
-- Move windows around current screen
hs.hotkey.bind(mash, "left", function() window:leftHalf() end);
hs.hotkey.bind(mash, "right", function() window:rightHalf() end);
hs.hotkey.bind(mash, "up", function() window:topHalf() end);
hs.hotkey.bind(mash, "down", function() window:bottomHalf() end);
hs.hotkey.bind(hyper, "f", function() window:maximize() end)
-- Move between screens
hs.hotkey.bind(hyper, "left", function() hs.window.focusedWindow():moveOneScreenWest() end)
hs.hotkey.bind(hyper, "right", function() hs.window.focusedWindow():moveOneScreenEast() end)
window = {}
local function currentFrame()
return hs.window.focusedWindow():frame()
end
local function currentScreenFrame()
return hs.window.focusedWindow():screen():frame()
end
local function currentScreenFullFrame()
return hs.window.focusedWindow():screen():fullFrame()
end
function window:maximize ()
hs.window.focusedWindow():maximize()
end
function window:move (f, window)
if window == nil then
window = hs.window.focusedWindow()
end
local oldFrame = window:frame()
if oldFrame ~= f then
window:move(hs.geometry(f.x, f.y, f.w, f.h))
end
end
function window:leftHalf ()
local s = currentScreenFrame()
self:move({ x = s.x, y = s.y, w = (s.w / 2), h = s.h })
end
function window:rightHalf ()
local s = currentScreenFrame()
self:move({ x = (s.w / 2), y = s.y, w = (s.w / 2), h = s.h })
end
function window:topHalf ()
local s = currentScreenFrame()
self:move({ x = 0, y = s.y, w = s.w, h = (s.h / 2) })
end
function window:bottomHalf ()
local s = currentScreenFrame()
self:move({ x = 0, y = (s.h / 2) + s.y, w = s.w, h = (s.h / 2) })
end
|
fix(Hammerspoon): Fix bottom-half window resize to respoect menubar height
|
fix(Hammerspoon): Fix bottom-half window resize to respoect menubar height
|
Lua
|
mit
|
sethvoltz/dotfiles,sethvoltz/dotfiles,sethvoltz/dotfiles,sethvoltz/dotfiles
|
bca1502ed14188676609d0903f9e8ab0ba6b9156
|
src/cjdnstools/addrcalc.lua
|
src/cjdnstools/addrcalc.lua
|
--- @module cjdnstools.addrcalc
local addrcalc = {}
local bit32 = require("bit32")
local sha2 = require("sha2")
function addrcalc.Base32_decode(input)
local numForAscii = {
99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,
99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,
99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,99,99,99,99,99,99,
99,99,10,11,12,99,13,14,15,99,16,17,18,19,20,99,
21,22,23,24,25,26,27,28,29,30,31,99,99,99,99,99,
99,99,10,11,12,99,13,14,15,99,16,17,18,19,20,99,
21,22,23,24,25,26,27,28,29,30,31,99,99,99,99,99,
}
local output = {}
local outputIndex = 0
local inputIndex = 0
local nextByte = 0
local bits = 0
while inputIndex < string.len(input) do
i = string.byte(input,inputIndex+1)
if bit32.band(i,0x80) ~= 0 then
error("Bad base32 decode input character " .. i)
end
b = numForAscii[i+1]
inputIndex = inputIndex + 1
if b > 31 then
error("Bad base32 decode input character " .. i)
end
nextByte = bit32.bor(nextByte, bit32.lshift(b, bits))
bits = bits + 5
if bits >= 8 then
output[outputIndex+1] = bit32.band(nextByte, 0xff)
outputIndex = outputIndex + 1
bits = bits - 8
nextByte = bit32.rshift(nextByte, 8)
end
end
if bits >= 5 or nextByte ~= 0 then
error("Bad base32 decode input, bits is " .. bits .. " and nextByte is " .. nextByte);
end
return string.char(unpack(output));
end
function addrcalc.pkey2ipv6(k)
if string.sub(k,-2) ~= ".k" then
error("Invalid key")
end
kdata = addrcalc.Base32_decode(string.sub(k,1,-3))
hash = sha2.sha512(kdata)
hash = sha2.sha512hex(hash)
addr = string.sub(hash,1,4)
for i = 2,8 do
addr = addr .. ":" .. string.sub(hash,i*4-3,i*4)
end
return addr
end
return addrcalc
|
--- @module cjdnstools.addrcalc
local addrcalc = {}
local bit32 = require("bit32")
local sha2 = require("sha2")
function addrcalc.Base32_decode(input)
local numForAscii = {
99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,
99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,
99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,99,99,99,99,99,99,
99,99,10,11,12,99,13,14,15,99,16,17,18,19,20,99,
21,22,23,24,25,26,27,28,29,30,31,99,99,99,99,99,
99,99,10,11,12,99,13,14,15,99,16,17,18,19,20,99,
21,22,23,24,25,26,27,28,29,30,31,99,99,99,99,99,
}
local output = {}
local outputIndex = 0
local inputIndex = 0
local nextByte = 0
local bits = 0
while inputIndex < string.len(input) do
i = string.byte(input,inputIndex+1)
if bit32.band(i,0x80) ~= 0 then
error("Bad base32 decode input character " .. i)
end
b = numForAscii[i+1]
inputIndex = inputIndex + 1
if b > 31 then
error("Bad base32 decode input character " .. i)
end
nextByte = bit32.bor(nextByte, bit32.lshift(b, bits))
bits = bits + 5
if bits >= 8 then
output[outputIndex+1] = bit32.band(nextByte, 0xff)
outputIndex = outputIndex + 1
bits = bits - 8
nextByte = bit32.rshift(nextByte, 8)
end
end
if bits >= 5 or nextByte ~= 0 then
error("Bad base32 decode input, bits is " .. bits .. " and nextByte is " .. nextByte);
end
return string.char(unpack(output));
end
function addrcalc.pkey2ipv6(k)
if string.sub(k,-2) ~= ".k" then
error("Invalid key")
end
kdata = addrcalc.Base32_decode(string.sub(k,1,-3))
hash = sha2.sha512(kdata)
hash = sha2.sha512hex(hash)
addr = string.sub(hash,1,4)
for i = 2,8 do
addr = addr .. ":" .. string.sub(hash,i*4-3,i*4)
end
return addr
end
return addrcalc
|
Fixed indentation
|
Fixed indentation
|
Lua
|
mit
|
intermesh-networks/transitd,pdxmeshnet/mnigs,pdxmeshnet/mnigs,transitd/transitd,transitd/transitd,transitd/transitd,intermesh-networks/transitd
|
89a7041cca8608e56940bf620a26797cdf734067
|
module/admin-core/src/model/cbi/admin_index/luci.lua
|
module/admin-core/src/model/cbi/admin_index/luci.lua
|
-- ToDo: Translate, Add descriptions and help texts
m = Map("luci", "FFLuCI")
c = m:section(NamedSection, "main", "core", "Allgemein")
c:option(Value, "lang", "Sprache")
c:option(Value, "mediaurlbase", "Mediaverzeichnis")
f = m:section(NamedSection, "flash", "extern", "Firmwareupgrade")
f:option(Value, "keep", "Übernehme Dateien").size = 64
p = m:section(NamedSection, "category_privileges", "core", "Kategorieprivilegien")
p.dynamic = true
u = m:section(NamedSection, "uci_oncommit", "event", "UCI-Befehle beim Anwenden")
u.dynamic = true
return m
|
-- ToDo: Translate, Add descriptions and help texts
m = Map("luci", "FFLuCI")
c = m:section(NamedSection, "main", "core", "Allgemein")
c:option(Value, "lang", "Sprache")
c:option(Value, "mediaurlbase", "Mediaverzeichnis")
f = m:section(NamedSection, "flash_keep", "extern", "Zu übernehmende Dateien bei Firmwareupgrade")
f.dynamic = true
p = m:section(NamedSection, "category_privileges", "core", "Kategorieprivilegien")
p.dynamic = true
u = m:section(NamedSection, "uci_oncommit", "event", "UCI-Befehle beim Anwenden")
u.dynamic = true
return m
|
* Fixed changed layout of flash_keep in admin > index
|
* Fixed changed layout of flash_keep in admin > index
git-svn-id: edf5ee79c2c7d29460bbb5b398f55862cc26620d@1848 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
|
Lua
|
apache-2.0
|
ch3n2k/luci,Flexibity/luci,saraedum/luci-packages-old,projectbismark/luci-bismark,yeewang/openwrt-luci,dtaht/cerowrt-luci-3.3,Canaan-Creative/luci,8devices/carambola2-luci,Flexibity/luci,gwlim/luci,stephank/luci,ThingMesh/openwrt-luci,ReclaimYourPrivacy/cloak-luci,yeewang/openwrt-luci,gwlim/luci,zwhfly/openwrt-luci,eugenesan/openwrt-luci,jschmidlapp/luci,ReclaimYourPrivacy/cloak-luci,freifunk-gluon/luci,ThingMesh/openwrt-luci,jschmidlapp/luci,Canaan-Creative/luci,ThingMesh/openwrt-luci,alxhh/piratenluci,stephank/luci,eugenesan/openwrt-luci,alxhh/piratenluci,phi-psi/luci,gwlim/luci,yeewang/openwrt-luci,ThingMesh/openwrt-luci,Flexibity/luci,alxhh/piratenluci,projectbismark/luci-bismark,yeewang/openwrt-luci,freifunk-gluon/luci,8devices/carambola2-luci,freifunk-gluon/luci,ReclaimYourPrivacy/cloak-luci,stephank/luci,projectbismark/luci-bismark,8devices/carambola2-luci,Flexibity/luci,zwhfly/openwrt-luci,freifunk-gluon/luci,ThingMesh/openwrt-luci,eugenesan/openwrt-luci,ReclaimYourPrivacy/cloak-luci,saraedum/luci-packages-old,vhpham80/luci,Canaan-Creative/luci,yeewang/openwrt-luci,ch3n2k/luci,dtaht/cerowrt-luci-3.3,8devices/carambola2-luci,dtaht/cerowrt-luci-3.3,ThingMesh/openwrt-luci,jschmidlapp/luci,Canaan-Creative/luci,phi-psi/luci,ch3n2k/luci,vhpham80/luci,Canaan-Creative/luci,phi-psi/luci,vhpham80/luci,jschmidlapp/luci,stephank/luci,freifunk-gluon/luci,freifunk-gluon/luci,gwlim/luci,alxhh/piratenluci,saraedum/luci-packages-old,ReclaimYourPrivacy/cloak-luci,jschmidlapp/luci,ch3n2k/luci,ReclaimYourPrivacy/cloak-luci,vhpham80/luci,ch3n2k/luci,zwhfly/openwrt-luci,phi-psi/luci,saraedum/luci-packages-old,zwhfly/openwrt-luci,Flexibity/luci,8devices/carambola2-luci,8devices/carambola2-luci,eugenesan/openwrt-luci,zwhfly/openwrt-luci,Flexibity/luci,vhpham80/luci,Flexibity/luci,projectbismark/luci-bismark,projectbismark/luci-bismark,yeewang/openwrt-luci,gwlim/luci,phi-psi/luci,dtaht/cerowrt-luci-3.3,zwhfly/openwrt-luci,ch3n2k/luci,phi-psi/luci,projectbismark/luci-bismark,jschmidlapp/luci,jschmidlapp/luci,eugenesan/openwrt-luci,ReclaimYourPrivacy/cloak-luci,projectbismark/luci-bismark,ReclaimYourPrivacy/cloak-luci,alxhh/piratenluci,phi-psi/luci,ThingMesh/openwrt-luci,freifunk-gluon/luci,gwlim/luci,saraedum/luci-packages-old,zwhfly/openwrt-luci,Canaan-Creative/luci,dtaht/cerowrt-luci-3.3,Canaan-Creative/luci,saraedum/luci-packages-old,yeewang/openwrt-luci,Flexibity/luci,stephank/luci,ch3n2k/luci,Canaan-Creative/luci,vhpham80/luci,eugenesan/openwrt-luci,eugenesan/openwrt-luci,alxhh/piratenluci,stephank/luci,projectbismark/luci-bismark,dtaht/cerowrt-luci-3.3,8devices/carambola2-luci,jschmidlapp/luci,freifunk-gluon/luci,gwlim/luci,alxhh/piratenluci,zwhfly/openwrt-luci,saraedum/luci-packages-old,zwhfly/openwrt-luci
|
6b4597a76db8bd32dd8165cbf9352a37aa175ade
|
agents/monitoring/tests/helper.lua
|
agents/monitoring/tests/helper.lua
|
local spawn = require('childprocess').spawn
local constants = require('constants')
local misc = require('monitoring/default/util/misc')
function runner(name)
return spawn('python', {'agents/monitoring/runner.py', name})
end
local child
local function start_server(callback)
local data = ''
callback = misc.fireOnce(callback)
child = runner('server_fixture_blocking')
child.stderr:on('data', function(d)
callback(d)
end)
child.stdout:on('data', function(chunk)
data = data .. chunk
if data:find('TLS fixture server listening on port 50061') then
callback()
end
end)
return child
end
local function stop_server(child)
if not child then return end
child:kill(constants.SIGUSR1) -- USR1
end
process:on('exit', function()
stop_server(child)
end)
local exports = {}
exports.runner = runner
exports.start_server = start_server
exports.stop_server = stop_server
return exports
|
local spawn = require('childprocess').spawn
local constants = require('constants')
local misc = require('monitoring/default/util/misc')
function runner(name)
return spawn('python', {'agents/monitoring/runner.py', name})
end
local child
local function start_server(callback)
local data = ''
callback = misc.fireOnce(callback)
child = runner('server_fixture_blocking')
child.stderr:on('data', function(d)
callback(d)
end)
child.stdout:on('data', function(chunk)
data = data .. chunk
if data:find('TLS fixture server listening on port 50061') then
callback()
end
end)
return child
end
local function stop_server(child)
if not child then return end
child:kill(constants.SIGUSR1) -- USR1
end
process:on('exit', function()
stop_server(child)
end)
process:on("error", function(e)
stop_server(child)
end)
local exports = {}
exports.runner = runner
exports.start_server = start_server
exports.stop_server = stop_server
return exports
|
Kill the fixture server always.
|
Kill the fixture server always.
As simple as process:on('error'). This will make tests go better.
|
Lua
|
apache-2.0
|
kans/zirgo,kans/zirgo,kans/zirgo
|
346ef3cfd01192d9b137b8a356d22c77babac446
|
gateway/config/standalone.lua
|
gateway/config/standalone.lua
|
local PolicyChain = require('apicast.policy_chain')
local resty_url = require('resty.url')
local format = string.format
local function to_url(uri)
local url = resty_url.parse(uri)
if url then
return uri
elseif uri then
return format('file:%s', uri)
end
end
local standalone = assert(PolicyChain.load_policy(
'apicast.policy.standalone',
'builtin',
{ url = to_url(context.configuration) }))
if arg then -- running CLI to generate nginx config
return {
template = 'http.d/standalone.conf.liquid',
standalone = standalone:load_configuration(),
configuration = standalone.url,
}
else -- booting APIcast
return {
policy_chain = PolicyChain.new{
standalone,
},
configuration = standalone.url,
}
end
|
local PolicyChain = require('apicast.policy_chain')
local resty_url = require('resty.url')
local linked_list = require('apicast.linked_list')
local format = string.format
local function to_url(uri)
local url = resty_url.parse(uri)
if url then
return uri
elseif uri then
return format('file:%s', uri)
end
end
local standalone = assert(PolicyChain.load_policy(
'apicast.policy.standalone',
'builtin',
{ url = to_url(context.configuration) }))
if arg then -- running CLI to generate nginx config
local config = standalone:load_configuration() or {}
return linked_list.readonly({
template = 'http.d/standalone.conf.liquid',
standalone = config,
configuration = standalone.url,
}, config.global)
else -- booting APIcast
return {
policy_chain = PolicyChain.new{
standalone,
},
configuration = standalone.url,
}
end
|
[standalone] fix propagating global configuration
|
[standalone] fix propagating global configuration
|
Lua
|
mit
|
3scale/apicast,3scale/docker-gateway,3scale/apicast,3scale/apicast,3scale/apicast,3scale/docker-gateway
|
a40a2fbc39e424a01b65c1ddee14aa8cd4f19064
|
loot.lua
|
loot.lua
|
local mod = EPGP:NewModule("loot", "AceEvent-3.0", "AceTimer-3.0")
local L = LibStub("AceLocale-3.0"):GetLocale("EPGP")
local LLN = LibStub("LibLootNotify-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
[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 loot_queue = {}
local timer
local function IsRLorML()
if UnitInRaid("player") then
local loot_method, ml_party_id, ml_raid_id = GetLootMethod()
if loot_method == "master" and ml_party_id == 0 then return true end
if loot_method ~= "master" and IsRaidLeader() then return true end
end
return false
end
function mod:PopLootQueue()
if in_combat then return end
if #loot_queue == 0 then
if timer then
self:CancelTimer(timer, true)
timer = nil
end
return
end
local player, item = unpack(loot_queue[1])
-- In theory this should never happen.
if not player or not item then
tremove(loot_queue, 1)
return
end
-- User is busy with other popup.
if StaticPopup_Visible("EPGP_CONFIRM_GP_CREDIT") then
return
end
tremove(loot_queue, 1)
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
tinsert(loot_queue, {player, itemLink, quantity})
if not timer then
timer = mod:ScheduleRepeatingTimer("PopLootQueue", 0.1)
end
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
}
}
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", "AceTimer-3.0")
local L = LibStub("AceLocale-3.0"):GetLocale("EPGP")
local LLN = LibStub("LibLootNotify-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
[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 loot_queue = {}
local timer
local function IsRLorML()
if UnitInRaid("player") then
local loot_method, ml_party_id, ml_raid_id = GetLootMethod()
if loot_method == "master" and ml_party_id == 0 then return true end
if loot_method ~= "master" and IsRaidLeader() then return true end
end
return false
end
function mod:PopLootQueue()
if in_combat then return end
if #loot_queue == 0 then
if timer then
self:CancelTimer(timer, true)
timer = nil
end
return
end
local player, item = unpack(loot_queue[1])
-- In theory this should never happen.
if not player or not item then
tremove(loot_queue, 1)
return
end
-- User is busy with other popup.
if StaticPopup_Visible("EPGP_CONFIRM_GP_CREDIT") then
return
end
tremove(loot_queue, 1)
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
tinsert(loot_queue, {player, itemLink, quantity})
if not timer then
timer = mod:ScheduleRepeatingTimer("PopLootQueue", 0.1)
end
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
}
}
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
|
Ignore emblems of triumph.
|
Ignore emblems of triumph.
This fixes issue 482.
|
Lua
|
bsd-3-clause
|
hayword/tfatf_epgp,protomech/epgp-dkp-reloaded,sheldon/epgp,hayword/tfatf_epgp,protomech/epgp-dkp-reloaded,ceason/epgp-tfatf,sheldon/epgp,ceason/epgp-tfatf
|
9b9174ee6030680892ebe791fe197cbb30d1e9e7
|
init.lua
|
init.lua
|
-- [boundary.com] Tomcat Metrics using default Manager Web Application
-- [author] Gabriel Nicolas Avellaneda <[email protected]>
local boundary = require('boundary')
local http = require('http')
local base64 = require('./modules/mime')
local timer = require('timer')
local string = require('string')
local table = require('table')
local os = require('os')
local fs = require('fs')
local parser = require('./modules/parser')
local math = require('math')
-- default parameter values
local host = 'localhost'
local port = 8080
local path = '/manager/status'
local username = 'admin'
local password = 'password'
local source = os.hostname()
local pollInterval = 5000
-- try to get parameters from plugin instance
if (boundary.param ~= nil) then
host = boundary.param['host'] or host
port = boundary.param['port'] or port
path = boundary.param['path'] or path
username = boundary.param['username'] or username
password = boundary.param['password'] or password
pollInterval = boundary.param['pollInterval'] or pollInterval
source = boundary.param['source'] or source
end
print("_bevent:Boundary Tomcat Manager Status plugin : version 1.0|t:info|tags:tomcat,plugin")
-- Some helper functions
function base64Encode(s)
return base64.b64(s)
end
function isEmpty(s)
return s == '' or s == nil
end
function currentTimestamp()
return os.time()
end
function round(val, decimal)
if (decimal) then
return math.floor( (val * 10^decimal) + 0.5) / (10^decimal)
else
return math.floor(val+0.5)
end
end
function authHeader(username, password)
return {Authorization = 'Basic ' ..
base64Encode(username .. ':' .. password)}
end
function parse(data)
local vals = parser.parse(data)
return vals
end
local headers = {}
if not isEmpty(username) then
headers = authHeader(username, password)
end
local reqOptions = {
host = host,
port = port,
path = path,
headers = headers
}
function poll()
getStatus(reqOptions,
function (data)
local vals = parse(data)
report(vals, source, currentTimestamp())
end)
timer.setTimeout(pollInterval, poll)
end
function formatMetric(metric, value, source, timestamp)
return string.format('%s %1.2f %s %s', metric, round(value, 2), source, timestamp)
end
function report(metrics, source, timestamp)
for metric, value in pairs(metrics) do
print(formatMetric(metric, value, source, timestamp))
end
end
function getStatus(reqOptions, successFunc)
local req = http.request(
reqOptions,
function (res)
local data = ''
res:on('error', function(err)
msg = tostring(err)
print('Error while receiving a response: ' .. msg)
end)
res:on('data', function(chunk)
data = data .. chunk
end)
res:on('end', function()
successFunc(data)
end)
end)
req:on('error', function(err)
msg = tostring(err)
print('Error while sending a request: ' .. msg)
end)
req:done()
end
-- Start pooling for metrics
poll()
|
-- [boundary.com] Tomcat Metrics using default Manager Web Application
-- [author] Gabriel Nicolas Avellaneda <[email protected]>
local boundary = require('boundary')
local http = require('http')
local base64 = require('./modules/mime')
local timer = require('timer')
local string = require('string')
local table = require('table')
local os = require('os')
local fs = require('fs')
local parser = require('./modules/parser')
local math = require('math')
-- default parameter values
local host = 'localhost'
local port = 8080
local path = '/manager/status'
local username = 'admin'
local password = 'password'
local source = os.hostname()
local pollInterval = 5000
-- try to get parameters from plugin instance
if (boundary.param ~= nil) then
host = boundary.param['host'] or host
port = boundary.param['port'] or port
path = boundary.param['path'] or path
username = boundary.param['username'] or username
password = boundary.param['password'] or password
pollInterval = boundary.param['pollInterval'] or pollInterval
source = boundary.param['source'] or source
end
print("_bevent:Boundary Tomcat Manager Status plugin : version 1.0|t:info|tags:tomcat,plugin")
-- Some helper functions
function base64Encode(s)
return base64.b64(s)
end
function isEmpty(s)
return s == '' or s == nil
end
function currentTimestamp()
return os.time()
end
function round(val, decimal)
if (decimal) then
return math.floor( (val * 10^decimal) + 0.5) / (10^decimal)
else
return math.floor(val+0.5)
end
end
function authHeader(username, password)
return {Authorization = 'Basic ' ..
base64Encode(username .. ':' .. password)}
end
function parse(data)
local vals = parser.parse(data)
return vals
end
local headers = {}
if not isEmpty(username) then
headers = authHeader(username, password)
end
local reqOptions = {
host = host,
port = port,
path = path,
headers = headers
}
function poll()
getStatus(reqOptions,
function (data)
local vals = parse(data)
report(vals, source, currentTimestamp())
end)
timer.setTimeout(pollInterval, poll)
end
function formatMetric(metric, value, source, timestamp)
return string.format('%s %1.2f %s %s', metric, round(value, 2), source, timestamp)
end
function report(metrics, source, timestamp)
for metric, value in pairs(metrics) do
print(formatMetric(metric, value, source, timestamp))
end
end
function getStatus(reqOptions, successFunc)
local req = http.request(
reqOptions,
function (res)
local data = ''
res:on('error', function(err)
msg = tostring(err)
process.stderr:write('Error while receiving a response: ' .. msg)
end)
res:on('data', function(chunk)
data = data .. chunk
end)
res:on('end', function()
successFunc(data)
end)
end)
req:on('error', function(err)
msg = tostring(err)
process.stderr:write('Error while sending a request: ' .. msg)
end)
req:done()
end
-- Start pooling for metrics
poll()
|
Fixed error handling to go to stderr
|
Fixed error handling to go to stderr
|
Lua
|
apache-2.0
|
GabrielNicolasAvellaneda/boundary-plugin-tomcat-deprecated,boundary/boundary-plugin-apache-tomcat,prashantabmc/boundary-plugin-apache-tomcat
|
e8928f77a8f75011db6fac8fe3f61906025d76ca
|
examples/uvbook/thread-create.lua
|
examples/uvbook/thread-create.lua
|
local uv = require('luv')
local hare_id = uv.new_thread()
local tortoise_id = uv.new_thread()
local step = 10
uv.thread_create(hare_id,function(step,...)
local ffi = require'ffi'
local uv = require('luv')
local sleep
if ffi.os=='Windows' then
ffi.cdef "void Sleep(int ms);"
sleep = ffi.C.Sleep
else
ffi.cdef "unsigned int usleep(unsigned int seconds);"
sleep = ffi.C.usleep
end
while (step>0) do
step = step - 1
uv.sleep(math.random(1000))
print("Hare ran another step")
end
print("Hare done running!")
end, step,true,'abcd','false')
uv.thread_create(tortoise_id,function(step,...)
local uv = require('luv')
while (step>0) do
step = step - 1
uv.sleep(math.random(100))
print("Tortoise ran another step")
end
print("Tortoise done running!")
end,step,'abcd','false')
print(hare_id==hare_id,uv.thread_equal(hare_id,hare_id))
print(tortoise_id==hare_id,uv.thread_equal(tortoise_id,hare_id))
uv.thread_join(hare_id)
uv.thread_join(tortoise_id)
|
local uv = require('luv')
local step = 10
local hare_id = uv.new_thread(function(step,...)
local ffi = require'ffi'
local uv = require('luv')
local sleep
if ffi.os=='Windows' then
ffi.cdef "void Sleep(int ms);"
sleep = ffi.C.Sleep
else
ffi.cdef "unsigned int usleep(unsigned int seconds);"
sleep = ffi.C.usleep
end
while (step>0) do
step = step - 1
uv.sleep(math.random(1000))
print("Hare ran another step")
end
print("Hare done running!")
end, step,true,'abcd','false')
local tortoise_id = uv.new_thread(function(step,...)
local uv = require('luv')
while (step>0) do
step = step - 1
uv.sleep(math.random(100))
print("Tortoise ran another step")
end
print("Tortoise done running!")
end,step,'abcd','false')
print(hare_id==hare_id,uv.thread_equal(hare_id,hare_id))
print(tortoise_id==hare_id,uv.thread_equal(tortoise_id,hare_id))
uv.thread_join(hare_id)
uv.thread_join(tortoise_id)
|
fix uvbook example thread-create
|
fix uvbook example thread-create
|
Lua
|
apache-2.0
|
zhaozg/luv,luvit/luv,daurnimator/luv,RomeroMalaquias/luv,luvit/luv,joerg-krause/luv,daurnimator/luv,RomeroMalaquias/luv,RomeroMalaquias/luv,joerg-krause/luv,daurnimator/luv,zhaozg/luv
|
ac96c53209f298eca8f9dbf0512bfb0714f0363c
|
src/inputkeymaputils/src/Client/InputKeyMapUtils.lua
|
src/inputkeymaputils/src/Client/InputKeyMapUtils.lua
|
--- Utility methods for input map
-- @module InputKeyMapUtils
-- @author Quenty
local require = require(script.Parent.loader).load(script)
local Set = require("Set")
local Table = require("Table")
local InputKeyMapUtils = {}
function InputKeyMapUtils.createKeyMap(inputMode, inputTypes)
assert(type(inputMode) == "table", "Bad inputMode")
assert(type(inputTypes) == "table", "Bad inputTypes")
return Table.readonly({
inputMode = inputMode;
inputTypes = inputTypes;
})
end
function InputKeyMapUtils.getInputTypesSetForActionBinding(inputKeyMapList)
return Set.fromList(InputKeyMapUtils.getInputTypesForActionBinding(inputKeyMapList))
end
--- Converts keymap into ContextActionService friendly types
function InputKeyMapUtils.getInputTypesForActionBinding(inputKeyMapList)
assert(type(inputKeyMapList) == "table", "inputKeyMapList must be a table")
local types = {}
for _, inputKeyMap in pairs(inputKeyMapList) do
assert(inputKeyMap.inputMode, "Bad inputKeyMap.inputMode")
assert(inputKeyMap.inputTypes, "Bad inputKeyMap.inputTypes")
for _, _type in pairs(inputKeyMap.inputTypes) do
if typeof(_type) == "EnumItem" then
table.insert(types, _type)
end
end
end
return types
end
function InputKeyMapUtils.getInputTypeListForMode(inputKeyMapList, inputMode)
assert(type(inputKeyMapList) == "table", "inputKeyMapList must be a table")
local results = {}
local seen = {}
for _, inputKeyMap in pairs(inputKeyMapList) do
if inputKeyMap.inputMode == inputMode then
for _, inputType in pairs(inputKeyMap.inputTypes) do
if not seen then
seen[inputType] = true
table.insert(results, inputType)
end
end
end
end
return results
end
function InputKeyMapUtils.getInputTypeSetForMode(inputKeyMapList, inputMode)
assert(type(inputKeyMapList) == "table", "inputKeyMapList must be a table")
local results = {}
for _, inputKeyMap in pairs(inputKeyMapList) do
if inputKeyMap.inputMode == inputMode then
for _, inputType in pairs(inputKeyMap.inputTypes) do
results[inputType] = true
end
end
end
return results
end
function InputKeyMapUtils.getInputModes(inputKeyMapList)
assert(type(inputKeyMapList) == "table", "inputKeyMapList must be a table")
local modes = {}
for _, inputKeyMap in pairs(inputKeyMapList) do
table.insert(modes, assert(inputKeyMap.inputMode, "Bad inputKeyMap.inputMode"))
end
return modes
end
function InputKeyMapUtils.isTouchButton(inputKeyMapList)
for _, inputKeyMap in pairs(inputKeyMapList) do
assert(inputKeyMap.inputMode, "Bad inputKeyMap.inputMode")
assert(inputKeyMap.inputTypes, "Bad inputKeyMap.inputTypes")
for _, _type in pairs(inputKeyMap.inputTypes) do
if _type == "TouchButton" then
return true
end
end
end
return false
end
function InputKeyMapUtils.isTapInWorld(inputKeyMapList)
assert(type(inputKeyMapList) == "table", "inputKeyMap must be a table")
for _, inputKeyMap in pairs(inputKeyMapList) do
assert(inputKeyMap.inputMode, "Bad inputKeyMap.inputMode")
assert(inputKeyMap.inputTypes, "Bad inputKeyMap.inputTypes")
for _, _type in pairs(inputKeyMap.inputTypes) do
if _type == "Tap" then
return true
end
end
end
return false
end
return InputKeyMapUtils
|
--- Utility methods for input map
-- @module InputKeyMapUtils
-- @author Quenty
local require = require(script.Parent.loader).load(script)
local Set = require("Set")
local Table = require("Table")
local InputKeyMapUtils = {}
function InputKeyMapUtils.createKeyMap(inputMode, inputTypes)
assert(type(inputMode) == "table", "Bad inputMode")
assert(type(inputTypes) == "table", "Bad inputTypes")
return Table.readonly({
inputMode = inputMode;
inputTypes = inputTypes;
})
end
function InputKeyMapUtils.getInputTypesSetForActionBinding(inputKeyMapList)
return Set.fromList(InputKeyMapUtils.getInputTypesForActionBinding(inputKeyMapList))
end
--- Converts keymap into ContextActionService friendly types
function InputKeyMapUtils.getInputTypesForActionBinding(inputKeyMapList)
assert(type(inputKeyMapList) == "table", "inputKeyMapList must be a table")
local types = {}
for _, inputKeyMap in pairs(inputKeyMapList) do
assert(inputKeyMap.inputMode, "Bad inputKeyMap.inputMode")
assert(inputKeyMap.inputTypes, "Bad inputKeyMap.inputTypes")
for _, _type in pairs(inputKeyMap.inputTypes) do
if typeof(_type) == "EnumItem" then
table.insert(types, _type)
end
end
end
return types
end
function InputKeyMapUtils.getInputTypeListForMode(inputKeyMapList, inputMode)
assert(type(inputKeyMapList) == "table", "inputKeyMapList must be a table")
local results = {}
local seen = {}
for _, inputKeyMap in pairs(inputKeyMapList) do
if inputKeyMap.inputMode == inputMode then
for _, inputType in pairs(inputKeyMap.inputTypes) do
if not seen then
seen[inputType] = true
table.insert(results, inputType)
end
end
end
end
return results
end
function InputKeyMapUtils.getInputTypeSetForMode(inputKeyMapList, inputMode)
assert(type(inputKeyMapList) == "table", "inputKeyMapList must be a table")
local results = {}
for _, inputKeyMap in pairs(inputKeyMapList) do
if inputKeyMap.inputMode == inputMode then
for _, inputType in pairs(inputKeyMap.inputTypes) do
results[inputType] = true
end
end
end
return results
end
function InputKeyMapUtils.getInputModes(inputKeyMapList)
assert(type(inputKeyMapList) == "table", "inputKeyMapList must be a table")
local modes = {}
for _, inputKeyMap in pairs(inputKeyMapList) do
local mode = assert(inputKeyMap.inputMode, "Bad inputKeyMap.inputMode")
table.insert(modes, mode)
end
return modes
end
function InputKeyMapUtils.isTouchButton(inputKeyMapList)
for _, inputKeyMap in pairs(inputKeyMapList) do
assert(inputKeyMap.inputMode, "Bad inputKeyMap.inputMode")
assert(inputKeyMap.inputTypes, "Bad inputKeyMap.inputTypes")
for _, _type in pairs(inputKeyMap.inputTypes) do
if _type == "TouchButton" then
return true
end
end
end
return false
end
function InputKeyMapUtils.isTapInWorld(inputKeyMapList)
assert(type(inputKeyMapList) == "table", "inputKeyMap must be a table")
for _, inputKeyMap in pairs(inputKeyMapList) do
assert(inputKeyMap.inputMode, "Bad inputKeyMap.inputMode")
assert(inputKeyMap.inputTypes, "Bad inputKeyMap.inputTypes")
for _, _type in pairs(inputKeyMap.inputTypes) do
if _type == "Tap" then
return true
end
end
end
return false
end
return InputKeyMapUtils
|
fix: Turns out assert passes multiple arguments so this was bad code
|
fix: Turns out assert passes multiple arguments so this was bad code
|
Lua
|
mit
|
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
|
049da6125a3c669845945049d4539435079e1182
|
himan-scripts/emc.lua
|
himan-scripts/emc.lua
|
--- ensemble member count
local currentProducer = configuration:GetSourceProducer(0)
local currentProducerName = currentProducer.GetName(currentProducer)
msg = string.format("Calculating ensemble member count for for producer: %s", currentProducerName)
logger:Info(msg)
local params = {}
params["T-K"] = { current_level, 0, 0 }
local ensemble_size = 0
if configuration:Exists("ensemble_size") then
ensemble_size = tonumber(configuration:GetValue("ensemble_size"))
end
msg = string.format("Ensemble size: %d", ensemble_size)
logger:Info(msg)
for key, value in pairs(params) do
ens = nil
-- For MEPS and GLAMEPS we use lagged ensemble (with different lag)
if currentProducerName == "GLAMEPSCAL" or currentProducerName == "MEPS" then
ens = lagged_ensemble(param(key), ensemble_size, time_duration(HPTimeResolution.kHourResolution, -6), 2)
else
ens = ensemble(param(key), ensemble_size)
end
ens:SetMaximumMissingForecasts(2500)
ens:Fetch(configuration, current_time, value[1])
local sz = ens:Size()
local missing_members = ensemble_size - sz
params[key][3] = sz
if missing_members > 0 then
params[key][2] = value[2] + missing_members
end
end
for key, value in pairs(params) do
msg = string.format("Parameter '%s' missing %d members", key, value[2])
logger:Info(msg)
end
local values = {}
for i = 1, result:SizeLocations() do
values[i] = params["T-K"][3]
end
result:SetValues(values)
result:SetParam(param("ENSMEMB-N"))
result:SetForecastType(forecast_type(HPForecastType.kStatisticalProcessing))
logger:Info("Writing source data to file")
luatool:WriteToFile(result)
|
--- ensemble member count
local currentProducer = configuration:GetSourceProducer(0)
local currentProducerName = currentProducer.GetName(currentProducer)
msg = string.format("Calculating ensemble member count for for producer: %s", currentProducerName)
logger:Info(msg)
local params = {}
params["T-K"] = { current_level, 0, 0 }
local ensemble_size = 0
if configuration:Exists("ensemble_size") then
ensemble_size = tonumber(configuration:GetValue("ensemble_size"))
end
msg = string.format("Ensemble size: %d", ensemble_size)
logger:Info(msg)
for key, value in pairs(params) do
ens = nil
-- For MEPS we use lagged ensemble
if currentProducerName == "MEPS" then
ens = lagged_ensemble(param(key), ensemble_size, time_duration(HPTimeResolution.kHourResolution, -1), 6)
else
ens = ensemble(param(key), ensemble_size)
end
ens:SetMaximumMissingForecasts(2500)
ens:Fetch(configuration, current_time, value[1])
local sz = ens:Size()
local missing_members = ensemble_size - sz
params[key][3] = sz
if missing_members > 0 then
params[key][2] = value[2] + missing_members
end
end
for key, value in pairs(params) do
msg = string.format("Parameter '%s' missing %d members", key, value[2])
logger:Info(msg)
end
local values = {}
for i = 1, result:SizeLocations() do
values[i] = params["T-K"][3]
end
result:SetValues(values)
result:SetParam(param("ENSMEMB-N"))
result:SetForecastType(forecast_type(HPForecastType.kStatisticalProcessing))
logger:Info("Writing source data to file")
luatool:WriteToFile(result)
|
HIMAN-294: fix emc.lua to work with cmeps
|
HIMAN-294: fix emc.lua to work with cmeps
|
Lua
|
mit
|
fmidev/himan,fmidev/himan,fmidev/himan
|
7bf0f748394e4ec19e3f6f1cff60f94943dbb348
|
src/cosy/tool/cli.lua
|
src/cosy/tool/cli.lua
|
package.path = package.path .. ";./?.lua"
local Loader = require "cosy.loader.lua" {}
local I18n = Loader.load "cosy.i18n"
local Scheduler = Loader.load "cosy.scheduler"
local Layer = Loader.require "layeredata"
local Arguments = Loader.require "argparse"
local Colors = Loader.require "ansicolors"
local i18n = I18n.load {
"cosy.tool",
}
local parser = Arguments () {
name = "cosy-tool",
description = i18n ["tool:description"] % {},
add_help = {
action = function () end
},
}
parser:argument "tool" {
description = i18n ["tool:tool:description"] % {},
}
parser:argument "parameters" {
args = "*",
description = i18n ["tool:parameters:description"] % {},
}
parser:require_command (false)
local toolname
do
local arguments = { table.unpack (_G.arg)}
local _exit = _G.os.exit
_G.os.exit = function () end
repeat
local ok, args = parser:pparse (arguments)
if ok then
toolname = args.tool
elseif args:match "^unknown option" then
local option = args:match "^unknown option '(.*)'$"
for i = 1, # arguments do
if arguments [i]:find (option) == 1 then
table.remove (arguments, i)
break
end
end
else
break
end
until ok
-- End of UGLY hack.
_G.os.exit = _exit
end
do
local oldrequire = Layer.require
Layer.require = function (name)
return oldrequire (name:gsub ("/", "."))
end
end
local mytool = toolname and Layer.require (toolname) or nil
local parameters = {}
if mytool then
local parameter_type = mytool [Layer.key.meta].parameter_type
local seen = {}
local function find_parameters (x)
if getmetatable (x) == Layer.Proxy then
if parameter_type <= x then
parameters [x] = true
end
seen [x] = true
for _, v in pairs (x) do
if not seen [v] then
find_parameters (v)
end
end
end
end
find_parameters (mytool)
end
local help = parser
if mytool then
parser = Arguments () {
name = "cosy-tool",
description = i18n ["tool:description"] % {},
add_help = {
action = function () print "here" end
},
}
local command = parser:command (toolname) {
description = mytool.description,
}
for key in pairs (parameters) do
command:option ("--" .. key.name) {
description = key.description
.. (key.type and " (" .. tostring (key.type) .. ")" or ""),
default = key.default,
required = key.default and false or true,
}
end
parser:require_command (true)
help = command
end
local ok, arguments = parser:pparse ()
if not ok then
print (arguments)
print (help:get_help ())
os.exit (1)
end
local all_found = true
for key in pairs (parameters) do
if not arguments [key.name] then
print ("Argument " .. key.name .. " is mandatory.")
all_found = false
else
local value = arguments [key.name]
if key.type == "string" then
value = value
elseif key.type == "number" then
value = tonumber (value)
elseif key.type == "boolean" and key.type:lower () == "true" then
value = true
elseif key.type == "boolean" and key.type:lower () == "false" then
value = false
elseif key.type == "function" then
value = loadstring (value) ()
elseif getmetatable (key.type) == Layer.Proxy then
value = {
[Layer.key.refines] = { Layer.require (value) }
}
else
assert (false)
end
Layer.Proxy.replacewith (key, value)
end
end
if not all_found then
print (help:get_help ())
os.exit (1)
end
Scheduler.addthread (function ()
mytool.run {
model = mytool,
scheduler = Scheduler,
}
end)
Scheduler.loop ()
do
local filename = os.tmpname ()
local file = io.open (filename, "w")
file:write (Layer.encode (mytool))
file:close ()
print (Colors ("%{green blackbg}" .. i18n ["tool:model-output"] % {
filename = filename,
}))
end
|
package.path = package.path .. ";./?.lua"
local Loader = require "cosy.loader.lua" {}
local I18n = Loader.load "cosy.i18n"
local Scheduler = Loader.load "cosy.scheduler"
local Layer = Loader.require "layeredata"
local Arguments = Loader.require "argparse"
local Colors = Loader.require "ansicolors"
local i18n = I18n.load {
"cosy.tool",
}
local parser = Arguments () {
name = "cosy-tool",
description = i18n ["tool:description"] % {},
add_help = {
action = function () end
},
}
parser:argument "tool" {
description = i18n ["tool:tool:description"] % {},
}
parser:argument "parameters" {
args = "*",
description = i18n ["tool:parameters:description"] % {},
}
parser:require_command (false)
local toolname
do
local arguments = { table.unpack (_G.arg)}
local _exit = _G.os.exit
_G.os.exit = function () end
repeat
local ok, args = parser:pparse (arguments)
if ok then
toolname = args.tool
elseif args:match "^unknown option" then
local option = args:match "^unknown option '(.*)'$"
for i = 1, # arguments do
if arguments [i]:find (option) == 1 then
table.remove (arguments, i)
break
end
end
else
break
end
until ok
-- End of UGLY hack.
_G.os.exit = _exit
end
do
Layer.require = function (name)
local package = name:gsub ("/", ".")
if Layer.loaded [package] then
return Layer.loaded [package]
else
local layer = Layer.new {
name = name,
data = {
[Layer.key.labels] = {
[name] = true,
}
}
}
local reference = Layer.reference (name)
layer = require (package) (Layer, layer, reference) or layer
return layer, reference
end
end
end
local mytool = toolname and Layer.require (toolname) or nil
local parameters = {}
if mytool then
local parameter_type = mytool [Layer.key.meta].parameter_type
local seen = {}
local function find_parameters (x)
if getmetatable (x) == Layer.Proxy then
if parameter_type <= x then
parameters [x] = true
end
seen [x] = true
for _, v in pairs (x) do
if not seen [v] then
find_parameters (v)
end
end
end
end
find_parameters (mytool)
end
local help = parser
if mytool then
parser = Arguments () {
name = "cosy-tool",
description = i18n ["tool:description"] % {},
add_help = {
action = function () print "here" end
},
}
local command = parser:command (toolname) {
description = mytool.description,
}
for key in pairs (parameters) do
command:option ("--" .. key.name) {
description = key.description
.. (key.type and " (" .. tostring (key.type) .. ")" or ""),
default = key.default,
required = key.default and false or true,
}
end
parser:require_command (true)
help = command
end
local ok, arguments = parser:pparse ()
if not ok then
print (arguments)
print (help:get_help ())
os.exit (1)
end
local all_found = true
for key in pairs (parameters) do
if not arguments [key.name] then
print ("Argument " .. key.name .. " is mandatory.")
all_found = false
else
local value = arguments [key.name]
if key.type == "string" then
value = value
elseif key.type == "number" then
value = tonumber (value)
elseif key.type == "boolean" and key.type:lower () == "true" then
value = true
elseif key.type == "boolean" and key.type:lower () == "false" then
value = false
elseif key.type == "function" then
value = loadstring (value) ()
elseif getmetatable (key.type) == Layer.Proxy then
value = {
[Layer.key.refines] = { Layer.require (value) }
}
else
assert (false)
end
Layer.Proxy.replacewith (key, value)
end
end
if not all_found then
print (help:get_help ())
os.exit (1)
end
Scheduler.addthread (function ()
mytool.run {
model = mytool,
scheduler = Scheduler,
}
end)
Scheduler.loop ()
do
local filename = os.tmpname ()
local file = io.open (filename, "w")
file:write (Layer.encode (mytool))
file:close ()
print (Colors ("%{green blackbg}" .. i18n ["tool:model-output"] % {
filename = filename,
}))
end
|
Update Layer.require to automatically add labels. Fix #190
|
Update Layer.require to automatically add labels.
Fix #190
|
Lua
|
mit
|
CosyVerif/library,CosyVerif/library,CosyVerif/library
|
4bbf168de180f887ab6005072bc8867b83b1995a
|
nyagos.lua
|
nyagos.lua
|
--------------------------------------------------------------------------
-- DO NOT EDIT THIS. PLEASE EDIT ~\.nyagos OR ADD SCRIPT INTO nyagos.d\ --
--------------------------------------------------------------------------
if nyagos == nil then
print("This is the startup script for NYAGOS")
print("Do not run this with lua.exe")
os.exit(0)
end
nyagos.ole = require('nyole')
local fsObj = nyagos.ole.create_object_utf8('Scripting.FileSystemObject')
nyagos.fsObj = fsObj
local nyoleVer = fsObj:GetFileVersion(nyagos.ole.dll_utf8)
nyagos.alias = setmetatable({},{
__call=function(t,k,v) nyagos.setalias(k,v) end,
__newindex=function(t,k,v) nyagos.setalias(k,v) end,
__index=function(t,k) return nyagos.getalias(k,v) end
})
function x(s)
for line in string.gmatch(s,'[^\r\n]+') do
local status,errmsg = nyagos.exec(line)
if not status then
nyagos.writerr(errmsg.."\n")
end
end
end
print( "Nihongo Yet Another GOing Shell " .. (nyagos.version or "") ..
" Powered by " .. _VERSION .. " & nyole.dll ".. nyoleVer)
if not nyagos.version or string.len(nyagos.version) <= 0 then
print("Build at "..(nyagos.stamp or "").." with commit "..(nyagos.commit or ""))
end
print("Copyright (c) 2014,2015 HAYAMA_Kaoru and NYAOS.ORG")
local function expand(text)
return string.gsub(text,"%%(%w+)%%",function(w)
return nyagos.getenv(w)
end)
end
local function set_(f,equation,expand)
if type(equation) == 'table' then
for left,right in pairs(equation) do
f(left,expand(right))
end
return true
end
local pluspos=string.find(equation,"+=",1,true)
if pluspos and pluspos > 0 then
local left=string.sub(equation,1,pluspos-1)
equation = string.format("%s=%s;%%%s%%",
left,string.sub(equation,pluspos+2),left)
end
local pos=string.find(equation,"=",1,true)
if pos then
local left=string.sub(equation,1,pos-1)
local right=string.sub(equation,pos+1)
f( left , expand(right) )
return true
end
return false,(equation .. ': invalid format')
end
function set(equation)
set_(nyagos.setenv,equation,expand)
end
function alias(equation)
set_(nyagos.alias,equation,function(x) return x end)
end
function addpath(...)
for _,dir in pairs{...} do
dir = expand(dir)
local list=nyagos.getenv("PATH")
if not string.find(";"..list..";",";"..dir..";",1,true) then
nyagos.setenv("PATH",dir..";"..list)
end
end
end
function nyagos.echo(s)
nyagos.write((s or '<nil>')..'\n')
end
io.getenv = nyagos.getenv
io.setenv = nyagos.setenv
original_print = print
print = nyagos.echo
local function include(fname)
local chank,err=loadfile(fname)
if err then
print(err)
elseif chank then
local ok,err=pcall(chank)
if not ok then
print(fname .. ": " ..err)
end
else
print(fname .. ":fail to load")
end
end
local dotFolderPath = string.gsub(nyagos.exe,"%.exe$",".d")
local dotFolder = fsObj:GetFolder(dotFolderPath)
local files = dotFolder:files()
for p in files:__iter__() do
local path = nyagos.fsObj:BuildPath(dotFolderPath,p.Name)
include(path)
end
local home = nyagos.getenv("HOME") or nyagos.getenv("USERPROFILE")
if home then
local dotfile = fsObj:BuildPath(home,'.nyagos')
local fd=io.open(dotfile)
if fd then
fd:close()
include(dotfile)
end
end
|
--------------------------------------------------------------------------
-- DO NOT EDIT THIS. PLEASE EDIT ~\.nyagos OR ADD SCRIPT INTO nyagos.d\ --
--------------------------------------------------------------------------
if nyagos == nil then
print("This is the startup script for NYAGOS")
print("Do not run this with lua.exe")
os.exit(0)
end
nyagos.ole = require('nyole')
local fsObj = nyagos.ole.create_object_utf8('Scripting.FileSystemObject')
nyagos.fsObj = fsObj
local nyoleVer = fsObj:GetFileVersion(nyagos.ole.dll_utf8)
nyagos.alias = setmetatable({},{
__call=function(t,k,v) nyagos.setalias(k,v) end,
__newindex=function(t,k,v) nyagos.setalias(k,v) end,
__index=function(t,k) return nyagos.getalias(k,v) end
})
function x(s)
for line in string.gmatch(s,'[^\r\n]+') do
local status,errmsg = nyagos.exec(line)
if not status then
nyagos.writerr(errmsg.."\n")
end
end
end
print( "Nihongo Yet Another GOing Shell " .. (nyagos.version or "") ..
" Powered by " .. _VERSION .. " & nyole.dll ".. nyoleVer)
if not nyagos.version or string.len(nyagos.version) <= 0 then
print("Build at "..(nyagos.stamp or "").." with commit "..(nyagos.commit or ""))
end
print("Copyright (c) 2014,2015 HAYAMA_Kaoru and NYAOS.ORG")
local function expand(text)
return string.gsub(text,"%%(%w+)%%",function(w)
return nyagos.getenv(w)
end)
end
local function set_(f,equation,expand)
if type(equation) == 'table' then
for left,right in pairs(equation) do
f(left,expand(right))
end
return true
end
local pluspos=string.find(equation,"+=",1,true)
if pluspos and pluspos > 0 then
local left=string.sub(equation,1,pluspos-1)
equation = string.format("%s=%s;%%%s%%",
left,string.sub(equation,pluspos+2),left)
end
local pos=string.find(equation,"=",1,true)
if pos then
local left=string.sub(equation,1,pos-1)
local right=string.sub(equation,pos+1)
f( left , expand(right) )
return true
end
return false,(equation .. ': invalid format')
end
function set(equation)
set_(nyagos.setenv,equation,expand)
end
function alias(equation)
set_(nyagos.alias,equation,function(x) return x end)
end
function addpath(...)
for _,dir in pairs{...} do
dir = expand(dir)
local list=nyagos.getenv("PATH")
if not string.find(";"..list..";",";"..dir..";",1,true) then
nyagos.setenv("PATH",dir..";"..list)
end
end
end
function nyagos.echo(s)
nyagos.write((s or '<nil>')..'\n')
end
io.getenv = nyagos.getenv
io.setenv = nyagos.setenv
original_print = print
print = nyagos.echo
local function include(fname)
local chank,err=loadfile(fname)
if err then
print(err)
elseif chank then
local ok,err=pcall(chank)
if not ok then
print(fname .. ": " ..err)
end
else
print(fname .. ":fail to load")
end
end
local dotFolderPath = string.gsub(nyagos.exe,"%.exe$",".d")
local dotFolder = fsObj:GetFolder(dotFolderPath)
local files = dotFolder:files()
for p in files:__iter__() do
if string.match(p.Name,"%.[lL][uU][aA]$") then
local path = nyagos.fsObj:BuildPath(dotFolderPath,p.Name)
include(path)
end
end
local home = nyagos.getenv("HOME") or nyagos.getenv("USERPROFILE")
if home then
local dotfile = fsObj:BuildPath(home,'.nyagos')
local fd=io.open(dotfile)
if fd then
fd:close()
include(dotfile)
end
end
|
Fix: nyagos.lua loaded nyagos.d\*.lua~
|
Fix: nyagos.lua loaded nyagos.d\*.lua~
|
Lua
|
bsd-3-clause
|
hattya/nyagos,kissthink/nyagos,tyochiai/nyagos,hattya/nyagos,hattya/nyagos,zetamatta/nyagos,kissthink/nyagos,nocd5/nyagos,tsuyoshicho/nyagos,kissthink/nyagos
|
b50974a20c9dac0d6b8b479d2e6b54b3c5703ab6
|
applications/luci-app-statistics/luasrc/statistics/rrdtool/definitions/load.lua
|
applications/luci-app-statistics/luasrc/statistics/rrdtool/definitions/load.lua
|
-- Copyright 2008 Freifunk Leipzig / Jo-Philipp Wich <[email protected]>
-- Licensed to the public under the Apache License 2.0.
module("luci.statistics.rrdtool.definitions.load", package.seeall)
function item()
return luci.i18n.translate("System Load")
end
function rrdargs( graph, plugin, plugin_instance, dtype )
return {
title = "%H: Load", vlabel = "Load",
y_min = "0",
units_exponent = "0",
number_format = "%5.2lf", data = {
sources = {
load = { "shortterm", "midterm", "longterm" }
},
options = {
load__shortterm = { color = "ff0000", title = "1 minute", noarea = true },
load__midterm = { color = "ff6600", title = "5 minutes", noarea = true },
load__longterm = { color = "ffaa00", title = "15 minutes", noarea = true }
}
}
}
end
|
-- Copyright 2008 Freifunk Leipzig / Jo-Philipp Wich <[email protected]>
-- Licensed to the public under the Apache License 2.0.
module("luci.statistics.rrdtool.definitions.load", package.seeall)
function item()
return luci.i18n.translate("System Load")
end
function rrdargs( graph, plugin, plugin_instance, dtype )
return {
title = "%H: Load", vlabel = "Load",
y_min = "0",
units_exponent = "0",
number_format = "%5.2lf", data = {
sources = {
load = { "shortterm", "midterm", "longterm" }
},
options = {
load__shortterm = {
color = "ff0000",
title = "1 minute",
noarea = true,
weight = 3
},
load__midterm = {
color = "ff6600",
title = "5 minutes",
overlay = true,
weight = 1
},
load__longterm = {
color = "ffaa00",
title = "15 minutes",
overlay = true,
weight = 2
}
}
}
}
end
|
luci-app-statistics: update misleading load view
|
luci-app-statistics: update misleading load view
Fixes: #3301
During my tests and developing with the collectd and so
luci-app-statistics I noticed that the values displayed in the Y-axis
are misleading, because probably the individual values are added
together in each case. So the view is not corrected.
Signed-off-by: Florian Eckert <[email protected]>
|
Lua
|
apache-2.0
|
rogerpueyo/luci,openwrt/luci,tobiaswaldvogel/luci,hnyman/luci,hnyman/luci,nmav/luci,lbthomsen/openwrt-luci,hnyman/luci,openwrt/luci,hnyman/luci,rogerpueyo/luci,hnyman/luci,rogerpueyo/luci,lbthomsen/openwrt-luci,openwrt/luci,lbthomsen/openwrt-luci,nmav/luci,hnyman/luci,tobiaswaldvogel/luci,lbthomsen/openwrt-luci,rogerpueyo/luci,openwrt/luci,nmav/luci,nmav/luci,rogerpueyo/luci,hnyman/luci,openwrt/luci,tobiaswaldvogel/luci,hnyman/luci,openwrt/luci,nmav/luci,rogerpueyo/luci,nmav/luci,tobiaswaldvogel/luci,openwrt/luci,tobiaswaldvogel/luci,rogerpueyo/luci,lbthomsen/openwrt-luci,nmav/luci,lbthomsen/openwrt-luci,lbthomsen/openwrt-luci,nmav/luci,nmav/luci,openwrt/luci,lbthomsen/openwrt-luci,tobiaswaldvogel/luci,tobiaswaldvogel/luci,rogerpueyo/luci,tobiaswaldvogel/luci
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.