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
|
|---|---|---|---|---|---|---|---|---|---|
fee73e603533da4ea73c1f1392122a62e566be03
|
lua/text/seg.lua
|
lua/text/seg.lua
|
ngx.req.read_body()
local POST = ngx.req.get_post_args()
local rapidjson = require("rapidjson")
if POST.q then
query = POST.q
local res = ngx.location.capture(
'/api/external/jieba',
{
method = ngx.HTTP_POST,
body = query
}
)
local split = require("split")
if not res.truncated then
rtn = {
errno = 0,
data = split.split(res.body, ' ')
}
ngx.say(rapidjson.encode(rtn))
else
ngx.say(rapidjson.encode({
errno = 2,
errmsg = "failed to access seg micro-service"
}))
end
return
else
ngx.say(rapidjson.encode({
errno = 1,
errmsg = "post parameter error"
}));
end
|
ngx.req.read_body()
local POST = ngx.req.get_post_args()
local rapidjson = require("rapidjson")
if POST.q then
query = POST.q
local res = ngx.location.capture(
'/api/external/jieba',
{
method = ngx.HTTP_POST,
args = { method = "HMM", format = "simple" },
body = query
}
)
local split = require("split")
if not res.truncated then
rtn = {
errno = 0,
data = split.split(res.body, ' ')
}
ngx.say(rapidjson.encode(rtn))
else
ngx.say(rapidjson.encode({
errno = 2,
errmsg = "failed to access seg micro-service"
}))
end
return
else
ngx.say(rapidjson.encode({
errno = 1,
errmsg = "post parameter error"
}));
end
|
fix seg call parameters to cppjieba-server
|
fix seg call parameters to cppjieba-server
|
Lua
|
apache-2.0
|
zxteloiv/docomo-qa,zxteloiv/docomo-qa,zxteloiv/docomo-qa
|
a98629fc40bae8e420a73559bf9a22a40d6352ce
|
src/runtime/pony/premake4.lua
|
src/runtime/pony/premake4.lua
|
-- premake.override is a premake5 feature.
-- We use this approach to improve Visual Studio Support for Windows.
-- The goal is to force C++ compilation for non-*.cpp/cxx/cc file extensions.
-- By doing this properly, we avoid a MSVC warning about overiding /TC
-- with /TP.
if premake.override then
local force_cpp = { }
function cppforce(inFiles)
for _, val in ipairs(inFiles) do
for _, fname in ipairs(os.matchfiles(val)) do
table.insert(force_cpp, path.getabsolute(fname))
end
end
end
premake.override(premake.vstudio.vc2010, "additionalCompileOptions", function(base, cfg, condition)
if cfg.abspath then
if table.contains(force_cpp, cfg.abspath) then
_p(3,'<CompileAs %s>CompileAsCpp</CompileAs>', condition)
end
end
return base(cfg, condition)
end)
end
function use_flto()
buildoptions {
"-O3",
"-flto",
}
linkoptions {
"-flto",
"-fuse-ld=gold",
}
end
function c_lib()
kind "StaticLib"
language "C"
configuration "not windows"
buildoptions "-std=gnu11"
configuration "Release or Profile"
if(macosx or linux) then
use_flto()
else
if(optimize) then
optimize "Speed"
else
flags "OptimizeSpeed"
end
end
configuration "*"
end
solution "ponyrt"
configurations {"Debug", "Release"}
configuration "not windows"
buildoptions {
"-mcx16",
"-pthread",
"-std=gnu11",
"-march=native",
"-Wunused-parameter",
"-Wno-error=deprecated-declarations",
}
linkoptions {
"-lm",
"-pthread"
}
configuration "*"
includedirs {
"../closure",
"../array",
"../encore",
"../future",
"../task",
"../adt",
"../party",
"libponyrt",
"../common",
"../dtrace",
}
flags {
"ExtraWarnings",
"FatalWarnings",
"Symbols"
}
configuration "Debug"
targetdir "bin/debug"
objdir "obj/debug"
configuration "Release"
targetdir "bin/release"
objdir "obj/release"
defines "NDEBUG"
configuration "macosx"
-- set these to suppress clang warning about -pthread being unused
buildoptions "-Qunused-arguments"
linkoptions "-Qunused-arguments"
configuration "windows"
if(architecture) then
architecture "x64"
end
linkoptions "/NODEFAULTLIB:msvcrt.lib"
if(cppforce) then
cppforce { "**.c" }
end
configuration "not windows"
if(table.contains(_ARGS, "dtrace")) then
defines "USE_DYNAMIC_TRACE"
os.execute("echo '#define USE_DYNAMIC_TRACE' > ../../../release/inc/dtrace_enabled.h")
if os.execute("dtrace -h -s ../common/encore_probes.d -o ../common/encore_probes.h") ~= 0 then
print("Error generating encore DTrace headers. Stop");
os.exit(1)
end
if os.execute("dtrace -h -s ../common/dtrace_probes.d -o ../common/dtrace_probes.h") ~= 0 then
print("Error generating ponyc DTrace headers. Stop");
os.exit(1)
end
if os.is("linux") then
os.execute("dtrace -G -s ../common/encore_probes.d -o ../common/encore_probes.o")
os.execute("dtrace -G -s ../common/dtrace_probes.d -o ../common/dtrace_probes.o")
project "ponyrt"
configuration "Debug"
postbuildcommands {
'ar -rcs bin/debug/libponyrt.a ../common/encore_probes.o',
'ar -rcs bin/debug/libponyrt.a ../common/dtrace_probes.o'
}
configuration "Release"
postbuildcommands {
'ar -rcs bin/release/libponyrt.a ../common/encore_probes.o',
'ar -rcs bin/release/libponyrt.a ../common/dtrace_probes.o',
}
end
else
os.execute("cat /dev/null > ../../../release/inc/dtrace_enabled.h")
end
project "ponyrt"
c_lib()
includedirs {
"./libponyrt/",
}
files {
"./libponyrt/**.h",
"./libponyrt/**.c"
}
project "encore"
c_lib()
files {
"../encore/encore.h",
"../encore/encore.c"
}
project "array"
c_lib()
files {
"../array/array.h",
"../array/array.c"
}
project "tuple"
c_lib()
files {
"../tuple/tuple.h",
"../tuple/tuple.c"
}
project "range"
c_lib()
files {
"../range/range.h",
"../range/range.c"
}
project "task"
c_lib()
files {
"../task/task.h",
"../task/task.c"
}
project "optiontype"
c_lib()
links { "encore" }
files {
"../adt/option.h",
"../adt/option.c"
}
project "closure"
c_lib()
files {
"../closure/closure.h",
"../closure/closure.c"
}
project "party"
c_lib()
links { "future", "array" }
files {
"../party/**.h",
"../party/**.c"
}
project "future"
c_lib()
links { "closure", "array" }
files {
"../future/future.c",
}
project "stream"
c_lib()
links { "future" }
files {
"../stream/stream.h",
"../stream/stream.c"
}
-- -- project "set"
-- -- kind "StaticLib"
-- -- language "C"
-- -- links { "closure" }
-- -- includedirs { "../closure" }
-- -- files {
-- -- "../set/set.c"
-- -- }
|
-- premake.override is a premake5 feature.
-- We use this approach to improve Visual Studio Support for Windows.
-- The goal is to force C++ compilation for non-*.cpp/cxx/cc file extensions.
-- By doing this properly, we avoid a MSVC warning about overiding /TC
-- with /TP.
if premake.override then
local force_cpp = { }
function cppforce(inFiles)
for _, val in ipairs(inFiles) do
for _, fname in ipairs(os.matchfiles(val)) do
table.insert(force_cpp, path.getabsolute(fname))
end
end
end
premake.override(premake.vstudio.vc2010, "additionalCompileOptions", function(base, cfg, condition)
if cfg.abspath then
if table.contains(force_cpp, cfg.abspath) then
_p(3,'<CompileAs %s>CompileAsCpp</CompileAs>', condition)
end
end
return base(cfg, condition)
end)
end
if os.execute("clang -v") == 0 then
premake.gcc.cc = 'clang'
premake.gcc.cxx = 'clang++'
end
function use_flto()
buildoptions {
"-O3",
"-flto",
}
linkoptions {
"-flto",
"-fuse-ld=gold",
}
end
function c_lib()
kind "StaticLib"
language "C"
configuration "not windows"
buildoptions "-std=gnu11"
configuration "Release or Profile"
if(macosx or linux) then
use_flto()
else
if(optimize) then
optimize "Speed"
else
flags "OptimizeSpeed"
end
end
configuration "*"
end
solution "ponyrt"
configurations {"Debug", "Release"}
configuration "not windows"
buildoptions {
"-mcx16",
"-pthread",
"-std=gnu11",
"-march=native",
"-Wunused-parameter",
"-Wno-error=deprecated-declarations",
}
linkoptions {
"-lm",
"-pthread"
}
configuration "*"
includedirs {
"../closure",
"../array",
"../encore",
"../future",
"../task",
"../adt",
"../party",
"libponyrt",
"../common",
"../dtrace",
}
flags {
"ExtraWarnings",
"FatalWarnings",
"Symbols"
}
configuration "Debug"
targetdir "bin/debug"
objdir "obj/debug"
configuration "Release"
targetdir "bin/release"
objdir "obj/release"
defines "NDEBUG"
configuration "macosx"
-- set these to suppress clang warning about -pthread being unused
buildoptions "-Qunused-arguments"
linkoptions "-Qunused-arguments"
configuration "windows"
if(architecture) then
architecture "x64"
end
linkoptions "/NODEFAULTLIB:msvcrt.lib"
if(cppforce) then
cppforce { "**.c" }
end
configuration "not windows"
if(table.contains(_ARGS, "dtrace")) then
defines "USE_DYNAMIC_TRACE"
os.execute("echo '#define USE_DYNAMIC_TRACE' > ../../../release/inc/dtrace_enabled.h")
if os.execute("dtrace -h -s ../common/encore_probes.d -o ../common/encore_probes.h") ~= 0 then
print("Error generating encore DTrace headers. Stop");
os.exit(1)
end
if os.execute("dtrace -h -s ../common/dtrace_probes.d -o ../common/dtrace_probes.h") ~= 0 then
print("Error generating ponyc DTrace headers. Stop");
os.exit(1)
end
if os.is("linux") then
os.execute("dtrace -G -s ../common/encore_probes.d -o ../common/encore_probes.o")
os.execute("dtrace -G -s ../common/dtrace_probes.d -o ../common/dtrace_probes.o")
project "ponyrt"
configuration "Debug"
postbuildcommands {
'ar -rcs bin/debug/libponyrt.a ../common/encore_probes.o',
'ar -rcs bin/debug/libponyrt.a ../common/dtrace_probes.o'
}
configuration "Release"
postbuildcommands {
'ar -rcs bin/release/libponyrt.a ../common/encore_probes.o',
'ar -rcs bin/release/libponyrt.a ../common/dtrace_probes.o',
}
end
else
os.execute("cat /dev/null > ../../../release/inc/dtrace_enabled.h")
end
project "ponyrt"
c_lib()
includedirs {
"./libponyrt/",
}
files {
"./libponyrt/**.h",
"./libponyrt/**.c"
}
project "encore"
c_lib()
files {
"../encore/encore.h",
"../encore/encore.c"
}
project "array"
c_lib()
files {
"../array/array.h",
"../array/array.c"
}
project "tuple"
c_lib()
files {
"../tuple/tuple.h",
"../tuple/tuple.c"
}
project "range"
c_lib()
files {
"../range/range.h",
"../range/range.c"
}
project "task"
c_lib()
files {
"../task/task.h",
"../task/task.c"
}
project "optiontype"
c_lib()
links { "encore" }
files {
"../adt/option.h",
"../adt/option.c"
}
project "closure"
c_lib()
files {
"../closure/closure.h",
"../closure/closure.c"
}
project "party"
c_lib()
links { "future", "array" }
files {
"../party/**.h",
"../party/**.c"
}
project "future"
c_lib()
links { "closure", "array" }
files {
"../future/future.c",
}
project "stream"
c_lib()
links { "future" }
files {
"../stream/stream.h",
"../stream/stream.c"
}
-- -- project "set"
-- -- kind "StaticLib"
-- -- language "C"
-- -- links { "closure" }
-- -- includedirs { "../closure" }
-- -- files {
-- -- "../set/set.c"
-- -- }
|
Fix #863: using clang as the default compiler for runtime
|
Fix #863: using clang as the default compiler for runtime
Currently, we use gcc for building the runtime, and clang for building
the final executable when `encorec` is invoked. However, using two
compilers is not only unnecessary but error-prone as well. 465 is another bug
related to using gcc, so let's use clang in the whole build stack from
now.
|
Lua
|
bsd-3-clause
|
parapluu/encore,parapluu/encore,parapluu/encore
|
ebd8214c5367631f43b583fa633d2d34e6405140
|
hammerspoon/hammerspoon.symlink/modules/monitor-monitor.lua
|
hammerspoon/hammerspoon.symlink/modules/monitor-monitor.lua
|
local serial = require("hs._asm.serial")
local lastScreenId = -1
local usePhysicalIndicator = true
local useVirtualIndicator = true
local currentIndicator = nil
local indicatorHeight = 3 -- 0..1 = percent of menubar, >1 = pixel height
local indicatorColor = hs.drawing.color.asRGB({
red = 0,
green = 1.0,
blue = 0,
alpha = 0.3
})
-- ----------------------------------------------------------------------------= Event Handlers =--=
function handleMonitorMonitorChange()
local focusedWindow = hs.window.focusedWindow()
if not focusedWindow then return end
local screen = focusedWindow:screen()
local screenId = screen:id()
if useVirtualIndicator then updateVirtualScreenIndicator(screen, focusedWindow) end
if screenId == lastScreenId then return end
lastScreenId = screenId
if usePhysicalIndicator then updatePhysicalScreenIndicator(screenId) end
print('Display changed to ' .. screenId)
end
function handleGlobalAppEvent(name, event, app)
if event == hs.application.watcher.launched then
watchApp(app)
elseif event == hs.application.watcher.terminated then
-- Clean up
local appWatcher = _monitorAppWatchers[app:pid()]
if appWatcher then
appWatcher.watcher:stop()
for id, watcher in pairs(appWatcher.windows) do
watcher:stop()
end
_monitorAppWatchers[app:pid()] = nil
end
elseif event == hs.application.watcher.activated then
handleMonitorMonitorChange()
end
end
function handleAppEvent(element, event, watcher, info)
if event == hs.uielement.watcher.windowCreated then
watchWindow(element)
elseif event == hs.uielement.watcher.focusedWindowChanged then
handleMonitorMonitorChange()
updateVirtualScreenIndicator(element:screen(), element)
end
end
function handleWindowEvent(win, event, watcher, info)
if event == hs.uielement.watcher.elementDestroyed then
watcher:stop()
_monitorAppWatchers[info.pid].windows[info.id] = nil
end
end
-- ------------------------------------------------------------------------= Virtual Indicators =--=
-- Based heavily on https://git.io/v6kZN
function updateVirtualScreenIndicator(screen, window)
clearIndicator()
local screeng = screen:fullFrame()
if indicatorHeight >= 0.0 and indicatorHeight <= 1.0 then
height = indicatorHeight*(screen:frame().y - screeng.y)
else
height = indicatorHeight
end
if window:isFullScreen() then
frame = window:frame()
left = frame.x
width = frame.w
else
left = screeng.x
width = screeng.w
end
indicator = hs.drawing.rectangle(hs.geometry.rect(
left,
screeng.y,
width,
height
))
indicator:setFillColor(indicatorColor)
:setFill(true)
:setLevel(hs.drawing.windowLevels.overlay)
:setStroke(false)
:setBehavior(hs.drawing.windowBehaviors.canJoinAllSpaces)
:show()
currentIndicator = indicator
end
function clearIndicator()
if currentIndicator ~= nil then
currentIndicator:delete()
currentIndicator = nil
end
end
-- -----------------------------------------------------------------------= Physical Indicators =--=
function updatePhysicalScreenIndicator(screenId)
local devicePath = getSerialOutputDevice()
if devicePath == "" then return end
port = serial.port(devicePath):baud(115200):open()
if port:isOpen() then
port:write("set " .. screenId .. "\n")
port:flushBuffer()
port:close()
end
end
function getSerialOutputDevice()
local command = "ioreg -c IOSerialBSDClient -r -t " ..
"| awk 'f;/com_silabs_driver_CP210xVCPDriver/{f=1};/IOCalloutDevice/{exit}' " ..
"| sed -n 's/.*\"\\(\\/dev\\/.*\\)\".*/\\1/p'"
local handle = io.popen(command)
local result = handle:read("*a")
handle:close()
-- Strip whitespace - https://www.rosettacode.org/wiki/Strip_whitespace_from_a_string/Top_and_tail#Lua
return result:match("^%s*(.-)%s*$")
end
-- ---------------------------------------------------------------------------= Watcher Helpers =--=
-- from https://gist.github.com/cmsj/591624ef07124ad80a1c
function attachExistingApps()
local apps = hs.application.runningApplications()
apps = hs.fnutils.filter(apps, function(app) return app:title() ~= "Hammerspoon" end)
hs.fnutils.each(apps, function(app) watchApp(app, true) end)
end
function watchApp(app, initializing)
if _monitorAppWatchers[app:pid()] then return end
local watcher = app:newWatcher(handleAppEvent)
if not watcher._element.pid then return end
_monitorAppWatchers[app:pid()] = {
watcher = watcher,
windows = {}
}
watcher:start({ hs.uielement.watcher.focusedWindowChanged })
-- Watch any windows that already exist
for i, window in pairs(app:allWindows()) do
watchWindow(window, initializing)
end
end
function watchWindow(win, initializing)
local appWindows = _monitorAppWatchers[win:application():pid()].windows
if win:isStandard() and not appWindows[win:id()] then
local watcher = win:newWatcher(handleWindowEvent, {
pid = win:pid(),
id = win:id()
})
appWindows[win:id()] = watcher
watcher:start({
hs.uielement.watcher.elementDestroyed,
hs.uielement.watcher.windowResized,
hs.uielement.watcher.windowMoved
})
end
end
-- ----------------------------------------------------------------------------------= Watchers =--=
_monitorAppWatchers = {}
attachExistingApps()
_monitorScreenWatcher = hs.screen.watcher.newWithActiveScreen(handleMonitorMonitorChange):start()
_monitorSpaceWatcher = hs.spaces.watcher.new(handleMonitorMonitorChange):start()
_monitorAppWatcher = hs.application.watcher.new(handleGlobalAppEvent):start()
handleMonitorMonitorChange() -- set the initial screen
-- Run this from the Hammerspoon console to get a listing of display IDs
function listAllScreens ()
local primaryId = hs.screen.primaryScreen():id()
for _, screen in pairs(hs.screen.allScreens()) do
local screenId = screen:id()
print(
"id: " .. screenId ..
" \"" .. screen:name() .. "\"" ..
(screenId == primaryId and " (primary)" or "")
)
end
end
|
local serial = require("hs._asm.serial")
local lastScreenId = -1
local usePhysicalIndicator = true
local useVirtualIndicator = true
local currentIndicator = nil
local indicatorHeight = 3 -- 0..1 = percent of menubar, >1 = pixel height
local indicatorColor = hs.drawing.color.asRGB({
red = 0,
green = 1.0,
blue = 0,
alpha = 0.3
})
-- ----------------------------------------------------------------------------= Event Handlers =--=
function handleMonitorMonitorChange()
local focusedWindow = hs.window.focusedWindow()
if not focusedWindow then return end
local screen = focusedWindow:screen()
local screenId = screen:id()
if useVirtualIndicator then updateVirtualScreenIndicator(screen, focusedWindow) end
if screenId == lastScreenId then return end
lastScreenId = screenId
if usePhysicalIndicator then updatePhysicalScreenIndicator(screenId) end
print('Display changed to ' .. screenId)
end
function handleGlobalAppEvent(name, event, app)
if event == hs.application.watcher.launched then
watchApp(app)
elseif event == hs.application.watcher.terminated then
-- Clean up
local appWatcher = _monitorAppWatchers[app:pid()]
if appWatcher then
appWatcher.watcher:stop()
for id, watcher in pairs(appWatcher.windows) do
watcher:stop()
end
_monitorAppWatchers[app:pid()] = nil
end
elseif event == hs.application.watcher.activated then
handleMonitorMonitorChange()
end
end
function handleAppEvent(element, event, watcher, info)
if event == hs.uielement.watcher.windowCreated then
watchWindow(element)
elseif event == hs.uielement.watcher.focusedWindowChanged then
if element:isWindow() or element:isApplication() then
handleMonitorMonitorChange()
updateVirtualScreenIndicator(element:screen(), element)
end
end
end
function handleWindowEvent(win, event, watcher, info)
if event == hs.uielement.watcher.elementDestroyed then
watcher:stop()
_monitorAppWatchers[info.pid].windows[info.id] = nil
end
end
-- ------------------------------------------------------------------------= Virtual Indicators =--=
-- Based heavily on https://git.io/v6kZN
function updateVirtualScreenIndicator(screen, window)
clearIndicator()
local screeng = screen:fullFrame()
if indicatorHeight >= 0.0 and indicatorHeight <= 1.0 then
height = indicatorHeight*(screen:frame().y - screeng.y)
else
height = indicatorHeight
end
if window:isFullScreen() then
frame = window:frame()
left = frame.x
width = frame.w
else
left = screeng.x
width = screeng.w
end
indicator = hs.drawing.rectangle(hs.geometry.rect(
left,
screeng.y,
width,
height
))
indicator:setFillColor(indicatorColor)
:setFill(true)
:setLevel(hs.drawing.windowLevels.overlay)
:setStroke(false)
:setBehavior(hs.drawing.windowBehaviors.canJoinAllSpaces)
:show()
currentIndicator = indicator
end
function clearIndicator()
if currentIndicator ~= nil then
currentIndicator:delete()
currentIndicator = nil
end
end
-- -----------------------------------------------------------------------= Physical Indicators =--=
function updatePhysicalScreenIndicator(screenId)
local devicePath = getSerialOutputDevice()
if devicePath == "" then return end
port = serial.port(devicePath):baud(115200):open()
if port:isOpen() then
port:write("set " .. screenId .. "\n")
port:flushBuffer()
port:close()
end
end
function getSerialOutputDevice()
local command = "ioreg -c IOSerialBSDClient -r -t " ..
"| awk 'f;/com_silabs_driver_CP210xVCPDriver/{f=1};/IOCalloutDevice/{exit}' " ..
"| sed -n 's/.*\"\\(\\/dev\\/.*\\)\".*/\\1/p'"
local handle = io.popen(command)
local result = handle:read("*a")
handle:close()
-- Strip whitespace - https://www.rosettacode.org/wiki/Strip_whitespace_from_a_string/Top_and_tail#Lua
return result:match("^%s*(.-)%s*$")
end
-- ---------------------------------------------------------------------------= Watcher Helpers =--=
-- from https://gist.github.com/cmsj/591624ef07124ad80a1c
function attachExistingApps()
local apps = hs.application.runningApplications()
apps = hs.fnutils.filter(apps, function(app) return app:title() ~= "Hammerspoon" end)
hs.fnutils.each(apps, function(app) watchApp(app, true) end)
end
function watchApp(app, initializing)
if _monitorAppWatchers[app:pid()] then return end
local watcher = app:newWatcher(handleAppEvent)
if not watcher._element.pid then return end
_monitorAppWatchers[app:pid()] = {
watcher = watcher,
windows = {}
}
watcher:start({ hs.uielement.watcher.focusedWindowChanged })
-- Watch any windows that already exist
for i, window in pairs(app:allWindows()) do
watchWindow(window, initializing)
end
end
function watchWindow(win, initializing)
local appWindows = _monitorAppWatchers[win:application():pid()].windows
if win:isStandard() and not appWindows[win:id()] then
local watcher = win:newWatcher(handleWindowEvent, {
pid = win:pid(),
id = win:id()
})
appWindows[win:id()] = watcher
watcher:start({
hs.uielement.watcher.elementDestroyed,
hs.uielement.watcher.windowResized,
hs.uielement.watcher.windowMoved
})
end
end
-- ----------------------------------------------------------------------------------= Watchers =--=
_monitorAppWatchers = {}
attachExistingApps()
_monitorScreenWatcher = hs.screen.watcher.newWithActiveScreen(handleMonitorMonitorChange):start()
_monitorSpaceWatcher = hs.spaces.watcher.new(handleMonitorMonitorChange):start()
_monitorAppWatcher = hs.application.watcher.new(handleGlobalAppEvent):start()
handleMonitorMonitorChange() -- set the initial screen
-- Run this from the Hammerspoon console to get a listing of display IDs
function listAllScreens ()
local primaryId = hs.screen.primaryScreen():id()
for _, screen in pairs(hs.screen.allScreens()) do
local screenId = screen:id()
print(
"id: " .. screenId ..
" \"" .. screen:name() .. "\"" ..
(screenId == primaryId and " (primary)" or "")
)
end
end
|
fix(Hammerspoon): only check for screen if the element is an app or window
|
fix(Hammerspoon): only check for screen if the element is an app or window
|
Lua
|
mit
|
sethvoltz/dotfiles,sethvoltz/dotfiles,sethvoltz/dotfiles,sethvoltz/dotfiles
|
eef62e622a848d6af09e3754c0f0b0cc7566384b
|
init.lua
|
init.lua
|
--[[
Copyright 2014 The Luvit Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
local uv = require('uv')
return function (main, ...)
-- Inject the global process table
_G.process = require('process').globalProcess()
-- Seed Lua's RNG
do
local math = require('math')
local os = require('os')
math.randomseed(os.time())
end
-- Load Resolver
do
local dns = require('dns')
dns.loadResolver()
end
-- EPIPE ignore
do
if jit.os ~= 'Windows' then
local sig = uv.new_signal()
uv.signal_start(sig, 'sigpipe')
uv.unref(sig)
end
end
local args = {...}
local success, err = xpcall(function ()
-- Call the main app inside a coroutine
coroutine.wrap(main)(unpack(args))
-- Start the event loop
uv.run()
end, function(err)
-- During a stack overflow error, this can fail due to exhausting the remaining stack.
-- We can't recover from that failure, but wrapping it in a pcall allows us to still
-- return the stack overflow error even if the 'process.uncaughtException' fails to emit
pcall(function() require('hooks'):emit('process.uncaughtException',err) end)
return debug.traceback(err)
end)
if success then
-- Allow actions to run at process exit.
require('hooks'):emit('process.exit')
uv.run()
else
_G.process.exitCode = -1
require('pretty-print').stderr:write("Uncaught exception:\n" .. err .. "\n")
end
local function isFileHandle(handle, name, fd)
return _G.process[name].handle == handle and uv.guess_handle(fd) == 'file'
end
local function isStdioFileHandle(handle)
return isFileHandle(handle, 'stdin', 0) or isFileHandle(handle, 'stdout', 1) or isFileHandle(handle, 'stderr', 2)
end
-- When the loop exits, close all unclosed uv handles (flushing any streams found).
uv.walk(function (handle)
if handle then
local function close()
if not handle:is_closing() then handle:close() end
end
-- The isStdioFileHandle check is a hacky way to avoid an abort when a stdio handle is a pipe to a file
-- TODO: Fix this in a better way, see https://github.com/luvit/luvit/issues/1094
if handle.shutdown and not isStdioFileHandle(handle) then
handle:shutdown(close)
else
close()
end
end
end)
uv.run()
-- Send the exitCode to luvi to return from C's main.
return _G.process.exitCode
end
|
--[[
Copyright 2014 The Luvit Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
local uv = require('uv')
return function (main, ...)
-- Inject the global process table
_G.process = require('process').globalProcess()
-- Seed Lua's RNG
do
local math = require('math')
local os = require('os')
math.randomseed(os.time())
end
-- Load Resolver
do
local dns = require('dns')
dns.loadResolver()
end
-- EPIPE ignore
do
if jit.os ~= 'Windows' then
local sig = uv.new_signal()
uv.signal_start(sig, 'sigpipe')
uv.unref(sig)
end
end
local args = {...}
local success, err = xpcall(function ()
-- Call the main app inside a coroutine
local utils = require('utils')
local thread = coroutine.create(main)
utils.assertResume(thread, unpack(args))
-- Start the event loop
uv.run()
end, function(err)
-- During a stack overflow error, this can fail due to exhausting the remaining stack.
-- We can't recover from that failure, but wrapping it in a pcall allows us to still
-- return the stack overflow error even if the 'process.uncaughtException' fails to emit
pcall(function() require('hooks'):emit('process.uncaughtException',err) end)
return debug.traceback(err)
end)
if success then
-- Allow actions to run at process exit.
require('hooks'):emit('process.exit')
uv.run()
else
_G.process.exitCode = -1
require('pretty-print').stderr:write("Uncaught exception:\n" .. err .. "\n")
end
local function isFileHandle(handle, name, fd)
return _G.process[name].handle == handle and uv.guess_handle(fd) == 'file'
end
local function isStdioFileHandle(handle)
return isFileHandle(handle, 'stdin', 0) or isFileHandle(handle, 'stdout', 1) or isFileHandle(handle, 'stderr', 2)
end
-- When the loop exits, close all unclosed uv handles (flushing any streams found).
uv.walk(function (handle)
if handle then
local function close()
if not handle:is_closing() then handle:close() end
end
-- The isStdioFileHandle check is a hacky way to avoid an abort when a stdio handle is a pipe to a file
-- TODO: Fix this in a better way, see https://github.com/luvit/luvit/issues/1094
if handle.shutdown and not isStdioFileHandle(handle) then
handle:shutdown(close)
else
close()
end
end
end)
uv.run()
-- Send the exitCode to luvi to return from C's main.
return _G.process.exitCode
end
|
fix main thread tracebacks
|
fix main thread tracebacks
|
Lua
|
apache-2.0
|
zhaozg/luvit,luvit/luvit,zhaozg/luvit,luvit/luvit
|
604f2f412e5a5ca9cdb21e7642e0ec856039ca2c
|
plugins/lua.lua
|
plugins/lua.lua
|
local lua = {}
local mattata = require('mattata')
local URL = require('socket.url')
local JSON = require('serpent')
function lua:init(configuration)
lua.commands = mattata.commands(self.info.username, configuration.commandPrefix):c('lua'):c('return').table
JSON = require('dkjson')
lua.serialise = function(t) return JSON.encode(t, {indent=true}) end
lua.loadstring = load or loadstring
lua.error_message = function(x)
return 'Error:\n' .. tostring(x)
end
end
function lua:onMessageReceive(msg, configuration)
if msg.from.id ~= configuration.owner then
if msg.from.id ~= 265945726 then
return true
end
end
local input = mattata.input(msg.text)
if not input then
mattata.sendMessage(msg.chat.id, 'Please enter a string of lua to execute', nil, true, false, msg.message_id, nil)
return
end
if msg.text_lower:match('^' .. configuration.commandPrefix .. 'return') then
input = 'return ' .. input
end
local output, success = loadstring( [[
local mattata = require('mattata')
local JSON = require('dkjson')
local URL = require('socket.url')
local HTTP = require('socket.http')
local HTTPS = require('ssl.https')
return function (msg, configuration) ]] .. input .. [[ end
]] )
if output == nil then
output = success
else
success, output = xpcall(output(), lua.error_message, msg, configuration)
end
if output ~= nil then
if type(output) == 'table' then
local s = lua.serialise(output)
output = s
end
output = '`' .. tostring(output) .. '`'
end
mattata.sendMessage(msg.chat.id, output, 'Markdown', true, false, msg.message_id, nil)
end
return lua
|
local lua = {}
local mattata = require('mattata')
local URL = require('socket.url')
local JSON = require('serpent')
function lua:init(configuration)
lua.commands = mattata.commands(self.info.username, configuration.commandPrefix):c('lua'):c('return').table
JSON = require('dkjson')
lua.serialise = function(t) return JSON.encode(t, {indent=true}) end
lua.loadstring = load or loadstring
lua.error_message = function(x)
return 'Error:\n' .. tostring(x)
end
end
function lua:onMessageReceive(msg, configuration)
if msg.from.id ~= configuration.owner then
return true
end
local input = mattata.input(msg.text)
if not input then
mattata.sendMessage(msg.chat.id, 'Please enter a string of lua to execute', nil, true, false, msg.message_id, nil)
return
end
if msg.text_lower:match('^' .. configuration.commandPrefix .. 'return') then
input = 'return ' .. input
end
local output, success = loadstring( [[
local mattata = require('mattata')
local JSON = require('dkjson')
local URL = require('socket.url')
local HTTP = require('socket.http')
local HTTPS = require('ssl.https')
return function (msg, configuration) ]] .. input .. [[ end
]] )
if output == nil then
output = success
else
success, output = xpcall(output(), lua.error_message, msg, configuration)
end
if output ~= nil then
if type(output) == 'table' then
local s = lua.serialise(output)
output = s
end
output = '`' .. tostring(output) .. '`'
end
mattata.sendMessage(msg.chat.id, output, 'Markdown', true, false, msg.message_id, nil)
end
return lua
|
mattata v3.1
|
mattata v3.1
Fixed a deadly bug which would grant my account access to your server
|
Lua
|
mit
|
barreeeiroo/BarrePolice
|
b728deb96705ea4febb7f161d6fefb28f742bd01
|
lexers/props.lua
|
lexers/props.lua
|
-- Copyright 2006-2011 Mitchell mitchell<att>caladbolg.net. See LICENSE.
-- Props LPeg lexer.
local l = lexer
local token, style, color, word_match = l.token, l.style, l.color, l.word_match
local P, R, S = l.lpeg.P, l.lpeg.R, l.lpeg.S
module(...)
-- Whitespace.
local ws = token(l.WHITESPACE, l.space^1)
-- Comments.
local comment = token(l.COMMENT, '#' * l.nonnewline^0)
-- Equals.
local equals = token(l.OPERATOR, '=')
-- Strings.
local sq_str = l.delimited_range("'", '\\', true)
local dq_str = l.delimited_range('"', '\\', true)
local string = token(l.STRING, sq_str + dq_str)
-- Variables.
local variable = token(l.VARIABLE, '$(' * (l.any - ')')^1 * ')')
-- Colors.
local xdigit = l.xdigit
local color = token('color', '#' * xdigit * xdigit * xdigit * xdigit * xdigit *
xdigit)
_rules = {
{ 'whitespace', ws },
{ 'comment', comment },
{ 'equals', equals },
{ 'string', string },
{ 'variable', variable },
{ 'color', color },
{ 'any_char', l.any_char },
}
_tokenstyles = {
{ 'variable', l.style_keyword },
{ 'color', l.style_number },
}
_LEXBYLINE = true
|
-- Copyright 2006-2011 Mitchell mitchell<att>caladbolg.net. See LICENSE.
-- Props LPeg lexer.
local l = lexer
local token, style, color, word_match = l.token, l.style, l.color, l.word_match
local P, R, S = l.lpeg.P, l.lpeg.R, l.lpeg.S
module(...)
-- Whitespace.
local ws = token(l.WHITESPACE, l.space^1)
-- Comments.
local comment = token(l.COMMENT, '#' * l.nonnewline^0)
-- Equals.
local equals = token(l.OPERATOR, '=')
-- Strings.
local sq_str = l.delimited_range("'", '\\', true)
local dq_str = l.delimited_range('"', '\\', true)
local string = token(l.STRING, sq_str + dq_str)
-- Variables.
local variable = token(l.VARIABLE, '$(' * (l.any - ')')^1 * ')')
-- Colors.
local xdigit = l.xdigit
local color = token('color', '#' * xdigit * xdigit * xdigit * xdigit * xdigit *
xdigit)
_rules = {
{ 'whitespace', ws },
{ 'color', color },
{ 'comment', comment },
{ 'equals', equals },
{ 'string', string },
{ 'variable', variable },
{ 'any_char', l.any_char },
}
_tokenstyles = {
{ 'variable', l.style_keyword },
{ 'color', l.style_number },
}
_LEXBYLINE = true
|
Fixed bug with colors styled as comments; lexers/props.lua
|
Fixed bug with colors styled as comments; lexers/props.lua
|
Lua
|
mit
|
rgieseke/scintillua
|
723fca093893e92b075db2eeb03c7e9365ce1fa5
|
lua/tools/git.lua
|
lua/tools/git.lua
|
local nvim = require'nvim'
local executable = require'tools.files'.executable
if not executable('git') then
return false
end
local set_command = nvim.commands.set_command
-- local set_mapping = nvim.mappings.set_mapping
-- local get_mapping = nvim.mappings.get_mapping
local jobs = require'jobs'
local M = {}
local function parse_git_output(jobid, data)
assert(type(data) == 'string', 'Not valid data: '..type(data))
local input = ''
if data:match('^[uU]sername.*') then
input = nvim.fn.inputsecret('Git username: ')
elseif data:match('^[pP]assword.*') then
input = nvim.fn.inputsecret('Git password: ')
end
if input and input ~= '' then
if input:sub(#input, #input) ~= '\n' then
input = input .. '\n'
end
nvim.fn.chansend(jobid, input)
else
vim.defer_fn(function()
jobs.kill_job(jobid)
end,
1
)
end
end
function M.set_commands()
set_command {
lhs = 'GPull',
rhs = function(args)
local cmd = {'git'}
if nvim.b.project_root and nvim.b.project_root.is_git then
vim.list_extend(cmd, {'--git-dir', nvim.b.project_root.git_dir})
end
cmd[#cmd + 1] = 'pull'
if args and args ~= '' then
cmd[#cmd + 1] = args
end
jobs.send_job{
cmd = cmd,
save_data = true,
opts = {
pty = true,
on_stdout = function(jobid, data, _)
-- print('Git data: ', vim.inspect(data))
if type(data) == 'table' then
for _,val in pairs(data) do
parse_git_output(jobid, val)
end
elseif type(data) == 'string' then
parse_git_output(jobid, data)
end
end
},
}
end,
args = {nargs = '*', force = true, buffer = true}
}
end
return M
|
local nvim = require'nvim'
local executable = require'tools.files'.executable
if not executable('git') then
return false
end
local set_command = nvim.commands.set_command
-- local set_mapping = nvim.mappings.set_mapping
-- local get_mapping = nvim.mappings.get_mapping
local jobs = require'jobs'
local M = {}
local function parse_git_output(jobid, data)
assert(type(data) == 'string', 'Not valid data: '..type(data))
local input = ''
local requested_input = false
if data:match('^[uU]sername.*') then
input = nvim.fn.inputsecret('Git username: ')
requested_input = true
elseif data:match('^[pP]assword.*') then
input = nvim.fn.inputsecret('Git password: ')
requested_input = true
end
if input and input ~= '' then
if input:sub(#input, #input) ~= '\n' then
input = input .. '\n'
end
nvim.fn.chansend(jobid, input)
elseif requested_input then
vim.defer_fn(function()
jobs.kill_job(jobid)
end,
1
)
end
end
function M.set_commands()
set_command {
lhs = 'GPull',
rhs = function(args)
local cmd = {'git'}
if nvim.b.project_root and nvim.b.project_root.is_git then
vim.list_extend(cmd, {'--git-dir', nvim.b.project_root.git_dir})
end
cmd[#cmd + 1] = 'pull'
if args and args ~= '' then
cmd[#cmd + 1] = args
end
jobs.send_job{
cmd = cmd,
save_data = true,
opts = {
pty = true,
on_stdout = function(jobid, data, _)
-- print('Git data: ', vim.inspect(data))
if type(data) == 'table' then
for _,val in pairs(data) do
parse_git_output(jobid, val)
end
elseif type(data) == 'string' then
parse_git_output(jobid, data)
end
end
},
}
end,
args = {nargs = '*', force = true, buffer = true}
}
end
return M
|
fix: parse_git_output request input
|
fix: parse_git_output request input
|
Lua
|
mit
|
Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim
|
1227d5c6206e313d220fc205d525650b7c2394d3
|
tests/oven/test_filtering.lua
|
tests/oven/test_filtering.lua
|
--
-- tests/oven/test_filtering.lua
-- Test the project object configuration accessor.
-- Copyright (c) 2011-2014 Jason Perkins and the Premake project
--
local suite = test.declare("oven_filtering")
--
-- Setup
--
local wks, prj
function suite.setup()
wks = test.createWorkspace()
end
local function prepare()
wks = test.getWorkspace(wks)
prj = test.getproject(wks, 1)
end
--
-- Test filtering by the selected action.
--
function suite.onAction()
premake.action.set("vs2012")
filter { "action:vs2012" }
defines { "USE_VS2012" }
prepare()
test.isequal({ "USE_VS2012" }, prj.defines)
end
function suite.onActionMismatch()
premake.action.set("vs2010")
filter { "action:vs2012" }
defines { "USE_VS2012" }
prepare()
test.isequal({}, prj.defines)
end
--
-- Test filtering on command line options.
--
function suite.onOptionNoValue()
_OPTIONS["release"] = ""
filter { "options:release" }
defines { "USE_RELEASE" }
prepare()
test.isequal({ "USE_RELEASE" }, prj.defines)
end
function suite.onOptionNoValueUnset()
filter { "options:release" }
defines { "USE_RELEASE" }
prepare()
test.isequal({ }, prj.defines)
end
function suite.onOptionWithValue()
_OPTIONS["renderer"] = "opengl"
filter { "options:renderer=opengl" }
defines { "USE_OPENGL" }
prepare()
test.isequal({ "USE_OPENGL" }, prj.defines)
end
function suite.onOptionWithValueMismatch()
_OPTIONS["renderer"] = "direct3d"
filter { "options:renderer=opengl" }
defines { "USE_OPENGL" }
prepare()
test.isequal({ }, prj.defines)
end
function suite.onOptionWithValueUnset()
filter { "options:renderer=opengl" }
defines { "USE_OPENGL" }
prepare()
test.isequal({ }, prj.defines)
end
--
-- Test filtering by the selected toolset.
--
function suite.onFilterToolset()
toolset "msc"
filter { "toolset:msc" }
defines { "USE_MSC" }
prepare()
test.isequal({ "USE_MSC" }, prj.defines)
end
function suite.onFilterToolsetMismatch()
toolset "clang"
filter { "toolset:msc" }
defines { "USE_MSC" }
prepare()
test.isequal({}, prj.defines)
end
|
--
-- tests/oven/test_filtering.lua
-- Test the project object configuration accessor.
-- Copyright (c) 2011-2014 Jason Perkins and the Premake project
--
local suite = test.declare("oven_filtering")
--
-- Setup
--
local wks, prj, cfg
function suite.setup()
wks = test.createWorkspace()
end
local function prepare()
wks = test.getWorkspace(wks)
prj = test.getproject(wks, 1)
cfg = test.getconfig(prj, "Debug")
end
--
-- Test filtering by the selected action.
--
function suite.onAction()
premake.action.set("vs2012")
filter { "action:vs2012" }
defines { "USE_VS2012" }
prepare()
test.isequal({ "USE_VS2012" }, prj.defines)
end
function suite.onActionMismatch()
premake.action.set("vs2010")
filter { "action:vs2012" }
defines { "USE_VS2012" }
prepare()
test.isequal({}, prj.defines)
end
--
-- Test filtering on command line options.
--
function suite.onOptionNoValue()
_OPTIONS["release"] = ""
filter { "options:release" }
defines { "USE_RELEASE" }
prepare()
test.isequal({ "USE_RELEASE" }, prj.defines)
end
function suite.onOptionNoValueUnset()
filter { "options:release" }
defines { "USE_RELEASE" }
prepare()
test.isequal({ }, prj.defines)
end
function suite.onOptionWithValue()
_OPTIONS["renderer"] = "opengl"
filter { "options:renderer=opengl" }
defines { "USE_OPENGL" }
prepare()
test.isequal({ "USE_OPENGL" }, prj.defines)
end
function suite.onOptionWithValueMismatch()
_OPTIONS["renderer"] = "direct3d"
filter { "options:renderer=opengl" }
defines { "USE_OPENGL" }
prepare()
test.isequal({ }, prj.defines)
end
function suite.onOptionWithValueUnset()
filter { "options:renderer=opengl" }
defines { "USE_OPENGL" }
prepare()
test.isequal({ }, prj.defines)
end
--
-- Test filtering by the selected toolset.
--
function suite.onFilterToolset()
toolset "msc"
filter { "toolset:msc" }
defines { "USE_MSC" }
prepare()
test.isequal({ "USE_MSC" }, cfg.defines)
end
function suite.onFilterToolsetMismatch()
toolset "clang"
filter { "toolset:msc" }
defines { "USE_MSC" }
prepare()
test.isequal({}, cfg.defines)
end
|
Fixed testing of filtering.
|
Fixed testing of filtering.
|
Lua
|
bsd-3-clause
|
martin-traverse/premake-core,premake/premake-core,Blizzard/premake-core,lizh06/premake-core,soundsrc/premake-core,Zefiros-Software/premake-core,Blizzard/premake-core,CodeAnxiety/premake-core,jstewart-amd/premake-core,tvandijck/premake-core,dcourtois/premake-core,Zefiros-Software/premake-core,CodeAnxiety/premake-core,starkos/premake-core,dcourtois/premake-core,sleepingwit/premake-core,bravnsgaard/premake-core,dcourtois/premake-core,jstewart-amd/premake-core,noresources/premake-core,Blizzard/premake-core,starkos/premake-core,CodeAnxiety/premake-core,bravnsgaard/premake-core,LORgames/premake-core,sleepingwit/premake-core,sleepingwit/premake-core,xriss/premake-core,mendsley/premake-core,tvandijck/premake-core,jstewart-amd/premake-core,CodeAnxiety/premake-core,tvandijck/premake-core,lizh06/premake-core,martin-traverse/premake-core,TurkeyMan/premake-core,lizh06/premake-core,jstewart-amd/premake-core,noresources/premake-core,TurkeyMan/premake-core,LORgames/premake-core,Zefiros-Software/premake-core,Blizzard/premake-core,mandersan/premake-core,lizh06/premake-core,LORgames/premake-core,premake/premake-core,tvandijck/premake-core,starkos/premake-core,xriss/premake-core,tvandijck/premake-core,aleksijuvani/premake-core,noresources/premake-core,soundsrc/premake-core,soundsrc/premake-core,premake/premake-core,dcourtois/premake-core,TurkeyMan/premake-core,LORgames/premake-core,xriss/premake-core,sleepingwit/premake-core,mendsley/premake-core,premake/premake-core,mandersan/premake-core,soundsrc/premake-core,noresources/premake-core,jstewart-amd/premake-core,TurkeyMan/premake-core,Zefiros-Software/premake-core,noresources/premake-core,starkos/premake-core,martin-traverse/premake-core,Zefiros-Software/premake-core,resetnow/premake-core,starkos/premake-core,starkos/premake-core,CodeAnxiety/premake-core,LORgames/premake-core,TurkeyMan/premake-core,dcourtois/premake-core,mendsley/premake-core,bravnsgaard/premake-core,aleksijuvani/premake-core,dcourtois/premake-core,premake/premake-core,mandersan/premake-core,mendsley/premake-core,mandersan/premake-core,noresources/premake-core,xriss/premake-core,aleksijuvani/premake-core,resetnow/premake-core,premake/premake-core,aleksijuvani/premake-core,martin-traverse/premake-core,dcourtois/premake-core,premake/premake-core,resetnow/premake-core,resetnow/premake-core,mandersan/premake-core,soundsrc/premake-core,aleksijuvani/premake-core,starkos/premake-core,mendsley/premake-core,xriss/premake-core,Blizzard/premake-core,bravnsgaard/premake-core,Blizzard/premake-core,sleepingwit/premake-core,bravnsgaard/premake-core,noresources/premake-core,resetnow/premake-core
|
a71f103ce02b59243e07ae7c78856dfebaf2a130
|
src/luaclie.lua
|
src/luaclie.lua
|
require("luaclie_c")
luaclie = {}
--D: Table Miner
--P: table_path : Table path string
--R: keys : Table with all keys on table
luaclie.tableminer = function (table_path)
local current_table = {}
local keys = {}
local key_name
local table_name
if table_path == nil then
table_path = ""
end
current_table = _ENV
for table_name in string.gmatch(table_path, "[^%.^:]+[%.:]") do
if type(current_table) ~= "table" then
return {}
end
current_table = current_table[string.match(table_name, "[^%.^:]+")]
end
if type(current_table) ~= "table" then
return {}
end
for key in pairs(current_table) do
key_name = key
if type(current_table[key]) == "function" then
key_name = key_name .. "("
elseif type(current_table[key]) == "table" then
key_name = key_name .. "."
end
table.insert(keys, key_name)
end
return keys
end
--D: Function Reference
--P: text : Input text with command line
luaclie.funcref = function (text)
local current_table = _ENV
local table_name
local last_func_name = nil
local comment_table = {}
local func_info
local maxlen = 0
local currlen
print()
-- Get function name with table path
for func_name in string.gmatch(text, "[%a%d%.:_]+%(") do
last_func_name = func_name
end
if last_func_name == nil then
print("no function found in \"" .. text .. "\"")
return
end
-- Travel thought tables until function
for func_name in string.gmatch(last_func_name, "[^%.^:^%(]+[%.:%(]") do
if current_table == nil then
print("table \"" .. table_name .. "\" is a nil value")
return
end
table_name = string.match(func_name, "[^%.^:^%(]+")
current_table = current_table[table_name]
end
-- Error: no table
if current_table == nil then
print("function \"" .. table_name .. "\" is a nil value")
return
end
func_info = debug.getinfo(current_table)
-- Error: defined in user interface
if func_info["short_src"] == "stdin" then
print("function defined in user interface, it has no description")
return
elseif func_info["short_src"] == "[C]" then
print("function defined in C code, it has no description")
return
end
local file = io.open(func_info["short_src"])
-- Error: no such file
if file == nil then
print("error: no such file: " .. func_info["short_src"])
return
end
-- Search comments above function
local counter = func_info["linedefined"]-1;
for line in file:lines() do
if string.match(line, "^%-%-") ~= nil then
table.insert(comment_table, line)
else
comment_table = {}
end
counter = counter-1
if counter == 0 then
break
end
end
-- Get maximum string length from comment
for _, line in pairs(comment_table) do
currlen = string.len(line)
if currlen > maxlen then
maxlen = currlen
end
end
if maxlen >= 80 then
maxlen = 80
end
-- Print separator
luaclie.printf("\27[30;4;1m")
for i = 1, maxlen + 18 do
luaclie.printf("-")
end
luaclie.printf("\27[0m\n")
-- Print help text
print("\27[33;1mFunction:\27[0m ")
print(" " .. last_func_name)
print("\27[33;1mReference:\27[0m")
for _, line in pairs(comment_table) do
print(" " .. line)
end
-- Print separator
luaclie.printf("\27[30;4;1m")
for i = 1, maxlen + 18 do
luaclie.printf("-")
end
luaclie.printf("\27[0m\n")
end
--D: C-like printf
luaclie.printf = function (string, ...)
io.write(string.format(string, ...))
end
--D: Clear screen
luaclie.cls = function ()
os.execute("clear")
end
|
require("luaclie_c")
luaclie = {}
luaclie.COLOR = {}
luaclie.COLOR.DEFAULT = "\27[0m"
luaclie.COLOR.GRAY = "\27[2m"
luaclie.COLOR.GRAY0 = "\27[30;1m"
luaclie.COLOR.GRAY1 = "\27[90;2m"
luaclie.COLOR.GRAY2 = "\27[30;3m"
luaclie.COLOR.RED = "\27[31;1m"
luaclie.COLOR.RED0 = "\27[91;2m"
luaclie.COLOR.RED1 = "\27[31;3m"
luaclie.COLOR.RED2 = "\27[31;2m"
luaclie.COLOR.GREEN = "\27[32;1m"
luaclie.COLOR.GREEN0 = "\27[92;2m"
luaclie.COLOR.GREEN1 = "\27[32;3m"
luaclie.COLOR.GREEN2 = "\27[32;2m"
luaclie.COLOR.YELLOW = "\27[33;1m"
luaclie.COLOR.YELLOW0 = "\27[93;2m"
luaclie.COLOR.YELLOW1 = "\27[33;3m"
luaclie.COLOR.YELLOW2 = "\27[33;2m"
luaclie.COLOR.BLUE = "\27[34;1m"
luaclie.COLOR.BLUE0 = "\27[94;2m"
luaclie.COLOR.BLUE1 = "\27[34;3m"
luaclie.COLOR.BLUE2 = "\27[34;2m"
luaclie.COLOR.MAGENTA = "\27[35;1m"
luaclie.COLOR.MAGENTA0 = "\27[95;2m"
luaclie.COLOR.MAGENTA1 = "\27[35;3m"
luaclie.COLOR.MAGENTA2 = "\27[35;2m"
luaclie.COLOR.CYAN = "\27[36;1m"
luaclie.COLOR.CYAN0 = "\27[96;2m"
luaclie.COLOR.CYAN1 = "\27[36;3m"
luaclie.COLOR.CYAN2 = "\27[36;2m"
luaclie.COLOR.BOLD = "\27[1m"
luaclie.COLOR.BG = {}
luaclie.COLOR.BG.GRAY = "\27[47m"
luaclie.COLOR.BG.RED = "\27[41m"
luaclie.COLOR.BG.GREEN = "\27[42m"
luaclie.COLOR.BG.YELLOW = "\27[43m"
luaclie.COLOR.BG.BLUE = "\27[44m"
luaclie.COLOR.BG.MAGENTA = "\27[45m"
luaclie.COLOR.BG.CYAN = "\27[46m"
--D: Table Miner
--P: table_path : Table path string
--R: keys : Table with all keys on table
luaclie.tableminer = function (table_path)
local current_table = {}
local keys = {}
local key_name
local table_name
if table_path == nil then
table_path = ""
end
current_table = _ENV
for table_name in string.gmatch(table_path, "[^%.^:]+[%.:]") do
if type(current_table) ~= "table" then
return {}
end
current_table = current_table[string.match(table_name, "[^%.^:]+")]
end
if type(current_table) ~= "table" then
return {}
end
for key in pairs(current_table) do
key_name = key
if type(current_table[key]) == "function" then
key_name = key_name .. "("
elseif type(current_table[key]) == "table" then
key_name = key_name .. "."
end
table.insert(keys, key_name)
end
return keys
end
--D: Function Reference
--P: text : Input text with command line
luaclie.funcref = function (text)
local current_table = _ENV
local table_name
local last_func_name = nil
local comment_table = {}
local func_info
local maxlen = 0
local currlen
print()
-- Get function name with table path
for func_name in string.gmatch(text, "[%a%d%.:_]+%(") do
last_func_name = func_name
end
if last_func_name == nil then
print("no function found in \"" .. text .. "\"")
return
end
-- Travel thought tables until function
for func_name in string.gmatch(last_func_name, "[^%.^:^%(]+[%.:%(]") do
if current_table == nil then
print("table \"" .. table_name .. "\" is a nil value")
return
end
table_name = string.match(func_name, "[^%.^:^%(]+")
current_table = current_table[table_name]
end
-- Error: no table
if current_table == nil then
print("function \"" .. table_name .. "\" is a nil value")
return
end
func_info = debug.getinfo(current_table)
-- Error: defined in user interface
if func_info["short_src"] == "stdin" then
print("function defined in user interface, it has no description")
return
elseif func_info["short_src"] == "[C]" then
print("function defined in C code, it has no description")
return
end
local file = io.open(func_info["short_src"])
-- Error: no such file
if file == nil then
print("error: no such file: " .. func_info["short_src"])
return
end
-- Search comments above function
local counter = func_info["linedefined"]-1;
for line in file:lines() do
if string.match(line, "^[%s\t]*%-%-") ~= nil then
table.insert(comment_table, string.match(line, "^[%s\t]*(%-%-.*)"))
else
comment_table = {}
end
counter = counter-1
if counter == 0 then
break
end
end
-- Get maximum string length from comment
for _, line in pairs(comment_table) do
currlen = string.len(line)
if currlen > maxlen then
maxlen = currlen
end
end
if maxlen >= 80 then
maxlen = 80
end
-- Print separator
luaclie.printf("\27[30;4;1m")
for i = 1, maxlen + 18 do
luaclie.printf("-")
end
luaclie.printf("\27[0m\n")
-- Print help text
print("\27[33;1mFunction:\27[0m ")
print(" " .. last_func_name)
print("\27[33;1mReference:\27[0m")
for _, line in pairs(comment_table) do
print(" " .. line)
end
-- Print separator
luaclie.printf("\27[30;4;1m")
for i = 1, maxlen + 18 do
luaclie.printf("-")
end
luaclie.printf("\27[0m\n")
end
--D: C-like printf
luaclie.printf = function (string, ...)
io.write(string.format(string, ...))
end
--D: printf with color
luaclie.printc = function (color, string, ...)
luaclie.printf(color)
luaclie.printf(string, ...)
luaclie.printf(luaclie.COLOR.DEFAULT)
end
--D: Clear screen
luaclie.cls = function ()
os.execute("clear")
end
|
- Added print color function - Fixed spaces and tabs ignoring function references.
|
- Added print color function
- Fixed spaces and tabs ignoring function references.
|
Lua
|
mit
|
robimp/luaclie,robimp/luaclie
|
50e8750db46087de805ef419decbbf1a6259e0cb
|
frontend/ui/reader/readerview.lua
|
frontend/ui/reader/readerview.lua
|
ReaderView = WidgetContainer:new{
document = nil,
state = {
page = 0,
pos = 0,
zoom = 1.0,
rotation = 0,
offset = {},
bbox = nil,
},
outer_page_color = 7,
-- DjVu page rendering mode (used in djvu.c:drawPage())
render_mode = 0, -- default to COLOR
-- Crengine view mode
view_mode = "page", -- default to page mode
-- visible area within current viewing page
visible_area = Geom:new{x = 0, y = 0},
-- dimen for current viewing page
page_area = Geom:new{},
-- dimen for area to dim
dim_area = Geom:new{w = 0, h = 0},
}
function ReaderView:paintTo(bb, x, y)
DEBUG("painting", self.visible_area, "to", x, y)
local inner_offset = Geom:new{x = 0, y = 0}
-- draw surrounding space, if any
if self.ui.dimen.h > self.visible_area.h then
inner_offset.y = (self.ui.dimen.h - self.visible_area.h) / 2
bb:paintRect(x, y, self.ui.dimen.w, inner_offset.y, self.outer_page_color)
bb:paintRect(x, y + self.ui.dimen.h - inner_offset.y - 1, self.ui.dimen.w, inner_offset.y + 1, self.outer_page_color)
end
if self.ui.dimen.w > self.visible_area.w then
inner_offset.x = (self.ui.dimen.w - self.visible_area.w) / 2
bb:paintRect(x, y, inner_offset.x, self.ui.dimen.h, self.outer_page_color)
bb:paintRect(x + self.ui.dimen.w - inner_offset.x - 1, y, inner_offset.x + 1, self.ui.dimen.h, self.outer_page_color)
end
-- draw content
if self.ui.document.info.has_pages then
self.ui.document:drawPage(
bb,
x + inner_offset.x,
y + inner_offset.y,
self.visible_area,
self.state.page,
self.state.zoom,
self.state.rotation,
self.render_mode)
UIManager:scheduleIn(0, function() self.ui:handleEvent(Event:new("HintPage")) end)
else
if self.view_mode == "page" then
self.ui.document:drawCurrentViewByPage(
bb,
x + inner_offset.x,
y + inner_offset.y,
self.visible_area,
self.state.page)
else
self.ui.document:drawCurrentViewByPos(
bb,
x + inner_offset.x,
y + inner_offset.y,
self.visible_area,
self.state.pos)
end
end
-- dim last read area
if self.document.view_mode ~= "page"
and self.dim_area.w ~= 0 and self.dim_area.h ~= 0 then
bb:dimRect(
self.dim_area.x, self.dim_area.y,
self.dim_area.w, self.dim_area.h
)
end
end
--[[
This method is supposed to be only used by ReaderPaging
--]]
function ReaderView:recalculate()
local page_size = nil
if self.ui.document.info.has_pages then
if not self.bbox then
self.page_area = self.ui.document:getPageDimensions(
self.state.page,
self.state.zoom,
self.state.rotation)
else
self.page_area = self.ui.document:getUsedBBoxDimensions(
self.state.page,
self.state.zoom,
self.state.rotation)
end
-- starts from left top of page_area
self.visible_area.x = self.page_area.x
self.visible_area.y = self.page_area.y
-- reset our size
self.visible_area:setSizeTo(self.dimen)
-- and recalculate it according to page size
self.visible_area:offsetWithin(self.page_area, 0, 0)
-- clear dim area
self.dim_area.w = 0
self.dim_area.h = 0
self.ui:handleEvent(
Event:new("ViewRecalculate", self.visible_area, self.page_area))
else
self.visible_area:setSizeTo(self.dimen)
end
-- flag a repaint so self:paintTo will be called
UIManager:setDirty(self.dialog)
end
function ReaderView:PanningUpdate(dx, dy)
DEBUG("pan by", dx, dy)
local old = self.visible_area:copy()
self.visible_area:offsetWithin(self.page_area, dx, dy)
if self.visible_area ~= old then
-- flag a repaint
UIManager:setDirty(self.dialog)
DEBUG("on pan: page_area", self.page_area)
DEBUG("on pan: visible_area", self.visible_area)
self.ui:handleEvent(
Event:new("ViewRecalculate", self.visible_area, self.page_area))
end
return true
end
function ReaderView:onSetDimensions(dimensions)
self.dimen = dimensions
-- recalculate view
self:recalculate()
end
function ReaderView:onReadSettings(config)
self.render_mode = config:readSetting("render_mode") or 0
end
function ReaderView:onPageUpdate(new_page_no)
self.state.page = new_page_no
self:recalculate()
end
function ReaderView:onPosUpdate(new_pos)
self.state.pos = new_pos
self:recalculate()
end
function ReaderView:onZoomUpdate(zoom)
self.state.zoom = zoom
self:recalculate()
end
function ReaderView:onBBoxUpdate(bbox)
self.bbox = bbox
end
function ReaderView:onRotationUpdate(rotation)
self.state.rotation = rotation
self:recalculate()
end
function ReaderView:onHintPage()
self.ui.document:hintPage(self.state.page+1, self.state.zoom, self.state.rotation, self.render_mode)
return true
end
function ReaderView:onSetViewMode(new_mode)
self.ui.view_mode = new_mode
self.ui.document:setViewMode(new_mode)
self.ui:handleEvent(Event:new("UpdatePos"))
return true
end
function ReaderView:onCloseDocument()
self.ui.doc_settings:saveSetting("render_mode", self.render_mode)
end
|
ReaderView = WidgetContainer:new{
document = nil,
state = {
page = 0,
pos = 0,
zoom = 1.0,
rotation = 0,
offset = {},
bbox = nil,
},
outer_page_color = 7,
-- DjVu page rendering mode (used in djvu.c:drawPage())
render_mode = 0, -- default to COLOR
-- Crengine view mode
view_mode = "page", -- default to page mode
-- visible area within current viewing page
visible_area = Geom:new{x = 0, y = 0},
-- dimen for current viewing page
page_area = Geom:new{},
-- dimen for area to dim
dim_area = Geom:new{w = 0, h = 0},
}
function ReaderView:paintTo(bb, x, y)
DEBUG("painting", self.visible_area, "to", x, y)
local inner_offset = Geom:new{x = 0, y = 0}
-- draw surrounding space, if any
if self.ui.dimen.h > self.visible_area.h then
inner_offset.y = (self.ui.dimen.h - self.visible_area.h) / 2
bb:paintRect(x, y, self.ui.dimen.w, inner_offset.y, self.outer_page_color)
bb:paintRect(x, y + self.ui.dimen.h - inner_offset.y - 1, self.ui.dimen.w, inner_offset.y + 1, self.outer_page_color)
end
if self.ui.dimen.w > self.visible_area.w then
inner_offset.x = (self.ui.dimen.w - self.visible_area.w) / 2
bb:paintRect(x, y, inner_offset.x, self.ui.dimen.h, self.outer_page_color)
bb:paintRect(x + self.ui.dimen.w - inner_offset.x - 1, y, inner_offset.x + 1, self.ui.dimen.h, self.outer_page_color)
end
-- draw content
if self.ui.document.info.has_pages then
self.ui.document:drawPage(
bb,
x + inner_offset.x,
y + inner_offset.y,
self.visible_area,
self.state.page,
self.state.zoom,
self.state.rotation,
self.render_mode)
UIManager:scheduleIn(0, function() self.ui:handleEvent(Event:new("HintPage")) end)
else
if self.view_mode == "page" then
self.ui.document:drawCurrentViewByPage(
bb,
x + inner_offset.x,
y + inner_offset.y,
self.visible_area,
self.state.page)
else
self.ui.document:drawCurrentViewByPos(
bb,
x + inner_offset.x,
y + inner_offset.y,
self.visible_area,
self.state.pos)
end
end
-- dim last read area
if self.document.view_mode ~= "page"
and self.dim_area.w ~= 0 and self.dim_area.h ~= 0 then
bb:dimRect(
self.dim_area.x, self.dim_area.y,
self.dim_area.w, self.dim_area.h
)
end
end
--[[
This method is supposed to be only used by ReaderPaging
--]]
function ReaderView:recalculate()
local page_size = nil
if self.ui.document.info.has_pages then
if not self.bbox then
self.page_area = self.ui.document:getPageDimensions(
self.state.page,
self.state.zoom,
self.state.rotation)
else
self.page_area = self.ui.document:getUsedBBoxDimensions(
self.state.page,
self.state.zoom,
self.state.rotation)
end
-- starts from left top of page_area
self.visible_area.x = self.page_area.x
self.visible_area.y = self.page_area.y
-- reset our size
self.visible_area:setSizeTo(self.dimen)
-- and recalculate it according to page size
self.visible_area:offsetWithin(self.page_area, 0, 0)
-- clear dim area
self.dim_area.w = 0
self.dim_area.h = 0
self.ui:handleEvent(
Event:new("ViewRecalculate", self.visible_area, self.page_area))
else
self.visible_area:setSizeTo(self.dimen)
end
-- flag a repaint so self:paintTo will be called
UIManager:setDirty(self.dialog)
end
function ReaderView:PanningUpdate(dx, dy)
DEBUG("pan by", dx, dy)
local old = self.visible_area:copy()
self.visible_area:offsetWithin(self.page_area, dx, dy)
if self.visible_area ~= old then
-- flag a repaint
UIManager:setDirty(self.dialog)
DEBUG("on pan: page_area", self.page_area)
DEBUG("on pan: visible_area", self.visible_area)
self.ui:handleEvent(
Event:new("ViewRecalculate", self.visible_area, self.page_area))
end
return true
end
function ReaderView:onSetDimensions(dimensions)
self.dimen = dimensions
-- recalculate view
self:recalculate()
end
function ReaderView:onReadSettings(config)
self.render_mode = config:readSetting("render_mode") or 0
end
function ReaderView:onPageUpdate(new_page_no)
self.state.page = new_page_no
self:recalculate()
end
function ReaderView:onPosUpdate(new_pos)
self.state.pos = new_pos
self:recalculate()
end
function ReaderView:onZoomUpdate(zoom)
self.state.zoom = zoom
self:recalculate()
end
function ReaderView:onBBoxUpdate(bbox)
self.bbox = bbox
end
function ReaderView:onRotationUpdate(rotation)
self.state.rotation = rotation
self:recalculate()
end
function ReaderView:onHintPage()
if self.state.page < self.ui.document.info.number_of_pages then
self.ui.document:hintPage(
self.state.page+1,
self.state.zoom,
self.state.rotation,
self.render_mode)
end
return true
end
function ReaderView:onSetViewMode(new_mode)
self.ui.view_mode = new_mode
self.ui.document:setViewMode(new_mode)
self.ui:handleEvent(Event:new("UpdatePos"))
return true
end
function ReaderView:onCloseDocument()
self.ui.doc_settings:saveSetting("render_mode", self.render_mode)
end
|
fix: check number of pages before calling hintPage
|
fix: check number of pages before calling hintPage
otherwise, we will reach out page limit when reached last page
|
Lua
|
agpl-3.0
|
Hzj-jie/koreader-base,NickSavage/koreader,apletnev/koreader-base,pazos/koreader,NiLuJe/koreader-base,robert00s/koreader,Frenzie/koreader-base,frankyifei/koreader-base,mwoz123/koreader,poire-z/koreader,houqp/koreader-base,houqp/koreader-base,lgeek/koreader,Frenzie/koreader,mihailim/koreader,chihyang/koreader,Markismus/koreader,noname007/koreader,frankyifei/koreader,NiLuJe/koreader-base,houqp/koreader-base,ashhher3/koreader,chrox/koreader,apletnev/koreader-base,houqp/koreader,Frenzie/koreader-base,poire-z/koreader,frankyifei/koreader-base,frankyifei/koreader-base,Hzj-jie/koreader-base,NiLuJe/koreader,NiLuJe/koreader,ashang/koreader,apletnev/koreader-base,apletnev/koreader,Frenzie/koreader-base,Hzj-jie/koreader-base,koreader/koreader-base,NiLuJe/koreader-base,frankyifei/koreader-base,houqp/koreader-base,koreader/koreader-base,Hzj-jie/koreader-base,NiLuJe/koreader-base,koreader/koreader-base,apletnev/koreader-base,koreader/koreader,Frenzie/koreader-base,Frenzie/koreader,koreader/koreader,Hzj-jie/koreader,koreader/koreader-base
|
39548194719b5bd831c7e10b7a1e68da9f685933
|
Nncache.lua
|
Nncache.lua
|
-- Nncache.lua
-- nearest neighbors cache
-- API overview
if false then
-- construction
nnc = Nncache()
-- setter and getter
nnc:setLine(obsIndex, tensor1D)
tensor1D = nnc:getLine(obsIndex) -- may return null
-- apply a function to each key-value pair
local function f(key,value)
end
nnc:apply(f)
-- saving to a file and restoring from one
-- the suffix is determined by the class Nncachebuilder
nnc:save(filePath)
nnc = nnc.load(filePath)
nnc = nnc.loadUsingPrefix(filePathPrefix)
end
--------------------------------------------------------------------------------
-- CONSTRUCTION
--------------------------------------------------------------------------------
torch.class('Nncache')
function Nncache:__init()
self._table = {}
self._lastValuesSize = nil
end
--------------------------------------------------------------------------------
-- PUBLIC CLASS METHODS
--------------------------------------------------------------------------------
function Nncache.load(filePath)
-- return an nnc; error if there is no saved Nncache at the filePath
local v, isVerbose = makeVerbose(true, 'Nncache.load')
verify(v, isVerbose,
{{filePath, 'filePath', 'isString'}})
local nnc = torch.load(filePath,
Nncachebuilder.format())
--v('nnc', nnc)
v('nnc:size()', nnc:size())
v('typename', torch.typename(nnc))
assert(torch.typename(nnc) == 'Nncache',
'bad typename = ' .. tostring(torch.typename(nnc)))
-- NOTE: cannot test if each table entry has 256 rows, because the
-- original allXs may have had fewer than 256 observations
return nnc
end -- read
function Nncache.loadUsingPrefix(filePathPrefix)
return Nncache.load(Nncache._filePath(filePathPrefix))
end -- loadUsingPrefix
--------------------------------------------------------------------------------
-- PRIVATE CLASS METHODS
--------------------------------------------------------------------------------
function Nncache._filePath(filePathPrefix)
return filePathPrefix .. Nncachebuilder.mergedFileSuffix()
end -- _filePath
--------------------------------------------------------------------------------
-- PUBLIC INSTANCE METHODS
--------------------------------------------------------------------------------
function Nncache:apply(f)
-- apply a function to each key-value pair
for key, value in pairs(self._table) do
f(key, value)
end
end -- apply
function Nncache:getLine(obsIndex)
-- return line at key or null
local v, isVerbose = makeVerbose(false, 'Nncache:getline')
verify(v, isVerbose,
{{obsIndex, 'obsIndex', 'isIntegerPositive'}})
return self._table[obsIndex]
end -- getline
function Nncache:setLine(obsIndex, values)
-- set the line, checking that it is not already set
local v, isVerbose = makeVerbose(false, 'Nncache:setLine')
verify(v, isVerbose,
{{obsIndex, 'obsIndex', 'isIntegerPositive'},
{values, 'values', 'isTensor1D'}})
v('self', self)
-- check that size of values is same on every call
if self._lastValuesSize then
local newSize = values:size(1)
assert(self._lastValuesSize == newSize,
string.format('cannot change size of values; \n was %s; \n is %s',
tostring(self._lastValuesSize),
tostring(newSize)))
self._lastValuesSize = newSize
else
self._lastValuesSize = values:size(1)
end
-- check that the obsIndex slot has not already been filled
assert(self._table[obsIndex] == nil,
string.format('attempt to set cache line already filled; \nobsIndex ',
tostring(obsIndex)))
self._table[obsIndex] = values
end -- setLine
function Nncache:save(filePath)
-- write to disk by serializing
-- NOTE: if the name of this method were 'write', then the call below
-- to torch.save would call this function recursively. Hence the name
-- of this function.
local v, isVerbose = makeVerbose(false, 'Nncache:write')
v('self', self)
verify(v, isVerbose,
{{filePath, 'filePath', 'isString'}})
v('filePath', filePath)
v('Nncachebuilder.format()', Nncachebuilder.format())
torch.save(filePath, self, Nncachebuilder.format())
end -- write
|
-- Nncache.lua
-- nearest neighbors cache
-- API overview
if false then
-- construction
nnc = Nncache()
-- setter and getter
nnc:setLine(obsIndex, tensor1D)
tensor1D = nnc:getLine(obsIndex) -- may return null
-- apply a function to each key-value pair
local function f(key,value)
end
nnc:apply(f)
-- saving to a file and restoring from one
-- the suffix is determined by the class Nncachebuilder
nnc:save(filePath)
nnc = nnc.load(filePath)
nnc = nnc.loadUsingPrefix(filePathPrefix)
end
--------------------------------------------------------------------------------
-- CONSTRUCTION
--------------------------------------------------------------------------------
torch.class('Nncache')
function Nncache:__init()
self._table = {}
self._lastValuesSize = nil
end
--------------------------------------------------------------------------------
-- PUBLIC CLASS METHODS
--------------------------------------------------------------------------------
function Nncache.load(filePath)
-- return an nnc; error if there is no saved Nncache at the filePath
local v, isVerbose = makeVerbose(true, 'Nncache.load')
verify(v, isVerbose,
{{filePath, 'filePath', 'isString'}})
local nnc = torch.load(filePath,
Nncachebuilder.format())
--v('nnc', nnc)
v('typename', torch.typename(nnc))
assert(torch.typename(nnc) == 'Nncache',
'bad typename = ' .. tostring(torch.typename(nnc)))
-- NOTE: cannot test if each table entry has 256 rows, because the
-- original allXs may have had fewer than 256 observations
return nnc
end -- read
function Nncache.loadUsingPrefix(filePathPrefix)
return Nncache.load(Nncache._filePath(filePathPrefix))
end -- loadUsingPrefix
--------------------------------------------------------------------------------
-- PRIVATE CLASS METHODS
--------------------------------------------------------------------------------
function Nncache._filePath(filePathPrefix)
return filePathPrefix .. Nncachebuilder.mergedFileSuffix()
end -- _filePath
--------------------------------------------------------------------------------
-- PUBLIC INSTANCE METHODS
--------------------------------------------------------------------------------
function Nncache:apply(f)
-- apply a function to each key-value pair
for key, value in pairs(self._table) do
f(key, value)
end
end -- apply
function Nncache:getLine(obsIndex)
-- return line at key or null
local v, isVerbose = makeVerbose(false, 'Nncache:getline')
verify(v, isVerbose,
{{obsIndex, 'obsIndex', 'isIntegerPositive'}})
return self._table[obsIndex]
end -- getline
function Nncache:setLine(obsIndex, values)
-- set the line, checking that it is not already set
local v, isVerbose = makeVerbose(false, 'Nncache:setLine')
verify(v, isVerbose,
{{obsIndex, 'obsIndex', 'isIntegerPositive'},
{values, 'values', 'isTensor1D'}})
v('self', self)
-- check that size of values is same on every call
if self._lastValuesSize then
local newSize = values:size(1)
assert(self._lastValuesSize == newSize,
string.format('cannot change size of values; \n was %s; \n is %s',
tostring(self._lastValuesSize),
tostring(newSize)))
self._lastValuesSize = newSize
else
self._lastValuesSize = values:size(1)
end
-- check that the obsIndex slot has not already been filled
assert(self._table[obsIndex] == nil,
string.format('attempt to set cache line already filled; \nobsIndex ',
tostring(obsIndex)))
self._table[obsIndex] = values
end -- setLine
function Nncache:save(filePath)
-- write to disk by serializing
-- NOTE: if the name of this method were 'write', then the call below
-- to torch.save would call this function recursively. Hence the name
-- of this function.
local v, isVerbose = makeVerbose(false, 'Nncache:write')
v('self', self)
verify(v, isVerbose,
{{filePath, 'filePath', 'isString'}})
v('filePath', filePath)
v('Nncachebuilder.format()', Nncachebuilder.format())
torch.save(filePath, self, Nncachebuilder.format())
end -- write
|
Fix bug in call to verbose (delete it)
|
Fix bug in call to verbose (delete it)
|
Lua
|
bsd-3-clause
|
rlowrance/kernel-smoothers
|
8d52470cbafbd3815bd5e6fe397c7faed2d6f5bc
|
src/attributeutils/src/Shared/AttributeValue.lua
|
src/attributeutils/src/Shared/AttributeValue.lua
|
---
-- @classmod AttributeValue
-- @author Quenty
local AttributeValue = {}
AttributeValue.ClassName = "AttributeValue"
AttributeValue.__index = AttributeValue
function AttributeValue.new(object, attributeName, defaultValue)
local self = {
_object = object;
_attributeName = attributeName;
_defaultValue = defaultValue;
}
if defaultValue ~= nil and self._object:GetAttribute(self._attributeName) == nil then
self._object:SetAttribute(rawget(self, "_attributeName"), defaultValue)
end
self.Changed = self._object:GetAttributeChangedSignal(self._attributeName)
return setmetatable(self, AttributeValue)
end
function AttributeValue:__index(index)
if index == "Value" then
local result = self._object:GetAttribute(rawget(self, "_attributeName"))
local default = rawget(self, "_defaultValue")
if result == nil then
return default
else
return result
end
elseif AttributeValue[index] then
return AttributeValue[index]
else
error(("%q is not a member of AttributeValue"):format(tostring(index)))
end
end
function AttributeValue:__newindex(index, value)
if index == "Value" then
self._object:SetAttribute(rawget(self, "_attributeName"), value)
else
error(("%q is not a member of AttributeValue"):format(tostring(index)))
end
end
return AttributeValue
|
---
-- @classmod AttributeValue
-- @author Quenty
local AttributeValue = {}
AttributeValue.ClassName = "AttributeValue"
AttributeValue.__index = AttributeValue
function AttributeValue.new(object, attributeName, defaultValue)
local self = {
_object = object;
_attributeName = attributeName;
_defaultValue = defaultValue;
}
if defaultValue ~= nil and self._object:GetAttribute(self._attributeName) == nil then
self._object:SetAttribute(rawget(self, "_attributeName"), defaultValue)
end
return setmetatable(self, AttributeValue)
end
function AttributeValue:__index(index)
if index == "Value" then
local result = self._object:GetAttribute(rawget(self, "_attributeName"))
local default = rawget(self, "_defaultValue")
if result == nil then
return default
else
return result
end
elseif index == "Changed" then
return self._object:GetAttributeChangedSignal(self._attributeName)
elseif AttributeValue[index] then
return AttributeValue[index]
else
error(("%q is not a member of AttributeValue"):format(tostring(index)))
end
end
function AttributeValue:__newindex(index, value)
if index == "Value" then
self._object:SetAttribute(rawget(self, "_attributeName"), value)
else
error(("%q is not a member of AttributeValue"):format(tostring(index)))
end
end
return AttributeValue
|
fix: Defer signal creation
|
fix: Defer signal creation
|
Lua
|
mit
|
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
|
55e2b8cbb7bc504d20fcc7d6b6505f74cce48ed9
|
src/coreguienabler/src/Client/CoreGuiEnabler.lua
|
src/coreguienabler/src/Client/CoreGuiEnabler.lua
|
--[=[
Key based CoreGuiEnabler, singleton
Use this class to load/unload CoreGuis / other GUIs, by disabling based upon keys
Keys are additive, so if you have more than 1 disabled, it's ok.
```lua
local CoreGuiEnabler = require("CoreGuiEnabler")
-- Disable the backpack for 5 seconds
local cleanup = CoreGuiEnabler:Disable(newproxy(), Enum.CoreGuiType.Backpack)
task.delay(5, cleanup)
```
@class CoreGuiEnabler
]=]
local require = require(script.Parent.loader).load(script)
local Players = game:GetService("Players")
local StarterGui = game:GetService("StarterGui")
local UserInputService = game:GetService("UserInputService")
local CharacterUtils = require("CharacterUtils")
local Maid = require("Maid")
local CoreGuiEnabler = {}
CoreGuiEnabler.__index = CoreGuiEnabler
CoreGuiEnabler.ClassName = "CoreGuiEnabler"
function CoreGuiEnabler.new()
local self = setmetatable({}, CoreGuiEnabler)
self._maid = Maid.new()
self._states = {}
self:AddState(Enum.CoreGuiType.Backpack, function(isEnabled)
StarterGui:SetCoreGuiEnabled(Enum.CoreGuiType.Backpack, isEnabled)
CharacterUtils.unequipTools(Players.LocalPlayer)
end)
for _, coreGuiType in pairs(Enum.CoreGuiType:GetEnumItems()) do
if not self._states[coreGuiType] then
self:AddState(coreGuiType, function(isEnabled)
StarterGui:SetCoreGuiEnabled(coreGuiType, isEnabled)
end)
end
end
self:_addStarterGuiState("TopbarEnabled")
self:_addStarterGuiState("BadgesNotificationsActive")
self:_addStarterGuiState("PointsNotificationsActive")
self:AddState("ModalEnabled", function(isEnabled)
UserInputService.ModalEnabled = not isEnabled
end)
self:AddState("MouseIconEnabled", function(isEnabled)
if isEnabled then
UserInputService.MouseIconEnabled = isEnabled
else
UserInputService.MouseIconEnabled = false
self._maid:GiveTask(UserInputService:GetPropertyChangedSignal("MouseIconEnabled"):Connect(function()
UserInputService.MouseIconEnabled = false
end))
end
end)
return self
end
function CoreGuiEnabler:_addStarterGuiState(stateName)
local boolValueName = stateName .. "State"
self[boolValueName] = Instance.new("BoolValue")
self[boolValueName].Value = false
self:AddState(stateName, function(isEnabled)
self[boolValueName].Value = isEnabled
local success, err = pcall(function()
StarterGui:SetCore(stateName, isEnabled)
end)
if not success then
warn("Failed to set core", err)
end
end)
end
--[=[
Adds a state that can be disabled or enabled.
@param coreGuiState string | CoreGuiType
@param coreGuiStateChangeFunc (isEnabled: boolean)
]=]
function CoreGuiEnabler:AddState(coreGuiState, coreGuiStateChangeFunc)
assert(type(coreGuiStateChangeFunc) == "function", "must have coreGuiStateChangeFunc as function")
assert(self._states[coreGuiState] == nil, "state already exists")
local realState = {}
local lastState = true
local function isEnabled()
return next(realState) == nil
end
self._states[coreGuiState] = setmetatable({}, {
__newindex = function(_, index, value)
rawset(realState, index, value)
local newState = isEnabled()
if lastState ~= newState then
lastState = newState
coreGuiStateChangeFunc(newState)
end
end;
})
end
--[=[
Disables a CoreGuiState
@param key any
@param coreGuiState string | CoreGuiType
@return function -- Callback function to re-enable the state
]=]
function CoreGuiEnabler:Disable(key, coreGuiState)
if not self._states[coreGuiState] then
error(("[CoreGuiEnabler] - State '%s' does not exist."):format(tostring(coreGuiState)))
end
self._states[coreGuiState][key] = true
return function()
self:Enable(key, coreGuiState)
end
end
--[=[
Enables a state for a given key
@param key any
@param coreGuiState string | CoreGuiType
]=]
function CoreGuiEnabler:Enable(key, coreGuiState)
if not self._states[coreGuiState] then
error(("[CoreGuiEnabler] - State '%s' does not exist."):format(tostring(coreGuiState)))
end
self._states[coreGuiState][key] = nil
end
return CoreGuiEnabler.new()
|
--[=[
Key based CoreGuiEnabler, singleton
Use this class to load/unload CoreGuis / other GUIs, by disabling based upon keys
Keys are additive, so if you have more than 1 disabled, it's ok.
```lua
local CoreGuiEnabler = require("CoreGuiEnabler")
-- Disable the backpack for 5 seconds
local cleanup = CoreGuiEnabler:Disable(newproxy(), Enum.CoreGuiType.Backpack)
task.delay(5, cleanup)
```
@class CoreGuiEnabler
]=]
local require = require(script.Parent.loader).load(script)
local Players = game:GetService("Players")
local StarterGui = game:GetService("StarterGui")
local UserInputService = game:GetService("UserInputService")
local CharacterUtils = require("CharacterUtils")
local Maid = require("Maid")
local CoreGuiEnabler = {}
CoreGuiEnabler.__index = CoreGuiEnabler
CoreGuiEnabler.ClassName = "CoreGuiEnabler"
function CoreGuiEnabler.new()
local self = setmetatable({}, CoreGuiEnabler)
self._maid = Maid.new()
self._states = {}
self:AddState(Enum.CoreGuiType.Backpack, function(isEnabled)
StarterGui:SetCoreGuiEnabled(Enum.CoreGuiType.Backpack, isEnabled)
CharacterUtils.unequipTools(Players.LocalPlayer)
end)
for _, coreGuiType in pairs(Enum.CoreGuiType:GetEnumItems()) do
if not self._states[coreGuiType] then
self:AddState(coreGuiType, function(isEnabled)
StarterGui:SetCoreGuiEnabled(coreGuiType, isEnabled)
end)
end
end
self:_addStarterGuiState("TopbarEnabled")
self:_addStarterGuiState("BadgesNotificationsActive")
self:_addStarterGuiState("PointsNotificationsActive")
self:AddState("ModalEnabled", function(isEnabled)
UserInputService.ModalEnabled = not isEnabled
end)
self:AddState("MouseIconEnabled", function(isEnabled)
UserInputService.MouseIconEnabled = isEnabled
end)
return self
end
function CoreGuiEnabler:_addStarterGuiState(stateName)
local boolValueName = stateName .. "State"
self[boolValueName] = Instance.new("BoolValue")
self[boolValueName].Value = false
self:AddState(stateName, function(isEnabled)
self[boolValueName].Value = isEnabled
local success, err = pcall(function()
StarterGui:SetCore(stateName, isEnabled)
end)
if not success then
warn("Failed to set core", err)
end
end)
end
--[=[
Adds a state that can be disabled or enabled.
@param coreGuiState string | CoreGuiType
@param coreGuiStateChangeFunc (isEnabled: boolean)
]=]
function CoreGuiEnabler:AddState(coreGuiState, coreGuiStateChangeFunc)
assert(type(coreGuiStateChangeFunc) == "function", "must have coreGuiStateChangeFunc as function")
assert(self._states[coreGuiState] == nil, "state already exists")
local realState = {}
local lastState = true
local function isEnabled()
return next(realState) == nil
end
self._states[coreGuiState] = setmetatable({}, {
__newindex = function(_, index, value)
rawset(realState, index, value)
local newState = isEnabled()
if lastState ~= newState then
lastState = newState
coreGuiStateChangeFunc(newState)
end
end;
})
end
--[=[
Disables a CoreGuiState
@param key any
@param coreGuiState string | CoreGuiType
@return function -- Callback function to re-enable the state
]=]
function CoreGuiEnabler:Disable(key, coreGuiState)
if not self._states[coreGuiState] then
error(("[CoreGuiEnabler] - State '%s' does not exist."):format(tostring(coreGuiState)))
end
self._states[coreGuiState][key] = true
return function()
self:Enable(key, coreGuiState)
end
end
--[=[
Enables a state for a given key
@param key any
@param coreGuiState string | CoreGuiType
]=]
function CoreGuiEnabler:Enable(key, coreGuiState)
if not self._states[coreGuiState] then
error(("[CoreGuiEnabler] - State '%s' does not exist."):format(tostring(coreGuiState)))
end
self._states[coreGuiState][key] = nil
end
return CoreGuiEnabler.new()
|
fix: Stop leaking MouseIconEnabled property events in CoreGuiEnabler
|
fix: Stop leaking MouseIconEnabled property events in CoreGuiEnabler
|
Lua
|
mit
|
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
|
c4058c031940ab75bc39294daec5d7d1b9f0e9c2
|
src/romdisk/application/launcher/AppPager.lua
|
src/romdisk/application/launcher/AppPager.lua
|
local AppItem = require "AppItem"
local M = Class(DisplayPager)
function M:init(width, height)
self.super:init(width, height, false)
self._font = Font.new("assets/fonts/Roboto-Regular.ttf", 24)
self._color = Pattern.color(1, 1, 1)
self:reload()
end
function M:setWidth(width)
return self
end
function M:setHeight(height)
return self
end
function M:setSize(width, height)
return self
end
function M:reload()
local pw, ph = self:getSize()
local iw, ih = 128, 128
local col = (pw * 2 - iw) // (iw * 3)
local row = (ph * 2 - ih) // (ih * 3)
local num = col * row
local ox = (pw - col * iw) // (col + 1)
local oy = (ph - row * ih) // (row + 1)
local launcher = Application.new()
local pages = {}
local c = 0
self:clear()
for k, v in pairs(Application.list()) do
if launcher:getPath() ~= k then
local index = c // num + 1
if not pages[index] then
pages[index] = DisplayObject.new(pw, ph)
self:addPage(pages[index])
end
local n = c % num
local y = n // col
local x = (n - y * col) % col
local ix = (iw + ox) * x + ox
local iy = (ih + oy) * y + oy
local item = AppItem.new(v)
:setPosition(ix, iy)
:addEventListener("click", function(d, e)
local path = d:getPath()
for k, v in pairs(Window.list()) do
if k == path then
v:toFront()
return
end
end
d:execute()
for k, v in pairs(Window.list()) do
if k == path then
v:toFront()
break
end
end
end)
pages[index]:addChild(item)
local label = DisplayText.new(self._font, self._color, v:getName())
local w, h = label:getSize()
label:setPosition((iw - w) / 2 + ix, iy + ih + 4)
pages[index]:addChild(label)
c = c + 1
end
end
end
return M
|
local AppItem = require "AppItem"
local M = Class(DisplayPager)
function M:init(width, height)
self.super:init(width, height, false)
self._fontFamily = "roboto-regular"
self._fontSize = 24
self._color = {red = 1, green = 1, blue = 1, alpha = 1}
self:reload()
end
function M:setWidth(width)
return self
end
function M:setHeight(height)
return self
end
function M:setSize(width, height)
return self
end
function M:reload()
local pw, ph = self:getSize()
local iw, ih = 128, 128
local col = (pw * 2 - iw) // (iw * 3)
local row = (ph * 2 - ih) // (ih * 3)
local num = col * row
local ox = (pw - col * iw) // (col + 1)
local oy = (ph - row * ih) // (row + 1)
local launcher = Application.new()
local pages = {}
local c = 0
self:clear()
for k, v in pairs(Application.list()) do
if launcher:getPath() ~= k then
local index = c // num + 1
if not pages[index] then
pages[index] = DisplayObject.new(pw, ph)
self:addPage(pages[index])
end
local n = c % num
local y = n // col
local x = (n - y * col) % col
local ix = (iw + ox) * x + ox
local iy = (ih + oy) * y + oy
local item = AppItem.new(v)
:setPosition(ix, iy)
:addEventListener("click", function(d, e)
local path = d:getPath()
for k, v in pairs(Window.list()) do
if k == path then
v:toFront()
return
end
end
d:execute()
for k, v in pairs(Window.list()) do
if k == path then
v:toFront()
break
end
end
end)
pages[index]:addChild(item)
local color = self._color
local label = DisplayText.new(v:getName(), self._fontFamily, self._fontSize, color.red, color.green, color.blur, color.alpha)
local w, h = label:getSize()
label:setPosition((iw - w) / 2 + ix, iy + ih + 4)
pages[index]:addChild(label)
c = c + 1
end
end
end
return M
|
[launcher]fix launcher
|
[launcher]fix launcher
|
Lua
|
mit
|
xboot/xboot,xboot/xboot
|
a4e5eea7692fdaab5f5f281197c150459eadd815
|
clock.lua
|
clock.lua
|
local clock_tmr=5
local clock_int=60000
local clock_int_demo=50
local clock_warn=4*clock_int
local show_clock=function(ts,h,m,s)
local hp=(math.floor(h*rgb_max/12)+rgb_max/2)%rgb_max
local mp=(math.floor(m*rgb_max/60)+rgb_max/2)%rgb_max
local p
if hp == mp then
p = string.char(3,3,0):rep(hp)..string.char(rgb_dim,0,rgb_dim)..string.char(3,3,0):rep(rgb_max-mp-1)
elseif hp < mp then
p = string.char(3,3,0):rep(hp)..string.char(rgb_dim,0,0)..string.char(0,63,0):rep(mp-hp-1)..string.char(0,0,rgb_dim)..string.char(3,3,0):rep(rgb_max-mp-1)
else
p = string.char(0,63,0):rep(mp)..string.char(0,0,rgb_dim)..string.char(3,3,0):rep(hp-mp-1)..string.char(rgb_dim,0,0)..string.char(0,64,0):rep(rgb_max-hp-1)
end
ws2812.writergb(rgb_pin,p)
p=nil
collectgarbage()
status.clkup=status.uptime_ms
end
function clock(run)
tmr.stop(clock_tmr)
if run then
status.clkup=0
rgbset(nil,{pattern="770770770",ms=0,norepeat="1"})
nettime(show_clock)
tmr.alarm(clock_tmr, clock_int, 1, function()
if(status.clkup+clock_warn<status.uptime_ms) then
rgbset(nil,{pattern="700700",ms=0,norepeat="1"})
end
nettime(show_clock)
end)
end
end
local demo_counter=0
function clockmode(n)
if n == nil or n == -1 then
clock(true)
elseif n == 1 then
tmr.alarm(clock_tmr, clock_int_demo, 1, function()
show_clock(0,math.floor(demo_counter/60)%24,demo_counter%60,0)
demo_counter=demo_counter+1
end)
end
end
|
local clock_tmr=5
local clock_int=60000
local clock_int_demo=50
local clock_warn=4*clock_int
local show_clock=function(ts,h,m,s)
local hp=(math.floor(h*rgb_max/12)+rgb_max/2)%rgb_max
local mp=(math.floor(m*rgb_max/60)+rgb_max/2)%rgb_max
local blank=string.char(0,0,0)
local p
if hp == mp then
p = blank:rep(hp)..string.char(rgb_dim,0,rgb_dim)..blank:rep(rgb_max-mp-1)
elseif hp < mp then
p = blank:rep(hp)..string.char(rgb_dim,0,0)..string.char(0,rgb_dim/4,0):rep(mp-hp-1)..string.char(0,0,rgb_dim)..blank:rep(rgb_max-mp-1)
else
p = string.char(0,rgb_dim/4,0):rep(mp)..string.char(0,0,rgb_dim)..blank:rep(hp-mp-1)..string.char(rgb_dim,0,0)..string.char(0,rgb_dim/4,0):rep(rgb_max-hp-1)
end
ws2812.writergb(rgb_pin,p)
p=nil
collectgarbage()
status.clkup=status.uptime_ms
end
function clock(run)
tmr.stop(clock_tmr)
if run then
status.clkup=0
rgbset(nil,{pattern="770770770",ms=0,norepeat="1"})
nettime(show_clock)
tmr.alarm(clock_tmr, clock_int, 1, function()
if(status.clkup+clock_warn<status.uptime_ms) then
rgbset(nil,{pattern="700700",ms=0,norepeat="1"})
end
nettime(show_clock)
end)
end
end
local demo_counter=0
function clockmode(n)
if n == nil or n == -1 then
clock(true)
elseif n == 1 then
tmr.alarm(clock_tmr, clock_int_demo, 1, function()
show_clock(0,math.floor(demo_counter/60)%24,demo_counter%60,0)
demo_counter=demo_counter+1
end)
end
end
|
Fixed dimmed clock segments
|
Fixed dimmed clock segments
|
Lua
|
mit
|
matgoebl/nodemcu-wifimusicledclock,matgoebl/nodemcu-wifimusicledclock
|
d74eae8faee15255ca66ca4b803312afe966acc4
|
src/cancellabledelay/src/Shared/cancellableDelay.lua
|
src/cancellabledelay/src/Shared/cancellableDelay.lua
|
--[=[
A version of task.delay that can be cancelled. Soon to be useless.
@class cancellableDelay
]=]
--[=[
@function cancellableDelay
@param timeoutInSeconds number
@param func function
@param ... any -- Args to pass into the function
@return function? -- Can be used to cancel
@within cancellableDelay
]=]
local function cancellableDelay(timeoutInSeconds, func, ...)
assert(type(timeoutInSeconds) == "number", "Bad timeoutInSeconds")
assert(type(func) == "function", "Bad func")
local args = table.pack(...)
local running
task.spawn(function()
running = coroutine.running()
task.wait(timeoutInSeconds)
func(table.unpack(args, 1, args.n))
end)
return function()
if running then
-- selene: allow(incorrect_standard_library_use)
coroutine.close(running)
running = nil
args = nil
end
end
end
return cancellableDelay
|
--[=[
A version of task.delay that can be cancelled. Soon to be useless.
@class cancellableDelay
]=]
--[=[
@function cancellableDelay
@param timeoutInSeconds number
@param func function
@param ... any -- Args to pass into the function
@return function? -- Can be used to cancel
@within cancellableDelay
]=]
local function cancellableDelay(timeoutInSeconds, func, ...)
assert(type(timeoutInSeconds) == "number", "Bad timeoutInSeconds")
assert(type(func) == "function", "Bad func")
local args = table.pack(...)
local running
task.spawn(function()
running = coroutine.running()
task.wait(timeoutInSeconds)
local localArgs = args
running = nil
args = nil
func(table.unpack(localArgs, 1, localArgs.n))
end)
return function()
if running then
-- selene: allow(incorrect_standard_library_use)
coroutine.close(running)
running = nil
args = nil
end
end
end
return cancellableDelay
|
fix: Fix cancellation occuring when the resulting task yields
|
fix: Fix cancellation occuring when the resulting task yields
|
Lua
|
mit
|
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
|
5e55ba38087c594b29ef646a5719410b8c7d2b44
|
src/logging.lua
|
src/logging.lua
|
-------------------------------------------------------------------------------
-- includes a new tostring function that handles tables recursively
--
-- @author Danilo Tuler (tuler@ideais.com.br)
-- @author Andre Carregal (info@keplerproject.org)
-- @author Thiago Costa Ponte (thiago@ideais.com.br)
--
-- @copyright 2004-2013 Kepler Project
-------------------------------------------------------------------------------
local type, table, string, _tostring, tonumber = type, table, string, tostring, tonumber
local select = select
local error = error
local format = string.format
local pairs = pairs
local ipairs = ipairs
local logging = {
-- Meta information
_COPYRIGHT = "Copyright (C) 2004-2013 Kepler Project",
_DESCRIPTION = "A simple API to use logging features in Lua",
_VERSION = "LuaLogging 1.3.0",
-- The DEBUG Level designates fine-grained instring.formational events that are most
-- useful to debug an application
DEBUG = "DEBUG",
-- The INFO level designates instring.formational messages that highlight the
-- progress of the application at coarse-grained level
INFO = "INFO",
-- The WARN level designates potentially harmful situations
WARN = "WARN",
-- The ERROR level designates error events that might still allow the
-- application to continue running
ERROR = "ERROR",
-- The FATAL level designates very severe error events that will presumably
-- lead the application to abort
FATAL = "FATAL",
}
local LEVEL = {"DEBUG", "INFO", "WARN", "ERROR", "FATAL"}
local MAX_LEVELS = #LEVEL
-- make level names to order
for i=1,MAX_LEVELS do
LEVEL[LEVEL[i]] = i
end
-- private log function, with support for formating a complex log message.
local function LOG_MSG(self, level, fmt, ...)
local f_type = type(fmt)
if f_type == 'string' then
if select('#', ...) > 0 then
local status, msg = pcall(format, fmt, ...)
if status then
return self:append(level, msg)
else
return self:append(level, "Error formatting log message: " .. msg)
end
else
-- only a single string, no formating needed.
return self:append(level, fmt)
end
elseif f_type == 'function' then
-- fmt should be a callable function which returns the message to log
return self:append(level, fmt(...))
end
-- fmt is not a string and not a function, just call tostring() on it.
return self:append(level, logging.tostring(fmt))
end
-- create the proxy functions for each log level.
local LEVEL_FUNCS = {}
for i=1,MAX_LEVELS do
local level = LEVEL[i]
LEVEL_FUNCS[i] = function(self, ...)
-- no level checking needed here, this function will only be called if it's level is active.
return LOG_MSG(self, level, ...)
end
end
-- do nothing function for disabled levels.
local function disable_level() end
-- improved assertion function.
local function assert(exp, ...)
-- if exp is true, we are finished so don't do any processing of the parameters
if exp then return exp, ... end
-- assertion failed, raise error
error(format(...), 2)
end
-------------------------------------------------------------------------------
-- Creates a new logger object
-- @param append Function used by the logger to append a message with a
-- log-level to the log stream.
-- @return Table representing the new logger object.
-------------------------------------------------------------------------------
function logging.new(append)
if type(append) ~= "function" then
return nil, "Appender must be a function."
end
local logger = {}
logger.append = append
logger.setLevel = function (self, level)
local order = LEVEL[level]
assert(order, "undefined level `%s'", _tostring(level))
if self.level then
self:log(logging.WARN, "Logger: changing loglevel from %s to %s", self.level, level)
end
self.level = level
self.level_order = order
-- enable/disable levels
for i=1,MAX_LEVELS do
local name = LEVEL[i]:lower()
if i >= order then
self[name] = LEVEL_FUNCS[i]
else
self[name] = disable_level
end
end
end
-- generic log function.
logger.log = function (self, level, ...)
local order = LEVEL[level]
assert(order, "undefined level `%s'", _tostring(level))
if order < self.level_order then
return
end
return LOG_MSG(self, level, ...)
end
-- initialize log level.
logger:setLevel(logging.DEBUG)
return logger
end
-------------------------------------------------------------------------------
-- Prepares the log message
-------------------------------------------------------------------------------
function logging.prepareLogMsg(pattern, dt, level, message)
local logMsg = pattern or "%date %level %message\n"
message = string.gsub(message, "%%", "%%%%")
logMsg = string.gsub(logMsg, "%%date", dt)
logMsg = string.gsub(logMsg, "%%level", level)
logMsg = string.gsub(logMsg, "%%message", message)
return logMsg
end
-------------------------------------------------------------------------------
-- Converts a Lua value to a string
--
-- Converts Table fields in alphabetical order
-------------------------------------------------------------------------------
local function tostring(value)
local str = ''
if (type(value) ~= 'table') then
if (type(value) == 'string') then
str = string.format("%q", value)
else
str = _tostring(value)
end
else
local auxTable = {}
for key in pairs(value) do
if (tonumber(key) ~= key) then
table.insert(auxTable, key)
else
table.insert(auxTable, tostring(key))
end
end
table.sort(auxTable)
str = str..'{'
local separator = ""
local entry = ""
for _, fieldName in ipairs(auxTable) do
if ((tonumber(fieldName)) and (tonumber(fieldName) > 0)) then
entry = tostring(value[tonumber(fieldName)])
else
entry = fieldName.." = "..tostring(value[fieldName])
end
str = str..separator..entry
separator = ", "
end
str = str..'}'
end
return str
end
logging.tostring = tostring
if _VERSION ~= 'Lua 5.2' then
-- still create 'logging' global for Lua versions < 5.2
_G.logging = logging
end
return logging
|
-------------------------------------------------------------------------------
-- includes a new tostring function that handles tables recursively
--
-- @author Danilo Tuler (tuler@ideais.com.br)
-- @author Andre Carregal (info@keplerproject.org)
-- @author Thiago Costa Ponte (thiago@ideais.com.br)
--
-- @copyright 2004-2013 Kepler Project
-------------------------------------------------------------------------------
local type, table, string, _tostring, tonumber = type, table, string, tostring, tonumber
local select = select
local error = error
local format = string.format
local pairs = pairs
local ipairs = ipairs
local logging = {
-- Meta information
_COPYRIGHT = "Copyright (C) 2004-2013 Kepler Project",
_DESCRIPTION = "A simple API to use logging features in Lua",
_VERSION = "LuaLogging 1.3.0",
-- The DEBUG Level designates fine-grained instring.formational events that are most
-- useful to debug an application
DEBUG = "DEBUG",
-- The INFO level designates instring.formational messages that highlight the
-- progress of the application at coarse-grained level
INFO = "INFO",
-- The WARN level designates potentially harmful situations
WARN = "WARN",
-- The ERROR level designates error events that might still allow the
-- application to continue running
ERROR = "ERROR",
-- The FATAL level designates very severe error events that will presumably
-- lead the application to abort
FATAL = "FATAL",
}
local LEVEL = {"DEBUG", "INFO", "WARN", "ERROR", "FATAL"}
local MAX_LEVELS = #LEVEL
-- make level names to order
for i=1,MAX_LEVELS do
LEVEL[LEVEL[i]] = i
end
-- private log function, with support for formating a complex log message.
local function LOG_MSG(self, level, fmt, ...)
local f_type = type(fmt)
if f_type == 'string' then
if select('#', ...) > 0 then
local status, msg = pcall(format, fmt, ...)
if status then
return self:append(level, msg)
else
return self:append(level, "Error formatting log message: " .. msg)
end
else
-- only a single string, no formating needed.
return self:append(level, fmt)
end
elseif f_type == 'function' then
-- fmt should be a callable function which returns the message to log
return self:append(level, fmt(...))
end
-- fmt is not a string and not a function, just call tostring() on it.
return self:append(level, logging.tostring(fmt))
end
-- create the proxy functions for each log level.
local LEVEL_FUNCS = {}
for i=1,MAX_LEVELS do
local level = LEVEL[i]
LEVEL_FUNCS[i] = function(self, ...)
-- no level checking needed here, this function will only be called if it's level is active.
return LOG_MSG(self, level, ...)
end
end
-- do nothing function for disabled levels.
local function disable_level() end
-- improved assertion function.
local function assert(exp, ...)
-- if exp is true, we are finished so don't do any processing of the parameters
if exp then return exp, ... end
-- assertion failed, raise error
error(format(...), 2)
end
-------------------------------------------------------------------------------
-- Creates a new logger object
-- @param append Function used by the logger to append a message with a
-- log-level to the log stream.
-- @return Table representing the new logger object.
-------------------------------------------------------------------------------
function logging.new(append)
if type(append) ~= "function" then
return nil, "Appender must be a function."
end
local logger = {}
logger.append = append
logger.setLevel = function (self, level)
local order = LEVEL[level]
assert(order, "undefined level `%s'", _tostring(level))
if self.level then
self:log(logging.WARN, "Logger: changing loglevel from %s to %s", self.level, level)
end
self.level = level
self.level_order = order
-- enable/disable levels
for i=1,MAX_LEVELS do
local name = LEVEL[i]:lower()
if i >= order then
self[name] = LEVEL_FUNCS[i]
else
self[name] = disable_level
end
end
end
-- generic log function.
logger.log = function (self, level, ...)
local order = LEVEL[level]
assert(order, "undefined level `%s'", _tostring(level))
if order < self.level_order then
return
end
return LOG_MSG(self, level, ...)
end
-- initialize log level.
logger:setLevel(logging.DEBUG)
return logger
end
-------------------------------------------------------------------------------
-- Prepares the log message
-------------------------------------------------------------------------------
function logging.prepareLogMsg(pattern, dt, level, message)
local logMsg = pattern or "%date %level %message\n"
message = string.gsub(message, "%%", "%%%%")
logMsg = string.gsub(logMsg, "%%date", dt)
logMsg = string.gsub(logMsg, "%%level", level)
logMsg = string.gsub(logMsg, "%%message", message)
return logMsg
end
-------------------------------------------------------------------------------
-- Converts a Lua value to a string
--
-- Converts Table fields in alphabetical order
-------------------------------------------------------------------------------
local function tostring(value)
local str = ''
if (type(value) ~= 'table') then
if (type(value) == 'string') then
str = string.format("%q", value)
else
str = _tostring(value)
end
else
local auxTable = {}
for key in pairs(value) do
if (tonumber(key) ~= key) then
table.insert(auxTable, key)
else
table.insert(auxTable, tostring(key))
end
end
table.sort(auxTable)
str = str..'{'
local separator = ""
local entry = ""
for _, fieldName in ipairs(auxTable) do
if ((tonumber(fieldName)) and (tonumber(fieldName) > 0)) then
entry = tostring(value[tonumber(fieldName)])
else
entry = fieldName.." = "..tostring(value[fieldName])
end
str = str..separator..entry
separator = ", "
end
str = str..'}'
end
return str
end
logging.tostring = tostring
local luamaj, luamin = _VERSION:match("Lua (%d+)%.(%d+)")
if luamaj == 5 and luamin < 2 then
-- still create 'logging' global for Lua versions < 5.2
_G.logging = logging
end
return logging
|
Fix test for Lua 5.3 and above.
|
Fix test for Lua 5.3 and above.
|
Lua
|
mit
|
mwchase/log4l
|
9769396050fd29a7ab225cfcd3332f907e18e5e9
|
lua/wire/server/debuggerlib.lua
|
lua/wire/server/debuggerlib.lua
|
local formatPort = {}
WireLib.Debugger = { formatPort = formatPort } -- Make it global
function formatPort.NORMAL(value)
return string.format("%.3f",value)
end
function formatPort.STRING(value)
return '"' .. value .. '"'
end
function formatPort.VECTOR(value)
return string.format("(%.1f,%.1f,%.1f)", value[1], value[2], value[3])
end
function formatPort.ANGLE(value)
return string.format("(%.1f,%.1f,%.1f)", value.p, value.y, value.r)
end
formatPort.ENTITY = function(ent)
if not IsValid(ent) then return "(null)" end
return tostring(ent)
end
formatPort.BONE = e2_tostring_bone
function formatPort.MATRIX(value)
local RetText = "[11="..value[1]..",12="..value[2]..",13="..value[3]
RetText = RetText..",21="..value[4]..",22="..value[5]..",23="..value[6]
RetText = RetText..",31="..value[7]..",32="..value[8]..",33="..value[9].."]"
return RetText
end
function formatPort.MATRIX2(value)
local RetText = "[11="..value[1]..",12="..value[2]
RetText = RetText..",21="..value[3]..",22="..value[4].."]"
return RetText
end
function formatPort.MATRIX4(value)
local RetText = "[11="..value[1]..",12="..value[2]..",13="..value[3]..",14="..value[4]
RetText = RetText..",21="..value[5]..",22="..value[6]..",23="..value[7]..",24="..value[8]
RetText = RetText..",31="..value[9]..",32="..value[10]..",33="..value[11]..",34="..value[12]
RetText = RetText..",41="..value[13]..",42="..value[14]..",43="..value[15]..",44="..value[16].."]"
return RetText
end
function formatPort.RANGER(value) return "ranger" end
function formatPort.ARRAY(value, OrientVertical)
local RetText = ""
local ElementCount = 0
for Index, Element in ipairs(value) do
ElementCount = ElementCount+1
if(ElementCount > 10) then
break
end
RetText = RetText..Index.."="
--Check for array element type
if isnumber(Element) then --number
RetText = RetText..formatPort.NORMAL(Element)
elseif((istable(Element) and #Element == 3) or isvector(Element)) then --vector
RetText = RetText..formatPort.VECTOR(Element)
elseif(istable(Element) and #Element == 2) then --vector2
RetText = RetText..formatPort.VECTOR2(Element)
elseif(istable(Element) and #Element == 4) then --vector4
RetText = RetText..formatPort.VECTOR4(Element)
elseif((istable(Element) and #Element == 3) or isangle(Element)) then --angle
if(isangle(Element)) then
RetText = RetText..formatPort.ANGLE(Element)
else
RetText = RetText.."(" .. math.Round(Element[1],1) .. "," .. math.Round(Element[2],1) .. "," .. math.Round(Element[3],1) .. ")"
end
elseif(istable(Element) and #Element == 9) then --matrix
RetText = RetText..formatPort.MATRIX(Element)
elseif(istable(Element) and #Element == 16) then --matrix4
RetText = RetText..formatPort.MATRIX4(Element)
elseif(isstring(Element)) then --string
RetText = RetText..formatPort.STRING(Element)
elseif(isentity(Element)) then --entity
RetText = RetText..formatPort.ENTITY(Element)
elseif(type(Element) == "Player") then --player
RetText = RetText..tostring(Element)
elseif(type(Element) == "Weapon") then --weapon
RetText = RetText..tostring(Element)..Element:GetClass()
elseif(type(Element) == "PhysObj" and e2_tostring_bone(Element) != "(null)") then --Bone
RetText = RetText..formatPort.BONE(Element)
else
RetText = RetText.."No Display for "..type(Element)
end
--TODO: add matrix 2
if OrientVertical then
RetText = RetText..",\n"
else
RetText = RetText..", "
end
end
RetText = string.sub(RetText,1,-3)
return "{"..RetText.."}"
end
function formatPort.TABLE(value, OrientVertical)
local RetText = ""
local ElementCount = 0
for Index, Element in pairs(value) do
ElementCount = ElementCount+1
if(ElementCount > 7) then
break
end
local long_typeid = string.sub(Index,1,1) == "x"
local typeid = string.sub(Index,1,long_typeid and 3 or 1)
local IdxID = string.sub(Index,(long_typeid and 3 or 1)+1)
RetText = RetText..IdxID.."="
--Check for array element type
if(typeid == "n") then --number
RetText = RetText..formatPort.NORMAL(Element)
elseif(istable(Element) and #Element == 3) or isvector(Element) then --vector
RetText = RetText..formatPort.VECTOR(Element)
elseif(istable(Element) and #Element == 2) then --vector2
RetText = RetText..formatPort.VECTOR2(Element)
elseif(istable(Element) and #Element == 4 and typeid == "v4") then --vector4
RetText = RetText..formatPort.VECTOR4(Element)
elseif(istable(Element) and #Element == 3) or isangle(Element) then --angle
if isangle(Element) then
RetText = RetText..formatPort.ANGLE(Element)
else
RetText = RetText.."(" .. math.Round(Element[1]*10)/10 .. "," .. math.Round(Element[2]*10)/10 .. "," .. math.Round(Element[3]*10)/10 .. ")"
end
elseif(istable(Element) and #Element == 9) then --matrix
RetText = RetText..formatPort.MATRIX(Element)
elseif(istable(Element) and #Element == 16) then --matrix4
RetText = RetText..formatPort.MATRIX4(Element)
elseif(typeid == "s") then --string
RetText = RetText..formatPort.STRING(Element)
elseif(isentity(Element) and typeid == "e") then --entity
RetText = RetText..formatPort.ENTITY(Element)
elseif(type(Element) == "Player") then --player
RetText = RetText..tostring(Element)
elseif(type(Element) == "Weapon") then --weapon
RetText = RetText..tostring(Element)..Element:GetClass()
elseif(typeid == "b") then
RetText = RetText..formatPort.BONE(Element)
else
RetText = RetText.."No Display for "..type(Element)
end
--TODO: add matrix 2
if OrientVertical then
RetText = RetText..",\n"
else
RetText = RetText..", "
end
end
RetText = string.sub(RetText,1,-3)
return "{"..RetText.."}"
end
function WireLib.registerDebuggerFormat(typename, func)
formatPort[typename:upper()] = func
end
|
local formatPort = {}
WireLib.Debugger = { formatPort = formatPort } -- Make it global
function formatPort.NORMAL(value)
return string.format("%.3f",value)
end
function formatPort.STRING(value)
return '"' .. value .. '"'
end
function formatPort.VECTOR(value)
return string.format("(%.1f,%.1f,%.1f)", value[1], value[2], value[3])
end
function formatPort.ANGLE(value)
return string.format("(%.1f,%.1f,%.1f)", value[1], value[2], value[3])
end
formatPort.ENTITY = function(ent)
if not IsValid(ent) then return "(null)" end
return tostring(ent)
end
formatPort.BONE = e2_tostring_bone
function formatPort.MATRIX(value)
local RetText = "[11="..value[1]..",12="..value[2]..",13="..value[3]
RetText = RetText..",21="..value[4]..",22="..value[5]..",23="..value[6]
RetText = RetText..",31="..value[7]..",32="..value[8]..",33="..value[9].."]"
return RetText
end
function formatPort.MATRIX2(value)
local RetText = "[11="..value[1]..",12="..value[2]
RetText = RetText..",21="..value[3]..",22="..value[4].."]"
return RetText
end
function formatPort.MATRIX4(value)
local RetText = "[11="..value[1]..",12="..value[2]..",13="..value[3]..",14="..value[4]
RetText = RetText..",21="..value[5]..",22="..value[6]..",23="..value[7]..",24="..value[8]
RetText = RetText..",31="..value[9]..",32="..value[10]..",33="..value[11]..",34="..value[12]
RetText = RetText..",41="..value[13]..",42="..value[14]..",43="..value[15]..",44="..value[16].."]"
return RetText
end
function formatPort.RANGER(value) return "ranger" end
function formatPort.ARRAY(value, OrientVertical)
local RetText = ""
local ElementCount = 0
for Index, Element in ipairs(value) do
ElementCount = ElementCount+1
if(ElementCount > 10) then
break
end
RetText = RetText..Index.."="
--Check for array element type
if isnumber(Element) then --number
RetText = RetText..formatPort.NORMAL(Element)
elseif((istable(Element) and #Element == 3) or isvector(Element)) or isangle(Element) then --vector
RetText = RetText..formatPort.VECTOR(Element)
elseif(istable(Element) and #Element == 2) then --vector2
RetText = RetText..formatPort.VECTOR2(Element)
elseif(istable(Element) and #Element == 4) then --vector4
RetText = RetText..formatPort.VECTOR4(Element)
elseif(istable(Element) and #Element == 9) then --matrix
RetText = RetText..formatPort.MATRIX(Element)
elseif(istable(Element) and #Element == 16) then --matrix4
RetText = RetText..formatPort.MATRIX4(Element)
elseif(isstring(Element)) then --string
RetText = RetText..formatPort.STRING(Element)
elseif(isentity(Element)) then --entity
RetText = RetText..formatPort.ENTITY(Element)
elseif(type(Element) == "Player") then --player
RetText = RetText..tostring(Element)
elseif(type(Element) == "Weapon") then --weapon
RetText = RetText..tostring(Element)..Element:GetClass()
elseif(type(Element) == "PhysObj" and e2_tostring_bone(Element) != "(null)") then --Bone
RetText = RetText..formatPort.BONE(Element)
else
RetText = RetText.."No Display for "..type(Element)
end
--TODO: add matrix 2
if OrientVertical then
RetText = RetText..",\n"
else
RetText = RetText..", "
end
end
RetText = string.sub(RetText,1,-3)
return "{"..RetText.."}"
end
function formatPort.TABLE(value, OrientVertical)
local RetText = ""
local ElementCount = 0
for Index, Element in pairs(value) do
ElementCount = ElementCount+1
if(ElementCount > 7) then
break
end
local long_typeid = string.sub(Index,1,1) == "x"
local typeid = string.sub(Index,1,long_typeid and 3 or 1)
local IdxID = string.sub(Index,(long_typeid and 3 or 1)+1)
RetText = RetText..IdxID.."="
--Check for array element type
if(typeid == "n") then --number
RetText = RetText..formatPort.NORMAL(Element)
elseif(istable(Element) and #Element == 3) or isvector(Element) or isangle(Element) then --vector
RetText = RetText..formatPort.VECTOR(Element)
elseif(istable(Element) and #Element == 2) then --vector2
RetText = RetText..formatPort.VECTOR2(Element)
elseif(istable(Element) and #Element == 4 and typeid == "v4") then --vector4
RetText = RetText..formatPort.VECTOR4(Element)
elseif(istable(Element) and #Element == 9) then --matrix
RetText = RetText..formatPort.MATRIX(Element)
elseif(istable(Element) and #Element == 16) then --matrix4
RetText = RetText..formatPort.MATRIX4(Element)
elseif(typeid == "s") then --string
RetText = RetText..formatPort.STRING(Element)
elseif(isentity(Element) and typeid == "e") then --entity
RetText = RetText..formatPort.ENTITY(Element)
elseif(type(Element) == "Player") then --player
RetText = RetText..tostring(Element)
elseif(type(Element) == "Weapon") then --weapon
RetText = RetText..tostring(Element)..Element:GetClass()
elseif(typeid == "b") then
RetText = RetText..formatPort.BONE(Element)
else
RetText = RetText.."No Display for "..type(Element)
end
--TODO: add matrix 2
if OrientVertical then
RetText = RetText..",\n"
else
RetText = RetText..", "
end
end
RetText = string.sub(RetText,1,-3)
return "{"..RetText.."}"
end
function WireLib.registerDebuggerFormat(typename, func)
formatPort[typename:upper()] = func
end
|
fixed the way the angle tables are referenced where they are formatted for the debugger
|
fixed the way the angle tables are referenced where they are formatted for the debugger
|
Lua
|
apache-2.0
|
dvdvideo1234/wire,wiremod/wire,Grocel/wire
|
5237ba947d0efd0e5d1eb5a562d754350a2c1ee9
|
screen.lua
|
screen.lua
|
--[[
Copyright (C) 2011 Hans-Werner Hilse <hilse@web.de>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
]]--
--[[
Codes for rotation modes:
1 for no rotation,
2 for landscape with bottom on the right side of screen, etc.
2
+--------------+
| +----------+ |
| | | |
| | Freedom! | |
| | | |
| | | |
3 | | | | 1
| | | |
| | | |
| +----------+ |
| |
| |
+--------------+
0
--]]
Screen = {
cur_rotation_mode = 0,
}
-- @ orien: 1 for clockwise rotate, -1 for anti-clockwise
function Screen:screenRotate(orien)
if orien == "clockwise" then
orien = -1
elseif orien == "anticlockwise" then
orien = 1
else
return
end
self.cur_rotation_mode = (self.cur_rotation_mode + orien) % 4
fb:setOrientation(self.cur_rotation_mode)
fb:close()
--local mode = self.rotation_modes[self.cur_rotation_mode]
--self.cur_rotation_mode = (self.cur_rotation_mode-1 + 1*orien)%4 + 1
--os.execute("lipc-send-event -r 3 com.lab126.hal orientation"..mode)
fb = einkfb.open("/dev/fb0")
end
function Screen:updateRotationMode()
if KEY_FW_DOWN == 116 then -- in EMU mode always set to 0
self.cur_rotation_mode = 0
else
orie_fd = assert(io.open("/sys/module/eink_fb_hal_broads/parameters/bs_orientation", "r"))
updown_fd = assert(io.open("/sys/module/eink_fb_hal_broads/parameters/bs_upside_down", "r"))
self.cur_rotation_mode = orie_fd:read() + (updown_fd:read() * 2)
end
end
|
--[[
Copyright (C) 2011 Hans-Werner Hilse <hilse@web.de>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
]]--
--[[
Codes for rotation modes:
1 for no rotation,
2 for landscape with bottom on the right side of screen, etc.
2
+--------------+
| +----------+ |
| | | |
| | Freedom! | |
| | | |
| | | |
3 | | | | 1
| | | |
| | | |
| +----------+ |
| |
| |
+--------------+
0
--]]
Screen = {
cur_rotation_mode = 0,
}
-- @ orien: 1 for clockwise rotate, -1 for anti-clockwise
function Screen:screenRotate(orien)
if orien == "clockwise" then
orien = -1
elseif orien == "anticlockwise" then
orien = 1
else
return
end
self.cur_rotation_mode = (self.cur_rotation_mode + orien) % 4
-- you have to reopen framebuffer after rotate
fb:setOrientation(self.cur_rotation_mode)
fb:close()
--local mode = self.rotation_modes[self.cur_rotation_mode]
--self.cur_rotation_mode = (self.cur_rotation_mode-1 + 1*orien)%4 + 1
--os.execute("lipc-send-event -r 3 com.lab126.hal orientation"..mode)
fb = einkfb.open("/dev/fb0")
end
function Screen:updateRotationMode()
if KEY_FW_DOWN == 116 then -- in EMU mode always set to 0
self.cur_rotation_mode = 0
else
orie_fd = assert(io.open("/sys/module/eink_fb_hal_broads/parameters/bs_orientation", "r"))
updown_fd = assert(io.open("/sys/module/eink_fb_hal_broads/parameters/bs_upside_down", "r"))
self.cur_rotation_mode = orie_fd:read() + (updown_fd:read() * 2)
end
end
|
fix: typo
|
fix: typo
|
Lua
|
agpl-3.0
|
Frenzie/koreader-base,koreader/koreader-base,noname007/koreader,houqp/koreader-base,NiLuJe/koreader-base,houqp/koreader-base,koreader/koreader-base,apletnev/koreader-base,NiLuJe/koreader-base,mwoz123/koreader,houqp/koreader-base,frankyifei/koreader,houqp/koreader,NiLuJe/koreader-base,Markismus/koreader,poire-z/koreader,ashang/koreader,Hzj-jie/koreader-base,NiLuJe/koreader,robert00s/koreader,frankyifei/koreader-base,koreader/koreader,Hzj-jie/koreader,Frenzie/koreader-base,apletnev/koreader-base,lgeek/koreader,ashhher3/koreader,poire-z/koreader,frankyifei/koreader-base,Frenzie/koreader,apletnev/koreader-base,frankyifei/koreader-base,Frenzie/koreader,koreader/koreader-base,apletnev/koreader,Hzj-jie/koreader-base,NickSavage/koreader,chihyang/koreader,Frenzie/koreader-base,frankyifei/koreader-base,Hzj-jie/koreader-base,apletnev/koreader-base,Hzj-jie/koreader-base,houqp/koreader-base,Frenzie/koreader-base,koreader/koreader,NiLuJe/koreader,pazos/koreader,NiLuJe/koreader-base,mihailim/koreader,koreader/koreader-base,chrox/koreader
|
85e012d45eb159c6748c6a2a2852be608045d8b5
|
src/jet/daemon/sorter.lua
|
src/jet/daemon/sorter.lua
|
local jutils = require'jet.utils'
local tinsert = table.insert
local tremove = table.remove
local tconcat = table.concat
local tsort = table.sort
local unpack = unpack
local mmin = math.min
local mmax = math.max
local noop = jutils.noop
local is_empty_table = jutils.is_empty_table
-- may create and return a sorter function.
-- the sort function is based on the options.sort entries.
local create_sorter = function(options,notify)
if not options.sort then
return nil
end
local sort
if (options.sort.byValue == nil and options.sort.byValueField == nil) or options.sort.byPath then
if options.sort.descending then
sort = function(a,b)
return a.path > b.path
end
else
sort = function(a,b)
return a.path < b.path
end
end
else
local lt
local gt
if options.sort.byValue then
lt = function(a,b)
return a < b
end
gt = function(a,b)
return a > b
end
elseif options.sort.byValueField then
local tmp = options.sort.byValueField
local field_str = pairs(tmp)(tmp)
local get_field = jutils.access_field(field_str)
lt = function(a,b)
return get_field(a) < get_field(b)
end
gt = function(a,b)
return get_field(a) > get_field(b)
end
end
-- protected sort
local psort = function(s,a,b)
local ok,res = pcall(s,a,b)
if not ok or not res then
return false
else
return true
end
end
if options.sort.descending then
sort = function(a,b)
return psort(gt,a.value,b.value)
end
else
sort = function(a,b)
return psort(lt,a.value,b.value)
end
end
end
assert(sort)
local from = options.sort.from or 1
local to = options.sort.to or 10
local sorted = {}
local matches = {}
local index = {}
local n
local is_in_range = function(i)
return i and i >= from and i <= to
end
local sorter = function(notification,initializing)
local event = notification.event
local path = notification.path
local value = notification.value
if initializing then
if index[path] then
return
end
tinsert(matches,{
path = path,
value = value,
})
index[path] = #matches
return
end
local last_matches_len = #matches
local lastindex = index[path]
if event == 'remove' then
if lastindex then
tremove(matches,lastindex)
index[path] = nil
else
return
end
elseif lastindex then
matches[lastindex].value = value
else
tinsert(matches,{
path = path,
value = value,
})
end
tsort(matches,sort)
for i,m in ipairs(matches) do
index[m.path] = i
end
if last_matches_len < from and #matches < from then
return
end
local newindex = index[path]
local is_in = is_in_range(newindex)
-- special treatment for states which change
-- value without changing positions
if is_in and lastindex and newindex == lastindex then
notify({
n = n,
changes = {
{
path = path,
value = value,
index = newindex,
}
}
})
return
end
local start
local stop
local was_in = is_in_range(lastindex)
if is_in and was_in then
start = mmin(lastindex,newindex)
stop = mmax(lastindex,newindex)
elseif is_in and not was_in then
start = newindex
stop = mmin(to,#matches)
elseif not is_in and was_in then
start = lastindex
stop = mmin(to,#matches)
else
-- not is_in and not was_in
return
end
local changes = {}
for i=start,stop do
local new = matches[i]
local old = sorted[i]
if new and new ~= old then
tinsert(changes,{
path = new.path,
value = new.value,
index = i,
})
end
sorted[i] = new
if not new then
break
end
end
local new_n = mmin(to,#matches) - from + 1
if new_n ~= n or #changes > 0 then
n = new_n
notify({
changes = changes,
n = n,
})
end
end
local flush = function()
tsort(matches,sort)
for i,m in ipairs(matches) do
index[m.path] = i
end
n = 0
local changes = {}
for i=from,to do
local new = matches[i]
if new then
new.index = i
n = i - from + 1
sorted[i] = new
tinsert(changes,new)
end
end
notify({
changes = changes,
n = n,
})
end
return sorter,flush
end
return {
new = create_sorter
}
|
local jutils = require'jet.utils'
local tinsert = table.insert
local tremove = table.remove
local tconcat = table.concat
local tsort = table.sort
local unpack = unpack
local mmin = math.min
local mmax = math.max
local noop = jutils.noop
local is_empty_table = jutils.is_empty_table
-- may create and return a sorter function.
-- the sort function is based on the options.sort entries.
local create_sorter = function(options,notify)
if not options.sort then
return nil
end
local sort
if (options.sort.byValue == nil and options.sort.byValueField == nil) or options.sort.byPath then
if options.sort.descending then
sort = function(a,b)
return a.path > b.path
end
else
sort = function(a,b)
return a.path < b.path
end
end
else
local lt
local gt
if options.sort.byValue then
lt = function(a,b)
return a < b
end
gt = function(a,b)
return a > b
end
elseif options.sort.byValueField then
local tmp = options.sort.byValueField
local field_str = pairs(tmp)(tmp)
local get_field = jutils.access_field(field_str)
lt = function(a,b)
return get_field(a) < get_field(b)
end
gt = function(a,b)
return get_field(a) > get_field(b)
end
end
-- protected sort
local psort = function(s,a,b)
local ok,res = pcall(s,a,b)
if not ok or not res then
return false
else
return true
end
end
if options.sort.descending then
sort = function(a,b)
return psort(gt,a.value,b.value)
end
else
sort = function(a,b)
return psort(lt,a.value,b.value)
end
end
end
assert(sort)
local from = options.sort.from or 1
local to = options.sort.to or 10
local sorted = {}
local matches = {}
local index = {}
local n
local is_in_range = function(i)
return i and i >= from and i <= to
end
local initialized
local sorter = function(notification,initializing)
local event = notification.event
local path = notification.path
local value = notification.value
if initializing then
if index[path] then
return
end
tinsert(matches,{
path = path,
value = value,
})
index[path] = #matches
return
end
local last_matches_len = #matches
local lastindex = index[path]
if event == 'remove' then
if lastindex then
tremove(matches,lastindex)
index[path] = nil
else
return
end
elseif lastindex then
matches[lastindex].value = value
else
tinsert(matches,{
path = path,
value = value,
})
end
tsort(matches,sort)
for i,m in ipairs(matches) do
index[m.path] = i
end
if last_matches_len < from and #matches < from then
return
end
local newindex = index[path]
local is_in = is_in_range(newindex)
-- special treatment for states which change
-- value without changing positions
if is_in and lastindex and newindex == lastindex then
notify({
n = n,
changes = {
{
path = path,
value = value,
index = newindex,
}
}
})
return
end
local start
local stop
local was_in = is_in_range(lastindex)
if is_in and was_in then
start = mmin(lastindex,newindex)
stop = mmax(lastindex,newindex)
elseif is_in and not was_in then
start = newindex
stop = mmin(to,#matches)
elseif not is_in and was_in then
start = lastindex
stop = mmin(to,#matches)
elseif not initialized then
initialized = true
start = from
stop = mmin(to,#matches)
else
return
end
local changes = {}
for i=start,stop do
local new = matches[i]
local old = sorted[i]
if new and new ~= old then
tinsert(changes,{
path = new.path,
value = new.value,
index = i,
})
end
sorted[i] = new
if not new then
break
end
end
local new_n = mmin(to,#matches) - from + 1
if new_n ~= n or #changes > 0 then
n = new_n
notify({
changes = changes,
n = n,
})
end
end
local flush = function()
tsort(matches,sort)
for i,m in ipairs(matches) do
index[m.path] = i
end
n = 0
local changes = {}
for i=from,to do
local new = matches[i]
if new then
new.index = i
n = i - from + 1
sorted[i] = new
tinsert(changes,new)
end
end
notify({
changes = changes,
n = n,
})
end
return sorter,flush
end
return {
new = create_sorter
}
|
fix initialised state for sorter
|
fix initialised state for sorter
|
Lua
|
mit
|
lipp/lua-jet
|
4603b2fd43b39a9ec6cd0e566d063cea49f74255
|
scripts/shaderc.lua
|
scripts/shaderc.lua
|
--
-- Copyright 2010-2017 Branimir Karadzic. All rights reserved.
-- License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause
--
project "glslang"
kind "StaticLib"
local GLSLANG = path.join(BGFX_DIR, "3rdparty/glslang")
configuration { "vs2012" }
defines {
"atoll=_atoi64",
"strtoll=_strtoi64",
"strtoull=_strtoui64",
}
configuration { "vs*" }
buildoptions {
"/wd4005", -- warning C4005: '_CRT_SECURE_NO_WARNINGS': macro redefinition
}
configuration { "not vs*" }
buildoptions {
"-Wno-ignored-qualifiers",
"-Wno-inconsistent-missing-override",
"-Wno-missing-field-initializers",
"-Wno-reorder",
"-Wno-shadow",
"-Wno-sign-compare",
"-Wno-undef",
"-Wno-unknown-pragmas",
"-Wno-unused-parameter",
"-Wno-unused-variable",
}
configuration { "osx" }
buildoptions {
"-Wno-c++11-extensions",
"-Wno-unused-const-variable",
}
configuration { "linux-*" }
buildoptions {
"-Wno-unused-but-set-variable",
}
configuration {}
flags {
"Optimize",
}
includedirs {
GLSLANG,
}
files {
path.join(GLSLANG, "glslang/**.cpp"),
path.join(GLSLANG, "glslang/**.h"),
path.join(GLSLANG, "hlsl/**.cpp"),
path.join(GLSLANG, "hlsl/**.h"),
path.join(GLSLANG, "SPIRV/**.cpp"),
path.join(GLSLANG, "SPIRV/**.h"),
path.join(GLSLANG, "OGLCompilersDLL/**.cpp"),
path.join(GLSLANG, "OGLCompilersDLL/**.h"),
}
removefiles {
path.join(GLSLANG, "glslang/OSDependent/Unix/main.cpp"),
path.join(GLSLANG, "glslang/OSDependent/Windows/main.cpp"),
}
configuration { "windows" }
removefiles {
path.join(GLSLANG, "glslang/OSDependent/Unix/**.cpp"),
path.join(GLSLANG, "glslang/OSDependent/Unix/**.h"),
}
configuration { "not windows" }
removefiles {
path.join(GLSLANG, "glslang/OSDependent/Windows/**.cpp"),
path.join(GLSLANG, "glslang/OSDependent/Windows/**.h"),
}
configuration {}
project "shaderc"
kind "ConsoleApp"
local GLSL_OPTIMIZER = path.join(BGFX_DIR, "3rdparty/glsl-optimizer")
local FCPP_DIR = path.join(BGFX_DIR, "3rdparty/fcpp")
includedirs {
path.join(GLSL_OPTIMIZER, "src"),
}
flags {
"Optimize",
}
removeflags {
-- GCC 4.9 -O2 + -fno-strict-aliasing don't work together...
"OptimizeSpeed",
}
links {
"bx",
}
configuration { "vs*" }
includedirs {
path.join(GLSL_OPTIMIZER, "src/glsl/msvc"),
}
defines { -- glsl-optimizer
"__STDC__",
"__STDC_VERSION__=199901L",
"strdup=_strdup",
"alloca=_alloca",
"isascii=__isascii",
}
buildoptions {
"/wd4996" -- warning C4996: 'strdup': The POSIX name for this item is deprecated. Instead, use the ISO C++ conformant name: _strdup.
}
configuration { "mingw-*" }
targetextension ".exe"
configuration { "mingw* or linux or osx" }
buildoptions {
"-fno-strict-aliasing", -- glsl-optimizer has bugs if strict aliasing is used.
"-Wno-unused-parameter",
}
removebuildoptions {
"-Wshadow", -- glsl-optimizer is full of -Wshadow warnings ignore it.
}
configuration { "osx" }
links {
"Cocoa.framework",
}
configuration { "vs*" }
includedirs {
path.join(GLSL_OPTIMIZER, "include/c99"),
}
configuration {}
defines { -- fcpp
"NINCLUDE=64",
"NWORK=65536",
"NBUFF=65536",
"OLD_PREPROCESSOR=0",
}
includedirs {
path.join(BX_DIR, "include"),
path.join(BGFX_DIR, "include"),
path.join(BGFX_DIR, "3rdparty/dxsdk/include"),
FCPP_DIR,
path.join(BGFX_DIR, "3rdparty/glslang/glslang/Public"),
path.join(BGFX_DIR, "3rdparty/glslang/glslang/Include"),
path.join(BGFX_DIR, "3rdparty/glslang"),
-- path.join(BGFX_DIR, "3rdparty/spirv-tools/include"),
path.join(GLSL_OPTIMIZER, "include"),
path.join(GLSL_OPTIMIZER, "src/mesa"),
path.join(GLSL_OPTIMIZER, "src/mapi"),
path.join(GLSL_OPTIMIZER, "src/glsl"),
}
files {
path.join(BGFX_DIR, "tools/shaderc/**.cpp"),
path.join(BGFX_DIR, "tools/shaderc/**.h"),
path.join(BGFX_DIR, "src/vertexdecl.**"),
path.join(BGFX_DIR, "src/shader_spirv.**"),
path.join(FCPP_DIR, "**.h"),
path.join(FCPP_DIR, "cpp1.c"),
path.join(FCPP_DIR, "cpp2.c"),
path.join(FCPP_DIR, "cpp3.c"),
path.join(FCPP_DIR, "cpp4.c"),
path.join(FCPP_DIR, "cpp5.c"),
path.join(FCPP_DIR, "cpp6.c"),
path.join(FCPP_DIR, "cpp6.c"),
path.join(GLSL_OPTIMIZER, "src/mesa/**.c"),
path.join(GLSL_OPTIMIZER, "src/glsl/**.cpp"),
path.join(GLSL_OPTIMIZER, "src/mesa/**.h"),
path.join(GLSL_OPTIMIZER, "src/glsl/**.c"),
path.join(GLSL_OPTIMIZER, "src/glsl/**.cpp"),
path.join(GLSL_OPTIMIZER, "src/glsl/**.h"),
path.join(GLSL_OPTIMIZER, "src/util/**.c"),
path.join(GLSL_OPTIMIZER, "src/util/**.h"),
}
removefiles {
path.join(GLSL_OPTIMIZER, "src/glsl/glcpp/glcpp.c"),
path.join(GLSL_OPTIMIZER, "src/glsl/glcpp/tests/**"),
path.join(GLSL_OPTIMIZER, "src/glsl/glcpp/**.l"),
path.join(GLSL_OPTIMIZER, "src/glsl/glcpp/**.y"),
path.join(GLSL_OPTIMIZER, "src/glsl/ir_set_program_inouts.cpp"),
path.join(GLSL_OPTIMIZER, "src/glsl/main.cpp"),
path.join(GLSL_OPTIMIZER, "src/glsl/builtin_stubs.cpp"),
}
links {
"glslang",
}
if filesexist(BGFX_DIR, path.join(BGFX_DIR, "../bgfx-ext"), {
path.join(BGFX_DIR, "scripts/shaderc.lua"), }) then
if filesexist(BGFX_DIR, path.join(BGFX_DIR, "../bgfx-ext"), {
path.join(BGFX_DIR, "tools/shaderc/shaderc_pssl.cpp"), }) then
removefiles {
path.join(BGFX_DIR, "tools/shaderc/shaderc_pssl.cpp"),
}
end
dofile(path.join(BGFX_DIR, "../bgfx-ext/scripts/shaderc.lua") )
end
configuration { "osx or linux*" }
links {
"pthread",
}
configuration {}
strip()
|
--
-- Copyright 2010-2017 Branimir Karadzic. All rights reserved.
-- License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause
--
project "glslang"
kind "StaticLib"
local GLSLANG = path.join(BGFX_DIR, "3rdparty/glslang")
configuration { "vs2012" }
defines {
"atoll=_atoi64",
"strtoll=_strtoi64",
"strtoull=_strtoui64",
}
configuration { "vs*" }
buildoptions {
"/wd4005", -- warning C4005: '_CRT_SECURE_NO_WARNINGS': macro redefinition
}
configuration { "not vs*" }
buildoptions {
"-Wno-ignored-qualifiers",
"-Wno-inconsistent-missing-override",
"-Wno-missing-field-initializers",
"-Wno-reorder",
"-Wno-shadow",
"-Wno-sign-compare",
"-Wno-undef",
"-Wno-unknown-pragmas",
"-Wno-unused-parameter",
"-Wno-unused-variable",
}
configuration { "osx" }
buildoptions {
"-Wno-c++11-extensions",
"-Wno-unused-const-variable",
}
configuration { "linux-*" }
buildoptions {
"-Wno-unused-but-set-variable",
}
configuration {}
includedirs {
GLSLANG,
}
files {
path.join(GLSLANG, "glslang/**.cpp"),
path.join(GLSLANG, "glslang/**.h"),
path.join(GLSLANG, "hlsl/**.cpp"),
path.join(GLSLANG, "hlsl/**.h"),
path.join(GLSLANG, "SPIRV/**.cpp"),
path.join(GLSLANG, "SPIRV/**.h"),
path.join(GLSLANG, "OGLCompilersDLL/**.cpp"),
path.join(GLSLANG, "OGLCompilersDLL/**.h"),
}
removefiles {
path.join(GLSLANG, "glslang/OSDependent/Unix/main.cpp"),
path.join(GLSLANG, "glslang/OSDependent/Windows/main.cpp"),
}
configuration { "windows" }
removefiles {
path.join(GLSLANG, "glslang/OSDependent/Unix/**.cpp"),
path.join(GLSLANG, "glslang/OSDependent/Unix/**.h"),
}
configuration { "not windows" }
removefiles {
path.join(GLSLANG, "glslang/OSDependent/Windows/**.cpp"),
path.join(GLSLANG, "glslang/OSDependent/Windows/**.h"),
}
configuration {}
project "shaderc"
kind "ConsoleApp"
local GLSL_OPTIMIZER = path.join(BGFX_DIR, "3rdparty/glsl-optimizer")
local FCPP_DIR = path.join(BGFX_DIR, "3rdparty/fcpp")
includedirs {
path.join(GLSL_OPTIMIZER, "src"),
}
links {
"bx",
}
configuration { "Release" }
flags {
"Optimize",
}
removeflags {
-- GCC 4.9 -O2 + -fno-strict-aliasing don't work together...
"OptimizeSpeed",
}
configuration { "vs*" }
includedirs {
path.join(GLSL_OPTIMIZER, "src/glsl/msvc"),
}
defines { -- glsl-optimizer
"__STDC__",
"__STDC_VERSION__=199901L",
"strdup=_strdup",
"alloca=_alloca",
"isascii=__isascii",
}
buildoptions {
"/wd4996" -- warning C4996: 'strdup': The POSIX name for this item is deprecated. Instead, use the ISO C++ conformant name: _strdup.
}
configuration { "mingw-*" }
targetextension ".exe"
configuration { "mingw* or linux or osx" }
buildoptions {
"-fno-strict-aliasing", -- glsl-optimizer has bugs if strict aliasing is used.
"-Wno-unused-parameter",
}
removebuildoptions {
"-Wshadow", -- glsl-optimizer is full of -Wshadow warnings ignore it.
}
configuration { "osx" }
links {
"Cocoa.framework",
}
configuration { "vs*" }
includedirs {
path.join(GLSL_OPTIMIZER, "include/c99"),
}
configuration {}
defines { -- fcpp
"NINCLUDE=64",
"NWORK=65536",
"NBUFF=65536",
"OLD_PREPROCESSOR=0",
}
includedirs {
path.join(BX_DIR, "include"),
path.join(BGFX_DIR, "include"),
path.join(BGFX_DIR, "3rdparty/dxsdk/include"),
FCPP_DIR,
path.join(BGFX_DIR, "3rdparty/glslang/glslang/Public"),
path.join(BGFX_DIR, "3rdparty/glslang/glslang/Include"),
path.join(BGFX_DIR, "3rdparty/glslang"),
-- path.join(BGFX_DIR, "3rdparty/spirv-tools/include"),
path.join(GLSL_OPTIMIZER, "include"),
path.join(GLSL_OPTIMIZER, "src/mesa"),
path.join(GLSL_OPTIMIZER, "src/mapi"),
path.join(GLSL_OPTIMIZER, "src/glsl"),
}
files {
path.join(BGFX_DIR, "tools/shaderc/**.cpp"),
path.join(BGFX_DIR, "tools/shaderc/**.h"),
path.join(BGFX_DIR, "src/vertexdecl.**"),
path.join(BGFX_DIR, "src/shader_spirv.**"),
path.join(FCPP_DIR, "**.h"),
path.join(FCPP_DIR, "cpp1.c"),
path.join(FCPP_DIR, "cpp2.c"),
path.join(FCPP_DIR, "cpp3.c"),
path.join(FCPP_DIR, "cpp4.c"),
path.join(FCPP_DIR, "cpp5.c"),
path.join(FCPP_DIR, "cpp6.c"),
path.join(FCPP_DIR, "cpp6.c"),
path.join(GLSL_OPTIMIZER, "src/mesa/**.c"),
path.join(GLSL_OPTIMIZER, "src/glsl/**.cpp"),
path.join(GLSL_OPTIMIZER, "src/mesa/**.h"),
path.join(GLSL_OPTIMIZER, "src/glsl/**.c"),
path.join(GLSL_OPTIMIZER, "src/glsl/**.cpp"),
path.join(GLSL_OPTIMIZER, "src/glsl/**.h"),
path.join(GLSL_OPTIMIZER, "src/util/**.c"),
path.join(GLSL_OPTIMIZER, "src/util/**.h"),
}
removefiles {
path.join(GLSL_OPTIMIZER, "src/glsl/glcpp/glcpp.c"),
path.join(GLSL_OPTIMIZER, "src/glsl/glcpp/tests/**"),
path.join(GLSL_OPTIMIZER, "src/glsl/glcpp/**.l"),
path.join(GLSL_OPTIMIZER, "src/glsl/glcpp/**.y"),
path.join(GLSL_OPTIMIZER, "src/glsl/ir_set_program_inouts.cpp"),
path.join(GLSL_OPTIMIZER, "src/glsl/main.cpp"),
path.join(GLSL_OPTIMIZER, "src/glsl/builtin_stubs.cpp"),
}
links {
"glslang",
}
if filesexist(BGFX_DIR, path.join(BGFX_DIR, "../bgfx-ext"), {
path.join(BGFX_DIR, "scripts/shaderc.lua"), }) then
if filesexist(BGFX_DIR, path.join(BGFX_DIR, "../bgfx-ext"), {
path.join(BGFX_DIR, "tools/shaderc/shaderc_pssl.cpp"), }) then
removefiles {
path.join(BGFX_DIR, "tools/shaderc/shaderc_pssl.cpp"),
}
end
dofile(path.join(BGFX_DIR, "../bgfx-ext/scripts/shaderc.lua") )
end
configuration { "osx or linux*" }
links {
"pthread",
}
configuration {}
strip()
|
Fixed shaderc build.
|
Fixed shaderc build.
|
Lua
|
bsd-2-clause
|
MikePopoloski/bgfx,jpcy/bgfx,Synxis/bgfx,mmicko/bgfx,attilaz/bgfx,attilaz/bgfx,jdryg/bgfx,bkaradzic/bgfx,bkaradzic/bgfx,jdryg/bgfx,emoon/bgfx,emoon/bgfx,bkaradzic/bgfx,mendsley/bgfx,fluffyfreak/bgfx,fluffyfreak/bgfx,jdryg/bgfx,mmicko/bgfx,jpcy/bgfx,Synxis/bgfx,LWJGL-CI/bgfx,emoon/bgfx,MikePopoloski/bgfx,LWJGL-CI/bgfx,MikePopoloski/bgfx,mendsley/bgfx,mmicko/bgfx,Synxis/bgfx,fluffyfreak/bgfx,septag/bgfx,septag/bgfx,LWJGL-CI/bgfx,jpcy/bgfx,septag/bgfx,fluffyfreak/bgfx,mendsley/bgfx,jdryg/bgfx,jpcy/bgfx,LWJGL-CI/bgfx,bkaradzic/bgfx,attilaz/bgfx
|
72e40db9b9c1ee85c11ecf225dfa2118db6ef076
|
Source/genie.lua
|
Source/genie.lua
|
project "LudumDare32"
kind "ConsoleApp"
language "C++"
files { "**.h", "**.hpp", "**.cpp" }
location ( "../build" )
targetdir ( "../build/out/" )
objdir ( "../build/obj" )
local allIncludes =
{
"../bubblewrap/include",
"../bubblewrap/External",
SFML2DIR .. "/include/"
}
for k, v in pairs( additionalIncludes ) do
table.insert(allIncludes, v)
end
includedirs
{
allIncludes
}
links
{
"Bubblewrap",
"External_Json",
additionalLibraries
}
buildoptions "-std=c++11"
configuration "CrashNBurn"
targetdir ( "../build/lib/crashnburn" )
defines { "DEBUG", "CRASHNBURN" }
flags { "Symbols" }
links
{
SFML2DIR .. "/lib/sfml-graphics-d",
SFML2DIR .. "/lib/sfml-window-d",
SFML2DIR .. "/lib/sfml-system-d",
SFML2DIR .. "/lib/sfml-audio-d",
PHYSFSBUILDDIR .. "/Debug/physfs"
}
libdirs
{
"../build/lib/debug"
}
configuration "Debug and windows"
defines { "DEBUG" }
flags { "Symbols" }
links
{
SFML2DIR .. "/lib/sfml-graphics-d",
SFML2DIR .. "/lib/sfml-window-d",
SFML2DIR .. "/lib/sfml-system-d",
SFML2DIR .. "/lib/sfml-audio-d",
PHYSFSBUILDDIR .. "/Release/physfs"
}
libdirs
{
"../build/lib/debug"
}
configuration "Release"
defines { "NDEBUG" }
flags { "Optimize" }
links
{
SFML2DIR .. "/lib/sfml-graphics",
SFML2DIR .. "/lib/sfml-window",
SFML2DIR .. "/lib/sfml-system",
SFML2DIR .. "/lib/sfml-audio"
}
libdirs
{
"../build/lib/release"
}
configuration ( "Debug", "linux" )
defines { "DEBUG" }
flags { "Symbols" }
links
{
"sfml-graphics",
"sfml-window",
"sfml-system",
"sfml-audio",
"physfs"
}
libdirs
{
"../build/lib/debug"
}
|
project "LudumDare32"
kind "ConsoleApp"
language "C++"
files { "**.h", "**.hpp", "**.cpp" }
location ( "../build" )
targetdir ( "../build/out/" )
objdir ( "../build/obj" )
local allIncludes =
{
"../bubblewrap/include",
"../bubblewrap/External",
SFML2DIR .. "/include/"
}
for k, v in pairs( additionalIncludes ) do
table.insert(allIncludes, v)
end
includedirs
{
allIncludes
}
links
{
"Bubblewrap",
"External_Json",
additionalLibraries
}
buildoptions "-std=c++11"
configuration "CrashNBurn"
targetdir ( "../build/lib/crashnburn" )
defines { "DEBUG", "CRASHNBURN" }
flags { "Symbols" }
links
{
SFML2DIR .. "/lib/sfml-graphics-d",
SFML2DIR .. "/lib/sfml-window-d",
SFML2DIR .. "/lib/sfml-system-d",
SFML2DIR .. "/lib/sfml-audio-d",
PHYSFSBUILDDIR .. "/Debug/physfs"
}
libdirs
{
"../build/lib/debug"
}
configuration "Debug and windows"
defines { "DEBUG" }
flags { "Symbols" }
links
{
SFML2DIR .. "/lib/sfml-graphics-d",
SFML2DIR .. "/lib/sfml-window-d",
SFML2DIR .. "/lib/sfml-system-d",
SFML2DIR .. "/lib/sfml-audio-d",
PHYSFSBUILDDIR .. "/Release/physfs"
}
libdirs
{
"../build/lib/debug"
}
configuration "Release"
defines { "NDEBUG" }
flags { "Optimize" }
links
{
SFML2DIR .. "/lib/sfml-graphics",
SFML2DIR .. "/lib/sfml-window",
SFML2DIR .. "/lib/sfml-system",
SFML2DIR .. "/lib/sfml-audio"
}
libdirs
{
"../build/lib/release"
}
configuration ( "Debug", "linux" )
defines { "DEBUG" }
flags { "Symbols" }
links
{
"sfml-graphics",
"sfml-window",
"sfml-system",
"sfml-audio",
"physfs"
}
libdirs
{
"../build/lib/debug"
}
configuration ( "Release", "linux" )
defines { "NDEBUG" }
flags { "Optimize" }
links
{
"sfml-graphics",
"sfml-window",
"sfml-system",
"sfml-audio",
"physfs"
}
libdirs
{
"../build/lib/release"
}
|
fixed release build
|
fixed release build
|
Lua
|
mit
|
Dezzles/ludumdare32,Dezzles/ludumdare32
|
c1c53305e1c08296aa10efa6af2a612661761aee
|
genie.lua
|
genie.lua
|
function linkFBX()
configuration {"Debug"}
libdirs { "C:\\Program Files\\Autodesk\\FBX\\FBX SDK\\2017.1\\lib\\vs2015\\x64\\debug"}
configuration {"Release", "RelWithDebInfo"}
libdirs { "C:\\Program Files\\Autodesk\\FBX\\FBX SDK\\2017.1\\lib\\vs2015\\x64\\release"}
configuration {}
includedirs { "../../luxmiengine_fbx/src", "C:\\Program Files\\Autodesk\\FBX\\FBX SDK\\2017.1\\include", }
links { "libfbxsdk" }
defines {"FBXSDK_SHARED"}
end
project "lumixengine_fbx"
libType()
files {
"src/**.cpp",
"src/**.h",
"genie.lua"
}
if not build_studio then
removefiles { "src/editor/*" }
end
includedirs { "../../luxmiengine_fbx/src",
"../LumixEngine/external/lua/include",
"../LumixEngine/external/bgfx/include"
}
links { "engine" }
linkFBX()
defaultConfigurations()
table.insert(build_app_callbacks, linkFBX)
table.insert(build_studio_callbacks, linkFBX)
|
function linkFBX()
configuration {"Debug"}
libdirs { "../src"}
libdirs { "C:\\Program Files\\Autodesk\\FBX\\FBX SDK\\2017.1\\lib\\vs2015\\x64\\debug"}
configuration {"Release or RelWithDebInfo"}
libdirs { "C:\\Program Files\\Autodesk\\FBX\\FBX SDK\\2017.1\\lib\\vs2015\\x64\\release"}
configuration {}
includedirs { "../../luxmiengine_fbx/src", "C:\\Program Files\\Autodesk\\FBX\\FBX SDK\\2017.1\\include", }
links { "libfbxsdk" }
defines {"FBXSDK_SHARED"}
configuration {}
end
project "lumixengine_fbx"
libType()
files {
"src/**.cpp",
"src/**.h",
"genie.lua"
}
if not build_studio then
removefiles { "src/editor/*" }
end
includedirs { "../../luxmiengine_fbx/src",
"../LumixEngine/external/lua/include",
"../LumixEngine/external/bgfx/include"
}
links { "engine" }
linkFBX()
defaultConfigurations()
table.insert(build_app_callbacks, linkFBX)
table.insert(build_studio_callbacks, linkFBX)
|
fixed release build
|
fixed release build
|
Lua
|
mit
|
nem0/lumixengine_fbx
|
e983c3687ff2caf2fdf6ca331f2af9326436934b
|
core/libtexpdf-output.lua
|
core/libtexpdf-output.lua
|
local pdf = require("justenoughlibtexpdf")
if (not SILE.outputters) then SILE.outputters = {} end
local cursorX = 0
local cursorY = 0
local font = 0
local started = false
local function ensureInit ()
if not started then
pdf.init(SILE.outputFilename, SILE.documentState.paperSize[1],SILE.documentState.paperSize[2])
pdf.beginpage()
started = true
end
end
SILE.outputters.libtexpdf = {
init = function()
-- We don't do anything yet because this commits us to a page size.
end,
_init = ensureInit,
newPage = function()
ensureInit()
pdf.endpage()
pdf.beginpage()
end,
finish = function()
if not started then return end
pdf.endpage()
pdf.finish()
end,
setColor = function(self, color)
ensureInit()
if color.r then pdf.setcolor_rgb(color.r, color.g, color.b) end
if color.c then pdf.setcolor_cmyk(color.c, color.m, color.y, color.k) end
if color.l then pdf.setcolor_gray(color.l) end
end,
pushColor = function (self, color)
ensureInit()
if color.r then pdf.colorpush_rgb(color.r, color.g, color.b) end
if color.c then pdf.colorpush_cmyk(color.c, color.m, color.y, color.k) end
if color.l then pdf.colorpush_gray(color.l) end
end,
popColor = function (self)
ensureInit()
pdf.colorpop()
end,
cursor = function(self)
return cursorX, cursorY
end,
outputHbox = function (value,w)
ensureInit()
if not value.glyphString then return end
-- Nodes which require kerning or have offsets to the glyph
-- position should be output a glyph at a time. We pass the
-- glyph advance from the htmx table, so that libtexpdf knows
-- how wide each glyph is. It uses this to then compute the
-- relative position between the pen after the glyph has been
-- painted (cursorX + glyphAdvance) and the next painting
-- position (cursorX + width - remember that the box's "width"
-- is actually the shaped x_advance).
if value.complex then
for i=1,#(value.items) do
local glyph = value.items[i].gid
local buf = string.char(math.floor(glyph % 2^32 / 2^8)) .. string.char(glyph % 0x100)
pdf.setstring(cursorX + (value.items[i].x_offset or 0), cursorY + (value.items[i].y_offset or 0), buf, string.len(buf), font, value.items[i].glyphAdvance)
cursorX = cursorX + value.items[i].width
end
return
end
local buf = {}
for i=1,#(value.glyphString) do
glyph = value.glyphString[i]
buf[#buf+1] = string.char(math.floor(glyph % 2^32 / 2^8))
buf[#buf+1] = string.char(glyph % 0x100)
end
buf = table.concat(buf, "")
pdf.setstring(cursorX, cursorY, buf, string.len(buf), font, w)
end,
setFont = function (options)
ensureInit()
if SILE.font._key(options) == lastkey then return end
lastkey = SILE.font._key(options)
font = SILE.font.cache(options, SILE.shaper.getFace)
if options.direction == "TTB" then
font.layout_dir = 1
end
if SILE.typesetter.frame and SILE.typesetter.frame:writingDirection() == "TTB" then
pdf.setdirmode(1)
else
pdf.setdirmode(0)
end
f = pdf.loadfont(font)
if f< 0 then SU.error("Font loading error for "..options) end
font = f
end,
drawImage = function (src, x,y,w,h)
ensureInit()
pdf.drawimage(src, x, y, w, h)
end,
imageSize = function (src)
ensureInit() -- in case it's a PDF file
local llx, lly, urx, ury = pdf.imagebbox(src)
return (urx-llx), (ury-lly)
end,
moveTo = function (x,y)
cursorX = x
cursorY = SILE.documentState.paperSize[2] - y
end,
rule = function (x,y,w,d)
ensureInit()
pdf.setrule(x,SILE.documentState.paperSize[2] -y-d,w,d)
end,
debugFrame = function (self,f)
ensureInit()
pdf.colorpush_rgb(0.8, 0, 0)
self.rule(f:left(), f:top(), f:width(), 0.5)
self.rule(f:left(), f:top(), 0.5, f:height())
self.rule(f:right(), f:top(), 0.5, f:height())
self.rule(f:left(), f:bottom(), f:width(), 0.5)
--self.rule(f:left() + f:width()/2 - 5, (f:top() + f:bottom())/2+5, 10, 10)
local stuff = SILE.shaper:createNnodes(f.id, SILE.font.loadDefaults({}))
stuff = stuff[1].nodes[1].value.glyphString -- Horrible hack
local buf = {}
for i=1,#stuff do
glyph = stuff[i]
buf[#buf+1] = string.char(math.floor(glyph % 2^32 / 2^8))
buf[#buf+1] = string.char(glyph % 0x100)
end
buf = table.concat(buf, "")
if font == 0 then SILE.outputter.setFont(SILE.font.loadDefaults({})) end
pdf.setstring(f:left(), SILE.documentState.paperSize[2] -f:top(), buf, string.len(buf), font, 0)
pdf.colorpop()
end,
debugHbox = function(typesetter, hbox, scaledWidth)
end
}
SILE.outputter = SILE.outputters.libtexpdf
|
local pdf = require("justenoughlibtexpdf")
if (not SILE.outputters) then SILE.outputters = {} end
local cursorX = 0
local cursorY = 0
local font = 0
local started = false
local function ensureInit ()
if not started then
pdf.init(SILE.outputFilename, SILE.documentState.paperSize[1],SILE.documentState.paperSize[2])
pdf.beginpage()
started = true
end
end
SILE.outputters.libtexpdf = {
init = function()
-- We don't do anything yet because this commits us to a page size.
end,
_init = ensureInit,
newPage = function()
ensureInit()
pdf.endpage()
pdf.beginpage()
end,
finish = function()
if not started then return end
pdf.endpage()
pdf.finish()
end,
setColor = function(self, color)
ensureInit()
if color.r then pdf.setcolor_rgb(color.r, color.g, color.b) end
if color.c then pdf.setcolor_cmyk(color.c, color.m, color.y, color.k) end
if color.l then pdf.setcolor_gray(color.l) end
end,
pushColor = function (self, color)
ensureInit()
if color.r then pdf.colorpush_rgb(color.r, color.g, color.b) end
if color.c then pdf.colorpush_cmyk(color.c, color.m, color.y, color.k) end
if color.l then pdf.colorpush_gray(color.l) end
end,
popColor = function (self)
ensureInit()
pdf.colorpop()
end,
cursor = function(self)
return cursorX, cursorY
end,
outputHbox = function (value,w)
ensureInit()
if not value.glyphString then return end
-- Nodes which require kerning or have offsets to the glyph
-- position should be output a glyph at a time. We pass the
-- glyph advance from the htmx table, so that libtexpdf knows
-- how wide each glyph is. It uses this to then compute the
-- relative position between the pen after the glyph has been
-- painted (cursorX + glyphAdvance) and the next painting
-- position (cursorX + width - remember that the box's "width"
-- is actually the shaped x_advance).
if value.complex then
for i=1,#(value.items) do
local glyph = value.items[i].gid
local buf = string.char(math.floor(glyph % 2^32 / 2^8)) .. string.char(glyph % 0x100)
pdf.setstring(cursorX + (value.items[i].x_offset or 0), cursorY + (value.items[i].y_offset or 0), buf, string.len(buf), font, value.items[i].glyphAdvance)
cursorX = cursorX + value.items[i].width
end
return
end
local buf = {}
for i=1,#(value.glyphString) do
glyph = value.glyphString[i]
buf[#buf+1] = string.char(math.floor(glyph % 2^32 / 2^8))
buf[#buf+1] = string.char(glyph % 0x100)
end
buf = table.concat(buf, "")
pdf.setstring(cursorX, cursorY, buf, string.len(buf), font, w)
end,
setFont = function (options)
ensureInit()
if SILE.font._key(options) == lastkey then return end
lastkey = SILE.font._key(options)
font = SILE.font.cache(options, SILE.shaper.getFace)
if options.direction == "TTB" then
font.layout_dir = 1
end
if SILE.typesetter.frame and SILE.typesetter.frame:writingDirection() == "TTB" then
pdf.setdirmode(1)
else
pdf.setdirmode(0)
end
f = pdf.loadfont(font)
if f< 0 then SU.error("Font loading error for "..options) end
font = f
end,
drawImage = function (src, x,y,w,h)
ensureInit()
pdf.drawimage(src, x, y, w, h)
end,
imageSize = function (src)
ensureInit() -- in case it's a PDF file
local llx, lly, urx, ury = pdf.imagebbox(src)
return (urx-llx), (ury-lly)
end,
moveTo = function (x,y)
cursorX = x
cursorY = SILE.documentState.paperSize[2] - y
end,
rule = function (x,y,w,d)
ensureInit()
pdf.setrule(x,SILE.documentState.paperSize[2] -y-d,w,d)
end,
debugFrame = function (self,f)
ensureInit()
pdf.colorpush_rgb(0.8, 0, 0)
self.rule(f:left(), f:top(), f:width(), 0.5)
self.rule(f:left(), f:top(), 0.5, f:height())
self.rule(f:right(), f:top(), 0.5, f:height())
self.rule(f:left(), f:bottom(), f:width(), 0.5)
--self.rule(f:left() + f:width()/2 - 5, (f:top() + f:bottom())/2+5, 10, 10)
local stuff = SILE.shaper:createNnodes(f.id, SILE.font.loadDefaults({}))
stuff = stuff[1].nodes[1].value.glyphString -- Horrible hack
local buf = {}
for i=1,#stuff do
glyph = stuff[i]
buf[#buf+1] = string.char(math.floor(glyph % 2^32 / 2^8))
buf[#buf+1] = string.char(glyph % 0x100)
end
buf = table.concat(buf, "")
if font == 0 then SILE.outputter.setFont(SILE.font.loadDefaults({})) end
pdf.setstring(f:left(), SILE.documentState.paperSize[2] -f:top(), buf, string.len(buf), font, 0)
pdf.colorpop()
end,
debugHbox = function(hbox, scaledWidth)
ensureInit()
pdf.colorpush_rgb(0.8, 0.3, 0.3)
pdf.setrule(cursorX,cursorY+(hbox.height), scaledWidth+0.5, 0.5)
pdf.setrule(cursorX,cursorY, 0.5, hbox.height)
pdf.setrule(cursorX, cursorY, scaledWidth+0.5, 0.5)
pdf.setrule(cursorX+scaledWidth,cursorY, 0.5, hbox.height)
if hbox.depth then
pdf.setrule(cursorX,cursorY-(hbox.depth), scaledWidth, 0.5)
pdf.setrule(cursorX+scaledWidth,cursorY-(hbox.depth), 0.5, hbox.depth)
pdf.setrule(cursorX,cursorY-(hbox.depth), 0.5, hbox.depth)
end
pdf.colorpop()
end
}
SILE.outputter = SILE.outputters.libtexpdf
|
Add a hbox debugging tool
|
Add a hbox debugging tool
Fixes #515
Use it like this in your hbox’s output routine:
SILE.outputter.debugHbox(self, self:scaledWidth(line))
|
Lua
|
mit
|
alerque/sile,simoncozens/sile,alerque/sile,alerque/sile,simoncozens/sile,alerque/sile,simoncozens/sile,neofob/sile,neofob/sile,neofob/sile,simoncozens/sile,neofob/sile
|
55823aa2f367af04f9a77d2764754d4b002c0b4e
|
Hydra/window.lua
|
Hydra/window.lua
|
function api.window.allwindows()
return api.fn.mapcat(api.app.runningapps(), api.app.allwindows)
end
function api.window:isvisible()
return not self:app():ishidden() and
not self:isminimized() and
self:isstandard()
end
function api.window:frame()
local s = self:size()
local tl = self:topleft()
return {x = tl.x, y = tl.y, w = s.w, h = s.h}
end
function api.window:setframe(f)
self:setsize(f)
self:settopleft(f)
self:setsize(f)
end
function api.window:otherwindows_samescreen()
return api.fn.filter(api.window.visiblewindows(), function(win) return self ~= win and self:screen() == win:screen() end)
end
function api.window:otherwindows_allscreens()
return api.fn.filter(api.window.visiblewindows(), function(win) return self ~= win end)
end
function api.window:focus()
return self:becomemain() and self:app():activate()
end
function api.window.visiblewindows()
return api.fn.filter(api.window:allwindows(), api.window.isvisible)
end
function api.window:maximize()
local screenrect = self:screen():frame_without_dock_or_menu()
self:setframe(screenrect)
end
function api.window:screen()
local windowframe = self:frame()
local lastvolume = 0
local lastscreen = nil
for _, screen in pairs(api.screen.allscreens()) do
local screenframe = screen:frame_including_dock_and_menu()
local intersection = api.geometry.intersectionrect(windowframe, screenframe)
local volume = intersection.w * intersection.h
if volume > lastvolume then
lastvolume = volume
lastscreen = screen
end
end
return lastscreen
end
local function windows_in_direction(win, numrotations)
-- assume looking to east
local thiswindow = api.window.focusedwindow()
local startingpoint = api.geometry.rectmidpoint(thiswindow:frame())
local otherwindows = thiswindow:otherwindows_allscreens()
local closestwindows = {}
for _, win in pairs(otherwindows) do
local otherpoint = api.geometry.rectmidpoint(win:frame())
otherpoint = api.geometry.rotateccw(otherpoint, startingpoint, numrotations)
local delta = {
x = otherpoint.x - startingpoint.x,
y = otherpoint.y - startingpoint.y,
}
local angle = math.atan2(delta.y, delta.x)
local distance = api.geometry.hypot(delta)
local anglediff = -angle
local score = distance / math.cos(anglediff / 2)
table.insert(closestwindows, {win = win, score = score})
end
table.sort(closestwindows, function(a, b) return a.score < b.score end)
return api.fn.map(closestwindows, function(x) return x.win end)
end
local function focus_first_valid_window(ordered_wins)
for _, win in pairs(ordered_wins) do
if win:focus() then break end
end
end
function api.window:windows_to_east() return windows_in_direction(self, 0) end
function api.window:windows_to_west() return windows_in_direction(self, 2) end
function api.window:windows_to_north() return windows_in_direction(self, 3) end
function api.window:windows_to_south() return windows_in_direction(self, 1) end
function api.window:focuswindow_east() return focus_first_valid_window(self:windows_to_east()) end
function api.window:focuswindow_west() return focus_first_valid_window(self:windows_to_west()) end
function api.window:focuswindow_north() return focus_first_valid_window(self:windows_to_north()) end
function api.window:focuswindow_south() return focus_first_valid_window(self:windows_to_south()) end
|
function api.window.allwindows()
return api.fn.mapcat(api.app.runningapps(), api.app.allwindows)
end
function api.window:isvisible()
return not self:app():ishidden() and
not self:isminimized() and
self:isstandard()
end
function api.window:frame()
local s = self:size()
local tl = self:topleft()
return {x = tl.x, y = tl.y, w = s.w, h = s.h}
end
function api.window:setframe(f)
self:setsize(f)
self:settopleft(f)
self:setsize(f)
end
function api.window:otherwindows_samescreen()
return api.fn.filter(api.window.visiblewindows(), function(win) return self ~= win and self:screen() == win:screen() end)
end
function api.window:otherwindows_allscreens()
return api.fn.filter(api.window.visiblewindows(), function(win) return self ~= win end)
end
function api.window:focus()
return self:becomemain() and self:app():activate()
end
function api.window.visiblewindows()
return api.fn.filter(api.window:allwindows(), api.window.isvisible)
end
function api.window:maximize()
local screenrect = self:screen():frame_without_dock_or_menu()
self:setframe(screenrect)
end
function api.window:screen()
local windowframe = self:frame()
local lastvolume = 0
local lastscreen = nil
for _, screen in pairs(api.screen.allscreens()) do
local screenframe = screen:frame_including_dock_and_menu()
local intersection = api.geometry.intersectionrect(windowframe, screenframe)
local volume = intersection.w * intersection.h
if volume > lastvolume then
lastvolume = volume
lastscreen = screen
end
end
return lastscreen
end
local function windows_in_direction(win, numrotations)
-- assume looking to east
-- use the score distance/cos(A/2), where A is the angle by which it
-- differs from the straight line in the direction you're looking
-- for. (may have to manually prevent division by zero.)
-- thanks mark!
local thiswindow = api.window.focusedwindow()
local startingpoint = api.geometry.rectmidpoint(thiswindow:frame())
local otherwindows = thiswindow:otherwindows_allscreens()
local closestwindows = {}
for _, win in pairs(otherwindows) do
local otherpoint = api.geometry.rectmidpoint(win:frame())
otherpoint = api.geometry.rotateccw(otherpoint, startingpoint, numrotations)
local delta = {
x = otherpoint.x - startingpoint.x,
y = otherpoint.y - startingpoint.y,
}
if delta.x > 0 then
local angle = math.atan2(delta.y, delta.x)
local distance = api.geometry.hypot(delta)
local anglediff = -angle
local score = distance / math.cos(anglediff / 2)
table.insert(closestwindows, {win = win, score = score})
end
end
table.sort(closestwindows, function(a, b) return a.score < b.score end)
return api.fn.map(closestwindows, function(x) return x.win end)
end
local function focus_first_valid_window(ordered_wins)
for _, win in pairs(ordered_wins) do
if win:focus() then break end
end
end
function api.window:windows_to_east() return windows_in_direction(self, 0) end
function api.window:windows_to_west() return windows_in_direction(self, 2) end
function api.window:windows_to_north() return windows_in_direction(self, 1) end
function api.window:windows_to_south() return windows_in_direction(self, 3) end
function api.window:focuswindow_east() return focus_first_valid_window(self:windows_to_east()) end
function api.window:focuswindow_west() return focus_first_valid_window(self:windows_to_west()) end
function api.window:focuswindow_north() return focus_first_valid_window(self:windows_to_north()) end
function api.window:focuswindow_south() return focus_first_valid_window(self:windows_to_south()) end
|
Fixing windows_in_direction function! Closes #6!
|
Fixing windows_in_direction function! Closes #6!
|
Lua
|
mit
|
latenitefilms/hammerspoon,nkgm/hammerspoon,ocurr/hammerspoon,wvierber/hammerspoon,junkblocker/hammerspoon,cmsj/hammerspoon,joehanchoi/hammerspoon,wsmith323/hammerspoon,latenitefilms/hammerspoon,hypebeast/hammerspoon,bradparks/hammerspoon,Stimim/hammerspoon,Hammerspoon/hammerspoon,heptal/hammerspoon,chrisjbray/hammerspoon,zzamboni/hammerspoon,wvierber/hammerspoon,Hammerspoon/hammerspoon,peterhajas/hammerspoon,TimVonsee/hammerspoon,joehanchoi/hammerspoon,Hammerspoon/hammerspoon,Habbie/hammerspoon,wsmith323/hammerspoon,wvierber/hammerspoon,asmagill/hammerspoon,tmandry/hammerspoon,knu/hammerspoon,TimVonsee/hammerspoon,wsmith323/hammerspoon,ocurr/hammerspoon,zzamboni/hammerspoon,hypebeast/hammerspoon,knl/hammerspoon,knu/hammerspoon,CommandPost/CommandPost-App,asmagill/hammerspoon,bradparks/hammerspoon,zzamboni/hammerspoon,Hammerspoon/hammerspoon,hypebeast/hammerspoon,lowne/hammerspoon,cmsj/hammerspoon,Hammerspoon/hammerspoon,knu/hammerspoon,asmagill/hammerspoon,lowne/hammerspoon,nkgm/hammerspoon,trishume/hammerspoon,wvierber/hammerspoon,junkblocker/hammerspoon,Stimim/hammerspoon,ocurr/hammerspoon,peterhajas/hammerspoon,peterhajas/hammerspoon,bradparks/hammerspoon,emoses/hammerspoon,chrisjbray/hammerspoon,emoses/hammerspoon,chrisjbray/hammerspoon,Stimim/hammerspoon,trishume/hammerspoon,latenitefilms/hammerspoon,trishume/hammerspoon,kkamdooong/hammerspoon,dopcn/hammerspoon,heptal/hammerspoon,Habbie/hammerspoon,chrisjbray/hammerspoon,zzamboni/hammerspoon,ocurr/hammerspoon,Hammerspoon/hammerspoon,tmandry/hammerspoon,joehanchoi/hammerspoon,hypebeast/hammerspoon,junkblocker/hammerspoon,heptal/hammerspoon,junkblocker/hammerspoon,dopcn/hammerspoon,kkamdooong/hammerspoon,knl/hammerspoon,Habbie/hammerspoon,lowne/hammerspoon,dopcn/hammerspoon,CommandPost/CommandPost-App,cmsj/hammerspoon,asmagill/hammerspoon,cmsj/hammerspoon,heptal/hammerspoon,chrisjbray/hammerspoon,knl/hammerspoon,emoses/hammerspoon,latenitefilms/hammerspoon,nkgm/hammerspoon,kkamdooong/hammerspoon,CommandPost/CommandPost-App,heptal/hammerspoon,Stimim/hammerspoon,latenitefilms/hammerspoon,TimVonsee/hammerspoon,ocurr/hammerspoon,joehanchoi/hammerspoon,lowne/hammerspoon,CommandPost/CommandPost-App,knu/hammerspoon,wsmith323/hammerspoon,wvierber/hammerspoon,dopcn/hammerspoon,knu/hammerspoon,latenitefilms/hammerspoon,joehanchoi/hammerspoon,peterhajas/hammerspoon,bradparks/hammerspoon,Habbie/hammerspoon,asmagill/hammerspoon,cmsj/hammerspoon,knl/hammerspoon,emoses/hammerspoon,emoses/hammerspoon,TimVonsee/hammerspoon,CommandPost/CommandPost-App,cmsj/hammerspoon,knu/hammerspoon,junkblocker/hammerspoon,asmagill/hammerspoon,Habbie/hammerspoon,peterhajas/hammerspoon,CommandPost/CommandPost-App,kkamdooong/hammerspoon,nkgm/hammerspoon,wsmith323/hammerspoon,lowne/hammerspoon,nkgm/hammerspoon,TimVonsee/hammerspoon,knl/hammerspoon,zzamboni/hammerspoon,zzamboni/hammerspoon,kkamdooong/hammerspoon,hypebeast/hammerspoon,dopcn/hammerspoon,tmandry/hammerspoon,bradparks/hammerspoon,chrisjbray/hammerspoon,Stimim/hammerspoon,Habbie/hammerspoon
|
25e1dc90b21215b7c7adc2e74b4e1c4b81aa73bb
|
ninja.lua
|
ninja.lua
|
--
-- Name: premake-ninja/ninja.lua
-- Purpose: Define the ninja action.
-- Author: Dmitry Ivanov
-- Created: 2015/07/04
-- Copyright: (c) 2015 Dmitry Ivanov
--
local p = premake
local tree = p.tree
local project = p.project
local solution = p.solution
local config = p.config
local fileconfig = p.fileconfig
premake.modules.ninja = {}
local ninja = p.modules.ninja
function ninja.esc(value)
return value -- TODO
end
-- generate solution that will call ninja for projects
function ninja.generateSolution(sln)
p.w("# solution build file")
p.w("# generated with premake ninja")
p.w("")
p.w("# build projects")
local cfgs = {} -- key is configuration name, value is string of outputs names
local cfg_first = nil
for prj in solution.eachproject(sln) do
for cfg in project.eachconfig(prj) do
-- fill list of output files
if not cfgs[cfg.name] then cfgs[cfg.name] = "" end
cfgs[cfg.name] = cfgs[cfg.name] .. ninja.outputFilename(cfg) .. " "
-- set first configuration name
if cfg_first == nil then cfg_first = cfg.name end
-- include other ninja file
p.w("subninja " .. ninja.projectCfgFilename(cfg))
end
end
p.w("")
p.w("# targets")
for cfg, outputs in pairs(cfgs) do
p.w("build " .. cfg .. ": phony " .. outputs)
end
p.w("")
p.w("# default target")
p.w("default " .. cfg_first)
end
function ninja.list(value)
if #value > 0 then
return " " .. table.concat(value, " ")
else
return ""
end
end
-- generate project + config build file
function ninja.generateProjectCfg(cfg)
if cfg.toolset == nil then
cfg.toolset = "msc" -- TODO why premake doesn't provide default name always ?
end
local prj = cfg.project
local toolset = premake.tools[cfg.toolset]
p.w("# project build file")
p.w("# generated with premake ninja")
p.w("")
---------------------------------------------------- figure out toolset executables
local cc = ""
local cxx = ""
local ar = ""
local link = ""
if cfg.toolset == "msc" then
-- TODO premake doesn't set tools names for msc, do we want to fix it ?
cc = "cl"
cxx = "cl"
ar = "lib"
link = "cl"
else
-- TODO
end
---------------------------------------------------- figure out settings
local buildopt = ninja.list(cfg.buildoptions)
local cflags = ninja.list(toolset.getcflags(cfg))
local cppflags = ninja.list(toolset.getcppflags(cfg))
local cxxflags = ninja.list(toolset.getcxxflags(cfg))
local warnings = ninja.list(toolset.getwarnings(cfg))
local defines = ninja.list(table.join(toolset.getdefines(cfg.defines), toolset.getundefines(cfg.undefines)))
local includes = ninja.list(premake.esc(toolset.getincludedirs(cfg, cfg.includedirs, cfg.sysincludedirs)))
local forceincludes = ninja.list(premake.esc(toolset.getforceincludes(cfg))) -- TODO pch
local lddeps = ninja.list(premake.esc(config.getlinks(cfg, "siblings", "fullpath")))
local ldflags = ninja.list(table.join(toolset.getLibraryDirectories(cfg), toolset.getldflags(cfg), cfg.linkoptions))
local libs = ninja.list(toolset.getlinks(cfg))
local all_cflags = buildopt .. cflags .. warnings .. defines .. includes .. forceincludes
local all_cxxflags = buildopt .. cflags .. cppflags .. cxxflags .. warnings .. defines .. includes .. forceincludes
local all_ldflags = buildopt .. lddeps .. ldflags .. libs
local obj_dir = project.getrelative(cfg.project, cfg.objdir)
---------------------------------------------------- write rules
p.w("# core rules")
if cfg.toolset == "msc" then -- TODO /NOLOGO is invalid, we need to use /nologo
p.w("rule cc_" .. cfg.name)
p.w(" command = " .. cc .. all_cflags .. " /nologo /showIncludes -c $in /Fo$out")
p.w(" description = cxx $out")
p.w(" deps = msvc")
p.w("rule cxx_" .. cfg.name)
p.w(" command = " .. cc .. all_cxxflags .. " /nologo /showIncludes -c $in /Fo$out")
p.w(" description = cxx $out")
p.w(" deps = msvc")
p.w("rule ar_" .. cfg.name)
p.w(" command = " .. ar .. " $in /nologo -OUT:$out")
p.w(" description = ar $out")
p.w("rule link_" .. cfg.name)
p.w(" command = " .. link .. " $in" .. all_ldflags .. " /nologo /link /out:$out")
p.w(" description = link $out")
p.w("")
else
-- TODO
end
---------------------------------------------------- build all files
p.w("# build files")
local intermediateExt = function(cfg, var)
if (var == "c") or (var == "cxx") then
return iif(cfg.toolset == "msc", ".obj", ".o")
elseif var == "res" then
-- TODO
return ".res"
elseif var == "link" then
return cfg.targetextension
end
end
local objfiles = {}
tree.traverse(project.getsourcetree(prj), {
onleaf = function(node, depth)
local filecfg = fileconfig.getconfig(node, cfg)
if fileconfig.hasCustomBuildRule(filecfg) then
-- TODO
elseif path.iscppfile(node.abspath) then
objfilename = obj_dir .. "/" .. node.objname .. intermediateExt(cfg, "cxx")
p.w("build " .. objfilename .. ": cxx_" .. cfg.name .. " " .. node.relpath)
objfiles[#objfiles + 1] = objfilename
elseif path.isresourcefile(node.abspath) then
-- TODO
end
end,
}, false, 1)
p.w("")
---------------------------------------------------- build final target
if cfg.kind == premake.STATICLIB then
p.w("# link static lib")
p.w("build " .. ninja.outputFilename(cfg) .. ": ar_" .. cfg.name .. " " .. table.concat(objfiles, " "))
elseif cfg.kind == premake.SHAREDLIB then
-- TODO
elseif (cfg.kind == premake.CONSOLEAPP) or (cfg.kind == premake.WINDOWEDAPP) then
-- TODO windowed app
p.w("# link executable")
p.w("build " .. ninja.outputFilename(cfg) .. ": link_" .. cfg.name .. " " .. table.concat(objfiles, " "))
else
p.error("ninja action doesn't support this kind " .. cfg.kind)
end
end
-- return name of output binary relative to build folder
function ninja.outputFilename(cfg)
return project.getrelative(cfg.project, cfg.buildtarget.directory) .. "/" .. cfg.buildtarget.name
end
-- return name of build file for configuration
function ninja.projectCfgFilename(cfg)
return "build_" .. cfg.project.name .. "_" .. cfg.name .. ".ninja"
end
-- generate all build files for every project configuration
function ninja.generateProject(prj)
for cfg in project.eachconfig(prj) do
p.generate(cfg, ninja.projectCfgFilename(cfg), ninja.generateProjectCfg)
end
end
include("_preload.lua")
return ninja
|
--
-- Name: premake-ninja/ninja.lua
-- Purpose: Define the ninja action.
-- Author: Dmitry Ivanov
-- Created: 2015/07/04
-- Copyright: (c) 2015 Dmitry Ivanov
--
local p = premake
local tree = p.tree
local project = p.project
local solution = p.solution
local config = p.config
local fileconfig = p.fileconfig
premake.modules.ninja = {}
local ninja = p.modules.ninja
function ninja.esc(value)
return value -- TODO
end
-- generate solution that will call ninja for projects
function ninja.generateSolution(sln)
p.w("# solution build file")
p.w("# generated with premake ninja")
p.w("")
p.w("# build projects")
local cfgs = {} -- key is configuration name, value is string of outputs names
local cfg_first = nil
for prj in solution.eachproject(sln) do
for cfg in project.eachconfig(prj) do
-- fill list of output files
if not cfgs[cfg.name] then cfgs[cfg.name] = "" end
cfgs[cfg.name] = cfgs[cfg.name] .. ninja.outputFilename(cfg) .. " "
-- set first configuration name
if cfg_first == nil then cfg_first = cfg.name end
-- include other ninja file
p.w("subninja " .. ninja.projectCfgFilename(cfg))
end
end
p.w("")
p.w("# targets")
for cfg, outputs in pairs(cfgs) do
p.w("build " .. cfg .. ": phony " .. outputs)
end
p.w("")
p.w("# default target")
p.w("default " .. cfg_first)
end
function ninja.list(value)
if #value > 0 then
return " " .. table.concat(value, " ")
else
return ""
end
end
-- generate project + config build file
function ninja.generateProjectCfg(cfg)
if cfg.toolset == nil then
cfg.toolset = "msc" -- TODO why premake doesn't provide default name always ?
end
local prj = cfg.project
local toolset = premake.tools[cfg.toolset]
p.w("# project build file")
p.w("# generated with premake ninja")
p.w("")
---------------------------------------------------- figure out toolset executables
local cc = ""
local cxx = ""
local ar = ""
local link = ""
if cfg.toolset == "msc" then
-- TODO premake doesn't set tools names for msc, do we want to fix it ?
cc = "cl"
cxx = "cl"
ar = "lib"
link = "cl"
else
-- TODO
end
---------------------------------------------------- figure out settings
local buildopt = ninja.list(cfg.buildoptions)
local cflags = ninja.list(toolset.getcflags(cfg))
local cppflags = ninja.list(toolset.getcppflags(cfg))
local cxxflags = ninja.list(toolset.getcxxflags(cfg))
local warnings = ninja.list(toolset.getwarnings(cfg))
local defines = ninja.list(table.join(toolset.getdefines(cfg.defines), toolset.getundefines(cfg.undefines)))
local includes = ninja.list(premake.esc(toolset.getincludedirs(cfg, cfg.includedirs, cfg.sysincludedirs)))
local forceincludes = ninja.list(premake.esc(toolset.getforceincludes(cfg))) -- TODO pch
local lddeps = ninja.list(premake.esc(config.getlinks(cfg, "siblings", "fullpath")))
local ldflags = ninja.list(table.join(toolset.getLibraryDirectories(cfg), toolset.getldflags(cfg), cfg.linkoptions))
local libs = ninja.list(toolset.getlinks(cfg))
local all_cflags = buildopt .. cflags .. warnings .. defines .. includes .. forceincludes
local all_cxxflags = buildopt .. cflags .. cppflags .. cxxflags .. warnings .. defines .. includes .. forceincludes
local all_ldflags = buildopt .. lddeps .. ldflags
local obj_dir = project.getrelative(cfg.project, cfg.objdir)
---------------------------------------------------- write rules
p.w("# core rules")
if cfg.toolset == "msc" then -- TODO /NOLOGO is invalid, we need to use /nologo
p.w("rule cc_" .. cfg.name)
p.w(" command = " .. cc .. all_cflags .. " /nologo /showIncludes -c $in /Fo$out")
p.w(" description = cxx $out")
p.w(" deps = msvc")
p.w("rule cxx_" .. cfg.name)
p.w(" command = " .. cc .. all_cxxflags .. " /nologo /showIncludes -c $in /Fo$out")
p.w(" description = cxx $out")
p.w(" deps = msvc")
p.w("rule ar_" .. cfg.name)
p.w(" command = " .. ar .. " $in /nologo -OUT:$out")
p.w(" description = ar $out")
p.w("rule link_" .. cfg.name)
p.w(" command = " .. link .. " $in" .. all_ldflags .. " /nologo /link /out:$out")
p.w(" description = link $out")
p.w("")
else
-- TODO
end
---------------------------------------------------- build all files
p.w("# build files")
local intermediateExt = function(cfg, var)
if (var == "c") or (var == "cxx") then
return iif(cfg.toolset == "msc", ".obj", ".o")
elseif var == "res" then
-- TODO
return ".res"
elseif var == "link" then
return cfg.targetextension
end
end
local objfiles = {}
tree.traverse(project.getsourcetree(prj), {
onleaf = function(node, depth)
local filecfg = fileconfig.getconfig(node, cfg)
if fileconfig.hasCustomBuildRule(filecfg) then
-- TODO
elseif path.iscppfile(node.abspath) then
objfilename = obj_dir .. "/" .. node.objname .. intermediateExt(cfg, "cxx")
p.w("build " .. objfilename .. ": cxx_" .. cfg.name .. " " .. node.relpath)
objfiles[#objfiles + 1] = objfilename
elseif path.isresourcefile(node.abspath) then
-- TODO
end
end,
}, false, 1)
p.w("")
---------------------------------------------------- build final target
if cfg.kind == premake.STATICLIB then
p.w("# link static lib")
p.w("build " .. ninja.outputFilename(cfg) .. ": ar_" .. cfg.name .. " " .. table.concat(objfiles, " ") .. " " .. libs)
elseif cfg.kind == premake.SHAREDLIB then
-- TODO
elseif (cfg.kind == premake.CONSOLEAPP) or (cfg.kind == premake.WINDOWEDAPP) then
-- TODO windowed app
p.w("# link executable")
p.w("build " .. ninja.outputFilename(cfg) .. ": link_" .. cfg.name .. " " .. table.concat(objfiles, " ") .. " " .. libs)
else
p.error("ninja action doesn't support this kind " .. cfg.kind)
end
end
-- return name of output binary relative to build folder
function ninja.outputFilename(cfg)
return project.getrelative(cfg.project, cfg.buildtarget.directory) .. "/" .. cfg.buildtarget.name
end
-- return name of build file for configuration
function ninja.projectCfgFilename(cfg)
return "build_" .. cfg.project.name .. "_" .. cfg.name .. ".ninja"
end
-- generate all build files for every project configuration
function ninja.generateProject(prj)
for cfg in project.eachconfig(prj) do
p.generate(cfg, ninja.projectCfgFilename(cfg), ninja.generateProjectCfg)
end
end
include("_preload.lua")
return ninja
|
fix linkage with libs
|
fix linkage with libs
|
Lua
|
mit
|
jimon/premake-ninja,jimon/premake-ninja,jimon/premake-ninja,jimon/premake-ninja
|
f8951ede581e5b0a92b23c2b6705e7b1e186323d
|
ConfusionMatrix.lua
|
ConfusionMatrix.lua
|
local ConfusionMatrix = torch.class('nn.ConfusionMatrix')
function ConfusionMatrix:__init(nclasses, classes)
if type(nclasses) == 'table' then
classes = nclasses
nclasses = #classes
end
self.mat = torch.FloatTensor(nclasses,nclasses):zero()
self.valids = torch.FloatTensor(nclasses):zero()
self.unionvalids = torch.FloatTensor(nclasses):zero()
self.nclasses = nclasses
self.totalValid = 0
self.averageValid = 0
self.classes = classes or {}
end
function ConfusionMatrix:add(prediction, target)
if type(prediction) == 'number' then
-- comparing numbers
self.mat[target][prediction] = self.mat[target][prediction] + 1
elseif type(target) == 'number' then
-- prediction is a vector, then target assumed to be an index
local prediction_1d = torch.FloatTensor(self.nclasses):copy(prediction)
local _,prediction = prediction_1d:max(1)
self.mat[target][prediction[1]] = self.mat[target][prediction[1]] + 1
else
-- both prediction and target are vectors
local prediction_1d = torch.FloatTensor(self.nclasses):copy(prediction)
local target_1d = torch.FloatTensor(self.nclasses):copy(target)
local _,prediction = prediction_1d:max(1)
local _,target = target_1d:max(1)
self.mat[target[1]][prediction[1]] = self.mat[target[1]][prediction[1]] + 1
end
end
function ConfusionMatrix:zero()
self.mat:zero()
self.valids:zero()
self.unionvalids:zero()
self.totalValid = 0
self.averageValid = 0
end
function ConfusionMatrix:updateValids()
local total = 0
for t = 1,self.nclasses do
self.valids[t] = self.mat[t][t] / self.mat:select(1,t):sum()
self.unionvalids[t] = self.mat[t][t] / (self.mat:select(1,t):sum()+self.mat:select(2,t):sum()-self.mat[t][t])
total = total + self.mat[t][t]
end
self.totalValid = total / self.mat:sum()
self.averageValid = 0
self.averageUnionValid = 0
local nvalids = 0
local nunionvalids = 0
for t = 1,self.nclasses do
if not sys.isNaN(self.valids[t]) then
self.averageValid = self.averageValid + self.valids[t]
nvalids = nvalids + 1
end
if not sys.isNaN(self.unionvalids[t]) then
self.averageUnionValid = self.averageUnionValid + self.unionvalids[t]
nunionvalids = nunionvalids + 1
end
end
self.averageValid = self.averageValid / nvalids
self.averageUnionValid = self.averageUnionValid / nunionvalids
end
function ConfusionMatrix:__tostring__()
self:updateValids()
local str = 'ConfusionMatrix:\n'
local nclasses = self.nclasses
str = str .. '['
for t = 1,nclasses do
local pclass = self.valids[t] * 100
pclass = string.format('%2.3f', pclass)
if t == 1 then
str = str .. '['
else
str = str .. ' ['
end
for p = 1,nclasses do
str = str .. '' .. string.format('%8d', self.mat[t][p])
end
if self.classes and self.classes[1] then
if t == nclasses then
str = str .. ']] ' .. pclass .. '% \t[class: ' .. (self.classes[t] or '') .. ']\n'
else
str = str .. '] ' .. pclass .. '% \t[class: ' .. (self.classes[t] or '') .. ']\n'
end
else
if t == nclasses then
str = str .. ']] ' .. pclass .. '% \n'
else
str = str .. '] ' .. pclass .. '% \n'
end
end
end
str = str .. ' + average row correct: ' .. (self.averageValid*100) .. '% \n'
str = str .. ' + average rowUcol correct (VOC measure): ' .. (self.averageUnionValid*100) .. '% \n'
str = str .. ' + global correct: ' .. (self.totalValid*100) .. '%'
return str
end
|
local ConfusionMatrix = torch.class('nn.ConfusionMatrix')
function ConfusionMatrix:__init(nclasses, classes)
if type(nclasses) == 'table' then
classes = nclasses
nclasses = #classes
end
self.mat = torch.FloatTensor(nclasses,nclasses):zero()
self.valids = torch.FloatTensor(nclasses):zero()
self.unionvalids = torch.FloatTensor(nclasses):zero()
self.nclasses = nclasses
self.totalValid = 0
self.averageValid = 0
self.classes = classes or {}
end
function ConfusionMatrix:add(prediction, target)
if type(prediction) == 'number' then
-- comparing numbers
self.mat[target][prediction] = self.mat[target][prediction] + 1
elseif type(target) == 'number' then
-- prediction is a vector, then target assumed to be an index
local prediction_1d = torch.FloatTensor(self.nclasses):copy(prediction)
local _,prediction = prediction_1d:max(1)
self.mat[target][prediction[1]] = self.mat[target][prediction[1]] + 1
else
-- both prediction and target are vectors
local prediction_1d = torch.FloatTensor(self.nclasses):copy(prediction)
local target_1d = torch.FloatTensor(self.nclasses):copy(target)
local _,prediction = prediction_1d:max(1)
local _,target = target_1d:max(1)
self.mat[target[1]][prediction[1]] = self.mat[target[1]][prediction[1]] + 1
end
end
function ConfusionMatrix:zero()
self.mat:zero()
self.valids:zero()
self.unionvalids:zero()
self.totalValid = 0
self.averageValid = 0
end
function ConfusionMatrix:updateValids()
local total = 0
for t = 1,self.nclasses do
self.valids[t] = self.mat[t][t] / self.mat:select(1,t):sum()
self.unionvalids[t] = self.mat[t][t] / (self.mat:select(1,t):sum()+self.mat:select(2,t):sum()-self.mat[t][t])
total = total + self.mat[t][t]
end
self.totalValid = total / self.mat:sum()
self.averageValid = 0
self.averageUnionValid = 0
local nvalids = 0
local nunionvalids = 0
for t = 1,self.nclasses do
if not sys.isNaN(self.valids[t]) then
self.averageValid = self.averageValid + self.valids[t]
nvalids = nvalids + 1
end
if not sys.isNaN(self.valids[t]) and not sys.isNaN(self.unionvalids[t]) then
self.averageUnionValid = self.averageUnionValid + self.unionvalids[t]
nunionvalids = nunionvalids + 1
end
end
self.averageValid = self.averageValid / nvalids
self.averageUnionValid = self.averageUnionValid / nunionvalids
end
function ConfusionMatrix:__tostring__()
self:updateValids()
local str = 'ConfusionMatrix:\n'
local nclasses = self.nclasses
str = str .. '['
for t = 1,nclasses do
local pclass = self.valids[t] * 100
pclass = string.format('%2.3f', pclass)
if t == 1 then
str = str .. '['
else
str = str .. ' ['
end
for p = 1,nclasses do
str = str .. '' .. string.format('%8d', self.mat[t][p])
end
if self.classes and self.classes[1] then
if t == nclasses then
str = str .. ']] ' .. pclass .. '% \t[class: ' .. (self.classes[t] or '') .. ']\n'
else
str = str .. '] ' .. pclass .. '% \t[class: ' .. (self.classes[t] or '') .. ']\n'
end
else
if t == nclasses then
str = str .. ']] ' .. pclass .. '% \n'
else
str = str .. '] ' .. pclass .. '% \n'
end
end
end
str = str .. ' + average row correct: ' .. (self.averageValid*100) .. '% \n'
str = str .. ' + average rowUcol correct (VOC measure): ' .. (self.averageUnionValid*100) .. '% \n'
str = str .. ' + global correct: ' .. (self.totalValid*100) .. '%'
return str
end
|
Fixed VOC metric
|
Fixed VOC metric
|
Lua
|
mit
|
clementfarabet/lua---nnx
|
f6e3ee8912f977608ca5b8a7f9cf0fc495bea2ec
|
lib/gen.lua
|
lib/gen.lua
|
--{{{ Ninja
Ninja = {
space = 4
}
function Ninja:new()
local o = {}
setmetatable(o, self)
self.__index = self
return o
end
function Ninja:indent(level)
level = level or 0
local t = {}
for i = 1, level * self.space do
table.insert(t, ' ')
end
return table.concat(t)
end
function Ninja:variable(k, v, level)
return string.format('%s%s = %s\n', self:indent(level), k, v)
end
function Ninja:rule(rule)
local o = {
string.format('rule %s', rule.name),
self:variable('command', rule.command, 1)
}
if rule.variables then
for k, v in pairs(rule.variables) do
table.insert(o, self:variable(k, v, 1))
end
end
return table.concat(o, '\n')
end
function Ninja:build(build)
local header = {
string.format('build %s: %s',
table.concat(build.outputs, ' '), build.rule),
unpack(map(tostring, build.inputs))
}
local o = {
table.concat(header, ' $\n'..self:indent(4))
}
if build.variables then
for k, v in pairs(build.variables) do
table.insert(o, self:variable(k, v, 1))
end
end
return table.concat(o, '\n')
end
function Ninja:header()
local o = {
self:variable('builddir', jagen.build_dir),
self:rule({
name = 'command',
command = '$command'
}),
self:rule({
name = 'script',
command = '$script && touch $out'
}),
}
return table.concat(o)
end
function Ninja:build_stage(target)
local shell = jagen.shell
local script = 'jagen-pkg '..target:__tostring(' ')
if shell and #shell > 0 then
script = shell.." "..script
end
return self:build({
rule = 'script',
outputs = { tostring(target) },
inputs = target.inputs,
variables = { script = script }
})
end
function Ninja:build_package(pkg)
local o = {}
for _, stage in ipairs(pkg.stages) do
table.insert(o, self:build_stage(stage))
end
return table.concat(o)
end
function Ninja:generate(out_file, packages)
local out = io.open(out_file, 'w')
out:write(self:header())
out:write('\n')
for _, pkg in ipairs(packages) do
out:write(self:build_package(pkg))
out:write('\n')
end
out:close()
end
--}}}
--{{{ Script
Script = {}
function Script:new(pkg)
local script = { pkg = pkg }
setmetatable(script, self)
self.__index = self
return script
end
function Script:write()
local pkg = self.pkg
local path = system.mkpath(jagen.include_dir, pkg.name..'.sh')
local file = assert(io.open(path, 'w+'))
local function w(format, ...)
file:write(string.format(format, ...))
end
w('#!/bin/sh\n')
do
local source = pkg.source
if source.type and source.location then
w('\npkg_source="%s %s"', source.type, source.location)
end
if source.branch then
w('\npkg_source_branch="%s"', source.branch)
end
if source.path then
w('\npkg_source_dir="%s"', source.path)
end
end
do
local build_dir
if pkg.build then
local build = pkg.build
if build.options then
w('\npkg_options=\'%s\'', build.options)
end
if build.libs then
w("\npkg_libs='%s'", table.concat(build.libs, ' '))
end
if build.generate then
w("\npkg_build_generate='yes'")
end
if build.in_source then
build_dir = '$pkg_source_dir'
end
if build.directory then
build_dir = build.directory
end
end
build_dir = build_dir or '$pkg_work_dir${pkg_config:+/$pkg_config}'
w('\npkg_build_dir="%s"', build_dir)
end
if pkg.patches then
w('\njagen_pkg_apply_patches() {')
w('\n pkg_run cd "$pkg_source_dir"')
for _, patch in ipairs(self.pkg.patches or {}) do
local name = patch[1]
local strip = patch[2]
w('\n pkg_run_patch %d "%s"', strip, name)
end
w('\n}')
end
file:close()
end
--}}}
|
--{{{ Ninja
Ninja = {
space = 4
}
function Ninja:new()
local o = {}
setmetatable(o, self)
self.__index = self
return o
end
function Ninja:indent(level)
level = level or 0
local t = {}
for i = 1, level * self.space do
table.insert(t, ' ')
end
return table.concat(t)
end
function Ninja:variable(k, v, level)
return string.format('%s%s = %s\n', self:indent(level), k, v)
end
function Ninja:rule(rule)
local o = {
string.format('rule %s', rule.name),
self:variable('command', rule.command, 1)
}
if rule.variables then
for k, v in pairs(rule.variables) do
table.insert(o, self:variable(k, v, 1))
end
end
return table.concat(o, '\n')
end
function Ninja:build(build)
local header = {
string.format('build %s: %s',
table.concat(build.outputs, ' '), build.rule),
unpack(map(tostring, build.inputs))
}
local o = {
table.concat(header, ' $\n'..self:indent(4))
}
if build.variables then
for k, v in pairs(build.variables) do
table.insert(o, self:variable(k, v, 1))
end
end
return table.concat(o, '\n')
end
function Ninja:header()
local o = {
self:variable('builddir', jagen.build_dir),
self:rule({
name = 'command',
command = '$command'
}),
self:rule({
name = 'script',
command = '$script && touch $out'
}),
}
return table.concat(o)
end
function Ninja:build_stage(target)
local shell = jagen.shell
local script = 'jagen-pkg '..target:__tostring(' ')
if shell and #shell > 0 then
script = shell.." "..script
end
return self:build({
rule = 'script',
outputs = { tostring(target) },
inputs = target.inputs,
variables = { script = script }
})
end
function Ninja:build_package(pkg)
local o = {}
for _, stage in ipairs(pkg.stages) do
table.insert(o, self:build_stage(stage))
end
return table.concat(o)
end
function Ninja:generate(out_file, packages)
local out = io.open(out_file, 'w')
out:write(self:header())
out:write('\n')
for _, pkg in ipairs(packages) do
out:write(self:build_package(pkg))
out:write('\n')
end
out:close()
end
--}}}
--{{{ Script
Script = {}
function Script:new(pkg)
local script = { pkg = pkg }
setmetatable(script, self)
self.__index = self
return script
end
function Script:write()
local pkg = self.pkg
local path = system.mkpath(jagen.include_dir, pkg.name..'.sh')
local file = assert(io.open(path, 'w+'))
local function w(format, ...)
file:write(string.format(format, ...))
end
w('#!/bin/sh\n')
do
local source = pkg.source
if source.type and source.location then
w('\npkg_source="%s %s"', source.type, source.location)
end
if source.branch then
w('\npkg_source_branch="%s"', source.branch)
end
if source.path then
w('\npkg_source_dir="%s"', source.path)
end
end
do
local build_dir
if pkg.build then
local build = pkg.build
if build.options then
local o = build.options
if type(build.options) == 'string' then
o = { build.options }
end
w('\npkg_options="%s"', table.concat(o, '\n'))
end
if build.libs then
w("\npkg_libs='%s'", table.concat(build.libs, ' '))
end
if build.generate then
w("\npkg_build_generate='yes'")
end
if build.prefix then
w('\npkg_prefix="%s"', build.prefix)
end
if build.install then
w('\npkg_dest_dir="%s"', build.install)
end
if build.in_source then
build_dir = '$pkg_source_dir'
end
if build.directory then
build_dir = build.directory
end
end
build_dir = build_dir or '$pkg_work_dir${pkg_config:+/$pkg_config}'
w('\npkg_build_dir="%s"', build_dir)
end
if pkg.patches then
w('\njagen_pkg_apply_patches() {')
w('\n pkg_run cd "$pkg_source_dir"')
for _, patch in ipairs(self.pkg.patches or {}) do
local name = patch[1]
local strip = patch[2]
w('\n pkg_run_patch %d "%s"', strip, name)
end
w('\n}')
end
file:close()
end
--}}}
|
Generate prefix and dest_dir for pkg include script
|
Generate prefix and dest_dir for pkg include script
|
Lua
|
mit
|
bazurbat/jagen
|
9b3630f8b0e7012a0bf062ce366b35be043ed8f7
|
aliases.lua
|
aliases.lua
|
local std = stead
local type = std.type
std.rawset(_G, 'std', stead)
p = std.p
pr = std.pr
pn = std.pn
pf = std.pf
obj = std.obj
stat = std.stat
room = std.room
dlg = std.dlg
me = std.me
here = std.here
from = std.from
walk = std.walk
walkin = std.walkin
walkout = std.walkout
function object(w)
local o
if std.is_tag(w) then
o = std.here():lookup(w)
if not o then
std.err("Wrong tag: "..w, 3)
end
return o
end
o = std.ref(w)
if not o then
std.err("Wrong object: "..std.tostr(w), 3)
end
return o
end
function for_all(fn, ...)
if type(fn) ~= 'function' then
std.err("Wrong argument to for_all: "..std.tostr(fn), 2)
end
local a = {...}
for i = 1, #a do
fn(a[i])
end
end
function closed(w)
return object(w):closed()
end
function disabled(w)
return object(w):enabled()
end
function enable(w)
return object(w):enable()
end
function pop(w)
if not std.is_obi(std.here(), 'dlg') then
std.err("Call pop() in non-dialog object: "..std.tostr(std.here()), 2)
end
local r = std.here():pop(w)
if type(r) == 'string' then
std.p(r)
end
return r
end
function push(w)
if not std.is_obi(std.here(), 'dlg') then
std.err("Call push() in non-dialog object: "..std.tostr(std.here()), 2)
end
local r = std.here():push(w)
if type(r) == 'string' then
std.p(r)
end
return r
end
std.mod_init(function()
declare {
game = std.ref 'game',
pl = std.ref 'pl',
}
end)
|
local std = stead
local type = std.type
std.rawset(_G, 'std', stead)
p = std.p
pr = std.pr
pn = std.pn
pf = std.pf
obj = std.obj
stat = std.stat
room = std.room
dlg = std.dlg
me = std.me
here = std.here
from = std.from
walk = std.walk
walkin = std.walkin
walkout = std.walkout
function walk(w)
local r, v = std.walk(w)
if type(r) == 'string' then
std.p(r)
end
return r, v
end
function walkin(w)
local r, v = std.walkin(w)
if type(r) == 'string' then
std.p(r)
end
return r, v
end
function walkout(w)
local r, v = std.walkout(w)
if type(r) == 'string' then
std.p(r)
end
return r, v
end
function object(w)
local o
if std.is_tag(w) then
o = std.here():lookup(w)
if not o then
std.err("Wrong tag: "..w, 3)
end
return o
end
o = std.ref(w)
if not o then
std.err("Wrong object: "..std.tostr(w), 3)
end
return o
end
function for_all(fn, ...)
if type(fn) ~= 'function' then
std.err("Wrong argument to for_all: "..std.tostr(fn), 2)
end
local a = {...}
for i = 1, #a do
fn(a[i])
end
end
function closed(w)
return object(w):closed()
end
function disabled(w)
return object(w):enabled()
end
function enable(w)
return object(w):enable()
end
function pop(w)
if not std.is_obj(std.here(), 'dlg') then
std.err("Call pop() in non-dialog object: "..std.tostr(std.here()), 2)
end
local r, v = std.here():pop(w)
if type(r) == 'string' then
std.p(r)
end
return r, v
end
function push(w)
if not std.is_obj(std.here(), 'dlg') then
std.err("Call push() in non-dialog object: "..std.tostr(std.here()), 2)
end
local r, v = std.here():push(w)
if type(r) == 'string' then
std.p(r)
end
return r, v
end
std.mod_init(function()
declare {
game = std.ref 'game',
pl = std.ref 'pl',
}
end)
|
aliases fix
|
aliases fix
|
Lua
|
mit
|
gl00my/stead3
|
2e85aebe5c0b7f4b0cf200a99ab2c1d65329d514
|
examples/l2-load-latency.lua
|
examples/l2-load-latency.lua
|
-- vim:ts=4:sw=4:noexpandtab
local dpdk = require "dpdk"
local memory = require "memory"
local device = require "device"
local ts = require "timestamping"
local stats = require "stats"
local hist = require "histogram"
local PKT_SIZE = 60
local ETH_DST = "11:12:13:14:15:16"
function master(...)
local txPort, rxPort, rate = tonumberall(...)
if not txPort or not rxPort then
return print("usage: txPort rxPort [rate]")
end
rate = rate or 10000
-- hardware rate control fails with small packets at these rates
local numQueues = rate > 6000 and rate < 10000 and 3 or 1
local txDev = device.config(txPort, 2, 4)
local rxDev = device.config(rxPort, 2, 4) -- ignored if txDev == rxDev
device.waitForLinks()
local queues1, queues2 = {}, {}
for i = 1, numQueues do
local queue = txDev:getTxQueue(i)
queues1[#queues1 + 1] = queue
if rate < 10000 then -- only set rate if necessary to work with devices that don't support hw rc
queue:setRate(rate / numQueues)
end
local queue = rxDev:getTxQueue(i)
queues2[#queues2 + 1] = queue
if rate < 10000 then -- only set rate if necessary to work with devices that don't support hw rc
queue:setRate(rate / numQueues)
end
end
dpdk.launchLua("loadSlave", queues1, txDev, rxDev)
if rxPort ~= txPort then
dpdk.launchLua("loadSlave", queues2, rxDev, txDev)
end
dpdk.launchLua("timerSlave", txDev:getTxQueue(0), rxDev:getRxQueue(1))
dpdk.waitForSlaves()
end
function loadSlave(queues, txDev, rxDev)
local mem = memory.createMemPool(function(buf)
buf:getEthernetPacket():fill{
ethSrc = txDev,
ethDst = ETH_DST,
ethType = 0x1234
}
end)
local bufs = mem:bufArray()
local txCtr = stats:newDevTxCounter(txDev, "plain")
local rxCtr = stats:newDevRxCounter(rxDev, "plain")
while dpdk.running() do
for i, queue in ipairs(queues) do
bufs:alloc(PKT_SIZE)
queue:send(bufs)
end
txCtr:update()
rxCtr:update()
end
txCtr:finalize()
rxCtr:finalize()
end
function timerSlave(txQueue, rxQueue)
local timestamper = ts:newTimestamper(txQueue, rxQueue)
local hist = hist:new()
dpdk.sleepMillis(1000) -- ensure that the load task is running
while dpdk.running() do
hist:update(timestamper:measureLatency(function(buf) buf:getEthernetPacket().eth.dst:setString(ETH_DST) end))
end
hist:print()
hist:save("histogram.csv")
end
|
-- vim:ts=4:sw=4:noexpandtab
local dpdk = require "dpdk"
local memory = require "memory"
local device = require "device"
local ts = require "timestamping"
local stats = require "stats"
local hist = require "histogram"
local PKT_SIZE = 60
local ETH_DST = "11:12:13:14:15:16"
function master(...)
local txPort, rxPort, rate = tonumberall(...)
if not txPort or not rxPort then
return print("usage: txPort rxPort [rate]")
end
rate = rate or 10000
-- hardware rate control fails with small packets at these rates
local numQueues = rate > 6000 and rate < 10000 and 3 or 1
local txDev = device.config(txPort, 2, 4)
local rxDev = device.config(rxPort, 2, 4) -- ignored if txDev == rxDev
device.waitForLinks()
local queues1, queues2 = {}, {}
for i = 1, numQueues do
local queue = txDev:getTxQueue(i)
queues1[#queues1 + 1] = queue
if rate < 10000 then -- only set rate if necessary to work with devices that don't support hw rc
queue:setRate(rate / numQueues)
end
local queue = rxDev:getTxQueue(i)
queues2[#queues2 + 1] = queue
if rate < 10000 then -- only set rate if necessary to work with devices that don't support hw rc
queue:setRate(rate / numQueues)
end
end
dpdk.launchLua("loadSlave", queues1, txDev, rxDev)
if rxPort ~= txPort then
dpdk.launchLua("loadSlave", queues2, rxDev, txDev)
end
dpdk.launchLua("timerSlave", txDev:getTxQueue(0), rxDev:getRxQueue(1))
dpdk.waitForSlaves()
end
function loadSlave(queues, txDev, rxDev)
local mem = {}
local bufs = {}
for i in ipairs(queues) do
mem[i] = memory.createMemPool(function(buf)
buf:getEthernetPacket():fill{
ethSrc = txDev,
ethDst = ETH_DST,
ethType = 0x1234
}
end)
bufs[i] = mem[i]:bufArray()
end
local txCtr = stats:newDevTxCounter(txDev, "plain")
local rxCtr = stats:newDevRxCounter(rxDev, "plain")
while dpdk.running() do
for i, queue in ipairs(queues) do
bufs[i]:alloc(PKT_SIZE)
queue:send(bufs[i])
end
txCtr:update()
rxCtr:update()
end
txCtr:finalize()
rxCtr:finalize()
end
function timerSlave(txQueue, rxQueue)
local timestamper = ts:newTimestamper(txQueue, rxQueue)
local hist = hist:new()
dpdk.sleepMillis(1000) -- ensure that the load task is running
while dpdk.running() do
hist:update(timestamper:measureLatency(function(buf) buf:getEthernetPacket().eth.dst:setString(ETH_DST) end))
end
hist:print()
hist:save("histogram.csv")
end
|
l2-load-latency: fix crash at rates between 6500 and 9999
|
l2-load-latency: fix crash at rates between 6500 and 9999
|
Lua
|
mit
|
atheurer/MoonGen,gallenmu/MoonGen,duk3luk3/MoonGen,dschoeffm/MoonGen,NetronomeMoongen/MoonGen,dschoeffm/MoonGen,NetronomeMoongen/MoonGen,bmichalo/MoonGen,bmichalo/MoonGen,scholzd/MoonGen,gallenmu/MoonGen,emmericp/MoonGen,scholzd/MoonGen,gallenmu/MoonGen,duk3luk3/MoonGen,scholzd/MoonGen,dschoeffm/MoonGen,bmichalo/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen,duk3luk3/MoonGen,emmericp/MoonGen,atheurer/MoonGen,emmericp/MoonGen,gallenmu/MoonGen,atheurer/MoonGen,gallenmu/MoonGen,bmichalo/MoonGen,NetronomeMoongen/MoonGen,gallenmu/MoonGen
|
7f8720992744b0cea6850828cec9ab5fc024219c
|
extensions/dialog/init.lua
|
extensions/dialog/init.lua
|
--- === hs.dialog ===
---
--- A collection of useful dialog boxes, alerts and panels for user interaction.
--- === hs.dialog.color ===
---
--- A panel that allows users to select a color.
local USERDATA_TAG = "hs.dialog"
local module = require(USERDATA_TAG..".internal")
local color = require("hs.drawing.color")
-- Private Variables & Methods -----------------------------------------
-- Public Interface ------------------------------------------------------
color.panel = module.color
--- hs.dialog.alert(rect, callbackFn, message, [informativeText], [buttonOne], [buttonTwo], [style]) -> string
--- Function
--- Displays a simple non-blocking dialog box using `NSAlert` and a hidden `hs.webview` that's automatically destroyed when the alert is closed.
---
--- Parameters:
--- * x - A number containing the horizontal co-ordinate of the top-left point of the dialog box.
--- * y - A number containing the vertical co-ordinate of the top-left point of the dialog box.
--- * callbackFn - The callback function that's called when a button is pressed.
--- * message - The message text to display.
--- * [informativeText] - Optional informative text to display.
--- * [buttonOne] - An optional value for the first button as a string. Defaults to "OK".
--- * [buttonTwo] - An optional value for the second button as a string. If `nil` is used, no second button will be displayed.
--- * [style] - An optional style of the dialog box as a string. Defaults to "warning".
---
--- Returns:
--- * nil
---
--- Notes:
--- * The optional values must be entered in order (i.e. you can't supply `style` without also supplying `buttonOne` and `buttonTwo`).
--- * [style] can be "warning", "informational" or "critical". If something other than these string values is given, it will use "informational".
--- * Example:
--- ```testCallbackFn = function(result) print("Callback Result: " .. result) end
--- hs.dialog.alert(100, 100, testCallbackFn, "Message", "Informative Text", "Button One", "Button Two", "NSCriticalAlertStyle")
--- hs.dialog.alert(200, 200, testCallbackFn, "Message", "Informative Text", "Single Button")```
function module.alert(x, y, callback, ...)
local rect = {
h = 10, -- Small enough to be hidden by the alert panel
w = 10,
x = 1,
y = 1,
}
if type(x) == "number" then rect.x = x end
if type(y) == "number" then rect.y = y end
local wv = hs.webview.new(rect):show()
hs.dialog.webviewAlert(wv, function(...)
wv:delete()
callback(...)
end, ...)
end
-- Return Module Object --------------------------------------------------
return module
|
--- === hs.dialog ===
---
--- A collection of useful dialog boxes, alerts and panels for user interaction.
--- === hs.dialog.color ===
---
--- A panel that allows users to select a color.
local USERDATA_TAG = "hs.dialog"
local module = require(USERDATA_TAG..".internal")
local color = require("hs.drawing.color")
-- Private Variables & Methods -----------------------------------------
-- Public Interface ------------------------------------------------------
color.panel = module.color
--- hs.dialog.alert(x, y, callbackFn, message, [informativeText], [buttonOne], [buttonTwo], [style]) -> string
--- Function
--- Displays a simple non-blocking dialog box using `NSAlert` and a hidden `hs.webview` that's automatically destroyed when the alert is closed.
---
--- Parameters:
--- * x - A number containing the horizontal co-ordinate of the top-left point of the dialog box. Defaults to 1.
--- * y - A number containing the vertical co-ordinate of the top-left point of the dialog box. Defaults to 1.
--- * callbackFn - The callback function that's called when a button is pressed.
--- * message - The message text to display.
--- * [informativeText] - Optional informative text to display.
--- * [buttonOne] - An optional value for the first button as a string. Defaults to "OK".
--- * [buttonTwo] - An optional value for the second button as a string. If `nil` is used, no second button will be displayed.
--- * [style] - An optional style of the dialog box as a string. Defaults to "warning".
---
--- Returns:
--- * nil
---
--- Notes:
--- * The optional values must be entered in order (i.e. you can't supply `style` without also supplying `buttonOne` and `buttonTwo`).
--- * [style] can be "warning", "informational" or "critical". If something other than these string values is given, it will use "informational".
--- * Example:
--- ```testCallbackFn = function(result) print("Callback Result: " .. result) end
--- hs.dialog.alert(100, 100, testCallbackFn, "Message", "Informative Text", "Button One", "Button Two", "NSCriticalAlertStyle")
--- hs.dialog.alert(200, 200, testCallbackFn, "Message", "Informative Text", "Single Button")```
function module.alert(x, y, callback, ...)
local rect = {
h = 10, -- Small enough to be hidden by the alert panel
w = 10,
x = 1,
y = 1,
}
if type(x) == "number" then rect.x = x end
if type(y) == "number" then rect.y = y end
local wv = hs.webview.new(rect):show()
hs.dialog.webviewAlert(wv, function(...)
wv:delete()
callback(...)
end, ...)
end
-- Return Module Object --------------------------------------------------
return module
|
Fixed hs.dialog.alert in-line documentation
|
Fixed hs.dialog.alert in-line documentation
- Fixed a typo in `hs.dialog.alert`
|
Lua
|
mit
|
asmagill/hammerspoon,Hammerspoon/hammerspoon,Hammerspoon/hammerspoon,cmsj/hammerspoon,Habbie/hammerspoon,Hammerspoon/hammerspoon,Habbie/hammerspoon,CommandPost/CommandPost-App,latenitefilms/hammerspoon,cmsj/hammerspoon,Habbie/hammerspoon,Habbie/hammerspoon,CommandPost/CommandPost-App,Hammerspoon/hammerspoon,cmsj/hammerspoon,asmagill/hammerspoon,Hammerspoon/hammerspoon,CommandPost/CommandPost-App,CommandPost/CommandPost-App,latenitefilms/hammerspoon,CommandPost/CommandPost-App,Habbie/hammerspoon,cmsj/hammerspoon,latenitefilms/hammerspoon,Hammerspoon/hammerspoon,asmagill/hammerspoon,asmagill/hammerspoon,asmagill/hammerspoon,latenitefilms/hammerspoon,cmsj/hammerspoon,latenitefilms/hammerspoon,CommandPost/CommandPost-App,Habbie/hammerspoon,cmsj/hammerspoon,asmagill/hammerspoon,latenitefilms/hammerspoon
|
a7e832b5dd9f11bb81ebbf593fa1ea786a5b5aa1
|
src/plugins/lua/forged_recipients.lua
|
src/plugins/lua/forged_recipients.lua
|
--[[
Copyright (c) 2011-2015, Vsevolod Stakhov <vsevolod@highsecure.ru>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
]]--
-- Plugin for comparing smtp dialog recipients and sender with recipients and sender
-- in mime headers
local symbol_rcpt = 'FORGED_RECIPIENTS'
local symbol_sender = 'FORGED_SENDER'
function check_forged_headers(task)
local smtp_rcpt = task:get_recipients(1)
local res = false
if smtp_rcpt then
local mime_rcpt = task:get_recipients(2)
local count = 0
if mime_rcpt then
count = table.maxn(mime_rcpt)
end
if count < table.maxn(smtp_rcpt) then
task:insert_result(symbol_rcpt, 1)
else
-- Find pair for each smtp recipient recipient in To or Cc headers
for _,sr in ipairs(smtp_rcpt) do
if mime_rcpt then
for _,mr in ipairs(mime_rcpt) do
if string.lower(mr['addr']) == string.lower(sr['addr']) then
res = true
break
end
end
end
if not res then
task:insert_result(symbol_rcpt, 1)
break
end
end
end
end
-- Check sender
local smtp_from = task:get_from(1)
if smtp_from and smtp_from[1] then
local mime_from = task:get_from(2)
if not mime_from or not mime_from[1] or
not (string.lower(mime_from[1]['addr']) == string.lower(smtp_from[1]['addr'])) then
task:insert_result(symbol_sender, 1)
end
end
end
-- Registration
if type(rspamd_config.get_api_version) ~= 'nil' then
if rspamd_config:get_api_version() >= 1 then
rspamd_config:register_module_option('forged_recipients', 'symbol_rcpt', 'string')
rspamd_config:register_module_option('forged_recipients', 'symbol_sender', 'string')
end
end
-- Configuration
local opts = rspamd_config:get_all_opt('forged_recipients')
if opts then
if opts['symbol_rcpt'] or opts['symbol_sender'] then
if opts['symbol_rcpt'] then
symbol_rcpt = opts['symbol_rcpt']
if type(rspamd_config.get_api_version) ~= 'nil' then
rspamd_config:register_virtual_symbol(symbol_rcpt, 1.0, 'check_forged_headers')
end
end
if opts['symbol_sender'] then
symbol_sender = opts['symbol_sender']
if type(rspamd_config.get_api_version) ~= 'nil' then
rspamd_config:register_virtual_symbol(symbol_sender, 1.0)
end
end
if type(rspamd_config.get_api_version) ~= 'nil' then
rspamd_config:register_callback_symbol('FORGED_RECIPIENTS', 1.0, 'check_forged_headers')
else
rspamd_config:register_symbol('FORGED_RECIPIENTS', 1.0, 'check_forged_headers')
end
end
end
|
--[[
Copyright (c) 2011-2015, Vsevolod Stakhov <vsevolod@highsecure.ru>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
]]--
-- Plugin for comparing smtp dialog recipients and sender with recipients and sender
-- in mime headers
local logger = require "rspamd_logger"
local symbol_rcpt = 'FORGED_RECIPIENTS'
local symbol_sender = 'FORGED_SENDER'
local function check_forged_headers(task)
local smtp_rcpt = task:get_recipients(1)
local res = false
if smtp_rcpt then
local mime_rcpt = task:get_recipients(2)
local count = 0
if mime_rcpt then
count = table.maxn(mime_rcpt)
end
if count < table.maxn(smtp_rcpt) then
task:insert_result(symbol_rcpt, 1)
else
-- Find pair for each smtp recipient recipient in To or Cc headers
for _,sr in ipairs(smtp_rcpt) do
if mime_rcpt then
for _,mr in ipairs(mime_rcpt) do
if string.lower(mr['addr']) == string.lower(sr['addr']) then
res = true
break
end
end
end
if not res then
task:insert_result(symbol_rcpt, 1)
break
end
end
end
end
-- Check sender
local smtp_from = task:get_from(1)
if smtp_from and smtp_from[1] then
local mime_from = task:get_from(2)
if not mime_from or not mime_from[1] or
not (string.lower(mime_from[1]['addr']) == string.lower(smtp_from[1]['addr'])) then
task:insert_result(symbol_sender, 1)
end
end
end
-- Registration
if type(rspamd_config.get_api_version) ~= 'nil' then
if rspamd_config:get_api_version() >= 1 then
rspamd_config:register_module_option('forged_recipients', 'symbol_rcpt', 'string')
rspamd_config:register_module_option('forged_recipients', 'symbol_sender', 'string')
end
end
-- Configuration
local opts = rspamd_config:get_all_opt('forged_recipients')
if opts then
if opts['symbol_rcpt'] or opts['symbol_sender'] then
if opts['symbol_rcpt'] then
symbol_rcpt = opts['symbol_rcpt']
rspamd_config:register_virtual_symbol(symbol_rcpt, 1.0, check_forged_headers)
end
if opts['symbol_sender'] then
symbol_sender = opts['symbol_sender']
rspamd_config:register_virtual_symbol(symbol_sender, 1.0)
end
rspamd_config:register_callback_symbol('FORGED_RECIPIENTS', 1.0, check_forged_headers)
end
end
|
Fix forged recipients plugin for the modern rspamd.
|
Fix forged recipients plugin for the modern rspamd.
|
Lua
|
apache-2.0
|
awhitesong/rspamd,amohanta/rspamd,minaevmike/rspamd,dark-al/rspamd,amohanta/rspamd,andrejzverev/rspamd,minaevmike/rspamd,dark-al/rspamd,minaevmike/rspamd,AlexeySa/rspamd,minaevmike/rspamd,minaevmike/rspamd,minaevmike/rspamd,AlexeySa/rspamd,amohanta/rspamd,dark-al/rspamd,dark-al/rspamd,awhitesong/rspamd,minaevmike/rspamd,amohanta/rspamd,andrejzverev/rspamd,andrejzverev/rspamd,awhitesong/rspamd,amohanta/rspamd,AlexeySa/rspamd,AlexeySa/rspamd,AlexeySa/rspamd,minaevmike/rspamd,AlexeySa/rspamd,andrejzverev/rspamd,andrejzverev/rspamd,AlexeySa/rspamd,awhitesong/rspamd,andrejzverev/rspamd,AlexeySa/rspamd,minaevmike/rspamd,AlexeySa/rspamd,andrejzverev/rspamd,dark-al/rspamd,andrejzverev/rspamd
|
120cf6757e7559fb6079cd2efffbbecd4aebb54d
|
lib/lua/utils.lua
|
lib/lua/utils.lua
|
--------------------
-- Module with utility functions
--
-- @module utils
--
-- Submodules:
--
-- * `file`: Operations on files
-- * `math`: Contains a few math functions
-- * `string`: Operations on strings
-- * `table`: Operations on tables
util = {}
-- IO Functions
util.file = {}
-- Opens the file at path with the given mode and format
-- @param path File to be opened
-- @param mode Optional mode to open file with
-- @param format Optional format to read file with
-- @return The content of the file
function util.file.read_all(path, mode, format)
assert(path ~= nil, "File path was nil")
if mode == nil then
mod = "*all"
end
local file = io.open(path)
if file == nil then
error("Unable to open " .. path .. "!", 2)
end
local data = file:read(format)
file:close()
return data
end
-- Math functions
util.math = {}
-- Converts a number in a range to a percentage
-- @param min The minimum value in the range
-- @param max The maximum value in the range
-- @param value The value in the range to convert
-- @return A percentage from 0 to 100 for the value
function util.math.range_to_percent(min, max, value)
assert(type(min) == 'number', "min: expected number")
assert(type(max) == 'number', "max: expected number")
assert(type(value) == 'number', "value: expected number")
assert(min < max, "min value was not less than max!")
value = math.min(max, value)
value = math.max(min, value)
return math.ceil( (value - min) / (max - min) * 100 )
end
-- String functions
util.string = {}
-- Counts the number of lines in a string.
-- @param text String to count lines of
-- @return The number of lines in the string.
function util.string.line_count(text)
assert(type(text) == 'string', "Non-string given to string.line_count!")
local count = 0
for result in text:gmatch("\n") do
count = count + 1
end
return count
end
-- Escapes backslashes and quotes in a string.
--
-- Replaces " with \", ' with \', and \ with \\.
-- @param text String to escape
-- @return String escaped with quotes.
function util.string.escape_quotes(text)
assert(type(text) == 'string', "string.escape: Expected a string")
text = text:gsub('\\', '\\\\')
text = text:gsub('"', '\\"')
text = text:gsub("'", "\\'")
return text
end
-- Escapes strings for HTML encoding.
--
-- Replaces <, >, &, ", and ' with their HTML &name; equivalents.
-- @param test The text to escape
-- @return HTML escaped text.
function util.string.escape_html(text)
assert(type(text) == 'string', "string.html_escape: Expected a string")
builder = ""
for i = 1, text:len() do
if char == '<' then
builder = builder + '<'
elseif char == '>' then
builder = builder + '>'
elseif char == '&' then
builder = builder + '&'
elseif char == '"' then
builder = builder + '"'
elseif char == "'" then
builder = builder + '''
else
builder = builder + text[i]
end
end
return builder
end
-- Table functions
util.table = {}
-- Gets a random element from a numerically-indexed list.
--
-- # Errors
-- Function will error if the table is nil or empty,
-- or if the indicies are not numbers.
--
-- @param tab The list to pick from
-- @return A random element from the list
function util.table.get_random(tab)
assert(type(tab) == 'table', "Non table given to table.get_random!")
local len = #tab
if len == 0 then
error("Empty table given to table.get_random!", 2)
elseif len == 1 then
return tab[1]
else
return tab[math.random(1, len)]
end
end
-- List of programs that should be spawned each start/restart.
util.program = {}
util.program.programs = {}
-- Spawns a program once. Does not update the global program spawn list.
-- @param bin The program to run. Can be an absolute path or a command to run.
-- @param args The arguments (as a string) to pass to the program.
function util.program.spawn_once(bin, args)
assert(type(bin) == 'string', 'Non string given for program')
if type(args) ~= 'string' then
args = ""
end
os.execute(bin .. " " .. args .. " &")
end
-- Registers the program to spawn at startup and every time it restarts
-- @param bin The program to run. Can be an absolute path or a command to run.
-- @param args The arguments (as a string) to pass to the program.
function util.program.spawn_at_startup(bin, args)
assert(type(bin) == 'string', 'Non string given for program')
if type(args) ~= 'string' then
args = ""
end
table.insert(util.program.programs, {
bin = bin,
args = args
})
end
-- Spawns the startup programs
function util.program.spawn_startup_programs()
for index, program in ipairs(util.program.programs) do
os.execute(program.bin .. " " .. program.args .. " &")
end
end
-- Stops the startup programs. Does not remove them from the global list.
function util.program.terminate_startup_programs()
for index, program in ipairs(util.program.programs) do
-- TODO Kill in a more fine-grained matter...
-- parent joining on child process? PIDs won't work, they can be reclaimed.
os.execute("pkill " .. program.bin)
end
end
-- Stops the startup programs and then immediately starts them again.
-- Useful for the "restart" command
function util.program.restart_startup_programs()
util.program.terminate_startup_programs()
util.program.spawn_startup_programs()
end
|
--------------------
-- Module with utility functions
--
-- @module utils
--
-- Submodules:
--
-- * `file`: Operations on files
-- * `math`: Contains a few math functions
-- * `string`: Operations on strings
-- * `table`: Operations on tables
util = {}
-- IO Functions
util.file = {}
-- Opens the file at path with the given mode and format
-- @param path File to be opened
-- @param mode Optional mode to open file with
-- @param format Optional format to read file with
-- @return The content of the file
function util.file.read_all(path, mode, format)
assert(path ~= nil, "File path was nil")
if mode == nil then
mod = "*all"
end
local file = io.open(path)
if file == nil then
error("Unable to open " .. path .. "!", 2)
end
local data = file:read(format)
file:close()
return data
end
-- Math functions
util.math = {}
-- Converts a number in a range to a percentage
-- @param min The minimum value in the range
-- @param max The maximum value in the range
-- @param value The value in the range to convert
-- @return A percentage from 0 to 100 for the value
function util.math.range_to_percent(min, max, value)
assert(type(min) == 'number', "min: expected number")
assert(type(max) == 'number', "max: expected number")
assert(type(value) == 'number', "value: expected number")
assert(min < max, "min value was not less than max!")
value = math.min(max, value)
value = math.max(min, value)
return math.ceil( (value - min) / (max - min) * 100 )
end
-- String functions
util.string = {}
-- Counts the number of lines in a string.
-- @param text String to count lines of
-- @return The number of lines in the string.
function util.string.line_count(text)
assert(type(text) == 'string', "Non-string given to string.line_count!")
local count = 0
for result in text:gmatch("\n") do
count = count + 1
end
return count
end
-- Escapes backslashes and quotes in a string.
--
-- Replaces " with \", ' with \', and \ with \\.
-- @param text String to escape
-- @return String escaped with quotes.
function util.string.escape_quotes(text)
assert(type(text) == 'string', "string.escape: Expected a string")
text = text:gsub('\\', '\\\\')
text = text:gsub('"', '\\"')
text = text:gsub("'", "\\'")
return text
end
-- Escapes strings for HTML encoding.
--
-- Replaces <, >, &, ", and ' with their HTML &name; equivalents.
-- @param test The text to escape
-- @return HTML escaped text.
function util.string.escape_html(text)
assert(type(text) == 'string', "string.html_escape: Expected a string")
builder = ""
for i = 1, text:len() do
if char == '<' then
builder = builder + '<'
elseif char == '>' then
builder = builder + '>'
elseif char == '&' then
builder = builder + '&'
elseif char == '"' then
builder = builder + '"'
elseif char == "'" then
builder = builder + '''
else
builder = builder + text[i]
end
end
return builder
end
-- Table functions
util.table = {}
-- Gets a random element from a numerically-indexed list.
--
-- # Errors
-- Function will error if the table is nil or empty,
-- or if the indicies are not numbers.
--
-- @param tab The list to pick from
-- @return A random element from the list
function util.table.get_random(tab)
assert(type(tab) == 'table', "Non table given to table.get_random!")
local len = #tab
if len == 0 then
error("Empty table given to table.get_random!", 2)
elseif len == 1 then
return tab[1]
else
return tab[math.random(1, len)]
end
end
-- List of programs that should be spawned each start/restart.
util.program = {}
util.program.programs = {}
-- Spawns a program once. Does not update the global program spawn list.
-- @param bin The program to run. Can be an absolute path or a command to run.
-- @param args The arguments (as a string) to pass to the program.
function util.program.spawn_once(bin, args)
assert(type(bin) == 'string', 'Non string given for program')
if type(args) ~= 'string' then
args = ""
end
os.execute(bin .. " " .. args .. " &")
end
-- Registers the program to spawn at startup and every time it restarts
-- @param bin The program to run. Can be an absolute path or a command to run.
-- @param args The arguments (as a string) to pass to the program.
function util.program.spawn_at_startup(bin, args)
assert(type(bin) == 'string', 'Non string given for program')
table.insert(util.program.programs, {
bin = bin,
args = args
})
end
-- Spawns the startup programs
function util.program.spawn_startup_programs()
for index, program in ipairs(util.program.programs) do
os.execute(program.bin .. " " .. program.args .. " &")
end
end
-- Stops the startup programs. Does not remove them from the global list.
function util.program.terminate_startup_programs()
for index, program in ipairs(util.program.programs) do
-- TODO Kill in a more fine-grained matter...
-- parent joining on child process? PIDs won't work, they can be reclaimed.
os.execute("pkill " .. program.bin)
end
end
-- Stops the startup programs and then immediately starts them again.
-- Useful for the "restart" command
function util.program.restart_startup_programs()
util.program.terminate_startup_programs()
util.program.spawn_startup_programs()
end
|
Fixed non-string args not being passed
|
Fixed non-string args not being passed
|
Lua
|
mit
|
Immington-Industries/way-cooler,Immington-Industries/way-cooler,way-cooler/way-cooler,Immington-Industries/way-cooler,way-cooler/way-cooler,way-cooler/way-cooler
|
9b23272dc3de71adb25a1f5e7910d13ed9d249b0
|
.config/awesome/themes/MY_default/theme.lua
|
.config/awesome/themes/MY_default/theme.lua
|
------------------------------
-- MY Default awesome theme --
------------------------------
G_THEMEDIR = awful.util.getdir("config") .. "/themes/" -- name of this folder
G_THEMENAME = "MY_default" -- must be the name of the theme's folder
G_T = G_THEMEDIR .. G_THEMENAME .. "/"
theme = {}
theme.font = "sans 10"
theme.bg_normal = "#222222"
theme.bg_focus = "#535d6c"
theme.bg_urgent = "#ff0000"
theme.bg_minimize = "#444444"
theme.bg_systray = theme.bg_normal
theme.fg_normal = "#aaaaaa"
theme.fg_focus = "#ffffff"
theme.fg_urgent = "#ffffff"
theme.fg_minimize = "#ffffff"
theme.border_width = 0
theme.border_normal = "#0c0e10"
theme.border_focus = "#535d6c"
theme.border_marked = "#91231c"
-- There are other variable sets
-- overriding the default one when
-- defined, the sets are:
-- [taglist|tasklist]_[bg|fg]_[focus|urgent]
-- titlebar_[bg|fg]_[normal|focus]
-- tooltip_[font|opacity|fg_color|bg_color|border_width|border_color]
-- mouse_finder_[color|timeout|animate_timeout|radius|factor]
-- Example:
--theme.taglist_bg_focus = "#ff0000"
-- Display the taglist squares
theme.taglist_squares_sel = G_T .. "taglist/squarefw.png"
theme.taglist_squares_unsel = G_T .. "taglist/squarew.png"
-- Variables set for theming the menu:
-- menu_[bg|fg]_[normal|focus]
-- menu_[border_color|border_width]
theme.menu_submenu_icon = G_T .. "submenu.png"
theme.menu_height = 20
theme.menu_width = 120
-- You can add as many variables as
-- you wish and access them by using
-- beautiful.variable in your rc.lua
--theme.bg_widget = "#cc0000"
-- Define the image to load
-- X icon
theme.titlebar_close_button_normal = G_T .. "titlebar/close_normal.png"
theme.titlebar_close_button_focus = G_T .. "titlebar/close_focus.png"
-- star icon
theme.titlebar_ontop_button_normal_inactive = G_T .. "titlebar/ontop_normal_inactive.png"
theme.titlebar_ontop_button_focus_inactive = G_T .. "titlebar/ontop_focus_inactive.png"
theme.titlebar_ontop_button_normal_active = G_T .. "titlebar/ontop_normal_active.png"
theme.titlebar_ontop_button_focus_active = G_T .. "titlebar/ontop_focus_active.png"
-- plus icon
theme.titlebar_sticky_button_normal_inactive = G_T .. "titlebar/sticky_normal_inactive.png"
theme.titlebar_sticky_button_focus_inactive = G_T .. "titlebar/sticky_focus_inactive.png"
theme.titlebar_sticky_button_normal_active = G_T .. "titlebar/sticky_normal_active.png"
theme.titlebar_sticky_button_focus_active = G_T .. "titlebar/sticky_focus_active.png"
-- arrow icon
theme.titlebar_floating_button_normal_inactive = G_T .. "titlebar/floating_normal_inactive.png"
theme.titlebar_floating_button_focus_inactive = G_T .. "titlebar/floating_focus_inactive.png"
theme.titlebar_floating_button_normal_active = G_T .. "titlebar/floating_normal_active.png"
theme.titlebar_floating_button_focus_active = G_T .. "titlebar/floating_focus_active.png"
-- rocet icon
theme.titlebar_maximized_button_normal_inactive = G_T .. "titlebar/maximized_normal_inactive.png"
theme.titlebar_maximized_button_focus_inactive = G_T .. "titlebar/maximized_focus_inactive.png"
theme.titlebar_maximized_button_normal_active = G_T .. "titlebar/maximized_normal_active.png"
theme.titlebar_maximized_button_focus_active = G_T .. "titlebar/maximized_focus_active.png"
-- theme.wallpaper = G_T .. "background.png"
-- You can use your own layout icons like this:
theme.layout_fairh = G_T .. "layouts/fairhw.png"
theme.layout_fairv = G_T .. "layouts/fairvw.png"
theme.layout_floating = G_T .. "layouts/floatingw.png"
theme.layout_magnifier = G_T .. "layouts/magnifierw.png"
theme.layout_max = G_T .. "layouts/maxw.png"
theme.layout_fullscreen = G_T .. "layouts/fullscreenw.png"
theme.layout_tilebottom = G_T .. "layouts/tilebottomw.png"
theme.layout_tileleft = G_T .. "layouts/tileleftw.png"
theme.layout_tile = G_T .. "layouts/tilew.png"
theme.layout_tiletop = G_T .. "layouts/tiletopw.png"
theme.layout_spiral = G_T .. "layouts/spiralw.png"
theme.layout_dwindle = G_T .. "layouts/dwindlew.png"
theme.awesome_icon = "/usr/share/awesome/icons/awesome16.png"
-- Define the icon theme for application icons. If not set then the icons
-- from /usr/share/icons and /usr/share/icons/hicolor will be used.
theme.icon_theme = nil
return theme
-- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
|
------------------------------
-- MY Default awesome theme --
------------------------------
local awful = require("awful")
G_THEMEDIR = awful.util.getdir("config") .. "/themes/" -- name of this folder
G_THEMENAME = "MY_default" -- must be the name of the theme's folder
G_T = G_THEMEDIR .. G_THEMENAME .. "/"
theme = {}
theme.font = "sans 10"
theme.bg_normal = "#222222"
theme.bg_focus = "#535d6c"
theme.bg_urgent = "#ff0000"
theme.bg_minimize = "#444444"
theme.bg_systray = theme.bg_normal
theme.fg_normal = "#aaaaaa"
theme.fg_focus = "#ffffff"
theme.fg_urgent = "#ffffff"
theme.fg_minimize = "#ffffff"
theme.border_width = 0
theme.border_normal = "#0c0e10"
theme.border_focus = "#535d6c"
theme.border_marked = "#91231c"
-- There are other variable sets
-- overriding the default one when
-- defined, the sets are:
-- [taglist|tasklist]_[bg|fg]_[focus|urgent]
-- titlebar_[bg|fg]_[normal|focus]
-- tooltip_[font|opacity|fg_color|bg_color|border_width|border_color]
-- mouse_finder_[color|timeout|animate_timeout|radius|factor]
-- Example:
--theme.taglist_bg_focus = "#ff0000"
-- Display the taglist squares
theme.taglist_squares_sel = G_T .. "taglist/squarefw.png"
theme.taglist_squares_unsel = G_T .. "taglist/squarew.png"
-- Variables set for theming the menu:
-- menu_[bg|fg]_[normal|focus]
-- menu_[border_color|border_width]
theme.menu_submenu_icon = G_T .. "submenu.png"
theme.menu_height = 20
theme.menu_width = 120
-- You can add as many variables as
-- you wish and access them by using
-- beautiful.variable in your rc.lua
--theme.bg_widget = "#cc0000"
-- Define the image to load
-- X icon
theme.titlebar_close_button_normal = G_T .. "titlebar/close_normal.png"
theme.titlebar_close_button_focus = G_T .. "titlebar/close_focus.png"
-- star icon
theme.titlebar_ontop_button_normal_inactive = G_T .. "titlebar/ontop_normal_inactive.png"
theme.titlebar_ontop_button_focus_inactive = G_T .. "titlebar/ontop_focus_inactive.png"
theme.titlebar_ontop_button_normal_active = G_T .. "titlebar/ontop_normal_active.png"
theme.titlebar_ontop_button_focus_active = G_T .. "titlebar/ontop_focus_active.png"
-- plus icon
theme.titlebar_sticky_button_normal_inactive = G_T .. "titlebar/sticky_normal_inactive.png"
theme.titlebar_sticky_button_focus_inactive = G_T .. "titlebar/sticky_focus_inactive.png"
theme.titlebar_sticky_button_normal_active = G_T .. "titlebar/sticky_normal_active.png"
theme.titlebar_sticky_button_focus_active = G_T .. "titlebar/sticky_focus_active.png"
-- arrow icon
theme.titlebar_floating_button_normal_inactive = G_T .. "titlebar/floating_normal_inactive.png"
theme.titlebar_floating_button_focus_inactive = G_T .. "titlebar/floating_focus_inactive.png"
theme.titlebar_floating_button_normal_active = G_T .. "titlebar/floating_normal_active.png"
theme.titlebar_floating_button_focus_active = G_T .. "titlebar/floating_focus_active.png"
-- rocet icon
theme.titlebar_maximized_button_normal_inactive = G_T .. "titlebar/maximized_normal_inactive.png"
theme.titlebar_maximized_button_focus_inactive = G_T .. "titlebar/maximized_focus_inactive.png"
theme.titlebar_maximized_button_normal_active = G_T .. "titlebar/maximized_normal_active.png"
theme.titlebar_maximized_button_focus_active = G_T .. "titlebar/maximized_focus_active.png"
-- theme.wallpaper = G_T .. "background.png"
-- You can use your own layout icons like this:
theme.layout_fairh = G_T .. "layouts/fairhw.png"
theme.layout_fairv = G_T .. "layouts/fairvw.png"
theme.layout_floating = G_T .. "layouts/floatingw.png"
theme.layout_magnifier = G_T .. "layouts/magnifierw.png"
theme.layout_max = G_T .. "layouts/maxw.png"
theme.layout_fullscreen = G_T .. "layouts/fullscreenw.png"
theme.layout_tilebottom = G_T .. "layouts/tilebottomw.png"
theme.layout_tileleft = G_T .. "layouts/tileleftw.png"
theme.layout_tile = G_T .. "layouts/tilew.png"
theme.layout_tiletop = G_T .. "layouts/tiletopw.png"
theme.layout_spiral = G_T .. "layouts/spiralw.png"
theme.layout_dwindle = G_T .. "layouts/dwindlew.png"
theme.awesome_icon = "/usr/share/awesome/icons/awesome16.png"
-- Define the icon theme for application icons. If not set then the icons
-- from /usr/share/icons and /usr/share/icons/hicolor will be used.
theme.icon_theme = nil
return theme
-- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
|
Fix: forgot to load awful module, trashed theme.
|
Fix: forgot to load awful module, trashed theme.
|
Lua
|
unlicense
|
BirMa/dotfiles_home,BirMa/dotfiles_home,BirMa/dotfiles_home
|
fd8f8f07588b44e9d7de09e747bc05ef813a5138
|
spec/complex_spec.lua
|
spec/complex_spec.lua
|
local literal = require "literal"
local serpent = require "serpent"
local refser = require "refser"
local function random_var(is_key, deep)
local key = math.random(1000)
if key <= 100 then
if is_key then
return 0
else
return nil
end
elseif key <= 200 then
return false
elseif key <= 500 then
return math.random(-1e6, 1e6)
elseif key <= 900 then
local len = math.random(0, 100)
local res = {}
for i=1, len do
table.insert(res, string.char(math.random(0, 255)))
end
return table.concat(res)
else
if deep > 3 or is_key then
return 0
else
local len = math.random(0, 10)
local res = {}
for i=1, len do
if math.random(0, 1) == 0 then
table.insert(res, random_var(false, deep+1))
else
res[random_var(true, deep+1)] = random_var(false, deep+1)
end
end
return res
end
end
end
describe("randomized test", function()
it("evaluates literals produced by serpent", function()
math.randomseed(os.time())
for i=1, 100 do
local x = random_var(false, 0)
local s = serpent.block(x, {sortkeys=false})
local x2 = literal.eval(s)
assert.same(x, x2)
end
end)
end)
|
local literal = require "literal"
local serpent = require "serpent"
local function random_var(is_key, deep)
local key = math.random(1000)
if key <= 100 then
if is_key then
return 0
else
return nil
end
elseif key <= 200 then
return false
elseif key <= 300 then
return true
elseif key <= 600 then
return math.random(-1e6, 1e6)
elseif key <= 900 then
local len = math.random(0, 100)
local res = {}
for i=1, len do
table.insert(res, string.char(math.random(0, 255)))
end
return table.concat(res)
else
if deep > 3 or is_key then
return 0
else
local len = math.random(0, 10)
local res = {}
for i=1, len do
if math.random(0, 1) == 0 then
table.insert(res, random_var(false, deep+1))
else
res[random_var(true, deep+1)] = random_var(false, deep+1)
end
end
return res
end
end
end
describe("randomized test", function()
it("evaluates literals produced by serpent", function()
math.randomseed(os.time())
for i=1, 100 do
local x = random_var(false, 0)
local s = serpent.block(x, {sortkeys=false})
local x2 = literal.eval(s)
assert.same(x, x2)
end
end)
end)
|
fixed random test not using true
|
fixed random test not using true
|
Lua
|
unlicense
|
mpeterv/literal
|
d2205a8fca84d17ef771be749e93a193bddf8529
|
src/rxbinderutils/src/Shared/RxBinderUtils.lua
|
src/rxbinderutils/src/Shared/RxBinderUtils.lua
|
---
-- @module RxBinderUtils
-- @author Quenty
local require = require(script.Parent.loader).load(script)
local Binder = require("Binder")
local Brio = require("Brio")
local Maid = require("Maid")
local Observable = require("Observable")
local Rx = require("Rx")
local RxBrioUtils = require("RxBrioUtils")
local RxInstanceUtils = require("RxInstanceUtils")
local RxLinkUtils = require("RxLinkUtils")
local RxBinderUtils = {}
function RxBinderUtils.observeLinkedBoundClassBrio(linkName, parent, binder)
assert(type(linkName) == "string", "Bad linkName")
assert(typeof(parent) == "Instance", "Bad parent")
assert(Binder.isBinder(binder), "Bad binder")
return RxLinkUtils.observeValidLinksBrio(linkName, parent)
:Pipe({
RxBrioUtils.flatMap(function(_, linkValue)
return RxBinderUtils.observeBoundClassBrio(binder, linkValue)
end);
});
end
function RxBinderUtils.observeBoundChildClassBrio(binder, instance)
assert(Binder.isBinder(binder), "Bad binder")
assert(typeof(instance) == "Instance", "Bad instance")
return RxInstanceUtils.observeChildrenBrio(instance)
:Pipe({
RxBrioUtils.flatMap(function(child)
return RxBinderUtils.observeBoundClassBrio(binder, child)
end);
})
end
function RxBinderUtils.observeBoundChildClassesBrio(binders, instance)
assert(Binder.isBinder(binders), "Bad binders")
assert(typeof(instance) == "Instance", "Bad instance")
return RxInstanceUtils.observeChildrenBrio(instance)
:Pipe({
RxBrioUtils.flatMap(function(child)
return RxBinderUtils.observeBoundClassesBrio(binders, child)
end);
})
end
function RxBinderUtils.observeBoundClass(binder, instance)
assert(type(binder) == "table", "Bad binder")
assert(typeof(instance) == "Instance", "Bad instance")
return Observable.new(function(sub)
local maid = Maid.new()
maid:GiveTask(binder:ObserveInstance(instance, function(...)
sub:Fire(...)
end))
sub:Fire(binder:Get(instance))
return maid
end)
end
function RxBinderUtils.observeBoundClassBrio(binder, instance)
assert(type(binder) == "table", "Bad binder")
assert(typeof(instance) == "Instance", "Bad instance")
return Observable.new(function(sub)
local maid = Maid.new()
local function handleClassChanged(class)
if class then
local brio = Brio.new(class)
maid._lastBrio = brio
sub:Fire(brio)
else
maid._lastBrio = nil
end
end
maid:GiveTask(binder:ObserveInstance(instance, handleClassChanged))
handleClassChanged(binder:Get(instance))
return maid
end)
end
function RxBinderUtils.observeBoundClassesBrio(binders, instance)
assert(Binder.isBinder(binders), "Bad binders")
assert(typeof(instance) == "Instance", "Bad instance")
local observables = {}
for _, binder in pairs(binders) do
table.insert(observables, RxBinderUtils.observeBoundClassBrio(binder, instance))
end
return Rx.of(unpack(observables)):Pipe({
Rx.mergeAll();
})
end
function RxBinderUtils.observeAllBrio(binder)
assert(Binder.isBinder(binder), "Bad binder")
return Observable.new(function(sub)
local maid = Maid.new()
local function handleNewClass(class)
local brio = Brio.new(class)
maid[class] = brio
sub:Fire(brio)
end
maid:GiveTask(binder:GetClassAddedSignal():Connect(handleNewClass))
maid:GiveTask(binder:GetClassRemovingSignal():Connect(function(class)
maid[class] = nil
end))
for class, _ in pairs(binder:GetAllSet()) do
handleNewClass(class)
end
return maid
end)
end
return RxBinderUtils
|
---
-- @module RxBinderUtils
-- @author Quenty
local require = require(script.Parent.loader).load(script)
local Binder = require("Binder")
local Brio = require("Brio")
local Maid = require("Maid")
local Observable = require("Observable")
local Rx = require("Rx")
local RxBrioUtils = require("RxBrioUtils")
local RxInstanceUtils = require("RxInstanceUtils")
local RxLinkUtils = require("RxLinkUtils")
local RxBinderUtils = {}
function RxBinderUtils.observeLinkedBoundClassBrio(linkName, parent, binder)
assert(type(linkName) == "string", "Bad linkName")
assert(typeof(parent) == "Instance", "Bad parent")
assert(Binder.isBinder(binder), "Bad binder")
return RxLinkUtils.observeValidLinksBrio(linkName, parent)
:Pipe({
RxBrioUtils.flatMap(function(_, linkValue)
return RxBinderUtils.observeBoundClassBrio(binder, linkValue)
end);
});
end
function RxBinderUtils.observeBoundChildClassBrio(binder, instance)
assert(Binder.isBinder(binder), "Bad binder")
assert(typeof(instance) == "Instance", "Bad instance")
return RxInstanceUtils.observeChildrenBrio(instance)
:Pipe({
RxBrioUtils.flatMap(function(child)
return RxBinderUtils.observeBoundClassBrio(binder, child)
end);
})
end
function RxBinderUtils.observeBoundParentClassBrio(binder, instance)
assert(Binder.isBinder(binder), "Bad binder")
assert(typeof(instance) == "Instance", "Bad instance")
return RxInstanceUtils.observePropertyBrio(instance, "Parent")
:Pipe({
RxBrioUtils.switchMap(function(child)
if child then
return RxBinderUtils.observeBoundClassBrio(binder, child)
else
return Rx.EMPTY
end
end);
})
end
function RxBinderUtils.observeBoundChildClassesBrio(binders, instance)
assert(Binder.isBinder(binders), "Bad binders")
assert(typeof(instance) == "Instance", "Bad instance")
return RxInstanceUtils.observeChildrenBrio(instance)
:Pipe({
RxBrioUtils.flatMap(function(child)
return RxBinderUtils.observeBoundClassesBrio(binders, child)
end);
})
end
function RxBinderUtils.observeBoundClass(binder, instance)
assert(type(binder) == "table", "Bad binder")
assert(typeof(instance) == "Instance", "Bad instance")
return Observable.new(function(sub)
local maid = Maid.new()
maid:GiveTask(binder:ObserveInstance(instance, function(...)
sub:Fire(...)
end))
sub:Fire(binder:Get(instance))
return maid
end)
end
function RxBinderUtils.observeBoundClassBrio(binder, instance)
assert(type(binder) == "table", "Bad binder")
assert(typeof(instance) == "Instance", "Bad instance")
return Observable.new(function(sub)
local maid = Maid.new()
local function handleClassChanged(class)
if class then
local brio = Brio.new(class)
maid._lastBrio = brio
sub:Fire(brio)
else
maid._lastBrio = nil
end
end
maid:GiveTask(binder:ObserveInstance(instance, handleClassChanged))
handleClassChanged(binder:Get(instance))
return maid
end)
end
function RxBinderUtils.observeBoundClassesBrio(binders, instance)
assert(Binder.isBinder(binders), "Bad binders")
assert(typeof(instance) == "Instance", "Bad instance")
local observables = {}
for _, binder in pairs(binders) do
table.insert(observables, RxBinderUtils.observeBoundClassBrio(binder, instance))
end
return Rx.of(unpack(observables)):Pipe({
Rx.mergeAll();
})
end
function RxBinderUtils.observeAllBrio(binder)
assert(Binder.isBinder(binder), "Bad binder")
return Observable.new(function(sub)
local maid = Maid.new()
local function handleNewClass(class)
local brio = Brio.new(class)
maid[class] = brio
sub:Fire(brio)
end
maid:GiveTask(binder:GetClassAddedSignal():Connect(handleNewClass))
maid:GiveTask(binder:GetClassRemovingSignal():Connect(function(class)
maid[class] = nil
end))
for class, _ in pairs(binder:GetAllSet()) do
handleNewClass(class)
end
return maid
end)
end
return RxBinderUtils
|
fix: Add RxBinderUtils.observeBoundParentClassBrio(binder, instance)
|
fix: Add RxBinderUtils.observeBoundParentClassBrio(binder, instance)
|
Lua
|
mit
|
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
|
3f469b49bdde7fa6efe30e4f639b95599b8f1a91
|
data/dist/shooter/main.lua
|
data/dist/shooter/main.lua
|
oldprint = print
print = function(...)
local args = { n = select("#", ...), ... }
local t = ""
for i=1,args.n do
t = t .. tostring(args[i])
end
oldprint(t)
end
print('Hello world')
IsDown = function(key)
return key.state > 0.1
end
WasDown = function(key)
return key.last_state > 0.1
end
JustPressed = function(key)
return IsDown(key) and not WasDown(key)
end
StarRandom = Math.NewRandom()
if StarRandom ~= nil then
print("has random")
else
print("no random")
end
Types = {
Pos2= Registry.GetPosition2Id(),
Sprite= Registry.GetSpriteId(),
Player= Registry.New("Player"),
MoveUp= Registry.New("MoveUp"),
Star= Registry.New("Star", function(args)
c = {}
c.speed = args:GetNumber("speed") + StarRandom:NextRangeFloat(args:GetNumber("random_boost"))
return c
end),
DestroyOutside= Registry.New("DestroyOutside"),
TimeOut= Registry.New("TimeOut", function()
c = {}
c.time = 4
return c
end)
}
-- todo: create some on init callback, to spawn the stars
-- or enter level callback
-- or init callback on entity that is directly destroyed, or keep spawning points
-- move sprite anchor to config
Systems.OnInit("place star", {Types.Pos2, Types.Star}, function(entity)
local vec = Registry.GetPosition2vec(entity)
local p = StarRandom:NextPoint2(Camera.GetRect())
vec.x = p.x
vec.y = p.y
end)
Systems.AddUpdate("star movement", function(dt)
local ents = Registry.Entities({Types.Sprite, Types.Star})
ents.forEach(function(entity)
local star = Registry.Get(entity, Types.Star)
local vec = Registry.GetPosition2vec(entity)
if vec ~= null then
vec.y = vec.y - dt * star.speed;
if vec.y < 0 then
vec.x = StarRandom:NextRangeFloat(Camera.GetRect().GetWidth())
vec.y = vec.y + Camera.GetRect().GetHeight()
end
end
end)
end)
-- todo: new update function
-- Systems.OnUpdate("move up", [Types.Pos2, Types.MoveUp], function(dt, entities) { });
time = 0
bark = 0
Systems.AddUpdate("bark", function(dt)
time = time + dt
if time>1 then
time = time - 1
bark = bark + 1
print('Bark!', bark)
end
end)
Systems.AddUpdate("move up", function(dt)
local ents = Registry.Entities({Types.Pos2, Types.MoveUp})
ents.forEach(function(entity)
local vec = Registry.GetPosition2vec(entity)
if vec ~= null then
local speed = 250
vec.y = vec.y + dt * speed
end
end)
end)
Systems.AddUpdate("time out", function(dt)
local ents = Registry.Entities({Types.TimeOut});
ents.forEach(function(entity)
local data = Registry.Get(entity, Types.TimeOut)
data.time = data.time - dt
if data.time < 0 then
print("Timeout")
Registry.DestroyEntity(entity)
end
end)
end)
Systems.AddUpdate("destroy outside", function (dt)
local ents = Registry.Entities({Types.Sprite, Types.Pos2, Types.DestroyOutside})
ents.forEach(function (entity)
local sp = Registry.GetSprite(entity)
local p = Registry.GetPosition2(entity)
if sp ~= null then
local cam = Camera.GetRect()
local r = sp.GetRect(p)
if not cam.Contains(r) then
Registry.DestroyEntity(entity)
end
end
end)
end)
shotTemplate = Templates.Find("shot")
Systems.AddUpdate("player", function(dt)
ents = Registry.Entities({Types.Pos2, Types.Player})
ents.forEach(function(entity)
local vec = Registry.GetPosition2vec(entity)
if vec ~= null then
local speed = 150
local vertical = Input.up.state - Input.down.state
local horizontal = Input.right.state - Input.left.state
if JustPressed(Input.fire) then
if not shotTemplate then
print("no shot")
else
local shot = shotTemplate.Create()
local v = Registry.GetPosition2vec(shot)
if v ~= null then
v.x = vec.x
v.y = vec.y
end
end
end
vec.y = vec.y + dt * speed * vertical
vec.x = vec.x + dt * speed * horizontal
end
end)
end)
|
oldprint = print
print = function(...)
local args = { n = select("#", ...), ... }
local t = ""
for i=1,args.n do
t = t .. tostring(args[i])
end
oldprint(t)
end
print('Hello world')
IsDown = function(key)
return key.state > 0.1
end
WasDown = function(key)
return key.last_state > 0.1
end
JustPressed = function(key)
return IsDown(key) and not WasDown(key)
end
StarRandom = Math.NewRandom()
Types = {
Pos2= Registry.GetPosition2Id(),
Sprite= Registry.GetSpriteId(),
Player= Registry.New("Player"),
MoveUp= Registry.New("MoveUp"),
Star= Registry.New("Star", function(args)
c = {}
c.speed = args:GetNumber("speed") + StarRandom:NextRangeFloat(args:GetNumber("random_boost"))
return c
end),
DestroyOutside= Registry.New("DestroyOutside"),
TimeOut= Registry.New("TimeOut", function()
c = {}
c.time = 4
return c
end)
}
-- todo: create some on init callback, to spawn the stars
-- or enter level callback
-- or init callback on entity that is directly destroyed, or keep spawning points
-- move sprite anchor to config
Systems.OnInit("place star", {Types.Pos2, Types.Star}, function(entity)
local vec = Registry.GetPosition2vec(entity)
local p = StarRandom:NextPoint2(Camera.GetRect())
vec.x = p.x
vec.y = p.y
end)
Systems.AddUpdate("star movement", function(dt)
local ents = Registry.Entities({Types.Sprite, Types.Star})
for _, entity in pairs(ents) do
local star = Registry.Get(entity, Types.Star)
local vec = Registry.GetPosition2vec(entity)
if vec ~= null then
vec.y = vec.y - dt * star.speed;
local vy = vec.y
-- print("Moving star to ", vy)
if vy < 0.0 then
vec.x = StarRandom:NextRangeFloat(Camera.GetRect():GetWidth())
vec.y = vec.y + Camera.GetRect():GetHeight()
print("Reseting star to ", vec.x, " ", vec.y)
end
end
end
end)
-- todo: new update function
-- Systems.OnUpdate("move up", [Types.Pos2, Types.MoveUp], function(dt, entities) { });
time = 0
bark = 0
Systems.AddUpdate("bark", function(dt)
time = time + dt
if time>1 then
time = time - 1
bark = bark + 1
print('Bark!', bark)
end
end)
Systems.AddUpdate("move up", function(dt)
local ents = Registry.Entities({Types.Pos2, Types.MoveUp})
for _, entity in pairs(ents) do
local vec = Registry.GetPosition2vec(entity)
if vec ~= null then
local speed = 250
vec.y = vec.y + dt * speed
end
end
end)
Systems.AddUpdate("time out", function(dt)
local ents = Registry.Entities({Types.TimeOut});
for _, entity in pairs(ents) do
local data = Registry.Get(entity, Types.TimeOut)
data.time = data.time - dt
if data.time < 0 then
print("Timeout")
Registry.DestroyEntity(entity)
end
end
end)
Systems.AddUpdate("destroy outside", function (dt)
local ents = Registry.Entities({Types.Sprite, Types.Pos2, Types.DestroyOutside})
for _, entity in pairs(ents) do
local sp = Registry.GetSprite(entity)
local p = Registry.GetPosition2(entity)
if sp ~= null then
local cam = Camera.GetRect()
local r = sp.GetRect(p)
if not cam:Contains(r) then
Registry.DestroyEntity(entity)
end
end
end
end)
shotTemplate = Templates.Find("shot")
Systems.AddUpdate("player", function(dt)
ents = Registry.Entities({Types.Pos2, Types.Player})
for _, entity in pairs(ents) do
local vec = Registry.GetPosition2vec(entity)
if vec ~= null then
local speed = 150
local vertical = Input.up.state - Input.down.state
local horizontal = Input.right.state - Input.left.state
if JustPressed(Input.fire) then
if not shotTemplate then
print("no shot")
else
local shot = shotTemplate:Create()
local v = Registry.GetPosition2vec(shot)
if v ~= null then
v.x = vec.x
v.y = vec.y
end
end
end
vec.y = vec.y + dt * speed * vertical
vec.x = vec.x + dt * speed * horizontal
end
end
end)
|
fixed a few js/lua issues: forEach 'loop', and a few . instead of : member function calls
|
fixed a few js/lua issues: forEach 'loop', and a few . instead of : member function calls
|
Lua
|
mit
|
madeso/euphoria,madeso/euphoria,madeso/euphoria,madeso/euphoria,madeso/euphoria,madeso/euphoria
|
70a5d17410f5800197dfe1c6e5bc78f06e7c2213
|
shared/entity.lua
|
shared/entity.lua
|
local anim8 = require "libs.anim8"
-- local blocking = require "shared.blocking"
local Class = require "shared.middleclass"
local GameMath = require "shared.gamemath"
local Entity = Class "Entity"
function Entity:initialize(entityStatics, player)
for key, value in pairs(entityStatics) do
self[key] = value
end
self.health = self.health or 0
self.maxHealth = self.health
self.position = GameMath.Vector2:new(0, 0)
self.orientation = 0
self.id = 0
self.animation = false
self.radius = 10
self:setPlayer(player)
-- blocking.addDynamicBlock(self.position.x, self.position.y)
end
function Entity:setPlayer(player)
self.playerId = player and player.playerId
end
function Entity:pauseAnimation()
if self.animation then
self.animation:pause()
else
self:pause()
end
end
function Entity:setAnimation(imagePath, delay, loop, scale)
local image = love.graphics.newImage(imagePath)
local imageWidth, imageHeight = image:getDimensions()
local frameWidth, frameHeight = imageHeight, imageHeight
local grid = anim8.newGrid(frameWidth, frameHeight, imageWidth, imageHeight)
local frames = imageWidth / frameWidth
self.scale = scale or 1
self.spriteSize = imageHeight
self.image = image
self.animation = anim8.newAnimation(grid('1-' .. frames,1), delay, loop and self.pauseAnimation)
end
function Entity:setRandomStartAnimationTime()
self.animation.timer = math.random() * self.animation.durations[1]
end
function Entity:update(dt)
if self.animation then
self.animation:update(dt)
end
end
function Entity:draw(dt)
local x, y = self.position.x, self.position.y
if self.animation then
self.animation:draw(self.image, x, y, self.orientation, self.scale, self.scale, self.spriteSize/2, self.spriteSize/2)
else
love.graphics.circle("fill", x, y, self.radius, self.radius)
end
end
function Entity:delete()
-- blocking.removeDynamicBlock(self.position.x, self.position.y)
end
function Entity:setPosition(x, y)
-- local oldX = self.position.x
-- local oldY = self.position.y
self.position.x = x
self.position.y = y
-- blocking.updateDynamicBlock(oldX, oldY, x, y)
end
function Entity:addHealth(amount)
self.health = self.health + amount
end
function Entity:takeDamage(dmg)
self.health = self.health - dmg
end
return Entity
|
local anim8 = require "libs.anim8"
-- local blocking = require "shared.blocking"
local Class = require "shared.middleclass"
local GameMath = require "shared.gamemath"
local Entity = Class "Entity"
function Entity:initialize(entityStatics, player)
for key, value in pairs(entityStatics) do
self[key] = value
end
self.health = self.health or 0
self.maxHealth = self.health
self.position = GameMath.Vector2:new(0, 0)
self.orientation = 0
self.id = 0
self.animation = false
self.radius = 10
self:setPlayer(player)
-- blocking.addDynamicBlock(self.position.x, self.position.y)
end
function Entity:setPlayer(player)
self.playerId = player and player.playerId
end
function Entity:setAnimation(imagePath, delay, scale, playOnce)
local image = love.graphics.newImage(imagePath)
local imageWidth, imageHeight = image:getDimensions()
local frameWidth, frameHeight = imageHeight, imageHeight
local grid = anim8.newGrid(frameWidth, frameHeight, imageWidth, imageHeight)
local frames = imageWidth / frameWidth
self.scale = scale or 1
self.spriteSize = imageHeight
self.image = image
self.animation = anim8.newAnimation(grid('1-' .. frames,1), delay, playOnce and "pauseAtEnd")
end
function Entity:setRandomStartAnimationTime()
self.animation.timer = math.random() * self.animation.durations[1]
end
function Entity:update(dt)
if self.animation then
self.animation:update(dt)
end
end
function Entity:draw(dt)
local x, y = self.position.x, self.position.y
if self.animation then
self.animation:draw(self.image, x, y, self.orientation, self.scale, self.scale, self.spriteSize/2, self.spriteSize/2)
else
love.graphics.circle("fill", x, y, self.radius, self.radius)
end
end
function Entity:delete()
-- blocking.removeDynamicBlock(self.position.x, self.position.y)
end
function Entity:setPosition(x, y)
-- local oldX = self.position.x
-- local oldY = self.position.y
self.position.x = x
self.position.y = y
-- blocking.updateDynamicBlock(oldX, oldY, x, y)
end
function Entity:addHealth(amount)
self.health = self.health + amount
end
function Entity:takeDamage(dmg)
self.health = self.health - dmg
end
return Entity
|
fixed play animation once
|
fixed play animation once
|
Lua
|
mit
|
ExcelF/project-navel
|
95f9a1edec8d842f3a944b8965bfe464fc871b98
|
src/models/upload.lua
|
src/models/upload.lua
|
--- A basic lower upload API
--
module(..., package.seeall)
require 'posix'
local http = require 'lglib.http'
local Model = require 'bamboo.model'
local Form = require 'bamboo.form'
local function calcNewFilename(dir, oldname)
-- separate the base name and extense name of a filename
local main, ext = oldname:match('^(.+)(%.%w+)$')
if not ext then
main = oldname
ext = ''
end
-- check if exists the same name file
local tstr = ''
local i = 0
while posix.stat( dir + main + tstr + ext ) do
i = i + 1
tstr = '_' + tostring(i)
end
-- concat to new filename
local newbasename = main + tstr
return newbasename, ext
end
--- here, we temprorily only consider the file data is passed wholly by zeromq
-- and save by bamboo
-- @field t.req
-- @field t.file_obj
-- @field t.dest_dir
-- @field t.prefix
-- @field t.postfix
--
local function savefile(t)
local req, file_obj = t.req, t.file_obj
local dest_dir = t.dest_dir and ('media/uploads/' + t.dest_dir + '/') or 'media/uploads/'
dest_dir = string.trailingPath(dest_dir)
local prefix = t.prefix or ''
local postfix = t.postfix or ''
local filename = ''
local body = ''
local rename_func = t.rename_func or nil
-- if upload in html5 way
if req.headers['x-requested-with'] then
-- when html5 upload, we think of the name of that file was stored in header x-file-name
-- if this info missing, we may consider the filename was put in the query string
filename = req.headers['x-file-name'] or Form:parseQuery(req)['filename']
-- TODO:
-- req.body contains all file binary data
body = req.body
else
checkType(file_obj, 'table')
-- Notice: the filename in the form string are quoted by ""
-- this pattern rule can deal with the windows style directory delimiter
-- file_obj['content-disposition'] contains many file associated info
filename = file_obj['content-disposition'].filename:sub(2, -2):match('\\?([^\\]-%.%w+)$')
body = file_obj.body
end
if isFalse(filename) or isFalse(body) then return nil, nil end
if not req.ajax then
filename = http.encodeURL(filename)
end
if not posix.stat(dest_dir) then
-- why posix have no command like " mkdir -p "
os.execute('mkdir -p ' + dest_dir)
end
-- if passed in a rename function, use it to replace the orignial filename
if rename_func and type(rename_func) == 'function' then
filename = rename_func(filename)
end
local newbasename, ext = calcNewFilename(dest_dir, filename)
local newname = prefix + newbasename + postfix + ext
local path = dest_dir + newname
-- write file to disk
local fd = io.open(path, "wb")
fd:write(body)
fd:close()
return newname, path
end
local Upload = Model:extend {
__tag = 'Bamboo.Model.Upload';
__name = 'Upload';
__desc = "User's upload files.";
__indexfd = "path";
__fields = {
['name'] = {},
['path'] = {unique=true},
['size'] = {},
['timestamp'] = {},
['desc'] = {},
};
__decorators = {
del = function (odel)
return function (self, ...)
I_AM_INSTANCE_OR_QUERY_SET(self)
-- if self is query set
if I_AM_QUERY_SET(self) then
for _, v in ipairs(self) do
-- remove file from disk
os.execute('rm ' + v.path)
end
else
-- remove file from disk
os.execute('rm ' + self.path)
end
return odel(self, ...)
end
end
};
init = function (self, t)
if not t then return self end
self.name = t.name
self.path = t.path or 'media/uploads/default'
self.size = posix.stat(self.path).size
self.timestamp = os.time()
-- according the current design, desc field is nil
self.desc = t.desc or ''
return self
end;
--- For traditional Html4 form upload
--
batch = function (self, req, params, dest_dir, prefix, postfix, rename_func)
I_AM_CLASS(self)
local file_objs = List()
-- file data are stored as arraies in params
for i, v in ipairs(params) do
local name, path = savefile { req = req, file_obj = v, dest_dir = dest_dir, prefix = prefix, postfix = postfix, rename_func }
if not path or not name then return nil end
-- create file instance
local file_instance = self { name = name, path = path }
if file_instance then
-- store to db
-- file_instance:save()
file_objs:append(file_instance)
end
end
-- a file object list
return file_objs
end;
process = function (self, web, req, dest_dir, prefix, postfix, rename_func)
I_AM_CLASS(self)
assert(web, '[Error] Upload input parameter: "web" must be not nil.')
assert(req, '[Error] Upload input parameter: "req" must be not nil.')
-- current scheme: for those larger than PRESIZE, send a ABORT signal, and abort immediately
if req.headers['x-mongrel2-upload-start'] then
print('return blank to abort upload.')
web.conn:reply(req, '')
return nil, 'Uploading file is too large.'
end
-- if upload in html5 way
if req.headers['x-requested-with'] then
-- stored to disk
local name, path = savefile { req = req, dest_dir = dest_dir, prefix = prefix, postfix = postfix, rename_func = rename_func }
if not path or not name then return nil, '[Error] empty file.' end
local file_instance = self { name = name, path = path }
if file_instance then
-- file_instance:save()
return file_instance, 'single'
end
else
-- for uploading in html4 way
local params = Form:parse(req)
local files = self:batch ( req, params, dest_dir, prefix, postfix, rename_func )
if files:isEmpty() then return nil, '[Error] empty file.' end
if #files == 1 then
-- even only one file upload, batch function will return a list
return files[1], 'single'
else
return files, 'multiple'
end
end
end;
calcNewFilename = function (self, dest_dir, oldname)
return calcNewFilename(dest_dir, oldname)
end;
-- this function, encorage override by child model, to execute their own delete action
-- specDelete = function (self)
-- I_AM_INSTANCE(self)
-- -- remove file from disk
-- os.execute('rm ' + self.path)
-- return self
-- end;
}
return Upload
|
--- A basic lower upload API
--
module(..., package.seeall)
require 'posix'
local http = require 'lglib.http'
local Model = require 'bamboo.model'
local Form = require 'bamboo.form'
local function calcNewFilename(dir, oldname)
-- separate the base name and extense name of a filename
local main, ext = oldname:match('^(.+)(%.%w+)$')
if not ext then
main = oldname
ext = ''
end
-- check if exists the same name file
local tstr = ''
local i = 0
while posix.stat( dir + main + tstr + ext ) do
i = i + 1
tstr = '_' + tostring(i)
end
-- concat to new filename
local newbasename = main + tstr
return newbasename, ext
end
--- here, we temprorily only consider the file data is passed wholly by zeromq
-- and save by bamboo
-- @field t.req
-- @field t.file_obj
-- @field t.dest_dir
-- @field t.prefix
-- @field t.postfix
--
local function savefile(t)
local req, file_obj = t.req, t.file_obj
local dest_dir = t.dest_dir and ('media/uploads/' + t.dest_dir + '/') or 'media/uploads/'
dest_dir = string.trailingPath(dest_dir)
local prefix = t.prefix or ''
local postfix = t.postfix or ''
local filename = ''
local body = ''
local rename_func = t.rename_func or nil
-- if upload in html5 way
if req.headers['x-requested-with'] then
-- when html5 upload, we think of the name of that file was stored in header x-file-name
-- if this info missing, we may consider the filename was put in the query string
filename = req.headers['x-file-name'] or Form:parseQuery(req)['filename']
-- TODO:
-- req.body contains all file binary data
body = req.body
else
checkType(file_obj, 'table')
-- Notice: the filename in the form string are quoted by ""
-- this pattern rule can deal with the windows style directory delimiter
-- file_obj['content-disposition'] contains many file associated info
filename = file_obj['content-disposition'].filename:sub(2, -2):match('\\?([^\\]-%.%w+)$')
body = file_obj.body
end
if isFalse(filename) or isFalse(body) then return nil, nil end
if not req.ajax then
filename = http.encodeURL(filename)
end
if not posix.stat(dest_dir) then
-- why posix have no command like " mkdir -p "
os.execute('mkdir -p ' + dest_dir)
end
-- if passed in a rename function, use it to replace the orignial filename
if rename_func and type(rename_func) == 'function' then
filename = rename_func(filename)
end
local newbasename, ext = calcNewFilename(dest_dir, filename)
local newname = prefix + newbasename + postfix + ext
local path = dest_dir + newname
-- write file to disk
local fd = io.open(path, "wb")
fd:write(body)
fd:close()
return newname, path
end
local Upload = Model:extend {
__tag = 'Bamboo.Model.Upload';
__name = 'Upload';
__desc = "User's upload files.";
__indexfd = "path";
__fields = {
['name'] = {},
['path'] = {unique=true},
['size'] = {},
['timestamp'] = {},
['desc'] = {},
};
__decorators = {
del = function (odel)
return function (self, ...)
I_AM_INSTANCE_OR_QUERY_SET(self)
-- if self is query set
if I_AM_QUERY_SET(self) then
for _, v in ipairs(self) do
-- remove file from disk
os.execute('rm ' + v.path)
end
else
-- remove file from disk
os.execute('rm ' + self.path)
end
return odel(self, ...)
end
end
};
init = function (self, t)
if not t then return self end
self.name = t.name
self.path = t.path or 'media/uploads/default'
self.size = posix.stat(self.path).size
self.timestamp = os.time()
-- according the current design, desc field is nil
self.desc = t.desc or ''
return self
end;
--- For traditional Html4 form upload
--
batch = function (self, req, params, dest_dir, prefix, postfix, rename_func)
I_AM_CLASS(self)
local file_objs = List()
-- file data are stored as arraies in params
for i, v in ipairs(params) do
local name, path = savefile { req = req, file_obj = v, dest_dir = dest_dir, prefix = prefix, postfix = postfix, rename_func }
if not path or not name then return nil end
-- create file instance
local file_instance = self { name = name, path = path }
if file_instance then
-- store to db
-- file_instance:save()
-- fix the id sequence
file_instance.id = file_instance.id + i - 1
file_objs:append(file_instance)
end
end
-- a file object list
return file_objs
end;
process = function (self, web, req, dest_dir, prefix, postfix, rename_func)
I_AM_CLASS(self)
assert(web, '[Error] Upload input parameter: "web" must be not nil.')
assert(req, '[Error] Upload input parameter: "req" must be not nil.')
-- current scheme: for those larger than PRESIZE, send a ABORT signal, and abort immediately
if req.headers['x-mongrel2-upload-start'] then
print('return blank to abort upload.')
web.conn:reply(req, '')
return nil, 'Uploading file is too large.'
end
-- if upload in html5 way
if req.headers['x-requested-with'] then
-- stored to disk
local name, path = savefile { req = req, dest_dir = dest_dir, prefix = prefix, postfix = postfix, rename_func = rename_func }
if not path or not name then return nil, '[Error] empty file.' end
local file_instance = self { name = name, path = path }
if file_instance then
-- file_instance:save()
return file_instance, 'single'
end
else
-- for uploading in html4 way
local params = Form:parse(req)
local files = self:batch ( req, params, dest_dir, prefix, postfix, rename_func )
if files:isEmpty() then return nil, '[Error] empty file.' end
if #files == 1 then
-- even only one file upload, batch function will return a list
return files[1], 'single'
else
return files, 'multiple'
end
end
end;
calcNewFilename = function (self, dest_dir, oldname)
return calcNewFilename(dest_dir, oldname)
end;
-- this function, encorage override by child model, to execute their own delete action
-- specDelete = function (self)
-- I_AM_INSTANCE(self)
-- -- remove file from disk
-- os.execute('rm ' + self.path)
-- return self
-- end;
}
return Upload
|
fix a multiple upload bug. But user also need to use for repeat statement to save the file_objs manually.
|
fix a multiple upload bug. But user also need to use for repeat statement to save the file_objs manually.
Signed-off-by: Daogang Tang <6435653d2db08e7863743a16df53ecbb301fb4b0@gmail.com>
|
Lua
|
bsd-3-clause
|
daogangtang/bamboo,daogangtang/bamboo
|
dcce0443a4b2c10a64c15ec531cd9692f61afaaa
|
build/Editor.lua
|
build/Editor.lua
|
Editor = {}
Editor.defines = {}
function SetupWxWidgets()
wxWidgets = {}
wxWidgets.includedirs =
{
"../deps/wxWidgets/include",
"../deps/wxWidgets/include/msvc"
}
wxWidgets.libdirs =
{
"../deps/wxWidgets/lib/vc_dll",
}
wxWidgets.links = { }
wxWidgets.defines = { '_LIB', 'WXUSINGDLL', 'WXMONOLITHIC' }
defines { wxWidgets.defines }
local c = configuration "windows"
defines { "__WXMSW__" }
configuration { "windows", "Debug" }
links { "wxmsw29ud","wxmsw29ud_gl" }
configuration { "windows", "Release" }
links { "wxmsw29u","wxmsw29u_gl" }
configuration (c)
end
project "Editor"
debugdir "../bin"
builddeps { Core.name, Resources.name, Graphics.name, Engine.name, Pipeline.name }
defines
{
Core.defines,
Resources.defines,
Graphics.defines,
Engine.defines,
Pipeline.defines
}
editor_flags = common_flags
table.remove(editor_flags, #editor_flags)
flags { editor_flags }
pchheader "Editor/API.h"
pchsource "../src/Editor/Editor.cpp"
configuration "Debug"
kind "ConsoleApp"
configuration "Release"
kind "WindowedApp"
flags { "WinMain" }
configuration "*"
files
{
"Editor.lua",
"../inc/Editor/**.h",
"../src/Editor/**.h",
"../src/Editor/**.cpp",
"../src/Editor/**.rc",
}
vpaths
{
["*"] = { "../src/Editor/", "../inc/Editor/" },
}
Editor.deps =
{
"Mono"
}
SetupWxWidgets()
includedirs
{
"../inc/",
"../src/",
"../inc/Editor",
"../src/Editor",
"../src/Editor/Widgets",
wxWidgets.includedirs
}
libdirs
{
"lib/",
Core.libdirs,
Resources.libdirs,
Engine.libdirs,
Pipeline.libdirs,
wxWidgets.libdirs,
}
links
{
Engine.name,
Engine.links,
Pipeline.name,
Pipeline.links,
wxWidgets.links
}
deps { Editor.deps }
configuration "vs*"
defines { "_CRT_SECURE_NO_WARNINGS" }
configuration "windows"
links { Mono.links }
|
Editor = {}
Editor.defines = {}
function SetupWxWidgets()
wxWidgets = {}
wxWidgets.includedirs =
{
"../deps/wxWidgets/include",
"../deps/wxWidgets/include/msvc"
}
wxWidgets.libdirs =
{
"../deps/wxWidgets/lib/vc_dll",
}
wxWidgets.links = { }
wxWidgets.defines = { '_LIB', 'WXUSINGDLL', 'WXMONOLITHIC' }
defines { wxWidgets.defines }
local c = configuration "windows"
defines { "__WXMSW__" }
configuration { "windows", "Debug" }
links { "wxmsw29ud","wxmsw29ud_gl" }
configuration { "windows", "Release" }
links { "wxmsw29u","wxmsw29u_gl" }
configuration (c)
end
project "Editor"
debugdir "../bin"
builddeps { Core.name, Resources.name, Graphics.name, Engine.name, Pipeline.name }
defines
{
Core.defines,
Resources.defines,
Graphics.defines,
Engine.defines,
Pipeline.defines
}
editor_flags = common_flags
table.remove(editor_flags, #editor_flags)
flags { editor_flags }
pchheader "Editor/API.h"
pchsource "../src/Editor/Editor.cpp"
configuration "Debug"
kind "ConsoleApp"
configuration "Release"
kind "WindowedApp"
flags { "WinMain" }
configuration "*"
files
{
"Editor.lua",
"../inc/Editor/**.h",
"../src/Editor/**.h",
"../src/Editor/**.cpp",
"../src/Editor/**.rc",
}
vpaths
{
["*"] = { "../src/Editor/", "../inc/Editor/" },
}
Editor.deps = {}
if config.SCRIPTING_MONO then
table.insert(Editor.deps,"Mono")
end
SetupWxWidgets()
includedirs
{
"../inc/",
"../src/",
"../inc/Editor",
"../src/Editor",
"../src/Editor/Widgets",
wxWidgets.includedirs
}
libdirs
{
"lib/",
Core.libdirs,
Resources.libdirs,
Engine.libdirs,
Pipeline.libdirs,
wxWidgets.libdirs,
}
links
{
Engine.name,
Engine.links,
Pipeline.name,
Pipeline.links,
wxWidgets.links
}
deps { Editor.deps }
configuration "vs*"
defines { "_CRT_SECURE_NO_WARNINGS" }
if config.SCRIPTING_MONO then
configuration "windows"
links { Mono.links }
end
|
Fixed Editor project conditional mono dependency
|
Fixed Editor project conditional mono dependency
|
Lua
|
bsd-2-clause
|
FloodProject/flood,FloodProject/flood,FloodProject/flood
|
4a8b82eb8f93c496d8a7172dc6aa74e84ae14691
|
l2l/list.lua
|
l2l/list.lua
|
-- A very fast Lua linked list implementation that can only add a number of
-- items equal to the maximum integer that can be held in a lua number,
-- i.e. 9007199254740992.
-- If the program creates 100000000 list cells per second, the program will
-- fail after 2.85 years.
-- The reference counting O(n) for length of remaining list when doing cdr or
-- cons.
local utils = require("leftry").utils
local vector = require("l2l.vector")
local lua = require("l2l.lua")
local ipairs = require("l2l.iterator")
local len = require("l2l.len")
local data = setmetatable({n=0, free=0}, {})
local retains = {}
local index_base = 1
local function retain(n)
retains[n] = (retains[n] or 0) + 1
local rest = data[n+1]
if rest then
return retain(rest)
end
end
local function release(n)
retains[n] = retains[n] - 1
if retains[n] == 0 then
retains[n] = nil
data[n] = nil
data[n+1] = nil
data.free = data.free + 1
end
if data.free == data.n then
-- Take the opportunity to reset `data`.
data = setmetatable({n=0, free=0}, {})
end
local rest = data[n+1]
if rest then
return release(rest)
end
end
local list = utils.prototype("list", function(list, ...)
if select("#", ...) == 0 then
return vector()
end
local count = select("#", ...)
local self = setmetatable({position = data.n + 1, contiguous = count}, list)
local index = self.position
for i=1, count do
local datum = (select(i, ...))
data.n = data.n + 1
data[data.n] = datum
data.n = data.n + 1
if i < count then
data[data.n] = index + i * 2
end
end
retain(self.position)
return self
end)
function list:__gc()
release(self.position)
end
function list:__index(key)
if type(key) ~= "number" then
return rawget(list, key)
end
if self.contiguous then
assert(key <= self.contiguous)
return data[self.position + 2 * (key - index_base)]
end
local position = self.position
while position and key > index_base do
position = data[position + 1]
key = key - 1
end
if position then
return data[position]
end
end
function list:__newindex(key, value)
if type(key) ~= "number" then
return rawset(self, key, value)
end
if self.contiguous then
assert(key <= self.contiguous)
data[self.position + 2 * (key - index_base)] = value
return
end
local position = self.position
while position and key > index_base do
position = data[position + 1]
key = key - 1
end
if position then
data[position] = value
end
error("cannot assign value to key where key extends length of list")
end
function list:repr()
local parameters = {}
local cdr = self
local i = 0
while cdr do
i = i + 1
local car = cdr:car()
if type(car) == "string" then
car = utils.escape(car)
end
parameters[i] = car
cdr = cdr:cdr()
end
return lua.lua_functioncall.new(lua.lua_name("list"),
lua.lua_args.new(
lua.lua_explist(parameters)))
end
function list:__tostring()
local text = {}
local cdr = self
local i = 0
while cdr do
i = i + 1
local car = cdr:car()
if type(car) == "string" then
car = utils.escape(car)
end
text[i] = tostring(car)
cdr = cdr:cdr()
end
return "list("..table.concat(text, ", ")..")"
end
function list:__ipairs()
local position = self.position
local i = 0
return function()
if not position then
return
end
i = i + 1
local car = data[position]
position = data[position + 1]
return i, car
end, self, 0
end
function list:__len()
if not self then
return 0
end
if self.contiguous then
return self.contiguous
end
local position = data[self.position + 1]
local count = 1
while position do
count = count + 1
position = data[position + 1]
end
return count
end
function list:car()
return data[self.position]
end
function list:cdr()
local position = data[self.position + 1]
if position then
retain(position)
local contiguous = self.contiguous
if contiguous then
contiguous = contiguous - 1
end
return setmetatable({position = position, contiguous = contiguous}, list)
end
end
function list:__eq(l)
if rawequal(self, l) then
return true
end
return getmetatable(self) == getmetatable(l) and
self:car() == l:car() and self:cdr() == l:cdr()
end
function list:unpack()
if not self then
return
end
local car, cdr = self:car(), self:cdr()
if cdr then
return car, cdr:unpack()
end
return car
end
-- WARNING, this uses 1-based
function list.sub(t, from, to)
to = to or len(t)
from = from or 1
return list.cast(t, function(i)
return i >= from and i <= to
end)
end
function list.cast(t, f)
-- Cast an ipairs-enumerable object into a list.
local count = len(t)
if not t or count == 0 then
return nil
end
local self = setmetatable({position = data.n + 1, contiguous = count}, list)
local n = data.n
data.n = data.n + count * 2
for i, v in ipairs(t) do
n = n + 1
if f then
data[n] = f(v, i)
else
data[n] = v
end
n = n + 1
if i < count then
data[n] = n + 1
end
end
retain(self.position)
return self
end
function list:cons(car)
-- Prepend car to the list and return a new head.
data.n = data.n + 1
local position = data.n
data[data.n] = car
data.n = data.n + 1
if self then
data[data.n] = self.position
end
retain(position)
return setmetatable({position = position, contiguous = false}, list)
end
function list:prepend(t)
local position = data.n + 1
local count = len(t)
for i, datum in ipairs(t) do
data.n = data.n + 1
data[data.n] = datum
data.n = data.n + 1
if i < count then
data[data.n] = position + i * 2
else
data[data.n] = self.position
end
end
retain(position)
return setmetatable({position = position}, list)
end
return list
|
local utils = require("leftry").utils
local vector = require("l2l.vector")
local lua = require("l2l.lua")
local ipairs = require("l2l.iterator")
local len = require("l2l.len")
local index_base = 0
local list = utils.prototype("list", function(list, ...)
if select("#", ...) == 0 then
return vector()
end
local count = select("#", ...)
local self = {}
for i=1, count do
local datum = (select(i, ...))
self[i + index_base - 1] = datum
end
self.n = count
return setmetatable(self, list)
end)
function list:repr()
local parameters = {}
for i,v in ipairs(self) do
if type(v) == "string" then
v = utils.escape(v)
end
parameters[i] = v
end
return lua.lua_functioncall.new(lua.lua_name("list"),
lua.lua_args.new(
lua.lua_explist(parameters)))
end
function list:__tostring()
local text = {}
for i,v in ipairs(self) do
if type(v) == "string" then
v = utils.escape(v)
end
text[i] = tostring(v)
end
return "list("..table.concat(text, ", ")..")"
end
-- we can store nil, so we need our own ipairs
-- also ipairs i is always 1-based
function list:__ipairs()
local s = self
local i = -1
return function()
i = i + 1
if i >= s.n then
return
end
return i + 1, s[i + index_base]
end, self, 0
end
function list:__len()
if not self then
return 0
end
return self.n
end
function list:car()
return self[index_base]
end
function list:cdr()
if self.n < 2 then
return nil
end
local r = {}
for i=1, self.n - 1 do
r[i + index_base - 1] = self[i + index_base]
end
r.n = self.n - 1
return setmetatable(r, list)
end
function list:__eq(l)
if rawequal(self, l) then
return true
end
if getmetatable(self) ~= getmetatable(l) then
return false
end
if self.n ~= l.n then
return false
end
for i=index_base,self.n - 1 + index_base do
if self[i] ~= l[i] then
return false
end
end
return true
end
function list:unpack_i(i)
if i == self.n - 1 + index_base then
return self[i]
end
return self[i], self:unpack_i(i + 1)
end
function list:unpack()
if not self then
return
end
return self:unpack_i(index_base)
end
-- WARNING, this uses 1-based
function list.sub(t, from, to)
-- to = to or len(t)
-- from = from or 1
-- local j = index_base
-- local r = {}
-- for i=from - 1 + index_base, to - 1 + index_base do
-- r[j] = t[i]
-- j = j + 1
-- end
-- r.n = j - 1
-- return setmetatable(r, list)
to = to or len(t)
from = from or 1
return list.cast(t, function(i)
return i >= from and i <= to
end)
end
function list.cast(t, f)
-- Cast an ipairs-enumerable object into a list.
local count = len(t)
if not t or count == 0 then
return nil
end
local self = setmetatable({n = count}, list)
for i, v in ipairs(t) do
if f then
self[i - 1 + index_base] = f(v, i)
else
self[i - 1 + index_base] = v
end
end
return self
end
function list:cons(car)
local r = {}
for i=self.n - 1 + index_base, index_base, -1 do
r[i+1] = self[i]
end
r[index_base] = car
r.n = self.n + 1
return setmetatable(r, list)
end
-- function list:prepend(t)
-- local position = data.n + 1
-- local count = len(t)
-- for i, datum in ipairs(t) do
-- data.n = data.n + 1
-- data[data.n] = datum
-- data.n = data.n + 1
-- if i < count then
-- data[data.n] = position + i * 2
-- else
-- data[data.n] = self.position
-- end
-- end
-- retain(position)
-- return setmetatable({position = position}, list)
-- end
return list
|
lobotomize list.lua into a vector-like structure, fixing the lack of table __gc in luajit
|
lobotomize list.lua into a vector-like structure, fixing the lack of table __gc in luajit
|
Lua
|
bsd-2-clause
|
meric/l2l
|
f418b7c41101a3a0061efe4ae2176ee335e7ab1b
|
messages/client/messages.lua
|
messages/client/messages.lua
|
local messages = { global = { }, local = { } }
local screenWidth, screenHeight = guiGetScreenSize( )
local messageWidth, messageHeight = 316, 152
function createMessage( message, messageType, messageGlobalID, hideButton, disableInput )
destroyMessage( nil, messageType )
local messageID = messageGlobalID or exports.common:nextIndex( messages )
local messageRealm = messageGlobalID and "global" or "local"
local messageHolder
messages[ messageRealm ][ messageID ] = { messageType = messageType or "other", disableInput = disableInput }
messageHolder = messages[ messageRealm ][ messageID ]
local messageHeight = messageHeight - ( hideButton and 25 or 0 )
messageHolder.window = guiCreateWindow( ( screenWidth - messageWidth ) / 2, ( screenHeight - messageHeight ) / 2, messageWidth, messageHeight, "Message", false )
guiWindowSetSizable( messageHolder.window, false )
guiSetProperty( messageHolder.window, "AlwaysOnTop", "True" )
guiSetAlpha( messageHolder.window, 0.925 )
setElementData( messageHolder.window, "messages:id", messageID, false )
setElementData( messageHolder.window, "messages:type", messageHolder.messageType, false )
setElementData( messageHolder.window, "messages:realm", messageRealm, false )
setElementData( messageHolder.window, "messages:disableInput", disableInput, false )
messageHolder.message = guiCreateLabel( 17, 35, 283, 60, message, false, messageHolder.window )
guiLabelSetHorizontalAlign( messageHolder.message, "center", true )
guiLabelSetVerticalAlign( messageHolder.message, "center" )
if ( disableInput ) then
guiSetInputEnabled( true )
end
if ( not hideButton ) then
messageHolder.button = guiCreateButton( 16, 109, 284, 25, "Continue", false, messageHolder.window )
addEventHandler( "onClientGUIClick", messageHolder.button,
function( )
local parent = getElementParent( source )
local id = tonumber( getElementData( parent, "messages:id" ) )
local realm = getElementData( parent, "messages:realm" )
local disableInput = getElementData( parent, "messages:disableInput" )
destroyElement( getElementParent( source ) )
if ( messages[ realm ][ id ] ) then
messages[ realm ][ id ] = nil
end
showCursor( false )
if ( disableInput ) then
guiSetInputEnabled( false )
end
triggerEvent( "accounts:enableGUI", localPlayer )
end, false
)
end
end
addEvent( "messages:create", true )
addEventHandler( "messages:create", root, createMessage )
function destroyMessage( messageType, messageGlobalID )
if ( messageType ) then
local message = exports.common:findByValue( messages, messageType, true )
for index, message in ipairs( message ) do
if ( isElement( message.window ) ) then
destroyElement( message.window )
end
message[ index ] = nil
end
else
local message = messages.global[ messageGlobalID ]
if ( message ) then
if ( isElement( message.window ) ) then
destroyElement( message.window )
end
messages.global[ messageGlobalID ] = nil
end
end
end
addEvent( "messages:destroy", true )
addEventHandler( "messages:destroy", root, destroyMessage )
addEventHandler( "onClientResourceStop", root,
function( resource )
if ( not getElementData( localPlayer, "account:id" ) ) then
triggerEvent( "accounts:enableGUI", localPlayer )
end
if ( getResourceName( resource ) == "accounts" ) then
destroyMessage( "login" )
end
end
)
addEventHandler( "onClientResourceStart", root,
function( )
triggerServerEvent( "messages:ready", localPlayer )
end
)
|
local messages = { global = { }, client = { } }
local screenWidth, screenHeight = guiGetScreenSize( )
local messageWidth, messageHeight = 316, 152
function createMessage( message, messageType, messageGlobalID, hideButton, disableInput )
destroyMessage( messageType )
destroyMessage( nil, nil, messageGlobalID )
local messageID = messageGlobalID or exports.common:nextIndex( messages )
local messageRealm = messageGlobalID and "global" or "client"
local messageHolder
messages[ messageRealm ][ messageID ] = { messageType = messageType or "other", disableInput = disableInput }
messageHolder = messages[ messageRealm ][ messageID ]
local messageHeight = messageHeight - ( hideButton and 25 or 0 )
messageHolder.window = guiCreateWindow( ( screenWidth - messageWidth ) / 2, ( screenHeight - messageHeight ) / 2, messageWidth, messageHeight, "Message", false )
guiWindowSetSizable( messageHolder.window, false )
guiSetProperty( messageHolder.window, "AlwaysOnTop", "True" )
guiSetAlpha( messageHolder.window, 0.925 )
setElementData( messageHolder.window, "messages:id", messageID, false )
setElementData( messageHolder.window, "messages:type", messageHolder.messageType, false )
setElementData( messageHolder.window, "messages:realm", messageRealm, false )
setElementData( messageHolder.window, "messages:disableInput", disableInput, false )
messageHolder.message = guiCreateLabel( 17, 35, 283, 60, message, false, messageHolder.window )
guiLabelSetHorizontalAlign( messageHolder.message, "center", true )
guiLabelSetVerticalAlign( messageHolder.message, "center" )
if ( disableInput ) then
guiSetInputEnabled( true )
end
if ( not hideButton ) then
messageHolder.button = guiCreateButton( 16, 109, 284, 25, "Continue", false, messageHolder.window )
addEventHandler( "onClientGUIClick", messageHolder.button,
function( )
local parent = getElementParent( source )
local id = tonumber( getElementData( parent, "messages:id" ) )
local realm = getElementData( parent, "messages:realm" )
local disableInput = getElementData( parent, "messages:disableInput" )
destroyElement( getElementParent( source ) )
if ( messages[ realm ][ id ] ) then
messages[ realm ][ id ] = nil
end
showCursor( false )
if ( disableInput ) then
guiSetInputEnabled( false )
end
triggerEvent( "accounts:enableGUI", localPlayer )
end, false
)
end
end
addEvent( "messages:create", true )
addEventHandler( "messages:create", root, createMessage )
function destroyMessage( messageType, messageGlobalID )
if ( messageType ) then
for _, messageID in ipairs( exports.common:findByValue( messages.client, messageType, true ) ) do
local message = messages.client[ messageID ]
if ( isElement( message.window ) ) then
destroyElement( message.window )
end
message = nil
end
else
if ( messageGlobalID ) then
local message = messages.global[ messageGlobalID ]
if ( message ) then
if ( isElement( message.window ) ) then
destroyElement( message.window )
end
messages.global[ messageGlobalID ] = nil
end
end
end
end
addEvent( "messages:destroy", true )
addEventHandler( "messages:destroy", root, destroyMessage )
addEventHandler( "onClientResourceStop", root,
function( resource )
if ( not getElementData( localPlayer, "account:id" ) ) then
triggerEvent( "accounts:enableGUI", localPlayer )
end
if ( getResourceName( resource ) == "accounts" ) then
destroyMessage( "login" )
end
end
)
addEventHandler( "onClientResourceStart", root,
function( )
triggerServerEvent( "messages:ready", localPlayer )
end
)
|
messages: fixed issues with client side code
|
messages: fixed issues with client side code
|
Lua
|
mit
|
smile-tmb/lua-mta-fairplay-roleplay
|
9c69bf54a85e2a6695fea1def66e4470b706fa1b
|
scripts/gui/dragbutton.lua
|
scripts/gui/dragbutton.lua
|
class 'DragButton' (Panel)
function DragButton:__init( layer, x, y, parentToDrag )
guiLog 'creating DragButton'
if parentToDrag == nil then
error( 'You must give a gui object to drag.' )
end
Panel.__init( self, layer, x, y, 16, 16 )
self.parent = parentToDrag
self:background( 'drag.normal' )
self.state = "normal"
self.oldstate = "normal"
guiLog 'DragButton created'
end
function DragButton:destroy()
guiLog 'Destroying DragButton.'
Panel.destroy(self)
end
function DragButton:keypressed( key )
end
function DragButton:mouseMoved( x, y, button )
if self.rect:intersects( Vector2(x, y) ) then
if button == 0 and self.state == "click" then -- click release
stopMouseDrag()
end
self.state = "hover"
else
self.state = "normal"
stopMouseDrag()
end
if self.state == "hover" and button == 1 then
self.state = "click"
startMouseDrag(self.parent)
end
self:updateVisualState()
end
function DragButton:updateVisualState()
if self.state ~= self.oldstate then
if self.state == "normal" then
self.rect:backgroundImage("drag.normal")
elseif self.state == "hover" then
self.rect:backgroundImage("drag.hover")
else
self.rect:backgroundImage("drag.pressed")
end
self.oldstate = self.state
end
end
function DragButton:move( x, y )
if Panel.move( self, x, y ) then return end
for _,child in pairs( self.children ) do
if child.move then child:move( x, y ) end
end
end
function DragButton:lostMouse()
self.state = "normal"
self:updateVisualState()
for _,child in pairs( self.children ) do
if child.lostMouse then child:lostMouse() end
end
end
|
class 'DragButton' (Panel)
function DragButton:__init( layer, x, y, parentToDrag )
guiLog 'creating DragButton'
if parentToDrag == nil then
error( 'You must give a gui object to drag.' )
end
Panel.__init( self, layer, x, y, 16, 16 )
self.parent = parentToDrag
self:background( 'drag.normal' )
self.state = "normal"
self.oldstate = "normal"
guiLog 'DragButton created'
end
function DragButton:destroy()
guiLog 'Destroying DragButton.'
Panel.destroy(self)
end
function DragButton:keypressed( key )
end
function DragButton:mouseMoved( x, y, button )
if self.rect:intersects( Vector2(x, y) ) then
if button == 0 and self.state == "click" then -- click release
stopMouseDrag()
end
self.state = "hover"
else
self.state = "normal"
stopMouseDrag()
end
if self.state == "hover" and button == 1 then
self.state = "click"
startMouseDrag(self.parent)
end
self:updateVisualState()
end
function DragButton:updateVisualState()
if self.state ~= self.oldstate then
if self.state == "normal" then
self.rect:backgroundImage("drag.normal")
elseif self.state == "hover" then
self.rect:backgroundImage("drag.hover")
else
self.rect:backgroundImage("drag.pressed")
end
self.oldstate = self.state
end
end
function DragButton:move( x, y )
if Panel.move( self, x, y ) then return end
for _,child in pairs( self.children ) do
if child.move then child:move( x, y ) end
end
end
function DragButton:lostMouse()
if self.state == "click" then
stopMouseDrag()
end
self.state = "normal"
self:updateVisualState()
for _,child in pairs( self.children ) do
if child.lostMouse then child:lostMouse() end
end
end
|
Fix to drag button being stuck on.
|
Fix to drag button being stuck on.
|
Lua
|
mit
|
merlinblack/Game-Engine-Testbed,merlinblack/Game-Engine-Testbed,merlinblack/Game-Engine-Testbed,merlinblack/Game-Engine-Testbed
|
3e43d99c32e4367dcd1908551c1a4f50bb2dbccd
|
share/lua/playlist/cue.lua
|
share/lua/playlist/cue.lua
|
--[[
Parse CUE files
$Id$
Copyright (C) 2009 Laurent Aimar
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
--]]
-- Probe function.
function probe()
if( not string.match( string.upper( vlc.path ), ".CUE$" ) ) then
return false
end
header = vlc.peek( 2048 )
return string.match( header, "FILE.*WAVE%s*[\r\n]+" ) or
string.match( header, "FILE.*AIFF%s*[\r\n]+" ) or
string.match( header, "FILE.*MP3%s*[\r\n]+" )
end
-- Helpers
function cue_string( src )
local sub = string.match( src, "^\"(.*)\".*$" );
if( sub ) then
return sub
end
return string.match( src, "^(%S+).*$" )
end
function cue_path( src )
if( string.match( src, "^/" ) or
string.match( src, "^\\" ) or
string.match( src, "^[%l%u]:\\" ) ) then
return vlc.strings.make_uri(src)
end
local slash = string.find( string.reverse( vlc.path ), '/' )
local prefix = vlc.access .. "://" .. string.sub( vlc.path, 1, -slash )
-- FIXME: postfix may not be encoded correctly (esp. slashes)
local postfix = vlc.strings.encode_uri_component(src)
return prefix .. postfix
end
function cue_track( global, track )
if( track.index01 == nil ) then
return nil
end
t = {}
t.path = cue_path( track.file or global.file )
t.title = track.title
t.album = global.title
t.artist = track.performer or global.performer
t.genre = track.genre or global.genre
t.date = track.date or global.date
t.description = global.comment
t.tracknum = track.num
t.options = { ":start-time=" .. math.floor(track.index01) }
return t
end
function cue_append( tracks, global, track )
local t = cue_track( global, track )
if( t ~= nil ) then
if( #tracks > 0 ) then
local prev = tracks[#tracks]
table.insert( prev.options, ":stop-time=" .. math.floor(track.index01) )
end
table.insert( tracks, t )
end
end
-- Parse function.
function parse()
p = {}
global_data = nil
data = {}
file = nil
while true
do
line = vlc.readline()
if not line then break end
cmd, arg = string.match( line, "^%s*(%S+)%s*(.*)$" )
if( cmd == "REM" and arg ) then
subcmd, value = string.match( arg, "^(%S+)%s*(.*)$" )
if( subcmd == "GENRE" and value ) then
data.genre = cue_string( value )
elseif( subcmd == "DATE" and value ) then
data.date = cue_string( value )
elseif( subcmd == "COMMENT" and value ) then
data.comment = cue_string( value )
end
elseif( cmd == "PERFORMER" and arg ) then
data.performer = cue_string( arg )
elseif( cmd == "TITLE" and arg ) then
data.title = cue_string( arg )
elseif( cmd == "FILE" ) then
file = cue_string( arg )
elseif( cmd == "TRACK" ) then
if( not global_data ) then
global_data = data
else
cue_append( p, global_data, data )
end
data = { file = file, num = string.match( arg, "^(%d+)" ) }
elseif( cmd == "INDEX" ) then
local idx, m, s, f = string.match( arg, "(%d+)%s+(%d+):(%d+):(%d+)" )
if( idx == "01" and m ~= nil and s ~= nil and f ~= nil ) then
data.index01 = m * 60 + s + f / 75
end
end
end
cue_append( p, global_data, data )
return p
end
|
--[[
Parse CUE files
$Id$
Copyright (C) 2009 Laurent Aimar
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
--]]
-- Probe function.
function probe()
if( not string.match( string.upper( vlc.path ), ".CUE$" ) ) then
return false
end
header = vlc.peek( 2048 )
return string.match( header, "FILE.*WAVE%s*[\r\n]+" ) or
string.match( header, "FILE.*AIFF%s*[\r\n]+" ) or
string.match( header, "FILE.*MP3%s*[\r\n]+" )
end
-- Helpers
function is_utf8( src )
return vlc.strings.from_charset( "UTF-8", src ) == src
end
function cue_string( src )
if not is_utf8( src ) then
-- Convert to UTF-8 since it's probably Latin1
src = vlc.strings.from_charset( "ISO_8859-1", src )
end
local sub = string.match( src, "^\"(.*)\".*$" );
if( sub ) then
return sub
end
return string.match( src, "^(%S+).*$" )
end
function cue_path( src )
if( string.match( src, "^/" ) or
string.match( src, "^\\" ) or
string.match( src, "^[%l%u]:\\" ) ) then
return vlc.strings.make_uri(src)
end
local slash = string.find( string.reverse( vlc.path ), '/' )
local prefix = vlc.access .. "://" .. string.sub( vlc.path, 1, -slash )
-- FIXME: postfix may not be encoded correctly (esp. slashes)
local postfix = vlc.strings.encode_uri_component(src)
return prefix .. postfix
end
function cue_track( global, track )
if( track.index01 == nil ) then
return nil
end
t = {}
t.path = cue_path( track.file or global.file )
t.title = track.title
t.album = global.title
t.artist = track.performer or global.performer
t.genre = track.genre or global.genre
t.date = track.date or global.date
t.description = global.comment
t.tracknum = track.num
t.options = { ":start-time=" .. math.floor(track.index01) }
return t
end
function cue_append( tracks, global, track )
local t = cue_track( global, track )
if( t ~= nil ) then
if( #tracks > 0 ) then
local prev = tracks[#tracks]
table.insert( prev.options, ":stop-time=" .. math.floor(track.index01) )
end
table.insert( tracks, t )
end
end
-- Parse function.
function parse()
p = {}
global_data = nil
data = {}
file = nil
while true
do
line = vlc.readline()
if not line then break end
cmd, arg = string.match( line, "^%s*(%S+)%s*(.*)$" )
if( cmd == "REM" and arg ) then
subcmd, value = string.match( arg, "^(%S+)%s*(.*)$" )
if( subcmd == "GENRE" and value ) then
data.genre = cue_string( value )
elseif( subcmd == "DATE" and value ) then
data.date = cue_string( value )
elseif( subcmd == "COMMENT" and value ) then
data.comment = cue_string( value )
end
elseif( cmd == "PERFORMER" and arg ) then
data.performer = cue_string( arg )
elseif( cmd == "TITLE" and arg ) then
data.title = cue_string( arg )
elseif( cmd == "FILE" ) then
file = cue_string( arg )
elseif( cmd == "TRACK" ) then
if( not global_data ) then
global_data = data
else
cue_append( p, global_data, data )
end
data = { file = file, num = string.match( arg, "^(%d+)" ) }
elseif( cmd == "INDEX" ) then
local idx, m, s, f = string.match( arg, "(%d+)%s+(%d+):(%d+):(%d+)" )
if( idx == "01" and m ~= nil and s ~= nil and f ~= nil ) then
data.index01 = m * 60 + s + f / 75
end
end
end
cue_append( p, global_data, data )
return p
end
|
cue: support Latin1 cue files (fix #9238)
|
cue: support Latin1 cue files (fix #9238)
|
Lua
|
lgpl-2.1
|
vlc-mirror/vlc,shyamalschandra/vlc,xkfz007/vlc,krichter722/vlc,vlc-mirror/vlc,krichter722/vlc,jomanmuk/vlc-2.2,xkfz007/vlc,vlc-mirror/vlc,vlc-mirror/vlc,shyamalschandra/vlc,vlc-mirror/vlc,jomanmuk/vlc-2.2,krichter722/vlc,xkfz007/vlc,jomanmuk/vlc-2.2,xkfz007/vlc,shyamalschandra/vlc,xkfz007/vlc,vlc-mirror/vlc,vlc-mirror/vlc,shyamalschandra/vlc,krichter722/vlc,shyamalschandra/vlc,shyamalschandra/vlc,krichter722/vlc,jomanmuk/vlc-2.2,jomanmuk/vlc-2.2,xkfz007/vlc,krichter722/vlc,krichter722/vlc,jomanmuk/vlc-2.2,shyamalschandra/vlc,jomanmuk/vlc-2.2,xkfz007/vlc
|
e4b7a286b5ff93bb11fdc5db9a0c9f61d552f468
|
home/.hammerspoon/confluence.lua
|
home/.hammerspoon/confluence.lua
|
-- Copyright © 2016, 2017, 2019, 2022 Emmanuel Roubion
--
-- Author: Emmanuel Roubion
-- URL: https://github.com/maanuair/dotfiles
-- This file is part of Emmanuel's Roubion dot files, released under
-- the MIT License as published by the Massachusetts Institute of Technology
--
-- These dotfiles are distributed in the hope they wil lbe useful, but
-- without any warranty. See the MIT License for more details
--
-- You should have received a copy of the MIT License along with this file.
-- If not, see https://opensource.org/licenses/mit-license.php
-- 8<-----
-- This is some helper functions, probably to tune to use our own...
-- Requirements and local vars
local utils = require('utils')
local confluenceAccount = require ('confluenceAccount')
local log = hs.logger.new('confluence.lua', 'debug')
local confluence = {}
-- Search the highlighted selection in Confluence
function confluence.search()
local url = confluenceAccount.getSearchUrl(utils.getTrimmedSelectedText())
log.f("confluence.search: opening url '%s'", url)
utils.browseUrl(url)
end
-- Add an Epic in Confluence
function confluence.addEpic()
local url = string.format("%s%s", confluenceAccount.getBaseUrl(), "pages/createpage-entervariables.action?templateId=8159257&spaceKey=PRD&title&newSpaceKey=PRD&fromPageId=4754503")
log.f("confluence.addEpic: opening url '%s'", url)
utils.browseUrl(url)
end
return confluence
|
-- Copyright © 2016, 2017, 2019, 2022 Emmanuel Roubion
--
-- Author: Emmanuel Roubion
-- URL: https://github.com/maanuair/dotfiles
-- This file is part of Emmanuel's Roubion dot files, released under
-- the MIT License as published by the Massachusetts Institute of Technology
--
-- These dotfiles are distributed in the hope they wil lbe useful, but
-- without any warranty. See the MIT License for more details
--
-- You should have received a copy of the MIT License along with this file.
-- If not, see https://opensource.org/licenses/mit-license.php
-- 8<-----
-- This is some helper functions, probably to tune to use our own...
-- Requirements and local vars
local utils = require('utils')
local confluenceAccount = require ('confluenceAccount')
local log = hs.logger.new('confluence.lua', 'debug')
local confluence = {}
-- Search the highlighted selection in Confluence
function confluence.search()
local url = confluenceAccount.getSearchUrl(confluenceAccount.getBaseUrl(), utils.getTrimmedSelectedText())
log.f("confluence.search: opening url '%s'", url)
utils.browseUrl(url)
end
-- Add an Epic in Confluence
function confluence.addEpic()
local url = string.format("%s%s", confluenceAccount.getBaseUrl(), "pages/createpage-entervariables.action?templateId=8159257&spaceKey=PRD&title&newSpaceKey=PRD&fromPageId=4754503")
log.f("confluence.addEpic: opening url '%s'", url)
utils.browseUrl(url)
end
return confluence
|
fix: Fix the search by injecting the baseUrl
|
fix: Fix the search by injecting the baseUrl
|
Lua
|
mit
|
maanuair/dotfiles
|
7502721f4ae4d4f82879b2f3b4fe026101e60072
|
OS/DiskOS/Programs/disk.lua
|
OS/DiskOS/Programs/disk.lua
|
--PNG Floppy Disk Drive controlling program.
local args = {...} --Get the arguments passed to this program
if #args < 3 or args[1] == "-?" then
printUsage(
"disk write <source> <destination> [color]", "Writes a file to a png image",
"disk read <source> <destination>", "Reads a png image to a file",
"disk raw-write <source> <destination> [color]", "Writes a file to a png image without a header",
"disk raw-read <source> <destination>", "Reads a png image to a file"
)
return
end
color(8)
local mode = args[1]
if mode ~= "write" and mode ~= "read" then return 1, "Invalid disk task '"..mode.."' !" end
local term = require("terminal")
local source = term.resolve(args[2])
local destination = term.resolve(args[3])
local diskColor = args[4]
local diskheader = "LK12;FileDisk;DiskOS;" --The header of each file disk.
if not fs.exists(source) then return 1, "Source doesn't exist !" end
if fs.exists(destination) then return 1, "Destination already exists !" end
if fs.isDirectory(source) then return 1, "Source can't be a directory !" end
source = fs.read(source)
local FRAM = RamUtils.FRAM
if mode == "read" then
FDD.importDisk(source)
if memget(FRAM, diskheader:len()) ~= diskheader then
return 1, "Invalid Header !"
end
local fsize = BinUtils.binToNum(memget(FRAM+diskheader:len(),4))
local fdata = memget(FRAM+diskheader:len()+4, fsize)
fs.write(destination,fdata)
color(11) print("Read disk successfully")
elseif mode == "write" then
if source:len() > 64*1024-(diskheader:len()+4) then return 1, "File too big (Should be almost 64kb or less) !" end
memset(FRAM,string.rep(BinUtils.Null,64*1024))
memset(FRAM,diskheader) --Set the disk header
memset(FRAM+diskheader:len(), BinUtils.numToBin(source:len(),4)) --Set the file size
memset(FRAM+diskheader:len()+4,source) --Set the file data
local data = FDD.exportDisk(diskColor)
fs.write(destination,data)
color(11) print("Wrote disk successfully")
elseif mode == "raw-read" then
FDD.importDisk(source)
local fdata = memget(FRAM, 64*1024)
fs.write(destination,fdata)
color(11) print("Read disk successfully")
elseif mode == "raw-write" then
memset(FRAM,string.rep(BinUtils.Null,64*1024))
memset(FRAM,source)
local data = FDD.exportDisk(diskColor)
fs.write(destination,data)
color(11) print("Wrote disk successfully")
end
|
--PNG Floppy Disk Drive controlling program.
local args = {...} --Get the arguments passed to this program
if #args < 3 or args[1] == "-?" then
printUsage(
"disk write <source> <destination> [color]", "Writes a file to a png image",
"disk read <source> <destination>", "Reads a png image to a file",
"disk raw-write <source> <destination> [color]", "Writes a file to a png image without a header",
"disk raw-read <source> <destination>", "Reads a png image to a file"
)
return
end
color(8)
local mode = args[1]
if mode ~= "write" and mode ~= "read" and mode ~= "raw-write" and mode ~= "raw-read" then return 1, "Invalid disk task '"..mode.."' !" end
local term = require("terminal")
local source = term.resolve(args[2])
local destination = term.resolve(args[3])
local diskColor = args[4]
local diskheader = "LK12;FileDisk;DiskOS;" --The header of each file disk.
if not fs.exists(source) then return 1, "Source doesn't exist !" end
if fs.exists(destination) then return 1, "Destination already exists !" end
if fs.isDirectory(source) then return 1, "Source can't be a directory !" end
source = fs.read(source)
local FRAM = RamUtils.FRAM
if mode == "read" then
FDD.importDisk(source)
if memget(FRAM, diskheader:len()) ~= diskheader then
return 1, "Invalid Header !"
end
local fsize = BinUtils.binToNum(memget(FRAM+diskheader:len(),4))
local fdata = memget(FRAM+diskheader:len()+4, fsize)
fs.write(destination,fdata)
color(11) print("Read disk successfully")
elseif mode == "write" then
if source:len() > 64*1024-(diskheader:len()+4) then return 1, "File too big (Should be almost 64kb or less) !" end
memset(FRAM,string.rep(BinUtils.Null,64*1024))
memset(FRAM,diskheader) --Set the disk header
memset(FRAM+diskheader:len(), BinUtils.numToBin(source:len(),4)) --Set the file size
memset(FRAM+diskheader:len()+4,source) --Set the file data
local data = FDD.exportDisk(diskColor)
fs.write(destination,data)
color(11) print("Wrote disk successfully")
elseif mode == "raw-read" then
FDD.importDisk(source)
local fdata = memget(FRAM, 64*1024)
fs.write(destination,fdata)
color(11) print("Read disk successfully")
elseif mode == "raw-write" then
memset(FRAM,string.rep(BinUtils.Null,64*1024))
memset(FRAM,source)
local data = FDD.exportDisk(diskColor)
fs.write(destination,data)
color(11) print("Wrote disk successfully")
end
|
Fix `raw-read` and `raw-write` in the `disk` program.
|
Fix `raw-read` and `raw-write` in the `disk` program.
Former-commit-id: a789d64f48cba5efa3e2147122c5f53133160979
|
Lua
|
mit
|
RamiLego4Game/LIKO-12
|
d929634cd13bbe6be6dfa9b5a0ed3c17d0438294
|
libs/weblit-static.lua
|
libs/weblit-static.lua
|
exports.name = "creationix/weblit-static"
exports.version = "0.3.3"
exports.dependencies = {
"creationix/mime@0.1.2",
"creationix/hybrid-fs@0.1.1",
}
exports.description = "The auto-headers middleware helps Weblit apps implement proper HTTP semantics"
exports.tags = {"weblit", "middleware", "http"}
exports.license = "MIT"
exports.author = { name = "Tim Caswell" }
exports.homepage = "https://github.com/creationix/weblit/blob/master/libs/weblit-auto-headers.lua"
local getType = require("mime").getType
local jsonStringify = require('json').stringify
local makeChroot = require('hybrid-fs')
return function (rootPath)
local fs = makeChroot(rootPath)
return function (req, res, go)
if req.method ~= "GET" then return go() end
local path = (req.params and req.params.path) or req.path
path = path:match("^[^?#]*")
if path:byte(1) == 47 then
path = path:sub(2)
end
local stat = fs.stat(path)
if not stat then return go() end
local function renderFile()
local body = assert(fs.readFile(path))
res.code = 200
res.headers["Content-Type"] = getType(path)
res.body = body
return
end
local function renderDirectory()
if req.path:byte(-1) ~= 47 then
res.code = 301
res.headers.Location = req.path .. '/'
return
end
local files = {}
for entry in fs.scandir(path) do
if entry.name == "index.html" and entry.type == "file" then
path = (#path > 0 and path .. "/" or "") .. "index.html"
return renderFile()
end
files[#files + 1] = entry
entry.url = "http://" .. req.headers.host .. req.path .. entry.name
end
local body = jsonStringify(files) .. "\n"
res.code = 200
res.headers["Content-Type"] = "application/json"
res.body = body
return
end
if stat.type == "directory" then
return renderDirectory()
elseif stat.type == "file" then
if req.path:byte(-1) == 47 then
res.code = 301
res.headers.Location = req.path:match("^(.*[^/])/+$")
return
end
return renderFile()
end
end
end
|
exports.name = "creationix/weblit-static"
exports.version = "0.3.3-1"
exports.dependencies = {
"creationix/mime@0.1.2",
"creationix/hybrid-fs@0.1.1",
}
exports.description = "A weblit middleware for serving static files from disk or bundle."
exports.tags = {"weblit", "middleware", "static"}
exports.license = "MIT"
exports.author = { name = "Tim Caswell" }
exports.homepage = "https://github.com/creationix/weblit/blob/master/libs/weblit-auto-headers.lua"
local getType = require("mime").getType
local jsonStringify = require('json').stringify
local makeChroot = require('hybrid-fs')
return function (rootPath)
local fs = makeChroot(rootPath)
return function (req, res, go)
if req.method ~= "GET" then return go() end
local path = (req.params and req.params.path) or req.path
path = path:match("^[^?#]*")
if path:byte(1) == 47 then
path = path:sub(2)
end
local stat = fs.stat(path)
if not stat then return go() end
local function renderFile()
local body = assert(fs.readFile(path))
res.code = 200
res.headers["Content-Type"] = getType(path)
res.body = body
return
end
local function renderDirectory()
if req.path:byte(-1) ~= 47 then
res.code = 301
res.headers.Location = req.path .. '/'
return
end
local files = {}
for entry in fs.scandir(path) do
if entry.name == "index.html" and entry.type == "file" then
path = (#path > 0 and path .. "/" or "") .. "index.html"
return renderFile()
end
files[#files + 1] = entry
entry.url = "http://" .. req.headers.host .. req.path .. entry.name
end
local body = jsonStringify(files) .. "\n"
res.code = 200
res.headers["Content-Type"] = "application/json"
res.body = body
return
end
if stat.type == "directory" then
return renderDirectory()
elseif stat.type == "file" then
if req.path:byte(-1) == 47 then
res.code = 301
res.headers.Location = req.path:match("^(.*[^/])/+$")
return
end
return renderFile()
end
end
end
|
Fix metadata on weblit-static
|
Fix metadata on weblit-static
|
Lua
|
mit
|
zhaozg/weblit
|
771f7849094d25acb92bf5d1d16d43a7153f8825
|
UCDutil/confirmation_c.lua
|
UCDutil/confirmation_c.lua
|
function createConfirmationWindow(text, callbackString, arg)
local confirmation = {window={}, label={}, button={}}
local calledResource = tostring(Resource.getName(sourceResource))
-- Replace 'UCD' with blank and capitalise the first letter
calledResource = calledResource:gsub("UCD", "")
calledResource = calledResource:gsub("^%l", string.upper)
outputDebugString(callbackString)
confirmation.window[1] = guiCreateWindow(819, 425, 282, 132, "UCD | "..calledResource.." - Confirmation", false)
guiWindowSetSizable(confirmation.window[1], false)
confirmation.label[1] = guiCreateLabel(10, 26, 262, 44, tostring(text), false, confirmation.window[1])
guiLabelSetHorizontalAlign(confirmation.label[1], "center", false)
confirmation.button[1] = guiCreateButton(47, 85, 76, 36, "Yes", false, confirmation.window[1])
confirmation.button[2] = guiCreateButton(164, 85, 76, 36, "No", false, confirmation.window[1])
showCursor(true)
-- The purchase house bit underneath is not part of this general function.
function confirmationWindowClick()
if (source == confirmation.button[1]) then
if (isElement(confirmation.window[1])) then
removeEventHandler("onClientGUIClick", confirmation.window[1], confirmationWindowClick)
confirmation.window[1]:destroy()
end
if (callbackString ~= "") then
outputDebugString("UCDutil: argument passed = "..tostring(arg))
local arg = arg
outputDebugString(callbackString)
loadstring(callbackString)(arg) -- This runs it straight away and allows argument passing
assert(loadstring(callbackString))(arg) -- This runs it straight away and allows argument passing
end
showCursor(false)
return true
elseif (source == confirmation.button[2]) then
if (isElement(confirmation.window[1])) then
removeEventHandler("onClientGUIClick", confirmation.window[1], confirmationWindowClick)
confirmation.window[1]:destroy()
end
showCursor(false)
return false
end
end
addEventHandler("onClientGUIClick", confirmation.window[1], confirmationWindowClick)
end
--[[
-- CALLBACK STRING SHOULD BE IN FORM OF
-- "exports.resource:function(args)"
--]]
|
function createConfirmationWindow(text, callbackString)
local confirmation = {window={}, label={}, button={}}
local calledResource = tostring(Resource.getName(sourceResource))
-- Replace 'UCD' with blank and capitalise the first letter
calledResource = calledResource:gsub("UCD", "")
calledResource = calledResource:gsub("^%l", string.upper)
outputDebugString(callbackString)
confirmation.window[1] = guiCreateWindow(819, 425, 282, 132, "UCD | "..calledResource.." - Confirmation", false)
guiWindowSetSizable(confirmation.window[1], false)
confirmation.label[1] = guiCreateLabel(10, 26, 262, 44, tostring(text), false, confirmation.window[1])
guiLabelSetHorizontalAlign(confirmation.label[1], "center", false)
confirmation.button[1] = guiCreateButton(47, 85, 76, 36, "Yes", false, confirmation.window[1])
confirmation.button[2] = guiCreateButton(164, 85, 76, 36, "No", false, confirmation.window[1])
showCursor(true)
-- The purchase house bit underneath is not part of this general function.
function confirmationWindowClick()
if (source == confirmation.button[1]) then
if (isElement(confirmation.window[1])) then
removeEventHandler("onClientGUIClick", confirmation.window[1], confirmationWindowClick)
confirmation.window[1]:destroy()
end
if (callbackString ~= "") then
loadstring(callbackString)()
end
showCursor(false)
return true
elseif (source == confirmation.button[2]) then
if (isElement(confirmation.window[1])) then
removeEventHandler("onClientGUIClick", confirmation.window[1], confirmationWindowClick)
confirmation.window[1]:destroy()
end
showCursor(false)
return false
end
end
addEventHandler("onClientGUIClick", confirmation.window[1], confirmationWindowClick)
end
--[[
-- CALLBACK STRING SHOULD BE IN FORM OF
-- "exports.resource:function(args)"
--]]
|
UCDutil
|
UCDutil
- Fixed loadstring callback issue by concatenating the value.
|
Lua
|
mit
|
nokizorque/ucd,nokizorque/ucd
|
7e818ccfa3d887740c6867049f79a0c4e8dd66fa
|
codesamples/AsyncPatterns.lua
|
codesamples/AsyncPatterns.lua
|
#reference 'MavHttp.dll'
#compile 'Something.cs'
import 'System.Threading.Tasks'
LOG_CLR_CACHE()
serv = Http()
-- asynchronously call a blocking .NET method then call back via scheduler
async(Thread).Sleep(1000):success(function() print "waited a sec" end)
serv:GET('/async',function(req,res)
sw = StreamWriter(res.OutputStream)
sw.AutoFlush = true
-- _async mirrors the global table but wraps its elements with async(), providing an alternative syntax.
_async.sw:Write("HIII {0}",1):success(function() print("omfg") res:Close() end)
end)
serv:GET('/sync_callback',function(req,res)
--call an asynchronous .NET method, providing an AsyncCallback that delegates to the scheduler, with sync_callback()
res.OutputStream:BeginWrite(Utility.GetBytes("hello"),0,10,
sync_callback(function(x) res.OutputStream:EndWrite(x) res:Close() end)
,obj({}))
end)
serv:listen("http://+:8080/")
Console.WriteLine("Listening 8080")
Console.ReadKey()
|
#reference 'MavHttp.dll'
import 'System.Threading.Tasks'
LOG_CLR_CACHE()
serv = Http()
-- asynchronously call a blocking .NET method then call back via scheduler
async(Thread).Sleep(1000):success(function() print "waited a sec" end)
serv:GET('/async',function(req,res)
sw = StreamWriter(res.OutputStream)
sw.AutoFlush = true
-- _async mirrors the global table but wraps its elements with async(), providing an alternative syntax.
_async.sw:Write("HIII {0}",1):success(function() print("omfg") res:Close() end)
end)
serv:GET('/sync_callback',function(req,res)
--call an asynchronous .NET method, providing an AsyncCallback that delegates to the scheduler, with sync_callback()
res.OutputStream:BeginWrite(Utility.GetBytes("hello"),0,10,
sync_callback(function(x) res.OutputStream:EndWrite(x) res:Close() end)
,obj({}))
end)
serv:listen("http://+:8080/")
Console.WriteLine("Listening 8080")
Console.ReadKey()
exit()
|
Fix AsyncPatterns code sample
|
Fix AsyncPatterns code sample
|
Lua
|
mit
|
drew-r/Maverick
|
2f54c4878d6a336407c4aa5d079f941718f95b63
|
lua/weapons/gmod_tool/stools/wire_value.lua
|
lua/weapons/gmod_tool/stools/wire_value.lua
|
TOOL.Category = "Wire - I/O"
TOOL.Name = "Constant Value"
TOOL.Command = nil
TOOL.ConfigName = ""
TOOL.Tab = "Wire"
if (CLIENT) then
language.Add("Tool.wire_value.name", "Value Tool (Wire)")
language.Add("Tool.wire_value.desc", "Spawns a constant value for use with the wire system.")
language.Add("Tool.wire_value.0", "Primary: Create/Update Value, Secondary: Copy Settings")
language.Add("WireValueTool_value", "Value:")
language.Add("WireValueTool_model", "Model:")
language.Add("sboxlimit_wire_values", "You've hit values limit!")
language.Add("undone_wirevalue", "Undone Wire Value")
end
TOOL.ClientConVar["model"] = "models/kobilica/value.mdl"
// Supported Data Types.
// Should be requested by client and only kept serverside.
local DataTypes =
{
["NORMAL"] = "Number",
["STRING"] = "String",
["VECTOR"] = "Vector",
["ANGLE"] = "Angle"
}
cleanup.Register("wire_values")
if CLIENT then
function TOOL:LeftClick( trace )
return true
end
end
if (SERVER) then
local playerValues = {}
CreateConVar('sbox_maxwire_values', 20)
ModelPlug_Register("value")
util.AddNetworkString( "wire_value_values" )
net.Receive( "wire_value_values", function( length, ply )
playerValues[ply] = net.ReadTable()
end)
local function MakeWireValue( ply, Pos, Ang, model )
if (!ply:CheckLimit("wire_values")) then return false end
local wire_value = ents.Create("gmod_wire_value")
if (!wire_value:IsValid()) then return false end
undo.Create("wirevalue")
undo.AddEntity( wire_value )
undo.SetPlayer( ply )
undo.Finish()
wire_value:SetAngles(Ang)
wire_value:SetPos(Pos)
wire_value:SetModel(model)
wire_value:Spawn()
wire_value:Setup(playerValues[ply])
wire_value:SetPlayer(ply)
ply:AddCount("wire_values", wire_value)
return wire_value
end
duplicator.RegisterEntityClass("gmod_wire_value", MakeWireValue, "Pos", "Ang", "Model", "value")
function TOOL:LeftClick(trace)
if (!trace.HitPos) then return false end
if (trace.Entity:IsPlayer()) then return false end
if not util.IsValidPhysicsObject( trace.Entity, trace.PhysicsBone ) then return false end
if trace.Entity:IsValid() && trace.Entity:GetClass() == "gmod_wire_value" then
local ply = self:GetOwner()
trace.Entity:Setup( playerValues[ply] )
else
local ply = self:GetOwner()
local tbl = playerValues[ply]
if tbl != nil then
local ang = trace.HitNormal:Angle()
ang.pitch = ang.pitch + 90
local ent = MakeWireValue(ply, trace.HitPos, ang, self:GetModel() )
local weld = constraint.Weld( ent, trace.Entity, trace.PhysicsBone,0,0, true )
return true
else
return false
end
end
return false
end
function TOOL:RightClick(trace)
return false
end
end
function TOOL:UpdateGhostWireValue(ent, player)
if (!ent || !ent:IsValid()) then return end
local tr = util.GetPlayerTrace(player)
local trace = util.TraceLine(tr)
if (!trace.Hit || trace.Entity:IsPlayer() || trace.Entity:GetClass() == "gmod_wire_value") then
ent:SetNoDraw(true)
return
end
local Ang = trace.HitNormal:Angle()
Ang.pitch = Ang.pitch + 90
local min = ent:OBBMins()
ent:SetPos(trace.HitPos - trace.HitNormal * min.z)
ent:SetAngles(Ang)
ent:SetNoDraw(false)
end
function TOOL:Think()
local model = self:GetModel()
if (!self.GhostEntity || !self.GhostEntity:IsValid() || self.GhostEntity:GetModel() != model) then
self:MakeGhostEntity(Model(model), Vector(0,0,0), Angle(0,0,0))
end
self:UpdateGhostWireValue(self.GhostEntity, self:GetOwner())
end
function TOOL:GetModel()
local model = "models/kobilica/value.mdl"
local modelcheck = self:GetClientInfo("model")
if (util.IsValidModel(modelcheck) and util.IsValidProp(modelcheck)) then
model = modelcheck
end
return model
end
if CLIENT then
local selectedValues = {}
local function SendUpdate()
net.Start("wire_value_values")
net.WriteTable(selectedValues)
net.SendToServer()
end
local function AddValue( panel, id )
local w,_ = panel:GetSize()
selectedValues[id] = {
DataType = "Number",
Value = 0
}
local control = vgui.Create( "DCollapsibleCategory", panel )
control:SetSize( w-6, 100 )
control:SetText( "Value: " .. id )
control:SetLabel( "Value " .. id )
control:DockMargin( 5,5,5,5 )
control:Dock(TOP)
local controlPanel = vgui.Create( "DPanel", control )
controlPanel:SetSize( w-6, 100 )
controlPanel:Dock(TOP)
local typeSelection = vgui.Create( "DComboBox", controlPanel )
local _, controlW = control:GetSize()
typeSelection:SetText( DataTypes["NORMAL"] )
typeSelection:SetSize( controlW , 25 )
typeSelection:DockMargin( 5,5,5,5)
typeSelection:Dock( TOP )
typeSelection.OnSelect = function( panel, index, value )
selectedValues[id].DataType = value
SendUpdate()
end
for k,v in pairs( DataTypes ) do
typeSelection:AddChoice(v)
end
local valueEntry = vgui.Create( "DTextEntry", controlPanel )
valueEntry:SetSize( controlW, 25 )
valueEntry:DockMargin( 5,5,5,5 )
valueEntry:SetText("0")
valueEntry:Dock( TOP )
valueEntry.OnLoseFocus = function( panel )
if panel:GetValue() != nil then
local value = panel:GetValue()
selectedValues[id].Value = panel:GetValue()
SendUpdate()
end
end
return control
end
local ValuePanels = {}
function TOOL.BuildCPanel( panel )
local LastValueAmount = 0
local valuePanel = vgui.Create("DPanel", panel)
valuePanel:SetSize(w, 500 )
valuePanel:Dock( TOP )
-- WIP.
local reset = vgui.Create( "DButton", valuePanel )
local w,_ = panel:GetSize()
reset:SetSize(w, 25)
reset:SetText("Reset Values.")
reset:DockMargin( 5, 5, 5, 5 )
reset:Dock( TOP )
local valueSlider = vgui.Create( "DNumSlider", valuePanel )
valueSlider:SetSize(w, 25 )
valueSlider:SetText( "Amount:" )
valueSlider:SetMin(1)
valueSlider:SetMax(20)
valueSlider:SetDecimals( 0 )
valueSlider:DockMargin( 5, 5, 5, 5 )
valueSlider:Dock( TOP )
valueSlider.OnValueChanged = function( panel, value )
local value = tonumber(value) -- Silly Garry, giving me strings.
if value != LastValueAmount then
if value > LastValueAmount then
for i = LastValueAmount + 1, value, 1 do
ValuePanels[i] = AddValue( valuePanel, i )
local _,h = valuePanel:GetSize()
valuePanel:SetSize(w, h+120 )
end
elseif value < LastValueAmount then
for i = value + 1, LastValueAmount, 1 do
selectedValues[i] = nil
ValuePanels[i]:Remove()
ValuePanels[i] = nil
local _,h = valuePanel:GetSize()
valuePanel:SetSize(w, h-120 )
end
else
Msg("Error Incorrect value exists?!?!.\n")
end
LastValueAmount = value
SendUpdate()
end
end
valueSlider.OnValueChanged( valuePanel, 1 )
end
end
|
TOOL.Category = "Wire - I/O"
TOOL.Name = "Constant Value"
TOOL.Command = nil
TOOL.ConfigName = ""
TOOL.Tab = "Wire"
if (CLIENT) then
language.Add("Tool.wire_value.name", "Value Tool (Wire)")
language.Add("Tool.wire_value.desc", "Spawns a constant value for use with the wire system.")
language.Add("Tool.wire_value.0", "Primary: Create/Update Value, Secondary: Copy Settings")
language.Add("WireValueTool_value", "Value:")
language.Add("WireValueTool_model", "Model:")
language.Add("sboxlimit_wire_values", "You've hit values limit!")
language.Add("undone_wirevalue", "Undone Wire Value")
end
TOOL.ClientConVar["model"] = "models/kobilica/value.mdl"
// Supported Data Types.
// Should be requested by client and only kept serverside.
local DataTypes =
{
["NORMAL"] = "Number",
["STRING"] = "String",
["VECTOR"] = "Vector",
["ANGLE"] = "Angle"
}
cleanup.Register("wire_values")
if CLIENT then
function TOOL:LeftClick( trace )
return true
end
end
if (SERVER) then
local playerValues = {}
CreateConVar('sbox_maxwire_values', 20)
ModelPlug_Register("value")
util.AddNetworkString( "wire_value_values" )
net.Receive( "wire_value_values", function( length, ply )
playerValues[ply] = net.ReadTable()
end)
local function MakeWireValue( ply, Pos, Ang, model, value )
if (!ply:CheckLimit("wire_values")) then return false end
local wire_value = ents.Create("gmod_wire_value")
if (!wire_value:IsValid()) then return false end
undo.Create("wirevalue")
undo.AddEntity( wire_value )
undo.SetPlayer( ply )
undo.Finish()
wire_value:SetAngles(Ang)
wire_value:SetPos(Pos)
wire_value:SetModel(model)
wire_value:Spawn()
wire_value:Setup(value)
wire_value:SetPlayer(ply)
ply:AddCount("wire_values", wire_value)
return wire_value
end
duplicator.RegisterEntityClass("gmod_wire_value", MakeWireValue, "Pos", "Ang", "Model", "value")
function TOOL:LeftClick(trace)
if (!trace.HitPos) then return false end
if (trace.Entity:IsPlayer()) then return false end
if not util.IsValidPhysicsObject( trace.Entity, trace.PhysicsBone ) then return false end
if trace.Entity:IsValid() && trace.Entity:GetClass() == "gmod_wire_value" then
local ply = self:GetOwner()
trace.Entity:Setup( playerValues[ply] )
else
local ply = self:GetOwner()
local tbl = playerValues[ply]
if tbl != nil then
local ang = trace.HitNormal:Angle()
ang.pitch = ang.pitch + 90
local ent = MakeWireValue(ply, trace.HitPos, ang, self:GetModel(), playerValues[ply] )
local weld = constraint.Weld( ent, trace.Entity, trace.PhysicsBone,0,0, true )
return true
else
return false
end
end
return false
end
function TOOL:RightClick(trace)
return false
end
end
function TOOL:UpdateGhostWireValue(ent, player)
if (!ent || !ent:IsValid()) then return end
local tr = util.GetPlayerTrace(player)
local trace = util.TraceLine(tr)
if (!trace.Hit || trace.Entity:IsPlayer() || trace.Entity:GetClass() == "gmod_wire_value") then
ent:SetNoDraw(true)
return
end
local Ang = trace.HitNormal:Angle()
Ang.pitch = Ang.pitch + 90
local min = ent:OBBMins()
ent:SetPos(trace.HitPos - trace.HitNormal * min.z)
ent:SetAngles(Ang)
ent:SetNoDraw(false)
end
function TOOL:Think()
local model = self:GetModel()
if (!self.GhostEntity || !self.GhostEntity:IsValid() || self.GhostEntity:GetModel() != model) then
self:MakeGhostEntity(Model(model), Vector(0,0,0), Angle(0,0,0))
end
self:UpdateGhostWireValue(self.GhostEntity, self:GetOwner())
end
function TOOL:GetModel()
local model = "models/kobilica/value.mdl"
local modelcheck = self:GetClientInfo("model")
if (util.IsValidModel(modelcheck) and util.IsValidProp(modelcheck)) then
model = modelcheck
end
return model
end
if CLIENT then
local selectedValues = {}
local function SendUpdate()
net.Start("wire_value_values")
net.WriteTable(selectedValues)
net.SendToServer()
end
local function AddValue( panel, id )
local w,_ = panel:GetSize()
selectedValues[id] = {
DataType = "Number",
Value = 0
}
local control = vgui.Create( "DCollapsibleCategory", panel )
control:SetSize( w-6, 100 )
control:SetText( "Value: " .. id )
control:SetLabel( "Value " .. id )
control:DockMargin( 5,5,5,5 )
control:Dock(TOP)
local controlPanel = vgui.Create( "DPanel", control )
controlPanel:SetSize( w-6, 100 )
controlPanel:Dock(TOP)
local typeSelection = vgui.Create( "DComboBox", controlPanel )
local _, controlW = control:GetSize()
typeSelection:SetText( DataTypes["NORMAL"] )
typeSelection:SetSize( controlW , 25 )
typeSelection:DockMargin( 5,5,5,5)
typeSelection:Dock( TOP )
typeSelection.OnSelect = function( panel, index, value )
selectedValues[id].DataType = value
SendUpdate()
end
for k,v in pairs( DataTypes ) do
typeSelection:AddChoice(v)
end
local valueEntry = vgui.Create( "DTextEntry", controlPanel )
valueEntry:SetSize( controlW, 25 )
valueEntry:DockMargin( 5,5,5,5 )
valueEntry:SetText("0")
valueEntry:Dock( TOP )
local oldLoseFocus = valueEntry.OnLoseFocus
valueEntry.OnLoseFocus = function( panel )
if panel:GetValue() != nil then
local value = panel:GetValue()
selectedValues[id].Value = panel:GetValue()
SendUpdate()
end
oldLoseFocus(panel) -- Otherwise we can't close the spawnmenu!
end
return control
end
local ValuePanels = {}
function TOOL.BuildCPanel( panel )
local LastValueAmount = 0
local valuePanel = vgui.Create("DPanel", panel)
valuePanel:SetSize(w, 500 )
valuePanel:Dock( TOP )
-- WIP.
local reset = vgui.Create( "DButton", valuePanel )
local w,_ = panel:GetSize()
reset:SetSize(w, 25)
reset:SetText("Reset Values.")
reset:DockMargin( 5, 5, 5, 5 )
reset:Dock( TOP )
local valueSlider = vgui.Create( "DNumSlider", valuePanel )
valueSlider:SetSize(w, 25 )
valueSlider:SetText( "Amount:" )
valueSlider:SetMin(1)
valueSlider:SetMax(20)
valueSlider:SetDecimals( 0 )
valueSlider:DockMargin( 5, 5, 5, 5 )
valueSlider:Dock( TOP )
valueSlider.OnValueChanged = function( panel, value )
local value = tonumber(value) -- Silly Garry, giving me strings.
if value != LastValueAmount then
if value > LastValueAmount then
for i = LastValueAmount + 1, value, 1 do
ValuePanels[i] = AddValue( valuePanel, i )
local _,h = valuePanel:GetSize()
valuePanel:SetSize(w, h+120 )
end
elseif value < LastValueAmount then
for i = value + 1, LastValueAmount, 1 do
selectedValues[i] = nil
ValuePanels[i]:Remove()
ValuePanels[i] = nil
local _,h = valuePanel:GetSize()
valuePanel:SetSize(w, h-120 )
end
else
Msg("Error Incorrect value exists?!?!.\n")
end
LastValueAmount = value
SendUpdate()
end
end
valueSlider.OnValueChanged( valuePanel, 1 )
end
end
|
Fixed wire_values duplication support, previously it would use the player's current settings when pasting wire_value's.
|
Fixed wire_values duplication support, previously it would use the player's current settings when pasting wire_value's.
Also fixed the cpanel so typing in the textentrys does not lock you into the spawnmenu.
|
Lua
|
apache-2.0
|
plinkopenguin/wiremod,CaptainPRICE/wire,bigdogmat/wire,immibis/wiremod,sammyt291/wire,thegrb93/wire,mms92/wire,garrysmodlua/wire,wiremod/wire,NezzKryptic/Wire,Python1320/wire,Grocel/wire,notcake/wire,mitterdoo/wire,rafradek/wire,dvdvideo1234/wire
|
cea3ab24ac10aa7c117c6fb63f0abb5b24d50074
|
SpatialConvolution.lua
|
SpatialConvolution.lua
|
local SpatialConvolution, parent = torch.class('nn.SpatialConvolution', 'nn.Module')
function SpatialConvolution:__init(nInputPlane, nOutputPlane, kW, kH, dW, dH, padding)
parent.__init(self)
dW = dW or 1
dH = dH or 1
self.nInputPlane = nInputPlane
self.nOutputPlane = nOutputPlane
self.kW = kW
self.kH = kH
self.dW = dW
self.dH = dH
self.padding = padding or 0
self.weight = torch.Tensor(nOutputPlane, nInputPlane, kH, kW)
self.bias = torch.Tensor(nOutputPlane)
self.gradWeight = torch.Tensor(nOutputPlane, nInputPlane, kH, kW)
self.gradBias = torch.Tensor(nOutputPlane)
self:reset()
end
function SpatialConvolution:reset(stdv)
if stdv then
stdv = stdv * math.sqrt(3)
else
stdv = 1/math.sqrt(self.kW*self.kH*self.nInputPlane)
end
if nn.oldSeed then
self.weight:apply(function()
return torch.uniform(-stdv, stdv)
end)
self.bias:apply(function()
return torch.uniform(-stdv, stdv)
end)
else
self.weight:uniform(-stdv, stdv)
self.bias:uniform(-stdv, stdv)
end
end
local function backCompatibility(self)
self.finput = self.finput or self.weight.new()
self.fgradInput = self.fgradInput or self.weight.new()
self.padding = self.padding or 0
if self.weight:dim() == 2 then
self.weight = self.weight:view(self.nOutputPlane, self.nInputPlane, self.kH, self.kW)
end
if self.gradWeight:dim() == 2 then
self.gradWeight = self.gradWeight:view(self.nOutputPlane, self.nInputPlane, self.kH, self.kW)
end
end
local function makeContiguous(self, input, gradOutput)
if not input:isContiguous() then
self._input = self._input or input.new()
self._input:resizeAs(input):copy(input)
input = self._input
end
if gradOutput then
if not gradOutput:isContiguous() then
self._gradOutput = self._gradOutput or gradOutput.new()
self._gradOutput:resizeAs(gradOutput):copy(gradOutput)
gradOutput = self._gradOutput
end
end
return input, gradOutput
end
-- function to re-view the weight layout in a way that would make the MM ops happy
local function viewWeight(self)
self.weight = self.weight:view(self.nOutputPlane, self.nInputPlane * self.kH * self.kW)
self.gradWeight = self.gradWeight:view(self.nOutputPlane, self.nInputPlane * self.kH * self.kW)
end
local function unviewWeight(self)
self.weight = self.weight:view(self.nOutputPlane, self.nInputPlane, self.kH, self.kW)
self.gradWeight = self.gradWeight:view(self.nOutputPlane, self.nInputPlane, self.kH, self.kW)
end
function SpatialConvolution:updateOutput(input)
backCompatibility(self)
viewWeight(self)
input = makeContiguous(self, input)
local out = input.nn.SpatialConvolutionMM_updateOutput(self, input)
unviewWeight(self)
return out
end
function SpatialConvolution:updateGradInput(input, gradOutput)
if self.gradInput then
backCompatibility(self)
viewWeight(self)
input, gradOutput = makeContiguous(self, input, gradOutput)
local out = input.nn.SpatialConvolutionMM_updateGradInput(self, input, gradOutput)
unviewWeight(self)
return out
end
end
function SpatialConvolution:accGradParameters(input, gradOutput, scale)
backCompatibility(self)
input, gradOutput = makeContiguous(self, input, gradOutput)
viewWeight(self)
local out = input.nn.SpatialConvolutionMM_accGradParameters(self, input, gradOutput, scale)
unviewWeight(self)
return out
end
|
local SpatialConvolution, parent = torch.class('nn.SpatialConvolution', 'nn.Module')
function SpatialConvolution:__init(nInputPlane, nOutputPlane, kW, kH, dW, dH, padding)
parent.__init(self)
dW = dW or 1
dH = dH or 1
self.nInputPlane = nInputPlane
self.nOutputPlane = nOutputPlane
self.kW = kW
self.kH = kH
self.dW = dW
self.dH = dH
self.padding = padding or 0
self.weight = torch.Tensor(nOutputPlane, nInputPlane, kH, kW)
self.bias = torch.Tensor(nOutputPlane)
self.gradWeight = torch.Tensor(nOutputPlane, nInputPlane, kH, kW)
self.gradBias = torch.Tensor(nOutputPlane)
self:reset()
end
function SpatialConvolution:reset(stdv)
if stdv then
stdv = stdv * math.sqrt(3)
else
stdv = 1/math.sqrt(self.kW*self.kH*self.nInputPlane)
end
if nn.oldSeed then
self.weight:apply(function()
return torch.uniform(-stdv, stdv)
end)
self.bias:apply(function()
return torch.uniform(-stdv, stdv)
end)
else
self.weight:uniform(-stdv, stdv)
self.bias:uniform(-stdv, stdv)
end
end
local function backCompatibility(self)
self.finput = self.finput or self.weight.new()
self.fgradInput = self.fgradInput or self.weight.new()
self.padding = self.padding or 0
if self.weight:dim() == 2 then
self.weight = self.weight:view(self.nOutputPlane, self.nInputPlane, self.kH, self.kW)
end
if self.gradWeight and self.gradWeight:dim() == 2 then
self.gradWeight = self.gradWeight:view(self.nOutputPlane, self.nInputPlane, self.kH, self.kW)
end
end
local function makeContiguous(self, input, gradOutput)
if not input:isContiguous() then
self._input = self._input or input.new()
self._input:resizeAs(input):copy(input)
input = self._input
end
if gradOutput then
if not gradOutput:isContiguous() then
self._gradOutput = self._gradOutput or gradOutput.new()
self._gradOutput:resizeAs(gradOutput):copy(gradOutput)
gradOutput = self._gradOutput
end
end
return input, gradOutput
end
-- function to re-view the weight layout in a way that would make the MM ops happy
local function viewWeight(self)
self.weight = self.weight:view(self.nOutputPlane, self.nInputPlane * self.kH * self.kW)
self.gradWeight = self.gradWeight and self.gradWeight:view(self.nOutputPlane, self.nInputPlane * self.kH * self.kW)
end
local function unviewWeight(self)
self.weight = self.weight:view(self.nOutputPlane, self.nInputPlane, self.kH, self.kW)
self.gradWeight = self.gradWeight and self.gradWeight:view(self.nOutputPlane, self.nInputPlane, self.kH, self.kW)
end
function SpatialConvolution:updateOutput(input)
backCompatibility(self)
viewWeight(self)
input = makeContiguous(self, input)
local out = input.nn.SpatialConvolutionMM_updateOutput(self, input)
unviewWeight(self)
return out
end
function SpatialConvolution:updateGradInput(input, gradOutput)
if self.gradInput then
backCompatibility(self)
viewWeight(self)
input, gradOutput = makeContiguous(self, input, gradOutput)
local out = input.nn.SpatialConvolutionMM_updateGradInput(self, input, gradOutput)
unviewWeight(self)
return out
end
end
function SpatialConvolution:accGradParameters(input, gradOutput, scale)
backCompatibility(self)
input, gradOutput = makeContiguous(self, input, gradOutput)
viewWeight(self)
local out = input.nn.SpatialConvolutionMM_accGradParameters(self, input, gradOutput, scale)
unviewWeight(self)
return out
end
|
fix missing gradWeight bug
|
fix missing gradWeight bug
|
Lua
|
bsd-3-clause
|
rotmanmi/nn,fmassa/nn,GregSatre/nn,lvdmaaten/nn,PierrotLC/nn,EnjoyHacking/nn,rickyHong/nn_lib_torch,jzbontar/nn,PraveerSINGH/nn,xianjiec/nn,Aysegul/nn,aaiijmrtt/nn,karpathy/nn,davidBelanger/nn,zhangxiangxiao/nn,sagarwaghmare69/nn,LinusU/nn,caldweln/nn,sbodenstein/nn,clementfarabet/nn,eriche2016/nn,jonathantompson/nn,kmul00/nn,nicholas-leonard/nn,abeschneider/nn,diz-vara/nn,jhjin/nn,mys007/nn,witgo/nn,elbamos/nn,adamlerer/nn,Jeffyrao/nn,andreaskoepf/nn,hery/nn,mlosch/nn,hughperkins/nn,forty-2/nn,ivendrov/nn,apaszke/nn,Djabbz/nn,lukasc-ch/nn,eulerreich/nn,zchengquan/nn,noa/nn,vgire/nn,Moodstocks/nn,colesbury/nn,bartvm/nn,douwekiela/nn,boknilev/nn,szagoruyko/nn,ominux/nn,joeyhng/nn
|
2df4b00693c0d3b9ae85794dc528dc0aee23bff8
|
plumber.lua
|
plumber.lua
|
#!/usr/local/bin/tjost -i
--[[
-- Copyright (c) 2014 Hanspeter Portner (dev@open-music-kontrollers.ch)
--
-- This software is provided 'as-is', without any express or implied
-- warranty. In no event will the authors be held liable for any damages
-- arising from the use of this software.
--
-- Permission is granted to anyone to use this software for any purpose,
-- including commercial applications, and to alter it and redistribute it
-- freely, subject to the following restrictions:
--
-- 1. The origin of this software must not be misrepresented; you must not
-- claim that you wrote the original software. If you use this software
-- in a product, an acknowledgment in the product documentation would be
-- appreciated but is not required.
--
-- 2. Altered source versions must be plainly marked as such, and must not be
-- misrepresented as being the original software.
--
-- 3. This notice may not be removed or altered from any source
-- distribution.
--]]
message = plugin('dump')
graph = {}
rules = {
{'system:capture_1', 'system:playback_1'},
{'system:capture_2', 'system:playback_2'}
}
function update_plumbing()
for _, v in ipairs(rules) do
local a = v[1]
local b = v[2]
if graph[a] and graph[b] and (not graph[a][b]) then
uplink(0, '/jack/connect', 'ss', a, b)
end
end
end
function clone_graph()
graph = {}
uplink(0, '/jack/ports', '')
end
methods = {
['/jack/ports'] = function(time, fmt, ...)
for _, v in ipairs({...}) do
graph[v] = {}
uplink(0, '/jack/connections', 's', v)
end
end,
['/jack/connections'] = function(time, fmt, port, ...)
for _, v in ipairs({...}) do
graph[port][v] = true
end
update_plumbing()
end,
['/jack/client/registration'] = function(time, fmt, name, state)
--
end,
['/jack/port/registration'] = function(time, fmt, name, state)
if state then
graph[name] = {}
uplink(0, '/jack/connections', 's', name)
else
graph[name] = nil
end
end,
['/jack/port/connect'] = function(time, fmt, name_a, name_b, state)
graph[name_a][name_b] = state
end,
['/jack/port/rename'] = function(time, fmt, name_old, name_new)
graph[name_new] = graph[name_old]
graph[name_old] = nil
for k, v in pairs(graph) do
if v[name_old] then
v[name_new] = v[name_old]
v[name_old] = nil
end
end
update_plumbing()
end,
['/jack/graph/order'] = function(time)
--
end
}
uplink = plugin('uplink', function(time, path, fmt, ...)
message(time, path, fmt, ...)
local cb = methods[path]
if cb then
cb(time, fmt, ...)
end
end)
clone_graph()
|
#!/usr/local/bin/tjost -i
--[[
-- Copyright (c) 2014 Hanspeter Portner (dev@open-music-kontrollers.ch)
--
-- This software is provided 'as-is', without any express or implied
-- warranty. In no event will the authors be held liable for any damages
-- arising from the use of this software.
--
-- Permission is granted to anyone to use this software for any purpose,
-- including commercial applications, and to alter it and redistribute it
-- freely, subject to the following restrictions:
--
-- 1. The origin of this software must not be misrepresented; you must not
-- claim that you wrote the original software. If you use this software
-- in a product, an acknowledgment in the product documentation would be
-- appreciated but is not required.
--
-- 2. Altered source versions must be plainly marked as such, and must not be
-- misrepresented as being the original software.
--
-- 3. This notice may not be removed or altered from any source
-- distribution.
--]]
message = plugin('dump')
graph = {}
rules = {
{'system:capture_1', 'system:playback_1'},
{'system:capture_2', 'system:playback_2'}
}
function update_plumbing()
for _, v in ipairs(rules) do
local a = v[1]
local b = v[2]
if graph[a] and graph[b] and (not graph[a][b]) then
uplink(0, '/jack/connect', 'ss', a, b)
end
end
end
function clone_graph()
graph = {}
uplink(0, '/jack/ports', '')
end
methods = {
['/jack/ports'] = function(time, fmt, ...)
for _, v in ipairs({...}) do
graph[v] = {}
uplink(0, '/jack/connections', 's', v)
end
end,
['/jack/connections'] = function(time, fmt, port, ...)
for _, v in ipairs({...}) do
graph[port][v] = true
end
update_plumbing()
end,
['/jack/client/registration'] = function(time, fmt, name, state)
--
end,
['/jack/port/registration'] = function(time, fmt, name, state)
if state then
graph[name] = {}
uplink(0, '/jack/connections', 's', name)
else
graph[name] = nil
end
end,
['/jack/port/connect'] = function(time, fmt, name_a, name_b, state)
graph[name_a][name_b] = state
if not state then
update_plumbing()
end
end,
['/jack/port/rename'] = function(time, fmt, name_old, name_new)
graph[name_new] = graph[name_old]
graph[name_old] = nil
for k, v in pairs(graph) do
if v[name_old] then
v[name_new] = v[name_old]
v[name_old] = nil
end
end
end,
['/jack/graph/order'] = function(time)
--
end
}
uplink = plugin('uplink', function(time, path, fmt, ...)
message(time, path, fmt, ...)
local cb = methods[path]
if cb then
cb(time, fmt, ...)
end
end)
clone_graph()
|
bug fixes in plumber and uplink
|
bug fixes in plumber and uplink
|
Lua
|
artistic-2.0
|
OpenMusicKontrollers/chimaera_tjost
|
ec4a04fd7bb3e83169ff3042cb47c7ea09269b96
|
src_trunk/resources/tow-system/c_towing_system.lua
|
src_trunk/resources/tow-system/c_towing_system.lua
|
local ped = createPed(123, 224.0537109375, 112.4599609375, 1010.2117919922)
local ped2 = createPed(123, 1025.2021484375, -901.103515625, 41.983009338379)
setElementInterior(ped, 10)
setElementDimension(ped, 9001)
setPedRotation(ped2, 180)
addEventHandler("onClientPedDamage", ped, cancelEvent)
addEventHandler("onClientPedDamage", ped2, cancelEvent)
local vehElements = {}
car, wImpound, bClose, bRelease, gCars, lCost, IDcolumn = nil
function showImpoundUI(vehElementsret)
local width, height = 400, 200
local scrWidth, scrHeight = guiGetScreenSize()
local x = scrWidth - width
local y = scrHeight/10
wImpound = guiCreateWindow(x, y, width, height, "Impound: Release a vehicle", false)
guiWindowSetSizable(wImpound, false)
bClose = guiCreateButton(0.6, 0.85, 0.2, 0.1, "Close", true, wImpound)
bRelease = guiCreateButton(0.825, 0.85, 0.2, 0.1, "Release", true, wImpound)
addEventHandler("onClientGUIClick", bClose, hideImpoundUI, false)
addEventHandler("onClientGUIClick", bRelease, releaseCar, false)
gCars = guiCreateGridList(0.05, 0.1, 0.9, 0.65, true, wImpound)
addEventHandler("onClientGUIClick", gCars, updateCar, false)
local col = guiGridListAddColumn(gCars, "Impounded Vehicles", 0.7)
IDcolumn = guiGridListAddColumn(gCars, "ID", 0.2)
vehElements = vehElementsret
for key, value in ipairs(vehElements) do
local dbid = getElementData(value, "dbid")
local row = guiGridListAddRow(gCars)
guiGridListSetItemText(gCars, row, col, getVehicleName(value), false, false)
guiGridListSetItemText(gCars, row, IDcolumn, tostring(dbid), false, false)
end
guiGridListSetSelectedItem(gCars, 0, 1)
lCost = guiCreateLabel(0.3, 0.85, 0.2, 0.1, "Cost: 75$", true, wImpound)
guiSetFont(lCost, "default-bold-small")
updateCar()
guiSetInputEnabled(true)
outputChatBox("Welcome to The Impound lot.")
end
function updateCar()
local row, col = guiGridListGetSelectedItem(gCars)
if (row~=-1) and (col~=-1) then
guiSetText(lCost, "Cost: 75$")
local money = getElementData(getLocalPlayer(), "money")
if (75>money and exports.global:cdoesPlayerHaveItem(getLocalPlayer(), 3, guiGridListGetItemText(gCars, row, IDcolumn))) then
guiLabelSetColor(lCost, 255, 0, 0)
guiSetEnabled(bRelease, false)
else
guiLabelSetColor(lCost, 0, 255, 0)
guiSetEnabled(bRelease, true)
end
else
guiSetEnabled(bRelease, false)
end
end
function hideImpoundUI()
destroyElement(bClose)
bClose = nil
destroyElement(bRelease)
bRelease = nil
destroyElement(wImpound)
wImpound = nil
--removeEventHandler("onClientRender", getRootElement(), rotateCar)
setCameraTarget(getLocalPlayer())
guiSetInputEnabled(false)
end
function releaseCar(button)
if (button=="left") then
local row = guiGridListGetSelectedItem(gCars)
hideImpoundUI()
triggerServerEvent("releaseCar", getLocalPlayer(), vehElements[row+1])
end
end
addEvent("ShowImpound", true)
addEventHandler("ShowImpound", getRootElement(), showImpoundUI)
|
local ped = createPed(123, 224.0537109375, 112.4599609375, 1010.2117919922)
local ped2 = createPed(123, 1025.2021484375, -901.103515625, 41.983009338379)
setElementInterior(ped, 10)
setElementDimension(ped, 9001)
setPedRotation(ped2, 180)
addEventHandler("onClientPedDamage", ped, cancelEvent)
addEventHandler("onClientPedDamage", ped2, cancelEvent)
local vehElements = {}
car, wImpound, bClose, bRelease, gCars, lCost, IDcolumn = nil
function showImpoundUI(vehElementsret)
if not wImpound then
local width, height = 400, 200
local scrWidth, scrHeight = guiGetScreenSize()
local x = scrWidth - width
local y = scrHeight/10
wImpound = guiCreateWindow(x, y, width, height, "Impound: Release a vehicle", false)
guiWindowSetSizable(wImpound, false)
bClose = guiCreateButton(0.6, 0.85, 0.2, 0.1, "Close", true, wImpound)
bRelease = guiCreateButton(0.825, 0.85, 0.2, 0.1, "Release", true, wImpound)
addEventHandler("onClientGUIClick", bClose, hideImpoundUI, false)
addEventHandler("onClientGUIClick", bRelease, releaseCar, false)
gCars = guiCreateGridList(0.05, 0.1, 0.9, 0.65, true, wImpound)
addEventHandler("onClientGUIClick", gCars, updateCar, false)
local col = guiGridListAddColumn(gCars, "Impounded Vehicles", 0.7)
IDcolumn = guiGridListAddColumn(gCars, "ID", 0.2)
vehElements = vehElementsret
for key, value in ipairs(vehElements) do
local dbid = getElementData(value, "dbid")
local row = guiGridListAddRow(gCars)
guiGridListSetItemText(gCars, row, col, getVehicleName(value), false, false)
guiGridListSetItemText(gCars, row, IDcolumn, tostring(dbid), false, false)
end
guiGridListSetSelectedItem(gCars, 0, 1)
lCost = guiCreateLabel(0.3, 0.85, 0.2, 0.1, "Cost: 75$", true, wImpound)
guiSetFont(lCost, "default-bold-small")
updateCar()
guiSetInputEnabled(true)
outputChatBox("Welcome to The Impound lot.")
end
end
function updateCar()
local row, col = guiGridListGetSelectedItem(gCars)
if (row~=-1) and (col~=-1) then
guiSetText(lCost, "Cost: 75$")
local money = getElementData(getLocalPlayer(), "money")
if (75>money and exports.global:cdoesPlayerHaveItem(getLocalPlayer(), 3, guiGridListGetItemText(gCars, row, IDcolumn))) then
guiLabelSetColor(lCost, 255, 0, 0)
guiSetEnabled(bRelease, false)
else
guiLabelSetColor(lCost, 0, 255, 0)
guiSetEnabled(bRelease, true)
end
else
guiSetEnabled(bRelease, false)
end
end
function hideImpoundUI()
destroyElement(bClose)
bClose = nil
destroyElement(bRelease)
bRelease = nil
destroyElement(wImpound)
wImpound = nil
--removeEventHandler("onClientRender", getRootElement(), rotateCar)
setCameraTarget(getLocalPlayer())
guiSetInputEnabled(false)
end
function releaseCar(button)
if (button=="left") then
local row = guiGridListGetSelectedItem(gCars)
hideImpoundUI()
triggerServerEvent("releaseCar", getLocalPlayer(), vehElements[row+1])
end
end
addEvent("ShowImpound", true)
addEventHandler("ShowImpound", getRootElement(), showImpoundUI)
|
fixed impound gui showing multiple times
|
fixed impound gui showing multiple times
git-svn-id: 8769cb08482c9977c94b72b8e184ec7d2197f4f7@993 64450a49-1f69-0410-a0a2-f5ebb52c4f5b
|
Lua
|
bsd-3-clause
|
valhallaGaming/uno,valhallaGaming/uno,valhallaGaming/uno
|
5a52226dfcaee336d58ae34eb589242cfa19db23
|
lexers/tcl.lua
|
lexers/tcl.lua
|
-- Copyright 2006-2010 Mitchell mitchell<att>caladbolg.net. See LICENSE.
-- TCL LPeg lexer
local l = lexer
local token, style, color, word_match = l.token, l.style, l.color, l.word_match
local P, R, S = l.lpeg.P, l.lpeg.R, l.lpeg.S
module(...)
local ws = token(l.WHITESPACE, l.space^1)
-- comments
local comment = token(l.COMMENT, '#' * l.nonnewline^0)
-- strings
local sq_str = l.delimited_range("'", '\\', true, false, '\n')
local dq_str = l.delimited_range('"', '\\', true, false, '\n')
local regex = l.delimited_range('/', '\\', false, false, '\n')
local string = token(l.STRING, sq_str + dq_str + regex)
-- numbers
local number = token(l.NUMBER, l.float + l.integer)
-- keywords
local keyword = token(l.KEYWORD, word_match {
'string', 'subst', 'regexp', 'regsub', 'scan', 'format', 'binary', 'list',
'split', 'join', 'concat', 'llength', 'lrange', 'lsearch', 'lreplace',
'lindex', 'lsort', 'linsert', 'lrepeat', 'dict', 'if', 'else', 'elseif',
'then', 'for', 'foreach', 'switch', 'case', 'while', 'continue', 'return',
'break', 'catch', 'error', 'eval', 'uplevel', 'after', 'update', 'vwait',
'proc', 'rename', 'set', 'lset', 'lassign', 'unset', 'namespace', 'variable',
'upvar', 'global', 'trace', 'array', 'incr', 'append', 'lappend', 'expr',
'file', 'open', 'close', 'socket', 'fconfigure', 'puts', 'gets', 'read',
'seek', 'tell', 'eof', 'flush', 'fblocked', 'fcopy', 'fileevent', 'source',
'load', 'unload', 'package', 'info', 'interp', 'history', 'bgerror',
'unknown', 'memory', 'cd', 'pwd', 'clock', 'time', 'exec', 'glob', 'pid',
'exit'
})
-- identifiers
local identifier = token(l.IDENTIFIER, l.word)
-- variables
local variable = token(l.VARIABLE, S('$@') * P('$')^-1 * l.word)
-- operators
local operator = token(l.OPERATOR, S('<>=+-*/!@|&.,:;?()[]{}'))
_rules = {
{ 'whitespace', ws },
{ 'keyword', keyword },
{ 'identifier', identifier },
{ 'string', string },
{ 'comment', comment },
{ 'number', number },
{ 'variable', variable },
{ 'operator', operator },
{ 'any_char', l.any_char },
}
|
-- Copyright 2006-2010 Mitchell mitchell<att>caladbolg.net. See LICENSE.
-- TCL LPeg lexer
local l = lexer
local token, style, color, word_match = l.token, l.style, l.color, l.word_match
local P, R, S = l.lpeg.P, l.lpeg.R, l.lpeg.S
module(...)
local ws = token(l.WHITESPACE, l.space^1)
-- comments
local comment = token(l.COMMENT, '#' * P(function(input, index)
local i = index - 2
while i > 0 and input:find('^[ \t]', i) do i = i - 1 end
if i < 1 or input:find('^[\r\n;]', i) then return index end
end) * l.nonnewline^0)
-- strings
local sq_str = l.delimited_range("'", '\\', true, false, '\n')
local dq_str = l.delimited_range('"', '\\', true, false, '\n')
local regex = l.delimited_range('/', '\\', false, false, '\n')
local string = token(l.STRING, sq_str + dq_str + regex)
-- numbers
local number = token(l.NUMBER, l.float + l.integer)
-- keywords
local keyword = token(l.KEYWORD, word_match {
'string', 'subst', 'regexp', 'regsub', 'scan', 'format', 'binary', 'list',
'split', 'join', 'concat', 'llength', 'lrange', 'lsearch', 'lreplace',
'lindex', 'lsort', 'linsert', 'lrepeat', 'dict', 'if', 'else', 'elseif',
'then', 'for', 'foreach', 'switch', 'case', 'while', 'continue', 'return',
'break', 'catch', 'error', 'eval', 'uplevel', 'after', 'update', 'vwait',
'proc', 'rename', 'set', 'lset', 'lassign', 'unset', 'namespace', 'variable',
'upvar', 'global', 'trace', 'array', 'incr', 'append', 'lappend', 'expr',
'file', 'open', 'close', 'socket', 'fconfigure', 'puts', 'gets', 'read',
'seek', 'tell', 'eof', 'flush', 'fblocked', 'fcopy', 'fileevent', 'source',
'load', 'unload', 'package', 'info', 'interp', 'history', 'bgerror',
'unknown', 'memory', 'cd', 'pwd', 'clock', 'time', 'exec', 'glob', 'pid',
'exit'
})
-- identifiers
local identifier = token(l.IDENTIFIER, l.word)
-- variables
local variable = token(l.VARIABLE, S('$@') * P('$')^-1 * l.word)
-- operators
local operator = token(l.OPERATOR, S('<>=+-*/!@|&.,:;?()[]{}'))
_rules = {
{ 'whitespace', ws },
{ 'keyword', keyword },
{ 'identifier', identifier },
{ 'string', string },
{ 'comment', comment },
{ 'number', number },
{ 'variable', variable },
{ 'operator', operator },
{ 'any_char', l.any_char },
}
|
Fixed comments in Tcl lexer; lexers/tcl.lua
|
Fixed comments in Tcl lexer; lexers/tcl.lua
|
Lua
|
mit
|
rgieseke/scintillua
|
0067f6b077b20f30e50f0e96dc1ede4d392dd510
|
resources/prosody-plugins/mod_muc_allowners.lua
|
resources/prosody-plugins/mod_muc_allowners.lua
|
local filters = require 'util.filters';
local jid = require "util.jid";
local jid_bare = require "util.jid".bare;
local um_is_admin = require "core.usermanager".is_admin;
local util = module:require "util";
local is_healthcheck_room = util.is_healthcheck_room;
local extract_subdomain = util.extract_subdomain;
local presence_check_status = util.presence_check_status;
local MUC_NS = 'http://jabber.org/protocol/muc';
local moderated_subdomains;
local moderated_rooms;
local function load_config()
moderated_subdomains = module:get_option_set("allowners_moderated_subdomains", {})
moderated_rooms = module:get_option_set("allowners_moderated_rooms", {})
end
load_config();
local function is_admin(jid)
return um_is_admin(jid, module.host);
end
-- List of the bare_jids of all occupants that are currently joining (went through pre-join) and will be promoted
-- as moderators. As pre-join (where added) and joined event (where removed) happen one after another this list should
-- have length of 1
local joining_moderator_participants = {};
-- Checks whether the jid is moderated, the room name is in moderated_rooms
-- or if the subdomain is in the moderated_subdomains
-- @return returns on of the:
-- -> false
-- -> true, room_name, subdomain
-- -> true, room_name, nil (if no subdomain is used for the room)
local function is_moderated(room_jid)
if moderated_subdomains:empty() and moderated_rooms:empty() then
return false;
end
local room_node = jid.node(room_jid);
-- parses bare room address, for multidomain expected format is:
-- [subdomain]roomName@conference.domain
local target_subdomain, target_room_name = extract_subdomain(room_node);
if target_subdomain then
if moderated_subdomains:contains(target_subdomain) then
return true, target_room_name, target_subdomain;
end
elseif moderated_rooms:contains(room_node) then
return true, room_node, nil;
end
return false;
end
module:hook("muc-occupant-pre-join", function (event)
local room, occupant = event.room, event.occupant;
if is_healthcheck_room(room.jid) or is_admin(occupant.bare_jid) then
return;
end
local moderated, room_name, subdomain = is_moderated(room.jid);
if moderated then
local session = event.origin;
local token = session.auth_token;
if not token then
module:log('debug', 'skip allowners for non-auth user subdomain:%s room_name:%s', subdomain, room_name);
return;
end
if not (room_name == session.jitsi_meet_room or session.jitsi_meet_room == '*') then
module:log('debug', 'skip allowners for auth user and non matching room name: %s, jwt room name: %s', room_name, session.jitsi_meet_room);
return;
end
if not (subdomain == session.jitsi_meet_context_group) then
module:log('debug', 'skip allowners for auth user and non matching room subdomain: %s, jwt subdomain: %s', subdomain, session.jitsi_meet_context_group);
return;
end
end
-- mark this participant that it will be promoted and is currently joining
joining_moderator_participants[occupant.bare_jid] = true;
end, 2);
module:hook("muc-occupant-joined", function (event)
local room, occupant = event.room, event.occupant;
local promote_to_moderator = joining_moderator_participants[occupant.bare_jid];
-- clear it
joining_moderator_participants[occupant.bare_jid] = nil;
if promote_to_moderator ~= nil then
room:set_affiliation(true, occupant.bare_jid, "owner");
end
end, 2);
module:hook("muc-occupant-left", function (event)
local room, occupant = event.room, event.occupant;
if is_healthcheck_room(room.jid) then
return;
end
room:set_affiliation(true, occupant.bare_jid, nil);
end, 2);
module:hook_global('config-reloaded', load_config);
-- Filters self-presences to a jid that exist in joining_participants array
-- We want to filter those presences where we send first `participant` and just after it `moderator`
function filter_stanza(stanza)
-- when joining_moderator_participants is empty there is nothing to filter
if next(joining_moderator_participants) == nil or not stanza.attr or not stanza.attr.to or stanza.name ~= "presence" then
return stanza;
end
local muc_x = stanza:get_child('x', MUC_NS..'#user');
if not muc_x then
return stanza;
end
local bare_to = jid_bare(stanza.attr.to);
if joining_moderator_participants[bare_to] and presence_check_status(muc_x, '110') then
-- skip the local presence for participant
return nil;
end
-- skip sending the 'participant' presences to all other people in the room
for item in muc_x:childtags('item') do
if joining_moderator_participants[jid_bare(item.attr.jid)] then
return nil;
end
end
return stanza;
end
function filter_session(session)
-- domain mapper is filtering on default priority 0, and we need it after that
filters.add_filter(session, 'stanzas/out', filter_stanza, -1);
end
-- enable filtering presences
filters.add_filter_hook(filter_session);
|
local filters = require 'util.filters';
local jid = require "util.jid";
local jid_bare = require "util.jid".bare;
local jid_host = require "util.jid".host;
local um_is_admin = require "core.usermanager".is_admin;
local util = module:require "util";
local is_healthcheck_room = util.is_healthcheck_room;
local extract_subdomain = util.extract_subdomain;
local presence_check_status = util.presence_check_status;
local MUC_NS = 'http://jabber.org/protocol/muc';
local moderated_subdomains;
local moderated_rooms;
local function load_config()
moderated_subdomains = module:get_option_set("allowners_moderated_subdomains", {})
moderated_rooms = module:get_option_set("allowners_moderated_rooms", {})
end
load_config();
local function is_admin(jid)
return um_is_admin(jid, module.host);
end
-- List of the bare_jids of all occupants that are currently joining (went through pre-join) and will be promoted
-- as moderators. As pre-join (where added) and joined event (where removed) happen one after another this list should
-- have length of 1
local joining_moderator_participants = {};
-- Checks whether the jid is moderated, the room name is in moderated_rooms
-- or if the subdomain is in the moderated_subdomains
-- @return returns on of the:
-- -> false
-- -> true, room_name, subdomain
-- -> true, room_name, nil (if no subdomain is used for the room)
local function is_moderated(room_jid)
if moderated_subdomains:empty() and moderated_rooms:empty() then
return false;
end
local room_node = jid.node(room_jid);
-- parses bare room address, for multidomain expected format is:
-- [subdomain]roomName@conference.domain
local target_subdomain, target_room_name = extract_subdomain(room_node);
if target_subdomain then
if moderated_subdomains:contains(target_subdomain) then
return true, target_room_name, target_subdomain;
end
elseif moderated_rooms:contains(room_node) then
return true, room_node, nil;
end
return false;
end
module:hook("muc-occupant-pre-join", function (event)
local room, occupant = event.room, event.occupant;
if is_healthcheck_room(room.jid) or is_admin(occupant.bare_jid) then
return;
end
local moderated, room_name, subdomain = is_moderated(room.jid);
if moderated then
local session = event.origin;
local token = session.auth_token;
if not token then
module:log('debug', 'skip allowners for non-auth user subdomain:%s room_name:%s', subdomain, room_name);
return;
end
if not (room_name == session.jitsi_meet_room or session.jitsi_meet_room == '*') then
module:log('debug', 'skip allowners for auth user and non matching room name: %s, jwt room name: %s', room_name, session.jitsi_meet_room);
return;
end
if not (subdomain == session.jitsi_meet_context_group) then
module:log('debug', 'skip allowners for auth user and non matching room subdomain: %s, jwt subdomain: %s', subdomain, session.jitsi_meet_context_group);
return;
end
end
-- mark this participant that it will be promoted and is currently joining
joining_moderator_participants[occupant.bare_jid] = true;
end, 2);
module:hook("muc-occupant-joined", function (event)
local room, occupant = event.room, event.occupant;
local promote_to_moderator = joining_moderator_participants[occupant.bare_jid];
-- clear it
joining_moderator_participants[occupant.bare_jid] = nil;
if promote_to_moderator ~= nil then
room:set_affiliation(true, occupant.bare_jid, "owner");
end
end, 2);
module:hook("muc-occupant-left", function (event)
local room, occupant = event.room, event.occupant;
if is_healthcheck_room(room.jid) then
return;
end
room:set_affiliation(true, occupant.bare_jid, nil);
end, 2);
module:hook_global('config-reloaded', load_config);
-- Filters self-presences to a jid that exist in joining_participants array
-- We want to filter those presences where we send first `participant` and just after it `moderator`
function filter_stanza(stanza)
-- when joining_moderator_participants is empty there is nothing to filter
if next(joining_moderator_participants) == nil or not stanza.attr or not stanza.attr.to or stanza.name ~= "presence" then
return stanza;
end
-- we want to filter presences only on this host for allowners and skip anything like lobby etc.
local host_from = jid_host(stanza.attr.from);
if host_from ~= module.host then
return stanza;
end
local bare_to = jid_bare(stanza.attr.to);
if stanza:get_error() and joining_moderator_participants[bare_to] then
-- pre-join succeeded but joined did not so we need to clear cache
joining_moderator_participants[bare_to] = nil;
return stanza;
end
local muc_x = stanza:get_child('x', MUC_NS..'#user');
if not muc_x then
return stanza;
end
if joining_moderator_participants[bare_to] and presence_check_status(muc_x, '110') then
-- skip the local presence for participant
return nil;
end
-- skip sending the 'participant' presences to all other people in the room
for item in muc_x:childtags('item') do
if joining_moderator_participants[jid_bare(item.attr.jid)] then
return nil;
end
end
return stanza;
end
function filter_session(session)
-- domain mapper is filtering on default priority 0, and we need it after that
filters.add_filter(session, 'stanzas/out', filter_stanza, -1);
end
-- enable filtering presences
filters.add_filter_hook(filter_session);
|
fix: Fixes lobby when allowners is enabled.
|
fix: Fixes lobby when allowners is enabled.
|
Lua
|
apache-2.0
|
jitsi/jitsi-meet,gpolitis/jitsi-meet,jitsi/jitsi-meet,jitsi/jitsi-meet,jitsi/jitsi-meet,gpolitis/jitsi-meet,gpolitis/jitsi-meet,gpolitis/jitsi-meet,jitsi/jitsi-meet,gpolitis/jitsi-meet,jitsi/jitsi-meet,jitsi/jitsi-meet,gpolitis/jitsi-meet,jitsi/jitsi-meet,gpolitis/jitsi-meet,gpolitis/jitsi-meet
|
bb80490723e1dad6731ab19419681744b0eba047
|
src/remy/cgilua.lua
|
src/remy/cgilua.lua
|
-- Remy - CGI-Lua compatibility
-- Copyright (c) 2014 Felipe Daragon
-- License: MIT
require "base64"
-- TODO: implement all functions from mod_lua's request_rec
local request = {
-- ENCODING/DECODING FUNCTIONS
base64_decode = function(_,...) return base64.decode(...) end,
base64_encode = function(_,...) return base64.encode(...) end,
escape = function(_,...) return cgilua.urlcode.escape(...) end,
unescape = function(_,...) return cgilua.urlcode.unescape(...) end,
-- REQUEST PARSING FUNCTIONS
parseargs = function(_) return cgilua.QUERY, {} end,
parsebody = function(_) return cgilua.POST, {} end,
-- REQUEST RESPONSE FUNCTIONS
--puts = function(_,...) cgilua.put(...) end,
--write = function(_,...) cgilua.print(...) end
puts = function(_,...) remy.print(...) end,
write = function(_,...) remy.print(...) end
}
local M = {
mode = "cgilua",
request = request
}
function M.init()
local r = request
local query = cgilua.servervariable("QUERY_STRING")
local port = cgilua.servervariable("SERVER_PORT")
local server_name = cgilua.servervariable("SERVER_NAME")
local path_info = M.getpathinfo()
apache2.version = cgilua.servervariable("SERVER_SOFTWARE")
r = remy.loadrequestrec(r)
r.ap_auth_type = cgilua.servervariable("AUTH_TYPE")
if query ~= nil and query ~= '' then
r.args = query
end
r.banner = apache2.version
r.canonical_filename = cgilua.script_path
r.content_type = "text/html" -- CGILua needs a default content_type
r.context_document_root = cgilua.script_pdir
r.document_root = cgilua.script_pdir
r.filename = cgilua.script_path
r.hostname = server_name
r.method = cgilua.servervariable("REQUEST_METHOD")
r.path_info = path_info
if port ~= nil then
r.port = tonumber(port)
if r.port == 443 then
r.is_https = true
end
end
r.protocol = cgilua.servervariable("SERVER_PROTOCOL")
r.range = cgilua.servervariable("HTTP_RANGE")
r.server_name = server_name
r.started = os.time()
r.the_request = r.method..' '..M.getunparseduri()..' '..r.protocol
r.unparsed_uri = M.getunparseduri()
r.uri = path_info
r.user = cgilua.servervariable("REMOTE_USER")
r.useragent_ip = cgilua.servervariable("REMOTE_ADDR")
end
function M.getpathinfo()
-- Xavante compatibility fix (Etiene)
if cgilua.servervariable("SERVER_NAME") == "" then
-- By default, Xavante will have an empty server name
-- A more accurate detection method is needed here
local p = cgilua.urlpath
end
local p = cgilua.servervariable("PATH_INFO")
if p == nil then
p = cgilua.servervariable("SCRIPT_NAME")
end
return p
end
function M.getunparseduri()
local uri = M.getpathinfo()
local query = cgilua.servervariable("QUERY_STRING")
if query ~= nil and query ~= '' then
uri = uri..'?'..query
end
return uri
end
function M.contentheader(content_type)
local r = request
r.content_type = content_type
end
-- TODO: better handle the return code
function M.finish(code)
local r = request
-- Handle page redirect
local location = r.headers_out['Location']
if location ~= nil and r.status == 302 then
if location:match('^https?://') then
cgilua.redirect(location)
else
-- CGILua needs a full URL
if r.is_https then
location = 'https://'..cgilua.servervariable("HTTP_HOST")..location
else
location = 'http://'..cgilua.servervariable("HTTP_HOST")..location
end
cgilua.redirect(location)
end
end
-- Prints the response text (if any)
if r.content_type == "text/html" then
cgilua.htmlheader()
else
local header_sep = "/"
local header_type = remy.splitstring(r.content_type,header_sep)[1]
local header_subtype = remy.splitstring(r.content_type,header_sep)[2]
cgilua.contentheader(header_type,header_subtype)
end
if remy.responsetext ~= nil then
cgilua.print(remy.responsetext)
end
end
return M
|
-- Remy - CGI-Lua compatibility
-- Copyright (c) 2014 Felipe Daragon
-- License: MIT
require "base64"
-- TODO: implement all functions from mod_lua's request_rec
local request = {
-- ENCODING/DECODING FUNCTIONS
base64_decode = function(_,...) return base64.decode(...) end,
base64_encode = function(_,...) return base64.encode(...) end,
escape = function(_,...) return cgilua.urlcode.escape(...) end,
unescape = function(_,...) return cgilua.urlcode.unescape(...) end,
-- REQUEST PARSING FUNCTIONS
parseargs = function(_) return cgilua.QUERY, {} end,
parsebody = function(_) return cgilua.POST, {} end,
-- REQUEST RESPONSE FUNCTIONS
--puts = function(_,...) cgilua.put(...) end,
--write = function(_,...) cgilua.print(...) end
puts = function(_,...) remy.print(...) end,
write = function(_,...) remy.print(...) end
}
local M = {
mode = "cgilua",
request = request
}
function M.init()
local r = request
local query = cgilua.servervariable("QUERY_STRING")
local port = cgilua.servervariable("SERVER_PORT")
local server_name = cgilua.servervariable("SERVER_NAME")
local path_info = M.getpathinfo()
apache2.version = cgilua.servervariable("SERVER_SOFTWARE")
r = remy.loadrequestrec(r)
r.ap_auth_type = cgilua.servervariable("AUTH_TYPE")
if query ~= nil and query ~= '' then
r.args = query
end
r.banner = apache2.version
r.canonical_filename = cgilua.script_path
r.content_type = "text/html" -- CGILua needs a default content_type
r.context_document_root = cgilua.script_pdir
r.document_root = cgilua.script_pdir
r.filename = cgilua.script_path
r.hostname = server_name
r.method = cgilua.servervariable("REQUEST_METHOD")
r.path_info = path_info
if port ~= nil then
r.port = tonumber(port)
if r.port == 443 then
r.is_https = true
end
end
r.protocol = cgilua.servervariable("SERVER_PROTOCOL")
r.range = cgilua.servervariable("HTTP_RANGE")
r.server_name = server_name
r.started = os.time()
r.the_request = r.method..' '..M.getunparseduri()..' '..r.protocol
r.unparsed_uri = M.getunparseduri()
r.uri = path_info
r.user = cgilua.servervariable("REMOTE_USER")
r.useragent_ip = cgilua.servervariable("REMOTE_ADDR")
end
function M.getpathinfo()
local p = cgilua.servervariable("PATH_INFO")
-- Xavante compatibility fix (Etiene)
if cgilua.servervariable("SERVER_NAME") == "" then
-- By default, Xavante will have an empty server name
-- A more accurate detection method is needed here
p = cgilua.urlpath
end
if p == nil then
p = cgilua.servervariable("SCRIPT_NAME")
end
return p
end
function M.getunparseduri()
local uri = M.getpathinfo()
local query = cgilua.servervariable("QUERY_STRING")
if query ~= nil and query ~= '' then
uri = uri..'?'..query
end
return uri
end
function M.contentheader(content_type)
local r = request
r.content_type = content_type
end
-- TODO: better handle the return code
function M.finish(code)
local r = request
-- Handle page redirect
local location = r.headers_out['Location']
if location ~= nil and r.status == 302 then
if location:match('^https?://') then
cgilua.redirect(location)
else
-- CGILua needs a full URL
if r.is_https then
location = 'https://'..cgilua.servervariable("HTTP_HOST")..location
else
location = 'http://'..cgilua.servervariable("HTTP_HOST")..location
end
cgilua.redirect(location)
end
end
-- Prints the response text (if any)
if r.content_type == "text/html" then
cgilua.htmlheader()
else
local header_sep = "/"
local header_type = remy.splitstring(r.content_type,header_sep)[1]
local header_subtype = remy.splitstring(r.content_type,header_sep)[2]
cgilua.contentheader(header_type,header_subtype)
end
if remy.responsetext ~= nil then
cgilua.print(remy.responsetext)
end
end
return M
|
Fix wrong order in CGILua getpathinfo() (compatibility mode)
|
Fix wrong order in CGILua getpathinfo() (compatibility mode)
|
Lua
|
mit
|
sailorproject/sailor,noname007/sailor,ignacio/sailor,ignacio/sailor,mpeterv/sailor,felipedaragon/sailor,hallison/sailor,felipedaragon/sailor,Etiene/sailor,mpeterv/sailor,Etiene/sailor,jeary/sailor
|
fe6209773832f15840f6a0e9309f17279da0525d
|
modules/admin-full/luasrc/model/cbi/admin_system/system.lua
|
modules/admin-full/luasrc/model/cbi/admin_system/system.lua
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2011 Jo-Philipp Wich <xm@subsignal.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
require("luci.sys")
require("luci.sys.zoneinfo")
require("luci.tools.webadmin")
require("luci.fs")
require("luci.config")
local m, s, o
local has_ntpd = luci.fs.access("/usr/sbin/ntpd")
m = Map("system", translate("System"), translate("Here you can configure the basic aspects of your device like its hostname or the timezone."))
m:chain("luci")
s = m:section(TypedSection, "system", translate("System Properties"))
s.anonymous = true
s.addremove = false
s:tab("general", translate("General Settings"))
s:tab("logging", translate("Logging"))
s:tab("language", translate("Language and Style"))
--
-- System Properties
--
o = s:taboption("general", DummyValue, "_systime", translate("Local Time"))
o.template = "admin_system/clock_status"
o = s:taboption("general", Value, "hostname", translate("Hostname"))
o.datatype = "hostname"
function o.write(self, section, value)
Value.write(self, section, value)
luci.sys.hostname(value)
end
o = s:taboption("general", ListValue, "zonename", translate("Timezone"))
o:value("UTC")
for i, zone in ipairs(luci.sys.zoneinfo.TZ) do
o:value(zone[1])
end
function o.write(self, section, value)
local function lookup_zone(title)
for _, zone in ipairs(luci.sys.zoneinfo.TZ) do
if zone[1] == title then return zone[2] end
end
end
AbstractValue.write(self, section, value)
local timezone = lookup_zone(value) or "GMT0"
self.map.uci:set("system", section, "timezone", timezone)
luci.fs.writefile("/etc/TZ", timezone .. "\n")
end
--
-- Logging
--
o = s:taboption("logging", Value, "log_size", translate("System log buffer size"), "kiB")
o.optional = true
o.placeholder = 16
o.datatype = "uinteger"
o = s:taboption("logging", Value, "log_ip", translate("External system log server"))
o.optional = true
o.placeholder = "0.0.0.0"
o.datatype = "ip4addr"
o = s:taboption("logging", Value, "log_port", translate("External system log server port"))
o.optional = true
o.placeholder = 514
o.datatype = "port"
o = s:taboption("logging", ListValue, "conloglevel", translate("Log output level"))
o:value(8, translate("Debug"))
o:value(7, translate("Info"))
o:value(6, translate("Notice"))
o:value(5, translate("Warning"))
o:value(4, translate("Error"))
o:value(3, translate("Critical"))
o:value(2, translate("Alert"))
o:value(1, translate("Emergency"))
o = s:taboption("logging", ListValue, "cronloglevel", translate("Cron Log Level"))
o.default = 8
o:value(5, translate("Debug"))
o:value(8, translate("Normal"))
o:value(9, translate("Warning"))
--
-- Langauge & Style
--
o = s:taboption("language", ListValue, "_lang", translate("Language"))
o:value("auto")
local i18ndir = luci.i18n.i18ndir .. "base."
for k, v in luci.util.kspairs(luci.config.languages) do
local file = i18ndir .. k:gsub("_", "-")
if k:sub(1, 1) ~= "." and luci.fs.access(file .. ".lmo") then
o:value(k, v)
end
end
function o.cfgvalue(...)
return m.uci:get("luci", "main", "lang")
end
function o.write(self, section, value)
m.uci:set("luci", "main", "lang", value)
end
o = s:taboption("language", ListValue, "_mediaurlbase", translate("Design"))
for k, v in pairs(luci.config.themes) do
if k:sub(1, 1) ~= "." then
o:value(v, k)
end
end
function o.cfgvalue(...)
return m.uci:get("luci", "main", "mediaurlbase")
end
function o.write(self, section, value)
m.uci:set("luci", "main", "mediaurlbase", value)
end
--
-- NTP
--
if has_ntpd then
s = m:section(TypedSection, "timeserver", translate("Time Synchronization"))
s.anonymous = true
s.addremove = false
function m.on_parse()
local has_section = false
m.uci:foreach("system", "timeserver",
function(s)
has_section = true
return false
end)
if not has_section then
m.uci:section("system", "timeserver", "ntp")
end
end
o = s:option(Flag, "enable", translate("Enable builtin NTP server"))
o.rmempty = false
function o.cfgvalue(self)
return luci.sys.init.enabled("sysntpd")
and self.enabled or self.disabled
end
function o.write(self, section, value)
if value == self.enabled then
luci.sys.init.enable("sysntpd")
luci.sys.call("env -i /etc/init.d/sysntpd start >/dev/null")
else
luci.sys.call("env -i /etc/init.d/sysntpd stop >/dev/null")
luci.sys.init.disable("sysntpd")
end
end
o = s:option(DynamicList, "server", translate("NTP server candidates"))
o.datatype = "host"
o:depends("enable", "1")
-- retain server list even if disabled
function o.remove() end
end
return m
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2011 Jo-Philipp Wich <xm@subsignal.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
require("luci.sys")
require("luci.sys.zoneinfo")
require("luci.tools.webadmin")
require("luci.fs")
require("luci.config")
local m, s, o
local has_ntpd = luci.fs.access("/usr/sbin/ntpd")
m = Map("system", translate("System"), translate("Here you can configure the basic aspects of your device like its hostname or the timezone."))
m:chain("luci")
s = m:section(TypedSection, "system", translate("System Properties"))
s.anonymous = true
s.addremove = false
s:tab("general", translate("General Settings"))
s:tab("logging", translate("Logging"))
s:tab("language", translate("Language and Style"))
--
-- System Properties
--
o = s:taboption("general", DummyValue, "_systime", translate("Local Time"))
o.template = "admin_system/clock_status"
o = s:taboption("general", Value, "hostname", translate("Hostname"))
o.datatype = "hostname"
function o.write(self, section, value)
Value.write(self, section, value)
luci.sys.hostname(value)
end
o = s:taboption("general", ListValue, "zonename", translate("Timezone"))
o:value("UTC")
for i, zone in ipairs(luci.sys.zoneinfo.TZ) do
o:value(zone[1])
end
function o.write(self, section, value)
local function lookup_zone(title)
for _, zone in ipairs(luci.sys.zoneinfo.TZ) do
if zone[1] == title then return zone[2] end
end
end
AbstractValue.write(self, section, value)
local timezone = lookup_zone(value) or "GMT0"
self.map.uci:set("system", section, "timezone", timezone)
luci.fs.writefile("/etc/TZ", timezone .. "\n")
end
--
-- Logging
--
o = s:taboption("logging", Value, "log_size", translate("System log buffer size"), "kiB")
o.optional = true
o.placeholder = 16
o.datatype = "uinteger"
o = s:taboption("logging", Value, "log_ip", translate("External system log server"))
o.optional = true
o.placeholder = "0.0.0.0"
o.datatype = "ip4addr"
o = s:taboption("logging", Value, "log_port", translate("External system log server port"))
o.optional = true
o.placeholder = 514
o.datatype = "port"
o = s:taboption("logging", ListValue, "conloglevel", translate("Log output level"))
o:value(8, translate("Debug"))
o:value(7, translate("Info"))
o:value(6, translate("Notice"))
o:value(5, translate("Warning"))
o:value(4, translate("Error"))
o:value(3, translate("Critical"))
o:value(2, translate("Alert"))
o:value(1, translate("Emergency"))
o = s:taboption("logging", ListValue, "cronloglevel", translate("Cron Log Level"))
o.default = 8
o:value(5, translate("Debug"))
o:value(8, translate("Normal"))
o:value(9, translate("Warning"))
--
-- Langauge & Style
--
o = s:taboption("language", ListValue, "_lang", translate("Language"))
o:value("auto")
local i18ndir = luci.i18n.i18ndir .. "base."
for k, v in luci.util.kspairs(luci.config.languages) do
local file = i18ndir .. k:gsub("_", "-")
if k:sub(1, 1) ~= "." and luci.fs.access(file .. ".lmo") then
o:value(k, v)
end
end
function o.cfgvalue(...)
return m.uci:get("luci", "main", "lang")
end
function o.write(self, section, value)
m.uci:set("luci", "main", "lang", value)
end
o = s:taboption("language", ListValue, "_mediaurlbase", translate("Design"))
for k, v in pairs(luci.config.themes) do
if k:sub(1, 1) ~= "." then
o:value(v, k)
end
end
function o.cfgvalue(...)
return m.uci:get("luci", "main", "mediaurlbase")
end
function o.write(self, section, value)
m.uci:set("luci", "main", "mediaurlbase", value)
end
--
-- NTP
--
if has_ntpd then
-- timeserver setup was requested, create section and reload page
if m:formvalue("cbid.system._timeserver._enable") then
m.uci:section("system", "timeserver", "ntp")
m.uci:save("system")
luci.http.redirect(luci.dispatcher.build_url("admin/system", arg[1]))
return
end
local has_section = false
m.uci:foreach("system", "timeserver",
function(s)
has_section = true
return false
end)
if not has_section then
s = m:section(TypedSection, "timeserver", translate("Time Synchronization"))
s.anonymous = true
s.cfgsections = function() return { "_timeserver" } end
x = s:option(Button, "_enable")
x.title = translate("Time Synchronization is not configured yet.")
x.inputtitle = translate("Setup Time Synchronization")
x.inputstyle = "apply"
else
s = m:section(TypedSection, "timeserver", translate("Time Synchronization"))
s.anonymous = true
s.addremove = false
o = s:option(Flag, "enable", translate("Enable builtin NTP server"))
o.rmempty = false
function o.cfgvalue(self)
return luci.sys.init.enabled("sysntpd")
and self.enabled or self.disabled
end
function o.write(self, section, value)
if value == self.enabled then
luci.sys.init.enable("sysntpd")
luci.sys.call("env -i /etc/init.d/sysntpd start >/dev/null")
else
luci.sys.call("env -i /etc/init.d/sysntpd stop >/dev/null")
luci.sys.init.disable("sysntpd")
end
end
o = s:option(DynamicList, "server", translate("NTP server candidates"))
o.datatype = "host"
o:depends("enable", "1")
-- retain server list even if disabled
function o.remove() end
end
end
return m
|
admin-full: Better fix for the last change (timeserver setup), add button to add the missing section
|
admin-full: Better fix for the last change (timeserver setup), add button to add the missing section
|
Lua
|
apache-2.0
|
deepak78/luci,deepak78/luci,8devices/luci,deepak78/luci,deepak78/luci,deepak78/luci,8devices/luci,8devices/luci,deepak78/luci,8devices/luci,deepak78/luci,8devices/luci,8devices/luci,deepak78/luci
|
cf96cf949b33b138f03c7357072c1cbc5926a2e1
|
modules/admin-full/luasrc/model/cbi/admin_network/routes.lua
|
modules/admin-full/luasrc/model/cbi/admin_network/routes.lua
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
require("luci.tools.webadmin")
m = Map("network", translate("a_n_routes"), translate("a_n_routes1"))
local routes6 = luci.sys.net.routes6()
if not arg or not arg[1] then
local routes = luci.sys.net.routes()
v = m:section(Table, routes, translate("a_n_routes_kernel4"))
net = v:option(DummyValue, "iface", translate("network"))
function net.cfgvalue(self, section)
return luci.tools.webadmin.iface_get_network(routes[section].device)
or routes[section].device
end
target = v:option(DummyValue, "target", translate("target"))
function target.cfgvalue(self, section)
return routes[section].dest:network():string()
end
netmask = v:option(DummyValue, "netmask", translate("netmask"))
function netmask.cfgvalue(self, section)
return routes[section].dest:mask():string()
end
gateway = v:option(DummyValue, "gateway", translate("gateway"))
function gateway.cfgvalue(self, section)
return routes[section].gateway:string()
end
metric = v:option(DummyValue, "metric", translate("metric"))
function metric.cfgvalue(self, section)
return routes[section].metric
end
if routes6 then
v = m:section(Table, routes6, translate("a_n_routes_kernel6"))
net = v:option(DummyValue, "iface", translate("network"))
function net.cfgvalue(self, section)
return luci.tools.webadmin.iface_get_network(routes6[section].device)
or routes6[section].device
end
target = v:option(DummyValue, "target", translate("target"))
function target.cfgvalue(self, section)
return routes6[section].dest:string()
end
gateway = v:option(DummyValue, "gateway", translate("gateway6"))
function gateway.cfgvalue(self, section)
return routes6[section].source:string()
end
metric = v:option(DummyValue, "metric", translate("metric"))
function metric.cfgvalue(self, section)
return string.format( "%08X", routes6[section].metric )
end
end
end
s = m:section(TypedSection, "route", translate("a_n_routes_static4"))
s.addremove = true
s.anonymous = true
s.template = "cbi/tblsection"
iface = s:option(ListValue, "interface", translate("interface"))
luci.tools.webadmin.cbi_add_networks(iface)
if not arg or not arg[1] then
net.titleref = iface.titleref
end
s:option(Value, "target", translate("target"), translate("a_n_r_target1"))
s:option(Value, "netmask", translate("netmask"), translate("a_n_r_netmask1")).rmemepty = true
s:option(Value, "gateway", translate("gateway"))
if routes6 then
s = m:section(TypedSection, "route6", translate("a_n_routes_static6"))
s.addremove = true
s.anonymous = true
s.template = "cbi/tblsection"
iface = s:option(ListValue, "interface", translate("interface"))
luci.tools.webadmin.cbi_add_networks(iface)
if not arg or not arg[1] then
net.titleref = iface.titleref
end
s:option(Value, "target", translate("target"), translate("a_n_r_target6"))
s:option(Value, "gateway", translate("gateway6")).rmempty = true
end
return m
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
require("luci.tools.webadmin")
m = Map("network", translate("a_n_routes"), translate("a_n_routes1"))
local routes6 = luci.sys.net.routes6()
local bit = require "bit"
if not arg or not arg[1] then
local routes = luci.sys.net.routes()
v = m:section(Table, routes, translate("a_n_routes_kernel4"))
net = v:option(DummyValue, "iface", translate("network"))
function net.cfgvalue(self, section)
return luci.tools.webadmin.iface_get_network(routes[section].device)
or routes[section].device
end
target = v:option(DummyValue, "target", translate("target"))
function target.cfgvalue(self, section)
return routes[section].dest:network():string()
end
netmask = v:option(DummyValue, "netmask", translate("netmask"))
function netmask.cfgvalue(self, section)
return routes[section].dest:mask():string()
end
gateway = v:option(DummyValue, "gateway", translate("gateway"))
function gateway.cfgvalue(self, section)
return routes[section].gateway:string()
end
metric = v:option(DummyValue, "metric", translate("metric"))
function metric.cfgvalue(self, section)
return routes[section].metric
end
if routes6 then
v = m:section(Table, routes6, translate("a_n_routes_kernel6"))
net = v:option(DummyValue, "iface", translate("network"))
function net.cfgvalue(self, section)
return luci.tools.webadmin.iface_get_network(routes6[section].device)
or routes6[section].device
end
target = v:option(DummyValue, "target", translate("target"))
function target.cfgvalue(self, section)
return routes6[section].dest:string()
end
gateway = v:option(DummyValue, "gateway", translate("gateway6"))
function gateway.cfgvalue(self, section)
return routes6[section].source:string()
end
metric = v:option(DummyValue, "metric", translate("metric"))
function metric.cfgvalue(self, section)
local metr = routes6[section].metric
local lower = bit.band(metr, 0xffff)
local higher = bit.rshift(bit.band(metr, 0xffff0000), 16)
return "%04X%04X" % {higher, lower}
end
end
end
s = m:section(TypedSection, "route", translate("a_n_routes_static4"))
s.addremove = true
s.anonymous = true
s.template = "cbi/tblsection"
iface = s:option(ListValue, "interface", translate("interface"))
luci.tools.webadmin.cbi_add_networks(iface)
if not arg or not arg[1] then
net.titleref = iface.titleref
end
s:option(Value, "target", translate("target"), translate("a_n_r_target1"))
s:option(Value, "netmask", translate("netmask"), translate("a_n_r_netmask1")).rmemepty = true
s:option(Value, "gateway", translate("gateway"))
if routes6 then
s = m:section(TypedSection, "route6", translate("a_n_routes_static6"))
s.addremove = true
s.anonymous = true
s.template = "cbi/tblsection"
iface = s:option(ListValue, "interface", translate("interface"))
luci.tools.webadmin.cbi_add_networks(iface)
if not arg or not arg[1] then
net.titleref = iface.titleref
end
s:option(Value, "target", translate("target"), translate("a_n_r_target6"))
s:option(Value, "gateway", translate("gateway6")).rmempty = true
end
return m
|
Fixed an overflow error with IPv6 route metric
|
Fixed an overflow error with IPv6 route metric
git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@3887 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
|
Lua
|
apache-2.0
|
ReclaimYourPrivacy/cloak-luci,phi-psi/luci,projectbismark/luci-bismark,projectbismark/luci-bismark,saraedum/luci-packages-old,freifunk-gluon/luci,saraedum/luci-packages-old,alxhh/piratenluci,phi-psi/luci,jschmidlapp/luci,stephank/luci,gwlim/luci,stephank/luci,yeewang/openwrt-luci,eugenesan/openwrt-luci,alxhh/piratenluci,stephank/luci,Flexibity/luci,ThingMesh/openwrt-luci,zwhfly/openwrt-luci,jschmidlapp/luci,Flexibity/luci,phi-psi/luci,eugenesan/openwrt-luci,vhpham80/luci,jschmidlapp/luci,Canaan-Creative/luci,yeewang/openwrt-luci,eugenesan/openwrt-luci,Canaan-Creative/luci,zwhfly/openwrt-luci,vhpham80/luci,Flexibity/luci,zwhfly/openwrt-luci,gwlim/luci,8devices/carambola2-luci,8devices/carambola2-luci,dtaht/cerowrt-luci-3.3,Canaan-Creative/luci,ReclaimYourPrivacy/cloak-luci,vhpham80/luci,jschmidlapp/luci,8devices/carambola2-luci,phi-psi/luci,ReclaimYourPrivacy/cloak-luci,8devices/carambola2-luci,Canaan-Creative/luci,projectbismark/luci-bismark,ch3n2k/luci,alxhh/piratenluci,ReclaimYourPrivacy/cloak-luci,Flexibity/luci,zwhfly/openwrt-luci,alxhh/piratenluci,projectbismark/luci-bismark,ch3n2k/luci,dtaht/cerowrt-luci-3.3,ThingMesh/openwrt-luci,dtaht/cerowrt-luci-3.3,ReclaimYourPrivacy/cloak-luci,Flexibity/luci,alxhh/piratenluci,ch3n2k/luci,projectbismark/luci-bismark,phi-psi/luci,dtaht/cerowrt-luci-3.3,phi-psi/luci,ThingMesh/openwrt-luci,alxhh/piratenluci,gwlim/luci,Canaan-Creative/luci,zwhfly/openwrt-luci,eugenesan/openwrt-luci,phi-psi/luci,projectbismark/luci-bismark,vhpham80/luci,ch3n2k/luci,saraedum/luci-packages-old,yeewang/openwrt-luci,ReclaimYourPrivacy/cloak-luci,ch3n2k/luci,ThingMesh/openwrt-luci,saraedum/luci-packages-old,stephank/luci,saraedum/luci-packages-old,freifunk-gluon/luci,ReclaimYourPrivacy/cloak-luci,vhpham80/luci,alxhh/piratenluci,gwlim/luci,freifunk-gluon/luci,ch3n2k/luci,8devices/carambola2-luci,saraedum/luci-packages-old,freifunk-gluon/luci,Flexibity/luci,eugenesan/openwrt-luci,freifunk-gluon/luci,ThingMesh/openwrt-luci,gwlim/luci,dtaht/cerowrt-luci-3.3,projectbismark/luci-bismark,vhpham80/luci,freifunk-gluon/luci,eugenesan/openwrt-luci,stephank/luci,yeewang/openwrt-luci,freifunk-gluon/luci,zwhfly/openwrt-luci,yeewang/openwrt-luci,zwhfly/openwrt-luci,8devices/carambola2-luci,8devices/carambola2-luci,projectbismark/luci-bismark,Canaan-Creative/luci,Canaan-Creative/luci,gwlim/luci,ch3n2k/luci,zwhfly/openwrt-luci,jschmidlapp/luci,jschmidlapp/luci,ReclaimYourPrivacy/cloak-luci,ThingMesh/openwrt-luci,jschmidlapp/luci,yeewang/openwrt-luci,zwhfly/openwrt-luci,stephank/luci,gwlim/luci,Flexibity/luci,dtaht/cerowrt-luci-3.3,jschmidlapp/luci,freifunk-gluon/luci,Canaan-Creative/luci,ThingMesh/openwrt-luci,eugenesan/openwrt-luci,Flexibity/luci,yeewang/openwrt-luci,saraedum/luci-packages-old
|
9c88107beaf4e9f5b0bdfea803c182b35222f7f3
|
modules/admin-full/luasrc/model/cbi/admin_network/routes.lua
|
modules/admin-full/luasrc/model/cbi/admin_network/routes.lua
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
require("luci.tools.webadmin")
m = Map("network", translate("a_n_routes"), translate("a_n_routes1"))
local routes6 = luci.sys.net.routes6()
if not arg or not arg[1] then
local routes = luci.sys.net.routes()
v = m:section(Table, routes, translate("a_n_routes_kernel4"))
net = v:option(DummyValue, "iface", translate("network"))
function net.cfgvalue(self, section)
return luci.tools.webadmin.iface_get_network(routes[section].device)
or routes[section].device
end
target = v:option(DummyValue, "target", translate("target"))
function target.cfgvalue(self, section)
return routes[section].dest:network():string()
end
netmask = v:option(DummyValue, "netmask", translate("netmask"))
function netmask.cfgvalue(self, section)
return routes[section].dest:mask():string()
end
gateway = v:option(DummyValue, "gateway", translate("gateway"))
function gateway.cfgvalue(self, section)
return routes[section].gateway:string()
end
metric = v:option(DummyValue, "metric", translate("metric"))
function metric.cfgvalue(self, section)
return routes[section].metric
end
if routes6 then
v = m:section(Table, routes6, translate("a_n_routes_kernel6"))
net = v:option(DummyValue, "iface", translate("network"))
function net.cfgvalue(self, section)
return luci.tools.webadmin.iface_get_network(routes6[section].device)
or routes6[section].device
end
target = v:option(DummyValue, "target", translate("target"))
function target.cfgvalue(self, section)
return routes6[section].dest:string()
end
gateway = v:option(DummyValue, "gateway", translate("gateway6"))
function gateway.cfgvalue(self, section)
return routes6[section].source:string()
end
metric = v:option(DummyValue, "metric", translate("metric"))
function metric.cfgvalue(self, section)
return string.format( "%08X", routes6[section].metric )
end
end
end
s = m:section(TypedSection, "route", translate("a_n_routes_static4"))
s.addremove = true
s.anonymous = true
s.template = "cbi/tblsection"
iface = s:option(ListValue, "interface", translate("interface"))
luci.tools.webadmin.cbi_add_networks(iface)
if not arg or not arg[1] then
net.titleref = iface.titleref
end
s:option(Value, "target", translate("target"), translate("a_n_r_target1"))
s:option(Value, "netmask", translate("netmask"), translate("a_n_r_netmask1")).rmemepty = true
s:option(Value, "gateway", translate("gateway"))
if routes6 then
s = m:section(TypedSection, "route6", translate("a_n_routes_static6"))
s.addremove = true
s.anonymous = true
s.template = "cbi/tblsection"
iface = s:option(ListValue, "interface", translate("interface"))
luci.tools.webadmin.cbi_add_networks(iface)
if not arg or not arg[1] then
net.titleref = iface.titleref
end
s:option(Value, "target", translate("target"), translate("a_n_r_target6"))
s:option(Value, "gateway", translate("gateway6")).rmempty = true
end
return m
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
require("luci.tools.webadmin")
m = Map("network", translate("a_n_routes"), translate("a_n_routes1"))
local routes6 = luci.sys.net.routes6()
local bit = require "bit"
if not arg or not arg[1] then
local routes = luci.sys.net.routes()
v = m:section(Table, routes, translate("a_n_routes_kernel4"))
net = v:option(DummyValue, "iface", translate("network"))
function net.cfgvalue(self, section)
return luci.tools.webadmin.iface_get_network(routes[section].device)
or routes[section].device
end
target = v:option(DummyValue, "target", translate("target"))
function target.cfgvalue(self, section)
return routes[section].dest:network():string()
end
netmask = v:option(DummyValue, "netmask", translate("netmask"))
function netmask.cfgvalue(self, section)
return routes[section].dest:mask():string()
end
gateway = v:option(DummyValue, "gateway", translate("gateway"))
function gateway.cfgvalue(self, section)
return routes[section].gateway:string()
end
metric = v:option(DummyValue, "metric", translate("metric"))
function metric.cfgvalue(self, section)
return routes[section].metric
end
if routes6 then
v = m:section(Table, routes6, translate("a_n_routes_kernel6"))
net = v:option(DummyValue, "iface", translate("network"))
function net.cfgvalue(self, section)
return luci.tools.webadmin.iface_get_network(routes6[section].device)
or routes6[section].device
end
target = v:option(DummyValue, "target", translate("target"))
function target.cfgvalue(self, section)
return routes6[section].dest:string()
end
gateway = v:option(DummyValue, "gateway", translate("gateway6"))
function gateway.cfgvalue(self, section)
return routes6[section].source:string()
end
metric = v:option(DummyValue, "metric", translate("metric"))
function metric.cfgvalue(self, section)
local metr = routes6[section].metric
local lower = bit.band(metr, 0xffff)
local higher = bit.rshift(bit.band(metr, 0xffff0000), 16)
return "%04X%04X" % {higher, lower}
end
end
end
s = m:section(TypedSection, "route", translate("a_n_routes_static4"))
s.addremove = true
s.anonymous = true
s.template = "cbi/tblsection"
iface = s:option(ListValue, "interface", translate("interface"))
luci.tools.webadmin.cbi_add_networks(iface)
if not arg or not arg[1] then
net.titleref = iface.titleref
end
s:option(Value, "target", translate("target"), translate("a_n_r_target1"))
s:option(Value, "netmask", translate("netmask"), translate("a_n_r_netmask1")).rmemepty = true
s:option(Value, "gateway", translate("gateway"))
if routes6 then
s = m:section(TypedSection, "route6", translate("a_n_routes_static6"))
s.addremove = true
s.anonymous = true
s.template = "cbi/tblsection"
iface = s:option(ListValue, "interface", translate("interface"))
luci.tools.webadmin.cbi_add_networks(iface)
if not arg or not arg[1] then
net.titleref = iface.titleref
end
s:option(Value, "target", translate("target"), translate("a_n_r_target6"))
s:option(Value, "gateway", translate("gateway6")).rmempty = true
end
return m
|
Fixed an overflow error with IPv6 route metric
|
Fixed an overflow error with IPv6 route metric
git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@3887 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
|
Lua
|
apache-2.0
|
fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci
|
3935a5a40460bb4807d2108f737dd5edb86bba5c
|
dataset.lua
|
dataset.lua
|
require 'torch'
require 'image'
require 'paths'
local dataset = {}
dataset.dirs = {}
dataset.fileExtension = ""
dataset.originalScale = 64
dataset.scale = 32
dataset.nbChannels = 3
-- cache for filepaths to all images
dataset.paths = nil
-- Set one or more directories to load images from
-- @param dirs Table of directories, e.g. {"/path/to/images", "/another/path"}
function dataset.setDirs(dirs)
dataset.dirs = dirs
end
-- Set exactly one file extensions for the images.
-- Only images with that file extension will be loaded from the defined directories.
-- @param fileExtension The file extension, e.g. "jpg"-
function dataset.setFileExtension(fileExtension)
dataset.fileExtension = fileExtension
end
-- Set the width and height in pixels to which the input images will be scaled.
-- @param scale The desired width/height of the images after scaling, e.g. 32.
function dataset.setScale(scale)
dataset.scale = scale
end
-- Set the number of channels of your images, so 1 for grayscale or 3 for color.
-- If set to 1 then color images will be converted to grayscale.
-- @param nbChannels Number of channels, e.g. 1 (grayscale) or 3 (color).
function dataset.setNbChannels(nbChannels)
dataset.nbChannels = nbChannels
end
-- Load images from the dataset.
-- @param startAt Number of the first image.
-- @param count Count of the images to load.
-- @return Table of images. You can call :size() on that table to get the number of loaded images.
function dataset.loadImages(startAt, count)
local endBefore = startAt + count
local images = dataset.loadImagesFromDirs(dataset.dirs, dataset.fileExtension, startAt, count, true)
local data = torch.FloatTensor(#images, dataset.nbChannels, dataset.scale, dataset.scale)
for i=1, #images do
data[i] = image.scale(images[i], dataset.scale, dataset.scale)
end
local result = {}
result.data = data
local N = data:size(1)
function result:size()
return N
end
setmetatable(result, {
__index = function(self, index) return self.data[index] end,
__len = function(self) return self.data:size(1) end
})
print(string.format('<dataset> loaded %d examples', N))
return result
end
-- Loads a defined number of randomly selected images from
-- the cached paths (cached in loadPaths()).
-- @param count Number of random images.
-- @return List of Tensors
function dataset.loadRandomImages(count)
if dataset.paths == nil then
dataset.loadPaths()
end
local shuffle = torch.randperm(#dataset.paths)
local images = {}
for i=1,math.min(shuffle:size(1), count) do
-- load each image
table.insert(images, image.load(dataset.paths[shuffle[i]], dataset.nbChannels, "float"))
end
local data = torch.FloatTensor(#images, dataset.nbChannels, dataset.scale, dataset.scale)
for i=1, #images do
data[i] = image.scale(images[i], dataset.scale, dataset.scale)
end
--local ker = torch.ones(3)
--local m = nn.SpatialSubtractiveNormalization(1, ker)
--data = m:forward(data)
local N = data:size(1)
local result = {}
result.scaled = data
function result:size()
return N
end
setmetatable(result, {__index = function(self, index)
return self.scaled[index]
end})
print(string.format('<dataset> loaded %d random examples', N))
return result
end
-- Loads the paths of all images in the defined files
-- (with defined file extensions)
function dataset.loadPaths()
local files = {}
local dirs = dataset.dirs
local ext = dataset.fileExtension
for i=1, #dirs do
local dir = dirs[i]
-- Go over all files in directory. We use an iterator, paths.files().
for file in paths.files(dir) do
-- We only load files that match the extension
if file:find(ext .. '$') then
-- and insert the ones we care about in our table
table.insert(files, paths.concat(dir,file))
end
end
-- Check files
if #files == 0 then
error('given directory doesnt contain any files of type: ' .. ext)
end
end
print(string.format("<dataset> Loaded %d filepaths", #files))
dataset.paths = files
end
-- Loads defined range of images of given file extension from one or more directories.
-- @param dirs Tabel of directories.
-- @param ext One file extension as string.
-- @param startAt Number of first image.
-- @param count Count of images to load (max).
-- @param doSort Whether to sort the images before reducing to range [startAt:startAt+count].
-- @return Table of images, as loaded by image.load()
function dataset.loadImagesFromDirs(dirs, ext, startAt, count, doSort)
-- code from: https://github.com/andresy/torch-demos/blob/master/load-data/load-images.lua
local files = {}
for i=1, #dirs do
local dir = dirs[i]
-- Go over all files in directory. We use an iterator, paths.files().
for file in paths.files(dir) do
-- We only load files that match the extension
if file:find(ext .. '$') then
-- and insert the ones we care about in our table
table.insert(files, paths.concat(dir,file))
end
end
-- Check files
if #files == 0 then
error('given directory doesnt contain any files of type: ' .. ext)
end
end
----------------------------------------------------------------------
-- 3. Sort file names
-- We sort files alphabetically, it's quite simple with table.sort()
if doSort then
table.sort(files, function (a,b) return a < b end)
end
----------------------------------------------------------------------
-- Extract requested files from startAt to startAt+count
local filesExtracted = {}
local endAt = math.min(startAt+count-1, #files)
for i=startAt, endAt do
filesExtracted[#filesExtracted+1] = files[i]
end
----------------------------------------------------------------------
-- 4. Finally we load images
-- Go over the file list:
local images = {}
for i,file in ipairs(filesExtracted) do
-- load each image
table.insert(images, image.load(file, dataset.nbChannels, "float"))
end
return images
end
return dataset
|
require 'torch'
require 'image'
require 'paths'
local dataset = {}
dataset.dirs = {}
dataset.fileExtension = ""
dataset.originalScale = 64
dataset.scale = 32
dataset.nbChannels = 3
-- cache for filepaths to all images
dataset.paths = nil
-- Set one or more directories to load images from
-- @param dirs Table of directories, e.g. {"/path/to/images", "/another/path"}
function dataset.setDirs(dirs)
dataset.dirs = dirs
end
-- Set exactly one file extensions for the images.
-- Only images with that file extension will be loaded from the defined directories.
-- @param fileExtension The file extension, e.g. "jpg"-
function dataset.setFileExtension(fileExtension)
dataset.fileExtension = fileExtension
end
-- Set the width and height in pixels to which the input images will be scaled.
-- @param scale The desired width/height of the images after scaling, e.g. 32.
function dataset.setScale(scale)
dataset.scale = scale
end
-- Set the number of channels of your images, so 1 for grayscale or 3 for color.
-- If set to 1 then color images will be converted to grayscale.
-- @param nbChannels Number of channels, e.g. 1 (grayscale) or 3 (color).
function dataset.setNbChannels(nbChannels)
dataset.nbChannels = nbChannels
end
-- Load images from the dataset.
-- @param startAt Number of the first image.
-- @param count Count of the images to load.
-- @return Table of images. You can call :size() on that table to get the number of loaded images.
function dataset.loadImages(startAt, count)
local endBefore = startAt + count
--[[
local images = dataset.loadImagesFromDirs(dataset.dirs, dataset.fileExtension, startAt, count, true, dataset.scale)
local data = torch.FloatTensor(#images, dataset.nbChannels, dataset.scale, dataset.scale)
for i=1, #images do
data[i] = images[i]
end
--]]
local data = dataset.loadImagesFromDirs(dataset.dirs, dataset.fileExtension, startAt, count, true, dataset.scale)
local result = {}
result.data = data
local N = data:size(1)
function result:size()
return N
end
setmetatable(result, {
__index = function(self, index) return self.data[index] end,
__len = function(self) return self.data:size(1) end
})
print(string.format('<dataset> loaded %d examples', N))
return result
end
-- Loads a defined number of randomly selected images from
-- the cached paths (cached in loadPaths()).
-- @param count Number of random images.
-- @return List of Tensors
function dataset.loadRandomImages(count)
if dataset.paths == nil then
dataset.loadPaths()
end
local shuffle = torch.randperm(#dataset.paths)
local images = {}
for i=1,math.min(shuffle:size(1), count) do
-- load each image
table.insert(images, image.load(dataset.paths[shuffle[i]], dataset.nbChannels, "float"))
end
local data = torch.FloatTensor(#images, dataset.nbChannels, dataset.scale, dataset.scale)
for i=1, #images do
data[i] = image.scale(images[i], dataset.scale, dataset.scale)
end
--local ker = torch.ones(3)
--local m = nn.SpatialSubtractiveNormalization(1, ker)
--data = m:forward(data)
local N = data:size(1)
local result = {}
result.scaled = data
function result:size()
return N
end
setmetatable(result, {__index = function(self, index)
return self.scaled[index]
end})
print(string.format('<dataset> loaded %d random examples', N))
return result
end
-- Loads the paths of all images in the defined files
-- (with defined file extensions)
function dataset.loadPaths()
local files = {}
local dirs = dataset.dirs
local ext = dataset.fileExtension
for i=1, #dirs do
local dir = dirs[i]
-- Go over all files in directory. We use an iterator, paths.files().
for file in paths.files(dir) do
-- We only load files that match the extension
if file:find(ext .. '$') then
-- and insert the ones we care about in our table
table.insert(files, paths.concat(dir,file))
end
end
-- Check files
if #files == 0 then
error('given directory doesnt contain any files of type: ' .. ext)
end
end
print(string.format("<dataset> Loaded %d filepaths", #files))
dataset.paths = files
end
-- Loads defined range of images of given file extension from one or more directories.
-- @param dirs Tabel of directories.
-- @param ext One file extension as string.
-- @param startAt Number of first image.
-- @param count Count of images to load (max).
-- @param doSort Whether to sort the images before reducing to range [startAt:startAt+count].
-- @param scale Desired height/width of images.
-- @return FloatTensor
function dataset.loadImagesFromDirs(dirs, ext, startAt, count, doSort, scale)
-- code from: https://github.com/andresy/torch-demos/blob/master/load-data/load-images.lua
local files = {}
for i=1, #dirs do
local dir = dirs[i]
-- Go over all files in directory. We use an iterator, paths.files().
for file in paths.files(dir) do
-- We only load files that match the extension
if file:find(ext .. '$') then
-- and insert the ones we care about in our table
table.insert(files, paths.concat(dir,file))
end
end
-- Check files
if #files == 0 then
error('given directory doesnt contain any files of type: ' .. ext)
end
end
----------------------------------------------------------------------
-- 3. Sort file names
-- We sort files alphabetically, it's quite simple with table.sort()
if doSort then
table.sort(files, function (a,b) return a < b end)
end
----------------------------------------------------------------------
-- Extract requested files from startAt to startAt+count
local filesExtracted = {}
local endAt = math.min(startAt+count-1, #files)
for i=startAt, endAt do
filesExtracted[#filesExtracted+1] = files[i]
end
----------------------------------------------------------------------
-- 4. Finally we load images
-- Go over the file list:
local images = torch.FloatTensor(#filesExtracted, dataset.nbChannels, scale, scale)
for i,file in ipairs(filesExtracted) do
-- load each image
local img = image.load(file, dataset.nbChannels, "float")
images[i] = image.scale(img, scale, scale)
if i % 10000 == 0 then
collectgarbage()
end
end
return images
end
return dataset
|
Fix out of memory problem
|
Fix out of memory problem
|
Lua
|
mit
|
aleju/face-generator
|
8b090dcaeb77298cb01c59d6db3450e0e1e33951
|
models/upload.lua
|
models/upload.lua
|
--- A basic lower upload API
--
module(..., package.seeall)
require 'posix'
local Model = require 'bamboo.model'
local Form = require 'bamboo.form'
local function calcNewFilename(dest_dir, oldname)
-- separate the base name and extense name of a filename
local main, ext = oldname:match('^(.+)(%.%w+)$')
-- check if exists the same name file
local tstr = ''
local i = 0
while posix.stat( dest_dir + main + tstr + ext ) do
i = i + 1
tstr = '_' + tostring(i)
end
-- concat to new filename
local newbasename = main + tstr
return newbasename, ext
end
--- here, we temprorily only consider the file data is passed wholly by zeromq
-- and save by bamboo
-- @field t.req
-- @field t.file_obj
-- @field t.dest_dir
-- @field t.prefix
-- @field t.postfix
--
local function savefile(t)
local req, file_obj = t.req, t.file_obj
local monserver_dir = bamboo.config.monserver_dir
local project_name = bamboo.config.project_name
assert(monserver_dir)
assert(project_name)
local dest_dir = (t.dest_dir and monserver_dir + '/sites/' + project_name + '/uploads/' + t.dest_dir)
dest_dir = string.trailingPath(dest_dir)
local url_prefix = 'media/uploads/' + t.dest_dir + '/'
url_prefix = string.trailingPath(url_prefix)
local prefix = t.prefix or ''
local postfix = t.postfix or ''
local filename = ''
local body = ''
-- if upload in html5 way
if req.headers['x-requested-with'] then
-- when html5 upload, we think of the name of that file was stored in header x-file-name
-- if this info missing, we may consider the filename was put in the query string
filename = req.headers['x-file-name']
-- TODO:
-- req.body contains all file binary data
body = req.body
else
checkType(file_obj, 'table')
-- Notice: the filename in the form string are quoted by ""
-- this pattern rule can deal with the windows style directory delimiter
-- file_obj['content-disposition'] contains many file associated info
filename = file_obj['content-disposition'].filename:sub(2, -2):match('\\?([^\\]-%.%w+)$')
body = file_obj.body
end
if isFalse(filename) or isFalse(body) then return nil, nil end
if not posix.stat(dest_dir) then
-- why posix have no command like " mkdir -p "
os.execute('mkdir -p ' + dest_dir)
end
local newbasename, ext = calcNewFilename(dest_dir, filename)
local newname = prefix + newbasename + postfix + ext
local disk_path = dest_dir + newname
local url_path = url_prefix + newname
-- write file to disk
local fd = io.open(disk_path, "wb")
fd:write(body)
fd:close()
return disk_path, newname, url_path
end
local Upload = Model:extend {
__tag = 'Bamboo.Model.Upload';
__name = 'Upload';
__desc = "User's upload files.";
__fields = {
['name'] = {},
['path'] = {},
['size'] = {},
['timestamp'] = {},
['desc'] = {},
};
init = function (self, t)
if not t then return self end
self.name = t.name or self.name
self.path = t.url_path
self.size = posix.stat(t.path).size
self.timestamp = os.time()
-- according the current design, desc field is nil
self.desc = t.desc or ''
return self
end;
--- For traditional Html4 form upload
--
batch = function (self, req, params, dest_dir, prefix, postfix)
I_AM_CLASS(self)
local file_objs = List()
-- file data are stored as arraies in params
for i, v in ipairs(params) do
local path, name, url_path = savefile { req = req, file_obj = v, dest_dir = dest_dir, prefix = prefix, postfix = postfix }
if not path or not name then return nil end
-- create file instance
local file_instance = self { name = name, path = path, url_path = url_path }
if file_instance then
-- store to db
file_instance:save()
file_objs:append(file_instance)
end
end
-- a file object list
return file_objs
end;
process = function (self, web, req, dest_dir, prefix, postfix)
I_AM_CLASS(self)
assert(web, '[ERROR] Upload input parameter: "web" must be not nil.')
assert(req, '[ERROR] Upload input parameter: "req" must be not nil.')
-- current scheme: for those larger than PRESIZE, send a ABORT signal, and abort immediately
if req.headers['x-mongrel2-upload-start'] then
print('return blank to abort upload.')
web.conn:reply(req, '')
return nil, 'Uploading file is too large.'
end
-- if upload in html5 way
if req.headers['x-requested-with'] then
-- stored to disk
local path, name, url_path = savefile { req = req, dest_dir = dest_dir, prefix = prefix, postfix = postfix }
if not path or not name then return nil, '[ERROR] empty file.' end
local file_instance = self { name = name, path = path, url_path = url_path }
if file_instance then
file_instance:save()
return file_instance, 'single'
end
else
-- for uploading in html4 way
local params = Form:parse(req)
local files = self:batch ( req, params, dest_dir, prefix, postfix )
if not files then return nil, '[ERROR] empty file.' end
if #files == 1 then
-- even only one file upload, batch function will return a list
return files[1], 'single'
else
return files, 'multiple'
end
end
end;
calcNewFilename = function (self, dest_dir, oldname)
return calcNewFilename(dest_dir, oldname)
end;
-- this function, encorage override by child model, to execute their own delete action
specDelete = function (self)
I_AM_INSTANCE()
-- remove file from disk
os.execute('mkdir -p ' + self.path)
return self
end;
}
return Upload
|
--- A basic lower upload API
--
module(..., package.seeall)
require 'posix'
local Model = require 'bamboo.model'
local Form = require 'bamboo.form'
local function calcNewFilename(dest_dir, oldname)
-- separate the base name and extense name of a filename
local main, ext = oldname:match('^(.+)(%.%w+)$')
if not ext then
main = oldname
ext = ''
end
-- check if exists the same name file
local tstr = ''
local i = 0
while posix.stat( dest_dir + main + tstr + ext ) do
i = i + 1
tstr = '_' + tostring(i)
end
-- concat to new filename
local newbasename = main + tstr
return newbasename, ext
end
--- here, we temprorily only consider the file data is passed wholly by zeromq
-- and save by bamboo
-- @field t.req
-- @field t.file_obj
-- @field t.dest_dir
-- @field t.prefix
-- @field t.postfix
--
local function savefile(t)
local req, file_obj = t.req, t.file_obj
local monserver_dir = bamboo.config.monserver_dir
local project_name = bamboo.config.project_name
assert(monserver_dir)
assert(project_name)
local dest_dir = (t.dest_dir and monserver_dir + '/sites/' + project_name + '/uploads/' + t.dest_dir)
dest_dir = string.trailingPath(dest_dir)
local url_prefix = 'media/uploads/' + t.dest_dir + '/'
url_prefix = string.trailingPath(url_prefix)
local prefix = t.prefix or ''
local postfix = t.postfix or ''
local filename = ''
local body = ''
-- if upload in html5 way
if req.headers['x-requested-with'] then
-- when html5 upload, we think of the name of that file was stored in header x-file-name
-- if this info missing, we may consider the filename was put in the query string
filename = req.headers['x-file-name']
-- TODO:
-- req.body contains all file binary data
body = req.body
else
checkType(file_obj, 'table')
-- Notice: the filename in the form string are quoted by ""
-- this pattern rule can deal with the windows style directory delimiter
-- file_obj['content-disposition'] contains many file associated info
filename = file_obj['content-disposition'].filename:sub(2, -2):match('\\?([^\\]-%.%w+)$')
body = file_obj.body
end
if isFalse(filename) or isFalse(body) then return nil, nil end
if not posix.stat(dest_dir) then
-- why posix have no command like " mkdir -p "
os.execute('mkdir -p ' + dest_dir)
end
local newbasename, ext = calcNewFilename(dest_dir, filename)
local newname = prefix + newbasename + postfix + ext
local disk_path = dest_dir + newname
local url_path = url_prefix + newname
-- write file to disk
local fd = io.open(disk_path, "wb")
fd:write(body)
fd:close()
return disk_path, newname, url_path
end
local Upload = Model:extend {
__tag = 'Bamboo.Model.Upload';
__name = 'Upload';
__desc = "User's upload files.";
__fields = {
['name'] = {},
['path'] = {},
['size'] = {},
['timestamp'] = {},
['desc'] = {},
};
init = function (self, t)
if not t then return self end
self.name = t.name or self.name
self.path = t.url_path
self.size = posix.stat(t.path).size
self.timestamp = os.time()
-- according the current design, desc field is nil
self.desc = t.desc or ''
return self
end;
--- For traditional Html4 form upload
--
batch = function (self, req, params, dest_dir, prefix, postfix)
I_AM_CLASS(self)
local file_objs = List()
-- file data are stored as arraies in params
for i, v in ipairs(params) do
local path, name, url_path = savefile { req = req, file_obj = v, dest_dir = dest_dir, prefix = prefix, postfix = postfix }
if not path or not name then return nil end
-- create file instance
local file_instance = self { name = name, path = path, url_path = url_path }
if file_instance then
-- store to db
file_instance:save()
file_objs:append(file_instance)
end
end
-- a file object list
return file_objs
end;
process = function (self, web, req, dest_dir, prefix, postfix)
I_AM_CLASS(self)
assert(web, '[ERROR] Upload input parameter: "web" must be not nil.')
assert(req, '[ERROR] Upload input parameter: "req" must be not nil.')
-- current scheme: for those larger than PRESIZE, send a ABORT signal, and abort immediately
if req.headers['x-mongrel2-upload-start'] then
print('return blank to abort upload.')
web.conn:reply(req, '')
return nil, 'Uploading file is too large.'
end
-- if upload in html5 way
if req.headers['x-requested-with'] then
-- stored to disk
local path, name, url_path = savefile { req = req, dest_dir = dest_dir, prefix = prefix, postfix = postfix }
if not path or not name then return nil, '[ERROR] empty file.' end
local file_instance = self { name = name, path = path, url_path = url_path }
if file_instance then
file_instance:save()
return file_instance, 'single'
end
else
-- for uploading in html4 way
local params = Form:parse(req)
local files = self:batch ( req, params, dest_dir, prefix, postfix )
if not files then return nil, '[ERROR] empty file.' end
if #files == 1 then
-- even only one file upload, batch function will return a list
return files[1], 'single'
else
return files, 'multiple'
end
end
end;
calcNewFilename = function (self, dest_dir, oldname)
return calcNewFilename(dest_dir, oldname)
end;
-- this function, encorage override by child model, to execute their own delete action
specDelete = function (self)
I_AM_INSTANCE()
-- remove file from disk
os.execute('mkdir -p ' + self.path)
return self
end;
}
return Upload
|
fix a upload file bug
|
fix a upload file bug
when upload a file with no extension name, bamboo will error. Fixed it.
Signed-off-by: Daogang Tang <6435653d2db08e7863743a16df53ecbb301fb4b0@gmail.com>
|
Lua
|
bsd-3-clause
|
daogangtang/bamboo,daogangtang/bamboo
|
de45f554b46a217a522036f5cc337a816d9ce481
|
App/MyASDJourney.codea/Main.lua
|
App/MyASDJourney.codea/Main.lua
|
-- My ASD Journey
supportedOrientations(LANDSCAPE_ANY)
displayMode(FULLSCREEN_NO_BUTTONS)
-- Use this function to perform your initial setup
function setup()
math.randomseed(os.date("*t")["month"]*os.date("*t")["day"]*os.date("*t")["hour"]*os.date("*t")["min"]*os.date("*t")["sec"]*os.date("*t")["wday"])
stage = 2
stageMax = 2
bool = true
item = ""
touching = false
right_answer_position = -1
itemList = {"apple","waffle","ball","box","table"}
points = 0
face_list={vec3(0,0,0),vec3(0,0,0),vec3(0,0,0)}
face1 = vec3(0,0,0)
face2 = vec3(0,0,0)
face3=vec3(0,0,0)
speech.volume = 1
bodies = {}
wall1 = physics.body(POLYGON, vec2(20,0), vec2(0,0), vec2(0,HEIGHT), vec2(20,HEIGHT))
wall1.type = STATIC
wall2 = physics.body(POLYGON, vec2(WIDTH-(20),0), vec2(WIDTH,0), vec2(WIDTH,HEIGHT), vec2(WIDTH-(20),HEIGHT))
wall2.type = STATIC
floor = physics.body(POLYGON, vec2(0,20), vec2(0,0), vec2(WIDTH,0), vec2(WIDTH,20))
floor.type = STATIC
floor = physics.body(POLYGON, vec2(0,HEIGHT-20), vec2(0,HEIGHT), vec2(WIDTH,HEIGHT), vec2(WIDTH,HEIGHT-20))
end
--Austin make your game here
function game1()
if bool then
--Generate random vec3
face1 = vec3(math.random(1,3), math.random(1,3), math.random(1,3))
--Generate a unique second face
repeat
face2 = vec3(math.random(1,3), math.random(1,3), math.random(1,3))
until face2 ~= face1
--Generate a unique third face
repeat
face3 = vec3(math.random(1,3), math.random(1,3), math.random(1,3))
until face3 ~= face1 and face3 ~= face2
right_answer_position = math.random(1,3)
face_list={face1,face2,face3}
bool=false
end
--Draw faces
--Draw correct face in corner
--Width/14 is temporary
sprite("Project:Face"..right_answer_position, 0, HEIGHT, WIDTH/14)
sprite("Project:Nose"..right_answer_position, 0, HEIGHT, WIDTH/28)
sprite("Project:eyes"..right_answer_position, 0, HEIGHT, WIDTH/20)
--Loop through face list
for i = 1,3 do
sprite("Project:Face"..face_list[i].x,(i*WIDTH)/4,HEIGHT/6,WIDTH/14)
sprite("Project:Nose"..face_list[i].y,(i*WIDTH)/4,HEIGHT/6,WIDTH/28)
sprite("Project:eyes"..face_list[i].z,(i*WIDTH)/4,HEIGHT/6,WIDTH/20)
end
end
function nextGame()
stage = math.random(1,stageMax)
end
--In this game, the user must select the right answer to "what color is this apple?"
--while there is a lot of background noise and everything is blurred
function game2()
sound(SOUND_EXPLODE, 45885)
sound(SOUND_EXPLODE, 24166)
fontSize(20)
physics.gravity(Gravity)
if bool then
bodies = {}
table.insert(bodies,makeBox(WIDTH/30,HEIGHT/30, (WIDTH/2)-(WIDTH/15), (HEIGHT/6)-(HEIGHT/30)))
table.insert(bodies,makeBox(WIDTH/30,(HEIGHT/6)+(HEIGHT/30),(WIDTH/2)-(WIDTH/15), (HEIGHT/4)-(1.75*HEIGHT/15)))
table.insert(bodies,makeBox(WIDTH/2,HEIGHT/30, (WIDTH/2)-(WIDTH/15), (HEIGHT/6)-(HEIGHT/30)))
table.insert(bodies,makeBox(WIDTH/2,(HEIGHT/6)+(HEIGHT/30), (WIDTH/2)-(WIDTH/15), (HEIGHT/6)-(HEIGHT/30)))
item = itemList[math.random(1,5)]
--Randomly select right answer
--0|1
--2|3
right_answer_position = math.random(0,3)
if right_answer_position == 0 then
speech.say("The "..item.." is green")
elseif right_answer_position == 1 then
speech.say("The "..item.." is yellow")
elseif right_answer_position == 2 then
speech.say("The "..item.." is red")
elseif right_answer_position == 3 then
speech.say("The "..item.." is blue")
end
fontSize(45*WIDTH/1024)
end
bool = false
--Make four rectangles
draw_game2_rectangles()
fill(255)
text("What color is this "..item.."?", WIDTH/2, HEIGHT/2)
text("The "..item.." is green",WIDTH/4,HEIGHT/6+HEIGHT/8)
text("The "..item.." is yellow",WIDTH*2.85/4,HEIGHT/6+HEIGHT/8)
text("The "..item.." is red",WIDTH/4,HEIGHT/8)
text("The "..item.." is blue",WIDTH*2.85/4,HEIGHT/8)
--read touches
if CurrentTouch.state == BEGAN and touching then
touching = false
if CurrentTouch.x < WIDTH/2 then
if CurrentTouch.y < HEIGHT/6 then
if right_answer_position == 2 then
stage = 0
else
bool = true
end
elseif CurrentTouch.y < HEIGHT/6 + (HEIGHT/4)-(1.75*HEIGHT/15) then
if right_answer_position == 0 then
stage = 0
else
bool = true
end
end
else
if CurrentTouch.y < HEIGHT/6 then
if right_answer_position == 3 then
stage = 0
else
bool = true
end
elseif CurrentTouch.y < HEIGHT/6 + (HEIGHT/4)-(1.75*HEIGHT/15) then
if right_answer_position == 1 then
stage = 0
else
bool = true
end
end
end
end
if CurrentTouch.state == ENDED then
touching=true
end
end
--Draw the four rectangles for the answer choices
function draw_game2_rectangles()
rectMode(CORNER)
fill(30,30,30,160)
--Bottom left rectangleS
rect(WIDTH/30,HEIGHT/30, (WIDTH/2)-(WIDTH/15), (HEIGHT/6)-(HEIGHT/30))
--Top left rectangle
rect(WIDTH/30,(HEIGHT/6)+(HEIGHT/30), (WIDTH/2)-(WIDTH/15), (HEIGHT/4)-(1.75*HEIGHT/15))
--Bottom Right
rect(WIDTH/2,HEIGHT/30, (WIDTH/2)-(WIDTH/15), (HEIGHT/6)-(HEIGHT/30))
--Top right
rect(WIDTH/2,(HEIGHT/6)+(HEIGHT/30), (WIDTH/2)-(WIDTH/15), (HEIGHT/6)-(HEIGHT/30))
end
-- This function gets called once every frame
function draw()
-- This sets a dark background color
background(174, 174, 190, 255)
if stage == 0 then
elseif stage == 1 then
game1()
elseif stage == 2 then
--Katie make a mini game here
game2()
end
end
-- Helper function to create a box using a polygon body
function makeBox(x,y,w,h)
-- Points are defined in counter-clockwise order
local body = physics.body(POLYGON,vec2(-w/2, h/2),
vec2(-w/2, -h/2), vec2(w/2, -h/2), vec2(w/2, h/2))
-- Set the body's transform (position, angle)
body.x = x
body.y = y
-- Make movement smoother regardless of framerate
body.interpolate = true
return body
end
|
-- My ASD Journey
supportedOrientations(LANDSCAPE_ANY)
displayMode(FULLSCREEN_NO_BUTTONS)
-- Use this function to perform your initial setup
function setup()
math.randomseed(os.date("*t")["month"]*os.date("*t")["day"]*os.date("*t")["hour"]*os.date("*t")["min"]*os.date("*t")["sec"]*os.date("*t")["wday"])
stage = 2
stageMax = 2
bool = true
item = ""
touching = false
right_answer_position = -1
itemList = {"apple","waffle","ball","box","table"}
points = 0
face_list={vec3(0,0,0),vec3(0,0,0),vec3(0,0,0)}
face1 = vec3(0,0,0)
face2 = vec3(0,0,0)
face3=vec3(0,0,0)
speech.volume = 1
bodies = {}
wall1 = physics.body(POLYGON, vec2(20,0), vec2(0,0), vec2(0,HEIGHT), vec2(20,HEIGHT))
wall1.type = STATIC
wall2 = physics.body(POLYGON, vec2(WIDTH-(20),0), vec2(WIDTH,0), vec2(WIDTH,HEIGHT), vec2(WIDTH-(20),HEIGHT))
wall2.type = STATIC
floor = physics.body(POLYGON, vec2(0,20), vec2(0,0), vec2(WIDTH,0), vec2(WIDTH,20))
floor.type = STATIC
floor = physics.body(POLYGON, vec2(0,HEIGHT-20), vec2(0,HEIGHT), vec2(WIDTH,HEIGHT), vec2(WIDTH,HEIGHT-20))
end
--Austin make your game here
function game1()
if bool then
--Generate random vec3
face1 = vec3(math.random(1,3), math.random(1,3), math.random(1,3))
--Generate a unique second face
repeat
face2 = vec3(math.random(1,3), math.random(1,3), math.random(1,3))
until face2 ~= face1
--Generate a unique third face
repeat
face3 = vec3(math.random(1,3), math.random(1,3), math.random(1,3))
until face3 ~= face1 and face3 ~= face2
right_answer_position = math.random(1,3)
face_list={face1,face2,face3}
bool=false
end
--Draw faces
--Draw correct face in corner
--Width/14 is temporary
sprite("Project:Face"..right_answer_position, WIDTH/28, 7*HEIGHT/8, WIDTH/14)
sprite("Project:Nose"..right_answer_position, WIDTH/56, 7*HEIGHT/8, WIDTH/28)
sprite("Project:eyes"..right_answer_position, WIDTH/40, 7*HEIGHT/8, WIDTH/20)
--Loop through face list
for i = 1,3 do
sprite("Project:Face"..face_list[i].x,(i*WIDTH)/4,HEIGHT/6,WIDTH/14)
sprite("Project:Nose"..face_list[i].y,(i*WIDTH)/4,HEIGHT/6,WIDTH/28)
sprite("Project:eyes"..face_list[i].z,(i*WIDTH)/4,HEIGHT/6,WIDTH/20)
end
end
function nextGame()
stage = math.random(1,stageMax)
end
--In this game, the user must select the right answer to "what color is this apple?"
--while there is a lot of background noise and everything is blurred
function game2()
sound(SOUND_EXPLODE, 45885)
sound(SOUND_EXPLODE, 24166)
fontSize(20)
physics.gravity(Gravity)
if bool then
bodies = {}
table.insert(bodies,makeBox(WIDTH/30,HEIGHT/30, (WIDTH/2)-(WIDTH/15), (HEIGHT/6)-(HEIGHT/30)))
table.insert(bodies,makeBox(WIDTH/30,(HEIGHT/6)+(HEIGHT/30),(WIDTH/2)-(WIDTH/15), (HEIGHT/4)-(1.75*HEIGHT/15)))
table.insert(bodies,makeBox(WIDTH/2,HEIGHT/30, (WIDTH/2)-(WIDTH/15), (HEIGHT/6)-(HEIGHT/30)))
table.insert(bodies,makeBox(WIDTH/2,(HEIGHT/6)+(HEIGHT/30), (WIDTH/2)-(WIDTH/15), (HEIGHT/6)-(HEIGHT/30)))
item = itemList[math.random(1,5)]
--Randomly select right answer
--0|1
--2|3
right_answer_position = math.random(0,3)
if right_answer_position == 0 then
speech.say("The "..item.." is green")
elseif right_answer_position == 1 then
speech.say("The "..item.." is yellow")
elseif right_answer_position == 2 then
speech.say("The "..item.." is red")
elseif right_answer_position == 3 then
speech.say("The "..item.." is blue")
end
fontSize(45*WIDTH/1024)
end
bool = false
--Make four rectangles
draw_game2_rectangles()
fill(255)
text("What color is this "..item.."?", WIDTH/2, HEIGHT/2)
text("The "..item.." is green",WIDTH/4,HEIGHT/6+HEIGHT/8)
text("The "..item.." is yellow",WIDTH*2.85/4,HEIGHT/6+HEIGHT/8)
text("The "..item.." is red",WIDTH/4,HEIGHT/8)
text("The "..item.." is blue",WIDTH*2.85/4,HEIGHT/8)
--read touches
if CurrentTouch.state == BEGAN and touching then
touching = false
if CurrentTouch.x < WIDTH/2 then
if CurrentTouch.y < HEIGHT/6 then
if right_answer_position == 2 then
stage = 0
else
bool = true
end
elseif CurrentTouch.y < HEIGHT/6 + (HEIGHT/4)-(1.75*HEIGHT/15) then
if right_answer_position == 0 then
stage = 0
else
bool = true
end
end
else
if CurrentTouch.y < HEIGHT/6 then
if right_answer_position == 3 then
stage = 0
else
bool = true
end
elseif CurrentTouch.y < HEIGHT/6 + (HEIGHT/4)-(1.75*HEIGHT/15) then
if right_answer_position == 1 then
stage = 0
else
bool = true
end
end
end
end
if CurrentTouch.state == ENDED then
touching=true
end
end
--Draw the four rectangles for the answer choices
function draw_game2_rectangles()
rectMode(CORNER)
fill(30,30,30,160)
--Bottom left rectangleS
rect(WIDTH/30,HEIGHT/30, (WIDTH/2)-(WIDTH/15), (HEIGHT/6)-(HEIGHT/30))
--Top left rectangle
rect(WIDTH/30,(HEIGHT/6)+(HEIGHT/30), (WIDTH/2)-(WIDTH/15), (HEIGHT/4)-(1.75*HEIGHT/15))
--Bottom Right
rect(WIDTH/2,HEIGHT/30, (WIDTH/2)-(WIDTH/15), (HEIGHT/6)-(HEIGHT/30))
--Top right
rect(WIDTH/2,(HEIGHT/6)+(HEIGHT/30), (WIDTH/2)-(WIDTH/15), (HEIGHT/6)-(HEIGHT/30))
end
-- This function gets called once every frame
function draw()
-- This sets a dark background color
background(174, 174, 190, 255)
if stage == 0 then
elseif stage == 1 then
game1()
elseif stage == 2 then
--Katie make a mini game here
game2()
end
end
-- Helper function to create a box using a polygon body
function makeBox(x,y,w,h)
-- Points are defined in counter-clockwise order
local body = physics.body(POLYGON,vec2(-w/2, h/2),
vec2(-w/2, -h/2), vec2(w/2, -h/2), vec2(w/2, h/2))
-- Set the body's transform (position, angle)
body.x = x
body.y = y
-- Make movement smoother regardless of framerate
body.interpolate = true
return body
end
|
attempt to fix positioning error
|
attempt to fix positioning error
|
Lua
|
apache-2.0
|
kburk1997/My-ASD-Journey,kburk1997/My-ASD-Journey,kburk1997/My-ASD-Journey,kburk1997/My-ASD-Journey,kburk1997/My-ASD-Journey
|
884bc234e68cde604fdc8362dcb58dcfe81ef4b0
|
nvim/session.lua
|
nvim/session.lua
|
require('coxpcall')
local uv = require('luv')
local wait = require('posix.sys.wait')
local kill = require('posix.signal').kill
local MsgpackStream = require('nvim.msgpack_stream')
local MsgpackRpcStream = require('nvim.msgpack_rpc_stream')
local Session = {}
Session.__index = Session
local function resume(co, ...)
local status, result = coroutine.resume(co, ...)
if coroutine.status(co) == 'dead' then
if not status then
error(result)
end
return
end
assert(coroutine.status(co) == 'suspended')
result(co)
end
local function coroutine_exec(func, ...)
local args = {...}
local on_complete
if #args > 0 and type(args[#args]) == 'function' then
-- completion callback
on_complete = table.remove(args)
end
resume(coroutine.create(function()
local status, result = copcall(func, unpack(args))
if on_complete then
coroutine.yield(function()
-- run the completion callback on the main thread
on_complete(status, result)
end)
end
end))
end
function Session.new(stream)
return setmetatable({
_msgpack_rpc_stream = MsgpackRpcStream.new(MsgpackStream.new(stream)),
_pending_messages = {},
_prepare = uv.new_prepare(),
_timer = uv.new_timer(),
_is_running = false
}, Session)
end
function Session:next_message(timeout)
local function on_request(method, args, response)
table.insert(self._pending_messages, {'request', method, args, response})
uv.stop()
end
local function on_notification(method, args)
table.insert(self._pending_messages, {'notification', method, args})
uv.stop()
end
if self._is_running then
error('Event loop already running')
end
if #self._pending_messages > 0 then
return table.remove(self._pending_messages, 1)
end
self:_run(on_request, on_notification, timeout)
return table.remove(self._pending_messages, 1)
end
function Session:notify(method, ...)
self._msgpack_rpc_stream:write(method, {...})
end
function Session:request(method, ...)
local args = {...}
local err, result
if self._is_running then
err, result = self:_yielding_request(method, args)
else
err, result = self:_blocking_request(method, args)
end
if err then
return false, err
end
return true, result
end
function Session:run(request_cb, notification_cb, setup_cb, timeout)
local function on_request(method, args, response)
coroutine_exec(request_cb, method, args, function(status, result)
if status then
response:send(result)
else
response:send(result, true)
end
end)
end
local function on_notification(method, args)
coroutine_exec(notification_cb, method, args)
end
self._is_running = true
if setup_cb then
coroutine_exec(setup_cb)
end
while #self._pending_messages > 0 do
local msg = table.remove(self._pending_messages, 1)
if msg[1] == 'request' then
on_request(msg[2], msg[3], msg[4])
else
on_notification(msg[2], msg[3])
end
end
self:_run(on_request, on_notification, timeout)
self._is_running = false
end
function Session:stop()
uv.stop()
end
function Session:exit()
self._exited = true
self._timer:close()
self._prepare:close()
self._msgpack_rpc_stream:close()
local pid = self._msgpack_rpc_stream._msgpack_stream._stream._pid
if pid == nil then
return -- not a child stream
end
-- Work around libuv bug that leaves defunct children:
-- https://github.com/libuv/libuv/issues/154
uv.run('nowait')
while kill(pid, 0) == 0 do
-- wait.wait(pid, wait.WNOHANG)
wait.wait(pid, wait.WNOHANG)
end
end
function Session:_yielding_request(method, args)
return coroutine.yield(function(co)
self._msgpack_rpc_stream:write(method, args, function(err, result)
resume(co, err, result)
end)
end)
end
function Session:_blocking_request(method, args)
local err, result
local function on_request(method, args, response)
table.insert(self._pending_messages, {'request', method, args, response})
end
local function on_notification(method, args)
table.insert(self._pending_messages, {'notification', method, args})
end
self._msgpack_rpc_stream:write(method, args, function(e, r)
err = e
result = r
uv.stop()
end)
self:_run(on_request, on_notification)
return err, result
end
function Session:_run(request_cb, notification_cb, timeout)
if type(timeout) == 'number' then
self._prepare:start(function()
self._timer:start(timeout, 0, function()
uv.stop()
end)
self._prepare:stop()
end)
end
self._msgpack_rpc_stream:read_start(request_cb, notification_cb, uv.stop)
uv.run()
self._msgpack_rpc_stream:read_stop()
end
return Session
|
require('coxpcall')
local uv = require('luv')
local wait = require('posix.sys.wait')
local kill = require('posix.signal').kill
local MsgpackStream = require('nvim.msgpack_stream')
local MsgpackRpcStream = require('nvim.msgpack_rpc_stream')
local Session = {}
Session.__index = Session
local function resume(co, ...)
local status, result = coroutine.resume(co, ...)
if coroutine.status(co) == 'dead' then
if not status then
error(result)
end
return
end
assert(coroutine.status(co) == 'suspended')
result(co)
end
local function coroutine_exec(func, ...)
local args = {...}
local on_complete
if #args > 0 and type(args[#args]) == 'function' then
-- completion callback
on_complete = table.remove(args)
end
resume(coroutine.create(function()
local status, result = copcall(func, unpack(args))
if on_complete then
coroutine.yield(function()
-- run the completion callback on the main thread
on_complete(status, result)
end)
end
end))
end
function Session.new(stream)
return setmetatable({
_msgpack_rpc_stream = MsgpackRpcStream.new(MsgpackStream.new(stream)),
_pending_messages = {},
_prepare = uv.new_prepare(),
_timer = uv.new_timer(),
_is_running = false
}, Session)
end
function Session:next_message(timeout)
local function on_request(method, args, response)
table.insert(self._pending_messages, {'request', method, args, response})
uv.stop()
end
local function on_notification(method, args)
table.insert(self._pending_messages, {'notification', method, args})
uv.stop()
end
if self._is_running then
error('Event loop already running')
end
if #self._pending_messages > 0 then
return table.remove(self._pending_messages, 1)
end
self:_run(on_request, on_notification, timeout)
return table.remove(self._pending_messages, 1)
end
function Session:notify(method, ...)
self._msgpack_rpc_stream:write(method, {...})
end
function Session:request(method, ...)
local args = {...}
local err, result
if self._is_running then
err, result = self:_yielding_request(method, args)
else
err, result = self:_blocking_request(method, args)
end
if err then
return false, err
end
return true, result
end
function Session:run(request_cb, notification_cb, setup_cb, timeout)
local function on_request(method, args, response)
coroutine_exec(request_cb, method, args, function(status, result)
if status then
response:send(result)
else
response:send(result, true)
end
end)
end
local function on_notification(method, args)
coroutine_exec(notification_cb, method, args)
end
self._is_running = true
if setup_cb then
coroutine_exec(setup_cb)
end
while #self._pending_messages > 0 do
local msg = table.remove(self._pending_messages, 1)
if msg[1] == 'request' then
on_request(msg[2], msg[3], msg[4])
else
on_notification(msg[2], msg[3])
end
end
self:_run(on_request, on_notification, timeout)
self._is_running = false
end
function Session:stop()
uv.stop()
end
function Session:exit()
self._exited = true
if not self._timer:is_closing() then self._timer:close() end
if not self._prepare:is_closing() then self._prepare:close() end
self._msgpack_rpc_stream:close()
uv.run('nowait')
local pid = self._msgpack_rpc_stream._msgpack_stream._stream._pid
if pid == nil then
return -- not a child stream
end
-- Work around libuv bug that leaves defunct children:
-- https://github.com/libuv/libuv/issues/154
while kill(pid, 0) == 0 do
-- wait.wait(pid, wait.WNOHANG)
wait.wait(pid, wait.WNOHANG)
end
end
function Session:_yielding_request(method, args)
return coroutine.yield(function(co)
self._msgpack_rpc_stream:write(method, args, function(err, result)
resume(co, err, result)
end)
end)
end
function Session:_blocking_request(method, args)
local err, result
local function on_request(method, args, response)
table.insert(self._pending_messages, {'request', method, args, response})
end
local function on_notification(method, args)
table.insert(self._pending_messages, {'notification', method, args})
end
self._msgpack_rpc_stream:write(method, args, function(e, r)
err = e
result = r
uv.stop()
end)
self:_run(on_request, on_notification)
return err, result
end
function Session:_run(request_cb, notification_cb, timeout)
if type(timeout) == 'number' then
self._prepare:start(function()
self._timer:start(timeout, 0, function()
uv.stop()
end)
self._prepare:stop()
end)
end
self._msgpack_rpc_stream:read_start(request_cb, notification_cb, uv.stop)
uv.run()
self._msgpack_rpc_stream:read_stop()
end
return Session
|
Fix session cleanup
|
Fix session cleanup
Always call uv.run to ensure the timer/prepare handles are closed.
|
Lua
|
apache-2.0
|
neovim/lua-client,neovim/lua-client,neovim/lua-client
|
bc0a9032f607bed0bef27ebbdd71e18db10a3573
|
util/multitable.lua
|
util/multitable.lua
|
-- Prosody IM
-- Copyright (C) 2008-2010 Matthew Wild
-- Copyright (C) 2008-2010 Waqas Hussain
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
local select = select;
local t_insert = table.insert;
local pairs = pairs;
local next = next;
module "multitable"
local function get(self, ...)
local t = self.data;
for n = 1,select('#', ...) do
t = t[select(n, ...)];
if not t then break; end
end
return t;
end
local function add(self, ...)
local t = self.data;
local count = select('#', ...);
for n = 1,count-1 do
local key = select(n, ...);
local tab = t[key];
if not tab then tab = {}; t[key] = tab; end
t = tab;
end
t_insert(t, (select(count, ...)));
end
local function set(self, ...)
local t = self.data;
local count = select('#', ...);
for n = 1,count-2 do
local key = select(n, ...);
local tab = t[key];
if not tab then tab = {}; t[key] = tab; end
t = tab;
end
t[(select(count-1, ...))] = (select(count, ...));
end
local function r(t, n, _end, ...)
if t == nil then return; end
local k = select(n, ...);
if n == _end then
t[k] = nil;
return;
end
if k then
local v = t[k];
if v then
r(v, n+1, _end, ...);
if not next(v) then
t[k] = nil;
end
end
else
for _,b in pairs(t) do
r(b, n+1, _end, ...);
if not next(b) then
t[_] = nil;
end
end
end
end
local function remove(self, ...)
local _end = select('#', ...);
for n = _end,1 do
if select(n, ...) then _end = n; break; end
end
r(self.data, 1, _end, ...);
end
local function s(t, n, results, _end, ...)
if t == nil then return; end
local k = select(n, ...);
if n == _end then
if k == nil then
for _, v in pairs(t) do
t_insert(results, v);
end
else
t_insert(results, t[k]);
end
return;
end
if k then
local v = t[k];
if v then
s(v, n+1, results, _end, ...);
end
else
for _,b in pairs(t) do
s(b, n+1, results, _end, ...);
end
end
end
-- Search for keys, nil == wildcard
local function search(self, ...)
local _end = select('#', ...);
for n = _end,1 do
if select(n, ...) then _end = n; break; end
end
local results = {};
s(self.data, 1, results, _end, ...);
return results;
end
-- Append results to an existing list
local function search_add(self, results, ...)
if not results then results = {}; end
local _end = select('#', ...);
for n = _end,1 do
if select(n, ...) then _end = n; break; end
end
s(self.data, 1, results, _end, ...);
return results;
end
function new()
return {
data = {};
get = get;
add = add;
set = set;
remove = remove;
search = search;
search_add = search_add;
};
end
return _M;
|
-- Prosody IM
-- Copyright (C) 2008-2010 Matthew Wild
-- Copyright (C) 2008-2010 Waqas Hussain
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
local select = select;
local t_insert, t_remove = table.insert, table.remove;
local unpack, pairs, next, type = unpack, pairs, next, type;
module "multitable"
local function get(self, ...)
local t = self.data;
for n = 1,select('#', ...) do
t = t[select(n, ...)];
if not t then break; end
end
return t;
end
local function add(self, ...)
local t = self.data;
local count = select('#', ...);
for n = 1,count-1 do
local key = select(n, ...);
local tab = t[key];
if not tab then tab = {}; t[key] = tab; end
t = tab;
end
t_insert(t, (select(count, ...)));
end
local function set(self, ...)
local t = self.data;
local count = select('#', ...);
for n = 1,count-2 do
local key = select(n, ...);
local tab = t[key];
if not tab then tab = {}; t[key] = tab; end
t = tab;
end
t[(select(count-1, ...))] = (select(count, ...));
end
local function r(t, n, _end, ...)
if t == nil then return; end
local k = select(n, ...);
if n == _end then
t[k] = nil;
return;
end
if k then
local v = t[k];
if v then
r(v, n+1, _end, ...);
if not next(v) then
t[k] = nil;
end
end
else
for _,b in pairs(t) do
r(b, n+1, _end, ...);
if not next(b) then
t[_] = nil;
end
end
end
end
local function remove(self, ...)
local _end = select('#', ...);
for n = _end,1 do
if select(n, ...) then _end = n; break; end
end
r(self.data, 1, _end, ...);
end
local function s(t, n, results, _end, ...)
if t == nil then return; end
local k = select(n, ...);
if n == _end then
if k == nil then
for _, v in pairs(t) do
t_insert(results, v);
end
else
t_insert(results, t[k]);
end
return;
end
if k then
local v = t[k];
if v then
s(v, n+1, results, _end, ...);
end
else
for _,b in pairs(t) do
s(b, n+1, results, _end, ...);
end
end
end
-- Search for keys, nil == wildcard
local function search(self, ...)
local _end = select('#', ...);
for n = _end,1 do
if select(n, ...) then _end = n; break; end
end
local results = {};
s(self.data, 1, results, _end, ...);
return results;
end
-- Append results to an existing list
local function search_add(self, results, ...)
if not results then results = {}; end
local _end = select('#', ...);
for n = _end,1 do
if select(n, ...) then _end = n; break; end
end
s(self.data, 1, results, _end, ...);
return results;
end
function iter(self, ...)
local query = { ... };
local maxdepth = select("#", ...);
local stack = { self.data };
local keys = { };
local function it(self)
local depth = #stack;
local key = next(stack[depth], keys[depth]);
if key == nil then -- Go up the stack
t_remove(stack);
t_remove(keys);
if depth > 1 then
return it(self);
end
return; -- The end
else
keys[depth] = key;
end
local value = stack[depth][key];
if depth == maxdepth then -- Result
local result = {}; -- Collect keys forming path to result
for i = 1, depth do
result[i] = keys[i];
end
return unpack(result, 1, depth);
else
if (query[depth] == nil or key == query[depth]) and type(value) == "table" then -- Descend
t_insert(stack, value);
end
return it(self);
end
end;
return it, self;
end
function new()
return {
data = {};
get = get;
add = add;
set = set;
remove = remove;
search = search;
search_add = search_add;
iter = iter;
};
end
return _M;
|
util.multitable: Add :iter() method to iterate over results at a fixed depth (parameters are equivalent to :search())
|
util.multitable: Add :iter() method to iterate over results at a fixed depth (parameters are equivalent to :search())
|
Lua
|
mit
|
sarumjanuch/prosody,sarumjanuch/prosody
|
97fcc6df3f79925e330eea609a7c3c5a59102675
|
applications/luci-initmgr/luasrc/controller/init.lua
|
applications/luci-initmgr/luasrc/controller/init.lua
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
module("luci.controller.init", package.seeall)
function index()
if not luci.fs.isfile("/etc/rc.common") then
return
end
local page = entry({"admin", "system", "init"}, form("init/init"), luci.i18n.translate("initmgr", "Init Scripts"))
page.i18n = "initmgr"
page.dependent = true
end
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
module("luci.controller.init", package.seeall)
function index()
if not luci.fs.isfile("/etc/rc.common") then
return
end
require("luci.i18n")
luci.i18n.loadc("initmgr")
entry(
{"admin", "system", "init"}, form("init/init"),
luci.i18n.translate("initmgr", "Init Scripts")
).i18n = "initmgr"
end
|
* luci/app/initmgr: fix translation issue in menu entry
|
* luci/app/initmgr: fix translation issue in menu entry
|
Lua
|
apache-2.0
|
dwmw2/luci,lcf258/openwrtcn,cappiewu/luci,marcel-sch/luci,rogerpueyo/luci,wongsyrone/luci-1,dwmw2/luci,nmav/luci,981213/luci-1,oyido/luci,oyido/luci,palmettos/cnLuCI,david-xiao/luci,aa65535/luci,schidler/ionic-luci,rogerpueyo/luci,nmav/luci,LazyZhu/openwrt-luci-trunk-mod,ollie27/openwrt_luci,Wedmer/luci,palmettos/cnLuCI,urueedi/luci,daofeng2015/luci,urueedi/luci,ReclaimYourPrivacy/cloak-luci,florian-shellfire/luci,opentechinstitute/luci,thesabbir/luci,jlopenwrtluci/luci,db260179/openwrt-bpi-r1-luci,remakeelectric/luci,LuttyYang/luci,RedSnake64/openwrt-luci-packages,dismantl/luci-0.12,oneru/luci,joaofvieira/luci,kuoruan/luci,jorgifumi/luci,Hostle/luci,keyidadi/luci,openwrt/luci,slayerrensky/luci,ollie27/openwrt_luci,tobiaswaldvogel/luci,cappiewu/luci,Noltari/luci,fkooman/luci,dwmw2/luci,schidler/ionic-luci,joaofvieira/luci,bittorf/luci,wongsyrone/luci-1,dwmw2/luci,cshore-firmware/openwrt-luci,marcel-sch/luci,hnyman/luci,deepak78/new-luci,tcatm/luci,LazyZhu/openwrt-luci-trunk-mod,dwmw2/luci,thess/OpenWrt-luci,Hostle/openwrt-luci-multi-user,Sakura-Winkey/LuCI,zhaoxx063/luci,jchuang1977/luci-1,thesabbir/luci,opentechinstitute/luci,ff94315/luci-1,thess/OpenWrt-luci,opentechinstitute/luci,981213/luci-1,remakeelectric/luci,harveyhu2012/luci,taiha/luci,taiha/luci,bittorf/luci,zhaoxx063/luci,harveyhu2012/luci,deepak78/new-luci,thesabbir/luci,Kyklas/luci-proto-hso,LuttyYang/luci,cshore/luci,zhaoxx063/luci,Hostle/luci,opentechinstitute/luci,kuoruan/lede-luci,NeoRaider/luci,artynet/luci,remakeelectric/luci,tcatm/luci,Wedmer/luci,981213/luci-1,palmettos/test,sujeet14108/luci,Hostle/openwrt-luci-multi-user,obsy/luci,981213/luci-1,maxrio/luci981213,florian-shellfire/luci,daofeng2015/luci,tcatm/luci,daofeng2015/luci,shangjiyu/luci-with-extra,harveyhu2012/luci,palmettos/test,LazyZhu/openwrt-luci-trunk-mod,thess/OpenWrt-luci,teslamint/luci,ff94315/luci-1,keyidadi/luci,cshore-firmware/openwrt-luci,shangjiyu/luci-with-extra,kuoruan/luci,daofeng2015/luci,NeoRaider/luci,ReclaimYourPrivacy/cloak-luci,oneru/luci,teslamint/luci,LazyZhu/openwrt-luci-trunk-mod,shangjiyu/luci-with-extra,nwf/openwrt-luci,LuttyYang/luci,teslamint/luci,LazyZhu/openwrt-luci-trunk-mod,artynet/luci,oyido/luci,sujeet14108/luci,Noltari/luci,cshore/luci,nmav/luci,teslamint/luci,jlopenwrtluci/luci,sujeet14108/luci,ReclaimYourPrivacy/cloak-luci,teslamint/luci,LuttyYang/luci,Hostle/openwrt-luci-multi-user,aa65535/luci,RuiChen1113/luci,thess/OpenWrt-luci,MinFu/luci,deepak78/new-luci,palmettos/cnLuCI,cappiewu/luci,nwf/openwrt-luci,joaofvieira/luci,obsy/luci,rogerpueyo/luci,thesabbir/luci,kuoruan/luci,Hostle/openwrt-luci-multi-user,joaofvieira/luci,lcf258/openwrtcn,rogerpueyo/luci,jorgifumi/luci,bright-things/ionic-luci,dismantl/luci-0.12,db260179/openwrt-bpi-r1-luci,artynet/luci,teslamint/luci,jlopenwrtluci/luci,marcel-sch/luci,nwf/openwrt-luci,bright-things/ionic-luci,jchuang1977/luci-1,nmav/luci,chris5560/openwrt-luci,kuoruan/luci,bright-things/ionic-luci,male-puppies/luci,ff94315/luci-1,oyido/luci,db260179/openwrt-bpi-r1-luci,kuoruan/luci,chris5560/openwrt-luci,nwf/openwrt-luci,kuoruan/luci,teslamint/luci,obsy/luci,thesabbir/luci,bittorf/luci,opentechinstitute/luci,nmav/luci,openwrt/luci,kuoruan/lede-luci,openwrt-es/openwrt-luci,Hostle/luci,tobiaswaldvogel/luci,oyido/luci,ReclaimYourPrivacy/cloak-luci,aa65535/luci,cshore-firmware/openwrt-luci,tobiaswaldvogel/luci,dwmw2/luci,male-puppies/luci,remakeelectric/luci,lbthomsen/openwrt-luci,keyidadi/luci,lbthomsen/openwrt-luci,zhaoxx063/luci,bittorf/luci,mumuqz/luci,Noltari/luci,wongsyrone/luci-1,urueedi/luci,NeoRaider/luci,db260179/openwrt-bpi-r1-luci,openwrt-es/openwrt-luci,opentechinstitute/luci,palmettos/cnLuCI,openwrt/luci,RuiChen1113/luci,marcel-sch/luci,schidler/ionic-luci,tcatm/luci,thess/OpenWrt-luci,Hostle/openwrt-luci-multi-user,jlopenwrtluci/luci,schidler/ionic-luci,cshore/luci,rogerpueyo/luci,keyidadi/luci,artynet/luci,obsy/luci,opentechinstitute/luci,Hostle/luci,nwf/openwrt-luci,bittorf/luci,aircross/OpenWrt-Firefly-LuCI,maxrio/luci981213,urueedi/luci,forward619/luci,daofeng2015/luci,hnyman/luci,forward619/luci,aircross/OpenWrt-Firefly-LuCI,openwrt-es/openwrt-luci,remakeelectric/luci,oneru/luci,ReclaimYourPrivacy/cloak-luci,MinFu/luci,taiha/luci,cappiewu/luci,male-puppies/luci,Hostle/openwrt-luci-multi-user,jorgifumi/luci,nmav/luci,lbthomsen/openwrt-luci,tcatm/luci,jchuang1977/luci-1,thesabbir/luci,cappiewu/luci,marcel-sch/luci,keyidadi/luci,wongsyrone/luci-1,hnyman/luci,remakeelectric/luci,NeoRaider/luci,lcf258/openwrtcn,Sakura-Winkey/LuCI,Wedmer/luci,cshore-firmware/openwrt-luci,joaofvieira/luci,ff94315/luci-1,thess/OpenWrt-luci,slayerrensky/luci,harveyhu2012/luci,david-xiao/luci,keyidadi/luci,RuiChen1113/luci,Wedmer/luci,db260179/openwrt-bpi-r1-luci,artynet/luci,MinFu/luci,rogerpueyo/luci,jlopenwrtluci/luci,RuiChen1113/luci,palmettos/test,tcatm/luci,remakeelectric/luci,wongsyrone/luci-1,dismantl/luci-0.12,jlopenwrtluci/luci,RuiChen1113/luci,wongsyrone/luci-1,artynet/luci,forward619/luci,db260179/openwrt-bpi-r1-luci,maxrio/luci981213,urueedi/luci,openwrt/luci,palmettos/test,slayerrensky/luci,openwrt/luci,palmettos/test,forward619/luci,lbthomsen/openwrt-luci,RuiChen1113/luci,RedSnake64/openwrt-luci-packages,LuttyYang/luci,openwrt-es/openwrt-luci,palmettos/test,fkooman/luci,florian-shellfire/luci,Sakura-Winkey/LuCI,keyidadi/luci,deepak78/new-luci,cshore-firmware/openwrt-luci,bright-things/ionic-luci,taiha/luci,Hostle/luci,ReclaimYourPrivacy/cloak-luci,ollie27/openwrt_luci,mumuqz/luci,hnyman/luci,lbthomsen/openwrt-luci,jchuang1977/luci-1,forward619/luci,tobiaswaldvogel/luci,RedSnake64/openwrt-luci-packages,jlopenwrtluci/luci,bright-things/ionic-luci,urueedi/luci,kuoruan/lede-luci,mumuqz/luci,chris5560/openwrt-luci,chris5560/openwrt-luci,fkooman/luci,forward619/luci,lcf258/openwrtcn,david-xiao/luci,aircross/OpenWrt-Firefly-LuCI,shangjiyu/luci-with-extra,taiha/luci,fkooman/luci,artynet/luci,Wedmer/luci,deepak78/new-luci,kuoruan/lede-luci,urueedi/luci,oneru/luci,harveyhu2012/luci,chris5560/openwrt-luci,florian-shellfire/luci,ollie27/openwrt_luci,jorgifumi/luci,shangjiyu/luci-with-extra,tobiaswaldvogel/luci,ollie27/openwrt_luci,lbthomsen/openwrt-luci,Kyklas/luci-proto-hso,nwf/openwrt-luci,openwrt-es/openwrt-luci,openwrt/luci,palmettos/test,cshore-firmware/openwrt-luci,chris5560/openwrt-luci,palmettos/cnLuCI,harveyhu2012/luci,david-xiao/luci,daofeng2015/luci,taiha/luci,dismantl/luci-0.12,hnyman/luci,Noltari/luci,aa65535/luci,MinFu/luci,Sakura-Winkey/LuCI,aa65535/luci,shangjiyu/luci-with-extra,jorgifumi/luci,male-puppies/luci,deepak78/new-luci,lcf258/openwrtcn,Hostle/luci,Sakura-Winkey/LuCI,joaofvieira/luci,hnyman/luci,kuoruan/luci,aircross/OpenWrt-Firefly-LuCI,lcf258/openwrtcn,ff94315/luci-1,harveyhu2012/luci,obsy/luci,NeoRaider/luci,sujeet14108/luci,oneru/luci,ReclaimYourPrivacy/cloak-luci,jlopenwrtluci/luci,cshore/luci,bittorf/luci,LazyZhu/openwrt-luci-trunk-mod,daofeng2015/luci,nmav/luci,cshore-firmware/openwrt-luci,bright-things/ionic-luci,kuoruan/lede-luci,bright-things/ionic-luci,mumuqz/luci,lcf258/openwrtcn,Kyklas/luci-proto-hso,nmav/luci,tcatm/luci,artynet/luci,981213/luci-1,hnyman/luci,tobiaswaldvogel/luci,lcf258/openwrtcn,Noltari/luci,openwrt/luci,cshore/luci,kuoruan/luci,maxrio/luci981213,ollie27/openwrt_luci,openwrt-es/openwrt-luci,urueedi/luci,david-xiao/luci,RuiChen1113/luci,aircross/OpenWrt-Firefly-LuCI,schidler/ionic-luci,joaofvieira/luci,RedSnake64/openwrt-luci-packages,Hostle/luci,chris5560/openwrt-luci,taiha/luci,oyido/luci,jchuang1977/luci-1,Hostle/openwrt-luci-multi-user,obsy/luci,remakeelectric/luci,dismantl/luci-0.12,dismantl/luci-0.12,fkooman/luci,981213/luci-1,NeoRaider/luci,cappiewu/luci,jorgifumi/luci,dwmw2/luci,jchuang1977/luci-1,tobiaswaldvogel/luci,Wedmer/luci,deepak78/new-luci,florian-shellfire/luci,RedSnake64/openwrt-luci-packages,sujeet14108/luci,palmettos/cnLuCI,LuttyYang/luci,slayerrensky/luci,lbthomsen/openwrt-luci,zhaoxx063/luci,db260179/openwrt-bpi-r1-luci,jchuang1977/luci-1,MinFu/luci,openwrt-es/openwrt-luci,oyido/luci,cshore/luci,bright-things/ionic-luci,wongsyrone/luci-1,keyidadi/luci,ReclaimYourPrivacy/cloak-luci,RedSnake64/openwrt-luci-packages,fkooman/luci,forward619/luci,cappiewu/luci,RedSnake64/openwrt-luci-packages,Kyklas/luci-proto-hso,dwmw2/luci,RuiChen1113/luci,thess/OpenWrt-luci,rogerpueyo/luci,maxrio/luci981213,aa65535/luci,mumuqz/luci,wongsyrone/luci-1,oneru/luci,palmettos/cnLuCI,cshore-firmware/openwrt-luci,deepak78/new-luci,cappiewu/luci,LazyZhu/openwrt-luci-trunk-mod,slayerrensky/luci,nwf/openwrt-luci,sujeet14108/luci,teslamint/luci,bittorf/luci,kuoruan/lede-luci,obsy/luci,Kyklas/luci-proto-hso,david-xiao/luci,jchuang1977/luci-1,zhaoxx063/luci,jorgifumi/luci,oneru/luci,obsy/luci,LuttyYang/luci,bittorf/luci,male-puppies/luci,nmav/luci,palmettos/test,marcel-sch/luci,ollie27/openwrt_luci,Kyklas/luci-proto-hso,ff94315/luci-1,rogerpueyo/luci,MinFu/luci,florian-shellfire/luci,lcf258/openwrtcn,forward619/luci,daofeng2015/luci,oyido/luci,dismantl/luci-0.12,shangjiyu/luci-with-extra,ff94315/luci-1,Hostle/luci,florian-shellfire/luci,Sakura-Winkey/LuCI,Noltari/luci,Wedmer/luci,florian-shellfire/luci,Noltari/luci,sujeet14108/luci,Noltari/luci,joaofvieira/luci,slayerrensky/luci,zhaoxx063/luci,openwrt-es/openwrt-luci,NeoRaider/luci,cshore/luci,aircross/OpenWrt-Firefly-LuCI,maxrio/luci981213,schidler/ionic-luci,Noltari/luci,nwf/openwrt-luci,thess/OpenWrt-luci,lcf258/openwrtcn,opentechinstitute/luci,ollie27/openwrt_luci,slayerrensky/luci,Sakura-Winkey/LuCI,david-xiao/luci,Hostle/openwrt-luci-multi-user,marcel-sch/luci,maxrio/luci981213,zhaoxx063/luci,981213/luci-1,artynet/luci,aircross/OpenWrt-Firefly-LuCI,kuoruan/lede-luci,aa65535/luci,ff94315/luci-1,aa65535/luci,thesabbir/luci,jorgifumi/luci,kuoruan/lede-luci,taiha/luci,palmettos/cnLuCI,fkooman/luci,db260179/openwrt-bpi-r1-luci,LazyZhu/openwrt-luci-trunk-mod,oneru/luci,slayerrensky/luci,MinFu/luci,MinFu/luci,Sakura-Winkey/LuCI,tobiaswaldvogel/luci,male-puppies/luci,fkooman/luci,mumuqz/luci,cshore/luci,LuttyYang/luci,marcel-sch/luci,shangjiyu/luci-with-extra,mumuqz/luci,tcatm/luci,thesabbir/luci,hnyman/luci,lbthomsen/openwrt-luci,schidler/ionic-luci,male-puppies/luci,mumuqz/luci,openwrt/luci,schidler/ionic-luci,sujeet14108/luci,male-puppies/luci,maxrio/luci981213,david-xiao/luci,NeoRaider/luci,Wedmer/luci,Kyklas/luci-proto-hso,chris5560/openwrt-luci
|
cd0b6fe0c479ccf48d36fa342b6ce7789f99f6bc
|
lib/luvit/utils.lua
|
lib/luvit/utils.lua
|
--[[
Copyright 2012 The Luvit Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
local table = require('table')
local utils = {}
local colors = {
black = "0;30",
red = "0;31",
green = "0;32",
yellow = "0;33",
blue = "0;34",
magenta = "0;35",
cyan = "0;36",
white = "0;37",
B = "1;",
Bblack = "1;30",
Bred = "1;31",
Bgreen = "1;32",
Byellow = "1;33",
Bblue = "1;34",
Bmagenta = "1;35",
Bcyan = "1;36",
Bwhite = "1;37"
}
if utils._useColors == nil then
utils._useColors = true
end
function utils.color(color_name)
if utils._useColors then
return "\27[" .. (colors[color_name] or "0") .. "m"
else
return ""
end
end
function utils.colorize(color_name, string, reset_name)
return utils.color(color_name) .. tostring(string) .. utils.color(reset_name)
end
local escapes = { backslash = "\\\\", null = "\\0", newline = "\\n", carriage = "\\r",
tab = "\\t", quote = '"', quote2 = '"', obracket = '[', cbracket = ']'
}
local colorized_escapes = {}
function utils.loadColors (n)
if n ~= nil then utils._useColors = n end
colorized_escapes["backslash"] = utils.colorize("Bgreen", escapes.backslash, "green")
colorized_escapes["null"] = utils.colorize("Bgreen", escapes.null, "green")
colorized_escapes["newline"] = utils.colorize("Bgreen", escapes.newline, "green")
colorized_escapes["carriage"] = utils.colorize("Bgreen", escapes.carriage, "green")
colorized_escapes["tab"] = utils.colorize("Bgreen", escapes.tab, "green")
colorized_escapes["quote"] = utils.colorize("Bgreen", escapes.quote, "green")
colorized_escapes["quote2"] = utils.colorize("Bgreen", escapes.quote2)
for k,v in pairs(escapes) do
if not colorized_escapes[k] then
colorized_escapes[k] = utils.colorize("B", v)
end
end
end
utils.loadColors()
local function colorize_nop(color, obj)
return obj
end
function utils.dump(o, depth, no_colorize)
local colorize_func
local _escapes
if no_colorize then
_escapes = escapes
colorize_func = colorize_nop
else
_escapes = colorized_escapes
colorize_func = utils.colorize
end
local t = type(o)
if t == 'string' then
return _escapes.quote .. o:gsub("\\", _escapes.backslash):gsub("%z", _escapes.null):gsub("\n", _escapes.newline):gsub("\r", _escapes.carriage):gsub("\t", _escapes.tab) .. _escapes.quote2
end
if t == 'nil' then
return colorize_func("Bblack", "nil")
end
if t == 'boolean' then
return colorize_func("yellow", tostring(o))
end
if t == 'number' then
return colorize_func("blue", tostring(o))
end
if t == 'userdata' then
return colorize_func("magenta", tostring(o))
end
if t == 'thread' then
return colorize_func("Bred", tostring(o))
end
if t == 'function' then
return colorize_func("cyan", tostring(o))
end
if t == 'cdata' then
return colorize_func("Bmagenta", tostring(o))
end
if t == 'table' then
if type(depth) == 'nil' then
depth = 0
end
if depth > 1 then
return colorize_func("yellow", tostring(o))
end
local indent = (" "):rep(depth)
-- Check to see if this is an array
local is_array = true
local i = 1
for k,v in pairs(o) do
if not (k == i) then
is_array = false
end
i = i + 1
end
local first = true
local lines = {}
i = 1
local estimated = 0
for k,v in (is_array and ipairs or pairs)(o) do
local s
if is_array then
s = ""
else
if type(k) == "string" and k:find("^[%a_][%a%d_]*$") then
s = k .. ' = '
else
s = '[' .. utils.dump(k, 100, no_colorize) .. '] = '
end
end
s = s .. utils.dump(v, depth + 1, no_colorize)
lines[i] = s
estimated = estimated + #s
i = i + 1
end
if estimated > 200 then
return "{\n " .. indent .. table.concat(lines, ",\n " .. indent) .. "\n" .. indent .. "}"
else
return "{ " .. table.concat(lines, ", ") .. " }"
end
end
-- This doesn't happen right?
return tostring(o)
end
-- Replace print
function utils.print(...)
local n = select('#', ...)
local arguments = { ... }
for i = 1, n do
arguments[i] = tostring(arguments[i])
end
process.stdout:write(table.concat(arguments, "\t") .. "\n")
end
-- A nice global data dumper
function utils.prettyPrint(...)
local n = select('#', ...)
local arguments = { ... }
for i = 1, n do
arguments[i] = utils.dump(arguments[i])
end
process.stdout:write(table.concat(arguments, "\t") .. "\n")
end
-- Like p, but prints to stderr using blocking I/O for better debugging
function utils.debug(...)
local n = select('#', ...)
local arguments = { ... }
for i = 1, n do
arguments[i] = utils.dump(arguments[i])
end
process.stderr:write(table.concat(arguments, "\t") .. "\n")
end
function utils.bind(fn, self, ...)
local bindArgsLength = select("#", ...)
-- Simple binding, just inserts self (or one arg or any kind)
if bindArgsLength == 0 then
return function (...)
return fn(self, ...)
end
end
-- More complex binding inserts arbitrary number of args into call.
local bindArgs = {...}
return function (...)
local argsLength = select("#", ...)
local args = {...}
local arguments = {}
for i = 1, bindArgsLength do
arguments[i] = bindArgs[i]
end
for i = 1, argsLength do
arguments[i + bindArgsLength] = args[i]
end
return fn(self, unpack(arguments, 1, bindArgsLength + argsLength))
end
end
return utils
--print("nil", dump(nil))
--print("number", dump(42))
--print("boolean", dump(true), dump(false))
--print("string", dump("\"Hello\""), dump("world\nwith\r\nnewlines\r\t\n"))
--print("funct", dump(print))
--print("table", dump({
-- ["nil"] = nil,
-- ["8"] = 8,
-- ["number"] = 42,
-- ["boolean"] = true,
-- ["table"] = {age = 29, name="Tim"},
-- ["string"] = "Another String",
-- ["function"] = dump,
-- ["thread"] = coroutine.create(dump),
-- [print] = {{"deep"},{{"nesting"}},3,4,5},
-- [{1,2,3}] = {4,5,6}
--}))
|
--[[
Copyright 2012 The Luvit Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
local table = require('table')
local utils = {}
local colors = {
black = "0;30",
red = "0;31",
green = "0;32",
yellow = "0;33",
blue = "0;34",
magenta = "0;35",
cyan = "0;36",
white = "0;37",
B = "1;",
Bblack = "1;30",
Bred = "1;31",
Bgreen = "1;32",
Byellow = "1;33",
Bblue = "1;34",
Bmagenta = "1;35",
Bcyan = "1;36",
Bwhite = "1;37"
}
if utils._useColors == nil then
utils._useColors = true
end
function utils.color(color_name)
if utils._useColors then
return "\27[" .. (colors[color_name] or "0") .. "m"
else
return ""
end
end
function utils.colorize(color_name, string, reset_name)
return utils.color(color_name) .. tostring(string) .. utils.color(reset_name)
end
local escapes = { backslash = "\\\\", null = "\\0", newline = "\\n", carriage = "\\r",
tab = "\\t", quote = '"', quote2 = '"', obracket = '[', cbracket = ']'
}
local colorized_escapes = {}
function utils.loadColors (n)
if n ~= nil then utils._useColors = n end
colorized_escapes["backslash"] = utils.colorize("Bgreen", escapes.backslash, "green")
colorized_escapes["null"] = utils.colorize("Bgreen", escapes.null, "green")
colorized_escapes["newline"] = utils.colorize("Bgreen", escapes.newline, "green")
colorized_escapes["carriage"] = utils.colorize("Bgreen", escapes.carriage, "green")
colorized_escapes["tab"] = utils.colorize("Bgreen", escapes.tab, "green")
colorized_escapes["quote"] = utils.colorize("Bgreen", escapes.quote, "green")
colorized_escapes["quote2"] = utils.colorize("Bgreen", escapes.quote2)
for k,v in pairs(escapes) do
if not colorized_escapes[k] then
colorized_escapes[k] = utils.colorize("B", v)
end
end
end
utils.loadColors()
local function colorize_nop(color, obj)
return obj
end
function utils.dump(o, depth, no_colorize)
local colorize_func
local _escapes
if no_colorize then
_escapes = escapes
colorize_func = colorize_nop
else
_escapes = colorized_escapes
colorize_func = utils.colorize
end
local t = type(o)
if t == 'string' then
return _escapes.quote .. o:gsub("\\", _escapes.backslash):gsub("%z", _escapes.null):gsub("\n", _escapes.newline):gsub("\r", _escapes.carriage):gsub("\t", _escapes.tab) .. _escapes.quote2
end
if t == 'nil' then
return colorize_func("Bblack", "nil")
end
if t == 'boolean' then
return colorize_func("yellow", tostring(o))
end
if t == 'number' then
return colorize_func("blue", tostring(o))
end
if t == 'userdata' then
return colorize_func("magenta", tostring(o))
end
if t == 'thread' then
return colorize_func("Bred", tostring(o))
end
if t == 'function' then
return colorize_func("cyan", tostring(o))
end
if t == 'cdata' then
return colorize_func("Bmagenta", tostring(o))
end
if t == 'table' then
if type(depth) == 'nil' then
depth = 0
end
if depth > 1 then
return colorize_func("yellow", tostring(o))
end
local indent = (" "):rep(depth)
-- Check to see if this is an array
local is_array = true
local i = 1, k, v
for k,v in pairs(o) do
if not (k == i) then
is_array = false
end
i = i + 1
end
local first = true
local lines = {}
i = 1
local estimated = 0
for k,v in (is_array and ipairs or pairs)(o) do
local s
if is_array then
s = ""
else
if type(k) == "string" and k:find("^[%a_][%a%d_]*$") then
s = k .. ' = '
else
s = '[' .. utils.dump(k, 100, no_colorize) .. '] = '
end
end
s = s .. utils.dump(v, depth + 1, no_colorize)
lines[i] = s
estimated = estimated + #s
i = i + 1
end
if estimated > 200 then
local s = "{\n " .. indent
for k, v in pairs(lines) do
s = s .. v .. ",\n " .. indent
end
s = s .. "\n" .. indent .. "}"
return s
else
return "{ " .. table.concat(lines, ", ") .. " }"
end
end
-- This doesn't happen right?
return tostring(o)
end
-- Replace print
function utils.print(...)
local n = select('#', ...)
local arguments = { ... }
for i = 1, n do
arguments[i] = tostring(arguments[i])
end
process.stdout:write(table.concat(arguments, "\t") .. "\n")
end
-- A nice global data dumper
function utils.prettyPrint(...)
local n = select('#', ...)
local arguments = { ... }
for i = 1, n do
arguments[i] = utils.dump(arguments[i])
end
process.stdout:write(table.concat(arguments, "\t") .. "\n")
end
-- Like p, but prints to stderr using blocking I/O for better debugging
function utils.debug(...)
local n = select('#', ...)
local arguments = { ... }
for i = 1, n do
arguments[i] = utils.dump(arguments[i])
end
process.stderr:write(table.concat(arguments, "\t") .. "\n")
end
function utils.bind(fn, self, ...)
local bindArgsLength = select("#", ...)
-- Simple binding, just inserts self (or one arg or any kind)
if bindArgsLength == 0 then
return function (...)
return fn(self, ...)
end
end
-- More complex binding inserts arbitrary number of args into call.
local bindArgs = {...}
return function (...)
local argsLength = select("#", ...)
local args = {...}
local arguments = {}
for i = 1, bindArgsLength do
arguments[i] = bindArgs[i]
end
for i = 1, argsLength do
arguments[i + bindArgsLength] = args[i]
end
return fn(self, unpack(arguments, 1, bindArgsLength + argsLength))
end
end
return utils
--print("nil", dump(nil))
--print("number", dump(42))
--print("boolean", dump(true), dump(false))
--print("string", dump("\"Hello\""), dump("world\nwith\r\nnewlines\r\t\n"))
--print("funct", dump(print))
--print("table", dump({
-- ["nil"] = nil,
-- ["8"] = 8,
-- ["number"] = 42,
-- ["boolean"] = true,
-- ["table"] = {age = 29, name="Tim"},
-- ["string"] = "Another String",
-- ["function"] = dump,
-- ["thread"] = coroutine.create(dump),
-- [print] = {{"deep"},{{"nesting"}},3,4,5},
-- [{1,2,3}] = {4,5,6}
--}))
|
fix utils.dump infinite loop on 32bit
|
fix utils.dump infinite loop on 32bit
|
Lua
|
apache-2.0
|
sousoux/luvit,DBarney/luvit,sousoux/luvit,rjeli/luvit,luvit/luvit,boundary/luvit,bsn069/luvit,rjeli/luvit,DBarney/luvit,boundary/luvit,zhaozg/luvit,boundary/luvit,bsn069/luvit,rjeli/luvit,kaustavha/luvit,rjeli/luvit,sousoux/luvit,sousoux/luvit,bsn069/luvit,zhaozg/luvit,GabrielNicolasAvellaneda/luvit-upstream,GabrielNicolasAvellaneda/luvit-upstream,GabrielNicolasAvellaneda/luvit-upstream,sousoux/luvit,kaustavha/luvit,luvit/luvit,GabrielNicolasAvellaneda/luvit-upstream,DBarney/luvit,boundary/luvit,DBarney/luvit,boundary/luvit,sousoux/luvit,boundary/luvit,kaustavha/luvit
|
6bb4eef6abb723857ee5da3981cffa6a2f5ef794
|
spec/02-integration/05-proxy/06-upstream_timeouts_spec.lua
|
spec/02-integration/05-proxy/06-upstream_timeouts_spec.lua
|
local helpers = require "spec.helpers"
local Factory = require "kong.dao.factory"
local dao_helpers = require "spec.02-integration.02-dao.helpers"
local factory
local function insert_apis(arr)
if type(arr) ~= "table" then
return error("expected arg #1 to be a table", 2)
end
factory:truncate_tables()
for i = 1, #arr do
assert(factory.apis:insert(arr[i]))
end
end
dao_helpers.for_each_dao(function(kong_config)
describe("upstream timeouts", function()
local client
setup(function()
factory = assert(Factory.new(kong_config))
assert(factory:run_migrations())
factory:truncate_tables()
insert_apis {
{
name = "api-1",
methods = "HEAD",
upstream_url = "http://httpbin.org",
upstream_connect_timeout = 1, -- ms
},
{
name = "api-2",
methods = "POST",
upstream_url = "http://httpbin.org",
upstream_send_timeout = 100, -- ms
},
{
name = "api-3",
methods = "GET",
upstream_url = "http://httpbin.org",
upstream_read_timeout = 100, -- ms
}
}
assert(helpers.start_kong({
database = kong_config.database
}))
end)
teardown(function()
helpers.stop_kong(nil, true)
end)
before_each(function()
client = helpers.proxy_client()
end)
after_each(function()
if client then
client:close()
end
end)
describe("upstream_connect_timeout", function()
it("sets upstream connect timeout value", function()
local res = assert(client:send {
method = "HEAD",
path = "/",
})
assert.res_status(504, res)
end)
end)
describe("upstream_read_timeout", function()
it("sets upstream read timeout value", function()
local res = assert(client:send {
method = "GET",
path = "/delay/2",
})
assert.res_status(504, res)
end)
end)
describe("upstream_send_timeout", function()
it("sets upstream send timeout value", function()
local res = assert(client:send {
method = "POST",
path = "/post",
body = {
huge = string.rep("a", 2^20)
},
headers = { ["Content-Type"] = "application/json" }
})
assert.res_status(504, res)
end)
end)
end)
end) -- for_each_dao
|
local helpers = require "spec.helpers"
local Factory = require "kong.dao.factory"
local dao_helpers = require "spec.02-integration.02-dao.helpers"
local factory
local function insert_apis(arr)
if type(arr) ~= "table" then
return error("expected arg #1 to be a table", 2)
end
factory:truncate_tables()
for i = 1, #arr do
assert(factory.apis:insert(arr[i]))
end
end
dao_helpers.for_each_dao(function(kong_config)
describe("upstream timeouts with DB: " .. kong_config.database, function()
local client
setup(function()
factory = assert(Factory.new(kong_config))
assert(factory:run_migrations())
factory:truncate_tables()
insert_apis {
{
name = "api-1",
methods = "HEAD",
upstream_url = "http://httpbin.org:81",
upstream_connect_timeout = 1, -- ms
},
{
name = "api-2",
methods = "POST",
upstream_url = "http://httpbin.org",
upstream_send_timeout = 1, -- ms
},
{
name = "api-3",
methods = "GET",
upstream_url = "http://httpbin.org",
upstream_read_timeout = 1, -- ms
}
}
assert(helpers.start_kong({
database = kong_config.database
}))
end)
teardown(function()
helpers.stop_kong()
end)
before_each(function()
client = helpers.proxy_client()
end)
after_each(function()
if client then
client:close()
end
end)
describe("upstream_connect_timeout", function()
it("sets upstream connect timeout value", function()
local res = assert(client:send {
method = "HEAD",
path = "/",
})
assert.res_status(504, res)
end)
end)
describe("upstream_read_timeout", function()
it("sets upstream read timeout value", function()
local res = assert(client:send {
method = "GET",
path = "/delay/2",
})
assert.res_status(504, res)
end)
end)
describe("upstream_send_timeout", function()
it("sets upstream send timeout value", function()
local res = assert(client:send {
method = "POST",
path = "/post",
body = {
huge = string.rep("a", 2^20)
},
headers = { ["Content-Type"] = "application/json" }
})
-- do *not* use assert.res_status() here in case of
-- failure to avoid a 1MB long error log
assert.equal(504, res.status)
end)
end)
end)
end) -- for_each_dao
|
tests(proxy) fix upstream timeouts tests in CI
|
tests(proxy) fix upstream timeouts tests in CI
|
Lua
|
apache-2.0
|
Kong/kong,icyxp/kong,Mashape/kong,salazar/kong,Kong/kong,jebenexer/kong,ccyphers/kong,shiprabehera/kong,Kong/kong,li-wl/kong,akh00/kong
|
3fc143b9272b45c9957889986ceec5043fb77ff4
|
scripts/main.lua
|
scripts/main.lua
|
--
-- Copyright 2014-2015 Dario Manesku. All rights reserved.
-- License: http://www.opensource.org/licenses/BSD-2-Clause
--
local CMFTSTUDIO_DIR = (path.getabsolute("..") .. "/")
local CMFTSTUDIO_SRC_DIR = (CMFTSTUDIO_DIR .. "src/")
local CMFTSTUDIO_RES_DIR = (CMFTSTUDIO_DIR .. "res/")
local CMFTSTUDIO_RUNTIME_DIR = (CMFTSTUDIO_DIR .. "runtime/")
local CMFTSTUDIO_BUILD_DIR = (CMFTSTUDIO_DIR .. "_build/")
local CMFTSTUDIO_PROJECTS_DIR = (CMFTSTUDIO_DIR .. "_projects/")
local ROOT_DIR = (CMFTSTUDIO_DIR .. "../")
local DEPENDENCY_DIR = (CMFTSTUDIO_DIR .. "dependency/")
local CMFT_DIR = (ROOT_DIR .. "cmft/")
BGFX_DIR = (ROOT_DIR .. "bgfx/")
BX_DIR = (ROOT_DIR .. "bx/")
DM_DIR = (ROOT_DIR .. "dm/")
local BGFX_SCRIPTS_DIR = (BGFX_DIR .. "scripts/")
local DM_SCRIPTS_DIR = (DM_DIR .. "scripts/")
local CMFT_SCRIPTS_DIR = (CMFT_DIR .. "scripts/")
local CMFTSTUDIO_SCRIPTS_DIR = (CMFTSTUDIO_DIR .. "scripts/")
-- Required for bgfx and example-common
function copyLib()
end
newoption
{
trigger = "with-tools",
description = "Enable building tools.",
}
newoption
{
trigger = "unity-build",
description = "Single compilation unit build.",
}
newoption
{
trigger = "with-amalgamated",
description = "Enable amalgamated build.",
}
newoption
{
trigger = "with-sdl",
description = "Enable SDL entry.",
}
if _OPTIONS["with-sdl"] then
if os.is("windows") then
if not os.getenv("SDL2_DIR") then
print("Set SDL2_DIR enviroment variable.")
end
end
end
--
-- Solution
--
solution "cmftStudio"
language "C++"
configurations { "Debug", "Release" }
platforms { "x32", "x64" }
defines
{
"ENTRY_CONFIG_IMPLEMENT_DEFAULT_ALLOCATOR=0",
"BX_CONFIG_ENABLE_MSVC_LEVEL4_WARNINGS=1",
"ENTRY_DEFAULT_WIDTH=1920",
"ENTRY_DEFAULT_HEIGHT=1027",
"BGFX_CONFIG_RENDERER_DIRECT3D9=1",
"BGFX_CONFIG_RENDERER_DIRECT3D11=1",
"BGFX_CONFIG_RENDERER_OPENGL=32",
}
configuration {}
-- Use cmft toolchain for cmft and cmftStudio
dofile (DM_SCRIPTS_DIR .. "dm_toolchain.lua")
dofile (CMFT_SCRIPTS_DIR .. "toolchain.lua")
dofile (CMFT_SCRIPTS_DIR .. "cmft.lua")
dofile (BGFX_SCRIPTS_DIR .. "bgfx.lua")
dm_toolchain(CMFTSTUDIO_BUILD_DIR, CMFTSTUDIO_PROJECTS_DIR, DEPENDENCY_DIR, BX_DIR)
--
-- External projects.
--
bgfxProject("", "StaticLib", {})
dofile (BGFX_SCRIPTS_DIR .. "example-common.lua")
cmftProject(CMFT_DIR)
--
-- Tools/rawcompress project.
--
project "rawcompress"
uuid "4b0e6dae-6486-44ea-a57b-840de7c3a9fe"
kind "ConsoleApp"
includedirs
{
BX_DIR .. "include",
DEPENDENCY_DIR,
}
files
{
"../tools/src/rawcompress.cpp",
}
configuration {}
--
-- cmftStudio project.
--
project "cmftStudio"
uuid("c8847cba-775c-40fd-bcb2-f40f9abb04a7")
kind "WindowedApp"
configuration {}
debugdir (CMFTSTUDIO_RUNTIME_DIR)
includedirs
{
BX_DIR .. "include",
BX_DIR .. "3rdparty",
BGFX_DIR .. "include",
BGFX_DIR .. "3rdparty",
BGFX_DIR .. "examples/common",
BGFX_DIR .. "3rdparty/forsyth-too",
DM_DIR .. "include",
CMFT_DIR .. "include",
DEPENDENCY_DIR,
}
files
{
CMFTSTUDIO_SRC_DIR .. "**.cpp",
CMFTSTUDIO_SRC_DIR .. "**.h",
BGFX_DIR .. "3rdparty/forsyth-too/**.cpp",
BGFX_DIR .. "3rdparty/forsyth-too/**.h",
DM_DIR .. "include/**.h",
}
if _OPTIONS["unity-build"] then
excludes
{
CMFTSTUDIO_SRC_DIR .. "*.cpp",
CMFTSTUDIO_SRC_DIR .. "geometry/*.cpp",
CMFTSTUDIO_SRC_DIR .. "common/*.cpp",
CMFTSTUDIO_SRC_DIR .. "common/allocator/*.cpp",
}
else
excludes
{
CMFTSTUDIO_SRC_DIR .. "build/*.cpp",
}
end
links
{
"bgfx",
"example-common",
"cmft",
}
if _OPTIONS["with-sdl"] then
defines { "ENTRY_CONFIG_USE_SDL=1" }
links { "SDL2" }
configuration { "x32", "windows" }
libdirs { "$(SDL2_DIR)/lib/x86" }
configuration { "x64", "windows" }
libdirs { "$(SDL2_DIR)/lib/x64" }
configuration {}
end
configuration { "vs*" }
buildoptions
{
"/wd 4127", -- Disable 'Conditional expression is constant' for do {} while(0).
"/wd 4201", -- Disable 'Nonstandard extension used: nameless struct/union'. Used for uniforms in the project.
"/wd 4345", -- Disable 'An object of POD type constructed with an initializer of the form () will be default-initialized'. It's an obsolete warning.
}
linkoptions
{
"/ignore:4199", -- LNK4199: /DELAYLOAD:*.dll ignored; no imports found from *.dll
}
links
{ -- this is needed only for testing with GLES2/3 on Windows with VS2008
"DelayImp",
}
files
{
CMFTSTUDIO_RES_DIR .. "icon/*"
}
configuration { "vs*", "x32" }
links
{
"psapi",
}
configuration { "vs2010" }
linkoptions
{ -- this is needed only for testing with GLES2/3 on Windows with VS201x
"/DELAYLOAD:\"libEGL.dll\"",
"/DELAYLOAD:\"libGLESv2.dll\"",
}
configuration { "linux-*" }
links
{
"X11",
"GL",
"pthread",
}
configuration { "xcode4 or osx" }
includedirs
{
path.join(BGFX_DIR, "3rdparty/khronos"),
}
files
{
path.join(BGFX_DIR, "src/**.mm"),
path.join(BGFX_DIR, "examples/common/**.mm"),
}
links
{
"Cocoa.framework",
"OpenGL.framework",
}
configuration { "xcode4" }
linkoptions
{
"-framework Cocoa",
"-lc++",
}
configuration {}
if _OPTIONS["with-tools"] then
dofile (BGFX_SCRIPTS_DIR .. "makedisttex.lua")
dofile (BGFX_SCRIPTS_DIR .. "shaderc.lua")
dofile (BGFX_SCRIPTS_DIR .. "texturec.lua")
dofile (BGFX_SCRIPTS_DIR .. "geometryc.lua")
end
strip()
-- vim: set sw=4 ts=4 expandtab:
|
--
-- Copyright 2014-2015 Dario Manesku. All rights reserved.
-- License: http://www.opensource.org/licenses/BSD-2-Clause
--
local CMFTSTUDIO_DIR = (path.getabsolute("..") .. "/")
local CMFTSTUDIO_SRC_DIR = (CMFTSTUDIO_DIR .. "src/")
local CMFTSTUDIO_RES_DIR = (CMFTSTUDIO_DIR .. "res/")
local CMFTSTUDIO_RUNTIME_DIR = (CMFTSTUDIO_DIR .. "runtime/")
local CMFTSTUDIO_BUILD_DIR = (CMFTSTUDIO_DIR .. "_build/")
local CMFTSTUDIO_PROJECTS_DIR = (CMFTSTUDIO_DIR .. "_projects/")
local ROOT_DIR = (CMFTSTUDIO_DIR .. "../")
local DEPENDENCY_DIR = (CMFTSTUDIO_DIR .. "dependency/")
local CMFT_DIR = (ROOT_DIR .. "cmft/")
BGFX_DIR = (ROOT_DIR .. "bgfx/")
BX_DIR = (ROOT_DIR .. "bx/")
DM_DIR = (ROOT_DIR .. "dm/")
local BGFX_SCRIPTS_DIR = (BGFX_DIR .. "scripts/")
local DM_SCRIPTS_DIR = (DM_DIR .. "scripts/")
local CMFT_SCRIPTS_DIR = (CMFT_DIR .. "scripts/")
local CMFTSTUDIO_SCRIPTS_DIR = (CMFTSTUDIO_DIR .. "scripts/")
-- Required for bgfx and example-common
function copyLib()
end
newoption
{
trigger = "with-tools",
description = "Enable building tools.",
}
newoption
{
trigger = "unity-build",
description = "Single compilation unit build.",
}
newoption
{
trigger = "with-amalgamated",
description = "Enable amalgamated build.",
}
newoption
{
trigger = "with-sdl",
description = "Enable SDL entry.",
}
if _OPTIONS["with-sdl"] then
if os.is("windows") then
if not os.getenv("SDL2_DIR") then
print("Set SDL2_DIR enviroment variable.")
end
end
end
--
-- Solution
--
solution "cmftStudio"
language "C++"
configurations { "Debug", "Release" }
platforms { "x32", "x64" }
defines
{
"ENTRY_CONFIG_IMPLEMENT_DEFAULT_ALLOCATOR=0",
"BX_CONFIG_ENABLE_MSVC_LEVEL4_WARNINGS=1",
"ENTRY_DEFAULT_WIDTH=1920",
"ENTRY_DEFAULT_HEIGHT=1027",
"BGFX_CONFIG_RENDERER_OPENGL=21",
}
configuration { "vs or mingw-*" }
defines
{
"BGFX_CONFIG_RENDERER_DIRECT3D9=1",
"BGFX_CONFIG_RENDERER_DIRECT3D11=1",
}
configuration {}
-- Use cmft toolchain for cmft and cmftStudio
dofile (DM_SCRIPTS_DIR .. "dm_toolchain.lua")
dofile (CMFT_SCRIPTS_DIR .. "toolchain.lua")
dofile (CMFT_SCRIPTS_DIR .. "cmft.lua")
dofile (BGFX_SCRIPTS_DIR .. "bgfx.lua")
dm_toolchain(CMFTSTUDIO_BUILD_DIR, CMFTSTUDIO_PROJECTS_DIR, DEPENDENCY_DIR, BX_DIR)
--
-- External projects.
--
bgfxProject("", "StaticLib", {})
dofile (BGFX_SCRIPTS_DIR .. "example-common.lua")
cmftProject(CMFT_DIR)
--
-- Tools/rawcompress project.
--
project "rawcompress"
uuid "4b0e6dae-6486-44ea-a57b-840de7c3a9fe"
kind "ConsoleApp"
includedirs
{
BX_DIR .. "include",
DEPENDENCY_DIR,
}
files
{
"../tools/src/rawcompress.cpp",
}
configuration {}
--
-- cmftStudio project.
--
project "cmftStudio"
uuid("c8847cba-775c-40fd-bcb2-f40f9abb04a7")
kind "WindowedApp"
configuration {}
debugdir (CMFTSTUDIO_RUNTIME_DIR)
includedirs
{
BX_DIR .. "include",
BX_DIR .. "3rdparty",
BGFX_DIR .. "include",
BGFX_DIR .. "3rdparty",
BGFX_DIR .. "examples/common",
BGFX_DIR .. "3rdparty/forsyth-too",
DM_DIR .. "include",
CMFT_DIR .. "include",
DEPENDENCY_DIR,
}
files
{
CMFTSTUDIO_SRC_DIR .. "**.cpp",
CMFTSTUDIO_SRC_DIR .. "**.h",
BGFX_DIR .. "3rdparty/forsyth-too/**.cpp",
BGFX_DIR .. "3rdparty/forsyth-too/**.h",
DM_DIR .. "include/**.h",
}
if _OPTIONS["unity-build"] then
excludes
{
CMFTSTUDIO_SRC_DIR .. "*.cpp",
CMFTSTUDIO_SRC_DIR .. "geometry/*.cpp",
CMFTSTUDIO_SRC_DIR .. "common/*.cpp",
CMFTSTUDIO_SRC_DIR .. "common/allocator/*.cpp",
}
else
excludes
{
CMFTSTUDIO_SRC_DIR .. "build/*.cpp",
}
end
links
{
"bgfx",
"example-common",
"cmft",
}
if _OPTIONS["with-sdl"] then
defines { "ENTRY_CONFIG_USE_SDL=1" }
links { "SDL2" }
configuration { "x32", "windows" }
libdirs { "$(SDL2_DIR)/lib/x86" }
configuration { "x64", "windows" }
libdirs { "$(SDL2_DIR)/lib/x64" }
configuration {}
end
configuration { "vs*" }
buildoptions
{
"/wd 4127", -- Disable 'Conditional expression is constant' for do {} while(0).
"/wd 4201", -- Disable 'Nonstandard extension used: nameless struct/union'. Used for uniforms in the project.
"/wd 4345", -- Disable 'An object of POD type constructed with an initializer of the form () will be default-initialized'. It's an obsolete warning.
}
linkoptions
{
"/ignore:4199", -- LNK4199: /DELAYLOAD:*.dll ignored; no imports found from *.dll
}
links
{ -- this is needed only for testing with GLES2/3 on Windows with VS2008
"DelayImp",
}
files
{
CMFTSTUDIO_RES_DIR .. "icon/*"
}
configuration { "vs*", "x32" }
links
{
"psapi",
}
configuration { "vs2010" }
linkoptions
{ -- this is needed only for testing with GLES2/3 on Windows with VS201x
"/DELAYLOAD:\"libEGL.dll\"",
"/DELAYLOAD:\"libGLESv2.dll\"",
}
configuration { "linux-*" }
links
{
"X11",
"GL",
"pthread",
}
configuration { "xcode4 or osx" }
includedirs
{
path.join(BGFX_DIR, "3rdparty/khronos"),
}
files
{
path.join(BGFX_DIR, "src/**.mm"),
path.join(BGFX_DIR, "examples/common/**.mm"),
}
links
{
"Cocoa.framework",
"OpenGL.framework",
}
configuration { "xcode4" }
linkoptions
{
"-framework Cocoa",
"-lc++",
}
configuration {}
if _OPTIONS["with-tools"] then
dofile (BGFX_SCRIPTS_DIR .. "makedisttex.lua")
dofile (BGFX_SCRIPTS_DIR .. "shaderc.lua")
dofile (BGFX_SCRIPTS_DIR .. "texturec.lua")
dofile (BGFX_SCRIPTS_DIR .. "geometryc.lua")
end
strip()
-- vim: set sw=4 ts=4 expandtab:
|
Fixup for previous commit.
|
Fixup for previous commit.
|
Lua
|
bsd-2-clause
|
leegoonz/cmftStudio,leegoonz/cmftStudio,leegoonz/cmftStudio
|
a7a5f5b1b2a491430d644e986b93d8beaba1fb66
|
web.lua
|
web.lua
|
_G.TURBO_SSL = true
local turbo = require 'turbo'
local uuid = require 'uuid'
local ffi = require 'ffi'
local md5 = require 'md5'
require 'pl'
require './lib/portable'
require './lib/LeakyReLU'
local cmd = torch.CmdLine()
cmd:text()
cmd:text("waifu2x-api")
cmd:text("Options:")
cmd:option("-port", 8812, 'listen port')
cmd:option("-gpu", 1, 'Device ID')
cmd:option("-core", 2, 'number of CPU cores')
local opt = cmd:parse(arg)
cutorch.setDevice(opt.gpu)
torch.setdefaulttensortype('torch.FloatTensor')
torch.setnumthreads(opt.core)
local iproc = require './lib/iproc'
local reconstruct = require './lib/reconstruct'
local image_loader = require './lib/image_loader'
local MODEL_DIR = "./models/anime_style_art_rgb"
local noise1_model = torch.load(path.join(MODEL_DIR, "noise1_model.t7"), "ascii")
local noise2_model = torch.load(path.join(MODEL_DIR, "noise2_model.t7"), "ascii")
local scale20_model = torch.load(path.join(MODEL_DIR, "scale2.0x_model.t7"), "ascii")
local USE_CACHE = true
local CACHE_DIR = "./cache"
local MAX_NOISE_IMAGE = 2560 * 2560
local MAX_SCALE_IMAGE = 1280 * 1280
local CURL_OPTIONS = {
request_timeout = 15,
connect_timeout = 10,
allow_redirects = true,
max_redirects = 2
}
local CURL_MAX_SIZE = 2 * 1024 * 1024
local BLOCK_OFFSET = 7 -- see srcnn.lua
local function valid_size(x, scale)
if scale == 0 then
return x:size(2) * x:size(3) <= MAX_NOISE_IMAGE
else
return x:size(2) * x:size(3) <= MAX_SCALE_IMAGE
end
end
local function get_image(req)
local file = req:get_argument("file", "")
local url = req:get_argument("url", "")
local blob = nil
local img = nil
local alpha = nil
if file and file:len() > 0 then
blob = file
img, alpha = image_loader.decode_float(blob)
elseif url and url:len() > 0 then
local res = coroutine.yield(
turbo.async.HTTPClient({verify_ca=false},
nil,
CURL_MAX_SIZE):fetch(url, CURL_OPTIONS)
)
if res.code == 200 then
local content_type = res.headers:get("Content-Type", true)
if type(content_type) == "table" then
content_type = content_type[1]
end
if content_type and content_type:find("image") then
blob = res.body
img, alpha = image_loader.decode_float(blob)
end
end
end
return img, blob, alpha
end
local function apply_denoise1(x)
return reconstruct.image(noise1_model, x, BLOCK_OFFSET)
end
local function apply_denoise2(x)
return reconstruct.image(noise2_model, x, BLOCK_OFFSET)
end
local function apply_scale2x(x)
return reconstruct.scale(scale20_model, 2.0, x, BLOCK_OFFSET)
end
local function cache_do(cache, x, func)
if path.exists(cache) then
return image.load(cache)
else
x = func(x)
image.save(cache, x)
return x
end
end
local function client_disconnected(handler)
return not(handler.request and
handler.request.connection and
handler.request.connection.stream and
(not handler.request.connection.stream:closed()))
end
local APIHandler = class("APIHandler", turbo.web.RequestHandler)
function APIHandler:post()
if client_disconnected(self) then
self:set_status(400)
self:write("client disconnected")
return
end
local x, src, alpha = get_image(self)
local scale = tonumber(self:get_argument("scale", "0"))
local noise = tonumber(self:get_argument("noise", "0"))
if x and valid_size(x, scale) then
if USE_CACHE and (noise ~= 0 or scale ~= 0) then
local hash = md5.sumhexa(src)
local cache_noise1 = path.join(CACHE_DIR, hash .. "_noise1.png")
local cache_noise2 = path.join(CACHE_DIR, hash .. "_noise2.png")
local cache_scale = path.join(CACHE_DIR, hash .. "_scale.png")
local cache_noise1_scale = path.join(CACHE_DIR, hash .. "_noise1_scale.png")
local cache_noise2_scale = path.join(CACHE_DIR, hash .. "_noise2_scale.png")
if noise == 1 then
x = cache_do(cache_noise1, x, apply_denoise1)
elseif noise == 2 then
x = cache_do(cache_noise2, x, apply_denoise2)
end
if scale == 1 or scale == 2 then
if noise == 1 then
x = cache_do(cache_noise1_scale, x, apply_scale2x)
elseif noise == 2 then
x = cache_do(cache_noise2_scale, x, apply_scale2x)
else
x = cache_do(cache_scale, x, apply_scale2x)
end
if scale == 1 then
x = iproc.scale(x,
math.floor(x:size(3) * (1.6 / 2.0) + 0.5),
math.floor(x:size(2) * (1.6 / 2.0) + 0.5),
"Jinc")
end
end
elseif noise ~= 0 or scale ~= 0 then
if noise == 1 then
x = apply_denoise1(x)
elseif noise == 2 then
x = apply_denoise2(x)
end
if scale == 1 then
local x16 = {math.floor(x:size(3) * 1.6 + 0.5), math.floor(x:size(2) * 1.6 + 0.5)}
x = apply_scale2x(x)
x = iproc.scale(x, x16[1], x16[2], "Jinc")
elseif scale == 2 then
x = apply_scale2x(x)
end
end
local name = uuid() .. ".png"
local blob, len = image_loader.encode_png(x, alpha)
self:set_header("Content-Disposition", string.format('filename="%s"', name))
self:set_header("Content-Type", "image/png")
self:set_header("Content-Length", string.format("%d", len))
self:write(ffi.string(blob, len))
else
if not x then
self:set_status(400)
self:write("ERROR: unsupported image format.")
else
self:set_status(400)
self:write("ERROR: image size exceeds maximum allowable size.")
end
end
collectgarbage()
end
local FormHandler = class("FormHandler", turbo.web.RequestHandler)
local index_ja = file.read("./assets/index.ja.html")
local index_en = file.read("./assets/index.html")
function FormHandler:get()
local lang = self.request.headers:get("Accept-Language")
if lang then
local langs = utils.split(lang, ",")
for i = 1, #langs do
langs[i] = utils.split(langs[i], ";")[1]
end
if langs[1] == "ja" then
self:write(index_ja)
else
self:write(index_en)
end
else
self:write(index_en)
end
end
local app = turbo.web.Application:new(
{
{"^/$", FormHandler},
{"^/index.html", turbo.web.StaticFileHandler, path.join("./assets", "index.html")},
{"^/index.ja.html", turbo.web.StaticFileHandler, path.join("./assets", "index.ja.html")},
{"^/api$", APIHandler},
}
)
app:listen(opt.port, "0.0.0.0", {max_body_size = CURL_MAX_SIZE})
turbo.ioloop.instance():start()
|
_G.TURBO_SSL = true
local turbo = require 'turbo'
local uuid = require 'uuid'
local ffi = require 'ffi'
local md5 = require 'md5'
require 'pl'
require './lib/portable'
require './lib/LeakyReLU'
local cmd = torch.CmdLine()
cmd:text()
cmd:text("waifu2x-api")
cmd:text("Options:")
cmd:option("-port", 8812, 'listen port')
cmd:option("-gpu", 1, 'Device ID')
cmd:option("-core", 2, 'number of CPU cores')
local opt = cmd:parse(arg)
cutorch.setDevice(opt.gpu)
torch.setdefaulttensortype('torch.FloatTensor')
torch.setnumthreads(opt.core)
local iproc = require './lib/iproc'
local reconstruct = require './lib/reconstruct'
local image_loader = require './lib/image_loader'
local MODEL_DIR = "./models/anime_style_art_rgb"
local noise1_model = torch.load(path.join(MODEL_DIR, "noise1_model.t7"), "ascii")
local noise2_model = torch.load(path.join(MODEL_DIR, "noise2_model.t7"), "ascii")
local scale20_model = torch.load(path.join(MODEL_DIR, "scale2.0x_model.t7"), "ascii")
local USE_CACHE = true
local CACHE_DIR = "./cache"
local MAX_NOISE_IMAGE = 2560 * 2560
local MAX_SCALE_IMAGE = 1280 * 1280
local CURL_OPTIONS = {
request_timeout = 15,
connect_timeout = 10,
allow_redirects = true,
max_redirects = 2
}
local CURL_MAX_SIZE = 2 * 1024 * 1024
local BLOCK_OFFSET = 7 -- see srcnn.lua
local function valid_size(x, scale)
if scale == 0 then
return x:size(2) * x:size(3) <= MAX_NOISE_IMAGE
else
return x:size(2) * x:size(3) <= MAX_SCALE_IMAGE
end
end
local function get_image(req)
local file = req:get_argument("file", "")
local url = req:get_argument("url", "")
local blob = nil
local img = nil
local alpha = nil
if file and file:len() > 0 then
blob = file
img, alpha = image_loader.decode_float(blob)
elseif url and url:len() > 0 then
local res = coroutine.yield(
turbo.async.HTTPClient({verify_ca=false},
nil,
CURL_MAX_SIZE):fetch(url, CURL_OPTIONS)
)
if res.code == 200 then
local content_type = res.headers:get("Content-Type", true)
if type(content_type) == "table" then
content_type = content_type[1]
end
if content_type and content_type:find("image") then
blob = res.body
img, alpha = image_loader.decode_float(blob)
end
end
end
return img, blob, alpha
end
local function apply_denoise1(x)
return reconstruct.image(noise1_model, x, BLOCK_OFFSET)
end
local function apply_denoise2(x)
return reconstruct.image(noise2_model, x, BLOCK_OFFSET)
end
local function apply_scale2x(x)
return reconstruct.scale(scale20_model, 2.0, x, BLOCK_OFFSET)
end
local function cache_do(cache, x, func)
if path.exists(cache) then
return image.load(cache)
else
x = func(x)
image.save(cache, x)
return x
end
end
local function client_disconnected(handler)
return not(handler.request and
handler.request.connection and
handler.request.connection.stream and
(not handler.request.connection.stream:closed()))
end
local APIHandler = class("APIHandler", turbo.web.RequestHandler)
function APIHandler:post()
if client_disconnected(self) then
self:set_status(400)
self:write("client disconnected")
return
end
local x, src, alpha = get_image(self)
local scale = tonumber(self:get_argument("scale", "0"))
local noise = tonumber(self:get_argument("noise", "0"))
if x and valid_size(x, scale) then
if USE_CACHE and (noise ~= 0 or scale ~= 0) then
local hash = md5.sumhexa(src)
local cache_noise1 = path.join(CACHE_DIR, hash .. "_noise1.png")
local cache_noise2 = path.join(CACHE_DIR, hash .. "_noise2.png")
local cache_scale = path.join(CACHE_DIR, hash .. "_scale.png")
local cache_noise1_scale = path.join(CACHE_DIR, hash .. "_noise1_scale.png")
local cache_noise2_scale = path.join(CACHE_DIR, hash .. "_noise2_scale.png")
if noise == 1 then
x = cache_do(cache_noise1, x, apply_denoise1)
elseif noise == 2 then
x = cache_do(cache_noise2, x, apply_denoise2)
end
if scale == 1 or scale == 2 then
if noise == 1 then
x = cache_do(cache_noise1_scale, x, apply_scale2x)
elseif noise == 2 then
x = cache_do(cache_noise2_scale, x, apply_scale2x)
else
x = cache_do(cache_scale, x, apply_scale2x)
end
if scale == 1 then
x = iproc.scale(x,
math.floor(x:size(3) * (1.6 / 2.0) + 0.5),
math.floor(x:size(2) * (1.6 / 2.0) + 0.5),
"Jinc")
end
end
elseif noise ~= 0 or scale ~= 0 then
if noise == 1 then
x = apply_denoise1(x)
elseif noise == 2 then
x = apply_denoise2(x)
end
if scale == 1 then
local x16 = {math.floor(x:size(3) * 1.6 + 0.5), math.floor(x:size(2) * 1.6 + 0.5)}
x = apply_scale2x(x)
x = iproc.scale(x, x16[1], x16[2], "Jinc")
elseif scale == 2 then
x = apply_scale2x(x)
end
end
local name = uuid() .. ".png"
local blob, len = image_loader.encode_png(x, alpha)
self:set_header("Content-Disposition", string.format('filename="%s"', name))
self:set_header("Content-Type", "image/png")
self:set_header("Content-Length", string.format("%d", len))
self:write(ffi.string(blob, len))
else
if not x then
self:set_status(400)
self:write("ERROR: unsupported image format.")
else
self:set_status(400)
self:write("ERROR: image size exceeds maximum allowable size.")
end
end
collectgarbage()
end
local FormHandler = class("FormHandler", turbo.web.RequestHandler)
local index_ja = file.read("./assets/index.ja.html")
local index_en = file.read("./assets/index.html")
function FormHandler:get()
local lang = self.request.headers:get("Accept-Language")
if lang then
local langs = utils.split(lang, ",")
for i = 1, #langs do
langs[i] = utils.split(langs[i], ";")[1]
end
if langs[1] == "ja" then
self:write(index_ja)
else
self:write(index_en)
end
else
self:write(index_en)
end
end
turbo.log.categories = {
["success"] = true,
["notice"] = false,
["warning"] = true,
["error"] = true,
["debug"] = false,
["development"] = false
}
local app = turbo.web.Application:new(
{
{"^/$", FormHandler},
{"^/index.html", turbo.web.StaticFileHandler, path.join("./assets", "index.html")},
{"^/index.ja.html", turbo.web.StaticFileHandler, path.join("./assets", "index.ja.html")},
{"^/api$", APIHandler},
}
)
app:listen(opt.port, "0.0.0.0", {max_body_size = CURL_MAX_SIZE})
turbo.ioloop.instance():start()
|
fix disk full
|
fix disk full
|
Lua
|
mit
|
AshWilliams/waifu2x,Spitfire1900/upscaler,archienz/waifu2x,darkrebirth/waifu2x,Spitfire1900/upscaler,gotomypc/waifu2x,noname007/waifu2x,HastyJ/waifu2x,zyhkz/waifu2x,GodOfConquest/waifu2x,athasach/waifu2x,zhaohao/waifu2x,ivanfoong/waifu2x,srivignessh/waifu2x,ilovecv/waifu2x,lazypanda/waifu2x,gotomypc/waifu2x,vincentstorme/waifu2x,nagadomi/waifu2x,programlocura/waifu2x,nagadomi/waifu2x,nagadomi/waifu2x,ss-bb/waifu2x,wan-qy/waifu2x,vitaliylag/waifu2x,stps/waifu2x,karamage/waifu2x,zyhkz/waifu2x,nagadomi/waifu2x,vvw/waifu2x,Vamic/waifu2x,higankanshi/waifu2x,cvfish/waifu2x,Lilystar/waifu2x,GodOfConquest/waifu2x,nopsky/waifu2x,zyhkz/waifu2x,Laendasill/waifu2x,Laendasill/waifu2x,higankanshi/waifu2x,zhaohao/waifu2x,HastyJ/waifu2x,Mastersey/waifu2x,vitaliylag/waifu2x,srivignessh/waifu2x,rohmad-st/waifu2x,Mastersey/waifu2x,KevinFrans3/waifu2x,karamage/waifu2x,cvfish/waifu2x,nopsky/waifu2x,GrimDerp/waifu2x,ivanfoong/waifu2x,stps/waifu2x,programlocura/waifu2x,varner/waifu2x,darkrebirth/waifu2x,vvw/waifu2x,vincentstorme/waifu2x,zyhkz/waifu2x,YosAwed/waifu2x,Vamic/waifu2x,mcanthony/waifu2x,noname007/waifu2x,varner/waifu2x,GrimDerp/waifu2x,ktcunreal/waifu2x,KevinFrans3/waifu2x,Lilystar/waifu2x,AshWilliams/waifu2x,ilovecv/waifu2x,lazypanda/waifu2x,wan-qy/waifu2x,ss-bb/waifu2x,higankanshi/waifu2x,nagadomi/waifu2x,athasach/waifu2x,rohmad-st/waifu2x,ktcunreal/waifu2x,vitaliylag/waifu2x,mcanthony/waifu2x,YosAwed/waifu2x,archienz/waifu2x
|
4c245ed30a730d4bb721ee4c0b204cc2a536c803
|
hymn/ui.lua
|
hymn/ui.lua
|
local quickie = require "libs.quickie"
local LogicCore = require "hymn.logiccore"
local sharedui = require "shared.ui"
local ui = {}
local inputHandler
local entityManager
local selectionCircle = love.graphics.newImage("images/ui/selectionCircle.png")
local pathFlag = love.graphics.newImage("images/ui/waypoint.png")
function ui.load()
-- preload fonts
fonts = {
[12] = love.graphics.newFont("fonts/Edson_Comics_Bold.ttf", 28),
[20] = love.graphics.newFont("fonts/Edson_Comics_Bold.ttf", 45),
}
love.graphics.setBackgroundColor(17,17,17)
love.graphics.setFont(fonts[12])
-- group defaults
quickie.group.default.size[1] = 150
quickie.group.default.size[2] = 25
quickie.group.default.spacing = 5
inputHandler = LogicCore.inputHandler
entityManager = LogicCore.entityManager
ui.windowWidth, ui.windowHeight = love.graphics.getDimensions()
end
function ui.update(dt)
love.graphics.setColor(0, 0, 0, 255)
quickie.Label { pos = { ui.windowWidth - 200, ui.windowHeight - 40 }, text = "Spice: " .. LogicCore.players[1].resource }
quickie.Label { pos = { ui.windowWidth - 350, ui.windowHeight - 40 }, text = "rate: " .. 800/LogicCore.players[1].resource }
if quickie.Button { text = "Build", pos = { 10, ui.windowHeight - 40 } } then
inputHandler:setMode("build")
end
if inputHandler.selection and quickie.Button { text = "Path", pos = { 170, ui.windowHeight - 40 } } then
inputHandler:setMode("path")
end
end
function ui.draw()
love.graphics.translate(inputHandler.translate.x, inputHandler.translate.y)
for id, entity in pairs(entityManager.entities) do
if entity.health then
sharedui.drawHealthBar(entity)
end
end
-- draw selection
local entity = inputHandler.selection and entityManager.entities[inputHandler.selection]
if entity then
love.graphics.draw(selectionCircle, entity.position.x-126/2, entity.position.y-126/2)
if entity.path then
local startPoint = entity.position
for _, endPoint in ipairs(entity.path) do
love.graphics.line(startPoint.x, startPoint.y, endPoint.x, endPoint.y)
love.graphics.draw(pathFlag, endPoint.x-8, endPoint.y-8)
startPoint = endPoint
end
end
end
love.graphics.translate(-inputHandler.translate.x, -inputHandler.translate.y)
love.graphics.rectangle("fill", 0, ui.windowHeight - 50, ui.windowWidth, 50)
quickie.core.draw()
end
function ui.resize(w, h)
ui.windowWidth = w
ui.windowHeight = h
end
return ui
|
local quickie = require "libs.quickie"
local LogicCore = require "hymn.logiccore"
local sharedui = require "shared.ui"
local ui = {}
local inputHandler
local entityManager
local selectionCircle = love.graphics.newImage("images/ui/selectionCircle.png")
local pathFlag = love.graphics.newImage("images/ui/waypoint.png")
function ui.load()
-- preload fonts
fonts = {
[12] = love.graphics.newFont("fonts/Edson_Comics_Bold.ttf", 28),
[20] = love.graphics.newFont("fonts/Edson_Comics_Bold.ttf", 45),
}
love.graphics.setBackgroundColor(17,17,17)
love.graphics.setFont(fonts[12])
-- group defaults
quickie.group.default.size[1] = 150
quickie.group.default.size[2] = 25
quickie.group.default.spacing = 5
inputHandler = LogicCore.inputHandler
entityManager = LogicCore.entityManager
ui.windowWidth, ui.windowHeight = love.graphics.getDimensions()
end
function ui.update(dt)
love.graphics.setColor(0, 0, 0, 255)
local resourceText = string.format("%.2f", 800/LogicCore.players[1].resource)
quickie.Label { pos = { ui.windowWidth - 200, ui.windowHeight - 40 }, text = "Spice: " .. LogicCore.players[1].resource }
quickie.Label { pos = { ui.windowWidth - 350, ui.windowHeight - 40 }, text = "rate: " .. resourceText }
if quickie.Button { text = "Build", pos = { 10, ui.windowHeight - 40 } } then
inputHandler:setMode("build")
end
if inputHandler.selection and quickie.Button { text = "Path", pos = { 170, ui.windowHeight - 40 } } then
inputHandler:setMode("path")
end
end
function ui.draw()
love.graphics.translate(inputHandler.translate.x, inputHandler.translate.y)
for id, entity in pairs(entityManager.entities) do
if entity.health then
sharedui.drawHealthBar(entity)
end
end
-- draw selection
local entity = inputHandler.selection and entityManager.entities[inputHandler.selection]
if entity then
love.graphics.draw(selectionCircle, entity.position.x-126/2, entity.position.y-126/2)
if entity.path then
local startPoint = entity.position
for _, endPoint in ipairs(entity.path) do
love.graphics.line(startPoint.x, startPoint.y, endPoint.x, endPoint.y)
love.graphics.draw(pathFlag, endPoint.x-8, endPoint.y-8)
startPoint = endPoint
end
end
end
love.graphics.translate(-inputHandler.translate.x, -inputHandler.translate.y)
love.graphics.rectangle("fill", 0, ui.windowHeight - 50, ui.windowWidth, 50)
quickie.core.draw()
end
function ui.resize(w, h)
ui.windowWidth = w
ui.windowHeight = h
end
return ui
|
Hymn: UI: Fix: Rounding gather rate
|
Hymn: UI: Fix: Rounding gather rate
|
Lua
|
mit
|
ExcelF/project-navel
|
b6f36ca91b74e708cb8866a0299923dab3f5343b
|
applications/luci-app-openvpn/luasrc/controller/openvpn.lua
|
applications/luci-app-openvpn/luasrc/controller/openvpn.lua
|
-- Copyright 2008 Steven Barth <steven@midlink.org>
-- Copyright 2008 Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
module("luci.controller.openvpn", package.seeall)
function index()
entry( {"admin", "vpn", "openvpn"}, cbi("openvpn"), _("OpenVPN") ).acl_depends = { "luci-app-openvpn" }
entry( {"admin", "vpn", "openvpn", "basic"}, cbi("openvpn-basic"), nil ).leaf = true
entry( {"admin", "vpn", "openvpn", "advanced"}, cbi("openvpn-advanced"), nil ).leaf = true
entry( {"admin", "vpn", "openvpn", "file"}, form("openvpn-file"), nil ).leaf = true
entry( {"admin", "vpn", "openvpn", "upload"}, call("ovpn_upload"))
end
function ovpn_upload()
local fs = require("nixio.fs")
local http = require("luci.http")
local util = require("luci.util")
local uci = require("luci.model.uci").cursor()
local upload = http.formvalue("ovpn_file")
local name = http.formvalue("instance_name2")
local file = "/etc/openvpn/" ..name.. ".ovpn"
if name and upload then
local fp
http.setfilehandler(
function(meta, chunk, eof)
local data = util.trim(chunk:gsub("\r\n", "\n")) .. "\n"
data = util.trim(data:gsub("[\128-\255]", ""))
if not fp and meta and meta.name == "ovpn_file" then
fp = io.open(file, "w")
end
if fp and data then
fp:write(data)
end
if fp and eof then
fp:close()
end
end
)
if fs.access(file) then
if not uci:get_first("openvpn", name) then
uci:set("openvpn", name, "openvpn")
uci:set("openvpn", name, "config", file)
uci:save("openvpn")
uci:commit("openvpn")
end
end
end
http.redirect(luci.dispatcher.build_url('admin/vpn/openvpn'))
end
|
-- Copyright 2008 Steven Barth <steven@midlink.org>
-- Copyright 2008 Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
module("luci.controller.openvpn", package.seeall)
function index()
entry( {"admin", "vpn", "openvpn"}, cbi("openvpn"), _("OpenVPN") ).acl_depends = { "luci-app-openvpn" }
entry( {"admin", "vpn", "openvpn", "basic"}, cbi("openvpn-basic"), nil ).leaf = true
entry( {"admin", "vpn", "openvpn", "advanced"}, cbi("openvpn-advanced"), nil ).leaf = true
entry( {"admin", "vpn", "openvpn", "file"}, form("openvpn-file"), nil ).leaf = true
entry( {"admin", "vpn", "openvpn", "upload"}, call("ovpn_upload"))
end
function ovpn_upload()
local fs = require("nixio.fs")
local http = require("luci.http")
local util = require("luci.util")
local uci = require("luci.model.uci").cursor()
local upload = http.formvalue("ovpn_file")
local name = http.formvalue("instance_name2")
local basedir = "/etc/openvpn"
local file = basedir.. "/" ..name.. ".ovpn"
if not fs.stat(basedir) then
fs.mkdir(basedir)
end
if name and upload then
local fp
http.setfilehandler(
function(meta, chunk, eof)
local data = util.trim(chunk:gsub("\r\n", "\n")) .. "\n"
data = util.trim(data:gsub("[\128-\255]", ""))
if not fp and meta and meta.name == "ovpn_file" then
fp = io.open(file, "w")
end
if fp and data then
fp:write(data)
end
if fp and eof then
fp:close()
end
end
)
if fs.access(file) then
if not uci:get_first("openvpn", name) then
uci:set("openvpn", name, "openvpn")
uci:set("openvpn", name, "config", file)
uci:save("openvpn")
uci:commit("openvpn")
end
end
end
http.redirect(luci.dispatcher.build_url('admin/vpn/openvpn'))
end
|
luci-app-openvpn: create base directory if not available
|
luci-app-openvpn: create base directory if not available
* trivial fix for never ending ticket #3454
Signed-off-by: Dirk Brenken <34c6fceca75e456f25e7e99531e2425c6c1de443@brenken.org>
|
Lua
|
apache-2.0
|
hnyman/luci,lbthomsen/openwrt-luci,lbthomsen/openwrt-luci,openwrt/luci,openwrt/luci,lbthomsen/openwrt-luci,openwrt/luci,lbthomsen/openwrt-luci,openwrt/luci,lbthomsen/openwrt-luci,lbthomsen/openwrt-luci,openwrt/luci,openwrt/luci,hnyman/luci,hnyman/luci,lbthomsen/openwrt-luci,openwrt/luci,hnyman/luci,hnyman/luci,hnyman/luci,hnyman/luci,hnyman/luci,lbthomsen/openwrt-luci,openwrt/luci
|
7a01a1e37cc96dddb99a995f58bfa733779362fd
|
extensions/row.lua
|
extensions/row.lua
|
local params = {...}
local Dataframe = params[1]
local argcheck = require "argcheck"
local doc = require "argcheck.doc"
doc[[
## Row functions
]]
Dataframe.get_row = argcheck{
doc = [[
<a name="Dataframe.get_row">
### Dataframe.get_row(@ARGP)
Gets a single row from the Dataframe
@ARGT
_Return value_: A table with the row content
]],
{name="self", type="Dataframe"},
{name='index', type='number', doc='The row index to retrieve'},
call=function(self, index)
self:assert_is_index(index)
local row = {}
for _,cn in pairs(self.column_order) do
row[cn] = self.dataset[cn][index]
end
return row
end}
Dataframe.insert = argcheck{
doc = [[
<a name="Dataframe.insert">
### Dataframe.insert(@ARGP)
Inserts a row or multiple rows into database at the position of the provided index.
@ARGT
_Return value_: self
]],
{name="self", type="Dataframe"},
{name="index", type="number", doc="The row number where to insert the row(s)"},
{name="rows", type="Df_Dict", doc="Insert values to the dataset"},
call=function(self, index, rows)
if (self:size(1) == 0 and index == 1) then
return self:append{rows = rows}
end
self:assert_is_index{index = index, plus_one = true}
if (index == self:size(1) + 1) then
return self:append(rows)
end
rows, no_rows_2_insert =
self:_check_and_prep_row_argmnt{rows = rows,
add_new_columns = true,
add_old_columns = true}
for _, column_name in pairs(self.column_order) do
for j = index,(index + no_rows_2_insert - 1) do
value = rows[column_name][j-index + 1]
self.dataset[column_name]:insert(j, value)
end
end
self:_infer_schema()
return self
end}
Dataframe.insert = argcheck{
doc = [[
Note, if you provide a Dataframe the primary dataframes meta-information will
be the ones that are kept
@ARGT
]],
overload=Dataframe.insert,
{name="self", type="Dataframe"},
{name="index", type="number", doc="The row number where to insert the row(s)"},
{name="rows", type="Dataframe", doc="A Dataframe that you want to insert"},
call=function(self, index, rows)
if (index == self:size(1) + 1) then
return self:append(rows)
end
return self:insert(index, Df_Dict(rows.dataset))
end}
Dataframe.insert = argcheck{
overload=Dataframe.insert,
{name="self", type="Dataframe"},
{name="rows", type="Df_Dict", doc="Insert values to the dataset"},
call=function(self, rows)
print("Warning: The insert without row number is a deprecated function and support will be dropped - use append instead")
return self:append(rows)
end}
Dataframe.insert = argcheck{
overload=Dataframe.insert,
{name="self", type="Dataframe"},
{name="rows", type="Dataframe", doc="A Dataframe that you want to append"},
call=function(self, rows)
print("Warning: The insert without row number is a deprecated function and support will be dropped - use append instead")
self:append(Df_Dict(rows.dataset))
end}
Dataframe._check_and_prep_row_argmnt = argcheck{
{name="self", type="Dataframe"},
{name="rows", type="Df_Dict"},
{name="add_new_columns", type="boolean", default=true,
doc="Add columns with missing values to the datafame that appear in the rows dict"},
{name="add_old_columns", type="boolean", default=true,
doc="Add columns with missing values to rows that are only in the dataframe"},
call=function(self, rows, add_new_columns, add_old_columns)
rows = rows.data
local no_rows_2_insert = 0
local new_columns = {}
for k,v in pairs(rows) do
-- Force all input into tables
if (type(v) ~= 'table') then
v = {v}
rows[k] = v
end
-- Check input size
if (no_rows_2_insert == 0) then
no_rows_2_insert = table.maxn(v)
else
assert(no_rows_2_insert == table.maxn(v),
"The rows aren't the same between the columns." ..
" The " .. k .. " column has " .. " " .. table.maxn(v) .. " rows" ..
" while previous columns had " .. no_rows_2_insert .. " rows")
end
if (not table.has_element(self.column_order, k) and add_new_columns) then
self:add_column(k)
end
end
if (add_old_columns) then
for i=1,#self.column_order do
local k = self.column_order[i]
if (rows[k] == nil) then
local tmp = {}
for i=1,no_rows_2_insert do
tmp[i] = 0/0
end
rows[k] = tmp
end
end
end
return rows, no_rows_2_insert
end}
Dataframe.append = argcheck{
doc = [[
<a name="Dataframe.append">
### Dataframe.append(@ARGP)
Appends the row(s) to the Dataframe.
@ARGT
_Return value_: self
]],
{name="self", type="Dataframe"},
{name="rows", type="Df_Dict", doc="Values to append to the Dataframe"},
{name="column_order", type="Df_Array", opt=true,
doc="The order of the column (has to be array and _not_ a dictionary). Only used when the Dataframe is empty"},
{name="schema", type="Df_Array", opt=true,
doc="The schema for the data - used in case the table is new"},
call=function(self, rows, column_order)
if (self:size(1) == 0) then
return self:load_table{data = rows, column_order = column_order, schema=schema}
end
rows, no_rows_2_insert =
self:_check_and_prep_row_argmnt{rows = rows,
add_new_columns = true,
add_old_columns = true}
for _, column_name in pairs(self.column_order) do
for j = 1,no_rows_2_insert do
value = rows[column_name][j]
self.dataset[column_name][self.n_rows + j] = value
end
end
self:_infer_schema()
return self
end}
Dataframe.append = argcheck{
doc = [[
Note, if you provide a Dataframe the primary dataframes meta-information will
be the ones that are kept
@ARGT
]],
overload=Dataframe.append,
{name="self", type="Dataframe"},
{name="rows", type="Dataframe", doc="A Dataframe that you want to append"},
call=function(self, rows)
if (self:size(1) == 0) then
self.dataset = clone(rows.dataset)
self.n_rows = rows.n_rows
self:_infer_schema()
rows:_copy_meta(self)
return self
end
return self:append(Df_Dict(rows.dataset))
end}
Dataframe.rbind = argcheck{
doc = [[
<a name="Dataframe.rbind">
### Dataframe.rbind(@ARGP)
Alias to Dataframe.append
@ARGT
_Return value_: self
]],
{name="self", type="Dataframe"},
{name="rows", type="Df_Dict", doc="Values to append to the Dataframe"},
call=function(self, rows)
return self:append(rows)
end}
Dataframe.rbind = argcheck{
doc = [[
Note, if you provide a Dataframe the primary dataframes meta-information will
be the ones that are kept
@ARGT
]],
overload=Dataframe.rbind,
{name="self", type="Dataframe"},
{name="rows", type="Dataframe", doc="A Dataframe that you want to append"},
call=function(self, rows)
return self:append(rows)
end}
Dataframe.remove_index = argcheck{
doc = [[
<a name="Dataframe.remove_index">
### Dataframe.remove_index(@ARGP)
Deletes a given row
@ARGT
_Return value_: self
]],
{name="self", type="Dataframe"},
{name="index", type="number", doc="The row index to remove"},
call=function(self, index)
self:assert_is_index(index)
for i = 1,#self.column_order do
self.dataset[self.column_order[i]]:remove(index)
end
self.n_rows = self.n_rows - 1
return self
end}
|
local params = {...}
local Dataframe = params[1]
local argcheck = require "argcheck"
local doc = require "argcheck.doc"
doc[[
## Row functions
]]
Dataframe.get_row = argcheck{
doc = [[
<a name="Dataframe.get_row">
### Dataframe.get_row(@ARGP)
Gets a single row from the Dataframe
@ARGT
_Return value_: A table with the row content
]],
{name="self", type="Dataframe"},
{name='index', type='number', doc='The row index to retrieve'},
call=function(self, index)
self:assert_is_index(index)
local row = {}
for _,cn in pairs(self.column_order) do
row[cn] = self.dataset[cn][index]
end
return row
end}
Dataframe.insert = argcheck{
doc = [[
<a name="Dataframe.insert">
### Dataframe.insert(@ARGP)
Inserts a row or multiple rows into database at the position of the provided index.
@ARGT
_Return value_: self
]],
{name="self", type="Dataframe"},
{name="index", type="number", doc="The row number where to insert the row(s)"},
{name="rows", type="Df_Dict", doc="Insert values to the dataset"},
call=function(self, index, rows)
if (self:size(1) == 0 and index == 1) then
return self:append{rows = rows}
end
self:assert_is_index{index = index, plus_one = true}
if (index == self:size(1) + 1) then
return self:append(rows)
end
rows, no_rows_2_insert =
self:_check_and_prep_row_argmnt{rows = rows,
add_new_columns = true,
add_old_columns = true}
for _, column_name in pairs(self.column_order) do
for j = index,(index + no_rows_2_insert - 1) do
value = rows[column_name][j-index + 1]
self.dataset[column_name]:insert(j, value)
end
end
self:_infer_schema()
return self
end}
Dataframe.insert = argcheck{
doc = [[
Note, if you provide a Dataframe the primary dataframes meta-information will
be the ones that are kept
@ARGT
]],
overload=Dataframe.insert,
{name="self", type="Dataframe"},
{name="index", type="number", doc="The row number where to insert the row(s)"},
{name="rows", type="Dataframe", doc="A Dataframe that you want to insert"},
call=function(self, index, rows)
if (index == self:size(1) + 1) then
return self:append(rows)
end
return self:insert(index, Df_Dict(rows.dataset))
end}
Dataframe.insert = argcheck{
overload=Dataframe.insert,
{name="self", type="Dataframe"},
{name="rows", type="Df_Dict", doc="Insert values to the dataset"},
call=function(self, rows)
print("Warning: The insert without row number is a deprecated function and support will be dropped - use append instead")
return self:append(rows)
end}
Dataframe.insert = argcheck{
overload=Dataframe.insert,
{name="self", type="Dataframe"},
{name="rows", type="Dataframe", doc="A Dataframe that you want to append"},
call=function(self, rows)
print("Warning: The insert without row number is a deprecated function and support will be dropped - use append instead")
self:append(Df_Dict(rows.dataset))
end}
Dataframe._check_and_prep_row_argmnt = argcheck{
{name="self", type="Dataframe"},
{name="rows", type="Df_Dict"},
{name="add_new_columns", type="boolean", default=true,
doc="Add columns with missing values to the datafame that appear in the rows dict"},
{name="add_old_columns", type="boolean", default=true,
doc="Add columns with missing values to rows that are only in the dataframe"},
call=function(self, rows, add_new_columns, add_old_columns)
rows = rows.data
local no_rows_2_insert = 0
local new_columns = {}
for k,v in pairs(rows) do
-- Force all input into tables
if (type(v) ~= 'table') then
v = {v}
rows[k] = v
end
-- Check input size
if (no_rows_2_insert == 0) then
no_rows_2_insert = table.maxn(v)
else
assert(no_rows_2_insert == table.maxn(v),
"The rows aren't the same between the columns." ..
" The " .. k .. " column has " .. " " .. table.maxn(v) .. " rows" ..
" while previous columns had " .. no_rows_2_insert .. " rows")
end
if (not table.has_element(self.column_order, k) and add_new_columns) then
self:add_column(k)
end
end
if (add_old_columns) then
for i=1,#self.column_order do
local k = self.column_order[i]
if (rows[k] == nil) then
local tmp = {}
for i=1,no_rows_2_insert do
tmp[i] = 0/0
end
rows[k] = tmp
end
end
end
return rows, no_rows_2_insert
end}
Dataframe.append = argcheck{
doc = [[
<a name="Dataframe.append">
### Dataframe.append(@ARGP)
Appends the row(s) to the Dataframe.
@ARGT
_Return value_: self
]],
{name="self", type="Dataframe"},
{name="rows", type="Df_Dict", doc="Values to append to the Dataframe"},
{name="column_order", type="Df_Array", opt=true,
doc="The order of the column (has to be array and _not_ a dictionary). Only used when the Dataframe is empty"},
{name="schema", type="Df_Array", opt=true,
doc="The schema for the data - used in case the table is new"},
call=function(self, rows, column_order)
if (self:size(1) == 0) then
return self:load_table{data = rows, column_order = column_order, schema=schema}
end
rows, no_rows_2_insert =
self:_check_and_prep_row_argmnt{rows = rows,
add_new_columns = true,
add_old_columns = true}
for _, column_name in pairs(self.column_order) do
for j = 1,no_rows_2_insert do
value = rows[column_name][j]
self.dataset[column_name]:append(value)
end
end
self.n_rows = self.n_rows + no_rows_2_insert
self:_infer_schema()
return self
end}
Dataframe.append = argcheck{
doc = [[
Note, if you provide a Dataframe the primary dataframes meta-information will
be the ones that are kept
@ARGT
]],
overload=Dataframe.append,
{name="self", type="Dataframe"},
{name="rows", type="Dataframe", doc="A Dataframe that you want to append"},
call=function(self, rows)
if (self:size(1) == 0) then
self.dataset = clone(rows.dataset)
self.n_rows = rows.n_rows
self:_infer_schema()
rows:_copy_meta(self)
return self
end
return self:append(Df_Dict(rows.dataset))
end}
Dataframe.rbind = argcheck{
doc = [[
<a name="Dataframe.rbind">
### Dataframe.rbind(@ARGP)
Alias to Dataframe.append
@ARGT
_Return value_: self
]],
{name="self", type="Dataframe"},
{name="rows", type="Df_Dict", doc="Values to append to the Dataframe"},
call=function(self, rows)
return self:append(rows)
end}
Dataframe.rbind = argcheck{
doc = [[
Note, if you provide a Dataframe the primary dataframes meta-information will
be the ones that are kept
@ARGT
]],
overload=Dataframe.rbind,
{name="self", type="Dataframe"},
{name="rows", type="Dataframe", doc="A Dataframe that you want to append"},
call=function(self, rows)
return self:append(rows)
end}
Dataframe.remove_index = argcheck{
doc = [[
<a name="Dataframe.remove_index">
### Dataframe.remove_index(@ARGP)
Deletes a given row
@ARGT
_Return value_: self
]],
{name="self", type="Dataframe"},
{name="index", type="number", doc="The row index to remove"},
call=function(self, index)
self:assert_is_index(index)
for i = 1,#self.column_order do
self.dataset[self.column_order[i]]:remove(index)
end
self.n_rows = self.n_rows - 1
return self
end}
|
Fixed n_rows update for append
|
Fixed n_rows update for append
|
Lua
|
mit
|
AlexMili/torch-dataframe
|
5c50795d90106ed4d89a2ef4ff0a103fb69c34d5
|
util/array.lua
|
util/array.lua
|
-- Prosody IM
-- Copyright (C) 2008-2009 Matthew Wild
-- Copyright (C) 2008-2009 Waqas Hussain
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
local t_insert, t_sort, t_remove, t_concat
= table.insert, table.sort, table.remove, table.concat;
local array = {};
local array_base = {};
local array_methods = {};
local array_mt = { __index = array_methods, __tostring = function (array) return array:concat(", "); end };
local function new_array(_, t)
return setmetatable(t or {}, array_mt);
end
function array_mt.__add(a1, a2)
local res = new_array();
return res:append(a1):append(a2);
end
setmetatable(array, { __call = new_array });
function array_base.map(outa, ina, func)
for k,v in ipairs(ina) do
outa[k] = func(v);
end
return outa;
end
function array_base.filter(outa, ina, func)
for k,v in ipairs(ina) do
if func(v) then
outa:push(v);
end
end
return outa;
end
function array_base.sort(outa, ina, ...)
if ina ~= outa then
outa:append(ina);
end
t_sort(outa, ...);
return outa;
end
--- These methods only mutate
function array_methods:random()
return self[math.random(1,#self)];
end
function array_methods:shuffle(outa, ina)
local len = #self;
for i=1,#self do
local r = math.random(i,len);
self[i], self[r] = self[r], self[i];
end
return self;
end
function array_methods:reverse()
local len = #self-1;
for i=len,1,-1 do
self:push(self[i]);
self:pop(i);
end
return self;
end
function array_methods:append(array)
local len,len2 = #self, #array;
for i=1,len2 do
self[len+i] = array[i];
end
return self;
end
array_methods.push = table.insert;
array_methods.pop = table.remove;
array_methods.concat = table.concat;
array_methods.length = function (t) return #t; end
--- These methods always create a new array
function array.collect(f, s, var)
local t, var = {};
while true do
var = f(s, var);
if var == nil then break; end
table.insert(t, var);
end
return setmetatable(t, array_mt);
end
---
-- Setup methods from array_base
for method, f in pairs(array_base) do
local method = method; -- Yes, this is necessary :)
local base_method = f;
-- Setup global array method which makes new array
array[method] = function (old_a, ...)
local a = new_array();
return base_method(a, old_a, ...);
end
-- Setup per-array (mutating) method
array_methods[method] = function (self, ...)
return base_method(self, self, ...);
end
end
_G.array = array;
module("array");
return array;
|
-- Prosody IM
-- Copyright (C) 2008-2009 Matthew Wild
-- Copyright (C) 2008-2009 Waqas Hussain
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
local t_insert, t_sort, t_remove, t_concat
= table.insert, table.sort, table.remove, table.concat;
local array = {};
local array_base = {};
local array_methods = {};
local array_mt = { __index = array_methods, __tostring = function (array) return array:concat(", "); end };
local function new_array(_, t)
return setmetatable(t or {}, array_mt);
end
function array_mt.__add(a1, a2)
local res = new_array();
return res:append(a1):append(a2);
end
setmetatable(array, { __call = new_array });
function array_base.map(outa, ina, func)
for k,v in ipairs(ina) do
outa[k] = func(v);
end
return outa;
end
function array_base.filter(outa, ina, func)
local inplace, start_length = ina == outa, #ina;
local write = 1;
for read=1,start_length do
local v = ina[read];
if func(v) then
outa[write] = v;
write = write + 1;
end
end
if inplace and write < start_length then
for i=write,start_length do
outa[i] = nil;
end
end
return outa;
end
function array_base.sort(outa, ina, ...)
if ina ~= outa then
outa:append(ina);
end
t_sort(outa, ...);
return outa;
end
--- These methods only mutate
function array_methods:random()
return self[math.random(1,#self)];
end
function array_methods:shuffle(outa, ina)
local len = #self;
for i=1,#self do
local r = math.random(i,len);
self[i], self[r] = self[r], self[i];
end
return self;
end
function array_methods:reverse()
local len = #self-1;
for i=len,1,-1 do
self:push(self[i]);
self:pop(i);
end
return self;
end
function array_methods:append(array)
local len,len2 = #self, #array;
for i=1,len2 do
self[len+i] = array[i];
end
return self;
end
array_methods.push = table.insert;
array_methods.pop = table.remove;
array_methods.concat = table.concat;
array_methods.length = function (t) return #t; end
--- These methods always create a new array
function array.collect(f, s, var)
local t, var = {};
while true do
var = f(s, var);
if var == nil then break; end
table.insert(t, var);
end
return setmetatable(t, array_mt);
end
---
-- Setup methods from array_base
for method, f in pairs(array_base) do
local method = method; -- Yes, this is necessary :)
local base_method = f;
-- Setup global array method which makes new array
array[method] = function (old_a, ...)
local a = new_array();
return base_method(a, old_a, ...);
end
-- Setup per-array (mutating) method
array_methods[method] = function (self, ...)
return base_method(self, self, ...);
end
end
_G.array = array;
module("array");
return array;
|
util.array: Fix for array:filter() (in-place filtering)
|
util.array: Fix for array:filter() (in-place filtering)
|
Lua
|
mit
|
sarumjanuch/prosody,sarumjanuch/prosody
|
c8c798129dd6c9a119abd43bc41a183497b3ef7b
|
lua/entities/gmod_wire_gate.lua
|
lua/entities/gmod_wire_gate.lua
|
AddCSLuaFile()
DEFINE_BASECLASS( "base_wire_entity" )
ENT.PrintName = "Wire Gate"
ENT.WireDebugName = "Gate"
if CLIENT then return end -- No more client
function ENT:Initialize()
self:PhysicsInit( SOLID_VPHYSICS )
self:SetMoveType( MOVETYPE_VPHYSICS )
self:SetSolid( SOLID_VPHYSICS )
self.Inputs = {}
self.Outputs = {}
end
function ENT:Setup( action, noclip )
local gate = GateActions[action]
if not gate then return end
self.action = action
self.WireDebugName = gate.name
WireLib.AdjustSpecialInputs(self, gate.inputs, gate.inputtypes )
if (gate.outputs) then
WireLib.AdjustSpecialOutputs(self, gate.outputs, gate.outputtypes)
else
//Wire_AdjustOutputs(self, { "Out" })
WireLib.AdjustSpecialOutputs(self, { "Out" }, gate.outputtypes)
end
if (gate.reset) then
gate.reset(self)
end
local ReadCell = gate.ReadCell
if ReadCell then
function self:ReadCell(Address)
return ReadCell(gate,self,Address)
end
else
self.ReadCell = nil
end
local WriteCell = gate.WriteCell
if WriteCell then
function self:WriteCell(Address,value)
return WriteCell(gate,self,Address,value)
end
else
self.WriteCell = nil
end
if (noclip) then
self:SetCollisionGroup( COLLISION_GROUP_WORLD )
end
self.noclip = noclip
self.Action = gate
self.PrevValue = nil
//self.Action.inputtypes = self.Action.inputtypes or {}
self:CalcOutput()
self:ShowOutput()
end
function ENT:OnInputWireLink(iname, itype, src, oname, otype)
if (self.Action) and (self.Action.OnInputWireLink) then
self.Action.OnInputWireLink(self, iname, itype, src, oname, otype)
end
end
function ENT:OnOutputWireLink(oname, otype, dst, iname, itype)
if (self.Action) and (self.Action.OnOutputWireLink) then
self.Action.OnOutputWireLink(self, oname, otype, dst, iname, itype)
end
end
function ENT:TriggerInput(iname, value, iter)
if (self.Action) and (not self.Action.timed) then
self:CalcOutput(iter)
self:ShowOutput()
end
end
function ENT:Think()
self.BaseClass.Think(self)
if (self.Action) and (self.Action.timed) then
self:CalcOutput()
self:ShowOutput()
self:NextThink(CurTime()+0.02)
return true
end
end
function ENT:CalcOutput(iter)
if (self.Action) and (self.Action.output) then
if (self.Action.outputs) then
local result = { self.Action.output(self, unpack(self:GetActionInputs())) }
for k,v in ipairs(self.Action.outputs) do
Wire_TriggerOutput(self, v, result[k], iter)
end
else
local value = self.Action.output(self, unpack(self:GetActionInputs())) or 0
Wire_TriggerOutput(self, "Out", value, iter)
end
end
end
function ENT:ShowOutput()
local txt = ""
if (self.Action) then
txt = (self.Action.name or "No Name")
if (self.Action.label) then
txt = txt.."\n"..self.Action.label(self:GetActionOutputs(), unpack(self:GetActionInputs(Wire_EnableGateInputValues)))
end
else
txt = "Invalid gate!"
end
self:SetOverlayText(txt)
end
function ENT:OnRestore()
self.Action = GateActions[self.action]
self.BaseClass.OnRestore(self)
end
function ENT:GetActionInputs(as_names)
local Args = {}
if (self.Action.compact_inputs) then
-- If a gate has compact inputs (like Arithmetic - Add), nil inputs are truncated so {0, nil, nil, 5, nil, 1} becomes {0, 5, 1}
for k,v in ipairs(self.Action.inputs) do
local input = self.Inputs[v]
if (not input) then
ErrorNoHalt("Wire Gate ("..self.action..") error: Missing input! ("..k..","..v..")")
return {}
end
if IsValid(input.Src) then
if (as_names) then
table.insert(Args, input.Src.WireName or input.Src.WireDebugName or v)
else
table.insert(Args, input.Value)
end
end
end
while (#Args < self.Action.compact_inputs) do
if (as_names) then
table.insert(Args, self.Action.inputs[#Args+1] or "*Not enough inputs*")
else
//table.insert( Args, WireLib.DT[ (self.Action.inputtypes[#Args+1] or "NORMAL") ].Zero )
table.insert( Args, WireLib.DT[ self.Inputs[ self.Action.inputs[#Args+1] ].Type ].Zero )
end
end
else
for k,v in ipairs(self.Action.inputs) do
local input = self.Inputs[v]
if (not input) then
ErrorNoHalt("Wire Gate ("..self.action..") error: Missing input! ("..k..","..v..")")
return {}
end
if (as_names) then
Args[k] = IsValid(input.Src) and (input.Src.WireName or input.Src.WireDebugName) or v
else
Args[k] = IsValid(input.Src) and input.Value or WireLib.DT[ self.Inputs[v].Type ].Zero
end
end
end
return Args
end
function ENT:GetActionOutputs()
if (self.Action.outputs) then
local result = {}
for _,v in ipairs(self.Action.outputs) do
result[v] = self.Outputs[v].Value or 0
end
return result
end
return self.Outputs.Out.Value or 0
end
function MakeWireGate(pl, Pos, Ang, model, action, noclip, frozen, nocollide)
local gate = GateActions[action]
if not gate then return end
local group = gate.group
if not group then return end
group = string.lower(group)
if IsValid(pl) and not pl:CheckLimit( "wire_gate_" .. group .. "s" ) then return end
local wire_gate = WireLib.MakeWireEnt( pl, {Class = "gmod_wire_gate", Pos=Pos, Angle=Ang, Model=model}, action, noclip )
if not IsValid(wire_gate) then return end
if IsValid(pl) then pl:AddCount( "wire_gate_" .. group .. "s", wire_gate ) end
return wire_gate
end
duplicator.RegisterEntityClass("gmod_wire_gate", MakeWireGate, "Pos", "Ang", "Model", "action", "noclip")
|
AddCSLuaFile()
DEFINE_BASECLASS( "base_wire_entity" )
ENT.PrintName = "Wire Gate"
ENT.WireDebugName = "Gate"
if CLIENT then return end -- No more client
function ENT:Initialize()
self:PhysicsInit( SOLID_VPHYSICS )
self:SetMoveType( MOVETYPE_VPHYSICS )
self:SetSolid( SOLID_VPHYSICS )
self.Inputs = {}
self.Outputs = {}
end
function ENT:Setup( action, noclip )
local gate = GateActions[action]
if not gate then return end
self.action = action
self.WireDebugName = gate.name
WireLib.AdjustSpecialInputs(self, gate.inputs, gate.inputtypes )
if (gate.outputs) then
WireLib.AdjustSpecialOutputs(self, gate.outputs, gate.outputtypes)
else
//Wire_AdjustOutputs(self, { "Out" })
WireLib.AdjustSpecialOutputs(self, { "Out" }, gate.outputtypes)
end
if (gate.reset) then
gate.reset(self)
end
local ReadCell = gate.ReadCell
if ReadCell then
function self:ReadCell(Address)
return ReadCell(gate,self,Address)
end
else
self.ReadCell = nil
end
local WriteCell = gate.WriteCell
if WriteCell then
function self:WriteCell(Address,value)
return WriteCell(gate,self,Address,value)
end
else
self.WriteCell = nil
end
if (noclip) then
self:SetCollisionGroup( COLLISION_GROUP_WORLD )
end
self.noclip = noclip
self.Action = gate
self.PrevValue = nil
//self.Action.inputtypes = self.Action.inputtypes or {}
self:CalcOutput()
self:ShowOutput()
end
function ENT:OnInputWireLink(iname, itype, src, oname, otype)
if (self.Action) and (self.Action.OnInputWireLink) then
self.Action.OnInputWireLink(self, iname, itype, src, oname, otype)
end
end
function ENT:OnOutputWireLink(oname, otype, dst, iname, itype)
if (self.Action) and (self.Action.OnOutputWireLink) then
self.Action.OnOutputWireLink(self, oname, otype, dst, iname, itype)
end
end
function ENT:TriggerInput(iname, value, iter)
if (self.Action) and (not self.Action.timed) then
self:CalcOutput(iter)
self:ShowOutput()
end
end
function ENT:Think()
self.BaseClass.Think(self)
if (self.Action) and (self.Action.timed) then
self:CalcOutput()
self:ShowOutput()
self:NextThink(CurTime()+0.02)
return true
end
end
function ENT:CalcOutput(iter)
if (self.Action) and (self.Action.output) then
if (self.Action.outputs) then
local result = { self.Action.output(self, unpack(self:GetActionInputs())) }
for k,v in ipairs(self.Action.outputs) do
Wire_TriggerOutput(self, v, result[k] or WireLib.DT[ self.Outputs[v].Type ].Zero, iter)
end
else
local value = self.Action.output(self, unpack(self:GetActionInputs())) or WireLib.DT[ self.Outputs.Out.Type ].Zero
Wire_TriggerOutput(self, "Out", value, iter)
end
end
end
function ENT:ShowOutput()
local txt = ""
if (self.Action) then
txt = (self.Action.name or "No Name")
if (self.Action.label) then
txt = txt.."\n"..self.Action.label(self:GetActionOutputs(), unpack(self:GetActionInputs(Wire_EnableGateInputValues)))
end
else
txt = "Invalid gate!"
end
self:SetOverlayText(txt)
end
function ENT:OnRestore()
self.Action = GateActions[self.action]
self.BaseClass.OnRestore(self)
end
function ENT:GetActionInputs(as_names)
local Args = {}
if (self.Action.compact_inputs) then
-- If a gate has compact inputs (like Arithmetic - Add), nil inputs are truncated so {0, nil, nil, 5, nil, 1} becomes {0, 5, 1}
for k,v in ipairs(self.Action.inputs) do
local input = self.Inputs[v]
if (not input) then
ErrorNoHalt("Wire Gate ("..self.action..") error: Missing input! ("..k..","..v..")")
return {}
end
if IsValid(input.Src) then
if (as_names) then
table.insert(Args, input.Src.WireName or input.Src.WireDebugName or v)
else
table.insert(Args, input.Value)
end
end
end
while (#Args < self.Action.compact_inputs) do
if (as_names) then
table.insert(Args, self.Action.inputs[#Args+1] or "*Not enough inputs*")
else
//table.insert( Args, WireLib.DT[ (self.Action.inputtypes[#Args+1] or "NORMAL") ].Zero )
table.insert( Args, WireLib.DT[ self.Inputs[ self.Action.inputs[#Args+1] ].Type ].Zero )
end
end
else
for k,v in ipairs(self.Action.inputs) do
local input = self.Inputs[v]
if (not input) then
ErrorNoHalt("Wire Gate ("..self.action..") error: Missing input! ("..k..","..v..")")
return {}
end
if (as_names) then
Args[k] = IsValid(input.Src) and (input.Src.WireName or input.Src.WireDebugName) or v
else
Args[k] = IsValid(input.Src) and input.Value or WireLib.DT[ self.Inputs[v].Type ].Zero
end
end
end
return Args
end
function ENT:GetActionOutputs()
if (self.Action.outputs) then
local result = {}
for _,v in ipairs(self.Action.outputs) do
result[v] = self.Outputs[v].Value or WireLib.DT[ self.Outputs[v].Type ].Zero
end
return result
end
return self.Outputs.Out.Value or WireLib.DT[ self.Outputs.Out.Type ].Zero
end
function MakeWireGate(pl, Pos, Ang, model, action, noclip, frozen, nocollide)
local gate = GateActions[action]
if not gate then return end
local group = gate.group
if not group then return end
group = string.lower(group)
if IsValid(pl) and not pl:CheckLimit( "wire_gate_" .. group .. "s" ) then return end
local wire_gate = WireLib.MakeWireEnt( pl, {Class = "gmod_wire_gate", Pos=Pos, Angle=Ang, Model=model}, action, noclip )
if not IsValid(wire_gate) then return end
if IsValid(pl) then pl:AddCount( "wire_gate_" .. group .. "s", wire_gate ) end
return wire_gate
end
duplicator.RegisterEntityClass("gmod_wire_gate", MakeWireGate, "Pos", "Ang", "Model", "action", "noclip")
|
Fixed gates that return nil returning 0 instead of their type's zero value
|
Fixed gates that return nil returning 0 instead of their type's zero value
Fixes #674
|
Lua
|
apache-2.0
|
CaptainPRICE/wire,plinkopenguin/wiremod,mms92/wire,notcake/wire,wiremod/wire,bigdogmat/wire,NezzKryptic/Wire,Grocel/wire,mitterdoo/wire,sammyt291/wire,rafradek/wire,thegrb93/wire,Python1320/wire,garrysmodlua/wire,immibis/wiremod,dvdvideo1234/wire
|
7b7a3400af0967fe75610c5edccbd8da1b5a25f2
|
lua/wire/stools/sensor.lua
|
lua/wire/stools/sensor.lua
|
WireToolSetup.setCategory( "Detection/Beacon" )
WireToolSetup.open( "sensor", "Beacon Sensor", "gmod_wire_sensor", nil, "Beacon Sensors" )
if ( CLIENT ) then
language.Add( "Tool.wire_sensor.name", "Beacon Sensor Tool (Wire)" )
language.Add( "Tool.wire_sensor.desc", "Returns distance and/or bearing to a beacon" )
language.Add( "Tool.wire_sensor.0", "Primary: Create Sensor Secondary: Link Sensor" )
language.Add( "Tool.wire_sensor.1", "Click on the beacon to link to." )
language.Add( "WireSensorTool_outdist", "Output distance" )
language.Add( "WireSensorTool_outbrng", "Output bearing" )
language.Add( "WireSensorTool_xyz_mode", "Output local position" )
language.Add( "WireSensorTool_gpscord", "Output world position (gps cords)" )
language.Add( "WireSensorTool_direction_vector", "Output direction Vector" )
language.Add( "WireSensorTool_direction_normalized", "Normalize direction Vector" )
language.Add( "WireSensorTool_target_velocity", "Output target's velocity" )
language.Add( "WireSensorTool_velocity_normalized", "Normalize velocity" )
end
WireToolSetup.BaseLang()
WireToolSetup.SetupMax( 20 )
if SERVER then
function TOOL:GetConVars()
return self:GetClientNumber("xyz_mode") ~= 0, self:GetClientNumber("outdist") ~= 0, self:GetClientNumber("outbrng") ~= 0,
self:GetClientNumber("gpscord") ~= 0, self:GetClientNumber("direction_vector") ~= 0, self:GetClientNumber("direction_normalized") ~= 0,
self:GetClientNumber("target_velocity") ~= 0, self:GetClientNumber("velocity_normalized") ~= 0
end
-- Uses default WireToolObj:MakeEnt's WireLib.MakeWireEnt function
end
TOOL.ClientConVar[ "xyz_mode" ] = "0"
TOOL.ClientConVar[ "outdist" ] = "1"
TOOL.ClientConVar[ "outbrng" ] = "0"
TOOL.ClientConVar[ "gpscord" ] = "0"
TOOL.ClientConVar[ "direction_vector" ] = "0"
TOOL.ClientConVar[ "direction_normalized" ] = "0"
TOOL.ClientConVar[ "target_velocity" ] = "0"
TOOL.ClientConVar[ "velocity_normalized" ] = "0"
TOOL.Model = "models/props_lab/huladoll.mdl"
WireToolSetup.SetupLinking(true)
function TOOL.BuildCPanel( panel )
panel:CheckBox("#WireSensorTool_outdist", "wire_sensor_outdist")
panel:CheckBox("#WireSensorTool_outbrng", "wire_sensor_outbrng")
panel:CheckBox("#WireSensorTool_xyz_mode", "wire_sensor_xyz_mode")
panel:CheckBox("#WireSensorTool_gpscord", "wire_sensor_gpscord")
panel:CheckBox("#WireSensorTool_direction_vector", "wire_sensor_direction_vector")
panel:CheckBox("#WireSensorTool_direction_normalized", "wire_sensor_direction_normalized")
panel:CheckBox("#WireSensorTool_target_velocity", "wire_sensor_target_velocity")
panel:CheckBox("#WireSensorTool_velocity_normalized", "wire_sensor_velocity_normalized")
end
|
WireToolSetup.setCategory( "Detection/Beacon" )
WireToolSetup.open( "sensor", "Beacon Sensor", "gmod_wire_sensor", nil, "Beacon Sensors" )
if ( CLIENT ) then
language.Add( "Tool.wire_sensor.name", "Beacon Sensor Tool (Wire)" )
language.Add( "Tool.wire_sensor.desc", "Returns distance and/or bearing to a beacon" )
language.Add( "Tool.wire_sensor.0", "Primary: Create Sensor Secondary: Link Sensor" )
language.Add( "Tool.wire_sensor.1", "Click on the beacon to link to." )
language.Add( "WireSensorTool_outdist", "Output distance" )
language.Add( "WireSensorTool_outbrng", "Output bearing" )
language.Add( "WireSensorTool_xyz_mode", "Output local position, relative to beacon" )
language.Add( "WireSensorTool_gpscord", "Output world position ('split XYZ')" )
language.Add( "WireSensorTool_direction_vector", "Output direction Vector" )
language.Add( "WireSensorTool_direction_normalized", "Normalize direction Vector" )
language.Add( "WireSensorTool_target_velocity", "Output target's velocity" )
language.Add( "WireSensorTool_velocity_normalized", "Normalize velocity" )
end
WireToolSetup.BaseLang()
WireToolSetup.SetupMax( 20 )
if SERVER then
function TOOL:GetConVars()
return self:GetClientNumber("xyz_mode") ~= 0, self:GetClientNumber("outdist") ~= 0, self:GetClientNumber("outbrng") ~= 0,
self:GetClientNumber("gpscord") ~= 0, self:GetClientNumber("direction_vector") ~= 0, self:GetClientNumber("direction_normalized") ~= 0,
self:GetClientNumber("target_velocity") ~= 0, self:GetClientNumber("velocity_normalized") ~= 0
end
-- Uses default WireToolObj:MakeEnt's WireLib.MakeWireEnt function
end
TOOL.ClientConVar[ "xyz_mode" ] = "0"
TOOL.ClientConVar[ "outdist" ] = "1"
TOOL.ClientConVar[ "outbrng" ] = "0"
TOOL.ClientConVar[ "gpscord" ] = "0"
TOOL.ClientConVar[ "direction_vector" ] = "0"
TOOL.ClientConVar[ "direction_normalized" ] = "0"
TOOL.ClientConVar[ "target_velocity" ] = "0"
TOOL.ClientConVar[ "velocity_normalized" ] = "0"
TOOL.Model = "models/props_lab/huladoll.mdl"
WireToolSetup.SetupLinking(true)
function TOOL.BuildCPanel( panel )
panel:CheckBox("#WireSensorTool_outdist", "wire_sensor_outdist")
panel:CheckBox("#WireSensorTool_outbrng", "wire_sensor_outbrng")
panel:CheckBox("#WireSensorTool_xyz_mode", "wire_sensor_xyz_mode")
panel:CheckBox("#WireSensorTool_gpscord", "wire_sensor_gpscord")
panel:CheckBox("#WireSensorTool_direction_vector", "wire_sensor_direction_vector")
panel:CheckBox("#WireSensorTool_direction_normalized", "wire_sensor_direction_normalized")
panel:CheckBox("#WireSensorTool_target_velocity", "wire_sensor_target_velocity")
panel:CheckBox("#WireSensorTool_velocity_normalized", "wire_sensor_velocity_normalized")
end
|
Beacon Sensor: Added mention of 'split XYZ' to tool Fixes #857 (people are just going to keep asking)
|
Beacon Sensor: Added mention of 'split XYZ' to tool
Fixes #857 (people are just going to keep asking)
|
Lua
|
apache-2.0
|
notcake/wire,immibis/wiremod,sammyt291/wire,mitterdoo/wire,bigdogmat/wire,CaptainPRICE/wire,NezzKryptic/Wire,plinkopenguin/wiremod,thegrb93/wire,mms92/wire,dvdvideo1234/wire,Grocel/wire,rafradek/wire,wiremod/wire,garrysmodlua/wire,Python1320/wire
|
fc8270ac4ee36280fa2a2c293cac162b93dc84fe
|
nyagos.d/suffix.lua
|
nyagos.d/suffix.lua
|
nyagos.suffixes={}
function suffix(suffix,cmdline)
local suffix=string.lower(suffix)
if string.sub(suffix,1,1)=='.' then
suffix = string.sub(suffix,2)
end
if not nyagos.suffixes[suffix] then
local orgpathext = nyagos.getenv("PATHEXT")
local newext="."..suffix
if not string.find(";"..orgpathext..";",";"..newext..";",1,true) then
nyagos.setenv("PATHEXT",orgpathext..";"..newext)
end
end
nyagos.suffixes[suffix]=cmdline
end
nyagos.argsfilter = function(args)
local path=nyagos.which(args[0])
if not path then
return
end
local m = string.match(path,"%.(%w+)$")
if not m then
return
end
local cmdline = nyagos.suffixes[ string.lower(m) ]
if not cmdline then
return
end
local newargs={}
for i=1,#cmdline do
newargs[i-1]=cmdline[i]
end
newargs[#cmdline] = path
for i=1,#args do
newargs[#cmdline+i] = args[i]
end
return newargs
end
alias{
suffix=function(args)
if #args < 2 then
print "Usage: suffix SUFFIX COMMAND"
else
suffix(args[1],args[2])
end
end
}
suffix(".pl",{"perl"})
suffix(".py",{"ipy"})
suffix(".rb",{"ruby"})
suffix(".lua",{"lua"})
suffix(".awk",{"awk","-f"})
suffix(".js",{"cscript","//nologo"})
suffix(".vbs",{"cscript","//nologo"})
|
nyagos.suffixes={}
function suffix(suffix,cmdline)
local suffix=string.lower(suffix)
if string.sub(suffix,1,1)=='.' then
suffix = string.sub(suffix,2)
end
if not nyagos.suffixes[suffix] then
local orgpathext = nyagos.getenv("PATHEXT")
local newext="."..suffix
if not string.find(";"..orgpathext..";",";"..newext..";",1,true) then
nyagos.setenv("PATHEXT",orgpathext..";"..newext)
end
end
nyagos.suffixes[suffix]=cmdline
end
nyagos.argsfilter = function(args)
local path=nyagos.which(args[0])
if not path then
return
end
local m = string.match(path,"%.(%w+)$")
if not m then
return
end
local cmdline = nyagos.suffixes[ string.lower(m) ]
if not cmdline then
return
end
local newargs={}
for i=1,#cmdline do
newargs[i-1]=cmdline[i]
end
newargs[#cmdline] = path
for i=1,#args do
newargs[#cmdline+i] = args[i]
end
return newargs
end
alias{
suffix=function(args)
if #args < 2 then
print "Usage: suffix SUFFIX COMMAND"
else
suffix(args[1],args[2])
end
end
}
suffix(".pl",{"perl"})
suffix(".py",{"ipy"})
suffix(".rb",{"ruby"})
suffix(".lua",{"lua"})
suffix(".awk",{"awk","-f"})
suffix(".js",{"cscript","//nologo"})
suffix(".vbs",{"cscript","//nologo"})
suffix(".ps1",{"powershell","-file"})
|
拡張子.ps1 を suffix に追加
|
拡張子.ps1 を suffix に追加
|
Lua
|
bsd-3-clause
|
kissthink/nyagos,kissthink/nyagos,nocd5/nyagos,zetamatta/nyagos,hattya/nyagos,kissthink/nyagos,tsuyoshicho/nyagos,tyochiai/nyagos,hattya/nyagos,hattya/nyagos
|
5916eca3868c4ea37d142974dd8d25dc73c31989
|
programs/hammerspoon/init.lua
|
programs/hammerspoon/init.lua
|
local requireLeo = function()
require("leo");
end;
if pcall(requireLeo) then
print("Loaded Leo");
else
hs.notify.new({title="Hammerspoon", informativeText="Failed to load Leo"}):send()
end
-- Get around paste blockers with cmd+alt+v
hs.hotkey.bind({"cmd", "shift"}, "V", function()
hs.eventtap.keyStrokes(hs.pasteboard.getContents())
end)
-- Set up a hyper key tree
hyperKeys = hs.json.read("~/Google Drive/programs/hammerspoon/hyper-keys.json")
currentKey = nil
currentTree = hyperKeys or {}
hyperTime = nil
function executeHyperAction (tree)
if tree["action"] == "type" then
-- Avoid treating the emulated keystrokes as hyper commands
down:stop()
hs.eventtap.keyStrokes(tree["text"])
down:start()
elseif tree["action"] == "launch-or-focus" then
hs.application.launchOrFocus(tree["program"])
elseif tree["action"] == "direction" then
hs.eventtap.keyStroke(nil, tree["direction"], 0)
end
end
down = hs.eventtap.new({hs.eventtap.event.types.keyDown}, function(event)
local character = event:getCharacters()
local keyCode = event:getKeyCode()
-- print("down", character, keyCode)
-- Disable the insert key because overwrite mode is annoying
if keyCode == 114 then
return true
end
if currentKey == character then
return true
elseif currentTree["keys"] and currentTree["keys"][character] then
--[[
There's no need to wait for the up event if we know the tree doesn't go
any deeper, so we can execute the action immediately.
This also lets us hold down the current hyper key and execute multiple or
repeated actions for its tree. For example for multiple actions, we could
hold down the hyper key and tap two keys in its tree that both do not
have subtrees. Both actions can execute without having to restart the
sequence.
For example for repeated actions, we could hold down the hyper key and
hold another key to emulate holding down the up key.
]]
if currentTree["keys"][character]["action"] and
not currentTree["keys"][character]["keys"] then
executeHyperAction(currentTree["keys"][character])
-- Reset the time so that the up event handler doesn't execute any actions
hyperTime = nil
-- Otherwise, go deeper into the tree
elseif currentTree["keys"][character]["keys"] then
currentKey = character
currentTree = currentTree["keys"][character]
hyperTime = hs.timer.absoluteTime()
end
return true
end
end)
down:start()
up = hs.eventtap.new({hs.eventtap.event.types.keyUp}, function(event)
local character = event:getCharacters()
-- print("up", character)
if character == currentKey then
local currentTime = hs.timer.absoluteTime()
-- print(currentTime, hyperTime)
if hyperTime ~= nil and (currentTime - hyperTime) / 1000000 < 250 then
executeHyperAction(currentTree)
end
currentKey = nil
currentTree = hyperKeys
hyperTime = nil
end
end)
up:start()
--[[
Set the audio output and input devices, based on the priorities in the look
up functions because macOS is bad at keeping track of my preferences.
Crucially, this also avoids the issue of macOS setting the default device to
a monitor that doesn't even have speakers but registers as an output device
for some reason.
]]
function getAudioOutputPriority (device)
if device:name() == "WH-1000XM3" then
return 1
elseif device:transportType() == "Bluetooth" then
return 2
elseif device:transportType() == "Built-in" and
device:name() == "External Headphones" then
return 3
elseif device:name() == "CalDigit Thunderbolt 3 Audio" then
return 4
elseif device:transportType() == "Built-in" then
return 5
else
return 6
end
end
function getAudioInputPriority (device)
if device:name() == "ATR2100x-USB Microphone" then
return 1
elseif device:name() == "WH-1000XM3" then
return 2
elseif device:transportType() == "Bluetooth" then
return 3
elseif device:name() == "HD Pro Webcam C920" then
return 4
elseif device:transportType() == "Built-in" then
return 5
else
return 6
end
end
hs.audiodevice.watcher.setCallback(function(event)
--[[
We only care about when devices are connected or disconnected. This allows
us to manually change the default device without issues.
]]
if event ~= "dev#" then
return
end
for i, device in ipairs(hs.audiodevice.allOutputDevices()) do
local currentDevice = hs.audiodevice.defaultOutputDevice()
local currentPriority = getAudioOutputPriority(currentDevice)
if getAudioOutputPriority(device) < currentPriority then
device:setDefaultOutputDevice()
end
end
for i, device in ipairs(hs.audiodevice.allInputDevices()) do
local currentDevice = hs.audiodevice.defaultInputDevice()
local currentPriority = getAudioInputPriority(currentDevice)
if getAudioInputPriority(device) < currentPriority then
device:setDefaultInputDevice()
end
end
end)
hs.audiodevice.watcher.start()
--[[
Make control act as escape when tapped
Thanks to https://gist.github.com/arbelt/b91e1f38a0880afb316dd5b5732759f1
]]
send_escape = false
last_mods = {}
control_key_handler = function()
send_escape = false
end
control_key_timer = hs.timer.delayed.new(0.15, control_key_handler)
control_handler = function(evt)
local new_mods = evt:getFlags()
if last_mods["ctrl"] == new_mods["ctrl"] then
return false
end
if not last_mods["ctrl"] then
last_mods = new_mods
send_escape = true
control_key_timer:start()
else
last_mods = new_mods
control_key_timer:stop()
if send_escape then
return true, {
hs.eventtap.event.newKeyEvent({}, 'escape', true),
hs.eventtap.event.newKeyEvent({}, 'escape', false),
}
end
end
return false
end
control_tap = hs.eventtap.new({hs.eventtap.event.types.flagsChanged}, control_handler)
control_tap:start()
other_handler = function(evt)
send_escape = false
return false
end
other_tap = hs.eventtap.new({hs.eventtap.event.types.keyDown}, other_handler)
other_tap:start()
|
local requireLeo = function()
require("leo");
end;
if pcall(requireLeo) then
print("Loaded Leo");
else
hs.notify.new({title="Hammerspoon", informativeText="Failed to load Leo"}):send()
end
-- Get around paste blockers with cmd+alt+v
hs.hotkey.bind({"cmd", "shift"}, "V", function()
hs.eventtap.keyStrokes(hs.pasteboard.getContents())
end)
-- Set up a hyper key tree
hyperKeys = hs.json.read("~/Google Drive/programs/hammerspoon/hyper-keys.json")
currentKey = nil
currentTree = hyperKeys or {}
hyperTime = nil
-- Return true if it's definitely a terminating action
function executeHyperAction (tree)
if tree["action"] == "type" then
-- Avoid treating the emulated keystrokes as hyper commands
down:stop()
hs.eventtap.keyStrokes(tree["text"])
down:start()
elseif tree["action"] == "launch-or-focus" then
hs.application.launchOrFocus(tree["program"])
--[[
If we don't ask the caller to end hyper mode, launching Anki causes us to
temporarily get stuck in hyper mode.
]]
return true
elseif tree["action"] == "direction" then
hs.eventtap.keyStroke(nil, tree["direction"], 0)
end
return false
end
down = hs.eventtap.new({hs.eventtap.event.types.keyDown}, function(event)
local character = event:getCharacters()
local keyCode = event:getKeyCode()
-- print("down", character, keyCode)
-- Disable the insert key because overwrite mode is annoying
if keyCode == 114 then
return true
end
if currentKey == character then
return true
elseif currentTree["keys"] and currentTree["keys"][character] then
--[[
There's no need to wait for the up event if we know the tree doesn't go
any deeper, so we can execute the action immediately.
This also lets us hold down the current hyper key and execute multiple or
repeated actions for its tree. For example for multiple actions, we could
hold down the hyper key and tap two keys in its tree that both do not
have subtrees. Both actions can execute without having to restart the
sequence.
For example for repeated actions, we could hold down the hyper key and
hold another key to emulate holding down the up key.
]]
if currentTree["keys"][character]["action"] and
not currentTree["keys"][character]["keys"] then
local isTerminatingAction = executeHyperAction(currentTree["keys"][character])
-- Reset the time so that the up event handler doesn't execute any actions
hyperTime = nil
if isTerminatingAction then
currentKey = nil
currentTree = hyperKeys
end
-- Otherwise, go deeper into the tree
elseif currentTree["keys"][character]["keys"] then
currentKey = character
currentTree = currentTree["keys"][character]
hyperTime = hs.timer.absoluteTime()
end
return true
end
end)
down:start()
up = hs.eventtap.new({hs.eventtap.event.types.keyUp}, function(event)
local character = event:getCharacters()
-- print("up", character)
if character == currentKey then
local currentTime = hs.timer.absoluteTime()
-- print(currentTime, hyperTime)
if hyperTime ~= nil and (currentTime - hyperTime) / 1000000 < 250 then
executeHyperAction(currentTree)
end
currentKey = nil
currentTree = hyperKeys
hyperTime = nil
end
end)
up:start()
--[[
Set the audio output and input devices, based on the priorities in the look
up functions because macOS is bad at keeping track of my preferences.
Crucially, this also avoids the issue of macOS setting the default device to
a monitor that doesn't even have speakers but registers as an output device
for some reason.
]]
function getAudioOutputPriority (device)
if device:name() == "WH-1000XM3" then
return 1
elseif device:transportType() == "Bluetooth" then
return 2
elseif device:transportType() == "Built-in" and
device:name() == "External Headphones" then
return 3
elseif device:name() == "CalDigit Thunderbolt 3 Audio" then
return 4
elseif device:transportType() == "Built-in" then
return 5
else
return 6
end
end
function getAudioInputPriority (device)
if device:name() == "ATR2100x-USB Microphone" then
return 1
elseif device:name() == "WH-1000XM3" then
return 2
elseif device:transportType() == "Bluetooth" then
return 3
elseif device:name() == "HD Pro Webcam C920" then
return 4
elseif device:transportType() == "Built-in" then
return 5
else
return 6
end
end
hs.audiodevice.watcher.setCallback(function(event)
--[[
We only care about when devices are connected or disconnected. This allows
us to manually change the default device without issues.
]]
if event ~= "dev#" then
return
end
for i, device in ipairs(hs.audiodevice.allOutputDevices()) do
local currentDevice = hs.audiodevice.defaultOutputDevice()
local currentPriority = getAudioOutputPriority(currentDevice)
if getAudioOutputPriority(device) < currentPriority then
device:setDefaultOutputDevice()
end
end
for i, device in ipairs(hs.audiodevice.allInputDevices()) do
local currentDevice = hs.audiodevice.defaultInputDevice()
local currentPriority = getAudioInputPriority(currentDevice)
if getAudioInputPriority(device) < currentPriority then
device:setDefaultInputDevice()
end
end
end)
hs.audiodevice.watcher.start()
--[[
Make control act as escape when tapped
Thanks to https://gist.github.com/arbelt/b91e1f38a0880afb316dd5b5732759f1
]]
send_escape = false
last_mods = {}
control_key_handler = function()
send_escape = false
end
control_key_timer = hs.timer.delayed.new(0.15, control_key_handler)
control_handler = function(evt)
local new_mods = evt:getFlags()
if last_mods["ctrl"] == new_mods["ctrl"] then
return false
end
if not last_mods["ctrl"] then
last_mods = new_mods
send_escape = true
control_key_timer:start()
else
last_mods = new_mods
control_key_timer:stop()
if send_escape then
return true, {
hs.eventtap.event.newKeyEvent({}, 'escape', true),
hs.eventtap.event.newKeyEvent({}, 'escape', false),
}
end
end
return false
end
control_tap = hs.eventtap.new({hs.eventtap.event.types.flagsChanged}, control_handler)
control_tap:start()
other_handler = function(evt)
send_escape = false
return false
end
other_tap = hs.eventtap.new({hs.eventtap.event.types.keyDown}, other_handler)
other_tap:start()
|
Fix getting stuck in hyper mode when launching Anki
|
Fix getting stuck in hyper mode when launching Anki
|
Lua
|
mit
|
dguo/dotfiles,dguo/dotfiles,dguo/dotfiles
|
8a11dd81abfbb44435cbd551cbd46a339e28456a
|
scripts/ship.lua
|
scripts/ship.lua
|
local v2 = require 'dokidoki.v2'
assert(player, 'missing player argument')
assert(turn_speed, 'missing turn_speed argument')
assert(accel, 'missing accel argument')
assert(hit_points, 'missing hit_points argument')
local max_hit_points = hit_points
--player_colors = {
-- {1.0, 1.0, 1.0},
-- {0.5, 0.8, 0.2},
-- {0.2, 0.6, 0.6},
-- {0.8, 0.4, 0.2}
--}
--self.sprite.color = player_colors[player]
if sprites_table then
self.sprite.image = assert(game.resources[sprites_table][player])
end
velocity = v2(0, 0)
-- 1 for left, -1 for right
function turn(direction, amount)
amount = amount or 1
self.transform.facing =
v2.norm(v2.rotate(self.transform.facing, turn_speed * direction * amount))
end
function thrust(amount)
amount = amount or 1
velocity = velocity + self.transform.facing * accel * amount
end
local function random_point_on_ship()
-- assumes the ship is a rectangle
local a = self.collision.poly.vertices[1]
local ab = self.collision.poly.vertices[2] - a
local ac = self.collision.poly.vertices[4] - a
return self.transform.pos +
v2.rotate_to(self.transform.facing,
a + ab * math.random() + ac * math.random())
end
function update()
velocity = velocity * 0.97
self.transform.pos = self.transform.pos + velocity
if hit_points <= 0 then destruct() end
if math.random() < v2.mag(velocity) / 10 then
game.particles.add_bubble(random_point_on_ship())
end
-- debug
game.tracing.trace_bar(self.transform.pos + v2(0, 10),
hit_points / max_hit_points)
end
local function go_towards_or_away(target_pos, force_thrust, is_away)
local target_direction = target_pos - self.transform.pos
if is_away then target_direction = -target_direction end
if v2.cross(self.transform.facing, target_direction) > 0 then
turn(1)
else
turn(-1)
end
if force_thrust or v2.dot(self.transform.facing, target_direction) > 0 then
thrust()
end
end
function health_percentage()
return math.max(hit_points / max_hit_points, 0)
end
function damage(amount)
hit_points = math.max(hit_points - amount, 0)
end
function destruct()
if self.factory_ai then
factory_destruct()
else
game.particles.explode(self.transform.pos)
game.log.record_death(self.blueprint)
self.dead = true
end
end
local death_counter = 100
local next_explosion = 10
local opacity = 0.93
function factory_destruct()
if death_counter > 0 then
self.production.halt_production = true
self.sprite.color = {self.sprite.color[1], self.sprite.color[2], self.sprite.color[3], math.max(0, opacity)}
-- opacity = opacity - 0.006
opacity = 0
if death_counter % next_explosion == 0 then
random_vector = (v2.random() + v2.random()) * 30
game.particles.explode(self.transform.pos + random_vector)
next_explosion = math.random(6,15)
end
death_counter = death_counter - 1
else
for i = 1,5 do
random = (v2.random() + v2.random()) * 20
game.particles.explode(self.transform.pos + random)
end
game.log.record_death(self.blueprint)
self.dead = true
end
end
-- automatically thrusts and turns according to the target
function go_towards(target_pos, force_thrust)
go_towards_or_away(target_pos, force_thrust, false)
end
function go_away(target_pos, force_thrust)
go_towards_or_away(target_pos, force_thrust, true)
end
|
local v2 = require 'dokidoki.v2'
assert(player, 'missing player argument')
assert(turn_speed, 'missing turn_speed argument')
assert(accel, 'missing accel argument')
assert(hit_points, 'missing hit_points argument')
local max_hit_points = hit_points
self.sprite.color = {1.0, 1.0, 1.0}
if sprites_table then
self.sprite.image = assert(game.resources[sprites_table][player])
end
velocity = v2(0, 0)
-- 1 for left, -1 for right
function turn(direction, amount)
amount = amount or 1
self.transform.facing =
v2.norm(v2.rotate(self.transform.facing, turn_speed * direction * amount))
end
function thrust(amount)
amount = amount or 1
velocity = velocity + self.transform.facing * accel * amount
end
local function random_point_on_ship()
-- assumes the ship is a rectangle
local a = self.collision.poly.vertices[1]
local ab = self.collision.poly.vertices[2] - a
local ac = self.collision.poly.vertices[4] - a
return self.transform.pos +
v2.rotate_to(self.transform.facing,
a + ab * math.random() + ac * math.random())
end
function update()
velocity = velocity * 0.97
self.transform.pos = self.transform.pos + velocity
if hit_points <= 0 then destruct() end
if math.random() < v2.mag(velocity) / 10 then
game.particles.add_bubble(random_point_on_ship())
end
-- debug
game.tracing.trace_bar(self.transform.pos + v2(0, 10),
hit_points / max_hit_points)
end
local function go_towards_or_away(target_pos, force_thrust, is_away)
local target_direction = target_pos - self.transform.pos
if is_away then target_direction = -target_direction end
if v2.cross(self.transform.facing, target_direction) > 0 then
turn(1)
else
turn(-1)
end
if force_thrust or v2.dot(self.transform.facing, target_direction) > 0 then
thrust()
end
end
function health_percentage()
return math.max(hit_points / max_hit_points, 0)
end
function damage(amount)
hit_points = math.max(hit_points - amount, 0)
end
function destruct()
if self.factory_ai then
factory_destruct()
else
game.particles.explode(self.transform.pos)
game.log.record_death(self.blueprint)
self.dead = true
end
end
local death_counter = 100
local next_explosion = 10
local opacity = 0.3
function factory_destruct()
if death_counter > 0 then
self.production.halt_production = true
self.sprite.color = {self.sprite.color[1], self.sprite.color[2], self.sprite.color[3], math.max(0, opacity)}
opacity = opacity - 0.006
if death_counter % next_explosion == 0 then
random_vector = (v2.random() + v2.random()) * 30
game.particles.explode(self.transform.pos + random_vector)
next_explosion = math.random(6,15)
end
death_counter = death_counter - 1
else
for i = 1,5 do
random = (v2.random() + v2.random()) * 20
game.particles.explode(self.transform.pos + random)
end
game.log.record_death(self.blueprint)
self.dead = true
end
end
-- automatically thrusts and turns according to the target
function go_towards(target_pos, force_thrust)
go_towards_or_away(target_pos, force_thrust, false)
end
function go_away(target_pos, force_thrust)
go_towards_or_away(target_pos, force_thrust, true)
end
|
Bugfix for factory explosion.
|
Bugfix for factory explosion.
|
Lua
|
mit
|
henkboom/pax-britannica
|
bafdfe9194cd3ed565cd2f415b36df3b27bc9501
|
lua_scripts/init.lua
|
lua_scripts/init.lua
|
-- Copyright (c) 2011 Nokia Corporation.
-- Author: Lauri T. Aarnio
--
-- Licensed under LGPL version 2.1, see top level LICENSE file for details.
-- This script is executed by sb2d at startup, this
-- initializes the rule tree database (which is empty
-- but attached when this script is started)
session_dir = os.getenv("SBOX_SESSION_DIR")
debug_messages_enabled = sblib.debug_messages_enabled()
function do_file(filename)
if (debug_messages_enabled) then
sblib.log("debug", string.format("Loading '%s'", filename))
end
local f, err = loadfile(filename)
if (f == nil) then
error("\nError while loading " .. filename .. ": \n"
.. err .. "\n")
-- "error()" never returns
else
f() -- execute the loaded chunk
end
end
-- Load session-specific settings
do_file(session_dir .. "/sb2-session.conf")
target_root = sbox_target_root
if (not target_root or target_root == "") then
target_root = "/"
end
tools_root = sbox_tools_root
if (tools_root == "") then
tools_root = nil
end
-- Build "all_modes" table. all_modes[1] will be name of default mode.
all_modes_str = os.getenv("SB2_ALL_MODES")
all_modes = {}
if (all_modes_str) then
for m in string.gmatch(all_modes_str, "[^ ]*") do
if m ~= "" then
table.insert(all_modes, m)
ruletree.catalog_set("MODES", m, 0)
end
end
end
ruletree.catalog_set("MODES", "#default", ruletree.new_string(all_modes[1]))
-- Exec preprocessing rules to ruletree:
do_file(session_dir .. "/lua_scripts/init_argvmods_rules.lua")
-- mode-spefic config to ruletree:
do_file(session_dir .. "/lua_scripts/init_modeconfig.lua")
|
-- Copyright (c) 2011 Nokia Corporation.
-- Author: Lauri T. Aarnio
--
-- Licensed under LGPL version 2.1, see top level LICENSE file for details.
-- This script is executed by sb2d at startup, this
-- initializes the rule tree database (which is empty
-- but attached when this script is started)
session_dir = os.getenv("SBOX_SESSION_DIR")
debug_messages_enabled = sblib.debug_messages_enabled()
function do_file(filename)
if (debug_messages_enabled) then
sblib.log("debug", string.format("Loading '%s'", filename))
end
local f, err = loadfile(filename)
if (f == nil) then
error("\nError while loading " .. filename .. ": \n"
.. err .. "\n")
-- "error()" never returns
else
f() -- execute the loaded chunk
end
end
-- Load session-specific settings
do_file(session_dir .. "/sb2-session.conf")
target_root = sbox_target_root
if (not target_root or target_root == "") then
target_root = "/"
end
tools_root = sbox_tools_root
if (tools_root == "") then
tools_root = nil
end
tools = tools_root
if (not tools) then
tools = "/"
end
if (tools == "/") then
tools_prefix = ""
else
tools_prefix = tools
end
-- Build "all_modes" table. all_modes[1] will be name of default mode.
all_modes_str = os.getenv("SB2_ALL_MODES")
all_modes = {}
if (all_modes_str) then
for m in string.gmatch(all_modes_str, "[^ ]*") do
if m ~= "" then
table.insert(all_modes, m)
ruletree.catalog_set("MODES", m, 0)
end
end
end
ruletree.catalog_set("MODES", "#default", ruletree.new_string(all_modes[1]))
-- Exec preprocessing rules to ruletree:
do_file(session_dir .. "/lua_scripts/init_argvmods_rules.lua")
-- mode-spefic config to ruletree:
do_file(session_dir .. "/lua_scripts/init_modeconfig.lua")
|
Set "tools" and "tools_prefix" in init.lua
|
Set "tools" and "tools_prefix" in init.lua
|
Lua
|
lgpl-2.1
|
OlegGirko/ldbox,h113331pp/scratchbox2,ldbox/ldbox,ldbox/ldbox,h113331pp/scratchbox2,OlegGirko/ldbox,ldbox/ldbox,OlegGirko/ldbox,ldbox/ldbox,h113331pp/scratchbox2,ldbox/ldbox,OlegGirko/ldbox,h113331pp/scratchbox2,h113331pp/scratchbox2,ldbox/ldbox,OlegGirko/ldbox,OlegGirko/ldbox,h113331pp/scratchbox2
|
752ae1d60c5d06f3923328ed9663b14e436775da
|
CosineDistance.lua
|
CosineDistance.lua
|
local CosineDistance, parent = torch.class('nn.CosineDistance', 'nn.Module')
function CosineDistance:__init()
parent.__init(self)
self.gradInput = {torch.Tensor(), torch.Tensor()}
end
function CosineDistance:updateOutput(input)
local input1, input2 = input[1], input[2]
if not input1:isContiguous() then input1 = input1:clone() end
if not input2:isContiguous() then input2 = input2:clone() end
if input1:dim() == 1 then
input1 = input1:view(1,-1)
input2 = input2:view(1,-1)
end
if not self.buffer then
self.buffer = input1.new()
self.w1 = input1.new()
self.w22 = input1.new()
self.w = input1.new()
self.w32 = input1.new()
self.ones = input1.new()
end
self.buffer:cmul(input1,input2)
self.w1:sum(self.buffer,2)
local epsilon = 1e-12
self.buffer:cmul(input1,input1)
self.w22:sum(self.buffer,2):add(epsilon)
self.ones:resizeAs(self.w22):fill(1)
self.w22:cdiv(self.ones, self.w22)
self.w:resizeAs(self.w22):copy(self.w22)
self.buffer:cmul(input2,input2)
self.w32:sum(self.buffer,2):add(epsilon)
self.w32:cdiv(self.ones, self.w32)
self.w:cmul(self.w32)
self.w:sqrt()
self.output:cmul(self.w1,self.w)
self.output = self.output:select(2,1)
return self.output
end
function CosineDistance:updateGradInput(input, gradOutput)
local v1 = input[1]
local v2 = input[2]
local not_batch = false
if not v1:isContiguous() then v1 = v1:clone() end
if not v2:isContiguous() then v2 = v2:clone() end
if v1:dim() == 1 then
v1 = v1:view(1,-1)
v2 = v2:view(1,-1)
not_batch = true
end
local gw1 = self.gradInput[1]
local gw2 = self.gradInput[2]
gw1:resizeAs(v1):copy(v2)
gw2:resizeAs(v1):copy(v1)
self.w = self.w:expandAs(v1)
self.buffer:cmul(self.w1,self.w22)
self.buffer = self.buffer:expandAs(v1)
gw1:addcmul(-1,self.buffer,v1)
gw1:cmul(self.w)
self.buffer:cmul(self.w1,self.w32)
self.buffer = self.buffer:expandAs(v1)
gw2:addcmul(-1,self.buffer,v2)
gw2:cmul(self.w)
local go = gradOutput:view(-1,1):expandAs(v1)
gw1:cmul(go)
gw2:cmul(go)
if not_batch then
self.gradInput[1] = gw1:select(1,1)
self.gradInput[2] = gw2:select(1,1)
end
-- fix for torch bug
-- https://github.com/torch/torch7/issues/289
self.buffer:resize()
return self.gradInput
end
|
local CosineDistance, parent = torch.class('nn.CosineDistance', 'nn.Module')
function CosineDistance:__init()
parent.__init(self)
self.gradInput = {torch.Tensor(), torch.Tensor()}
end
local function makeContiguous(self, input1, input2)
if not input1:isContiguous() then
self._input1 = self._input1 or input1.new()
self._input1:resizeAs(input1):copy(input1)
input1 = self._input1
end
if not input2:isContiguous() then
self._input2 = self._input2 or input2.new()
self._input2:resizeAs(input2):copy(input2)
input2 = self._input2
end
return input1, input2
end
function CosineDistance:updateOutput(input)
local input1, input2 = input[1], input[2]
input1, input2 = makeContiguous(self, input1, input2)
if input1:dim() == 1 then
input1 = input1:view(1,-1)
input2 = input2:view(1,-1)
end
if not self.buffer then
self.buffer = input1.new()
self.w1 = input1.new()
self.w22 = input1.new()
self.w = input1.new()
self.w32 = input1.new()
self.ones = input1.new()
end
self.buffer:cmul(input1,input2)
self.w1:sum(self.buffer,2)
local epsilon = 1e-12
self.buffer:cmul(input1,input1)
self.w22:sum(self.buffer,2):add(epsilon)
self.ones:resizeAs(self.w22):fill(1)
self.w22:cdiv(self.ones, self.w22)
self.w:resizeAs(self.w22):copy(self.w22)
self.buffer:cmul(input2,input2)
self.w32:sum(self.buffer,2):add(epsilon)
self.w32:cdiv(self.ones, self.w32)
self.w:cmul(self.w32)
self.w:sqrt()
self.output:cmul(self.w1,self.w)
self.output = self.output:select(2,1)
return self.output
end
function CosineDistance:updateGradInput(input, gradOutput)
local v1 = input[1]
local v2 = input[2]
local not_batch = false
v1, v2 = makeContiguous(self, v1, v2)
if v1:dim() == 1 then
v1 = v1:view(1,-1)
v2 = v2:view(1,-1)
not_batch = true
end
local gw1 = self.gradInput[1]
local gw2 = self.gradInput[2]
gw1:resizeAs(v1):copy(v2)
gw2:resizeAs(v1):copy(v1)
self.w = self.w:expandAs(v1)
self.buffer:cmul(self.w1,self.w22)
self.buffer = self.buffer:expandAs(v1)
gw1:addcmul(-1,self.buffer,v1)
gw1:cmul(self.w)
self.buffer:cmul(self.w1,self.w32)
self.buffer = self.buffer:expandAs(v1)
gw2:addcmul(-1,self.buffer,v2)
gw2:cmul(self.w)
local go = gradOutput:view(-1,1):expandAs(v1)
gw1:cmul(go)
gw2:cmul(go)
if not_batch then
self.gradInput[1] = gw1:select(1,1)
self.gradInput[2] = gw2:select(1,1)
end
-- fix for torch bug
-- https://github.com/torch/torch7/issues/289
self.buffer:resize()
return self.gradInput
end
|
Fix CosineDistance to handle non-contiguous input
|
Fix CosineDistance to handle non-contiguous input
Reuse the buffer of contiguous input tensor in backward pass as suggested..
|
Lua
|
bsd-3-clause
|
witgo/nn,xianjiec/nn,andreaskoepf/nn,jonathantompson/nn,caldweln/nn,joeyhng/nn,kmul00/nn,nicholas-leonard/nn,elbamos/nn,Moodstocks/nn,diz-vara/nn,apaszke/nn,clementfarabet/nn,colesbury/nn,mlosch/nn,sagarwaghmare69/nn,jhjin/nn,vgire/nn,lukasc-ch/nn,PraveerSINGH/nn,eriche2016/nn
|
6b5682e4521cf9ae7f94f875cf6cf02e46127bdc
|
tests/actions/make/cpp/test_make_linking.lua
|
tests/actions/make/cpp/test_make_linking.lua
|
--
-- tests/actions/make/cpp/test_make_linking.lua
-- Validate the link step generation for makefiles.
-- Copyright (c) 2010-2013 Jason Perkins and the Premake project
--
local suite = test.declare("make_linking")
local make = premake.make
local project = premake.project
--
-- Setup and teardown
--
local sln, prj
function suite.setup()
_OS = "linux"
sln, prj = test.createsolution()
end
local function prepare(calls)
local cfg = test.getconfig(prj, "Debug")
local toolset = premake.tools.gcc
premake.callarray(make, calls, cfg, toolset)
end
--
-- Check link command for a shared C++ library.
--
function suite.links_onCppSharedLib()
kind "SharedLib"
prepare { "ldFlags", "linkCmd" }
test.capture [[
ALL_LDFLAGS += $(LDFLAGS) -s -shared
LINKCMD = $(CXX) -o $(TARGET) $(OBJECTS) $(RESOURCES) $(ARCH) $(ALL_LDFLAGS) $(LIBS)
]]
end
--
-- Check link command for a shared C library.
--
function suite.links_onCSharedLib()
language "C"
kind "SharedLib"
prepare { "ldFlags", "linkCmd" }
test.capture [[
ALL_LDFLAGS += $(LDFLAGS) -s -shared
LINKCMD = $(CC) -o $(TARGET) $(OBJECTS) $(RESOURCES) $(ARCH) $(ALL_LDFLAGS) $(LIBS)
]]
end
--
-- Check link command for a static library.
--
function suite.links_onStaticLib()
kind "StaticLib"
prepare { "ldFlags", "linkCmd" }
test.capture [[
ALL_LDFLAGS += $(LDFLAGS) -s
LINKCMD = $(AR) -rcs $(TARGET) $(OBJECTS)
]]
end
--
-- Check link command for a Mac OS X universal static library.
--
function suite.links_onMacUniversalStaticLib()
architecture "universal"
kind "StaticLib"
prepare { "ldFlags", "linkCmd" }
test.capture [[
ALL_LDFLAGS += $(LDFLAGS) -s
LINKCMD = libtool -o $(TARGET) $(OBJECTS)
]]
end
--
-- Check a linking to a sibling static library.
--
function suite.links_onSiblingStaticLib()
links "MyProject2"
test.createproject(sln)
kind "StaticLib"
location "build"
prepare { "ldFlags", "libs", "ldDeps" }
test.capture [[
ALL_LDFLAGS += $(LDFLAGS) -s
LIBS += build/libMyProject2.a
LDDEPS += build/libMyProject2.a
]]
end
--
-- Check a linking to a sibling shared library.
--
function suite.links_onSiblingSharedLib()
links "MyProject2"
test.createproject(sln)
kind "SharedLib"
location "build"
prepare { "ldFlags", "libs", "ldDeps" }
test.capture [[
ALL_LDFLAGS += $(LDFLAGS) -s
LIBS += build/libMyProject2.so
LDDEPS += build/libMyProject2.so
]]
end
--
-- When referencing an external library via a path, the directory
-- should be added to the library search paths, and the library
-- itself included via an -l flag.
--
function suite.onExternalLibraryWithPath()
location "MyProject"
links { "libs/SomeLib" }
prepare { "ldFlags", "libs" }
test.capture [[
ALL_LDFLAGS += $(LDFLAGS) -s -L../libs
LIBS += -lSomeLib
]]
end
|
--
-- tests/actions/make/cpp/test_make_linking.lua
-- Validate the link step generation for makefiles.
-- Copyright (c) 2010-2013 Jason Perkins and the Premake project
--
local suite = test.declare("make_linking")
local make = premake.make
local project = premake.project
--
-- Setup and teardown
--
local sln, prj
function suite.setup()
_OS = "linux"
sln, prj = test.createsolution()
end
local function prepare(calls)
local cfg = test.getconfig(prj, "Debug")
local toolset = premake.tools.gcc
premake.callarray(make, calls, cfg, toolset)
end
--
-- Check link command for a shared C++ library.
--
function suite.links_onCppSharedLib()
kind "SharedLib"
prepare { "ldFlags", "linkCmd" }
test.capture [[
ALL_LDFLAGS += $(LDFLAGS) -s -shared
LINKCMD = $(CXX) -o $(TARGET) $(OBJECTS) $(RESOURCES) $(ARCH) $(ALL_LDFLAGS) $(LIBS)
]]
end
--
-- Check link command for a shared C library.
--
function suite.links_onCSharedLib()
language "C"
kind "SharedLib"
prepare { "ldFlags", "linkCmd" }
test.capture [[
ALL_LDFLAGS += $(LDFLAGS) -s -shared
LINKCMD = $(CC) -o $(TARGET) $(OBJECTS) $(RESOURCES) $(ARCH) $(ALL_LDFLAGS) $(LIBS)
]]
end
--
-- Check link command for a static library.
--
function suite.links_onStaticLib()
kind "StaticLib"
prepare { "ldFlags", "linkCmd" }
test.capture [[
ALL_LDFLAGS += $(LDFLAGS) -s
LINKCMD = $(AR) -rcs $(TARGET) $(OBJECTS)
]]
end
--
-- Check link command for a Mac OS X universal static library.
--
function suite.links_onMacUniversalStaticLib()
architecture "universal"
kind "StaticLib"
prepare { "ldFlags", "linkCmd" }
test.capture [[
ALL_LDFLAGS += $(LDFLAGS) -s
LINKCMD = libtool -o $(TARGET) $(OBJECTS)
]]
end
--
-- Check a linking to a sibling static library.
--
function suite.links_onSiblingStaticLib()
links "MyProject2"
test.createproject(sln)
kind "StaticLib"
location "build"
prepare { "ldFlags", "libs", "ldDeps" }
test.capture [[
ALL_LDFLAGS += $(LDFLAGS) -s
LIBS += build/libMyProject2.a
LDDEPS += build/libMyProject2.a
]]
end
--
-- Check a linking to a sibling shared library.
--
function suite.links_onSiblingSharedLib()
links "MyProject2"
test.createproject(sln)
kind "SharedLib"
location "build"
prepare { "ldFlags", "libs", "ldDeps" }
test.capture [[
ALL_LDFLAGS += $(LDFLAGS) -s
LIBS += build/libMyProject2.so
LDDEPS += build/libMyProject2.so
]]
end
--
-- When referencing an external library via a path, the directory
-- should be added to the library search paths, and the library
-- itself included via an -l flag.
--
function suite.onExternalLibraryWithPath()
location "MyProject"
links { "libs/SomeLib" }
prepare { "ldFlags", "libs" }
test.capture [[
ALL_LDFLAGS += $(LDFLAGS) -s -L../libs
LIBS += -lSomeLib
]]
end
--
-- When referencing an external library with a period in the
-- file name make sure it appears correctly in the LIBS
-- directive. Currently the period and everything after it
-- is stripped
--
function suite.onExternalLibraryWithPath()
location "MyProject"
links { "libs/SomeLib-1.1" }
prepare { "libs", }
test.capture [[
LIBS += -lSomeLib-1.1
]]
end
|
Linking gmake test - checks external lib name isn't mangled
|
Linking gmake test - checks external lib name isn't mangled
External libs with a period in the currently get changed.
The period and everything after it is deleted. So:
links {"lua-5.1"}
becomes:
-llua-5
in the makefile. This test checks for that. Fix in next commit
--HG--
extra : amend_source : cae92c3948f08c98ed2ac683ec10f88211fd0726
|
Lua
|
bsd-3-clause
|
annulen/premake,annulen/premake,annulen/premake,annulen/premake
|
2a57968d738fae9e13a0c257fa7c908b77ec2525
|
MMOCoreORB/bin/scripts/object/tangible/deed/pet_deed/sand_panther_deed.lua
|
MMOCoreORB/bin/scripts/object/tangible/deed/pet_deed/sand_panther_deed.lua
|
--Copyright (C) 2010 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 2 of the License,
--or (at your option) any later version.
--This program is distributed in the hope that it will be useful,
--but WITHOUT ANY WARRANTY; without even the implied warranty of
--MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
--See the GNU Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
object_tangible_deed_pet_deed_sand_panther_deed = object_tangible_deed_pet_deed_shared_sand_panther_deed:new {
templateType = PETDEED,
numberExperimentalProperties = {1, 1},
experimentalProperties = {"XX", "XX"},
experimentalWeights = {1, 1},
experimentalGroupTitles = {"null", "null"},
experimentalSubGroupTitles = {"null", "null"},
experimentalMin = {0, 0},
experimentalMax = {0, 0},
experimentalPrecision = {0, 0},
experimentalCombineType = {0, 0},
}
ObjectTemplates:addTemplate(object_tangible_deed_pet_deed_sand_panther_deed, "object/tangible/deed/pet_deed/sand_panther_deed.iff")
|
--Copyright (C) 2010 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 2 of the License,
--or (at your option) any later version.
--This program is distributed in the hope that it will be useful,
--but WITHOUT ANY WARRANTY; without even the implied warranty of
--MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
--See the GNU Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
object_tangible_deed_pet_deed_sand_panther_deed = object_tangible_deed_pet_deed_shared_sand_panther_deed:new {
templateType = PETDEED,
numberExperimentalProperties = {1, 1},
experimentalProperties = {"XX", "XX"},
experimentalWeights = {1, 1},
experimentalGroupTitles = {"null", "null"},
experimentalSubGroupTitles = {"null", "null"},
experimentalMin = {0, 0},
experimentalMax = {0, 0},
experimentalPrecision = {0, 0},
experimentalCombineType = {0, 0},
generatedObjectTemplate = "mobile/pet/razor_cat_be.iff",
controlDeviceObjectTemplate = "object/intangible/pet/corellian_sand_panther_hue.iff",
mobileTemplate = "razor_cat_be",
}
ObjectTemplates:addTemplate(object_tangible_deed_pet_deed_sand_panther_deed, "object/tangible/deed/pet_deed/sand_panther_deed.iff")
|
[Fixed] razor cat deeds - mantis 5484
|
[Fixed] razor cat deeds - mantis 5484
Change-Id: I9dcd2c26ae421ec051dce0b2d3e438135b74e9d1
|
Lua
|
agpl-3.0
|
Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo
|
18f5b42e33e8fdabd3c144e83ff229a59fc580ad
|
lua/autorun/Wire_Load.lua
|
lua/autorun/Wire_Load.lua
|
if VERSION < 143 then
ErrorNoHalt("WireMod: This branch of wiremod only supports Gmod13+.\n")
return
end
if SERVER then
-- this file
AddCSLuaFile("autorun/Wire_Load.lua")
-- shared includes
AddCSLuaFile("wire/WireShared.lua")
AddCSLuaFile("wire/Beam_NetVars.lua")
AddCSLuaFile("wire/WireGates.lua")
AddCSLuaFile("wire/WireMonitors.lua")
AddCSLuaFile("wire/GPULib.lua")
AddCSLuaFile("wire/CPULib.lua")
AddCSLuaFile("wire/Timedpairs.lua")
-- client includes
AddCSLuaFile("wire/client/cl_wirelib.lua")
AddCSLuaFile("wire/client/cl_modelplug.lua")
AddCSLuaFile("wire/client/cl_wire_map_interface.lua")
AddCSLuaFile("wire/client/WireDermaExts.lua")
AddCSLuaFile("wire/client/WireMenus.lua")
AddCSLuaFile("wire/client/TextEditor.lua")
AddCSLuaFile("wire/client/toolscreen.lua")
AddCSLuaFile("wire/client/wire_expression2_browser.lua")
AddCSLuaFile("wire/client/wire_expression2_editor.lua")
AddCSLuaFile("wire/client/e2helper.lua")
AddCSLuaFile("wire/client/e2descriptions.lua")
AddCSLuaFile("wire/client/gmod_tool_auto.lua")
AddCSLuaFile("wire/client/sound_browser.lua")
AddCSLuaFile("wire/client/rendertarget_fix.lua")
-- HL-ZASM
AddCSLuaFile("wire/client/hlzasm/hc_compiler.lua")
AddCSLuaFile("wire/client/hlzasm/hc_opcodes.lua")
AddCSLuaFile("wire/client/hlzasm/hc_expression.lua")
AddCSLuaFile("wire/client/hlzasm/hc_preprocess.lua")
AddCSLuaFile("wire/client/hlzasm/hc_syntax.lua")
AddCSLuaFile("wire/client/hlzasm/hc_codetree.lua")
AddCSLuaFile("wire/client/hlzasm/hc_optimize.lua")
AddCSLuaFile("wire/client/hlzasm/hc_output.lua")
AddCSLuaFile("wire/client/hlzasm/hc_tokenizer.lua")
-- ZVM
AddCSLuaFile("wire/zvm/zvm_core.lua")
AddCSLuaFile("wire/zvm/zvm_features.lua")
AddCSLuaFile("wire/zvm/zvm_opcodes.lua")
AddCSLuaFile("wire/zvm/zvm_data.lua")
AddCSLuaFile("von.lua")
-- resource files
for i=1,32 do
resource.AddSingleFile("settings/render_targets/WireGPU_RT_"..i..".txt")
end
resource.AddFile("materials/expression 2/cog.vmt")
resource.AddFile("materials/gui/silkicons/page_white_add.vmt")
resource.AddFile("materials/gui/silkicons/page_white_delete.vmt")
resource.AddFile("materials/wirelogo.vmt")
resource.AddSingleFile("materials/expression 2/cog_world.vmt")
resource.AddFile( "materials/gui/silkicons/folder.vmt" )
resource.AddFile( "materials/gui/silkicons/computer.vmt" )
resource.AddFile("materials/gui/silkicons/wrench.vtf")
resource.AddFile("materials/vgui/spawnmenu/save.vtf")
resource.AddFile("materials/gui/silkicons/help.vmt")
resource.AddFile("materials/gui/silkicons/emoticon_smile.vtf")
resource.AddFile("materials/gui/silkicons/newspaper.vtf")
end
-- shared includes
include("wire/WireShared.lua")
include("wire/Beam_NetVars.lua")
include("wire/WireGates.lua")
include("wire/WireMonitors.lua")
include("wire/GPULib.lua")
include("wire/CPULib.lua")
include("wire/Timedpairs.lua")
include("von.lua")
-- server includes
if SERVER then
include("wire/server/WireLib.lua")
include("wire/server/ModelPlug.lua")
include("wire/server/radiolib.lua")
end
-- client includes
if CLIENT then
include("wire/client/cl_wirelib.lua")
include("wire/client/cl_modelplug.lua")
include("wire/client/cl_wire_map_interface.lua")
include("wire/client/WireDermaExts.lua")
include("wire/client/WireMenus.lua")
include("wire/client/toolscreen.lua")
include("wire/client/TextEditor.lua")
include("wire/client/wire_expression2_browser.lua")
include("wire/client/wire_expression2_editor.lua")
include("wire/client/e2helper.lua")
include("wire/client/e2descriptions.lua")
include("wire/client/gmod_tool_auto.lua")
include("wire/client/sound_browser.lua")
include("wire/client/rendertarget_fix.lua")
include("wire/client/hlzasm/hc_compiler.lua")
end
|
if VERSION < 143 then
ErrorNoHalt("WireMod: This branch of wiremod only supports Gmod13+.\n")
return
end
if SERVER then
-- this file
AddCSLuaFile("autorun/Wire_Load.lua")
-- shared includes
AddCSLuaFile("wire/WireShared.lua")
AddCSLuaFile("wire/Beam_NetVars.lua")
AddCSLuaFile("wire/WireGates.lua")
AddCSLuaFile("wire/WireMonitors.lua")
AddCSLuaFile("wire/GPULib.lua")
AddCSLuaFile("wire/CPULib.lua")
AddCSLuaFile("wire/Timedpairs.lua")
-- client includes
AddCSLuaFile("wire/client/cl_wirelib.lua")
AddCSLuaFile("wire/client/cl_modelplug.lua")
AddCSLuaFile("wire/client/cl_wire_map_interface.lua")
AddCSLuaFile("wire/client/WireDermaExts.lua")
AddCSLuaFile("wire/client/WireMenus.lua")
AddCSLuaFile("wire/client/TextEditor.lua")
AddCSLuaFile("wire/client/toolscreen.lua")
AddCSLuaFile("wire/client/wire_expression2_browser.lua")
AddCSLuaFile("wire/client/wire_expression2_editor.lua")
AddCSLuaFile("wire/client/e2helper.lua")
AddCSLuaFile("wire/client/e2descriptions.lua")
AddCSLuaFile("wire/client/gmod_tool_auto.lua")
AddCSLuaFile("wire/client/sound_browser.lua")
AddCSLuaFile("wire/client/rendertarget_fix.lua")
-- HL-ZASM
AddCSLuaFile("wire/client/hlzasm/hc_compiler.lua")
AddCSLuaFile("wire/client/hlzasm/hc_opcodes.lua")
AddCSLuaFile("wire/client/hlzasm/hc_expression.lua")
AddCSLuaFile("wire/client/hlzasm/hc_preprocess.lua")
AddCSLuaFile("wire/client/hlzasm/hc_syntax.lua")
AddCSLuaFile("wire/client/hlzasm/hc_codetree.lua")
AddCSLuaFile("wire/client/hlzasm/hc_optimize.lua")
AddCSLuaFile("wire/client/hlzasm/hc_output.lua")
AddCSLuaFile("wire/client/hlzasm/hc_tokenizer.lua")
-- ZVM
AddCSLuaFile("wire/zvm/zvm_core.lua")
AddCSLuaFile("wire/zvm/zvm_features.lua")
AddCSLuaFile("wire/zvm/zvm_opcodes.lua")
AddCSLuaFile("wire/zvm/zvm_data.lua")
AddCSLuaFile("von.lua")
-- resource files
for i=1,32 do
resource.AddSingleFile("settings/render_targets/WireGPU_RT_"..i..".txt")
end
resource.AddFile("materials/expression 2/cog.vmt")
resource.AddFile("materials/gui/silkicons/page_white_add.vmt")
resource.AddFile("materials/gui/silkicons/page_white_delete.vmt")
resource.AddFile("materials/wirelogo.vmt")
resource.AddSingleFile("materials/expression 2/cog_world.vmt")
resource.AddFile( "materials/gui/silkicons/folder.vmt" )
resource.AddFile( "materials/gui/silkicons/computer.vmt" )
resource.AddFile("materials/gui/silkicons/wrench.vtf")
resource.AddFile("materials/vgui/spawnmenu/save.vtf")
resource.AddFile("materials/gui/silkicons/help.vmt")
resource.AddFile("materials/gui/silkicons/emoticon_smile.vtf")
resource.AddFile("materials/gui/silkicons/newspaper.vtf")
end
-- shared includes
include("wire/WireShared.lua")
include("wire/Beam_NetVars.lua")
include("wire/WireGates.lua")
include("wire/WireMonitors.lua")
include("wire/GPULib.lua")
include("wire/CPULib.lua")
include("wire/Timedpairs.lua")
include("von.lua")
-- server includes
if SERVER then
include("wire/server/WireLib.lua")
include("wire/server/ModelPlug.lua")
include("wire/server/radiolib.lua")
end
-- client includes
if CLIENT then
include("wire/client/cl_wirelib.lua")
include("wire/client/cl_modelplug.lua")
include("wire/client/cl_wire_map_interface.lua")
include("wire/client/WireDermaExts.lua")
include("wire/client/WireMenus.lua")
include("wire/client/toolscreen.lua")
include("wire/client/TextEditor.lua")
include("wire/client/wire_expression2_browser.lua")
include("wire/client/wire_expression2_editor.lua")
include("wire/client/e2helper.lua")
include("wire/client/e2descriptions.lua")
include("wire/client/gmod_tool_auto.lua")
include("wire/client/sound_browser.lua")
include("wire/client/rendertarget_fix.lua")
include("wire/client/hlzasm/hc_compiler.lua")
-- Temporary workaround while OnEntityCreated isn't working...
timer.Create("OnEntityCreatedWorkaround", 10, 1, function() hook.Call("OnEntityCreated",GAMEMODE,LocalPlayer()) end)
end
|
Temporary workaround while OnEntityCreated isn't working... Fixes E2 editor not ever asking for functions
|
Temporary workaround while OnEntityCreated isn't working...
Fixes E2 editor not ever asking for functions
|
Lua
|
apache-2.0
|
Python1320/wire,CaptainPRICE/wire,NezzKryptic/Wire,mms92/wire,mitterdoo/wire,Grocel/wire,sammyt291/wire,immibis/wiremod,bigdogmat/wire,rafradek/wire,notcake/wire,plinkopenguin/wiremod,thegrb93/wire,dvdvideo1234/wire,garrysmodlua/wire,wiremod/wire
|
2926bac3c8fae8116091727f850f89baf1951e2f
|
spec/fs_spec.lua
|
spec/fs_spec.lua
|
local lfs = require "lfs"
local fs = require "luacheck.fs"
local utils = require "luacheck.utils"
local P = fs.normalize
describe("fs", function()
describe("is_dir", function()
it("returns true for directories", function()
assert.is_true(fs.is_dir("spec/folder"))
end)
it("returns false for files", function()
assert.is_false(fs.is_dir("spec/folder/foo"))
end)
it("returns false for non-existent paths", function()
assert.is_false(fs.is_dir("spec/folder/non-existent"))
end)
end)
describe("is_file", function()
it("returns true for files", function()
assert.is_true(fs.is_file("spec/folder/foo"))
end)
it("returns false for directories", function()
assert.is_false(fs.is_file("spec/folder"))
end)
it("returns false for non-existent paths", function()
assert.is_false(fs.is_file("spec/folder/non-existent"))
end)
end)
describe("extract_files", function()
it("returns sorted list of files in a directory matching pattern", function()
assert.same({
P"spec/folder/folder1/fail",
P"spec/folder/folder1/file",
P"spec/folder/foo"
}, fs.extract_files(P"spec/folder", "^f"))
end)
end)
describe("get_mtime", function()
it("returns modification time as a number", function()
assert.number(fs.get_mtime("spec/folder/foo"))
end)
it("returns nil for non-existent files", function()
assert.is_nil(fs.get_mtime("spec/folder/non-existent"))
end)
end)
describe("get_current_dir", function()
it("returns absolute path to current directory with trailing directory separator", function()
local current_dir = fs.get_current_dir()
assert.string(current_dir)
assert.matches(utils.dir_sep .. "$", current_dir)
assert.not_equal("", (fs.split_base(current_dir)))
assert.is_true(fs.is_file(current_dir .. "spec/folder/foo"))
end)
end)
describe("find_file", function()
it("finds file in a directory", function()
local path = fs.get_current_dir() .. P"spec/folder"
assert.equal(path, fs.find_file(path, "foo"))
end)
it("finds file in a parent directory", function()
local path = fs.get_current_dir() .. P"spec/folder"
assert.equal(path, fs.find_file(fs.join(path, "folder1"), "foo"))
end)
it("returns nil if can't find file", function()
assert.is_nil(
fs.find_file(fs.get_current_dir(), "this file shouldn't exist or it will make luacheck testsuite break"))
end)
end)
end)
for _, fs_name in ipairs({"lua_fs", "lfs_fs"}) do
local base_fs = require("luacheck." .. fs_name)
describe(fs_name, function()
describe("get_current_dir", function()
it("returns absolute path to current directory", function()
local current_dir = base_fs.get_current_dir()
assert.string(current_dir)
assert.not_equal("", (fs.split_base(current_dir)))
assert.is_true(fs.is_file(fs.join(current_dir, "spec/folder/foo")))
end)
end)
describe("get_mode", function()
local tricky_path = "spec/'"
it("returns 'file' for a file", function()
assert(io.open(tricky_path, "w"))
finally(function() assert(os.remove(tricky_path)) end)
assert.equal("file", base_fs.get_mode(tricky_path))
end)
it("returns 'directory' for a directory", function()
assert(lfs.mkdir(tricky_path))
finally(function() assert(lfs.rmdir(tricky_path)) end)
assert.equal("directory", base_fs.get_mode(tricky_path))
end)
it("returns not 'file' or 'directory' if path doesn't point to a file or a directory", function()
local mode = base_fs.get_mode(tricky_path)
assert.not_equal("file", mode)
assert.not_equal("directory", mode)
end)
it("returns not 'file' or 'directory' if path is bad", function()
local mode = base_fs.get_mode('"^<>!|&%')
assert.not_equal("file", mode)
assert.not_equal("directory", mode)
end)
end)
end)
end
|
local lfs = require "lfs"
local fs = require "luacheck.fs"
local utils = require "luacheck.utils"
local P = fs.normalize
describe("fs", function()
describe("is_dir", function()
it("returns true for directories", function()
assert.is_true(fs.is_dir("spec/folder"))
end)
it("returns false for files", function()
assert.is_false(fs.is_dir("spec/folder/foo"))
end)
it("returns false for non-existent paths", function()
assert.is_false(fs.is_dir("spec/folder/non-existent"))
end)
end)
describe("is_file", function()
it("returns true for files", function()
assert.is_true(fs.is_file("spec/folder/foo"))
end)
it("returns false for directories", function()
assert.is_false(fs.is_file("spec/folder"))
end)
it("returns false for non-existent paths", function()
assert.is_false(fs.is_file("spec/folder/non-existent"))
end)
end)
describe("extract_files", function()
it("returns sorted list of files in a directory matching pattern", function()
assert.same({
P"spec/folder/folder1/fail",
P"spec/folder/folder1/file",
P"spec/folder/foo"
}, fs.extract_files(P"spec/folder", "^f"))
end)
end)
describe("get_mtime", function()
it("returns modification time as a number", function()
assert.number(fs.get_mtime("spec/folder/foo"))
end)
it("returns nil for non-existent files", function()
assert.is_nil(fs.get_mtime("spec/folder/non-existent"))
end)
end)
describe("get_current_dir", function()
it("returns absolute path to current directory with trailing directory separator", function()
local current_dir = fs.get_current_dir()
assert.string(current_dir)
assert.matches(utils.dir_sep .. "$", current_dir)
assert.not_equal("", (fs.split_base(current_dir)))
assert.is_true(fs.is_file(current_dir .. "spec/folder/foo"))
end)
end)
describe("find_file", function()
it("finds file in a directory", function()
local path = fs.get_current_dir() .. P"spec/folder"
assert.equal(path, fs.find_file(path, "foo"))
end)
it("finds file in a parent directory", function()
local path = fs.get_current_dir() .. P"spec/folder"
assert.equal(path, fs.find_file(fs.join(path, "folder1"), "foo"))
end)
it("returns nil if can't find file", function()
assert.is_nil(
fs.find_file(fs.get_current_dir(), "this file shouldn't exist or it will make luacheck testsuite break"))
end)
end)
end)
for _, fs_name in ipairs({"lua_fs", "lfs_fs"}) do
local base_fs = require("luacheck." .. fs_name)
describe(fs_name, function()
describe("get_current_dir", function()
it("returns absolute path to current directory", function()
local current_dir = base_fs.get_current_dir()
assert.string(current_dir)
assert.not_equal("", (fs.split_base(current_dir)))
assert.is_true(fs.is_file(fs.join(current_dir, "spec/folder/foo")))
end)
end)
describe("get_mode", function()
local tricky_path = "spec" .. utils.dir_sep .. "'"
it("returns 'file' for a file", function()
local fh = assert(io.open(tricky_path, "w"))
fh:close()
finally(function() assert(os.remove(tricky_path)) end)
assert.equal("file", base_fs.get_mode(tricky_path))
end)
it("returns 'directory' for a directory", function()
assert(lfs.mkdir(tricky_path))
finally(function() assert(lfs.rmdir(tricky_path)) end)
assert.equal("directory", base_fs.get_mode(tricky_path))
end)
it("returns not 'file' or 'directory' if path doesn't point to a file or a directory", function()
local mode = base_fs.get_mode(tricky_path)
assert.not_equal("file", mode)
assert.not_equal("directory", mode)
end)
it("returns not 'file' or 'directory' if path is bad", function()
local mode = base_fs.get_mode('"^<>!|&%')
assert.not_equal("file", mode)
assert.not_equal("directory", mode)
end)
end)
end)
end
|
Fix spec for Windows
|
Fix spec for Windows
Use platform dependent directory separator, close files before deleting
them.
|
Lua
|
mit
|
xpol/luacheck,linuxmaniac/luacheck,mpeterv/luacheck,linuxmaniac/luacheck,mpeterv/luacheck,xpol/luacheck,mpeterv/luacheck,xpol/luacheck
|
6908f0015c8a7158f4d3f4df688e9564aa201117
|
OS/DiskOS/Libraries/map.lua
|
OS/DiskOS/Libraries/map.lua
|
local path = select(1,...)
return function(w,h,sheet)
local Map = {}
Map.w, Map.h = w or 24, h or 9
--Initialize the map table
Map.m = {}
for x=1, Map.w do
Map.m[x] = {}
for y=1, Map.h do
Map.m[x][y] = 0
end
end
Map.sheet = sheet
--If called with a function, it will be called on everycell with x,y,sprid args
--The function can return an new sprid to set
--If called with no args, it will return the map table.
function Map:map(func)
if func then
for x=1, self.w do
for y=1, self.h do
self.m[x][y] = func(x,y,self.m[x][y]) or self.m[x][y]
--func(x,y,self.m[x][y])
end
end
end
return self.m
end
function Map:cell(x,y,newID)
if newID then
self.m[x][y] = newID or 0
return self
else
return self.m[x][y]
end
end
function Map:cut(x,y,w,h)
local x,y,w,h = x or 1, y or 1, w or self.w, h or self.h
local nMap = require(path)(w,h)
local m = nMap:map()
for my=1,h do
for mx=1,w do
if self.m[mx+x-1] and self.m[mx+x-1][my+y-1] then
m[mx][my] = self.m[mx+x-1][my+y-1]
end
end
end
return nMap
end
function Map:size() return self.w, self.h end
function Map:width() return self.w end
function Map:height() return self.h end
function Map:draw(dx,dy,x,y,w,h,sx,sy,sheet)
local dx,dy,x,y,w,h,sx,sy = dx or 1, dy or 1, x or 1, y or 1, w or self.w, h or self.h, sx or 1, sy or 1
local cm = self:cut(x,y,w,h)
cm:map(function(spx,spy,sprid)
if sprid < 1 then return end
(self.sheet or sheet):draw(sprid,dx + spx*8*sx - 8*sx, dy + spy*8*sy - 8*sy, 0, sx, sy)
end)
return self
end
function Map:export()
local data = "LK12;TILEMAP;"..self.w.."x"..self.h..";"
self:map(function(x,y,sprid)
data = data..sprid..";"
end)
return data
end
function Map:import(data)
if not data:sub(0,13) == "LK12;TILEMAP;" then error("Wrong header") end
local w,h,mdata = string.match(data,"LK12;TILEMAP;(%d+)x(%d+);(.+)")
local nextid = mdata:gmatch("(.-);")
self:map(function(x,y,sprid)
return tonumber(nextid())
end)
return self
end
return Map
end
|
local path = select(1,...)
return function(w,h,sheet)
local Map = {}
Map.w, Map.h = w or 24, h or 9
--Initialize the map table
Map.m = {}
for x=1, Map.w do
Map.m[x] = {}
for y=1, Map.h do
Map.m[x][y] = 0
end
end
Map.sheet = sheet
--If called with a function, it will be called on everycell with x,y,sprid args
--The function can return an new sprid to set
--If called with no args, it will return the map table.
function Map:map(func)
if func then
for x=1, self.w do
for y=1, self.h do
self.m[x][y] = func(x,y,self.m[x][y]) or self.m[x][y]
--func(x,y,self.m[x][y])
end
end
end
return self.m
end
function Map:cell(x,y,newID)
if newID then
self.m[x][y] = newID or 0
return self
else
return self.m[x][y]
end
end
function Map:cut(x,y,w,h)
local x,y,w,h = x or 1, y or 1, w or self.w, h or self.h
local nMap = require(path)(w,h)
local m = nMap:map()
for my=1,h do
for mx=1,w do
if self.m[mx+x-1] and self.m[mx+x-1][my+y-1] then
m[mx][my] = self.m[mx+x-1][my+y-1]
end
end
end
return nMap
end
function Map:size() return self.w, self.h end
function Map:width() return self.w end
function Map:height() return self.h end
function Map:draw(dx,dy,x,y,w,h,sx,sy,sheet)
local dx,dy,x,y,w,h,sx,sy = dx or 1, dy or 1, x or 1, y or 1, w or self.w, h or self.h, sx or 1, sy or 1
local cm = self:cut(x,y,w,h)
cm:map(function(spx,spy,sprid)
if sprid < 1 then return end
(self.sheet or sheet):draw(sprid,dx + spx*8*sx - 8*sx, dy + spy*8*sy - 8*sy, 0, sx, sy)
end)
return self
end
function Map:export()
local data = "LK12;TILEMAP;"..self.w.."x"..self.h..";"
self:map(function(x,y,sprid)
data = data..sprid..";"
end)
return data
end
function Map:import(data)
if not data:sub(0,13) == "LK12;TILEMAP;" then error("Wrong header") end
local w,h,mdata = string.match(data,"LK12;TILEMAP;(%d+)x(%d+);(.+)")
local nextid = mdata:gmatch("(.-);")
self:map(function(x,y,sprid)
return 0
end)
for x=1,w do
for y=1,h do
self:cell(x,y,tonumber(nextid()))
end
end
return self
end
return Map
end
|
Bugfix inporting old maps
|
Bugfix inporting old maps
|
Lua
|
mit
|
RamiLego4Game/LIKO-12
|
369a7d3b64a91d6d2bb7e46bd985fca372a94682
|
interface/Tracker/core.lua
|
interface/Tracker/core.lua
|
local targetName = null
local lastSearch = 0
local window = View(GameScreen)
window:setBackgroundColor(0.0, 0.0, 0.0, 0.0)
window:setAnchor1(0.0, 0.0, 0.0, 0.0, 20.0, 20.0)
window:setAnchor2(1.0, 1.0, 0.0, 0.0, 400.0, 40.0)
window:hide()
local textView = TextView(window)
textView:setBackgroundColor(0.0, 0.0, 0.0, 0.5)
textView:setColor(1.0, 1.0, 1.0)
textView:setAnchor1(0.0, 0.0, 0.0, 0.0)
textView:setAnchor2(1.0, 1.0, 1.0, 1.0)
textView:show()
local eventHandler = function(event, arg1)
if event == "LOG_ENTRY" and arg1:sub(9, 12) == "0038" then
local target = arg1:match("!track (%a+ %a+)")
if target then
targetName = target
window:show()
elseif arg1:find("!track") then
targetName = null
window:hide()
else
return
end
end
if not targetName then
return
end
local now = SteadyTime()
if now - lastSearch > 0.5 then
if SearchEntities(targetName) > 0 then
local x, y, z = UnitPosition("player")
local tx, ty, tz = UnitPosition("search")
textView:setText(string.format(" %s located at %.1f, %.1f, %.1f (%+.1f, %+.1f, %+.1f).", targetName, tx, ty, tz, tx - x, ty - y, tz - z))
else
textView:setText(" "..targetName.." not found.")
end
end
end
RegisterEventCallback(eventHandler)
|
local targetName = null
local lastSearch = 0
local window = View(GameScreen)
window:setBackgroundColor(0.0, 0.0, 0.0, 0.0)
window:setAnchor1(0.0, 0.0, 0.0, 0.0, 20.0, 20.0)
window:setAnchor2(1.0, 1.0, 0.0, 0.0, 400.0, 40.0)
window:hide()
local textView = TextView(window)
textView:setBackgroundColor(0.0, 0.0, 0.0, 0.5)
textView:setColor(1.0, 1.0, 1.0)
textView:setAnchor1(0.0, 0.0, 0.0, 0.0)
textView:setAnchor2(1.0, 1.0, 1.0, 1.0)
textView:show()
local eventHandler = function(event, arg1)
if event == "LOG_ENTRY" and arg1:sub(9, 12) == "0038" then
local target = arg1:match("!track (%a+ %a+)") or arg1:match("!track (%a+)")
if target then
targetName = target
window:show()
elseif arg1:find("!track") then
targetName = null
window:hide()
else
return
end
end
if not targetName then
return
end
local now = SteadyTime()
if now - lastSearch > 0.5 then
if SearchEntities(targetName) > 0 then
local x, y, z = UnitPosition("player")
local tx, ty, tz = UnitPosition("search")
textView:setText(string.format(" %s located at %.1f, %.1f, %.1f (%+.1f, %+.1f, %+.1f).", targetName, tx, ty, tz, tx - x, ty - y, tz - z))
else
textView:setText(" "..targetName.." not found.")
end
end
end
RegisterEventCallback(eventHandler)
|
tracker fix
|
tracker fix
|
Lua
|
mit
|
kidaa/xiv-lua,ccbrown/xiv-lua,kidaa/xiv-lua
|
15a64d402a9b52e4b27608f258b1acac8873b292
|
scripts/boot.lua
|
scripts/boot.lua
|
dofile("scripts/adaptIO.lua")
local font = dofile("../font.lua")
local dataH = io.open("../coreFont", "rb")
local data = dataH:read("*a")
dataH:close()
local coreFont = font.new(data)
gpu.font = coreFont
function write(t, x, y, col, target)
t = tostring(t)
col = col or 16
local xoff = 0
for i=1, #t do
local text = t:sub(i, i)
local c = string.byte(text)
if gpu.font.data[c] then
for j=1, 7 do
for k=1, 7 do
if gpu.font.data[c][j][k] then
local dx = x + xoff + k
local dy = y + j
if target then
target:drawPixel(dx, dy, col)
else
gpu.drawPixel(dx, dy, col)
end
end
end
end
end
xoff = xoff + 7
end
end
function sleep(s)
local stime = os.clock()
while true do
coroutine.yield()
local ctime = os.clock()
if ctime - stime >= s then
break
end
end
end
loadfile("../shell.lua")() -- dofile creates a seperate thread, so coroutines get messed up
|
if jit.os == "Linux" or jit.os == "OSX" or jit.os == "BSD" or jit.os == "POSIX" or jit.os == "Other" then
local ffi = require("ffi")
ffi.cdef [[
struct timeval {
long tv_sec;
long tv_usec;
};
struct timezone {
int tz_minuteswest;
int tz_dsttime;
};
int gettimeofday(struct timeval *tv, struct timezone *tz);
]]
local start
do
local a = ffi.new("struct timeval") ffi.C.gettimeofday(a, nil)
start = (tonumber(a.tv_sec) + (tonumber(a.tv_usec) / 1000000))
end
function os.clock()
local Time = ffi.new("struct timeval")
ffi.C.gettimeofday(Time, nil)
return tonumber(Time.tv_sec) + (tonumber(Time.tv_usec) / 1000000) - start;
end
end
dofile("scripts/adaptIO.lua")
local font = dofile("../font.lua")
local dataH = io.open("../coreFont", "rb")
local data = dataH:read("*a")
dataH:close()
local coreFont = font.new(data)
gpu.font = coreFont
function write(t, x, y, col, target)
t = tostring(t)
col = col or 16
local xoff = 0
for i=1, #t do
local text = t:sub(i, i)
local c = string.byte(text)
if gpu.font.data[c] then
for j=1, 7 do
for k=1, 7 do
if gpu.font.data[c][j][k] then
local dx = x + xoff + k
local dy = y + j
if target then
target:drawPixel(dx, dy, col)
else
gpu.drawPixel(dx, dy, col)
end
end
end
end
end
xoff = xoff + 7
end
end
function sleep(s)
local stime = os.clock()
while true do
coroutine.yield()
local ctime = os.clock()
if ctime - stime >= s then
break
end
end
end
loadfile("../shell.lua")() -- dofile creates a seperate thread, so coroutines get messed up
|
Fix os.clock on linux, correcting timings
|
Fix os.clock on linux, correcting timings
|
Lua
|
mit
|
incinirate/Riko4,incinirate/Riko4,incinirate/Riko4
|
fb08ca3caf21967928246cc9c0974b09be185a23
|
src/main/resources/std/math.lua
|
src/main/resources/std/math.lua
|
-- Copyright (c) 2018. tangzx(love.tangzx@qq.com)
--
-- Licensed under the Apache License, Version 2.0 (the "License"); you may not
-- use this file except in compliance with the License. You may obtain a copy of
-- the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-- WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-- License for the specific language governing permissions and limitations under
-- the License.
---@class number
math = {}
---
--- Returns the absolute value of `x`. (integer/float)
---@param x number
---@return number
function math.abs(x) return 0 end
---
--- Returns the arc cosine of `x` (in radians).
---@param x number
---@return number
function math.acos(x) return 0 end
---
--- Returns the arc sine of `x` (in radians).
---@param x number
---@return number
function math.asin(x) return 0 end
---
--- Returns the arc tangent of `y/x` (in radians), but uses the signs of both
--- parameters to find the quadrant of the result. (It also handles correctly
--- the case of `x` being zero.)
---
--- The default value for `x` is 1, so that the call `math.atan(y)`` returns the
--- arc tangent of `y`.
---@param y number
---@param x number
---@return number
function math.atan(y, x) return 0 end
---
--- Returns the smallest integer larger than or equal to `x`.
---@param x number
---@return number
function math.ceil(x) return 0 end
---
--- Returns the cosine of `x` (assumed to be in radians).
---@param x number
---@return number
function math.cos(x) return 0 end
---
--- Converts the angle `x` from radians to degrees.
---@param x number
---@return number
function math.deg(x) return 0 end
---
--- Returns the value *e^x* (where e is the base of natural logarithms).
---@param x number
---@return number
function math.exp(x) end
---
--- Returns the largest integer smaller than or equal to `x`.
---@param x number
---@return number
function math.floor(x) end
---
--- Returns the remainder of the division of `x` by `y` that rounds the
--- quotient towards zero. (integer/float)
---@param x number
---@param y number
---@return number
function math.fmod(x, y) end
---
--- The float value `HUGE_VAL`, a value larger than any other numeric value.
math.huge = ""
---
--- Returns the logarithm of `x` in the given base. The default for `base` is
--- *e* (so that the function returns the natural logarithm of `x`).
---@param x number
---@param base number
---@return number
function math.log(x, base) end
---
--- Returns the argument with the maximum value, according to the Lua operator
--- `<`. (integer/float)
---@param x number
---@return number
function math.max(x, ...) end
---
--- An integer with the maximum value for an integer.
math.maxinteger = ""
---
--- Returns the argument with the minimum value, according to the Lua operator
--- `<`. (integer/float)
---@param x number
---@return number
function math.min(x, ...) end
---
--- An integer with the minimum value for an integer.
math.mininteger = ""
---
--- Returns the integral part of `x` and the fractional part of `x`. Its second
--- result is always a float.
---@param x number
---@return number|number
function math.modf(x) end
---
--- The value of π.
math.pi = 3.1415
---
--- Converts the angle `x` from degrees to radians.
---@param x number
---@return number
function math.rad(x) end
---
--- When called without arguments, returns a pseudo-random float with uniform
--- distribution in the range *[0,1)*. When called with two integers `m` and
--- `n`, `math.random` returns a pseudo-random integer with uniform distribution
--- in the range *[m, n]*. The call `math.random(n)` is equivalent to `math
--- .random`(1,n).
---@overload fun():number
---@param m number
---@param n number
---@return number
function math.random(m, n) end
---
--- Sets `x` as the "seed" for the pseudo-random generator: equal seeds
--- produce equal sequences of numbers.
---@param x number
function math.randomseed(x) end
---
--- Returns the sine of `x` (assumed to be in radians).
---@param x number
---@return number
function math.sin(x) return 0 end
---
--- Returns the square root of `x`. (You can also use the expression `x^0.5` to
--- compute this value.)
---@param x number
---@return number
function math.sqrt(x) return 0 end
---
--- Returns the tangent of `x` (assumed to be in radians).
---@param x number
---@return number
function math.tan(x) return 0 end
---
--- If the value `x` is convertible to an integer, returns that integer.
--- Otherwise, returns `nil`.
---@param x number
---@return number
function math.tointeger(x) end
---
--- Returns "`integer`" if `x` is an integer, "`float`" if it is a float, or
--- **nil** if `x` is not a number.
---@param x number
---@return number
function math.type(x) end
---
--- Returns a boolean, true if and only if integer `m` is below integer `n` when
--- they are compared as unsigned integers.
---@param m number
---@param n number
---@return boolean
function math.ult(m, n) end
return math
|
-- Copyright (c) 2018. tangzx(love.tangzx@qq.com)
--
-- Licensed under the Apache License, Version 2.0 (the "License"); you may not
-- use this file except in compliance with the License. You may obtain a copy of
-- the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-- WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-- License for the specific language governing permissions and limitations under
-- the License.
---@class number
math = {}
---
--- Returns the absolute value of `x`. (integer/float)
---@param x number
---@return number
function math.abs(x) return 0 end
---
--- Returns the arc cosine of `x` (in radians).
---@param x number
---@return number
function math.acos(x) return 0 end
---
--- Returns the arc sine of `x` (in radians).
---@param x number
---@return number
function math.asin(x) return 0 end
---
--- Returns the arc tangent of `y/x` (in radians), but uses the signs of both
--- parameters to find the quadrant of the result. (It also handles correctly
--- the case of `x` being zero.)
---
--- The default value for `x` is 1, so that the call `math.atan(y)`` returns the
--- arc tangent of `y`.
---@param y number
---@param optional x number
---@return number
function math.atan(y, x) return 0 end
---
--- Returns the smallest integer larger than or equal to `x`.
---@param x number
---@return number
function math.ceil(x) return 0 end
---
--- Returns the cosine of `x` (assumed to be in radians).
---@param x number
---@return number
function math.cos(x) return 0 end
---
--- Converts the angle `x` from radians to degrees.
---@param x number
---@return number
function math.deg(x) return 0 end
---
--- Returns the value *e^x* (where e is the base of natural logarithms).
---@param x number
---@return number
function math.exp(x) end
---
--- Returns the largest integer smaller than or equal to `x`.
---@param x number
---@return number
function math.floor(x) end
---
--- Returns the remainder of the division of `x` by `y` that rounds the
--- quotient towards zero. (integer/float)
---@param x number
---@param y number
---@return number
function math.fmod(x, y) end
---
--- The float value `HUGE_VAL`, a value larger than any other numeric value.
math.huge = ""
---
--- Returns the logarithm of `x` in the given base. The default for `base` is
--- *e* (so that the function returns the natural logarithm of `x`).
---@param x number
---@param optional base number
---@return number
function math.log(x, base) end
---
--- Returns the argument with the maximum value, according to the Lua operator
--- `<`. (integer/float)
---@param x number
---@return number
function math.max(x, ...) end
---
--- An integer with the maximum value for an integer.
math.maxinteger = ""
---
--- Returns the argument with the minimum value, according to the Lua operator
--- `<`. (integer/float)
---@param x number
---@return number
function math.min(x, ...) end
---
--- An integer with the minimum value for an integer.
math.mininteger = ""
---
--- Returns the integral part of `x` and the fractional part of `x`. Its second
--- result is always a float.
---@param x number
---@return number|number
function math.modf(x) end
---
--- The value of π.
math.pi = 3.1415
---
--- Converts the angle `x` from degrees to radians.
---@param x number
---@return number
function math.rad(x) end
---
--- When called without arguments, returns a pseudo-random float with uniform
--- distribution in the range *[0,1)*. When called with two integers `m` and
--- `n`, `math.random` returns a pseudo-random integer with uniform distribution
--- in the range *[m, n]*. The call `math.random(n)` is equivalent to `math
--- .random`(1,n).
---@overload fun():number
---@param optional m number
---@param optional n number
---@return number
function math.random(m, n) end
---
--- Sets `x` as the "seed" for the pseudo-random generator: equal seeds
--- produce equal sequences of numbers.
---@param x number
function math.randomseed(x) end
---
--- Returns the sine of `x` (assumed to be in radians).
---@param x number
---@return number
function math.sin(x) return 0 end
---
--- Returns the square root of `x`. (You can also use the expression `x^0.5` to
--- compute this value.)
---@param x number
---@return number
function math.sqrt(x) return 0 end
---
--- Returns the tangent of `x` (assumed to be in radians).
---@param x number
---@return number
function math.tan(x) return 0 end
---
--- If the value `x` is convertible to an integer, returns that integer.
--- Otherwise, returns `nil`.
---@param x number
---@return number
function math.tointeger(x) end
---
--- Returns "`integer`" if `x` is an integer, "`float`" if it is a float, or
--- **nil** if `x` is not a number.
---@param x number
---@return number
function math.type(x) end
---
--- Returns a boolean, true if and only if integer `m` is below integer `n` when
--- they are compared as unsigned integers.
---@param m number
---@param n number
---@return boolean
function math.ult(m, n) end
return math
|
fix params, return types and doc
|
fix params, return types and doc
Check params and return types for rightness.
|
Lua
|
apache-2.0
|
EmmyLua/IntelliJ-EmmyLua,tangzx/IntelliJ-EmmyLua,EmmyLua/IntelliJ-EmmyLua,EmmyLua/IntelliJ-EmmyLua,tangzx/IntelliJ-EmmyLua,tangzx/IntelliJ-EmmyLua,EmmyLua/IntelliJ-EmmyLua,tangzx/IntelliJ-EmmyLua
|
f23993da14f0ae858d5a6a25fec227f4bbc45c45
|
spec/check_spec.lua
|
spec/check_spec.lua
|
local check = require "luacheck.check"
local luacompiler = require "metalua.compiler"
local luaparser = luacompiler.new()
local function get_report(source, options)
local ast = assert(luaparser:src_to_ast(source))
return check(ast, options)
end
describe("test luacheck.check", function()
it("does not find anything wrong in an empty block", function()
assert.same({}, get_report(""))
end)
it("does not find anything wrong in used locals", function()
assert.same({}, get_report[[
local a
local b = 5
do
print(b, {a})
end
]])
end)
it("detects global access", function()
assert.same({
{type = "global", subtype = "set", name = "foo", line = 1, column = 1}
}, get_report[[
foo = {}
]])
end)
it("doesn't detect global access when not asked to", function()
assert.same({}, get_report([[
foo()
]], {global = false}))
end)
it("detects global access in self swap", function()
assert.same({
{type = "global", subtype = "access", name = "a", line = 1, column = 11}
}, get_report[[
local a = a
print(a)
]])
end)
it("uses custom globals", function()
assert.same({}, get_report([[
foo()
]], {globals = {"foo"}}))
end)
it("is _ENV-aware", function()
assert.same({}, get_report[[
print(_ENV)
local _ENV = {}
do
x = 4
end
]])
end)
it("can detect unused _ENV", function()
assert.same({
{type = "unused", subtype = "var", name = "_ENV", line = 3, column = 7}
}, get_report[[
print(_ENV)
local _ENV = {}
do
-- something
end
]])
end)
it("correctly checks if _ENV is unused with check_global == false", function()
assert.same({}, get_report([[
print(_ENV)
local _ENV = {}
do
x = 4
end
]], {global = false}))
end)
it("can be not _ENV-aware", function()
assert.same({
{type = "global", subtype = "access", name = "_ENV", line = 1, column = 7},
{type = "unused", subtype = "var", name = "_ENV", line = 3, column = 7},
{type = "global", subtype = "set", name = "x", line = 5, column = 4}
}, get_report([[
print(_ENV)
local _ENV = {}
do
x = 4
end
]], {env_aware = false}))
end)
it("detects unused locals", function()
assert.same({
{type = "unused", subtype = "var", name = "a", line = 1, column = 7}
}, get_report[[
local a = 4
do
local a = 6
print(a)
end
]])
end)
it("detects unused locals from function arguments", function()
assert.same({
{type = "unused", subtype = "arg", name = "foo", line = 1, column = 17}
}, get_report[[
return function(foo, ...)
return ...
end
]])
end)
it("detects unused implicit self", function()
assert.same({
{type = "unused", subtype = "arg", name = "self", line = 2, column = 13}
}, get_report[[
local a = {}
function a:b()
end
]])
end)
it("detects unused locals from loops", function()
assert.same({
{type = "unused", subtype = "loop", name = "i", line = 1, column = 5},
{type = "unused", subtype = "loop", name = "i", line = 2, column = 5}
}, get_report[[
for i=1, 2 do end
for i in pairs{} do end
]])
end)
it("detects unused values", function()
assert.same({
{type = "unused_value", subtype = "var", name = "a", line = 5, column = 4}
}, get_report[[
local a
if true then
a = 2
else
a = 3
end
a = 5
print(a)
]])
end)
it("does not detect unused values in loops", function()
assert.same({}, get_report[[
local a = 10
while a > 0 do
print(a)
a = math.floor(a/2)
end
]])
end)
it("allows `_` to be unused", function()
assert.same({}, get_report[[
for _, foo in pairs{} do
print(foo)
end
]])
end)
it("allows `_` to be redefined", function()
assert.same({}, get_report[[
for _, foo in pairs{} do
local _ = print(foo)
end
]])
end)
it("doesn't detect unused variables when not asked to", function()
assert.same({}, get_report([[
local foo
]], {unused = false}))
end)
it("doesn't detect unused arguments when not asked to", function()
assert.same({
{type = "unused", subtype = "var", name = "c", line = 4, column = 13}
}, get_report([[
local a = {}
function a:b()
for i=1, 5 do
local c
end
end
]], {unused_args = false}))
end)
it("detects redefinition in the same scope", function()
assert.same({
{type = "unused", subtype = "var", name = "foo", line = 1, column = 7},
{type = "redefined", subtype = "var", name = "foo", line = 2, column = 7, prev_line = 1, prev_column = 7}
}, get_report[[
local foo
local foo = "bar"
print(foo)
]])
end)
it("detects redefinition of function arguments", function()
assert.same({
{type = "unused", subtype = "arg", name = "foo", line = 1, column = 17},
{type = "unused", subtype = "vararg", name = "...", line = 1, column = 22},
{type = "redefined", subtype = "arg", name = "foo", line = 2, column = 10, prev_line = 1, prev_column = 17}
}, get_report[[
return function(foo, ...)
local foo
return foo
end
]])
end)
it("doesn't detect redefenition when not asked to", function()
assert.same({}, get_report([[
local foo; local foo; print(foo)
]], {redefined = false, unused = false}))
end)
it("detects unused redefined variables", function()
assert.same({
{type = "unused", subtype = "var", name = "a", line = 1, column = 7}
}, get_report([[
local a
local a = 5; print(a)
]], {redefined = false}))
end)
it("handles argparse sample", function()
assert.same({
{type = "unused", subtype = "loop", name = "setter", line = 34, column = 27},
{type = "unused", subtype = "arg", name = "self", line = 117, column = 27},
{type = "unused", subtype = "arg", name = "self", line = 125, column = 27},
{type = "unused", subtype = "arg", name = "parser", line = 957, column = 41}
}, get_report(io.open("spec/samples/argparse.lua", "rb"):read("*a")))
end)
end)
|
local check = require "luacheck.check"
local luacompiler = require "metalua.compiler"
local luaparser = luacompiler.new()
local function get_report(source, options)
local ast = assert(luaparser:src_to_ast(source))
return check(ast, options)
end
describe("test luacheck.check", function()
it("does not find anything wrong in an empty block", function()
assert.same({}, get_report(""))
end)
it("does not find anything wrong in used locals", function()
assert.same({}, get_report[[
local a
local b = 5
do
print(b, {a})
end
]])
end)
it("detects global access", function()
assert.same({
{type = "global", subtype = "set", name = "foo", line = 1, column = 1}
}, get_report[[
foo = {}
]])
end)
it("doesn't detect global access when not asked to", function()
assert.same({}, get_report([[
foo()
]], {global = false}))
end)
it("detects global access in self swap", function()
assert.same({
{type = "global", subtype = "access", name = "a", line = 1, column = 11}
}, get_report[[
local a = a
print(a)
]])
end)
it("uses custom globals", function()
assert.same({}, get_report([[
foo()
]], {globals = {"foo"}}))
end)
it("is _ENV-aware", function()
assert.same({}, get_report[[
print(_ENV)
local _ENV = {}
do
x = 4
end
]])
end)
it("can detect unused _ENV", function()
assert.same({
{type = "unused", subtype = "var", name = "_ENV", line = 3, column = 7}
}, get_report[[
print(_ENV)
local _ENV = {}
do
-- something
end
]])
end)
it("correctly checks if _ENV is unused with check_global == false", function()
assert.same({}, get_report([[
print(_ENV)
local _ENV = {}
do
x = 4
end
]], {global = false}))
end)
it("can be not _ENV-aware", function()
assert.same({
{type = "global", subtype = "access", name = "_ENV", line = 1, column = 7},
{type = "unused", subtype = "var", name = "_ENV", line = 3, column = 7},
{type = "global", subtype = "set", name = "x", line = 5, column = 4}
}, get_report([[
print(_ENV)
local _ENV = {}
do
x = 4
end
]], {env_aware = false}))
end)
it("detects unused locals", function()
assert.same({
{type = "unused", subtype = "var", name = "a", line = 1, column = 7}
}, get_report[[
local a = 4
do
local a = 6
print(a)
end
]])
end)
it("detects unused locals from function arguments", function()
assert.same({
{type = "unused", subtype = "arg", name = "foo", line = 1, column = 17}
}, get_report[[
return function(foo, ...)
return ...
end
]])
end)
it("detects unused implicit self", function()
assert.same({
{type = "unused", subtype = "arg", name = "self", line = 2, column = 13}
}, get_report[[
local a = {}
function a:b()
end
]])
end)
it("detects unused locals from loops", function()
assert.same({
{type = "unused", subtype = "loop", name = "i", line = 1, column = 5},
{type = "unused", subtype = "loop", name = "i", line = 2, column = 5}
}, get_report[[
for i=1, 2 do end
for i in pairs{} do end
]])
end)
it("detects unused values", function()
assert.same({
{type = "unused_value", subtype = "var", name = "a", line = 5, column = 4}
}, get_report[[
local a
if true then
a = 2
else
a = 3
end
a = 5
print(a)
]])
end)
it("does not detect unused values in loops", function()
assert.same({}, get_report[[
local a = 10
while a > 0 do
print(a)
a = math.floor(a/2)
end
]])
end)
it("allows `_` to be unused", function()
assert.same({}, get_report[[
for _, foo in pairs{} do
print(foo)
end
]])
end)
it("allows `_` to be redefined", function()
assert.same({}, get_report[[
for _, foo in pairs{} do
local _ = print(foo)
end
]])
end)
it("doesn't detect unused variables when not asked to", function()
assert.same({}, get_report([[
local foo
]], {unused = false}))
end)
it("doesn't detect unused arguments when not asked to", function()
assert.same({
{type = "unused", subtype = "var", name = "c", line = 4, column = 13}
}, get_report([[
local a = {}
function a:b()
for i=1, 5 do
local c
end
end
]], {unused_args = false}))
end)
it("detects redefinition in the same scope", function()
assert.same({
{type = "unused", subtype = "var", name = "foo", line = 1, column = 7},
{type = "redefined", subtype = "var", name = "foo", line = 2, column = 7, prev_line = 1, prev_column = 7}
}, get_report[[
local foo
local foo = "bar"
print(foo)
]])
end)
it("detects redefinition of function arguments", function()
assert.same({
{type = "unused", subtype = "arg", name = "foo", line = 1, column = 17},
{type = "unused", subtype = "vararg", name = "...", line = 1, column = 22},
{type = "redefined", subtype = "arg", name = "foo", line = 2, column = 10, prev_line = 1, prev_column = 17}
}, get_report[[
return function(foo, ...)
local foo
return foo
end
]])
end)
it("doesn't detect redefenition when not asked to", function()
assert.same({}, get_report([[
local foo; local foo; print(foo)
]], {redefined = false, unused = false}))
end)
it("detects unused redefined variables", function()
assert.same({
{type = "unused", subtype = "var", name = "a", line = 1, column = 7}
}, get_report([[
local a
local a = 5; print(a)
]], {redefined = false}))
end)
it("handles argparse sample", function()
assert.same({
{type = "unused", subtype = "loop", name = "setter", line = 34, column = 27},
{type = "unused", subtype = "arg", name = "self", line = 117, column = 27},
{type = "unused", subtype = "arg", name = "self", line = 125, column = 27},
{type = "global", subtype = "access", name = "_TEST", line = 942, column = 7},
{type = "unused", subtype = "arg", name = "parser", line = 957, column = 41}
}, get_report(io.open("spec/samples/argparse.lua", "rb"):read("*a")))
end)
end)
|
Fixed spec to work with busted 2.0
|
Fixed spec to work with busted 2.0
|
Lua
|
mit
|
mpeterv/luacheck,mpeterv/luacheck,xpol/luacheck,adan830/luacheck,tst2005/luacheck,linuxmaniac/luacheck,tst2005/luacheck,xpol/luacheck,kidaa/luacheck,linuxmaniac/luacheck,xpol/luacheck,adan830/luacheck,kidaa/luacheck,mpeterv/luacheck
|
ca1e85fd56d3db8c1f19fd4f828c89684ff8da3c
|
packages/bidi.lua
|
packages/bidi.lua
|
SILE.registerCommand("thisframeLTR", function(options, content)
SILE.typesetter.frame.direction = "LTR"
SILE.typesetter:leaveHmode()
SILE.typesetter.frame:newLine()
end);
SILE.registerCommand("thisframedirection", function(options, content)
SILE.typesetter.frame.direction = SU.required(options, "direction", "frame direction")
SILE.typesetter:leaveHmode()
SILE.typesetter.frame:init()
end);
SILE.registerCommand("thisframeRTL", function(options, content)
SILE.typesetter.frame.direction = "RTL"
SILE.typesetter:leaveHmode()
SILE.typesetter.frame:newLine()
end);
local bidi = require("unicode-bidi-algorithm")
require("char-def")
local chardata = characters.data
local reorder = function(n, self)
local nl = n.nodes
local newNl = {}
local matrix = {}
local levels = {}
local base_level = self.frame:writingDirection() == "RTL" and 1 or 0
local prev_level = base_level
for i=1,#nl do
if nl[i].options and nl[i].options.bidilevel then
levels[i] = { level = nl[i].options.bidilevel }
end
end
for i=1,#nl do if not levels[i] then
-- resolve neutrals
local left_level, right_level, left, right
for left = i-1,1,-1 do if nl[left].options and nl[left].options.bidilevel then
left_level = nl[left].options.bidilevel
break
end end
for right = i+1,#nl do if nl[right].options and nl[right].options.bidilevel then
right_level = nl[right].options.bidilevel
break
end end
levels[i] = { level = (left_level == right_level and left_level or base_level) }
end end
local matrix = bidi.create_matrix(levels,base_level)
local rv = {}
local reverse_array = function (t)
local n = {}
for i =1,#t do n[#t-i+1] = t[i] end
for i =1,#t do t[i] = n[i] end
end
for i = 1, #nl do
if nl[i]:isNnode() and levels[i].level %2 == 1 then
reverse_array(nl[i].nodes)
for j =1,#(nl[i].nodes) do
if nl[i].nodes[j].type =="hbox" then
if nl[i].nodes[j].value.items then reverse_array(nl[i].nodes[j].value.items) end
reverse_array(nl[i].nodes[j].value.glyphString)
end
end
end
rv[matrix[i]] = nl[i]
-- rv[i] = nl[i]
end
n.nodes = rv
end
local nodeListToText = function (nl)
local owners, text = {}, {}
local p = 1
for i = 1,#nl do local n = nl[i]
if n.text then
local utfchars = SU.splitUtf8(n.text)
for j = 1,#utfchars do
owners[p] = { node = n, pos = j }
text[p] = utfchars[j]
p = p + 1
end
else
owners[p] = { node = n }
text[p] = SU.utf8char(0xFFFC)
p = p + 1
end
end
return owners, text
end
local splitNodeAtPos = function (n,splitstart, p)
if n:isUnshaped() then
local utf8chars = SU.splitUtf8(n.text)
local n2 = SILE.nodefactory.newUnshaped({ text = "", options = table.clone(n.options) })
local n1 = SILE.nodefactory.newUnshaped({ text = "", options = table.clone(n.options) })
for i = splitstart,#utf8chars do
if i < p then n1.text = n1.text .. utf8chars[i]
else n2.text = n2.text .. utf8chars[i]
end
end
return n1,n2
else
SU.error("Unsure how to split node "..n.." at position p",1)
end
end
local splitNodelistIntoBidiRuns = function (self)
local nl = self.state.nodes
if #nl == 0 then return nl end
local owners, text = nodeListToText(nl)
local levels = bidi.process(text, self.frame,true)
local base_direction = "LTR"
local flipped_direction = "RTL"
local base_level = self.frame:writingDirection() == "RTL" and 1 or 0
local lastlevel = base_level
local nl = {}
local lastowner
local splitstart = 1
for i = 1,#levels do
if levels[i] % 2 ~= lastlevel % 2 and owners[i].node == lastowner then
owners[i].bidilevel = levels[i]
local before,after = splitNodeAtPos(owners[i].node,splitstart,owners[i].pos)
nl[#nl] = before
nl[#nl+1] = after
lastowner = owners[i].node
splitstart = owners[i].pos
before.options.bidilevel = lastlevel
after.options.direction = (levels[i] %2) == 0 and base_direction or flipped_direction
after.options.bidilevel = levels[i]
before.options.direction = (levels[i-1] %2) == 0 and base_direction or flipped_direction
-- assign direction for both nodes
else
if owners[i].node ~= lastowner then
nl[#nl+1] = owners[i].node
splitstart = 1
if nl[#nl].options then
nl[#nl].options.direction = (levels[i] %2) == 0 and base_direction or flipped_direction
end
end
lastowner = owners[i].node
if nl[#nl].options then nl[#nl].options.bidilevel = (levels[i]) end
end
lastlevel = levels[i]
end
return nl
end
local bidiBoxupNodes = function (self)
local newNodeList = splitNodelistIntoBidiRuns(self)
self:shapeAllNodes(newNodeList)
self.state.nodes = newNodeList
local vboxlist = SILE.defaultTypesetter.boxUpNodes(self)
-- Scan for out-of-direction material
for i=1,#vboxlist do local v = vboxlist[i]
if v:isVbox() then reorder(v, self) end
end
return vboxlist
end
SILE.typesetter.boxUpNodes = bidiBoxupNodes
SILE.registerCommand("bidi-on", function(options, content)
SILE.typesetter.boxUpNodes = bidiBoxupNodes
end)
SILE.registerCommand("bidi-off", function(options, content)
SILE.typesetter.boxUpNodes = SILE.defaultTypesetter.boxUpNodes
end)
return {
reorder = reorder,
documentation = [[\begin{document}
Scripts like the Latin alphabet you are currently reading are normally written left to
right; however, some scripts, such as Arabic and Hebrew, are written right to left.
The \code{bidi} package, which is loaded by default, provides SILE with the ability to
correctly typeset right-to-left text and also documents which mix right-to-left and
left-to-right typesetting. Because it is loaded by default, you can use both
LTR and RTL text within a paragraph and SILE will ensure that the output
characters appear in the correct order.
The \code{bidi} package provides two commands, \command{\\thisframeLTR} and
\command{\\thisframeRTL}, which set the default text direction for the current frame.
That is, if you tell SILE that a frame is RTL, the text will start in the right margin
and proceed leftward. It also provides the commands \command{\\bidi-off} and
\command{\\bidi-on}, which allow you to trade off bidirectional support for a dubious
increase in speed.
\end{document}]] }
|
SILE.registerCommand("thisframeLTR", function(options, content)
SILE.typesetter.frame.direction = "LTR"
SILE.typesetter:leaveHmode()
SILE.typesetter.frame:newLine()
end);
SILE.registerCommand("thisframedirection", function(options, content)
SILE.typesetter.frame.direction = SU.required(options, "direction", "frame direction")
SILE.typesetter:leaveHmode()
SILE.typesetter.frame:init()
end);
SILE.registerCommand("thisframeRTL", function(options, content)
SILE.typesetter.frame.direction = "RTL"
SILE.typesetter:leaveHmode()
SILE.typesetter.frame:newLine()
end);
local bidi = require("unicode-bidi-algorithm")
require("char-def")
local chardata = characters.data
local reorder = function(n, self)
local nl = n.nodes
local newNl = {}
local matrix = {}
local levels = {}
local base_level = self.frame:writingDirection() == "RTL" and 1 or 0
local prev_level = base_level
for i=1,#nl do
if nl[i].options and nl[i].options.bidilevel then
levels[i] = { level = nl[i].options.bidilevel }
end
end
for i=1,#nl do if not levels[i] then
-- resolve neutrals
local left_level, right_level, left, right
for left = i-1,1,-1 do if nl[left].options and nl[left].options.bidilevel then
left_level = nl[left].options.bidilevel
break
end end
for right = i+1,#nl do if nl[right].options and nl[right].options.bidilevel then
right_level = nl[right].options.bidilevel
break
end end
levels[i] = { level = (left_level == right_level and left_level or base_level) }
end end
local matrix = bidi.create_matrix(levels,base_level)
local rv = {}
local reverse_array = function (t)
local n = {}
for i =1,#t do n[#t-i+1] = t[i] end
for i =1,#t do t[i] = n[i] end
end
for i = 1, #nl do
if nl[i]:isNnode() and levels[i].level %2 == 1 then
reverse_array(nl[i].nodes)
for j =1,#(nl[i].nodes) do
if nl[i].nodes[j].type =="hbox" then
if nl[i].nodes[j].value.items then reverse_array(nl[i].nodes[j].value.items) end
reverse_array(nl[i].nodes[j].value.glyphString)
end
end
end
rv[matrix[i]] = nl[i]
nl[i].bidiDone = true
-- rv[i] = nl[i]
end
n.nodes = rv
end
local nodeListToText = function (nl)
local owners, text = {}, {}
local p = 1
for i = 1,#nl do local n = nl[i]
if n.text then
local utfchars = SU.splitUtf8(n.text)
for j = 1,#utfchars do
owners[p] = { node = n, pos = j }
text[p] = utfchars[j]
p = p + 1
end
else
owners[p] = { node = n }
text[p] = SU.utf8char(0xFFFC)
p = p + 1
end
end
return owners, text
end
local splitNodeAtPos = function (n,splitstart, p)
if n:isUnshaped() then
local utf8chars = SU.splitUtf8(n.text)
local n2 = SILE.nodefactory.newUnshaped({ text = "", options = table.clone(n.options) })
local n1 = SILE.nodefactory.newUnshaped({ text = "", options = table.clone(n.options) })
for i = splitstart,#utf8chars do
if i < p then n1.text = n1.text .. utf8chars[i]
else n2.text = n2.text .. utf8chars[i]
end
end
return n1,n2
else
SU.error("Unsure how to split node "..n.." at position p",1)
end
end
local splitNodelistIntoBidiRuns = function (self)
local nl = self.state.nodes
if #nl == 0 then return nl end
local owners, text = nodeListToText(nl)
local levels = bidi.process(text, self.frame,true)
local base_direction = "LTR"
local flipped_direction = "RTL"
local base_level = self.frame:writingDirection() == "RTL" and 1 or 0
local lastlevel = base_level
local nl = {}
local lastowner
local splitstart = 1
for i = 1,#levels do
if levels[i] % 2 ~= lastlevel % 2 and owners[i].node == lastowner then
owners[i].bidilevel = levels[i]
local before,after = splitNodeAtPos(owners[i].node,splitstart,owners[i].pos)
nl[#nl] = before
nl[#nl+1] = after
lastowner = owners[i].node
splitstart = owners[i].pos
before.options.bidilevel = lastlevel
after.options.direction = (levels[i] %2) == 0 and base_direction or flipped_direction
after.options.bidilevel = levels[i]
before.options.direction = (levels[i-1] %2) == 0 and base_direction or flipped_direction
-- assign direction for both nodes
else
if owners[i].node ~= lastowner then
nl[#nl+1] = owners[i].node
splitstart = 1
if nl[#nl].options then
nl[#nl].options.direction = (levels[i] %2) == 0 and base_direction or flipped_direction
end
end
lastowner = owners[i].node
if nl[#nl].options then nl[#nl].options.bidilevel = (levels[i]) end
end
lastlevel = levels[i]
end
return nl
end
local bidiBoxupNodes = function (self)
local allDone = true
for i=1,#self.state.nodes do
if not self.state.nodes[i].bidiDone then allDone = false end
end
if allDone then return SILE.defaultTypesetter.boxUpNodes(self) end
local newNodeList = splitNodelistIntoBidiRuns(self)
self:shapeAllNodes(newNodeList)
self.state.nodes = newNodeList
local vboxlist = SILE.defaultTypesetter.boxUpNodes(self)
-- Scan for out-of-direction material
for i=1,#vboxlist do local v = vboxlist[i]
if v:isVbox() then reorder(v, self) end
end
return vboxlist
end
SILE.typesetter.boxUpNodes = bidiBoxupNodes
SILE.registerCommand("bidi-on", function(options, content)
SILE.typesetter.boxUpNodes = bidiBoxupNodes
end)
SILE.registerCommand("bidi-off", function(options, content)
SILE.typesetter.boxUpNodes = SILE.defaultTypesetter.boxUpNodes
end)
return {
reorder = reorder,
documentation = [[\begin{document}
Scripts like the Latin alphabet you are currently reading are normally written left to
right; however, some scripts, such as Arabic and Hebrew, are written right to left.
The \code{bidi} package, which is loaded by default, provides SILE with the ability to
correctly typeset right-to-left text and also documents which mix right-to-left and
left-to-right typesetting. Because it is loaded by default, you can use both
LTR and RTL text within a paragraph and SILE will ensure that the output
characters appear in the correct order.
The \code{bidi} package provides two commands, \command{\\thisframeLTR} and
\command{\\thisframeRTL}, which set the default text direction for the current frame.
That is, if you tell SILE that a frame is RTL, the text will start in the right margin
and proceed leftward. It also provides the commands \command{\\bidi-off} and
\command{\\bidi-on}, which allow you to trade off bidirectional support for a dubious
increase in speed.
\end{document}]] }
|
A stupid but possibly workable fix to #192.
|
A stupid but possibly workable fix to #192.
|
Lua
|
mit
|
neofob/sile,simoncozens/sile,alerque/sile,neofob/sile,alerque/sile,neofob/sile,simoncozens/sile,neofob/sile,alerque/sile,simoncozens/sile,alerque/sile,simoncozens/sile
|
f91bb8f9c6d5f1375c1ced9e0bda6abf0acff6f3
|
sloongnet/scripts/main.lua
|
sloongnet/scripts/main.lua
|
-- When message is recved, the fm will call this function.
require_ex('ex');
local main_Req = {};
main_Req.ReloadScript = function( u, req, res )
ReloadScript();
return 0;
end
main_Req.SqlTest = function( u, req, res )
local cmd = req['cmd'] or '';
local res = QuerySQL(cmd);
return 0,res;
end
main_Req.TextTest = function( u, req, res )
res['TestText'] = GetEngineVer() .. ' -- Sloong Network Engine -- Copyright 2015 Sloong.com. All Rights Reserved';
return 0
end
-- 上传文件流程
-- 客户端准备要上传的文件信息,包括style 和 文件的md5,以及扩展名
-- 服务端检查md5信息,并根据检查结果,返回是否需要上传.如无需上传则直接秒传并保存文件记录
-- 如需要上传,则构建一个uuid, 将路径改为uploadurl/user/uuid+扩展名的格式返回.
-- 客户端根据返回,将需要上传的文件传至指定目录.
-- 客户端发送UploadEnd消息,并附带参数为目标路径
--
--
-- 服务端按照年/月/日/uuid的结构来存储文件
-- get the total for the file need upload
-- then check the all file md5, if file is have one server,
-- then gen the new guid and create the folder with the guid name.
-- return the path with guid.
-- then client upload the file to the folder,
function main_Req.UploadStart(u, req, res)
res['ftpuser']=Get('FTP','User','');
res['ftppwd']=Get('FTP','Password','');
showLog(res['filename'])
res['filename']=req['filename'];
res['fullname']=req['fullname'];
local baseUrl = Get('FTP','UploadUrl','')
res['ftpurl']=baseUrl
-- get guid from c++
--GetGUID()
local uuid = GenUUID();
res['uuid']=uuid;
-- Return a floder path.
local path = uuid .. '/';
res['filepath']=path;
res['UploadURL'] = path;
return 0;
end
function main_Req.UploadEnd( u, req, res )
local folder = Get('FTP','UploadFolder','')
local path = folder .. req['UploadURL'] .. req['filename'];
local newPath = folder .. os.date('%Y%m%d') .. '/' .. req['filename'];
local errmsg ,errcode = MoveFile(path,newPath);
return errcode, errmsg;
end
g_all_request_processer =
{
['Reload'] = main_Req.ReloadScript,
['GetText'] = main_Req.TextTest,
['RunSql'] = main_Req.SqlTest,
['UploadStart'] = main_Req.UploadStart,
['UploadEnd'] = main_Req.UploadEnd,
}
AddModule(g_ex_function);
|
-- When message is recved, the fm will call this function.
require_ex('ex');
local main_Req = {};
main_Req.ReloadScript = function( u, req, res )
ReloadScript();
return 0;
end
main_Req.SqlTest = function( u, req, res )
local cmd = req['cmd'] or '';
local res = QuerySQL(cmd);
return 0,res;
end
main_Req.TextTest = function( u, req, res )
res['TestText'] = GetEngineVer() .. ' -- Sloong Network Engine -- Copyright 2015 Sloong.com. All Rights Reserved';
return 0
end
-- 上传文件流程
-- 客户端准备要上传的文件信息,包括style 和 文件的md5,以及扩展名
-- 服务端检查md5信息,并根据检查结果,返回是否需要上传.如无需上传则直接秒传并保存文件记录
-- 如需要上传,则构建一个uuid, 将路径改为uploadurl/user/uuid+扩展名的格式返回.
-- 客户端根据返回,将需要上传的文件传至指定目录.
-- 客户端发送UploadEnd消息,并附带参数为目标路径
--
--
-- 服务端按照年/月/日/uuid的结构来存储文件
-- get the total for the file need upload
-- then check the all file md5, if file is have one server,
-- then gen the new guid and create the folder with the guid name.
-- return the path with guid.
-- then client upload the file to the folder,
function main_Req.UploadStart(u, req, res)
res['ftpuser']=Get('FTP','User','');
res['ftppwd']=Get('FTP','Password','');
showLog(res['filename'])
res['filename']=req['filename'];
res['fullname']=req['fullname'];
local baseUrl = Get('FTP','UploadUrl','')
res['ftpurl']=baseUrl
-- get guid from c++
--GetGUID()
local uuid = GenUUID();
res['uuid']=uuid;
-- Return a floder path.
local path = uuid .. '/';
res['filepath']=path;
res['UploadURL'] = path;
return 0;
end
function main_Req.UploadEnd( u, req, res )
local folder = Get('FTP','UploadFolder','')
local path = folder .. req['UploadURL'] .. req['filename'];
local newPath = folder .. os.date('%Y%m%d') .. '/' .. req['filename'];
local errmsg ,errcode = MoveFile(path,newPath);
return errcode, errmsg;
end
function main_Req.GetIP( u, req, res )
res['IPInfo'] = u:getdata('ip') .. ':' .. u:getdata('port')
return 0;
end
g_all_request_processer =
{
['Reload'] = main_Req.ReloadScript,
['GetText'] = main_Req.TextTest,
['RunSql'] = main_Req.SqlTest,
['UploadStart'] = main_Req.UploadStart,
['UploadEnd'] = main_Req.UploadEnd,
['GetIP'] = main_Req.GetIP,
}
AddModule(g_ex_function);
|
Fix #15
|
Fix #15
|
Lua
|
mit
|
sloong/sloongnet,sloong/sloongnet,sloong/sloongnet,sloong/sloongnet,sloong/sloongnet
|
26afcec76912f88cc25bbeb70a6cc8850d999516
|
core/text-output.lua
|
core/text-output.lua
|
if (not SILE.outputters) then SILE.outputters = {} end
local outfile
local cursorX = 0
local cursorY = 0
local hboxCount = 0
local writeline = function (...)
local args = table.pack(...)
if hboxCount >= 1 then outfile:write(" ") end
for i=1, #args do
outfile:write(args[i])
if i < #args then outfile:write(" ") end
hboxCount = hboxCount + 1
end
end
SILE.outputters.text = {
init = function()
outfile = io.open(SILE.outputFilename, "w+")
end,
newPage = function()
outfile:write("")
end,
finish = function()
outfile:close()
end,
setColor = function() end,
pushColor = function () end,
popColor = function () end,
outputHbox = function (value)
writeline(value.text)
end,
setFont = function () end,
drawImage = function () end,
imageSize = function () end,
moveTo = function (x, y)
if y > cursorY or x <= cursorX then
outfile:write("\n")
hboxCount = 0
end
cursorY = y
cursorX = x
end,
rule = function () end,
debugFrame = function (_) end,
debugHbox = function() end
}
SILE.outputter = SILE.outputters.text
if not SILE.outputFilename and SILE.masterFilename then
SILE.outputFilename = SILE.masterFilename..".txt"
end
|
if (not SILE.outputters) then SILE.outputters = {} end
local outfile
local cursorX = 0
local cursorY = 0
local started = false
local writeline = function (...)
local args = table.pack(...)
for i=1, #args do
outfile:write(args[i])
end
end
SILE.outputters.text = {
init = function()
outfile = io.open(SILE.outputFilename, "w+")
end,
newPage = function()
outfile:write("")
end,
finish = function()
outfile:close()
end,
setColor = function() end,
pushColor = function () end,
popColor = function () end,
outputHbox = function (value, width)
width = SU.cast("number", width)
if width > 0 then
writeline(value.text)
started = true
cursorX = cursorX + width
end
end,
setFont = function () end,
drawImage = function () end,
imageSize = function () end,
moveTo = function (x, y)
if started then
if y > cursorY or x < cursorX then
outfile:write("\n")
elseif x > cursorX then
outfile:write(" ")
end
end
cursorY = y
cursorX = x
end,
rule = function () end,
debugFrame = function (_) end,
debugHbox = function() end
}
SILE.outputter = SILE.outputters.text
if not SILE.outputFilename and SILE.masterFilename then
SILE.outputFilename = SILE.masterFilename..".txt"
end
|
fix(backends): Implement cursor tracking to roughly simulate glues
|
fix(backends): Implement cursor tracking to roughly simulate glues
|
Lua
|
mit
|
alerque/sile,alerque/sile,alerque/sile,alerque/sile
|
ee9728d4849918622f5ff462f4cee513dd026727
|
src/bot.lua
|
src/bot.lua
|
local bot = {}
local api = require("api")
local soul = require("soul")
function bot.analyzeMessageType(upd)
if upd.message then
local msg = upd.message
if msg.audio then
return "Audio"
elseif msg.voice then
return "Voice"
elseif msg.video then
return "Video"
elseif msg.document then
return "Document"
elseif msg.game then
return "Game"
elseif msg.photo then
return "Photo"
elseif msg.sticker then
return "Sticker"
elseif msg.dice then
return "Dice"
elseif msg.video_note then
return "VideoNote"
elseif msg.contact then
return "Contact"
elseif msg.location then
return "Location"
elseif msg.venue then
return "Venue"
elseif msg.new_chat_members then
return "NewChatMembers"
elseif msg.left_chat_member then
return "LeftChatMembers"
elseif msg.new_chat_title then
return "NewChatTitle"
elseif msg.new_chat_photo then
return "NewChatPhoto"
elseif msg.delete_chat_title then
return "DeleteChatPhoto"
elseif msg.group_chat_created then
return "GroupChatCreated"
elseif msg.supergroup_chat_created then
return "SupergroupChatCreated"
elseif msg.channel_chat_created then
return "ChannelChatCreated"
elseif msg.migrate_to_chat_id or msg.migrate_from_chat_id then
return "MigrateToChat"
elseif msg.pinned_message then
return "PinnedMessage"
elseif msg.invoice then
return "Invoice"
elseif msg.successful_payment then
return "SuccessfulPayment"
elseif msg.chat.type == "channel" then
return "ChannelMessage"
else
return "Message"
end
elseif upd.edited_message then
return "EditedMessage"
elseif upd.channel_post then
return "ChannelPost"
elseif upd.edited_channel_post then
return "EditedChannelPost"
elseif upd.inline_query then
return "InlineQuery"
elseif upd.chosen_inline_result then
return "ChosenInlineResult"
elseif upd.callback_query then
return "CallbackQuery"
elseif upd.shipping_query then
return "ShippingQuery"
elseif upd.pre_checkout_query then
return "PreCheckoutQuery"
else
return "Unknown"
end
end
-- reload soul only
function bot.reload()
package.loaded.soul = nil
package.loaded.utils = nil
package.loaded.conversation = nil
soul = require("soul")
return true
end
function bot.getUpdates(offset, limit, timeout, allowed_updates)
local body = {}
body.offset = offset
body.limit = limit
body.timeout = timeout
body.allowed_updates = allowed_updates
return api.makeRequest("getUpdates", body)
end
function bot.downloadFile(file_id, path)
local ret = bot.getFile(file_id)
if ret and ret.ok then
os.execute(string.format("wget --timeout=5 -O %s https://api.telegram.org/file/bot%s/%s", path or "tmp", config.token, ret.result.file_path))
end
end
function bot.run()
logger:info("link start.")
local t = api.fetch()
for k, v in pairs(t) do
bot[k] = v
end
local ret = bot.getMe()
if ret then
bot.info = ret.result
logger:info("bot online. I am " .. bot.info.first_name .. ".")
end
local offset = 0
local threads = {
coroutine.create(function()
while true do
pcall(soul.tick)
coroutine.yield()
end
end)
}
while true do
local updates = bot.getUpdates(offset, config.limit, config.timeout)
if updates and updates.result then
for key, upd in pairs(updates.result) do
threads[upd.update_id] = coroutine.create(function()
soul[("on%sReceive"):format(bot.analyzeMessageType(upd))](
upd.message or upd.edited_message or upd.channel_post or upd.edited_channel_post
or upd.inline_query or upd.chosen_inline_result or upd.callback_query
or upd.shipping_query or upd.pre_checkout_query
)
end)
offset = upd.update_id + 1
end
end
for uid, thread in pairs(threads) do
local status, res = coroutine.resume(thread)
if not status then
threads[uid] = nil
if (res ~= "cannot resume dead coroutine") then
logger:error("coroutine #" .. uid .. " crashed, reason: " .. res)
end
end
end
end
end
setmetatable(bot, {
__index = function(t, key)
logger:warn("called undefined method " .. key)
end
})
return bot
|
local bot = {}
local api = require("api")
local soul = require("soul")
function bot.analyzeMessageType(upd)
if upd.message then
local msg = upd.message
if msg.audio then
return "Audio"
elseif msg.voice then
return "Voice"
elseif msg.video then
return "Video"
elseif msg.document then
return "Document"
elseif msg.game then
return "Game"
elseif msg.photo then
return "Photo"
elseif msg.sticker then
return "Sticker"
elseif msg.dice then
return "Dice"
elseif msg.video_note then
return "VideoNote"
elseif msg.contact then
return "Contact"
elseif msg.location then
return "Location"
elseif msg.venue then
return "Venue"
elseif msg.new_chat_members then
return "NewChatMembers"
elseif msg.left_chat_member then
return "LeftChatMembers"
elseif msg.new_chat_title then
return "NewChatTitle"
elseif msg.new_chat_photo then
return "NewChatPhoto"
elseif msg.delete_chat_title then
return "DeleteChatPhoto"
elseif msg.group_chat_created then
return "GroupChatCreated"
elseif msg.supergroup_chat_created then
return "SupergroupChatCreated"
elseif msg.channel_chat_created then
return "ChannelChatCreated"
elseif msg.migrate_to_chat_id or msg.migrate_from_chat_id then
return "MigrateToChat"
elseif msg.pinned_message then
return "PinnedMessage"
elseif msg.invoice then
return "Invoice"
elseif msg.successful_payment then
return "SuccessfulPayment"
elseif msg.chat.type == "channel" then
return "ChannelMessage"
else
return "Message"
end
elseif upd.edited_message then
return "EditedMessage"
elseif upd.channel_post then
return "ChannelPost"
elseif upd.edited_channel_post then
return "EditedChannelPost"
elseif upd.inline_query then
return "InlineQuery"
elseif upd.chosen_inline_result then
return "ChosenInlineResult"
elseif upd.callback_query then
return "CallbackQuery"
elseif upd.shipping_query then
return "ShippingQuery"
elseif upd.pre_checkout_query then
return "PreCheckoutQuery"
else
return "Unknown"
end
end
-- reload soul only
function bot.reload()
package.loaded.soul = nil
package.loaded.utils = nil
package.loaded.conversation = nil
soul = require("soul")
return true
end
function bot.getUpdates(offset, limit, timeout, allowed_updates)
local body = {}
body.offset = offset
body.limit = limit
body.timeout = timeout
body.allowed_updates = allowed_updates
return api.makeRequest("getUpdates", body)
end
function bot.downloadFile(file_id, path)
local ret = bot.getFile(file_id)
if ret and ret.ok then
os.execute(string.format("wget --timeout=5 -O %s https://api.telegram.org/file/bot%s/%s", path or "tmp", config.token, ret.result.file_path))
end
end
function bot.run()
logger:info("link start.")
local t = api.fetch()
for k, v in pairs(t) do
bot[k] = v
end
local ret = bot.getMe()
if ret then
bot.info = ret.result
logger:info("bot online. I am " .. bot.info.first_name .. ".")
end
local offset = 0
local threads = {}
while true do
local updates = bot.getUpdates(offset, config.limit, config.timeout)
if updates and updates.result then
for key, upd in pairs(updates.result) do
threads[upd.update_id] = coroutine.create(function()
soul[("on%sReceive"):format(bot.analyzeMessageType(upd))](
upd.message or upd.edited_message or upd.channel_post or upd.edited_channel_post
or upd.inline_query or upd.chosen_inline_result or upd.callback_query
or upd.shipping_query or upd.pre_checkout_query
)
end)
offset = upd.update_id + 1
end
end
threads[0] = coroutine.create(function()
soul.tick()
end)
for uid, thread in pairs(threads) do
local status, res = coroutine.resume(thread)
if not status then
threads[uid] = nil
if (res ~= "cannot resume dead coroutine") then
logger:error("coroutine #" .. uid .. " crashed, reason: " .. res)
end
end
end
end
end
setmetatable(bot, {
__index = function(t, key)
logger:warn("called undefined method " .. key)
end
})
return bot
|
fix(bot): create coroutine for tick each round
|
fix(bot): create coroutine for tick each round
|
Lua
|
apache-2.0
|
SJoshua/Project-Small-R
|
fa2cbeba529c5d3ff515558b4355ffce7b5f4ef8
|
OS/DiskOS/terminal.lua
|
OS/DiskOS/terminal.lua
|
--The terminal !--
local PATH = "C://Programs/;"
local curdrive, curdir, curpath = "C", "/", "C:///"
local function nextPath(p)
if p:sub(-1)~=";" then p=p..";" end
return p:gmatch("(.-);")
end
printCursor(1,1,1)
color(9) print("LIKO-12 V0.6.0 DEV")
color(8) print("DiskOS DEV B1")
flip() sleep(0.5)
color(7) print("\nA PICO-8 CLONE OS WITH EXTRA ABILITIES")
flip() sleep(0.25)
color(10) print("TYPE HELP FOR HELP")
flip() sleep(0.25)
local history = {}
local btimer, btime, blink = 0, 0.5, true
local function checkCursor()
local cx, cy = printCursor()
local tw, th = termSize()
if cx > tw+1 then cx = tw+1 end
if cx < 1 then cx = 1 end
if cy > th+1 then cy = th+1 end
if cy < 1 then cy = 1 end
printCursor(cx,cy) cy = cy-1
rect(cx*4-2,cy*8+2,4,5,false,blink and 5 or 1)
end
local function split(str)
local t = {}
for val in str:gmatch("%S+") do
table.insert(t, val)
end
return unpack(t)
end
local term = {}
function term.setdrive(d)
if type(d) ~= "string" then return error("DriveLetter must be a string, provided: "..type(d)) end
if not fs.drives()[d] then return error("Drive '"..d.."' doesn't exists !") end
curdrive = d
curpath = curdrive.."://"..curdir
end
function term.setdirectory(d)
if type(d) ~= "string" then return error("Directory must be a string, provided: "..type(d)) end
if not fs.exists(curdrive.."://"..d) then return error("Directory doesn't exists !") end
if not fs.isDirectory(curdrive.."://"..d) then return error("It must be a directory, not a file") end
if d:sub(0,1) ~= "/" then d = "/"..d end
if d:sub(-2,-1) ~= "/" then d = d.."/" end
d = d:gsub("//","/")
curdir = d
curpath = curdrive.."://"..d
end
function term.setpath(p)
if type(p) ~= "string" then return error("Path must be a string, provided: "..type(p)) end
local dv, d = p:match("(.+)://(.+)")
if (not dv) or (not d) then return error("Invalied path: "..p) end
if not fs.drives()[dv] then return error("Drive '"..dv.."' doesn't exists !") end
if d:sub(0,1) ~= "/" then d = "/"..d end
if d:sub(-2,-1) ~= "/" then d = d.."/" end
if not fs.exists(dv.."://"..d) then return error("Directory doesn't exists !") end
if not fs.isDirectory(dv.."://"..d) then return error("It must be a directory, not a file") end
d = d:gsub("//","/")
curdrive, curdir, curpath = dv, d, dv.."://"..d
end
function term.getpath() return curpath end
function term.getdrive() return curdrive end
function term.getdirectory() return curdir end
function term.setPATH(p) PATH = p end
function term.getPATH() return PATH end
function term.parsePath(path)
if path:sub(1,3) == "../" then
local fld = {} --A list of folders in the path
for p in string.gmatch(curdir,"(.-)/") do
table.insert(fld,p)
end
if #fld == 0 then return curdrive..":///", fs.exists(curdrive..":///") end
table.remove(fld, #fld) --Remove the last directory
return curdrive..":///"..table.concat(fld,"/")..path:sub(4,-1), fs.exists(curdrive..":///"..table.concat(fld,"/")..path:sub(4,-1))
elseif path:sub(1,2) == "./" then return curpath..sub(3,-1), fs.exists(curpath..sub(3,-1))
elseif path == ".." then
local fld = {} --A list of folders in the path
for p in string.gmatch(curdir,"(.-)/") do
table.insert(fld,p)
end
if #fld == 0 then return curdrive..":///", fs.exists(curdrive..":///") end
table.remove(fld, #fld) --Remove the last directory
return curdrive..":///"..table.concat(fld,"/"), fs.exists(curdrive..":///"..table.concat(fld,"/"))
elseif path == "." or path == "/" then return curpath, fs.exists(curpath) end
local d, p = path:match("(.+)://(.+)")
if d and p then return path, fs.exists(path) end
local d = path:match("(.+):") --ex: D:
if d then return d..":///", fs.exists(d..":///") end
local d = path:match("/(.+)")
if d then return curdrive.."://"..path, fs.exists(curdrive.."://"..path) end
return curpath..path
end
function term.execute(command,...)
if not command then print("") return false, "No command" end
if fs.exists(curpath..command..".lua") then
local chunk, err = fs.load(curpath..command..".lua")
if not chunk then color(9) print("\nL-ERR:"..tostring(err)) color(8) return false, tostring(err) end
local ok, err = pcall(chunk,...)
if not ok then color(9) print("ERR: "..tostring(err)) color(8) return false, tostring(err) end
if not fs.exists(curpath) then curdir, curpath = "/", curdrive..":///" end
color(8) return true
end
for path in nextPath(PATH) do
if fs.exists(path) then
local files = fs.directoryItems(path)
for _,file in ipairs(files) do
if file == command..".lua" then
local chunk, err = fs.load(path..file)
if not chunk then color(9) print("\nL-ERR:"..tostring(err)) color(8) return false, tostring(err) end
local ok, err = pcall(chunk,...)
if not ok then color(9) print("\nERR: "..tostring(err)) color(8) return false, tostring(err) end
if not fs.exists(curpath) then curdir, curpath = "/", curdrive..":///" end
color(8) return true
end
end
end
end
color(10) print("\nFile not found") color(8) return false, "File not found"
end
function term.loop() --Enter the while loop of the terminal
clearEStack()
color(8) checkCursor() print(term.getpath().."> ",false)
local buffer = ""
while true do
checkCursor()
local event, a, b, c, d, e, f = pullEvent()
if event == "textinput" then
buffer = buffer..a
print(a,false)
elseif event == "keypressed" then
if a == "return" then
table.insert(history, buffer)
blink = false; checkCursor()
term.execute(split(buffer)) buffer = ""
color(8) checkCursor() print(term.getpath().."> ",false) blink = true
elseif a == "backspace" then
blink = false; checkCursor()
if buffer:len() > 0 then
buffer = buffer:sub(0,-2)
printBackspace()
end
blink = true; checkCursor()
elseif a == "delete" then
blink = false; checkCursor()
for i=1,buffer:len() do
printBackspace()
end
buffer = ""
blink = true; checkCursor()
end
elseif event == "touchpressed" then
textinput(true)
elseif event == "update" then
btimer = btimer + a
if btimer > btime then
btimer = btimer-btime
blink = not blink
end
end
end
end
return term
|
--The terminal !--
local PATH = "C://Programs/;"
local curdrive, curdir, curpath = "C", "/", "C:///"
local function nextPath(p)
if p:sub(-1)~=";" then p=p..";" end
return p:gmatch("(.-);")
end
printCursor(1,1,1)
color(9) print("LIKO-12 V0.6.0 DEV")
color(8) print("DiskOS DEV B1")
flip() sleep(0.5)
color(7) print("\nA PICO-8 CLONE OS WITH EXTRA ABILITIES")
flip() sleep(0.25)
color(10) print("TYPE HELP FOR HELP")
flip() sleep(0.25)
local history = {}
local btimer, btime, blink = 0, 0.5, true
local function checkCursor()
local cx, cy = printCursor()
local tw, th = termSize()
if cx > tw+1 then cx = tw+1 end
if cx < 1 then cx = 1 end
if cy > th+1 then cy = th+1 end
if cy < 1 then cy = 1 end
printCursor(cx,cy) cy = cy-1
rect(cx*4-2,cy*8+2,4,5,false,blink and 5 or 1)
end
local function split(str)
local t = {}
for val in str:gmatch("%S+") do
table.insert(t, val)
end
return unpack(t)
end
local term = {}
function term.setdrive(d)
if type(d) ~= "string" then return error("DriveLetter must be a string, provided: "..type(d)) end
if not fs.drives()[d] then return error("Drive '"..d.."' doesn't exists !") end
curdrive = d
curpath = curdrive.."://"..curdir
end
function term.setdirectory(d)
if type(d) ~= "string" then return error("Directory must be a string, provided: "..type(d)) end
if not fs.exists(curdrive.."://"..d) then return error("Directory doesn't exists !") end
if not fs.isDirectory(curdrive.."://"..d) then return error("It must be a directory, not a file") end
if d:sub(0,1) ~= "/" then d = "/"..d end
if d:sub(-2,-1) ~= "/" then d = d.."/" end
d = d:gsub("//","/")
curdir = d
curpath = curdrive.."://"..d
end
function term.setpath(p)
if type(p) ~= "string" then return error("Path must be a string, provided: "..type(p)) end
local dv, d = p:match("(.+)://(.+)")
if (not dv) or (not d) then return error("Invalied path: "..p) end
if not fs.drives()[dv] then return error("Drive '"..dv.."' doesn't exists !") end
if d:sub(0,1) ~= "/" then d = "/"..d end
if d:sub(-2,-1) ~= "/" then d = d.."/" end
if not fs.exists(dv.."://"..d) then return error("Directory doesn't exists !") end
if not fs.isDirectory(dv.."://"..d) then return error("It must be a directory, not a file") end
d = d:gsub("//","/")
curdrive, curdir, curpath = dv, d, dv.."://"..d
end
function term.getpath() return curpath end
function term.getdrive() return curdrive end
function term.getdirectory() return curdir end
function term.setPATH(p) PATH = p end
function term.getPATH() return PATH end
function term.parsePath(path)
if path:sub(1,3) == "../" then
local fld = {} --A list of folders in the path
for p in string.gmatch(curdir,"(.-)/") do
table.insert(fld,p)
end
if #fld == 0 then return curdrive..":///", fs.exists(curdrive..":///") end
table.remove(fld, #fld) --Remove the last directory
return curdrive..":///"..table.concat(fld,"/")..path:sub(4,-1), fs.exists(curdrive..":///"..table.concat(fld,"/")..path:sub(4,-1))
elseif path:sub(1,2) == "./" then return curpath..sub(3,-1), fs.exists(curpath..sub(3,-1))
elseif path == ".." then
local fld = {} --A list of folders in the path
for p in string.gmatch(curdir,"(.-)/") do
table.insert(fld,p)
end
if #fld == 0 then return curdrive..":///", fs.exists(curdrive..":///") end
table.remove(fld, #fld) --Remove the last directory
return curdrive..":///"..table.concat(fld,"/"), fs.exists(curdrive..":///"..table.concat(fld,"/"))
elseif path == "." then return curpath, fs.exists(curpath) end
local d, p = path:match("(.+)://(.+)")
if d and p then return path, fs.exists(path) end
local d = path:match("(.+):") --ex: D:
if d then return d..":///", fs.exists(d..":///") end
local d = path:match("/(.+)")
if d then return curdrive.."://"..path, fs.exists(curdrive.."://"..path) end
return curpath..path, fs.exists(curpath..path)
end
function term.execute(command,...)
if not command then print("") return false, "No command" end
if fs.exists(curpath..command..".lua") then
local chunk, err = fs.load(curpath..command..".lua")
if not chunk then color(9) print("\nL-ERR:"..tostring(err)) color(8) return false, tostring(err) end
local ok, err = pcall(chunk,...)
if not ok then color(9) print("ERR: "..tostring(err)) color(8) return false, tostring(err) end
if not fs.exists(curpath) then curdir, curpath = "/", curdrive..":///" end
color(8) return true
end
for path in nextPath(PATH) do
if fs.exists(path) then
local files = fs.directoryItems(path)
for _,file in ipairs(files) do
if file == command..".lua" then
local chunk, err = fs.load(path..file)
if not chunk then color(9) print("\nL-ERR:"..tostring(err)) color(8) return false, tostring(err) end
local ok, err = pcall(chunk,...)
if not ok then color(9) print("\nERR: "..tostring(err)) color(8) return false, tostring(err) end
if not fs.exists(curpath) then curdir, curpath = "/", curdrive..":///" end
color(8) return true
end
end
end
end
color(10) print("\nFile not found") color(8) return false, "File not found"
end
function term.loop() --Enter the while loop of the terminal
clearEStack()
color(8) checkCursor() print(term.getpath().."> ",false)
local buffer = ""
while true do
checkCursor()
local event, a, b, c, d, e, f = pullEvent()
if event == "textinput" then
buffer = buffer..a
print(a,false)
elseif event == "keypressed" then
if a == "return" then
table.insert(history, buffer)
blink = false; checkCursor()
term.execute(split(buffer)) buffer = ""
color(8) checkCursor() print(term.getpath().."> ",false) blink = true
elseif a == "backspace" then
blink = false; checkCursor()
if buffer:len() > 0 then
buffer = buffer:sub(0,-2)
printBackspace()
end
blink = true; checkCursor()
elseif a == "delete" then
blink = false; checkCursor()
for i=1,buffer:len() do
printBackspace()
end
buffer = ""
blink = true; checkCursor()
end
elseif event == "touchpressed" then
textinput(true)
elseif event == "update" then
btimer = btimer + a
if btimer > btime then
btimer = btimer-btime
blink = not blink
end
end
end
end
return term
|
Bugfix
|
Bugfix
|
Lua
|
mit
|
RamiLego4Game/LIKO-12
|
a6619a5cb7a05e1e8c761b27f28ec2c5e791020a
|
libs/httpd/luasrc/httpd.lua
|
libs/httpd/luasrc/httpd.lua
|
--[[
HTTP server implementation for LuCI - core
(c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net>
(c) 2008 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
module("luci.httpd", package.seeall)
require("socket")
THREAD_IDLEWAIT = 0.01
THREAD_TIMEOUT = 90
THREAD_LIMIT = nil
local reading = {}
local clhandler = {}
local erhandler = {}
local threadc = 0
local threads = {}
local threadm = {}
local threadi = {}
function Socket(ip, port)
local sock, err = socket.bind( ip, port )
if sock then
sock:settimeout( 0, "t" )
end
return sock, err
end
function corecv(socket, ...)
threadi[socket] = true
while true do
local chunk, err, part = socket:receive(...)
if err ~= "timeout" then
threadi[socket] = false
return chunk, err, part
end
coroutine.yield()
end
end
function cosend(socket, chunk, i, ...)
threadi[socket] = true
i = i or 1
while true do
local stat, err, sent = socket:send(chunk, i, ...)
if err ~= "timeout" then
threadi[socket] = false
return stat, err, sent
else
i = sent and (sent + 1) or i
end
coroutine.yield()
end
end
function register(socket, s_clhandler, s_errhandler)
table.insert(reading, socket)
clhandler[socket] = s_clhandler
erhandler[socket] = s_errhandler
end
function run()
while true do
step()
end
end
function step()
local idle = true
if not THREAD_LIMIT or threadc < THREAD_LIMIT then
local now = os.time()
for i, server in ipairs(reading) do
local client = server:accept()
if client then
threadm[client] = now
threadc = threadc + 1
threads[client] = coroutine.create(clhandler[server])
end
end
end
for client, thread in pairs(threads) do
coroutine.resume(thread, client)
local now = os.time()
if coroutine.status(thread) == "dead" then
threads[client] = nil
threadc = threadc - 1
elseif threadm[client] and threadm[client] + THREAD_TIMEOUT < now then
threads[client] = nil
threadc = threadc - 1
client:close()
elseif not threadi[client] then
threadm[client] = now
idle = false
end
end
if idle then
socket.sleep(THREAD_IDLEWAIT)
end
end
|
--[[
HTTP server implementation for LuCI - core
(c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net>
(c) 2008 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
module("luci.httpd", package.seeall)
require("socket")
THREAD_IDLEWAIT = 0.01
THREAD_TIMEOUT = 90
THREAD_LIMIT = nil
local reading = {}
local clhandler = {}
local erhandler = {}
local threadc = 0
local threads = {}
local threadm = {}
local threadi = {}
function Socket(ip, port)
local sock, err = socket.bind( ip, port )
if sock then
sock:settimeout( 0, "t" )
end
return sock, err
end
function corecv(socket, ...)
threadi[socket] = true
while true do
local chunk, err, part = socket:receive(...)
if err ~= "timeout" then
threadi[socket] = false
return chunk, err, part
end
coroutine.yield()
end
end
function cosend(socket, chunk, i, ...)
threadi[socket] = true
i = i or 1
while true do
local stat, err, sent = socket:send(chunk, i, ...)
if err ~= "timeout" then
threadi[socket] = false
return stat, err, sent
else
i = sent and (sent + 1) or i
end
coroutine.yield()
end
end
function register(socket, s_clhandler, s_errhandler)
table.insert(reading, socket)
clhandler[socket] = s_clhandler
erhandler[socket] = s_errhandler
end
function run()
while true do
step()
end
end
function step()
local idle = true
if not THREAD_LIMIT or threadc < THREAD_LIMIT then
local now = os.time()
for i, server in ipairs(reading) do
local client = server:accept()
if client then
threadm[client] = now
threadc = threadc + 1
threads[client] = coroutine.create(clhandler[server])
end
end
end
for client, thread in pairs(threads) do
coroutine.resume(thread, client)
local now = os.time()
if coroutine.status(thread) == "dead" then
threads[client] = nil
threadc = threadc - 1
threadm[client] = nil
threadi[client] = nil
elseif threadm[client] and threadm[client] + THREAD_TIMEOUT < now then
threads[client] = nil
threadc = threadc - 1
client:close()
elseif not threadi[client] then
threadm[client] = now
idle = false
end
end
if idle then
socket.sleep(THREAD_IDLEWAIT)
end
end
|
* libs/httpd: Fixed a memleak
|
* libs/httpd: Fixed a memleak
|
Lua
|
apache-2.0
|
teslamint/luci,oneru/luci,thesabbir/luci,RedSnake64/openwrt-luci-packages,NeoRaider/luci,taiha/luci,cshore-firmware/openwrt-luci,aircross/OpenWrt-Firefly-LuCI,dwmw2/luci,harveyhu2012/luci,dismantl/luci-0.12,mumuqz/luci,kuoruan/luci,mumuqz/luci,artynet/luci,dwmw2/luci,harveyhu2012/luci,cappiewu/luci,aa65535/luci,remakeelectric/luci,wongsyrone/luci-1,joaofvieira/luci,deepak78/new-luci,obsy/luci,hnyman/luci,male-puppies/luci,Sakura-Winkey/LuCI,bittorf/luci,shangjiyu/luci-with-extra,aircross/OpenWrt-Firefly-LuCI,aircross/OpenWrt-Firefly-LuCI,Hostle/luci,Kyklas/luci-proto-hso,kuoruan/lede-luci,jchuang1977/luci-1,RuiChen1113/luci,obsy/luci,jlopenwrtluci/luci,ReclaimYourPrivacy/cloak-luci,schidler/ionic-luci,fkooman/luci,lcf258/openwrtcn,daofeng2015/luci,joaofvieira/luci,cshore-firmware/openwrt-luci,david-xiao/luci,male-puppies/luci,palmettos/test,ollie27/openwrt_luci,Hostle/openwrt-luci-multi-user,nwf/openwrt-luci,Sakura-Winkey/LuCI,oyido/luci,Sakura-Winkey/LuCI,david-xiao/luci,forward619/luci,cappiewu/luci,palmettos/cnLuCI,openwrt-es/openwrt-luci,cappiewu/luci,slayerrensky/luci,joaofvieira/luci,nwf/openwrt-luci,thesabbir/luci,cappiewu/luci,chris5560/openwrt-luci,slayerrensky/luci,teslamint/luci,jchuang1977/luci-1,hnyman/luci,Wedmer/luci,nmav/luci,Sakura-Winkey/LuCI,openwrt-es/openwrt-luci,palmettos/cnLuCI,LuttyYang/luci,ff94315/luci-1,wongsyrone/luci-1,obsy/luci,taiha/luci,LuttyYang/luci,tobiaswaldvogel/luci,florian-shellfire/luci,urueedi/luci,dismantl/luci-0.12,david-xiao/luci,tcatm/luci,ReclaimYourPrivacy/cloak-luci,slayerrensky/luci,kuoruan/luci,joaofvieira/luci,joaofvieira/luci,MinFu/luci,Noltari/luci,jchuang1977/luci-1,rogerpueyo/luci,obsy/luci,oneru/luci,joaofvieira/luci,palmettos/test,nwf/openwrt-luci,david-xiao/luci,db260179/openwrt-bpi-r1-luci,jlopenwrtluci/luci,deepak78/new-luci,tobiaswaldvogel/luci,palmettos/test,MinFu/luci,florian-shellfire/luci,remakeelectric/luci,slayerrensky/luci,fkooman/luci,zhaoxx063/luci,bittorf/luci,oneru/luci,ff94315/luci-1,Noltari/luci,Sakura-Winkey/LuCI,palmettos/cnLuCI,nmav/luci,taiha/luci,rogerpueyo/luci,RedSnake64/openwrt-luci-packages,thesabbir/luci,cshore/luci,opentechinstitute/luci,ollie27/openwrt_luci,nmav/luci,MinFu/luci,palmettos/test,nmav/luci,db260179/openwrt-bpi-r1-luci,sujeet14108/luci,lbthomsen/openwrt-luci,bright-things/ionic-luci,tobiaswaldvogel/luci,maxrio/luci981213,bittorf/luci,lbthomsen/openwrt-luci,forward619/luci,hnyman/luci,openwrt/luci,forward619/luci,wongsyrone/luci-1,kuoruan/lede-luci,marcel-sch/luci,981213/luci-1,LuttyYang/luci,harveyhu2012/luci,schidler/ionic-luci,urueedi/luci,LazyZhu/openwrt-luci-trunk-mod,ff94315/luci-1,shangjiyu/luci-with-extra,chris5560/openwrt-luci,Hostle/openwrt-luci-multi-user,bright-things/ionic-luci,aa65535/luci,jchuang1977/luci-1,tobiaswaldvogel/luci,jlopenwrtluci/luci,fkooman/luci,cshore/luci,shangjiyu/luci-with-extra,opentechinstitute/luci,oyido/luci,bright-things/ionic-luci,NeoRaider/luci,opentechinstitute/luci,forward619/luci,maxrio/luci981213,remakeelectric/luci,LuttyYang/luci,schidler/ionic-luci,ff94315/luci-1,jorgifumi/luci,db260179/openwrt-bpi-r1-luci,shangjiyu/luci-with-extra,aa65535/luci,db260179/openwrt-bpi-r1-luci,florian-shellfire/luci,ollie27/openwrt_luci,chris5560/openwrt-luci,urueedi/luci,schidler/ionic-luci,openwrt/luci,openwrt/luci,teslamint/luci,LazyZhu/openwrt-luci-trunk-mod,lbthomsen/openwrt-luci,taiha/luci,daofeng2015/luci,cshore/luci,zhaoxx063/luci,deepak78/new-luci,ff94315/luci-1,thess/OpenWrt-luci,openwrt/luci,chris5560/openwrt-luci,schidler/ionic-luci,nwf/openwrt-luci,Sakura-Winkey/LuCI,aircross/OpenWrt-Firefly-LuCI,981213/luci-1,LazyZhu/openwrt-luci-trunk-mod,tcatm/luci,palmettos/cnLuCI,artynet/luci,oyido/luci,maxrio/luci981213,nmav/luci,male-puppies/luci,urueedi/luci,chris5560/openwrt-luci,maxrio/luci981213,RedSnake64/openwrt-luci-packages,db260179/openwrt-bpi-r1-luci,rogerpueyo/luci,Hostle/luci,marcel-sch/luci,teslamint/luci,harveyhu2012/luci,cappiewu/luci,keyidadi/luci,NeoRaider/luci,jorgifumi/luci,Noltari/luci,RuiChen1113/luci,jorgifumi/luci,jorgifumi/luci,palmettos/test,obsy/luci,joaofvieira/luci,Kyklas/luci-proto-hso,cappiewu/luci,LuttyYang/luci,slayerrensky/luci,rogerpueyo/luci,cshore-firmware/openwrt-luci,sujeet14108/luci,LuttyYang/luci,shangjiyu/luci-with-extra,lbthomsen/openwrt-luci,jlopenwrtluci/luci,teslamint/luci,artynet/luci,Sakura-Winkey/LuCI,981213/luci-1,Hostle/openwrt-luci-multi-user,palmettos/test,keyidadi/luci,sujeet14108/luci,palmettos/cnLuCI,RuiChen1113/luci,Kyklas/luci-proto-hso,bright-things/ionic-luci,RuiChen1113/luci,openwrt-es/openwrt-luci,dismantl/luci-0.12,openwrt-es/openwrt-luci,david-xiao/luci,jlopenwrtluci/luci,hnyman/luci,aircross/OpenWrt-Firefly-LuCI,sujeet14108/luci,wongsyrone/luci-1,Wedmer/luci,MinFu/luci,thess/OpenWrt-luci,981213/luci-1,schidler/ionic-luci,tcatm/luci,openwrt/luci,nwf/openwrt-luci,deepak78/new-luci,kuoruan/lede-luci,bright-things/ionic-luci,kuoruan/lede-luci,sujeet14108/luci,fkooman/luci,opentechinstitute/luci,nmav/luci,palmettos/cnLuCI,nwf/openwrt-luci,NeoRaider/luci,dwmw2/luci,nwf/openwrt-luci,Wedmer/luci,tobiaswaldvogel/luci,bright-things/ionic-luci,jchuang1977/luci-1,LazyZhu/openwrt-luci-trunk-mod,aircross/OpenWrt-Firefly-LuCI,oneru/luci,deepak78/new-luci,jchuang1977/luci-1,obsy/luci,openwrt-es/openwrt-luci,kuoruan/luci,Hostle/luci,lcf258/openwrtcn,jchuang1977/luci-1,thesabbir/luci,Hostle/luci,kuoruan/lede-luci,MinFu/luci,jorgifumi/luci,lbthomsen/openwrt-luci,taiha/luci,jchuang1977/luci-1,artynet/luci,harveyhu2012/luci,981213/luci-1,thess/OpenWrt-luci,ReclaimYourPrivacy/cloak-luci,ff94315/luci-1,dismantl/luci-0.12,david-xiao/luci,tcatm/luci,remakeelectric/luci,tobiaswaldvogel/luci,Noltari/luci,opentechinstitute/luci,teslamint/luci,Kyklas/luci-proto-hso,ReclaimYourPrivacy/cloak-luci,male-puppies/luci,tcatm/luci,ReclaimYourPrivacy/cloak-luci,Wedmer/luci,NeoRaider/luci,zhaoxx063/luci,oyido/luci,Hostle/luci,RuiChen1113/luci,artynet/luci,shangjiyu/luci-with-extra,hnyman/luci,palmettos/cnLuCI,marcel-sch/luci,sujeet14108/luci,kuoruan/luci,bittorf/luci,Hostle/luci,remakeelectric/luci,bright-things/ionic-luci,jlopenwrtluci/luci,thess/OpenWrt-luci,openwrt-es/openwrt-luci,db260179/openwrt-bpi-r1-luci,obsy/luci,oyido/luci,obsy/luci,ollie27/openwrt_luci,cshore-firmware/openwrt-luci,Kyklas/luci-proto-hso,openwrt/luci,hnyman/luci,remakeelectric/luci,male-puppies/luci,david-xiao/luci,Sakura-Winkey/LuCI,mumuqz/luci,hnyman/luci,981213/luci-1,palmettos/test,lbthomsen/openwrt-luci,Wedmer/luci,marcel-sch/luci,Noltari/luci,bittorf/luci,zhaoxx063/luci,urueedi/luci,aa65535/luci,tobiaswaldvogel/luci,lbthomsen/openwrt-luci,artynet/luci,Hostle/luci,cappiewu/luci,slayerrensky/luci,nwf/openwrt-luci,zhaoxx063/luci,fkooman/luci,dwmw2/luci,bright-things/ionic-luci,wongsyrone/luci-1,kuoruan/luci,Kyklas/luci-proto-hso,harveyhu2012/luci,keyidadi/luci,dwmw2/luci,slayerrensky/luci,MinFu/luci,RedSnake64/openwrt-luci-packages,shangjiyu/luci-with-extra,cshore/luci,daofeng2015/luci,LazyZhu/openwrt-luci-trunk-mod,oneru/luci,tcatm/luci,taiha/luci,taiha/luci,Wedmer/luci,maxrio/luci981213,ollie27/openwrt_luci,RuiChen1113/luci,Hostle/openwrt-luci-multi-user,mumuqz/luci,artynet/luci,Kyklas/luci-proto-hso,oyido/luci,ReclaimYourPrivacy/cloak-luci,remakeelectric/luci,thess/OpenWrt-luci,marcel-sch/luci,zhaoxx063/luci,lcf258/openwrtcn,rogerpueyo/luci,taiha/luci,david-xiao/luci,lcf258/openwrtcn,lcf258/openwrtcn,RuiChen1113/luci,LuttyYang/luci,Wedmer/luci,sujeet14108/luci,kuoruan/lede-luci,ollie27/openwrt_luci,daofeng2015/luci,remakeelectric/luci,zhaoxx063/luci,bittorf/luci,opentechinstitute/luci,Noltari/luci,thesabbir/luci,lbthomsen/openwrt-luci,Hostle/openwrt-luci-multi-user,LazyZhu/openwrt-luci-trunk-mod,lcf258/openwrtcn,cshore/luci,ollie27/openwrt_luci,LazyZhu/openwrt-luci-trunk-mod,joaofvieira/luci,kuoruan/luci,daofeng2015/luci,LazyZhu/openwrt-luci-trunk-mod,florian-shellfire/luci,lcf258/openwrtcn,aa65535/luci,mumuqz/luci,schidler/ionic-luci,Hostle/openwrt-luci-multi-user,mumuqz/luci,ReclaimYourPrivacy/cloak-luci,oneru/luci,cshore/luci,wongsyrone/luci-1,deepak78/new-luci,dismantl/luci-0.12,maxrio/luci981213,ff94315/luci-1,keyidadi/luci,florian-shellfire/luci,nmav/luci,dwmw2/luci,shangjiyu/luci-with-extra,daofeng2015/luci,teslamint/luci,sujeet14108/luci,Hostle/openwrt-luci-multi-user,daofeng2015/luci,ff94315/luci-1,nmav/luci,openwrt-es/openwrt-luci,openwrt-es/openwrt-luci,marcel-sch/luci,dwmw2/luci,oneru/luci,daofeng2015/luci,mumuqz/luci,florian-shellfire/luci,Hostle/luci,oyido/luci,ollie27/openwrt_luci,db260179/openwrt-bpi-r1-luci,kuoruan/lede-luci,NeoRaider/luci,Noltari/luci,kuoruan/luci,nmav/luci,artynet/luci,lcf258/openwrtcn,aa65535/luci,dwmw2/luci,thess/OpenWrt-luci,forward619/luci,keyidadi/luci,dismantl/luci-0.12,mumuqz/luci,rogerpueyo/luci,kuoruan/luci,hnyman/luci,NeoRaider/luci,lcf258/openwrtcn,lcf258/openwrtcn,ReclaimYourPrivacy/cloak-luci,fkooman/luci,palmettos/test,maxrio/luci981213,harveyhu2012/luci,openwrt/luci,male-puppies/luci,forward619/luci,florian-shellfire/luci,urueedi/luci,forward619/luci,chris5560/openwrt-luci,cshore-firmware/openwrt-luci,jorgifumi/luci,deepak78/new-luci,bittorf/luci,aircross/OpenWrt-Firefly-LuCI,palmettos/cnLuCI,cshore/luci,chris5560/openwrt-luci,opentechinstitute/luci,RuiChen1113/luci,wongsyrone/luci-1,deepak78/new-luci,oyido/luci,fkooman/luci,zhaoxx063/luci,keyidadi/luci,cshore-firmware/openwrt-luci,cshore-firmware/openwrt-luci,rogerpueyo/luci,MinFu/luci,tcatm/luci,rogerpueyo/luci,RedSnake64/openwrt-luci-packages,urueedi/luci,cshore-firmware/openwrt-luci,teslamint/luci,thesabbir/luci,tcatm/luci,oneru/luci,MinFu/luci,wongsyrone/luci-1,RedSnake64/openwrt-luci-packages,urueedi/luci,jorgifumi/luci,male-puppies/luci,marcel-sch/luci,openwrt/luci,thess/OpenWrt-luci,florian-shellfire/luci,cshore/luci,slayerrensky/luci,thesabbir/luci,thesabbir/luci,Noltari/luci,Hostle/openwrt-luci-multi-user,thess/OpenWrt-luci,kuoruan/lede-luci,NeoRaider/luci,fkooman/luci,dismantl/luci-0.12,chris5560/openwrt-luci,schidler/ionic-luci,marcel-sch/luci,jorgifumi/luci,keyidadi/luci,forward619/luci,keyidadi/luci,aa65535/luci,cappiewu/luci,Wedmer/luci,jlopenwrtluci/luci,RedSnake64/openwrt-luci-packages,male-puppies/luci,maxrio/luci981213,LuttyYang/luci,Noltari/luci,bittorf/luci,artynet/luci,981213/luci-1,db260179/openwrt-bpi-r1-luci,opentechinstitute/luci,jlopenwrtluci/luci,tobiaswaldvogel/luci,aa65535/luci
|
484ef13e502fea64929ed15d1b505931d3514d10
|
applications/luci-polipo/luasrc/model/cbi/polipo.lua
|
applications/luci-polipo/luasrc/model/cbi/polipo.lua
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Aleksandar Krsteski <alekrsteski@gmail.com>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
m = Map("polipo")
-- General section
s = m:section(NamedSection, "general", "polipo")
-- General settings
s:option(Flag, "enabled", translate("enable"))
s:option(Value, "proxyAddress")
s:option(Value, "proxyPort").optional = true
s:option(DynamicList, "allowedClients")
s:option(Flag, "logSyslog")
s:option(Value, "logFacility"):depends("logSyslog", "1")
v = s:option(Value, "logFile")
v:depends("logSyslog", "")
v.rmempty = true
s:option(Value, "chunkHighMark")
-- DNS and proxy settings
s:option(Value, "dnsNameServer").optional = true
s:option(Value, "parentProxy").optional = true
s:option(Value, "parentAuthCredentials").optional = true
l = s:option(ListValue, "dnsQueryIPv6")
l.optional = true
l.default = "happily"
l:value("")
l:value("true")
l:value("reluctantly")
l:value("happily")
l:value("false")
l = s:option(ListValue, "dnsUseGethostbyname")
l.optional = true
l.default = "reluctantly"
l:value("")
l:value("true")
l:value("reluctantly")
l:value("happily")
l:value("false")
-- Dsik cache section
s = m:section(NamedSection, "cache", "polipo")
-- Dsik cache settings
s:option(Value, "diskCacheRoot").rmempty = true
s:option(Flag, "cacheIsShared")
s:option(Value, "diskCacheTruncateSize").optional = true
s:option(Value, "diskCacheTruncateTime").optional = true
s:option(Value, "diskCacheUnlinkTime").optional = true
-- Poor man's multiplexing section
s = m:section(NamedSection, "pmm", "polipo")
s:option(Value, "pmmSize").rmempty = true
s:option(Value, "pmmFirstSize").optional = true
return m
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Aleksandar Krsteski <alekrsteski@gmail.com>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
m = Map("polipo", translate("Polipo"),
translate("Polipo is a small and fast caching web proxy."))
-- General section
s = m:section(NamedSection, "general", "polipo", translate("Proxy"))
s:tab("general", translate("General Settings"))
s:tab("dns", translate("DNS and Query Settings"))
s:tab("proxy", translate("Parent Proxy"))
s:tab("logging", translate("Logging and RAM"))
-- General settings
s:taboption("general", Flag, "enabled", translate("enable"))
o = s:taboption("general", Value, "proxyAddress", translate("Listen address"),
translate("The interface on which Polipo will listen. To listen on all " ..
"interfaces use 0.0.0.0 or :: (IPv6)."))
o.placeholder = "0.0.0.0"
o.datatype = "ipaddr"
o = s:taboption("general", Value, "proxyPort", translate("Listen port"),
translate("Port on which Polipo will listen"))
o.optional = true
o.placeholder = "8123"
o.datatype = "port"
o = s:taboption("general", DynamicList, "allowedClients",
translate("Allowed clients"),
translate("When listen address is set to 0.0.0.0 or :: (IPv6), you must " ..
"list clients that are allowed to connect. The format is IP address " ..
"or network address (192.168.1.123, 192.168.1.0/24, " ..
"2001:660:116::/48 (IPv6))"))
o.datatype = "ipaddr"
o.placeholder = "0.0.0.0/0"
-- DNS settings
dns = s:taboption("dns", Value, "dnsNameServer", translate("DNS server address"),
translate("Set the DNS server address to use, if you want Polipo to use " ..
"different DNS server than the host system."))
dns.optional = true
dns.datatype = "ipaddr"
l = s:taboption("dns", ListValue, "dnsQueryIPv6",
translate("Query DNS for IPv6"))
l.default = "happily"
l:value("true", translate("Query only IPv6"))
l:value("happily", translate("Query IPv4 and IPv6, prefer IPv6"))
l:value("reluctantly", translate("Query IPv4 and IPv6, prefer IPv4"))
l:value("false", translate("Do not query IPv6"))
l = s:taboption("dns", ListValue, "dnsUseGethostbyname",
translate("Query DNS by hostname"))
l.default = "reluctantly"
l:value("true", translate("Always use system DNS resolver"))
l:value("happily",
translate("Query DNS directly, for unknown hosts fall back " ..
"to system resolver"))
l:value("reluctantly",
translate("Query DNS directly, fallback to system resolver"))
l:value("false", translate("Never use system DNS resolver"))
-- Proxy settings
o = s:taboption("proxy", Value, "parentProxy",
translate("Parent proxy address"),
translate("Parent proxy address (in host:port format), to which Polipo " ..
"will forward the requests."))
o.optional = true
o.datatype = "ipaddr"
o = s:taboption("proxy", Value, "parentAuthCredentials",
translate("Parent proxy authentication"),
translate("Basic HTTP authentication supported. Provide username and " ..
"password in username:password format."))
o.optional = true
o.placeholder = "username:password"
-- Logging
s:taboption("logging", Flag, "logSyslog", translate("Log to syslog"))
s:taboption("logging", Value, "logFacility",
translate("Syslog facility")):depends("logSyslog", "1")
v = s:taboption("logging", Value, "logFile",
translate("Log file location"),
translate("Use of external storage device is recommended, because the " ..
"log file is written frequently and can grow considerably."))
v:depends("logSyslog", "")
v.rmempty = true
o = s:taboption("logging", Value, "chunkHighMark",
translate("In RAM cache size (in bytes)"),
translate("How much RAM should Polipo use for its cache."))
o.datatype = "uinteger"
-- Disk cache section
s = m:section(NamedSection, "cache", "polipo", translate("On-Disk Cache"))
s:tab("general", translate("General Settings"))
s:tab("advanced", translate("Advanced Settings"))
-- Disk cache settings
s:taboption("general", Value, "diskCacheRoot", translate("Disk cache location"),
translate("Location where polipo will cache files permanently. Use of " ..
"external storage devices is recommended, because the cache can " ..
"grow considerably. Leave it empty to disable on-disk " ..
"cache.")).rmempty = true
s:taboption("general", Flag, "cacheIsShared", translate("Shared cache"),
translate("Enable if cache (proxy) is shared by multiple users."))
o = s:taboption("advanced", Value, "diskCacheTruncateSize",
translate("Truncate cache files size (in bytes)"),
translate("Size to which cached files should be truncated"))
o.optional = true
o.placeholder = "1048576"
o.datatype = "uinteger"
o = s:taboption("advanced", Value, "diskCacheTruncateTime",
translate("Truncate cache files time"),
translate("Time after which cached files will be truncated"))
o.optional = true
o.placeholder = "4d12h"
o = s:taboption("advanced", Value, "diskCacheUnlinkTime",
translate("Delete cache files time"),
translate("Time after which cached files will be deleted"))
o.optional = true
o.placeholder = "32d"
-- Poor man's multiplexing section
s = m:section(NamedSection, "pmm", "polipo",
translate("Poor Man's Multiplexing"),
translate("Poor Man's Multiplexing (PMM) is a technique that simulates " ..
"multiplexing by requesting an instance in multiple segments. It " ..
"tries to lower the latency caused by the weakness of HTTP " ..
"protocol. NOTE: some sites may not work with PMM enabled."))
s:option(Value, "pmmSize", translate("PMM segments size (in bytes)"),
translate("To enable PMM, PMM segment size must be set to some " ..
"positive value.")).rmempty = true
s:option(Value, "pmmFirstSize", translate("First PMM segment size (in bytes)"),
translate("Size of the first PMM segment. If not defined, it defaults " ..
"to twice the PMM segment size.")).rmempty = true
return m
|
applications/luci-polipo: fix polipo page
|
applications/luci-polipo: fix polipo page
|
Lua
|
apache-2.0
|
deepak78/luci,deepak78/luci,8devices/luci,8devices/luci,8devices/luci,deepak78/luci,deepak78/luci,deepak78/luci,8devices/luci,8devices/luci,8devices/luci,deepak78/luci,deepak78/luci,deepak78/luci
|
9d018485cbc9ed3e33377b59dce9ec423c05abbb
|
build/scripts/tools/ndk_server.lua
|
build/scripts/tools/ndk_server.lua
|
TOOL.Name = "SDKServer"
TOOL.Directory = "../SDK"
TOOL.Kind = "Library"
TOOL.TargetDirectory = "../SDK/lib"
TOOL.Defines = {
"NDK_BUILD",
"NDK_SERVER"
}
TOOL.Includes = {
"../SDK/include",
"../SDK/src"
}
TOOL.Files = {
"../SDK/include/NDK/**.hpp",
"../SDK/include/NDK/**.inl",
"../SDK/src/NDK/**.hpp",
"../SDK/src/NDK/**.inl",
"../SDK/src/NDK/**.cpp"
}
-- Excludes client-only files
TOOL.FilesExcluded = {
"../SDK/**/CameraComponent.*",
"../SDK/**/Console.*",
"../SDK/**/GraphicsComponent.*",
"../SDK/**/LightComponent.*",
"../SDK/**/ListenerComponent.*",
"../SDK/**/ListenerSystem.*",
"../SDK/**/RenderSystem.*",
"../SDK/**/LuaBinding_Audio.*",
"../SDK/**/LuaBinding_Graphics.*",
"../SDK/**/LuaBinding_Renderer.*"
}
TOOL.Libraries = function()
local libraries = {}
for k,v in pairs(NazaraBuild.Modules) do
if (not v.ClientOnly) then
table.insert(libraries, "Nazara" .. v.Name)
end
end
return libraries
end
|
TOOL.Name = "SDKServer"
TOOL.Directory = "../SDK"
TOOL.Kind = "Library"
TOOL.TargetDirectory = "../SDK/lib"
TOOL.Defines = {
"NDK_BUILD",
"NDK_SERVER"
}
TOOL.Includes = {
"../SDK/include",
"../SDK/src"
}
TOOL.Files = {
"../SDK/include/NDK/**.hpp",
"../SDK/include/NDK/**.inl",
"../SDK/src/NDK/**.hpp",
"../SDK/src/NDK/**.inl",
"../SDK/src/NDK/**.cpp"
}
-- Excludes client-only files
TOOL.FilesExcluded = {
"../SDK/**/CameraComponent.*",
"../SDK/**/Console.*",
"../SDK/**/GraphicsComponent.*",
"../SDK/**/LightComponent.*",
"../SDK/**/ListenerComponent.*",
"../SDK/**/ListenerSystem.*",
"../SDK/**/RenderSystem.*",
"../SDK/**/LuaBinding_Audio.*",
"../SDK/**/LuaBinding_Graphics.*",
"../SDK/**/LuaBinding_Renderer.*"
}
TOOL.Libraries = {
"NazaraCore",
"NazaraLua",
"NazaraNetwork",
"NazaraNoise",
"NazaraPhysics",
"NazaraUtility"
}
|
Build/NDKServer: Fix dependencies, allowing it to exists in server mode
|
Build/NDKServer: Fix dependencies, allowing it to exists in server mode
Former-commit-id: 8130fc4bd6898f21d08bfad37e3b54676ee34b96 [formerly 9f64adc84777930b63419690bf0e454582989158]
Former-commit-id: 3838886ff2303fe94b69403e1cab51cc4c99a05c
|
Lua
|
mit
|
DigitalPulseSoftware/NazaraEngine
|
4553ce6dac0b1aa9a46d6b033eb866581900f722
|
share/lua/meta/art/03_lastfm.lua
|
share/lua/meta/art/03_lastfm.lua
|
--[[
Gets an artwork from last.fm
$Id$
Copyright © 2010 the VideoLAN team
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
--]]
function descriptor()
return { scope="network" }
end
-- Return the artwork
function fetch_art()
if vlc.item == nil then return nil end
local meta = vlc.item:metas()
if meta["Listing Type"] == "radio"
or meta["Listing Type"] == "tv"
then return nil end
if meta["artist"] and meta["album"] then
title = meta["artist"].."/"..meta["album"]
else
return nil
end
-- remove -.* from string
title = string.gsub( title, " ?%-.*", "" )
-- remove (info..) from string
title = string.gsub( title, "%(.*%)", "" )
-- remove CD2 etc from string
title = string.gsub( title, "CD%d+", "" )
-- remove Disc \w+ from string
title = string.gsub( title, "Disc %w+", "" )
fd = vlc.stream( "http://www.last.fm/music/" .. title )
if not fd then return nil end
page = fd:read( 65653 )
fd = nil
_, _, arturl = string.find( page, "<img width=\"174\" src=\"([^\"]+)\" class=\"art\" />\n" )
-- Don't use default album-art (not found one)
if not arturl or string.find( arturl, "default_album_mega.png") then
return nil
end
return arturl
end
|
--[[
Gets an artwork from last.fm
$Id$
Copyright © 2010 the VideoLAN team
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
--]]
function descriptor()
return { scope="network" }
end
-- Return the artwork
function fetch_art()
if vlc.item == nil then return nil end
local meta = vlc.item:metas()
if meta["Listing Type"] == "radio"
or meta["Listing Type"] == "tv"
then return nil end
if meta["artist"] and meta["album"] then
title = meta["artist"].."/"..meta["album"]
else
return nil
end
-- remove -.* from string
title = string.gsub( title, " ?%-.*", "" )
-- remove (info..) from string
title = string.gsub( title, "%(.*%)", "" )
-- remove CD2 etc from string
title = string.gsub( title, "CD%d+", "" )
-- remove Disc \w+ from string
title = string.gsub( title, "Disc %w+", "" )
fd = vlc.stream( "http://www.last.fm/music/" .. title )
if not fd then return nil end
page = fd:read( 65653 )
fd = nil
_, _, arturl = string.find( page, "<meta property=\"og:image\" content=\"([^\"]+)\" />" )
-- Don't use default album-art (not found one)
if not arturl or string.find( arturl, "default_album_mega.png") then
return nil
end
return arturl
end
|
lua: lastfm: fix matching
|
lua: lastfm: fix matching
|
Lua
|
lgpl-2.1
|
shyamalschandra/vlc,vlc-mirror/vlc,shyamalschandra/vlc,xkfz007/vlc,xkfz007/vlc,krichter722/vlc,shyamalschandra/vlc,shyamalschandra/vlc,jomanmuk/vlc-2.2,shyamalschandra/vlc,xkfz007/vlc,xkfz007/vlc,jomanmuk/vlc-2.2,vlc-mirror/vlc,vlc-mirror/vlc,jomanmuk/vlc-2.2,xkfz007/vlc,shyamalschandra/vlc,krichter722/vlc,vlc-mirror/vlc,krichter722/vlc,krichter722/vlc,jomanmuk/vlc-2.2,shyamalschandra/vlc,vlc-mirror/vlc,jomanmuk/vlc-2.2,krichter722/vlc,jomanmuk/vlc-2.2,krichter722/vlc,vlc-mirror/vlc,krichter722/vlc,jomanmuk/vlc-2.2,xkfz007/vlc,xkfz007/vlc,vlc-mirror/vlc
|
48bb93a9cacccae7f975e174fda658abc6148bf2
|
tools/build/scripts/pkg_config.lua
|
tools/build/scripts/pkg_config.lua
|
-- Helper methods to use the system pkg-config utility
pkg_config = {}
function pkg_config.cflags(lib)
if not os.istarget("linux") then
return
end
buildoptions({
({os.outputof("pkg-config --cflags "..lib)})[1],
})
end
function pkg_config.lflags(lib)
if not os.istarget("linux") then
return
end
linkoptions({
({os.outputof("pkg-config --libs-only-L " ..lib)})[1],
({os.outputof("pkg-config --libs-only-other "..lib)})[1],
})
-- We can't just drop the stdout of the `--libs` command in
-- linkoptions because library order matters
local output = ({os.outputof("pkg-config --libs-only-l "..lib)})[1]
for k, flag in next, string.explode(output, " ") do
-- remove "-l"
links(string.sub(flag, 3))
end
end
function pkg_config.all(lib)
pkg_config.cflags(lib)
pkg_config.lflags(lib)
end
|
-- Helper methods to use the system pkg-config utility
pkg_config = {}
function pkg_config.cflags(lib)
if not os.istarget("linux") then
return
end
buildoptions({
({os.outputof("pkg-config --cflags "..lib)})[1],
})
end
function pkg_config.lflags(lib)
if not os.istarget("linux") then
return
end
linkoptions({
({os.outputof("pkg-config --libs-only-L " ..lib)})[1],
({os.outputof("pkg-config --libs-only-other "..lib)})[1],
})
-- We can't just drop the stdout of the `--libs` command in
-- linkoptions because library order matters
local output = ({os.outputof("pkg-config --libs-only-l "..lib)})[1]
for k, flag in next, string.explode(output, " ") do
-- remove "-l"
if flag ~= "" then
links(string.sub(flag, 3))
end
end
end
function pkg_config.all(lib)
pkg_config.cflags(lib)
pkg_config.lflags(lib)
end
|
[Linux] Fix pkg-config trailing space causing premake to output an extra empty library -l Fixes #1868
|
[Linux] Fix pkg-config trailing space causing premake to output an extra empty library -l
Fixes #1868
|
Lua
|
bsd-3-clause
|
sephiroth99/xenia,sephiroth99/xenia,sephiroth99/xenia
|
e073f6f1ee2bbb0a130c18e88c1875964a273ea8
|
ZeroGrad.lua
|
ZeroGrad.lua
|
local ZeroGrad, parent = torch.class("nn.ZeroGrad", "nn.Module")
local function recursiveZero(t1,t2)
if torch.type(t2) == 'table' then
t1 = (torch.type(t1) == 'table') and t1 or {t1}
for key,_ in pairs(t2) do
t1[key], t2[key] = recursiveZero(t1[key], t2[key])
end
elseif torch.isTensor(t2) then
t1 = t1 or t2.new()
t1:resizeAs(t2):zero()
else
error("expecting nested tensors or tables. Got "..
torch.type(t1).." and "..torch.type(t2).." instead")
end
return t1, t2
end
-- the gradient is simply zeroed.
-- useful when you don't want to backpropgate through certain paths.
function ZeroGrad:updateGradInput(input, gradOutput)
self.gradInput = recursiveZero(self.gradInput, gradOutput)
end
|
local ZeroGrad, parent = torch.class("nn.ZeroGrad", "nn.Module")
local function recursiveZero(t1,t2)
if torch.type(t2) == 'table' then
t1 = (torch.type(t1) == 'table') and t1 or {t1}
for key,_ in pairs(t2) do
t1[key], t2[key] = recursiveZero(t1[key], t2[key])
end
elseif torch.isTensor(t2) then
t1 = t1 or t2.new()
t1:resizeAs(t2):zero()
else
error("expecting nested tensors or tables. Got "..
torch.type(t1).." and "..torch.type(t2).." instead")
end
return t1, t2
end
function ZeroGrad:updateOutput(input)
self.output:set(input)
return self.output
end
-- the gradient is simply zeroed.
-- useful when you don't want to backpropgate through certain paths.
function ZeroGrad:updateGradInput(input, gradOutput)
self.gradInput = recursiveZero(self.gradInput, gradOutput)
end
|
fixed ZeroGrad:updateOutput
|
fixed ZeroGrad:updateOutput
|
Lua
|
mit
|
clementfarabet/lua---nnx
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.