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
|
---|---|---|---|---|---|---|---|---|---|
491960586a7b917a21817efe3d31228d7114ae2c
|
share/lua/website/liveleak.lua
|
share/lua/website/liveleak.lua
|
-- libquvi-scripts
-- Copyright (C) 2010-2011 Toni Gundogdu <[email protected]>
--
-- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>.
--
-- This library is free software; you can redistribute it and/or
-- modify it under the terms of the GNU Lesser General Public
-- License as published by the Free Software Foundation; either
-- version 2.1 of the License, or (at your option) any later version.
--
-- This library is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-- Lesser General Public License for more details.
--
-- You should have received a copy of the GNU Lesser General Public
-- License along with this library; if not, write to the Free Software
-- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
-- 02110-1301 USA
--
local LiveLeak = {} -- Utility functions specific to this script
-- Identify the script.
function ident (self)
package.path = self.script_dir .. '/?.lua'
local C = require 'quvi/const'
local r = {}
r.domain = "liveleak%.com"
r.formats = "default"
r.categories = C.proto_http
local U = require 'quvi/util'
LiveLeak.normalize(self)
r.handles = U.handles(self.page_url,
{r.domain}, {"view"}, {"i=[%w_]+"})
return r
end
-- Query available formats.
function query_formats(self)
self.formats = 'default'
return self
end
-- Parse media URL.
function parse (self)
self.host_id = "liveleak"
LiveLeak.normalize(self)
local page = quvi.fetch(self.page_url)
local _,_,s = page:find("<title>LiveLeak.com%s+%-%s+(.-)</")
self.title = s or error ("no match: media title")
local _,_,s = self.page_url:find('view%?i=([%w_]+)')
self.id = s or error ("no match: media id")
local _,_,s = page:find('config: "(.-)"')
local config_url = s or error ("no match: config")
local opts = { fetch_type = 'config' }
local U = require 'quvi/util'
local config = quvi.fetch (U.unescape(config_url), opts)
local _,_,s = config:find("<file>(.-)</")
self.url = {s or error ("no match: file")}
return self
end
--
-- Utility functions
--
function LiveLeak.normalize(self)
if not self.page_url then return self.page_url end
local U = require 'quvi/url'
local t = U.parse(self.page_url)
local i = t.path:match('/e/([_%w]+)')
if i then
t.query = 'i=' .. i
t.path = '/view'
self.page_url = U.build(t)
end
end
-- vim: set ts=4 sw=4 tw=72 expandtab:
|
-- libquvi-scripts
-- Copyright (C) 2010-2011 Toni Gundogdu <[email protected]>
--
-- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>.
--
-- This library is free software; you can redistribute it and/or
-- modify it under the terms of the GNU Lesser General Public
-- License as published by the Free Software Foundation; either
-- version 2.1 of the License, or (at your option) any later version.
--
-- This library is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-- Lesser General Public License for more details.
--
-- You should have received a copy of the GNU Lesser General Public
-- License along with this library; if not, write to the Free Software
-- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
-- 02110-1301 USA
--
local LiveLeak = {} -- Utility functions specific to this script
-- Identify the script.
function ident (self)
package.path = self.script_dir .. '/?.lua'
local C = require 'quvi/const'
local r = {}
r.domain = "liveleak%.com"
r.formats = "default"
r.categories = C.proto_http
local U = require 'quvi/util'
LiveLeak.normalize(self)
r.handles = U.handles(self.page_url,
{r.domain}, {"view"}, {"i=[%w_]+"})
return r
end
-- Query available formats.
function query_formats(self)
self.formats = 'default'
return self
end
-- Parse media URL.
function parse (self)
self.host_id = "liveleak"
LiveLeak.normalize(self)
local page = quvi.fetch(self.page_url)
local _,_,s = page:find("<title>LiveLeak.com%s+%-%s+(.-)</")
self.title = s or error ("no match: media title")
local _,_,s = self.page_url:find('view%?i=([%w_]+)')
self.id = s or error ("no match: media id")
local _,_,s = page:find('config: "(.-)"')
local config_url = s or error ("no match: config")
local opts = { fetch_type = 'config' }
local U = require 'quvi/util'
local config = quvi.fetch (U.unescape(config_url), opts)
local _,_,s = config:find("<file>(.-)</")
self.url = {s or error ("no match: file")}
return self
end
--
-- Utility functions
--
function LiveLeak.normalize(self)
if not self.page_url then return self.page_url end
local U = require 'quvi/url'
local t = U.parse(self.page_url)
if not t.path then return self.page_url end
local i = t.path:match('/e/([_%w]+)')
if i then
t.query = 'i=' .. i
t.path = '/view'
self.page_url = U.build(t)
end
end
-- vim: set ts=4 sw=4 tw=72 expandtab:
|
FIX: liveleak.lua: attempt to index field 'path' (nil)
|
FIX: liveleak.lua: attempt to index field 'path' (nil)
|
Lua
|
lgpl-2.1
|
hadess/libquvi-scripts-iplayer,alech/libquvi-scripts,DangerCove/libquvi-scripts,hadess/libquvi-scripts-iplayer,legatvs/libquvi-scripts,legatvs/libquvi-scripts,alech/libquvi-scripts,DangerCove/libquvi-scripts
|
3544b1a45ba0cb61670126d380b7daed99b92740
|
Resources/Scripts/Modules/Physics.lua
|
Resources/Scripts/Modules/Physics.lua
|
import('Math')
import('PrintRecursive')
Physics = {
system = { gravity, gravityIsLoc, gravityMass }, -- this is quite static'd up, to use a Java term
GRAVITY = 6.6742e-11,
ID = 0,
NewSystem = function(gravity, gravityIsLoc, gravityMass)
Physics.system.gravity = gravity or vec(0, 0)
Physics.system.gravityIsLoc = gravityIsLoc or false
Physics.system.gravityMass = gravityMass
end,
UpdateSystem = function(dt, objects)
if physicsObjects ~= nil and next(physicsObjects) ~= nil then
if objects ~= nil and next(objects) ~= nil then
for i, o in pairs(objects) do
if o.physics == nil then
printTable(o)
end
if Physics.system.gravityIsLoc then
local distX = o.position.x - Physics.system.gravity.x
local distY = o.position.y - physics.system.gravity.y
local relativeGravityPosition = o.position - Physics.system.gravity
local hypot = hypot(distX, distY)
local grav = GRAVITY * (Physics.system.gravityMass * o.mass) / (distX^2 + distY^2)
Physics.UpdateObject(o.physics, dt, grav / hypot * relativeGravityPosition)
-- the above line really needs to be tested
else
Physics.UpdateObject(o.physics, dt, Physics.system.gravity)
end
end
end
end
end,
NewObject = function(mass, vel, pos)
Physics.ID = Physics.ID + 1
return { velocity = vel or vec(0, 0), angle = 0, angularVelocity = 0, torque = 0, mass = mass or 1, position = pos or vec(0, 0), force = vec(0, 0), object_id = Physics.ID }
end,
ApplyImpulse = function(obj, impulse)
if obj.mass == nil then
if obj.object_id == nil then
printTable(obj, "obj")
error("non-standard object passed", 2)
end
print("WARNING: OBJECT (ID: " .. obj.object_id .. ") DOES NOT HAVE MASS!")
else
obj.velocity = obj.velocity + (impulse / obj.mass) * (dt * TIME_FACTOR)
end
end,
ApplyAngularImpulse = function(obj, impulse)
obj.angularVelocity = obj.angularVelocity + impulse
end,
SetVelocity = function(obj, newVelocity)
obj.velocity = newVelocity
end,
UpdateObject = function(obj, dt, gravity)
obj.force = obj.force + gravity * obj.mass
obj.velocity = obj.velocity + (obj.force * dt) / obj.mass
obj.position = obj.position + (obj.velocity * dt)
obj.angularVelocity = obj.angularVelocity + (obj.torque * dt)
obj.angle = obj.angle + (obj.angularVelocity * dt)
obj.angle = normalizeAngle(obj.angle)
obj.torque = 0
obj.force = vec(0, 0)
end
}
|
import('Math')
import('PrintRecursive')
Physics = {
system = { gravity, gravityIsLoc, gravityMass }, -- this is quite static'd up, to use a Java term
GRAVITY = 6.6742e-11,
ID = 0,
NewSystem = function(gravity, gravityIsLoc, gravityMass)
Physics.system.gravity = gravity or vec(0, 0)
Physics.system.gravityIsLoc = gravityIsLoc or false
Physics.system.gravityMass = gravityMass
end,
UpdateSystem = function(dt, objects)
if objects ~= nil and next(objects) ~= nil then
for _, o in pairs(objects) do
if o.physics == nil then
printTable(o)
end
if Physics.system.gravityIsLoc then
local distX = o.position.x - Physics.system.gravity.x
local distY = o.position.y - physics.system.gravity.y
local relativeGravityPosition = o.position - Physics.system.gravity
local hypot = hypot(distX, distY)
local grav = GRAVITY * (Physics.system.gravityMass * o.mass) / (distX^2 + distY^2)
Physics.UpdateObject(o.physics, dt, grav / hypot * relativeGravityPosition)
-- the above line really needs to be tested
else
Physics.UpdateObject(o.physics, dt, Physics.system.gravity)
end
end
end
end,
NewObject = function(mass, vel, pos)
Physics.ID = Physics.ID + 1
return { velocity = vel or vec(0, 0), angle = 0, angularVelocity = 0, torque = 0, mass = mass or 1, position = pos or vec(0, 0), force = vec(0, 0), object_id = Physics.ID }
end,
ApplyImpulse = function(obj, impulse)
if obj.mass == nil then
if obj.object_id == nil then
printTable(obj, "obj")
error("non-standard object passed", 2)
end
print("WARNING: OBJECT (ID: " .. obj.object_id .. ") DOES NOT HAVE MASS!")
else
obj.velocity = obj.velocity + (impulse / obj.mass) * (dt * TIME_FACTOR)
end
end,
ApplyAngularImpulse = function(obj, impulse)
obj.angularVelocity = obj.angularVelocity + impulse
end,
SetVelocity = function(obj, newVelocity)
obj.velocity = newVelocity
end,
UpdateObject = function(obj, dt, gravity)
obj.force = obj.force + gravity * obj.mass
obj.velocity = obj.velocity + (obj.force * dt) / obj.mass
obj.position = obj.position + (obj.velocity * dt)
obj.angularVelocity = obj.angularVelocity + (obj.torque * dt)
obj.angle = obj.angle + (obj.angularVelocity * dt)
obj.angle = normalizeAngle(obj.angle)
obj.torque = 0
obj.force = vec(0, 0)
end
}
|
Fixed physics.
|
Fixed physics.
Signed-off-by: Adam Hintz <[email protected]>
|
Lua
|
mit
|
prophile/xsera,prophile/xsera,prophile/xsera,prophile/xsera,adam000/xsera,adam000/xsera,adam000/xsera,prophile/xsera,adam000/xsera
|
f41709fa12890c9d7bb7e590ededa3efe3d02acb
|
scripts/toolchain.lua
|
scripts/toolchain.lua
|
function toolchain(_buildDir, _libDir)
newoption {
trigger = "gcc",
value = "GCC",
description = "Choose GCC flavor",
allowed = {
{ "linux-gcc", "Linux (GCC compiler)" },
{ "linux-clang", "Linux (Clang compiler)" },
},
}
newoption {
trigger = "xcode",
value = "xcode_target",
description = "Choose XCode target",
allowed = {
{ "osx", "OSX" },
}
}
newoption {
trigger = "with-dynamic-runtime",
description = "Dynamically link with the runtime rather than statically",
}
newoption {
trigger = "with-32bit-compiler",
description = "Use 32-bit compiler instead 64-bit.",
}
newoption {
trigger = "with-avx",
description = "Use AVX extension.",
}
newoption {
trigger = "with-coverage",
description = "Compile with code coverage support",
}
newoption {
trigger = "sanitizer",
description = "Clang sanitizer to include in the build",
}
-- Avoid error when invoking genie --help.
if (_ACTION == nil) then return false end
location (path.join(_buildDir, "projects", _ACTION))
if _ACTION == "clean" then
os.rmdir(_buildDir)
os.mkdir(_buildDir)
os.exit(1)
end
local windowsPlatform = "10.0.16299.0"
local compiler32bit = false
if _OPTIONS["with-32bit-compiler"] then
compiler32bit = true
end
if _ACTION == "gmake" or _ACTION == "ninja" then
if nil == _OPTIONS["gcc"] then
print("GCC flavor must be specified!")
os.exit(1)
end
if "linux-gcc" == _OPTIONS["gcc"] then
premake.gcc.cc = "gcc-8"
premake.gcc.cxx = "g++-8"
premake.gcc.ar = "ar"
location (path.join(_buildDir, "projects", _ACTION .. "-linux"))
elseif "linux-clang" == _OPTIONS["gcc"] then
premake.gcc.cc = "clang-6.0"
premake.gcc.cxx = "clang++-6.0"
premake.gcc.ar = "ar"
location (path.join(_buildDir, "projects", _ACTION .. "-linux-clang"))
end
elseif _ACTION == "xcode4" then
if "osx" == _OPTIONS["xcode"] then
premake.xcode.toolset = "macosx"
location (path.join(_buildDir, "projects", _ACTION .. "-osx"))
end
elseif _ACTION == "vs2017" then
local action = premake.action.current()
action.vstudio.windowsTargetPlatformVersion = windowsPlatform
action.vstudio.windowsTargetPlatformMinVersion = windowsPlatform
end
if not _OPTIONS["with-dynamic-runtime"] then
flags { "StaticRuntime" }
end
if _OPTIONS["with-avx"] then
flags { "EnableAVX" }
end
flags {
"NoPCH",
"NativeWChar",
"NoEditAndContinue",
"Symbols",
"ExtraWarnings",
"FatalWarnings"
}
defines {
"__STDC_LIMIT_MACROS",
"__STDC_FORMAT_MACROS",
"__STDC_CONSTANT_MACROS",
}
configuration { "Debug" }
targetsuffix "Debug"
defines {
"_DEBUG",
}
configuration { "Release" }
flags {
"NoBufferSecurityCheck",
"NoFramePointer",
"OptimizeSpeed",
}
defines {
"NDEBUG",
}
targetsuffix "Release"
configuration { "vs*" }
defines {
"WIN32",
"_WIN32",
"_UNICODE",
"UNICODE",
"_SCL_SECURE=0",
"_SECURE_SCL=0",
"_SCL_SECURE_NO_WARNINGS",
"_CRT_SECURE_NO_WARNINGS",
"_CRT_SECURE_NO_DEPRECATE",
}
buildoptions {
"/wd4324", -- warning C4324: '': structure was padded due to alignment specifier
"/std:c++latest",
"/permissive-"
}
linkoptions {
"/ignore:4221", -- LNK4221: This object file does not define any previously undefined public symbols, so it will not be used by any link operation that consumes this library
}
configuration { "x64", "vs*" }
defines { "_WIN64" }
targetdir (path.join(_buildDir, "win64_" .. _ACTION, "bin"))
objdir (path.join(_buildDir, "win64_" .. _ACTION, "obj"))
libdirs {
path.join(_libDir, "lib/win64_" .. _ACTION),
}
configuration { "x64", "vs2017" }
defines { "_WIN64" }
targetdir (path.join(_buildDir, "win64_" .. _ACTION, "bin"))
objdir (path.join(_buildDir, "win64_" .. _ACTION, "obj"))
libdirs {
path.join(_libDir, "lib/win64_" .. _ACTION),
}
configuration { "linux-gcc" }
buildoptions {
"-mfpmath=sse",
}
if _OPTIONS["with-coverage"] then
configuration { "linux-gcc* or linux-clang*" }
buildoptions {
"--coverage",
"-fno-inline",
"-fno-inline-small-functions",
"-fno-default-inline",
"-fno-omit-frame-pointer",
"-fno-optimize-sibling-calls"
}
linkoptions {
"--coverage"
}
else
configuration { "linux-gcc* or linux-clang*" }
linkoptions {
"-Wl,--gc-sections",
"-Wl,--as-needed",
}
end
if _OPTIONS["sanitizer"] then
configuration { "linux-clang" }
buildoptions {
"-fsanitize=" .. _OPTIONS["sanitizer"]
}
linkoptions {
"-fsanitize=" .. _OPTIONS["sanitizer"]
}
end
configuration { "linux-gcc*" }
buildoptions {
"-msse2",
"-Wunused-value",
"-Wformat-security",
"-Wnull-dereference",
"-Wimplicit-fallthrough=5",
"-Wsuggest-override",
"-Walloc-zero",
"-Wlogical-op",
"-Wlogical-not-parentheses",
"-Wvla",
"-Wnoexcept",
"-Wduplicated-cond",
"-Wtype-limits"
}
buildoptions_cpp {
"-std=c++1z",
}
links {
"rt",
"dl",
}
configuration { "linux-clang*" }
buildoptions {
"-msse2",
"-Warray-bounds-pointer-arithmetic",
"-Wassign-enum",
"-Wbad-function-cast",
"-Wcast-qual",
"-Wcomma",
"-Wduplicate-enum",
"-Wduplicate-method-arg",
"-Wimplicit-fallthrough",
"-Wrange-loop-analysis",
"-Wpedantic",
"-Wconversion",
"-Wshadow",
"-Wno-missing-braces",
}
buildoptions_cpp {
"-std=c++1z",
}
if os.is("macosx") then
links {
"dl",
}
linkoptions {
"-W",
}
else
links {
"rt",
"dl",
}
end
configuration { "linux-gcc* or linux-clang*", "Debug" }
buildoptions {
"-g"
}
configuration { "linux-gcc*", "x64" }
targetdir (path.join(_buildDir, "linux64_gcc/bin"))
objdir (path.join(_buildDir, "linux64_gcc/obj"))
libdirs { path.join(_libDir, "lib/linux64_gcc") }
buildoptions {
"-m64",
}
configuration { "linux-clang*", "x64" }
targetdir (path.join(_buildDir, "linux64_clang/bin"))
objdir (path.join(_buildDir, "linux64_clang/obj"))
libdirs { path.join(_libDir, "lib/linux64_clang") }
buildoptions {
"-m64",
}
configuration { "osx", "x64" }
targetdir (path.join(_buildDir, "osx64_clang/bin"))
objdir (path.join(_buildDir, "osx64_clang/obj"))
buildoptions {
"-m64",
}
configuration { "osx" }
buildoptions_cpp {
"-std=c++11",
}
buildoptions {
"-Wfatal-errors",
"-msse2",
"-Wunused-value",
"-Wundef",
}
configuration {} -- reset configuration
return true
end
|
function toolchain(_buildDir, _libDir)
newoption {
trigger = "gcc",
value = "GCC",
description = "Choose GCC flavor",
allowed = {
{ "linux-gcc", "Linux (GCC compiler)" },
{ "linux-clang", "Linux (Clang compiler)" },
},
}
newoption {
trigger = "xcode",
value = "xcode_target",
description = "Choose XCode target",
allowed = {
{ "osx", "OSX" },
}
}
newoption {
trigger = "with-dynamic-runtime",
description = "Dynamically link with the runtime rather than statically",
}
newoption {
trigger = "with-32bit-compiler",
description = "Use 32-bit compiler instead 64-bit.",
}
newoption {
trigger = "with-avx",
description = "Use AVX extension.",
}
newoption {
trigger = "with-coverage",
description = "Compile with code coverage support",
}
newoption {
trigger = "sanitizer",
description = "Clang sanitizer to include in the build",
}
-- Avoid error when invoking genie --help.
if (_ACTION == nil) then return false end
location (path.join(_buildDir, "projects", _ACTION))
if _ACTION == "clean" then
os.rmdir(_buildDir)
os.mkdir(_buildDir)
os.exit(1)
end
local windowsPlatform = "10.0.16299.0"
local compiler32bit = false
if _OPTIONS["with-32bit-compiler"] then
compiler32bit = true
end
if _ACTION == "gmake" or _ACTION == "ninja" then
if nil == _OPTIONS["gcc"] then
print("GCC flavor must be specified!")
os.exit(1)
end
if "linux-gcc" == _OPTIONS["gcc"] then
premake.gcc.cc = "gcc-8"
premake.gcc.cxx = "g++-8"
premake.gcc.ar = "ar"
location (path.join(_buildDir, "projects", _ACTION .. "-linux"))
elseif "linux-clang" == _OPTIONS["gcc"] then
premake.gcc.cc = "clang-6.0"
premake.gcc.cxx = "clang++-6.0"
premake.gcc.ar = "ar"
location (path.join(_buildDir, "projects", _ACTION .. "-linux-clang"))
end
elseif _ACTION == "xcode4" then
if "osx" == _OPTIONS["xcode"] then
premake.xcode.toolset = "macosx"
location (path.join(_buildDir, "projects", _ACTION .. "-osx"))
end
elseif _ACTION == "vs2017" then
local action = premake.action.current()
action.vstudio.windowsTargetPlatformVersion = windowsPlatform
action.vstudio.windowsTargetPlatformMinVersion = windowsPlatform
end
if not _OPTIONS["with-dynamic-runtime"] then
flags { "StaticRuntime" }
end
if _OPTIONS["with-avx"] then
flags { "EnableAVX" }
end
flags {
"NoPCH",
"NativeWChar",
"NoEditAndContinue",
"Symbols",
"ExtraWarnings",
"FatalWarnings"
}
defines {
"__STDC_LIMIT_MACROS",
"__STDC_FORMAT_MACROS",
"__STDC_CONSTANT_MACROS",
}
configuration { "Debug" }
targetsuffix "Debug"
defines {
"_DEBUG",
}
configuration { "Release" }
flags {
"NoBufferSecurityCheck",
"NoFramePointer",
"OptimizeSpeed",
}
defines {
"NDEBUG",
}
targetsuffix "Release"
configuration { "vs*" }
defines {
"WIN32",
"_WIN32",
"_UNICODE",
"UNICODE",
"_SCL_SECURE=0",
"_SECURE_SCL=0",
"_SCL_SECURE_NO_WARNINGS",
"_CRT_SECURE_NO_WARNINGS",
"_CRT_SECURE_NO_DEPRECATE",
}
buildoptions {
"/wd4324", -- warning C4324: '': structure was padded due to alignment specifier
"/std:c++latest",
"/permissive-"
}
linkoptions {
"/ignore:4221", -- LNK4221: This object file does not define any previously undefined public symbols, so it will not be used by any link operation that consumes this library
}
configuration { "x64", "vs*" }
defines { "_WIN64" }
targetdir (path.join(_buildDir, "win64_" .. _ACTION, "bin"))
objdir (path.join(_buildDir, "win64_" .. _ACTION, "obj"))
libdirs {
path.join(_libDir, "lib/win64_" .. _ACTION),
}
configuration { "x64", "vs2017" }
defines { "_WIN64" }
targetdir (path.join(_buildDir, "win64_" .. _ACTION, "bin"))
objdir (path.join(_buildDir, "win64_" .. _ACTION, "obj"))
libdirs {
path.join(_libDir, "lib/win64_" .. _ACTION),
}
configuration { "linux-gcc" }
buildoptions {
"-mfpmath=sse",
}
if _OPTIONS["with-coverage"] then
configuration { "linux-gcc*" }
buildoptions {
"--coverage",
"-fno-inline",
"-fno-inline-small-functions",
"-fno-default-inline",
"-fno-omit-frame-pointer",
"-fno-optimize-sibling-calls"
}
linkoptions {
"--coverage"
}
configuration { "linux-clang*" }
buildoptions {
"--coverage",
"-O0"
}
linkoptions {
"--coverage"
}
else
configuration { "linux-gcc* or linux-clang*" }
linkoptions {
"-Wl,--gc-sections",
"-Wl,--as-needed",
}
end
if _OPTIONS["sanitizer"] then
configuration { "linux-clang" }
buildoptions {
"-fsanitize=" .. _OPTIONS["sanitizer"]
}
linkoptions {
"-fsanitize=" .. _OPTIONS["sanitizer"]
}
end
configuration { "linux-gcc*" }
buildoptions {
"-msse2",
"-Wunused-value",
"-Wformat-security",
"-Wnull-dereference",
"-Wimplicit-fallthrough=5",
"-Wsuggest-override",
"-Walloc-zero",
"-Wlogical-op",
"-Wlogical-not-parentheses",
"-Wvla",
"-Wnoexcept",
"-Wduplicated-cond",
"-Wtype-limits"
}
buildoptions_cpp {
"-std=c++1z",
}
links {
"rt",
"dl",
}
configuration { "linux-clang*" }
buildoptions {
"-msse2",
"-Warray-bounds-pointer-arithmetic",
"-Wassign-enum",
"-Wbad-function-cast",
"-Wcast-qual",
"-Wcomma",
"-Wduplicate-enum",
"-Wduplicate-method-arg",
"-Wimplicit-fallthrough",
"-Wrange-loop-analysis",
"-Wpedantic",
"-Wconversion",
"-Wshadow",
"-Wno-missing-braces",
}
buildoptions_cpp {
"-std=c++1z",
}
if os.is("macosx") then
links {
"dl",
}
linkoptions {
"-W",
}
else
links {
"rt",
"dl",
}
end
configuration { "linux-gcc* or linux-clang*", "Debug" }
buildoptions {
"-g"
}
configuration { "linux-gcc*", "x64" }
targetdir (path.join(_buildDir, "linux64_gcc/bin"))
objdir (path.join(_buildDir, "linux64_gcc/obj"))
libdirs { path.join(_libDir, "lib/linux64_gcc") }
buildoptions {
"-m64",
}
configuration { "linux-clang*", "x64" }
targetdir (path.join(_buildDir, "linux64_clang/bin"))
objdir (path.join(_buildDir, "linux64_clang/obj"))
libdirs { path.join(_libDir, "lib/linux64_clang") }
buildoptions {
"-m64",
}
configuration { "osx", "x64" }
targetdir (path.join(_buildDir, "osx64_clang/bin"))
objdir (path.join(_buildDir, "osx64_clang/obj"))
buildoptions {
"-m64",
}
configuration { "osx" }
buildoptions_cpp {
"-std=c++11",
}
buildoptions {
"-Wfatal-errors",
"-msse2",
"-Wunused-value",
"-Wundef",
}
configuration {} -- reset configuration
return true
end
|
Fix clang coverage build options
|
Fix clang coverage build options
|
Lua
|
mit
|
MikePopoloski/slang,MikePopoloski/slang
|
43ab7fd0c6972da40ac7c19f2270a75d1d75ed10
|
scripts/autocomplete.lua
|
scripts/autocomplete.lua
|
doubleTab = doubleTab or {}
function autoComplete( str )
local prefixend = string.find( str:reverse(), '[() %[%]=+/,%%]' )
local prefix = ''
local posibles
if prefixend then
prefix = string.sub( str, 1, #str - prefixend + 1 )
str = string.sub( str, #str - prefixend + 2 )
end
str, posibles = complete(str)
if #posibles > 1 then
if doubleTab.str == str then
print( table.unpack( posibles ) )
else
doubleTab.str = str
end
end
return prefix..str
end
function autoCompleteClear()
doubleTab.str = nil
end
function complete( str )
local possibles = getCompletions( str )
if #possibles > 0 then
str = string.sub( possibles[1], 1, getIdenticalPrefixLength( possibles, #str ) )
end
return str, possibles
end
function getCompletions( str )
local g = _G
local ret = {}
local dotpos = string.find( str:reverse(), '[%.:]' )
local prefix = ''
local dottype = ''
if dotpos ~= nil then
dotpos = #str - dotpos
prefix = string.sub( str, 1, dotpos )
dottype = string.sub( str, dotpos + 1, dotpos + 1 )
g = getTable(prefix)
str = string.sub( str, dotpos + 2 )
end
if g == nil then
return {}
end
-- Retrieve class info if any
for k,v in pairs( getClassInfo( g ) ) do
if string.find( v, str ) == 1 then
table.insert( ret, prefix .. dottype .. v )
end
end
if type( g ) == 'table' then
for k,v in pairs(g) do
if string.find( k, str ) == 1 and string.sub(k,1,1) ~= '_' then
table.insert( ret, prefix .. dottype .. k )
end
end
end
return ret
end
function getTable( tblname )
--print( 'Looking up:', tblname )
local lastdot = string.find( tblname:reverse(), '%.' )
if lastdot == nil then
return _G[tblname]
end
local prefix = string.sub( tblname, 1, #tblname - lastdot )
local tbl = getTable( prefix )
if type(tbl) ~= 'table' then
if type(tbl) ~= 'userdata' then
error( prefix .. ' is not a table or class.' )
end
tbl = infotable( tbl )
end
local subscript = string.sub( tblname, #tblname - string.find( tblname:reverse(), '%.' ) + 2 )
--print( "Subscript:", subscript, tblname )
return tbl[subscript]
end
function getIdenticalPrefixLength( tbl, start )
if #tbl == 0 then return start end
local l = start
local str
local allSame = true
while allSame == true do
if l > #tbl[1] then return #tbl[1] end
str = string.sub( tbl[1], 1, l )
table.foreach( tbl,
function(k,v)
if string.find( v, str ) ~= 1 then
allSame = false
end
end
)
l = l + 1
end
return l - 2
end
|
doubleTab = doubleTab or {}
function autoComplete( str )
local prefixend = string.find( str:reverse(), '[() %[%]=+/,%%]' )
local prefix = ''
local posibles
if prefixend then
prefix = string.sub( str, 1, #str - prefixend + 1 )
str = string.sub( str, #str - prefixend + 2 )
end
str, posibles = complete(str)
if #posibles > 1 then
if doubleTab.str == str then
print( table.unpack( posibles ) )
else
doubleTab.str = str
end
end
return prefix..str
end
function autoCompleteClear()
doubleTab.str = nil
end
function complete( str )
local possibles = getCompletions( str )
if #possibles > 0 then
str = string.sub( possibles[1], 1, getIdenticalPrefixLength( possibles, #str ) )
end
return str, possibles
end
function getCompletions( str )
local g = _G
local ret = {}
local dotpos = string.find( str:reverse(), '[%.:]' )
local prefix = ''
local dottype = ''
if dotpos ~= nil then
dotpos = #str - dotpos
prefix = string.sub( str, 1, dotpos )
dottype = string.sub( str, dotpos + 1, dotpos + 1 )
g = getTable(prefix)
str = string.sub( str, dotpos + 2 )
end
if g == nil then
return {}
end
if type( g ) == 'table' then
for k,v in pairs(g) do
if string.find( k, str ) == 1 and string.sub(k,1,1) ~= '_' then
table.insert( ret, prefix .. dottype .. k )
end
end
else
-- Retrieve class info if any
for k,v in pairs( getClassInfo( g ) ) do
if string.find( v, str ) == 1 then
table.insert( ret, prefix .. dottype .. v )
end
end
end
return ret
end
function getTable( tblname )
--print( 'Looking up:', tblname )
local lastdot = string.find( tblname:reverse(), '%.' )
if lastdot == nil then
return _G[tblname]
end
local prefix = string.sub( tblname, 1, #tblname - lastdot )
local tbl = getTable( prefix )
if type(tbl) ~= 'table' then
if type(tbl) ~= 'userdata' then
error( prefix .. ' is not a table or class.' )
end
tbl = infotable( tbl )
end
local subscript = string.sub( tblname, #tblname - string.find( tblname:reverse(), '%.' ) + 2 )
--print( "Subscript:", subscript, tblname )
return tbl[subscript]
end
function getIdenticalPrefixLength( tbl, start )
if #tbl == 0 then return start end
local l = start
local str
local allSame = true
while allSame == true do
if l > #tbl[1] then return #tbl[1] end
str = string.sub( tbl[1], 1, l )
table.foreach( tbl,
function(k,v)
if string.find( v, str ) ~= 1 then
allSame = false
end
end
)
l = l + 1
end
return l - 2
end
|
Fix autoComplete double ups
|
Fix autoComplete double ups
|
Lua
|
mit
|
merlinblack/Game-Engine-Testbed,merlinblack/Game-Engine-Testbed,merlinblack/Game-Engine-Testbed,merlinblack/Game-Engine-Testbed
|
2cb7a91bf266680266de51636ce6620cbecc9362
|
xmake/core/base/privilege.lua
|
xmake/core/base/privilege.lua
|
--!The Make-like Build Utility based on Lua
--
-- Licensed to the Apache Software Foundation (ASF) under one
-- or more contributor license agreements. See the NOTICE file
-- distributed with this work for additional information
-- regarding copyright ownership. The ASF licenses this file
-- to you under the Apache License, Version 2.0 (the
-- "License"); you may not use this file except in compliance
-- with the License. You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015 - 2017, TBOOX Open Source Group.
--
-- @author TitanSnow
-- @file privilege.lua
--
-- define module
local privilege = privilege or {}
-- load modules
local os = require("base/os")
-- store privilege
function privilege.store()
-- check if root
if not os.isroot() then
return false
end
-- find projectdir's owner
local projectdir = xmake._PROJECT_DIR
assert(projectdir)
local owner = os.getown(projectdir)
if not owner then
-- fallback to current dir
owner = os.getown(".")
if not owner then
return false
end
end
-- set gid
if os.gid(owner.gid).setegid_errno ~= 0 then
return false
end
-- set uid
if os.uid(owner.uid).seteuid_errno ~= 0 then
return false
end
-- set flag
privilege._HAS_PRIVILEGE = true
-- ok
return true
end
-- check if has stored privilege
function privilege.has()
return privilege._HAS_PRIVILEGE or false
end
function privilege.get()
-- has?
if privilege._HAS_PRIVILEGE ~= true then
return false
end
-- set uid
if os.uid(0).seteuid_errno ~= 0 then
return false
end
-- set gid
if os.gid(0).setegid_errno ~= 0 then
return false
end
return true
end
-- return module
return privilege
|
--!The Make-like Build Utility based on Lua
--
-- Licensed to the Apache Software Foundation (ASF) under one
-- or more contributor license agreements. See the NOTICE file
-- distributed with this work for additional information
-- regarding copyright ownership. The ASF licenses this file
-- to you under the Apache License, Version 2.0 (the
-- "License"); you may not use this file except in compliance
-- with the License. You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015 - 2017, TBOOX Open Source Group.
--
-- @author TitanSnow
-- @file privilege.lua
--
-- define module
local privilege = privilege or {}
-- load modules
local os = require("base/os")
-- store privilege
function privilege.store()
-- check if root
if not os.isroot() then
return false
end
-- find projectdir's owner
local projectdir = xmake._PROJECT_DIR
assert(projectdir)
local owner = os.getown(projectdir)
if not owner then
-- fallback to current dir
owner = os.getown(".")
if not owner then
return false
end
end
-- set gid
if os.gid(owner.gid).errno ~= 0 then
return false
end
-- set uid
if os.uid({["ruid"] = owner.uid}).errno ~= 0 or os.uid({["euid"] = owner.uid}).errno ~= 0 then
return false
end
-- set flag
privilege._HAS_PRIVILEGE = true
-- ok
return true
end
-- check if has stored privilege
function privilege.has()
return privilege._HAS_PRIVILEGE or false
end
function privilege.get()
-- has?
if privilege._HAS_PRIVILEGE ~= true then
return false
end
-- set uid
if os.uid({["euid"] = 0}).errno ~= 0 or os.uid({["ruid"] = 0}).errno ~= 0 then
return false
end
-- set gid
if os.gid(0).errno ~= 0 then
return false
end
return true
end
-- return module
return privilege
|
fix privilege
|
fix privilege
|
Lua
|
apache-2.0
|
tboox/xmake,tboox/xmake,waruqi/xmake,tboox/xmake,tboox/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,tboox/xmake,tboox/xmake,waruqi/xmake,waruqi/xmake,tboox/xmake,waruqi/xmake
|
7c7b6f4ba94c499bea4065e1e6b250f44a7fa0d3
|
applications/luci-app-travelmate/luasrc/model/cbi/travelmate/wifi_add.lua
|
applications/luci-app-travelmate/luasrc/model/cbi/travelmate/wifi_add.lua
|
-- Copyright 2017-2018 Dirk Brenken ([email protected])
-- This is free software, licensed under the Apache License, Version 2.0
local fs = require("nixio.fs")
local uci = require("luci.model.uci").cursor()
local http = require("luci.http")
local trmiface = uci:get("travelmate", "global", "trm_iface") or "trm_wwan"
local encr_psk = {"psk", "psk2", "psk-mixed"}
local encr_wpa = {"wpa", "wpa2", "wpa-mixed"}
m = SimpleForm("add", translate("Add Wireless Uplink Configuration"))
m.submit = translate("Save")
m.cancel = translate("Back to overview")
m.reset = false
function m.on_cancel()
http.redirect(luci.dispatcher.build_url("admin/services/travelmate/stations"))
end
m.hidden = {
device = http.formvalue("device"),
ssid = http.formvalue("ssid"),
bssid = http.formvalue("bssid"),
wep = http.formvalue("wep"),
wpa_suites = http.formvalue("wpa_suites"),
wpa_version = http.formvalue("wpa_version")
}
if m.hidden.ssid == "" then
wssid = m:field(Value, "ssid", translate("SSID (hidden)"))
else
wssid = m:field(Value, "ssid", translate("SSID"))
end
wssid.datatype = "rangelength(1,32)"
wssid.default = m.hidden.ssid or ""
bssid = m:field(Value, "bssid", translate("BSSID"),
translatef("The BSSID information '%s' is optional and only required for hidden networks", m.hidden.bssid or ""))
bssid.datatype = "macaddr"
if m.hidden.ssid == "" then
bssid.default = m.hidden.bssid or ""
else
bssid.default = ""
end
if (tonumber(m.hidden.wep) or 0) == 1 then
encr = m:field(ListValue, "encryption", translate("Encryption"))
encr:value("wep", "WEP")
encr:value("wep+open", "WEP Open System")
encr:value("wep+mixed", "WEP mixed")
encr:value("wep+shared", "WEP Shared Key")
encr.default = "wep+open"
wkey = m:field(Value, "key", translate("WEP-Passphrase"))
wkey.password = true
wkey.datatype = "wepkey"
elseif (tonumber(m.hidden.wpa_version) or 0) > 0 then
if m.hidden.wpa_suites == "PSK" or m.hidden.wpa_suites == "PSK2" then
encr = m:field(ListValue, "encryption", translate("Encryption"))
encr:value("psk", "WPA PSK")
encr:value("psk-mixed", "WPA/WPA2 mixed")
encr:value("psk2", "WPA2 PSK")
encr.default = encr_psk[tonumber(m.hidden.wpa_version)] or "psk2"
ciph = m:field(ListValue, "cipher", translate("Cipher"))
ciph:value("auto", translate("Automatic"))
ciph:value("ccmp", translate("Force CCMP (AES)"))
ciph:value("tkip", translate("Force TKIP"))
ciph:value("tkip+ccmp", translate("Force TKIP and CCMP (AES)"))
ciph.default = "auto"
wkey = m:field(Value, "key", translate("WPA-Passphrase"))
wkey.password = true
wkey.datatype = "wpakey"
elseif m.hidden.wpa_suites == "802.1X" then
encr = m:field(ListValue, "encryption", translate("Encryption"))
encr:value("wpa", "WPA Enterprise")
encr:value("wpa-mixed", "WPA/WPA2 Enterprise mixed")
encr:value("wpa2", "WPA2 Enterprise")
encr.default = encr_wpa[tonumber(m.hidden.wpa_version)] or "wpa2"
ciph = m:field(ListValue, "cipher", translate("Cipher"))
ciph:value("auto", translate("Automatic"))
ciph:value("ccmp", translate("Force CCMP (AES)"))
ciph:value("tkip", translate("Force TKIP"))
ciph:value("tkip+ccmp", translate("Force TKIP and CCMP (AES)"))
ciph.default = "auto"
eaptype = m:field(ListValue, "eap_type", translate("EAP-Method"))
eaptype:value("tls", "TLS")
eaptype:value("ttls", "TTLS")
eaptype:value("peap", "PEAP")
eaptype:value("fast", "FAST")
eaptype.default = "peap"
authentication = m:field(ListValue, "auth", translate("Authentication"))
authentication:value("PAP")
authentication:value("CHAP")
authentication:value("MSCHAP")
authentication:value("MSCHAPV2")
authentication:value("EAP-GTC")
authentication:value("EAP-MD5")
authentication:value("EAP-MSCHAPV2")
authentication:value("EAP-TLS")
authentication:value("auth=PAP")
authentication:value("auth=MSCHAPV2")
authentication.default = "EAP-MSCHAPV2"
ident = m:field(Value, "identity", translate("Identity"))
wkey = m:field(Value, "password", translate("Password"))
wkey.password = true
wkey.datatype = "wpakey"
cacert = m:field(Value, "ca_cert", translate("Path to CA-Certificate"))
cacert.rmempty = true
clientcert = m:field(Value, "client_cert", translate("Path to Client-Certificate"))
clientcert:depends("eap_type","tls")
clientcert.rmempty = true
privkey = m:field(Value, "priv_key", translate("Path to Private Key"))
privkey:depends("eap_type","tls")
privkey.rmempty = true
privkeypwd = m:field(Value, "priv_key_pwd", translate("Password of Private Key"))
privkeypwd:depends("eap_type","tls")
privkeypwd.datatype = "wpakey"
privkeypwd.password = true
privkeypwd.rmempty = true
end
end
function wssid.write(self, section, value)
newsection = uci:section("wireless", "wifi-iface", nil, {
mode = "sta",
network = trmiface,
device = m.hidden.device,
ssid = wssid:formvalue(section),
bssid = bssid:formvalue(section),
disabled = "1"
})
if (tonumber(m.hidden.wep) or 0) == 1 then
uci:set("wireless", newsection, "encryption", encr:formvalue(section))
uci:set("wireless", newsection, "key", wkey:formvalue(section) or "")
elseif (tonumber(m.hidden.wpa_version) or 0) > 0 then
if m.hidden.wpa_suites == "PSK" or m.hidden.wpa_suites == "PSK2" then
if ciph:formvalue(section) ~= "auto" then
uci:set("wireless", newsection, "encryption", encr:formvalue(section) .. "+" .. ciph:formvalue(section))
else
uci:set("wireless", newsection, "encryption", encr:formvalue(section))
end
uci:set("wireless", newsection, "key", wkey:formvalue(section) or "")
elseif m.hidden.wpa_suites == "802.1X" then
if ciph:formvalue(section) ~= "auto" then
uci:set("wireless", newsection, "encryption", encr:formvalue(section) .. "+" .. ciph:formvalue(section))
else
uci:set("wireless", newsection, "encryption", encr:formvalue(section))
end
uci:set("wireless", newsection, "eap_type", eaptype:formvalue(section))
uci:set("wireless", newsection, "auth", authentication:formvalue(section))
uci:set("wireless", newsection, "identity", ident:formvalue(section) or "")
uci:set("wireless", newsection, "password", wkey:formvalue(section) or "")
uci:set("wireless", newsection, "ca_cert", cacert:formvalue(section) or "")
uci:set("wireless", newsection, "client_cert", clientcert:formvalue(section) or "")
uci:set("wireless", newsection, "priv_key", privkey:formvalue(section) or "")
uci:set("wireless", newsection, "priv_key_pwd", privkeypwd:formvalue(section) or "")
end
else
uci:set("wireless", newsection, "encryption", "none")
end
uci:save("wireless")
uci:commit("wireless")
luci.sys.call("env -i /bin/ubus call network reload >/dev/null 2>&1")
http.redirect(luci.dispatcher.build_url("admin/services/travelmate/stations"))
end
return m
|
-- Copyright 2017-2018 Dirk Brenken ([email protected])
-- This is free software, licensed under the Apache License, Version 2.0
local fs = require("nixio.fs")
local uci = require("luci.model.uci").cursor()
local http = require("luci.http")
local trmiface = uci:get("travelmate", "global", "trm_iface") or "trm_wwan"
local encr_psk = {"psk", "psk2", "psk-mixed"}
local encr_wpa = {"wpa", "wpa2", "wpa-mixed"}
m = SimpleForm("add", translate("Add Wireless Uplink Configuration"))
m.submit = translate("Save")
m.cancel = translate("Back to overview")
m.reset = false
function m.on_cancel()
http.redirect(luci.dispatcher.build_url("admin/services/travelmate/stations"))
end
m.hidden = {
device = http.formvalue("device"),
ssid = http.formvalue("ssid"),
bssid = http.formvalue("bssid"),
wep = http.formvalue("wep"),
wpa_suites = http.formvalue("wpa_suites"),
wpa_version = http.formvalue("wpa_version")
}
if m.hidden.ssid == "" then
wssid = m:field(Value, "ssid", translate("SSID (hidden)"))
else
wssid = m:field(Value, "ssid", translate("SSID"))
end
wssid.datatype = "rangelength(1,32)"
wssid.default = m.hidden.ssid or ""
nobssid = m:field(Flag, "no_bssid", translate("Ignore BSSID"))
if m.hidden.ssid == "" then
nobssid.default = nobssid.disabled
else
nobssid.default = nobssid.enabled
end
bssid = m:field(Value, "bssid", translate("BSSID"),
translatef("The BSSID information '%s' is optional and only required for hidden networks", m.hidden.bssid or ""))
bssid:depends("no_bssid", 0)
bssid.datatype = "macaddr"
bssid.default = m.hidden.bssid or ""
if (tonumber(m.hidden.wep) or 0) == 1 then
encr = m:field(ListValue, "encryption", translate("Encryption"))
encr:value("wep", "WEP")
encr:value("wep+open", "WEP Open System")
encr:value("wep+mixed", "WEP mixed")
encr:value("wep+shared", "WEP Shared Key")
encr.default = "wep+open"
wkey = m:field(Value, "key", translate("WEP-Passphrase"))
wkey.password = true
wkey.datatype = "wepkey"
elseif (tonumber(m.hidden.wpa_version) or 0) > 0 then
if m.hidden.wpa_suites == "PSK" or m.hidden.wpa_suites == "PSK2" then
encr = m:field(ListValue, "encryption", translate("Encryption"))
encr:value("psk", "WPA PSK")
encr:value("psk-mixed", "WPA/WPA2 mixed")
encr:value("psk2", "WPA2 PSK")
encr.default = encr_psk[tonumber(m.hidden.wpa_version)] or "psk2"
ciph = m:field(ListValue, "cipher", translate("Cipher"))
ciph:value("auto", translate("Automatic"))
ciph:value("ccmp", translate("Force CCMP (AES)"))
ciph:value("tkip", translate("Force TKIP"))
ciph:value("tkip+ccmp", translate("Force TKIP and CCMP (AES)"))
ciph.default = "auto"
wkey = m:field(Value, "key", translate("WPA-Passphrase"))
wkey.password = true
wkey.datatype = "wpakey"
elseif m.hidden.wpa_suites == "802.1X" then
encr = m:field(ListValue, "encryption", translate("Encryption"))
encr:value("wpa", "WPA Enterprise")
encr:value("wpa-mixed", "WPA/WPA2 Enterprise mixed")
encr:value("wpa2", "WPA2 Enterprise")
encr.default = encr_wpa[tonumber(m.hidden.wpa_version)] or "wpa2"
ciph = m:field(ListValue, "cipher", translate("Cipher"))
ciph:value("auto", translate("Automatic"))
ciph:value("ccmp", translate("Force CCMP (AES)"))
ciph:value("tkip", translate("Force TKIP"))
ciph:value("tkip+ccmp", translate("Force TKIP and CCMP (AES)"))
ciph.default = "auto"
eaptype = m:field(ListValue, "eap_type", translate("EAP-Method"))
eaptype:value("tls", "TLS")
eaptype:value("ttls", "TTLS")
eaptype:value("peap", "PEAP")
eaptype:value("fast", "FAST")
eaptype.default = "peap"
authentication = m:field(ListValue, "auth", translate("Authentication"))
authentication:value("PAP")
authentication:value("CHAP")
authentication:value("MSCHAP")
authentication:value("MSCHAPV2")
authentication:value("EAP-GTC")
authentication:value("EAP-MD5")
authentication:value("EAP-MSCHAPV2")
authentication:value("EAP-TLS")
authentication:value("auth=PAP")
authentication:value("auth=MSCHAPV2")
authentication.default = "EAP-MSCHAPV2"
ident = m:field(Value, "identity", translate("Identity"))
wkey = m:field(Value, "password", translate("Password"))
wkey.password = true
wkey.datatype = "wpakey"
cacert = m:field(Value, "ca_cert", translate("Path to CA-Certificate"))
cacert.rmempty = true
clientcert = m:field(Value, "client_cert", translate("Path to Client-Certificate"))
clientcert:depends("eap_type","tls")
clientcert.rmempty = true
privkey = m:field(Value, "priv_key", translate("Path to Private Key"))
privkey:depends("eap_type","tls")
privkey.rmempty = true
privkeypwd = m:field(Value, "priv_key_pwd", translate("Password of Private Key"))
privkeypwd:depends("eap_type","tls")
privkeypwd.datatype = "wpakey"
privkeypwd.password = true
privkeypwd.rmempty = true
end
end
function wssid.write(self, section, value)
newsection = uci:section("wireless", "wifi-iface", nil, {
mode = "sta",
network = trmiface,
device = m.hidden.device,
ssid = wssid:formvalue(section),
bssid = bssid:formvalue(section),
disabled = "1"
})
if (tonumber(m.hidden.wep) or 0) == 1 then
uci:set("wireless", newsection, "encryption", encr:formvalue(section))
uci:set("wireless", newsection, "key", wkey:formvalue(section) or "")
elseif (tonumber(m.hidden.wpa_version) or 0) > 0 then
if m.hidden.wpa_suites == "PSK" or m.hidden.wpa_suites == "PSK2" then
if ciph:formvalue(section) ~= "auto" then
uci:set("wireless", newsection, "encryption", encr:formvalue(section) .. "+" .. ciph:formvalue(section))
else
uci:set("wireless", newsection, "encryption", encr:formvalue(section))
end
uci:set("wireless", newsection, "key", wkey:formvalue(section) or "")
elseif m.hidden.wpa_suites == "802.1X" then
if ciph:formvalue(section) ~= "auto" then
uci:set("wireless", newsection, "encryption", encr:formvalue(section) .. "+" .. ciph:formvalue(section))
else
uci:set("wireless", newsection, "encryption", encr:formvalue(section))
end
uci:set("wireless", newsection, "eap_type", eaptype:formvalue(section))
uci:set("wireless", newsection, "auth", authentication:formvalue(section))
uci:set("wireless", newsection, "identity", ident:formvalue(section) or "")
uci:set("wireless", newsection, "password", wkey:formvalue(section) or "")
uci:set("wireless", newsection, "ca_cert", cacert:formvalue(section) or "")
uci:set("wireless", newsection, "client_cert", clientcert:formvalue(section) or "")
uci:set("wireless", newsection, "priv_key", privkey:formvalue(section) or "")
uci:set("wireless", newsection, "priv_key_pwd", privkeypwd:formvalue(section) or "")
end
else
uci:set("wireless", newsection, "encryption", "none")
end
uci:save("wireless")
uci:commit("wireless")
luci.sys.call("env -i /bin/ubus call network reload >/dev/null 2>&1")
http.redirect(luci.dispatcher.build_url("admin/services/travelmate/stations"))
end
return m
|
luci-app-travelmate: bring back cbi element to wifi_add.lua
|
luci-app-travelmate: bring back cbi element to wifi_add.lua
* b00b676 fixed the cbi initialization for SimpleForm, therefore bring
back "Ignore BSSID" flag with dependent input field
Signed-off-by: Dirk Brenken <[email protected]>
|
Lua
|
apache-2.0
|
kuoruan/lede-luci,kuoruan/lede-luci,981213/luci-1,hnyman/luci,nmav/luci,openwrt-es/openwrt-luci,lbthomsen/openwrt-luci,tobiaswaldvogel/luci,nmav/luci,rogerpueyo/luci,kuoruan/luci,nmav/luci,kuoruan/luci,hnyman/luci,chris5560/openwrt-luci,openwrt-es/openwrt-luci,rogerpueyo/luci,wongsyrone/luci-1,wongsyrone/luci-1,chris5560/openwrt-luci,kuoruan/luci,remakeelectric/luci,hnyman/luci,nmav/luci,lbthomsen/openwrt-luci,openwrt-es/openwrt-luci,lbthomsen/openwrt-luci,remakeelectric/luci,rogerpueyo/luci,openwrt/luci,kuoruan/luci,tobiaswaldvogel/luci,hnyman/luci,openwrt/luci,Noltari/luci,tobiaswaldvogel/luci,kuoruan/lede-luci,tobiaswaldvogel/luci,kuoruan/lede-luci,remakeelectric/luci,openwrt/luci,lbthomsen/openwrt-luci,wongsyrone/luci-1,artynet/luci,openwrt/luci,artynet/luci,kuoruan/luci,981213/luci-1,rogerpueyo/luci,chris5560/openwrt-luci,Noltari/luci,artynet/luci,981213/luci-1,981213/luci-1,artynet/luci,wongsyrone/luci-1,kuoruan/luci,artynet/luci,artynet/luci,981213/luci-1,Noltari/luci,wongsyrone/luci-1,openwrt-es/openwrt-luci,openwrt-es/openwrt-luci,hnyman/luci,remakeelectric/luci,nmav/luci,lbthomsen/openwrt-luci,chris5560/openwrt-luci,rogerpueyo/luci,remakeelectric/luci,chris5560/openwrt-luci,rogerpueyo/luci,Noltari/luci,wongsyrone/luci-1,981213/luci-1,rogerpueyo/luci,artynet/luci,kuoruan/lede-luci,wongsyrone/luci-1,hnyman/luci,nmav/luci,kuoruan/luci,tobiaswaldvogel/luci,remakeelectric/luci,rogerpueyo/luci,Noltari/luci,openwrt/luci,kuoruan/lede-luci,remakeelectric/luci,Noltari/luci,hnyman/luci,wongsyrone/luci-1,artynet/luci,tobiaswaldvogel/luci,981213/luci-1,hnyman/luci,lbthomsen/openwrt-luci,nmav/luci,tobiaswaldvogel/luci,kuoruan/lede-luci,kuoruan/lede-luci,chris5560/openwrt-luci,kuoruan/luci,lbthomsen/openwrt-luci,openwrt/luci,nmav/luci,lbthomsen/openwrt-luci,openwrt/luci,artynet/luci,nmav/luci,Noltari/luci,remakeelectric/luci,tobiaswaldvogel/luci,chris5560/openwrt-luci,openwrt-es/openwrt-luci,chris5560/openwrt-luci,openwrt-es/openwrt-luci,openwrt/luci,Noltari/luci,openwrt-es/openwrt-luci,Noltari/luci
|
7d486e88c2b3301449974e0e97168bc0f0fd6c64
|
xmake/rules/qt/moc.lua
|
xmake/rules/qt/moc.lua
|
--!A cross-platform build utility based on Lua
--
-- Licensed to the Apache Software Foundation (ASF) under one
-- or more contributor license agreements. See the NOTICE file
-- distributed with this work for additional information
-- regarding copyright ownership. The ASF licenses this file
-- to you under the Apache License, Version 2.0 (the
-- "License"); you may not use this file except in compliance
-- with the License. You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015 - 2018, TBOOX Open Source Group.
--
-- @author ruki
-- @file moc.lua
--
-- make flags from target
function _make_flags_from_target(target)
local flags = {}
for _, define in ipairs(target:get("defines")) do
table.insert(flags, "-D" .. define)
end
for _, includedir in ipairs(target:get("includedirs")) do
table.insert(flags, "-I" .. os.args(includedir))
end
for _, frameworkdir in ipairs(target:get("frameworkdirs")) do
table.insert(flags, "-F" .. os.args(frameworkdir))
end
return flags
end
-- make flags
function _make_flags(target)
-- attempt to get flags from cache first
local key = target:name()
local cache = _g._FLAGS or {}
if cache[key] then
return cache[key]
end
-- make flags
local flags = _make_flags_from_target(target)
-- save flags to cache
cache[key] = flags
_g._FLAGS = cache
-- done
return flags
end
-- generate c++ source file from header file with Q_OBJECT
function generate(target, headerfile_moc, sourcefile_moc)
-- get moc
local moc = assert(target:data("qt.moc"), "moc not found!")
-- ensure the parent directory of source file
local sourcefile_dir = path.directory(sourcefile_moc)
if not os.isdir(sourcefile_dir) then
os.mkdir(sourcefile_dir)
end
-- generate c++ source file for moc
local argv = _make_flags(target)
table.insert(argv, headerfile_moc)
table.insert(argv, "-o")
table.insert(argv, sourcefile_moc)
os.vrunv(moc, argv)
end
|
--!A cross-platform build utility based on Lua
--
-- Licensed to the Apache Software Foundation (ASF) under one
-- or more contributor license agreements. See the NOTICE file
-- distributed with this work for additional information
-- regarding copyright ownership. The ASF licenses this file
-- to you under the Apache License, Version 2.0 (the
-- "License"); you may not use this file except in compliance
-- with the License. You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015 - 2018, TBOOX Open Source Group.
--
-- @author ruki
-- @file moc.lua
--
-- make flags from target
function _make_flags_from_target(target)
local flags = {}
for _, define in ipairs(target:get("defines")) do
table.insert(flags, "-D" .. define)
end
for _, includedir in ipairs(target:get("includedirs")) do
table.insert(flags, "-I" .. os.args(includedir))
end
for _, frameworkdir in ipairs(target:get("frameworkdirs")) do
table.insert(flags, "-F" .. os.args(frameworkdir))
end
return flags
end
-- make flags
function _make_flags(target)
-- attempt to get flags from cache first
local key = target:name()
local cache = _g._FLAGS or {}
if cache[key] then
return cache[key]
end
-- make flags
local flags = _make_flags_from_target(target)
-- save flags to cache
cache[key] = flags
_g._FLAGS = cache
-- done
return flags
end
-- generate c++ source file from header file with Q_OBJECT
function generate(target, headerfile_moc, sourcefile_moc)
-- get moc
local moc = assert(target:data("qt.moc"), "moc not found!")
-- ensure the parent directory of source file
local sourcefile_dir = path.directory(sourcefile_moc)
if not os.isdir(sourcefile_dir) then
os.mkdir(sourcefile_dir)
end
-- generate c++ source file for moc
os.vrunv(moc, table.join(_make_flags(target), headerfile_moc, "-o", sourcefile_moc))
end
|
fix moc bug
|
fix moc bug
|
Lua
|
apache-2.0
|
tboox/xmake,tboox/xmake,tboox/xmake,tboox/xmake,tboox/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,tboox/xmake,waruqi/xmake,waruqi/xmake,tboox/xmake
|
1ba1717e76f402b561bae0ab0e56fa6e7b605941
|
wyx/event/EventManager.lua
|
wyx/event/EventManager.lua
|
local Class = require 'lib.hump.class'
-- EventManager
-- Provides a class that registers objects with itself, then notifies
-- those object when events occur.
local Event = getClass 'wyx.event.Event'
local eventsMT = {__mode = 'k'}
local format = string.format
-- EventManager class
local EventManager = Class{name='EventManager',
function(self, name)
name = name or 'EventManager'
verify('string', name)
self._name = name
self._events = {}
end
}
-- validate that the given object is an object or a function
local _validateObj = function(obj)
assert(obj and (type(obj) == 'table' or type(obj) == 'function'),
'expected an object or function (was %s)', type(obj))
end
-- destructor
function EventManager:destroy()
self:clear()
for k,v in pairs(self._events) do
for l,w in pairs(self._events[k]) do
self._events[k][l] = nil
end
self._events[k] = nil
end
self._events = nil
if self._unregisterQueue then self:_unregisterPending() end
self._name = nil
self._lastDebugMsg = nil
self._lastDebugRepeat = nil
self._debug = nil
end
-- register an object to listen for the given events
-- obj can be:
-- a function
-- an object with a method that has the same name as the event
-- an object with an onEvent method
function EventManager:register(obj, events)
_validateObj(obj)
verify('table', events)
if events.is_a then events = {events} end
self._registerQueue = self._registerQueue or {}
self._registerQueue[obj] = events
if not self._notifying then self:_registerPending() end
end
-- unregister an object from listening for the given events
function EventManager:unregister(obj, events)
_validateObj(obj)
verify('table', events)
if events.is_a then events = {events} end
self._unregisterQueue = self._unregisterQueue or {}
self._unregisterQueue[obj] = events
if not self._notifying then self:_unregisterPending() end
end
-- register an object for all events
function EventManager:registerAll(obj)
self:register(obj, Event:getAllEvents())
end
-- unregister an object from all events
function EventManager:unregisterAll(obj)
local events = self:getRegisteredEvents(obj)
if events then self:unregister(obj, events) end
end
-- return a list of events for which obj is registered
function EventManager:getRegisteredEvents(obj)
_validateObj(obj)
local events = {}
for event,objs in pairs(self._events) do
if objs[obj] then
events[#events+1] = event
end
end
return #events > 0 and events or nil
end
function EventManager:_registerPending()
if self._registerQueue then
for obj,events in pairs(self._registerQueue) do
local hasOnEvent = type(obj) == 'function'
or (type(obj) == 'table'
and obj.onEvent
and type(obj.onEvent) == 'function')
for _,event in ipairs(events) do
verifyClass(Event, event)
local keyStr = tostring(event:getEventKey())
assert(hasOnEvent or (obj[keyStr] and type(obj[keyStr]) == 'function'),
'object "%s" is missing event callback method for event "%s"',
tostring(obj), keyStr)
local key = event:getEventKey()
-- event table has weak keys
self._events[key] = self._events[key] or setmetatable({}, eventsMT)
self._events[key][obj] = true
end
self._registerQueue[obj] = nil
end
self._registerQueue = nil
end
end
function EventManager:_unregisterPending()
if self._unregisterQueue then
for obj,events in pairs(self._unregisterQueue) do
for _,event in ipairs(events) do
verifyClass(Event, event)
local key = event:getEventKey()
if self._events[key] and self._events[key][obj] then
self._events[key][obj] = nil
end
end
self._unregisterQueue[obj] = nil
end
self._unregisterQueue = nil
end
end
-- notify a specific event, notifying all listeners of the event.
function EventManager:notify(event)
verifyClass(Event, event)
self._notifying = true
local key = event:getEventKey()
if self._events[key] then
for obj in pairs(self._events[key]) do
if self._debug then
local eventLevel = event:getDebugLevel()
if eventLevel <= self._debug then
local mgr = tostring(self)
local eventstr = tostring(event)
local objstr = tostring(obj.__class or obj)
local msg = format('[%s@%s] %s', mgr, objstr, eventstr)
if self._lastDebugMsg ~= msg then
if self._lastDebugRepeat and self._lastDebugRepeat > 0 then
local m = format('(Last message repeated %d times.)',
self._lastDebugRepeat)
if Console then Console:print(m) end
print(m)
end
self._lastDebugMsg = msg
self._lastDebugRepeat = 0
if Console then Console:print(msg) end
print(msg)
else
self._lastDebugRepeat = self._lastDebugRepeat + 1
end
end
end
if type(obj) == 'function' then -- function()
obj(event)
else
local keyStr = tostring(event:getEventKey())
if obj[keyStr] then obj[keyStr](obj, event) end -- obj:NamedEvent()
if obj.onEvent then obj:onEvent(event) end -- obj:onEvent()
end
end
end
self:_registerPending()
self:_unregisterPending()
self._notifying = false
event:destroy()
end
-- push an event into the event queue
function EventManager:push(event)
verifyClass(Event, event)
self._queue = self._queue or {}
self._queue[#self._queue + 1] = event
end
-- flush all events in the event queue and notify their listeners
function EventManager:flush()
if self._queue then
-- copy the queue to a local table in case notifying an event pushes
-- more events on the queue
local queue = {}
for i,event in ipairs(self._queue) do
queue[i] = event
self._queue[i] = nil
end
self._queue = nil
-- iterate through the copy of the queue and notify events
for _,event in ipairs(queue) do
self:notify(event)
end
end
if not self._notifying then self:_unregisterPending() end
end
-- remove all events in the queue without notifying listeners
function EventManager:clear()
if self._queue then
local num = #self._queue
for i=1,num do
self._queue[i] = nil
end
self._queue = nil
end
if not self._notifying then self:_unregisterPending() end
end
function EventManager:debug(level)
verify('number', level)
self._debug = level
end
function EventManager:__tostring() return self._name end
-- the module
return EventManager
|
local Class = require 'lib.hump.class'
-- EventManager
-- Provides a class that registers objects with itself, then notifies
-- those object when events occur.
local Event = getClass 'wyx.event.Event'
local eventsMT = {__mode = 'k'}
local format = string.format
-- EventManager class
local EventManager = Class{name='EventManager',
function(self, name)
name = name or 'EventManager'
verify('string', name)
self._name = name
self._events = {}
end
}
-- validate that the given object is an object or a function
local _validateObj = function(obj)
assert(obj and (type(obj) == 'table' or type(obj) == 'function'),
'expected an object or function (was %s)', type(obj))
end
-- destructor
function EventManager:destroy()
if self._registerQueue then self:_registerPending() end
if self._unregisterQueue then self:_unregisterPending() end
self:clear()
for k,v in pairs(self._events) do
for l,w in pairs(self._events[k]) do
self._events[k][l] = nil
end
self._events[k] = nil
end
self._events = nil
self._name = nil
self._lastDebugMsg = nil
self._lastDebugRepeat = nil
self._debug = nil
end
-- register an object to listen for the given events
-- obj can be:
-- a function
-- an object with a method that has the same name as the event
-- an object with an onEvent method
function EventManager:register(obj, events)
_validateObj(obj)
verify('table', events)
if events.is_a then events = {events} end
self._registerQueue = self._registerQueue or {}
self._registerQueue[obj] = events
if not self._notifying then self:_registerPending() end
end
-- unregister an object from listening for the given events
function EventManager:unregister(obj, events)
_validateObj(obj)
verify('table', events)
if events.is_a then events = {events} end
self._unregisterQueue = self._unregisterQueue or {}
self._unregisterQueue[obj] = events
if not self._notifying then self:_unregisterPending() end
end
-- register an object for all events
function EventManager:registerAll(obj)
self:register(obj, Event:getAllEvents())
end
-- unregister an object from all events
function EventManager:unregisterAll(obj)
local events = self:getRegisteredEvents(obj)
if events then self:unregister(obj, events) end
end
-- return a list of events for which obj is registered
function EventManager:getRegisteredEvents(obj)
_validateObj(obj)
local events = {}
for event,objs in pairs(self._events) do
if objs[obj] then
events[#events+1] = event
end
end
return #events > 0 and events or nil
end
function EventManager:_registerPending()
if self._registerQueue then
for obj,events in pairs(self._registerQueue) do
local hasOnEvent = type(obj) == 'function'
or (type(obj) == 'table'
and obj.onEvent
and type(obj.onEvent) == 'function')
for _,event in ipairs(events) do
verifyClass(Event, event)
local keyStr = tostring(event:getEventKey())
assert(hasOnEvent or (obj[keyStr] and type(obj[keyStr]) == 'function'),
'object "%s" is missing event callback method for event "%s"',
tostring(obj), keyStr)
local key = event:getEventKey()
-- event table has weak keys
self._events[key] = self._events[key] or setmetatable({}, eventsMT)
self._events[key][obj] = true
end
self._registerQueue[obj] = nil
end
self._registerQueue = nil
end
end
function EventManager:_unregisterPending()
if self._unregisterQueue then
for obj,events in pairs(self._unregisterQueue) do
for _,event in ipairs(events) do
verifyClass(Event, event)
local key = event:getEventKey()
if self._events[key] and self._events[key][obj] then
self._events[key][obj] = nil
end
end
self._unregisterQueue[obj] = nil
end
self._unregisterQueue = nil
end
end
-- notify a specific event, notifying all listeners of the event.
function EventManager:notify(event)
verifyClass(Event, event)
self._notifying = true
local key = event:getEventKey()
if self._events[key] then
for obj in pairs(self._events[key]) do
if self._debug then
local eventLevel = event:getDebugLevel()
if eventLevel <= self._debug then
local mgr = tostring(self)
local eventstr = tostring(event)
local objstr = tostring(obj.__class or obj)
local msg = format('[%s->%s] %s', mgr, objstr, eventstr)
if self._lastDebugMsg ~= msg then
if self._lastDebugRepeat and self._lastDebugRepeat > 0 then
local m = format('(Last message repeated %d times.)',
self._lastDebugRepeat)
if Console then Console:print(m) end
print(m)
end
self._lastDebugMsg = msg
self._lastDebugRepeat = 0
if Console then Console:print(msg) end
print(msg)
else
self._lastDebugRepeat = self._lastDebugRepeat + 1
end
end
end
if type(obj) == 'function' then -- function()
obj(event)
else
local keyStr = tostring(event:getEventKey())
if obj[keyStr] then obj[keyStr](obj, event) end -- obj:NamedEvent()
if obj.onEvent then obj:onEvent(event) end -- obj:onEvent()
end
if not self._notifying then break end
end -- for obj in pairs(self._events[key])
end -- if self._events[key]
self:_registerPending()
self:_unregisterPending()
self._notifying = false
event:destroy()
end
-- push an event into the event queue
function EventManager:push(event)
verifyClass(Event, event)
self._queue = self._queue or {}
self._queue[#self._queue + 1] = event
end
-- flush all events in the event queue and notify their listeners
function EventManager:flush()
if self._queue then
-- copy the queue to a local table in case notifying an event pushes
-- more events on the queue
local queue = {}
for i,event in ipairs(self._queue) do
queue[i] = event
self._queue[i] = nil
end
self._queue = nil
-- iterate through the copy of the queue and notify events
for _,event in ipairs(queue) do
self:notify(event)
end
end
end
-- remove all events in the queue without notifying listeners
function EventManager:clear()
if self._queue then
local num = #self._queue
for i=1,num do
self._queue[i] = nil
end
self._queue = nil
end
self._notifying = false
end
function EventManager:debug(level)
verify('number', level)
self._debug = level
end
function EventManager:__tostring() return self._name end
-- the module
return EventManager
|
fix EventManager to stop notifying if cleared
|
fix EventManager to stop notifying if cleared
|
Lua
|
mit
|
scottcs/wyx
|
54b5071df907b8c9d35a0ec356c673701a3c6025
|
packages/parallel/init.lua
|
packages/parallel/init.lua
|
local base = require("packages.base")
local package = pl.class(base)
package._name = "parallel"
local typesetterPool = {}
local calculations = {}
local folioOrder = {}
local allTypesetters = function (callback)
local oldtypesetter = SILE.typesetter
for frame, typesetter in pairs(typesetterPool) do
SILE.typesetter = typesetter
callback(frame, typesetter)
end
SILE.typesetter = oldtypesetter
end
local nulTypesetter = pl.class(SILE.defaultTypesetter) -- we ignore this
nulTypesetter.outputLinesToPage = function () end
local parallelPagebreak = function ()
for i = 1, #folioOrder do
local thisPageFrames = folioOrder[i]
for j = 1, #thisPageFrames do
local frame = thisPageFrames[j]
local typesetter = typesetterPool[frame]
local thispage = {}
SU.debug("parallel", "Dumping lines for page on typesetter "..typesetter.id)
if #typesetter.state.outputQueue > 0 and calculations[frame].mark == 0 then
-- More than one page worth of stuff here.
-- Just ship out one page and hope for the best.
SILE.defaultTypesetter.buildPage(typesetter)
else
for l = 1, calculations[frame].mark do
thispage[l] = table.remove(typesetter.state.outputQueue, 1)
SU.debug("parallel", thispage[l])
end
typesetter:outputLinesToPage(thispage)
end
end
SILE.documentState.documentClass:endPage()
for l = 1, #thisPageFrames do
local frame = thisPageFrames[l]
local typesetter = typesetterPool[frame]
typesetter:initFrame(typesetter.frame)
end
SILE.documentState.documentClass:newPage()
end
end
local addBalancingGlue = function (height)
allTypesetters(function (frame, typesetter)
local glue = height - calculations[frame].heightOfNewMaterial
if glue.length:tonumber() > 0 then
SU.debug("parallel", "Adding " .. tostring(glue) .. " to " .. tostring(frame))
typesetter:pushVglue({ height = glue })
end
calculations[frame].mark = #typesetter.state.outputQueue
end)
end
function package:_init (options)
base._init(self, options)
SILE.typesetter = nulTypesetter(SILE.getFrame("page"))
for frame, typesetter in pairs(options.frames) do
typesetterPool[frame] = SILE.defaultTypesetter(SILE.getFrame(typesetter))
typesetterPool[frame].id = typesetter
typesetterPool[frame].buildPage = function ()
-- No thank you, I will do that.
end
-- Fixed leading here is obviously a bug, but n-way leading calculations
-- get very complicated...
-- typesetterPool[frame].leadingFor = function() return SILE.nodefactory.vglue(SILE.settings:get("document.lineskip")) end
self:registerCommand(frame, function (_, _) -- \left ...
SILE.typesetter = typesetterPool[frame]
SILE.call(frame..":font")
end)
self:registerCommand(frame..":font", function (_, _) end) -- to be overridden
end
if not options.folios then
folioOrder = { {} }
-- Note output order doesn't matter for PDF, but for our test suite it is
-- essential that the output order is deterministic, hence this sort()
for frame, _ in pl.tablex.sort(options.frames) do table.insert(folioOrder[1], frame) end
else
folioOrder = options.folios -- As usual we trust the user knows what they're doing
end
self.class.newPage = function(self_)
allTypesetters(function (frame, _)
calculations[frame] = { mark = 0 }
end)
self.class._base.newPage(self_)
SILE.call("sync")
end
allTypesetters(function (frame, _) calculations[frame] = { mark = 0 } end)
local oldfinish = self.class.finish
self.class.finish = function (self_)
parallelPagebreak()
oldfinish(self_)
end
end
function package:registerCommands ()
self:registerCommand("sync", function (_, _)
local anybreak = false
local maxheight = SILE.length()
SU.debug("parallel", "Trying a sync")
allTypesetters(function (_, typesetter)
SU.debug("parallel", "Leaving hmode on "..typesetter.id)
typesetter:leaveHmode(true)
-- Now we have each typesetter's content boxed up onto the output stream
-- but page breaking has not been run. See if page breaking would cause a
-- break
local lines = pl.tablex.copy(typesetter.state.outputQueue)
if SILE.pagebuilder:findBestBreak({ vboxlist = lines, target = typesetter:getTargetLength() }) then
anybreak = true
end
end)
if anybreak then
parallelPagebreak()
return
end
allTypesetters(function (frame, typesetter)
calculations[frame].heightOfNewMaterial = SILE.length()
for i = calculations[frame].mark + 1, #typesetter.state.outputQueue do
local thisHeight = typesetter.state.outputQueue[i].height + typesetter.state.outputQueue[i].depth
calculations[frame].heightOfNewMaterial = calculations[frame].heightOfNewMaterial + thisHeight
end
if maxheight < calculations[frame].heightOfNewMaterial then maxheight = calculations[frame].heightOfNewMaterial end
SU.debug("parallel", frame .. ": pre-sync content=" .. calculations[frame].mark .. ", now " .. #typesetter.state.outputQueue .. ", height of material: " .. tostring(calculations[frame].heightOfNewMaterial))
end)
addBalancingGlue(maxheight)
end)
end
package.documentation = [[
\begin{document}
The \autodoc:package{parallel} package provides the mechanism for typesetting diglot or other parallel documents.
When used by a class such as \code{classes/diglot.lua}, it registers a command for each parallel frame, to allow you to select which frame you’re typesetting into.
It also defines the \autodoc:command{\sync} command, which adds vertical spacing to each frame such that the \em{next} set of text is vertically aligned.
See \url{https://sile-typesetter.org/examples/parallel.sil} and the source of \code{classes/diglot.lua} for examples which makes the operation clear.
\end{document}
]]
return package
|
local base = require("packages.base")
local package = pl.class(base)
package._name = "parallel"
local typesetterPool = {}
local calculations = {}
local folioOrder = {}
local allTypesetters = function (callback)
local oldtypesetter = SILE.typesetter
for frame, typesetter in pairs(typesetterPool) do
SILE.typesetter = typesetter
callback(frame, typesetter)
end
SILE.typesetter = oldtypesetter
end
local nulTypesetter = pl.class(SILE.defaultTypesetter) -- we ignore this
nulTypesetter.outputLinesToPage = function () end
local parallelPagebreak = function ()
for i = 1, #folioOrder do
local thisPageFrames = folioOrder[i]
for j = 1, #thisPageFrames do
local frame = thisPageFrames[j]
local typesetter = typesetterPool[frame]
local thispage = {}
SU.debug("parallel", "Dumping lines for page on typesetter "..typesetter.id)
if #typesetter.state.outputQueue > 0 and calculations[frame].mark == 0 then
-- More than one page worth of stuff here.
-- Just ship out one page and hope for the best.
SILE.defaultTypesetter.buildPage(typesetter)
else
for l = 1, calculations[frame].mark do
thispage[l] = table.remove(typesetter.state.outputQueue, 1)
SU.debug("parallel", thispage[l])
end
typesetter:outputLinesToPage(thispage)
end
end
SILE.documentState.documentClass:endPage()
for l = 1, #thisPageFrames do
local frame = thisPageFrames[l]
local typesetter = typesetterPool[frame]
typesetter:initFrame(typesetter.frame)
end
SILE.documentState.documentClass:newPage()
end
end
local addBalancingGlue = function (height)
allTypesetters(function (frame, typesetter)
local glue = height - calculations[frame].heightOfNewMaterial
if glue.length:tonumber() > 0 then
SU.debug("parallel", "Adding " .. tostring(glue) .. " to " .. tostring(frame))
typesetter:pushVglue({ height = glue })
end
calculations[frame].mark = #typesetter.state.outputQueue
end)
end
function package:_init (options)
base._init(self, options)
SILE.typesetter = nulTypesetter(SILE.getFrame("page"))
for frame, typesetter in pairs(options.frames) do
typesetterPool[frame] = SILE.defaultTypesetter(SILE.getFrame(typesetter))
typesetterPool[frame].id = typesetter
typesetterPool[frame].buildPage = function ()
-- No thank you, I will do that.
end
-- Fixed leading here is obviously a bug, but n-way leading calculations
-- get very complicated...
-- typesetterPool[frame].leadingFor = function() return SILE.nodefactory.vglue(SILE.settings:get("document.lineskip")) end
local fontcommand = frame .. ":font"
self:registerCommand(frame, function (_, _) -- \left ...
SILE.typesetter = typesetterPool[frame]
SILE.call(fontcommand)
end)
if not SILE.Commands[fontcommand] then
self:registerCommand(fontcommand, function (_, _) end) -- to be overridden
end
end
if not options.folios then
folioOrder = { {} }
-- Note output order doesn't matter for PDF, but for our test suite it is
-- essential that the output order is deterministic, hence this sort()
for frame, _ in pl.tablex.sort(options.frames) do table.insert(folioOrder[1], frame) end
else
folioOrder = options.folios -- As usual we trust the user knows what they're doing
end
self.class.newPage = function(self_)
allTypesetters(function (frame, _)
calculations[frame] = { mark = 0 }
end)
self.class._base.newPage(self_)
SILE.call("sync")
end
allTypesetters(function (frame, _) calculations[frame] = { mark = 0 } end)
local oldfinish = self.class.finish
self.class.finish = function (self_)
parallelPagebreak()
oldfinish(self_)
end
end
function package:registerCommands ()
self:registerCommand("sync", function (_, _)
local anybreak = false
local maxheight = SILE.length()
SU.debug("parallel", "Trying a sync")
allTypesetters(function (_, typesetter)
SU.debug("parallel", "Leaving hmode on "..typesetter.id)
typesetter:leaveHmode(true)
-- Now we have each typesetter's content boxed up onto the output stream
-- but page breaking has not been run. See if page breaking would cause a
-- break
local lines = pl.tablex.copy(typesetter.state.outputQueue)
if SILE.pagebuilder:findBestBreak({ vboxlist = lines, target = typesetter:getTargetLength() }) then
anybreak = true
end
end)
if anybreak then
parallelPagebreak()
return
end
allTypesetters(function (frame, typesetter)
calculations[frame].heightOfNewMaterial = SILE.length()
for i = calculations[frame].mark + 1, #typesetter.state.outputQueue do
local thisHeight = typesetter.state.outputQueue[i].height + typesetter.state.outputQueue[i].depth
calculations[frame].heightOfNewMaterial = calculations[frame].heightOfNewMaterial + thisHeight
end
if maxheight < calculations[frame].heightOfNewMaterial then maxheight = calculations[frame].heightOfNewMaterial end
SU.debug("parallel", frame .. ": pre-sync content=" .. calculations[frame].mark .. ", now " .. #typesetter.state.outputQueue .. ", height of material: " .. tostring(calculations[frame].heightOfNewMaterial))
end)
addBalancingGlue(maxheight)
end)
end
package.documentation = [[
\begin{document}
The \autodoc:package{parallel} package provides the mechanism for typesetting diglot or other parallel documents.
When used by a class such as \code{classes/diglot.lua}, it registers a command for each parallel frame, to allow you to select which frame you’re typesetting into.
It also defines the \autodoc:command{\sync} command, which adds vertical spacing to each frame such that the \em{next} set of text is vertically aligned.
See \url{https://sile-typesetter.org/examples/parallel.sil} and the source of \code{classes/diglot.lua} for examples which makes the operation clear.
\end{document}
]]
return package
|
fix(packages): Check for user supplied commands before setting noops
|
fix(packages): Check for user supplied commands before setting noops
Blindly setting a dummy command "to be overridden" by the user without
checking if they already set one first is very frustrating to use. In
particular it makes it very hard to write a class that provides these
commands because class init stuff happens before package init stuff.
|
Lua
|
mit
|
alerque/sile,alerque/sile,alerque/sile,alerque/sile
|
a0eb7a42b9ba93338a076d74530aabe5dda493cb
|
demos/8vb/main.lua
|
demos/8vb/main.lua
|
-- 8vb
-- A shooter game to demo Modipulate
require('modipulate')
require('AnAL')
-- Constants
Direction = {
NONE = 0,
LEFT = 1,
RIGHT = 2
}
SHIP_SPEED = 4
ENEMY_SPEED = 4
LASER_SPEED = 6
LOW_NOTE = 50
HIGH_NOTE = 70
EVIL_INSTRUMENT = 2
-- Direction we're moving in.
dir = Direction.NONE
---- Modipulate callbacks
function love.load()
-- Modipulate
modipulate.load(true)
modipulate.open_file('../media/sponge1.it')
modipulate.set_on_note_changed(note_changed)
modipulate.set_on_pattern_changed(pattern_changed)
modipulate.set_on_row_changed(row_changed)
modipulate.set_on_tempo_changed(tempo_changed)
-- Graphics
imgs = {}
imgs.bat = love.graphics.newImage('gfx/bat.png')
imgs.mouse = love.graphics.newImage('gfx/mouse.png')
imgs.laser = love.graphics.newImage('gfx/laser.png')
-- List of enemies
enemies = {}
-- List of lasers
lasers = {}
-- The ship
ship = {}
ship.anim = newAnimation(imgs.bat, 32, 20, 0.125, 0)
ship.w = ship.anim:getWidth()
ship.h = ship.anim:getHeight()
ship.x = love.graphics.getWidth() / 2
ship.y = love.graphics.getHeight() - ship.h * 2
-- Font
love.graphics.setFont('Courier_New.ttf', 12)
end
----
function love.quit()
modipulate.quit()
end
----
function love.update(dt)
modipulate.update(dt)
-- Update animations
ship.anim:update(dt)
for i,enemy in ipairs(enemies) do
enemy.anim:update(dt)
end
-- Move ship
if dir == Direction.LEFT then
if ship.x > ship.w then
ship.x = ship.x - SHIP_SPEED * dt * 50
end
elseif dir == Direction.RIGHT then
if ship.x < love.graphics.getWidth() - ship.w then
ship.x = ship.x + SHIP_SPEED * dt * 50
end
end
-- Move enemies
for i,enemy in ipairs(enemies) do
enemy.y = enemy.y + ENEMY_SPEED * dt * 50
end
-- Move lasers
for i, laser in ipairs(lasers) do
laser.y = laser.y + LASER_SPEED * dt * 50
end
end
----
function love.keypressed(k)
if k == 'escape' or k == 'q' then
love.event.push('q')
elseif k == 'left' then
dir = Direction.LEFT
elseif k == 'right' then
dir = Direction.RIGHT
end
end
----
function love.keyreleased(k)
if k == 'left' then
if love.keyboard.isDown('right') then
dir = Direction.RIGHT
else
dir = Direction.NONE
end
elseif k == 'right' then
if love.keyboard.isDown('left') then
dir = Direction.LEFT
else
dir = Direction.NONE
end
end
end
----
function love.draw()
-- Background
love.graphics.setBackgroundColor(0xa0, 0xa0, 0xa0)
-- Reset foreground
love.graphics.setColor(0xff, 0xff, 0xff, 0xff)
-- Draw lasers
for i,laser in ipairs(lasers) do
laser.anim:draw(laser.x, laser.y, 0, 1, 1, laser.w / 2, laser.h / 2)
end
-- Draw enemies
for i,enemy in ipairs(enemies) do
enemy.anim:draw(enemy.x, enemy.y, 0, 1, 1, enemy.w / 2, enemy.h / 2)
end
-- Draw ship
ship.anim:draw(ship.x, ship.y, 0, 1, 1, ship.w / 2, ship.h / 2)
-- Debug
love.graphics.setColor(0x40, 0x40, 0x40)
love.graphics.print('Active animations\n'
.. ' Enemies: ' #enemies
.. ' Lasers: ' #lasers, 10, 10)
end
---- Modipulate callbacks
function note_changed(channel, note, instrument, sample, volume)
if sample == EVIL_INSTRUMENT then
local a = newAnimation(imgs.mouse, 24, 44, 0.1, 0)
local x = ----> TODO - Use LOW_NOTE and HIGH_NOTE
if x < 0 then
x = 0
elseif x > love.graphics.getWidth() then
x = love.graphics.getWidth()
end
local w = a:getWidth()
local h = a:getHeight()
table.insert(enemies, {anim = a, x = x, y = 0, w = w, h = h})
end
end
----
function pattern_changed(pattern)
-- Take a sec to clean up dead anims
if #enemies == 0 and #lasers == 0 then
return
end
local dirty = true
while dirty do
dirty = false
--print('checking enemy ' .. i)
--print('y = ' .. enemies[i].y)
for i,enemy in ipairs(enemies) do
if enemies[i].y > love.graphics.getHeight() + 50 then
--print('deleting...')
table.remove(enemies, i)
dirty = true
break
end
end
end
end
----
function row_changed(row)
if row % 4 == 0 then
-- Make a new laser instance
local a = newAnimation(imgs.laser, 2, 12, 0.08, 0)
table.insert(lasers, {anim = a, x = ship.x, y = ship.y, w = 2, h = 12})
end
end
----
function tempo_changed(tempo)
end
|
-- 8vb
-- A shooter game to demo Modipulate
require('modipulate')
require('AnAL')
-- Constants
Direction = {
NONE = 0,
LEFT = 1,
RIGHT = 2
}
SHIP_SPEED = 4
ENEMY_SPEED = 4
LASER_SPEED = 6
LOW_NOTE = 85
HIGH_NOTE = 92
EVIL_INSTRUMENT = 2
-- Direction we're moving in.
dir = Direction.NONE
---- Modipulate callbacks
function love.load()
-- Modipulate
modipulate.load(true)
modipulate.open_file('../media/sponge1.it')
modipulate.set_on_note_changed(note_changed)
modipulate.set_on_pattern_changed(pattern_changed)
modipulate.set_on_row_changed(row_changed)
modipulate.set_on_tempo_changed(tempo_changed)
-- Graphics
imgs = {}
imgs.bat = love.graphics.newImage('gfx/bat.png')
imgs.mouse = love.graphics.newImage('gfx/mouse.png')
imgs.laser = love.graphics.newImage('gfx/laser.png')
-- List of enemies
enemies = {}
-- List of lasers
lasers = {}
-- The ship
ship = {}
ship.anim = newAnimation(imgs.bat, 32, 20, 0.125, 0)
ship.w = ship.anim:getWidth()
ship.h = ship.anim:getHeight()
ship.x = love.graphics.getWidth() / 2
ship.y = love.graphics.getHeight() - ship.h * 2
-- Font
love.graphics.setFont('Courier_New.ttf', 12)
end
----
function love.quit()
modipulate.quit()
end
----
function love.update(dt)
modipulate.update(dt)
-- Update animations
ship.anim:update(dt)
for i,enemy in ipairs(enemies) do
enemy.anim:update(dt)
end
-- Move ship
if dir == Direction.LEFT then
if ship.x > ship.w then
ship.x = ship.x - SHIP_SPEED * dt * 50
end
elseif dir == Direction.RIGHT then
if ship.x < love.graphics.getWidth() - ship.w then
ship.x = ship.x + SHIP_SPEED * dt * 50
end
end
-- Move enemies
for i,enemy in ipairs(enemies) do
enemy.y = enemy.y + ENEMY_SPEED * dt * 50
end
-- Move lasers
for i, laser in ipairs(lasers) do
laser.y = laser.y + LASER_SPEED * dt * 50
end
end
----
function love.keypressed(k)
if k == 'escape' or k == 'q' then
love.event.push('q')
elseif k == 'left' then
dir = Direction.LEFT
elseif k == 'right' then
dir = Direction.RIGHT
end
end
----
function love.keyreleased(k)
if k == 'left' then
if love.keyboard.isDown('right') then
dir = Direction.RIGHT
else
dir = Direction.NONE
end
elseif k == 'right' then
if love.keyboard.isDown('left') then
dir = Direction.LEFT
else
dir = Direction.NONE
end
end
end
----
function love.draw()
-- Background
love.graphics.setBackgroundColor(0xa0, 0xa0, 0xa0)
-- Reset foreground
love.graphics.setColor(0xff, 0xff, 0xff, 0xff)
-- Draw lasers
for i,laser in ipairs(lasers) do
laser.anim:draw(laser.x, laser.y, 0, 1, 1, laser.w / 2, laser.h / 2)
end
-- Draw enemies
for i,enemy in ipairs(enemies) do
enemy.anim:draw(enemy.x, enemy.y, 0, 1, 1, enemy.w / 2, enemy.h / 2)
end
-- Draw ship
ship.anim:draw(ship.x, ship.y, 0, 1, 1, ship.w / 2, ship.h / 2)
-- Debug
love.graphics.setColor(0x40, 0x40, 0x40)
love.graphics.print('Active animations\n'
.. ' Enemies: ' #enemies
.. ' Lasers: ' #lasers, 10, 10)
end
---- Modipulate callbacks
function note_changed(channel, note, instrument, sample, volume)
if sample == EVIL_INSTRUMENT then
local a = newAnimation(imgs.mouse, 24, 44, 0.1, 0)
-- Adjust note value
if note > HIGH_NOTE then
note = HIGH_NOTE
elseif note < LOW_NOTE then
note = LOW_NOTE
end;
local p = ((note - LOW_NOTE) / (HIGH_NOTE - LOW_NOTE)) -- percentage
local x = p * love.graphics.getWidth() + 15 -- add an adjustment to keep 'em on screen.
if x < 0 then
x = 0
elseif x > love.graphics.getWidth() then
x = love.graphics.getWidth()
end
local w = a:getWidth()
local h = a:getHeight()
table.insert(enemies, {anim = a, x = x, y = 0, w = w, h = h})
end
end
----
function pattern_changed(pattern)
-- Take a sec to clean up dead anims
if #enemies == 0 and #lasers == 0 then
return
end
local dirty = true
while dirty do
dirty = false
--print('checking enemy ' .. i)
--print('y = ' .. enemies[i].y)
for i,enemy in ipairs(enemies) do
if enemies[i].y > love.graphics.getHeight() + 50 then
--print('deleting...')
table.remove(enemies, i)
dirty = true
break
end
end
end
end
----
function row_changed(row)
if row % 4 == 0 then
-- Make a new laser instance
local a = newAnimation(imgs.laser, 2, 12, 0.08, 0)
table.insert(lasers, {anim = a, x = ship.x, y = ship.y, w = 2, h = 12})
end
end
----
function tempo_changed(tempo)
end
|
Fixed minor conflict... ?
|
Fixed minor conflict... ?
|
Lua
|
bsd-3-clause
|
MrEricSir/Modipulate,MrEricSir/Modipulate
|
820121252fe99212f366940dd51b851b8991bd8f
|
AceComm-3.0/AceComm-3.0.lua
|
AceComm-3.0/AceComm-3.0.lua
|
--[[ $Id$ ]]
--[[ AceComm-3.0 proof-of-concept
]]
local MAJOR, MINOR = "AceComm-3.0", 0
local AceComm, oldminor = LibStub:NewLibrary(MAJOR, MINOR)
if not AceComm then return end
local CallbackHandler = LibStub:GetLibrary("CallbackHandler-1.0")
local CTL = ChatThrottleLib
local single_prio = "NORMAL"
local multipart_prio = "BULK"
local pairs = pairs
local ceil = math.ceil
local strsub = string.sub
AceComm.frame = AceComm.frame or CreateFrame("Frame", "AceComm30Frame")
AceComm.embeds = AceComm.embeds or {}
AceComm.__incomplete_data = AceComm.__incomplete_data or {}
AceComm.__prefixes = AceComm.__prefixes or {}
AceComm.__original_prefix = AceComm.__original_prefix or {}
----------------------------------------
-- abbreviated prefix metadata for quick lookup in CHAT_MSG_ADDON
----------------------------------------
local message_types = {
["\001A"] = "multipart_begin",
["\001B"] = "multipart_continue",
["\001C"] = "multipart_end",
}
local message_type_rev = {
["multipart_begin"] = "\001A",
["multipart_continue"] = "\001B",
["multipart_end"] = "\001C",
}
----------------------------------------
-- Callbacks
----------------------------------------
if not AceComm.callbacks then
-- ensure that 'prefix to watch' table is consistent with registered
-- callbacks
AceComm.__prefixes = {}
function AceComm:PrefixUsed(prefix)
local prefixes = self.__prefixes
local original_prefix = self.__original_prefix
prefixes[prefix] = true
for k, v in pairs(message_types) do
local p = prefix .. k
prefixes[p] = v
original_prefix[p] = prefix
end
end
function AceComm:PrefixUnused(prefix)
local prefixes = self.__prefixes
local original_prefix = self.__original_prefix
prefixes[prefix] = nil
for k, v in pairs(message_types) do
local p = prefix .. k
prefixes[p] = nil
original_prefix[p] = nil
end
end
AceComm.callbacks = CallbackHandler:New(AceComm,
"_RegisterComm",
"UnregisterComm",
"UnregisterAllComm",
AceComm.PrefixUsed,
AceComm.PrefixUnused)
AceComm.MessageCompleted = AceComm.callbacks.Fire
end
function AceComm.RegisterComm(addon, prefix, method)
if method == nil then
method = "OnCommReceived"
end
return AceComm._RegisterComm(addon, prefix, method)
end
----------------------------------------
-- Mixins
----------------------------------------
local mixins = {
"RegisterComm",
"UnregisterComm",
"UnregisterAllComm",
"SendCommMessage",
}
function AceComm:Embed(target)
for k, v in pairs(mixins) do
target[v] = self[v]
end
self.embeds[target] = true
end
function AceComm:OnEmbedDisable(target)
target:UnregisterAllComm()
end
----------------------------------------
-- Message sending
----------------------------------------
-- 254 is the max length of prefix + text that can be sent in one message
function AceComm.SendCommMessage(addon, prefix, text, distribution, target)
local prefix_len = #prefix
local text_len = #text
local meta_len = 2
local chunk_size = 253 - prefix_len - meta_len
assert(type(prefix) == "string")
assert(type(text) == "string")
assert(type(distribution) == "string")
if text_len < chunk_size + meta_len then
-- fits all in one message
CTL:SendAddonMessage(single_prio, prefix, text, distribution,
target)
else
local chunks = ceil(text_len / chunk_size)
-- string offsets
local chunk_begin = 1
local chunk_end = 1 + chunk_size
-- first part
local real_prefix = prefix .. message_type_rev["multipart_begin"]
local chunk = strsub(text, chunk_begin, chunk_end)
chunk_begin = chunk_end + 1
chunk_end = chunk_begin + chunk_size
CTL:SendAddonMessage(multipart_prio, real_prefix, chunk,
distribution, target)
-- continuation
real_prefix = prefix .. message_type_rev["multipart_continue"]
for i = 2, chunks - 1, 1 do
chunk = strsub(text, chunk_begin, chunk_end)
chunk_begin = chunk_end + 1
chunk_end = chunk_begin + chunk_size
CTL:SendAddonMessage(multipart_prio, real_prefix, chunk,
distribution, target)
end
-- end
real_prefix = prefix .. message_type_rev["multipart_end"]
chunk = strsub(text, chunk_begin, chunk_end)
CTL:SendAddonMessage(multipart_prio, real_prefix, chunk,
distribution, target)
end
end
----------------------------------------
-- Message receiving
----------------------------------------
function AceComm:ReceiveMultipart(prefix, message, distribution, sender,
messagetype)
-- a unique stream is defined by the prefix + distribution + sender
local data_key = ("%s\t%s\t%s"):format(prefix, distribution, sender)
local incomplete_data = self.__incomplete_data
local data = incomplete_data[data_key]
if messagetype == "multipart_begin" then
-- Begin multipart message
data = message
incomplete_data[data_key] = data
elseif messagetype == "multipart_continue" then
-- Continue multipart message
assert(data ~= nil)
data = data .. message
incomplete_data[data_key] = data
elseif messagetype == "multipart_end" then
-- End multipart message
assert(data ~= nil)
data = data .. message
self:MessageCompleted(prefix, data, distribution, sender)
incomplete_data[data_key] = nil
else
-- Unknown!
-- No erroring on data received from others! /mikk : error("AceComm:ReceiveMultipart unknown messagetype.")
end
end
function AceComm:CHAT_MSG_ADDON(prefix, message, distribution, sender)
-- ignore messages from ourself
--if sender == player_name then return end
--local prefix, layer, options =
-- strmatch(prefix, "^([^\001-\031]+)([\001-\031]?)(.*)")
local messagetype = self.__prefixes[prefix]
if not messagetype then
-- not a prefix registered with us
return
elseif messagetype == true then
-- single-part message
self:MessageCompleted(prefix, message, distribution, sender)
else
-- multi-part message
self:ReceiveMultipart(self.__original_prefix[prefix], message,
distribution, sender, messagetype)
end
end
-- Event Handling
function AceComm.OnEvent(this, event, ...)
if event == "CHAT_MSG_ADDON" then
AceComm:CHAT_MSG_ADDON(...)
else
error("Something strange happened to AceComm's event frame.")
end
end
AceComm.frame:SetScript("OnEvent", AceComm.OnEvent)
AceComm.frame:UnregisterAllEvents()
AceComm.frame:RegisterEvent("CHAT_MSG_ADDON")
-- Update embeds
for target, v in pairs(AceComm.embeds) do
AceComm:Embed(target)
end
|
--[[ $Id$ ]]
--[[ AceComm-3.0 proof-of-concept
]]
local MAJOR, MINOR = "AceComm-3.0", 0
local AceComm, oldminor = LibStub:NewLibrary(MAJOR, MINOR)
if not AceComm then return end
local CallbackHandler = LibStub:GetLibrary("CallbackHandler-1.0")
local CTL = ChatThrottleLib
local single_prio = "NORMAL"
local multipart_prio = "BULK"
local pairs = pairs
local ceil = math.ceil
local strsub = string.sub
AceComm.frame = AceComm.frame or CreateFrame("Frame", "AceComm30Frame")
AceComm.embeds = AceComm.embeds or {}
AceComm.__incomplete_data = AceComm.__incomplete_data or {}
AceComm.__prefixes = AceComm.__prefixes or {}
AceComm.__original_prefix = AceComm.__original_prefix or {}
----------------------------------------
-- abbreviated prefix metadata for quick lookup in CHAT_MSG_ADDON
----------------------------------------
local message_types = {
["\001A"] = "multipart_begin",
["\001B"] = "multipart_continue",
["\001C"] = "multipart_end",
}
local message_type_rev = {
["multipart_begin"] = "\001A",
["multipart_continue"] = "\001B",
["multipart_end"] = "\001C",
}
----------------------------------------
-- Callbacks
----------------------------------------
if not AceComm.callbacks then
-- ensure that 'prefix to watch' table is consistent with registered
-- callbacks
AceComm.__prefixes = {}
function AceComm:PrefixUsed(prefix)
local prefixes = self.__prefixes
local original_prefix = self.__original_prefix
prefixes[prefix] = true
for k, v in pairs(message_types) do
local p = prefix .. k
prefixes[p] = v
original_prefix[p] = prefix
end
end
function AceComm:PrefixUnused(prefix)
local prefixes = self.__prefixes
local original_prefix = self.__original_prefix
prefixes[prefix] = nil
for k, v in pairs(message_types) do
local p = prefix .. k
prefixes[p] = nil
original_prefix[p] = nil
end
end
AceComm.callbacks = CallbackHandler:New(AceComm,
"_RegisterComm",
"UnregisterComm",
"UnregisterAllComm",
AceComm.PrefixUsed,
AceComm.PrefixUnused)
AceComm.MessageCompleted = AceComm.callbacks.Fire
end
function AceComm.RegisterComm(addon, prefix, method)
if method == nil then
method = "OnCommReceived"
end
return AceComm._RegisterComm(addon, prefix, method)
end
----------------------------------------
-- Mixins
----------------------------------------
local mixins = {
"RegisterComm",
"UnregisterComm",
"UnregisterAllComm",
"SendCommMessage",
}
function AceComm:Embed(target)
for k, v in pairs(mixins) do
target[v] = self[v]
end
self.embeds[target] = true
end
function AceComm:OnEmbedDisable(target)
target:UnregisterAllComm()
end
----------------------------------------
-- Message sending
----------------------------------------
-- 254 is the max length of prefix + text that can be sent in one message
function AceComm.SendCommMessage(addon, prefix, text, distribution, target)
local prefix_len = #prefix
local text_len = #text
local meta_len = 2
local chunk_size = 253 - prefix_len - meta_len
assert(type(prefix) == "string")
assert(type(text) == "string")
assert(type(distribution) == "string")
if text_len < chunk_size + meta_len then
-- fits all in one message
CTL:SendAddonMessage(single_prio, prefix, text, distribution,
target)
else
local chunks = ceil(text_len / chunk_size)
-- string offsets
local chunk_begin = 1
local chunk_end = 1 + chunk_size
-- first part
local real_prefix = prefix .. message_type_rev["multipart_begin"]
local chunk = strsub(text, chunk_begin, chunk_end)
chunk_begin = chunk_end + 1
chunk_end = chunk_begin + chunk_size
CTL:SendAddonMessage(multipart_prio, real_prefix, chunk,
distribution, target)
-- continuation
real_prefix = prefix .. message_type_rev["multipart_continue"]
for i = 2, chunks - 1, 1 do
chunk = strsub(text, chunk_begin, chunk_end)
chunk_begin = chunk_end + 1
chunk_end = chunk_begin + chunk_size
CTL:SendAddonMessage(multipart_prio, real_prefix, chunk,
distribution, target)
end
-- end
real_prefix = prefix .. message_type_rev["multipart_end"]
chunk = strsub(text, chunk_begin, chunk_end)
CTL:SendAddonMessage(multipart_prio, real_prefix, chunk,
distribution, target)
end
end
----------------------------------------
-- Message receiving
----------------------------------------
function AceComm:ReceiveMultipart(prefix, message, distribution, sender,
messagetype)
-- a unique stream is defined by the prefix + distribution + sender
local data_key = ("%s\t%s\t%s"):format(prefix, distribution, sender)
local incomplete_data = self.__incomplete_data
local data = incomplete_data[data_key]
if messagetype == "multipart_begin" then
-- Begin multipart message
data = message
incomplete_data[data_key] = data
elseif messagetype == "multipart_continue" then
-- Continue multipart message
if data == nil then
return -- out of sequence, ignore
end
data = data .. message
incomplete_data[data_key] = data
elseif messagetype == "multipart_end" then
-- End multipart message
if data == nil then
return -- out of sequence, ignore
end
data = data .. message
self:MessageCompleted(prefix, data, distribution, sender)
incomplete_data[data_key] = nil
else
-- This can only be reached if self.__prefixes contains bad
-- data.
error("AceComm:ReceiveMultipart unknown messagetype.")
end
end
function AceComm:CHAT_MSG_ADDON(prefix, message, distribution, sender)
-- ignore messages from ourself
--if sender == player_name then return end
--local prefix, layer, options =
-- strmatch(prefix, "^([^\001-\031]+)([\001-\031]?)(.*)")
local messagetype = self.__prefixes[prefix]
if not messagetype then
-- not a prefix registered with us
return
elseif messagetype == true then
-- single-part message
self:MessageCompleted(prefix, message, distribution, sender)
else
-- multi-part message
self:ReceiveMultipart(self.__original_prefix[prefix], message,
distribution, sender, messagetype)
end
end
-- Event Handling
function AceComm.OnEvent(this, event, ...)
if event == "CHAT_MSG_ADDON" then
AceComm:CHAT_MSG_ADDON(...)
else
error("Something strange happened to AceComm's event frame.")
end
end
AceComm.frame:SetScript("OnEvent", AceComm.OnEvent)
AceComm.frame:UnregisterAllEvents()
AceComm.frame:RegisterEvent("CHAT_MSG_ADDON")
-- Update embeds
for target, v in pairs(AceComm.embeds) do
AceComm:Embed(target)
end
|
Ace3: * AceComm-3.0 - ignore out-of-sequence data. - re-added error since it's not reached unless self.__prefixes has bad data.
|
Ace3:
* AceComm-3.0
- ignore out-of-sequence data.
- re-added error since it's not reached unless self.__prefixes has bad data.
git-svn-id: d324031ee001e5fbb202928c503a4bc65708d41c@314 5debad98-a965-4143-8383-f471b3509dcf
|
Lua
|
bsd-3-clause
|
sarahgerweck/Ace3
|
9ee54ed727fe5f48e280a707c8f0484db5be710b
|
src/lua/sancus/template/generator.lua
|
src/lua/sancus/template/generator.lua
|
-- This file is part of sancus-lua-template
-- <https://github.com/sancus-project/sancus-lua-template>
--
-- Copyright (c) 2012, Alejandro Mery <[email protected]>
--
local lpeg = assert(require"lpeg")
local P,R,S,V = lpeg.P, lpeg.R, lpeg.S, lpeg.V
local C,Cc,Cg,Ct,Cp = lpeg.C, lpeg.Cc, lpeg.Cg, lpeg.Ct, lpeg.Cp
local assert, setmetatable, tostring, type = assert, setmetatable, tostring, type
local sformat = string.format
local _M = {}
local function parser()
local space, nl = S" \t", P"\n" + P"\r\n"
local rest = (1 - nl)^1
local eol = (P(-1) + nl)
local char = R"az" + R"AZ"
local num = R"09"
local dq = P'"'
local be, ee = P"${", P"}"
local bi, ei = P"<%", P"%>"
local bc, ec = bi, P"/>"
local attr = char * (char + num + P"_")^0
local value = (dq * C((1-dq)^0) * dq) + (num^1)/tonumber
-- ${ ... }
local expression = be * C((1 - nl - ee)^1) * ee
expression = Ct(Cg(expression, "value") * Cg(Cc("expr"), "type"))
-- <%command ... />
local command = space^1 * C(attr) * P"=" * value
command = bc * Cg(attr, "value") * Cg(Cc("command"), "type") * (command^0) * space^0 * ec
command = Ct(command)
-- <% ... %>
local inline = (1 - ei)^1
inline = bi * (C(
(space * inline) + (nl * inline)
)+(space + nl)^1) * ei
inline = Ct(Cg(inline, "value") * Cg(Cc("inline"), "type"))
-- [ \t]* %% comment
local comment = space^0 * P"%%" * rest * eol
-- [ \t]* % ...
local code = space^0 * P"%" * C(rest) * eol
-- everything else
local content = 1 - nl - be - bi
content = content^1 * eol^-1
content = C(nl + content)
local things = comment + code +
content + expression + inline +
command
return Ct(things^1) * Cp()
end
parser = parser()
local function find_line_col_by_pos(s, p)
local nl = P"\n" + P"\r\n"
local content = (1-nl)^1
local patt = (nl + (content * nl))*Cp()
local t = Ct(patt^0):match(s)
local line_no, from, to = 1, 0, nil
for _, q in ipairs(t) do
if q <= p then
line_no = line_no + 1
from = q
else
to = q
break
end
end
local col = p - from
local s1, s2 = s:sub(from, to), ""
s1 = C(content):match(s1)
if col > 0 then
s2 = s1:sub(1,col):gsub("[^\t]", " ") .. "^"
else
s2 = "^"
end
return line_no, col+1, s1, s2
end
local function parse(s)
assert(type(s) == "string", "argument must be an string")
if #s == 0 then
return {}
end
local t, p = parser:match(s)
if t and p == #s+1 then
return t
elseif p == nil then
p = 1
end
-- useful error message
local line, col, s1, s2 = find_line_col_by_pos(s, p)
local fmt = "sancus.template.parse: invalid element at (%s, %d):\n%s:%s\n%s%s"
local prefix
line = tostring(line)
prefix = (" "):rep(#line+1)
error(fmt:format(line, col, line, s1, prefix, s2))
end
local function new(s)
local t = parse(s)
return t
end
setmetatable(_M, {
__call = function(_, s) return new(s) end,
})
return _M
|
-- This file is part of sancus-lua-template
-- <https://github.com/sancus-project/sancus-lua-template>
--
-- Copyright (c) 2012, Alejandro Mery <[email protected]>
--
local lpeg = assert(require"lpeg")
local P,R,S,V = lpeg.P, lpeg.R, lpeg.S, lpeg.V
local C,Cc,Cg,Ct,Cp = lpeg.C, lpeg.Cc, lpeg.Cg, lpeg.Ct, lpeg.Cp
local assert, setmetatable, tostring, type = assert, setmetatable, tostring, type
local sformat = string.format
local _M = {}
local function parser()
local space, nl = S" \t", P"\n" + P"\r\n"
local rest = (1 - nl)^1
local eol = (P(-1) + nl)
local char = R"az" + R"AZ"
local num = R"09"
local dq = P'"'
local be, ee = P"${", P"}"
local bi, ei = P"<%", P"%>"
local bc, ec = bi, P"/>"
local attr = char * (char + num + P"_")^0
local value = (dq * C((1-dq)^0) * dq) + (num^1)/tonumber
-- ${ ... }
local expression = be * C((1 - nl - ee)^1) * ee
expression = Ct(Cg(expression, "value") * Cg(Cc("expr"), "type"))
-- <%command ... />
local command = space^1 * C(attr) * P"=" * value
command = bc * Cg(attr, "value") * Cg(Cc("command"), "type") * (command^0) * space^0 * ec
command = Ct(command)
-- <% ... %>
local inline = (1 - ei)^1
inline = bi * (C(
(space * inline) + (nl * inline)
)+(space + nl)^1) * ei
inline = Ct(Cg(inline, "value") * Cg(Cc("inline"), "type"))
-- [ \t]* %% comment
local comment = space^0 * P"%%" * rest * eol
-- [ \t]* % ...
local code = space^0 * P"%" * C(rest) * eol
code = Ct(Cg(code, "value") * Cg(Cc("code"), "type"))
-- everything else
local content = 1 - nl - be - bi
content = content^1 * eol^-1
content = C(nl + content)
local things = comment + code +
content + expression + inline +
command
return Ct(things^1) * Cp()
end
parser = parser()
local function find_line_col_by_pos(s, p)
local nl = P"\n" + P"\r\n"
local content = (1-nl)^1
local patt = (nl + (content * nl))*Cp()
local t = Ct(patt^0):match(s)
local line_no, from, to = 1, 0, nil
for _, q in ipairs(t) do
if q <= p then
line_no = line_no + 1
from = q
else
to = q
break
end
end
local col = p - from
local s1, s2 = s:sub(from, to), ""
s1 = C(content):match(s1)
if col > 0 then
s2 = s1:sub(1,col):gsub("[^\t]", " ") .. "^"
else
s2 = "^"
end
return line_no, col+1, s1, s2
end
local function parse(s)
assert(type(s) == "string", "argument must be an string")
if #s == 0 then
return {}
end
local t, p = parser:match(s)
if t and p == #s+1 then
return t
elseif p == nil then
p = 1
end
-- useful error message
local line, col, s1, s2 = find_line_col_by_pos(s, p)
local fmt = "sancus.template.parse: invalid element at (%s, %d):\n%s:%s\n%s%s"
local prefix
line = tostring(line)
prefix = (" "):rep(#line+1)
error(fmt:format(line, col, line, s1, prefix, s2))
end
local function new(s)
local t = parse(s)
return t
end
setmetatable(_M, {
__call = function(_, s) return new(s) end,
})
return _M
|
generator: parser: fix code catch
|
generator: parser: fix code catch
|
Lua
|
bsd-2-clause
|
sancus-project/sancus-lua-template
|
c9e3a36811a70e8b9954eacc00ca43f983c74bd6
|
busted/core.lua
|
busted/core.lua
|
local getfenv = require 'busted.compatibility'.getfenv
local setfenv = require 'busted.compatibility'.setfenv
local unpack = require 'busted.compatibility'.unpack
local pretty = require 'pl.pretty'
local throw = error
local failureMt = {
__index = {},
__tostring = function(e) return tostring(e.message) end,
__type = 'failure'
}
local failureMtNoString = {
__index = {},
__type = 'failure'
}
local pendingMt = {
__index = {},
__tostring = function(p) return p.message end,
__type = 'pending'
}
local function metatype(obj)
local otype = type(obj)
return otype == 'table' and (getmetatable(obj) or {}).__type or otype
end
local function hasToString(obj)
return type(obj) == 'string' or (getmetatable(obj) or {}).__tostring
end
return function()
local mediator = require 'mediator'()
local busted = {}
busted.version = '2.0.rc5-0'
local root = require 'busted.context'()
busted.context = root.ref()
local environment = require 'busted.environment'(busted.context)
busted.executors = {}
local executors = {}
busted.status = require 'busted.status'
function busted.getTrace(element, level, msg)
level = level or 3
local info = debug.getinfo(level, 'Sl')
while info.what == 'C' or info.short_src:match('luassert[/\\].*%.lua$') or
info.short_src:match('busted[/\\].*%.lua$') do
level = level + 1
info = debug.getinfo(level, 'Sl')
end
info.traceback = debug.traceback('', level)
info.message = msg
local file = busted.getFile(element)
return file.getTrace(file.name, info)
end
function busted.rewriteMessage(element, message, trace)
local file = busted.getFile(element)
local msg = hasToString(message) and tostring(message)
msg = msg or (message ~= nil and pretty.write(message) or 'Nil error')
msg = (file.rewriteMessage and file.rewriteMessage(file.name, msg) or msg)
local hasFileLine = msg:match('^[^\n]-:%d+: .*')
if not hasFileLine then
local trace = trace or busted.getTrace(element, 3, message)
local fileline = trace.short_src .. ':' .. trace.currentline .. ': '
msg = fileline .. msg
end
return msg
end
function busted.publish(...)
return mediator:publish(...)
end
function busted.subscribe(...)
return mediator:subscribe(...)
end
function busted.getFile(element)
local current, parent = element, busted.context.parent(element)
while parent do
if parent.file then
local file = parent.file[1]
return {
name = file.name,
getTrace = file.run.getTrace,
rewriteMessage = file.run.rewriteMessage
}
end
if parent.descriptor == 'file' then
return {
name = parent.name,
getTrace = parent.run.getTrace,
rewriteMessage = parent.run.rewriteMessage
}
end
parent = busted.context.parent(parent)
end
return parent
end
function busted.fail(msg, level)
local _, emsg = pcall(throw, msg, level+2)
local e = { message = emsg }
setmetatable(e, hasToString(msg) and failureMt or failureMtNoString)
throw(e, level+1)
end
function busted.pending(msg)
local p = { message = msg }
setmetatable(p, pendingMt)
throw(p)
end
function busted.replaceErrorWithFail(callable)
local env = {}
local f = (getmetatable(callable) or {}).__call or callable
setmetatable(env, { __index = getfenv(f) })
env.error = busted.fail
setfenv(f, env)
end
function busted.wrapEnv(callable)
if (type(callable) == 'function' or getmetatable(callable).__call) then
-- prioritize __call if it exists, like in files
environment.wrap((getmetatable(callable) or {}).__call or callable)
end
end
function busted.safe(descriptor, run, element)
busted.context.push(element)
local trace, message
local status = 'success'
local ret = { xpcall(run, function(msg)
local errType = metatype(msg)
status = ((errType == 'pending' or errType == 'failure') and errType or 'error')
trace = busted.getTrace(element, 3, msg)
message = busted.rewriteMessage(element, msg, trace)
end) }
if not ret[1] then
busted.publish({ status, descriptor }, element, busted.context.parent(element), message, trace)
end
ret[1] = busted.status(status)
busted.context.pop()
return unpack(ret)
end
function busted.register(descriptor, executor)
executors[descriptor] = executor
local publisher = function(name, fn)
if not fn and type(name) == 'function' then
fn = name
name = nil
end
local trace
local ctx = busted.context.get()
if busted.context.parent(ctx) then
trace = busted.getTrace(ctx, 3, name)
end
local publish = function(f)
busted.publish({ 'register', descriptor }, name, f, trace)
end
if fn then publish(fn) else return publish end
end
busted.executors[descriptor] = publisher
if descriptor ~= 'file' then
environment.set(descriptor, publisher)
end
busted.subscribe({ 'register', descriptor }, function(name, fn, trace)
local ctx = busted.context.get()
local plugin = {
descriptor = descriptor,
name = name,
run = fn,
trace = trace
}
busted.context.attach(plugin)
if not ctx[descriptor] then
ctx[descriptor] = { plugin }
else
ctx[descriptor][#ctx[descriptor]+1] = plugin
end
end)
end
function busted.execute(current)
if not current then current = busted.context.get() end
for _, v in pairs(busted.context.children(current)) do
local executor = executors[v.descriptor]
if executor then
busted.safe(v.descriptor, function() executor(v) end, v)
end
end
end
return busted
end
|
local getfenv = require 'busted.compatibility'.getfenv
local setfenv = require 'busted.compatibility'.setfenv
local unpack = require 'busted.compatibility'.unpack
local pretty = require 'pl.pretty'
local throw = error
local failureMt = {
__index = {},
__tostring = function(e) return tostring(e.message) end,
__type = 'failure'
}
local failureMtNoString = {
__index = {},
__type = 'failure'
}
local pendingMt = {
__index = {},
__tostring = function(p) return p.message end,
__type = 'pending'
}
local function metatype(obj)
local otype = type(obj)
return otype == 'table' and (getmetatable(obj) or {}).__type or otype
end
local function hasToString(obj)
return type(obj) == 'string' or (getmetatable(obj) or {}).__tostring
end
return function()
local mediator = require 'mediator'()
local busted = {}
busted.version = '2.0.rc5-0'
local root = require 'busted.context'()
busted.context = root.ref()
local environment = require 'busted.environment'(busted.context)
busted.executors = {}
local executors = {}
busted.status = require 'busted.status'
function busted.getTrace(element, level, msg)
level = level or 3
local info = debug.getinfo(level, 'Sl')
while info.what == 'C' or info.short_src:match('luassert[/\\].*%.lua$') or
info.short_src:match('busted[/\\].*%.lua$') do
level = level + 1
info = debug.getinfo(level, 'Sl')
end
info.traceback = debug.traceback('', level)
info.message = msg
local file = busted.getFile(element)
return file.getTrace(file.name, info)
end
function busted.rewriteMessage(element, message, trace)
local file = busted.getFile(element)
local msg = hasToString(message) and tostring(message)
msg = msg or (message ~= nil and pretty.write(message) or 'Nil error')
msg = (file.rewriteMessage and file.rewriteMessage(file.name, msg) or msg)
local hasFileLine = msg:match('^[^\n]-:%d+: .*')
if not hasFileLine then
local trace = trace or busted.getTrace(element, 3, message)
local fileline = trace.short_src .. ':' .. trace.currentline .. ': '
msg = fileline .. msg
end
return msg
end
function busted.publish(...)
return mediator:publish(...)
end
function busted.subscribe(...)
return mediator:subscribe(...)
end
function busted.getFile(element)
local current, parent = element, busted.context.parent(element)
while parent do
if parent.file then
local file = parent.file[1]
return {
name = file.name,
getTrace = file.run.getTrace,
rewriteMessage = file.run.rewriteMessage
}
end
if parent.descriptor == 'file' then
return {
name = parent.name,
getTrace = parent.run.getTrace,
rewriteMessage = parent.run.rewriteMessage
}
end
parent = busted.context.parent(parent)
end
return parent
end
function busted.fail(msg, level)
local rawlevel = (type(level) ~= 'number' or level <= 0) and level
local level = level or 1
local _, emsg = pcall(throw, msg, rawlevel or level+2)
local e = { message = emsg }
setmetatable(e, hasToString(msg) and failureMt or failureMtNoString)
throw(e, rawlevel or level+1)
end
function busted.pending(msg)
local p = { message = msg }
setmetatable(p, pendingMt)
throw(p)
end
function busted.replaceErrorWithFail(callable)
local env = {}
local f = (getmetatable(callable) or {}).__call or callable
setmetatable(env, { __index = getfenv(f) })
env.error = busted.fail
setfenv(f, env)
end
function busted.wrapEnv(callable)
if (type(callable) == 'function' or getmetatable(callable).__call) then
-- prioritize __call if it exists, like in files
environment.wrap((getmetatable(callable) or {}).__call or callable)
end
end
function busted.safe(descriptor, run, element)
busted.context.push(element)
local trace, message
local status = 'success'
local ret = { xpcall(run, function(msg)
local errType = metatype(msg)
status = ((errType == 'pending' or errType == 'failure') and errType or 'error')
trace = busted.getTrace(element, 3, msg)
message = busted.rewriteMessage(element, msg, trace)
end) }
if not ret[1] then
busted.publish({ status, descriptor }, element, busted.context.parent(element), message, trace)
end
ret[1] = busted.status(status)
busted.context.pop()
return unpack(ret)
end
function busted.register(descriptor, executor)
executors[descriptor] = executor
local publisher = function(name, fn)
if not fn and type(name) == 'function' then
fn = name
name = nil
end
local trace
local ctx = busted.context.get()
if busted.context.parent(ctx) then
trace = busted.getTrace(ctx, 3, name)
end
local publish = function(f)
busted.publish({ 'register', descriptor }, name, f, trace)
end
if fn then publish(fn) else return publish end
end
busted.executors[descriptor] = publisher
if descriptor ~= 'file' then
environment.set(descriptor, publisher)
end
busted.subscribe({ 'register', descriptor }, function(name, fn, trace)
local ctx = busted.context.get()
local plugin = {
descriptor = descriptor,
name = name,
run = fn,
trace = trace
}
busted.context.attach(plugin)
if not ctx[descriptor] then
ctx[descriptor] = { plugin }
else
ctx[descriptor][#ctx[descriptor]+1] = plugin
end
end)
end
function busted.execute(current)
if not current then current = busted.context.get() end
for _, v in pairs(busted.context.children(current)) do
local executor = executors[v.descriptor]
if executor then
busted.safe(v.descriptor, function() executor(v) end, v)
end
end
end
return busted
end
|
Fix error level reporting
|
Fix error level reporting
|
Lua
|
mit
|
sobrinho/busted,Olivine-Labs/busted,DorianGray/busted,xyliuke/busted,istr/busted,ryanplusplus/busted,leafo/busted,o-lim/busted,mpeterv/busted,nehz/busted
|
ee85b3b76b38abc65a744e30ef4b505e5a9f9456
|
libs/core/luasrc/model/network/wireless.lua
|
libs/core/luasrc/model/network/wireless.lua
|
--[[
LuCI - Network model - Wireless extension
Copyright 2009 Jo-Philipp Wich <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
local pairs, i18n, uci = pairs, luci.i18n, luci.model.uci
local iwi = require "iwinfo"
local utl = require "luci.util"
local uct = require "luci.model.uci.bind"
module "luci.model.network.wireless"
local ub = uct.bind("wireless")
local st, ifs
function init(self, cursor)
cursor:unload("wireless")
cursor:load("wireless")
ub:init(cursor)
st = uci.cursor_state()
ifs = { }
local count = 0
ub.uci:foreach("wireless", "wifi-iface",
function(s)
count = count + 1
local device = s.device or "wlan0"
local state = st:get_all("wireless", s['.name'])
local name = device .. ".network" .. count
ifs[name] = {
idx = count,
name = name,
rawname = state and state.ifname or name,
flags = { },
ipaddrs = { },
ip6addrs = { },
type = "wifi",
network = s.network,
handler = self,
wifi = state or s,
sid = s['.name']
}
end)
end
local function _mode(m)
if m == "ap" then m = "AP"
elseif m == "sta" then m = "Client"
elseif m == "adhoc" then m = "Ad-Hoc"
elseif m == "mesh" then m = "Mesh"
elseif m == "monitor" then m = "Monitor"
end
return m or "Client"
end
function shortname(self, iface)
if iface.dev and iface.dev.wifi then
return "%s %q" %{
i18n.translate(_mode(iface.dev.wifi.mode)),
iface.dev.wifi.ssid or iface.dev.wifi.bssid
or i18n.translate("(hidden)")
}
else
return iface:name()
end
end
function get_i18n(self, iface)
if iface.dev and iface.dev.wifi then
return "%s: %s %q" %{
i18n.translate("Wireless Network"),
i18n.translate(iface.dev.wifi.mode or "Client"),
iface.dev.wifi.ssid or iface.dev.wifi.bssid
or i18n.translate("(hidden)")
}
else
return "%s: %q" %{ i18n.translate("Wireless Network"), iface:name() }
end
end
function rename_network(self, old, new)
local i
for i, _ in pairs(ifs) do
if ifs[i].network == old then
ifs[i].network = new
end
end
ub.uci:foreach("wireless", "wifi-iface",
function(s)
if s.network == old then
if new then
ub.uci:set("wireless", s['.name'], "network", new)
else
ub.uci:delete("wireless", s['.name'], "network")
end
end
end)
end
function del_network(self, old)
return self:rename_network(old, nil)
end
function find_interfaces(self, iflist, brlist)
local iface
for iface, _ in pairs(ifs) do
iflist[iface] = ifs[iface]
end
end
function ignore_interface(self, iface)
if ifs and ifs[iface] then
return false
else
return iwi.type(iface) and true or false
end
end
function add_interface(self, net, iface)
if ifs and ifs[iface] and ifs[iface].sid then
ub.uci:set("wireless", ifs[iface].sid, "network", net:name())
ifs[iface].network = net:name()
return true
end
return false
end
function del_interface(self, net, iface)
if ifs and ifs[iface] and ifs[iface].sid then
ub.uci:delete("wireless", ifs[iface].sid, "network")
--return true
end
return false
end
return _M
|
--[[
LuCI - Network model - Wireless extension
Copyright 2009 Jo-Philipp Wich <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
local pairs, i18n, uci = pairs, luci.i18n, luci.model.uci
local iwi = require "iwinfo"
local utl = require "luci.util"
local uct = require "luci.model.uci.bind"
module "luci.model.network.wireless"
local ub = uct.bind("wireless")
local st, ifs
function init(self, cursor)
cursor:unload("wireless")
cursor:load("wireless")
ub:init(cursor)
st = uci.cursor_state()
ifs = { }
local count = 0
ub.uci:foreach("wireless", "wifi-iface",
function(s)
count = count + 1
local device = s.device or "wlan0"
local state = st:get_all("wireless", s['.name'])
local name = device .. ".network" .. count
ifs[name] = {
idx = count,
name = name,
rawname = state and state.ifname or name,
flags = { },
ipaddrs = { },
ip6addrs = { },
type = "wifi",
network = s.network,
handler = self,
wifi = state or s,
sid = s['.name']
}
end)
end
local function _mode(m)
if m == "ap" then m = "AP"
elseif m == "sta" then m = "Client"
elseif m == "adhoc" then m = "Ad-Hoc"
elseif m == "mesh" then m = "Mesh"
elseif m == "monitor" then m = "Monitor"
elseif m == "wds" then m = "WDS"
end
return m or "Client"
end
function shortname(self, iface)
if iface.dev and iface.dev.wifi then
return "%s %q" %{
i18n.translate(_mode(iface.dev.wifi.mode)),
iface.dev.wifi.ssid or iface.dev.wifi.bssid
or i18n.translate("(hidden)")
}
else
return iface:name()
end
end
function get_i18n(self, iface)
if iface.dev and iface.dev.wifi then
return "%s: %s %q" %{
i18n.translate("Wireless Network"),
i18n.translate(_mode(iface.dev.wifi.mode)),
iface.dev.wifi.ssid or iface.dev.wifi.bssid
or i18n.translate("(hidden)")
}
else
return "%s: %q" %{ i18n.translate("Wireless Network"), iface:name() }
end
end
function rename_network(self, old, new)
local i
for i, _ in pairs(ifs) do
if ifs[i].network == old then
ifs[i].network = new
end
end
ub.uci:foreach("wireless", "wifi-iface",
function(s)
if s.network == old then
if new then
ub.uci:set("wireless", s['.name'], "network", new)
else
ub.uci:delete("wireless", s['.name'], "network")
end
end
end)
end
function del_network(self, old)
return self:rename_network(old, nil)
end
function find_interfaces(self, iflist, brlist)
local iface
for iface, _ in pairs(ifs) do
iflist[iface] = ifs[iface]
end
end
function ignore_interface(self, iface)
if ifs and ifs[iface] then
return false
else
return iwi.type(iface) and true or false
end
end
function add_interface(self, net, iface)
if ifs and ifs[iface] and ifs[iface].sid then
ub.uci:set("wireless", ifs[iface].sid, "network", net:name())
ifs[iface].network = net:name()
return true
end
return false
end
function del_interface(self, net, iface)
if ifs and ifs[iface] and ifs[iface].sid then
ub.uci:delete("wireless", ifs[iface].sid, "network")
--return true
end
return false
end
return _M
|
libs/core: i18n fixes for wds mode
|
libs/core: i18n fixes for wds mode
|
Lua
|
apache-2.0
|
taiha/luci,hnyman/luci,male-puppies/luci,ff94315/luci-1,nwf/openwrt-luci,taiha/luci,ReclaimYourPrivacy/cloak-luci,MinFu/luci,RedSnake64/openwrt-luci-packages,fkooman/luci,nwf/openwrt-luci,ff94315/luci-1,male-puppies/luci,obsy/luci,fkooman/luci,joaofvieira/luci,jchuang1977/luci-1,kuoruan/luci,openwrt-es/openwrt-luci,lcf258/openwrtcn,joaofvieira/luci,981213/luci-1,sujeet14108/luci,bittorf/luci,jlopenwrtluci/luci,ReclaimYourPrivacy/cloak-luci,forward619/luci,kuoruan/luci,981213/luci-1,florian-shellfire/luci,cappiewu/luci,MinFu/luci,LazyZhu/openwrt-luci-trunk-mod,LazyZhu/openwrt-luci-trunk-mod,ollie27/openwrt_luci,aa65535/luci,Sakura-Winkey/LuCI,cshore/luci,db260179/openwrt-bpi-r1-luci,deepak78/new-luci,marcel-sch/luci,teslamint/luci,jchuang1977/luci-1,ollie27/openwrt_luci,RuiChen1113/luci,LuttyYang/luci,slayerrensky/luci,lcf258/openwrtcn,ReclaimYourPrivacy/cloak-luci,dwmw2/luci,Kyklas/luci-proto-hso,taiha/luci,jorgifumi/luci,hnyman/luci,maxrio/luci981213,palmettos/cnLuCI,remakeelectric/luci,Sakura-Winkey/LuCI,tobiaswaldvogel/luci,lbthomsen/openwrt-luci,thess/OpenWrt-luci,palmettos/cnLuCI,oneru/luci,wongsyrone/luci-1,fkooman/luci,MinFu/luci,schidler/ionic-luci,kuoruan/lede-luci,david-xiao/luci,fkooman/luci,Wedmer/luci,openwrt-es/openwrt-luci,ReclaimYourPrivacy/cloak-luci,sujeet14108/luci,remakeelectric/luci,wongsyrone/luci-1,keyidadi/luci,jlopenwrtluci/luci,kuoruan/lede-luci,NeoRaider/luci,tobiaswaldvogel/luci,jorgifumi/luci,zhaoxx063/luci,cshore-firmware/openwrt-luci,thess/OpenWrt-luci,Wedmer/luci,RedSnake64/openwrt-luci-packages,jchuang1977/luci-1,cappiewu/luci,cappiewu/luci,obsy/luci,nmav/luci,remakeelectric/luci,obsy/luci,db260179/openwrt-bpi-r1-luci,mumuqz/luci,Sakura-Winkey/LuCI,teslamint/luci,MinFu/luci,hnyman/luci,palmettos/test,cshore/luci,NeoRaider/luci,marcel-sch/luci,tcatm/luci,cshore/luci,NeoRaider/luci,rogerpueyo/luci,shangjiyu/luci-with-extra,kuoruan/lede-luci,jchuang1977/luci-1,Hostle/openwrt-luci-multi-user,openwrt-es/openwrt-luci,dismantl/luci-0.12,male-puppies/luci,RuiChen1113/luci,tobiaswaldvogel/luci,nwf/openwrt-luci,opentechinstitute/luci,keyidadi/luci,palmettos/cnLuCI,harveyhu2012/luci,Sakura-Winkey/LuCI,david-xiao/luci,Hostle/luci,opentechinstitute/luci,nwf/openwrt-luci,urueedi/luci,nmav/luci,Hostle/openwrt-luci-multi-user,Hostle/openwrt-luci-multi-user,nmav/luci,chris5560/openwrt-luci,oyido/luci,tobiaswaldvogel/luci,slayerrensky/luci,NeoRaider/luci,Hostle/luci,db260179/openwrt-bpi-r1-luci,hnyman/luci,981213/luci-1,maxrio/luci981213,taiha/luci,male-puppies/luci,rogerpueyo/luci,schidler/ionic-luci,chris5560/openwrt-luci,Sakura-Winkey/LuCI,cappiewu/luci,Wedmer/luci,Kyklas/luci-proto-hso,wongsyrone/luci-1,forward619/luci,harveyhu2012/luci,LazyZhu/openwrt-luci-trunk-mod,tcatm/luci,artynet/luci,bright-things/ionic-luci,981213/luci-1,cshore-firmware/openwrt-luci,ReclaimYourPrivacy/cloak-luci,shangjiyu/luci-with-extra,cshore/luci,mumuqz/luci,taiha/luci,RedSnake64/openwrt-luci-packages,chris5560/openwrt-luci,tobiaswaldvogel/luci,hnyman/luci,male-puppies/luci,cappiewu/luci,lcf258/openwrtcn,forward619/luci,dismantl/luci-0.12,aircross/OpenWrt-Firefly-LuCI,Kyklas/luci-proto-hso,schidler/ionic-luci,jlopenwrtluci/luci,lcf258/openwrtcn,nmav/luci,rogerpueyo/luci,florian-shellfire/luci,cshore-firmware/openwrt-luci,jchuang1977/luci-1,lcf258/openwrtcn,981213/luci-1,remakeelectric/luci,artynet/luci,ff94315/luci-1,sujeet14108/luci,thess/OpenWrt-luci,david-xiao/luci,bittorf/luci,slayerrensky/luci,openwrt/luci,dwmw2/luci,harveyhu2012/luci,lbthomsen/openwrt-luci,shangjiyu/luci-with-extra,Hostle/openwrt-luci-multi-user,nmav/luci,palmettos/test,cshore-firmware/openwrt-luci,shangjiyu/luci-with-extra,maxrio/luci981213,RuiChen1113/luci,dismantl/luci-0.12,aa65535/luci,lbthomsen/openwrt-luci,obsy/luci,db260179/openwrt-bpi-r1-luci,aircross/OpenWrt-Firefly-LuCI,RuiChen1113/luci,LazyZhu/openwrt-luci-trunk-mod,sujeet14108/luci,harveyhu2012/luci,dwmw2/luci,joaofvieira/luci,RedSnake64/openwrt-luci-packages,palmettos/test,Noltari/luci,joaofvieira/luci,teslamint/luci,marcel-sch/luci,thesabbir/luci,LuttyYang/luci,Kyklas/luci-proto-hso,oyido/luci,harveyhu2012/luci,shangjiyu/luci-with-extra,LuttyYang/luci,thess/OpenWrt-luci,palmettos/cnLuCI,Sakura-Winkey/LuCI,ff94315/luci-1,Hostle/openwrt-luci-multi-user,shangjiyu/luci-with-extra,nmav/luci,keyidadi/luci,openwrt-es/openwrt-luci,oyido/luci,chris5560/openwrt-luci,tcatm/luci,Noltari/luci,remakeelectric/luci,artynet/luci,Noltari/luci,Kyklas/luci-proto-hso,cappiewu/luci,LuttyYang/luci,MinFu/luci,openwrt/luci,mumuqz/luci,maxrio/luci981213,Noltari/luci,harveyhu2012/luci,zhaoxx063/luci,Kyklas/luci-proto-hso,nwf/openwrt-luci,joaofvieira/luci,oyido/luci,david-xiao/luci,deepak78/new-luci,daofeng2015/luci,nwf/openwrt-luci,david-xiao/luci,male-puppies/luci,forward619/luci,teslamint/luci,daofeng2015/luci,rogerpueyo/luci,slayerrensky/luci,david-xiao/luci,openwrt/luci,david-xiao/luci,Hostle/luci,dwmw2/luci,palmettos/test,artynet/luci,thess/OpenWrt-luci,hnyman/luci,sujeet14108/luci,Hostle/openwrt-luci-multi-user,zhaoxx063/luci,lcf258/openwrtcn,jchuang1977/luci-1,marcel-sch/luci,oyido/luci,slayerrensky/luci,jlopenwrtluci/luci,openwrt/luci,bright-things/ionic-luci,ff94315/luci-1,981213/luci-1,chris5560/openwrt-luci,zhaoxx063/luci,florian-shellfire/luci,taiha/luci,ollie27/openwrt_luci,NeoRaider/luci,urueedi/luci,db260179/openwrt-bpi-r1-luci,thess/OpenWrt-luci,taiha/luci,artynet/luci,openwrt/luci,jlopenwrtluci/luci,aa65535/luci,opentechinstitute/luci,Noltari/luci,thesabbir/luci,artynet/luci,aa65535/luci,thess/OpenWrt-luci,nmav/luci,jchuang1977/luci-1,cshore-firmware/openwrt-luci,LazyZhu/openwrt-luci-trunk-mod,cshore-firmware/openwrt-luci,keyidadi/luci,jorgifumi/luci,aircross/OpenWrt-Firefly-LuCI,openwrt-es/openwrt-luci,maxrio/luci981213,LazyZhu/openwrt-luci-trunk-mod,dwmw2/luci,schidler/ionic-luci,dismantl/luci-0.12,keyidadi/luci,Kyklas/luci-proto-hso,schidler/ionic-luci,thesabbir/luci,mumuqz/luci,kuoruan/luci,marcel-sch/luci,daofeng2015/luci,kuoruan/luci,obsy/luci,oneru/luci,oyido/luci,zhaoxx063/luci,marcel-sch/luci,zhaoxx063/luci,fkooman/luci,rogerpueyo/luci,schidler/ionic-luci,opentechinstitute/luci,thesabbir/luci,bright-things/ionic-luci,florian-shellfire/luci,teslamint/luci,forward619/luci,aa65535/luci,forward619/luci,Wedmer/luci,nmav/luci,maxrio/luci981213,oneru/luci,chris5560/openwrt-luci,urueedi/luci,MinFu/luci,cshore/luci,oyido/luci,slayerrensky/luci,remakeelectric/luci,Noltari/luci,openwrt-es/openwrt-luci,cshore-firmware/openwrt-luci,teslamint/luci,chris5560/openwrt-luci,LuttyYang/luci,cshore/luci,bittorf/luci,Noltari/luci,chris5560/openwrt-luci,forward619/luci,openwrt-es/openwrt-luci,Hostle/openwrt-luci-multi-user,aa65535/luci,bright-things/ionic-luci,wongsyrone/luci-1,sujeet14108/luci,male-puppies/luci,NeoRaider/luci,cshore/luci,oyido/luci,bright-things/ionic-luci,bittorf/luci,shangjiyu/luci-with-extra,fkooman/luci,aircross/OpenWrt-Firefly-LuCI,slayerrensky/luci,nwf/openwrt-luci,NeoRaider/luci,Wedmer/luci,Hostle/luci,RuiChen1113/luci,urueedi/luci,ff94315/luci-1,fkooman/luci,lbthomsen/openwrt-luci,zhaoxx063/luci,mumuqz/luci,joaofvieira/luci,mumuqz/luci,Wedmer/luci,MinFu/luci,david-xiao/luci,MinFu/luci,LuttyYang/luci,ReclaimYourPrivacy/cloak-luci,opentechinstitute/luci,openwrt/luci,obsy/luci,bright-things/ionic-luci,lcf258/openwrtcn,ollie27/openwrt_luci,artynet/luci,kuoruan/luci,deepak78/new-luci,Sakura-Winkey/LuCI,ollie27/openwrt_luci,kuoruan/lede-luci,lcf258/openwrtcn,ollie27/openwrt_luci,RedSnake64/openwrt-luci-packages,kuoruan/luci,cshore-firmware/openwrt-luci,981213/luci-1,thesabbir/luci,florian-shellfire/luci,schidler/ionic-luci,shangjiyu/luci-with-extra,Wedmer/luci,tcatm/luci,LuttyYang/luci,palmettos/test,ff94315/luci-1,joaofvieira/luci,wongsyrone/luci-1,Noltari/luci,Hostle/luci,forward619/luci,db260179/openwrt-bpi-r1-luci,joaofvieira/luci,oneru/luci,Hostle/luci,marcel-sch/luci,oneru/luci,teslamint/luci,oneru/luci,artynet/luci,aircross/OpenWrt-Firefly-LuCI,dwmw2/luci,bittorf/luci,obsy/luci,LazyZhu/openwrt-luci-trunk-mod,deepak78/new-luci,keyidadi/luci,kuoruan/luci,palmettos/cnLuCI,daofeng2015/luci,palmettos/cnLuCI,jorgifumi/luci,bright-things/ionic-luci,openwrt/luci,florian-shellfire/luci,ollie27/openwrt_luci,deepak78/new-luci,schidler/ionic-luci,palmettos/test,tcatm/luci,keyidadi/luci,lcf258/openwrtcn,deepak78/new-luci,Hostle/luci,Noltari/luci,jlopenwrtluci/luci,Sakura-Winkey/LuCI,zhaoxx063/luci,daofeng2015/luci,aircross/OpenWrt-Firefly-LuCI,artynet/luci,obsy/luci,lbthomsen/openwrt-luci,cappiewu/luci,rogerpueyo/luci,male-puppies/luci,remakeelectric/luci,Hostle/openwrt-luci-multi-user,jorgifumi/luci,bittorf/luci,opentechinstitute/luci,dwmw2/luci,bright-things/ionic-luci,palmettos/cnLuCI,jchuang1977/luci-1,oneru/luci,palmettos/test,opentechinstitute/luci,jlopenwrtluci/luci,openwrt/luci,dismantl/luci-0.12,urueedi/luci,daofeng2015/luci,tcatm/luci,ollie27/openwrt_luci,nwf/openwrt-luci,oneru/luci,urueedi/luci,aa65535/luci,kuoruan/luci,sujeet14108/luci,palmettos/cnLuCI,db260179/openwrt-bpi-r1-luci,thesabbir/luci,mumuqz/luci,tobiaswaldvogel/luci,tcatm/luci,florian-shellfire/luci,thesabbir/luci,remakeelectric/luci,tobiaswaldvogel/luci,dismantl/luci-0.12,openwrt-es/openwrt-luci,Wedmer/luci,opentechinstitute/luci,lbthomsen/openwrt-luci,jlopenwrtluci/luci,deepak78/new-luci,wongsyrone/luci-1,urueedi/luci,RuiChen1113/luci,rogerpueyo/luci,jorgifumi/luci,taiha/luci,aircross/OpenWrt-Firefly-LuCI,dwmw2/luci,db260179/openwrt-bpi-r1-luci,urueedi/luci,cshore/luci,kuoruan/lede-luci,bittorf/luci,teslamint/luci,lcf258/openwrtcn,ff94315/luci-1,jorgifumi/luci,kuoruan/lede-luci,LuttyYang/luci,harveyhu2012/luci,deepak78/new-luci,daofeng2015/luci,lbthomsen/openwrt-luci,marcel-sch/luci,Hostle/luci,RedSnake64/openwrt-luci-packages,thess/OpenWrt-luci,bittorf/luci,thesabbir/luci,RedSnake64/openwrt-luci-packages,lbthomsen/openwrt-luci,hnyman/luci,kuoruan/lede-luci,aa65535/luci,LazyZhu/openwrt-luci-trunk-mod,cappiewu/luci,mumuqz/luci,wongsyrone/luci-1,RuiChen1113/luci,RuiChen1113/luci,florian-shellfire/luci,palmettos/test,dismantl/luci-0.12,NeoRaider/luci,fkooman/luci,tobiaswaldvogel/luci,wongsyrone/luci-1,ReclaimYourPrivacy/cloak-luci,jorgifumi/luci,keyidadi/luci,rogerpueyo/luci,maxrio/luci981213,slayerrensky/luci,nmav/luci,sujeet14108/luci,tcatm/luci,maxrio/luci981213,hnyman/luci,daofeng2015/luci,ReclaimYourPrivacy/cloak-luci,kuoruan/lede-luci
|
32a40076be36b8005883b9b864a3c93e2203219f
|
premake4.lua
|
premake4.lua
|
--[[
DAGON
An Adventure Game Engine
This is a fairly basic Premake configuration that generates project files for
your preferred build system. Premake may be downloaded from the following
site:
http://industriousone.com/premake
Usage is as simple as typing 'premake4 [action]'. Because this Premake file is
primarily intended for building from source and contributing to Dagon, we
strongly suggest that you download the official binary releases for deploying
your games:
https://github.com/Senscape/Dagon/releases
Copyright (c) 2011-2013 Senscape s.r.l. All rights reserved.
This Source Code Form is subject to the terms of the Mozilla Public License,
v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain
one at http://mozilla.org/MPL/2.0/.
--]]
--[[
BUILD INSTRUCTIONS
Dagon requires the following dependencies: FreeType, GLEW, Lua 5.1, Ogg, OpenAL,
Theora, Vorbis, SDL2.
Linux:
We suggest installing the following packages via apt-get: libfreetype6-dev,
libglew-dev, liblua5.1-0-dev, libogg-dev, libopenal-dev, libvorbis-dev,
libtheora-dev, libSDL2-dev.
SDL2 was not available in some default repos as of this writing and had to be
built from scratch.
Mac OS X:
Libraries are included in the extlibs folder. You may also use Homebrew to
install custom packages: http://brew.sh
Suggested Homebrew formulas are: freetype, glew, lua, libogg, libvorbis,
theora, sdl2.
Windows:
Libraries for Visual Studio are included in the extlibs folder.
]]--
-- Base solution
solution "Dagon"
configurations { "Debug", "Release" }
platforms { "x32", "x64", "universal" }
location "build"
configuration { "Debug" }
defines { "_DEBUG", "DEBUG" }
flags { "Symbols" }
targetdir "build/debug"
configuration { "Release" }
defines { "NDEBUG" }
flags { "Optimize" }
targetdir "build/release"
-- Clean up if required and exit
if _ACTION == "clean" then
os.rmdir("build")
end
-- The main Dagon project
project "Dagon"
targetname "dagon"
-- GLEW_STATIC only applies to Windows, but there's no harm done if defined
-- on other systems.
defines { "GLEW_STATIC", "OV_EXCLUDE_STATIC_CALLBACKS" }
location "build"
objdir "build/objs"
-- Note that we always build as a console app, even on Windows. Please use
-- the corresponding Xcode or Visual Studio project files to build a
-- user-friendly binary.
kind "ConsoleApp"
language "C++"
files { "src/**.h", "src/**.c", "src/**.cpp" }
-- Libraries required for Unix-based systems
libs_unix = { "freetype", "GLEW", "GL", "GLU", "ogg", "openal",
"SDL2", "vorbis", "vorbisfile", "theoradec" }
-- Search for libraries on Linux systems
if os.get() == "linux" then
-- Attempt to look for Lua library with most commonly used names
local lua_lib_names = { "lua-5.1", "lua5.1", "lua" }
local lua_lib = { name = nil, dir = nil }
for i = 1, #lua_lib_names do
lua_lib.name = lua_lib_names[i]
lua_lib.dir = os.findlib(lua_lib.name)
if(lua_lib.dir ~= nil) then
break
end
end
table.insert(libs_unix, lua_lib.name)
-- Confirm that all the required libraries are present
for i = 1, #libs_unix do
local lib = libs_unix[i]
if os.findlib(lib) == nil then
print ("WARNING: Library " .. lib .. " not found")
end
end
end
-- Final configuration, includes and links according to the host system
configuration "linux"
includedirs { "/usr/include", "/usr/include/lua5.1",
"/usr/include/freetype2", "/usr/local/include",
"/usr/local/include/lua5.1",
"/usr/local/include/freetype2" }
libdirs { "/usr/lib", "/usr/local/lib" }
links { libs_unix }
configuration "macosx"
includedirs { "/usr/include", "/usr/include/lua5.1",
"/usr/include/freetype2", "/usr/local/include",
"/usr/local/include/lua5.1",
"/usr/local/include/freetype2",
"extlibs/headers",
"extlibs/headers/libfreetype/osx",
"extlibs/headers/libfreetype/osx/freetype2",
"extlibs/headers/libsdl2/osx" }
libdirs { "/usr/lib", "/usr/local/lib",
"extlibs/libs-osx/Frameworks", "extlibs/libs-osx/lib" }
links { "freetype", "GLEW", "lua", "ogg", "SDL2",
"vorbis", "vorbisfile", "theoradec" }
links { "AudioToolbox.framework", "AudioUnit.framework",
"Carbon.framework", "Cocoa.framework", "CoreAudio.framework",
"CoreFoundation.framework", "ForceFeedback.framework",
"IOKit.framework", "OpenAL.framework", "OpenGL.framework" }
configuration "windows"
includedirs { "extlibs/headers",
"extlibs/headers/libfreetype/windows",
"extlibs/headers/libfreetype/windows/freetype",
"extlibs/headers/libsdl2/windows" }
links { "freetype", "glew32s", "libogg_static",
"libtheora_static", "libvorbis_static",
"libvorbisfile_static", "lua", "OpenAL32",
"SDL2", "SDL2main", "opengl32", "glu32",
"Imm32", "version", "winmm" }
configuration ("windows", "x32")
libdirs { "extlibs/libs-msvc/x86" }
configuration ("windows", "x64")
libdirs { "extlibs/libs-msvc/x64" }
|
--[[
DAGON
An Adventure Game Engine
This is a fairly basic Premake configuration that generates project files for
your preferred build system. Premake may be downloaded from the following
site:
http://industriousone.com/premake
Usage is as simple as typing 'premake4 [action]'. Because this Premake file is
primarily intended for building from source and contributing to Dagon, we
strongly suggest that you download the official binary releases for deploying
your games:
https://github.com/Senscape/Dagon/releases
Copyright (c) 2011-2013 Senscape s.r.l. All rights reserved.
This Source Code Form is subject to the terms of the Mozilla Public License,
v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain
one at http://mozilla.org/MPL/2.0/.
--]]
--[[
BUILD INSTRUCTIONS
Dagon requires the following dependencies: FreeType, GLEW, Lua 5.1, Ogg, OpenAL,
Theora, Vorbis, SDL2.
Linux:
We suggest installing the following packages via apt-get: libfreetype6-dev,
libglew-dev, liblua5.1-0-dev, libogg-dev, libopenal-dev, libvorbis-dev,
libtheora-dev, libSDL2-dev.
SDL2 was not available in some default repos as of this writing and had to be
built from scratch.
Mac OS X:
Libraries are included in the extlibs folder. You may also use Homebrew to
install custom packages: http://brew.sh
Suggested Homebrew formulas are: freetype, glew, lua, libogg, libvorbis,
theora, sdl2.
Windows:
Libraries for Visual Studio are included in the extlibs folder.
]]--
-- Base solution
solution "Dagon"
configurations { "debug", "release" }
platforms { "native" }
location "build"
configuration { "debug" }
defines { "_DEBUG", "DEBUG" }
flags { "Symbols" }
targetdir "build/debug"
configuration { "release" }
defines { "NDEBUG" }
flags { "Optimize" }
targetdir "build/release"
-- Clean up if required and exit
if _ACTION == "clean" then
os.rmdir("build")
end
-- The main Dagon project
project "Dagon"
targetname "dagon"
-- GLEW_STATIC only applies to Windows, but there's no harm done if defined
-- on other systems.
defines { "GLEW_STATIC", "OV_EXCLUDE_STATIC_CALLBACKS" }
location "build"
objdir "build/objs"
-- Note that we always build as a console app, even on Windows. Please use
-- the corresponding Xcode or Visual Studio project files to build a
-- user-friendly binary.
kind "ConsoleApp"
language "C++"
files { "src/**.h", "src/**.c", "src/**.cpp" }
-- Libraries required for Unix-based systems
libs_unix = { "freetype", "GLEW", "GL", "GLU", "ogg", "openal", "vorbis",
"vorbisfile", "theoradec", "SDL2", "dl", "pthread" }
-- Search for libraries on Linux systems
if os.get() == "linux" then
-- Attempt to look for Lua library with most commonly used names
local lua_lib_names = { "lua-5.1", "lua5.1", "lua" }
local lua_lib = { name = nil, dir = nil }
for i = 1, #lua_lib_names do
lua_lib.name = lua_lib_names[i]
lua_lib.dir = os.findlib(lua_lib.name)
if(lua_lib.dir ~= nil) then
break
end
end
table.insert(libs_unix, lua_lib.name)
-- Confirm that all the required libraries are present
for i = 1, #libs_unix do
local lib = libs_unix[i]
if os.findlib(lib) == nil then
print ("WARNING: Library " .. lib .. " not found")
end
end
end
-- Final configuration, includes and links according to the host system
configuration "linux"
includedirs { "/usr/include", "/usr/include/lua5.1",
"/usr/include/freetype2", "/usr/local/include",
"/usr/local/include/lua5.1",
"/usr/local/include/freetype2" }
libdirs { "/usr/lib", "/usr/local/lib" }
links { libs_unix }
configuration "macosx"
includedirs { "/usr/include", "/usr/include/lua5.1",
"/usr/include/freetype2", "/usr/local/include",
"/usr/local/include/lua5.1",
"/usr/local/include/freetype2",
"extlibs/headers",
"extlibs/headers/libfreetype/osx",
"extlibs/headers/libfreetype/osx/freetype2",
"extlibs/headers/libsdl2/osx" }
libdirs { "/usr/lib", "/usr/local/lib",
"extlibs/libs-osx/Frameworks", "extlibs/libs-osx/lib" }
links { "freetype", "GLEW", "lua", "ogg", "SDL2",
"vorbis", "vorbisfile", "theoradec" }
links { "AudioToolbox.framework", "AudioUnit.framework",
"Carbon.framework", "Cocoa.framework", "CoreAudio.framework",
"CoreFoundation.framework", "ForceFeedback.framework",
"IOKit.framework", "OpenAL.framework", "OpenGL.framework" }
configuration "windows"
includedirs { "extlibs/headers",
"extlibs/headers/libfreetype/windows",
"extlibs/headers/libfreetype/windows/freetype",
"extlibs/headers/libsdl2/windows" }
links { "freetype", "glew32s", "libogg_static",
"libtheora_static", "libvorbis_static",
"libvorbisfile_static", "lua", "OpenAL32",
"SDL2", "SDL2main", "opengl32", "glu32",
"Imm32", "version", "winmm" }
if os.is64bit then
libdirs { "extlibs/libs-msvc/x64" }
else
libdirs { "extlibs/libs-msvc/x86" }
end
|
Several fixes for building on Linux.
|
Several fixes for building on Linux.
|
Lua
|
mpl-2.0
|
Senscape/Dagon,Senscape/Dagon
|
2c3363bb675f847fd60ba5e125560ded4c271c7f
|
lua/entities/starfall_screen/init.lua
|
lua/entities/starfall_screen/init.lua
|
AddCSLuaFile('cl_init.lua')
AddCSLuaFile('shared.lua')
include('shared.lua')
include("starfall/SFLib.lua")
assert(SF, "Starfall didn't load correctly!")
local context = SF.CreateContext()
local screens = {}
util.AddNetworkString( "starfall_screen_download" )
util.AddNetworkString( "starfall_screen_update" )
util.AddNetworkString( "starfall_screen_used" )
local function sendScreenCode ( screen, owner, files, mainfile, recipient )
net.Start( "starfall_screen_download" )
net.WriteEntity( screen )
net.WriteEntity( owner )
net.WriteString( mainfile )
if recipient then net.Send( recipient ) else net.Broadcast() end
local fname = next( files )
while fname do
local fdata = files[ fname ]
local offset = 1
repeat
net.Start( "starfall_screen_download" )
net.WriteBit( false )
net.WriteString( fname )
local data = fdata:sub( offset, offset + 60000 )
net.WriteString( data )
if recipient then net.Send( recipient ) else net.Broadcast() end
offset = offset + #data + 1
until offset > #fdata
fname = next( files, fname )
end
net.Start( "starfall_screen_download" )
net.WriteBit( true )
if recipient then net.Send( recipient ) else net.Broadcast() end
end
local requests = {}
local function sendCodeRequest(ply, screenid)
local screen = Entity(screenid)
if not screen.mainfile then
if not requests[screenid] then requests[screenid] = {} end
if requests[screenid][player] then return end
requests[screenid][ply] = true
return
elseif screen.mainfile then
if requests[screenid] then
requests[screenid][ply] = nil
end
sendScreenCode(screen, screen.owner, screen.files, screen.mainfile, ply)
end
end
local function retryCodeRequests()
for screenid,plys in pairs(requests) do
for ply,_ in pairs(requests[screenid]) do
sendCodeRequest(ply, screenid)
end
end
end
net.Receive("starfall_screen_download", function(len, ply)
local screen = net.ReadEntity()
sendCodeRequest(ply, screen:EntIndex())
end)
function ENT:Initialize ()
self.BaseClass.Initialize( self )
self:SetUseType( 3 )
end
function ENT:Error ( msg, traceback )
self.BaseClass.Error( self, msg, traceback )
end
function ENT:CodeSent(ply, files, mainfile)
if ply ~= self.owner then return end
local update = self.mainfile ~= nil
self.files = files
self.mainfile = mainfile
screens[self] = self
if update then
net.Start("starfall_screen_update")
net.WriteEntity(self)
for k,v in pairs(files) do
net.WriteBit(false)
net.WriteString(k)
net.WriteString(util.CRC(v))
end
net.WriteBit(true)
net.Broadcast()
--sendScreenCode(self, ply, files, mainfile)
end
local ppdata = {}
SF.Preprocessor.ParseDirectives(mainfile, files[mainfile], {}, ppdata)
if ppdata.sharedscreen then
local ok, instance = SF.Compiler.Compile( files, context, mainfile, ply, { entity = self } )
if not ok then self:Error(instance) return end
instance.runOnError = function(inst,...) self:Error(...) end
if self.instance then
self.instance:deinitialize()
self.instance = nil
end
self.instance = instance
local ok, msg, traceback = instance:initialize()
if not ok then
self:Error( msg, traceback )
return
end
if not self.instance then return end
local r,g,b,a = self:GetColor()
self:SetColor(Color(255, 255, 255, a))
self.sharedscreen = true
end
end
local i = 0
function ENT:Think()
self.BaseClass.Think(self)
i = i + 1
if i % 22 == 0 then
retryCodeRequests()
i = 0
end
self:NextThink(CurTime())
if self.instance and not self.instance.error then
self.instance:updateCPUBuffer()
self:runScriptHook("think")
end
return true
end
-- Sends a net message to all clients about the use.
function ENT:Use( activator )
if activator:IsPlayer() then
net.Start( "starfall_screen_used" )
net.WriteEntity( self )
net.WriteEntity( activator )
net.Broadcast()
end
if self.sharedscreen then
self:runScriptHook( "starfallUsed", SF.Entities.Wrap( activator ) )
end
end
function ENT:OnRemove()
self.BaseClass.OnRemove( self )
screens[ self ] = nil
end
local function tableCopy ( t, lookup_table )
if ( t == nil ) then return nil end
local copy = {}
setmetatable( copy, debug.getmetatable( t ) )
for i, v in pairs( t ) do
if ( not istable( v ) ) then
copy[ i ] = v
else
lookup_table = lookup_table or {}
lookup_table[ t ] = copy
if lookup_table[ v ] then
copy[ i ] = lookup_table[ v ] -- we already copied this table. reuse the copy.
else
copy[ i ] = table.Copy( v, lookup_table ) -- not yet copied. copy it.
end
end
end
return copy
end
function ENT:BuildDupeInfo ()
local info = self.BaseClass.BuildDupeInfo( self ) or {}
info.starfall = SF.SerializeCode( self.files, self.mainfile )
return info
end
function ENT:ApplyDupeInfo ( ply, ent, info, GetEntByID )
self.BaseClass.ApplyDupeInfo( self, ply, ent, info, GetEntByID )
self.owner = ply
local code, main = SF.DeserializeCode( info.starfall )
self:CodeSent( ply, code, main )
end
|
AddCSLuaFile('cl_init.lua')
AddCSLuaFile('shared.lua')
include('shared.lua')
include("starfall/SFLib.lua")
assert(SF, "Starfall didn't load correctly!")
local context = SF.CreateContext()
local screens = {}
util.AddNetworkString( "starfall_screen_download" )
util.AddNetworkString( "starfall_screen_update" )
util.AddNetworkString( "starfall_screen_used" )
local function sendScreenCode ( screen, owner, files, mainfile, recipient )
net.Start( "starfall_screen_download" )
net.WriteEntity( screen )
net.WriteEntity( owner )
net.WriteString( mainfile )
if recipient then net.Send( recipient ) else net.Broadcast() end
local fname = next( files )
while fname do
local fdata = files[ fname ]
local offset = 1
repeat
net.Start( "starfall_screen_download" )
net.WriteBit( false )
net.WriteString( fname )
local data = fdata:sub( offset, offset + 60000 )
net.WriteString( data )
if recipient then net.Send( recipient ) else net.Broadcast() end
offset = offset + #data + 1
until offset > #fdata
fname = next( files, fname )
end
net.Start( "starfall_screen_download" )
net.WriteBit( true )
if recipient then net.Send( recipient ) else net.Broadcast() end
end
local requests = {}
local function sendCodeRequest(ply, screenid)
local screen = Entity(screenid)
if not screen.mainfile then
if not requests[screenid] then requests[screenid] = {} end
if requests[screenid][player] then return end
requests[screenid][ply] = true
return
elseif screen.mainfile then
if requests[screenid] then
requests[screenid][ply] = nil
end
sendScreenCode(screen, screen.owner, screen.files, screen.mainfile, ply)
end
end
local function retryCodeRequests()
for screenid,plys in pairs(requests) do
for ply,_ in pairs(requests[screenid]) do
sendCodeRequest(ply, screenid)
end
end
end
net.Receive("starfall_screen_download", function(len, ply)
local screen = net.ReadEntity()
sendCodeRequest(ply, screen:EntIndex())
end)
function ENT:Initialize ()
self.BaseClass.Initialize( self )
self:SetUseType( 3 )
end
function ENT:Error ( msg, traceback )
self.BaseClass.Error( self, msg, traceback )
end
function ENT:CodeSent(ply, files, mainfile)
if ply ~= self.owner then return end
local update = self.mainfile ~= nil
self.files = files
self.mainfile = mainfile
screens[self] = self
if update then
net.Start("starfall_screen_update")
net.WriteEntity(self)
for k,v in pairs(files) do
net.WriteBit(false)
net.WriteString(k)
net.WriteString(util.CRC(v))
end
net.WriteBit(true)
net.Broadcast()
--sendScreenCode(self, ply, files, mainfile)
end
local ppdata = {}
SF.Preprocessor.ParseDirectives(mainfile, files[mainfile], {}, ppdata)
if ppdata.sharedscreen then
local ok, instance = SF.Compiler.Compile( files, context, mainfile, ply, { entity = self } )
if not ok then self:Error(instance) return end
instance.runOnError = function(inst,...) self:Error(...) end
if self.instance then
self.instance:deinitialize()
self.instance = nil
end
self.instance = instance
local ok, msg, traceback = instance:initialize()
if not ok then
self:Error( msg, traceback )
return
end
if not self.instance then return end
local r,g,b,a = self:GetColor()
self:SetColor(Color(255, 255, 255, a))
self.sharedscreen = true
end
end
local i = 0
function ENT:Think()
self.BaseClass.Think(self)
i = i + 1
if i % 22 == 0 then
retryCodeRequests()
i = 0
end
self:NextThink(CurTime())
if self.instance and not self.instance.error then
self.instance:updateCPUBuffer()
self:runScriptHook("think")
end
return true
end
-- Sends a net message to all clients about the use.
function ENT:Use( activator )
if activator:IsPlayer() then
net.Start( "starfall_screen_used" )
net.WriteEntity( self )
net.WriteEntity( activator )
net.Broadcast()
end
if self.sharedscreen then
self:runScriptHook( "starfallUsed", SF.Entities.Wrap( activator ) )
end
end
function ENT:OnRemove()
self.BaseClass.OnRemove( self )
screens[ self ] = nil
end
function ENT:BuildDupeInfo ()
local info = self.BaseClass.BuildDupeInfo( self ) or {}
info.starfall = SF.SerializeCode( self.files, self.mainfile )
return info
end
function ENT:ApplyDupeInfo ( ply, ent, info, GetEntByID )
self.BaseClass.ApplyDupeInfo( self, ply, ent, info, GetEntByID )
self.owner = ply
local code, main = SF.DeserializeCode( info.starfall )
self:CodeSent( ply, code, main )
end
|
Fixing the missed table.copy from #210 fix.
|
Fixing the missed table.copy from #210 fix.
|
Lua
|
bsd-3-clause
|
INPStarfall/Starfall,Jazzelhawk/Starfall,Jazzelhawk/Starfall,INPStarfall/Starfall,Ingenious-Gaming/Starfall,Xandaros/Starfall,Xandaros/Starfall,Ingenious-Gaming/Starfall
|
aad9966403ee37a69215fe9b2ffb0cb169c0b265
|
Modules/Thumbnail/PlayerThumbnails.lua
|
Modules/Thumbnail/PlayerThumbnails.lua
|
--- Reimplementation of Player:GetUserThumbnailAsync but as a promise with
-- retry logic
-- @module PlayerThumbnails
local require = require(game:GetService("ReplicatedStorage"):WaitForChild("Nevermore"))
local Players = game:GetService("Players")
local Promise = require("Promise")
local PlayerThumbnails = {}
PlayerThumbnails.ThumbnailPollerName = "PlayerThumbnails"
PlayerThumbnails.__index = PlayerThumbnails
PlayerThumbnails.MAX_TRIES = 5
function PlayerThumbnails.new()
local self = setmetatable({}, PlayerThumbnails)
return self
end
function PlayerThumbnails:GetUserThumbnail(userId, thumbnailType, thumbnailSize)
assert(userId)
assert(thumbnailType)
assert(thumbnailSize)
local promise
promise = Promise.new(function(resolve, reject)
local tries = 0
repeat
tries = tries + 1
local content, isReady = Players:GetUserThumbnailAsync(userId, thumbnailType, thumbnailSize)
if isReady then
return resolve(content)
else
wait(0.05)
end
until tries >= self.MAX_TRIES or (not promise:IsPending())
reject()
end)
return promise
end
return PlayerThumbnails.new()
|
--- Reimplementation of Player:GetUserThumbnailAsync but as a promise with
-- retry logic
-- @module PlayerThumbnails
local require = require(game:GetService("ReplicatedStorage"):WaitForChild("Nevermore"))
local Players = game:GetService("Players")
local Promise = require("Promise")
local PlayerThumbnails = {}
PlayerThumbnails.ThumbnailPollerName = "PlayerThumbnails"
PlayerThumbnails.__index = PlayerThumbnails
PlayerThumbnails.MAX_TRIES = 5
function PlayerThumbnails.new()
local self = setmetatable({}, PlayerThumbnails)
return self
end
function PlayerThumbnails:GetUserThumbnail(userId, thumbnailType, thumbnailSize)
assert(userId)
assert(thumbnailType)
assert(thumbnailSize)
local promise
promise = Promise.new(function(resolve, reject)
local tries = 0
repeat
tries = tries + 1
local content, isReady
local ok, err = pcall(function()
content, isReady = Players:GetUserThumbnailAsync(userId, thumbnailType, thumbnailSize)
end)
-- Don't retry if we immediately error (timeout exceptions!)
if not ok then
return reject(err)
end
if isReady then
return resolve(content)
else
wait(0.05)
end
until tries >= self.MAX_TRIES or (not promise:IsPending())
reject()
end)
return promise
end
return PlayerThumbnails.new()
|
Fix PlayerThumbnails so it doesn't error on timeout
|
Fix PlayerThumbnails so it doesn't error on timeout
|
Lua
|
mit
|
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
|
4fa96290d576fecb42eb8dedefb452092314a067
|
lux/lux-expt/tsl2561lib.lua
|
lux/lux-expt/tsl2561lib.lua
|
-- This code is AGPL v3 by [email protected]
-- blah blah blah standard licence conditions apply blah blah blah
-- Special hat-tip to lady ada - hacker hero - amongst many others
-- Reads value of TSL2561 I2C Luminosity sensor
-- As used on breakout board by Adafruit
-- the package table, and lots of constants
tsl2561lib = {
TSL2561_ADDR_FLOAT = 0x39,
TSL2561_COMMAND_BIT = 0x80, -- Must be 1
TSL2561_CONTROL_POWERON = 0x03,
TSL2561_CONTROL_POWEROFF = 0x00,
TSL2561_REGISTER_CONTROL = 0x00,
TSL2561_REGISTER_TIMING = 0x01,
TSL2561_REGISTER_ID = 0x0A,
TSL2561_REGISTER_CHAN0_LOW = 0x0C,
TSL2561_REGISTER_CHAN0_HIGH = 0x0D,
TSL2561_REGISTER_CHAN1_LOW = 0x0E,
TSL2561_REGISTER_CHAN1_HIGH = 0x0F,
TSL2561_INTEGRATIONTIME_13MS = 0x00, -- 13.7ms
TSL2561_INTEGRATIONTIME_101MS = 0x01, -- 101ms
TSL2561_INTEGRATIONTIME_402MS = 0x02, -- 402ms
TSL2561_GAIN_0X = 0x00, -- No gain
TSL2561_GAIN_16X = 0x10, -- 16x gain
TSL2561_LUX_CHSCALE = 10, -- Scale channel values by 2^10
TSL2561_LUX_CHSCALE_TINT0 = 0x7517, -- 322/11 * 2^TSL2561_LUX_CHSCALE
TSL2561_LUX_LUXSCALE = 14, -- Scale by 2^14
TSL2561_LUX_RATIOSCALE = 9, -- Scale ratio by 2^9
-- T, FN and CL package values
TSL2561_LUX_K1T = 0x0040, -- 0.125 * 2^RATIO_SCALE
TSL2561_LUX_B1T = 0x01f2, -- 0.0304 * 2^LUX_SCALE
TSL2561_LUX_M1T = 0x01be, -- 0.0272 * 2^LUX_SCALE
TSL2561_LUX_K2T = 0x0080, -- 0.250 * 2^RATIO_SCALE
TSL2561_LUX_B2T = 0x0214, -- 0.0325 * 2^LUX_SCALE
TSL2561_LUX_M2T = 0x02d1, -- 0.0440 * 2^LUX_SCALE
TSL2561_LUX_K3T = 0x00c0, -- 0.375 * 2^RATIO_SCALE
TSL2561_LUX_B3T = 0x023f, -- 0.0351 * 2^LUX_SCALE
TSL2561_LUX_M3T = 0x037b, -- 0.0544 * 2^LUX_SCALE
TSL2561_LUX_K4T = 0x0100, -- 0.50 * 2^RATIO_SCALE
TSL2561_LUX_B4T = 0x0270, -- 0.0381 * 2^LUX_SCALE
TSL2561_LUX_M4T = 0x03fe, -- 0.0624 * 2^LUX_SCALE
TSL2561_LUX_K5T = 0x0138, -- 0.61 * 2^RATIO_SCALE
TSL2561_LUX_B5T = 0x016f, -- 0.0224 * 2^LUX_SCALE
TSL2561_LUX_M5T = 0x01fc, -- 0.0310 * 2^LUX_SCALE
TSL2561_LUX_K6T = 0x019a, -- 0.80 * 2^RATIO_SCALE
TSL2561_LUX_B6T = 0x00d2, -- 0.0128 * 2^LUX_SCALE
TSL2561_LUX_M6T = 0x00fb, -- 0.0153 * 2^LUX_SCALE
TSL2561_LUX_K7T = 0x029a, -- 1.3 * 2^RATIO_SCALE
TSL2561_LUX_B7T = 0x0018, -- 0.00146 * 2^LUX_SCALE
TSL2561_LUX_M7T = 0x0012, -- 0.00112 * 2^LUX_SCALE
TSL2561_LUX_K8T = 0x029a, -- 1.3 * 2^RATIO_SCALE
TSL2561_LUX_B8T = 0x0000, -- 0.000 * 2^LUX_SCALE
TSL2561_LUX_M8T = 0x0000, -- 0.000 * 2^LUX_SCALE
id = 0, -- identify (software) I2C bus
-- this maps GPIO numbers to internal IO references
io_pin= {[0]=3,[2]=4,[4]=2,[5]=1,[12]=6,[13]=7,[14]=5},
}
-- add a few recursive definitions
tl = tsl2561lib
tl.sda=tl.io_pin[14] -- connect to pin GPIO14
tl.scl=tl.io_pin[12] -- connect to pin GPIO12
tl.addr=tl.TSL2561_ADDR_FLOAT -- I2C address of device with ADDR pin floating
function tl.read_reg(dev_addr, reg_addr) -- read a single byte from register
id = tl.id
i2c.start(id)
i2c.address(id, dev_addr, i2c.TRANSMITTER)
i2c.write(id,reg_addr)
i2c.stop(id)
i2c.start(id)
i2c.address(id, dev_addr,i2c.RECEIVER)
c=i2c.read(id,1)
print("read command 0x"..string.format("%02X",reg_addr),"0x"..string.format("%02X",string.byte(c)))
i2c.stop(id)
return c
end
function tl.write_reg(dev_addr, reg_addr, reg_val)
id = tl.id
i2c.start(id)
i2c.address(id, dev_addr, i2c.TRANSMITTER)
i2c.write(id, reg_addr)
i2c.write(id, reg_val)
i2c.stop(id)
print("write command 0x"..string.format("%02X",reg_addr),"0x"..string.format("%02X",reg_val))
return c
end
function tl.initialise(dev_addr) -- initialize i2c with our id and pins in slow mode :-)
id = tl.id
i2c.setup(id, tl.sda, tl.scl, i2c.SLOW)
result=tl.read_reg(dev_addr,bit.bor(tl.TSL2561_COMMAND_BIT,tl.TSL2561_REGISTER_ID))
if string.byte(result) == 0x50 then
print("Initialised TSL2561T/FN/CL")
end
end
function tl.enable(dev_addr) -- enable the device
write_reg(dev_addr,bit.bor(TSL2561_COMMAND_BIT,TSL2561_REGISTER_CONTROL), TSL2561_CONTROL_POWERON)
-- if we add the below statement, then require("lux") will trigger reboot
-- --[[
print(" ")
print(" ")
print(" ")
print(" ")
print(" ")
print(" ")
print(" ")
print(" ")
print(" ")
print(" ")
-- ]] --
end
function tl.disable(dev_addr) -- disable the device
write_reg(dev_addr,bit.bor(TSL2561_COMMAND_BIT,TSL2561_REGISTER_CONTROL), TSL2561_CONTROL_POWEROFF)
end
function tl.settimegain(dev_addr, time, gain) -- set the integration time and gain together
write_reg(dev_addr,bit.bor(TSL2561_COMMAND_BIT,TSL2561_REGISTER_TIMING), bit.bor(time,gain))
end
function tl.getFullLuminosity(dev_addr) -- Do the actual reading from the sensor
tmr.delay(14000)
ch0low = read_reg(dev_addr, bit.bor(TSL2561_COMMAND_BIT, TSL2561_REGISTER_CHAN0_LOW))
ch0high = read_reg(dev_addr,bit.bor(TSL2561_COMMAND_BIT, TSL2561_REGISTER_CHAN0_HIGH))
ch0=string.byte(ch0low)+(string.byte(ch0high)*256)
ch1low = read_reg(dev_addr, bit.bor(TSL2561_COMMAND_BIT, TSL2561_REGISTER_CHAN1_LOW))
ch1high = read_reg(dev_addr,bit.bor(TSL2561_COMMAND_BIT, TSL2561_REGISTER_CHAN1_HIGH))
ch1=string.byte(ch1low)+(string.byte(ch1high)*256)
return ch0,ch1
end
-- print("Setup 1 complete")
return tl
|
-- This code is AGPL v3 by [email protected]
-- blah blah blah standard licence conditions apply blah blah blah
-- Special hat-tip to lady ada - hacker hero - amongst many others
-- Reads value of TSL2561 I2C Luminosity sensor
-- As used on breakout board by Adafruit
-- the package table, and lots of constants
tsl2561lib = {
TSL2561_ADDR_FLOAT = 0x39,
TSL2561_COMMAND_BIT = 0x80, -- Must be 1
TSL2561_CONTROL_POWERON = 0x03,
TSL2561_CONTROL_POWEROFF = 0x00,
TSL2561_REGISTER_CONTROL = 0x00,
TSL2561_REGISTER_TIMING = 0x01,
TSL2561_REGISTER_ID = 0x0A,
TSL2561_REGISTER_CHAN0_LOW = 0x0C,
TSL2561_REGISTER_CHAN0_HIGH = 0x0D,
TSL2561_REGISTER_CHAN1_LOW = 0x0E,
TSL2561_REGISTER_CHAN1_HIGH = 0x0F,
TSL2561_INTEGRATIONTIME_13MS = 0x00, -- 13.7ms
TSL2561_INTEGRATIONTIME_101MS = 0x01, -- 101ms
TSL2561_INTEGRATIONTIME_402MS = 0x02, -- 402ms
TSL2561_GAIN_0X = 0x00, -- No gain
TSL2561_GAIN_16X = 0x10, -- 16x gain
TSL2561_LUX_CHSCALE = 10, -- Scale channel values by 2^10
TSL2561_LUX_CHSCALE_TINT0 = 0x7517, -- 322/11 * 2^TSL2561_LUX_CHSCALE
TSL2561_LUX_LUXSCALE = 14, -- Scale by 2^14
TSL2561_LUX_RATIOSCALE = 9, -- Scale ratio by 2^9
-- T, FN and CL package values
TSL2561_LUX_K1T = 0x0040, -- 0.125 * 2^RATIO_SCALE
TSL2561_LUX_B1T = 0x01f2, -- 0.0304 * 2^LUX_SCALE
TSL2561_LUX_M1T = 0x01be, -- 0.0272 * 2^LUX_SCALE
TSL2561_LUX_K2T = 0x0080, -- 0.250 * 2^RATIO_SCALE
TSL2561_LUX_B2T = 0x0214, -- 0.0325 * 2^LUX_SCALE
TSL2561_LUX_M2T = 0x02d1, -- 0.0440 * 2^LUX_SCALE
TSL2561_LUX_K3T = 0x00c0, -- 0.375 * 2^RATIO_SCALE
TSL2561_LUX_B3T = 0x023f, -- 0.0351 * 2^LUX_SCALE
TSL2561_LUX_M3T = 0x037b, -- 0.0544 * 2^LUX_SCALE
TSL2561_LUX_K4T = 0x0100, -- 0.50 * 2^RATIO_SCALE
TSL2561_LUX_B4T = 0x0270, -- 0.0381 * 2^LUX_SCALE
TSL2561_LUX_M4T = 0x03fe, -- 0.0624 * 2^LUX_SCALE
TSL2561_LUX_K5T = 0x0138, -- 0.61 * 2^RATIO_SCALE
TSL2561_LUX_B5T = 0x016f, -- 0.0224 * 2^LUX_SCALE
TSL2561_LUX_M5T = 0x01fc, -- 0.0310 * 2^LUX_SCALE
TSL2561_LUX_K6T = 0x019a, -- 0.80 * 2^RATIO_SCALE
TSL2561_LUX_B6T = 0x00d2, -- 0.0128 * 2^LUX_SCALE
TSL2561_LUX_M6T = 0x00fb, -- 0.0153 * 2^LUX_SCALE
TSL2561_LUX_K7T = 0x029a, -- 1.3 * 2^RATIO_SCALE
TSL2561_LUX_B7T = 0x0018, -- 0.00146 * 2^LUX_SCALE
TSL2561_LUX_M7T = 0x0012, -- 0.00112 * 2^LUX_SCALE
TSL2561_LUX_K8T = 0x029a, -- 1.3 * 2^RATIO_SCALE
TSL2561_LUX_B8T = 0x0000, -- 0.000 * 2^LUX_SCALE
TSL2561_LUX_M8T = 0x0000, -- 0.000 * 2^LUX_SCALE
id = 0, -- identify (software) I2C bus
-- this maps GPIO numbers to internal IO references
io_pin= {[0]=3,[2]=4,[4]=2,[5]=1,[12]=6,[13]=7,[14]=5},
}
-- add a few recursive definitions
tl = tsl2561lib
tl.sda=tl.io_pin[14] -- connect to pin GPIO14
tl.scl=tl.io_pin[12] -- connect to pin GPIO12
tl.addr=tl.TSL2561_ADDR_FLOAT -- I2C address of device with ADDR pin floating
function tl.read_reg(dev_addr, reg_addr) -- read a single byte from register
id = tl.id
i2c.start(id)
i2c.address(id, dev_addr, i2c.TRANSMITTER)
i2c.write(id,reg_addr)
i2c.stop(id)
i2c.start(id)
i2c.address(id, dev_addr,i2c.RECEIVER)
c=i2c.read(id,1)
print("read command 0x"..string.format("%02X",reg_addr),"0x"..string.format("%02X",string.byte(c)))
i2c.stop(id)
return c
end
function tl.write_reg(dev_addr, reg_addr, reg_val)
id = tl.id
i2c.start(id)
i2c.address(id, dev_addr, i2c.TRANSMITTER)
i2c.write(id, reg_addr)
i2c.write(id, reg_val)
i2c.stop(id)
print("write command 0x"..string.format("%02X",reg_addr),"0x"..string.format("%02X",reg_val))
return c
end
function tl.initialise(dev_addr) -- initialize i2c with our id and pins in slow mode :-)
id = tl.id
i2c.setup(id, tl.sda, tl.scl, i2c.SLOW)
result=tl.read_reg(dev_addr,bit.bor(tl.TSL2561_COMMAND_BIT,tl.TSL2561_REGISTER_ID))
if string.byte(result) == 0x50 then
print("Initialised TSL2561T/FN/CL")
end
end
function tl.enable(dev_addr) -- enable the device
write_reg(dev_addr,bit.bor(TSL2561_COMMAND_BIT,TSL2561_REGISTER_CONTROL), TSL2561_CONTROL_POWERON)
-- if we add the below statement, then require("lux") will trigger reboot
-- TODO finish adding tl. references... but need to resolve code size issue first!
--[[
print(" ")
print(" ")
print(" ")
print(" ")
print(" ")
print(" ")
print(" ")
print(" ")
print(" ")
print(" ")
]] --
end
function tl.disable(dev_addr) -- disable the device
write_reg(dev_addr,bit.bor(TSL2561_COMMAND_BIT,TSL2561_REGISTER_CONTROL), TSL2561_CONTROL_POWEROFF)
end
function tl.settimegain(dev_addr, time, gain) -- set the integration time and gain together
write_reg(dev_addr,bit.bor(TSL2561_COMMAND_BIT,TSL2561_REGISTER_TIMING), bit.bor(time,gain))
end
function tl.getFullLuminosity(dev_addr) -- Do the actual reading from the sensor
tmr.delay(14000)
ch0low = read_reg(dev_addr, bit.bor(TSL2561_COMMAND_BIT, TSL2561_REGISTER_CHAN0_LOW))
ch0high = read_reg(dev_addr,bit.bor(TSL2561_COMMAND_BIT, TSL2561_REGISTER_CHAN0_HIGH))
ch0=string.byte(ch0low)+(string.byte(ch0high)*256)
ch1low = read_reg(dev_addr, bit.bor(TSL2561_COMMAND_BIT, TSL2561_REGISTER_CHAN1_LOW))
ch1high = read_reg(dev_addr,bit.bor(TSL2561_COMMAND_BIT, TSL2561_REGISTER_CHAN1_HIGH))
ch1=string.byte(ch1low)+(string.byte(ch1high)*256)
return ch0,ch1
end
-- print("Setup 1 complete")
return tl
|
note re. code size bug and lux refactor
|
note re. code size bug and lux refactor
|
Lua
|
agpl-3.0
|
pastukhov/fishy-wifi,pastukhov/fishy-wifi,hamishcunningham/fishy-wifi,hamishcunningham/fishy-wifi,pastukhov/fishy-wifi,hamishcunningham/fishy-wifi,hamishcunningham/fishy-wifi,pastukhov/fishy-wifi,hamishcunningham/fishy-wifi,hamishcunningham/fishy-wifi
|
4307ac5dabce5177d1517b0e043a35b5a7c58512
|
xmake/actions/require/impl/environment.lua
|
xmake/actions/require/impl/environment.lua
|
--!A cross-platform build utility based on Lua
--
-- Licensed to the Apache Software Foundation (ASF) under one
-- or more contributor license agreements. See the NOTICE file
-- distributed with this work for additional information
-- regarding copyright ownership. The ASF licenses this file
-- to you under the Apache License, Version 2.0 (the
-- "License"); you may not use this file except in compliance
-- with the License. You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015 - 2018, TBOOX Open Source Group.
--
-- @author ruki
-- @file environment.lua
--
-- imports
import("core.project.config")
import("core.platform.environment")
import("core.package.package", {alias = "core_package"})
import("lib.detect.find_tool")
import("package")
-- enter environment
--
-- ensure that we can find some basic tools: git, make/nmake/cmake, msbuild ...
--
-- If these tools not exist, we will install it first.
--
function enter()
-- set search pathes of toolchains
environment.enter("toolchains")
-- git not found? install it first
if not find_tool("git") then
package.install_packages("git")
end
-- get prefix directories
local plat = get_config("plat")
local arch = get_config("arch")
_g.prefixdirs = _g.prefixdirs or
{
core_package.prefixdir(false, false, plat, arch),
core_package.prefixdir(false, true, plat, arch),
core_package.prefixdir(true, false, plat, arch),
core_package.prefixdir(true, true, plat, arch)
}
-- add search directories of pkgconfig, aclocal
_g._ACLOCAL_PATH = os.getenv("ACLOCAL_PATH")
_g._PKG_CONFIG_PATH = os.getenv("PKG_CONFIG_PATH")
if not is_plat("windows") then
for _, prefixdir in ipairs(_g.prefixdirs) do
os.addenv("ACLOCAL_PATH", path.join(prefixdir, "share", "aclocal"))
os.addenv("PKG_CONFIG_PATH", path.join(prefixdir, "lib", "pkgconfig"))
end
end
end
-- leave environment
function leave()
-- restore search directories of pkgconfig, aclocal
os.setenv("ACLOCAL_PATH", _g._ACLOCAL_PATH)
os.setenv("PKG_CONFIG_PATH", _g._PKG_CONFIG_PATH)
-- restore search pathes of toolchains
environment.leave("toolchains")
end
|
--!A cross-platform build utility based on Lua
--
-- Licensed to the Apache Software Foundation (ASF) under one
-- or more contributor license agreements. See the NOTICE file
-- distributed with this work for additional information
-- regarding copyright ownership. The ASF licenses this file
-- to you under the Apache License, Version 2.0 (the
-- "License"); you may not use this file except in compliance
-- with the License. You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015 - 2018, TBOOX Open Source Group.
--
-- @author ruki
-- @file environment.lua
--
-- imports
import("core.project.config")
import("core.platform.environment")
import("core.package.package", {alias = "core_package"})
import("lib.detect.find_tool")
import("package")
-- enter environment
--
-- ensure that we can find some basic tools: git, make/nmake/cmake, msbuild ...
--
-- If these tools not exist, we will install it first.
--
function enter()
-- set search pathes of toolchains
environment.enter("toolchains")
-- git not found? install it first
if not find_tool("git") then
package.install_packages("git")
end
-- get prefix directories
local plat = get_config("plat")
local arch = get_config("arch")
_g.prefixdirs = _g.prefixdirs or
{
core_package.prefixdir(false, false, plat, arch),
core_package.prefixdir(false, true, plat, arch),
core_package.prefixdir(true, false, plat, arch),
core_package.prefixdir(true, true, plat, arch)
}
-- add search directories of pkgconfig, aclocal, cmake
_g._ACLOCAL_PATH = os.getenv("ACLOCAL_PATH")
_g._PKG_CONFIG_PATH = os.getenv("PKG_CONFIG_PATH")
_g._CMAKE_PREFIX_PATH = os.getenv("CMAKE_PREFIX_PATH")
for _, prefixdir in ipairs(_g.prefixdirs) do
if not is_plat("windows") then
os.addenv("ACLOCAL_PATH", path.join(prefixdir, "share", "aclocal"))
os.addenv("PKG_CONFIG_PATH", path.join(prefixdir, "lib", "pkgconfig"))
end
os.addenv("CMAKE_PREFIX_PATH", prefixdir)
end
end
-- leave environment
function leave()
-- restore search directories of pkgconfig, aclocal, cmake
os.setenv("ACLOCAL_PATH", _g._ACLOCAL_PATH)
os.setenv("PKG_CONFIG_PATH", _g._PKG_CONFIG_PATH)
os.setenv("CMAKE_PREFIX_PATH", _g._CMAKE_PREFIX_PATH)
-- restore search pathes of toolchains
environment.leave("toolchains")
end
|
add cmake prefix dirs
|
add cmake prefix dirs
|
Lua
|
apache-2.0
|
waruqi/xmake,waruqi/xmake,tboox/xmake,waruqi/xmake,waruqi/xmake,tboox/xmake,tboox/xmake,waruqi/xmake,tboox/xmake,tboox/xmake,tboox/xmake,waruqi/xmake,tboox/xmake,waruqi/xmake
|
165c56a58ee203b5c9c9666bc93a99f3f70e8e35
|
mod_s2s_reload_newcomponent/mod_s2s_reload_newcomponent.lua
|
mod_s2s_reload_newcomponent/mod_s2s_reload_newcomponent.lua
|
local modulemanager = require "core.modulemanager";
local config = require "core.configmanager";
module.host = "*";
local function reload_components()
module:log ("debug", "reload_components");
local defined_hosts = config.getconfig();
for host in pairs(defined_hosts) do
module:log ("debug", "found host %s", host);
if (not hosts[host] and host ~= "*") then
module:log ("debug", "found new host %s", host);
modulemanager.load(host, configmanager.get(host, "core", "component_module"));
end
end;
return;
end
module:hook("config-reloaded", reload_components);
|
local modulemanager = require "core.modulemanager";
local config = require "core.configmanager";
module.host = "*";
local function reload_components()
local defined_hosts = config.getconfig();
for host in pairs(defined_hosts) do
if (not hosts[host] and host ~= "*") then
module:log ("debug", "loading new component %s", host);
modulemanager.load(host, configmanager.get(host, "core", "component_module"));
end
end;
return;
end
module:hook("config-reloaded", reload_components);
|
mod_s2s_reload_newcomponent: fix debug logs
|
mod_s2s_reload_newcomponent: fix debug logs
|
Lua
|
mit
|
Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules
|
3cb99c3a22c096be8797f4b70e7fe22e53efee6f
|
NLBW/res/vnstead/modules/paginator.lua
|
NLBW/res/vnstead/modules/paginator.lua
|
-- paginator module
require "kbd"
require "click"
require "theme"
require "modules/vn"
require 'modules/log'
click.bg = true
local clickInInvArea = function(x, y)
local invx, invy, invw, invh =
tonumber(theme.get("inv.x")),
tonumber(theme.get("inv.y")),
tonumber(theme.get("inv.w")),
tonumber(theme.get("inv.h"));
if ((x >= invx) and (x <= invx + invw) and (y >= invy) and (y <= invy + invh)) then
-- Click in inventory area
return true;
end
return false;
end
local paginatorKbd = function(down, key)
if here().debug then
return
end
if key:find("ctrl") then
vn.skip_mode = down
end
if vn:actonkey(down, key) then
if here().autos then
here():autos();
end
return
end
if down and key == 'space' then
if vn:finish() then
return
end
if paginator.onproceed then
paginator.onproceed();
end
if paginator._last then
if here().walk_to then
vn:request_full_clear();
return walk(here().walk_to)
end
return
end
paginator.process = true
RAW_TEXT = true
return game._realdisp
end
end
local paginatorClick = function(x, y, a, b, c, d)
if here().debug then
return
end
if clickInInvArea(x, y) then
-- Click in inventory area
return
end
local v, g = vn:test_click(x, y);
if v then
-- Click inside some gobj in vn
vn:click_sprite(v, g);
if here().autos then
here():autos();
end
if vn.direct_lock then
return true;
else
return;
end
end
if (paginator._last and here().walk_to) or not paginator._last then
return paginatorKbd(true, 'space')
else
vn:finish();
end
end
local text_page = function(txt)
local s, e
local pg = paginator
local ss = pg._page
local res = ''
if not txt then
return nil;
end
txt = txt:gsub("[ \t\n]+$", ""):gsub("^[ \t\n]+", "");
s, e = txt:find(pg.delim, ss)
if s then
res = txt:sub(ss, s)
pg._page = e + 1
else
pg._last = true
res = txt:sub(ss)
end
res = res:gsub("%$[^%$]+%$", function(s)
s = s:gsub("^%$", ""):gsub("%$$", "");
local f = stead.eval(s)
if not f then
print("Error in expression: ", s)
error("Bug in expression:" .. s);
end
f();
return ''
end)
res = res:gsub("[ \t\n]+$", ""):gsub("^[ \t\n]+", "");
local loc = here();
if loc.nextsnd and res ~= '' then
loc.nextsnd(loc);
end
return res .. '\n'
end
paginator = obj {
nam = 'paginator';
system_type = true;
w = 0;
h = 0;
_page = 1;
var { process = false; on = true; onproceed = false; },
delim = '\n\n';
turnon = function(s)
s.on = true;
end,
turnoff = function(s)
s.on = false;
end,
set_onproceed = function(s, callback)
s.onproceed = callback;
end;
}
local paginatorIfaceCmd = function(f, s, cmd, ...)
local r, v = f(s, cmd, ...)
if here().debug or not paginator.on then
return r, v
end
if type(r) == 'string' and (stead.state or RAW_TEXT) then
if not RAW_TEXT then -- and player_moved() then
if player_moved() then
paginator._page = 1
paginator._last = false
end
game._realdisp = game._lastdisp
end
if RAW_TEXT and not paginator.process and
--- timer:get() == 0 and r:find("^[ \t\n]*$") and not paginator._last then
r:find("^[ \t\n]*$") and not paginator._last then
paginator.process = true
r = game._realdisp
end
if paginator.process or not RAW_TEXT then
while true do
r = text_page(r)
if not r then
paginator._last = true;
game._lastdisp = "\n";
return "\n", v;
end
--- if timer:get() ~= 0 or not r:find("^[ \t\n]*$") or paginator._last then
if not r:find("^[ \t\n]*$") or paginator._last then
break
end
r = game._realdisp
end
end
paginator.process = false
game._lastdisp = r
end
return r, v
end
local paginatorIfaceFmt = function(f, self, cmd, st, moved, r, av, objs, pv)
if paginator.on then
-- st -- changed state (main win), move -- loc changed
-- maybe we should print action reactions and life texts somewhere, but we shouldn't print it to the main window
local l, vv
if st then
if isForcedsc(stead.here()) or NEED_SCENE then
l = stead.here():scene(); -- статическая часть сцены
end
end
vv = stead.fmt(stead.cat(stead.par(stead.scene_delim, l, nil, nil, objs, nil), '^'));
return vv
else
return f(self, cmd, st, moved, r, av, objs, pv);
end
end
local paginatorGetTitle = function(f, s, cmd, ...)
if not paginator.on then
return f(s, cmd, ...)
end
-- else no title
end
stead.phrase_prefix = ''
stead.module_init(function()
hook_keys('space', 'right ctrl', 'left ctrl');
game.click = function(s, x, y, a, b, c, d)
local result;
if paginator.on then
result = paginatorClick(x, y, a, b, c, d);
else
return vn:click(x, y, a, b, c, d);
end
return result;
end
game.kbd = function(s, down, key)
local result;
if paginator.on then
result = paginatorKbd(down, key);
else
return;
end
return result;
end
iface.cmd = stead.hook(iface.cmd, function(f, s, cmd, ...)
vn:need_renew();
return paginatorIfaceCmd(f, s, cmd, ...);
end)
iface.fmt = stead.hook(iface.fmt, function(f, self, cmd, st, moved, r, av, objs, pv)
return paginatorIfaceFmt(f, self, cmd, st, moved, r, av, objs, pv);
end)
instead.get_title = stead.hook(instead.get_title, function(f, s, cmd, ...)
return paginatorGetTitle(f, s, cmd, ...);
end)
end)
|
-- paginator module
require "kbd"
require "click"
require "theme"
require "modules/vn"
require 'modules/log'
click.bg = true
local clickInInvArea = function(x, y)
local invx, invy, invw, invh =
tonumber(theme.get("inv.x")),
tonumber(theme.get("inv.y")),
tonumber(theme.get("inv.w")),
tonumber(theme.get("inv.h"));
if ((x >= invx) and (x <= invx + invw) and (y >= invy) and (y <= invy + invh)) then
-- Click in inventory area
return true;
end
return false;
end
local paginatorKbd = function(down, key)
if here().debug then
return
end
if key:find("ctrl") then
vn.skip_mode = down
end
if vn:actonkey(down, key) then
if here().autos then
here():autos();
end
return
end
if down and key == 'space' then
if vn:finish() then
return
end
if paginator.onproceed then
paginator.onproceed();
end
if paginator._last then
if here().walk_to then
vn:request_full_clear();
return walk(here().walk_to)
end
return
end
paginator.process = true
RAW_TEXT = true
return game._realdisp
end
end
local paginatorClick = function(x, y, a, b, c, d)
if here().debug then
return
end
if clickInInvArea(x, y) then
-- Click in inventory area
return
end
local v, g = vn:test_click(x, y);
if v then
-- Click inside some gobj in vn
vn:click_sprite(v, g);
if here().autos then
here():autos();
end
if vn.direct_lock then
return true;
else
return;
end
end
if (paginator._last and here().walk_to) or not paginator._last then
return paginatorKbd(true, 'space')
else
vn:finish();
end
end
local text_page = function(txt)
local s, e
local pg = paginator
local ss = pg._page
local res = ''
if not txt then
return nil;
end
txt = txt:gsub("[ \t\n]+$", ""):gsub("^[ \t\n]+", "");
s, e = txt:find(pg.delim, ss)
if s then
res = txt:sub(ss, s)
pg._page = e + 1
else
pg._last = true
res = txt:sub(ss)
end
res = res:gsub("%$[^%$]+%$", function(s)
s = s:gsub("^%$", ""):gsub("%$$", "");
local f = stead.eval(s)
if not f then
print("Error in expression: ", s)
error("Bug in expression:" .. s);
end
f();
return ''
end)
res = res:gsub("[ \t\n]+$", ""):gsub("^[ \t\n]+", "");
local loc = here();
if loc.nextsnd and res ~= '' then
loc.nextsnd(loc);
end
return res .. '\n'
end
paginator = obj {
nam = 'paginator';
system_type = true;
w = 0;
h = 0;
_page = 1;
var { process = false; on = true; onproceed = false; },
delim = '\n\n';
turnon = function(s)
s.on = true;
end,
turnoff = function(s)
s.on = false;
end,
set_onproceed = function(s, callback)
s.onproceed = callback;
end;
}
local paginatorIfaceCmd = function(f, s, cmd, ...)
local r, v = f(s, cmd, ...)
if here().debug or not paginator.on then
return r, v
end
if type(r) == 'string' and (stead.state or RAW_TEXT) then
if not RAW_TEXT then -- and player_moved() then
if player_moved() then
paginator._page = 1
paginator._last = false
end
game._realdisp = game._lastdisp
end
if RAW_TEXT and not paginator.process and
--- timer:get() == 0 and r:find("^[ \t\n]*$") and not paginator._last then
r:find("^[ \t\n]*$") and not paginator._last then
paginator.process = true
r = game._realdisp
end
if paginator.process or not RAW_TEXT then
while true do
r = text_page(r)
if not r then
paginator._last = true;
game._lastdisp = "\n";
return "\n", v;
end
--- if timer:get() ~= 0 or not r:find("^[ \t\n]*$") or paginator._last then
if not r:find("^[ \t\n]*$") or paginator._last then
break
end
r = game._realdisp
end
end
paginator.process = false
game._lastdisp = r
end
return r, v
end
local paginatorIfaceFmt = function(f, self, cmd, st, moved, r, av, objs, pv)
if paginator.on then
-- st -- changed state (main win), move -- loc changed
-- maybe we should print action reactions and life texts somewhere, but we shouldn't print it to the main window
local l, vv
if st then
if isForcedsc(stead.here()) or NEED_SCENE then
l = stead.here():scene(); -- статическая часть сцены
end
end
vv = stead.fmt(stead.cat(stead.par(stead.scene_delim, l, nil, nil, objs, nil), '^'));
return vv
else
return f(self, cmd, st, moved, r, av, objs, pv);
end
end
local paginatorGetTitle = function(f, s, cmd, ...)
if not paginator.on then
return f(s, cmd, ...)
end
-- else no title
end
stead.phrase_prefix = ''
stead.module_init(function()
hook_keys('space', 'right ctrl', 'left ctrl');
game.click = function(s, x, y, a, b, c, d)
local result;
if paginator.on then
result = paginatorClick(x, y, a, b, c, d);
else
return vn:click(x, y, a, b, c, d);
end
return result;
end
game.kbd = function(s, down, key)
local result;
if paginator.on then
result = paginatorKbd(down, key);
else
return;
end
return result;
end
end)
iface.cmd = stead.hook(iface.cmd, function(f, s, cmd, ...)
vn:need_renew();
return paginatorIfaceCmd(f, s, cmd, ...);
end)
iface.fmt = stead.hook(iface.fmt, function(f, self, cmd, st, moved, r, av, objs, pv)
return paginatorIfaceFmt(f, self, cmd, st, moved, r, av, objs, pv);
end)
instead.get_title = stead.hook(instead.get_title, function(f, s, cmd, ...)
return paginatorGetTitle(f, s, cmd, ...);
end)
|
dev::NLB-276::Autos first + Page theme modifications + bugfixing
|
dev::NLB-276::Autos first + Page theme modifications + bugfixing
|
Lua
|
agpl-3.0
|
Antokolos/NLB,Antokolos/NLB,Antokolos/NLB,Antokolos/NLB
|
60e01b68a035fa076c03a639f5f62feb0220ed87
|
util/indexedbheap.lua
|
util/indexedbheap.lua
|
local setmetatable = setmetatable;
local math_floor = math.floor;
local t_remove = table.remove;
local function _heap_insert(self, item, sync, item2, index)
local pos = #self + 1;
while true do
local half_pos = math_floor(pos / 2);
if half_pos == 0 or item > self[half_pos] then break; end
self[pos] = self[half_pos];
sync[pos] = sync[half_pos];
index[sync[pos]] = pos;
pos = half_pos;
end
self[pos] = item;
sync[pos] = item2;
index[item2] = pos;
end
local function _percolate_up(self, k, sync, index)
local tmp = self[k];
local tmp_sync = sync[k];
while k ~= 1 do
local parent = math_floor(k/2);
if tmp < self[parent] then break; end
self[k] = self[parent];
sync[k] = sync[parent];
index[sync[k]] = k;
k = parent;
end
self[k] = tmp;
sync[k] = tmp_sync;
index[tmp_sync] = k;
return k;
end
local function _percolate_down(self, k, sync, index)
local tmp = self[k];
local tmp_sync = sync[k];
local size = #self;
local child = 2*k;
while 2*k <= size do
if child ~= size and self[child] > self[child + 1] then
child = child + 1;
end
if tmp > self[child] then
self[k] = self[child];
sync[k] = sync[child];
index[sync[k]] = k;
else
break;
end
k = child;
child = 2*k;
end
self[k] = tmp;
sync[k] = tmp_sync;
index[tmp_sync] = k;
return k;
end
local function _heap_pop(self, sync, index)
local size = #self;
if size == 0 then return nil; end
local result = self[1];
local result_sync = sync[1];
index[result_sync] = nil;
if size == 1 then
self[1] = nil;
sync[1] = nil;
return result, result_sync;
end
self[1] = t_remove(self);
sync[1] = t_remove(sync);
index[sync[1]] = 1;
_percolate_down(self, 1, sync, index);
return result, result_sync;
end
local indexed_heap = {};
function indexed_heap:insert(item, priority, id)
if id == nil then
id = self.current_id;
self.current_id = id + 1;
end
self.items[id] = item;
_heap_insert(self.priorities, priority, self.ids, id, self.index);
return id;
end
function indexed_heap:pop()
local priority, id = _heap_pop(self.priorities, self.ids, self.index);
if id then
local item = self.items[id];
self.items[id] = nil;
return priority, item, id;
end
end
function indexed_heap:peek()
return self.priorities[1];
end
function indexed_heap:reprioritize(id, priority)
local k = self.index[id];
if k == nil then return; end
self.priorities[k] = priority;
k = _percolate_up(self.priorities, k, self.ids, self.index);
k = _percolate_down(self.priorities, k, self.ids, self.index);
end
function indexed_heap:remove_index(k)
local size = #self.priorities;
local result = self.priorities[k];
local result_sync = self.ids[k];
local item = self.items[result_sync];
if result == nil then return; end
self.index[result_sync] = nil;
self.items[result_sync] = nil;
self.priorities[k] = self.priorities[size];
self.ids[k] = self.ids[size];
self.index[self.ids[k]] = k;
t_remove(self.priorities);
t_remove(self.ids);
k = _percolate_up(self.priorities, k, self.ids, self.index);
k = _percolate_down(self.priorities, k, self.ids, self.index);
return result, item, result_sync;
end
function indexed_heap:remove(id)
return self:remove_index(self.index[id]);
end
local mt = { __index = indexed_heap };
local _M = {
create = function()
return setmetatable({
ids = {}; -- heap of ids, sync'd with priorities
items = {}; -- map id->items
priorities = {}; -- heap of priorities
index = {}; -- map of id->index of id in ids
current_id = 1.5
}, mt);
end
};
return _M;
|
local setmetatable = setmetatable;
local math_floor = math.floor;
local t_remove = table.remove;
local function _heap_insert(self, item, sync, item2, index)
local pos = #self + 1;
while true do
local half_pos = math_floor(pos / 2);
if half_pos == 0 or item > self[half_pos] then break; end
self[pos] = self[half_pos];
sync[pos] = sync[half_pos];
index[sync[pos]] = pos;
pos = half_pos;
end
self[pos] = item;
sync[pos] = item2;
index[item2] = pos;
end
local function _percolate_up(self, k, sync, index)
local tmp = self[k];
local tmp_sync = sync[k];
while k ~= 1 do
local parent = math_floor(k/2);
if tmp < self[parent] then break; end
self[k] = self[parent];
sync[k] = sync[parent];
index[sync[k]] = k;
k = parent;
end
self[k] = tmp;
sync[k] = tmp_sync;
index[tmp_sync] = k;
return k;
end
local function _percolate_down(self, k, sync, index)
local tmp = self[k];
local tmp_sync = sync[k];
local size = #self;
local child = 2*k;
while 2*k <= size do
if child ~= size and self[child] > self[child + 1] then
child = child + 1;
end
if tmp > self[child] then
self[k] = self[child];
sync[k] = sync[child];
index[sync[k]] = k;
else
break;
end
k = child;
child = 2*k;
end
self[k] = tmp;
sync[k] = tmp_sync;
index[tmp_sync] = k;
return k;
end
local function _heap_pop(self, sync, index)
local size = #self;
if size == 0 then return nil; end
local result = self[1];
local result_sync = sync[1];
index[result_sync] = nil;
if size == 1 then
self[1] = nil;
sync[1] = nil;
return result, result_sync;
end
self[1] = t_remove(self);
sync[1] = t_remove(sync);
index[sync[1]] = 1;
_percolate_down(self, 1, sync, index);
return result, result_sync;
end
local indexed_heap = {};
function indexed_heap:insert(item, priority, id)
if id == nil then
id = self.current_id;
self.current_id = id + 1;
end
self.items[id] = item;
_heap_insert(self.priorities, priority, self.ids, id, self.index);
return id;
end
function indexed_heap:pop()
local priority, id = _heap_pop(self.priorities, self.ids, self.index);
if id then
local item = self.items[id];
self.items[id] = nil;
return priority, item, id;
end
end
function indexed_heap:peek()
return self.priorities[1];
end
function indexed_heap:reprioritize(id, priority)
local k = self.index[id];
if k == nil then return; end
self.priorities[k] = priority;
k = _percolate_up(self.priorities, k, self.ids, self.index);
k = _percolate_down(self.priorities, k, self.ids, self.index);
end
function indexed_heap:remove_index(k)
local result = self.priorities[k];
if result == nil then return; end
local result_sync = self.ids[k];
local item = self.items[result_sync];
local size = #self.priorities;
self.priorities[k] = self.priorities[size];
self.ids[k] = self.ids[size];
self.index[self.ids[k]] = k;
t_remove(self.priorities);
t_remove(self.ids);
self.index[result_sync] = nil;
self.items[result_sync] = nil;
if size > k then
k = _percolate_up(self.priorities, k, self.ids, self.index);
k = _percolate_down(self.priorities, k, self.ids, self.index);
end
return result, item, result_sync;
end
function indexed_heap:remove(id)
return self:remove_index(self.index[id]);
end
local mt = { __index = indexed_heap };
local _M = {
create = function()
return setmetatable({
ids = {}; -- heap of ids, sync'd with priorities
items = {}; -- map id->items
priorities = {}; -- heap of priorities
index = {}; -- map of id->index of id in ids
current_id = 1.5
}, mt);
end
};
return _M;
|
util.indexedbheap: Fix a possible traceback when removing the last item.
|
util.indexedbheap: Fix a possible traceback when removing the last item.
|
Lua
|
mit
|
sarumjanuch/prosody,sarumjanuch/prosody
|
0e2d2e1b7adf8a770ef5cbc37a9203b7bf8951bb
|
modules/title/post/olds.lua
|
modules/title/post/olds.lua
|
local sql = require'lsqlite3'
local date = require'date'
local uri = require"handler.uri"
local uri_parse = uri.parse
local patterns = {
-- X://Y url
"^(https?://%S+)",
"^<(https?://%S+)>",
"%f[%S](https?://%S+)",
-- www.X.Y url
"^(www%.[%w_-%%]+%.%S+)",
"%f[%S](www%.[%w_-%%]+%.%S+)",
}
local openDB = function()
local dbfilename = string.format("cache/urls.%s.sql", ivar2.network)
local db = sql.open(dbfilename)
db:exec([[
CREATE TABLE IF NOT EXISTS urls (
nick text,
timestamp integer,
url text,
channel text
);
]])
return db
end
-- check for existing url
local checkOld = function(source, destination, url)
-- Don't lookup root path URLs.
local info = uri_parse(url)
if(info.path == '' or info.path == '/') then
return
end
local db = openDB()
-- create a select handle
local sth = db:prepare([[
SELECT
nick,
timestamp
FROM urls
WHERE
url=?
AND
channel=?
ORDER BY timestamp ASC
]])
-- execute select with a url bound to variable
sth:bind_values(url, destination)
local count, first = 0
while(sth:step() == sql.ROW) do
count = count + 1
if(count == 1) then
first = sth:get_named_values()
end
end
sth:finalize()
db:close()
if(count > 0) then
local age = date.relativeTimeShort(first.timestamp)
return first.nick, count, age
end
end
local updateDB = function(source, destination, url)
local db = openDB()
local sth = db:prepare[[
INSERT INTO urls(nick, channel, url, timestamp)
values(?, ?, ?, ?)
]]
sth:bind_values(source.nick, destination, url, os.time())
sth:step()
sth:finalize()
end
do
return function(source, destination, queue)
local nick, count, age = checkOld(source, destination, queue.url)
updateDB(source, destination, queue.url)
-- relativeTimeShort() returns nil if it gets fed os.time().
if(not age) then return end
local prepend
if(count > 1) then
prepend = string.format("Old! %s times, first by %s %s ago", count, nick, age)
else
prepend = string.format("Old! Linked by %s %s ago", nick, age)
end
if(queue.output) then
queue.output = string.format("%s - %s", prepend, queue.output)
else
queue.output = prepend
end
end
end
|
local sql = require'lsqlite3'
local date = require'date'
local uri = require"handler.uri"
local uri_parse = uri.parse
local patterns = {
-- X://Y url
"^(https?://%S+)",
"^<(https?://%S+)>",
"%f[%S](https?://%S+)",
-- www.X.Y url
"^(www%.[%w_-%%]+%.%S+)",
"%f[%S](www%.[%w_-%%]+%.%S+)",
}
local openDB = function()
local dbfilename = string.format("cache/urls.%s.sql", ivar2.network)
local db = sql.open(dbfilename)
db:exec([[
CREATE TABLE IF NOT EXISTS urls (
nick text,
timestamp integer,
url text,
channel text
);
]])
return db
end
-- check for existing url
local checkOld = function(source, destination, url)
-- Don't lookup root path URLs.
local info = uri_parse(url)
if(info.path == '' or info.path == '/') then
return
end
local db = openDB()
-- create a select handle
local sth = db:prepare([[
SELECT
nick,
timestamp
FROM urls
WHERE
url=?
AND
channel=?
ORDER BY timestamp ASC
]])
-- execute select with a url bound to variable
sth:bind_values(url, destination)
local count, first = 0
while(sth:step() == sql.ROW) do
count = count + 1
if(count == 1) then
first = sth:get_named_values()
end
end
sth:finalize()
db:close()
if(count > 0) then
local age = date.relativeTimeShort(first.timestamp)
return first.nick, count, age
end
end
local updateDB = function(source, destination, url)
local db = openDB()
local sth = db:prepare[[
INSERT INTO urls(nick, channel, url, timestamp)
values(?, ?, ?, ?)
]]
sth:bind_values(source.nick, destination, url, os.time())
sth:step()
sth:finalize()
end
do
return function(source, destination, queue)
local nick, count, age = checkOld(source, destination, queue.url)
updateDB(source, destination, queue.url)
-- relativeTimeShort() returns nil if it gets fed os.time().
-- Don't yell if it's the initial poster.
if(not age or (nick and nick:lower() == source.nick:lower())) then return end
local prepend
if(count > 1) then
prepend = string.format("Old! %s times, first by %s %s ago", count, nick, age)
else
prepend = string.format("Old! Linked by %s %s ago", nick, age)
end
if(queue.output) then
queue.output = string.format("%s - %s", prepend, queue.output)
else
queue.output = prepend
end
end
end
|
title/olds: Don't yell if the poster is the same as the first.
|
title/olds: Don't yell if the poster is the same as the first.
Fixes #45.
Former-commit-id: 6085c6b39c193b74651ba71add32d204b8b4272e [formerly 090d600351bfd88cd7470408ea5c69936143bb69]
Former-commit-id: 49b60c8abd3f2df83c967ba45ea18e6eab2589b2
|
Lua
|
mit
|
torhve/ivar2,torhve/ivar2,haste/ivar2,torhve/ivar2
|
459af8fae97eb810178e6ddd953a64e33395dd60
|
share/lua/playlist/dailymotion.lua
|
share/lua/playlist/dailymotion.lua
|
--[[
Translate Daily Motion video webpages URLs to the corresponding
FLV URL.
$Id$
Copyright © 2007 the VideoLAN team
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
--]]
-- Probe function.
function probe()
return vlc.access == "http"
and string.match( vlc.path, "dailymotion." )
and string.match( vlc.peek( 2048 ), "<!DOCTYPE.*video_type" )
end
function find( haystack, needle )
local _,_,ret = string.find( haystack, needle )
return ret
end
-- Parse function.
function parse()
while true
do
line = vlc.readline()
if not line then break end
if string.match( line, "param name=\"flashvars\" value=\".*video=" )
then
arturl = find( line, "param name=\"flashvars\" value=\".*preview=([^&]*)" )
videos = vlc.strings.decode_uri( find( line, "param name=\"flashvars\" value=\".*video=([^&]*)" ) )
--[[ we get a list of different streams available, at various codecs
and resolutions:
/A@@spark||/B@@spark-mini||/C@@vp6-hd||/D@@vp6||/E@@h264
Not everybody can decode HD, not everybody has a 80x60 screen,
H264/MP4 is buggy , so i choose VP6 as the highest priority
Ideally, VLC would propose the different streams available, codecs
and resolutions (the resolutions are part of the URL)
For now we just built a list of preferred codecs : lowest value
means highest priority
]]
local pref = { ["vp6"]=0, ["spark"]=1, ["h264"]=2, ["vp6-hd"]=3, ["spark-mini"]=4 }
local available = {}
for n in string.gmatch(videos, "[^|]+") do
i = string.find(n, "@@")
if i then
available[string.sub(n, i+2)] = string.sub(n, 0, i-1)
end
end
local score = 666
local bestcodec
for codec,_ in pairs(available) do
if pref[codec] == nil then
vlc.msg.warn( "Unknown codec: " .. codec )
pref[codec] = 42 -- try the 1st unknown codec if other fail
end
if pref[codec] < score then
bestcodec = codec
score = pref[codec]
end
end
if bestcodec then
path = "http://dailymotion.com" .. available[bestcodec]
end
end
if string.match( line, "<meta name=\"title\"" )
then
name = vlc.strings.resolve_xml_special_chars( find( line, "name=\"title\" content=\"(.-)\"" ) )
end
if string.match( line, "<meta name=\"description\"" )
then
description = vlc.strings.resolve_xml_special_chars( find( line, "name=\"description\" lang=\".-\" content=\"(.-)\"" ) )
end
if path and name and description and arturl then break end
end
return { { path = path; name = name; description = description; url = vlc.path; arturl = arturl } }
end
|
--[[
Translate Daily Motion video webpages URLs to the corresponding
FLV URL.
$Id$
Copyright © 2007 the VideoLAN team
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
--]]
-- Probe function.
function probe()
return vlc.access == "http"
and string.match( vlc.path, "dailymotion." )
and string.match( vlc.peek( 2048 ), "<!DOCTYPE.*video_type" )
end
function find( haystack, needle )
local _,_,ret = string.find( haystack, needle )
return ret
end
-- Parse function.
function parse()
while true
do
line = vlc.readline()
if not line then break end
if string.match( line, "param name=\"flashvars\" value=\".*video=" )
then
arturl = find( line, "param name=\"flashvars\" value=\".*preview=([^&]*)" )
videos = vlc.strings.decode_uri( find( line, "param name=\"flashvars\" value=\".*video=([^&]*)" ) )
--[[ we get a list of different streams available, at various codecs
and resolutions:
/A@@spark||/B@@spark-mini||/C@@vp6-hd||/D@@vp6||/E@@h264
Not everybody can decode HD, not everybody has a 80x60 screen,
H264/MP4 is buggy , so i choose VP6 as the highest priority
Ideally, VLC would propose the different streams available, codecs
and resolutions (the resolutions are part of the URL)
For now we just built a list of preferred codecs : lowest value
means highest priority
]]
local pref = { ["vp6"]=0, ["spark"]=1, ["h264"]=2, ["vp6-hd"]=3, ["spark-mini"]=4 }
local available = {}
for n in string.gmatch(videos, "[^|]+") do
i = string.find(n, "@@")
if i then
available[string.sub(n, i+2)] = string.sub(n, 0, i-1)
end
end
local score = 666
local bestcodec
for codec,_ in pairs(available) do
if pref[codec] == nil then
vlc.msg.warn( "Unknown codec: " .. codec )
pref[codec] = 42 -- try the 1st unknown codec if other fail
end
if pref[codec] < score then
bestcodec = codec
score = pref[codec]
end
end
if bestcodec then
path = "http://dailymotion.com" .. available[bestcodec]
end
end
if string.match( line, "<meta name=\"title\"" )
then
name = vlc.strings.resolve_xml_special_chars( find( line, "name=\"title\" content=\"(.-)\"" ) )
end
if string.match( line, "<meta name=\"description\"" )
then
description = vlc.strings.resolve_xml_special_chars( vlc.strings.resolve_xml_special_chars( find( line, "name=\"description\" lang=\".-\" content=\"(.-)\"" ) ) )
end
if path and name and description and arturl then break end
end
return { { path = path; name = name; description = description; url = vlc.path; arturl = arturl } }
end
|
Dailymotion: fix double encoding in video description
|
Dailymotion: fix double encoding in video description
Signed-off-by: Jean-Baptiste Kempf <[email protected]>
|
Lua
|
lgpl-2.1
|
vlc-mirror/vlc-2.1,jomanmuk/vlc-2.2,xkfz007/vlc,vlc-mirror/vlc,jomanmuk/vlc-2.2,xkfz007/vlc,shyamalschandra/vlc,jomanmuk/vlc-2.2,jomanmuk/vlc-2.2,vlc-mirror/vlc-2.1,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.1,jomanmuk/vlc-2.2,xkfz007/vlc,shyamalschandra/vlc,vlc-mirror/vlc,vlc-mirror/vlc-2.1,krichter722/vlc,vlc-mirror/vlc-2.1,xkfz007/vlc,xkfz007/vlc,vlc-mirror/vlc,vlc-mirror/vlc,jomanmuk/vlc-2.1,shyamalschandra/vlc,jomanmuk/vlc-2.1,vlc-mirror/vlc,shyamalschandra/vlc,jomanmuk/vlc-2.2,jomanmuk/vlc-2.1,krichter722/vlc,vlc-mirror/vlc-2.1,shyamalschandra/vlc,jomanmuk/vlc-2.2,jomanmuk/vlc-2.1,krichter722/vlc,jomanmuk/vlc-2.1,xkfz007/vlc,vlc-mirror/vlc,vlc-mirror/vlc,jomanmuk/vlc-2.1,krichter722/vlc,krichter722/vlc,xkfz007/vlc,krichter722/vlc,vlc-mirror/vlc-2.1,shyamalschandra/vlc,krichter722/vlc,shyamalschandra/vlc
|
8a5c842fdbe8dcbf53d86c4d290272733d5e2c11
|
game/scripts/vscripts/items/items_midas.lua
|
game/scripts/vscripts/items/items_midas.lua
|
function MidasCreep(keys)
local caster = keys.caster
local target = keys.target
local ability = keys.ability
Gold:AddGoldWithMessage(caster, keys.BonusGold)
if caster.AddExperience then
caster:AddExperience(target:GetDeathXP() * keys.XPMultiplier, false, false)
end
target:EmitSound("DOTA_Item.Hand_Of_Midas")
local midas_particle = ParticleManager:CreateParticle("particles/items2_fx/hand_of_midas.vpcf", PATTACH_ABSORIGIN_FOLLOW, target)
ParticleManager:SetParticleControlEnt(midas_particle, 1, caster, PATTACH_POINT_FOLLOW, "attach_hitloc", caster:GetAbsOrigin(), false)
target:SetDeathXP(0)
target:SetMinimumGoldBounty(0)
target:SetMaximumGoldBounty(0)
target:Kill(ability, caster)
end
function GiveOnAttackedGold(keys)
local attacker = keys.attacker
local caster = keys.caster
if attacker:IsConsideredHero() and
not caster:IsIllusion() and
caster:GetTeamNumber() ~= attacker:GetTeamNumber() then
local gold = keys.Gold
local xp = keys.Xp
local presymbol = POPUP_SYMBOL_PRE_PLUS
local particle = ParticleManager:CreateParticleForPlayer("particles/units/heroes/hero_alchemist/alchemist_lasthit_msg_gold.vpcf", PATTACH_ABSORIGIN, caster, caster:GetPlayerOwner())
if attacker:IsBoss() then
gold = -gold
presymbol = POPUP_SYMBOL_PRE_MINUS
xp = 0
end
ParticleManager:SetParticleControl(particle, 1, Vector(presymbol, math.abs(gold), 0))
ParticleManager:SetParticleControl(particle, 2, Vector(2, string.len(math.abs(gold)) + 1, 0))
ParticleManager:SetParticleControl(particle, 3, Vector(255, 200, 33))
caster:AddExperience(xp, false, false)
Gold:ModifyGold(caster, gold)
end
end
|
function MidasCreep(keys)
local caster = keys.caster
local target = keys.target
local ability = keys.ability
Gold:AddGoldWithMessage(caster, keys.BonusGold)
if caster.AddExperience then
caster:AddExperience(target:GetDeathXP() * keys.XPMultiplier, false, false)
end
target:EmitSound("DOTA_Item.Hand_Of_Midas")
local midas_particle = ParticleManager:CreateParticle("particles/items2_fx/hand_of_midas.vpcf", PATTACH_ABSORIGIN_FOLLOW, target)
ParticleManager:SetParticleControlEnt(midas_particle, 1, caster, PATTACH_POINT_FOLLOW, "attach_hitloc", caster:GetAbsOrigin(), false)
target:SetDeathXP(0)
target:SetMinimumGoldBounty(0)
target:SetMaximumGoldBounty(0)
target:Kill(ability, caster)
end
function GiveOnAttackedGold(keys)
local attacker = keys.attacker
local caster = keys.caster
if attacker:IsConsideredHero() and
not caster:IsIllusion() and
caster:GetTeamNumber() ~= attacker:GetTeamNumber() then
local gold = keys.Gold
local xp = keys.Xp
local presymbol = POPUP_SYMBOL_PRE_PLUS
local particle = ParticleManager:CreateParticleForPlayer("particles/units/heroes/hero_alchemist/alchemist_lasthit_msg_gold.vpcf", PATTACH_ABSORIGIN, caster, caster:GetPlayerOwner())
if attacker:IsBoss() then
gold = -gold
presymbol = POPUP_SYMBOL_PRE_MINUS
xp = 0
end
ParticleManager:SetParticleControl(particle, 1, Vector(presymbol, math.abs(gold), 0))
ParticleManager:SetParticleControl(particle, 2, Vector(2, string.len(math.abs(gold)) + 1, 0))
ParticleManager:SetParticleControl(particle, 3, Vector(255, 200, 33))
if caster.AddExperience then
caster:AddExperience(xp, false, false)
end
Gold:ModifyGold(caster, gold)
end
end
|
fix(items): Chest of Midas emits error for units without experience
|
fix(items): Chest of Midas emits error for units without experience
|
Lua
|
mit
|
ark120202/aabs
|
0659bb43a4d91987efeae499c7f86f439dbff00f
|
.config/nvim/lua/modules/telescope.lua
|
.config/nvim/lua/modules/telescope.lua
|
local actions = require("telescope.actions")
local action_state = require("telescope.actions.state")
local M = {}
local custom_actions = {}
function custom_actions.fzf_multi_select(prompt_bufnr, mode)
local picker = action_state.get_current_picker(prompt_bufnr)
local num_selections = table.getn(picker:get_multi_selection())
if num_selections > 1 then
-- actions.file_edit throws - context of picker seems to change
--actions.file_edit(prompt_bufnr)
actions.send_selected_to_qflist(prompt_bufnr)
actions.open_qflist()
else
actions.file_edit(prompt_bufnr)
end
end
require("telescope").setup {
defaults = {
mappings = {
i = {
-- close on escape
["<esc>"] = actions.close,
["<tab>"] = actions.toggle_selection + actions.move_selection_next,
["<s-tab>"] = actions.toggle_selection + actions.move_selection_previous,
["<cr>"] = custom_actions.fzf_multi_select
},
n = {
["<tab>"] = actions.toggle_selection + actions.move_selection_next,
["<s-tab>"] = actions.toggle_selection + actions.move_selection_previous,
["<cr>"] = custom_actions.fzf_multi_select
}
}
}
}
-- add hidden files to find_files
M.custom_find_files = function(opts)
opts = opts or {}
opts.hidden = true
opts.find_command = {
"rg",
"--files",
"--hidden",
"--no-heading",
"--with-filename",
"--line-number",
"--column",
"--smart-case",
"--color=never"
}
require "telescope.builtin".find_files(opts)
end
return M
|
local actions = require("telescope.actions")
local action_state = require("telescope.actions.state")
local M = {}
local custom_actions = {}
function custom_actions.fzf_multi_select(prompt_bufnr)
local picker = action_state.get_current_picker(prompt_bufnr)
local num_selections = table.getn(picker:get_multi_selection())
if num_selections > 1 then
-- actions.file_edit throws - context of picker seems to change
--actions.file_edit(prompt_bufnr)
actions.send_selected_to_qflist(prompt_bufnr)
actions.open_qflist()
else
actions.file_edit(prompt_bufnr)
end
end
require("telescope").setup {
defaults = {
mappings = {
i = {
["<esc>"] = actions.close
}
}
},
extensions = {
fzf = {
override_generic_sorter = true, -- override the generic sorter
override_file_sorter = true, -- override the file sorter
case_mode = "smart_case" -- or "ignore_case" or "respect_case"
}
}
}
require("telescope").load_extension("fzf")
M.custom_find_files = function(opts)
opts = opts or {}
-- add hidden files to find_files
opts.hidden = true
opts.find_command = {
"rg",
"--files",
"--hidden",
"--no-heading",
"--with-filename",
"--line-number",
"--column",
"--smart-case",
"--color=never"
}
opts.attach_mappings = function(_, map)
map("i", "<cr>", custom_actions.fzf_multi_select)
map("n", "<cr>", custom_actions.fzf_multi_select)
return true
end
require "telescope.builtin".find_files(opts)
end
return M
|
fix telescope mappings
|
fix telescope mappings
|
Lua
|
mit
|
larrybotha/dotfiles,larrybotha/dotfiles
|
9521451c50d0d16c91fe33904ed400f0bec9797e
|
nyagos.lua
|
nyagos.lua
|
--------------------------------------------------------------------------
-- DO NOT EDIT THIS. PLEASE EDIT ~\.nyagos OR ADD SCRIPT INTO nyagos.d\ --
--------------------------------------------------------------------------
if nyagos == nil then
print("This is the startup script for NYAGOS")
print("Do not run this with lua.exe")
os.exit(0)
end
print("Nihongo Yet Another GOing Shell " .. nyagos.version .. " Powered by " .. _VERSION )
if string.len(nyagos.version) <= 0 then
print("Build at ".. nyagos.stamp .. " with commit "..nyagos.commit)
end
print("Copyright (c) 2014,2015 HAYAMA_Kaoru and NYAOS.ORG")
local function expand(text)
return string.gsub(text,"%%(%w+)%%",function(w)
return nyagos.getenv(w)
end)
end
local function set_(f,equation,expand)
if type(equation) == 'table' then
for left,right in pairs(equation) do
f(left,expand(right))
end
return true
end
local pluspos=string.find(equation,"+=",1,true)
if pluspos and pluspos > 0 then
local left=string.sub(equation,1,pluspos-1)
equation = string.format("%s=%s;%%%s%%",
left,string.sub(equation,pluspos+2),left)
end
local pos=string.find(equation,"=",1,true)
if pos then
local left=string.sub(equation,1,pos-1)
local right=string.sub(equation,pos+1)
f( left , expand(right) )
return true
end
return false,(equation .. ': invalid format')
end
function set(equation)
set_(nyagos.setenv,equation,expand)
end
function alias(equation)
set_(nyagos.alias,equation,function(x) return x end)
end
function addpath(...)
for _,dir in pairs{...} do
dir = expand(dir)
local list=nyagos.getenv("PATH")
if not string.find(";"..list..";",";"..dir..";",1,true) then
nyagos.setenv("PATH",dir..";"..list)
end
end
end
function nyagos.echo(s)
nyagos.write(s..'\n')
end
function x(s)
for line in string.gmatch(s,'[^\r\n]+') do
nyagos.exec(line)
end
end
io.getenv = nyagos.getenv
io.setenv = nyagos.setenv
original_print = print
print = nyagos.echo
local function include(fname)
local chank,err=loadfile(fname)
if err then
print(err)
elseif chank then
chank()
else
print(fname .. ":fail to load")
end
end
local dotfolder = string.gsub(nyagos.exe,"%.exe",".d")
local fd = io.popen("dir /b /s "..dotfolder.."\\*.lua","r")
for fname in fd:lines() do
include(fname)
end
fd:close()
local home = nyagos.getenv("HOME") or nyagos.getenv("USERPROFILE")
if home then
local dotfile = home .. '\\.nyagos'
local fd=io.open(dotfile)
if fd then
fd:close()
include(dotfile)
end
end
|
--------------------------------------------------------------------------
-- DO NOT EDIT THIS. PLEASE EDIT ~\.nyagos OR ADD SCRIPT INTO nyagos.d\ --
--------------------------------------------------------------------------
if nyagos == nil then
print("This is the startup script for NYAGOS")
print("Do not run this with lua.exe")
os.exit(0)
end
print("Nihongo Yet Another GOing Shell " .. nyagos.version .. " Powered by " .. _VERSION )
if string.len(nyagos.version) <= 0 then
print("Build at ".. nyagos.stamp .. " with commit "..nyagos.commit)
end
print("Copyright (c) 2014,2015 HAYAMA_Kaoru and NYAOS.ORG")
local function expand(text)
return string.gsub(text,"%%(%w+)%%",function(w)
return nyagos.getenv(w)
end)
end
local function set_(f,equation,expand)
if type(equation) == 'table' then
for left,right in pairs(equation) do
f(left,expand(right))
end
return true
end
local pluspos=string.find(equation,"+=",1,true)
if pluspos and pluspos > 0 then
local left=string.sub(equation,1,pluspos-1)
equation = string.format("%s=%s;%%%s%%",
left,string.sub(equation,pluspos+2),left)
end
local pos=string.find(equation,"=",1,true)
if pos then
local left=string.sub(equation,1,pos-1)
local right=string.sub(equation,pos+1)
f( left , expand(right) )
return true
end
return false,(equation .. ': invalid format')
end
function set(equation)
set_(nyagos.setenv,equation,expand)
end
function alias(equation)
set_(nyagos.alias,equation,function(x) return x end)
end
function addpath(...)
for _,dir in pairs{...} do
dir = expand(dir)
local list=nyagos.getenv("PATH")
if not string.find(";"..list..";",";"..dir..";",1,true) then
nyagos.setenv("PATH",dir..";"..list)
end
end
end
function nyagos.echo(s)
nyagos.write(s..'\n')
end
function x(s)
for line in string.gmatch(s,'[^\r\n]+') do
nyagos.exec(line)
end
end
io.getenv = nyagos.getenv
io.setenv = nyagos.setenv
original_print = print
print = nyagos.echo
local function include(fname)
local chank,err=loadfile(fname)
if err then
print(err)
elseif chank then
local ok,err=pcall(chank)
if not ok then
print(fname .. ": " ..err)
end
else
print(fname .. ":fail to load")
end
end
local dotfolder = string.gsub(nyagos.exe,"%.exe",".d")
local fd = io.popen("dir /b /s "..dotfolder.."\\*.lua","r")
for fname in fd:lines() do
include(fname)
end
fd:close()
local home = nyagos.getenv("HOME") or nyagos.getenv("USERPROFILE")
if home then
local dotfile = home .. '\\.nyagos'
local fd=io.open(dotfile)
if fd then
fd:close()
include(dotfile)
end
end
|
Fix: nyagos.lua did not print plugin-error
|
Fix: nyagos.lua did not print plugin-error
|
Lua
|
bsd-3-clause
|
zetamatta/nyagos,kissthink/nyagos,hattya/nyagos,kissthink/nyagos,nocd5/nyagos,tyochiai/nyagos,hattya/nyagos,tsuyoshicho/nyagos,kissthink/nyagos,hattya/nyagos
|
56624cc873b20d1d0afbc67d71f83596580363a2
|
core/modulemanager.lua
|
core/modulemanager.lua
|
local log = require "util.logger".init("modulemanager")
local loadfile, pcall = loadfile, pcall;
local setmetatable, setfenv, getfenv = setmetatable, setfenv, getfenv;
local pairs, ipairs = pairs, ipairs;
local t_insert = table.insert;
local type = type;
local tostring, print = tostring, print;
local _G = _G;
module "modulemanager"
local handler_info = {};
local handlers = {};
local modulehelpers = setmetatable({}, { __index = _G });
function modulehelpers.add_iq_handler(origin_type, xmlns, handler)
if not (origin_type and handler and xmlns) then return false; end
handlers[origin_type] = handlers[origin_type] or {};
handlers[origin_type].iq = handlers[origin_type].iq or {};
if not handlers[origin_type].iq[xmlns] then
handlers[origin_type].iq[xmlns]= handler;
handler_info[handler] = getfenv(2).module;
log("debug", "mod_%s now handles tag 'iq' with query namespace '%s'", getfenv(2).module.name, xmlns);
else
log("warning", "mod_%s wants to handle tag 'iq' with query namespace '%s' but mod_%s already handles that", getfenv(2).module.name, xmlns, handler_info[handlers[origin_type].iq[xmlns]].module.name);
end
end
local function _add_handler(module, origin_type, tag, xmlns, handler)
handlers[origin_type] = handlers[origin_type] or {};
if not handlers[origin_type][tag] then
handlers[origin_type][tag] = handlers[origin_type][tag] or {};
handlers[origin_type][tag][xmlns]= handler;
handler_info[handler] = module;
log("debug", "mod_%s now handles tag '%s'", module.name, tag);
elseif handler_info[handlers[origin_type][tag]] then
log("warning", "mod_%s wants to handle tag '%s' but mod_%s already handles that", module.name, tag, handler_info[handlers[origin_type][tag]].module.name);
end
end
function modulehelpers.add_handler(origin_type, tag, xmlns, handler)
if not (origin_type and tag and xmlns and handler) then return false; end
if type(origin_type) == "table" then
for _, origin_type in ipairs(origin_type) do
_add_handler(getfenv(2).module, origin_type, tag, xmlns, handler);
end
return;
end
_add_handler(getfenv(2).module, origin_type, tag, xmlns, handler);
end
function loadall()
load("saslauth");
load("legacyauth");
load("roster");
load("register");
load("tls");
load("vcard");
load("private");
load("version");
load("dialback");
end
function load(name)
local mod, err = loadfile("plugins/mod_"..name..".lua");
if not mod then
log("error", "Unable to load module '%s': %s", name or "nil", err or "nil");
return;
end
local pluginenv = setmetatable({ module = { name = name } }, { __index = modulehelpers });
setfenv(mod, pluginenv);
local success, ret = pcall(mod);
if not success then
log("error", "Error initialising module '%s': %s", name or "nil", ret or "nil");
return;
end
end
function handle_stanza(origin, stanza)
local name, xmlns, origin_type = stanza.name, stanza.attr.xmlns, origin.type;
if name == "iq" and xmlns == "jabber:client" and handlers[origin_type] then
log("debug", "Stanza is an <iq/>");
local child = stanza.tags[1];
if child then
local xmlns = child.attr.xmlns;
log("debug", "Stanza has xmlns: %s", xmlns);
local handler = handlers[origin_type][name][xmlns];
if handler then
log("debug", "Passing stanza to mod_%s", handler_info[handler].name);
return handler(origin, stanza) or true;
end
end
elseif handlers[origin_type] then
local handler = handlers[origin_type][name];
if handler then
handler = handler[xmlns];
if handler then
log("debug", "Passing stanza to mod_%s", handler_info[handler].name);
return handler(origin, stanza) or true;
end
end
end
log("debug", "Stanza unhandled by any modules, xmlns: %s", stanza.attr.xmlns);
return false; -- we didn't handle it
end
do
local event_handlers = {};
function modulehelpers.add_event_hook(name, handler)
if not event_handlers[name] then
event_handlers[name] = {};
end
t_insert(event_handlers[name] , handler);
end
function fire_event(name, ...)
local event_handlers = event_handlers[name];
if event_handlers then
for name, handler in ipairs(event_handlers) do
handler(...);
end
end
end
end
return _M;
|
local log = require "util.logger".init("modulemanager")
local loadfile, pcall = loadfile, pcall;
local setmetatable, setfenv, getfenv = setmetatable, setfenv, getfenv;
local pairs, ipairs = pairs, ipairs;
local t_insert = table.insert;
local type = type;
local tostring, print = tostring, print;
local _G = _G;
module "modulemanager"
local handler_info = {};
local handlers = {};
local modulehelpers = setmetatable({}, { __index = _G });
local function _add_iq_handler(module, origin_type, xmlns, handler)
handlers[origin_type] = handlers[origin_type] or {};
handlers[origin_type].iq = handlers[origin_type].iq or {};
if not handlers[origin_type].iq[xmlns] then
handlers[origin_type].iq[xmlns]= handler;
handler_info[handler] = module;
log("debug", "mod_%s now handles tag 'iq' with query namespace '%s'", module.name, xmlns);
else
log("warning", "mod_%s wants to handle tag 'iq' with query namespace '%s' but mod_%s already handles that", module.name, xmlns, handler_info[handlers[origin_type].iq[xmlns]].module.name);
end
end
function modulehelpers.add_iq_handler(origin_type, xmlns, handler)
if not (origin_type and handler and xmlns) then return false; end
if type(origin_type) == "table" then
for _, origin_type in ipairs(origin_type) do
_add_iq_handler(getfenv(2), origin_type, xmlns, handler);
end
return;
end
_add_iq_handler(getfenv(2), origin_type, xmlns, handler);
end
local function _add_handler(module, origin_type, tag, xmlns, handler)
handlers[origin_type] = handlers[origin_type] or {};
if not handlers[origin_type][tag] then
handlers[origin_type][tag] = handlers[origin_type][tag] or {};
handlers[origin_type][tag][xmlns]= handler;
handler_info[handler] = module;
log("debug", "mod_%s now handles tag '%s'", module.name, tag);
elseif handler_info[handlers[origin_type][tag]] then
log("warning", "mod_%s wants to handle tag '%s' but mod_%s already handles that", module.name, tag, handler_info[handlers[origin_type][tag]].module.name);
end
end
function modulehelpers.add_handler(origin_type, tag, xmlns, handler)
if not (origin_type and tag and xmlns and handler) then return false; end
if type(origin_type) == "table" then
for _, origin_type in ipairs(origin_type) do
_add_handler(getfenv(2).module, origin_type, tag, xmlns, handler);
end
return;
end
_add_handler(getfenv(2).module, origin_type, tag, xmlns, handler);
end
function loadall()
load("saslauth");
load("legacyauth");
load("roster");
load("register");
load("tls");
load("vcard");
load("private");
load("version");
load("dialback");
end
function load(name)
local mod, err = loadfile("plugins/mod_"..name..".lua");
if not mod then
log("error", "Unable to load module '%s': %s", name or "nil", err or "nil");
return;
end
local pluginenv = setmetatable({ module = { name = name } }, { __index = modulehelpers });
setfenv(mod, pluginenv);
local success, ret = pcall(mod);
if not success then
log("error", "Error initialising module '%s': %s", name or "nil", ret or "nil");
return;
end
end
function handle_stanza(origin, stanza)
local name, xmlns, origin_type = stanza.name, stanza.attr.xmlns, origin.type;
if name == "iq" and xmlns == "jabber:client" and handlers[origin_type] then
log("debug", "Stanza is an <iq/>");
local child = stanza.tags[1];
if child then
local xmlns = child.attr.xmlns;
log("debug", "Stanza has xmlns: %s", xmlns);
local handler = handlers[origin_type][name][xmlns];
if handler then
log("debug", "Passing stanza to mod_%s", handler_info[handler].name);
return handler(origin, stanza) or true;
end
end
elseif handlers[origin_type] then
local handler = handlers[origin_type][name];
if handler then
handler = handler[xmlns];
if handler then
log("debug", "Passing stanza to mod_%s", handler_info[handler].name);
return handler(origin, stanza) or true;
end
end
end
log("debug", "Stanza unhandled by any modules, xmlns: %s", stanza.attr.xmlns);
return false; -- we didn't handle it
end
do
local event_handlers = {};
function modulehelpers.add_event_hook(name, handler)
if not event_handlers[name] then
event_handlers[name] = {};
end
t_insert(event_handlers[name] , handler);
end
function fire_event(name, ...)
local event_handlers = event_handlers[name];
if event_handlers then
for name, handler in ipairs(event_handlers) do
handler(...);
end
end
end
end
return _M;
|
Fix for add_iq_handler to allow multiple origin types too
|
Fix for add_iq_handler to allow multiple origin types too
|
Lua
|
mit
|
sarumjanuch/prosody,sarumjanuch/prosody
|
b4b138020fcc2507db44042c22be9829d07d779e
|
xmake.lua
|
xmake.lua
|
set_xmakever("2.5.4")
-- project
set_project("hikyuu")
add_rules("mode.debug", "mode.release")
if not is_plat("windows") then
add_rules("mode.coverage", "mode.asan", "mode.msan", "mode.tsan", "mode.lsan")
end
-- version
set_version("1.2.4", {build="%Y%m%d%H%M"})
set_configvar("LOG_ACTIVE_LEVEL", 0) -- 激活的日志级别
--if is_mode("debug") then
-- set_configvar("LOG_ACTIVE_LEVEL", 0) -- 激活的日志级别
--else
-- set_configvar("LOG_ACTIVE_LEVEL", 2) -- 激活的日志级别
--end
set_configvar("USE_SPDLOG_LOGGER", 1) -- 是否使用spdlog作为日志输出
set_configvar("USE_SPDLOG_ASYNC_LOGGER", 0) -- 使用异步的spdlog
set_configvar("CHECK_ACCESS_BOUND", 1)
if is_plat("macosx") then
set_configvar("SUPPORT_SERIALIZATION", 0)
else
set_configvar("SUPPORT_SERIALIZATION", is_mode("release") and 1 or 0)
end
set_configvar("SUPPORT_TEXT_ARCHIVE", 0)
set_configvar("SUPPORT_XML_ARCHIVE", 1)
set_configvar("SUPPORT_BINARY_ARCHIVE", 1)
set_configvar("HKU_DISABLE_ASSERT", 0)
-- set warning all as error
if is_plat("windows") then
set_warnings("all", "error")
else
set_warnings("all")
end
-- set language: C99, c++ standard
set_languages("cxx17", "C99")
add_plugindirs("./xmake_plugins")
local hdf5_version = "1.10.4"
local mysql_version = "8.0.21"
if is_plat("windows") then
add_repositories("project-repo hikyuu_extern_libs")
if is_mode("release") then
add_requires("hdf5 " .. hdf5_version)
else
add_requires("hdf5_D " .. hdf5_version)
end
add_requires("mysql " .. mysql_version)
end
add_requires("fmt 8.1.1", {system=false, configs = {header_only = true, vs_runtime = "MD"}})
add_requires("spdlog", {system=false, configs = {header_only = true, fmt_external=true, vs_runtime = "MD"}})
add_requires("flatbuffers", {system=false, configs = {vs_runtime="MD"}})
add_requires("nng", {system=false, configs = {vs_runtime="MD", cxflags="-fPIC"}})
add_requires("nlohmann_json", {system=false})
add_requires("cpp-httplib", {system=false})
add_requires("zlib", {system=false})
if is_plat("linux") and linuxos.name() == "ubuntu" then
add_requires("apt::libhdf5-dev", "apt::libmysqlclient-dev", "apt::libsqlite3-dev")
elseif is_plat("macosx") then
add_requires("brew::hdf5")
else
add_requires("sqlite3", {configs = {shared=true, vs_runtime="MD", cxflags="-fPIC"}})
end
add_defines("SPDLOG_DISABLE_DEFAULT_LOGGER") -- 禁用 spdlog 默认 logger
set_objectdir("$(buildir)/$(mode)/$(plat)/$(arch)/.objs")
set_targetdir("$(buildir)/$(mode)/$(plat)/$(arch)/lib")
add_includedirs("$(env BOOST_ROOT)")
add_linkdirs("$(env BOOST_LIB)")
-- modifed to use boost static library, except boost.python, serialization
--add_defines("BOOST_ALL_DYN_LINK")
add_defines("BOOST_SERIALIZATION_DYN_LINK")
if is_host("linux") then
if is_arch("x86_64") then
add_linkdirs("/usr/lib64")
if os.exists("/usr/lib/x86_64-linux-gnu") then
add_linkdirs("/usr/lib/x86_64-linux-gnu")
end
end
end
-- is release now
if is_mode("release") then
if is_plat("windows") then
--Unix-like systems hidden symbols will cause the link dynamic libraries to failed!
set_symbols("hidden")
end
end
-- for the windows platform (msvc)
if is_plat("windows") then
-- add some defines only for windows
add_defines("NOCRYPT", "NOGDI")
add_cxflags("-EHsc", "/Zc:__cplusplus", "/utf-8")
add_cxflags("-wd4819") --template dll export warning
add_defines("WIN32_LEAN_AND_MEAN")
if is_mode("release") then
add_cxflags("-MD")
elseif is_mode("debug") then
add_cxflags("-Gs", "-RTC1", "/bigobj")
add_cxflags("-MDd")
end
end
if not is_plat("windows") then
-- disable some compiler errors
add_cxflags("-Wno-error=deprecated-declarations", "-fno-strict-aliasing")
add_cxflags("-ftemplate-depth=1023", "-pthread")
add_shflags("-pthread")
add_ldflags("-pthread")
end
--add_vectorexts("sse", "sse2", "sse3", "ssse3", "mmx", "avx")
add_subdirs("./hikyuu_cpp/hikyuu")
add_subdirs("./hikyuu_pywrap")
add_subdirs("./hikyuu_cpp/unit_test")
add_subdirs("./hikyuu_cpp/demo")
add_subdirs("./hikyuu_cpp/hikyuu_server")
before_install("scripts.before_install")
on_install("scripts.on_install")
before_run("scripts.before_run")
|
set_xmakever("2.5.4")
-- project
set_project("hikyuu")
add_rules("mode.debug", "mode.release")
if not is_plat("windows") then
add_rules("mode.coverage", "mode.asan", "mode.msan", "mode.tsan", "mode.lsan")
end
-- version
set_version("1.2.4", {build="%Y%m%d%H%M"})
set_configvar("LOG_ACTIVE_LEVEL", 0) -- 激活的日志级别
--if is_mode("debug") then
-- set_configvar("LOG_ACTIVE_LEVEL", 0) -- 激活的日志级别
--else
-- set_configvar("LOG_ACTIVE_LEVEL", 2) -- 激活的日志级别
--end
set_configvar("USE_SPDLOG_LOGGER", 1) -- 是否使用spdlog作为日志输出
set_configvar("USE_SPDLOG_ASYNC_LOGGER", 0) -- 使用异步的spdlog
set_configvar("CHECK_ACCESS_BOUND", 1)
if is_plat("macosx") then
set_configvar("SUPPORT_SERIALIZATION", 0)
else
set_configvar("SUPPORT_SERIALIZATION", is_mode("release") and 1 or 0)
end
set_configvar("SUPPORT_TEXT_ARCHIVE", 0)
set_configvar("SUPPORT_XML_ARCHIVE", 1)
set_configvar("SUPPORT_BINARY_ARCHIVE", 1)
set_configvar("HKU_DISABLE_ASSERT", 0)
-- set warning all as error
if is_plat("windows") then
set_warnings("all", "error")
else
set_warnings("all")
end
-- set language: C99, c++ standard
set_languages("cxx17", "C99")
add_plugindirs("./xmake_plugins")
local hdf5_version = "1.10.4"
local mysql_version = "8.0.21"
if is_plat("windows") then
add_repositories("project-repo hikyuu_extern_libs")
if is_mode("release") then
add_requires("hdf5 " .. hdf5_version)
else
add_requires("hdf5_D " .. hdf5_version)
end
add_requires("mysql " .. mysql_version)
end
-- add_requires("fmt 8.1.1", {system=false, configs = {header_only = true}})
add_requires("spdlog", {system=false, configs = {header_only = true, fmt_external=true, vs_runtime = "MD"}})
add_requireconfs("spdlog.fmt", {override = true, version = "8.1.1", configs = {header_only = true}})
add_requires("flatbuffers", {system=false, configs = {vs_runtime="MD"}})
add_requires("nng", {system=false, configs = {vs_runtime="MD", cxflags="-fPIC"}})
add_requires("nlohmann_json", {system=false})
add_requires("cpp-httplib", {system=false})
add_requires("zlib", {system=false})
if is_plat("linux") and linuxos.name() == "ubuntu" then
add_requires("apt::libhdf5-dev", "apt::libmysqlclient-dev", "apt::libsqlite3-dev")
elseif is_plat("macosx") then
add_requires("brew::hdf5")
else
add_requires("sqlite3", {configs = {shared=true, vs_runtime="MD", cxflags="-fPIC"}})
end
add_defines("SPDLOG_DISABLE_DEFAULT_LOGGER") -- 禁用 spdlog 默认 logger
set_objectdir("$(buildir)/$(mode)/$(plat)/$(arch)/.objs")
set_targetdir("$(buildir)/$(mode)/$(plat)/$(arch)/lib")
add_includedirs("$(env BOOST_ROOT)")
add_linkdirs("$(env BOOST_LIB)")
-- modifed to use boost static library, except boost.python, serialization
--add_defines("BOOST_ALL_DYN_LINK")
add_defines("BOOST_SERIALIZATION_DYN_LINK")
if is_host("linux") then
if is_arch("x86_64") then
add_linkdirs("/usr/lib64")
if os.exists("/usr/lib/x86_64-linux-gnu") then
add_linkdirs("/usr/lib/x86_64-linux-gnu")
end
end
end
-- is release now
if is_mode("release") then
if is_plat("windows") then
--Unix-like systems hidden symbols will cause the link dynamic libraries to failed!
set_symbols("hidden")
end
end
-- for the windows platform (msvc)
if is_plat("windows") then
-- add some defines only for windows
add_defines("NOCRYPT", "NOGDI")
add_cxflags("-EHsc", "/Zc:__cplusplus", "/utf-8")
add_cxflags("-wd4819") --template dll export warning
add_defines("WIN32_LEAN_AND_MEAN")
if is_mode("release") then
add_cxflags("-MD")
elseif is_mode("debug") then
add_cxflags("-Gs", "-RTC1", "/bigobj")
add_cxflags("-MDd")
end
end
if not is_plat("windows") then
-- disable some compiler errors
add_cxflags("-Wno-error=deprecated-declarations", "-fno-strict-aliasing")
add_cxflags("-ftemplate-depth=1023", "-pthread")
add_shflags("-pthread")
add_ldflags("-pthread")
end
--add_vectorexts("sse", "sse2", "sse3", "ssse3", "mmx", "avx")
add_subdirs("./hikyuu_cpp/hikyuu")
add_subdirs("./hikyuu_pywrap")
add_subdirs("./hikyuu_cpp/unit_test")
add_subdirs("./hikyuu_cpp/demo")
add_subdirs("./hikyuu_cpp/hikyuu_server")
before_install("scripts.before_install")
on_install("scripts.on_install")
before_run("scripts.before_run")
|
fixed fmt
|
fixed fmt
|
Lua
|
mit
|
fasiondog/hikyuu
|
f8a475fe25ac487e5ca568453aab615b3ac72fad
|
App/NevermoreEngine.lua
|
App/NevermoreEngine.lua
|
--- Nevermore module loader.
-- Used to simply resource loading and networking so a more unified server / client codebased can be used
-- @module Nevermore
local DEBUG_MODE = false -- Set to true to help identify what libraries have circular dependencies
local RunService = game:GetService("RunService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local ServerScriptService = game:GetService("ServerScriptService")
assert(script:IsA("ModuleScript"), "Invalid script type. For NevermoreEngine to work correctly, it should be a ModuleScript named \"NevermoreEngine\" parented to ReplicatedStorage")
assert(script.Name == "NevermoreEngine", "Invalid script name. For NevermoreEngine to work correctly, it should be a ModuleScript named \"NevermoreEngine\" parented to ReplicatedStorage")
assert(script.Parent == ReplicatedStorage, "Invalid parent. For NevermoreEngine to work correctly, it should be a ModuleScript named \"NevermoreEngine\" parented to ReplicatedStorage")
--- Handles yielded operations by caching the retrieval process
local function _handleRetrieving(Retrieving, Function, Argument)
assert(type(Retrieving) == "table", "Error: Retrieving must be a table")
assert(type(Function) == "function", "Error: Function must be a function")
local Signal = Instance.new("BindableEvent")
local Result
Retrieving[Argument] = function()
if Result ~= nil and Result then
return Result
end
Signal.Event:Wait()
return Result
end
Result = Function(Argument)
assert(Result ~= nil, "Result cannot be nil")
Retrieving[Argument] = nil
Signal:Fire()
Signal:Destroy()
return Result
end
--- Caches single argument, single output only
local function _asyncCache(Function)
assert(type(Function) == "function", "Error: Function must be a userdata")
local Cache = {}
local Retrieving = {}
return function(Argument)
assert(Argument ~= nil, "Error: ARgument ")
if Cache[Argument] ~= nil then
return Cache[Argument]
elseif Retrieving[Argument] then
return Retrieving[Argument]()
else
Cache[Argument] = _handleRetrieving(Retrieving, Function, Argument)
return Cache[Argument]
end
end
end
--- Retrieves an instance from a parent
local function _retrieve(Parent, ClassName)
assert(type(ClassName) == "string", "Error: ClassName must be a string")
assert(typeof(Parent) == "Instance", ("Error: Parent must be an Instance, got '%s'"):format(typeof(Parent)))
return RunService:IsServer() and function(Name)
local Item = Parent:FindFirstChild(Name)
if not Item then
Item = Instance.new(ClassName)
Item.Archivable = false
Item.Name = Name
Item.Parent = Parent
end
return Item
end or function(Name)
local Resource = Parent:WaitForChild(Name, 5)
if Resource then
return Resource
end
warn(("Warning: No '%s' found, be sure to require '%s' on the server. Yielding for '%s'"):format(tostring(Name), tostring(Name), ClassName))
return Parent:WaitForChild(Name)
end
end
local function _getRepository(GetSubFolder)
if RunService:IsServer() then
local RepositoryFolder = ServerScriptService:FindFirstChild("Nevermore")
if not RepositoryFolder then
warn("Warning: No repository of Nevermore modules found (Expected in ServerScriptService with name \"Nevermore\"). Library retrieval will fail.")
RepositoryFolder = Instance.new("Folder")
RepositoryFolder.Name = "Nevermore"
end
return RepositoryFolder
else
return GetSubFolder("Modules")
end
end
local function _getLibraryCache(RepositoryFolder)
local LibraryCache = {}
for _, Child in pairs(RepositoryFolder:GetDescendants()) do
if Child:IsA("ModuleScript") and not Child:FindFirstAncestorOfClass("ModuleScript") then
if LibraryCache[Child.Name] then
error(("Error: Duplicate name of '%s' already exists"):format(Child.Name))
end
LibraryCache[Child.Name] = Child
end
end
return LibraryCache
end
local function _replicateRepository(ReplicationFolder, LibraryCache)
for Name, Library in pairs(LibraryCache) do
if not Name:lower():find("server") then
Library.Parent = ReplicationFolder
end
end
end
local function _debugLoading(Function)
local Count = 0
local RequestDepth = 0
return function(Module, ...)
Count = Count + 1
local LibraryID = Count
if DEBUG_MODE then
print(("\t"):rep(RequestDepth), LibraryID, "Loading: ", Module)
RequestDepth = RequestDepth + 1
end
local Result = Function(Module, ...)
if DEBUG_MODE then
RequestDepth = RequestDepth - 1
print(("\t"):rep(RequestDepth), LibraryID, "Done loading: ", Module)
end
return Result
end
end
local function _getLibraryLoader(LibraryCache)
--- Loads a library from Nevermore's library cache
-- @param Module The name of the library or a module
-- @return The library's value
return function(Module)
if typeof(Module) == "Instance" and Module:IsA("ModuleScript") then
return require(Module)
elseif type(Module) == "string" then
local ModuleScript = LibraryCache[Module] or error("Error: Library '" .. Module .. "' does not exist.", 2)
return require(ModuleScript)
else
error(("Error: Module must be a string or ModuleScript, got '%s'"):format(typeof(Module)))
end
end
end
local ResourceFolder = _retrieve(ReplicatedStorage, "Folder")("NevermoreResources")
local GetSubFolder = _retrieve(ResourceFolder, "Folder")
local RepositoryFolder = _getRepository(GetSubFolder)
local LibraryCache = _getLibraryCache(RepositoryFolder)
if RunService:IsServer() and not RunService:IsClient() then -- Don't move in SoloTestMode
_replicateRepository(GetSubFolder("Modules"), LibraryCache)
end
local Nevermore = {}
--- Load a library through Nevermore
-- @function LoadLibrary
-- @tparam string LibraryName
Nevermore.LoadLibrary = _asyncCache(_debugLoading(_getLibraryLoader(LibraryCache)))
--- Get a remote event
-- @function GetRemoteEvent
-- @tparam string RemoteEventName
-- @return RemoteEvent
Nevermore.GetRemoteEvent = _asyncCache(_retrieve(GetSubFolder("RemoteEvents"), "RemoteEvent"))
--- Get a remote function
-- @function GetRemoteFunction
-- @tparam string RemoteFunctionName
-- @return RemoteFunction
Nevermore.GetRemoteFunction = _asyncCache(_retrieve(GetSubFolder("RemoteFunctions"), "RemoteFunction"))
setmetatable(Nevermore, {
__call = Nevermore.LoadLibrary;
__index = function(self, Index)
error(("'%s is not a valid member of Nevermore"):format(tostring(Index)))
end;
})
return Nevermore
|
--- Nevermore module loader.
-- Used to simply resource loading and networking so a more unified server / client codebased can be used
-- @module Nevermore
local DEBUG_MODE = false -- Set to true to help identify what libraries have circular dependencies
local RunService = game:GetService("RunService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local ServerScriptService = game:GetService("ServerScriptService")
assert(script:IsA("ModuleScript"), "Invalid script type. For NevermoreEngine to work correctly, it should be a ModuleScript named \"NevermoreEngine\" parented to ReplicatedStorage")
assert(script.Name == "NevermoreEngine", "Invalid script name. For NevermoreEngine to work correctly, it should be a ModuleScript named \"NevermoreEngine\" parented to ReplicatedStorage")
assert(script.Parent == ReplicatedStorage, "Invalid parent. For NevermoreEngine to work correctly, it should be a ModuleScript named \"NevermoreEngine\" parented to ReplicatedStorage")
--- Handles yielded operations by caching the retrieval process
local function _handleRetrieving(Retrieving, Function, Argument)
assert(type(Retrieving) == "table", "Error: Retrieving must be a table")
assert(type(Function) == "function", "Error: Function must be a function")
local Signal = Instance.new("BindableEvent")
local Result
Retrieving[Argument] = function()
if Result ~= nil and Result then
return Result
end
Signal.Event:Wait()
return Result
end
Result = Function(Argument)
assert(Result ~= nil, "Result cannot be nil")
Retrieving[Argument] = nil
Signal:Fire()
Signal:Destroy()
return Result
end
--- Caches single argument, single output only
local function _asyncCache(Function)
assert(type(Function) == "function", "Error: Function must be a userdata")
local Cache = {}
local Retrieving = {}
return function(Argument)
assert(Argument ~= nil, "Error: ARgument ")
if Cache[Argument] ~= nil then
return Cache[Argument]
elseif Retrieving[Argument] then
return Retrieving[Argument]()
else
Cache[Argument] = _handleRetrieving(Retrieving, Function, Argument)
return Cache[Argument]
end
end
end
--- Retrieves an instance from a parent
local function _retrieve(Parent, ClassName)
assert(type(ClassName) == "string", "Error: ClassName must be a string")
assert(typeof(Parent) == "Instance", ("Error: Parent must be an Instance, got '%s'"):format(typeof(Parent)))
return RunService:IsServer() and function(Name)
local Item = Parent:FindFirstChild(Name)
if not Item then
Item = Instance.new(ClassName)
Item.Archivable = false
Item.Name = Name
Item.Parent = Parent
end
return Item
end or function(Name)
local Resource = Parent:WaitForChild(Name, 5)
if Resource then
return Resource
end
warn(("Warning: No '%s' found, be sure to require '%s' on the server. Yielding for '%s'"):format(tostring(Name), tostring(Name), ClassName))
return Parent:WaitForChild(Name)
end
end
local function _getRepository(GetSubFolder)
if RunService:IsServer() then
local RepositoryFolder = ServerScriptService:FindFirstChild("Nevermore")
if not RepositoryFolder then
warn("Warning: No repository of Nevermore modules found (Expected in ServerScriptService with name \"Nevermore\"). Library retrieval will fail.")
RepositoryFolder = Instance.new("Folder")
RepositoryFolder.Name = "Nevermore"
end
return RepositoryFolder
else
return GetSubFolder("Modules")
end
end
local function _getLibraryCache(RepositoryFolder)
local LibraryCache = {}
for _, Child in pairs(RepositoryFolder:GetDescendants()) do
if Child:IsA("ModuleScript") and not Child:FindFirstAncestorOfClass("ModuleScript") then
if LibraryCache[Child.Name] then
error(("Error: Duplicate name of '%s' already exists"):format(Child.Name))
end
LibraryCache[Child.Name] = Child
end
end
return LibraryCache
end
local function _replicateRepository(ReplicationFolder, LibraryCache)
for Name, Library in pairs(LibraryCache) do
if not Name:lower():find("server") then
Library.Parent = ReplicationFolder
end
end
end
local function _debugLoading(Function)
local Count = 0
local RequestDepth = 0
return function(Module, ...)
Count = Count + 1
local LibraryID = Count
if DEBUG_MODE then
print(("\t"):rep(RequestDepth), LibraryID, "Loading: ", Module)
RequestDepth = RequestDepth + 1
end
local Result = Function(Module, ...)
if DEBUG_MODE then
RequestDepth = RequestDepth - 1
print(("\t"):rep(RequestDepth), LibraryID, "Done loading: ", Module)
end
return Result
end
end
local function _getLibraryLoader(LibraryCache)
--- Loads a library from Nevermore's library cache
-- @param Module The name of the library or a module
-- @return The library's value
return function(Module)
if typeof(Module) == "Instance" and Module:IsA("ModuleScript") then
return require(Module)
elseif type(Module) == "string" then
local ModuleScript = LibraryCache[Module] or error("Error: Library '" .. Module .. "' does not exist.", 2)
return require(ModuleScript)
else
error(("Error: Module must be a string or ModuleScript, got '%s'"):format(typeof(Module)))
end
end
end
local ResourceFolder = _retrieve(ReplicatedStorage, "Folder")("NevermoreResources")
local GetSubFolder = _retrieve(ResourceFolder, "Folder")
local RepositoryFolder = _getRepository(GetSubFolder)
local LibraryCache = _getLibraryCache(RepositoryFolder)
if RunService:IsServer() and not RunService:IsClient() then -- Don't move in SoloTestMode
_replicateRepository(GetSubFolder("Modules"), LibraryCache)
end
local Nevermore = {}
--- Load a library through Nevermore
-- @function LoadLibrary
-- @tparam string LibraryName
Nevermore.LoadLibrary = _asyncCache(_debugLoading(_getLibraryLoader(LibraryCache)))
--- Get a remote event
-- @function GetRemoteEvent
-- @tparam string RemoteEventName
-- @return RemoteEvent
Nevermore.GetRemoteEvent = _asyncCache(_retrieve(GetSubFolder("RemoteEvents"), "RemoteEvent"))
--- Get a remote function
-- @function GetRemoteFunction
-- @tparam string RemoteFunctionName
-- @return RemoteFunction
Nevermore.GetRemoteFunction = _asyncCache(_retrieve(GetSubFolder("RemoteFunctions"), "RemoteFunction"))
setmetatable(Nevermore, {
__call = function(self, ...)
return self.LoadLibrary(...)
end;
__index = function(self, Index)
error(("'%s is not a valid member of Nevermore"):format(tostring(Index)))
end;
})
return Nevermore
|
Fix __call metamethod call
|
Fix __call metamethod call
|
Lua
|
mit
|
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
|
21289fb45487552802484adbb42e5a10b4b411e2
|
lib/hixie76.lua
|
lib/hixie76.lua
|
local Crypto = require('crypto')
local rshift = require('bit').rshift
local sub, gsub, match, byte, char
do
local _table_0 = require('string')
sub, gsub, match, byte, char = _table_0.sub, _table_0.gsub, _table_0.match, _table_0.byte, _table_0.char
end
--
-- verify connection secret
--
local function verify_secret(req_headers, nonce)
local k1 = req_headers['sec-websocket-key1']
local k2 = req_headers['sec-websocket-key2']
if not k1 or not k2 then
return false
end
local data = ''
for _, k in { k1, k2 } do
local n = tonumber((gsub(k, '[^%d]', '')), 10)
local spaces = #(gsub(k, '[^ ]', ''))
if spaces == 0 or n % spaces ~= 0 then
return false
end
n = n / spaces
data = data .. char(rshift(n, 24) % 256, rshift(n, 16) % 256, rshift(n, 8) % 256, n % 256)
end
data = data .. nonce
return Crypto.md5(data, true)
end
--
-- send payload
--
local function sender(self, payload, callback)
self:write('\000')
self:write(payload)
self:write('\255', callback)
end
--
-- extract complete message frames from incoming data
--
local receiver
receiver = function (self, chunk)
-- collect data chunks
if chunk then self.buffer = self.buffer .. chunk end
local buf = self.buffer
-- wait for data
if #buf == 0 then return end
-- message starts with 0x00
if byte(buf, 1) == 0 then
-- and lasts
for i = 2, #buf do
-- until 0xFF
if byte(buf, i) == 255 then
-- extract payload
local payload = sub(buf, 2, i - 1)
-- consume data
self.buffer = sub(buf, i + 1)
-- emit event
if #payload > 0 then
self:emit('message', payload)
end
-- start over
receiver(self)
return
end
end
-- close frame is sequence of 0xFF, 0x00
else
if byte(buf, 1) == 255 and byte(buf, 2) == 0 then
self:emit('error')
-- other sequences signify broken framimg
else
self:emit('error', 1002, 'Broken framing')
end
end
end
--
-- initialize the channel
--
local function handshake(self, origin, location, callback)
-- ack connection
self.sec = self.req.headers['sec-websocket-key1']
local prefix = self.sec and 'Sec-' or ''
local protocol = self.req.headers['sec-websocket-protocol']
if protocol then
protocol = (match(protocol, '[^,]*'))
end
self:write_head(101, {
['Upgrade'] = 'WebSocket',
['Connection'] = 'Upgrade',
[prefix .. 'WebSocket-Origin'] = origin,
[prefix .. 'WebSocket-Location'] = location,
['Sec-WebSocket-Protocol'] = protocol,
})
self.has_body = true
-- verify connection
local data = ''
self.req:once('data', function (chunk)
data = data .. chunk
if self.sec == false or #data >= 8 then
if self.sec then
local nonce = sub(data, 1, 8)
data = sub(data, 9)
local reply = verify_secret(self.req.headers, nonce)
-- close unless verified
if not reply then
self:emit('error')
return
end
self.sec = nil
-- setup receiver
self.buffer = ''
self.req:on('data', Utils.bind(self, receiver))
-- register connection
self:write(reply)
if callback then callback() end
end
end
end)
-- setup sender
self.send = sender
end
-- module
return {
sender = sender,
receiver = receiver,
handshake = handshake,
}
|
local Utils = require('utils')
local Crypto = require('crypto')
local rshift = require('bit').rshift
local sub, gsub, match, byte, char
do
local _table_0 = require('string')
sub, gsub, match, byte, char = _table_0.sub, _table_0.gsub, _table_0.match, _table_0.byte, _table_0.char
end
--
-- verify connection secret
--
local function verify_secret(req_headers, nonce)
local k1 = req_headers['sec-websocket-key1']
local k2 = req_headers['sec-websocket-key2']
if not k1 or not k2 then
return false
end
local data = ''
for _, k in ipairs({ k1, k2 }) do
local n = tonumber((gsub(k, '[^%d]', '')), 10)
local spaces = #(gsub(k, '[^ ]', ''))
if spaces == 0 or n % spaces ~= 0 then
return false
end
n = n / spaces
data = data .. char(rshift(n, 24) % 256, rshift(n, 16) % 256, rshift(n, 8) % 256, n % 256)
end
data = data .. nonce
return Crypto.md5(data, true)
end
--
-- send payload
--
local function sender(self, payload, callback)
self:write('\000')
self:write(payload)
self:write('\255', callback)
end
--
-- extract complete message frames from incoming data
--
local receiver
receiver = function (self, chunk)
-- collect data chunks
if chunk then self.buffer = self.buffer .. chunk end
local buf = self.buffer
-- wait for data
if #buf == 0 then return end
-- message starts with 0x00
if byte(buf, 1) == 0x00 then
-- and lasts
for i = 2, #buf do
-- until 0xFF
if byte(buf, i) == 0xFF then
-- extract payload
local payload = sub(buf, 2, i - 1)
-- consume data
self.buffer = sub(buf, i + 1)
-- emit event
if #payload > 0 then
self:emit('message', payload)
end
-- start over
receiver(self)
return
end
end
-- close frame is sequence of 0xFF, 0x00
else
if byte(buf, 1) == 0xFF and byte(buf, 2) == 0x00 then
self:emit('error')
-- other sequences signify broken framimg
else
self:emit('error', 1002, 'Broken framing')
end
end
end
--
-- initialize the channel
--
local function handshake(self, origin, location, callback)
-- ack connection
self.sec = self.req.headers['sec-websocket-key1']
local prefix = self.sec and 'Sec-' or ''
local protocol = self.req.headers['sec-websocket-protocol']
if protocol then
protocol = (match(protocol, '[^,]*'))
end
self:write_head(101, {
['Upgrade'] = 'WebSocket',
['Connection'] = 'Upgrade',
[prefix .. 'WebSocket-Origin'] = origin,
[prefix .. 'WebSocket-Location'] = location,
['Sec-WebSocket-Protocol'] = protocol,
})
self.has_body = true
-- verify connection
local data = ''
self.req:once('data', function (chunk)
data = data .. chunk
if self.sec == false or #data >= 8 then
if self.sec then
local nonce = sub(data, 1, 8)
data = sub(data, 9)
local reply = verify_secret(self.req.headers, nonce)
-- close unless verified
if not reply then
self:emit('error')
return
end
self.sec = nil
-- setup receiver
self.buffer = data
self.req:on('data', Utils.bind(self, receiver))
-- register connection
self:write(reply)
if callback then callback() end
end
end
end)
-- setup sender
self.send = sender
end
-- module
return {
sender = sender,
receiver = receiver,
handshake = handshake,
}
|
fixed cut down initial buffer
|
fixed cut down initial buffer
|
Lua
|
mit
|
tempbottle/luvit-websocket,tempbottle/luvit-websocket,dvv/luvit-websocket
|
90568bd4cf9aaa602329115bb9bd5e8375fee4c6
|
scen_edit/view/actions/action.lua
|
scen_edit/view/actions/action.lua
|
--- Action module
--- Action class. Inherit to create custom Actions
-- @type Action
Action = LCS.class{}
-- Registered action classes
SB.actionRegistry = {}
--- Register the action.
-- @tparam table opts Table
-- @tparam string opts.name Machine name of the action control. Built-in actions have the "sb_" prefix.
-- @tparam Action opts.action Class inheritng from Action
-- @tparam string opts.tooltip Mouseover tooltip.
-- @tparam string opts.image Path to the icon.
-- Use this if you want to show the action in the toolbar
-- @tparam number[opt=0] opts.toolbar_order Order in the control toolbar.
-- @tparam string opts.hotkey Hotkey configuration.
-- @usage
-- SaveAction = Action:extends{}
-- SaveAction:Register({
-- name = "myAction",
-- tooltip = "Do something",
-- image = SB_IMG_DIR .. "my_icon.png",
-- toolbar_order = 42,
-- })
function Action:Register(opts)
assert(opts.name, "Missing name for action.")
assert(not SB.actionRegistry[opts.name],
"Action with name: " .. opts.name .. " already exists")
Log.Notice("Registering action: " .. opts.name)
opts.action = self
if opts.image and opts.toolbar_order == nil then
opts.toolbar_order = 0
end
if opts.tooltip == nil then
opts.tooltip = ""
elseif opts.hotkey ~= nil then
local keyText = " ("
if opts.hotkey.alt then
keyText = keyText .. "Alt "
end
if opts.hotkey.ctrl then
keyText = keyText .. "Ctrl "
end
if opts.hotkey.shift then
keyText = keyText .. "Shift "
end
local keySymbol = Spring.GetKeySymbol(opts.hotkey.key) or ""
keySymbol = String.Capitalize(keySymbol)
keyText = keyText .. keySymbol .. ")"
opts.tooltip = opts.tooltip .. keyText
end
opts.icon = opts.icon or ""
opts.order = opts.order or 0
opts.limit_state = not not opts.limit_state
SB.actionRegistry[opts.name] = opts
end
--- Deregister the action.
-- @usage
-- MyAction:Deregister()
-- -- alternatively
-- Action.Deregister("my-action")
function Action:Deregister(name)
if type(self) == "string" then
SB.actionRegistry[self] = nil
else
SB.actionRegistry[self.name] = nil
end
-- TODO: Remove the action from the GUI?
end
local actionsLoaded = false
local actionKeys = {}
function Action.GetActionsForKeyPress(default_state, key, mods, isRepeat, label, unicode)
if not actionsLoaded then
Action.PostLoadActions()
end
local actions = actionKeys[key]
if not actions then
return
end
for _, actionCfg in ipairs(actions) do
if actionCfg.hotkey.ctrl == mods.ctrl and
actionCfg.hotkey.shift == mods.shift and
actionCfg.hotkey.alt == mods.alt and
-- some actions cannot be done outside the default state
not (actionCfg.limit_state and not default_state) then
local action = actionCfg.action()
if not action.canExecute or action:canExecute() then
return action
else
return
end
end
end
end
function Action.PostLoadActions()
actionsLoaded = true
for name, action in pairs(SB.actionRegistry) do
if action.hotkey and action.hotkey.key then
if not actionKeys[action.hotkey.key] then
actionKeys[action.hotkey.key] = {}
end
action.hotkey.ctrl = not not action.hotkey.ctrl
action.hotkey.shift = not not action.hotkey.shift
action.hotkey.alt = not not action.hotkey.alt
table.insert(actionKeys[action.hotkey.key], action)
end
end
end
|
--- Action module
--- Action class. Inherit to create custom Actions
-- @type Action
Action = LCS.class{}
-- Registered action classes
SB.actionRegistry = {}
function Table.FindKey(tbl, value)
for k, v in pairs(tbl) do
if v == value then
return k
end
end
end
--- Register the action.
-- @tparam table opts Table
-- @tparam string opts.name Machine name of the action control. Built-in actions have the "sb_" prefix.
-- @tparam Action opts.action Class inheritng from Action
-- @tparam string opts.tooltip Mouseover tooltip.
-- @tparam string opts.image Path to the icon.
-- Use this if you want to show the action in the toolbar
-- @tparam number[opt=0] opts.toolbar_order Order in the control toolbar.
-- @tparam string opts.hotkey Hotkey configuration.
-- @usage
-- SaveAction = Action:extends{}
-- SaveAction:Register({
-- name = "myAction",
-- tooltip = "Do something",
-- image = SB_IMG_DIR .. "my_icon.png",
-- toolbar_order = 42,
-- })
function Action:Register(opts)
assert(opts.name, "Missing name for action.")
assert(not SB.actionRegistry[opts.name],
"Action with name: " .. opts.name .. " already exists")
Log.Notice("Registering action: " .. opts.name)
opts.action = self
if opts.image and opts.toolbar_order == nil then
opts.toolbar_order = 0
end
if opts.tooltip == nil then
opts.tooltip = ""
elseif opts.hotkey ~= nil then
local keyText = " ("
if opts.hotkey.alt then
keyText = keyText .. "Alt "
end
if opts.hotkey.ctrl then
keyText = keyText .. "Ctrl "
end
if opts.hotkey.shift then
keyText = keyText .. "Shift "
end
-- local keySymbol = Spring.GetKeySymbol(opts.hotkey.key) or ""
-- keySymbol = String.Capitalize(keySymbol)
local keySymbol = Table.FindKey(KEYSYMS, opts.hotkey.key) or ""
keyText = keyText .. keySymbol .. ")"
opts.tooltip = opts.tooltip .. keyText
end
opts.icon = opts.icon or ""
opts.order = opts.order or 0
opts.limit_state = not not opts.limit_state
SB.actionRegistry[opts.name] = opts
end
--- Deregister the action.
-- @usage
-- MyAction:Deregister()
-- -- alternatively
-- Action.Deregister("my-action")
function Action:Deregister(name)
if type(self) == "string" then
SB.actionRegistry[self] = nil
else
SB.actionRegistry[self.name] = nil
end
-- TODO: Remove the action from the GUI?
end
local actionsLoaded = false
local actionKeys = {}
function Action.GetActionsForKeyPress(default_state, key, mods, isRepeat, label, unicode)
if not actionsLoaded then
Action.PostLoadActions()
end
local actions = actionKeys[key]
if not actions then
return
end
for _, actionCfg in ipairs(actions) do
if actionCfg.hotkey.ctrl == mods.ctrl and
actionCfg.hotkey.shift == mods.shift and
actionCfg.hotkey.alt == mods.alt and
-- some actions cannot be done outside the default state
not (actionCfg.limit_state and not default_state) then
local action = actionCfg.action()
if not action.canExecute or action:canExecute() then
return action
else
return
end
end
end
end
function Action.PostLoadActions()
actionsLoaded = true
for name, action in pairs(SB.actionRegistry) do
if action.hotkey and action.hotkey.key then
if not actionKeys[action.hotkey.key] then
actionKeys[action.hotkey.key] = {}
end
action.hotkey.ctrl = not not action.hotkey.ctrl
action.hotkey.shift = not not action.hotkey.shift
action.hotkey.alt = not not action.hotkey.alt
table.insert(actionKeys[action.hotkey.key], action)
end
end
end
|
fix hotkey strings
|
fix hotkey strings
|
Lua
|
mit
|
Spring-SpringBoard/SpringBoard-Core,Spring-SpringBoard/SpringBoard-Core
|
cf54820f189c3f6702443c115a02943137303abd
|
OS/DiskOS/Programs/save.lua
|
OS/DiskOS/Programs/save.lua
|
local destination = select(1,...)
local flag = select(2,...) or ""
local ctype = select(3,...) or "gzip"
local clvl = tonumber(select(4,...) or "9")
local term = require("terminal")
local eapi = require("Editors")
local png = false
if destination and destination ~= "@clip" and destination ~= "-?" then
destination = term.resolve(destination)
if destination:sub(-4,-1) == ".png" then
png = true
elseif destination:sub(-5,-1) ~= ".lk12" then
destination = destination..".lk12"
end
elseif not destination then
destination = eapi.filePath
end
if (not destination) or destination == "-?" then
printUsage(
"save <file>","Saves the current loaded game",
"save <file>.png","Save in a png disk",
"save <file>.png -color [color]","Specify the color of the png disk",
"save @clip","Saves into the clipboard",
"save <file> -c","Saves with compression",
"save <file> -b","Saves in binary format",
"save","Saves on the last known file",
"save <image> --sheet","Saves the spritesheet as external .lk12 image",
"save <filename> --code","Saves the code as a .lua file"
)
return
end
if destination ~= "@clip" and fs.exists(destination) and fs.isDirectory(destination) then return 1, "Destination must not be a directory" end
if destination ~= "@clip" and fs.isReadonly(destination) then
return 1, "Destination is readonly !"
end
local sw, sh = screenSize()
if string.lower(flag) == "--sheet" then --Sheet export
local data = eapi.leditors[eapi.editors.sprite]:export(true)
if destination == "@clip" then clipboard(data) else fs.write(destination,data) end
color(11) print("Exported Spritesheet successfully")
return
elseif string.lower(flag) == "--map" then --Sheet export
local data = eapi.leditors[eapi.editors.tile]:export(true)
if destination == "@clip" then clipboard(data) else fs.write(destination,data) end
color(11) print("Exported Spritesheet successfully")
return
elseif string.lower(flag) == "--code" then
local data = eapi.leditors[eapi.editors.code]:export(true)
if destination == "@clip" then clipboard(data) else fs.write(destination:sub(1,-6)..".lua",data) end
color(11) print("Exported Lua code successfully")
return
end
eapi.filePath = destination
local editorsData = eapi:export()
local diskData = ""
if string.lower(flag) == "-c" then
diskData = LK12Utils.encodeDiskGame(editorsData,ctype,clvl)
elseif string.lower(flag) == "-b" or png then
diskData = LK12Utils.encodeDiskGame(editorsData,"binary")
else
diskData = LK12Utils.encodeDiskGame(editorsData)
end
if string.lower(flag) == "-color" and png then
FDD.newDisk(select(3,...))
end
if destination == "@clip" then
clipboard(diskData)
elseif png then
local diskSize = #diskData
if diskSize > 64*1024 then
return 1, "Save too big to fit in a floppy disk ("..(math.floor(diskSize/102.4)*10).." kb/ 64 kb) !"
end
memset(RamUtils.FRAM, diskData)
fs.write(destination, FDD.exportDisk())
else
fs.write(destination,diskData)
end
color(11) print(destination == "@clip" and "Saved to clipboard successfully" or "Saved successfully")
|
local destination = select(1,...)
local flag = select(2,...) or ""
local ctype = select(3,...) or "gzip"
local clvl = tonumber(select(4,...) or "9")
local term = require("terminal")
local eapi = require("Editors")
local png = false
if destination and destination ~= "@clip" and destination ~= "-?" then
destination = term.resolve(destination)
if destination:sub(-4,-1) == ".png" then
png = true
elseif destination:sub(-5,-1) ~= ".lk12" then
destination = destination..".lk12"
end
elseif not destination then
destination = eapi.filePath
end
if (not destination) or destination == "-?" then
printUsage(
"save <file>","Saves the current loaded game",
"save <file>.png","Save in a png disk",
"save <file>.png -color [color]","Specify the color of the png disk",
"save @clip","Saves into the clipboard",
"save <file> -c","Saves with compression",
"save <file> -b","Saves in binary format",
"save","Saves on the last known file",
"save <image> --sheet","Saves the spritesheet as external .lk12 image",
"save <filename> --code","Saves the code as a .lua file"
)
return
end
if destination ~= "@clip" and fs.exists(destination) and fs.isDirectory(destination) then return 1, "Destination must not be a directory" end
if destination ~= "@clip" and fs.isReadonly(destination) then
return 1, "Destination is readonly !"
end
local sw, sh = screenSize()
if string.lower(flag) == "--sheet" then --Sheet export
local data = eapi.leditors[eapi.editors.sprite]:export(true)
if destination == "@clip" then clipboard(data) else fs.write(destination,data) end
color(11) print("Exported Spritesheet successfully")
return
elseif string.lower(flag) == "--map" then --Sheet export
local data = eapi.leditors[eapi.editors.tile]:export(true)
if destination == "@clip" then clipboard(data) else fs.write(destination,data) end
color(11) print("Exported Spritesheet successfully")
return
elseif string.lower(flag) == "--code" then
local data = eapi.leditors[eapi.editors.code]:export(true)
if destination == "@clip" then clipboard(data) else fs.write(destination:sub(1,-6)..".lua",data) end
color(11) print("Exported Lua code successfully")
return
end
eapi.filePath = destination
local editorsData = (string.lower(flag) == "-b" or png) and eapi:encode() or eapi:export()
local diskData = ""
if string.lower(flag) == "-c" then
diskData = LK12Utils.encodeDiskGame(editorsData,ctype,clvl)
elseif string.lower(flag) == "-b" or png then
diskData = LK12Utils.encodeDiskGame(editorsData,"binary")
else
diskData = LK12Utils.encodeDiskGame(editorsData)
end
if string.lower(flag) == "-color" and png then
FDD.newDisk(select(3,...))
end
if destination == "@clip" then
clipboard(diskData)
elseif png then
local diskSize = #diskData
if diskSize > 64*1024 then
return 1, "Save too big to fit in a floppy disk ("..(math.floor(diskSize/102.4)*10).." kb/ 64 kb) !"
end
memset(RamUtils.FRAM, diskData)
fs.write(destination, FDD.exportDisk())
else
fs.write(destination,diskData)
end
color(11) print(destination == "@clip" and "Saved to clipboard successfully" or "Saved successfully")
|
Fix binary saving.
|
Fix binary saving.
Former-commit-id: 0bdceac40244fd088f5a5e0695f328d256db71dd
|
Lua
|
mit
|
RamiLego4Game/LIKO-12
|
284f1aa0bc14c737e80e193e2d50c956c90b0a2e
|
Sandboxer/sandboxer.pre.lua
|
Sandboxer/sandboxer.pre.lua
|
config={}
config.profile = loader.extra[1]
config.home_dir = loader.extra[2]
config.sandboxer_dir = loader.extra[3]
config.pwd = loader.extra[4]
config.sandbox_uid = loader.extra[5]
config.tmpdir = loader.extra[6]
config.ctldir = loader.extra[7]
config.uid = loader.extra[8]
config.gid = loader.extra[9]
-- define some defaults to use inside user-sandbox config files, to make them more portable and simple
-- TODO: make different defaults-sets optimized for different linux-distributions (maintain it in different config files, included there)
defaults={}
defaults.custom_commands={}
-- TODO: move this to chroot table (not complete yet)
defaults.custom_commands.etc=
{
'mkdir -p "etc"',
'cp -r "/etc/zsh"* "etc"; true',
'cp "/etc/yp.conf" "etc"; true',
'cp -r "/etc/X11" "etc"; true',
'cp "/etc/wgetrc" "etc"; true',
'cp "/etc/vimrc" "etc"; true',
'cp "/etc/vdpau_wrapper.cfg" "etc"; true',
'cp "/etc/termcap" "etc"; true',
'cp -r "/etc/security" "etc"; true',
'cp "/etc/resolv.conf" "etc"; true',
'cp -r "/etc/pulse" "etc"; true',
'cp "/etc/profile" "etc"; true',
'cp -r "/etc/profile.d" "etc"; true',
'cp "/etc/protocols" "etc"; true',
'cp "/etc/os-release" "etc"; true',
'cp "/etc/nsswitch.conf" "etc"; true',
'cp "/etc/nscd.conf" "etc"; true',
'cp "/etc/networks" "etc"; true',
'rm -f "etc/mtab"; ln -s "/proc/self/mounts" "etc/mtab"',
'cp "/etc/mime.types" "etc"; true',
'cp "/etc/localtime" "etc"; true',
'cp -r "/etc/ld.so"* "etc"; true',
'cp "/etc/libao.conf" "etc"; true',
'cp "/etc/ksh.kshrc" "etc"; true',
'cp "/etc/krb5.conf" "etc"; true',
'cp -r "/etc/kde4" "etc"; true',
'cp -r "/etc/java" "etc"; true',
'cp "/etc/inputrc" "etc"; true',
'cp "/etc/host"* "etc"; true',
'cp "/etc/HOSTNAME" "etc"; true',
'cp "/etc/freshwrapper.conf" "etc"; true',
'cp "/etc/ethers" "etc"; true',
'cp "/etc/drirc" "etc"; true',
'cp "/etc/DIR_COLORS" "etc"; true',
'cp "/etc/dialogrc" "etc"; true',
'cp "/etc/csh"* "etc"; true',
'cp -r "/etc/ca-certificates" "etc"; true',
'cp "/etc/asound-pulse.conf" "etc"; true',
'cp "/etc/alsa-pulse.conf" "etc"; true',
'cp -r "/etc/alternatives" "etc"; true',
'cp -r "/etc/alias"* "etc"; true',
'cp "/etc/adjtime" "etc"; true',
}
defaults.custom_commands.pwd=
{
'mkdir -p "etc"',
-- passwd and group files generation
'getent passwd root nobody > "etc/passwd"',
'echo "sandbox:x:'..config.uid..':'..config.gid..':sandbox:/home/sandbox:/bin/bash" >> "etc/passwd"',
'getent group root nobody nogroup > "etc/group"',
'echo "sandbox:x:'..config.gid..':" >> "etc/group"',
}
defaults.custom_commands.home=
{
'mkdir -p "'..loader.path.combine(loader.workdir,"userdata-"..config.sandbox_uid)..'"',
'test ! -d "'..loader.path.combine(loader.workdir,"userdata-"..config.sandbox_uid,"sandbox")..'" && \
2>/dev/null cp -rf /etc/skel "'..loader.path.combine(loader.workdir,"userdata-"..config.sandbox_uid,"sandbox")..'" || \
true',
}
defaults.env={}
defaults.env.blacklist=
{
"DBUS_SESSION_BUS_ADDRESS",
"DESKTOP_SESSION",
"FROM_HEADER",
"GPG_AGENT_INFO",
"GPG_TTY",
"INPUTRC",
"LOGNAME",
"MAIL",
"OLDPWD",
"SESSION_MANAGER",
"SSH_AGENT_PID",
"SSH_ASKPASS",
"SSH_AUTH_SOCK",
"WINDOWID",
"XAUTHORITY",
"XDG_SEAT",
"XDG_SEAT_PATH",
}
defaults.env.set=
{
{"HOME","/home/sandbox"},
{"PATH","/usr/bin:/bin:/usr/bin/X11"},
}
defaults.bwrap={}
defaults.bwrap.home_mount = {"bind",loader.path.combine(loader.workdir,"userdata-"..config.sandbox_uid),"/home"}
function defaults.bwrap.etc_mount(basedir)
return {"ro-bind",loader.path.combine(basedir,"chroot","etc"),"/etc"}
end
|
config={}
config.profile = loader.extra[1]
config.home_dir = loader.extra[2]
config.sandboxer_dir = loader.extra[3]
config.pwd = loader.extra[4]
config.sandbox_uid = loader.extra[5]
config.tmpdir = loader.extra[6]
config.ctldir = loader.extra[7]
config.uid = loader.extra[8]
config.gid = loader.extra[9]
-- define some defaults to use inside user-sandbox config files, to make them more portable and simple
-- TODO: make different defaults-sets optimized for different linux-distributions (maintain it in different config files, included there)
defaults={}
defaults.custom_commands={}
-- TODO: move this to chroot table (not complete yet)
defaults.custom_commands.etc=
{
'mkdir -p "etc"',
'cp -r "/etc/zsh"* "etc"; true',
'cp "/etc/yp.conf" "etc"; true',
'cp -r "/etc/X11" "etc"; true',
'cp "/etc/wgetrc" "etc"; true',
'cp "/etc/vimrc" "etc"; true',
'cp "/etc/vdpau_wrapper.cfg" "etc"; true',
'cp "/etc/termcap" "etc"; true',
'cp -r "/etc/security" "etc"; true',
'cp "/etc/resolv.conf" "etc"; true',
'cp -r "/etc/pulse" "etc"; true',
'cp "/etc/profile" "etc"; true',
'cp -r "/etc/profile.d" "etc"; true',
'cp "/etc/protocols" "etc"; true',
'cp "/etc/os-release" "etc"; true',
'cp "/etc/nsswitch.conf" "etc"; true',
'cp "/etc/nscd.conf" "etc"; true',
'cp "/etc/networks" "etc"; true',
'rm -f "etc/mtab"; ln -s "/proc/self/mounts" "etc/mtab"',
'cp "/etc/mime.types" "etc"; true',
'cp "/etc/localtime" "etc"; true',
'cp -r "/etc/ld.so"* "etc"; true',
'cp "/etc/libao.conf" "etc"; true',
'cp "/etc/ksh.kshrc" "etc"; true',
'cp "/etc/krb5.conf" "etc"; true',
'cp -r "/etc/kde4" "etc"; true',
'cp -r "/etc/java" "etc"; true',
'cp "/etc/inputrc" "etc"; true',
'cp "/etc/host"* "etc"; true',
'cp "/etc/HOSTNAME" "etc"; true',
'cp "/etc/freshwrapper.conf" "etc"; true',
'cp "/etc/ethers" "etc"; true',
'cp "/etc/drirc" "etc"; true',
'cp "/etc/DIR_COLORS" "etc"; true',
'cp "/etc/dialogrc" "etc"; true',
'cp "/etc/csh"* "etc"; true',
'cp -r "/etc/ca-certificates" "etc"; true',
'cp -r "/etc/bash"* "etc"; true',
'cp -r "/etc/mc" "etc"; true',
'cp "/etc/asound-pulse.conf" "etc"; true',
'cp "/etc/alsa-pulse.conf" "etc"; true',
'cp -r "/etc/alternatives" "etc"; true',
'cp -r "/etc/alias"* "etc"; true',
'cp "/etc/adjtime" "etc"; true',
}
defaults.custom_commands.pwd=
{
'mkdir -p "etc"',
-- passwd and group files generation
'getent passwd root nobody > "etc/passwd"',
'echo "sandbox:x:'..config.uid..':'..config.gid..':sandbox:/home/sandbox:/bin/bash" >> "etc/passwd"',
'getent group root nobody nogroup > "etc/group"',
'echo "sandbox:x:'..config.gid..':" >> "etc/group"',
}
defaults.custom_commands.home=
{
'mkdir -p "'..loader.path.combine(loader.workdir,"userdata-"..config.sandbox_uid)..'"',
'test ! -d "'..loader.path.combine(loader.workdir,"userdata-"..config.sandbox_uid,"sandbox")..'" && \
2>/dev/null cp -rf /etc/skel "'..loader.path.combine(loader.workdir,"userdata-"..config.sandbox_uid,"sandbox")..'" || \
true',
}
defaults.env={}
defaults.env.blacklist=
{
"DBUS_SESSION_BUS_ADDRESS",
"DESKTOP_SESSION",
"FROM_HEADER",
"GPG_AGENT_INFO",
"GPG_TTY",
"INPUTRC",
"LOGNAME",
"MAIL",
"OLDPWD",
"SESSION_MANAGER",
"SSH_AGENT_PID",
"SSH_ASKPASS",
"SSH_AUTH_SOCK",
"WINDOWID",
"XAUTHORITY",
"XDG_SEAT",
"XDG_SEAT_PATH",
}
defaults.env.set=
{
{"HOME","/home/sandbox"},
{"PATH","/usr/bin:/bin:/usr/bin/X11"},
{"USER","sandbox"},
}
defaults.bwrap={}
defaults.bwrap.home_mount = {"bind",loader.path.combine(loader.workdir,"userdata-"..config.sandbox_uid),"/home"}
function defaults.bwrap.etc_mount(basedir)
return {"ro-bind",loader.path.combine(basedir,"chroot","etc"),"/etc"}
end
|
sandboxer.pre.lua: minor fixes
|
sandboxer.pre.lua: minor fixes
|
Lua
|
mit
|
DarkCaster/Sandboxer,DarkCaster/Sandboxer
|
ee791e3117ce3355bcc49e9c8108c5143c989a1c
|
examples/echo-client-ev.lua
|
examples/echo-client-ev.lua
|
-- connects to a echo websocket server running a localhost:8080
-- sends a strong every second and prints the echoed messages
-- to stdout
local ev = require'ev'
local ws_client = require('websocket.client').ev()
ws_client:on_connect(function()
print('connected')
end)
ws_client:connect('ws://localhost:8080','echo')
ws_client:on_message(function(msg)
print('received',msg)
end)
local i = 0
ev.Timer.new(function()
i = i + 1
ws_client:send('hello '..i)
end,1,1)
ev.Loop.default:loop()
|
-- connects to a echo websocket server running a localhost:8080
-- sends a strong every second and prints the echoed messages
-- to stdout
local ev = require'ev'
local ws_client = require('websocket.client').ev()
ws_client:on_open(function()
print('connected')
end)
ws_client:connect('ws://echo.websocket.org','echo')
ws_client:on_message(function(ws, msg)
print('received',msg)
end)
local i = 0
ev.Timer.new(function()
i = i + 1
ws_client:send('hello '..i)
end,1,1):start(ev.Loop.default)
ev.Loop.default:loop()
|
fix example
|
fix example
|
Lua
|
mit
|
OptimusLime/lua-websockets,lipp/lua-websockets,enginix/lua-websockets,lipp/lua-websockets,KSDaemon/lua-websockets,enginix/lua-websockets,enginix/lua-websockets,KSDaemon/lua-websockets,OptimusLime/lua-websockets,KSDaemon/lua-websockets,lipp/lua-websockets,OptimusLime/lua-websockets
|
acf294c8259710d82628547bfbc2b50372d870e1
|
src/MarkdownEdit/Lib/task-list.lua
|
src/MarkdownEdit/Lib/task-list.lua
|
local List = require 'pandoc.List'
local M = {}
local function is_html (format)
return format == 'html' or format == 'html4' or format == 'html5'
end
--- Create a ballot box for the given output format.
function M.ballot_box (format)
if is_html(format) then
return pandoc.RawInline(
'html',
'<input type="checkbox" class="task-list-item-checkbox" disabled />'
)
elseif format == 'gfm' then
-- GFM includes raw HTML
return pandoc.RawInline('html', '[ ]')
elseif format == 'org' then
return pandoc.RawInline('org', '[ ]')
elseif format == 'latex' then
return pandoc.RawInline('tex', '$\\square$')
else
return pandoc.Str '?'
end
end
--- Create a checked ballot box for the given output format.
function M.ballot_box_with_check (format)
if is_html(format) then
return pandoc.RawInline(
'html',
'<input type="checkbox" class="task-list-item-checkbox" checked disabled />'
)
elseif format == 'gfm' then
-- GFM includes raw HTML
return pandoc.RawInline('html', '[x]')
elseif format == 'org' then
return pandoc.RawInline('org', '[X]')
elseif format == 'latex' then
return pandoc.RawInline('tex', '$\\rlap{$\\checkmark$}\\square$')
else
return pandoc.Str '?'
end
end
--- Replace a Github-style task indicator with a bullet box representation
--- suitable for the given output format.
function M.todo_marker (inlines, format)
if (inlines[1] and inlines[1].text == '[' and
inlines[2] and inlines[2].t == 'Space' and
inlines[3] and inlines[3].text == ']') then
return M.ballot_box(format), 3
elseif (inlines[1] and
(inlines[1].text == '[x]' or
inlines[1].text == '[X]')) then
return M.ballot_box_with_check(format), 1
else
return nil, 0
end
end
M.css_styles = [[
<style>
.task-list-item {
list-style-type: none;
}
.task-list-item-checkbox {
margin-left: -1.6em;
}
</style>
]]
--- Add task-list CSS styles to the header.
function M.add_task_list_css(meta)
local header_includes
if meta['header-includes'] and meta['header-includes'].t == 'MetaList' then
header_includes = meta['header-includes']
else
header_includes = pandoc.MetaList{meta['header-includes']}
end
header_includes[#header_includes + 1] =
pandoc.MetaBlocks{pandoc.RawBlock('html', M.css_styles)}
meta['header-includes'] = header_includes
return meta
end
--- Replace the todo marker in the given block, if any.
function M.replace_todo_markers (blk, format)
if blk.t ~= 'Para' and blk.t ~= 'Plain' then
return blk
end
local inlines = blk.content
local box, num_inlines = M.todo_marker(inlines, format)
if box == nil then
return blk
end
local new_inlines = List:new{box}
for j = 1, #inlines do
new_inlines[j + 1] = inlines[j + num_inlines]
end
return pandoc[blk.t](new_inlines) -- create Plain or Para
end
--- Convert Github- and org-mode-style task markers in a BulletList.
function M.modifyBulletList (list)
if not is_html(FORMAT) then
for _, item in ipairs(list.content) do
item[1] = M.replace_todo_markers(item[1], FORMAT)
end
return list
else
local res = List:new{pandoc.RawBlock('html', '<ul>')}
for _, item in ipairs(list.content) do
local blk = M.replace_todo_markers(item[1], FORMAT)
if blk == item[1] then -- does not have a todo marker
res[#res + 1] = pandoc.RawBlock('html', '<li>')
else
res[#res + 1] = pandoc.RawBlock('html', '<li class="task-list-item">')
item[1] = blk
end
res:extend(item)
res[#res + 1] = pandoc.RawBlock('html', '</li>')
end
res[#res + 1] = pandoc.RawBlock('html', '</ul>')
return res
end
end
M[1] = {
BulletList = M.modifyBulletList,
Meta = is_html(FORMAT) and M.add_task_list_css or nil
}
return M
|
local List = require 'pandoc.List'
local M = {}
local function is_html (format)
return format == 'html' or format == 'html4' or format == 'html5'
end
--- Create a ballot box for the given output format.
function M.ballot_box (format)
if is_html(format) then
return pandoc.RawInline(
'html',
'<input type="checkbox" class="task-list-item-checkbox" disabled />'
)
elseif format == 'gfm' then
-- GFM includes raw HTML
return pandoc.RawInline('html', '[ ]')
elseif format == 'org' then
return pandoc.RawInline('org', '[ ]')
elseif format == 'latex' then
return pandoc.RawInline('tex', '$\\square$')
else
return pandoc.Str '?'
end
end
--- Create a checked ballot box for the given output format.
function M.ballot_box_with_check (format)
if is_html(format) then
return pandoc.RawInline(
'html',
'<input type="checkbox" class="task-list-item-checkbox" checked disabled />'
)
elseif format == 'gfm' then
-- GFM includes raw HTML
return pandoc.RawInline('html', '[x]')
elseif format == 'org' then
return pandoc.RawInline('org', '[X]')
elseif format == 'latex' then
return pandoc.RawInline('tex', '$\\rlap{$\\checkmark$}\\square$')
else
return pandoc.Str '?'
end
end
--- Replace a Github-style task indicator with a bullet box representation
--- suitable for the given output format.
function M.todo_marker (inlines, format)
if (inlines[1] and inlines[1].text == '[' and
inlines[2] and inlines[2].t == 'Space' and
inlines[3] and inlines[3].text == ']') then
return M.ballot_box(format), 3
elseif (inlines[1] and
(inlines[1].text == '[x]' or
inlines[1].text == '[X]')) then
return M.ballot_box_with_check(format), 1
else
return nil, 0
end
end
M.css_styles = [[
<style>
.task-list-item {
list-style-type: none;
}
.task-list-item-checkbox {
margin-left: -1.6em;
}
</style>
]]
--- Add task-list CSS styles to the header.
function M.add_task_list_css(meta)
local header_includes
if meta['header-includes'] and meta['header-includes'].t == 'MetaList' then
header_includes = meta['header-includes']
else
header_includes = pandoc.MetaList{meta['header-includes']}
end
header_includes[#header_includes + 1] =
pandoc.MetaBlocks{pandoc.RawBlock('html', M.css_styles)}
meta['header-includes'] = header_includes
return meta
end
--- Replace the todo marker in the given block, if any.
function M.replace_todo_markers (blk, format)
if blk == nil then
return blk;
end
if blk.t ~= 'Para' and blk.t ~= 'Plain' then
return blk
end
local inlines = blk.content
local box, num_inlines = M.todo_marker(inlines, format)
if box == nil then
return blk
end
local new_inlines = List:new{box}
for j = 1, #inlines do
new_inlines[j + 1] = inlines[j + num_inlines]
end
return pandoc[blk.t](new_inlines) -- create Plain or Para
end
--- Convert Github- and org-mode-style task markers in a BulletList.
function M.modifyBulletList (list)
if not is_html(FORMAT) then
for _, item in ipairs(list.content) do
item[1] = M.replace_todo_markers(item[1], FORMAT)
end
return list
else
local res = List:new{pandoc.RawBlock('html', '<ul>')}
for _, item in ipairs(list.content) do
local blk = M.replace_todo_markers(item[1], FORMAT)
if blk == item[1] then -- does not have a todo marker
res[#res + 1] = pandoc.RawBlock('html', '<li>')
else
res[#res + 1] = pandoc.RawBlock('html', '<li class="task-list-item">')
item[1] = blk
end
res:extend(item)
res[#res + 1] = pandoc.RawBlock('html', '</li>')
end
res[#res + 1] = pandoc.RawBlock('html', '</ul>')
return res
end
end
M[1] = {
BulletList = M.modifyBulletList,
Meta = is_html(FORMAT) and M.add_task_list_css or nil
}
return M
|
fix error in script
|
fix error in script
|
Lua
|
mit
|
punker76/Markdown-Edit,mike-ward/Markdown-Edit
|
5a83793b8b03919d3cfbdcd42aa221accff0ec6b
|
ffi/framebuffer_android.lua
|
ffi/framebuffer_android.lua
|
local ffi = require("ffi")
local android = require("android")
local BB = require("ffi/blitbuffer")
local framebuffer = {}
function framebuffer:init()
-- we present this buffer to the outside
self.bb = BB.new(android.screen.width, android.screen.height, BB.TYPE_BBRGB32)
-- TODO: should we better use these?
-- android.lib.ANativeWindow_getWidth(window)
-- android.lib.ANativeWindow_getHeight(window)
self.bb:fill(BB.COLOR_WHITE)
self:refreshFull()
framebuffer.parent.init(self)
end
function framebuffer:refreshFullImp()
if android.app.window == nil then
android.LOGW("cannot blit: no window")
return
end
local buffer = ffi.new("ANativeWindow_Buffer[1]")
if android.lib.ANativeWindow_lock(android.app.window, buffer, nil) < 0 then
android.LOGW("Unable to lock window buffer")
return
end
local bb = nil
if buffer[0].format == ffi.C.WINDOW_FORMAT_RGBA_8888
or buffer[0].format == ffi.C.WINDOW_FORMAT_RGBX_8888
then
bb = BB.new(buffer[0].width, buffer[0].height, BB.TYPE_BBRGB32, buffer[0].bits, buffer[0].stride*4)
elseif buffer[0].format == ffi.C.WINDOW_FORMAT_RGB_565 then
bb = BB.new(buffer[0].width, buffer[0].height, BB.TYPE_BBRGB16, buffer[0].bits, buffer[0].stride*2)
else
android.LOGE("unsupported window format!")
end
if bb then
local ext_bb = self.full_bb or self.bb
-- on Android we just do the whole screen
local x = 0
local y = 0
local w = buffer[0].width
local h = buffer[0].height
bb:setInverse(ext_bb:getInverse())
-- adapt to possible rotation changes
bb:setRotation(ext_bb:getRotation())
bb:blitFrom(ext_bb, x, y, x, y, w, h)
end
android.lib.ANativeWindow_unlockAndPost(android.app.window);
end
return require("ffi/framebuffer"):extend(framebuffer)
|
local ffi = require("ffi")
local android = require("android")
local BB = require("ffi/blitbuffer")
local framebuffer = {}
function framebuffer:init()
-- we present this buffer to the outside
self.bb = BB.new(android.screen.width, android.screen.height, BB.TYPE_BBRGB32)
-- TODO: should we better use these?
-- android.lib.ANativeWindow_getWidth(window)
-- android.lib.ANativeWindow_getHeight(window)
self.bb:fill(BB.COLOR_WHITE)
self:refreshFull()
framebuffer.parent.init(self)
end
function framebuffer:refreshFullImp()
if android.app.window == nil then
android.LOGW("cannot blit: no window")
return
end
local buffer = ffi.new("ANativeWindow_Buffer[1]")
if android.lib.ANativeWindow_lock(android.app.window, buffer, nil) < 0 then
android.LOGW("Unable to lock window buffer")
return
end
local bb = nil
if buffer[0].format == ffi.C.WINDOW_FORMAT_RGBA_8888
or buffer[0].format == ffi.C.WINDOW_FORMAT_RGBX_8888
then
bb = BB.new(buffer[0].width, buffer[0].height, BB.TYPE_BBRGB32, buffer[0].bits, buffer[0].stride*4)
elseif buffer[0].format == ffi.C.WINDOW_FORMAT_RGB_565 then
bb = BB.new(buffer[0].width, buffer[0].height, BB.TYPE_BBRGB16, buffer[0].bits, buffer[0].stride*2)
else
android.LOGE("unsupported window format!")
end
if bb then
local ext_bb = self.full_bb or self.bb
bb:setInverse(ext_bb:getInverse())
-- adapt to possible rotation changes
bb:setRotation(ext_bb:getRotation())
bb:blitFrom(ext_bb)
end
android.lib.ANativeWindow_unlockAndPost(android.app.window);
end
return require("ffi/framebuffer"):extend(framebuffer)
|
[fix] ffi/framebuffer_android: landscape mode was broken (#542)
|
[fix] ffi/framebuffer_android: landscape mode was broken (#542)
|
Lua
|
agpl-3.0
|
Frenzie/koreader-base,houqp/koreader-base,koreader/koreader-base,NiLuJe/koreader-base,NiLuJe/koreader-base,Frenzie/koreader-base,Frenzie/koreader-base,koreader/koreader-base,apletnev/koreader-base,koreader/koreader-base,apletnev/koreader-base,houqp/koreader-base,apletnev/koreader-base,NiLuJe/koreader-base,houqp/koreader-base,koreader/koreader-base,houqp/koreader-base,apletnev/koreader-base,Frenzie/koreader-base,NiLuJe/koreader-base
|
c2aac0f71eb4b3736928e3396cca063eaa63073b
|
frontend/document/documentregistry.lua
|
frontend/document/documentregistry.lua
|
--[[--
This is a registry for document providers
]]--
local logger = require("logger")
local lfs = require("libs/libkoreader-lfs")
local util = require("util")
local DocumentRegistry = {
registry = {},
providers = {},
filetype_provider = {},
}
function DocumentRegistry:addProvider(extension, mimetype, provider, weight)
extension = string.lower(extension)
table.insert(self.providers, {
extension = extension,
mimetype = mimetype,
provider = provider,
weight = weight or 100,
})
self.filetype_provider[extension] = true
end
function DocumentRegistry:getRandomFile(dir, opened, extension)
local DocSettings = require("docsettings")
if string.sub(dir, string.len(dir)) ~= "/" then
dir = dir .. "/"
end
local files = {}
local i = 0
local ok, iter, dir_obj = pcall(lfs.dir, dir)
if ok then
for entry in iter, dir_obj do
if lfs.attributes(dir .. entry, "mode") == "file" and self:hasProvider(dir .. entry)
and (opened == nil or DocSettings:hasSidecarFile(dir .. entry) == opened)
and (extension == nil or extension[util.getFileNameSuffix(entry)]) then
i = i + 1
files[i] = entry
end
end
if i == 0 then
return nil
end
else
return nil
end
math.randomseed(os.time())
return dir .. files[math.random(i)]
end
--- Returns true if file has provider.
-- @string file
-- @treturn boolean
function DocumentRegistry:hasProvider(file)
local filename_suffix = string.lower(util.getFileNameSuffix(file))
local filetype_provider = G_reader_settings:readSetting("provider") or {}
if self.filetype_provider[filename_suffix] or filetype_provider[filename_suffix] then
return true
end
local DocSettings = require("docsettings")
if DocSettings:hasSidecarFile(file) then
local doc_settings_provider = DocSettings:open(file):readSetting("provider")
if doc_settings_provider then
return true
end
end
return false
end
--- Returns the preferred registered document handler.
-- @string file
-- @treturn table provider, or nil
function DocumentRegistry:getProvider(file)
local providers = self:getProviders(file)
if providers then
-- provider for document
local DocSettings = require("docsettings")
if DocSettings:hasSidecarFile(file) then
local doc_settings_provider = DocSettings:open(file):readSetting("provider")
if doc_settings_provider then
for _, provider in ipairs(providers) do
if provider.provider.provider == doc_settings_provider then
return provider.provider
end
end
end
end
-- global provider for filetype
local filename_suffix = util.getFileNameSuffix(file)
local g_settings_provider = G_reader_settings:readSetting("provider")
if g_settings_provider and g_settings_provider[filename_suffix] then
for _, provider in ipairs(providers) do
if provider.provider.provider == g_settings_provider[filename_suffix] then
return provider.provider
end
end
end
-- highest weighted provider
return providers[1].provider
else
for _, provider in ipairs(self.providers) do
if provider.extension == "txt" then
return provider.provider
end
end
end
end
--- Returns the registered document handlers.
-- @string file
-- @treturn table providers, or nil
function DocumentRegistry:getProviders(file)
local providers = {}
--- @todo some implementation based on mime types?
for _, provider in ipairs(self.providers) do
local suffix = string.sub(file, -string.len(provider.extension) - 1)
if string.lower(suffix) == "."..provider.extension then
-- if extension == provider.extension then
-- stick highest weighted provider at the front
if #providers >= 1 and provider.weight > providers[1].weight then
table.insert(providers, 1, provider)
else
table.insert(providers, provider)
end
end
end
if #providers >= 1 then
return providers
end
end
--- Sets the preferred registered document handler.
-- @string file
-- @bool all
function DocumentRegistry:setProvider(file, provider, all)
local _, filename_suffix = util.splitFileNameSuffix(file)
-- per-document
if not all then
local DocSettings = require("docsettings"):open(file)
DocSettings:saveSetting("provider", provider.provider)
DocSettings:flush()
-- global
else
local filetype_provider = G_reader_settings:readSetting("provider") or {}
filetype_provider[filename_suffix] = provider.provider
G_reader_settings:saveSetting("provider", filetype_provider)
end
end
function DocumentRegistry:openDocument(file, provider)
-- force a GC, so that any previous document used memory can be reused
-- immediately by this new document without having to wait for the
-- next regular gc. The second call may help reclaming more memory.
collectgarbage()
collectgarbage()
if not self.registry[file] then
provider = provider or self:getProvider(file)
if provider ~= nil then
local ok, doc = pcall(provider.new, provider, {file = file})
if ok then
self.registry[file] = {
doc = doc,
refs = 1,
}
else
logger.warn("cannot open document", file, doc)
end
end
else
self.registry[file].refs = self.registry[file].refs + 1
end
if self.registry[file] then
return self.registry[file].doc
end
end
function DocumentRegistry:closeDocument(file)
if self.registry[file] then
self.registry[file].refs = self.registry[file].refs - 1
if self.registry[file].refs == 0 then
self.registry[file] = nil
return 0
else
return self.registry[file].refs
end
else
error("Try to close unregistered file.")
end
end
-- load implementations:
require("document/credocument"):register(DocumentRegistry)
require("document/pdfdocument"):register(DocumentRegistry)
require("document/djvudocument"):register(DocumentRegistry)
require("document/picdocument"):register(DocumentRegistry)
return DocumentRegistry
|
--[[--
This is a registry for document providers
]]--
local logger = require("logger")
local lfs = require("libs/libkoreader-lfs")
local util = require("util")
local DocumentRegistry = {
registry = {},
providers = {},
filetype_provider = {},
}
function DocumentRegistry:addProvider(extension, mimetype, provider, weight)
extension = string.lower(extension)
table.insert(self.providers, {
extension = extension,
mimetype = mimetype,
provider = provider,
weight = weight or 100,
})
self.filetype_provider[extension] = true
end
function DocumentRegistry:getRandomFile(dir, opened, extension)
local DocSettings = require("docsettings")
if string.sub(dir, string.len(dir)) ~= "/" then
dir = dir .. "/"
end
local files = {}
local i = 0
local ok, iter, dir_obj = pcall(lfs.dir, dir)
if ok then
for entry in iter, dir_obj do
if lfs.attributes(dir .. entry, "mode") == "file" and self:hasProvider(dir .. entry)
and (opened == nil or DocSettings:hasSidecarFile(dir .. entry) == opened)
and (extension == nil or extension[util.getFileNameSuffix(entry)]) then
i = i + 1
files[i] = entry
end
end
if i == 0 then
return nil
end
else
return nil
end
math.randomseed(os.time())
return dir .. files[math.random(i)]
end
--- Returns true if file has provider.
-- @string file
-- @treturn boolean
function DocumentRegistry:hasProvider(file)
local filename_suffix = string.lower(util.getFileNameSuffix(file))
local filetype_provider = G_reader_settings:readSetting("provider") or {}
if self.filetype_provider[filename_suffix] or filetype_provider[filename_suffix] then
return true
end
local DocSettings = require("docsettings")
if DocSettings:hasSidecarFile(file) then
local doc_settings_provider = DocSettings:open(file):readSetting("provider")
if doc_settings_provider then
return true
end
end
return false
end
--- Returns the preferred registered document handler.
-- @string file
-- @treturn table provider, or nil
function DocumentRegistry:getProvider(file)
local providers = self:getProviders(file)
if providers then
-- provider for document
local DocSettings = require("docsettings")
if DocSettings:hasSidecarFile(file) then
local doc_settings_provider = DocSettings:open(file):readSetting("provider")
if doc_settings_provider then
for _, provider in ipairs(providers) do
if provider.provider.provider == doc_settings_provider then
return provider.provider
end
end
end
end
-- global provider for filetype
local filename_suffix = util.getFileNameSuffix(file)
local g_settings_provider = G_reader_settings:readSetting("provider")
if g_settings_provider and g_settings_provider[filename_suffix] then
for _, provider in ipairs(providers) do
if provider.provider.provider == g_settings_provider[filename_suffix] then
return provider.provider
end
end
end
-- highest weighted provider
return providers[1].provider
else
for _, provider in ipairs(self.providers) do
if provider.extension == "txt" then
return provider.provider
end
end
end
end
--- Returns the registered document handlers.
-- @string file
-- @treturn table providers, or nil
function DocumentRegistry:getProviders(file)
local providers = {}
--- @todo some implementation based on mime types?
for _, provider in ipairs(self.providers) do
local added = false
local suffix = string.sub(file, -string.len(provider.extension) - 1)
if string.lower(suffix) == "."..provider.extension then
for i, prov_prev in ipairs(providers) do
if prov_prev.provider == provider.provider then
if prov_prev.weight >= provider.weight then
added = true
else
table.remove(providers, i)
end
end
end
-- if extension == provider.extension then
-- stick highest weighted provider at the front
if not added and #providers >= 1 and provider.weight > providers[1].weight then
table.insert(providers, 1, provider)
elseif not added then
table.insert(providers, provider)
end
end
end
if #providers >= 1 then
return providers
end
end
--- Sets the preferred registered document handler.
-- @string file
-- @bool all
function DocumentRegistry:setProvider(file, provider, all)
local _, filename_suffix = util.splitFileNameSuffix(file)
-- per-document
if not all then
local DocSettings = require("docsettings"):open(file)
DocSettings:saveSetting("provider", provider.provider)
DocSettings:flush()
-- global
else
local filetype_provider = G_reader_settings:readSetting("provider") or {}
filetype_provider[filename_suffix] = provider.provider
G_reader_settings:saveSetting("provider", filetype_provider)
end
end
function DocumentRegistry:openDocument(file, provider)
-- force a GC, so that any previous document used memory can be reused
-- immediately by this new document without having to wait for the
-- next regular gc. The second call may help reclaming more memory.
collectgarbage()
collectgarbage()
if not self.registry[file] then
provider = provider or self:getProvider(file)
if provider ~= nil then
local ok, doc = pcall(provider.new, provider, {file = file})
if ok then
self.registry[file] = {
doc = doc,
refs = 1,
}
else
logger.warn("cannot open document", file, doc)
end
end
else
self.registry[file].refs = self.registry[file].refs + 1
end
if self.registry[file] then
return self.registry[file].doc
end
end
function DocumentRegistry:closeDocument(file)
if self.registry[file] then
self.registry[file].refs = self.registry[file].refs - 1
if self.registry[file].refs == 0 then
self.registry[file] = nil
return 0
else
return self.registry[file].refs
end
else
error("Try to close unregistered file.")
end
end
-- load implementations:
require("document/credocument"):register(DocumentRegistry)
require("document/pdfdocument"):register(DocumentRegistry)
require("document/djvudocument"):register(DocumentRegistry)
require("document/picdocument"):register(DocumentRegistry)
return DocumentRegistry
|
[fix] DocumentRegistry: only add provider once (#5947)
|
[fix] DocumentRegistry: only add provider once (#5947)
Fixes <https://github.com/koreader/koreader/issues/5946>.
|
Lua
|
agpl-3.0
|
poire-z/koreader,Frenzie/koreader,NiLuJe/koreader,Frenzie/koreader,poire-z/koreader,NiLuJe/koreader,Markismus/koreader,koreader/koreader,koreader/koreader,mwoz123/koreader,pazos/koreader,mihailim/koreader,Hzj-jie/koreader
|
59896b4cff7ecbdec2cce868d93b7b1b9076570b
|
autologin/directives/login.lua
|
autologin/directives/login.lua
|
function main(splash)
local full_render = splash.args.full_render
local first_request = true
splash:on_request(function(request)
if first_request then
request:set_timeout(60)
first_request = false
end
end)
splash:init_cookies(splash.args.cookies)
local ok, reason = splash:go{
splash.args.url,
headers=splash.args.headers,
http_method=splash.args.http_method,
body=splash.args.body,
}
if ok then
assert(splash:wait(0.5))
if splash.args.extra_js then
assert(splash:runjs(splash.args.extra_js))
assert(splash:wait(1.0))
end
if full_render then
splash:set_viewport_full()
end
end
local entries = splash:history()
if #entries > 0 then
local last_response = entries[#entries].response
return {
headers=last_response.headers,
cookies=splash:get_cookies(),
html=splash:html(),
http_status=last_response.status,
forms=full_render and render_forms(splash) or nil,
page=splash:jpeg{quality=80},
}
else
error(reason)
end
end
function render_forms(splash)
-- Return a table with base64-encoded screenshots of forms on the page.
-- Ordering of getElementsByTagName is guaranteed by
-- https://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#method-getElementsByTagName
local get_forms_bboxes = splash:jsfunc([[
function() {
var forms = document.getElementsByTagName('form');
var bboxes = [];
for (var i = 0; i < forms.length; i++) {
var r = forms[i].getBoundingClientRect();
bboxes.push([r.left, r.top, r.right, r.bottom]);
}
return bboxes;
}
]])
local bboxes = get_forms_bboxes()
local forms = {}
for i = 1, #bboxes do
forms[i] = {
region=bboxes[i],
screenshot=splash:jpeg{region=bboxes[i], quality=70},
}
end
return forms
end
|
json = require('json')
function main(splash)
local full_render = splash.args.full_render
local first_request = true
splash:on_request(function(request)
if first_request then
request:set_timeout(60)
first_request = false
end
end)
splash:init_cookies(splash.args.cookies)
local ok, reason = splash:go{
splash.args.url,
headers=splash.args.headers,
http_method=splash.args.http_method,
body=splash.args.body,
}
if ok then
assert(splash:wait(0.5))
if splash.args.extra_js then
local js_ok, js_reason = splash:runjs(splash.args.extra_js)
if not js_ok then
if type(js_reason) == 'table' then
js_reason = json.encode(js_reason)
end
error(js_reason)
end
assert(splash:wait(1.0))
end
if full_render then
splash:set_viewport_full()
end
end
local entries = splash:history()
if #entries > 0 then
local last_response = entries[#entries].response
return {
headers=last_response.headers,
cookies=splash:get_cookies(),
html=splash:html(),
http_status=last_response.status,
forms=full_render and render_forms(splash) or nil,
page=splash:jpeg{quality=80},
}
else
error(reason)
end
end
function render_forms(splash)
-- Return a table with base64-encoded screenshots of forms on the page.
-- Ordering of getElementsByTagName is guaranteed by
-- https://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#method-getElementsByTagName
local get_forms_bboxes = splash:jsfunc([[
function() {
var forms = document.getElementsByTagName('form');
var bboxes = [];
for (var i = 0; i < forms.length; i++) {
var r = forms[i].getBoundingClientRect();
bboxes.push([r.left, r.top, r.right, r.bottom]);
}
return bboxes;
}
]])
local bboxes = get_forms_bboxes()
local forms = {}
for i = 1, #bboxes do
forms[i] = {
region=bboxes[i],
screenshot=splash:jpeg{region=bboxes[i], quality=70},
}
end
return forms
end
|
Convert reason of splash:runjs to string
|
Convert reason of splash:runjs to string
Fixes GH-33
|
Lua
|
apache-2.0
|
TeamHG-Memex/autologin,TeamHG-Memex/autologin,TeamHG-Memex/autologin
|
eb586d3241bc956972e379c777f642a1880e9e41
|
nginx-metrix/output/helper.lua
|
nginx-metrix/output/helper.lua
|
local exports = {}
local version = require 'nginx-metrix.version'
local lust = require 'Lust'
local logger = require 'nginx-metrix.logger'
local formats2headers = {
["text"] = "text/plain",
["html"] = "text/html",
["json"] = "application/json",
}
local headers2formats = {}
for k,v in pairs(formats2headers) do
headers2formats[v]=k
end
local header_http_accept = function()
local _accept = {}
local accept_headers = ngx.req.get_headers().accept
if accept_headers then
for accept in string.gmatch(accept_headers, "%w+/%w+") do
table.insert(_accept, accept)
end
end
return iter(_accept)
end
---
-- @return string
local get_format = function()
-- trying to get format from GET params
local uri_args = ngx.req.get_uri_args()
if uri_args["format"] and formats2headers[uri_args["format"]] then
return uri_args["format"]
end
for _, accept in header_http_accept() do
if headers2formats[accept] then
return headers2formats[accept]
end
end
-- default is text
return 'text'
end
---
-- @param content_type string
---
local set_content_type_header = function(content_type)
if ngx.headers_sent then
logger.warn('Can not set Content-type header because headers already sent')
else
ngx.header.content_type = content_type or formats2headers[get_format()]
end
end
local title = function()
return 'Nginx Metrix'
end
local title_version = function()
return title() .. ' v' .. version
end
---------------------------
-- Utils
---------------------------
local format_value = function(collector, name, value)
if value ~= nil and type(collector.fields) == 'table' and collector.fields[name] ~= nil and collector.fields[name].format ~= nil then
value = collector.fields[name].format:format(value)
end
return value
end
---------------------------
-- HTML
---------------------------
local html_page_template = function(body)
local tpl = lust{
[[
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://yastatic.net/bootstrap/3.3.6/css/bootstrap.min.css" crossorigin="anonymous">
<link rel="stylesheet" href="https://yastatic.net/bootstrap/3.3.6/css/bootstrap-theme.min.css" crossorigin="anonymous">
<title>@if(title)<title>else<default_title></title>
</head>
<body>
<div class="row">
<div class="col-md-4 col-md-offset-1">
<h1>@if(title)<title>else<default_title></h1>
@body
</div>
</div>
<script src="https://yastatic.net/jquery/1.12.0/jquery.min.js"></script>
<script src="https://yastatic.net/bootstrap/3.3.6/js/bootstrap.min.js" crossorigin="anonymous"></script>
</body>
</html>
]],
title = [[$title]],
default_title = title()
}
if body then
tpl.body = body
end
return tpl
end
local html_section_template = function(body)
local tpl = lust{
[[
<div class="panel panel-@if(class)<class>else<default_class>">
<div class="panel-heading">
<h3 class="panel-title">$name</h3>
</div>
@if(with_body)<panel_body>else<body>
</div>
]],
panel_body = [[
<div class="panel-body">
@body
</div>
]],
class = [[$class]],
default_class = [[default]],
}
if body then
tpl.body = body
end
return tpl
end
local html_table_template = function()
return lust{
[[
<table class="table table-bordered table-condensed table-hover">
@map{ item=items }:{{<tr><th class="col-md-2">$item.name</th><td>$item.value</td></tr>}}
</table>
]]
}
end
local html_render_stats = function(collector)
return html_section_template(
html_table_template():gen{
items = collector:get_raw_stats():map(
function(name, value)
return {name=name, value=format_value(collector, name, value)}
end
):totable()
}
):gen{name=collector.name, with_body=false}
end
local text_header = function()
return lust("### $title ###\n"):gen{title = title_version()}
end
local text_section_template = function(stats)
local tpl = lust("\n[$namespace@$collector]\n@stats")
if stats then
tpl.stats = stats
end
return tpl
end
local text_item_template = function()
return lust("$name=$value\n")
end
local text_render_stats = function(collector)
return collector:get_raw_stats():reduce(
function(formated_stats, name, value)
return formated_stats .. text_item_template():gen{name=name, value=format_value(collector, name, value)}
end,
''
)
end
--------------------------------------------------------------------------------
-- EXPORTS
--------------------------------------------------------------------------------
exports.get_format = get_format
exports.set_content_type_header = set_content_type_header
exports.title = title
exports.title_version = title_version
exports.html = {}
exports.html.page_template = html_page_template
exports.html.section_template = html_section_template
exports.html.table_template = html_table_template
exports.html.render_stats = html_render_stats
exports.text = {}
exports.text.header = text_header
exports.text.section_template = text_section_template
exports.text.item_template = text_item_template
exports.text.render_stats = text_render_stats
if __TEST__ then
exports.__private__ = {
header_http_accept = header_http_accept,
format_value = format_value
}
end
return exports
|
local exports = {}
local version = require 'nginx-metrix.version'
local lust = require 'Lust'
local logger = require 'nginx-metrix.logger'
local formats2headers = {
["text"] = "text/plain",
["html"] = "text/html",
["json"] = "application/json",
}
local headers2formats = {}
for k,v in pairs(formats2headers) do
headers2formats[v]=k
end
local header_http_accept = function()
local _accept = {}
local accept_headers = ngx.req.get_headers().accept
if accept_headers then
for accept in string.gmatch(accept_headers, "%w+/%w+") do
table.insert(_accept, accept)
end
end
return iter(_accept)
end
---
-- @return string
local get_format = function()
-- trying to get format from GET params
local uri_args = ngx.req.get_uri_args()
if uri_args["format"] and formats2headers[uri_args["format"]] then
return uri_args["format"]
end
for _, accept in header_http_accept() do
if headers2formats[accept] then
return headers2formats[accept]
end
end
-- default is text
return 'text'
end
---
-- @param content_type string
---
local set_content_type_header = function(content_type)
if ngx.headers_sent then
logger.warn('Can not set Content-type header because headers already sent')
else
ngx.header.content_type = content_type or formats2headers[get_format()]
end
end
local title = function()
return 'Nginx Metrix'
end
local title_version = function()
return title() .. ' v' .. version
end
---------------------------
-- Utils
---------------------------
local format_value = function(collector, name, value)
if value ~= nil and type(collector.fields) == 'table' and collector.fields[name] ~= nil and collector.fields[name].format ~= nil then
value = collector.fields[name].format:format(value)
end
return value
end
---------------------------
-- HTML
---------------------------
local html_page_template = function(body)
local tpl = lust{[[
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://yastatic.net/bootstrap/3.3.6/css/bootstrap.min.css" crossorigin="anonymous">
<link rel="stylesheet" href="https://yastatic.net/bootstrap/3.3.6/css/bootstrap-theme.min.css" crossorigin="anonymous">
<title>@if(title)<title>else<default_title></title>
</head>
<body>
<div class="row">
<div class="col-md-4 col-md-offset-1">
<h1>@if(title)<title>else<default_title></h1>
@body
</div>
</div>
<script src="https://yastatic.net/jquery/1.12.0/jquery.min.js"></script>
<script src="https://yastatic.net/bootstrap/3.3.6/js/bootstrap.min.js" crossorigin="anonymous"></script>
</body>
</html>
]],
title = [[$title]],
default_title = title()
}
if body then
tpl.body = body
end
return tpl
end
local html_section_template = function(body)
local tpl = lust{[[
<div class="panel panel-@if(class)<class>else<default_class>">
<div class="panel-heading">
<h3 class="panel-title">$name</h3>
</div>
@if(with_body)<panel_body>else<body>
</div>
]],
panel_body = [[
<div class="panel-body">
@body
</div>
]],
class = [[$class]],
default_class = [[default]],
}
if body then
tpl.body = body
end
return tpl
end
local html_table_template = function()
return lust{[[
<table class="table table-bordered table-condensed table-hover">
@map{ item=items }:{{<tr><th class="col-md-2">$item.name</th><td>$item.value</td></tr>}}
</table>
]]}
end
local html_render_stats = function(collector)
return html_section_template(
html_table_template():gen{
items = collector:get_raw_stats():map(
function(name, value)
return {name=name, value=format_value(collector, name, value)}
end
):totable()
}
):gen{name=collector.name, with_body=false}
end
local text_header = function()
return lust("### $title ###\n"):gen{title = title_version()}
end
local text_section_template = function(stats)
local tpl = lust("\n[$namespace@$collector]\n@stats")
if stats then
tpl.stats = stats
end
return tpl
end
local text_item_template = function()
return lust("$name=$value\n")
end
local text_render_stats = function(collector)
return collector:get_raw_stats():reduce(
function(formated_stats, name, value)
return formated_stats .. text_item_template():gen{name=name, value=format_value(collector, name, value)}
end,
''
)
end
--------------------------------------------------------------------------------
-- EXPORTS
--------------------------------------------------------------------------------
exports.get_format = get_format
exports.set_content_type_header = set_content_type_header
exports.title = title
exports.title_version = title_version
exports.html = {}
exports.html.page_template = html_page_template
exports.html.section_template = html_section_template
exports.html.table_template = html_table_template
exports.html.render_stats = html_render_stats
exports.text = {}
exports.text.header = text_header
exports.text.section_template = text_section_template
exports.text.item_template = text_item_template
exports.text.render_stats = text_render_stats
if __TEST__ then
exports.__private__ = {
header_http_accept = header_http_accept,
format_value = format_value
}
end
return exports
|
output.helper coverage fix
|
output.helper coverage fix
|
Lua
|
mit
|
bankiru/nginx-metrix
|
a07e99233db5c124f3f886e603821f8ccb9cd6ed
|
nvim/nvim/lua/_/completion.lua
|
nvim/nvim/lua/_/completion.lua
|
local has_cmp, cmp = pcall(require, 'cmp')
local has_lspkind, lspkind = pcall(require, 'lspkind')
local utils = require '_.utils'
local M = {}
local check_back_space = function()
local col = vim.fn.col('.') - 1
if col == 0 or vim.fn.getline('.'):sub(col, col):match('%s') then
return true
else
return false
end
end
-- Use (s-)tab to:
--- move to prev/next item in completion menuone
--- jump to prev/next snippet's placeholder
_G._.tab_complete = function()
if vim.fn.pumvisible() == 1 then
return utils.t '<C-n>'
elseif vim.fn.call('vsnip#available', {1}) == 1 then
return utils.t '<Plug>(vsnip-expand-or-jump)'
elseif check_back_space() then
return utils.t '<Tab>'
else
return vim.fn['compe#complete']()
end
end
_G._.s_tab_complete = function()
if vim.fn.pumvisible() == 1 then
return utils.t '<C-p>'
elseif vim.fn.call('vsnip#jumpable', {-1}) == 1 then
return utils.t '<Plug>(vsnip-jump-prev)'
else
return utils.t '<S-Tab>'
end
end
local format = {}
if has_lspkind then
format = lspkind.cmp_format({
mode='symbol', -- show only symbol annotations
maxwidth=50 -- prevent the popup from showing more than provided characters (e.g 50 will not show more than 50 characters)
})
end
M.setup = function()
if has_cmp then
cmp.setup({
formatting={format=format},
snippet={
-- REQUIRED - you must specify a snippet engine
expand=function(args)
vim.fn['vsnip#anonymous'](args.body) -- For `vsnip` users.
end
},
window={
-- completion = cmp.config.window.bordered(),
-- documentation = cmp.config.window.bordered(),
},
mapping=cmp.mapping.preset.insert({
['<C-b>']=cmp.mapping.scroll_docs(-4),
['<C-f>']=cmp.mapping.scroll_docs(4),
['<C-Space>']=cmp.mapping.complete(),
['<C-e>']=cmp.mapping.abort(),
['<CR>']=cmp.mapping.confirm({select=true}) -- Accept currently selected item. Set `select` to `false` to only confirm explicitly selected items.
}),
sources=cmp.config.sources({
{name='nvim_lsp'},
{name='nvim_lsp_document_symbol'},
{name='nvim_lsp_signature_help'},
{name='nvim_lua'},
{name='vsnip'},
{name='tmux'},
{name='path'}
}, {{name='buffer'}})
})
-- Set configuration for specific filetype.
for _, cmd_type in ipairs({':', '/', '?', '@'}) do
cmp.setup.cmdline(cmd_type, {sources={{name='cmdline_history'}}})
end
-- Use buffer source for `/` (if you enabled `native_menu`, this won't work anymore).
cmp.setup.cmdline('/', {
mapping=cmp.mapping.preset.cmdline(),
sources={{name='buffer'}}
})
-- Use cmdline & path source for ':' (if you enabled `native_menu`, this won't work anymore).
cmp.setup.cmdline(':', {
mapping=cmp.mapping.preset.cmdline(),
sources=cmp.config.sources({{name='path'}}, {{name='cmdline'}})
})
end
end
return M
|
local has_cmp, cmp = pcall(require, 'cmp')
local has_lspkind, lspkind = pcall(require, 'lspkind')
local utils = require '_.utils'
local M = {}
local check_back_space = function()
local col = vim.fn.col('.') - 1
if col == 0 or vim.fn.getline('.'):sub(col, col):match('%s') then
return true
else
return false
end
end
-- Use (s-)tab to:
--- move to prev/next item in completion menuone
--- jump to prev/next snippet's placeholder
_G._.tab_complete = function()
if vim.fn.pumvisible() == 1 then
return utils.t '<C-n>'
elseif vim.fn.call('vsnip#available', {1}) == 1 then
return utils.t '<Plug>(vsnip-expand-or-jump)'
elseif check_back_space() then
return utils.t '<Tab>'
else
return vim.fn['compe#complete']()
end
end
_G._.s_tab_complete = function()
if vim.fn.pumvisible() == 1 then
return utils.t '<C-p>'
elseif vim.fn.call('vsnip#jumpable', {-1}) == 1 then
return utils.t '<Plug>(vsnip-jump-prev)'
else
return utils.t '<S-Tab>'
end
end
local format = {}
if has_lspkind then
format = lspkind.cmp_format({
mode='symbol', -- show only symbol annotations
maxwidth=50 -- prevent the popup from showing more than provided characters (e.g 50 will not show more than 50 characters)
})
end
M.setup = function()
if has_cmp then
cmp.setup({
formatting={format=format},
snippet={
-- REQUIRED - you must specify a snippet engine
expand=function(args)
vim.fn['vsnip#anonymous'](args.body) -- For `vsnip` users.
end
},
window={
-- completion = cmp.config.window.bordered(),
-- documentation = cmp.config.window.bordered(),
},
mapping=cmp.mapping.preset.insert({
['<C-b>']=cmp.mapping.scroll_docs(-4),
['<C-f>']=cmp.mapping.scroll_docs(4),
['<C-Space>']=cmp.mapping.complete(),
['<C-e>']=cmp.mapping.abort(),
['<CR>']=cmp.mapping.confirm({select=true}) -- Accept currently selected item. Set `select` to `false` to only confirm explicitly selected items.
}),
sources=cmp.config.sources({
{name='nvim_lsp'},
{name='nvim_lsp_document_symbol'},
{name='nvim_lsp_signature_help'},
{name='nvim_lua'},
{name='vsnip'},
{name='tmux'},
{name='path'}
}, {{name='buffer'}})
})
-- Set configuration for specific filetype.
cmp.setup.filetype('gitcommit', {
sources=cmp.config.sources({{name='git'}}, {{name='buffer'}})
})
-- Set configuration for specific filetype.
for _, cmd_type in ipairs({':', '/', '?', '@'}) do
cmp.setup.cmdline(cmd_type, {sources={{name='cmdline_history'}}})
end
end
end
return M
|
fix(nvim): cmp
|
fix(nvim): cmp
|
Lua
|
mit
|
skyuplam/dotfiles,skyuplam/dotfiles
|
a27d0d445edc15dbaa26e200bff2666cf41172b6
|
mod_blocking/mod_blocking.lua
|
mod_blocking/mod_blocking.lua
|
module:add_feature("urn:xmpp:blocking");
-- Add JID to default privacy list
function add_blocked_jid(username, host, jid)
local privacy_lists = datamanager.load(username, host, "privacy") or {};
local default_list_name = privacy_lists.default;
if not default_list_name then
default_list_name = "blocklist";
privacy_lists.default = default_list_name;
end
local default_list = privacy_lists.list[default_list_name];
if not default_list then
default_list = { name = default_list_name, items = {} };
privacy_lists.lists[default_list_name] = default_list;
end
local items = default_list.items;
local order = items[1].order; -- Must come first
for i=1,#items do -- order must be unique
items[i].order = items[i].order + 1;
end
table.insert(items, 1, { type = "jid"
, action = "deny"
, value = jid
, message = false
, ["presence-out"] = false
, ["presence-in"] = false
, iq = false
, order = order
};
datamanager.store(username, host, "privacy", privacy_lists);
end
-- Remove JID from default privacy list
function remove_blocked_jid(username, host, jid)
local privacy_lists = datamanager.load(username, host, "privacy") or {};
local default_list_name = privacy_lists.default;
if not default_list_name then return; end
local default_list = privacy_lists.list[default_list_name];
if not default_list then return; end
local items = default_list.items;
local item;
for i=1,#items do -- order must be unique
item = items[i];
if item.type == "jid" and item.action == "deny" and item.value == jid then
table.remove(items, i);
return true;
end
end
end
function get_blocked_jids(username, host)
-- Return array of blocked JIDs in default privacy list
local privacy_lists = datamanager.load(username, host, "privacy") or {};
local default_list_name = privacy_lists.default;
if not default_list_name then return {}; end
local default_list = privacy_lists.list[default_list_name];
if not default_list then return {}; end
local items = default_list.items;
local item;
local jid_list = {};
for i=1,#items do -- order must be unique
item = items[i];
if item.type == "jid" and item.action == "deny" then
jid_list[#jid_list+1] = item.value;
end
end
return jid_list;
end
function handle_blocking_command(session, stanza)
local username, host = jid_split(stanza.attr.from);
if stanza.attr.type == "set" and stanza.tags[1].name == "block" then
local block = stanza.tags[1]:get_child("block");
local block_jid_list = {};
for item in block:childtags() do
block_jid_list[#block_jid_list+1] = item.attr.jid;
end
if #block_jid_list == 0 then
--FIXME: Reply bad-request
else
for _, jid in ipairs(block_jid_list) do
add_blocked_jid(username, host, jid);
end
session.send(st.reply(stanza));
end
elseif stanza.attr.type == "get" and stanza.tags[1].name == "blocklist" then
local reply = st.reply(stanza):tag("blocklist", { xmlns = xmlns_block });
local blocked_jids = get_blocked_jids(username, host);
for _, jid in ipairs(blocked_jids) do
reply:tag("item", { jid = jid }):up();
end
session.send(reply);
else
--FIXME: Need to respond with service-unavailable
end
end
module:add_iq_handler("c2s", xmlns_blocking, handle_blocking_command);
|
module:add_feature("urn:xmpp:blocking");
-- Add JID to default privacy list
function add_blocked_jid(username, host, jid)
local privacy_lists = datamanager.load(username, host, "privacy") or {};
local default_list_name = privacy_lists.default;
if not default_list_name then
default_list_name = "blocklist";
privacy_lists.default = default_list_name;
end
local default_list = privacy_lists.list[default_list_name];
if not default_list then
default_list = { name = default_list_name, items = {} };
privacy_lists.lists[default_list_name] = default_list;
end
local items = default_list.items;
local order = items[1].order; -- Must come first
for i=1,#items do -- order must be unique
items[i].order = items[i].order + 1;
end
table.insert(items, 1, { type = "jid"
, action = "deny"
, value = jid
, message = false
, ["presence-out"] = false
, ["presence-in"] = false
, iq = false
, order = order
};
datamanager.store(username, host, "privacy", privacy_lists);
end
-- Remove JID from default privacy list
function remove_blocked_jid(username, host, jid)
local privacy_lists = datamanager.load(username, host, "privacy") or {};
local default_list_name = privacy_lists.default;
if not default_list_name then return; end
local default_list = privacy_lists.list[default_list_name];
if not default_list then return; end
local items = default_list.items;
local item;
for i=1,#items do -- order must be unique
item = items[i];
if item.type == "jid" and item.action == "deny" and item.value == jid then
table.remove(items, i);
return true;
end
end
datamanager.store(username, host, "privacy", privacy_lists);
end
function remove_all_blocked_jids(username, host)
local privacy_lists = datamanager.load(username, host, "privacy") or {};
local default_list_name = privacy_lists.default;
if not default_list_name then return; end
local default_list = privacy_lists.list[default_list_name];
if not default_list then return; end
local items = default_list.items;
local item;
for i=#items,1 do -- order must be unique
item = items[i];
if item.type == "jid" and item.action == "deny" then
table.remove(items, i);
end
end
datamanager.store(username, host, "privacy", privacy_lists);
end
function get_blocked_jids(username, host)
-- Return array of blocked JIDs in default privacy list
local privacy_lists = datamanager.load(username, host, "privacy") or {};
local default_list_name = privacy_lists.default;
if not default_list_name then return {}; end
local default_list = privacy_lists.list[default_list_name];
if not default_list then return {}; end
local items = default_list.items;
local item;
local jid_list = {};
for i=1,#items do -- order must be unique
item = items[i];
if item.type == "jid" and item.action == "deny" then
jid_list[#jid_list+1] = item.value;
end
end
return jid_list;
end
function handle_blocking_command(session, stanza)
local username, host = jid_split(stanza.attr.from);
if stanza.attr.type == "set" then
if stanza.tags[1].name == "block" then
local block = stanza.tags[1]:get_child("block");
local block_jid_list = {};
for item in block:childtags() do
block_jid_list[#block_jid_list+1] = item.attr.jid;
end
if #block_jid_list == 0 then
--FIXME: Reply bad-request
else
for _, jid in ipairs(block_jid_list) do
add_blocked_jid(username, host, jid);
end
session.send(st.reply(stanza));
end
elseif stanza.tags[1].name == "unblock" then
remove_all_blocked_jids(username, host);
session.send(st.reply(stanza));
end
elseif stanza.attr.type == "get" and stanza.tags[1].name == "blocklist" then
local reply = st.reply(stanza):tag("blocklist", { xmlns = xmlns_block });
local blocked_jids = get_blocked_jids(username, host);
for _, jid in ipairs(blocked_jids) do
reply:tag("item", { jid = jid }):up();
end
session.send(reply);
else
--FIXME: Need to respond with service-unavailable
end
end
module:add_iq_handler("c2s", xmlns_blocking, handle_blocking_command);
|
mod_blocking: Support for the "unblock all JIDs" case, and fix saving of rules after removing a JID
|
mod_blocking: Support for the "unblock all JIDs" case, and fix saving of rules after removing a JID
|
Lua
|
mit
|
prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2
|
2d3d841f8f20c3aad31d00d9555f6521480452f7
|
sample.lua
|
sample.lua
|
--[[
This file samples characters from a trained model
Code is based on implementation in
https://github.com/oxford-cs-ml-2015/practical6
]]--
require 'torch'
require 'nn'
require 'nngraph'
require 'optim'
require 'lfs'
require 'util.OneHot'
require 'util.misc'
cmd = torch.CmdLine()
cmd:text()
cmd:text('Sample from a character-level language model')
cmd:text()
cmd:text('Options')
-- required:
cmd:argument('-model','model checkpoint to use for sampling')
-- optional parameters
cmd:option('-seed',123,'random number generator\'s seed')
cmd:option('-sample',1,' 0 to use max at each timestep, 1 to sample at each timestep')
cmd:option('-primetext',"",'used as a prompt to "seed" the state of the LSTM using a given sequence, before we sample.')
cmd:option('-length',2000,'number of characters to sample')
cmd:option('-temperature',1,'temperature of sampling')
cmd:option('-gpuid',0,'which gpu to use. -1 = use CPU')
cmd:option('-verbose',1,'set to 0 to ONLY print the sampled text, no diagnostics')
cmd:text()
-- parse input params
opt = cmd:parse(arg)
-- gated print: simple utility function wrapping a print
function gprint(str)
if opt.verbose == 1 then print(str) end
end
-- check that cunn/cutorch are installed if user wants to use the GPU
if opt.gpuid >= 0 then
local ok, cunn = pcall(require, 'cunn')
local ok2, cutorch = pcall(require, 'cutorch')
if not ok then gprint('package cunn not found!') end
if not ok2 then gprint('package cutorch not found!') end
if ok and ok2 then
gprint('using CUDA on GPU ' .. opt.gpuid .. '...')
cutorch.setDevice(opt.gpuid + 1) -- note +1 to make it 0 indexed! sigh lua
cutorch.manualSeed(opt.seed)
else
gprint('Falling back on CPU mode')
opt.gpuid = -1 -- overwrite user setting
end
end
torch.manualSeed(opt.seed)
-- load the model checkpoint
if not lfs.attributes(opt.model, 'mode') then
gprint('Error: File ' .. opt.model .. ' does not exist. Are you sure you didn\'t forget to prepend cv/ ?')
end
checkpoint = torch.load(opt.model)
protos = checkpoint.protos
protos.rnn:evaluate() -- put in eval mode so that dropout works properly
-- initialize the vocabulary (and its inverted version)
local vocab = checkpoint.vocab
local ivocab = {}
for c,i in pairs(vocab) do ivocab[i] = c end
-- initialize the rnn state to all zeros
gprint('creating an LSTM...')
local current_state
local num_layers = checkpoint.opt.num_layers
current_state = {}
for L = 1,checkpoint.opt.num_layers do
-- c and h for all layers
local h_init = torch.zeros(1, checkpoint.opt.rnn_size)
if opt.gpuid >= 0 then h_init = h_init:cuda() end
table.insert(current_state, h_init:clone())
table.insert(current_state, h_init:clone())
end
state_size = #current_state
-- parse characters from a string
function get_char(str)
local len = #str
local left = 0
local arr = {0, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc}
local unordered = {}
local start = 1
local wordLen = 0
while len ~= left do
local tmp = string.byte(str, start)
local i = #arr
while arr[i] do
if tmp >= arr[i] then
break
end
i = i - 1
end
wordLen = i + wordLen
local tmpString = string.sub(str, start, wordLen)
start = start + i
left = left + i
unordered[#unordered+1] = tmpString
end
return unordered
end
-- do a few seeded timesteps
local seed_text = opt.primetext
if string.len(seed_text) > 0 then
gprint('seeding with ' .. seed_text)
gprint('--------------------------')
local chars = get_char(seed_text)
for i,c in ipairs(chars) do
prev_char = torch.Tensor{vocab[c]}
io.write(ivocab[prev_char[1]])
if opt.gpuid >= 0 then prev_char = prev_char:cuda() end
local lst = protos.rnn:forward{prev_char, unpack(current_state)}
-- lst is a list of [state1,state2,..stateN,output]. We want everything but last piece
current_state = {}
for i=1,state_size do table.insert(current_state, lst[i]) end
prediction = lst[#lst] -- last element holds the log probabilities
end
else
-- fill with uniform probabilities over characters (? hmm)
gprint('missing seed text, using uniform probability over first character')
gprint('--------------------------')
prediction = torch.Tensor(1, #ivocab):fill(1)/(#ivocab)
if opt.gpuid >= 0 then prediction = prediction:cuda() end
end
-- start sampling/argmaxing
for i=1, opt.length do
-- log probabilities from the previous timestep
-- make sure the output char is not UNKNOW
prev_char = 'UNKNOW'
while(prev_char == 'UNKNOW') do
if opt.sample == 0 then
-- use argmax
local _, prev_char_ = prediction:max(2)
prev_char = prev_char_:resize(1)
else
-- use sampling
prediction:div(opt.temperature) -- scale by temperature
local probs = torch.exp(prediction):squeeze()
probs:div(torch.sum(probs)) -- renormalize so probs sum to one
prev_char = torch.multinomial(probs:float(), 1):resize(1):float()
end
end
-- forward the rnn for next character
local lst = protos.rnn:forward{prev_char, unpack(current_state)}
current_state = {}
for i=1,state_size do table.insert(current_state, lst[i]) end
prediction = lst[#lst] -- last element holds the log probabilities
io.write(ivocab[prev_char[1]])
end
io.write('\n') io.flush()
|
--[[
This file samples characters from a trained model
Code is based on implementation in
https://github.com/oxford-cs-ml-2015/practical6
]]--
require 'torch'
require 'nn'
require 'nngraph'
require 'optim'
require 'lfs'
require 'util.OneHot'
require 'util.misc'
cmd = torch.CmdLine()
cmd:text()
cmd:text('Sample from a character-level language model')
cmd:text()
cmd:text('Options')
-- required:
cmd:argument('-model','model checkpoint to use for sampling')
-- optional parameters
cmd:option('-seed',123,'random number generator\'s seed')
cmd:option('-sample',1,' 0 to use max at each timestep, 1 to sample at each timestep')
cmd:option('-primetext',"",'used as a prompt to "seed" the state of the LSTM using a given sequence, before we sample.')
cmd:option('-length',2000,'max number of characters to sample')
cmd:option('-stop','\\n\\n\\n\\n\\n','stop sampling when detected')
cmd:option('-temperature',1,'temperature of sampling')
cmd:option('-gpuid',0,'which gpu to use. -1 = use CPU')
cmd:option('-verbose',1,'set to 0 to ONLY print the sampled text, no diagnostics')
cmd:text()
-- parse input params
opt = cmd:parse(arg)
-- gated print: simple utility function wrapping a print
function gprint(str)
if opt.verbose == 1 then print(str) end
end
-- check that cunn/cutorch are installed if user wants to use the GPU
if opt.gpuid >= 0 then
local ok, cunn = pcall(require, 'cunn')
local ok2, cutorch = pcall(require, 'cutorch')
if not ok then gprint('package cunn not found!') end
if not ok2 then gprint('package cutorch not found!') end
if ok and ok2 then
gprint('using CUDA on GPU ' .. opt.gpuid .. '...')
cutorch.setDevice(opt.gpuid + 1) -- note +1 to make it 0 indexed! sigh lua
cutorch.manualSeed(opt.seed)
else
gprint('Falling back on CPU mode')
opt.gpuid = -1 -- overwrite user setting
end
end
torch.manualSeed(opt.seed)
-- load the model checkpoint
if not lfs.attributes(opt.model, 'mode') then
gprint('Error: File ' .. opt.model .. ' does not exist. Are you sure you didn\'t forget to prepend cv/ ?')
end
checkpoint = torch.load(opt.model)
protos = checkpoint.protos
protos.rnn:evaluate() -- put in eval mode so that dropout works properly
-- initialize the vocabulary (and its inverted version)
local vocab = checkpoint.vocab
local ivocab = {}
for c,i in pairs(vocab) do ivocab[i] = c end
-- initialize the rnn state to all zeros
gprint('creating an LSTM...')
local current_state
local num_layers = checkpoint.opt.num_layers
current_state = {}
for L = 1,checkpoint.opt.num_layers do
-- c and h for all layers
local h_init = torch.zeros(1, checkpoint.opt.rnn_size)
if opt.gpuid >= 0 then h_init = h_init:cuda() end
table.insert(current_state, h_init:clone())
table.insert(current_state, h_init:clone())
end
state_size = #current_state
-- parse characters from a string
function get_char(str)
local len = #str
local left = 0
local arr = {0, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc}
local unordered = {}
local start = 1
local wordLen = 0
while len ~= left do
local tmp = string.byte(str, start)
local i = #arr
while arr[i] do
if tmp >= arr[i] then
break
end
i = i - 1
end
wordLen = i + wordLen
local tmpString = string.sub(str, start, wordLen)
start = start + i
left = left + i
unordered[#unordered+1] = tmpString
end
return unordered
end
-- do a few seeded timesteps
local seed_text = opt.primetext
if string.len(seed_text) > 0 then
gprint('seeding with ' .. seed_text)
gprint('--------------------------')
local chars = get_char(seed_text)
for i,c in ipairs(chars) do
prev_char = torch.Tensor{vocab[c]}
io.write(ivocab[prev_char[1]])
if opt.gpuid >= 0 then prev_char = prev_char:cuda() end
local lst = protos.rnn:forward{prev_char, unpack(current_state)}
-- lst is a list of [state1,state2,..stateN,output]. We want everything but last piece
current_state = {}
for i=1,state_size do table.insert(current_state, lst[i]) end
prediction = lst[#lst] -- last element holds the log probabilities
end
else
-- fill with uniform probabilities over characters (? hmm)
gprint('missing seed text, using uniform probability over first character')
gprint('--------------------------')
prediction = torch.Tensor(1, #ivocab):fill(1)/(#ivocab)
if opt.gpuid >= 0 then prediction = prediction:cuda() end
end
-- start sampling/argmaxing
result = ''
for i=1, opt.length do
-- log probabilities from the previous timestep
-- make sure the output char is not UNKNOW
if opt.sample == 0 then
-- use argmax
local _, prev_char_ = prediction:max(2)
prev_char = prev_char_:resize(1)
else
-- use sampling
real_char = 'UNKNOW'
while(real_char == 'UNKNOW') do
prediction:div(opt.temperature) -- scale by temperature
local probs = torch.exp(prediction):squeeze()
probs:div(torch.sum(probs)) -- renormalize so probs sum to one
prev_char = torch.multinomial(probs:float(), 1):resize(1):float()
real_char = ivocab[prev_char[1]]
end
end
-- forward the rnn for next character
local lst = protos.rnn:forward{prev_char, unpack(current_state)}
current_state = {}
for i=1,state_size do table.insert(current_state, lst[i]) end
prediction = lst[#lst] -- last element holds the log probabilities
-- io.write(ivocab[prev_char[1]])
result = result .. ivocab[prev_char[1]]
-- in my data, five \n represent the end of each document
-- so count \n to stop sampling
if string.find(result, opt.stop) then break end
end
io.write(result)
io.write('\n') io.flush()
|
fix bug & add stop option
|
fix bug & add stop option
|
Lua
|
mit
|
tonyqtian/melody-generator
|
9e38799a6a4fe29f8da5c0a10d27bd08eba68aae
|
nvim/nvim/lua/_/formatter.lua
|
nvim/nvim/lua/_/formatter.lua
|
local has_config, formatter = pcall(require, 'formatter')
if not has_config then return end
local utils = require '_.utils'
local M = {}
local function prettier()
return {
exe='prettier',
args={
-- Config prettier
'--config-precedence',
'prefer-file',
'--no-bracket-spacing',
'--single-quote',
'--trailing-comma',
'all',
-- Get file
'--stdin-filepath',
vim.fn.shellescape(vim.api.nvim_buf_get_name(0))
},
stdin=true
}
end
local function shfmt() return {exe='shfmt', args={'-'}, stdin=true} end
local ftConfigs = {
lua={
function()
return {
exe='lua-format',
args={
vim.fn.shellescape(vim.api.nvim_buf_get_name(0)),
'--tab-width=2',
'--indent-width=2',
'--align-table-field',
'--chop-down-table',
'--chop-down-parameter',
'--double-quote-to-single-quote',
'--no-break-after-operator',
'--no-spaces-inside-table-braces',
'--no-spaces-around-equals-in-field',
'--no-spaces-inside-functioncall-parens',
'--no-spaces-inside-functiondef-parens'
},
stdin=true
}
end
},
rust={
function() return {exe='rustfmt', args={'--emit=stdout'}, stdin=true} end
},
nix={function() return {exe='nixpkgs-fmt', stdin=true} end},
sh={shfmt},
bash={shfmt}
}
local commonPrettierFTs = {
'css',
'scss',
'less',
'html',
'yaml',
'java',
'javascript',
'javascript.jsx',
'javascriptreact',
'typescript',
'typescript.tsx',
'typescriptreact',
'markdown',
'markdown.mdx',
'json'
}
for _, ft in ipairs(commonPrettierFTs) do ftConfigs[ft] = {prettier} end
local function setup()
utils.augroup('FormatAU', function()
vim.api.nvim_command('autocmd BufWritePost * FormatWrite')
end)
return {logging=true, filetype=ftConfigs}
end
function M.setup() formatter.setup(setup()) end
return M
|
local has_config, formatter = pcall(require, 'formatter')
if not has_config then return end
local utils = require '_.utils'
local M = {}
local function prettier()
return {
exe='prettier',
args={
-- Config prettier
'--config-precedence',
'prefer-file',
'--no-bracket-spacing',
'--single-quote',
'--trailing-comma',
'all',
-- Get file
'--stdin-filepath',
vim.fn.shellescape(vim.api.nvim_buf_get_name(0))
},
stdin=true
}
end
local function shfmt() return {exe='shfmt', args={'-'}, stdin=true} end
local ftConfigs = {
lua={
function()
return {
exe='lua-format',
args={
vim.fn.shellescape(vim.api.nvim_buf_get_name(0)),
'--tab-width=2',
'--indent-width=2',
'--align-table-field',
'--chop-down-table',
'--chop-down-parameter',
'--double-quote-to-single-quote',
'--no-break-after-operator',
'--no-spaces-inside-table-braces',
'--no-spaces-around-equals-in-field',
'--no-spaces-inside-functioncall-parens',
'--no-spaces-inside-functiondef-parens'
},
stdin=true
}
end
},
rust={
function() return {exe='rustfmt', args={'--emit=stdout'}, stdin=true} end
},
nix={function() return {exe='nixpkgs-fmt', stdin=true} end},
sh={shfmt},
bash={shfmt}
}
local commonPrettierFTs = {
'css',
'scss',
'less',
'html',
'yaml',
'java',
'javascript',
'javascript.jsx',
'javascriptreact',
'typescript',
'typescript.tsx',
'typescriptreact',
'markdown',
'markdown.mdx',
'json'
}
for _, ft in ipairs(commonPrettierFTs) do ftConfigs[ft] = {prettier} end
local function setup()
utils.augroup('FormatAU', function()
vim.api.nvim_command(
'autocmd BufWritePost *.js,*.jsx,*.ts,*.tsx,*.rs,*.md,*.json FormatWrite')
end)
return {logging=true, filetype=ftConfigs}
end
function M.setup() formatter.setup(setup()) end
return M
|
fix(nvim): specify files for auto formatting on write
|
fix(nvim): specify files for auto formatting on write
|
Lua
|
mit
|
skyuplam/dotfiles,skyuplam/dotfiles
|
88c98da0702e7ef2b527f3f1bccb5b3d43e78c24
|
semver.lua
|
semver.lua
|
local semver = {
_VERSION = '1.2.0',
_DESCRIPTION = 'semver for Lua',
_URL = 'https://github.com/kikito/semver.lua',
_LICENSE = [[
MIT LICENSE
Copyright (c) 2015 Enrique García Cota
Permission is hereby granted, free of charge, to any person obtaining a
copy of tother software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and tother permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
]]
}
local function checkPositiveInteger(number, name)
assert(number >= 0, name .. ' must be a valid positive number')
assert(math.floor(number) == number, name .. ' must be an integer')
end
local function present(value)
return value and value ~= ''
end
-- splitByDot("a.bbc.d") == {"a", "bbc", "d"}
local function splitByDot(str)
str = str or ""
local t, count = {}, 0
str:gsub("([^%.]+)", function(c)
count = count + 1
t[count] = c
end)
return t
end
local function parsePrereleaseAndBuildWithSign(str)
local prereleaseWithSign, buildWithSign = str:match("^(-[^+]+)(+.+)$")
if not (prereleaseWithSign and buildWithSign) then
prereleaseWithSign = str:match("^(-.+)$")
buildWithSign = str:match("^(+.+)$")
end
assert(prereleaseWithSign or buildWithSign, ("The parameter %q must begin with + or - to denote a prerelease or a build"):format(str))
return prereleaseWithSign, buildWithSign
end
local function parsePrerelease(prereleaseWithSign)
if prereleaseWithSign then
local prerelease = prereleaseWithSign:match("^-(%w[%.%w-]*)$")
assert(prerelease, ("The prerelease %q is not a slash followed by alphanumerics, dots and slashes"):format(prereleaseWithSign))
return prerelease
end
end
local function parseBuild(buildWithSign)
if buildWithSign then
local build = buildWithSign:match("^%+(%w[%.%w-]*)$")
assert(build, ("The build %q is not a + sign followed by alphanumerics, dots and slashes"):format(buildWithSign))
return build
end
end
local function parsePrereleaseAndBuild(str)
if not present(str) then return nil, nil end
local prereleaseWithSign, buildWithSign = parsePrereleaseAndBuildWithSign(str)
local prerelease = parsePrerelease(prereleaseWithSign)
local build = parseBuild(buildWithSign)
return prerelease, build
end
local function parseVersion(str)
local sMajor, sMinor, sPatch, sPrereleaseAndBuild = str:match("^(%d+)%.?(%d*)%.?(%d*)(.-)$")
assert(type(sMajor) == 'string', ("Could not extract version number(s) from %q"):format(str))
local major, minor, patch = tonumber(sMajor), tonumber(sMinor), tonumber(sPatch)
local prerelease, build = parsePrereleaseAndBuild(sPrereleaseAndBuild)
return major, minor, patch, prerelease, build
end
-- return 0 if a == b, -1 if a < b, and 1 if a > b
local function compare(a,b)
return a == b and 0 or a < b and -1 or 1
end
local function compareIds(myId, otherId)
if myId == otherId then return 0
elseif not myId then return -1
elseif not otherId then return 1
end
local selfNumber, otherNumber = tonumber(myId), tonumber(otherId)
if selfNumber and otherNumber then -- numerical comparison
return compare(selfNumber, otherNumber)
-- numericals are always smaller than alphanums
elseif selfNumber then
return -1
elseif otherNumber then
return 1
else
return compare(myId, otherId) -- alphanumerical comparison
end
end
local function smallerIdList(myIds, otherIds)
local myLength = #myIds
local comparison
for i=1, myLength do
comparison = compareIds(myIds[i], otherIds[i])
if comparison ~= 0 then
return comparison == -1
end
-- if comparison == 0, continue loop
end
return myLength < #otherIds
end
local function smallerPrerelease(mine, other)
if mine == other or not mine then return false
elseif not other then return true
end
return smallerIdList(splitByDot(mine), splitByDot(other))
end
local methods = {}
function methods:nextMajor()
return semver(self.major + 1, 0, 0)
end
function methods:nextMinor()
return semver(self.major, self.minor + 1, 0)
end
function methods:nextPatch()
return semver(self.major, self.minor, self.patch + 1)
end
local mt = { __index = methods }
function mt:__eq(other)
return self.major == other.major and
self.minor == other.minor and
self.patch == other.patch and
self.prerelease == other.prerelease
-- notice that build is ignored for precedence in semver 2.0.0
end
function mt:__lt(other)
if self.major ~= other.major then return self.major < other.major end
if self.minor ~= other.minor then return self.minor < other.minor end
if self.patch ~= other.patch then return self.patch < other.patch end
return smallerPrerelease(self.prerelease, other.prerelease)
-- notice that build is ignored for precedence in semver 2.0.0
end
-- This works like the "pessimisstic operator" in Rubygems.
-- if a and b are versions, a ^ b means "b is backwards-compatible with a"
-- in other words, "it's safe to upgrade from a to b"
function mt:__pow(other)
return self.major == other.major and
self.minor <= other.minor
end
function mt:__tostring()
local buffer = { ("%d.%d.%d"):format(self.major, self.minor, self.patch) }
if self.prerelease then table.insert(buffer, "-" .. self.prerelease) end
if self.build then table.insert(buffer, "+" .. self.build) end
return table.concat(buffer)
end
local function new(major, minor, patch, prerelease, build)
assert(major, "At least one parameter is needed")
if type(major) == 'string' then
major,minor,patch,prerelease,build = parseVersion(major)
end
patch = patch or 0
minor = minor or 0
checkPositiveInteger(major, "major")
checkPositiveInteger(minor, "minor")
checkPositiveInteger(patch, "patch")
local result = {major=major, minor=minor, patch=patch, prerelease=prerelease, build=build}
return setmetatable(result, mt)
end
setmetatable(semver, { __call = function(_, ...) return new(...) end })
semver._VERSION= semver(semver._VERSION)
return semver
|
local semver = {
_VERSION = '1.2.0',
_DESCRIPTION = 'semver for Lua',
_URL = 'https://github.com/kikito/semver.lua',
_LICENSE = [[
MIT LICENSE
Copyright (c) 2015 Enrique García Cota
Permission is hereby granted, free of charge, to any person obtaining a
copy of tother software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and tother permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
]]
}
local function checkPositiveInteger(number, name)
assert(number >= 0, name .. ' must be a valid positive number')
assert(math.floor(number) == number, name .. ' must be an integer')
end
local function present(value)
return value and value ~= ''
end
-- splitByDot("a.bbc.d") == {"a", "bbc", "d"}
local function splitByDot(str)
str = str or ""
local t, count = {}, 0
str:gsub("([^%.]+)", function(c)
count = count + 1
t[count] = c
end)
return t
end
local function parsePrereleaseAndBuildWithSign(str)
local prereleaseWithSign, buildWithSign = str:match("^(-[^+]+)(+.+)$")
if not (prereleaseWithSign and buildWithSign) then
prereleaseWithSign = str:match("^(-.+)$")
buildWithSign = str:match("^(+.+)$")
end
assert(prereleaseWithSign or buildWithSign, ("The parameter %q must begin with + or - to denote a prerelease or a build"):format(str))
return prereleaseWithSign, buildWithSign
end
local function parsePrerelease(prereleaseWithSign)
if prereleaseWithSign then
local prerelease = prereleaseWithSign:match("^-(%w[%.%w-]*)$")
assert(prerelease, ("The prerelease %q is not a slash followed by alphanumerics, dots and slashes"):format(prereleaseWithSign))
return prerelease
end
end
local function parseBuild(buildWithSign)
if buildWithSign then
local build = buildWithSign:match("^%+(%w[%.%w-]*)$")
assert(build, ("The build %q is not a + sign followed by alphanumerics, dots and slashes"):format(buildWithSign))
return build
end
end
local function parsePrereleaseAndBuild(str)
if not present(str) then return nil, nil end
local prereleaseWithSign, buildWithSign = parsePrereleaseAndBuildWithSign(str)
local prerelease = parsePrerelease(prereleaseWithSign)
local build = parseBuild(buildWithSign)
return prerelease, build
end
local function parseVersion(str)
local sMajor, sMinor, sPatch, sPrereleaseAndBuild = str:match("^(%d+)%.?(%d*)%.?(%d*)(.-)$")
assert(type(sMajor) == 'string', ("Could not extract version number(s) from %q"):format(str))
local major, minor, patch = tonumber(sMajor), tonumber(sMinor), tonumber(sPatch)
local prerelease, build = parsePrereleaseAndBuild(sPrereleaseAndBuild)
return major, minor, patch, prerelease, build
end
-- return 0 if a == b, -1 if a < b, and 1 if a > b
local function compare(a,b)
return a == b and 0 or a < b and -1 or 1
end
local function compareIds(myId, otherId)
if myId == otherId then return 0
elseif not myId then return -1
elseif not otherId then return 1
end
local selfNumber, otherNumber = tonumber(myId:match("%w(%d+)")), tonumber(otherId:match("%w(%d+)"))
print(myId,myId:match("%w(%d+)"))
if selfNumber and otherNumber then -- numerical comparison
return compare(selfNumber, otherNumber)
-- numericals are always smaller than alphanums
elseif selfNumber then
return -1
elseif otherNumber then
return 1
else
return compare(myId, otherId) -- alphanumerical comparison
end
end
local function smallerIdList(myIds, otherIds)
local myLength = #myIds
local comparison
for i=1, myLength do
comparison = compareIds(myIds[i], otherIds[i])
if comparison ~= 0 then
return comparison == -1
end
-- if comparison == 0, continue loop
end
return myLength < #otherIds
end
local function smallerPrerelease(mine, other)
if mine == other or not mine then return false
elseif not other then return true
end
return smallerIdList(splitByDot(mine), splitByDot(other))
end
local methods = {}
function methods:nextMajor()
return semver(self.major + 1, 0, 0)
end
function methods:nextMinor()
return semver(self.major, self.minor + 1, 0)
end
function methods:nextPatch()
return semver(self.major, self.minor, self.patch + 1)
end
local mt = { __index = methods }
function mt:__eq(other)
return self.major == other.major and
self.minor == other.minor and
self.patch == other.patch and
self.prerelease == other.prerelease
-- notice that build is ignored for precedence in semver 2.0.0
end
function mt:__lt(other)
if self.major ~= other.major then return self.major < other.major end
if self.minor ~= other.minor then return self.minor < other.minor end
if self.patch ~= other.patch then return self.patch < other.patch end
return smallerPrerelease(self.prerelease, other.prerelease)
-- notice that build is ignored for precedence in semver 2.0.0
end
-- This works like the "pessimisstic operator" in Rubygems.
-- if a and b are versions, a ^ b means "b is backwards-compatible with a"
-- in other words, "it's safe to upgrade from a to b"
function mt:__pow(other)
return self.major == other.major and
self.minor <= other.minor
end
function mt:__tostring()
local buffer = { ("%d.%d.%d"):format(self.major, self.minor, self.patch) }
if self.prerelease then table.insert(buffer, "-" .. self.prerelease) end
if self.build then table.insert(buffer, "+" .. self.build) end
return table.concat(buffer)
end
local function new(major, minor, patch, prerelease, build)
assert(major, "At least one parameter is needed")
if type(major) == 'string' then
major,minor,patch,prerelease,build = parseVersion(major)
end
patch = patch or 0
minor = minor or 0
checkPositiveInteger(major, "major")
checkPositiveInteger(minor, "minor")
checkPositiveInteger(patch, "patch")
local result = {major=major, minor=minor, patch=patch, prerelease=prerelease, build=build}
return setmetatable(result, mt)
end
setmetatable(semver, { __call = function(_, ...) return new(...) end })
semver._VERSION= semver(semver._VERSION)
return semver
|
Fixed semver compare
|
Fixed semver compare
|
Lua
|
mit
|
Zefiros-Software/ZPM
|
a5298d0221256a7a02e3575e07a95ada8d13bd10
|
src/vendor/tmx.lua
|
src/vendor/tmx.lua
|
local camera = require 'camera'
local tmx = {}
local Map = {}
Map.__index = Map
function Map:draw(x, y)
for _,layer in ipairs(self.layers) do
love.graphics.draw(layer.batch, -( x - ( camera.x * ( 1 - layer.parallax ) ) ), y)
end
end
function tmx.tileRotation(tile)
return {
r = tile.flipDiagonal and math.pi * 1.5 or 0,
sy = (tile.flipVertical and -1 or 1) * (tile.flipDiagonal and -1 or 1),
sx = tile.flipHorizontal and -1 or 1,
}
end
function tmx.getParallaxLayer( map, parallax )
for _, layer in ipairs( map.layers ) do
if layer.parallax == parallax then
return layer
end
end
local layer = { tileCount = 0, parallax = parallax }
table.insert( map.layers, layer )
return layer
end
function tmx.load(level)
local map = {}
setmetatable(map, Map)
local imagePath = "maps/" .. level.tilesets[1].image.source
map.tileset = love.graphics.newImage(imagePath)
map.offset = (tonumber(level.properties.offset) or 0) * level.tileheight
map.layers = {}
for _, tilelayer in ipairs(level.tilelayers) do
if tilelayer.tiles then
local parallax = tonumber(tilelayer.properties.parallax) or 1
layer = tmx.getParallaxLayer( map, parallax )
for _, tile in ipairs(tilelayer.tiles) do
if tile then
layer.tileCount = layer.tileCount + 1
end
end
end
end
for _, layer in ipairs(map.layers) do
layer.batch = love.graphics.newSpriteBatch(map.tileset, layer.tileCount)
end
local atlaswidth = map.tileset:getWidth()
local atlasheight = map.tileset:getHeight()
local tiles = {}
local tilewidth = level.tilewidth
local tileheight = level.tileheight
local tileRow = atlaswidth / tilewidth
local tileHeight = atlasheight / tileheight
for y=0,(tileHeight - 1) do
for x=0,(tileRow - 1) do
local index = y * tileRow + x
local offsetY = y * tileheight
local offsetX = x * tilewidth
tiles[index] = love.graphics.newQuad(offsetX, offsetY,
tilewidth, tileheight,
atlaswidth, atlasheight)
end
end
for _, tilelayer in ipairs(level.tilelayers) do
if tilelayer.tiles then
for i, tile in ipairs(tilelayer.tiles) do
local x = (i - 1) % level.width
local y = math.floor((i - 1)/ level.width)
if tile then
local info = tmx.tileRotation(tile)
local sx = tile.flipHorizontal and -1 or 1
local sy = tile.flipVertical and -1 or 1
if tile.flipDiagonal then
sx, sy = -sy, sx
end
local parallax = tonumber(tilelayer.properties.parallax) or 1
layer = tmx.getParallaxLayer( map, parallax )
layer.batch:addq(tiles[tile.id],
x * tilewidth + (tilewidth / 2),
y * tileheight + (tileheight / 2),
tile.flipDiagonal and math.pi * 1.5 or 0, --rotation
sx, sy, tilewidth / 2, tileheight / 2)
end
end
end
end
return map
end
return tmx
|
local camera = require 'camera'
local tmx = {}
local Map = {}
Map.__index = Map
function Map:draw(x, y)
for _,layer in ipairs(self.layers) do
local _x = math.floor( x - ( camera.x * ( 1 - layer.parallax ) ) )
love.graphics.draw(layer.batch, -_x, y)
end
end
function tmx.tileRotation(tile)
return {
r = tile.flipDiagonal and math.pi * 1.5 or 0,
sy = (tile.flipVertical and -1 or 1) * (tile.flipDiagonal and -1 or 1),
sx = tile.flipHorizontal and -1 or 1,
}
end
function tmx.getParallaxLayer( map, parallax )
for _, layer in ipairs( map.layers ) do
if layer.parallax == parallax then
return layer
end
end
local layer = { tileCount = 0, parallax = parallax }
table.insert( map.layers, layer )
return layer
end
function tmx.load(level)
local map = {}
setmetatable(map, Map)
local imagePath = "maps/" .. level.tilesets[1].image.source
map.tileset = love.graphics.newImage(imagePath)
map.offset = (tonumber(level.properties.offset) or 0) * level.tileheight
map.layers = {}
for _, tilelayer in ipairs(level.tilelayers) do
if tilelayer.tiles then
local parallax = tonumber(tilelayer.properties.parallax) or 1
layer = tmx.getParallaxLayer( map, parallax )
for _, tile in ipairs(tilelayer.tiles) do
if tile then
layer.tileCount = layer.tileCount + 1
end
end
end
end
for _, layer in ipairs(map.layers) do
layer.batch = love.graphics.newSpriteBatch(map.tileset, layer.tileCount)
end
local atlaswidth = map.tileset:getWidth()
local atlasheight = map.tileset:getHeight()
local tiles = {}
local tilewidth = level.tilewidth
local tileheight = level.tileheight
local tileRow = atlaswidth / tilewidth
local tileHeight = atlasheight / tileheight
for y=0,(tileHeight - 1) do
for x=0,(tileRow - 1) do
local index = y * tileRow + x
local offsetY = y * tileheight
local offsetX = x * tilewidth
tiles[index] = love.graphics.newQuad(offsetX, offsetY,
tilewidth, tileheight,
atlaswidth, atlasheight)
end
end
for _, tilelayer in ipairs(level.tilelayers) do
if tilelayer.tiles then
for i, tile in ipairs(tilelayer.tiles) do
local x = (i - 1) % level.width
local y = math.floor((i - 1)/ level.width)
if tile then
local info = tmx.tileRotation(tile)
local sx = tile.flipHorizontal and -1 or 1
local sy = tile.flipVertical and -1 or 1
if tile.flipDiagonal then
sx, sy = -sy, sx
end
local parallax = tonumber(tilelayer.properties.parallax) or 1
layer = tmx.getParallaxLayer( map, parallax )
layer.batch:addq(tiles[tile.id],
x * tilewidth + (tilewidth / 2),
y * tileheight + (tileheight / 2),
tile.flipDiagonal and math.pi * 1.5 or 0, --rotation
sx, sy, tilewidth / 2, tileheight / 2)
end
end
end
end
return map
end
return tmx
|
Fix parallax rounding issue
|
Fix parallax rounding issue
|
Lua
|
mit
|
hawkthorne/hawkthorne-client-lua,hawkthorne/hawkthorne-client-lua,hawkthorne/hawkthorne-server-lua,hawkthorne/hawkthorne-server-lua
|
8f3775d4130fc951e1053b5b45d3cab366c24bf0
|
site/api/mbox.lua
|
site/api/mbox.lua
|
--[[
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
-- This is mbox.lua - a script for generating mbox archives
local elastic = require 'lib/elastic'
local cross = require 'lib/cross'
local days = {
31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 30, 31
}
function leapYear(year)
if (year % 4 == 0) then
if (year%100 == 0)then
if (year %400 == 0) then
return true
end
else
return true
end
return false
end
end
function handle(r)
r.content_type = "application/mbox"
local get = r:parseargs()
if get.list and get.date then
local lid = ("<%s>"):format(get.list:gsub("@", "."):gsub("[<>]", ""))
local flid = get.list:gsub("[.@]", "_")
local month = get.date:match("(%d+%-%d+)")
if not month then
r:puts("Wrong date format given!\n")
return cross.OK
end
if r.headers_out then
r.headers_out['Content-Disposition'] = "attachment; filename=" .. flid .. "_" .. month .. ".mbox"
end
local y, m = month:match("(%d+)%-(%d+)")
m = tonumber(m)
y = tonumber(y)
local d
if m == 2 and leapYear(y) then
d = 29
else
d = days[m]
end
-- fetch all results from the list (up to 10k results), make sure to get the 'private' element
local docs = elastic.raw {
_source = {'mid','private'},
query = {
bool = {
must = {
{
range = {
date = {
gte = ("%04d/%02d/%02d 00:00:00"):format(y,m,1),
lte = ("%04d/%02d/%02d 23:59:59"):format(y,m,d)
}
}
},
{
term = {
list_raw = lid
}
}
}}
},
sort = {
{
epoch = {
order = "asc"
}
}
},
size = 10000
}
-- for each email, get the actual source of it to plop into the mbox file
for k, v in pairs(docs.hits.hits) do
v = v._source
if not v.private then
local doc = elastic.get('mbox_source', v.mid)
if doc and doc.source then
r:puts("From \n")
r:puts(doc.source)
r:puts("\n")
end
end
end
end
return cross.OK
end
cross.start(handle)
|
--[[
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
-- This is mbox.lua - a script for generating mbox archives
local elastic = require 'lib/elastic'
local cross = require 'lib/cross'
local days = {
31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 30, 31
}
function leapYear(year)
if (year % 4 == 0) then
if (year%100 == 0)then
if (year %400 == 0) then
return true
end
else
return true
end
return false
end
end
function handle(r)
r.content_type = "application/mbox"
local get = r:parseargs()
if get.list and get.date then
local lid = ("<%s>"):format(get.list:gsub("@", "."):gsub("[<>]", ""))
local flid = get.list:gsub("[.@]", "_")
local month = get.date:match("(%d+%-%d+)")
if not month then
r.content_type = "text/plain"
r:puts("Wrong date format given!\n")
return cross.OK
end
if r.headers_out then
r.headers_out['Content-Disposition'] = "attachment; filename=" .. flid .. "_" .. month .. ".mbox"
end
local y, m = month:match("(%d+)%-(%d+)")
m = tonumber(m)
y = tonumber(y)
local d
if m == 2 and leapYear(y) then
d = 29
else
d = days[m]
end
-- fetch all results from the list (up to 10k results), make sure to get the 'private' element
local docs = elastic.raw {
_source = {'mid','private'},
query = {
bool = {
must = {
{
range = {
date = {
gte = ("%04d/%02d/%02d 00:00:00"):format(y,m,1),
lte = ("%04d/%02d/%02d 23:59:59"):format(y,m,d)
}
}
},
{
term = {
list_raw = lid
}
}
}}
},
sort = {
{
epoch = {
order = "asc"
}
}
},
size = 10000
}
-- for each email, get the actual source of it to plop into the mbox file
for k, v in pairs(docs.hits.hits) do
v = v._source
if not v.private then
local doc = elastic.get('mbox_source', v.mid)
if doc and doc.source then
r:puts("From \n")
r:puts(doc.source)
r:puts("\n")
end
end
end
else
r.content_type = "text/plain"
r:puts("Both list and date are required!\n")
end
return cross.OK
end
cross.start(handle)
|
fix error handling - responses are not JSON!
|
fix error handling - responses are not JSON!
|
Lua
|
apache-2.0
|
Humbedooh/ponymail,quenda/ponymail,jimjag/ponymail,Humbedooh/ponymail,Humbedooh/ponymail,jimjag/ponymail,quenda/ponymail,quenda/ponymail,jimjag/ponymail,jimjag/ponymail
|
443f930141eb00a0b3dff74754033ab8ab20e796
|
buddycloud-stack/config/prosody.cfg.lua
|
buddycloud-stack/config/prosody.cfg.lua
|
modules_enabled = {
"saslauth"; -- Authentication for clients and servers. Recommended if you want to log in.
"tls"; -- Add support for secure TLS on c2s/s2s connections
"dialback"; -- s2s dialback support
"disco"; -- Service discovery
"time"; -- Let others know the time here on this server
"ping"; -- Replies to XMPP pings with pongs
"posix"; -- Do posixy things
"register"; -- Allow users to register on this server using a client and change passwords
"watchregistrations"; -- Alert admins of registrations (check "admins" option below too)
"compression"; -- Enable mod_compression
};
storage = "internal"
admins = { "[email protected]" } -- who receives registration alerts
pidfile = "/var/run/prosody/prosody.pid"
log = {{ levels = { min = "error" }, to = "file", filename = "/var/log/prosody/prosody.err" };
{ levels = { min = "info" }, to = "file", filename = "/var/log/prosody/prosody.log" };}
registration_whitelist = { "127.0.0.1" }
whitelist_registration_only = true
VirtualHost "EXAMPLE.COM"
authentication = "internal_hashed"
allow_registration = true
anonymous_login = false
ssl = { key = "/etc/apache2/certs/EXAMPLE.COM.key";
certificate = "/etc/apache2/certs/EXAMPLE.COM.pem" }
-- for non-logged in browsing of open channels.
VirtualHost "anon.EXAMPLE.COM"
authentication = "anonymous"
allow_registration = false
anonymous_login = true
-- Buddycloud Channel Server XMPP component configuration.
Component "buddycloud.EXAMPLE.COM"
component_secret = "tellnoone"
-- Buddycloud Channel Server (optional topic channels).
Component "topics.EXAMPLE.COM"
component_secret = "tellnoone"
-- Buddycloud Media Server XMPP component configuration.
Component "media.EXAMPLE.COM"
component_secret = "tellnoone"
-- Buddycloud Pusher Server XMPP component configuration.
Component "pusher.EXAMPLE.COM"
component_secret = "tellnoone"
|
modules_enabled = {
"saslauth"; -- Authentication for clients and servers. Recommended if you want to log in.
"tls"; -- Add support for secure TLS on c2s/s2s connections
"dialback"; -- s2s dialback support
"disco"; -- Service discovery
"time"; -- Let others know the time here on this server
"ping"; -- Replies to XMPP pings with pongs
"posix"; -- Do posixy things
"register"; -- Allow users to register on this server using a client and change passwords
"watchregistrations"; -- Alert admins of registrations (check "admins" option below too)
"compression"; -- Enable mod_compression
};
storage = "internal"
admins = { "[email protected]" } -- who receives registration alerts
pidfile = "/var/run/prosody/prosody.pid"
log = {{ levels = { min = "error" }, to = "file", filename = "/var/log/prosody/prosody.err" };
{ levels = { min = "info" }, to = "file", filename = "/var/log/prosody/prosody.log" };}
registration_whitelist = { "127.0.0.1" }
whitelist_registration_only = true
VirtualHost "buddycloud.dev"
authentication = "internal_hashed"
allow_registration = true
anonymous_login = false
ssl = { certificate = "/etc/apache2/certs/buddycloud.dev.cert.pem";
key = "/etc/apache2/certs/buddycloud.dev.key.pem" }
-- for non-logged in browsing of open channels.
VirtualHost "anon.buddycloud.dev"
authentication = "anonymous"
allow_registration = false
anonymous_login = true
-- Buddycloud Channel Server XMPP component configuration.
Component "buddycloud.buddycloud.dev"
component_secret = "tellnoone"
-- Buddycloud Channel Server (optional topic channels).
Component "topics.buddycloud.dev"
component_secret = "tellnoone"
-- Buddycloud Media Server XMPP component configuration.
Component "media.buddycloud.dev"
component_secret = "tellnoone"
-- Buddycloud Pusher Server XMPP component configuration.
Component "pusher.buddycloud.dev"
component_secret = "tellnoone"
|
fixing prosody
|
fixing prosody
|
Lua
|
apache-2.0
|
webhost/dockerfiles,buddycloud/dockerfiles,buddycloud/dockerfiles,webhost/dockerfiles
|
91d838ca49f2d76e29d65a8cb7b7a3bd9b50c4b4
|
share/lua/playlist/extreme.lua
|
share/lua/playlist/extreme.lua
|
--[[
$Id$
Copyright © 2011 the VideoLAN team
Authors: Konstantin Pavlov ([email protected])
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 get_prefres()
local prefres = -1
if vlc.var and vlc.var.inherit then
prefres = vlc.var.inherit(nil, "preferred-resolution")
if prefres == nil then
prefres = -1
end
end
return prefres
end
-- Probe function.
function probe()
return vlc.access == "http"
and string.match( vlc.path, "extreme.com/." )
or string.match( vlc.path, "freecaster.tv/." )
or string.match( vlc.path, "player.extreme.com/info/.")
end
-- Parse function.
function parse()
if (string.match( vlc.path, "extreme\.com/." ) or string.match( vlc.path, "freecaster\.tv/." )) and not string.match( vlc.path, "player.extreme.com/info/") then
while true do
line = vlc.readline()
if not line then break end
-- Try to find id of the video
if string.match( line, "http://player.extreme.com/FCPlayer.swf" ) then
_,_,vid = string.find( line, "id=(.*)\"" )
break
end
end
return { { path = "http://player.extreme.com/info/" .. vid; name = "extreme.com video"; } }
end
if string.match( vlc.path, "player.extreme.com/info/." ) then
prefres = get_prefres()
gostraight = true
while true do
line = vlc.readline()
if not line then break end
-- Try to find the video's title
if string.match( line, "title>(.*)<" ) then
_,_,name = string.find( line, "<title>(.*)<" )
end
-- Try to find image for thumbnail
if string.match( line, "<path>(*.)</path>" ) then
_,_,arturl = string.find( line, "<path>(*.)</path>" )
end
-- Try to find out if its a freecaster streaming or just a link to some
-- other video streaming website
-- FIXME: I was unable to find any http-based freecaster streams,
-- but I remember there were some a few months back.
-- Right now we assume everything is streamed using RTMP, so we feed them to avio.
if string.match( line, "<streams type=\"5\" server=\"(.*)\">" )
then
_,_,rtmpserver = string.find( line, "<streams type=\"5\" server=\"(.*)\">" )
gostraight = false
end
-- if we're going outside, we need to find out the path
if gostraight then
if string.match( line, ">(.*)</stream>" ) then
_,_,path = string.find( line, "bitrate=\"0\" duration=\"\">(.*)</stream>" )
end
end
-- and if we're using freecaster, use appropriate resolution
if not gostraight then
if string.match( line, "height=\"(.*)\" duration" ) then
_,_,height = string.find( line, "height=\"(%d+)\" duration" )
_,_,playpath = string.find( line, "\">(.*)</stream>" )
if ( prefres < 0 or tonumber( height ) <= prefres ) then
path = "avio://" .. rtmpserver .. " playpath=" .. playpath
end
end
end
end
return { { path = path; name = name; arturl = arturl } }
end
end
|
--[[
$Id$
Copyright © 2011 the VideoLAN team
Authors: Konstantin Pavlov ([email protected])
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 get_prefres()
local prefres = -1
if vlc.var and vlc.var.inherit then
prefres = vlc.var.inherit(nil, "preferred-resolution")
if prefres == nil then
prefres = -1
end
end
return prefres
end
-- Probe function.
function probe()
return vlc.access == "http"
and string.match( vlc.path, "extreme.com/." )
or string.match( vlc.path, "freecaster.tv/." )
or string.match( vlc.path, "player.extreme.com/info/.")
end
-- Parse function.
function parse()
if (string.match( vlc.path, "extreme\.com/." ) or string.match( vlc.path, "freecaster\.tv/." )) and not string.match( vlc.path, "player.extreme.com/info/") then
while true do
line = vlc.readline()
if not line then break end
-- Try to find id of the video
if string.match( line, "http://player.extreme.com/FCPlayer.swf" ) then
_,_,vid = string.find( line, "id=(.*)\"" )
break
end
end
return { { path = "http://player.extreme.com/info/" .. vid; name = "extreme.com video"; } }
end
if string.match( vlc.path, "player.extreme.com/info/." ) then
prefres = get_prefres()
gostraight = true
while true do
line = vlc.readline()
if not line then break end
-- Try to find the video's title
if string.match( line, "title>(.*)<" ) then
_,_,name = string.find( line, "<title>(.*)<" )
end
-- Try to find image for thumbnail
if string.match( line, "<path>(*.)</path>" ) then
_,_,arturl = string.find( line, "<path>(*.)</path>" )
end
-- Try to find out if its a freecaster streaming or just a link to some
-- other video streaming website
-- We assume freecaster now streams in http
if string.match( line, "<streams type=\"5\" server=\"(.*)\">" )
then
_,_,videoserver = string.find( line, "<streams type=\"5\" server=\"(.*)\">" )
gostraight = false
end
-- if we're going outside, we need to find out the path
if gostraight then
if string.match( line, ">(.*)</stream>" ) then
_,_,path = string.find( line, "bitrate=\"0\" duration=\"\">(.*)</stream>" )
end
end
-- and if we're using freecaster, use appropriate resolution
if not gostraight then
if string.match( line, "height=\"(.*)\" duration" ) then
_,_,height = string.find( line, "height=\"(%d+)\" duration" )
_,_,playpath = string.find( line, "\">(.*)</stream>" )
if ( prefres < 0 or tonumber( height ) <= prefres ) then
path = videoserver .. playpath
end
end
end
end
return { { path = path; name = name; arturl = arturl } }
end
end
|
Lua: Fix extreme.com playlist parser. They use http now.
|
Lua: Fix extreme.com playlist parser. They use http now.
|
Lua
|
lgpl-2.1
|
vlc-mirror/vlc-2.1,vlc-mirror/vlc,jomanmuk/vlc-2.2,xkfz007/vlc,krichter722/vlc,jomanmuk/vlc-2.1,shyamalschandra/vlc,vlc-mirror/vlc,shyamalschandra/vlc,vlc-mirror/vlc-2.1,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.1,vlc-mirror/vlc,krichter722/vlc,xkfz007/vlc,vlc-mirror/vlc,xkfz007/vlc,jomanmuk/vlc-2.1,vlc-mirror/vlc-2.1,xkfz007/vlc,krichter722/vlc,xkfz007/vlc,jomanmuk/vlc-2.2,vlc-mirror/vlc,xkfz007/vlc,vlc-mirror/vlc,krichter722/vlc,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.2,shyamalschandra/vlc,jomanmuk/vlc-2.2,krichter722/vlc,jomanmuk/vlc-2.1,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.2,jomanmuk/vlc-2.1,krichter722/vlc,shyamalschandra/vlc,jomanmuk/vlc-2.2,shyamalschandra/vlc,shyamalschandra/vlc,krichter722/vlc,xkfz007/vlc,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.1,jomanmuk/vlc-2.1,shyamalschandra/vlc,jomanmuk/vlc-2.2,vlc-mirror/vlc
|
671e2c8345ccb25bde4d5fd47b16e40e135a3a03
|
twitpic.lua
|
twitpic.lua
|
local url_count = 0
local tries = 0
local item_type = os.getenv('item_type')
local item_value = os.getenv('item_value')
read_file = function(file)
if file then
local f = assert(io.open(file))
local data = f:read("*all")
f:close()
return data
else
return ""
end
end
wget.callbacks.get_urls = function(file, url, is_css, iri)
local urls = {}
local html = nil
if string.match(url, "twitpic%.com/[0-9a-z]+") then
end
wget.callbacks.download_child_p = function(urlpos, parent, depth, start_url_parsed, iri, verdict, reason)
local url = urlpos["url"]["url"]
local ishtml = urlpos["link_expect_html"]
local parenturl = parent["url"]
-- Chfoo - Can I use "local html = nil" in "wget.callbacks.download_child_p"?
local html = nil
-- Skip redirect from mysite.verizon.net and members.bellatlantic.net
if item_type == "image" then
if string.match(url, "cloudfront%.net") then
return true
elseif string.match(url, "twimg%.com") then
return true
elseif string.match(url, "amazonaws%.com") then
return true
elseif string.match(url, "advertise%.twitpic%.com") then
return false
elseif not string.match(url, "twitpic%.com") then
if ishtml == 1 then
if string.match(parenturl, "twitpic%.com") then
return true
else
return false
end
else
return true
end
elseif string.match(url, item_value) then
return true
else
return false
end
elseif item_type == "user" then
if string.match(url, "cloudfront%.net") then
return true
elseif string.match(url, "twimg%.com") then
return true
elseif string.match(url, "amazonaws%.com") then
return true
elseif string.match(url, "advertise%.twitpic%.com") then
return false
elseif not string.match(url, "twitpic%.com") then
if ishtml == 1 then
if string.match(parenturl, "twitpic%.com") then
return true
else
return false
end
else
return true
end
elseif string.match(url, item_value) then
return true
else
return false
end
elseif item_type == "tag" then
if string.match(url, "cloudfront%.net") then
return true
elseif string.match(url, "twimg%.com") then
return true
elseif string.match(url, "amazonaws%.com") then
return true
elseif string.match(url, "advertise%.twitpic%.com") then
return false
-- Check if we are on the last page of a tag
elseif string.match(url, "twitpic%.com/tag/[^%?]+%?page=[0-9]+") then
if not html then
html = read_file(file)
end
if not string.match(url, '<div class="user%-photo%-content right">') then
return false
else
return true
end
elseif not string.match(url, "twitpic%.com") then
if ishtml == 1 then
if string.match(parenturl, "twitpic%.com") then
return true
else
return false
end
else
return true
end
elseif string.match(url, item_value) then
return true
else
return false
end
else
return verdict
end
end
wget.callbacks.httploop_result = function(url, err, http_stat)
-- NEW for 2014: Slightly more verbose messages because people keep
-- complaining that it's not moving or not working
local status_code = http_stat["statcode"]
url_count = url_count + 1
io.stdout:write(url_count .. "=" .. status_code .. " " .. url["url"] .. ". \r")
io.stdout:flush()
if status_code >= 500 or
(status_code >= 400) then
if string.match(url["host"], "twitpic%.com") or
string.match(url["host"], "cloudfront%.net") or
string.match(url["host"], "twimg%.com") or
string.match(url["host"], "amazonaws%.com") then
io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n")
io.stdout:flush()
os.execute("sleep 10")
tries = tries + 1
if tries >= 5 then
io.stdout:write("\nI give up...\n")
io.stdout:flush()
return wget.actions.ABORT
else
return wget.actions.CONTINUE
end
else
io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n")
io.stdout:flush()
os.execute("sleep 10")
tries = tries + 1
if tries >= 5 then
io.stdout:write("\nI give up...\n")
io.stdout:flush()
return wget.actions.NOTHING
else
return wget.actions.CONTINUE
end
end
elseif status_code == 0 then
return wget.actions.ABORT
end
tries = 0
-- We're okay; sleep a bit (if we have to) and continue
local sleep_time = 0.1 * (math.random(1000, 2000) / 100.0)
-- local sleep_time = 0
-- if string.match(url["host"], "cdn") or string.match(url["host"], "media") then
-- -- We should be able to go fast on images since that's what a web browser does
-- sleep_time = 0
-- end
if sleep_time > 0.001 then
os.execute("sleep " .. sleep_time)
end
return wget.actions.NOTHING
end
|
local url_count = 0
local tries = 0
local item_type = os.getenv('item_type')
local item_value = os.getenv('item_value')
read_file = function(file)
if file then
local f = assert(io.open(file))
local data = f:read("*all")
f:close()
return data
else
return ""
end
end
wget.callbacks.download_child_p = function(urlpos, parent, depth, start_url_parsed, iri, verdict, reason)
local url = urlpos["url"]["url"]
local ishtml = urlpos["link_expect_html"]
local parenturl = parent["url"]
-- Chfoo - Can I use "local html = nil" in "wget.callbacks.download_child_p"?
local html = nil
-- Skip redirect from mysite.verizon.net and members.bellatlantic.net
if item_type == "image" then
if string.match(url, "cloudfront%.net") then
return true
elseif string.match(url, "twimg%.com") then
return true
elseif string.match(url, "amazonaws%.com") then
return true
elseif string.match(url, "advertise%.twitpic%.com") then
return false
elseif not string.match(url, "twitpic%.com") then
if ishtml == 1 then
if string.match(parenturl, "twitpic%.com") then
return true
else
return false
end
else
return true
end
elseif string.match(url, item_value) then
return true
else
return false
end
elseif item_type == "user" then
if string.match(url, "cloudfront%.net") then
return true
elseif string.match(url, "twimg%.com") then
return true
elseif string.match(url, "amazonaws%.com") then
return true
elseif string.match(url, "advertise%.twitpic%.com") then
return false
elseif not string.match(url, "twitpic%.com") then
if ishtml == 1 then
if string.match(parenturl, "twitpic%.com") then
return true
else
return false
end
else
return true
end
elseif string.match(url, item_value) then
return true
else
return false
end
elseif item_type == "tag" then
if string.match(url, "cloudfront%.net") then
return true
elseif string.match(url, "twimg%.com") then
return true
elseif string.match(url, "amazonaws%.com") then
return true
elseif string.match(url, "advertise%.twitpic%.com") then
return false
-- Check if we are on the last page of a tag
elseif string.match(url, "twitpic%.com/tag/[^%?]+%?page=[0-9]+") then
if not html then
html = read_file(file)
end
if not string.match(url, '<div class="user%-photo%-content right">') then
return false
else
return true
end
elseif not string.match(url, "twitpic%.com") then
if ishtml == 1 then
if string.match(parenturl, "twitpic%.com") then
return true
else
return false
end
else
return true
end
elseif string.match(url, item_value) then
return true
else
return false
end
else
return verdict
end
end
wget.callbacks.httploop_result = function(url, err, http_stat)
-- NEW for 2014: Slightly more verbose messages because people keep
-- complaining that it's not moving or not working
local status_code = http_stat["statcode"]
url_count = url_count + 1
io.stdout:write(url_count .. "=" .. status_code .. " " .. url["url"] .. ". \r")
io.stdout:flush()
if status_code >= 500 or
(status_code >= 400) then
if string.match(url["host"], "twitpic%.com") or
string.match(url["host"], "cloudfront%.net") or
string.match(url["host"], "twimg%.com") or
string.match(url["host"], "amazonaws%.com") then
io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n")
io.stdout:flush()
os.execute("sleep 10")
tries = tries + 1
if tries >= 5 then
io.stdout:write("\nI give up...\n")
io.stdout:flush()
return wget.actions.ABORT
else
return wget.actions.CONTINUE
end
else
io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n")
io.stdout:flush()
os.execute("sleep 10")
tries = tries + 1
if tries >= 5 then
io.stdout:write("\nI give up...\n")
io.stdout:flush()
return wget.actions.NOTHING
else
return wget.actions.CONTINUE
end
end
elseif status_code == 0 then
return wget.actions.ABORT
end
tries = 0
-- We're okay; sleep a bit (if we have to) and continue
local sleep_time = 0.1 * (math.random(1000, 2000) / 100.0)
-- local sleep_time = 0
-- if string.match(url["host"], "cdn") or string.match(url["host"], "media") then
-- -- We should be able to go fast on images since that's what a web browser does
-- sleep_time = 0
-- end
if sleep_time > 0.001 then
os.execute("sleep " .. sleep_time)
end
return wget.actions.NOTHING
end
|
twitpic.lua: fix
|
twitpic.lua: fix
|
Lua
|
unlicense
|
ArchiveTeam/twitpic-grab,ArchiveTeam/twitpic-grab,ArchiveTeam/twitpic-grab
|
5f6bb86a59f8f5527f6d61deeefab50623275f76
|
spec/helper.lua
|
spec/helper.lua
|
local helper = {}
local dir_sep = package.config:sub(1, 1)
-- Return path to root directory when run from `path`.
local function antipath(path)
local _, level = path:gsub("[/\\]", "")
return (".."..dir_sep):rep(level)
end
function helper.luacov_config(prefix)
return {
statsfile = prefix.."luacov.stats.out",
modules = {
luacheck = "src/luacheck/init.lua",
["luacheck.*"] = "src"
},
exclude = {
"bin/luacheck$",
"luacheck/argparse$"
}
}
end
local luacov = package.loaded["luacov.runner"]
-- Returns command that runs `luacheck` executable from `loc_path`.
function helper.luacheck_command(loc_path)
loc_path = loc_path or "."
local prefix = antipath(loc_path)
local cmd = ("cd %s && %s"):format(loc_path, arg[-5] or "lua")
-- Extend package.path to allow loading this helper and luacheck modules.
cmd = cmd..(' -e "package.path=[[%s?.lua;%ssrc%s?.lua;%ssrc%s?%sinit.lua;]]..package.path"'):format(
prefix, prefix, dir_sep, prefix, dir_sep, dir_sep)
if luacov then
-- Launch luacov.
cmd = cmd..(' -e "require[[luacov.runner]](require[[spec.helper]].luacov_config([[%s]]))"'):format(prefix)
end
return ("%s %sbin%sluacheck.lua"):format(cmd, prefix, dir_sep)
end
return helper
|
local helper = {}
local function get_lua()
local index = -1
local res = "lua"
while arg[index] do
res = arg[index]
index = index - 1
end
return res
end
local lua = get_lua()
local dir_sep = package.config:sub(1, 1)
-- Return path to root directory when run from `path`.
local function antipath(path)
local _, level = path:gsub("[/\\]", "")
return (".."..dir_sep):rep(level)
end
function helper.luacov_config(prefix)
return {
statsfile = prefix.."luacov.stats.out",
modules = {
luacheck = "src/luacheck/init.lua",
["luacheck.*"] = "src"
},
exclude = {
"bin/luacheck$",
"luacheck/argparse$"
}
}
end
local luacov = package.loaded["luacov.runner"]
-- Returns command that runs `luacheck` executable from `loc_path`.
function helper.luacheck_command(loc_path)
loc_path = loc_path or "."
local prefix = antipath(loc_path)
local cmd = ("cd %s && %s"):format(loc_path, lua)
-- Extend package.path to allow loading this helper and luacheck modules.
cmd = cmd..(' -e "package.path=[[%s?.lua;%ssrc%s?.lua;%ssrc%s?%sinit.lua;]]..package.path"'):format(
prefix, prefix, dir_sep, prefix, dir_sep, dir_sep)
if luacov then
-- Launch luacov.
cmd = cmd..(' -e "require[[luacov.runner]](require[[spec.helper]].luacov_config([[%s]]))"'):format(prefix)
end
return ("%s %sbin%sluacheck.lua"):format(cmd, prefix, dir_sep)
end
return helper
|
Fix CLI tests failing depending the way busted wrapper works
|
Fix CLI tests failing depending the way busted wrapper works
Depending on luarocks version there may be different number of arguments
in the call of busted in its "binary" wrapper.
Don't expect arg[-5] to always point to the Lua binary, traverse negative
indexes to get the lowest one instead.
|
Lua
|
mit
|
xpol/luacheck,xpol/luacheck,mpeterv/luacheck,mpeterv/luacheck,xpol/luacheck,mpeterv/luacheck
|
845b64050f298150a6e03d3e61973add1e06327f
|
init.lua
|
init.lua
|
require 'textadept'
_M.common = require 'common'
textadept.editing.STRIP_TRAILING_SPACES = true
keys.LANGUAGE_MODULE_PREFIX = "cat"
function get_sel_lines()
if #buffer.get_sel_text(buffer) == 0 then
return buffer:line_from_position(buffer.current_pos),
buffer:line_from_position(buffer.current_pos)
else
startLine = buffer:line_from_position(buffer.selection_start)
endLine = buffer:line_from_position(buffer.selection_end)
if startLine > endLine then
startLine, endLine = endLine, startLine
end
return startLine, endLine
end
end
-- Deletes the currently selected lines
keys.cl = function()
buffer:begin_undo_action()
local startLine, endLine = get_sel_lines()
if buffer.current_pos == buffer.selection_end then
buffer:goto_line(startLine)
end
for i = startLine, endLine do
buffer:home()
buffer:del_line_right()
if buffer:line_from_position(buffer.current_pos) == 0 then
buffer:line_down()
buffer:home()
buffer:delete_back()
else
buffer:delete_back()
buffer:line_down()
end
end
buffer:end_undo_action()
end
-- Places cursors on both sides of the selected text
keys.ce = function()
buffer:begin_undo_action()
local start = buffer.selection_start
local sel_end = buffer.selection_end
buffer:set_selection(sel_end, sel_end)
buffer:add_selection(start, start)
buffer:end_undo_action()
end
-- Cursor movement
keys['cleft'] = {buffer.word_part_left, buffer}
keys['cright'] = {buffer.word_part_right, buffer}
keys['csleft'] = {buffer.word_part_left_extend, buffer}
keys['csright'] = {buffer.word_part_right_extend, buffer}
keys['csup'] = {buffer.line_up_extend, buffer}
keys['csdown'] = {buffer.line_down_extend, buffer}
keys['c\b'] = function() buffer:word_part_left_extend() buffer:delete_back() end
keys['cdel'] = function() buffer:word_part_right_extend() buffer:delete_back() end
-- Buffer list
keys.cm = ui.switch_buffer
-- Bookmarks
local m_bookmarks = textadept.bookmarks
keys.cb = {m_bookmarks.toggle}
keys.cB = {m_bookmarks.goto_mark, true}
keys.caB = {m_bookmarks.goto_mark, false}
-- Editing
local function toggle_comment(char)
local text = buffer:get_sel_text()
if #text > 0 then
first = text:match("/%"..char.."(.-)%"..char.."/")
if first == nil then
buffer:replace_sel("/"..char..text..char.."/")
else
buffer:replace_sel(first)
end
end
end
local m_editing = textadept.editing
keys['('] = {function() if #buffer.get_sel_text(buffer) == 0 then return false else m_editing.enclose("(", ")") end end}
keys['"'] = {function() if #buffer.get_sel_text(buffer) == 0 then return false else m_editing.enclose('"', '"') end end}
keys['['] = {function() if #buffer.get_sel_text(buffer) == 0 then return false else m_editing.enclose("[", "]") end end}
keys['{'] = {function() if #buffer.get_sel_text(buffer) == 0 then return false else m_editing.enclose("{", "}") end end}
keys["'"] = {function() if #buffer.get_sel_text(buffer) == 0 then return false else m_editing.enclose("'", "'") end end}
keys["*"] = {function() if #buffer.get_sel_text(buffer) == 0 then return false else toggle_comment("*") end end}
keys["+"] = {function() if #buffer.get_sel_text(buffer) == 0 then return false else toggle_comment("+") end end}
keys['f9'] = reset
-- Insert unicode arrow characters
keys.ac = {
["right"] = {function() buffer:add_text("→") end},
["up"] = {function() buffer:add_text("↑") end},
["left"] = {function() buffer:add_text("←") end},
["down"] = {function() buffer:add_text("↓") end},
}
function goto_nearest_occurrence(reverse)
local buffer = buffer
local s, e = buffer.selection_start, buffer.selection_end
if s == e then
s, e = buffer:word_start_position(s), buffer:word_end_position(s)
end
local word = buffer:text_range(s, e)
if word == '' then return end
buffer.search_flags = _SCINTILLA.constants.FIND_WHOLEWORD
+ _SCINTILLA.constants.FIND_MATCHCASE
if reverse then
buffer.target_start = s - 1
buffer.target_end = 0
else
buffer.target_start = e + 1
buffer.target_end = buffer.length
end
if buffer:search_in_target(word) == -1 then
if reverse then
buffer.target_start = buffer.length
buffer.target_end = e + 1
else
buffer.target_start = 0
buffer.target_end = s - 1
end
if buffer:search_in_target(word) == -1 then return end
end
buffer:set_sel(buffer.target_start, buffer.target_end)
end
keys.ck = {goto_nearest_occurrence, false}
keys.cK = {goto_nearest_occurrence, true}
function openTerminalHere()
terminalString = "xfce4-terminal"
pathString = "~"
if buffer.filename then
pathString = buffer.filename:match(".+/")
end
io.popen(terminalString.." --working-directory="..pathString.." &")
end
keys.cT = openTerminalHere
_M.common.multiedit = require "common.multiedit"
keys.cj = _M.common.multiedit.select_all_occurences
keys.ch = textadept.editing.highlight_word
keys.cg = textadept.editing.goto_line
keys.cO = function ()
local location
if buffer.filename then
if WIN32 then
location = buffer.filename:match(".+\\")
else
location = buffer.filename:match(".+/")
end
else
location = os.getenv("PWD")
end
_G.io.snapopen(location)
end
keys.cW = nil
function quoteAndComma()
local text = buffer:get_sel_text()
text = text:gsub("([^\n]+)$", "\"%1\"")
text = text:gsub("%s*([^\n]+)(\r?\n)", "\"%1\",%2")
buffer:replace_sel(text)
end
keys.cC = quoteAndComma
function itemize()
local text = buffer:get_sel_text()
text = text:gsub("([^\n]+)$", "<li>%1</li>")
text = text:gsub("%s*([^\n]+)(\r?\n)", "<li>%1</li>%2")
buffer:replace_sel(text)
end
keys.cI = itemize
function blockComment()
local text = buffer:get_sel_text()
local replacement = "/*\n * " .. text:gsub("\n", "\n * ") .. "\n */"
buffer:replace_sel(replacement)
end
keys["c?"] = blockComment
function commaSeparete()
local text = buffer:get_sel_text()
local replacement = text:gsub("([%w.]+)", "%1,")
buffer:replace_sel(replacement)
end
keys["c,"] = commaSeparete
keys['cD'] = {textadept.editing.filter_through, 'ddemangle'}
--ui.set_theme('IFR')
--ui.set_theme('eigengrau-solar')
if not _G.CURSES then
ui.set_theme('eigengrau-lunar')
end
if not _G.CURSES then
keys.cq = nil
end
|
require 'textadept'
_M.common = require 'common'
textadept.editing.STRIP_TRAILING_SPACES = true
keys.LANGUAGE_MODULE_PREFIX = "cat"
function get_sel_lines()
if #buffer.get_sel_text(buffer) == 0 then
return buffer:line_from_position(buffer.current_pos),
buffer:line_from_position(buffer.current_pos)
else
startLine = buffer:line_from_position(buffer.selection_start)
endLine = buffer:line_from_position(buffer.selection_end)
if startLine > endLine then
startLine, endLine = endLine, startLine
end
return startLine, endLine
end
end
-- Deletes the currently selected lines
keys.cl = function()
buffer:begin_undo_action()
local startLine, endLine = get_sel_lines()
if buffer.current_pos == buffer.selection_end then
buffer:goto_line(startLine)
end
for i = startLine, endLine do
buffer:home()
buffer:del_line_right()
if buffer:line_from_position(buffer.current_pos) == 0 then
buffer:line_down()
buffer:home()
buffer:delete_back()
else
buffer:delete_back()
buffer:line_down()
end
end
buffer:end_undo_action()
end
-- Places cursors on both sides of the selected text
keys.ce = function()
buffer:begin_undo_action()
local start = buffer.selection_start
local sel_end = buffer.selection_end
buffer:set_selection(sel_end, sel_end)
buffer:add_selection(start, start)
buffer:end_undo_action()
end
-- Cursor movement
keys['cleft'] = {buffer.word_part_left, buffer}
keys['cright'] = {buffer.word_part_right, buffer}
keys['csleft'] = {buffer.word_part_left_extend, buffer}
keys['csright'] = {buffer.word_part_right_extend, buffer}
keys['csup'] = {buffer.line_up_extend, buffer}
keys['csdown'] = {buffer.line_down_extend, buffer}
keys['c\b'] = function()
buffer:begin_undo_action()
for i = 1, buffer.selections do
buffer:rotate_selection()
buffer:word_part_left_extend()
buffer:delete_back()
end
buffer:end_undo_action()
end
keys['cdel'] = function()
buffer:begin_undo_action()
for i = 1, buffer.selections do
buffer:rotate_selection()
buffer:word_part_right_extend()
buffer:delete_back()
end
buffer:end_undo_action()
end
-- Buffer list
keys.cm = ui.switch_buffer
-- Bookmarks
local m_bookmarks = textadept.bookmarks
keys.cb = {m_bookmarks.toggle}
keys.cB = {m_bookmarks.goto_mark, true}
keys.caB = {m_bookmarks.goto_mark, false}
-- Editing
local function toggle_comment(char)
local text = buffer:get_sel_text()
if #text > 0 then
first = text:match("/%"..char.."(.-)%"..char.."/")
if first == nil then
buffer:replace_sel("/"..char..text..char.."/")
else
buffer:replace_sel(first)
end
end
end
local m_editing = textadept.editing
keys['('] = {function() if #buffer.get_sel_text(buffer) == 0 then return false else m_editing.enclose("(", ")") end end}
keys['"'] = {function() if #buffer.get_sel_text(buffer) == 0 then return false else m_editing.enclose('"', '"') end end}
keys['['] = {function() if #buffer.get_sel_text(buffer) == 0 then return false else m_editing.enclose("[", "]") end end}
keys['{'] = {function() if #buffer.get_sel_text(buffer) == 0 then return false else m_editing.enclose("{", "}") end end}
keys["'"] = {function() if #buffer.get_sel_text(buffer) == 0 then return false else m_editing.enclose("'", "'") end end}
keys["*"] = {function() if #buffer.get_sel_text(buffer) == 0 then return false else toggle_comment("*") end end}
keys["+"] = {function() if #buffer.get_sel_text(buffer) == 0 then return false else toggle_comment("+") end end}
keys['f9'] = reset
-- Insert unicode arrow characters
keys.ac = {
["right"] = {function() buffer:add_text("→") end},
["up"] = {function() buffer:add_text("↑") end},
["left"] = {function() buffer:add_text("←") end},
["down"] = {function() buffer:add_text("↓") end},
}
keys["aright"] = function() ui.goto_view(1, true) end
keys["aleft"] = function() ui.goto_view(-1, true) end
function goto_nearest_occurrence(reverse)
local buffer = buffer
local s, e = buffer.selection_start, buffer.selection_end
if s == e then
s, e = buffer:word_start_position(s), buffer:word_end_position(s)
end
local word = buffer:text_range(s, e)
if word == '' then return end
buffer.search_flags = _SCINTILLA.constants.FIND_WHOLEWORD
+ _SCINTILLA.constants.FIND_MATCHCASE
if reverse then
buffer.target_start = s - 1
buffer.target_end = 0
else
buffer.target_start = e + 1
buffer.target_end = buffer.length
end
if buffer:search_in_target(word) == -1 then
if reverse then
buffer.target_start = buffer.length
buffer.target_end = e + 1
else
buffer.target_start = 0
buffer.target_end = s - 1
end
if buffer:search_in_target(word) == -1 then return end
end
buffer:set_sel(buffer.target_start, buffer.target_end)
end
keys.ck = {goto_nearest_occurrence, false}
keys.cK = {goto_nearest_occurrence, true}
function openTerminalHere()
terminalString = "xfce4-terminal"
pathString = "~"
if buffer.filename then
pathString = buffer.filename:match(".+/")
end
io.popen(terminalString.." --working-directory="..pathString.." &")
end
keys.cT = openTerminalHere
_M.common.multiedit = require "common.multiedit"
keys.cj = _M.common.multiedit.select_all_occurences
keys.ch = textadept.editing.highlight_word
keys.cg = textadept.editing.goto_line
keys.cO = function ()
local location
if buffer.filename then
if WIN32 then
location = buffer.filename:match(".+\\")
else
location = buffer.filename:match(".+/")
end
else
location = os.getenv("PWD")
end
_G.io.snapopen(location)
end
keys.cW = nil
function quoteAndComma()
local text = buffer:get_sel_text()
text = text:gsub("([^\n]+)$", "\"%1\"")
text = text:gsub("%s*([^\n]+)(\r?\n)", "\"%1\",%2")
buffer:replace_sel(text)
end
keys.cC = quoteAndComma
function itemize()
local text = buffer:get_sel_text()
text = text:gsub("([^\n]+)$", "<li>%1</li>")
text = text:gsub("%s*([^\n]+)(\r?\n)", "<li>%1</li>%2")
buffer:replace_sel(text)
end
keys.cI = itemize
function blockComment()
local text = buffer:get_sel_text()
local replacement = "/*\n * " .. text:gsub("\n", "\n * ") .. "\n */"
buffer:replace_sel(replacement)
end
keys["c?"] = blockComment
function commaSeparete()
local text = buffer:get_sel_text()
local replacement = text:gsub("([%w.]+)", "%1,")
buffer:replace_sel(replacement)
end
keys["c,"] = commaSeparete
keys['cD'] = {textadept.editing.filter_through, 'ddemangle'}
--ui.set_theme('IFR')
--ui.set_theme('eigengrau-solar')
if not _G.CURSES then
ui.set_theme('eigengrau-lunar')
end
if not _G.CURSES then
keys.cq = nil
end
|
Fix keybindings
|
Fix keybindings
|
Lua
|
mit
|
Hackerpilot/TextadeptModules
|
450d184413cefe090c7d1332859fbbeca87f807d
|
mod_lastlog/mod_lastlog.lua
|
mod_lastlog/mod_lastlog.lua
|
local datamanager = require "util.datamanager";
local jid = require "util.jid";
local time = os.time;
local log_ip = module:get_option_boolean("lastlog_ip_address", false);
local host = module.host;
module:hook("authentication-success", function(event)
local session = event.session;
if session.username then
datamanager.store(session.username, host, "lastlog", {
event = "login";
timestamp = time(),
ip = log_ip and session.ip or nil,
});
end
end);
module:hook("resource-unbind", function(event)
local session = event.session;
if session.username then
datamanager.store(session.username, host, "lastlog", {
event = "logout";
timestamp = time(),
ip = log_ip and session.ip or nil,
});
end
end);
module:hook("user-registered", function(event)
local session = event.session;
datamanager.store(event.username, host, "lastlog", {
event = "registered";
timestamp = time(),
ip = log_ip and session.ip or nil,
});
end);
if module:get_host_type() == "component" then
module:hook("message/bare", function(event)
local room = jid.split(event.stanza.attr.to);
if room then
datamanager.store(room, module.host, "lastlog", {
event = "message";
timestamp = time(),
});
end
end);
elseif module:get_option_boolean("lastlog_stamp_offline") then
local datetime = require"util.datetime".datetime;
local function offline_stamp(event)
local stanza = event.stanza;
local node, to_host = jid.split(stanza.attr.from);
if to_host == host and event.origin == hosts[host] and stanza.attr.type == "unavailable" then
local data = datamanager.load(node, host, "lastlog");
local timestamp = data and data.timestamp;
if timestamp then
stanza:tag("delay", {
xmlns = "urn:xmpp:delay",
from = host,
stamp = datetime(timestamp),
}):up();
end
end
end
module:hook("pre-presence/bare", offline_stamp);
module:hook("pre-presence/full", offline_stamp);
end
function module.command(arg)
if not arg[1] or arg[1] == "--help" then
require"util.prosodyctl".show_usage([[mod_lastlog <user@host>]], [[Show when user last logged in or out]]);
return 1;
end
local user, host = jid.prepped_split(table.remove(arg, 1));
require"core.storagemanager".initialize_host(host);
local lastlog = datamanager.load(user, host, "lastlog");
if lastlog then
print(("Last %s: %s"):format(lastlog.event or "login",
lastlog.timestamp and os.date("%Y-%m-%d %H:%M:%S", lastlog.timestamp) or "<unknown>"));
if lastlog.ip then
print("IP address: "..lastlog.ip);
end
else
print("No record found");
return 1;
end
return 0;
end
|
local datamanager = require "util.datamanager";
local jid = require "util.jid";
local time = os.time;
local log_ip = module:get_option_boolean("lastlog_ip_address", false);
local host = module.host;
module:hook("authentication-success", function(event)
local session = event.session;
if session.username then
datamanager.store(session.username, host, "lastlog", {
event = "login";
timestamp = time(),
ip = log_ip and session and session.ip or nil,
});
end
end);
module:hook("resource-unbind", function(event)
local session = event.session;
if session.username then
datamanager.store(session.username, host, "lastlog", {
event = "logout";
timestamp = time(),
ip = log_ip and session and session.ip or nil,
});
end
end);
module:hook("user-registered", function(event)
local session = event.session;
datamanager.store(event.username, host, "lastlog", {
event = "registered";
timestamp = time(),
ip = log_ip and session and session.ip or nil,
});
end);
if module:get_host_type() == "component" then
module:hook("message/bare", function(event)
local room = jid.split(event.stanza.attr.to);
if room then
datamanager.store(room, module.host, "lastlog", {
event = "message";
timestamp = time(),
});
end
end);
elseif module:get_option_boolean("lastlog_stamp_offline") then
local datetime = require"util.datetime".datetime;
local function offline_stamp(event)
local stanza = event.stanza;
local node, to_host = jid.split(stanza.attr.from);
if to_host == host and event.origin == hosts[host] and stanza.attr.type == "unavailable" then
local data = datamanager.load(node, host, "lastlog");
local timestamp = data and data.timestamp;
if timestamp then
stanza:tag("delay", {
xmlns = "urn:xmpp:delay",
from = host,
stamp = datetime(timestamp),
}):up();
end
end
end
module:hook("pre-presence/bare", offline_stamp);
module:hook("pre-presence/full", offline_stamp);
end
function module.command(arg)
if not arg[1] or arg[1] == "--help" then
require"util.prosodyctl".show_usage([[mod_lastlog <user@host>]], [[Show when user last logged in or out]]);
return 1;
end
local user, host = jid.prepped_split(table.remove(arg, 1));
require"core.storagemanager".initialize_host(host);
local lastlog = datamanager.load(user, host, "lastlog");
if lastlog then
print(("Last %s: %s"):format(lastlog.event or "login",
lastlog.timestamp and os.date("%Y-%m-%d %H:%M:%S", lastlog.timestamp) or "<unknown>"));
if lastlog.ip then
print("IP address: "..lastlog.ip);
end
else
print("No record found");
return 1;
end
return 0;
end
|
mod_lastlog: Fix traceback if no session included with event (eg from mod_register_web) (thanks biszkopcik)
|
mod_lastlog: Fix traceback if no session included with event (eg from mod_register_web) (thanks biszkopcik)
|
Lua
|
mit
|
prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2
|
62b7f4a09784b44041c928d76a6c8e68095c2cc9
|
modules/admin-core/luasrc/tools/webadmin.lua
|
modules/admin-core/luasrc/tools/webadmin.lua
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <[email protected]>
Copyright 2008 Jo-Philipp Wich <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
module("luci.tools.webadmin", package.seeall)
require("luci.model.uci")
require("luci.sys")
require("luci.ip")
function byte_format(byte)
local suff = {"B", "KB", "MB", "GB", "TB"}
for i=1, 5 do
if byte > 1024 and i < 5 then
byte = byte / 1024
else
return string.format("%.2f %s", byte, suff[i])
end
end
end
function date_format(secs)
local suff = {"min", "h", "d"}
local mins = 0
local hour = 0
local days = 0
if secs > 60 then
mins = math.floor(secs / 60)
secs = secs % 60
end
if mins > 60 then
hour = math.floor(mins / 60)
mins = mins % 60
end
if hour > 24 then
days = math.floor(hour / 24)
hour = hour % 24
end
if days > 0 then
return string.format("%dd %02dh %02dmin %02ds", days, hour, mins, secs)
else
return string.format("%02dh %02dmin %02ds", hour, mins, secs)
end
end
function network_get_addresses(net)
luci.model.uci.load_state("network")
local addr = {}
local ipv4 = luci.model.uci.get("network", net, "ipaddr")
local mav4 = luci.model.uci.get("network", net, "netmask")
local ipv6 = luci.model.uci.get("network", net, "ip6addr")
if ipv4 and mav4 then
ipv4 = luci.ip.IPv4(ipv4, mav4)
if ipv4 then
table.insert(addr, ipv4:string())
end
end
if ipv6 then
table.insert(addr, ipv6)
end
luci.model.uci.foreach("network", "alias",
function (section)
if section.interface == net then
if section.ipaddr and section.netmask then
local ipv4 = luci.ip.IPv4(section.ipaddr, section.netmask)
if ipv4 then
table.insert(addr, ipv4:string())
end
end
if section.ip6addr then
table.insert(addr, section.ip6addr)
end
end
end
)
return addr
end
function cbi_add_networks(field)
luci.model.uci.foreach("network", "interface",
function (section)
if section[".name"] ~= "loopback" then
field:value(section[".name"])
end
end
)
field.titleref = luci.dispatcher.build_url("admin", "network", "network")
end
function cbi_add_knownips(field)
for i, dataset in ipairs(luci.sys.net.arptable()) do
field:value(dataset["IP address"])
end
end
function network_get_zones(net)
if not luci.model.uci.load_state("firewall") then
return nil
end
local zones = {}
luci.model.uci.foreach("firewall", "zone",
function (section)
local znet = section.network or section.name
if luci.util.contains(luci.util.split(znet, " "), net) then
table.insert(zones, section.name)
end
end
)
return zones
end
function firewall_find_zone(name)
local find
luci.model.uci.foreach("firewall", "zone",
function (section)
if section.name == name then
find = section[".name"]
end
end
)
return find
end
function iface_get_network(iface)
luci.model.uci.load_state("network")
local net
luci.model.uci.foreach("network", "interface",
function (section)
local ifname = luci.model.uci.get(
"network", section[".name"], "ifname"
)
if iface == ifname then
net = section[".name"]
end
end
)
return net
end
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <[email protected]>
Copyright 2008 Jo-Philipp Wich <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
module("luci.tools.webadmin", package.seeall)
require("luci.model.uci")
require("luci.sys")
require("luci.ip")
function byte_format(byte)
local suff = {"B", "KB", "MB", "GB", "TB"}
for i=1, 5 do
if byte > 1024 and i < 5 then
byte = byte / 1024
else
return string.format("%.2f %s", byte, suff[i])
end
end
end
function date_format(secs)
local suff = {"min", "h", "d"}
local mins = 0
local hour = 0
local days = 0
secs = math.floor(tonumber(secs))
if secs > 60 then
mins = math.floor(secs / 60)
secs = secs % 60
end
if mins > 60 then
hour = math.floor(mins / 60)
mins = mins % 60
end
if hour > 24 then
days = math.floor(hour / 24)
hour = hour % 24
end
if days > 0 then
return string.format("%dd %02dh %02dmin %02ds", days, hour, mins, secs)
else
return string.format("%02dh %02dmin %02ds", hour, mins, secs)
end
end
function network_get_addresses(net)
luci.model.uci.load_state("network")
local addr = {}
local ipv4 = luci.model.uci.get("network", net, "ipaddr")
local mav4 = luci.model.uci.get("network", net, "netmask")
local ipv6 = luci.model.uci.get("network", net, "ip6addr")
if ipv4 and mav4 then
ipv4 = luci.ip.IPv4(ipv4, mav4)
if ipv4 then
table.insert(addr, ipv4:string())
end
end
if ipv6 then
table.insert(addr, ipv6)
end
luci.model.uci.foreach("network", "alias",
function (section)
if section.interface == net then
if section.ipaddr and section.netmask then
local ipv4 = luci.ip.IPv4(section.ipaddr, section.netmask)
if ipv4 then
table.insert(addr, ipv4:string())
end
end
if section.ip6addr then
table.insert(addr, section.ip6addr)
end
end
end
)
return addr
end
function cbi_add_networks(field)
luci.model.uci.foreach("network", "interface",
function (section)
if section[".name"] ~= "loopback" then
field:value(section[".name"])
end
end
)
field.titleref = luci.dispatcher.build_url("admin", "network", "network")
end
function cbi_add_knownips(field)
for i, dataset in ipairs(luci.sys.net.arptable()) do
field:value(dataset["IP address"])
end
end
function network_get_zones(net)
if not luci.model.uci.load_state("firewall") then
return nil
end
local zones = {}
luci.model.uci.foreach("firewall", "zone",
function (section)
local znet = section.network or section.name
if luci.util.contains(luci.util.split(znet, " "), net) then
table.insert(zones, section.name)
end
end
)
return zones
end
function firewall_find_zone(name)
local find
luci.model.uci.foreach("firewall", "zone",
function (section)
if section.name == name then
find = section[".name"]
end
end
)
return find
end
function iface_get_network(iface)
luci.model.uci.load_state("network")
local net
luci.model.uci.foreach("network", "interface",
function (section)
local ifname = luci.model.uci.get(
"network", section[".name"], "ifname"
)
if iface == ifname then
net = section[".name"]
end
end
)
return net
end
|
Add missing number conversion (fixed #108)
|
Add missing number conversion (fixed #108)
git-svn-id: edf5ee79c2c7d29460bbb5b398f55862cc26620d@2862 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
|
Lua
|
apache-2.0
|
ch3n2k/luci,dtaht/cerowrt-luci-3.3,ReclaimYourPrivacy/cloak-luci,freifunk-gluon/luci,projectbismark/luci-bismark,Flexibity/luci,yeewang/openwrt-luci,ThingMesh/openwrt-luci,zwhfly/openwrt-luci,phi-psi/luci,alxhh/piratenluci,freifunk-gluon/luci,ThingMesh/openwrt-luci,zwhfly/openwrt-luci,jschmidlapp/luci,phi-psi/luci,phi-psi/luci,8devices/carambola2-luci,stephank/luci,gwlim/luci,projectbismark/luci-bismark,Flexibity/luci,yeewang/openwrt-luci,vhpham80/luci,dtaht/cerowrt-luci-3.3,ReclaimYourPrivacy/cloak-luci,projectbismark/luci-bismark,vhpham80/luci,Flexibity/luci,Canaan-Creative/luci,vhpham80/luci,ch3n2k/luci,Canaan-Creative/luci,ReclaimYourPrivacy/cloak-luci,zwhfly/openwrt-luci,Canaan-Creative/luci,ch3n2k/luci,zwhfly/openwrt-luci,gwlim/luci,Flexibity/luci,stephank/luci,ReclaimYourPrivacy/cloak-luci,phi-psi/luci,dtaht/cerowrt-luci-3.3,saraedum/luci-packages-old,ThingMesh/openwrt-luci,ThingMesh/openwrt-luci,dtaht/cerowrt-luci-3.3,zwhfly/openwrt-luci,jschmidlapp/luci,yeewang/openwrt-luci,8devices/carambola2-luci,8devices/carambola2-luci,8devices/carambola2-luci,Canaan-Creative/luci,freifunk-gluon/luci,projectbismark/luci-bismark,freifunk-gluon/luci,projectbismark/luci-bismark,phi-psi/luci,gwlim/luci,saraedum/luci-packages-old,stephank/luci,vhpham80/luci,freifunk-gluon/luci,8devices/carambola2-luci,ReclaimYourPrivacy/cloak-luci,yeewang/openwrt-luci,alxhh/piratenluci,ch3n2k/luci,ch3n2k/luci,saraedum/luci-packages-old,eugenesan/openwrt-luci,vhpham80/luci,zwhfly/openwrt-luci,saraedum/luci-packages-old,ReclaimYourPrivacy/cloak-luci,ch3n2k/luci,Flexibity/luci,eugenesan/openwrt-luci,eugenesan/openwrt-luci,saraedum/luci-packages-old,zwhfly/openwrt-luci,Flexibity/luci,projectbismark/luci-bismark,eugenesan/openwrt-luci,alxhh/piratenluci,8devices/carambola2-luci,dtaht/cerowrt-luci-3.3,vhpham80/luci,Canaan-Creative/luci,jschmidlapp/luci,jschmidlapp/luci,jschmidlapp/luci,ch3n2k/luci,8devices/carambola2-luci,yeewang/openwrt-luci,jschmidlapp/luci,gwlim/luci,yeewang/openwrt-luci,Canaan-Creative/luci,Canaan-Creative/luci,ReclaimYourPrivacy/cloak-luci,phi-psi/luci,stephank/luci,zwhfly/openwrt-luci,zwhfly/openwrt-luci,saraedum/luci-packages-old,alxhh/piratenluci,stephank/luci,alxhh/piratenluci,Flexibity/luci,saraedum/luci-packages-old,alxhh/piratenluci,gwlim/luci,stephank/luci,gwlim/luci,dtaht/cerowrt-luci-3.3,projectbismark/luci-bismark,Canaan-Creative/luci,gwlim/luci,ReclaimYourPrivacy/cloak-luci,eugenesan/openwrt-luci,ThingMesh/openwrt-luci,freifunk-gluon/luci,eugenesan/openwrt-luci,Flexibity/luci,eugenesan/openwrt-luci,jschmidlapp/luci,projectbismark/luci-bismark,freifunk-gluon/luci,jschmidlapp/luci,freifunk-gluon/luci,yeewang/openwrt-luci,alxhh/piratenluci,phi-psi/luci,ThingMesh/openwrt-luci,ThingMesh/openwrt-luci
|
797cc18d58399467cbf6fe2d610a745e5adb2b45
|
MY_Chat/src/MY_WhisperMetion.lua
|
MY_Chat/src/MY_WhisperMetion.lua
|
--------------------------------------------------------
-- This file is part of the JX3 Mingyi Plugin.
-- @link : https://jx3.derzh.com/
-- @desc : ¼Ƶ
-- @author : @˫ @Ӱ
-- @modifier : Emil Zhai ([email protected])
-- @copyright: Copyright (c) 2013 EMZ Kingsoft Co., Ltd.
--------------------------------------------------------
-------------------------------------------------------------------------------------------------------
-- these global functions are accessed all the time by the event handler
-- so caching them is worth the effort
-------------------------------------------------------------------------------------------------------
local ipairs, pairs, next, pcall, select = ipairs, pairs, next, pcall, select
local string, math, table = string, math, table
-- lib apis caching
local X = MY
local UI, GLOBAL, CONSTANT, wstring, lodash = X.UI, X.GLOBAL, X.CONSTANT, X.wstring, X.lodash
-------------------------------------------------------------------------------------------------------
local PLUGIN_NAME = 'MY_Chat'
local PLUGIN_ROOT = X.PACKET_INFO.ROOT .. PLUGIN_NAME
local MODULE_NAME = 'MY_Chat'
local _L = X.LoadLangPack(PLUGIN_ROOT .. '/lang/')
--------------------------------------------------------------------------
if not X.AssertVersion(MODULE_NAME, _L[MODULE_NAME], '^9.0.0') then
return
end
--------------------------------------------------------------------------
local O = X.CreateUserSettingsModule('MY_WhisperMetion', _L['Chat'], {
bEnable = {
ePathType = X.PATH_TYPE.ROLE,
szLabel = _L['MY_Chat'],
xSchema = X.Schema.Boolean,
xDefaultValue = true,
},
})
local D = {}
function D.Apply()
if O.bEnable then
X.RegisterMsgMonitor({
'MSG_NORMAL',
'MSG_PARTY',
'MSG_MAP',
'MSG_BATTLE_FILED',
'MSG_GUILD',
'MSG_GUILD_ALLIANCE',
'MSG_SCHOOL',
'MSG_WORLD',
'MSG_TEAM',
'MSG_CAMP',
'MSG_GROUP',
'MSG_SEEK_MENTOR',
'MSG_FRIEND',
'MSG_IDENTITY',
'MSG_SYS',
'MSG_NPC_NEARBY',
'MSG_NPC_YELL',
'MSG_NPC_PARTY',
'MSG_NPC_WHISPER',
}, 'MY_RedirectMetionToWhisper', function(szChannel, szMsg, nFont, bRich, r, g, b, dwTalkerID, szName)
local me = GetClientPlayer()
if not me or me.dwID == dwTalkerID then
return
end
local szText = "text=" .. EncodeComponentsString("[" .. me.szName .. "]")
local nPos = StringFindW(szMsg, g_tStrings.STR_TALK_HEAD_SAY1)
if nPos and StringFindW(szMsg, szText, nPos) then
OutputMessage('MSG_WHISPER', szMsg, bRich, nFont, {r, g, b}, dwTalkerID, szName)
end
end)
X.HookChatPanel('FILTER', 'MY_RedirectMetionToWhisper', function(h, szMsg, szChannel, dwTime)
if h.__MY_LastMsg == szMsg and h.__MY_LastMsgChannel ~= szChannel and szChannel == 'MSG_WHISPER' then
return false
end
h.__MY_LastMsg = szMsg
h.__MY_LastMsgChannel = szChannel
return true
end)
else
X.HookChatPanel('FILTER', 'MY_RedirectMetionToWhisper', false)
X.RegisterMsgMonitor('MSG_NORMAL', 'MY_RedirectMetionToWhisper', false)
X.RegisterMsgMonitor('MSG_PARTY', 'MY_RedirectMetionToWhisper', false)
X.RegisterMsgMonitor('MSG_MAP', 'MY_RedirectMetionToWhisper', false)
X.RegisterMsgMonitor('MSG_BATTLE_FILED', 'MY_RedirectMetionToWhisper', false)
X.RegisterMsgMonitor('MSG_GUILD', 'MY_RedirectMetionToWhisper', false)
X.RegisterMsgMonitor('MSG_GUILD_ALLIANCE', 'MY_RedirectMetionToWhisper', false)
X.RegisterMsgMonitor('MSG_SCHOOL', 'MY_RedirectMetionToWhisper', false)
X.RegisterMsgMonitor('MSG_WORLD', 'MY_RedirectMetionToWhisper',false)
X.RegisterMsgMonitor('MSG_TEAM', 'MY_RedirectMetionToWhisper', false)
X.RegisterMsgMonitor('MSG_CAMP', 'MY_RedirectMetionToWhisper', false)
X.RegisterMsgMonitor('MSG_GROUP', 'MY_RedirectMetionToWhisper', false)
X.RegisterMsgMonitor('MSG_SEEK_MENTOR', 'MY_RedirectMetionToWhisper', false)
X.RegisterMsgMonitor('MSG_FRIEND', 'MY_RedirectMetionToWhisper', false)
X.RegisterMsgMonitor('MSG_IDENTITY', 'MY_RedirectMetionToWhisper', false)
X.RegisterMsgMonitor('MSG_SYS', 'MY_RedirectMetionToWhisper',false)
X.RegisterMsgMonitor('MSG_NPC_NEARBY', 'MY_RedirectMetionToWhisper', false)
X.RegisterMsgMonitor('MSG_NPC_YELL', 'MY_RedirectMetionToWhisper', false)
X.RegisterMsgMonitor('MSG_NPC_PARTY', 'MY_RedirectMetionToWhisper', false)
X.RegisterMsgMonitor('MSG_NPC_WHISPER', 'MY_RedirectMetionToWhisper',false)
end
end
X.RegisterUserSettingsUpdate('@@INIT@@', 'MY_WhisperMetion', D.Apply)
function D.OnPanelActivePartial(ui, nPaddingX, nPaddingY, nW, nH, nX, nY, lineHeight)
nX = nPaddingX
ui:Append('WndCheckBox', {
x = nX, y = nY, w = 'auto',
text = _L['Redirect metion to whisper'],
checked = O.bEnable,
oncheck = function(bChecked)
O.bEnable = bChecked
D.Apply()
end,
})
nY = nY + lineHeight
return nX, nY
end
-- Global exports
do
local settings = {
name = 'MY_WhisperMetion',
exports = {
{
fields = {
OnPanelActivePartial = D.OnPanelActivePartial,
},
},
},
}
MY_WhisperMetion = X.CreateModule(settings)
end
|
--------------------------------------------------------
-- This file is part of the JX3 Mingyi Plugin.
-- @link : https://jx3.derzh.com/
-- @desc : ¼Ƶ
-- @author : @˫ @Ӱ
-- @modifier : Emil Zhai ([email protected])
-- @copyright: Copyright (c) 2013 EMZ Kingsoft Co., Ltd.
--------------------------------------------------------
-------------------------------------------------------------------------------------------------------
-- these global functions are accessed all the time by the event handler
-- so caching them is worth the effort
-------------------------------------------------------------------------------------------------------
local ipairs, pairs, next, pcall, select = ipairs, pairs, next, pcall, select
local string, math, table = string, math, table
-- lib apis caching
local X = MY
local UI, GLOBAL, CONSTANT, wstring, lodash = X.UI, X.GLOBAL, X.CONSTANT, X.wstring, X.lodash
-------------------------------------------------------------------------------------------------------
local PLUGIN_NAME = 'MY_Chat'
local PLUGIN_ROOT = X.PACKET_INFO.ROOT .. PLUGIN_NAME
local MODULE_NAME = 'MY_Chat'
local _L = X.LoadLangPack(PLUGIN_ROOT .. '/lang/')
--------------------------------------------------------------------------
if not X.AssertVersion(MODULE_NAME, _L[MODULE_NAME], '^9.0.0') then
return
end
--------------------------------------------------------------------------
local O = X.CreateUserSettingsModule('MY_WhisperMetion', _L['Chat'], {
bEnable = {
ePathType = X.PATH_TYPE.ROLE,
szLabel = _L['MY_Chat'],
xSchema = X.Schema.Boolean,
xDefaultValue = true,
},
})
local D = {}
function D.Apply()
if O.bEnable then
X.RegisterMsgMonitor({
'MSG_NORMAL',
'MSG_PARTY',
'MSG_MAP',
'MSG_BATTLE_FILED',
'MSG_GUILD',
'MSG_GUILD_ALLIANCE',
'MSG_SCHOOL',
'MSG_WORLD',
'MSG_TEAM',
'MSG_CAMP',
'MSG_GROUP',
'MSG_SEEK_MENTOR',
'MSG_FRIEND',
'MSG_IDENTITY',
'MSG_SYS',
'MSG_NPC_NEARBY',
'MSG_NPC_YELL',
'MSG_NPC_PARTY',
'MSG_NPC_WHISPER',
}, 'MY_RedirectMetionToWhisper', function(szChannel, szMsg, nFont, bRich, r, g, b, dwTalkerID, szName)
local me = GetClientPlayer()
if not me or me.dwID == dwTalkerID then
return
end
local bEcho = false
local aXMLNode = X.XMLDecode(szMsg)
if not X.IsTable(aXMLNode) then
return
end
for _, node in ipairs(aXMLNode) do
local nodeType = X.XMLGetNodeType(node)
local nodeName = X.XMLGetNodeData(node, 'name') or ''
local nodeText = X.XMLGetNodeData(node, 'text')
if nodeType == 'text' and nodeName:sub(1, 8) == 'namelink' and nodeText:sub(2, -2) == me.szName then
bEcho = true
break
end
end
if bEcho then
OutputMessage('MSG_WHISPER', szMsg, bRich, nFont, {r, g, b}, dwTalkerID, szName)
end
end)
X.HookChatPanel('FILTER', 'MY_RedirectMetionToWhisper', function(h, szMsg, szChannel, dwTime)
if h.__MY_LastMsg == szMsg and h.__MY_LastMsgChannel ~= szChannel and szChannel == 'MSG_WHISPER' then
return false
end
h.__MY_LastMsg = szMsg
h.__MY_LastMsgChannel = szChannel
return true
end)
else
X.HookChatPanel('FILTER', 'MY_RedirectMetionToWhisper', false)
X.RegisterMsgMonitor('MSG_NORMAL', 'MY_RedirectMetionToWhisper', false)
X.RegisterMsgMonitor('MSG_PARTY', 'MY_RedirectMetionToWhisper', false)
X.RegisterMsgMonitor('MSG_MAP', 'MY_RedirectMetionToWhisper', false)
X.RegisterMsgMonitor('MSG_BATTLE_FILED', 'MY_RedirectMetionToWhisper', false)
X.RegisterMsgMonitor('MSG_GUILD', 'MY_RedirectMetionToWhisper', false)
X.RegisterMsgMonitor('MSG_GUILD_ALLIANCE', 'MY_RedirectMetionToWhisper', false)
X.RegisterMsgMonitor('MSG_SCHOOL', 'MY_RedirectMetionToWhisper', false)
X.RegisterMsgMonitor('MSG_WORLD', 'MY_RedirectMetionToWhisper',false)
X.RegisterMsgMonitor('MSG_TEAM', 'MY_RedirectMetionToWhisper', false)
X.RegisterMsgMonitor('MSG_CAMP', 'MY_RedirectMetionToWhisper', false)
X.RegisterMsgMonitor('MSG_GROUP', 'MY_RedirectMetionToWhisper', false)
X.RegisterMsgMonitor('MSG_SEEK_MENTOR', 'MY_RedirectMetionToWhisper', false)
X.RegisterMsgMonitor('MSG_FRIEND', 'MY_RedirectMetionToWhisper', false)
X.RegisterMsgMonitor('MSG_IDENTITY', 'MY_RedirectMetionToWhisper', false)
X.RegisterMsgMonitor('MSG_SYS', 'MY_RedirectMetionToWhisper',false)
X.RegisterMsgMonitor('MSG_NPC_NEARBY', 'MY_RedirectMetionToWhisper', false)
X.RegisterMsgMonitor('MSG_NPC_YELL', 'MY_RedirectMetionToWhisper', false)
X.RegisterMsgMonitor('MSG_NPC_PARTY', 'MY_RedirectMetionToWhisper', false)
X.RegisterMsgMonitor('MSG_NPC_WHISPER', 'MY_RedirectMetionToWhisper',false)
end
end
X.RegisterUserSettingsUpdate('@@INIT@@', 'MY_WhisperMetion', D.Apply)
function D.OnPanelActivePartial(ui, nPaddingX, nPaddingY, nW, nH, nX, nY, lineHeight)
nX = nPaddingX
ui:Append('WndCheckBox', {
x = nX, y = nY, w = 'auto',
text = _L['Redirect metion to whisper'],
checked = O.bEnable,
oncheck = function(bChecked)
O.bEnable = bChecked
D.Apply()
end,
})
nY = nY + lineHeight
return nX, nY
end
-- Global exports
do
local settings = {
name = 'MY_WhisperMetion',
exports = {
{
fields = {
OnPanelActivePartial = D.OnPanelActivePartial,
},
},
},
}
MY_WhisperMetion = X.CreateModule(settings)
end
|
fix: 点名记录到密聊功能严格判定名字链接
|
fix: 点名记录到密聊功能严格判定名字链接
|
Lua
|
bsd-3-clause
|
tinymins/MY
|
ddf3169bdc4ca24a2df2a76ccab0ed93f207d271
|
test-server/test-server-copas.lua
|
test-server/test-server-copas.lua
|
#!/usr/bin/env lua
--- lua websocket equivalent to test-server.c from libwebsockets.
-- using copas as server framework
package.path = '../src/?.lua;../src/?/?.lua;'..package.path
local copas = require'copas'
local socket = require'socket'
local inc_clients = {}
local server = require'websocket'.server.copas.listen
{
protocols = {
['lws-mirror-protocol'] = function(ws)
while true do
local msg = ws:receive()
ws:broadcast(msg)
end
end,
['dumb-increment-protocol'] = function(ws)
local inc_client = {
number = 0,
ws = ws
}
table.insert(inc_clients,inc_client)
while true do
local message = ws:receive()
if message:match('reset') then
inc_client.number = 0
end
end
end
},
port = 12345
}
-- this fairly complex mechanism is required due to the
-- lack of copas timers...
-- sends periodically the 'dumb-increment-protocol' count
-- to the respective client.
copas.addthread(
function()
local last = socket.gettime()
while true do
copas.step(0.1)
local now = socket.gettime()
if (now - last) >= 0.1 then
last = now
for _,inc_client in pairs(inc_clients) do
inc_client.number = inc_client.number + 1
inc_client.ws:send(tostring(inc_client.number))
end
end
end
end)
print('Open browser:')
print('file://'..io.popen('pwd'):read()..'/index.html')
copas.loop()
|
#!/usr/bin/env lua
--- lua websocket equivalent to test-server.c from libwebsockets.
-- using copas as server framework
package.path = '../src/?.lua;../src/?/?.lua;'..package.path
local copas = require'copas'
local socket = require'socket'
print('Open browser:')
print('file://'..io.popen('pwd'):read()..'/index.html')
local inc_clients = {}
local websocket = require'websocket'
local server = websocket.server.copas.listen
{
protocols = {
['lws-mirror-protocol'] = function(ws)
while true do
local msg,opcode = ws:receive()
if not msg then
ws:close()
return
end
if opcode == websocket.TEXT then
ws:broadcast(msg)
end
end
end,
['dumb-increment-protocol'] = function(ws)
inc_clients[ws] = 0
while true do
local message,opcode = ws:receive()
if not message then
ws:close()
inc_clients[ws] = nil
return
end
if opcode == websocket.TEXT then
if message:match('reset') then
inc_clients[ws] = 0
end
end
end
end
},
port = 12345
}
-- this fairly complex mechanism is required due to the
-- lack of copas timers...
-- sends periodically the 'dumb-increment-protocol' count
-- to the respective client.
copas.addthread(
function()
local last = socket.gettime()
while true do
copas.step(0.1)
local now = socket.gettime()
if (now - last) >= 0.1 then
last = now
for ws,number in pairs(inc_clients) do
ws:send(tostring(number))
inc_clients[ws] = number + 1
end
end
end
end)
copas.loop()
|
bugfix handle cases, when client closes connection
|
bugfix handle cases, when client closes connection
|
Lua
|
mit
|
KSDaemon/lua-websockets,enginix/lua-websockets,lipp/lua-websockets,KSDaemon/lua-websockets,lipp/lua-websockets,enginix/lua-websockets,OptimusLime/lua-websockets,enginix/lua-websockets,lipp/lua-websockets,OptimusLime/lua-websockets,KSDaemon/lua-websockets,OptimusLime/lua-websockets
|
3ef8271285381840ec59f15c1c3d40582c8bc522
|
src/dao/cassandra/plugins.lua
|
src/dao/cassandra/plugins.lua
|
local constants = require "kong.constants"
local BaseDao = require "kong.dao.cassandra.base_dao"
local cjson = require "cjson"
local function load_value_schema(plugin_t)
local status, plugin_schema = pcall(require, "kong.plugins."..plugin_t.name..".schema")
if not status then
return nil, "Plugin \""..plugin_t.name.."\" not found"
end
return plugin_schema
end
local SCHEMA = {
id = { type = constants.DATABASE_TYPES.ID },
api_id = { type = constants.DATABASE_TYPES.ID, required = true, foreign = true, queryable = true },
application_id = { type = constants.DATABASE_TYPES.ID, foreign = true, queryable = true, default = constants.DATABASE_NULL_ID },
name = { type = "string", required = true, queryable = true, immutable = true },
value = { type = "table", required = true, schema = load_value_schema },
enabled = { type = "boolean", default = true },
created_at = { type = constants.DATABASE_TYPES.TIMESTAMP }
}
local Plugins = BaseDao:extend()
function Plugins:new(properties)
self._entity = "Plugin"
self._schema = SCHEMA
self._queries = {
insert = {
params = { "id", "api_id", "application_id", "name", "value", "enabled", "created_at" },
query = [[ INSERT INTO plugins(id, api_id, application_id, name, value, enabled, created_at)
VALUES(?, ?, ?, ?, ?, ?, ?); ]]
},
update = {
params = { "api_id", "application_id", "value", "enabled", "created_at", "id", "name" },
query = [[ UPDATE plugins SET api_id = ?, application_id = ?, value = ?, enabled = ?, created_at = ? WHERE id = ? AND name = ?; ]]
},
select = {
query = [[ SELECT * FROM plugins %s; ]]
},
select_one = {
params = { "id" },
query = [[ SELECT * FROM plugins WHERE id = ?; ]]
},
delete = {
params = { "id" },
query = [[ DELETE FROM plugins WHERE id = ?; ]]
},
__unique = {
self = {
params = { "api_id", "application_id", "name" },
query = [[ SELECT * FROM plugins WHERE api_id = ? AND application_id = ? AND name = ? ALLOW FILTERING; ]]
}
},
__foreign = {
api_id = {
params = { "api_id" },
query = [[ SELECT id FROM apis WHERE id = ?; ]]
},
application_id = {
params = { "application_id" },
query = [[ SELECT id FROM applications WHERE id = ?; ]]
}
}
}
Plugins.super.new(self, properties)
end
-- @override
function Plugins:_marshall(t)
if type(t.value) == "table" then
t.value = cjson.encode(t.value)
end
return t
end
-- @override
function Plugins:_unmarshall(t)
-- deserialize values (tables) string to json
if type(t.value) == "string" then
t.value = cjson.decode(t.value)
end
-- remove application_id if null uuid
if t.application_id == constants.DATABASE_NULL_ID then
t.application_id = nil
end
return t
end
function Plugins:find_distinct()
-- Open session
local session, err = Plugins.super._open_session(self)
if err then
return nil, err
end
-- Execute query
local distinct_names = {}
for _, rows, page, err in session:execute(self._statements.select.query, nil, {auto_paging=true}) do
if err then
return nil, err
end
for _, v in ipairs(rows) do
-- Rows also contains other properites, so making sure it's a plugin
if v.name then
distinct_names[v.name] = true
end
end
end
-- Close session
local socket_err = Plugins.super._close_session(self, session)
if socket_err then
return nil, socket_err
end
local result = {}
for k,_ in pairs(distinct_names) do
table.insert(result, k)
end
return result, nil
end
return Plugins
|
local constants = require "kong.constants"
local BaseDao = require "kong.dao.cassandra.base_dao"
local cjson = require "cjson"
local function load_value_schema(plugin_t)
if plugin_t.name then
local status, plugin_schema = pcall(require, "kong.plugins."..plugin_t.name..".schema")
if status then
return plugin_schema
end
end
return nil, "Plugin \""..(plugin_t.name and plugin_t.name or "").."\" not found"
end
local SCHEMA = {
id = { type = constants.DATABASE_TYPES.ID },
api_id = { type = constants.DATABASE_TYPES.ID, required = true, foreign = true, queryable = true },
application_id = { type = constants.DATABASE_TYPES.ID, foreign = true, queryable = true, default = constants.DATABASE_NULL_ID },
name = { type = "string", required = true, queryable = true, immutable = true },
value = { type = "table", required = true, schema = load_value_schema },
enabled = { type = "boolean", default = true },
created_at = { type = constants.DATABASE_TYPES.TIMESTAMP }
}
local Plugins = BaseDao:extend()
function Plugins:new(properties)
self._entity = "Plugin"
self._schema = SCHEMA
self._queries = {
insert = {
params = { "id", "api_id", "application_id", "name", "value", "enabled", "created_at" },
query = [[ INSERT INTO plugins(id, api_id, application_id, name, value, enabled, created_at)
VALUES(?, ?, ?, ?, ?, ?, ?); ]]
},
update = {
params = { "api_id", "application_id", "value", "enabled", "created_at", "id", "name" },
query = [[ UPDATE plugins SET api_id = ?, application_id = ?, value = ?, enabled = ?, created_at = ? WHERE id = ? AND name = ?; ]]
},
select = {
query = [[ SELECT * FROM plugins %s; ]]
},
select_one = {
params = { "id" },
query = [[ SELECT * FROM plugins WHERE id = ?; ]]
},
delete = {
params = { "id" },
query = [[ DELETE FROM plugins WHERE id = ?; ]]
},
__unique = {
self = {
params = { "api_id", "application_id", "name" },
query = [[ SELECT * FROM plugins WHERE api_id = ? AND application_id = ? AND name = ? ALLOW FILTERING; ]]
}
},
__foreign = {
api_id = {
params = { "api_id" },
query = [[ SELECT id FROM apis WHERE id = ?; ]]
},
application_id = {
params = { "application_id" },
query = [[ SELECT id FROM applications WHERE id = ?; ]]
}
}
}
Plugins.super.new(self, properties)
end
-- @override
function Plugins:_marshall(t)
if type(t.value) == "table" then
t.value = cjson.encode(t.value)
end
return t
end
-- @override
function Plugins:_unmarshall(t)
-- deserialize values (tables) string to json
if type(t.value) == "string" then
t.value = cjson.decode(t.value)
end
-- remove application_id if null uuid
if t.application_id == constants.DATABASE_NULL_ID then
t.application_id = nil
end
return t
end
function Plugins:find_distinct()
-- Open session
local session, err = Plugins.super._open_session(self)
if err then
return nil, err
end
-- Execute query
local distinct_names = {}
for _, rows, page, err in session:execute(self._statements.select.query, nil, {auto_paging=true}) do
if err then
return nil, err
end
for _, v in ipairs(rows) do
-- Rows also contains other properites, so making sure it's a plugin
if v.name then
distinct_names[v.name] = true
end
end
end
-- Close session
local socket_err = Plugins.super._close_session(self, session)
if socket_err then
return nil, socket_err
end
local result = {}
for k,_ in pairs(distinct_names) do
table.insert(result, k)
end
return result, nil
end
return Plugins
|
Fixing nil concatenation in Plugins
|
Fixing nil concatenation in Plugins
|
Lua
|
apache-2.0
|
wakermahmud/kong,skynet/kong,vmercierfr/kong,chourobin/kong,puug/kong,sbuettner/kong,Skyscanner/kong,AnsonSmith/kong,bbalu/kong,peterayeni/kong,paritoshmmmec/kong,ChristopherBiscardi/kong,ropik/kong
|
0ce63403f05ea2a6dfe247ba1178caf49557fb8d
|
kong/api/routes/plugins.lua
|
kong/api/routes/plugins.lua
|
local kong = kong
local null = ngx.null
local cjson = require "cjson"
local utils = require "kong.tools.utils"
local reports = require "kong.reports"
local endpoints = require "kong.api.endpoints"
local arguments = require "kong.api.arguments"
local singletons = require "kong.singletons"
local type = type
local pairs = pairs
local get_plugin = endpoints.get_entity_endpoint(kong.db.plugins.schema)
local put_plugin = endpoints.put_entity_endpoint(kong.db.plugins.schema)
local delete_plugin = endpoints.delete_entity_endpoint(kong.db.plugins.schema)
local function before_plugin_for_entity(entity_name, plugin_field)
return function(self, db, helpers)
local entity = endpoints.select_entity(self, db, kong.db[entity_name].schema)
if not entity then
return kong.response.exit(404, { message = "Not found" })
end
local plugin = db.plugins:select({ id = self.params.id })
if not plugin
or type(plugin[plugin_field]) ~= "table"
or plugin[plugin_field].id ~= entity.id then
return kong.response.exit(404, { message = "Not found" })
end
self.plugin = plugin
self.params.plugins = self.params.id
end
end
local function fill_plugin_data(args, plugin)
local post = args.post
post.name = post.name or plugin.name
-- Only now we can decode the 'config' table for form-encoded values
post = arguments.decode(post, kong.db.plugins.schema)
-- While we're at it, get values for composite uniqueness check
post.route = post.route or plugin.route
post.service = post.service or plugin.service
post.consumer = post.consumer or plugin.consumer
args.post = post
end
local patch_plugin
do
local patch_plugin_endpoint = endpoints.patch_entity_endpoint(kong.db.plugins.schema)
patch_plugin = function(self, db, helpers)
local plugin = self.plugin
fill_plugin_data(self.args, plugin)
return patch_plugin_endpoint(self, db, helpers)
end
end
-- Remove functions from a schema definition so that
-- cjson can encode the schema.
local schema_to_jsonable
do
local insert = table.insert
local ipairs = ipairs
local next = next
local fdata_to_jsonable
local function fields_to_jsonable(fields)
local out = {}
for _, field in ipairs(fields) do
local fname = next(field)
local fdata = field[fname]
insert(out, { [fname] = fdata_to_jsonable(fdata, "no") })
end
setmetatable(out, cjson.array_mt)
return out
end
-- Convert field data from schemas into something that can be
-- passed to a JSON encoder.
-- @tparam table fdata A Lua table with field data
-- @tparam string is_array A three-state enum: "yes", "no" or "maybe"
-- @treturn table A JSON-convertible Lua table
fdata_to_jsonable = function(fdata, is_array)
local out = {}
local iter = is_array == "yes" and ipairs or pairs
for k, v in iter(fdata) do
if is_array == "maybe" and type(k) ~= "number" then
is_array = "no"
end
if k == "schema" then
out[k] = schema_to_jsonable(v)
elseif type(v) == "table" then
if k == "fields" and fdata.type == "record" then
out[k] = fields_to_jsonable(v)
elseif k == "default" and fdata.type == "array" then
out[k] = fdata_to_jsonable(v, "yes")
else
out[k] = fdata_to_jsonable(v, "maybe")
end
elseif type(v) == "number" then
if v ~= v then
out[k] = "nan"
elseif v == math.huge then
out[k] = "inf"
elseif v == -math.huge then
out[k] = "-inf"
else
out[k] = v
end
elseif type(v) ~= "function" then
out[k] = v
end
end
if is_array == "yes" or is_array == "maybe" then
setmetatable(out, cjson.array_mt)
end
return out
end
schema_to_jsonable = function(schema)
local fields = fields_to_jsonable(schema.fields)
return { fields = fields }
end
end
local function post_process(data)
local r_data = utils.deep_copy(data)
r_data.config = nil
if data.service ~= null and data.service.id then
r_data.e = "s"
elseif data.route ~= null and data.route.id then
r_data.e = "r"
elseif data.consumer ~= null and data.consumer.id then
r_data.e = "c"
end
reports.send("api", r_data)
return data
end
return {
["/plugins"] = {
POST = function(_, _, _, parent)
return parent(post_process)
end,
},
["/plugins/:plugins"] = {
PATCH = function(self, db, helpers, parent)
local post = self.args and self.args.post
-- Read-before-write only if necessary
if post and (post.name == nil or
post.route == nil or
post.service == nil or
post.consumer == nil) then
-- We need the name, otherwise we don't know what type of
-- plugin this is and we can't perform *any* validations.
local plugin = db.plugins:select({ id = self.params.plugins })
if not plugin then
return kong.response.exit(404, { message = "Not found" })
end
fill_plugin_data(self.args, plugin)
end
return parent()
end,
},
["/plugins/schema/:name"] = {
GET = function(self, db, helpers)
local subschema = db.plugins.schema.subschemas[self.params.name]
if not subschema then
return kong.response.exit(404, { message = "No plugin named '" .. self.params.name .. "'" })
end
local copy = schema_to_jsonable(subschema.fields.config)
return kong.response.exit(200, copy)
end
},
["/plugins/enabled"] = {
GET = function(_, _, helpers)
local enabled_plugins = setmetatable({}, cjson.array_mt)
for k in pairs(singletons.configuration.loaded_plugins) do
enabled_plugins[#enabled_plugins+1] = k
end
return kong.response.exit(200, {
enabled_plugins = enabled_plugins
})
end
},
-- Available for backward compatibility
["/consumers/:consumers/plugins/:id"] = {
before = before_plugin_for_entity("consumers", "consumer"),
PATCH = patch_plugin,
GET = get_plugin,
PUT = put_plugin,
DELETE = delete_plugin,
},
-- Available for backward compatibility
["/routes/:routes/plugins/:id"] = {
before = before_plugin_for_entity("routes", "route"),
PATCH = patch_plugin,
GET = get_plugin,
PUT = put_plugin,
DELETE = delete_plugin,
},
-- Available for backward compatibility
["/services/:services/plugins/:id"] = {
before = before_plugin_for_entity("services", "service"),
PATCH = patch_plugin,
GET = get_plugin,
PUT = put_plugin,
DELETE = delete_plugin,
},
}
|
local kong = kong
local cjson = require "cjson"
local utils = require "kong.tools.utils"
local reports = require "kong.reports"
local endpoints = require "kong.api.endpoints"
local arguments = require "kong.api.arguments"
local singletons = require "kong.singletons"
local type = type
local pairs = pairs
local get_plugin = endpoints.get_entity_endpoint(kong.db.plugins.schema)
local put_plugin = endpoints.put_entity_endpoint(kong.db.plugins.schema)
local delete_plugin = endpoints.delete_entity_endpoint(kong.db.plugins.schema)
local function before_plugin_for_entity(entity_name, plugin_field)
return function(self, db, helpers)
local entity = endpoints.select_entity(self, db, kong.db[entity_name].schema)
if not entity then
return kong.response.exit(404, { message = "Not found" })
end
local plugin = db.plugins:select({ id = self.params.id })
if not plugin
or type(plugin[plugin_field]) ~= "table"
or plugin[plugin_field].id ~= entity.id then
return kong.response.exit(404, { message = "Not found" })
end
self.plugin = plugin
self.params.plugins = self.params.id
end
end
local function fill_plugin_data(args, plugin)
local post = args.post
post.name = post.name or plugin.name
-- Only now we can decode the 'config' table for form-encoded values
post = arguments.decode(post, kong.db.plugins.schema)
-- While we're at it, get values for composite uniqueness check
post.route = post.route or plugin.route
post.service = post.service or plugin.service
post.consumer = post.consumer or plugin.consumer
args.post = post
end
local patch_plugin
do
local patch_plugin_endpoint = endpoints.patch_entity_endpoint(kong.db.plugins.schema)
patch_plugin = function(self, db, helpers)
local plugin = self.plugin
fill_plugin_data(self.args, plugin)
return patch_plugin_endpoint(self, db, helpers)
end
end
-- Remove functions from a schema definition so that
-- cjson can encode the schema.
local schema_to_jsonable
do
local insert = table.insert
local ipairs = ipairs
local next = next
local fdata_to_jsonable
local function fields_to_jsonable(fields)
local out = {}
for _, field in ipairs(fields) do
local fname = next(field)
local fdata = field[fname]
insert(out, { [fname] = fdata_to_jsonable(fdata, "no") })
end
setmetatable(out, cjson.array_mt)
return out
end
-- Convert field data from schemas into something that can be
-- passed to a JSON encoder.
-- @tparam table fdata A Lua table with field data
-- @tparam string is_array A three-state enum: "yes", "no" or "maybe"
-- @treturn table A JSON-convertible Lua table
fdata_to_jsonable = function(fdata, is_array)
local out = {}
local iter = is_array == "yes" and ipairs or pairs
for k, v in iter(fdata) do
if is_array == "maybe" and type(k) ~= "number" then
is_array = "no"
end
if k == "schema" then
out[k] = schema_to_jsonable(v)
elseif type(v) == "table" then
if k == "fields" and fdata.type == "record" then
out[k] = fields_to_jsonable(v)
elseif k == "default" and fdata.type == "array" then
out[k] = fdata_to_jsonable(v, "yes")
else
out[k] = fdata_to_jsonable(v, "maybe")
end
elseif type(v) == "number" then
if v ~= v then
out[k] = "nan"
elseif v == math.huge then
out[k] = "inf"
elseif v == -math.huge then
out[k] = "-inf"
else
out[k] = v
end
elseif type(v) ~= "function" then
out[k] = v
end
end
if is_array == "yes" or is_array == "maybe" then
setmetatable(out, cjson.array_mt)
end
return out
end
schema_to_jsonable = function(schema)
local fields = fields_to_jsonable(schema.fields)
return { fields = fields }
end
end
local function post_process(data)
local r_data = utils.deep_copy(data)
r_data.config = nil
r_data.route = nil
r_data.service = nil
r_data.consumer = nil
r_data.enabled = nil
if type(data.service) == "table" and data.service.id then
r_data.e = "s"
elseif type(data.route) == "table" and data.route.id then
r_data.e = "r"
elseif type(data.consumer) == "table" and data.consumer.id then
r_data.e = "c"
end
reports.send("api", r_data)
return data
end
return {
["/plugins"] = {
POST = function(_, _, _, parent)
return parent(post_process)
end,
},
["/plugins/:plugins"] = {
PATCH = function(self, db, helpers, parent)
local post = self.args and self.args.post
-- Read-before-write only if necessary
if post and (post.name == nil or
post.route == nil or
post.service == nil or
post.consumer == nil) then
-- We need the name, otherwise we don't know what type of
-- plugin this is and we can't perform *any* validations.
local plugin = db.plugins:select({ id = self.params.plugins })
if not plugin then
return kong.response.exit(404, { message = "Not found" })
end
fill_plugin_data(self.args, plugin)
end
return parent()
end,
},
["/plugins/schema/:name"] = {
GET = function(self, db, helpers)
local subschema = db.plugins.schema.subschemas[self.params.name]
if not subschema then
return kong.response.exit(404, { message = "No plugin named '" .. self.params.name .. "'" })
end
local copy = schema_to_jsonable(subschema.fields.config)
return kong.response.exit(200, copy)
end
},
["/plugins/enabled"] = {
GET = function(_, _, helpers)
local enabled_plugins = setmetatable({}, cjson.array_mt)
for k in pairs(singletons.configuration.loaded_plugins) do
enabled_plugins[#enabled_plugins+1] = k
end
return kong.response.exit(200, {
enabled_plugins = enabled_plugins
})
end
},
-- Available for backward compatibility
["/consumers/:consumers/plugins/:id"] = {
before = before_plugin_for_entity("consumers", "consumer"),
PATCH = patch_plugin,
GET = get_plugin,
PUT = put_plugin,
DELETE = delete_plugin,
},
-- Available for backward compatibility
["/routes/:routes/plugins/:id"] = {
before = before_plugin_for_entity("routes", "route"),
PATCH = patch_plugin,
GET = get_plugin,
PUT = put_plugin,
DELETE = delete_plugin,
},
-- Available for backward compatibility
["/services/:services/plugins/:id"] = {
before = before_plugin_for_entity("services", "service"),
PATCH = patch_plugin,
GET = get_plugin,
PUT = put_plugin,
DELETE = delete_plugin,
},
}
|
fix(reports) do not send unnecessary attributes in 'ping' message
|
fix(reports) do not send unnecessary attributes in 'ping' message
Prior to this patch, configuring a plugin via `POST /plugins` would send
reports with `<entity>=userdata;<entity>=userdata;` when the plugin was
not configured on a given entity (e.g. when configuring a global plugin,
or a plugin with a Route only).
We also avoid sending `enabled=true` which has very little value and
takes space in our already limited UDP packet length.
From #4156
|
Lua
|
apache-2.0
|
Kong/kong,Kong/kong,Mashape/kong,Kong/kong
|
2f8964e83b2b1757009efb1a87a2372e6a557dec
|
main.lua
|
main.lua
|
-- Parameters taken from (tuned) Double DQN paper: http://arxiv.org/pdf/1509.06461.pdf
require 'cutorch'
local image = require 'image'
local environment = require 'environment'
local model = require 'model'
-- Detect QT for image display
local qt = pcall(require, 'qt')
local cmd = torch.CmdLine()
-- Base options
cmd:option('-seed', 123, 'Random seed')
cmd:option('-threads', 4, 'Number of BLAS threads')
cmd:option('-tensorType', 'torch.FloatTensor', 'Default tensor type')
cmd:option('-gpu', 1, 'GPU device ID (0 to disable)')
-- Game
cmd:option('-game', 'pong', 'Name of Atari ROM (stored in "roms" directory)')
-- Train vs. test mode
cmd:option('-mode', 'train', '"train" or "test" mode')
-- Experience replay options
cmd:option('-memSize', 1000000, 'Experience replay memory size (# of tuples)')
cmd:option('-memSampleFreq', 4, 'Memory sample frequency')
-- TODO: Add prioritised experience replay
-- Reinforcement learning parameters
cmd:option('-gamma', 0.99, 'Discount rate γ')
cmd:option('-alpha', 0.00025, 'Learning rate α') -- TODO: Lower learning rate as per dueling paper
cmd:option('-epsilonStart', 1, 'Initial value of greediness ε')
cmd:option('-epsilonEnd', 0.01, 'Final value of greediness ε')
cmd:option('-epsilonSteps', 1000000, 'Number of steps to linearly decay epsilonStart to epsilonEnd')
cmd:option('-tau', 30000, 'Steps between target net updates τ')
cmd:option('-rewardClamp', 1, 'Clamps reward magnitude')
cmd:option('-tdClamp', 1, 'Clamps TD error δ magnitude')
-- Training options
cmd:option('-optimiser', 'rmsprop', 'Training algorithm')
cmd:option('-momentum', 0.95, 'SGD momentum')
cmd:option('-batchSize', 32, 'Minibatch size')
cmd:option('-steps', 50000000, 'Training iterations')
--cmd:option('-learnStart', 50000, 'Number of steps after which learning starts')
-- Evaluation options
cmd:option('-evalFreq', 1000000, 'Evaluation frequency')
cmd:option('-evalSize', 500, '# of validation transitions to use')
-- alewrap options
cmd:option('-actrep', 4, 'Times to repeat action')
cmd:option('-random_starts', 30, 'Play action 0 between 1 and random_starts number of times at the start of each training episode')
-- TODO: Tidy up options/check agent_params
--cmd:option('-agent_params', 'hist_len=4,update_freq=4,n_replay=1,ncols=1,bufferSize=512', 'string of agent parameters')
local opt = cmd:parse(arg)
-- Torch setup
-- Enable memory management
torch.setheaptracking(true)
-- Set number of BLAS threads
torch.setnumthreads(opt.threads)
-- Set default Tensor type (float is more efficient than double)
torch.setdefaulttensortype(opt.tensorType)
-- Set manual seeds using random numbers to reduce correlations
math.randomseed(opt.seed)
torch.manualSeed(math.random(1, 10000))
-- GPU setup
cutorch.setDevice(opt.gpu)
cutorch.manualSeedAll(torch.random())
-- Initialise Arcade Learning Environment
local gameEnv = environment.init(opt)
-- Create agent
local agent = model.createAgent(gameEnv, opt)
-- Start gaming
local screen, reward, terminal = gameEnv:newGame()
-- Activate display if using QT
local window
if qt then
window = image.display({image=screen})
end
if opt.mode == 'train' then
-- Create ε decay vector
opt.epsilon = torch.linspace(opt.epsilonEnd, opt.epsilonStart, opt.epsilonSteps)
opt.epsilon:mul(-1):add(opt.epsilonStart)
local epsilonFinal = torch.Tensor(opt.steps - opt.epsilonSteps):fill(opt.epsilonEnd)
opt.epsilon = torch.cat(opt.epsilon, epsilonFinal)
-- Set agent (and hence environment steps) to training mode
agent:training()
-- Training loop
for step = 1, opt.steps do
opt.step = step -- Pass step to agent for use in training
-- Observe and choose next action
local actionIndex = agent:observe(screen)
if not terminal then
-- Act on environment and learn
screen, reward, terminal = agent:act(actionIndex)
else
-- Start a new episode
if opt.random_starts > 0 then
screen, reward, terminal = gameEnv:nextRandomGame()
else
screen, reward, terminal = gameEnv:newGame()
end
end
-- Update display
if qt then
image.display({image=screen, win=window})
end
if step % opt.evalFreq then
-- TODO: Perform evaluation
-- TODO: Save best parameters
end
end
elseif opt.mode == 'test' then
-- Set agent (and hence environment steps) to evaluation mode
agent:evaluation()
-- Play one game (episode)
while not terminal do
local actionIndex = agent:observe(screen)
-- Act on environment
screen, reward, terminal = agent:act(actionIndex)
if qt then
image.display({image=screen, win=window})
end
end
end
|
-- Parameters taken from (tuned) Double DQN paper: http://arxiv.org/pdf/1509.06461.pdf
require 'cutorch'
local image = require 'image'
local environment = require 'environment'
local model = require 'model'
-- Detect QT for image display
local qt = pcall(require, 'qt')
local cmd = torch.CmdLine()
-- Base options
cmd:option('-seed', 123, 'Random seed')
cmd:option('-threads', 4, 'Number of BLAS threads')
cmd:option('-tensorType', 'torch.FloatTensor', 'Default tensor type')
cmd:option('-gpu', 1, 'GPU device ID (0 to disable)')
-- Game
cmd:option('-game', 'pong', 'Name of Atari ROM (stored in "roms" directory)')
-- Train vs. test mode
cmd:option('-mode', 'train', '"train" or "test" mode')
-- Experience replay options
cmd:option('-memSize', 1000000, 'Experience replay memory size (# of tuples)')
cmd:option('-memSampleFreq', 4, 'Memory sample frequency')
-- TODO: Add prioritised experience replay
-- Reinforcement learning parameters
cmd:option('-gamma', 0.99, 'Discount rate γ')
cmd:option('-alpha', 0.00025, 'Learning rate α') -- TODO: Lower learning rate as per dueling paper
cmd:option('-epsilonStart', 1, 'Initial value of greediness ε')
cmd:option('-epsilonEnd', 0.01, 'Final value of greediness ε')
cmd:option('-epsilonSteps', 1000000, 'Number of steps to linearly decay epsilonStart to epsilonEnd')
cmd:option('-tau', 30000, 'Steps between target net updates τ')
cmd:option('-rewardClamp', 1, 'Clamps reward magnitude')
cmd:option('-tdClamp', 1, 'Clamps TD error δ magnitude')
-- Training options
cmd:option('-optimiser', 'rmsprop', 'Training algorithm')
cmd:option('-momentum', 0.95, 'SGD momentum')
cmd:option('-batchSize', 32, 'Minibatch size')
cmd:option('-steps', 50000000, 'Training iterations')
--cmd:option('-learnStart', 50000, 'Number of steps after which learning starts')
-- Evaluation options
cmd:option('-evalFreq', 1000000, 'Evaluation frequency')
cmd:option('-evalSize', 500, '# of validation transitions to use')
-- alewrap options
cmd:option('-actrep', 4, 'Times to repeat action')
cmd:option('-random_starts', 30, 'Play action 0 between 1 and random_starts number of times at the start of each training episode')
-- TODO: Tidy up options/check agent_params
--cmd:option('-agent_params', 'hist_len=4,update_freq=4,n_replay=1,ncols=1,bufferSize=512', 'string of agent parameters')
local opt = cmd:parse(arg)
-- Torch setup
-- Enable memory management
torch.setheaptracking(true)
-- Set number of BLAS threads
torch.setnumthreads(opt.threads)
-- Set default Tensor type (float is more efficient than double)
torch.setdefaulttensortype(opt.tensorType)
-- Set manual seeds using random numbers to reduce correlations
math.randomseed(opt.seed)
torch.manualSeed(math.random(1, 10000))
-- GPU setup
cutorch.setDevice(opt.gpu)
cutorch.manualSeedAll(torch.random())
-- Initialise Arcade Learning Environment
local gameEnv = environment.init(opt)
-- Create agent
local agent = model.createAgent(gameEnv, opt)
-- Start gaming
local screen, reward, terminal = gameEnv:newGame()
-- Activate display if using QT
local window
if qt then
window = image.display({image=screen})
end
if opt.mode == 'train' then
-- Create ε decay vector
opt.epsilon = torch.linspace(opt.epsilonEnd, opt.epsilonStart, opt.epsilonSteps)
opt.epsilon:mul(-1):add(opt.epsilonStart)
local epsilonFinal = torch.Tensor(opt.steps - opt.epsilonSteps):fill(opt.epsilonEnd)
opt.epsilon = torch.cat(opt.epsilon, epsilonFinal)
-- Set agent (and hence environment steps) to training mode
agent:training()
-- Training loop
for step = 1, opt.steps do
opt.step = step -- Pass step to agent for use in training
-- Observe and choose next action
local actionIndex = agent:observe(screen)
if not terminal then
-- Act on environment and learn
screen, reward, terminal = agent:act(actionIndex)
else
-- Start a new episode
if opt.random_starts > 0 then
screen, reward, terminal = gameEnv:nextRandomGame()
else
screen, reward, terminal = gameEnv:newGame()
end
end
-- Update display
if qt then
image.display({image=screen, win=window})
end
if step % opt.evalFreq then
agent:evaluate()
-- TODO: Perform evaluation
-- TODO: Save best parameters
agent:training()
end
end
elseif opt.mode == 'test' then
-- Set agent (and hence environment steps) to evaluation mode
agent:evaluate()
-- Play one game (episode)
while not terminal do
local actionIndex = agent:observe(screen)
-- Act on environment
screen, reward, terminal = agent:act(actionIndex)
if qt then
image.display({image=screen, win=window})
end
end
end
|
Fix agent evaluation calls
|
Fix agent evaluation calls
|
Lua
|
mit
|
Kaixhin/Atari
|
de06ff68930b84166151b56e4a2419ad7479344d
|
ssbase/gamemode/sv_profiles.lua
|
ssbase/gamemode/sv_profiles.lua
|
---------------------------
-- Bunny Hop --
-- Created by xAaron113x --
---------------------------
local selects = {"exp", "id", "steamId64", "lastLoginIp", "playtime", "lastLoginTimestamp", "steamId", "rank", "name", "money"}
SS.Profiles = {}
function PLAYER_META:CreateProfile()
local query = "INSERT INTO users (steamid64, steamid, name, registerIp, registerTimestamp) VALUES ('"..self:SteamID64().."','"..string.sub(self:SteamID(), 7).."','"..DB:escape(self:Name()).."','"..self:IPAddress().."','"..tostring(os.time()).."')"
DB_Query(query, function() if self and self:IsValid() then self:ProfileLoad() end end)
end
function PLAYER_META:ProfileLoad()
MsgN("[PROFILE] Loading ", self)
local steamid = self:SteamID()
SS.Profiles[steamid] = {}
self:ChatPrint("Loading your profile")
if DB_DEVS then self:ProfileLoaded() return end
timer.Simple(30, function() if self and self:IsValid() and !self:IsProfileLoaded() then self:ChatPrint("Your profile seems to be having problems loading. Our appologies.") end end)
DB_Query("SELECT "..table.concat(selects, ", ").." FROM users WHERE steamid='"..string.sub(steamid, 7).."'",
function(data) if self and self:IsValid() then self:ProfileLoaded(data) end end,
function()
if self and self:IsValid() then
self.ProfileFailed = true
self:ChatPrint("We failed to load your profile, trying again in 60 seconds.")
timer.Simple(60, function()
if self and self:IsValid() then
self:ProfileLoad()
end
end )
end
end)
end
function PLAYER_META:ProfileLoaded(res)
local steamid = self:SteamID()
if res and res[1] then
if res[2] then Error("Duplicate profile! Contact a developer! ("..steam..")") return end
self.profile = res[1]
MsgN("[PROFILE] Loaded ", self)
self:SetRank(self.profile.rank)
self:SetMoney(self.profile.money)
self:SetExp(self.profile.exp)
self.profile.lastLoginIp = self:IPAddress()
self.profile.lastLoginTimestamp = os.time()
self.playtimeStart = os.time()
SS.Profiles[self:SteamID()] = self.profile
self:ChatPrint("Your profile has been loaded")
elseif res and !res[1] then
self:ChatPrint("No profile detected, creating one for you.")
self:CreateProfile()
return
else
self.profile = {}
self:SetRank(DB_DEVS and 100 or 0)
self:SetMoney(100)
self:SetExp(1)
self:ChatPrint("We had problems loading your profile and have created a temporary one for you.")
end
timer.Create(self:SteamID().."_ProfileUpdate", 120, 0, function()
if self and self:IsValid() then
self.profile.lastLoginTimestamp = os.time()
self.profile.playtime = self.profile.playtime+(os.time()-self.playtimeStart)
self.playtimeStart = os.time()
self:ProfileSave()
else
timer.Destroy(steamid.."_ProfileUpdate")
end
end )
self:SetNetworkedBool("ss_profileloaded", true)
end
/* Sync Profile with database */
function PLAYER_META:ProfileSave()
local profile = SS.Profiles[self:SteamID()]
profile.money = self.money
profile.exp = self.exp
profile.playtime = profile.playtime+(os.time()-self.playtimeStart)
self.playtimeStart = os.time()
local Query = "UPDATE users SET "
local first = true
for k,v in pairs(profile) do
if first then
Query = Query..k.."='"..v.."'"
first = false
else
Query = Query..", "..k.."='"..v.."'"
end
end
Query = Query.." WHERE steamid='"..string.sub(self:SteamID(), 7).."'"
DB_Query(Query)
end
function PLAYER_META:ProfileUpdate(col, val) -- Don't be an idiot with this
if !SERVER then return end
DB_Query("UPDATE users SET "..tostring(col).."='"..tostring(val).."' WHERE steamid='"..string.sub(self:SteamID(), 7).."'" )
end
|
---------------------------
-- Bunny Hop --
-- Created by xAaron113x --
---------------------------
local selects = {"exp", "id", "steamId64", "lastLoginIp", "playtime", "lastLoginTimestamp", "steamId", "rank", "name", "money"}
SS.Profiles = {}
function PLAYER_META:CreateProfile()
local query = "INSERT INTO users (steamid64, steamid, name, registerIp, registerTimestamp) VALUES ('"..self:SteamID64().."','"..string.sub(self:SteamID(), 7).."','"..DB:escape(self:Name()).."','"..self:IPAddress().."','"..tostring(os.time()).."')"
DB_Query(query, function() if self and self:IsValid() then self:ProfileLoad() end end)
end
function PLAYER_META:ProfileLoad()
MsgN("[PROFILE] Loading ", self)
local steamid = self:SteamID()
SS.Profiles[steamid] = {}
self:ChatPrint("Loading your profile")
if DB_DEVS then self:ProfileLoaded() return end
timer.Simple(30, function() if self and self:IsValid() and !self:IsProfileLoaded() then self:ChatPrint("Your profile seems to be having problems loading. Our appologies.") end end)
DB_Query("SELECT "..table.concat(selects, ", ").." FROM users WHERE steamid='"..string.sub(steamid, 7).."'",
function(data) if self and self:IsValid() then self:ProfileLoaded(data) end end,
function()
if self and self:IsValid() then
self.ProfileFailed = true
self:ChatPrint("We failed to load your profile, trying again in 60 seconds.")
timer.Simple(60, function()
if self and self:IsValid() then
self:ProfileLoad()
end
end )
end
end)
end
function PLAYER_META:ProfileLoaded(res)
local steamid = self:SteamID()
if res and res[1] then
if res[2] then Error("Duplicate profile! Contact a developer! ("..steam..")") return end
self.profile = res[1]
MsgN("[PROFILE] Loaded ", self)
self:SetRank(self.profile.rank)
self:SetMoney(self.profile.money)
self:SetExp(self.profile.exp)
self.profile.lastLoginIp = self:IPAddress()
self.profile.lastLoginTimestamp = os.time()
self.playtimeStart = os.time()
SS.Profiles[self:SteamID()] = self.profile
self:ChatPrint("Your profile has been loaded")
elseif res and !res[1] then
self:ChatPrint("No profile detected, creating one for you.")
self:CreateProfile()
return
else
self.profile = {}
self.profile.lastLoginIp = self:IPAddress()
self.profile.lastLoginTimestamp = os.time()
self.playtimeStart = os.time()
self:SetRank(DB_DEVS and 100 or 0)
self:SetMoney(100)
self:SetExp(1)
self:ChatPrint("We had problems loading your profile and have created a temporary one for you.")
end
timer.Create(self:SteamID().."_ProfileUpdate", 120, 0, function()
if self and self:IsValid() then
self.profile.lastLoginTimestamp = os.time()
self.profile.playtime = self.profile.playtime+(os.time()-self.playtimeStart)
self.playtimeStart = os.time()
self:ProfileSave()
else
timer.Destroy(steamid.."_ProfileUpdate")
end
end )
self:SetNetworkedBool("ss_profileloaded", true)
end
/* Sync Profile with database */
function PLAYER_META:ProfileSave()
local profile = SS.Profiles[self:SteamID()]
profile.money = self.money
profile.exp = self.exp
profile.playtime = profile.playtime+(os.time()-self.playtimeStart)
self.playtimeStart = os.time()
local Query = "UPDATE users SET "
local first = true
for k,v in pairs(profile) do
if first then
Query = Query..k.."='"..v.."'"
first = false
else
Query = Query..", "..k.."='"..v.."'"
end
end
Query = Query.." WHERE steamid='"..string.sub(self:SteamID(), 7).."'"
DB_Query(Query)
end
function PLAYER_META:ProfileUpdate(col, val) -- Don't be an idiot with this
if !SERVER then return end
DB_Query("UPDATE users SET "..tostring(col).."='"..tostring(val).."' WHERE steamid='"..string.sub(self:SteamID(), 7).."'" )
end
|
One fix
|
One fix
|
Lua
|
bsd-3-clause
|
T3hArco/skeyler-gamemodes
|
c080ee0550ff1dbf4e60cc1c4e49c2f4c141f5c5
|
mod_register_json/mod_register_json.lua
|
mod_register_json/mod_register_json.lua
|
-- Expose a simple servlet to handle user registrations from web pages
-- via JSON.
--
-- A Good chunk of the code is from mod_data_access.lua by Kim Alvefur
-- aka Zash.
local jid_prep = require "util.jid".prep;
local jid_split = require "util.jid".split;
local usermanager = require "core.usermanager";
local b64_decode = require "util.encodings".base64.decode;
local json_decode = require "util.json".decode;
local os_time = os.time;
module.host = "*" -- HTTP/BOSH Servlets need to be global.
-- Pick up configuration.
local set_realm_name = module:get_option("reg_servlet_realm") or "Restricted";
local throttle_time = module:get_option("reg_servlet_ttime") or false;
local whitelist = module:get_option("reg_servlet_wl") or {};
local blacklist = module:get_option("reg_servlet_bl") or {};
local recent_ips = {};
-- Begin
for _, ip in ipairs(whitelist) do whitelisted_ips[ip] = true; end
for _, ip in ipairs(blacklist) do blacklisted_ips[ip] = true; end
local function http_response(code, message, extra_headers)
local response = {
status = code .. " " .. message;
body = message .. "\n"; }
if extra_headers then response.headers = extra_headers; end
return response
end
local function handle_req(method, body, request)
if request.method ~= "POST" then
return http_response(405, "Bad method...", {["Allow"] = "POST"});
end
if not request.headers["authorization"] then
return http_response(401, "No... No...",
{["WWW-Authenticate"]='Basic realm="'.. set_realm_name ..'"'})
end
local user, password = b64_decode(request.headers.authorization
:match("[^ ]*$") or ""):match("([^:]*):(.*)");
user = jid_prep(user);
if not user or not password then return http_response(400, "What's this..?"); end
local user_node, user_host = jid_split(user)
if not hosts[user_host] then return http_response(401, "Negative."); end
module:log("warn", "%s is authing to submit a new user registration data", user)
if not usermanager.test_password(user_node, user_host, password) then
module:log("warn", "%s failed authentication", user)
return http_response(401, "Who the hell are you?! Guards!");
end
local req_body;
-- We check that what we have is valid JSON wise else we throw an error...
if not pcall(function() req_body = json_decode(body) end) then
module:log("debug", "JSON data submitted for user registration by %s failed to Decode.", user);
return http_response(400, "JSON Decoding failed.");
else
-- Decode JSON data and check that all bits are there else throw an error
req_body = json_decode(body);
if req_body["username"] == nil or req_body["password"] == nil or req_body["host"] == nil or req_body["ip"] == nil then
module:log("debug", "%s supplied an insufficent number of elements or wrong elements for the JSON registration", user);
return http_response(400, "Invalid syntax.");
end
-- Check if user is an admin of said host
if not usermanager.is_admin(user, req_body["host"]) then
module:log("warn", "%s tried to submit registration data for %s but he's not an admin", user, req_body["host"]);
return http_response(401, "I obey only to my masters... Have a nice day.");
else
-- Checks for both Throttling/Whitelist and Blacklist (basically copycatted from prosody's register.lua code)
if blacklist[req_body["ip"]] then module:log("warn", "Attempt of reg. submission to the JSON servlet from blacklisted address: %s", req_body["ip"]); return http_response(403, "The specified address is blacklisted, sorry sorry."); end
if throttle_time and not whitelist[req_body["ip"]] then
if not recent_ips[req_body["ip"]] then
recent_ips[req_body["ip"]] = { time = os_time(), count = 1 };
else
local ip = recent_ips[req_body["ip"]];
ip.count = ip.count + 1;
if os_time() - ip.time < throttle_time then
ip.time = os_time();
module:log("warn", "JSON Registration request from %s has been throttled.", req_body["ip"]);
return http_response(503, "Woah... How many users you want to register..? Request throttled, wait a bit and try again.");
end
ip.time = os_time();
end
end
-- We first check if the supplied username for registration is already there.
if not usermanager.user_exists(req_body["username"], req_body["host"]) then
usermanager.create_user(req_body["username"], req_body["password"], req_body["host"]);
module:log("debug", "%s registration data submission for %s is successful", user, req_body["username"]);
return http_response(200, "Done.");
else
module:log("debug", "%s registration data submission for %s failed (user already exists)", user, req_body["username"]);
return http_response(409, "User already exists.");
end
end
end
end
-- Set it up!
local function setup()
local ports = module:get_option("reg_servlet_port") or { 9280 };
local base_name = module:get_option("reg_servlet_base") or "register_account";
local ssl_cert = module:get_option("reg_servlet_sslcert") or false;
local ssl_key = module:get_option("reg_servlet_sslkey") or false;
if not ssl_cert or not ssl_key then
require "net.httpserver".new_from_config(ports, handle_req, { base = base_name });
else
if module:get_option("reg_servlet_port") == nil then ports = { 9443 }; end
require "net.httpserver".new_from_config(ports, handle_req, { ssl = { key = ssl_key, certificate = ssl_cert }, base = base_name });
end
end
if prosody.start_time then -- already started
setup();
else
prosody.events.add_handler("server-started", setup);
end
|
-- Expose a simple servlet to handle user registrations from web pages
-- via JSON.
--
-- A Good chunk of the code is from mod_data_access.lua by Kim Alvefur
-- aka Zash.
local jid_prep = require "util.jid".prep;
local jid_split = require "util.jid".split;
local usermanager = require "core.usermanager";
local b64_decode = require "util.encodings".base64.decode;
local json_decode = require "util.json".decode;
local os_time = os.time;
module.host = "*" -- HTTP/BOSH Servlets need to be global.
-- Pick up configuration.
local set_realm_name = module:get_option("reg_servlet_realm") or "Restricted";
local throttle_time = module:get_option("reg_servlet_ttime") or false;
local whitelist = module:get_option("reg_servlet_wl") or {};
local blacklist = module:get_option("reg_servlet_bl") or {};
local recent_ips = {};
-- Begin
for _, ip in ipairs(whitelist) do whitelisted_ips[ip] = true; end
for _, ip in ipairs(blacklist) do blacklisted_ips[ip] = true; end
local function http_response(code, message, extra_headers)
local response = {
status = code .. " " .. message;
body = message .. "\n"; }
if extra_headers then response.headers = extra_headers; end
return response
end
local function handle_req(method, body, request)
if request.method ~= "POST" then
return http_response(405, "Bad method...", {["Allow"] = "POST"});
end
if not request.headers["authorization"] then
return http_response(401, "No... No...",
{["WWW-Authenticate"]='Basic realm="'.. set_realm_name ..'"'})
end
local user, password = b64_decode(request.headers.authorization
:match("[^ ]*$") or ""):match("([^:]*):(.*)");
user = jid_prep(user);
if not user or not password then return http_response(400, "What's this..?"); end
local user_node, user_host = jid_split(user)
if not hosts[user_host] then return http_response(401, "Negative."); end
module:log("warn", "%s is authing to submit a new user registration data", user)
if not usermanager.test_password(user_node, user_host, password) then
module:log("warn", "%s failed authentication", user)
return http_response(401, "Who the hell are you?! Guards!");
end
local req_body;
-- We check that what we have is valid JSON wise else we throw an error...
if not pcall(function() req_body = json_decode(body) end) then
module:log("debug", "JSON data submitted for user registration by %s failed to Decode.", user);
return http_response(400, "JSON Decoding failed.");
else
-- Decode JSON data and check that all bits are there else throw an error
req_body = json_decode(body);
if req_body["username"] == nil or req_body["password"] == nil or req_body["host"] == nil or req_body["ip"] == nil then
module:log("debug", "%s supplied an insufficent number of elements or wrong elements for the JSON registration", user);
return http_response(400, "Invalid syntax.");
end
-- Check if user is an admin of said host
if not usermanager.is_admin(user, req_body["host"]) then
module:log("warn", "%s tried to submit registration data for %s but he's not an admin", user, req_body["host"]);
return http_response(401, "I obey only to my masters... Have a nice day.");
else
-- Checks for both Throttling/Whitelist and Blacklist (basically copycatted from prosody's register.lua code)
if blacklist[req_body["ip"]] then module:log("warn", "Attempt of reg. submission to the JSON servlet from blacklisted address: %s", req_body["ip"]); return http_response(403, "The specified address is blacklisted, sorry sorry."); end
if throttle_time and not whitelist[req_body["ip"]] then
if not recent_ips[req_body["ip"]] then
recent_ips[req_body["ip"]] = { time = os_time(), count = 1 };
else
local ip = recent_ips[req_body["ip"]];
ip.count = ip.count + 1;
if os_time() - ip.time < throttle_time then
ip.time = os_time();
module:log("warn", "JSON Registration request from %s has been throttled.", req_body["ip"]);
return http_response(503, "Woah... How many users you want to register..? Request throttled, wait a bit and try again.");
end
ip.time = os_time();
end
end
-- We first check if the supplied username for registration is already there.
if not usermanager.user_exists(req_body["username"], req_body["host"]) then
usermanager.create_user(req_body["username"], req_body["password"], req_body["host"]);
module:log("debug", "%s registration data submission for %s is successful", user, req_body["username"]);
return http_response(200, "Done.");
else
module:log("debug", "%s registration data submission for %s failed (user already exists)", user, req_body["username"]);
return http_response(409, "User already exists.");
end
end
end
end
-- Set it up!
local function setup()
local port = module:get_option("reg_servlet_port") or 9280;
local base_name = module:get_option("reg_servlet_base") or "register_account";
local ssl_cert = module:get_option("reg_servlet_sslcert") or false;
local ssl_key = module:get_option("reg_servlet_sslkey") or false;
if not ssl_cert or not ssl_key then
require "net.httpserver".new_from_config({ port = port }, handle_req, { base = base_name });
else
if module:get_option("reg_servlet_port") == nil then port = 9443; end
require "net.httpserver".new_from_config({ port = port; ssl = { key = ssl_key, certificate = ssl_cert }; }, handle_req, { base = base_name });
end
end
if prosody.start_time then -- already started
setup();
else
prosody.events.add_handler("server-started", setup);
end
|
mod_register_json: Fixed http listener creation syntax. (Please document that in the API, that would avoid my brain overheating, thank you.)
|
mod_register_json: Fixed http listener creation syntax. (Please document that in the API, that would avoid my brain overheating, thank you.)
|
Lua
|
mit
|
stephen322/prosody-modules,guilhem/prosody-modules,crunchuser/prosody-modules,joewalker/prosody-modules,heysion/prosody-modules,brahmi2/prosody-modules,amenophis1er/prosody-modules,obelisk21/prosody-modules,vfedoroff/prosody-modules,iamliqiang/prosody-modules,mardraze/prosody-modules,brahmi2/prosody-modules,apung/prosody-modules,guilhem/prosody-modules,softer/prosody-modules,mmusial/prosody-modules,olax/prosody-modules,drdownload/prosody-modules,asdofindia/prosody-modules,LanceJenkinZA/prosody-modules,heysion/prosody-modules,NSAKEY/prosody-modules,joewalker/prosody-modules,vfedoroff/prosody-modules,dhotson/prosody-modules,prosody-modules/import,asdofindia/prosody-modules,iamliqiang/prosody-modules,iamliqiang/prosody-modules,Craige/prosody-modules,prosody-modules/import,softer/prosody-modules,brahmi2/prosody-modules,prosody-modules/import,either1/prosody-modules,crunchuser/prosody-modules,olax/prosody-modules,crunchuser/prosody-modules,apung/prosody-modules,olax/prosody-modules,apung/prosody-modules,dhotson/prosody-modules,olax/prosody-modules,stephen322/prosody-modules,prosody-modules/import,Craige/prosody-modules,vince06fr/prosody-modules,either1/prosody-modules,NSAKEY/prosody-modules,syntafin/prosody-modules,dhotson/prosody-modules,softer/prosody-modules,BurmistrovJ/prosody-modules,syntafin/prosody-modules,guilhem/prosody-modules,apung/prosody-modules,mardraze/prosody-modules,amenophis1er/prosody-modules,cryptotoad/prosody-modules,NSAKEY/prosody-modules,cryptotoad/prosody-modules,LanceJenkinZA/prosody-modules,1st8/prosody-modules,mmusial/prosody-modules,iamliqiang/prosody-modules,cryptotoad/prosody-modules,obelisk21/prosody-modules,mmusial/prosody-modules,jkprg/prosody-modules,jkprg/prosody-modules,syntafin/prosody-modules,BurmistrovJ/prosody-modules,asdofindia/prosody-modules,heysion/prosody-modules,stephen322/prosody-modules,syntafin/prosody-modules,mardraze/prosody-modules,olax/prosody-modules,BurmistrovJ/prosody-modules,BurmistrovJ/prosody-modules,mardraze/prosody-modules,joewalker/prosody-modules,obelisk21/prosody-modules,mmusial/prosody-modules,vince06fr/prosody-modules,vince06fr/prosody-modules,cryptotoad/prosody-modules,stephen322/prosody-modules,mardraze/prosody-modules,mmusial/prosody-modules,vfedoroff/prosody-modules,LanceJenkinZA/prosody-modules,asdofindia/prosody-modules,LanceJenkinZA/prosody-modules,brahmi2/prosody-modules,iamliqiang/prosody-modules,heysion/prosody-modules,brahmi2/prosody-modules,vfedoroff/prosody-modules,crunchuser/prosody-modules,softer/prosody-modules,crunchuser/prosody-modules,dhotson/prosody-modules,heysion/prosody-modules,vince06fr/prosody-modules,jkprg/prosody-modules,guilhem/prosody-modules,softer/prosody-modules,jkprg/prosody-modules,BurmistrovJ/prosody-modules,Craige/prosody-modules,1st8/prosody-modules,cryptotoad/prosody-modules,joewalker/prosody-modules,dhotson/prosody-modules,apung/prosody-modules,syntafin/prosody-modules,obelisk21/prosody-modules,jkprg/prosody-modules,either1/prosody-modules,either1/prosody-modules,drdownload/prosody-modules,1st8/prosody-modules,amenophis1er/prosody-modules,Craige/prosody-modules,guilhem/prosody-modules,LanceJenkinZA/prosody-modules,vince06fr/prosody-modules,joewalker/prosody-modules,obelisk21/prosody-modules,drdownload/prosody-modules,drdownload/prosody-modules,either1/prosody-modules,amenophis1er/prosody-modules,drdownload/prosody-modules,1st8/prosody-modules,amenophis1er/prosody-modules,vfedoroff/prosody-modules,1st8/prosody-modules,prosody-modules/import,asdofindia/prosody-modules,NSAKEY/prosody-modules,stephen322/prosody-modules,Craige/prosody-modules,NSAKEY/prosody-modules
|
92bb8399f591f0bad12ea7bbd01dda34f220257c
|
test/dom/Node-isEqualNode.lua
|
test/dom/Node-isEqualNode.lua
|
local gumbo = require "gumbo"
local document = assert(gumbo.parse [[
<!DOCTYPE html>
<body>
<div class="example">
<ul>
<li><a href="http://example.com/" hidden>Example.com</a></li>
<li><a href="http://example.org/" hidden>Example.org</a></li>
</ul>
</div>
<div class="example">
<ul>
<li><a href="http://example.com/" hidden>Example.com</a></li>
<li><a href="http://example.org/" hidden>Example.org</a></li>
</ul>
</div>
</body>
]])
local divs = assert(document:getElementsByTagName("div"))
local div1 = assert(divs[1])
local div2 = assert(divs[2])
assert(not rawequal(div1, div2))
assert(div1:isEqualNode(div2))
assert(div2:isEqualNode(div1))
assert(div1:isEqualNode(div1))
assert(div2:isEqualNode(div2))
div1:setAttribute("id", "div1")
assert(not div1:isEqualNode(div2))
assert(not div2:isEqualNode(div1))
div2:setAttribute("id", "div2")
assert(not div1:isEqualNode(div2))
assert(not div2:isEqualNode(div1))
div1:removeAttribute("id")
div2:removeAttribute("id")
assert(div1:isEqualNode(div2))
assert(div2:isEqualNode(div1))
local clone = assert(div1:cloneNode(true))
assert(rawequal(div1, clone) == false)
assert(clone:isEqualNode(div1))
assert(clone:isEqualNode(div2))
assert(div1.childNodes.length == div2.childNodes.length)
div1.childNodes[2]:remove()
assert(div1.childNodes.length ~= div2.childNodes.length)
assert(not div1:isEqualNode(div2))
assert(not div2:isEqualNode(div1))
div1:appendChild(div2:cloneNode())
assert(div1.childNodes.length == div2.childNodes.length)
assert(not div1:isEqualNode(div2))
assert(not div2:isEqualNode(div1))
assert(not div1:isEqualNode())
assert(not div1:isEqualNode({}))
assert(not div1:isEqualNode(55))
assert(not div1:isEqualNode(false))
assert(not div1:isEqualNode("<div1>"))
|
local gumbo = require "gumbo"
local assert, rawequal = assert, rawequal
local _ENV = nil
local document = assert(gumbo.parse [[
<!DOCTYPE html>
<body>
<div class="example">
<ul>
<li><a href="http://example.com/" hidden>Example.com</a></li>
<li><a href="http://example.org/" hidden>Example.org</a></li>
</ul>
</div>
<div class="example">
<ul>
<li><a href="http://example.com/" hidden>Example.com</a></li>
<li><a href="http://example.org/" hidden>Example.org</a></li>
</ul>
</div>
</body>
]])
local divs = assert(document:getElementsByTagName("div"))
local div1 = assert(divs[1])
local div2 = assert(divs[2])
assert(not rawequal(div1, div2))
assert(div1:isEqualNode(div2))
assert(div2:isEqualNode(div1))
assert(div1:isEqualNode(div1))
assert(div2:isEqualNode(div2))
div1:setAttribute("id", "div1")
assert(not div1:isEqualNode(div2))
assert(not div2:isEqualNode(div1))
div2:setAttribute("id", "div2")
assert(not div1:isEqualNode(div2))
assert(not div2:isEqualNode(div1))
div1:removeAttribute("id")
div2:removeAttribute("id")
assert(div1:isEqualNode(div2))
assert(div2:isEqualNode(div1))
local clone = assert(div1:cloneNode(true))
assert(not rawequal(div1, clone))
assert(clone:isEqualNode(div1))
assert(clone:isEqualNode(div2))
assert(div1.childNodes.length == div2.childNodes.length)
div1.childNodes[2]:remove()
assert(div1.childNodes.length ~= div2.childNodes.length)
assert(not div1:isEqualNode(div2))
assert(not div2:isEqualNode(div1))
div1:appendChild(div2:cloneNode())
assert(div1.childNodes.length == div2.childNodes.length)
assert(not div1:isEqualNode(div2))
assert(not div2:isEqualNode(div1))
assert(not div1:isEqualNode())
assert(not div1:isEqualNode({}))
assert(not div1:isEqualNode(55))
assert(not div1:isEqualNode(false))
assert(not div1:isEqualNode("<div1>"))
|
Minor style fixes in test/dom/Node-isEqualNode.lua
|
Minor style fixes in test/dom/Node-isEqualNode.lua
|
Lua
|
apache-2.0
|
craigbarnes/lua-gumbo,craigbarnes/lua-gumbo,craigbarnes/lua-gumbo
|
3a5acd7927e811674a35363927c11b0eb6dc8cfb
|
config/nvim/after.lua
|
config/nvim/after.lua
|
local map = require('utils').map
local cmd = vim.cmd
-- " Commands
cmd([[colorscheme dracula]])
-- " Remove trailing spaces on save
cmd([[autocmd BufWritePre * :%s/\s\+$//e]])
-- " Common typos
cmd(':command! WQ wq')
cmd(':command! WQ wq')
cmd(':command! Wq wq')
cmd(':command! Wqa wqa')
cmd(':command! Qall qall')
cmd(':command! W w')
cmd(':command! Q q')
-- " Mappings
-- " Search under word
map('n', '<Leader>rg', '<ESC>:FZFRg<Space>', { noremap = true, silent = false })
map('n', '<Leader>rw', '<ESC>:FZFRg <C-R><C-W><enter>', { noremap = true, silent = false })
-- " Split window and file navigation
map('n', '<Leader>hh', ':split<CR>', {silent = true})
map('n', '<Leader>vv', ':vsplit<CR>', {silent = true})
map('n', '\\', ':NERDTreeToggle<CR>', {noremap = true, silent = true})
map('n', '\\f', ':NERDTreeFind<CR>', {noremap = true, silent = true})
map('n', '<leader><space>', ':Vipe<CR>', {silent = true})
-- " Switch between test and production code
map('n', '<Leader>.', ':A<CR>',{})
-- " Open nvim help
map( "n", ",h", [[<Cmd>lua require'telescope.builtin'.help_tags({results_title='Help Results'})<CR>]], { noremap = true, silent = true })
-- " Plugin Config
vim.g.gutentags_ctags_exclude = {
'*.git', '*.svg', '*.hg',
'*/tests/*',
'build',
'dist',
'*sites/*/files/*',
'bin',
'node_modules',
'bower_components',
'cache',
'compiled',
'docs',
'example',
'bundle',
'vendor',
'*.md',
'*-lock.json',
'*.lock',
'*bundle*.js',
'*build*.js',
'.*rc*',
'*.json',
'*.min.*',
'*.map',
'*.bak',
'*.zip',
'*.pyc',
'*.class',
'*.sln',
'*.Master',
'*.csproj',
'*.tmp',
'*.csproj.user',
'*.cache',
'*.pdb',
'tags*',
'cscope.*',
'*.exe', '*.dll',
'*.mp3', '*.ogg', '*.flac',
'*.swp', '*.swo',
'*.bmp', '*.gif', '*.ico', '*.jpg', '*.png',
'*.rar', '*.zip', '*.tar', '*.tar.gz', '*.tar.xz', '*.tar.bz2',
'*.pdf', '*.doc', '*.docx', '*.ppt', '*.pptx',
}
vim.g.gutentags_add_default_project_roots = false
vim.g.gutentags_project_root = {'package.json', '.git'}
vim.g.gutentags_cache_dir = vim.fn.expand('~/.cache/nvim/ctags/')
vim.g.gutentags_generate_on_new = true
vim.g.gutentags_generate_on_missing = true
vim.g.gutentags_generate_on_write = true
vim.g.gutentags_generate_on_empty_buffer = true
vim.cmd([[command! -nargs=0 GutentagsClearCache call system('rm ' . g:gutentags_cache_dir . '/*')]])
vim.g.gutentags_ctags_extra_args = {'--tag-relative=yes', '--fields=+ailmnS', }
require'lspconfig'.solargraph.setup{}
require'lspconfig'.sorbet.setup{}
require'lspconfig'.gopls.setup{}
|
local map = require('utils').map
local cmd = vim.cmd
-- " Commands
cmd([[colorscheme dracula]])
-- " Remove trailing spaces on save
cmd([[autocmd BufWritePre * :%s/\s\+$//e]])
-- " Common typos
cmd(':command! WQ wq')
cmd(':command! WQ wq')
cmd(':command! Wq wq')
cmd(':command! Wqa wqa')
cmd(':command! Qall qall')
cmd(':command! W w')
cmd(':command! Q q')
-- " Mappings
-- " Search under word
map('n', '<Leader>rg', '<ESC>:FZFRg<Space>', { noremap = true, silent = false })
map('n', '<Leader>rw', '<ESC>:FZFRg <C-R><C-W><enter>', { noremap = true, silent = false })
-- " Split window and file navigation
map('n', '<Leader>hh', ':split<CR>', {silent = true})
map('n', '<Leader>vv', ':vsplit<CR>', {silent = true})
map('n', '\\', ':NERDTreeToggle<CR>', {noremap = true, silent = true})
map('n', '\\f', ':NERDTreeFind<CR>', {noremap = true, silent = true})
map('n', '<leader><space>', ':Vipe<CR>', {silent = true})
-- " Switch between test and production code
map('n', '<Leader>.', ':A<CR>',{})
-- " Open nvim help
map( "n", ",h", [[<Cmd>lua require'telescope.builtin'.help_tags({results_title='Help Results'})<CR>]], { noremap = true, silent = true })
-- " Plugin Config
vim.g.gutentags_ctags_exclude = {
'*.git', '*.svg', '*.hg',
'*/tests/*',
'build',
'dist',
'*sites/*/files/*',
'bin',
'node_modules',
'bower_components',
'cache',
'compiled',
'docs',
'example',
'bundle',
'vendor',
'*.md',
'*-lock.json',
'*.lock',
'*bundle*.js',
'*build*.js',
'.*rc*',
'*.json',
'*.min.*',
'*.map',
'*.bak',
'*.zip',
'*.pyc',
'*.class',
'*.sln',
'*.Master',
'*.csproj',
'*.tmp',
'*.csproj.user',
'*.cache',
'*.pdb',
'tags*',
'cscope.*',
'*.exe', '*.dll',
'*.mp3', '*.ogg', '*.flac',
'*.swp', '*.swo',
'*.bmp', '*.gif', '*.ico', '*.jpg', '*.png',
'*.rar', '*.zip', '*.tar', '*.tar.gz', '*.tar.xz', '*.tar.bz2',
'*.pdf', '*.doc', '*.docx', '*.ppt', '*.pptx',
}
vim.g.gutentags_add_default_project_roots = false
vim.g.gutentags_project_root = {'package.json', '.git'}
vim.g.gutentags_cache_dir = vim.fn.expand('~/.cache/nvim/ctags/')
vim.g.gutentags_generate_on_new = true
vim.g.gutentags_generate_on_missing = true
vim.g.gutentags_generate_on_write = true
vim.g.gutentags_generate_on_empty_buffer = true
vim.cmd([[command! -nargs=0 GutentagsClearCache call system('rm ' . g:gutentags_cache_dir . '/*')]])
vim.g.gutentags_ctags_extra_args = {'--tag-relative=yes', '--fields=+ailmnS', }
require'lspconfig'.solargraph.setup{}
require'lspconfig'.sorbet.setup{cmd = { 'srb', 'tc', '--lsp' ,'.'},}
require'lspconfig'.gopls.setup{}
|
Fix sorbet complaints about not providing a dir
|
Fix sorbet complaints about not providing a dir
|
Lua
|
mit
|
albertoleal/dotfiles,albertoleal/dotfiles
|
5853249c6950fcaffaa1ef15bf41d18c3824429e
|
nvim/lua/ryankoval/init.lua
|
nvim/lua/ryankoval/init.lua
|
vim.g.mapleader = ','
vim.opt.termguicolors = true
require('ryankoval.theme')
require('ryankoval.cmp')
require('ryankoval.gitsigns')
require('ryankoval.neotree')
require('ryankoval.treesitter')
require('ryankoval.indent-blankline')
require('ryankoval.telescope')
require('ryankoval.telescope.mappings')
require('ryankoval.lsp')
require('ryankoval.luasnip')
require('ryankoval.lualine')
require('ryankoval.barbar')
require('ryankoval.scrollbar')
require('ryankoval.nvim-autopairs')
require('ryankoval.custom.font')
require('ryankoval.custom.copy_filename_to_clipboard')
require('ryankoval.custom.add_log')
local parsers = require('nvim-treesitter.parsers')
local configs = parsers.get_parser_configs()
local ft_str = table.concat(
vim.tbl_map(function(ft)
return configs[ft].filetype or ft
end, parsers.available_parsers()),
','
)
vim.cmd('autocmd Filetype ' .. ft_str .. ' setlocal foldmethod=expr foldexpr=nvim_treesitter#foldexpr()')
local opts = { noremap = true }
-- open help in new tab
vim.cmd(':cabbrev help tab help')
vim.keymap.set('', '<Backspace>', '10k', opts)
vim.keymap.set('', '<Space>', '10j', opts)
-- reflow paragraph with Q in normal and visual mode
vim.keymap.set('n', 'Q', 'gqap', opts)
vim.keymap.set('x', 'Q', 'gq', opts)
-- sane movement with wrap turned on
vim.keymap.set('n', 'j', 'gj', opts)
vim.keymap.set('n', 'k', 'gk', opts)
vim.keymap.set('x', 'j', 'gj', opts)
vim.keymap.set('x', 'k', 'gk', opts)
vim.keymap.set('n', '<Down>', 'gj', opts)
vim.keymap.set('n', '<Up>', 'gk', opts)
vim.keymap.set('x', '<Down>', 'gj', opts)
vim.keymap.set('x', '<Up>', 'gk', opts)
vim.keymap.set('i', '<Down>', '<C-o>gj', opts)
vim.keymap.set('i', '<Up>', '<C-o>gk', opts)
-- tab indents
vim.keymap.set('n', '<TAB>', '>>', opts)
vim.keymap.set('x', '<TAB>', '>gv', opts)
vim.keymap.set('x', '<S-TAB>', '<gv', opts)
vim.keymap.set('i', '<S-TAB>', '<C-d>', opts)
-- map jk to leave insert mode
vim.keymap.set('i', 'jk', '<Esc>', {})
vim.keymap.set('i', 'Jk', '<Esc>', {})
vim.keymap.set('n', 'K', '<Esc>', {})
-- cmd+w should delete the buffer
vim.keymap.set('i', '<D-w>', '<esc>:bdelete<cr>', opts)
vim.keymap.set('n', '<D-w>', ':bdelete<cr>', opts)
vim.keymap.set('v', '<D-w>', ':bdelete<cr>', opts)
-- map find hotkeys
vim.keymap.set('n', '<D-f>', '/', {})
vim.keymap.set('n', '<D-r>', ':,$s/<C-r><C-w>//gc<Left><Left><Left>', {})
vim.keymap.set('x', '<D-r>', ':s/<C-r><C-w>//gc<Left><Left><Left>', {})
-- swap mark keys
vim.keymap.set('n', '`', "'", opts)
vim.keymap.set('n', "'", '`', opts)
|
vim.g.mapleader = ','
vim.opt.termguicolors = true
require('ryankoval.theme')
require('ryankoval.cmp')
require('ryankoval.gitsigns')
require('ryankoval.neotree')
require('ryankoval.treesitter')
require('ryankoval.indent-blankline')
require('ryankoval.telescope')
require('ryankoval.telescope.mappings')
require('ryankoval.lsp')
require('ryankoval.luasnip')
require('ryankoval.lualine')
require('ryankoval.barbar')
require('ryankoval.scrollbar')
require('ryankoval.nvim-autopairs')
require('ryankoval.custom.font')
require('ryankoval.custom.copy_filename_to_clipboard')
require('ryankoval.custom.add_log')
local parsers = require('nvim-treesitter.parsers')
local configs = parsers.get_parser_configs()
local ft_str = table.concat(
vim.tbl_map(function(ft)
return configs[ft].filetype or ft
end, parsers.available_parsers()),
','
)
vim.cmd('autocmd Filetype ' .. ft_str .. ' setlocal foldmethod=expr foldexpr=nvim_treesitter#foldexpr()')
local opts = { noremap = true }
-- open help in new tab
vim.cmd(':cabbrev help tab help')
vim.keymap.set('', '<Backspace>', '10k', opts)
vim.keymap.set('', '<Space>', '10j', opts)
-- reflow paragraph with Q in normal and visual mode
vim.keymap.set('n', 'Q', 'gqap', opts)
vim.keymap.set('x', 'Q', 'gq', opts)
-- sane movement with wrap turned on
vim.keymap.set('n', 'j', 'gj', opts)
vim.keymap.set('n', 'k', 'gk', opts)
vim.keymap.set('x', 'j', 'gj', opts)
vim.keymap.set('x', 'k', 'gk', opts)
vim.keymap.set('n', '<Down>', 'gj', opts)
vim.keymap.set('n', '<Up>', 'gk', opts)
vim.keymap.set('x', '<Down>', 'gj', opts)
vim.keymap.set('x', '<Up>', 'gk', opts)
vim.keymap.set('i', '<Down>', '<C-o>gj', opts)
vim.keymap.set('i', '<Up>', '<C-o>gk', opts)
-- tab indents
vim.keymap.set('n', '<TAB>', '>>', opts)
vim.keymap.set('x', '<TAB>', '>gv', opts)
vim.keymap.set('x', '<S-TAB>', '<gv', opts)
vim.keymap.set('i', '<S-TAB>', '<C-d>', opts)
-- map jk to leave insert mode
vim.keymap.set('i', 'jk', '<Esc>', {})
vim.keymap.set('i', 'Jk', '<Esc>', {})
vim.keymap.set('n', 'K', '<Esc>', {})
-- cmd+w should delete the buffer
vim.keymap.set('i', '<D-w>', '<esc>:bdelete<cr>', opts)
vim.keymap.set('n', '<D-w>', ':bdelete<cr>', opts)
vim.keymap.set('v', '<D-w>', ':bdelete<cr>', opts)
-- map find hotkeys
vim.keymap.set('n', '<D-f>', '/', {})
vim.keymap.set('n', '<D-r>', ':,$s/<C-r><C-w>//gc<Left><Left><Left>', {})
vim.keymap.set('x', '<D-r>', ':s/<C-r><C-w>//gc<Left><Left><Left>', {})
-- swap mark keys
vim.keymap.set('n', '`', "'", opts)
vim.keymap.set('n', "'", '`', opts)
-- split navigation
vim.keymap.set('n', '<c-h>', ':wincmd h<cr>', opts)
vim.keymap.set('n', '<c-j>', ':wincmd j<cr>', opts)
vim.keymap.set('n', '<c-k>', ':wincmd k<cr>', opts)
vim.keymap.set('n', '<c-l>', ':wincmd l<cr>', opts)
|
fixed split navigation
|
fixed split navigation
|
Lua
|
mit
|
rkoval/dotfiles,rkoval/dotfiles,rkoval/dotfiles
|
f87f7415eb8fc3f1b96f28a40a7537dd57e0876f
|
PairwiseDistance.lua
|
PairwiseDistance.lua
|
local PairwiseDistance, parent = torch.class('nn.PairwiseDistance', 'nn.Module')
function PairwiseDistance:__init(p)
parent.__init(self)
-- state
self.gradInput = {torch.Tensor(), torch.Tensor()}
self.output = torch.Tensor(1)
self.diff = torch.Tensor()
self.norm=p
end
function PairwiseDistance:updateOutput(input)
if input[1]:dim() == 1 then
self.output[1]=input[1]:dist(input[2],self.norm)
elseif input[1]:dim() == 2 then
self.diff = self.diff or input[1].new()
self.diff:resizeAs(input[1])
local diff = self.diff:zero()
diff:add(input[1], -1, input[2])
diff:abs()
self.output:resize(input[1]:size(1))
self.output:zero()
self.output:add(diff:pow(self.norm):sum(2))
self.output:pow(1./self.norm)
else
error('input must be vector or matrix')
end
if input[1]:dim() > 2 then
error('input must be vector or matrix')
end
return self.output
end
local function mathsign(x)
if x==0 then return 2*torch.random(2)-3; end
if x>0 then return 1; else return -1; end
end
function PairwiseDistance:updateGradInput(input, gradOutput)
if input[1]:dim() > 2 then
error('input must be vector or matrix')
end
self.gradInput[1]:resize(input[1]:size())
self.gradInput[2]:resize(input[2]:size())
self.gradInput[1]:copy(input[1])
self.gradInput[1]:add(-1, input[2])
if self.norm==1 then
self.gradInput[1]:apply(mathsign)
else
-- Note: derivative of p-norm:
-- d/dx_k(||x||_p) = (x_k * abs(x_k)^(p-2)) / (||x||_p)^(p-1)
if (self.norm > 2) then
self.gradInput[1]:cmul(self.gradInput[1]:clone():abs():pow(self.norm-2))
end
if (input[1]:dim() > 1) then
self.outExpand = self.outExpand or self.output.new()
self.outExpand:resize(self.output:size(1), 1)
self.outExpand:copy(self.output)
self.outExpand:add(1.0e-6) -- Prevent divide by zero errors
self.outExpand:pow(-(self.norm-1))
self.gradInput[1]:cmul(self.outExpand:expand(self.gradInput[1]:size(1),
self.gradInput[1]:size(2)))
else
self.gradInput[1]:mul(math.pow(self.output[1] + 1e-6, -(self.norm-1)))
end
end
if input[1]:dim() == 1 then
self.gradInput[1]:mul(gradOutput[1])
else
self.grad = self.grad or gradOutput.new()
self.ones = self.ones or gradOutput.new()
self.grad:resizeAs(input[1]):zero()
self.ones:resize(input[1]:size(2)):fill(1)
self.grad:addr(gradOutput, self.ones)
self.gradInput[1]:cmul(self.grad)
end
self.gradInput[2]:zero():add(-1, self.gradInput[1])
return self.gradInput
end
|
local PairwiseDistance, parent = torch.class('nn.PairwiseDistance', 'nn.Module')
function PairwiseDistance:__init(p)
parent.__init(self)
-- state
self.gradInput = {torch.Tensor(), torch.Tensor()}
self.output = torch.Tensor(1)
self.diff = torch.Tensor()
self.norm=p
end
function PairwiseDistance:updateOutput(input)
if input[1]:dim() == 1 then
self.output[1]=input[1]:dist(input[2],self.norm)
elseif input[1]:dim() == 2 then
self.diff = self.diff or input[1].new()
self.diff:resizeAs(input[1])
local diff = self.diff:zero()
diff:add(input[1], -1, input[2])
diff:abs()
self.output:resize(input[1]:size(1))
self.output:zero()
self.output:add(diff:pow(self.norm):sum(2))
self.output:pow(1./self.norm)
else
error('input must be vector or matrix')
end
if input[1]:dim() > 2 then
error('input must be vector or matrix')
end
return self.output
end
local function mathsign(x)
if x==0 then return 2*torch.random(2)-3; end
if x>0 then return 1; else return -1; end
end
function PairwiseDistance:updateGradInput(input, gradOutput)
if input[1]:dim() > 2 then
error('input must be vector or matrix')
end
self.gradInput[1]:resize(input[1]:size())
self.gradInput[2]:resize(input[2]:size())
self.gradInput[1]:copy(input[1])
self.gradInput[1]:add(-1, input[2])
if self.norm==1 then
self.gradInput[1]:apply(mathsign)
else
-- Note: derivative of p-norm:
-- d/dx_k(||x||_p) = (x_k * abs(x_k)^(p-2)) / (||x||_p)^(p-1)
if (self.norm > 2) then
self.gradInput[1]:cmul(self.gradInput[1]:clone():abs():pow(self.norm-2))
end
if (input[1]:dim() > 1) then
self.outExpand = self.outExpand or self.output.new()
self.outExpand:resize(self.output:size(1), 1)
self.outExpand:copy(self.output)
self.outExpand:add(1.0e-6) -- Prevent divide by zero errors
self.outExpand:pow(-(self.norm-1))
self.gradInput[1]:cmul(self.outExpand:expand(self.gradInput[1]:size(1),
self.gradInput[1]:size(2)))
else
self.gradInput[1]:mul(math.pow(self.output[1] + 1e-6, -(self.norm-1)))
end
end
if input[1]:dim() == 1 then
self.gradInput[1]:mul(gradOutput[1])
else
self.grad = self.grad or gradOutput.new()
self.ones = self.ones or gradOutput.new()
self.grad:resizeAs(input[1]):zero()
self.ones:resize(input[1]:size(2)):fill(1)
self.grad:addr(gradOutput, self.ones)
self.gradInput[1]:cmul(self.grad)
end
self.gradInput[2]:zero():add(-1, self.gradInput[1])
return self.gradInput
end
-- save away Module:type(type) for later use.
PairwiseDistance._parent_type = parent.type
-- Fix the bug where tmp = nn.PairwiseDistance:cuda() fails to convert table
-- contents. We could, and probably should, change Module.lua to loop over
-- and convert all the table elements in a module, but that might have
-- repercussions, so this is a safer solution.
function PairwiseDistance:type(type)
self:_parent_type(type) -- Call the parent (Module) type function
-- Now convert the left over table elements
self.gradInput[1] = self.gradInput[1]:type(type)
self.gradInput[2] = self.gradInput[2]:type(type)
end
|
Fixed a bug in PairwiseDistance where the gradInput table isn't converted when Module.type function is called (this bug has always existed and is not due to the recent changes).
|
Fixed a bug in PairwiseDistance where the gradInput table isn't converted when Module.type function is called (this bug has always existed and is not due to the recent changes).
|
Lua
|
bsd-3-clause
|
zhangxiangxiao/nn,lvdmaaten/nn,jzbontar/nn,boknilev/nn,PierrotLC/nn,jhjin/nn,nicholas-leonard/nn,witgo/nn,Aysegul/nn,bartvm/nn,xianjiec/nn,PraveerSINGH/nn,karpathy/nn,lukasc-ch/nn,jonathantompson/nn,rotmanmi/nn,Moodstocks/nn,kmul00/nn,EnjoyHacking/nn,caldweln/nn,davidBelanger/nn,andreaskoepf/nn,forty-2/nn,apaszke/nn,colesbury/nn,hughperkins/nn,elbamos/nn,Jeffyrao/nn,GregSatre/nn,mys007/nn,joeyhng/nn,szagoruyko/nn,clementfarabet/nn,zchengquan/nn,sagarwaghmare69/nn,eriche2016/nn,diz-vara/nn,mlosch/nn,adamlerer/nn,vgire/nn,eulerreich/nn,LinusU/nn,abeschneider/nn,hery/nn,douwekiela/nn,noa/nn,rickyHong/nn_lib_torch,soumith/nn,aaiijmrtt/nn,ivendrov/nn,ominux/nn,sbodenstein/nn,Djabbz/nn,fmassa/nn
|
d09db0de3073d275c7ce4517e6212c3640745598
|
util.lua
|
util.lua
|
local computer = require("computer")
local event = require("event")
local function trunc(num, numDecimalPlaces)
local mult = 10^(numDecimalPlaces or 0)
return math.floor(num * mult) / mult
end
local function needsCharging(threshold, distanceFromCharger)
distanceFromCharger = distanceFromCharger or 0
local percentCharge = (computer.energy() / computer.maxEnergy())
-- require additional 1% charge per 25 blocks distance to charger
local minCharge = threshold - (distanceFromCharger / 25 / 100)
if percentCharge <= minCharge then
return true
end
return false
end
local function waitUntilCharge(threshold, maxWaitSeconds)
maxWaitSeconds = maxWaitSeconds or 300
while maxWaitSeconds > 0 do
local percentCharge = (computer.energy() / computer.maxEnergy())
if (percentCharge >= threshold) then
return true
end
maxWaitSeconds = maxWaitSeconds - 1
event.pull(1, "_chargewait")
end
local percentCharge = (computer.energy() / computer.maxEnergy())
return percentCharge >= threshold
end
return {
trunc = trunc,
needsCharging = needsCharging,
waitUntilCharge = waitUntilCharge
}
|
local computer = require("computer")
local event = require("event")
local function trunc(num, numDecimalPlaces)
local mult = 10^(numDecimalPlaces or 0)
return math.floor(num * mult) / mult
end
local function needsCharging(threshold, distanceFromCharger)
distanceFromCharger = distanceFromCharger or 0
local percentCharge = (computer.energy() / computer.maxEnergy())
-- require additional 1% charge per 25 blocks distance to charger
if (percentCharge - ((distanceFromCharger / 25) / 100)) <= threshold then
return true
end
return false
end
local function waitUntilCharge(threshold, maxWaitSeconds)
maxWaitSeconds = maxWaitSeconds or 300
while maxWaitSeconds > 0 do
local percentCharge = (computer.energy() / computer.maxEnergy())
if (percentCharge >= threshold) then
return true
end
maxWaitSeconds = maxWaitSeconds - 1
event.pull(1, "_chargewait")
end
local percentCharge = (computer.energy() / computer.maxEnergy())
return percentCharge >= threshold
end
return {
trunc = trunc,
needsCharging = needsCharging,
waitUntilCharge = waitUntilCharge
}
|
attempting to fix charging util
|
attempting to fix charging util
|
Lua
|
apache-2.0
|
InfinitiesLoop/oclib
|
c7b1c25b16cec957763cf4413da2f90ed11869ca
|
share/util/resolve_redirections.lua
|
share/util/resolve_redirections.lua
|
-- libquvi-scripts
-- Copyright (C) 2012 Toni Gundogdu <[email protected]>
--
-- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>.
--
-- This library is free software; you can redistribute it and/or
-- modify it under the terms of the GNU Lesser General Public
-- License as published by the Free Software Foundation; either
-- version 2.1 of the License, or (at your option) any later version.
--
-- This library is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-- Lesser General Public License for more details.
--
-- You should have received a copy of the GNU Lesser General Public
-- License along with this library; if not, write to the Free Software
-- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
-- 02110-1301 USA
--
local ResolveExceptions = {} -- Utility functions unique to this script
function resolve_redirections(qargs)
-- Let libcURL resolve the URL redirections for us.
local resolved, dst = quvi.resolve(qargs.input_url)
if not resolved then return qargs.input_url end
-- Apply any exception rules to the destination URL.
return ResolveExceptions.YouTube(qargs, dst)
end
--
-- Utility functions
--
function ResolveExceptions.YouTube(qargs, dst)
-- Preserve the t= parameter (if any). The g00gle servers
-- strip them from the destination URL after redirecting.
-- e.g. http://www.youtube.com/watch?v=LWxTGJ3TK1U#t=2m22s
-- -> http://www.youtube.com/watch?v=LWxTGJ3TK1U
return dst .. (qargs.input_url:match('(#t=%w+)') or '')
end
-- vim: set ts=2 sw=2 tw=72 expandtab:
|
-- libquvi-scripts
-- Copyright (C) 2012 Toni Gundogdu <[email protected]>
--
-- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>.
--
-- This library is free software; you can redistribute it and/or
-- modify it under the terms of the GNU Lesser General Public
-- License as published by the Free Software Foundation; either
-- version 2.1 of the License, or (at your option) any later version.
--
-- This library is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-- Lesser General Public License for more details.
--
-- You should have received a copy of the GNU Lesser General Public
-- License along with this library; if not, write to the Free Software
-- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
-- 02110-1301 USA
--
local ResolveExceptions = {} -- Utility functions unique to this script
function resolve_redirections(qargs)
-- Let libcURL resolve the URL redirections for us.
local resolved, dst = quvi.resolve(qargs.input_url)
if not resolved then return qargs.input_url end
-- Apply any exception rules to the destination URL.
return ResolveExceptions.YouTube(qargs, dst)
end
--
-- Utility functions
--
function ResolveExceptions.YouTube(qargs, dst)
-- [UPDATE] 2012-11-18: g00gle servers seem not to strip the #t anymore
return dst
--[[
-- Preserve the t= parameter (if any). The g00gle servers
-- strip them from the destination URL after redirecting.
-- e.g. http://www.youtube.com/watch?v=LWxTGJ3TK1U#t=2m22s
-- -> http://www.youtube.com/watch?v=LWxTGJ3TK1U
return dst .. (qargs.input_url:match('(#t=%w+)') or '')
]]--
end
-- vim: set ts=2 sw=2 tw=72 expandtab:
|
FIX: resolve_redirections.lua: Do not append #t
|
FIX: resolve_redirections.lua: Do not append #t
g00gle servers seem not to strip the #t parameter anymore. Do not append
the #t parameter anymore. Comment out the code, in case this needs to
be reactivated.
Signed-off-by: Toni Gundogdu <[email protected]>
|
Lua
|
agpl-3.0
|
alech/libquvi-scripts,alech/libquvi-scripts,legatvs/libquvi-scripts,legatvs/libquvi-scripts
|
de63097f0411c6fba9158d28b56c14d9768f125a
|
examples/moonsniff/traffic-gen.lua
|
examples/moonsniff/traffic-gen.lua
|
--- Demonstrates and tests hardware timestamping capabilities
local lm = require "libmoon"
local device = require "device"
local memory = require "memory"
local ts = require "timestamping"
local hist = require "histogram"
local timer = require "timer"
local log = require "log"
local stats = require "stats"
local PKT_LEN = 100 -- in byte
function configure(parser)
parser:description("Generate traffic which can be used by moonsniff to establish latencies induced by a device under test.")
parser:argument("dev", "Devices to use."):args(2):convert(tonumber)
parser:option("-r --runtime", "Determines how long packets will be send in seconds."):args(1):convert(tonumber):default(10)
parser:option("-s --sendrate", "Approximate send rate in mbit/s. Due to IFG etc. rate on the wire may be higher."):args(1):convert(tonumber):default(1000)
return parser:parse()
end
function master(args)
args.dev[1] = device.config{port = args.dev[1], txQueues = 1}
args.dev[2] = device.config{port = args.dev[2], rxQueues = 1}
device.waitForLinks()
local dev0tx = args.dev[1]:getTxQueue(0)
local dev1rx = args.dev[2]:getRxQueue(0)
stats.startStatsTask{txDevices = {args.dev[1]}, rxDevices = {args.dev[2]}}
local sender0 = lm.startTask("generateTraffic", dev0tx, args)
sender0:wait()
end
function generateTraffic(queue, args)
log:info("Trying to enable rx timestamping of all packets, this isn't supported by most nics")
local pkt_id = 0
local runtime = timer:new(args.runtime)
local hist = hist:new()
local mempool = memory.createMemPool(function(buf)
buf:getUdpPacket():fill{
pktLength = PKT_LEN;
}
end)
local bufs = mempool:bufArray()
if lm.running() then
lm.sleepMillis(500)
end
log:info("Trying to generate ~" .. args.sendrate .. " mbit/s")
queue:setRate(args.sendrate)
local runtime = timer:new(args.runtime)
while lm.running() and runtime:running() do
bufs:alloc(PKT_LEN)
for i, buf in ipairs(bufs) do
local pkt = buf:getUdpPacket()
pkt.payload.uint32[0] = pkt_id
pkt_id = pkt_id + 1
end
queue:send(bufs)
end
end
|
--- Demonstrates and tests hardware timestamping capabilities
local lm = require "libmoon"
local device = require "device"
local memory = require "memory"
local ts = require "timestamping"
local hist = require "histogram"
local timer = require "timer"
local log = require "log"
local stats = require "stats"
local bit = require "bit"
local PKT_LEN = 100 -- in byte
local band = bit.band
function configure(parser)
parser:description("Generate traffic which can be used by moonsniff to establish latencies induced by a device under test.")
parser:argument("dev", "Devices to use."):args(2):convert(tonumber)
parser:option("-r --runtime", "Determines how long packets will be send in seconds."):args(1):convert(tonumber):default(10)
parser:option("-s --sendrate", "Approximate send rate in mbit/s. Due to IFG etc. rate on the wire may be higher."):args(1):convert(tonumber):default(1000)
return parser:parse()
end
function master(args)
args.dev[1] = device.config{port = args.dev[1], txQueues = 1}
args.dev[2] = device.config{port = args.dev[2], rxQueues = 1}
device.waitForLinks()
local dev0tx = args.dev[1]:getTxQueue(0)
local dev1rx = args.dev[2]:getRxQueue(0)
stats.startStatsTask{txDevices = {args.dev[1]}, rxDevices = {args.dev[2]}}
local sender0 = lm.startTask("generateTraffic", dev0tx, args)
sender0:wait()
end
function generateTraffic(queue, args)
log:info("Trying to enable rx timestamping of all packets, this isn't supported by most nics")
local pkt_id = 0
local runtime = timer:new(args.runtime)
local hist = hist:new()
local mempool = memory.createMemPool(function(buf)
buf:getUdpPacket():fill{
pktLength = PKT_LEN;
}
end)
local bufs = mempool:bufArray()
if lm.running() then
lm.sleepMillis(500)
end
log:info("Trying to generate ~" .. args.sendrate .. " mbit/s")
queue:setRate(args.sendrate)
local runtime = timer:new(args.runtime)
while lm.running() and runtime:running() do
bufs:alloc(PKT_LEN)
for i, buf in ipairs(bufs) do
local pkt = buf:getUdpPacket()
-- for setters to work correctly, the number is not allowed to exceed 16 bit
pkt.ip4:setID(band(pkt_id, 0xFFFF))
pkt.payload.uint32[0] = pkt_id
pkt_id = pkt_id + 1
end
queue:send(bufs)
end
end
|
fix counter showing values twice
|
fix counter showing values twice
|
Lua
|
mit
|
gallenmu/MoonGen,gallenmu/MoonGen,emmericp/MoonGen,emmericp/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen,emmericp/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen
|
64be8bc5409364e37b511fa130dec7777b072252
|
wyx/ui/TooltipFactory.lua
|
wyx/ui/TooltipFactory.lua
|
local Class = require 'lib.hump.class'
local Tooltip = getClass 'wyx.ui.Tooltip'
local Text = getClass 'wyx.ui.Text'
local Bar = getClass 'wyx.ui.Bar'
local Frame = getClass 'wyx.ui.Frame'
local Style = getClass 'wyx.ui.Style'
local property = require 'wyx.component.property'
local math_ceil = math.ceil
local colors = colors
-- some constants
local MARGIN = 16
local MINWIDTH = 300
-- Common styles for tooltips
local tooltipStyle = Style({
bgcolor = colors.BLACK_A85,
bordersize = 4,
borderinset = 4,
bordercolor = colors.GREY30,
})
local header1Style = Style({
font = GameFont.small,
fontcolor = colors.WHITE,
})
local header2Style = header1Style:clone({
fontcolor = colors.GREY90,
})
local textStyle = Style({
font = GameFont.verysmall,
fontcolor = colors.GREY80,
})
local iconStyle = Style({
bordersize = 2,
bordercolor = colors.GREY60,
bgcolor = colors.GREY10,
fgcolor = colors.WHITE,
})
local healthBarStyle = Style({
fgcolor = colors.RED,
bgcolor = colors.DARKRED,
})
-- TooltipFactory
--
local TooltipFactory = Class{name='TooltipFactory',
function(self)
end
}
-- destructor
function TooltipFactory:destroy()
end
-- make a tooltip for an entity
function TooltipFactory:makeEntityTooltip(entity)
local entity = type(id) == 'number' and EntityRegistry:get(id) or id
verifyClass('wyx.entity.Entity', entity)
local name = entity:getName()
local family = entity:getFamily()
local kind = entity:getKind()
local description = entity:getDescription()
local headerW = 0
-- make the icon
local icon
local image = entity:query(property('TileSet'))
if image then
local allcoords = entity:query(property('TileCoords'))
local coords = allcoords and allcoords[1]
if coords then
local size = entity:query(property('TileSize'))
if size then
local x, y = (coords[1]-1) * size, (coords[2]-1) * size
icon = self:_makeIcon(image, x, y, size, size)
else
warning('makeEntityTooltip: bad TileSize property in entity %q', name)
end
else
warning('makeEntityTooltip: bad TileCoords property in entity %q', name)
end
else
warning('makeEntityTooltip: bad TileSet property in entity %q', name)
end
-- make the first header
local header1
if name then
header1 = self:_makeHeader1(name)
headerW = header1:getWidth()
else
warning('makeEntityTooltip: bad Name for entity %q', tostring(entity))
end
-- make the second header
local header2
if family and kind then
local string = family..' ('..kind..')'
header2 = self:_makeHeader2(string)
local width = header2:getWidth()
headerW = width > headerW and width or headerW
else
warning('makeEntityTooltip: missing family or kind for entity %q', name)
end
headerW = icon and headerW + icon:getWidth() + MARGIN or headerW
local width = headerW > MINWIDTH and headerW or MINWIDTH
-- make the health bar
local health = entity:query(property('Health'))
local maxHealth = entity:query(property('MaxHealth'))
local healthBar
if health and maxHealth then
healthBar = Bar(0, 0, width, margin)
healthBar:setNormalStyle(healthBarStyle)
healthBar:setLimits(0, maxHealth)
healthBar:setValue(health)
end
-- make the stats frames
-- TODO
-- make the description
local body
if description then
body = self:_makeText(description, width)
else
warning('makeEntityTooltip: missing description for entity %q', name)
end
-- make the tooltip
local tooltip = Tooltip()
tooltip:setNormalStyle(tooltipStyle)
tooltip:setMargin(MARGIN)
if icon then tooltip:setIcon(icon) end
if header1 then tooltip:setHeader1(header1) end
if header2 then tooltip:setHeader2(header2) end
if healthBar then tooltip:addBar(healthBar) end
if stats then
for i=1,numStats do
local stat = stats[i]
tooltip:addText(stat)
end
end
if body then
if stats then tooltip:addSpace() end
tooltip:addText(body)
end
return tooltip
end
-- make a simple generic tooltip with a header and text
function TooltipFactory:makeSimpleTooltip(header, text)
verify('string', header, text)
local header1 = self:_makeHeader1(header)
local headerW = header1:getWidth()
local width = headerW > MINWIDTH and headerW or MINWIDTH
local body = self:_makeText(text, width)
local tooltip = Tooltip()
tooltip:setNormalStyle(tooltipStyle)
tooltip:setMargin(MARGIN)
if header1 then tooltip:setHeader1(header1) end
if body then tooltip:addText(body) end
return tooltip
end
-- make an icon frame
function TooltipFactory:_makeIcon(image, x, y, w, h)
local style = iconStyle:clone({fgimage = image})
style:setFGQuad(x, y, w, h)
local icon = Frame(0, 0, w, h)
icon:setNormalStyle(style, true)
return icon
end
-- make a header1 Text frame
function TooltipFactory:_makeHeader1(text)
local font = header1Style:getFont()
local fontH = font:getHeight()
local width = font:getWidth(text)
local header1 = Text(0, 0, width, fontH)
header1:setNormalStyle(header1Style)
header1:setText(text)
return header1
end
-- make a header2 Text frame
function TooltipFactory:_makeHeader2(text)
local font = header2Style:getFont()
local fontH = font:getHeight()
local width = font:getWidth(text)
local header2 = Text(0, 0, width, fontH)
header2:setNormalStyle(header2Style)
header2:setText(text)
return header2
end
-- make a generic Text frame
function TooltipFactory:_makeText(text, width)
local font = textStyle:getFont()
local fontH = font:getHeight()
local fontW = font:getWidth(text)
width = width or fontW
local numLines = math_ceil(fontW / width)
local line = Text(0, 0, width, numLines * fontH)
line:setMaxLines(numLines)
line:setNormalStyle(textStyle)
line:setText(text)
return line
end
-- the class
return TooltipFactory
|
local Class = require 'lib.hump.class'
local Tooltip = getClass 'wyx.ui.Tooltip'
local Text = getClass 'wyx.ui.Text'
local Bar = getClass 'wyx.ui.Bar'
local Frame = getClass 'wyx.ui.Frame'
local Style = getClass 'wyx.ui.Style'
local property = require 'wyx.component.property'
local math_ceil = math.ceil
local colors = colors
-- some constants
local MARGIN = 16
local MINWIDTH = 300
-- Common styles for tooltips
local tooltipStyle = Style({
bgcolor = colors.BLACK_A85,
bordersize = 4,
borderinset = 4,
bordercolor = colors.GREY30,
})
local header1Style = Style({
font = GameFont.small,
fontcolor = colors.WHITE,
})
local header2Style = header1Style:clone({
fontcolor = colors.GREY90,
})
local textStyle = Style({
font = GameFont.verysmall,
fontcolor = colors.GREY80,
})
local iconStyle = Style({
bordersize = 2,
bordercolor = colors.GREY60,
bgcolor = colors.GREY10,
fgcolor = colors.WHITE,
})
local healthBarStyle = Style({
fgcolor = colors.RED,
bgcolor = colors.DARKRED,
})
-- TooltipFactory
--
local TooltipFactory = Class{name='TooltipFactory',
function(self)
end
}
-- destructor
function TooltipFactory:destroy()
end
-- make a tooltip for an entity
function TooltipFactory:makeEntityTooltip(entity)
local entity = type(id) == 'number' and EntityRegistry:get(id) or id
verifyClass('wyx.entity.Entity', entity)
local name = entity:getName()
local family = entity:getFamily()
local kind = entity:getKind()
local description = entity:getDescription()
local headerW = 0
-- make the icon
local icon
local image = entity:query(property('TileSet'))
if image then
local allcoords = entity:query(property('TileCoords'))
local coords
local coords = allcoords.item
or allcoords.front
or allcoords.right
or allcoords.left
if not coords then
for k in pairs(allcoords) do coords = allcoords[k]; break end
end
if coords then
local size = entity:query(property('TileSize'))
if size then
local x, y = (coords[1]-1) * size, (coords[2]-1) * size
icon = self:_makeIcon(image, x, y, size, size)
else
warning('makeEntityTooltip: bad TileSize property in entity %q', name)
end
else
warning('makeEntityTooltip: bad TileCoords property in entity %q', name)
end
else
warning('makeEntityTooltip: bad TileSet property in entity %q', name)
end
-- make the first header
local header1
if name then
header1 = self:_makeHeader1(name)
headerW = header1:getWidth()
else
warning('makeEntityTooltip: bad Name for entity %q', tostring(entity))
end
-- make the second header
local header2
if family and kind then
local string = family..' ('..kind..')'
header2 = self:_makeHeader2(string)
local width = header2:getWidth()
headerW = width > headerW and width or headerW
else
warning('makeEntityTooltip: missing family or kind for entity %q', name)
end
headerW = icon and headerW + icon:getWidth() + MARGIN or headerW
local width = headerW > MINWIDTH and headerW or MINWIDTH
-- make the health bar
local health = entity:query(property('Health'))
local maxHealth = entity:query(property('MaxHealth'))
local healthBar
if health and maxHealth then
healthBar = Bar(0, 0, width, margin)
healthBar:setNormalStyle(healthBarStyle)
healthBar:setLimits(0, maxHealth)
healthBar:setValue(health)
end
-- make the stats frames
-- TODO
-- make the description
local body
if description then
body = self:_makeText(description, width)
else
warning('makeEntityTooltip: missing description for entity %q', name)
end
-- make the tooltip
local tooltip = Tooltip()
tooltip:setNormalStyle(tooltipStyle)
tooltip:setMargin(MARGIN)
if icon then tooltip:setIcon(icon) end
if header1 then tooltip:setHeader1(header1) end
if header2 then tooltip:setHeader2(header2) end
if healthBar then tooltip:addBar(healthBar) end
if stats then
for i=1,numStats do
local stat = stats[i]
tooltip:addText(stat)
end
end
if body then
if stats then tooltip:addSpace() end
tooltip:addText(body)
end
return tooltip
end
-- make a simple generic tooltip with a header and text
function TooltipFactory:makeSimpleTooltip(header, text)
verify('string', header, text)
local header1 = self:_makeHeader1(header)
local headerW = header1:getWidth()
local width = headerW > MINWIDTH and headerW or MINWIDTH
local body = self:_makeText(text, width)
local tooltip = Tooltip()
tooltip:setNormalStyle(tooltipStyle)
tooltip:setMargin(MARGIN)
if header1 then tooltip:setHeader1(header1) end
if body then tooltip:addText(body) end
return tooltip
end
-- make an icon frame
function TooltipFactory:_makeIcon(image, x, y, w, h)
local style = iconStyle:clone({fgimage = image})
style:setFGQuad(x, y, w, h)
local icon = Frame(0, 0, w, h)
icon:setNormalStyle(style, true)
return icon
end
-- make a header1 Text frame
function TooltipFactory:_makeHeader1(text)
local font = header1Style:getFont()
local fontH = font:getHeight()
local width = font:getWidth(text)
local header1 = Text(0, 0, width, fontH)
header1:setNormalStyle(header1Style)
header1:setText(text)
return header1
end
-- make a header2 Text frame
function TooltipFactory:_makeHeader2(text)
local font = header2Style:getFont()
local fontH = font:getHeight()
local width = font:getWidth(text)
local header2 = Text(0, 0, width, fontH)
header2:setNormalStyle(header2Style)
header2:setText(text)
return header2
end
-- make a generic Text frame
function TooltipFactory:_makeText(text, width)
local font = textStyle:getFont()
local fontH = font:getHeight()
local fontW = font:getWidth(text)
width = width or fontW
local numLines = math_ceil(fontW / width)
local line = Text(0, 0, width, numLines * fontH)
line:setMaxLines(numLines)
line:setNormalStyle(textStyle)
line:setText(text)
return line
end
-- the class
return TooltipFactory
|
fix TileCoords query in TooltipFactory
|
fix TileCoords query in TooltipFactory
|
Lua
|
mit
|
scottcs/wyx
|
1d88927934ac111d44edff77fdc4f5e122316a92
|
lua/iq-tex-filtered.lua
|
lua/iq-tex-filtered.lua
|
-- Visualize IQ data as a texture from the HackRF
-- You want seizures? 'Cause this is how you get seizures.
VERTEX_SHADER = [[
#version 400
layout (location = 0) in vec3 vp;
layout (location = 1) in vec3 vn;
layout (location = 2) in vec2 vt;
out vec3 color;
out vec2 texCoord;
uniform mat4 uViewMatrix, uProjectionMatrix;
uniform float uTime;
void main() {
color = vec3(1.0, 1.0, 1.0);
texCoord = vt;
gl_Position = vec4(vp.x*2, vp.z*2, 0, 1.0);
}
]]
FRAGMENT_SHADER = [[
#version 400
in vec3 color;
in vec2 texCoord;
uniform sampler2D uTexture;
layout (location = 0) out vec4 fragColor;
void main() {
float r = texture(uTexture, texCoord).r * 90;
fragColor = vec4(r, r, r, 1);
}
]]
function setup()
freq = 936.2
device = nrf_device_new(freq, "../rfdata/rf-200.500-big.raw")
filter = nrf_iq_filter_new(device.sample_rate, 200e3, 51)
nrf_block_connect(device, filter)
camera = ngl_camera_new_look_at(0, 0, 0) -- Camera is unnecessary but ngl_draw_model requires it
shader = ngl_shader_new(GL_TRIANGLES, VERTEX_SHADER, FRAGMENT_SHADER)
texture = ngl_texture_new(shader, "uTexture")
model = ngl_model_new_grid_triangles(2, 2, 1, 1)
end
function draw()
ngl_clear(0.2, 0.2, 0.2, 1.0)
buffer = nrf_iq_filter_get_buffer(filter)
-- Initially buffer will be empty, so only attempt to change size when we have data
if (buffer.length > 0) then
iq_buffer = nrf_buffer_to_iq_lines(buffer, 4, 0.5)
ngl_texture_update(texture, iq_buffer, 1024, 1024)
end
ngl_draw_model(camera, model, shader)
end
function on_key(key, mods)
keys_frequency_handler(key, mods)
if key == KEY_E then
nul_buffer_save(nul_buffer_convert(buffer, 1), "out.raw")
end
end
|
-- Visualize IQ data as a texture from the HackRF
-- You want seizures? 'Cause this is how you get seizures.
VERTEX_SHADER = [[
#version 400
layout (location = 0) in vec3 vp;
layout (location = 1) in vec3 vn;
layout (location = 2) in vec2 vt;
out vec3 color;
out vec2 texCoord;
uniform mat4 uViewMatrix, uProjectionMatrix;
uniform float uTime;
void main() {
color = vec3(1.0, 1.0, 1.0);
texCoord = vt;
gl_Position = vec4(vp.x*2, vp.z*2, 0, 1.0);
}
]]
FRAGMENT_SHADER = [[
#version 400
in vec3 color;
in vec2 texCoord;
uniform sampler2D uTexture;
layout (location = 0) out vec4 fragColor;
void main() {
float r = texture(uTexture, texCoord).r * 90;
fragColor = vec4(r, r, r, 1);
}
]]
function setup()
freq = 936.2
device = nrf_device_new(freq, "../rfdata/rf-200.500-big.raw")
filter = nrf_iq_filter_new(device.sample_rate, 200e3, 51)
camera = ngl_camera_new_look_at(0, 0, 0) -- Camera is unnecessary but ngl_draw_model requires it
shader = ngl_shader_new(GL_TRIANGLES, VERTEX_SHADER, FRAGMENT_SHADER)
texture = ngl_texture_new(shader, "uTexture")
model = ngl_model_new_grid_triangles(2, 2, 1, 1)
end
function draw()
samples_buffer = nrf_device_get_samples_buffer(device)
nrf_iq_filter_process(filter, samples_buffer)
filter_buffer = nrf_iq_filter_get_buffer(filter)
iq_buffer = nrf_buffer_to_iq_lines(filter_buffer, 4, 0.2)
ngl_clear(0.2, 0.2, 0.2, 1.0)
ngl_texture_update(texture, iq_buffer, 1024, 1024)
ngl_draw_model(camera, model, shader)
end
function on_key(key, mods)
keys_frequency_handler(key, mods)
if key == KEY_E then
nul_buffer_save(nul_buffer_convert(buffer, 1), "out.raw")
end
end
|
Do processing in main draw loop.
|
Do processing in main draw loop.
This sidesteps the nrf_block model, which is currently buggy. The
disadvantage is that all the processing needs to be done in the main
thread; however it is easier to understand what’s going on.
|
Lua
|
mit
|
silky/frequensea,fdb/frequensea,fdb/frequensea,silky/frequensea,fdb/frequensea,fdb/frequensea,silky/frequensea,silky/frequensea,fdb/frequensea,silky/frequensea
|
09937be9b29b30b54dd9ec5fcfd6006d9f12061e
|
Modules/qGUI/KeyIcon/KeyIcon.lua
|
Modules/qGUI/KeyIcon/KeyIcon.lua
|
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local NevermoreEngine = require(ReplicatedStorage:WaitForChild("NevermoreEngine"))
local LoadCustomLibrary = NevermoreEngine.LoadLibrary
local FunctionMap = LoadCustomLibrary("FunctionMap")
local qGUI = LoadCustomLibrary("qGUI")
-- KeyIcon.lua
-- @author Quenty
-- This is a GUI element that indicates input (a key!) to a player.
local function Map(ItemList, Function, ...)
-- @param ItemList The items to map the function to
-- @param Function The function to be called
-- Function(ItemInList, [...])
-- @param ItemInList The item mapped to the function
-- @param [...] Extra arguments passed into the map function
-- @param [...] The extra arguments passed in after the Item in the function being mapped
for _, Item in pairs(ItemList) do
Function(Item, ...)
end
end
local KeyIcon = {}
KeyIcon.__index = KeyIcon
KeyIcon.ClassName = "KeyIcon"
KeyIcon.DefaultIconData = {
Image = "rbxassetid://245609912";
ImageSize = Vector2.new(150, 150);
}
KeyIcon.DefaultFillIconData = {
Image = "rbxassetid://245608758";
ImageSize = Vector2.new(150, 150);
}
function KeyIcon.new(GUI, OutlineTween, FillFrameTween)
-- @param GUI The parent of both the outline and fillframe, the text of this label
-- also forms the basis of a key icon. Assumedly a TextLabel, but it doesn't
-- have to be
-- @param OutlineTween The functionmap that tweens for the outline of the KeyIcon. Makes
-- some more assumptions that all of its GUIs are parented to it. This
-- controlsanimations, using the Tween method, and can be combined however
-- one likes.
-- @param FillFrames The same as the OutlineTween, but for the fill of the KeyIcon.
local self = {}
setmetatable(self, KeyIcon)
self.GUI = GUI
self.OutlineTween = OutlineTween
self.FillFrameTween = FillFrameTween
self.Width = GUI.Size.X.Offset
return self
end
function KeyIcon:SetFillTransparency(PercentTransparency, AnimationTime)
--- Sets the fill of the KeyIcon to a specific transparency. Used to indicate state.
-- @param PercentTransparency Number [0, 1], where 1 is completely transparency
-- @param [AnimationTime] The time to animate the outline. Defaults at 0.2.
AnimationTime = AnimationTime or 0.2
self.FillFrameTween:Map(PercentTransparency, AnimationTime, true)
end
function KeyIcon:SetOutlineTransparency(PercentTransparency, AnimationTime)
--- Sets the outline of the KeyIcon to a specific transparency
-- @param PercentTransparency Number [0, 1], where 1 is completely transparency
-- @param [AnimationTime] The time to animate the outline. Defaults at 0.2.
AnimationTime = AnimationTime or 0.2
self.OutlineTween:Map(PercentTransparency, AnimationTime, true)
end
function KeyIcon.FromBaseGUI(GUI, OutlineImageData, FillImageData)
--- Creates a new KeyIcon from a GUI and some OutlineImageData and FillImageData
-- @param GUI The GUI to used as the base of the KeyIcon. Should include the actual icon image
-- whether that be text or an image is up to the user.
-- @param OutlineImageData Table, The data to be used to generate a NinePatch from qGUI. Should
-- include ["Image"] = "rbxasset URL"; and ["ImageSize"] = number; for the
-- size in pixels of the image.
-- @return The new KeyIcon that was produced
local OutlineLabels = {qGUI.AddNinePatch(GUI, OutlineImageData.Image, OutlineImageData.ImageSize, 5, "ImageLabel")}
local FillFrames = {qGUI.AddNinePatch(GUI, FillImageData.Image, FillImageData.ImageSize, 5, "ImageLabel")}
local function SetZIndex(Item)
Item.ZIndex = GUI.ZIndex - 1
end
Map(OutlineLabels, SetZIndex)
Map(FillFrames, function(Item)
SetZIndex(Item)
Item.ImageTransparency = 1
end)
local function TweenFunctionFactory(Properties, Function, Transform)
-- Hardcore functional programming here.
-- Properties is a table
-- Function is the animation function
-- Transform transforms the PercentTransparency per property...
return function (Item, PercentTransparency, AnimationTime)
local TweenData = {}
for _, PropertyName in pairs(Properties) do
TweenData[PropertyName] = Transform(PercentTransparency, PropertyName)
end
Function(Item, TweenData, AnimationTime, true)
end
end
local FillMap = FunctionMap.new(FillFrames,
TweenFunctionFactory({"ImageTransparency"}, qGUI.TweenTransparency,
function(PercentTransparency, PropertyName)
return PercentTransparency
end))
if GUI:IsA("TextLabel") then
FillMap:AddChild(FunctionMap.new({GUI},
TweenFunctionFactory({"TextColor3"}, qGUI.TweenColor3,
function(PercentTransparency, PropertyName)
return Color3.new(PercentTransparency^2, PercentTransparency^2, PercentTransparency^2)
end)))
end
return KeyIcon.new(GUI, FunctionMap.new(OutlineLabels, qGUI.TweenTransparency), FillMap, GUI)
end
function KeyIcon.NewDefaultTextLabel(Height)
--- Creates a new default text label to be used by the KeyIcon.
Height = Height or 30
local TextLabel = Instance.new("TextLabel")
TextLabel.Name = "DefaultKeyIcon"
TextLabel.Size = UDim2.new(0, Height, 0, Height)
TextLabel.BackgroundTransparency = 1
TextLabel.TextColor3 = Color3.new(1, 1, 1)
TextLabel.BorderSizePixel = 0
TextLabel.Font = "SourceSansBold"
TextLabel.FontSize = "Size24"
TextLabel.Text = "X"
return TextLabel
end
function KeyIcon.NewDefault(Height)
--- Creates a new "default" KeyIcon to be used.
-- @return The new KeyIcon produced
local TextLabel = KeyIcon.NewDefaultTextLabel(Height)
return KeyIcon.FromBaseGUI(TextLabel, KeyIcon.DefaultIconData, KeyIcon.DefaultFillIconData)
end
return KeyIcon
|
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local NevermoreEngine = require(ReplicatedStorage:WaitForChild("NevermoreEngine"))
local LoadCustomLibrary = NevermoreEngine.LoadLibrary
local FunctionMap = LoadCustomLibrary("FunctionMap")
local qGUI = LoadCustomLibrary("qGUI")
-- KeyIcon.lua
-- @author Quenty
-- This is a GUI element that indicates input (a key!) to a player.
local function Map(ItemList, Function, ...)
-- @param ItemList The items to map the function to
-- @param Function The function to be called
-- Function(ItemInList, [...])
-- @param ItemInList The item mapped to the function
-- @param [...] Extra arguments passed into the map function
-- @param [...] The extra arguments passed in after the Item in the function being mapped
for _, Item in pairs(ItemList) do
Function(Item, ...)
end
end
local KeyIcon = {}
KeyIcon.__index = KeyIcon
KeyIcon.ClassName = "KeyIcon"
KeyIcon.DefaultIconData = {
Image = "rbxassetid://245857779";
ImageSize = Vector2.new(30, 30);
}
KeyIcon.DefaultFillIconData = {
Image = "rbxassetid://245608758";
ImageSize = Vector2.new(150, 150);
}
-- CONSTRUCTION
function KeyIcon.new(GUI, OutlineTween, FillFrameTween)
-- @param GUI The parent of both the outline and fillframe, the text of this label
-- also forms the basis of a key icon. Assumedly a TextLabel, but it doesn't
-- have to be
-- @param OutlineTween The functionmap that tweens for the outline of the KeyIcon. Makes
-- some more assumptions that all of its GUIs are parented to it. This
-- controlsanimations, using the Tween method, and can be combined however
-- one likes.
-- @param FillFrames The same as the OutlineTween, but for the fill of the KeyIcon.
local self = {}
setmetatable(self, KeyIcon)
self.GUI = GUI
self.OutlineTween = OutlineTween
self.FillFrameTween = FillFrameTween
self:RescaleWidth()
return self
end
function KeyIcon.NewDefaultTextLabel(Height)
--- Creates a new default text label to be used by the KeyIcon.
Height = Height or 30
local TextLabel = Instance.new("TextLabel")
TextLabel.Name = "DefaultKeyIcon"
TextLabel.Size = UDim2.new(0, Height, 0, Height)
TextLabel.BackgroundTransparency = 1
TextLabel.TextColor3 = Color3.new(1, 1, 1)
TextLabel.BorderSizePixel = 0
TextLabel.Font = "Arial"
TextLabel.FontSize = "Size18"
TextLabel.Text = "X"
return TextLabel
end
function KeyIcon.NewDefault(Height)
--- Creates a new "default" KeyIcon to be used.
-- @return The new KeyIcon produced
local TextLabel = KeyIcon.NewDefaultTextLabel(Height)
return KeyIcon.FromBaseGUI(TextLabel, KeyIcon.DefaultIconData, KeyIcon.DefaultFillIconData)
end
function KeyIcon.FromBaseGUI(GUI, OutlineImageData, FillImageData)
--- Creates a new KeyIcon from a GUI and some OutlineImageData and FillImageData
-- @param GUI The GUI to used as the base of the KeyIcon. Should include the actual icon image
-- whether that be text or an image is up to the user.
-- @param OutlineImageData Table, The data to be used to generate a NinePatch from qGUI. Should
-- include ["Image"] = "rbxasset URL"; and ["ImageSize"] = number; for the
-- size in pixels of the image.
-- @return The new KeyIcon that was produced
local OutlineLabels = {qGUI.AddNinePatch(GUI, OutlineImageData.Image, OutlineImageData.ImageSize, 7, "ImageLabel")}
local FillFrames = {qGUI.AddNinePatch(GUI, FillImageData.Image, FillImageData.ImageSize, 7, "ImageLabel")}
local function SetZIndex(Item)
Item.ZIndex = GUI.ZIndex - 1
end
Map(OutlineLabels, SetZIndex)
Map(FillFrames, function(Item)
SetZIndex(Item)
Item.ImageTransparency = 1
end)
local function TweenFunctionFactory(Properties, Function, Transform)
-- Hardcore functional programming here.
-- Properties is a table
-- Function is the animation function
-- Transform transforms the PercentTransparency per property...
return function (Item, PercentTransparency, AnimationTime)
local TweenData = {}
for _, PropertyName in pairs(Properties) do
TweenData[PropertyName] = Transform(PercentTransparency, PropertyName)
end
Function(Item, TweenData, AnimationTime, true)
end
end
local FillMap = FunctionMap.new(FillFrames,
TweenFunctionFactory({"ImageTransparency"}, qGUI.TweenTransparency,
function(PercentTransparency, PropertyName)
return PercentTransparency
end))
if GUI:IsA("TextLabel") then
FillMap:AddChild(FunctionMap.new({GUI},
TweenFunctionFactory({"TextColor3"}, qGUI.TweenColor3,
function(PercentTransparency, PropertyName)
return Color3.new(PercentTransparency^2, PercentTransparency^2, PercentTransparency^2)
end)))
end
return KeyIcon.new(GUI, FunctionMap.new(OutlineLabels, qGUI.TweenTransparency), FillMap, GUI)
end
-- METHODS
function KeyIcon:SetFillTransparency(PercentTransparency, AnimationTime)
--- Sets the fill of the KeyIcon to a specific transparency. Used to indicate state.
-- @param PercentTransparency Number [0, 1], where 1 is completely transparency
-- @param [AnimationTime] The time to animate the outline. Defaults at 0.2.
AnimationTime = AnimationTime or 0.2
self.FillFrameTween:Map(PercentTransparency, AnimationTime, true)
end
function KeyIcon:SetOutlineTransparency(PercentTransparency, AnimationTime)
--- Sets the outline of the KeyIcon to a specific transparency
-- @param PercentTransparency Number [0, 1], where 1 is completely transparency
-- @param [AnimationTime] The time to animate the outline. Defaults at 0.2.
AnimationTime = AnimationTime or 0.2
self.OutlineTween:Map(PercentTransparency, AnimationTime, true)
end
function KeyIcon:RescaleWidth()
--- Used with TextLabels to rescale the width. Note: Only works if the icon is parented.
if self.GUI:IsA("TextLabel") then
local Y = self.GUI.Size.Y
local X = self.GUI.Size.X
self.GUI.Size = UDim2.new(0, math.max(X.Offset, self.GUI.TextBounds.X + 16), Y.Scale, Y.Offset)
end
self.Width = self.GUI.Size.X.Offset
end
function KeyIcon:Destroy()
setmetatable(self, nil)
self.OutlineTween = nil
self.FillFrameTween = nil
self.GUI:Destroy()
end
return KeyIcon
|
Update a few rendering things, fix a few glitches
|
Update a few rendering things, fix a few glitches
|
Lua
|
mit
|
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
|
fab02bcac2cc5e9b95512bd3e34b1a1e14616f4c
|
lua/wincent/commandt/private/scanners/git.lua
|
lua/wincent/commandt/private/scanners/git.lua
|
-- SPDX-FileCopyrightText: Copyright 2022-present Greg Hurrell and contributors.
-- SPDX-License-Identifier: BSD-2-Clause
local git = {}
git.scanner = function(dir, options)
local lib = require('wincent.commandt.private.lib')
local command = 'git ls-files --exclude-standard --cached -z'
if options.submodules then
command = command .. ' --recurse-submodules'
elseif options.untracked then
command = command .. ' --untracked'
end
if dir ~= '' then
command = command .. ' -- ' .. dir
end
print(vim.inspect(command))
local scanner = lib.scanner_new_command(command)
return scanner
end
return git
|
-- SPDX-FileCopyrightText: Copyright 2022-present Greg Hurrell and contributors.
-- SPDX-License-Identifier: BSD-2-Clause
local git = {}
git.scanner = function(dir, options)
options = options or {}
local lib = require('wincent.commandt.private.lib')
local command = 'git ls-files --exclude-standard --cached -z'
if options.submodules then
command = command .. ' --recurse-submodules'
elseif options.untracked then
command = command .. ' --untracked'
end
if dir ~= '' then
command = command .. ' -- ' .. dir
end
local scanner = lib.scanner_new_command(command)
return scanner
end
return git
|
fix(lua): unbreak scanner benchmarks
|
fix(lua): unbreak scanner benchmarks
|
Lua
|
bsd-2-clause
|
wincent/command-t,wincent/command-t,wincent/command-t
|
4fad0c9a528ad971c56d48b996aa440abed2c594
|
pud/command/Command.lua
|
pud/command/Command.lua
|
local Class = require 'lib.hump.class'
-- Command class
local Command = Class{name='Command',
function(self, target)
self._target = target
end
}
-- destructor
function Command:destroy()
self._target = nil
end
-- get the target object of this command
function Command:getTarget() return self._target end
-- set the callback to call when the command is completed
function Command:setOnComplete(func, ...)
assert(func and type(func) == 'function',
'onComplete must be a function (was %s)', type(func))
self._onComplete = func
self._onCompleteArgs = {...}
end
-- call the stored callback when the command is completed
function Command:_doOnComplete()
if self._onComplete then
self._onComplete(unpack(self._onCompleteArgs))
end
end
-- execute the command
function Command:execute() self:_doOnComplete() end
-- destructor
function Command:destroy()
self._onComplete = nil
self._onCompleteArgs = nil
end
-- the class
return Command
|
local Class = require 'lib.hump.class'
-- Command class
local Command = Class{name='Command',
function(self, target)
self._target = target
end
}
-- destructor
function Command:destroy()
self._target = nil
self._onComplete = nil
self._onCompleteArgs = nil
end
-- get the target object of this command
function Command:getTarget() return self._target end
-- set the callback to call when the command is completed
function Command:setOnComplete(func, ...)
assert(func and type(func) == 'function',
'onComplete must be a function (was %s)', type(func))
self._onComplete = func
self._onCompleteArgs = {...}
end
-- call the stored callback when the command is completed
function Command:_doOnComplete()
if self._onComplete then
self._onComplete(unpack(self._onCompleteArgs))
end
end
-- execute the command
function Command:execute() self:_doOnComplete() end
-- the class
return Command
|
fix destructor
|
fix destructor
|
Lua
|
mit
|
scottcs/wyx
|
2db654a1b50086e5ec536330d8d68c1ea15e9443
|
kong/tools/public.lua
|
kong/tools/public.lua
|
local pcall = pcall
local ngx_log = ngx.log
local ERR = ngx.ERR
local _M = {}
do
local multipart = require "multipart"
local cjson = require "cjson.safe"
local str_find = string.find
local str_format = string.format
local ngx_req_get_post_args = ngx.req.get_post_args
local ngx_req_get_body_data = ngx.req.get_body_data
local MIME_TYPES = {
form_url_encoded = 1,
json = 2,
xml = 3,
multipart = 4,
text = 5,
html = 6,
}
local ERRORS = {
no_ct = 1,
[1] = "don't know how to parse request body (no Content-Type)",
unknown_ct = 2,
[2] = "don't know how to parse request body (" ..
"unknown Content-Type '%s')",
unsupported_ct = 3,
[3] = "don't know how to parse request body (" ..
"can't decode Content-Type '%s')",
}
_M.req_mime_types = MIME_TYPES
_M.req_body_errors = ERRORS
local MIME_DECODERS = {
[MIME_TYPES.multipart] = function(content_type)
local raw_body = ngx_req_get_body_data()
local args = multipart(raw_body, content_type):get_all()
return args, raw_body
end,
[MIME_TYPES.json] = function()
local raw_body = ngx_req_get_body_data()
local args, err = cjson.decode(raw_body)
if err then
ngx_log(ERR, "could not decode JSON body args: ", err)
return {}, raw_body
end
return args, raw_body
end,
[MIME_TYPES.form_url_encoded] = function()
local ok, res, err = pcall(ngx_req_get_post_args)
if not ok or err then
local msg = res and res or err
ngx_log(ERR, "could not get body args: ", msg)
return {}
end
-- don't read raw_body if not necessary
-- if we called get_body_args(), we only want the parsed body
return res
end,
}
local function get_body_info()
local content_type = ngx.var.http_content_type
if not content_type or content_type == "" then
ngx_log(ERR, ERRORS[ERRORS.no_ct])
return {}, ERRORS.no_ct
end
local req_mime
if str_find(content_type, "multipart/form-data", nil, true) then
req_mime = MIME_TYPES.multipart
elseif str_find(content_type, "application/json", nil, true) then
req_mime = MIME_TYPES.json
elseif str_find(content_type, "application/www-form-urlencoded", nil, true) or
str_find(content_type, "application/x-www-form-urlencoded", nil, true)
then
req_mime = MIME_TYPES.form_url_encoded
elseif str_find(content_type, "text/plain", nil, true) then
req_mime = MIME_TYPES.text
elseif str_find(content_type, "text/html", nil, true) then
req_mime = MIME_TYPES.html
elseif str_find(content_type, "application/xml", nil, true) or
str_find(content_type, "text/xml", nil, true) or
str_find(content_type, "application/soap+xml", nil, true)
then
-- considering SOAP 1.1 (text/xml) and SOAP 1.2 (application/soap+xml)
-- as XML only for now.
req_mime = MIME_TYPES.xml
end
if not req_mime then
-- unknown Content-Type
ngx_log(ERR, str_format(ERRORS[ERRORS.unsupported_ct], content_type))
return {}, ERRORS.unknown_ct
end
if not MIME_DECODERS[req_mime] then
-- known Content-Type, but cannot decode
ngx_log(ERR, str_format(ERRORS[ERRORS.unsupported_ct], content_type))
return {}, ERRORS.unsupported_ct, nil, req_mime
end
-- decoded Content-Type
local args, raw_body = MIME_DECODERS[req_mime](content_type)
return args, nil, raw_body, req_mime
end
function _M.get_body_args()
-- only return args
return (get_body_info())
end
function _M.get_body_info()
local args, err_code, raw_body, req_mime = get_body_info()
if not raw_body then
-- if our body was form-urlencoded and read via ngx.req.get_post_args()
-- we need to retrieve the raw body because it was not retrieved by the
-- decoder
raw_body = ngx_req_get_body_data()
end
return args, err_code, raw_body, req_mime
end
end
return _M
|
local pcall = pcall
local ngx_log = ngx.log
local ERR = ngx.ERR
local _M = {}
do
local multipart = require "multipart"
local cjson = require "cjson.safe"
local str_find = string.find
local str_format = string.format
local ngx_req_get_post_args = ngx.req.get_post_args
local ngx_req_get_body_data = ngx.req.get_body_data
local MIME_TYPES = {
form_url_encoded = 1,
json = 2,
xml = 3,
multipart = 4,
text = 5,
html = 6,
}
local ERRORS = {
no_ct = 1,
[1] = "don't know how to parse request body (no Content-Type)",
unknown_ct = 2,
[2] = "don't know how to parse request body (" ..
"unknown Content-Type '%s')",
unsupported_ct = 3,
[3] = "don't know how to parse request body (" ..
"can't decode Content-Type '%s')",
}
_M.req_mime_types = MIME_TYPES
_M.req_body_errors = ERRORS
local MIME_DECODERS = {
[MIME_TYPES.multipart] = function(content_type)
local raw_body = ngx_req_get_body_data()
if not raw_body then
ngx_log(ERR, "could not read request body (ngx.req.get_body_data() ",
"returned nil)")
return {}, raw_body
end
local args = multipart(raw_body, content_type):get_all()
return args, raw_body
end,
[MIME_TYPES.json] = function()
local raw_body = ngx_req_get_body_data()
if not raw_body then
ngx_log(ERR, "could not read request body (ngx.req.get_body_data() ",
"returned nil)")
return {}, raw_body
end
local args, err = cjson.decode(raw_body)
if err then
ngx_log(ERR, "could not decode JSON body args: ", err)
return {}, raw_body
end
return args, raw_body
end,
[MIME_TYPES.form_url_encoded] = function()
local ok, res, err = pcall(ngx_req_get_post_args)
if not ok or err then
local msg = res and res or err
ngx_log(ERR, "could not get body args: ", msg)
return {}
end
-- don't read raw_body if not necessary
-- if we called get_body_args(), we only want the parsed body
return res
end,
}
local function get_body_info()
local content_type = ngx.var.http_content_type
if not content_type or content_type == "" then
ngx_log(ERR, ERRORS[ERRORS.no_ct])
return {}, ERRORS.no_ct
end
local req_mime
if str_find(content_type, "multipart/form-data", nil, true) then
req_mime = MIME_TYPES.multipart
elseif str_find(content_type, "application/json", nil, true) then
req_mime = MIME_TYPES.json
elseif str_find(content_type, "application/www-form-urlencoded", nil, true) or
str_find(content_type, "application/x-www-form-urlencoded", nil, true)
then
req_mime = MIME_TYPES.form_url_encoded
elseif str_find(content_type, "text/plain", nil, true) then
req_mime = MIME_TYPES.text
elseif str_find(content_type, "text/html", nil, true) then
req_mime = MIME_TYPES.html
elseif str_find(content_type, "application/xml", nil, true) or
str_find(content_type, "text/xml", nil, true) or
str_find(content_type, "application/soap+xml", nil, true)
then
-- considering SOAP 1.1 (text/xml) and SOAP 1.2 (application/soap+xml)
-- as XML only for now.
req_mime = MIME_TYPES.xml
end
if not req_mime then
-- unknown Content-Type
ngx_log(ERR, str_format(ERRORS[ERRORS.unsupported_ct], content_type))
return {}, ERRORS.unknown_ct
end
if not MIME_DECODERS[req_mime] then
-- known Content-Type, but cannot decode
ngx_log(ERR, str_format(ERRORS[ERRORS.unsupported_ct], content_type))
return {}, ERRORS.unsupported_ct, nil, req_mime
end
-- decoded Content-Type
local args, raw_body = MIME_DECODERS[req_mime](content_type)
return args, nil, raw_body, req_mime
end
function _M.get_body_args()
-- only return args
return (get_body_info())
end
function _M.get_body_info()
local args, err_code, raw_body, req_mime = get_body_info()
if not raw_body then
-- if our body was form-urlencoded and read via ngx.req.get_post_args()
-- we need to retrieve the raw body because it was not retrieved by the
-- decoder
raw_body = ngx_req_get_body_data()
end
return args, err_code, raw_body, req_mime
end
end
return _M
|
fix(tools) do not error on reading non-existent bodies
|
fix(tools) do not error on reading non-existent bodies
When calling `get_body_args()` or `get_body_info()` with a request that
had no body but a Content-Type header of JSON or url-encoded, we would
pass a `nil` reference to `cjson.decode` or `multipart()`.
We now log the error for the user and return gracefully. The error
message is as precise as it can be without being too verbose. It gives a
pointer to the reader as to where to dig for more information. For
reference, see:
https://github.com/openresty/lua-nginx-module#ngxreqget_body_data
From #3062
Signed-off-by: Thibault Charbonnier <[email protected]>
|
Lua
|
apache-2.0
|
Kong/kong,jebenexer/kong,Mashape/kong,Kong/kong,Kong/kong
|
06e073089b8c35b96a108d30e078f74923e8132b
|
lib/settings.lua
|
lib/settings.lua
|
require 'xlua'
require 'pl'
require 'trepl'
-- global settings
if package.preload.settings then
return package.preload.settings
end
-- default tensor type
torch.setdefaulttensortype('torch.FloatTensor')
local settings = {}
local cmd = torch.CmdLine()
cmd:text()
cmd:text("waifu2x-training")
cmd:text("Options:")
cmd:option("-gpu", -1, 'GPU Device ID')
cmd:option("-seed", 11, 'RNG seed')
cmd:option("-data_dir", "./data", 'path to data directory')
cmd:option("-backend", "cunn", '(cunn|cudnn)')
cmd:option("-test", "images/miku_small.png", 'path to test image')
cmd:option("-model_dir", "./models", 'model directory')
cmd:option("-method", "scale", 'method to training (noise|scale|noise_scale)')
cmd:option("-model", "vgg_7", 'model architecture (vgg_7|vgg_12|upconv_7|upconv_8_4x|dilated_7)')
cmd:option("-noise_level", 1, '(1|2|3)')
cmd:option("-style", "art", '(art|photo)')
cmd:option("-color", 'rgb', '(y|rgb)')
cmd:option("-random_color_noise_rate", 0.0, 'data augmentation using color noise (0.0-1.0)')
cmd:option("-random_overlay_rate", 0.0, 'data augmentation using flipped image overlay (0.0-1.0)')
cmd:option("-random_half_rate", 0.0, 'data augmentation using half resolution image (0.0-1.0)')
cmd:option("-random_unsharp_mask_rate", 0.0, 'data augmentation using unsharp mask (0.0-1.0)')
cmd:option("-scale", 2.0, 'scale factor (2)')
cmd:option("-learning_rate", 0.00025, 'learning rate for adam')
cmd:option("-crop_size", 48, 'crop size')
cmd:option("-max_size", 256, 'if image is larger than N, image will be crop randomly')
cmd:option("-batch_size", 16, 'mini batch size')
cmd:option("-patches", 64, 'number of patch samples')
cmd:option("-inner_epoch", 4, 'number of inner epochs')
cmd:option("-epoch", 50, 'number of epochs to run')
cmd:option("-thread", -1, 'number of CPU threads')
cmd:option("-jpeg_chroma_subsampling_rate", 0.5, 'the rate of using YUV 4:2:0 in denoising training (0.0-1.0)')
cmd:option("-validation_rate", 0.05, 'validation-set rate (number_of_training_images * validation_rate > 1)')
cmd:option("-validation_crops", 200, 'number of cropping region per image in validation')
cmd:option("-active_cropping_rate", 0.5, 'active cropping rate')
cmd:option("-active_cropping_tries", 10, 'active cropping tries')
cmd:option("-nr_rate", 0.65, 'trade-off between reducing noise and erasing details (0.0-1.0)')
cmd:option("-save_history", 0, 'save all model (0|1)')
cmd:option("-plot", 0, 'plot loss chart(0|1)')
cmd:option("-downsampling_filters", "Box,Lanczos,Sinc", '(comma separated)downsampling filters for 2x scale training. (Point,Box,Triangle,Hermite,Hanning,Hamming,Blackman,Gaussian,Quadratic,Cubic,Catrom,Mitchell,Lanczos,Bessel,Sinc)')
cmd:option("-max_training_image_size", -1, 'if training image is larger than N, image will be crop randomly when data converting')
cmd:option("-use_transparent_png", 0, 'use transparent png (0|1)')
cmd:option("-resize_blur_min", 0.95, 'min blur parameter for ResizeImage')
cmd:option("-resize_blur_max", 1.05, 'max blur parameter for ResizeImage')
cmd:option("-oracle_rate", 0.1, '')
cmd:option("-oracle_drop_rate", 0.5, '')
cmd:option("-learning_rate_decay", 3.0e-7, 'learning rate decay (learning_rate * 1/(1+num_of_data*patches*epoch))')
cmd:option("-loss", "y", 'loss (rgb|y)')
cmd:option("-resume", "", 'resume model file')
local function to_bool(settings, name)
if settings[name] == 1 then
settings[name] = true
else
settings[name] = false
end
end
local opt = cmd:parse(arg)
for k, v in pairs(opt) do
settings[k] = v
end
to_bool(settings, "plot")
to_bool(settings, "save_history")
to_bool(settings, "use_transparent_png")
if settings.plot then
require 'gnuplot'
end
if settings.save_history then
if settings.method == "noise" then
settings.model_file = string.format("%s/noise%d_model.%%d-%%d.t7",
settings.model_dir, settings.noise_level)
settings.model_file_best = string.format("%s/noise%d_model.t7",
settings.model_dir, settings.noise_level)
elseif settings.method == "scale" then
settings.model_file = string.format("%s/scale%.1fx_model.%%d-%%d.t7",
settings.model_dir, settings.scale)
settings.model_file_best = string.format("%s/scale%.1fx_model.t7",
settings.model_dir, settings.scale)
elseif settings.method == "noise_scale" then
settings.model_file = string.format("%s/noise%d_scale%.1fx_model.%%d-%%d.t7",
settings.model_dir,
settings.noise_level,
settings.scale)
settings.model_file_best = string.format("%s/noise%d_scale%.1fx_model.t7",
settings.model_dir,
settings.noise_level,
settings.scale)
else
error("unknown method: " .. settings.method)
end
else
if settings.method == "noise" then
settings.model_file = string.format("%s/noise%d_model.t7",
settings.model_dir, settings.noise_level)
elseif settings.method == "scale" then
settings.model_file = string.format("%s/scale%.1fx_model.t7",
settings.model_dir, settings.scale)
elseif settings.method == "noise_scale" then
settings.model_file = string.format("%s/noise%d_scale%.1fx_model.t7",
settings.model_dir, settings.noise_level, settings.scale)
else
error("unknown method: " .. settings.method)
end
end
if not (settings.color == "rgb" or settings.color == "y") then
error("color must be y or rgb")
end
if not (settings.scale == math.floor(settings.scale) and settings.scale % 2 == 0) then
error("scale must be mod-2")
end
if not (settings.style == "art" or
settings.style == "photo") then
error(string.format("unknown style: %s", settings.style))
end
if settings.thread > 0 then
torch.setnumthreads(tonumber(settings.thread))
end
if settings.downsampling_filters and settings.downsampling_filters:len() > 0 then
settings.downsampling_filters = settings.downsampling_filters:split(",")
else
settings.downsampling_filters = {"Box", "Lanczos", "Catrom"}
end
settings.images = string.format("%s/images.t7", settings.data_dir)
settings.image_list = string.format("%s/image_list.txt", settings.data_dir)
return settings
|
require 'xlua'
require 'pl'
require 'trepl'
-- global settings
if package.preload.settings then
return package.preload.settings
end
-- default tensor type
torch.setdefaulttensortype('torch.FloatTensor')
local settings = {}
local cmd = torch.CmdLine()
cmd:text()
cmd:text("waifu2x-training")
cmd:text("Options:")
cmd:option("-gpu", -1, 'GPU Device ID')
cmd:option("-seed", 11, 'RNG seed')
cmd:option("-data_dir", "./data", 'path to data directory')
cmd:option("-backend", "cunn", '(cunn|cudnn)')
cmd:option("-test", "images/miku_small.png", 'path to test image')
cmd:option("-model_dir", "./models", 'model directory')
cmd:option("-method", "scale", 'method to training (noise|scale|noise_scale|user)')
cmd:option("-model", "vgg_7", 'model architecture (vgg_7|vgg_12|upconv_7|upconv_8_4x|dilated_7)')
cmd:option("-noise_level", 1, '(0|1|2|3)')
cmd:option("-style", "art", '(art|photo)')
cmd:option("-color", 'rgb', '(y|rgb)')
cmd:option("-random_color_noise_rate", 0.0, 'data augmentation using color noise (0.0-1.0)')
cmd:option("-random_overlay_rate", 0.0, 'data augmentation using flipped image overlay (0.0-1.0)')
cmd:option("-random_half_rate", 0.0, 'data augmentation using half resolution image (0.0-1.0)')
cmd:option("-random_unsharp_mask_rate", 0.0, 'data augmentation using unsharp mask (0.0-1.0)')
cmd:option("-scale", 2.0, 'scale factor (2)')
cmd:option("-learning_rate", 0.00025, 'learning rate for adam')
cmd:option("-crop_size", 48, 'crop size')
cmd:option("-max_size", 256, 'if image is larger than N, image will be crop randomly')
cmd:option("-batch_size", 16, 'mini batch size')
cmd:option("-patches", 64, 'number of patch samples')
cmd:option("-inner_epoch", 4, 'number of inner epochs')
cmd:option("-epoch", 50, 'number of epochs to run')
cmd:option("-thread", -1, 'number of CPU threads')
cmd:option("-jpeg_chroma_subsampling_rate", 0.5, 'the rate of using YUV 4:2:0 in denoising training (0.0-1.0)')
cmd:option("-validation_rate", 0.05, 'validation-set rate (number_of_training_images * validation_rate > 1)')
cmd:option("-validation_crops", 200, 'number of cropping region per image in validation')
cmd:option("-active_cropping_rate", 0.5, 'active cropping rate')
cmd:option("-active_cropping_tries", 10, 'active cropping tries')
cmd:option("-nr_rate", 0.65, 'trade-off between reducing noise and erasing details (0.0-1.0)')
cmd:option("-save_history", 0, 'save all model (0|1)')
cmd:option("-plot", 0, 'plot loss chart(0|1)')
cmd:option("-downsampling_filters", "Box,Lanczos,Sinc", '(comma separated)downsampling filters for 2x scale training. (Point,Box,Triangle,Hermite,Hanning,Hamming,Blackman,Gaussian,Quadratic,Cubic,Catrom,Mitchell,Lanczos,Bessel,Sinc)')
cmd:option("-max_training_image_size", -1, 'if training image is larger than N, image will be crop randomly when data converting')
cmd:option("-use_transparent_png", 0, 'use transparent png (0|1)')
cmd:option("-resize_blur_min", 0.95, 'min blur parameter for ResizeImage')
cmd:option("-resize_blur_max", 1.05, 'max blur parameter for ResizeImage')
cmd:option("-oracle_rate", 0.1, '')
cmd:option("-oracle_drop_rate", 0.5, '')
cmd:option("-learning_rate_decay", 3.0e-7, 'learning rate decay (learning_rate * 1/(1+num_of_data*patches*epoch))')
cmd:option("-loss", "y", 'loss (rgb|y)')
cmd:option("-resume", "", 'resume model file')
cmd:option("-name", "user", 'model name for user method')
local function to_bool(settings, name)
if settings[name] == 1 then
settings[name] = true
else
settings[name] = false
end
end
local opt = cmd:parse(arg)
for k, v in pairs(opt) do
settings[k] = v
end
to_bool(settings, "plot")
to_bool(settings, "save_history")
to_bool(settings, "use_transparent_png")
if settings.plot then
require 'gnuplot'
end
if settings.save_history then
if settings.method == "noise" then
settings.model_file = string.format("%s/noise%d_model.%%d-%%d.t7",
settings.model_dir, settings.noise_level)
settings.model_file_best = string.format("%s/noise%d_model.t7",
settings.model_dir, settings.noise_level)
elseif settings.method == "scale" then
settings.model_file = string.format("%s/scale%.1fx_model.%%d-%%d.t7",
settings.model_dir, settings.scale)
settings.model_file_best = string.format("%s/scale%.1fx_model.t7",
settings.model_dir, settings.scale)
elseif settings.method == "noise_scale" then
settings.model_file = string.format("%s/noise%d_scale%.1fx_model.%%d-%%d.t7",
settings.model_dir,
settings.noise_level,
settings.scale)
settings.model_file_best = string.format("%s/noise%d_scale%.1fx_model.t7",
settings.model_dir,
settings.noise_level,
settings.scale)
elseif settings.method == "user" then
settings.model_file = string.format("%s/%s_model.%%d-%%d.t7",
settings.model_dir,
settings.name)
settings.model_file_best = string.format("%s/%s_model.t7",
settings.model_dir,
settings.name)
else
error("unknown method: " .. settings.method)
end
else
if settings.method == "noise" then
settings.model_file = string.format("%s/noise%d_model.t7",
settings.model_dir, settings.noise_level)
elseif settings.method == "scale" then
settings.model_file = string.format("%s/scale%.1fx_model.t7",
settings.model_dir, settings.scale)
elseif settings.method == "noise_scale" then
settings.model_file = string.format("%s/noise%d_scale%.1fx_model.t7",
settings.model_dir, settings.noise_level, settings.scale)
elseif settings.method == "user" then
settings.model_file = string.format("%s/%s_model.t7",
settings.model_dir, settings.name)
else
error("unknown method: " .. settings.method)
end
end
if not (settings.color == "rgb" or settings.color == "y") then
error("color must be y or rgb")
end
if not ( settings.scale == 1 or (settings.scale == math.floor(settings.scale) and settings.scale % 2 == 0)) then
error("scale must be 1 or mod-2")
end
if not (settings.style == "art" or
settings.style == "photo") then
error(string.format("unknown style: %s", settings.style))
end
if settings.thread > 0 then
torch.setnumthreads(tonumber(settings.thread))
end
if settings.downsampling_filters and settings.downsampling_filters:len() > 0 then
settings.downsampling_filters = settings.downsampling_filters:split(",")
else
settings.downsampling_filters = {"Box", "Lanczos", "Catrom"}
end
settings.images = string.format("%s/images.t7", settings.data_dir)
settings.image_list = string.format("%s/image_list.txt", settings.data_dir)
return settings
|
Fix for edac608f
|
Fix for edac608f
|
Lua
|
mit
|
nagadomi/waifu2x,Spitfire1900/upscaler,zyhkz/waifu2x,Spitfire1900/upscaler,nagadomi/waifu2x,nagadomi/waifu2x,zyhkz/waifu2x,nagadomi/waifu2x,zyhkz/waifu2x,nagadomi/waifu2x,zyhkz/waifu2x
|
31d9ed7a0d5ffbf1e1e089de32048d04f735677b
|
kong/db/strategies/postgres/connector.lua
|
kong/db/strategies/postgres/connector.lua
|
local pgmoon = require "pgmoon"
local setmetatable = setmetatable
local concat = table.concat
local setmetatable = setmetatable
--local pairs = pairs
--local type = type
local ngx = ngx
local get_phase = ngx.get_phase
local null = ngx.null
local log = ngx.log
local WARN = ngx.WARN
local SQL_INFORMATION_SCHEMA_TABLES = [[
SELECT table_name
FROM information_schema.tables
WHERE table_schema = 'public';
]]
--local function visit(k, n, m, s)
-- if m[k] == 0 then return 1 end
-- if m[k] == 1 then return end
-- m[k] = 0
-- local f = n[k]
-- for i=1, #f do
-- if visit(f[i], n, m, s) then return 1 end
-- end
-- m[k] = 1
-- s[#s+1] = k
--end
--
--
--local tsort = {}
--tsort.__index = tsort
--
--
--function tsort.new()
-- return setmetatable({ n = {} }, tsort)
--end
--
--
--function tsort:add(...)
-- local p = { ... }
-- local c = #p
-- if c == 0 then return self end
-- if c == 1 then
-- p = p[1]
-- if type(p) == "table" then
-- c = #p
-- else
-- p = { p }
-- end
-- end
-- local n = self.n
-- for i=1, c do
-- local f = p[i]
-- if n[f] == nil then n[f] = {} end
-- end
-- for i=2, c, 1 do
-- local f = p[i]
-- local t = p[i-1]
-- local o = n[f]
-- o[#o+1] = t
-- end
-- return self
--end
--
--
--function tsort:sort()
-- local n = self.n
-- local s = {}
-- local m = {}
-- for k in pairs(n) do
-- if m[k] == nil then
-- if visit(k, n, m, s) then
-- return nil, "There is a circular dependency in the graph. It is not possible to derive a topological sort."
-- end
-- end
-- end
-- return s
--end
local function iterator(rows)
local i = 0
return function()
i = i + 1
return rows[i]
end
end
local _mt = {}
_mt.__index = _mt
function _mt:connect()
local connection = self.connection
if connection then
return true
end
local config = self.config
local phase = get_phase()
if phase == "init" or phase == "init_worker" or ngx.IS_CLI then
config.socket_type = "luasocket"
else
config.socket_type = "nginx"
end
local db = pgmoon.new(config)
db.convert_null = true
db.NULL = null
local ok, err = db:connect()
if not ok then
return nil, err
end
self.connection = db
if db.sock:getreusedtimes() == 0 then
ok, err = self:query("SET TIME ZONE 'UTC';");
if not ok then
return nil, err
end
end
return true
end
function _mt:setkeepalive()
local connection = self.connection
self.connection = nil
if not connection then
return nil, "no active connection"
end
local ok, err
if connection.sock_type == "luasocket" then
ok, err = connection:disconnect()
else
ok, err = connection:keepalive()
end
if not ok then
return nil, err
end
return true
end
function _mt:query(sql)
local connection = self.connection
if connection then
return connection:query(sql)
end
local ok, err = self:connect()
if not ok then
return nil, err
end
local res, exc, partial, num_queries = self.connection:query(sql)
ok, err = self:setkeepalive()
if not ok then
log(WARN, err)
end
if not res then
return nil, exc, partial, num_queries
end
return res, exc
end
function _mt:iterate(sql)
local connection = self.connection
if connection then
local res, err, partial, num_queries = connection:query(sql)
if not res then
return nil, err, partial, num_queries
end
if res == true then
return iterator { true }
end
return iterator(res)
end
local ok, err = self:connect()
if not ok then
return nil, err
end
local res, exc, partial, num_queries = self.connection:query(sql)
ok, err = self:setkeepalive()
if not ok then
log(WARN, err)
end
if not res then
return nil, exc, partial, num_queries
end
if res == true then
return iterator { true }
end
return iterator(res)
end
function _mt:reset()
local user = self:escape_identifier(self.config.user)
local ok, err = self:connect()
if not ok then
return nil, err
end
ok, err = self:query(concat {
"BEGIN;\n",
"DROP SCHEMA IF EXISTS public CASCADE;\n",
"CREATE SCHEMA IF NOT EXISTS public AUTHORIZATION " .. user .. ";\n",
"GRANT ALL ON SCHEMA public TO " .. user .. ";\n",
"COMMIT;\n",
})
local success, exc = self:setkeepalive()
if not success then
log(WARN, exc)
end
if not ok then
return nil, err
end
--[[
-- Disabled for now because migrations will run from the old DAO.
-- Additionally, the purpose of `reset()` is to clean the database,
-- and leave it blank. Migrations will use it to reset the database,
-- and migrations will also be responsible for creating the necessary
-- tables.
local graph = tsort.new()
local hash = {}
for _, strategy in pairs(strategies) do
local schema = strategy.schema
local name = schema.name
local fields = schema.fields
hash[name] = strategy
graph:add(name)
for _, field in ipairs(fields) do
if field.type == "foreign" then
graph:add(field.schema.name, name)
end
end
end
local sorted_strategies = graph:sort()
for _, name in ipairs(sorted_strategies) do
ok, err = hash[name]:create()
if not ok then
return nil, err
end
end
--]]
return true
end
function _mt:truncate()
local i, table_names = 0, {}
for row in self:iterate(SQL_INFORMATION_SCHEMA_TABLES) do
local table_name = row.table_name
if table_name ~= "schema_migrations" then
i = i + 1
table_names[i] = self:escape_identifier(table_name)
end
end
if i == 0 then
return true
end
local truncate_statement = {
"TRUNCATE TABLE ", concat(table_names, ", "), " RESTART IDENTITY CASCADE;"
}
local ok, err = self:query(truncate_statement)
if not ok then
return nil, err
end
return true
end
local _M = {}
function _M.new(kong_config)
local config = {
host = kong_config.pg_host,
port = kong_config.pg_port,
user = kong_config.pg_user,
password = kong_config.pg_password,
database = kong_config.pg_database,
ssl = kong_config.pg_ssl,
ssl_verify = kong_config.pg_ssl_verify,
cafile = kong_config.lua_ssl_trusted_certificate,
}
local db = pgmoon.new(config)
return setmetatable({
config = config,
escape_identifier = db.escape_identifier,
escape_literal = db.escape_literal,
}, _mt)
end
return _M
|
local pgmoon = require "pgmoon"
local setmetatable = setmetatable
local concat = table.concat
local setmetatable = setmetatable
--local pairs = pairs
--local type = type
local ngx = ngx
local get_phase = ngx.get_phase
local null = ngx.null
local log = ngx.log
local WARN = ngx.WARN
local SQL_INFORMATION_SCHEMA_TABLES = [[
SELECT table_name
FROM information_schema.tables
WHERE table_schema = 'public';
]]
--local function visit(k, n, m, s)
-- if m[k] == 0 then return 1 end
-- if m[k] == 1 then return end
-- m[k] = 0
-- local f = n[k]
-- for i=1, #f do
-- if visit(f[i], n, m, s) then return 1 end
-- end
-- m[k] = 1
-- s[#s+1] = k
--end
--
--
--local tsort = {}
--tsort.__index = tsort
--
--
--function tsort.new()
-- return setmetatable({ n = {} }, tsort)
--end
--
--
--function tsort:add(...)
-- local p = { ... }
-- local c = #p
-- if c == 0 then return self end
-- if c == 1 then
-- p = p[1]
-- if type(p) == "table" then
-- c = #p
-- else
-- p = { p }
-- end
-- end
-- local n = self.n
-- for i=1, c do
-- local f = p[i]
-- if n[f] == nil then n[f] = {} end
-- end
-- for i=2, c, 1 do
-- local f = p[i]
-- local t = p[i-1]
-- local o = n[f]
-- o[#o+1] = t
-- end
-- return self
--end
--
--
--function tsort:sort()
-- local n = self.n
-- local s = {}
-- local m = {}
-- for k in pairs(n) do
-- if m[k] == nil then
-- if visit(k, n, m, s) then
-- return nil, "There is a circular dependency in the graph. It is not possible to derive a topological sort."
-- end
-- end
-- end
-- return s
--end
local function iterator(rows)
local i = 0
return function()
i = i + 1
return rows[i]
end
end
local setkeepalive
local function connect(config)
local phase = get_phase()
if phase == "init" or phase == "init_worker" or ngx.IS_CLI then
config.socket_type = "luasocket"
else
config.socket_type = "nginx"
end
local connection = pgmoon.new(config)
connection.convert_null = true
connection.NULL = null
local ok, err = connection:connect()
if not ok then
return nil, err
end
if connection.sock:getreusedtimes() == 0 then
ok, err = connection:query("SET TIME ZONE 'UTC';");
if not ok then
setkeepalive(connection)
return nil, err
end
end
return connection
end
setkeepalive = function(connection)
if not connection or not connection.sock then
return nil, "no active connection"
end
local ok, err
if connection.sock_type == "luasocket" then
ok, err = connection:disconnect()
if not ok then
if err then
log(WARN, "unable to close postgres connection (", err, ")")
else
log(WARN, "unable to close postgres connection")
end
return nil, err
end
else
ok, err = connection:keepalive()
if not ok then
if err then
log(WARN, "unable to set keepalive for postgres connection (", err, ")")
else
log(WARN, "unable to set keepalive for postgres connection")
end
return nil, err
end
end
return true
end
local _mt = {}
_mt.__index = _mt
function _mt:connect()
if self.connection and self.connection.sock then
return true
end
local connection, err = connect(self.config)
if not connection then
return nil, err
end
self.connection = connection
return true
end
function _mt:setkeepalive()
local ok, err = setkeepalive(self.connection)
self.connection = nil
if not ok then
return nil, err
end
return true
end
function _mt:query(sql)
if self.connection and self.connection.sock then
return self.connection:query(sql)
end
local connection, err = connect(self.config)
if not connection then
return nil, err
end
local res, exc, partial, num_queries = connection:query(sql)
setkeepalive(connection)
return res, exc, partial, num_queries
end
function _mt:iterate(sql)
local res, err, partial, num_queries = self:query(sql)
if not res then
return nil, err, partial, num_queries
end
if res == true then
return iterator { true }
end
return iterator(res)
end
function _mt:reset()
local user = self:escape_identifier(self.config.user)
local ok, err = self:query(concat {
"BEGIN;\n",
"DROP SCHEMA IF EXISTS public CASCADE;\n",
"CREATE SCHEMA IF NOT EXISTS public AUTHORIZATION " .. user .. ";\n",
"GRANT ALL ON SCHEMA public TO " .. user .. ";\n",
"COMMIT;\n",
})
if not ok then
return nil, err
end
--[[
-- Disabled for now because migrations will run from the old DAO.
-- Additionally, the purpose of `reset()` is to clean the database,
-- and leave it blank. Migrations will use it to reset the database,
-- and migrations will also be responsible for creating the necessary
-- tables.
local graph = tsort.new()
local hash = {}
for _, strategy in pairs(strategies) do
local schema = strategy.schema
local name = schema.name
local fields = schema.fields
hash[name] = strategy
graph:add(name)
for _, field in ipairs(fields) do
if field.type == "foreign" then
graph:add(field.schema.name, name)
end
end
end
local sorted_strategies = graph:sort()
for _, name in ipairs(sorted_strategies) do
ok, err = hash[name]:create()
if not ok then
return nil, err
end
end
--]]
return true
end
function _mt:truncate()
local i, table_names = 0, {}
for row in self:iterate(SQL_INFORMATION_SCHEMA_TABLES) do
local table_name = row.table_name
if table_name ~= "schema_migrations" then
i = i + 1
table_names[i] = self:escape_identifier(table_name)
end
end
if i == 0 then
return true
end
local truncate_statement = {
"TRUNCATE TABLE ", concat(table_names, ", "), " RESTART IDENTITY CASCADE;"
}
local ok, err = self:query(truncate_statement)
if not ok then
return nil, err
end
return true
end
local _M = {}
function _M.new(kong_config)
local config = {
host = kong_config.pg_host,
port = kong_config.pg_port,
user = kong_config.pg_user,
password = kong_config.pg_password,
database = kong_config.pg_database,
ssl = kong_config.pg_ssl,
ssl_verify = kong_config.pg_ssl_verify,
cafile = kong_config.lua_ssl_trusted_certificate,
}
local db = pgmoon.new(config)
return setmetatable({
config = config,
escape_identifier = db.escape_identifier,
escape_literal = db.escape_literal,
}, _mt)
end
return _M
|
fix(db) ensure postgres connector reentrancy
|
fix(db) ensure postgres connector reentrancy
Because the connector currently stores its connection in an
attribute, it is shared between all requests in a worker, which
will throw cosocket errors. Instead, `:query()` is now reentrant
by incoming requests (it instantiates and keepalive its own
connections). The connector `:connect()` and `:setkeepalive()`
methods are left untouched for now, but need further consideration
given their limitation with regards to their lack of reentrancy at runtime.
From #3423
|
Lua
|
apache-2.0
|
Kong/kong,Mashape/kong,Kong/kong,Kong/kong
|
41a75166476d915950096e3e88c03f44f0cba965
|
share/media/funnyordie.lua
|
share/media/funnyordie.lua
|
-- libquvi-scripts
-- Copyright (C) 2011,2013 Toni Gundogdu <[email protected]>
-- Copyright (C) 2010 quvi project
--
-- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>.
--
-- This program is free software: you can redistribute it and/or
-- modify it under the terms of the GNU Affero General Public
-- License as published by the Free Software Foundation, either
-- version 3 of the License, or (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU Affero General Public License for more details.
--
-- You should have received a copy of the GNU Affero General
-- Public License along with this program. If not, see
-- <http://www.gnu.org/licenses/>.
--
local FunnyOrDie = {} -- Utility functions unique to this script
-- Identify the media script.
function ident(qargs)
return {
can_parse_url = FunnyOrDie.can_parse_url(qargs),
domains = table.concat({'funnyordie.com'}, ',')
}
end
-- Parse media properties.
function parse(qargs)
local p = quvi.http.fetch(qargs.input_url).data
qargs.thumb_url = p:match('"og:image" content="(.-)"') or ''
qargs.title = p:match('"og:title" content="(.-)">') or ''
qargs.id = p:match('key:%s+"(.-)"') or ''
qargs.streams = FunnyOrDie.iter_streams(p)
return qargs
end
--
-- Utility functions
--
function FunnyOrDie.can_parse_url(qargs)
local U = require 'socket.url'
local t = U.parse(qargs.input_url)
if t and t.scheme and t.scheme:lower():match('^http$')
and t.host and t.host:lower():match('funnyordie%.com$')
and t.path and t.path:lower():match('^/videos/%w+')
then
return true
else
return false
end
end
function FunnyOrDie.iter_streams(p)
local t = {}
for u in p:gmatch('source src="(.-)"') do table.insert(t,u) end
-- There should be at least two stream URLs at this point.
-- first: the (playlist) URL for the segmented videos (unusable to us)
-- ...: the media stream URLs
if #t <2 then error('no match: media stream URL') end
table.remove(t,1) -- Remove the first stream URL.
local S = require 'quvi/stream'
local r = {}
-- nostd is a dictionary used by this script only. libquvi ignores it.
for _,u in pairs(t) do
local q,c = u:match('/(%w+)%.(%w+)$')
local s = S.stream_new(u)
s.nostd = {quality=q}
s.container = c
s.id = FunnyOrDie.to_id(s)
table.insert(r,s)
end
if #r >1 then
FunnyOrDie.ch_best(r)
end
return r
end
function FunnyOrDie.ch_best(t)
t[1].flags.best = true
end
function FunnyOrDie.to_id(t)
return string.format("%s_%s", t.nostd.quality, t.container)
end
-- vim: set ts=2 sw=2 tw=72 expandtab:
|
-- libquvi-scripts
-- Copyright (C) 2011,2013 Toni Gundogdu <[email protected]>
-- Copyright (C) 2010 quvi project
--
-- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>.
--
-- This program is free software: you can redistribute it and/or
-- modify it under the terms of the GNU Affero General Public
-- License as published by the Free Software Foundation, either
-- version 3 of the License, or (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU Affero General Public License for more details.
--
-- You should have received a copy of the GNU Affero General
-- Public License along with this program. If not, see
-- <http://www.gnu.org/licenses/>.
--
local FunnyOrDie = {} -- Utility functions unique to this script
-- Identify the media script.
function ident(qargs)
return {
can_parse_url = FunnyOrDie.can_parse_url(qargs),
domains = table.concat({'funnyordie.com'}, ',')
}
end
-- Parse media properties.
function parse(qargs)
local p = quvi.http.fetch(qargs.input_url).data
qargs.thumb_url = p:match('"og:image" content="(.-)"') or ''
qargs.title = p:match('"og:title" content="(.-)">') or ''
qargs.id = p:match('key:%s+"(.-)"') or ''
qargs.streams = FunnyOrDie.iter_streams(p)
return qargs
end
--
-- Utility functions
--
function FunnyOrDie.can_parse_url(qargs)
local U = require 'socket.url'
local t = U.parse(qargs.input_url)
if t and t.scheme and t.scheme:lower():match('^http$')
and t.host and t.host:lower():match('funnyordie%.com$')
and t.path and t.path:lower():match('^/videos/%w+')
then
return true
else
return false
end
end
function FunnyOrDie.iter_streams(p)
local t = {}
for u in p:gmatch('type: "video/mp4", src: "(.-)"') do
table.insert(t, u)
end
if #t ==0 then error('no match: media stream URL') end
local S = require 'quvi/stream'
local r = {}
-- nostd is a dictionary used by this script only. libquvi ignores it.
for _,u in pairs(t) do
local q,c = u:match('/(%w+)%.(%w+)$')
local s = S.stream_new(u)
s.nostd = {quality=q}
s.container = c
s.id = FunnyOrDie.to_id(s)
table.insert(r,s)
end
if #r >1 then
FunnyOrDie.ch_best(r)
end
return r
end
function FunnyOrDie.ch_best(t)
t[1].flags.best = true
end
function FunnyOrDie.to_id(t)
return string.format("%s_%s", t.nostd.quality, t.container)
end
-- vim: set ts=2 sw=2 tw=72 expandtab:
|
FIX: media/funnyordie.lua: Stream URL pattern
|
FIX: media/funnyordie.lua: Stream URL pattern
Update the media stream URL pattern to reflect the recent changes to the
website. Look for the video/mp4 content only.
Signed-off-by: Toni Gundogdu <[email protected]>
|
Lua
|
agpl-3.0
|
legatvs/libquvi-scripts,alech/libquvi-scripts,legatvs/libquvi-scripts,alech/libquvi-scripts
|
97fcda5ae0bd4ef5db5b1df62824d704409fa5ef
|
packages/url.lua
|
packages/url.lua
|
SILE.require("packages/verbatim")
local pdf
pcall(function() pdf = require("justenoughlibtexpdf") end)
if pdf then SILE.require("packages/pdf") end
local inputfilter = SILE.require("packages/inputfilter").exports
-- URL escape sequence, URL fragment:
local preferBreakBefore = "%#"
-- URL path elements, URL query arguments, acceptable extras:
local preferBreakAfter = ":/.;?&=!_-"
-- URL scheme:
local alwaysBreakAfter = ":" -- Must have only one character here!
local escapeRegExpMinimal = function (str)
-- Minimalist = just what's needed for the above strings
return string.gsub(str, '([%.%?%-%%])', '%%%1')
end
local breakPattern = "["..escapeRegExpMinimal(preferBreakBefore..preferBreakAfter..alwaysBreakAfter).."]"
local urlFilter = function (node, content, options)
if type(node) == "table" then return node end
local result = {}
for token in SU.gtoke(node, breakPattern) do
if token.string then
result[#result+1] = token.string
else
if string.find(preferBreakBefore, escapeRegExpMinimal(token.separator)) then
-- Accepts breaking before, and at the extreme worst after.
result[#result+1] = inputfilter.createCommand(
content.pos, content.col, content.line,
"penalty", { penalty = options.primaryPenalty }, nil
)
result[#result+1] = token.separator
result[#result+1] = inputfilter.createCommand(
content.pos, content.col, content.line,
"penalty", { penalty = options.worsePenalty }, nil
)
elseif token.separator == alwaysBreakAfter then
-- Accept breaking after (only).
result[#result+1] = token.separator
result[#result+1] = inputfilter.createCommand(
content.pos, content.col, content.line,
"penalty", { penalty = options.primaryPenalty }, nil
)
else
-- Accept breaking after, but tolerate breaking before.
result[#result+1] = inputfilter.createCommand(
content.pos, content.col, content.line,
"penalty", { penalty = options.secondaryPenalty }, nil
)
result[#result+1] = token.separator
result[#result+1] = inputfilter.createCommand(
content.pos, content.col, content.line,
"penalty", { penalty = options.primaryPenalty }, nil
)
end
end
end
return result
end
SILE.settings.declare({
parameter = "url.linebreak.primaryPenalty",
type = "integer",
default = 100,
help = "Penalty for breaking lines in URLs at preferred breakpoints"
})
SILE.settings.declare({
parameter = "url.linebreak.secondaryPenalty",
type = "integer",
default = 200,
help = "Penalty for breaking lines in URLs at tolerable breakpoints (should be higher than url.linebreak.primaryPenalty)"
})
SILE.registerCommand("href", function (options, content)
if not pdf then return SILE.process(content) end
if options.src then
SILE.call("pdf:link", { dest = options.src, external = true,
borderwidth = options.borderwidth,
borderstyle = options.borderstyle,
bordercolor = options.bordercolor,
borderoffset = options.borderoffset },
content)
else
options.src = content[1]
SILE.call("pdf:link", { dest = options.src, external = true,
borderwidth = options.borderwidth,
borderstyle = options.borderstyle,
bordercolor = options.bordercolor,
borderoffset = options.borderoffset },
function (_, _)
SILE.call("url", { language = options.language }, content)
end)
end
end, "Inserts a PDF hyperlink.")
SILE.registerCommand("url", function (options, content)
SILE.settings.temporarily(function ()
local primaryPenalty = SILE.settings.get("url.linebreak.primaryPenalty")
local secondaryPenalty = SILE.settings.get("url.linebreak.secondaryPenalty")
local worsePenalty = primaryPenalty + secondaryPenalty
if options.language then
SILE.languageSupport.loadLanguage(options.language)
if options.language == "fr" then
-- Trick the engine by declaring a "fake"" language that doesn't apply
-- the typographic rules for punctuations
SILE.hyphenator.languages["_fr_noSpacingRules"] = SILE.hyphenator.languages.fr
-- Not needed (the engine already defaults to SILE.nodeMakers.unicode if
-- the language is not found):
-- SILE.nodeMakers._fr_noSpacingRules = SILE.nodeMakers.unicode
SILE.settings.set("document.language", "_fr_noSpacingRules")
else
SILE.settings.set("document.language", options.language)
end
else
SILE.settings.set("document.language", 'und')
end
local result = inputfilter.transformContent(content, urlFilter, {
primaryPenalty = primaryPenalty,
secondaryPenalty = secondaryPenalty,
worsePenalty = worsePenalty
})
SILE.call("code", {}, result)
end)
end, "Inserts penalties in an URL so it can be broken over multiple lines at appropriate places.")
SILE.registerCommand("code", function(options, content)
SILE.call("verbatim:font", options, content)
end)
return {
documentation = [[\begin{document}
This package enhances the typesetting of URLs in two ways.
First, the \code{\\url} command will automatically insert breakpoints into unwieldy
URLs like \url{https://github.com/sile-typesetter/sile-typesetter.github.io/tree/master/examples}
so that they can be broken up over multiple lines.
It also provides the
\code{\\href[src=...]\{\}} command which inserts PDF hyperlinks,
\href[src=http://www.sile-typesetter.org/]{like this}.
The \code{\\href} command accepts the same \code{borderwidth}, \code{bordercolor},
\code{borderstyle} and \code{borderoffset} styling options as the \code{\\pdf:link} command
from the \code{pdf} package, for instance
\href[src=http://www.sile-typesetter.org/, borderwidth=0.4pt, bordercolor=blue, borderstyle=underline]{like this}.
||||||| 190683a8
This package enhances the typesetting of URLs in two ways.
First, the \code{\\url} command will automatically insert breakpoints into unwieldy
URLs like \url{https://github.com/sile-typesetter/sile-typesetter.github.io/tree/master/examples}
so that they can be broken up over multiple lines.
It also provides the
\code{\\href[src=...]\{\}} command which inserts PDF hyperlinks,
\href[src=http://www.sile-typesetter.org/]{like this}.
The \code{\\href} command accepts the same \code{borderwidth}, \code{bordercolor},
\code{borderstyle} and \code{borderoffset} styling options as the \code{\\pdf:link} command
from the \code{pdf} package, for instance
\href[src=http://www.sile-typesetter.org/, borderwidth=0.4pt, bordercolor=blue, borderstyle=underline]{like this}.
\end{document}]]
}
|
SILE.require("packages/verbatim")
local pdf
pcall(function() pdf = require("justenoughlibtexpdf") end)
if pdf then SILE.require("packages/pdf") end
local inputfilter = SILE.require("packages/inputfilter").exports
-- URL escape sequence, URL fragment:
local preferBreakBefore = "%#"
-- URL path elements, URL query arguments, acceptable extras:
local preferBreakAfter = ":/.;?&=!_-"
-- URL scheme:
local alwaysBreakAfter = ":" -- Must have only one character here!
local escapeRegExpMinimal = function (str)
-- Minimalist = just what's needed for the above strings
return string.gsub(str, '([%.%?%-%%])', '%%%1')
end
local breakPattern = "["..escapeRegExpMinimal(preferBreakBefore..preferBreakAfter..alwaysBreakAfter).."]"
local urlFilter = function (node, content, options)
if type(node) == "table" then return node end
local result = {}
for token in SU.gtoke(node, breakPattern) do
if token.string then
result[#result+1] = token.string
else
if string.find(preferBreakBefore, escapeRegExpMinimal(token.separator)) then
-- Accepts breaking before, and at the extreme worst after.
result[#result+1] = inputfilter.createCommand(
content.pos, content.col, content.line,
"penalty", { penalty = options.primaryPenalty }, nil
)
result[#result+1] = token.separator
result[#result+1] = inputfilter.createCommand(
content.pos, content.col, content.line,
"penalty", { penalty = options.worsePenalty }, nil
)
elseif token.separator == alwaysBreakAfter then
-- Accept breaking after (only).
result[#result+1] = token.separator
result[#result+1] = inputfilter.createCommand(
content.pos, content.col, content.line,
"penalty", { penalty = options.primaryPenalty }, nil
)
else
-- Accept breaking after, but tolerate breaking before.
result[#result+1] = inputfilter.createCommand(
content.pos, content.col, content.line,
"penalty", { penalty = options.secondaryPenalty }, nil
)
result[#result+1] = token.separator
result[#result+1] = inputfilter.createCommand(
content.pos, content.col, content.line,
"penalty", { penalty = options.primaryPenalty }, nil
)
end
end
end
return result
end
SILE.settings.declare({
parameter = "url.linebreak.primaryPenalty",
type = "integer",
default = 100,
help = "Penalty for breaking lines in URLs at preferred breakpoints"
})
SILE.settings.declare({
parameter = "url.linebreak.secondaryPenalty",
type = "integer",
default = 200,
help = "Penalty for breaking lines in URLs at tolerable breakpoints (should be higher than url.linebreak.primaryPenalty)"
})
SILE.registerCommand("href", function (options, content)
if not pdf then return SILE.process(content) end
if options.src then
SILE.call("pdf:link", { dest = options.src, external = true,
borderwidth = options.borderwidth,
borderstyle = options.borderstyle,
bordercolor = options.bordercolor,
borderoffset = options.borderoffset },
content)
else
options.src = content[1]
SILE.call("pdf:link", { dest = options.src, external = true,
borderwidth = options.borderwidth,
borderstyle = options.borderstyle,
bordercolor = options.bordercolor,
borderoffset = options.borderoffset },
function (_, _)
SILE.call("url", { language = options.language }, content)
end)
end
end, "Inserts a PDF hyperlink.")
SILE.registerCommand("url", function (options, content)
SILE.settings.temporarily(function ()
local primaryPenalty = SILE.settings.get("url.linebreak.primaryPenalty")
local secondaryPenalty = SILE.settings.get("url.linebreak.secondaryPenalty")
local worsePenalty = primaryPenalty + secondaryPenalty
if options.language then
SILE.languageSupport.loadLanguage(options.language)
if options.language == "fr" then
-- Trick the engine by declaring a "fake"" language that doesn't apply
-- the typographic rules for punctuations
SILE.hyphenator.languages["_fr_noSpacingRules"] = SILE.hyphenator.languages.fr
-- Not needed (the engine already defaults to SILE.nodeMakers.unicode if
-- the language is not found):
-- SILE.nodeMakers._fr_noSpacingRules = SILE.nodeMakers.unicode
SILE.settings.set("document.language", "_fr_noSpacingRules")
else
SILE.settings.set("document.language", options.language)
end
else
SILE.settings.set("document.language", 'und')
end
local result = inputfilter.transformContent(content, urlFilter, {
primaryPenalty = primaryPenalty,
secondaryPenalty = secondaryPenalty,
worsePenalty = worsePenalty
})
SILE.call("code", {}, result)
end)
end, "Inserts penalties in an URL so it can be broken over multiple lines at appropriate places.")
SILE.registerCommand("code", function(options, content)
SILE.call("verbatim:font", options, content)
end)
return {
documentation = [[\begin{document}
This package enhances the typesetting of URLs in two ways.
First, it provides the \code{\\href[src=...]\{\}} command which
inserts PDF hyperlinks,
\href[src=http://www.sile-typesetter.org/]{like this}.
The \code{\\href} command accepts the same \code{borderwidth},
\code{bordercolor}, \code{borderstyle} and \code{borderoffset} styling
options as the \code{\\pdf:link} command from the \code{pdf} package,
for instance
\href[src=http://www.sile-typesetter.org/, borderwidth=0.4pt,
bordercolor=blue, borderstyle=underline]{like this}.
Nowadays, it is a common practice to have URLs in print articles
(whether it is a good practice or not is yet \em{another} topic).
Therefore, the package also provides the \code{\\url} command, which will
automatically insert breakpoints into unwieldy
URLs like \url{https://github.com/sile-typesetter/sile-typesetter.github.io/tree/master/examples}
so that they can be broken up over multiple lines.
It allows line breaks after the colon, and before or after appropriate
segments of an URL (path elements, query parts, fragments, etc.).
By default, the \code{\\url} command ignores the current language,
as one would not want hyphenation to occur in URL segments. If you have no
other choice, however, you can pass it a \code{language} option
to enforce a language to be applied. Note that if French (\code{fr})
is selected, the special typographic rules applying to punctuations
in this language are disabled.
To typeset an URL and at the same type have it as active hyperlink,
one can use the \code{\\href} command without the \code{src} option,
but with the URL passed as argument.
The breaks are controlled by two penalty settings, \code{url.linebreak.primaryPenalty}
for preferred breakpoints and, for less acceptable but still tolerable breakpoints,
\code{url.linebreak.secondaryPenalty} – its value should
logically be higher than the previous one.
\end{document}]]
}
|
docs(packages): Fix mangled merge artifacts from f295974
|
docs(packages): Fix mangled merge artifacts from f295974
|
Lua
|
mit
|
alerque/sile,alerque/sile,alerque/sile,alerque/sile
|
1477f9bc981978bea28a265099acb3355110a11c
|
premake5.lua
|
premake5.lua
|
local environment = require "environment"
workspace "imquery"
configurations{ "Debug", "Release" }
startproject "testimq"
flags { "C++11" }
filter "system:windows"
defines {"_CRT_SECURE_NO_WARNINGS" }
project "imq"
kind "StaticLib"
language "C++"
targetdir "bin/%{cfg.buildcfg}"
files {
"include/imq/**.h",
"src/imq/**.cpp",
"grammar/imq/grammar/IMQLangBaseListener.cpp",
"grammar/imq/grammar/IMQLangBaseListener.h",
"grammar/imq/grammar/IMQLangLexer.cpp",
"grammar/imq/grammar/IMQLangLexer.h",
"grammar/imq/grammar/IMQLangListener.cpp",
"grammar/imq/grammar/IMQLangListener.h",
"grammar/imq/grammar/IMQLangParser.cpp",
"grammar/imq/grammar/IMQLangParser.h"
}
includedirs {"include/imq", "grammar", environment.ANTLR_CPP_PATH}
links {environment.ANTLR_LIB}
defines {"_SCL_SECURE_NO_WARNINGS"}
prebuildcommands {
"{ECHO} Cleaning grammar",
"{RMDIR} grammar/imq/grammar",
"{ECHO} Building grammar",
environment.ANTLR_CMD .. " -o grammar/imq/grammar -package imq -Dlanguage=Cpp IMQLang.g4"
}
filter "configurations:Debug"
libdirs {environment.ANTLR_DEBUG_LIB_DIR}
defines {"DEBUG"}
symbols "On"
filter "configurations:Release"
libdirs {environment.ANTLR_RELEASE_LIB_DIR}
defines {"NDEBUG"}
optimize "On"
project "iqc"
kind "ConsoleApp"
language "C++"
targetdir "bin/%{cfg.buildcfg}"
files {"include/iqc/**.h", "src/iqc/**.cpp"}
includedirs {"include", "include/iqc", "include/iqc/thirdparty", "grammar", environment.ANTLR_CPP_PATH}
libdirs {"bin"}
links {"imq", environment.ANTLR_LIB}
filter "configurations:Debug"
libdirs {environment.ANTLR_DEBUG_LIB_DIR}
defines {"DEBUG"}
symbols "On"
filter "configurations:Release"
libdirs {environment.ANTLR_RELEASE_LIB_DIR}
defines {"NDEBUG"}
optimize "On"
project "testimq"
kind "ConsoleApp"
language "C++"
targetdir "bin/%{cfg.buildcfg}"
files {"include/test/**.h", "src/test/**.cpp"}
includedirs {"include", "include/test", "grammar", environment.GTEST_PATH .. "/" .. environment.GTEST_INCLUDE_DIR, environment.ANTLR_CPP_PATH}
libdirs {"bin"}
links {"imq", environment.GTEST_LIB, environment.ANTLR_LIB}
filter "configurations:Debug"
libdirs {environment.GTEST_PATH .. "/" .. environment.GTEST_DEBUG_LIB_DIR, environment.ANTLR_DEBUG_LIB_DIR}
defines {"DEBUG"}
symbols "On"
filter "configurations:Release"
libdirs {environment.GTEST_PATH .. "/" .. environment.GTEST_RELEASE_LIB_DIR, environment.ANTLR_RELEASE_LIB_DIR}
defines {"NDEBUG"}
optimize "On"
filter "system:linux"
links {"pthread"}
|
local environment = require "environment"
workspace "imquery"
configurations{ "Debug", "Release" }
startproject "testimq"
flags { "C++11" }
filter "system:windows"
defines {"_CRT_SECURE_NO_WARNINGS" }
project "imq"
kind "StaticLib"
language "C++"
targetdir "bin/%{cfg.buildcfg}"
files {
"include/imq/**.h",
"src/imq/**.cpp",
"grammar/imq/grammar/IMQLangBaseListener.cpp",
"grammar/imq/grammar/IMQLangBaseListener.h",
"grammar/imq/grammar/IMQLangLexer.cpp",
"grammar/imq/grammar/IMQLangLexer.h",
"grammar/imq/grammar/IMQLangListener.cpp",
"grammar/imq/grammar/IMQLangListener.h",
"grammar/imq/grammar/IMQLangParser.cpp",
"grammar/imq/grammar/IMQLangParser.h"
}
includedirs {"include/imq", "grammar", environment.ANTLR_CPP_PATH}
links {environment.ANTLR_LIB}
defines {"_SCL_SECURE_NO_WARNINGS"}
prebuildcommands {
"{ECHO} Cleaning grammar",
"{RMDIR} grammar/imq/grammar",
"{ECHO} Building grammar",
environment.ANTLR_CMD .. " -o grammar/imq/grammar -package imq -Dlanguage=Cpp IMQLang.g4"
}
filter "configurations:Debug"
libdirs {environment.ANTLR_DEBUG_LIB_DIR}
defines {"DEBUG"}
symbols "On"
filter "configurations:Release"
libdirs {environment.ANTLR_RELEASE_LIB_DIR}
defines {"NDEBUG"}
optimize "On"
project "iqc"
kind "ConsoleApp"
language "C++"
targetdir "bin/%{cfg.buildcfg}"
files {"include/iqc/**.h", "src/iqc/**.cpp"}
includedirs {"include", "include/iqc", "include/iqc/thirdparty", "grammar", environment.ANTLR_CPP_PATH}
libdirs {"bin"}
links {"imq", environment.ANTLR_LIB}
filter "configurations:Debug"
libdirs {environment.ANTLR_DEBUG_LIB_DIR}
defines {"DEBUG"}
symbols "On"
filter "configurations:Release"
libdirs {environment.ANTLR_RELEASE_LIB_DIR}
defines {"NDEBUG"}
optimize "On"
project "testimq"
kind "ConsoleApp"
language "C++"
targetdir "bin/%{cfg.buildcfg}"
files {"include/test/**.h", "src/test/**.cpp"}
includedirs {"include", "include/test", "grammar", environment.GTEST_PATH .. "/" .. environment.GTEST_INCLUDE_DIR, environment.ANTLR_CPP_PATH}
libdirs {"bin"}
links {"imq", environment.GTEST_LIB, environment.ANTLR_LIB}
filter "configurations:Debug"
libdirs {environment.GTEST_PATH .. "/" .. environment.GTEST_DEBUG_LIB_DIR, environment.ANTLR_DEBUG_LIB_DIR}
defines {"DEBUG"}
symbols "On"
filter "configurations:Release"
libdirs {environment.GTEST_PATH .. "/" .. environment.GTEST_RELEASE_LIB_DIR, environment.ANTLR_RELEASE_LIB_DIR}
defines {"NDEBUG"}
optimize "On"
filter "system:linux"
links {"pthread"}
|
Fix indentation
|
Fix indentation
|
Lua
|
mit
|
redxdev/imquery,redxdev/imquery,redxdev/imquery
|
94bfe1476826da03ffc1fc066789fc8e11a04dfc
|
cherry/engine/sound.lua
|
cherry/engine/sound.lua
|
--------------------------------------------------------------------------------
local _ = require 'cherry.libs.underscore'
--------------------------------------------------------------------------------
local Sound = {}
--------------------------------------------------------------------------------
function Sound:init(extension)
local _sound = _.defaults(extension or {}, {
isOff = App.user:isSoundOff() or App.SOUND_OFF,
themes = {},
sfx = {},
options = {},
channels = {},
volume = App.user:soundVolume() or 1,
loopOnStart = false
})
setmetatable(_sound, { __index = Sound })
if(_sound.isOff) then
_sound:off(_sound.channels.music)
_sound:off(_sound.channels.effects)
end
if(_sound.loopOnStart) then
_sound:loop()
end
if(_sound.onStart) then
_sound:onStart()
end
return _sound
end
-----------------------------------------------------------------------------------------
function Sound:nextTheme()
self.currentTheme = self.currentTheme + 1
if(self.currentTheme == (#self.themes+1)) then self.currentTheme = 1 end
audio.pause(self.channels.music)
self.channels.music = audio.play( self.themes[self.currentTheme], {
onComplete = function()
self:nextTheme()
end,
})
end
--------------------------------------------------------------------------------
function Sound:toggleAll()
self.isOff = not self.isOff
App.user:saveSoundSettings(self.isOff)
self:toggleMusic()
self:toggleEffects()
end
function Sound:toggleMusic()
self:toggle(self.channels.music)
-- if(not self.isOff) then self:loop() end
end
function Sound:toggleEffects()
self:toggle(self.channels.effects)
end
--------------------------------------------------------------------------------
function Sound:off(channel)
audio.setVolume( 0, { channel = channel } )
end
function Sound:on(channel)
audio.setVolume( 1, { channel = channel } )
end
function Sound:toggle(channel)
if(self.isOff) then
self:off(channel)
else
self:on(channel)
end
end
--------------------------------------------------------------------------------
function Sound:musicVolume(value)
audio.setVolume( value, { channel = self.channels.music } )
end
function Sound:effectsVolume(value)
audio.setVolume( value, { channel = self.channels.effects } )
end
--------------------------------------------------------------------------------
function Sound:effect(effect)
if(self.isOff or App.SOUND_OFF) then
return
end
self.channels.effects = audio.play(effect)
end
function Sound:play(track)
self:stop()
if(self.isOff or App.SOUND_OFF) then
return
end
timer.performWithDelay(100, function()
self.channels.music = audio.play(track, {
onComplete = function()
self:play(track)
end
})
end)
end
function Sound:loop(num)
self.currentTheme = num or 0
self:nextTheme()
end
function Sound:stop()
audio.stop()
end
--------------------------------------------------------------------------------
return Sound
|
--------------------------------------------------------------------------------
local _ = require 'cherry.libs.underscore'
--------------------------------------------------------------------------------
local Sound = {}
--------------------------------------------------------------------------------
function Sound:init(extension)
local _sound = _.defaults(extension or {}, {
isOff = App.user:isSoundOff() or App.SOUND_OFF,
themes = {},
sfx = {},
options = {},
channels = {},
volume = App.user:soundVolume() or 1,
loopOnStart = false
})
setmetatable(_sound, { __index = Sound })
if(_sound.isOff) then
_sound:off(_sound.channels.music)
_sound:off(_sound.channels.effects)
end
if(_sound.loopOnStart) then
_sound:loop()
end
if(_sound.onStart) then
_sound:onStart()
end
return _sound
end
-----------------------------------------------------------------------------------------
function Sound:nextTheme()
self.currentTheme = self.currentTheme + 1
if(self.currentTheme == (#self.themes+1)) then self.currentTheme = 1 end
audio.pause(self.channels.music)
self.channels.music = audio.play( self.themes[self.currentTheme], {
onComplete = function()
self:nextTheme()
end,
})
end
--------------------------------------------------------------------------------
function Sound:toggleAll()
self.isOff = not self.isOff
App.user:saveSoundSettings(self.isOff)
self:toggleMusic()
self:toggleEffects()
end
function Sound:toggleMusic()
self:toggle(self.channels.music)
-- if(not self.isOff) then self:loop() end
end
function Sound:toggleEffects()
self:toggle(self.channels.effects)
end
--------------------------------------------------------------------------------
function Sound:off(channel)
audio.setVolume( 0, { channel = channel } )
end
function Sound:on(channel)
audio.setVolume( 1, { channel = channel } )
end
function Sound:toggle(channel)
if(self.isOff) then
self:off(channel)
else
self:on(channel)
end
end
--------------------------------------------------------------------------------
function Sound:musicVolume(value)
audio.setVolume( value, { channel = self.channels.music } )
end
function Sound:effectsVolume(value)
audio.setVolume( value, { channel = self.channels.effects } )
end
--------------------------------------------------------------------------------
function Sound:effect(effect)
if(self.isOff or App.SOUND_OFF) then
return
end
self.channels.effects = audio.play(effect)
end
function Sound:play(track)
self:stop()
if(self.isOff or App.SOUND_OFF) then
return
end
self.channels.music = audio.play(track, {loops = -1})
end
function Sound:loop(num)
self.currentTheme = num or 0
self:nextTheme()
end
function Sound:stop()
audio.stop()
end
--------------------------------------------------------------------------------
return Sound
|
fixed track loops
|
fixed track loops
|
Lua
|
bsd-3-clause
|
chrisdugne/cherry
|
694024de82c10d0f578f7c43c8fe288df695b420
|
premakeUtils.lua
|
premakeUtils.lua
|
function coInitParams(_params)
baseAbsPath = os.getcwd()
print("baseAbsPath: "..baseAbsPath)
externalAbsPath = baseAbsPath .. "/external"
buildPath = "build/" .. _ACTION
genAbsPath = baseAbsPath .. "/build/gen"
buildAbsPath = baseAbsPath .. "/" .. buildPath
coreRelativePath = "."
if _params.coreRelativePath then
coreRelativePath = _params.coreRelativePath
end
coreAbsolutePath = path.getabsolute(coreRelativePath)
prebuildPath = coreAbsolutePath .. "/build/prebuild.exe"
versionMajor = 0
versionMinor = 0
versionBuild = 0
end
function coSetWorkspaceDefaults(_name, _srcDirs)
print("Generating workspace ".._name.."... (in "..buildPath..")")
workspace(_name)
configurations {"debug", "release", "prebuildDebug", "prebuildRelease"}
location(buildPath)
objdir(buildPath .. "/obj")
libdirs { buildPath .. "/bin" }
targetdir(buildPath .. "/bin")
defines { "coVERSION_MAJOR="..versionMajor, "coVERSION_MINOR="..versionMinor, "coVERSION_BUILD="..versionBuild }
includedirs { "build/gen" }
includedirs(_srcDirs)
end
function coSetPCH(_dir, _projectName, _fileName)
pchheader(_projectName .. "/".. _fileName .. '.h')
pchsource(_fileName .. '.cpp')
--[[
filter { "action:vs*" }
pchheader(_fileName .. '.h')
pchsource(_fileName .. '.cpp')
filter { "action:not vs*" }
pchheader(_dir .. '/' .. _fileName .. '.h')
filter {}
--]]
end
function coSetProjectDefaults(_name, _options)
local buildLocation = buildAbsPath.."/projects"
print("Generating project ".._name.."... (in "..buildLocation..")")
project(_name)
architecture "x86_64"
warnings "Extra"
kind "StaticLib"
location(buildLocation)
defines { "coPROJECT_NAME=".._name }
debugdir "$(OutDir)"
if not (_options and _options.prebuildDependency) then
--removeconfigurations {"prebuild*"}
configurations { "debug", "release" }
end
filter{"configurations:debug or release"}
defines {"coREFLECT_ENABLED"}
filter { "configurations:debug or prebuildDebug" }
targetsuffix "_d"
filter { "configurations:release or prebuildRelease" }
optimize "On"
filter {}
end
function coSetCppProjectDefaults(_name)
coSetProjectDefaults(_name)
rtti "Off"
language "C++"
exceptionhandling "Off"
vectorextensions "SSE2"
floatingpoint "Fast"
editandcontinue "Off"
flags { "Symbols", "NoMinimalRebuild", "FatalWarnings", "C++14", "MultiProcessorCompile" }
files { "**.cpp", "**.h"}
if os.isfile("pch.h") then
coSetPCH(co_projectDir, _name, "pch")
end
filter { "gmake" }
buildoptions { "-Wno-reorder", "-Wno-deprecated" }
includedirs { gmakeIncludeDir }
filter { "vs*" }
defines { "_HAS_EXCEPTIONS=0" }
--flags { "StaticRuntime" }
linkoptions { "/ENTRY:mainCRTStartup" }
filter { "configurations:release or prebuildRelease" }
flags { "OptimizeSpeed", "NoFramePointer"}
filter {"configurations:debug or release"}
if os.isfile("reflect.cpp") then
local command = prebuildPath .. ' "' .. path.getabsolute(co_projectDir, baseAbsPath) .. "/.." .. '" "' .. genAbsPath .. '" "' .. _name .. '" "'.. _name ..'/pch.h"'
command = command .. ' -I="$(UniversalCRT_IncludePath)"'
prebuildcommands{command}
end
filter {}
end
function coSetShaderProjectDefaults(_name)
coSetProjectDefaults(_name)
kind "Utility"
-- Defaults
files { "**.vert", "**.frag"}
--language "C++" -- We don't have better here
---[[
shaderOutPath = "$(OutDir)/shaders/%{file.name}.spv"
filter {'files:**.vert or **.frag'}
buildmessage 'Compiling %{file.relpath}'
buildcommands
{
'$(VULKAN_SDK)/Bin/glslangValidator.exe -V -o "'..shaderOutPath ..'" %{file.relpath}'
}
buildoutputs { shaderOutPath }
filter {}
--]]
end
function coSetProjectDependencies(_deps)
if not co_dependencies then
co_dependencies = {}
end
for _,v in pairs(_deps) do table.insert(co_dependencies, v) end
links(_deps)
end
function coFindDir(_srcDirs, _dirName)
for _, d in pairs(_srcDirs) do
local foundDirs = os.matchdirs(d.."/**".._dirName)
for _, e in pairs(foundDirs) do
return e
end
end
return nil
end
function coIncludeProject(_srcDirs, _projectName)
local foundDir = coFindDir(_srcDirs, _projectName)
if foundDir == nil then
error("Failed to find the project: "..p)
else
co_projectDir = foundDir
include(foundDir)
end
end
function coGenerateProjectWorkspace(_params)
coSetWorkspaceDefaults(_params.name, _params.srcDirs)
startproject(_params.projects[0])
for _, p in pairs(_params.projects) do
coIncludeProject(_params.srcDirs, p)
--include(pPath)
end
if co_dependencies then
for _, d in pairs(co_dependencies) do
coIncludeProject(_params.srcDirs, d)
end
end
end
|
function coInitParams(_params)
baseAbsPath = os.getcwd()
print("baseAbsPath: "..baseAbsPath)
externalAbsPath = baseAbsPath .. "/external"
buildPath = "build/" .. _ACTION
genAbsPath = baseAbsPath .. "/build/gen"
buildAbsPath = baseAbsPath .. "/" .. buildPath
coreRelativePath = "."
if _params.coreRelativePath then
coreRelativePath = _params.coreRelativePath
end
coreAbsolutePath = path.getabsolute(coreRelativePath)
prebuildPath = coreAbsolutePath .. "/build/prebuild.exe"
versionMajor = 0
versionMinor = 0
versionBuild = 0
end
function coSetWorkspaceDefaults(_name, _srcDirs)
print("Generating workspace ".._name.."... (in "..buildPath..")")
workspace(_name)
configurations {"debug", "release", "prebuildDebug", "prebuildRelease"}
location(buildPath)
objdir(buildPath .. "/obj")
libdirs { buildPath .. "/bin" }
targetdir(buildPath .. "/bin")
defines { "coVERSION_MAJOR="..versionMajor, "coVERSION_MINOR="..versionMinor, "coVERSION_BUILD="..versionBuild }
includedirs { "build/gen" }
includedirs(_srcDirs)
end
function coSetPCH(_dir, _projectName, _fileName)
pchheader(_projectName .. "/".. _fileName .. '.h')
pchsource(_fileName .. '.cpp')
--[[
filter { "action:vs*" }
pchheader(_fileName .. '.h')
pchsource(_fileName .. '.cpp')
filter { "action:not vs*" }
pchheader(_dir .. '/' .. _fileName .. '.h')
filter {}
--]]
end
function coSetProjectDefaults(_name, _options)
local buildLocation = buildAbsPath.."/projects"
print("Generating project ".._name.."... (in "..buildLocation..")")
project(_name)
architecture "x86_64"
warnings "Extra"
kind "StaticLib"
location(buildLocation)
defines { "coPROJECT_NAME=".._name }
debugdir "$(OutDir)"
if not (_options and _options.prebuildDependency) then
--removeconfigurations {"prebuild*"}
configurations { "debug", "release" }
end
filter{"configurations:debug or release"}
defines {"coREFLECT_ENABLED"}
filter { "configurations:debug or prebuildDebug" }
targetsuffix "_d"
filter { "configurations:release or prebuildRelease" }
optimize "On"
filter {}
end
function coSetCppProjectDefaults(_name)
coSetProjectDefaults(_name)
rtti "Off"
language "C++"
exceptionhandling "Off"
vectorextensions "SSE2"
floatingpoint "Fast"
editandcontinue "Off"
flags { "Symbols", "NoMinimalRebuild", "FatalWarnings", "C++14", "MultiProcessorCompile" }
files { "**.cpp", "**.h"}
if os.isfile("pch.h") then
coSetPCH(co_projectDir, _name, "pch")
end
filter { "gmake" }
buildoptions { "-Wno-reorder", "-Wno-deprecated" }
includedirs { gmakeIncludeDir }
filter { "action:vs*" }
defines { "_HAS_EXCEPTIONS=0" }
--flags { "StaticRuntime" }
--linkoptions { "/ENTRY:mainCRTStartup" } -- TODO: Not working with DLL, should avoid that case somehow.
linkoptions {"/ignore:4221"} -- warns when .cpp are empty depending on the order of obj linking.
filter { "configurations:release or prebuildRelease" }
flags { "OptimizeSpeed", "NoFramePointer"}
filter {"configurations:debug or release"}
if os.isfile("reflect.cpp") then
local command = prebuildPath .. ' "' .. path.getabsolute(co_projectDir, baseAbsPath) .. "/.." .. '" "' .. genAbsPath .. '" "' .. _name .. '" "'.. _name ..'/pch.h"'
command = command .. ' -I="$(UniversalCRT_IncludePath)"'
prebuildcommands{command}
end
filter {}
end
function coSetShaderProjectDefaults(_name)
coSetProjectDefaults(_name)
kind "Utility"
-- Defaults
files { "**.vert", "**.frag"}
--language "C++" -- We don't have better here
---[[
shaderOutPath = "$(OutDir)/shaders/%{file.name}.spv"
filter {'files:**.vert or **.frag'}
buildmessage 'Compiling %{file.relpath}'
buildcommands
{
'$(VULKAN_SDK)/Bin/glslangValidator.exe -V -o "'..shaderOutPath ..'" %{file.relpath}'
}
buildoutputs { shaderOutPath }
filter {}
--]]
end
function coSetProjectDependencies(_deps)
if not co_dependencies then
co_dependencies = {}
end
for _,v in pairs(_deps) do table.insert(co_dependencies, v) end
links(_deps)
end
function coFindDir(_srcDirs, _dirName)
for _, d in pairs(_srcDirs) do
local foundDirs = os.matchdirs(d.."/**".._dirName)
for _, e in pairs(foundDirs) do
return e
end
end
return nil
end
function coIncludeProject(_srcDirs, _projectName)
local foundDir = coFindDir(_srcDirs, _projectName)
if foundDir == nil then
error("Failed to find the project: "..p)
else
co_projectDir = foundDir
include(foundDir)
end
end
function coGenerateProjectWorkspace(_params)
coSetWorkspaceDefaults(_params.name, _params.srcDirs)
startproject(_params.projects[0])
for _, p in pairs(_params.projects) do
coIncludeProject(_params.srcDirs, p)
--include(pPath)
end
if co_dependencies then
for _, d in pairs(co_dependencies) do
coIncludeProject(_params.srcDirs, d)
end
end
end
|
- Disabled some annoying link errors. - Fixed premake linkoptions not being taken into account by premake. - Remove the mainCRTstartup linkoption because it's not working correctly with DLLs.
|
- Disabled some annoying link errors.
- Fixed premake linkoptions not being taken into account by premake.
- Remove the mainCRTstartup linkoption because it's not working correctly with DLLs.
|
Lua
|
mit
|
smogpill/core,smogpill/core
|
7f5457b0584880befcbcfcbef47310b41281cb34
|
lua/wincent/commandt/private/match_listing.lua
|
lua/wincent/commandt/private/match_listing.lua
|
-- SPDX-FileCopyrightText: Copyright 2022-present Greg Hurrell and contributors.
-- SPDX-License-Identifier: BSD-2-Clause
local match_listing = {}
local Window = require('wincent.commandt.private.window').Window
local merge = require('wincent.commandt.private.merge')
local border_height = 2
local prompt_height = 1 + border_height
local MatchListing = {}
local mt = {
__index = MatchListing,
}
function MatchListing.new(options)
options = merge({
height = 15,
margin = 0,
position = 'bottom',
selection_highlight = 'PMenuSel',
}, options or {})
-- TODO: validate options
local m = {
_height = options.height,
_margin = options.margin,
_position = options.position,
_lines = nil,
_results = nil,
_selected = nil,
_selection_highlight = options.selection_highlight,
_window = nil,
}
setmetatable(m, mt)
return m
end
function MatchListing:close()
if self._window then
self._window:close()
end
end
local format_line = function(line, width, selected)
local prefix = selected and '> ' or ' '
-- Right pad so that selection highlighting is shown across full width.
if width < 104 then
if #line > 99 then
-- No padding needed.
line = prefix .. line
else
line = prefix .. string.format('%-' .. (width - #prefix) .. 's', line)
end
else
-- Avoid: "invalid option" caused by format argument > 99.
line = prefix .. string.format('%-99s', line)
local diff = width - line:len()
if diff > 0 then
line = line .. string.rep(' ', diff)
end
end
-- Trim right to make sure we never wrap.
return line:sub(1, width)
end
function MatchListing:select(selected)
assert(type(selected) == 'number')
assert(selected > 0)
assert(selected <= #self._results)
if self._window then
local width = self._window:width() or vim.o.columns -- BUG: width may be cached/stale
local previous_selection = format_line(self._results[self._selected], width, false)
self._window:replace_line(previous_selection, self._selected)
self._window:unhighlight_line(self._selected)
self._selected = selected
local new_selection = format_line(self._results[self._selected], width, true)
self._window:replace_line(new_selection, self._selected)
self._window:highlight_line(self._selected)
end
end
function MatchListing:show()
local bottom = nil
local top = nil
if self._position == 'center' then
local available_height = vim.o.lines - vim.o.cmdheight
local used_height = self._height -- note we need to know how high the match listing is going to be
+ 2 -- match listing border
+ 3 -- our height
local remaining_height = math.max(1, available_height - used_height)
top = math.floor(remaining_height / 2) + 3 -- prompt height
elseif self._position == 'bottom' then
bottom = prompt_height
else
top = prompt_height
end
-- TODO: deal with other options, like reverse
if self._window == nil then
self._window = Window.new({
bottom = bottom,
description = 'CommandT [match listing]',
filetype = 'CommandTMatchListing',
height = self._height,
margin = self._margin,
on_close = function()
-- print('got on_close for match listing')
self._window = nil
-- TODO: shouldn't really get this first, but close prompt
end,
on_leave = function()
-- print('got on_leave for match listing')
end,
on_resize = function()
if self._results then
-- Cause paddings to be re-rendered.
self:update(self._results, { selected = self._selected })
end
end,
selection_highlight = self._selection_highlight,
title = '',
top = top,
})
end
self._window:show()
end
function MatchListing:update(results, options)
self._selected = options.selected
self._results = results
if self._window then
local width = self._window:width() or vim.o.columns
self._lines = {}
for i, result in ipairs(results) do
local selected = i == self._selected
local line = format_line(result, width, selected)
table.insert(self._lines, line)
end
self._window:unhighlight()
self._window:replace_lines(self._lines, { adjust_height = true })
if self._selected then
self._window:highlight_line(self._selected)
end
end
end
match_listing.MatchListing = MatchListing
return match_listing
|
-- SPDX-FileCopyrightText: Copyright 2022-present Greg Hurrell and contributors.
-- SPDX-License-Identifier: BSD-2-Clause
local match_listing = {}
local Window = require('wincent.commandt.private.window').Window
local merge = require('wincent.commandt.private.merge')
local border_height = 2
local prompt_height = 1 + border_height
local MatchListing = {}
local mt = {
__index = MatchListing,
}
function MatchListing.new(options)
options = merge({
height = 15,
margin = 0,
position = 'bottom',
selection_highlight = 'PMenuSel',
}, options or {})
-- TODO: validate options
local m = {
_height = options.height,
_margin = options.margin,
_position = options.position,
_lines = nil,
_results = nil,
_selected = nil,
_selection_highlight = options.selection_highlight,
_window = nil,
}
setmetatable(m, mt)
return m
end
function MatchListing:close()
if self._window then
self._window:close()
end
end
local format_line = function(line, width, selected)
local prefix = selected and '> ' or ' '
-- Sanitize some control characters, plus blackslashes.
line = line
:gsub('\\', '\\\\')
:gsub('\b', '\\b')
:gsub('\f', '\\f')
:gsub('\n', '\\n')
:gsub('\r', '\\r')
:gsub('\t', '\\t')
:gsub('\v', '\\v')
-- Right pad so that selection highlighting is shown across full width.
if width < 104 then
if #line > 99 then
-- No padding needed.
line = prefix .. line
else
line = prefix .. string.format('%-' .. (width - #prefix) .. 's', line)
end
else
-- Avoid: "invalid option" caused by format argument > 99.
line = prefix .. string.format('%-99s', line)
local diff = width - line:len()
if diff > 0 then
line = line .. string.rep(' ', diff)
end
end
-- Trim right to make sure we never wrap.
return line:sub(1, width)
end
function MatchListing:select(selected)
assert(type(selected) == 'number')
assert(selected > 0)
assert(selected <= #self._results)
if self._window then
local width = self._window:width() or vim.o.columns -- BUG: width may be cached/stale
local previous_selection = format_line(self._results[self._selected], width, false)
self._window:replace_line(previous_selection, self._selected)
self._window:unhighlight_line(self._selected)
self._selected = selected
local new_selection = format_line(self._results[self._selected], width, true)
self._window:replace_line(new_selection, self._selected)
self._window:highlight_line(self._selected)
end
end
function MatchListing:show()
local bottom = nil
local top = nil
if self._position == 'center' then
local available_height = vim.o.lines - vim.o.cmdheight
local used_height = self._height -- note we need to know how high the match listing is going to be
+ 2 -- match listing border
+ 3 -- our height
local remaining_height = math.max(1, available_height - used_height)
top = math.floor(remaining_height / 2) + 3 -- prompt height
elseif self._position == 'bottom' then
bottom = prompt_height
else
top = prompt_height
end
-- TODO: deal with other options, like reverse
if self._window == nil then
self._window = Window.new({
bottom = bottom,
description = 'CommandT [match listing]',
filetype = 'CommandTMatchListing',
height = self._height,
margin = self._margin,
on_close = function()
-- print('got on_close for match listing')
self._window = nil
-- TODO: shouldn't really get this first, but close prompt
end,
on_leave = function()
-- print('got on_leave for match listing')
end,
on_resize = function()
if self._results then
-- Cause paddings to be re-rendered.
self:update(self._results, { selected = self._selected })
end
end,
selection_highlight = self._selection_highlight,
title = '',
top = top,
})
end
self._window:show()
end
function MatchListing:update(results, options)
self._selected = options.selected
self._results = results
if self._window then
local width = self._window:width() or vim.o.columns
self._lines = {}
for i, result in ipairs(results) do
local selected = i == self._selected
local line = format_line(result, width, selected)
table.insert(self._lines, line)
end
self._window:unhighlight()
self._window:replace_lines(self._lines, { adjust_height = true })
if self._selected then
self._window:highlight_line(self._selected)
end
end
end
match_listing.MatchListing = MatchListing
return match_listing
|
fix: don't let control characters mess up the display
|
fix: don't let control characters mess up the display
Before:
╭─ CommandT [file] ────────────────────────────────────────────╮
│> │
╰──────────────────────────────────────────────────────────────╯
╭──────────────────────────────────────────────────────────────╮
│> │
│↳ Icon^M │
│↳ │
│ brew.rb │
│ ...etc │
╰──────────────────────────────────────────────────────────────╯
After:
╭─ CommandT [file] ────────────────────────────────────────────╮
│> │
╰──────────────────────────────────────────────────────────────╯
╭──────────────────────────────────────────────────────────────╮
│> Icon\r │
│ brew.rb │
│ ...etc │
╰──────────────────────────────────────────────────────────────╯
Note that this is a display-only thing, to stop undesired wrapping and
other visual distortions. You can't actually type "Icr" and expect it to
match the file (these is no "r" in the name), although you can open it
by accepting the selection.
Closes: https://github.com/wincent/command-t/issues/402
|
Lua
|
bsd-2-clause
|
wincent/command-t,wincent/command-t,wincent/command-t
|
11464a3373ea3e3f7fc9aee934544d4b1e1bd96e
|
lualib/mongo.lua
|
lualib/mongo.lua
|
local bson = require "bson"
local socket = require "socket"
local socketchannel = require "socketchannel"
local skynet = require "skynet"
local driver = require "mongo.driver"
local rawget = rawget
local assert = assert
local bson_encode = bson.encode
local bson_encode_order = bson.encode_order
local bson_decode = bson.decode
local empty_bson = bson_encode {}
local mongo = {}
mongo.null = assert(bson.null)
mongo.maxkey = assert(bson.maxkey)
mongo.minkey = assert(bson.minkey)
mongo.type = assert(bson.type)
local mongo_cursor = {}
local cursor_meta = {
__index = mongo_cursor,
}
local mongo_client = {}
local client_meta = {
__index = function(self, key)
return rawget(mongo_client, key) or self:getDB(key)
end,
__tostring = function (self)
local port_string
if self.port then
port_string = ":" .. tostring(self.port)
else
port_string = ""
end
return "[mongo client : " .. self.host .. port_string .."]"
end,
__gc = function(self)
self:disconnect()
end
}
local mongo_db = {}
local db_meta = {
__index = function (self, key)
return rawget(mongo_db, key) or self:getCollection(key)
end,
__tostring = function (self)
return "[mongo db : " .. self.name .. "]"
end
}
local mongo_collection = {}
local collection_meta = {
__index = function(self, key)
return rawget(mongo_collection, key) or self:getCollection(key)
end ,
__tostring = function (self)
return "[mongo collection : " .. self.full_name .. "]"
end
}
local function dispatch_reply(so)
local len_reply = so:read(4)
local reply = so:read(driver.length(len_reply))
local result = {}
local succ, reply_id, document, cursor_id, startfrom = driver.reply(reply, result)
result.document = document
result.cursor_id = cursor_id
result.startfrom = startfrom
result.data = reply
return reply_id, succ, result
end
function mongo.client( obj )
obj.port = obj.port or 27017
obj.__id = 0
obj.__sock = socketchannel.channel {
host = obj.host,
port = obj.port,
response = dispatch_reply,
}
setmetatable(obj, client_meta)
obj.__sock:connect()
return obj
end
function mongo_client:getDB(dbname)
local db = {
connection = self,
name = dbname,
full_name = dbname,
database = false,
__cmd = dbname .. "." .. "$cmd",
}
db.database = db
return setmetatable(db, db_meta)
end
function mongo_client:disconnect()
if self.__sock then
local so = self.__sock
self.__sock = false
so:close()
end
end
function mongo_client:genId()
local id = self.__id + 1
self.__id = id
return id
end
function mongo_client:runCommand(...)
if not self.admin then
self.admin = self:getDB "admin"
end
return self.admin:runCommand(...)
end
function mongo_db:runCommand(cmd,cmd_v,...)
local conn = self.connection
local request_id = conn:genId()
local sock = conn.__sock
local bson_cmd
if not cmd_v then
bson_cmd = bson_encode_order(cmd,1)
else
bson_cmd = bson_encode_order(cmd,cmd_v,...)
end
local pack = driver.query(request_id, 0, self.__cmd, 0, 1, bson_cmd)
local doc = sock:request(pack, request_id).document
return bson_decode(doc)
end
function mongo_db:getCollection(collection)
local col = {
connection = self.connection,
name = collection,
full_name = self.full_name .. "." .. collection,
database = self.database,
}
self[collection] = setmetatable(col, collection_meta)
return col
end
mongo_collection.getCollection = mongo_db.getCollection
function mongo_collection:insert(doc)
if doc._id == nil then
doc._id = bson.objectid()
end
local sock = self.connection.__sock
local pack = driver.insert(0, self.full_name, bson_encode(doc))
-- flags support 1: ContinueOnError
sock:request(pack)
end
function mongo_collection:batch_insert(docs)
for i=1,#docs do
if docs[i]._id == nil then
docs[i]._id = bson.objectid()
end
docs[i] = bson_encode(docs[i])
end
local sock = self.connection.__sock
local pack = driver.insert(0, self.full_name, docs)
sock:request(pack)
end
function mongo_collection:update(selector,update,upsert,multi)
local flags = (upsert and 1 or 0) + (multi and 2 or 0)
local sock = self.connection.__sock
local pack = driver.update(self.full_name, flags, bson_encode(selector), bson_encode(update))
sock:request(pack)
end
function mongo_collection:delete(selector, single)
local sock = self.connection.__sock
local pack = driver.delete(self.full_name, single, bson_encode(selector))
sock:request(pack)
end
function mongo_collection:findOne(query, selector)
local conn = self.connection
local request_id = conn:genId()
local sock = conn.__sock
local pack = driver.query(request_id, 0, self.full_name, 0, 1, query and bson_encode(query) or empty_bson, selector and bson_encode(selector))
local doc = sock:request(pack, request_id).document
return bson_decode(doc)
end
function mongo_collection:find(query, selector)
return setmetatable( {
__collection = self,
__query = query and bson_encode(query) or empty_bson,
__selector = selector and bson_encode(selector),
__ptr = nil,
__data = nil,
__cursor = nil,
__document = {},
__flags = 0,
} , cursor_meta)
end
function mongo_cursor:hasNext()
if self.__ptr == nil then
if self.__document == nil then
return false
end
local conn = self.__collection.connection
local request_id = conn:genId()
local sock = conn.__sock
local pack
if self.__data == nil then
pack = driver.query(request_id, self.__flags, self.__collection.full_name,0,0,self.__query,self.__selector)
else
if self.__cursor then
pack = driver.more(request_id, self.__collection.full_name,0,self.__cursor)
else
-- no more
self.__document = nil
self.__data = nil
return false
end
end
local ok, result = pcall(sock.request,sock,pack, request_id)
local doc = result.document
local cursor = result.cursor_id
if ok then
if doc then
self.__document = doc
self.__data = data
self.__ptr = 1
self.__cursor = cursor
return true
else
self.__document = nil
self.__data = nil
self.__cursor = nil
return false
end
else
self.__document = nil
self.__data = nil
self.__cursor = nil
if doc then
local err = bson_decode(doc)
error(err["$err"])
else
error("Reply from mongod error")
end
end
end
return true
end
function mongo_cursor:next()
if self.__ptr == nil then
error "Call hasNext first"
end
local r = bson_decode(self.__document[self.__ptr])
self.__ptr = self.__ptr + 1
if self.__ptr > #self.__document then
self.__ptr = nil
end
return r
end
function mongo_cursor:close()
-- todo: warning hasNext after close
if self.__cursor then
local sock = self.__collection.connection.__sock
local pack = driver.kill(self.__cursor)
sock:request(pack)
end
end
return mongo
|
local bson = require "bson"
local socket = require "socket"
local socketchannel = require "socketchannel"
local skynet = require "skynet"
local driver = require "mongo.driver"
local rawget = rawget
local assert = assert
local bson_encode = bson.encode
local bson_encode_order = bson.encode_order
local bson_decode = bson.decode
local empty_bson = bson_encode {}
local mongo = {}
mongo.null = assert(bson.null)
mongo.maxkey = assert(bson.maxkey)
mongo.minkey = assert(bson.minkey)
mongo.type = assert(bson.type)
local mongo_cursor = {}
local cursor_meta = {
__index = mongo_cursor,
}
local mongo_client = {}
local client_meta = {
__index = function(self, key)
return rawget(mongo_client, key) or self:getDB(key)
end,
__tostring = function (self)
local port_string
if self.port then
port_string = ":" .. tostring(self.port)
else
port_string = ""
end
return "[mongo client : " .. self.host .. port_string .."]"
end,
__gc = function(self)
self:disconnect()
end
}
local mongo_db = {}
local db_meta = {
__index = function (self, key)
return rawget(mongo_db, key) or self:getCollection(key)
end,
__tostring = function (self)
return "[mongo db : " .. self.name .. "]"
end
}
local mongo_collection = {}
local collection_meta = {
__index = function(self, key)
return rawget(mongo_collection, key) or self:getCollection(key)
end ,
__tostring = function (self)
return "[mongo collection : " .. self.full_name .. "]"
end
}
local function dispatch_reply(so)
local len_reply = so:read(4)
local reply = so:read(driver.length(len_reply))
local result = { result = {} }
local succ, reply_id, document, cursor_id, startfrom = driver.reply(reply, result.result)
result.document = document
result.cursor_id = cursor_id
result.startfrom = startfrom
result.data = reply
return reply_id, succ, result
end
function mongo.client( obj )
obj.port = obj.port or 27017
obj.__id = 0
obj.__sock = socketchannel.channel {
host = obj.host,
port = obj.port,
response = dispatch_reply,
}
setmetatable(obj, client_meta)
obj.__sock:connect()
return obj
end
function mongo_client:getDB(dbname)
local db = {
connection = self,
name = dbname,
full_name = dbname,
database = false,
__cmd = dbname .. "." .. "$cmd",
}
db.database = db
return setmetatable(db, db_meta)
end
function mongo_client:disconnect()
if self.__sock then
local so = self.__sock
self.__sock = false
so:close()
end
end
function mongo_client:genId()
local id = self.__id + 1
self.__id = id
return id
end
function mongo_client:runCommand(...)
if not self.admin then
self.admin = self:getDB "admin"
end
return self.admin:runCommand(...)
end
function mongo_db:runCommand(cmd,cmd_v,...)
local conn = self.connection
local request_id = conn:genId()
local sock = conn.__sock
local bson_cmd
if not cmd_v then
bson_cmd = bson_encode_order(cmd,1)
else
bson_cmd = bson_encode_order(cmd,cmd_v,...)
end
local pack = driver.query(request_id, 0, self.__cmd, 0, 1, bson_cmd)
local doc = sock:request(pack, request_id).document
return bson_decode(doc)
end
function mongo_db:getCollection(collection)
local col = {
connection = self.connection,
name = collection,
full_name = self.full_name .. "." .. collection,
database = self.database,
}
self[collection] = setmetatable(col, collection_meta)
return col
end
mongo_collection.getCollection = mongo_db.getCollection
function mongo_collection:insert(doc)
if doc._id == nil then
doc._id = bson.objectid()
end
local sock = self.connection.__sock
local pack = driver.insert(0, self.full_name, bson_encode(doc))
-- flags support 1: ContinueOnError
sock:request(pack)
end
function mongo_collection:batch_insert(docs)
for i=1,#docs do
if docs[i]._id == nil then
docs[i]._id = bson.objectid()
end
docs[i] = bson_encode(docs[i])
end
local sock = self.connection.__sock
local pack = driver.insert(0, self.full_name, docs)
sock:request(pack)
end
function mongo_collection:update(selector,update,upsert,multi)
local flags = (upsert and 1 or 0) + (multi and 2 or 0)
local sock = self.connection.__sock
local pack = driver.update(self.full_name, flags, bson_encode(selector), bson_encode(update))
sock:request(pack)
end
function mongo_collection:delete(selector, single)
local sock = self.connection.__sock
local pack = driver.delete(self.full_name, single, bson_encode(selector))
sock:request(pack)
end
function mongo_collection:findOne(query, selector)
local conn = self.connection
local request_id = conn:genId()
local sock = conn.__sock
local pack = driver.query(request_id, 0, self.full_name, 0, 1, query and bson_encode(query) or empty_bson, selector and bson_encode(selector))
local doc = sock:request(pack, request_id).document
return bson_decode(doc)
end
function mongo_collection:find(query, selector)
return setmetatable( {
__collection = self,
__query = query and bson_encode(query) or empty_bson,
__selector = selector and bson_encode(selector),
__ptr = nil,
__data = nil,
__cursor = nil,
__document = {},
__flags = 0,
} , cursor_meta)
end
function mongo_cursor:hasNext()
if self.__ptr == nil then
if self.__document == nil then
return false
end
local conn = self.__collection.connection
local request_id = conn:genId()
local sock = conn.__sock
local pack
if self.__data == nil then
pack = driver.query(request_id, self.__flags, self.__collection.full_name,0,0,self.__query,self.__selector)
else
if self.__cursor then
pack = driver.more(request_id, self.__collection.full_name,0,self.__cursor)
else
-- no more
self.__document = nil
self.__data = nil
return false
end
end
local ok, result = pcall(sock.request,sock,pack, request_id)
local doc = result.document
local cursor = result.cursor_id
if ok then
if doc then
self.__document = result.result
self.__data = result.data
self.__ptr = 1
self.__cursor = cursor
return true
else
self.__document = nil
self.__data = nil
self.__cursor = nil
return false
end
else
self.__document = nil
self.__data = nil
self.__cursor = nil
if doc then
local err = bson_decode(doc)
error(err["$err"])
else
error("Reply from mongod error")
end
end
end
return true
end
function mongo_cursor:next()
if self.__ptr == nil then
error "Call hasNext first"
end
local r = bson_decode(self.__document[self.__ptr])
self.__ptr = self.__ptr + 1
if self.__ptr > #self.__document then
self.__ptr = nil
end
return r
end
function mongo_cursor:close()
-- todo: warning hasNext after close
if self.__cursor then
local sock = self.__collection.connection.__sock
local pack = driver.kill(self.__cursor)
sock:request(pack)
end
end
return mongo
|
bugfix: mongo driver, reply result
|
bugfix: mongo driver, reply result
|
Lua
|
mit
|
MoZhonghua/skynet,cmingjian/skynet,liuxuezhan/skynet,qyli/test,qyli/test,lynx-seu/skynet,zzh442856860/skynet,JiessieDawn/skynet,cdd990/skynet,javachengwc/skynet,helling34/skynet,lawnight/skynet,yinjun322/skynet,lawnight/skynet,cmingjian/skynet,lc412/skynet,xcjmine/skynet,sundream/skynet,fztcjjl/skynet,kyle-wang/skynet,bigrpg/skynet,pigparadise/skynet,codingabc/skynet,chenjiansnail/skynet,ilylia/skynet,czlc/skynet,cuit-zhaxin/skynet,ypengju/skynet_comment,harryzeng/skynet,Zirpon/skynet,winglsh/skynet,vizewang/skynet,cpascal/skynet,cmingjian/skynet,lawnight/skynet,JiessieDawn/skynet,catinred2/skynet,vizewang/skynet,fhaoquan/skynet,bttscut/skynet,bigrpg/skynet,jxlczjp77/skynet,ludi1991/skynet,ag6ag/skynet,chfg007/skynet,KittyCookie/skynet,zzh442856860/skynet-Note,Ding8222/skynet,harryzeng/skynet,zhaijialong/skynet,ypengju/skynet_comment,ludi1991/skynet,fhaoquan/skynet,u20024804/skynet,jiuaiwo1314/skynet,chuenlungwang/skynet,zzh442856860/skynet,lc412/skynet,liuxuezhan/skynet,KittyCookie/skynet,zhangshiqian1214/skynet,xinmingyao/skynet,KittyCookie/skynet,chenjiansnail/skynet,cuit-zhaxin/skynet,zzh442856860/skynet-Note,kebo/skynet,icetoggle/skynet,zhangshiqian1214/skynet,sanikoyes/skynet,xcjmine/skynet,cpascal/skynet,bigrpg/skynet,nightcj/mmo,microcai/skynet,zzh442856860/skynet,your-gatsby/skynet,wangyi0226/skynet,zhoukk/skynet,bttscut/skynet,yunGit/skynet,sundream/skynet,winglsh/skynet,gitfancode/skynet,cloudwu/skynet,pichina/skynet,peimin/skynet,ilylia/skynet,zzh442856860/skynet-Note,jiuaiwo1314/skynet,winglsh/skynet,xjdrew/skynet,yinjun322/skynet,xinjuncoding/skynet,gitfancode/skynet,kyle-wang/skynet,letmefly/skynet,czlc/skynet,xcjmine/skynet,rainfiel/skynet,sanikoyes/skynet,firedtoad/skynet,letmefly/skynet,wangyi0226/skynet,xinjuncoding/skynet,nightcj/mmo,matinJ/skynet,leezhongshan/skynet,samael65535/skynet,dymx101/skynet,KAndQ/skynet,your-gatsby/skynet,helling34/skynet,korialuo/skynet,letmefly/skynet,yunGit/skynet,felixdae/skynet,pichina/skynet,LuffyPan/skynet,microcai/skynet,zhaijialong/skynet,togolwb/skynet,icetoggle/skynet,great90/skynet,Markal128/skynet,cuit-zhaxin/skynet,lc412/skynet,zhangshiqian1214/skynet,ruleless/skynet,KAndQ/skynet,MRunFoss/skynet,pigparadise/skynet,cloudwu/skynet,kebo/skynet,your-gatsby/skynet,puXiaoyi/skynet,letmefly/skynet,wangjunwei01/skynet,samael65535/skynet,jxlczjp77/skynet,qyli/test,sdgdsffdsfff/skynet,firedtoad/skynet,javachengwc/skynet,icetoggle/skynet,Zirpon/skynet,gitfancode/skynet,catinred2/skynet,nightcj/mmo,LiangMa/skynet,hongling0/skynet,MRunFoss/skynet,hongling0/skynet,sanikoyes/skynet,enulex/skynet,Zirpon/skynet,MoZhonghua/skynet,cloudwu/skynet,bingo235/skynet,ludi1991/skynet,bingo235/skynet,xjdrew/skynet,harryzeng/skynet,Ding8222/skynet,zhoukk/skynet,zhangshiqian1214/skynet,helling34/skynet,liuxuezhan/skynet,jxlczjp77/skynet,plsytj/skynet,longmian/skynet,chuenlungwang/skynet,plsytj/skynet,pigparadise/skynet,kebo/skynet,cdd990/skynet,codingabc/skynet,LuffyPan/skynet,felixdae/skynet,cdd990/skynet,lynx-seu/skynet,Markal128/skynet,plsytj/skynet,xubigshu/skynet,zhangshiqian1214/skynet,LiangMa/skynet,qyli/test,great90/skynet,bttscut/skynet,matinJ/skynet,rainfiel/skynet,czlc/skynet,togolwb/skynet,u20024804/skynet,javachengwc/skynet,asanosoyokaze/skynet,JiessieDawn/skynet,leezhongshan/skynet,chfg007/skynet,vizewang/skynet,ruleless/skynet,dymx101/skynet,zhouxiaoxiaoxujian/skynet,codingabc/skynet,wangjunwei01/skynet,peimin/skynet_v0.1_with_notes,lynx-seu/skynet,kyle-wang/skynet,peimin/skynet_v0.1_with_notes,microcai/skynet,samael65535/skynet,xjdrew/skynet,ag6ag/skynet,zhaijialong/skynet,KAndQ/skynet,ruleless/skynet,cpascal/skynet,enulex/skynet,wangjunwei01/skynet,xinmingyao/skynet,wangyi0226/skynet,zzh442856860/skynet-Note,MetSystem/skynet,ludi1991/skynet,liuxuezhan/skynet,chenjiansnail/skynet,sdgdsffdsfff/skynet,sundream/skynet,boyuegame/skynet,catinred2/skynet,iskygame/skynet,LuffyPan/skynet,leezhongshan/skynet,peimin/skynet,zhouxiaoxiaoxujian/skynet,MetSystem/skynet,longmian/skynet,dymx101/skynet,iskygame/skynet,fztcjjl/skynet,zhouxiaoxiaoxujian/skynet,zhangshiqian1214/skynet,yinjun322/skynet,pichina/skynet,rainfiel/skynet,chuenlungwang/skynet,Markal128/skynet,korialuo/skynet,ilylia/skynet,QuiQiJingFeng/skynet,xinjuncoding/skynet,felixdae/skynet,boyuegame/skynet,asanosoyokaze/skynet,firedtoad/skynet,LiangMa/skynet,korialuo/skynet,MoZhonghua/skynet,enulex/skynet,ag6ag/skynet,puXiaoyi/skynet,fztcjjl/skynet,sdgdsffdsfff/skynet,hongling0/skynet,zhoukk/skynet,fhaoquan/skynet,puXiaoyi/skynet,longmian/skynet,yunGit/skynet,u20024804/skynet,xubigshu/skynet,Ding8222/skynet,togolwb/skynet,MRunFoss/skynet,iskygame/skynet,great90/skynet,asanosoyokaze/skynet,QuiQiJingFeng/skynet,lawnight/skynet,boyuegame/skynet,jiuaiwo1314/skynet,MetSystem/skynet,chfg007/skynet,ypengju/skynet_comment,bingo235/skynet,matinJ/skynet,QuiQiJingFeng/skynet
|
57fb2b364320c5bc51e60da5fda558ca847d3c55
|
mods/throwing/fire_arrow.lua
|
mods/throwing/fire_arrow.lua
|
minetest.register_craftitem("throwing:arrow_fire", {
description = "Fire Arrow",
inventory_image = "throwing_arrow_fire.png",
})
minetest.register_node("throwing:arrow_fire_box", {
drawtype = "nodebox",
node_box = {
type = "fixed",
fixed = {
-- Shaft
{-6.5/17, -1.5/17, -1.5/17, 6.5/17, 1.5/17, 1.5/17},
--Spitze
{-4.5/17, 2.5/17, 2.5/17, -3.5/17, -2.5/17, -2.5/17},
{-8.5/17, 0.5/17, 0.5/17, -6.5/17, -0.5/17, -0.5/17},
--Federn
{6.5/17, 1.5/17, 1.5/17, 7.5/17, 2.5/17, 2.5/17},
{7.5/17, -2.5/17, 2.5/17, 6.5/17, -1.5/17, 1.5/17},
{7.5/17, 2.5/17, -2.5/17, 6.5/17, 1.5/17, -1.5/17},
{6.5/17, -1.5/17, -1.5/17, 7.5/17, -2.5/17, -2.5/17},
{7.5/17, 2.5/17, 2.5/17, 8.5/17, 3.5/17, 3.5/17},
{8.5/17, -3.5/17, 3.5/17, 7.5/17, -2.5/17, 2.5/17},
{8.5/17, 3.5/17, -3.5/17, 7.5/17, 2.5/17, -2.5/17},
{7.5/17, -2.5/17, -2.5/17, 8.5/17, -3.5/17, -3.5/17},
}
},
tiles = {"throwing_arrow_fire.png", "throwing_arrow_fire.png", "throwing_arrow_fire_back.png", "throwing_arrow_fire_front.png", "throwing_arrow_fire_2.png", "throwing_arrow_fire.png"},
groups = {not_in_creative_inventory=1},
})
local THROWING_ARROW_ENTITY={
physical = false,
visual = "wielditem",
visual_size = {x=0.1, y=0.1},
textures = {"throwing:arrow_fire_box"},
lastpos={},
collisionbox = {0,0,0,0,0,0},
player = "",
}
THROWING_ARROW_ENTITY.on_step = function(self, dtime)
local newpos = self.object:getpos()
if self.lastpos.x ~= nil then
for _, pos in pairs(throwing_get_trajectoire(self, newpos)) do
local node = minetest.get_node(pos)
local objs = minetest.get_objects_inside_radius({x=pos.x,y=pos.y,z=pos.z}, 2)
for k, obj in pairs(objs) do
local objpos = obj:getpos()
if throwing_is_player(self.player, obj) or throwing_is_entity(obj) then
if (pos.x - objpos.x < 0.5 and pos.x - objpos.x > -0.5) and (pos.z - objpos.z < 0.5 and pos.z - objpos.z > -0.5) then
local damage = 4
obj:punch(self.object, 1.0, {
full_punch_interval=1.0,
damage_groups={fleshy=damage},
}, nil)
if math.random(0,100) % 2 == 0 then -- 50% of chance to drop //MFF (Mg|07/27/15)
minetest.add_item(pos, 'default:stick')
end
self.object:remove()
return
end
end
end
if node.name ~= "air" and node.name ~= "throwing:light" then
if node.name ~= "ignore" then
minetest.set_node(self.lastpos, {name="fire:basic_flame"})
end
self.object:remove()
return
end
if minetest.get_node(pos).name == "air" then
minetest.set_node(pos, {name="throwing:light"})
end
if minetest.get_node(self.lastpos).name == "throwing:light" then
minetest.remove_node(self.lastpos)
end
self.lastpos={x=pos.x, y=pos.y, z=pos.z}
end
end
self.lastpos={x=newpos.x, y=newpos.y, z=newpos.z}
end
minetest.register_entity("throwing:arrow_fire_entity", THROWING_ARROW_ENTITY)
minetest.register_node("throwing:light", {
drawtype = "airlike",
paramtype = "light",
sunlight_propagates = true,
tiles = {"throwing_empty.png"},
light_source = LIGHT_MAX-4,
selection_box = {
type = "fixed",
fixed = {
{0,0,0,0,0,0}
}
},
groups = {not_in_creative_inventory=1}
})
minetest.register_abm({
nodenames = {"throwing:light"},
interval = 10,
chance = 1,
action = function(pos, node)
minetest.remove_node(pos)
end
})
minetest.register_craft({
output = 'throwing:arrow_fire 4',
recipe = {
{'default:stick', 'default:stick', 'bucket:bucket_lava'},
},
replacements = {
{"bucket:bucket_lava", "bucket:bucket_empty"}
}
})
minetest.register_craft({
output = 'throwing:arrow_fire 4',
recipe = {
{'bucket:bucket_lava', 'default:stick', 'default:stick'},
},
replacements = {
{"bucket:bucket_lava", "bucket:bucket_empty"}
}
})
|
minetest.register_craftitem("throwing:arrow_fire", {
description = "Fire Arrow",
inventory_image = "throwing_arrow_fire.png",
})
minetest.register_node("throwing:arrow_fire_box", {
drawtype = "nodebox",
node_box = {
type = "fixed",
fixed = {
-- Shaft
{-6.5/17, -1.5/17, -1.5/17, 6.5/17, 1.5/17, 1.5/17},
--Spitze
{-4.5/17, 2.5/17, 2.5/17, -3.5/17, -2.5/17, -2.5/17},
{-8.5/17, 0.5/17, 0.5/17, -6.5/17, -0.5/17, -0.5/17},
--Federn
{6.5/17, 1.5/17, 1.5/17, 7.5/17, 2.5/17, 2.5/17},
{7.5/17, -2.5/17, 2.5/17, 6.5/17, -1.5/17, 1.5/17},
{7.5/17, 2.5/17, -2.5/17, 6.5/17, 1.5/17, -1.5/17},
{6.5/17, -1.5/17, -1.5/17, 7.5/17, -2.5/17, -2.5/17},
{7.5/17, 2.5/17, 2.5/17, 8.5/17, 3.5/17, 3.5/17},
{8.5/17, -3.5/17, 3.5/17, 7.5/17, -2.5/17, 2.5/17},
{8.5/17, 3.5/17, -3.5/17, 7.5/17, 2.5/17, -2.5/17},
{7.5/17, -2.5/17, -2.5/17, 8.5/17, -3.5/17, -3.5/17},
}
},
tiles = {"throwing_arrow_fire.png", "throwing_arrow_fire.png", "throwing_arrow_fire_back.png", "throwing_arrow_fire_front.png", "throwing_arrow_fire_2.png", "throwing_arrow_fire.png"},
groups = {not_in_creative_inventory=1},
})
local THROWING_ARROW_ENTITY={
physical = false,
visual = "wielditem",
visual_size = {x=0.1, y=0.1},
textures = {"throwing:arrow_fire_box"},
lastpos={},
collisionbox = {0,0,0,0,0,0},
player = "",
}
THROWING_ARROW_ENTITY.on_step = function(self, dtime)
local newpos = self.object:getpos()
if self.lastpos.x ~= nil then
for _, pos in pairs(throwing_get_trajectoire(self, newpos)) do
local node = minetest.get_node(pos)
local objs = minetest.get_objects_inside_radius({x=pos.x,y=pos.y,z=pos.z}, 2)
for k, obj in pairs(objs) do
local objpos = obj:getpos()
if throwing_is_player(self.player, obj) or throwing_is_entity(obj) then
if (pos.x - objpos.x < 0.5 and pos.x - objpos.x > -0.5) and (pos.z - objpos.z < 0.5 and pos.z - objpos.z > -0.5) then
local damage = 4
obj:punch(self.object, 1.0, {
full_punch_interval=1.0,
damage_groups={fleshy=damage},
}, nil)
if math.random(0,100) % 2 == 0 then -- 50% of chance to drop //MFF (Mg|07/27/15)
minetest.add_item(pos, 'default:stick')
end
self.object:remove()
return
end
end
end
if node.name ~= "air" and node.name ~= "throwing:light" and node.name ~= "fire:basic_flame" then
if node.name ~= "ignore" then
minetest.set_node(self.lastpos, {name="fire:basic_flame"})
end
self.object:remove()
return
end
if minetest.get_node(pos).name == "air" then
minetest.set_node(pos, {name="throwing:light"})
end
if minetest.get_node(self.lastpos).name == "throwing:light" then
minetest.remove_node(self.lastpos)
end
self.lastpos={x=pos.x, y=pos.y, z=pos.z}
end
end
self.lastpos={x=newpos.x, y=newpos.y, z=newpos.z}
end
minetest.register_entity("throwing:arrow_fire_entity", THROWING_ARROW_ENTITY)
minetest.register_node("throwing:light", {
drawtype = "airlike",
paramtype = "light",
sunlight_propagates = true,
tiles = {"throwing_empty.png"},
light_source = LIGHT_MAX-4,
selection_box = {
type = "fixed",
fixed = {
{0,0,0,0,0,0}
}
},
groups = {not_in_creative_inventory=1}
})
minetest.register_abm({
nodenames = {"throwing:light"},
interval = 10,
chance = 1,
action = function(pos, node)
minetest.remove_node(pos)
end
})
minetest.register_craft({
output = 'throwing:arrow_fire 4',
recipe = {
{'default:stick', 'default:stick', 'bucket:bucket_lava'},
},
replacements = {
{"bucket:bucket_lava", "bucket:bucket_empty"}
}
})
minetest.register_craft({
output = 'throwing:arrow_fire 4',
recipe = {
{'bucket:bucket_lava', 'default:stick', 'default:stick'},
},
replacements = {
{"bucket:bucket_lava", "bucket:bucket_empty"}
}
})
|
fix fire arrows don't touch fire
|
fix fire arrows don't touch fire
|
Lua
|
unlicense
|
MinetestForFun/server-minetestforfun,MinetestForFun/server-minetestforfun,Gael-de-Sailly/minetest-minetestforfun-server,Coethium/server-minetestforfun,crabman77/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,Gael-de-Sailly/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,LeMagnesium/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,Ombridride/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,MinetestForFun/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,Coethium/server-minetestforfun,Coethium/server-minetestforfun,LeMagnesium/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server
|
321fef3de8ad4257a7089b811412742111e91671
|
kong/plugins/jwt/handler.lua
|
kong/plugins/jwt/handler.lua
|
local singletons = require "kong.singletons"
local BasePlugin = require "kong.plugins.base_plugin"
local cache = require "kong.tools.database_cache"
local responses = require "kong.tools.responses"
local constants = require "kong.constants"
local jwt_decoder = require "kong.plugins.jwt.jwt_parser"
local string_format = string.format
local ngx_re_gmatch = ngx.re.gmatch
local JwtHandler = BasePlugin:extend()
JwtHandler.PRIORITY = 1000
--- Retrieve a JWT in a request.
-- Checks for the JWT in URI parameters, then in the `Authorization` header.
-- @param request ngx request object
-- @param conf Plugin configuration
-- @return token JWT token contained in request or nil
-- @return err
local function retrieve_token(request, conf)
local uri_parameters = request.get_uri_args()
for _, v in ipairs(conf.uri_param_names) do
if uri_parameters[v] then
return uri_parameters[v]
end
end
local authorization_header = request.get_headers()["authorization"]
if authorization_header then
local iterator, iter_err = ngx_re_gmatch(authorization_header, "\\s*[Bb]earer\\s+(.+)")
if not iterator then
return nil, iter_err
end
local m, err = iterator()
if err then
return nil, err
end
if m and #m > 0 then
return m[1]
end
end
end
function JwtHandler:new()
JwtHandler.super.new(self, "jwt")
end
function JwtHandler:access(conf)
JwtHandler.super.access(self)
local token, err = retrieve_token(ngx.req, conf)
if err then
return responses.send_HTTP_INTERNAL_SERVER_ERROR(err)
end
if not token then
return responses.send_HTTP_UNAUTHORIZED()
end
-- Decode token to find out who the consumer is
local jwt, err = jwt_decoder:new(token)
if err then
return responses.send_HTTP_INTERNAL_SERVER_ERROR()
end
local claims = jwt.claims
local jwt_secret_key = claims[conf.key_claim_name]
if not jwt_secret_key then
return responses.send_HTTP_UNAUTHORIZED("No mandatory '"..conf.key_claim_name.."' in claims")
end
-- Retrieve the secret
local jwt_secret = cache.get_or_set(cache.jwtauth_credential_key(jwt_secret_key), function()
local rows, err = singletons.dao.jwt_secrets:find_all {key = jwt_secret_key}
if err then
return responses.send_HTTP_INTERNAL_SERVER_ERROR()
elseif #rows > 0 then
return rows[1]
end
end)
if not jwt_secret then
return responses.send_HTTP_FORBIDDEN("No credentials found for given '"..conf.key_claim_name.."'")
end
-- Verify "alg"
if jwt.header.alg ~= jwt_secret.algorithm then
return responses.send_HTTP_FORBIDDEN("Invalid algorithm")
end
local jwt_secret_value = jwt_secret.algorithm == "HS256" and jwt_secret.secret or jwt_secret.rsa_public_key
if conf.secret_is_base64 then
jwt_secret_value = jwt:b64_decode(jwt_secret_value)
end
-- Now verify the JWT signature
if not jwt:verify_signature(jwt_secret_value) then
return responses.send_HTTP_FORBIDDEN("Invalid signature")
end
-- Verify the JWT registered claims
local ok_claims, errors = jwt:verify_registered_claims(conf.claims_to_verify)
if not ok_claims then
return responses.send_HTTP_FORBIDDEN(errors)
end
-- Retrieve the consumer
local consumer = cache.get_or_set(cache.consumer_key(jwt_secret_key), function()
local consumer, err = singletons.dao.consumers:find {id = jwt_secret.consumer_id}
if err then
return responses.send_HTTP_INTERNAL_SERVER_ERROR(err)
end
return consumer
end)
-- However this should not happen
if not consumer then
return responses.send_HTTP_FORBIDDEN(string_format("Could not find consumer for '%s=%s'", conf.key_claim_name, jwt_secret_key))
end
ngx.req.set_header(constants.HEADERS.CONSUMER_ID, consumer.id)
ngx.req.set_header(constants.HEADERS.CONSUMER_CUSTOM_ID, consumer.custom_id)
ngx.req.set_header(constants.HEADERS.CONSUMER_USERNAME, consumer.username)
ngx.ctx.authenticated_credential = jwt_secret
end
return JwtHandler
|
local singletons = require "kong.singletons"
local BasePlugin = require "kong.plugins.base_plugin"
local cache = require "kong.tools.database_cache"
local responses = require "kong.tools.responses"
local constants = require "kong.constants"
local jwt_decoder = require "kong.plugins.jwt.jwt_parser"
local string_format = string.format
local ngx_re_gmatch = ngx.re.gmatch
local JwtHandler = BasePlugin:extend()
JwtHandler.PRIORITY = 1000
--- Retrieve a JWT in a request.
-- Checks for the JWT in URI parameters, then in the `Authorization` header.
-- @param request ngx request object
-- @param conf Plugin configuration
-- @return token JWT token contained in request or nil
-- @return err
local function retrieve_token(request, conf)
local uri_parameters = request.get_uri_args()
for _, v in ipairs(conf.uri_param_names) do
if uri_parameters[v] then
return uri_parameters[v]
end
end
local authorization_header = request.get_headers()["authorization"]
if authorization_header then
local iterator, iter_err = ngx_re_gmatch(authorization_header, "\\s*[Bb]earer\\s+(.+)")
if not iterator then
return nil, iter_err
end
local m, err = iterator()
if err then
return nil, err
end
if m and #m > 0 then
return m[1]
end
end
end
function JwtHandler:new()
JwtHandler.super.new(self, "jwt")
end
function JwtHandler:access(conf)
JwtHandler.super.access(self)
local token, err = retrieve_token(ngx.req, conf)
if err then
return responses.send_HTTP_INTERNAL_SERVER_ERROR(err)
end
if not token then
return responses.send_HTTP_UNAUTHORIZED()
end
-- Decode token to find out who the consumer is
local jwt, err = jwt_decoder:new(token)
if err then
return responses.send_HTTP_INTERNAL_SERVER_ERROR()
end
local claims = jwt.claims
local jwt_secret_key = claims[conf.key_claim_name]
if not jwt_secret_key then
return responses.send_HTTP_UNAUTHORIZED("No mandatory '"..conf.key_claim_name.."' in claims")
end
-- Retrieve the secret
local jwt_secret = cache.get_or_set(cache.jwtauth_credential_key(jwt_secret_key), function()
local rows, err = singletons.dao.jwt_secrets:find_all {key = jwt_secret_key}
if err then
return responses.send_HTTP_INTERNAL_SERVER_ERROR()
elseif #rows > 0 then
return rows[1]
end
end)
if not jwt_secret then
return responses.send_HTTP_FORBIDDEN("No credentials found for given '"..conf.key_claim_name.."'")
end
local algorithm = jwt_secret.algorithm or "HS256"
-- Verify "alg"
if jwt.header.alg ~= algorithm then
return responses.send_HTTP_FORBIDDEN("Invalid algorithm")
end
local jwt_secret_value = algorithm == "HS256" and jwt_secret.secret or jwt_secret.rsa_public_key
if conf.secret_is_base64 then
jwt_secret_value = jwt:b64_decode(jwt_secret_value)
end
-- Now verify the JWT signature
if not jwt:verify_signature(jwt_secret_value) then
return responses.send_HTTP_FORBIDDEN("Invalid signature")
end
-- Verify the JWT registered claims
local ok_claims, errors = jwt:verify_registered_claims(conf.claims_to_verify)
if not ok_claims then
return responses.send_HTTP_FORBIDDEN(errors)
end
-- Retrieve the consumer
local consumer = cache.get_or_set(cache.consumer_key(jwt_secret_key), function()
local consumer, err = singletons.dao.consumers:find {id = jwt_secret.consumer_id}
if err then
return responses.send_HTTP_INTERNAL_SERVER_ERROR(err)
end
return consumer
end)
-- However this should not happen
if not consumer then
return responses.send_HTTP_FORBIDDEN(string_format("Could not find consumer for '%s=%s'", conf.key_claim_name, jwt_secret_key))
end
ngx.req.set_header(constants.HEADERS.CONSUMER_ID, consumer.id)
ngx.req.set_header(constants.HEADERS.CONSUMER_CUSTOM_ID, consumer.custom_id)
ngx.req.set_header(constants.HEADERS.CONSUMER_USERNAME, consumer.username)
ngx.ctx.authenticated_credential = jwt_secret
end
return JwtHandler
|
fix(jwt) default algorithm to 'HS256'
|
fix(jwt) default algorithm to 'HS256'
When migrating from an older version of Kong, the 'algorithm' field is
left empty. Better to include it in the code rather than in the
migration to resolve the issue for users who already migrated.
Fix #1233
|
Lua
|
apache-2.0
|
salazar/kong,icyxp/kong,Kong/kong,jebenexer/kong,akh00/kong,smanolache/kong,jerizm/kong,ccyphers/kong,shiprabehera/kong,Kong/kong,beauli/kong,li-wl/kong,Kong/kong,Mashape/kong,Vermeille/kong
|
f4f708d3af77ce164291ede97c709b14a620785e
|
LUA/spec/eep/EepFunktionen_spec.lua
|
LUA/spec/eep/EepFunktionen_spec.lua
|
describe("EepFunktionen.lua", function()
require("ak.eep.AkEepFunktionen")
it("EEPVer steht auf \"Testsimulator\"", function()
assert.are.equals("Testsimulator", EEPVer)
end)
it("print() Funktion ", function()
clearlog()
end)
describe("EEPSetSignal", function()
describe("setzt Signal 2 auf Stellung 4", function()
EEPSetSignal(2, 4, 1)
it("gibt 4 zurück bei EEPGetSignal(2)", function()
assert.are.equals(4, EEPGetSignal(2))
end)
end)
describe("setzt Signal 2 auf Stellung 3", function()
EEPSetSignal(2, 3, 1)
it("gibt 4 zurück bei EEPGetSignal(3)", function()
assert.are.equals(3, EEPGetSignal(2))
end)
end)
end)
-- more tests pertaining to the top level
end)
|
describe("EepFunktionen.lua", function()
require("ak.eep.AkEepFunktionen")
it("EEPVer steht auf \"15\"", function()
assert.are.equals("15", EEPVer)
end)
it("print() Funktion ", function()
clearlog()
end)
describe("EEPSetSignal", function()
describe("setzt Signal 2 auf Stellung 4", function()
EEPSetSignal(2, 4, 1)
it("gibt 4 zurück bei EEPGetSignal(2)", function()
assert.are.equals(4, EEPGetSignal(2))
end)
end)
describe("setzt Signal 2 auf Stellung 3", function()
EEPSetSignal(2, 3, 1)
it("gibt 4 zurück bei EEPGetSignal(3)", function()
assert.are.equals(3, EEPGetSignal(2))
end)
end)
end)
-- more tests pertaining to the top level
end)
|
fix busted error - correct EEP-Version
|
fix busted error - correct EEP-Version
|
Lua
|
mit
|
Andreas-Kreuz/ak-lua-skripte-fuer-eep,Andreas-Kreuz/ak-lua-skripte-fuer-eep
|
4f3c1d9e962730883955d90a4fbf588b3af36167
|
imprint.lua
|
imprint.lua
|
SILE.require("packages/markdown", CASILE.casiledir)
SILE.registerCommand("imprint:font", function (options, content)
options.weight = options.weight or 400
options.size = options.size or "9pt"
options.language = options.language or "und"
options.family = options.family or "Libertinus Serif"
SILE.call("font", options, content)
end)
SILE.registerCommand("imprint", function (_, _)
SILE.settings.temporarily(function ()
local imgUnit = SILE.length("1em")
SILE.settings.set("document.lskip", SILE.nodefactory.glue())
SILE.settings.set("document.rskip", SILE.nodefactory.glue())
SILE.settings.set("document.rskip", SILE.nodefactory.glue())
SILE.settings.set("document.parskip", SILE.nodefactory.vglue("1.2ex"))
SILE.call("nofolios")
SILE.call("noindent")
SILE.call("topfill")
SILE.call("raggedright", {}, function ()
SILE.call("imprint:font", {}, function ()
SILE.settings.set("linespacing.method", "fixed")
SILE.settings.set("linespacing.fixed.baselinedistance", SILE.length("2.8ex plus 1pt minus 0.5pt"))
if CASILE.metadata.publisher and not (CASILE.layout == "app") then
SILE.processMarkdown({SU.contentToString(CASILE.metadata.publisher)})
SILE.call("par")
end
if SILE.Commands["meta:title"] then
SILE.call("font", { weight = 600, style = "Bold" }, SILE.Commands["meta:title"])
SILE.call("break")
end
if SILE.Commands["meta:creators"] then SILE.call("meta:creators") end
if SILE.Commands["meta:source"] then
SILE.call("meta:source")
SILE.call("par")
end
if SILE.Commands["meta:rights"] then
SILE.call("meta:rights")
SILE.call("par")
end
if CASILE.metadata.manufacturer then
SILE.call("skip", { height = "5.4em" })
SILE.settings.temporarily(function ()
-- luacheck: ignore qrimg
SILE.call("img", { src = qrimg, height = "5.8em" })
SILE.call("skip", { height = "-6.3em" })
SILE.settings.set("document.lskip", SILE.nodefactory.glue({ width = imgUnit * 6.5 }))
if SILE.Commands["meta:identifiers"] then SILE.call("meta:identifiers") end
SILE.call("font", { weight = 600, style = "Bold" }, { "Version: " })
SILE.call("font", { family = "Hack", size = "0.8em" }, SILE.Commands["meta:surum"])
SILE.call("break")
SILE.call("font", { weight = 600, style = "Bold" }, { "URL: " })
SILE.call("font", { family = "Hack", size = "0.8em" }, SILE.Commands["meta:url"])
-- Hack around not being able to output a vbox with an indent
-- See https://github.com/simoncozens/sile/issues/318
local lines = 1
for i = 1, #SILE.typesetter.state.nodes do
lines = lines + (SILE.typesetter.state.nodes[i]:isPenalty() and 1 or 0)
end
for _ = lines, 5 do
SILE.call("hbox")
SILE.call("break")
end
SILE.call("par")
end)
else
SILE.call("font", { weight = 600, style = "Bold" }, { "Version: " })
SILE.call("font", { family = "Hack", size = "0.8em" }, SILE.Commands["meta:surum"])
SILE.call("par")
end
if SILE.Commands["meta:contributors"] then
SILE.call("meta:contributors")
SILE.call("par")
end
if SILE.Commands["meta:extracredits"] then
SILE.call("meta:extracredits")
SILE.call("par")
end
if SILE.Commands["meta:versecredits"] then
SILE.call("meta:versecredits")
SILE.call("par")
end
if CASILE.metadata.publisher then
local distributed = SILE.call("meta:distribution")
if not distributed and SILE.Commands["meta:date"] then
if CASILE.metadata.manufacturer then
SILE.call("meta:manufacturer")
SILE.call("par")
end
SILE.call("meta:date")
SILE.call("par")
end
end
end)
end)
end)
SILE.call("par")
SILE.call("break")
end)
SILE.registerCommand("meta:distribution", function (_, _)
local layout = CASILE.layout
local distros = CASILE.metadata.distribution
local text = nil
if distros then
for _, d in pairs(distros) do
if d.layout == layout then text = d.text end
end
end
if text then
SILE.call("font", { weight = 600, style = "Bold" }, { "Dağıtım: " })
SILE.typesetter:typeset(text)
SILE.call("par")
return true
else
return false
end
end)
|
SILE.require("packages/markdown", CASILE.casiledir)
SILE.registerCommand("imprint:font", function (options, content)
options.weight = options.weight or 400
options.size = options.size or "9pt"
options.language = options.language or "und"
options.family = options.family or "Libertinus Serif"
SILE.call("font", options, content)
end)
SILE.registerCommand("imprint", function (_, _)
SILE.settings.temporarily(function ()
local imgUnit = SILE.length("1em")
SILE.settings.set("document.lskip", SILE.nodefactory.glue())
SILE.settings.set("document.rskip", SILE.nodefactory.glue())
SILE.settings.set("document.rskip", SILE.nodefactory.glue())
SILE.settings.set("document.parskip", SILE.nodefactory.vglue("1.2ex"))
SILE.call("nofolios")
SILE.call("noindent")
SILE.call("topfill")
SILE.call("raggedright", {}, function ()
SILE.call("imprint:font", {}, function ()
SILE.settings.set("linespacing.method", "fixed")
SILE.settings.set("linespacing.fixed.baselinedistance", SILE.length("2.8ex plus 1pt minus 0.5pt"))
if CASILE.metadata.publisher and not (CASILE.layout == "app") then
SILE.processMarkdown({SU.contentToString(CASILE.metadata.publisher)})
SILE.call("par")
end
if SILE.Commands["meta:title"] then
SILE.call("font", { weight = 600, style = "Bold" }, function ()
SILE.call("meta:title")
end)
SILE.call("break")
end
if SILE.Commands["meta:creators"] then SILE.call("meta:creators") end
if SILE.Commands["meta:source"] then
SILE.call("meta:source")
SILE.call("par")
end
if SILE.Commands["meta:rights"] then
SILE.call("meta:rights")
SILE.call("par")
end
if CASILE.metadata.manufacturer then
SILE.call("skip", { height = "5.4em" })
SILE.settings.temporarily(function ()
-- luacheck: ignore qrimg
SILE.call("img", { src = qrimg, height = "5.8em" })
SILE.call("skip", { height = "-6.3em" })
SILE.settings.set("document.lskip", SILE.nodefactory.glue({ width = imgUnit * 6.5 }))
if SILE.Commands["meta:identifiers"] then SILE.call("meta:identifiers") end
SILE.call("font", { weight = 600, style = "Bold" }, { "Version: " })
SILE.call("font", { family = "Hack", size = "0.8em" }, function ()
SILE.call("meta:surum")
end)
SILE.call("break")
SILE.call("font", { weight = 600, style = "Bold" }, { "URL: " })
SILE.call("font", { family = "Hack", size = "0.8em" }, function ()
SILE.call("meta:url")
end)
-- Hack around not being able to output a vbox with an indent
-- See https://github.com/simoncozens/sile/issues/318
local lines = 1
for i = 1, #SILE.typesetter.state.nodes do
lines = lines + (SILE.typesetter.state.nodes[i]:isPenalty() and 1 or 0)
end
for _ = lines, 5 do
SILE.call("hbox")
SILE.call("break")
end
SILE.call("par")
end)
else
SILE.call("font", { weight = 600, style = "Bold" }, { "Version: " })
SILE.call("font", { family = "Hack", size = "0.8em" }, function()
SILE.call("meta:surum")
end)
SILE.call("par")
end
if SILE.Commands["meta:contributors"] then
SILE.call("meta:contributors")
SILE.call("par")
end
if SILE.Commands["meta:extracredits"] then
SILE.call("meta:extracredits")
SILE.call("par")
end
if SILE.Commands["meta:versecredits"] then
SILE.call("meta:versecredits")
SILE.call("par")
end
if CASILE.metadata.publisher then
local distributed = SILE.call("meta:distribution")
if not distributed and SILE.Commands["meta:date"] then
if CASILE.metadata.manufacturer then
SILE.call("meta:manufacturer")
SILE.call("par")
end
SILE.call("meta:date")
SILE.call("par")
end
end
end)
end)
end)
SILE.call("par")
SILE.call("break")
end)
SILE.registerCommand("meta:distribution", function (_, _)
local layout = CASILE.layout
local distros = CASILE.metadata.distribution
local text = nil
if distros then
for _, d in pairs(distros) do
if d.layout == layout then text = d.text end
end
end
if text then
SILE.call("font", { weight = 600, style = "Bold" }, { "Dağıtım: " })
SILE.typesetter:typeset(text)
SILE.call("par")
return true
else
return false
end
end)
|
fix: Only pass anonymous functions as content
|
fix: Only pass anonymous functions as content
|
Lua
|
agpl-3.0
|
alerque/casile,alerque/casile,alerque/casile,alerque/casile,alerque/casile
|
863dbc448e9e4f477b6b66ae94b1420ec7d04cd1
|
samples/gtk-demo/demo-images.lua
|
samples/gtk-demo/demo-images.lua
|
return function(parent, dir)
local coroutine = require 'coroutine'
local lgi = require 'lgi'
local bytes = require 'bytes'
local GLib = lgi.GLib
local Gio = lgi.Gio
local Gtk = lgi.Gtk
local GdkPixbuf = lgi.GdkPixbuf
local window = Gtk.Window {
title = 'Images',
border_width = 8,
Gtk.Box {
id = 'vbox',
orientation = 'VERTICAL',
spacing = 8,
border_width = 8,
Gtk.Label {
label = "<u>Image loaded from a file:</u>",
use_markup = true,
},
Gtk.Frame {
shadow_type = 'IN',
halign = 'CENTER',
valign = 'CENTER',
Gtk.Image {
file = dir:get_child('gtk-logo-rgb.gif'):get_path(),
},
},
Gtk.Label {
label = "<u>Animation loaded from a file:</u>",
use_markup = true,
},
Gtk.Frame {
shadow_type = 'IN',
halign = 'CENTER',
valign = 'CENTER',
Gtk.Image {
file = dir:get_child('floppybuddy.gif'):get_path(),
},
},
Gtk.Label {
label = "<u>Symbolic themed icon</u>",
use_markup = true,
},
Gtk.Frame {
shadow_type = 'IN',
halign = 'CENTER',
valign = 'CENTER',
Gtk.Image {
gicon = Gio.ThemedIcon.new_with_default_fallbacks(
'battery-caution-charging-symbolic'),
icon_size = Gtk.IconSize.DIALOG,
},
},
Gtk.Label {
label = "<u>Progressive image loading</u>",
use_markup = true,
},
Gtk.Frame {
shadow_type = 'IN',
halign = 'CENTER',
valign = 'CENTER',
Gtk.Image {
id = 'progressive',
},
},
Gtk.ToggleButton {
id = 'sensitive',
label = "_Insensitive",
use_underline = true,
},
}
}
function window.child.sensitive:on_toggled()
for _, child in ipairs(window.child.vbox.child) do
if child ~= self then
child.sensitive = not self.active
end
end
end
local function do_error(err)
local dialog = Gtk.MessageDialog {
transient_for = window,
destroy_with_parent = true,
text = "Failure reading image 'alphatest.png'",
secondary_text = err,
message_type = 'ERROR',
buttons = 'CLOSE',
on_response = Gtk.Widget.destroy,
}
dialog:show_all()
end
local abort_load, timer_id
local load_coro = coroutine.create(
function()
while not abort_load do
local stream, err = dir:get_child('alphatest.png'):read()
if not stream then
do_error(err)
abort_load = true
break
end
-- Create pixbuf loader and register callbacks.
local loader = GdkPixbuf.PixbufLoader()
function loader:on_area_prepared()
local pixbuf = self:get_pixbuf()
pixbuf:fill(0xaaaaaaff)
window.child.progressive.pixbuf = pixbuf
end
function loader:on_area_updated()
-- Let the image know that the pixbuf changed.
window.child.progressive:queue_draw()
end
while not abort_load do
-- Wait for the next timer tick.
coroutine.yield(true)
-- Load a chunk from the stream.
local buffer = bytes.new(256)
local read, err = stream:read(buffer, #buffer)
if read < 0 then
do_error(err)
abort_load = true
end
if read <= 0 then break end
-- Send it to the pixbuf loader.
if not loader:write(tostring(buffer):sub(1, read)) then
do_error(err)
abort_load = true
end
end
loader:close()
end
-- Make sure that timeout is unregistered when the coroutine
-- does not run any more.
timer_id = nil
return false
end)
timer_id = GLib.timeout_add(GLib.PRIORITY_DEFAULT, 150, load_coro)
-- Stop loading when the window is destroyed.
function window:on_destroy()
abort_load = true
if timer_id then
GLib.source_remove(timer_id)
coroutine.resume(load_coro)
end
end
window:show_all()
return window
end,
"Images",
table.concat {
[[Gtk.Image is used to display an image; the image can be in ]],
[[a number of formats. Typically, you load an image into a Gdk.Pixbuf, ]],
[[then display the pixbuf.
This demo code shows some of the more obscure cases, in the simple ]],
[[case a call to Gtk.Image.new_from_file() is all you need.]],
}
|
return function(parent, dir)
local coroutine = require 'coroutine'
local lgi = require 'lgi'
local bytes = require 'bytes'
local GLib = lgi.GLib
local Gio = lgi.Gio
local Gtk = lgi.Gtk
local GdkPixbuf = lgi.GdkPixbuf
local window = Gtk.Window {
title = 'Images',
border_width = 8,
Gtk.Box {
id = 'vbox',
orientation = 'VERTICAL',
spacing = 8,
border_width = 8,
Gtk.Label {
label = "<u>Image loaded from a file:</u>",
use_markup = true,
},
Gtk.Frame {
shadow_type = 'IN',
halign = 'CENTER',
valign = 'CENTER',
Gtk.Image {
file = dir:get_child('gtk-logo-rgb.gif'):get_path(),
},
},
Gtk.Label {
label = "<u>Animation loaded from a file:</u>",
use_markup = true,
},
Gtk.Frame {
shadow_type = 'IN',
halign = 'CENTER',
valign = 'CENTER',
Gtk.Image {
file = dir:get_child('floppybuddy.gif'):get_path(),
},
},
Gtk.Label {
label = "<u>Symbolic themed icon</u>",
use_markup = true,
},
Gtk.Frame {
shadow_type = 'IN',
halign = 'CENTER',
valign = 'CENTER',
Gtk.Image {
gicon = Gio.ThemedIcon.new_with_default_fallbacks(
'battery-caution-charging-symbolic'),
icon_size = Gtk.IconSize.DIALOG,
},
},
Gtk.Label {
label = "<u>Progressive image loading</u>",
use_markup = true,
},
Gtk.Frame {
shadow_type = 'IN',
halign = 'CENTER',
valign = 'CENTER',
Gtk.Image {
id = 'progressive',
},
},
Gtk.ToggleButton {
id = 'sensitive',
label = "_Insensitive",
use_underline = true,
},
}
}
function window.child.sensitive:on_toggled()
for _, child in ipairs(window.child.vbox.child) do
if child ~= self then
child.sensitive = not self.active
end
end
end
local function do_error(err)
local dialog = Gtk.MessageDialog {
transient_for = window,
destroy_with_parent = true,
text = "Failure reading image 'alphatest.png'",
secondary_text = err,
message_type = 'ERROR',
buttons = 'CLOSE',
on_response = Gtk.Widget.destroy,
}
dialog:show_all()
end
local abort_load, timer_id
local load_coro = coroutine.create(function()
while not abort_load do
local stream, err = dir:get_child('alphatest.png'):read()
if not stream then
do_error(err)
abort_load = true
break
end
-- Create pixbuf loader and register callbacks.
local loader = GdkPixbuf.PixbufLoader()
function loader:on_area_prepared()
local pixbuf = self:get_pixbuf()
pixbuf:fill(0xaaaaaaff)
window.child.progressive.pixbuf = pixbuf
end
function loader:on_area_updated()
-- Let the image know that the pixbuf changed.
window.child.progressive:queue_draw()
end
while not abort_load do
-- Wait for the next timer tick.
coroutine.yield(true)
-- Load a chunk from the stream.
local buffer = bytes.new(256)
local read, err = stream:read(buffer)
if read < 0 then
do_error(err)
abort_load = true
end
if read <= 0 then break end
-- Send it to the pixbuf loader.
if not loader:write(tostring(buffer):sub(1, read)) then
do_error(err)
abort_load = true
end
end
loader:close()
end
-- Make sure that timeout is unregistered when the coroutine does
-- not run any more.
timer_id = nil
return false
end)
timer_id = GLib.timeout_add(GLib.PRIORITY_DEFAULT, 150, load_coro)
-- Stop loading when the window is destroyed.
function window:on_destroy()
abort_load = true
if timer_id then
GLib.source_remove(timer_id)
coroutine.resume(load_coro)
end
end
window:show_all()
return window
end,
"Images",
table.concat {
[[Gtk.Image is used to display an image; the image can be in ]],
[[a number of formats. Typically, you load an image into a Gdk.Pixbuf, ]],
[[then display the pixbuf.
This demo code shows some of the more obscure cases, in the simple ]],
[[case a call to Gtk.Image.new_from_file() is all you need.]],
}
|
gtkdemo: fix images loading
|
gtkdemo: fix images loading
Another instance hit by Gio.InputStream[read|read_all|read_async] API change.
|
Lua
|
mit
|
psychon/lgi,pavouk/lgi
|
310679a01dacc039ddf6620c2fd890155b921f27
|
OS/DiskOS/Programs/help.lua
|
OS/DiskOS/Programs/help.lua
|
--Liko12 Help System !
local helpPATH = "C://Help/;C://Help/GPU/"
local function nextPath()
if helpPATH:sub(-1)~=";" then helpPATH=helpPATH..";" end
return helpPATH:gmatch("(.-);")
end
local topic = select(1,...)
topic = topic or "Welcome"
local giveApi = select(2,...)
if type(giveApi) == "boolean" then --Requesting HELP api
local api = {}
function api.setHelpPATH(p)
helpPath = p
end
function api.getHelpPath()
return helpPath
end
return api
end
helpPath = require("C://Programs/help",true).getHelpPath() --A smart way to keep the helpPath
palt(0,false) --Make black opaque
local doc --The help document to print
for path in nextPath() do
if fs.exists(path..topic) then
doc = path..topic break
elseif fs.exists(path..topic..".md") then
doc = path..topic..".md" break
end
end
if not doc then color(8) print("Help file not found '"..topic.."' !") return end
-- Waits for any input (keyboard or mouse) to continue
-- Returns true if "q" was pressed, to quit
local function waitkey()
while true do
local name, a = pullEvent()
if name == "keypressed" then
return false
elseif name == "textinput" then
if string.lower(a) == "q" then return true else return end
elseif name == "touchpressed" then
textinput(true)
end
end
end
printCursor(0) --Set the x pos to 0 (the start of the screen)
local tw, th = termSize()
local sw, sh = screenSize()
local _, top = printCursor()
local msg = "[press any key to continue, q to quit]"
local msglen = msg:len()
-- Smart print with the "press any key to continue" message
-- Returns true if "q" was pressed, which should abort the process
local function sprint(text)
local cx, cy = printCursor()
local cleantext = text:gsub("%^%x",""):gsub("%^%^","%^")
local txtlen = cleantext:len()
local txth = math.ceil(txtlen/tw)
local txtw = cleantext:sub((txth-1)*tw, -1)
text = "^7"..text
-- print text directly if it won't scroll the content past the screen
if top - txth > 0 then
for col, txt in string.gmatch(text,"%^%x(.-)") do
cprint(tostring(col).." "..tostring(txt))
color(col) print(txt,false)
end
print("")
top = top - txth
sleep(0.02) -- a short delay helps following the output
return
end
local plines = {}
local iter = string.gmatch(text,".")
local curline = { {"",7} }
for char in iter do
local flag = true
if char == "^" then
local n = iter()
if n ~= "^" then
flag = false
local col = string.match(n,"%x")
table.insert(curline, {"",col} )
end
end
if flag then
curline[#curline][1] = curline[#curline][1]..char
if curline[#curline][1]:len() == tw then
table.insert(plines,curline)
curline = { {"",7} }
end
end
end
local nextline = ipairs(plines)
for i=1, txth do
printCursor(0)
if cy + i >= th then
pushColor() color(9)
print(msg,false) popColor()
flip()
local quit = waitkey()
printCursor(0,th-1)
rect(0,sh-9,sw,8,false,0)
if quit then return true end
end
local lk, nline = nextline()
for k,v in ipairs(nline) do
color(v[2]) print(v[1],false)
end
print("")
--print(cleantext:sub( (i-1)*tw+1, (i)*tw ))
end
end
local md = (doc:sub(-3,-1) == ".md")
local doc = fs.read(doc)
doc = doc:gsub("\r\n","\n")
if doc:sub(-1,-1) ~= "\n" then doc = doc .. "\n" end
--Clear markdown
if md then
doc = doc:gsub("%-%-%-","")
doc = doc:gsub("```lua","")
doc = doc:gsub("```","")
doc = doc:gsub("# ","")
doc = doc:gsub("#","")
doc = doc:gsub("%*%*","")
doc = doc:gsub("__","")
doc = doc:gsub("\\>",">")
while doc:find("\n\n\n") do
doc = doc:gsub("\n\n\n","\n\n")
end
end
for line in string.gmatch(doc,"(.-)\n") do
if sprint(line) then break end
end
print("")
|
--Liko12 Help System !
local helpPATH = "C://Help/;C://Help/GPU/"
local function nextPath()
if helpPATH:sub(-1)~=";" then helpPATH=helpPATH..";" end
return helpPATH:gmatch("(.-);")
end
local topic = select(1,...)
topic = topic or "Welcome"
local giveApi = select(2,...)
if type(giveApi) == "boolean" then --Requesting HELP api
local api = {}
function api.setHelpPATH(p)
helpPath = p
end
function api.getHelpPath()
return helpPath
end
return api
end
helpPath = require("C://Programs/help",true).getHelpPath() --A smart way to keep the helpPath
palt(0,false) --Make black opaque
local doc --The help document to print
for path in nextPath() do
if fs.exists(path..topic) then
doc = path..topic break
elseif fs.exists(path..topic..".md") then
doc = path..topic..".md" break
end
end
if not doc then color(8) print("Help file not found '"..topic.."' !") return end
-- Waits for any input (keyboard or mouse) to continue
-- Returns true if "q" was pressed, to quit
local function waitkey()
while true do
local name, a = pullEvent()
if name == "keypressed" then
return false
elseif name == "textinput" then
if string.lower(a) == "q" then return true else return end
elseif name == "touchpressed" then
textinput(true)
end
end
end
printCursor(0) --Set the x pos to 0 (the start of the screen)
local tw, th = termSize()
local sw, sh = screenSize()
local _, top = printCursor()
local msg = "[press any key to continue, q to quit]"
local msglen = msg:len()
-- Smart print with the "press any key to continue" message
-- Returns true if "q" was pressed, which should abort the process
local function sprint(text)
local cx, cy = printCursor()
local txtlen = text:len()
local txth = math.ceil(txtlen/tw)
local txtw = text:sub((txth-1)*tw, -1)
-- print text directly if it won't scroll the content past the screen
if top - txth > 0 then
print(text)
top = top - txth
sleep(0.02) -- a short delay helps following the output
return
end
for i=1, txth do
printCursor(0)
if cy + i < th then
print(text:sub( (i-1)*tw+1, (i)*tw ))
else
pushColor() color(9)
print(msg,false) popColor()
flip()
local quit = waitkey()
printCursor(0,th-1)
rect(0,sh-9,sw,8,false,0)
if quit then return true end
print(text:sub( (i-1)*tw+1, (i)*tw ))
end
end
end
local md = (doc:sub(-3,-1) == ".md")
local doc = fs.read(doc)
doc = doc:gsub("\r\n","\n")
if doc:sub(-1,-1) ~= "\n" then doc = doc .. "\n" end
--Clear markdown
if md then
doc = doc:gsub("%-%-%-","")
doc = doc:gsub("```lua","")
doc = doc:gsub("```","")
doc = doc:gsub("# ","")
doc = doc:gsub("#","")
doc = doc:gsub("%*%*","")
doc = doc:gsub("__","")
doc = doc:gsub("\\>",">")
while doc:find("\n\n\n") do
doc = doc:gsub("\n\n\n","\n\n")
end
end
for line in string.gmatch(doc,"(.-)\n") do
if sprint(line) then break end
end
print("")
|
Reverted the colored help support because it's buggy and I don't have time before the FC Jam
|
Reverted the colored help support because it's buggy and I don't have time before the FC Jam
|
Lua
|
mit
|
RamiLego4Game/LIKO-12
|
7808a097124483a7245fbb3f8ebed8bd8fbf8ce2
|
testserver/item/id_90_flute.lua
|
testserver/item/id_90_flute.lua
|
-- I_90 Floete spielen
-- UPDATE common SET com_script='item.id_90_flute' WHERE com_itemid=90;
require("item.base.music")
module("item.id_90_flute", package.seeall)
item.base.music.addTalkText("#me produces some squeaking sounds on the flute.","#me macht einige quietschende Gerusche auf der Flte.","flute");
item.base.music.addTalkText("#me plays a horribly out of tune melody.","#me spielt eine frchterlich verstimmte Melodie auf der Flte.","flute");
item.base.music.addTalkText("#me plays an out of tune melody.","#me spielt eine verstimmte Melodie auf der Flte.","flute");
item.base.music.addTalkText("#me plays an airy tune on the flute.","#me spielt eine leichte Melodie auf der Flte.","flute");
item.base.music.addTalkText("#me plays a wild tune on the flute.","#me spielt eine wilde Melodie auf der Flte.","flute");
function UseItem(User,SourceItem,TargetItem,Counter,Param)
item.base.music.PlayInstrument(User,SourceItem,Character.flute);
end
|
-- I_90 Floete spielen
-- UPDATE common SET com_script='item.id_90_flute' WHERE com_itemid=90;
require("item.base.music")
module("item.id_90_flute", package.seeall)
skill = Character.flute
item.base.music.addTalkText("#me produces some squeaking sounds on the flute.","#me macht einige quietschende Gerusche auf der Flte.", skill);
item.base.music.addTalkText("#me plays a horribly out of tune melody.","#me spielt eine frchterlich verstimmte Melodie auf der Flte.", skill);
item.base.music.addTalkText("#me plays an out of tune melody.","#me spielt eine verstimmte Melodie auf der Flte.", skill);
item.base.music.addTalkText("#me plays an airy tune on the flute.","#me spielt eine leichte Melodie auf der Flte.", skill);
item.base.music.addTalkText("#me plays a wild tune on the flute.","#me spielt eine wilde Melodie auf der Flte.", skill);
function UseItem(User,SourceItem,TargetItem,Counter,Param)
item.base.music.PlayInstrument(User,SourceItem,skill);
end
|
Fix flute
|
Fix flute
|
Lua
|
agpl-3.0
|
Illarion-eV/Illarion-Content,Baylamon/Illarion-Content,LaFamiglia/Illarion-Content,KayMD/Illarion-Content,vilarion/Illarion-Content
|
e08420e5543dd34a8510da2d4e43a67938fda86a
|
share/lua/playlist/vimeo.lua
|
share/lua/playlist/vimeo.lua
|
--[[
$Id$
Copyright © 2009-2013 the VideoLAN team
Authors: Konstantin Pavlov ([email protected])
François Revol ([email protected])
Pierre Ynard
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
--]]
-- Probe function.
function probe()
return ( vlc.access == "http" or vlc.access == "https" )
and ( string.match( vlc.path, "vimeo%.com/%d+$" )
or string.match( vlc.path, "player%.vimeo%.com" ) )
-- do not match other addresses,
-- else we'll also try to decode the actual video url
end
-- Parse function.
function parse()
if not string.match( vlc.path, "player%.vimeo%.com" ) then -- Web page URL
while true do
local line = vlc.readline()
if not line then break end
-- Get the appropriate ubiquitous meta tag. It appears twice:
-- <meta property="og:video:url" content="https://player.vimeo.com/video/123456789?autoplay=1">
-- <meta property="og:video:url" content="https://vimeo.com/moogaloop.swf?clip_id=123456789&autoplay=1">
local meta = string.match( line, "(<meta[^>]- property=\"og:video:url\"[^>]->)" )
if meta then
local path = string.match( meta, " content=\"(.-)\"" )
-- Exclude moogaloop flash URL
if path and string.match( path, "player%.vimeo%.com" ) then
path = vlc.strings.resolve_xml_special_chars( path )
return { { path = path } }
end
end
end
vlc.msg.err( "Couldn't extract vimeo video URL, please check for updates to this script" )
return { }
else -- API URL
local prefres = vlc.var.inherit(nil, "preferred-resolution")
local bestres = nil
local line = vlc.readline() -- data is on one line only
for stream in string.gmatch( line, "{([^}]*\"profile\":[^}]*)}" ) do
local url = string.match( stream, "\"url\":\"(.-)\"" )
if url then
-- Apparently the different formats available are listed
-- in uncertain order of quality, so compare with what
-- we have so far.
local height = string.match( stream, "\"height\":(%d+)" )
height = tonumber( height )
-- Better than nothing
if not path or ( height and ( not bestres
-- Better quality within limits
or ( ( prefres < 0 or height <= prefres ) and height > bestres )
-- Lower quality more suited to limits
or ( prefres > -1 and bestres > prefres and height < bestres )
) ) then
path = url
bestres = height
end
end
end
if not path then
vlc.msg.err( "Couldn't extract vimeo video URL, please check for updates to this script" )
return { }
end
local name = string.match( line, "\"title\":\"(.-)\"" )
local artist = string.match( line, "\"owner\":{[^}]-\"name\":\"(.-)\"" )
local arturl = string.match( line, "\"thumbs\":{\"[^\"]+\":\"(.-)\"" )
local duration = string.match( line, "\"duration\":(%d+)[,}]" )
return { { path = path; name = name; artist = artist; arturl = arturl; duration = duration } }
end
end
|
--[[
$Id$
Copyright © 2009-2013 the VideoLAN team
Authors: Konstantin Pavlov ([email protected])
François Revol ([email protected])
Pierre Ynard
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
--]]
-- Probe function.
function probe()
return ( vlc.access == "http" or vlc.access == "https" )
and ( string.match( vlc.path, "vimeo%.com/%d+$" )
or string.match( vlc.path, "vimeo%.com/channels/(.-)/%d+$" )
or string.match( vlc.path, "player%.vimeo%.com" ) )
-- do not match other addresses,
-- else we'll also try to decode the actual video url
end
-- Parse function.
function parse()
if not string.match( vlc.path, "player%.vimeo%.com" ) then -- Web page URL
while true do
local line = vlc.readline()
if not line then break end
-- Get the appropriate ubiquitous meta tag. It appears twice:
-- <meta property="og:video:url" content="https://player.vimeo.com/video/123456789?autoplay=1">
-- <meta property="og:video:url" content="https://vimeo.com/moogaloop.swf?clip_id=123456789&autoplay=1">
local meta = string.match( line, "(<meta[^>]- property=\"og:video:url\"[^>]->)" )
if meta then
local path = string.match( meta, " content=\"(.-)\"" )
-- Exclude moogaloop flash URL
if path and string.match( path, "player%.vimeo%.com" ) then
path = vlc.strings.resolve_xml_special_chars( path )
return { { path = path } }
end
end
end
vlc.msg.err( "Couldn't extract vimeo video URL, please check for updates to this script" )
return { }
else -- API URL
local prefres = vlc.var.inherit(nil, "preferred-resolution")
local bestres = nil
local line = vlc.readline() -- data is on one line only
for stream in string.gmatch( line, "{([^}]*\"profile\":[^}]*)}" ) do
local url = string.match( stream, "\"url\":\"(.-)\"" )
if url then
-- Apparently the different formats available are listed
-- in uncertain order of quality, so compare with what
-- we have so far.
local height = string.match( stream, "\"height\":(%d+)" )
height = tonumber( height )
-- Better than nothing
if not path or ( height and ( not bestres
-- Better quality within limits
or ( ( prefres < 0 or height <= prefres ) and height > bestres )
-- Lower quality more suited to limits
or ( prefres > -1 and bestres > prefres and height < bestres )
) ) then
path = url
bestres = height
end
end
end
if not path then
vlc.msg.err( "Couldn't extract vimeo video URL, please check for updates to this script" )
return { }
end
local name = string.match( line, "\"title\":\"(.-)\"" )
local artist = string.match( line, "\"owner\":{[^}]-\"name\":\"(.-)\"" )
local arturl = string.match( line, "\"thumbs\":{\"[^\"]+\":\"(.-)\"" )
local duration = string.match( line, "\"duration\":(%d+)[,}]" )
return { { path = path; name = name; artist = artist; arturl = arturl; duration = duration } }
end
end
|
vimeo.lua: support channel video page URLs
|
vimeo.lua: support channel video page URLs
Fix #16195
|
Lua
|
lgpl-2.1
|
xkfz007/vlc,xkfz007/vlc,xkfz007/vlc,xkfz007/vlc,xkfz007/vlc,xkfz007/vlc,xkfz007/vlc
|
84db6981bc34aacc6b3379f19d763f8895ac1aee
|
xmake.lua
|
xmake.lua
|
local modules = {
Audio = {
Deps = {"NazaraCore"},
Packages = {"dr_wav", "libflac", "libvorbis", "minimp3"},
Custom = function ()
add_packages("openal-soft", {links = {}}) -- Don't link OpenAL (it will be loaded dynamically)
end
},
Core = {
Custom = function ()
add_headerfiles("include/(Nazara/*.hpp)")
-- NazaraMath is header-only, make it part of the core project
add_headerfiles("include/(Nazara/Math/**.hpp)", "include/(Nazara/Math/**.inl)")
if is_plat("windows", "mingw") then
add_syslinks("ole32")
elseif is_plat("linux") then
add_syslinks("dl", "pthread", "uuid")
end
end,
Packages = {"entt"}
},
Graphics = {
Deps = {"NazaraRenderer"},
Packages = {"entt"}
},
Network = {
Deps = {"NazaraCore"},
Custom = function()
if is_plat("windows", "mingw") then
add_syslinks("ws2_32")
end
if is_plat("linux") then
remove_files("src/Nazara/Network/Posix/SocketPollerImpl.hpp")
remove_files("src/Nazara/Network/Posix/SocketPollerImpl.cpp")
end
end
},
OpenGLRenderer = {
Deps = {"NazaraRenderer"},
Custom = function()
if is_plat("windows", "mingw") then
add_syslinks("gdi32", "user32")
else
remove_files("src/Nazara/OpenGLRenderer/Wrapper/Win32/**.cpp")
remove_files("src/Nazara/OpenGLRenderer/Wrapper/WGL/**.cpp")
end
if not is_plat("linux") then
remove_files("src/Nazara/OpenGLRenderer/Wrapper/Linux/**.cpp")
end
end
},
Physics2D = {
Deps = {"NazaraUtility"},
Packages = {"chipmunk2d"}
},
Physics3D = {
Deps = {"NazaraUtility"},
Packages = {"entt", "newtondynamics"}
},
Platform = {
Deps = {"NazaraUtility"},
Packages = {"libsdl"},
Custom = function()
if is_plat("windows", "mingw") then
add_defines("SDL_VIDEO_DRIVER_WINDOWS=1")
elseif is_plat("linux") then
add_defines("SDL_VIDEO_DRIVER_X11=1")
add_defines("SDL_VIDEO_DRIVER_WAYLAND=1")
elseif is_plat("macosx") then
add_defines("SDL_VIDEO_DRIVER_COCOA=1")
end
end
},
Renderer = {
Deps = {"NazaraPlatform", "NazaraShader"}
},
Shader = {
Deps = {"NazaraUtility"}
},
Utility = {
Deps = {"NazaraCore"},
Packages = {"entt", "freetype", "stb"}
},
VulkanRenderer = {
Deps = {"NazaraRenderer"},
Custom = function()
add_defines("VK_NO_PROTOTYPES")
if is_plat("windows", "mingw") then
add_defines("VK_USE_PLATFORM_WIN32_KHR")
add_syslinks("user32")
elseif is_plat("linux") then
add_defines("VK_USE_PLATFORM_XLIB_KHR")
add_defines("VK_USE_PLATFORM_WAYLAND_KHR")
elseif is_plat("macosx") then
add_defines("VK_USE_PLATFORM_MACOS_MVK")
end
end
},
Widgets = {
Deps = {"NazaraGraphics"},
Packages = {"entt", "kiwisolver"}
}
}
NazaraModules = modules
includes("xmake/**.lua")
set_project("NazaraEngine")
set_xmakever("2.6.3")
add_repositories("local-repo xmake-repo")
add_requires("chipmunk2d", "dr_wav", "entt >=3.9", "kiwisolver", "libflac", "libsdl", "minimp3", "stb")
add_requires("freetype", { configs = { bzip2 = true, png = true, woff2 = true, zlib = true, debug = is_mode("debug") } })
add_requires("libvorbis", { configs = { with_vorbisenc = false } })
add_requires("openal-soft", { configs = { shared = true }})
add_requires("newtondynamics", { debug = is_plat("windows") and is_mode("debug") }) -- Newton doesn't like compiling in Debug on Linux
add_rules("mode.asan", "mode.debug", "mode.releasedbg")
add_rules("plugin.vsxmake.autoupdate")
add_rules("build_rendererplugins")
set_allowedplats("windows", "mingw", "linux", "macosx")
set_allowedarchs("windows|x64", "mingw|x86_64", "linux|x86_64", "macosx|x86_64")
set_defaultmode("debug")
if is_plat("windows") then
set_allowedmodes("debug", "releasedbg", "asan")
else
set_allowedmodes("debug", "releasedbg", "asan", "coverage", "fuzz")
add_rules("mode.coverage")
add_rules("mode.fuzz")
end
if is_mode("debug") then
add_rules("debug_suffix")
elseif is_mode("asan") then
set_optimize("none") -- by default xmake will optimize asan builds
elseif is_mode("fuzz") then
-- we don't want packages to require compilation with fuzz toolchain
set_policy("package.inherit_external_configs", false)
elseif is_mode("coverage") then
if not is_plat("windows") then
add_links("gcov")
end
elseif is_mode("releasedbg") then
set_fpmodels("fast")
add_vectorexts("sse", "sse2", "sse3", "ssse3")
end
add_includedirs("include")
add_sysincludedirs("thirdparty/include")
set_languages("c89", "cxx17")
set_rundir("./bin/$(plat)_$(arch)_$(mode)")
set_symbols("debug", "hidden")
set_targetdir("./bin/$(plat)_$(arch)_$(mode)")
set_warnings("allextra")
if is_mode("debug") then
add_defines("NAZARA_DEBUG")
end
if is_plat("windows") then
set_runtimes(is_mode("debug") and "MDd" or "MD")
add_defines("_CRT_SECURE_NO_WARNINGS")
add_cxxflags("/bigobj", "/permissive-", "/Zc:__cplusplus", "/Zc:externConstexpr", "/Zc:inline", "/Zc:lambda", "/Zc:preprocessor", "/Zc:referenceBinding", "/Zc:strictStrings", "/Zc:throwingNew")
add_cxflags("/w44062") -- Enable warning: switch case not handled
add_cxflags("/wd4251") -- Disable warning: class needs to have dll-interface to be used by clients of class blah blah blah
elseif is_plat("mingw") then
add_cxflags("-Og", "-Wa,-mbig-obj")
add_ldflags("-Wa,-mbig-obj")
end
for name, module in pairs(modules) do
target("Nazara" .. name)
set_kind("shared")
set_group("Modules")
add_rules("embed_resources")
add_rpathdirs("$ORIGIN")
if module.Deps then
add_deps(table.unpack(module.Deps))
end
if module.Packages then
add_packages(table.unpack(module.Packages))
end
if module.Custom then
module.Custom()
end
add_defines("NAZARA_BUILD")
add_defines("NAZARA_" .. name:upper() .. "_BUILD")
if is_mode("debug") then
add_defines("NAZARA_" .. name:upper() .. "_DEBUG")
end
local headerExts = {".h", ".hpp", ".inl", ".natvis"}
for _, ext in ipairs(headerExts) do
add_headerfiles("include/(Nazara/" .. name .. "/**" .. ext .. ")")
add_headerfiles("src/Nazara/" .. name .. "/**" .. ext)
end
add_files("src/Nazara/" .. name .. "/**.cpp")
add_includedirs("src")
for _, filepath in pairs(os.files("src/Nazara/" .. name .. "/Resources/**|**.h")) do
add_files(filepath, {rule = "embed_resources"})
end
if is_plat("windows", "mingw") then
for _, ext in ipairs(headerExts) do
remove_headerfiles("src/Nazara/" .. name .. "/Posix/**" .. ext)
end
remove_files("src/Nazara/" .. name .. "/Posix/**.cpp")
else
for _, ext in ipairs(headerExts) do
remove_headerfiles("src/Nazara/" .. name .. "/Posix/**" .. ext)
end
remove_files("src/Nazara/" .. name .. "/Win32/**.cpp")
end
if not is_plat("linux") then
for _, ext in ipairs(headerExts) do
remove_headerfiles("src/Nazara/" .. name .. "/Linux/**" .. ext)
end
remove_files("src/Nazara/" .. name .. "/Linux/**.cpp")
end
end
includes("tools/xmake.lua")
includes("tests/xmake.lua")
includes("plugins/*/xmake.lua")
includes("examples/*/xmake.lua")
|
local modules = {
Audio = {
Deps = {"NazaraCore"},
Packages = {"dr_wav", "libflac", "libvorbis", "minimp3"},
Custom = function ()
add_packages("openal-soft", {links = {}}) -- Don't link OpenAL (it will be loaded dynamically)
end
},
Core = {
Custom = function ()
add_headerfiles("include/(Nazara/*.hpp)")
-- NazaraMath is header-only, make it part of the core project
add_headerfiles("include/(Nazara/Math/**.hpp)", "include/(Nazara/Math/**.inl)")
if is_plat("windows", "mingw") then
add_syslinks("ole32")
elseif is_plat("linux") then
add_syslinks("dl", "pthread", "uuid")
end
end,
Packages = {"entt"}
},
Graphics = {
Deps = {"NazaraRenderer"},
Packages = {"entt"}
},
Network = {
Deps = {"NazaraCore"},
Custom = function()
if is_plat("windows", "mingw") then
add_syslinks("ws2_32")
end
if is_plat("linux") then
remove_files("src/Nazara/Network/Posix/SocketPollerImpl.hpp")
remove_files("src/Nazara/Network/Posix/SocketPollerImpl.cpp")
end
end
},
OpenGLRenderer = {
Deps = {"NazaraRenderer"},
Custom = function()
if is_plat("windows", "mingw") then
add_syslinks("gdi32", "user32")
else
remove_files("src/Nazara/OpenGLRenderer/Wrapper/Win32/**.cpp")
remove_files("src/Nazara/OpenGLRenderer/Wrapper/WGL/**.cpp")
end
if not is_plat("linux") then
remove_files("src/Nazara/OpenGLRenderer/Wrapper/Linux/**.cpp")
end
end
},
Physics2D = {
Deps = {"NazaraUtility"},
Packages = {"chipmunk2d"}
},
Physics3D = {
Deps = {"NazaraUtility"},
Packages = {"entt", "newtondynamics"}
},
Platform = {
Deps = {"NazaraUtility"},
Packages = {"libsdl"},
Custom = function()
if is_plat("windows", "mingw") then
add_defines("SDL_VIDEO_DRIVER_WINDOWS=1")
elseif is_plat("linux") then
add_defines("SDL_VIDEO_DRIVER_X11=1")
add_defines("SDL_VIDEO_DRIVER_WAYLAND=1")
elseif is_plat("macosx") then
add_defines("SDL_VIDEO_DRIVER_COCOA=1")
end
end
},
Renderer = {
Deps = {"NazaraPlatform", "NazaraShader"}
},
Shader = {
Deps = {"NazaraUtility"}
},
Utility = {
Deps = {"NazaraCore"},
Packages = {"entt", "freetype", "stb"}
},
VulkanRenderer = {
Deps = {"NazaraRenderer"},
Custom = function()
add_defines("VK_NO_PROTOTYPES")
if is_plat("windows", "mingw") then
add_defines("VK_USE_PLATFORM_WIN32_KHR")
add_syslinks("user32")
elseif is_plat("linux") then
add_defines("VK_USE_PLATFORM_XLIB_KHR")
add_defines("VK_USE_PLATFORM_WAYLAND_KHR")
elseif is_plat("macosx") then
add_defines("VK_USE_PLATFORM_MACOS_MVK")
end
end
},
Widgets = {
Deps = {"NazaraGraphics"},
Packages = {"entt", "kiwisolver"}
}
}
NazaraModules = modules
includes("xmake/**.lua")
set_project("NazaraEngine")
set_xmakever("2.6.3")
add_repositories("local-repo xmake-repo")
add_requires("chipmunk2d", "dr_wav", "entt >=3.9", "kiwisolver", "libflac", "libsdl", "minimp3", "stb")
add_requires("freetype", { configs = { bzip2 = true, png = true, woff2 = true, zlib = true, debug = is_mode("debug") } })
add_requires("libvorbis", { configs = { with_vorbisenc = false } })
add_requires("openal-soft", { configs = { shared = true }})
add_requires("newtondynamics", { debug = is_plat("windows") and is_mode("debug") }) -- Newton doesn't like compiling in Debug on Linux
add_rules("mode.asan", "mode.debug", "mode.releasedbg")
add_rules("plugin.vsxmake.autoupdate")
add_rules("build_rendererplugins")
set_allowedplats("windows", "mingw", "linux", "macosx")
set_allowedarchs("windows|x64", "mingw|x86_64", "linux|x86_64", "macosx|x86_64")
set_allowedmodes("debug", "releasedbg", "asan", "coverage", "fuzz")
set_defaultmode("debug")
if not is_plat("windows") then
add_rules("mode.coverage")
add_rules("mode.fuzz")
end
if is_mode("debug") then
add_rules("debug_suffix")
elseif is_mode("asan") then
set_optimize("none") -- by default xmake will optimize asan builds
elseif is_mode("fuzz") then
-- we don't want packages to require compilation with fuzz toolchain
set_policy("package.inherit_external_configs", false)
elseif is_mode("coverage") then
if not is_plat("windows") then
add_links("gcov")
end
elseif is_mode("releasedbg") then
set_fpmodels("fast")
add_vectorexts("sse", "sse2", "sse3", "ssse3")
end
add_includedirs("include")
add_sysincludedirs("thirdparty/include")
set_languages("c89", "cxx17")
set_rundir("./bin/$(plat)_$(arch)_$(mode)")
set_symbols("debug", "hidden")
set_targetdir("./bin/$(plat)_$(arch)_$(mode)")
set_warnings("allextra")
if is_mode("debug") then
add_defines("NAZARA_DEBUG")
end
if is_plat("windows") then
set_runtimes(is_mode("debug") and "MDd" or "MD")
add_defines("_CRT_SECURE_NO_WARNINGS")
add_cxxflags("/bigobj", "/permissive-", "/Zc:__cplusplus", "/Zc:externConstexpr", "/Zc:inline", "/Zc:lambda", "/Zc:preprocessor", "/Zc:referenceBinding", "/Zc:strictStrings", "/Zc:throwingNew")
add_cxflags("/w44062") -- Enable warning: switch case not handled
add_cxflags("/wd4251") -- Disable warning: class needs to have dll-interface to be used by clients of class blah blah blah
elseif is_plat("mingw") then
add_cxflags("-Og", "-Wa,-mbig-obj")
add_ldflags("-Wa,-mbig-obj")
end
for name, module in pairs(modules) do
target("Nazara" .. name)
set_kind("shared")
set_group("Modules")
add_rules("embed_resources")
add_rpathdirs("$ORIGIN")
if module.Deps then
add_deps(table.unpack(module.Deps))
end
if module.Packages then
add_packages(table.unpack(module.Packages))
end
if module.Custom then
module.Custom()
end
add_defines("NAZARA_BUILD")
add_defines("NAZARA_" .. name:upper() .. "_BUILD")
if is_mode("debug") then
add_defines("NAZARA_" .. name:upper() .. "_DEBUG")
end
local headerExts = {".h", ".hpp", ".inl", ".natvis"}
for _, ext in ipairs(headerExts) do
add_headerfiles("include/(Nazara/" .. name .. "/**" .. ext .. ")")
add_headerfiles("src/Nazara/" .. name .. "/**" .. ext)
end
add_files("src/Nazara/" .. name .. "/**.cpp")
add_includedirs("src")
for _, filepath in pairs(os.files("src/Nazara/" .. name .. "/Resources/**|**.h")) do
add_files(filepath, {rule = "embed_resources"})
end
if is_plat("windows", "mingw") then
for _, ext in ipairs(headerExts) do
remove_headerfiles("src/Nazara/" .. name .. "/Posix/**" .. ext)
end
remove_files("src/Nazara/" .. name .. "/Posix/**.cpp")
else
for _, ext in ipairs(headerExts) do
remove_headerfiles("src/Nazara/" .. name .. "/Posix/**" .. ext)
end
remove_files("src/Nazara/" .. name .. "/Win32/**.cpp")
end
if not is_plat("linux") then
for _, ext in ipairs(headerExts) do
remove_headerfiles("src/Nazara/" .. name .. "/Linux/**" .. ext)
end
remove_files("src/Nazara/" .. name .. "/Linux/**.cpp")
end
end
includes("tools/xmake.lua")
includes("tests/xmake.lua")
includes("plugins/*/xmake.lua")
includes("examples/*/xmake.lua")
|
XMake: Fix allowed modes on Windows
|
XMake: Fix allowed modes on Windows
|
Lua
|
mit
|
DigitalPulseSoftware/NazaraEngine
|
be0e8c6d2404f6671ce82e8601f94eccd34b82ab
|
Helditemslist.lua
|
Helditemslist.lua
|
--[[
Module to create an entry in the list of Pokémon by wild held items.
--]]
local h = {}
local txt = require('Wikilib-strings') -- luacheck: no unused
local tab = require('Wikilib-tables') -- luacheck: no unused
local oop = require('Wikilib-oop')
local list = require('Wikilib-lists')
local multigen = require('Wikilib-multigen')
local links = require('Links')
local ms = require('MiniSprite')
local pokes = require("Poké-data")
local blackabbrev = require("Blackabbrev-data")
local colorabbrev = require("Colorabbrev-data")
h.Entry = oop.makeClass(list.PokeLabelledEntry)
-- Utility strings
h.Entry.strings = {
ENTRY_HEAD = [=[<div class="roundy text-center width-xl-100 flex flex-row flex-wrap flex-main-center flex-items-center horiz-grad-${type1}-${type2}" style="padding: 0.5ex; margin: 1ex 0">
<div class="roundy bg-white flex flex-row flex-nowrap flex-main-center flex-items-center" style="padding: 0 1ex; margin: 0.5ex;">
<div>'''${ndex}'''</div>
<div>${ms}</div>
<div>[[${name}]]${blacklink}</div>
</div>
<div class="flex-row-stretch-around flex-wrap">]=],
ENTRY_FOOT = [[</div></div>]],
BOX_HEAD = [[<div class="roundy bg-white flex-row-center-around flex-wrap" style="margin: 0.5ex;">]],
BOX_FOOT = [[</div>]],
PERC_BOX = [=[<div style="padding: 1ex;">
<div>${abbrev}</div>
<div>${img}</div>
<div>${percentage}%</div>
</div>]=]
}
-- Table to get colored abbrevs from type and game abbr
h.Entry.abbrevs = {
black = function(abbr) return blackabbrev[abbr] end,
color = function(abbr) return table.concat{
" ", colorabbrev[abbr], " "
}
end,
}
--[[
Create a single game box taking an array of item/game tables (element of the
data module array).
--]]
h.Entry.makeGameBox = function(this, itemsList, gen)
local percBoxes = table.map(itemsList, function(v)
local abbrevs = table.concat(table.map(v.games, function(abbr, index)
if v.abbrTypes then
return this.abbrevs[v.abbrTypes[index]](abbr)
else
return this.abbrevs.black(abbr)
end
end))
return string.interp(this.strings.PERC_BOX, {
abbrev = abbrevs,
img = gen < 3
and string.interp(
'<span class="black-text">[[${item}]]</span>',
{ item = v.item }
)
or links.bag(v.item),
percentage = v.perc,
})
end)
if #percBoxes > 0 then
table.insert(percBoxes, this.strings.BOX_FOOT)
return this.strings.BOX_HEAD .. table.concat(percBoxes)
else
return ''
end
end
--[[
Constructor: the first argument is an entry from HeldItems/data, the second one
is its key.
--]]
h.Entry.new = function(helds, poke)
-- Skip empty entries
if #helds == 0 then
return
end
local this = h.Entry.super.new(poke, pokes[poke].ndex)
this.helds = helds
return setmetatable(this, h.Entry)
end
--[[
Equality operator for grouping. True iff the two entries have the exact same
this.helds
--]]
h.Entry.__eq = function(a, b)
return a.ndex == b.ndex and table.equal(a.helds, b.helds)
end
--[[
Wikicode for a list entry.
--]]
h.Entry.__tostring = function(this)
local pokedata = multigen.getGen(pokes[this.name])
local form = "<div>" .. table.concat(table.map(this.labels, function(label)
return this.formsData.blacklinks[label]:gsub("<(/?)div", "<%1span")
end), ", ") .. "</div>"
local result = { string.interp(this.strings.ENTRY_HEAD, {
type1 = pokedata.type1,
type2 = pokedata.type2,
ndex = string.tf(this.ndex),
ms = ms.staticLua(string.tf(this.ndex) .. (this.formAbbr == 'base'
and '' or this.formAbbr or '')),
name = pokedata.name,
blacklink = form,
})}
table.map(this.helds, function(v, gen)
table.insert(result, this:makeGameBox(v, gen))
end, ipairs)
table.insert(result, this.strings.ENTRY_FOOT)
return table.concat(result)
end
--[[
Main wikicode interface.
--]]
h.helditem = function(_)
return list.makeGroupedList{
source = require('PokéItems-data'),
makeEntry = h.Entry.new,
iterator = list.pokeNames,
header = '',
separator = '',
footer = '',
fullGroupLabel = '',
}
end
h.Helditem = h.helditem
return h
|
--[[
Module to create an entry in the list of Pokémon by wild held items.
--]]
local h = {}
local txt = require('Wikilib-strings') -- luacheck: no unused
local tab = require('Wikilib-tables') -- luacheck: no unused
local oop = require('Wikilib-oop')
local list = require('Wikilib-lists')
local multigen = require('Wikilib-multigen')
local links = require('Links')
local ms = require('MiniSprite')
local pokes = require("Poké-data")
local blackabbrev = require("Blackabbrev-data")
local colorabbrev = require("Colorabbrev-data")
h.Entry = oop.makeClass(list.PokeLabelledEntry)
-- Utility strings
h.Entry.strings = {
ENTRY_HEAD = [=[<div class="roundy text-center width-xl-100 flex flex-row flex-wrap flex-main-center flex-items-center horiz-grad-${type1}-${type2}" style="padding: 0.5ex; margin: 1ex 0">
<div class="roundy bg-white flex flex-row flex-nowrap flex-main-center flex-items-center" style="padding: 0 1ex; margin: 0.5ex;">
<div>'''${ndex}'''</div>
<div>${ms}</div>
<div>[[${name}]]${blacklink}</div>
</div>
<div class="flex-row-stretch-around flex-wrap">]=],
ENTRY_FOOT = [[</div></div>]],
BOX_HEAD = [[<div class="roundy bg-white flex-row-center-around flex-wrap" style="margin: 0.5ex;">]],
BOX_FOOT = [[</div>]],
PERC_BOX = [=[<div style="padding: 1ex;">
<div>${abbrev}</div>
<div>${img}</div>
<div>${percentage}%</div>
</div>]=]
}
-- Table to get colored abbrevs from type and game abbr
h.Entry.abbrevs = {
black = function(abbr) return blackabbrev[abbr] end,
color = function(abbr) return table.concat{
" ", colorabbrev[abbr], " "
}
end,
}
--[[
Create a single game box taking an array of item/game tables (element of the
data module array).
--]]
h.Entry.makeGameBox = function(this, itemsList, gen)
local percBoxes = table.map(itemsList, function(v)
local abbrevs = table.concat(table.map(v.games, function(abbr, index)
if v.abbrTypes then
return this.abbrevs[v.abbrTypes[index]](abbr)
else
return this.abbrevs.black(abbr)
end
end))
return string.interp(this.strings.PERC_BOX, {
abbrev = abbrevs,
img = gen < 3
and string.interp(
'<span class="black-text">[[${item}]]</span>',
{ item = v.item == 'Perla' and 'Perla (strumento)|Perla'
or v.item }
)
or links.bag(v.item),
percentage = v.perc,
})
end)
if #percBoxes > 0 then
table.insert(percBoxes, this.strings.BOX_FOOT)
return this.strings.BOX_HEAD .. table.concat(percBoxes)
else
return ''
end
end
--[[
Constructor: the first argument is an entry from HeldItems/data, the second one
is its key.
--]]
h.Entry.new = function(helds, poke)
-- Skip empty entries
if #helds == 0 then
return
end
local this = h.Entry.super.new(poke, pokes[poke].ndex)
this.helds = helds
return setmetatable(this, h.Entry)
end
--[[
Equality operator for grouping. True iff the two entries have the exact same
this.helds
--]]
h.Entry.__eq = function(a, b)
return a.ndex == b.ndex and table.equal(a.helds, b.helds)
end
--[[
Wikicode for a list entry.
--]]
h.Entry.__tostring = function(this)
local pokedata = multigen.getGen(pokes[this.name])
local form = "<div>" .. table.concat(table.map(this.labels, function(label)
return this.formsData.blacklinks[label]:gsub("<(/?)div", "<%1span")
end), ", ") .. "</div>"
local result = { string.interp(this.strings.ENTRY_HEAD, {
type1 = pokedata.type1,
type2 = pokedata.type2,
ndex = string.tf(this.ndex),
ms = ms.staticLua(string.tf(this.ndex) .. (this.formAbbr == 'base'
and '' or this.formAbbr or '')),
name = pokedata.name,
blacklink = form,
})}
table.map(this.helds, function(v, gen)
table.insert(result, this:makeGameBox(v, gen))
end, ipairs)
table.insert(result, this.strings.ENTRY_FOOT)
return table.concat(result)
end
--[[
Main wikicode interface.
--]]
h.helditem = function(_)
return list.makeGroupedList{
source = require('PokéItems-data'),
makeEntry = h.Entry.new,
iterator = list.pokeNames,
header = '',
separator = '',
footer = '',
fullGroupLabel = '',
}
end
h.Helditem = h.helditem
return h
|
Fixed link to Perla in Helditemslist
|
Fixed link to Perla in Helditemslist
|
Lua
|
cc0-1.0
|
pokemoncentral/wiki-lua-modules
|
1529103d497e493ca2f8806ebffd1c939ec7bfe6
|
mbot_play_minetest/mod-mbot/mbot/init.lua
|
mbot_play_minetest/mod-mbot/mbot/init.lua
|
-- REST Arduino Interface
-- Luca Colciago @dottork
-- 13/12/2015
--
--
local www_box = {
type = "regular"
}
local reset_meta = function(pos)
minetest.get_meta(pos):set_string("formspec", "field[channel;Channel;${channel}]".."field[ArduinoIPAddress;ArduinoIPAddress;${ArduinoIPAddress}]")
end
local clearscreen = function(pos)
local objects = minetest.get_objects_inside_radius(pos, 0.5)
for _, o in ipairs(objects) do
local o_entity = o:get_luaentity()
if o_entity and o_entity.name == "mbot:text" then
o:remove()
end
end
end
local on_digiline_receive = function(pos, node, channel, msg)
local meta = minetest.get_meta(pos)
local setchan = meta:get_string("channel")
print(setchan)
local setip =meta:get_string("ArduinoIPAddress")
if setchan ~= channel then return end
meta:set_string("text", msg)
meta:set_string("infotext", msg)
clearscreen(pos)
if msg ~= "" then
print("Arrivato un messaggio. Mando al BT")
local answer = comandoz(msg)
if string.len(answer) > 11 then
print("Arrivata una risposta diversa da un semplice ACK")
end
digiline:receptor_send(pos, digiline.rules.default, channel, answer)
end
end
minetest.register_node("mbot:lcc", {
drawtype = "nodebox",
description = "Digiline ArduinoYUN Connection",
inventory_image = "mbot.jpg",
wield_image = "mbot.jpg",
tiles = {"mbot.jpg"},
paramtype = "light",
sunlight_propagates = true,
paramtype2 = "facedir",
node_box = www_box,
selection_box = www_box,
groups = {choppy = 3, dig_immediate = 2},
after_place_node = function (pos, placer, itemstack)
local param2 = minetest.get_node(pos).param2
if param2 == 0 or param2 == 1 then
minetest.add_node(pos, {name = "mbot:lcc", param2 = 3})
end
end,
on_construct = function(pos)
reset_meta(pos)
end,
on_destruct = function(pos)
clearscreen(pos)
end,
on_receive_fields = function(pos, formname, fields, sender)
if (fields.channel) then
minetest.get_meta(pos):set_string("channel", fields.channel)
end
if (fields.channel) then
minetest.get_meta(pos):set_string("ArduinoIPAddress",fields.ArduinoIPAddress)
end
end,
digiline =
{
receptor = {},
effector = {
action = on_digiline_receive
},
},
light_source = 6,
})
minetest.register_entity("mbot:text", {
collisionbox = { 0, 0, 0, 0, 0, 0 },
visual = "upright_sprite",
textures = {},
on_activate = function(self)
local meta = minetest.get_meta(self.object:getpos())
local text = meta:get_string("text")
end
})
-- Funzione da migliorare per inviare i dati via bluetooth
-- comandoz = function(c)
-- print("Ho ricevuto questi caratteri")
-- print(string.len(c))
--
--
-- local wserial=io.open("/dev/rfcomm0","wb")
-- -- local wserial=io.open("/dev/ttyUSB0","w")
-- -- local wserial=io.open("datimbot","a")
-- if wserial ~= nil then
-- local rs = io.open("/dev/rfcomm0","rb")
-- print(wserial)
-- wserial:write(c)
-- wserial:close()
--
-- while chaine==nil do
-- chaine=rserial:read()
-- rserial:flush()
-- end
-- print("ricevuto")
-- print(string.len(chaine))
-- rs:close()
-- print("Ho spedito a BT!")
-- else
-- print("Non spedito a BT, Errore apertura porta!")
-- end
--
-- end
comandoz = function(c)
local socket = require("socket")
host = host or "localhost"
port = port or 4444
local sock = assert(socket.connect(host, port))
sock:send(c)
local answer, e = sock:receive('*l', 'ANSWER-')
if (e) then
print("Errore " .. e)
else
print("Risposta " .. answer)
end
sock:close()
return answer
end
post_string = function(s,purl)
local http = require"socket.http"
local ltn12 = require"ltn12"
local reqbody = s --"this is the body to be sent via post"
local respbody = {} -- for the response body
local result, respcode, respheaders, respstatus = http.request {
method = "POST",
url = purl,
source = ltn12.source.string(reqbody),
headers = {
["content-type"] = "text/plain",
["content-length"] = tostring(#reqbody)
},
sink = ltn12.sink.table(respbody)
}
-- get body as string by concatenating table filled by sink
respbody = table.concat(respbody)
return respbody
end
|
-- REST Arduino Interface
-- Luca Colciago @dottork
-- 13/12/2015
--
--
local www_box = {
type = "regular"
}
local reset_meta = function(pos)
minetest.get_meta(pos):set_string("formspec", "field[channel;Channel;${channel}]".."field[ArduinoIPAddress;ArduinoIPAddress;${ArduinoIPAddress}]")
end
local clearscreen = function(pos)
local objects = minetest.get_objects_inside_radius(pos, 0.5)
for _, o in ipairs(objects) do
local o_entity = o:get_luaentity()
if o_entity and o_entity.name == "mbot:text" then
o:remove()
end
end
end
local on_digiline_receive = function(pos, node, channel, msg)
local meta = minetest.get_meta(pos)
local setchan = meta:get_string("channel")
print(setchan)
local setip =meta:get_string("ArduinoIPAddress")
if setchan ~= channel then return end
meta:set_string("text", msg)
meta:set_string("infotext", msg)
clearscreen(pos)
if msg ~= "" then
print("Arrivato un messaggio. Mando al BT")
local answer = comandoz(msg)
if answer ~= nil then
if string.len(answer) > 11 then
print("Arrivata una risposta diversa da un semplice ACK")
end
digiline:receptor_send(pos, digiline.rules.default, "risposta", answer)
end
end
end
minetest.register_node("mbot:lcc", {
drawtype = "nodebox",
description = "Digiline ArduinoYUN Connection",
inventory_image = "mbot.jpg",
wield_image = "mbot.jpg",
tiles = {"mbot.jpg"},
paramtype = "light",
sunlight_propagates = true,
paramtype2 = "facedir",
node_box = www_box,
selection_box = www_box,
groups = {choppy = 3, dig_immediate = 2},
after_place_node = function (pos, placer, itemstack)
local param2 = minetest.get_node(pos).param2
if param2 == 0 or param2 == 1 then
minetest.add_node(pos, {name = "mbot:lcc", param2 = 3})
end
end,
on_construct = function(pos)
reset_meta(pos)
end,
on_destruct = function(pos)
clearscreen(pos)
end,
on_receive_fields = function(pos, formname, fields, sender)
if (fields.channel) then
minetest.get_meta(pos):set_string("channel", fields.channel)
end
if (fields.channel) then
minetest.get_meta(pos):set_string("ArduinoIPAddress",fields.ArduinoIPAddress)
end
end,
digiline =
{
receptor = {},
effector = {
action = on_digiline_receive
},
},
light_source = 6,
})
minetest.register_entity("mbot:text", {
collisionbox = { 0, 0, 0, 0, 0, 0 },
visual = "upright_sprite",
textures = {},
on_activate = function(self)
local meta = minetest.get_meta(self.object:getpos())
local text = meta:get_string("text")
end
})
-- Funzione da migliorare per inviare i dati via bluetooth
-- comandoz = function(c)
-- print("Ho ricevuto questi caratteri")
-- print(string.len(c))
--
--
-- local wserial=io.open("/dev/rfcomm0","wb")
-- -- local wserial=io.open("/dev/ttyUSB0","w")
-- -- local wserial=io.open("datimbot","a")
-- if wserial ~= nil then
-- local rs = io.open("/dev/rfcomm0","rb")
-- print(wserial)
-- wserial:write(c)
-- wserial:close()
--
-- while chaine==nil do
-- chaine=rserial:read()
-- rserial:flush()
-- end
-- print("ricevuto")
-- print(string.len(chaine))
-- rs:close()
-- print("Ho spedito a BT!")
-- else
-- print("Non spedito a BT, Errore apertura porta!")
-- end
--
-- end
comandoz = function(c)
local socket = require("socket")
host = host or "localhost"
port = port or 4444
local sock = assert(socket.connect(host, port))
sock:send(c)
local answer, e = sock:receive('*l', 'ANSWER-')
--answer = "ANSWER-pippo"
if (e) then
print("Errore " .. e)
else
print("Risposta " .. answer)
end
sock:close()
return answer
end
post_string = function(s,purl)
local http = require"socket.http"
local ltn12 = require"ltn12"
local reqbody = s --"this is the body to be sent via post"
local respbody = {} -- for the response body
local result, respcode, respheaders, respstatus = http.request {
method = "POST",
url = purl,
source = ltn12.source.string(reqbody),
headers = {
["content-type"] = "text/plain",
["content-length"] = tostring(#reqbody)
},
sink = ltn12.sink.table(respbody)
}
-- get body as string by concatenating table filled by sink
respbody = table.concat(respbody)
return respbody
end
|
Piccoli fix alla mod_mbot
|
Piccoli fix alla mod_mbot
|
Lua
|
agpl-3.0
|
pdpfsug/playing-mBot,pdpfsug/playing-mBot
|
0e4f8f0823e07ea55aad633570531d46697735f8
|
spec/utils_spec.lua
|
spec/utils_spec.lua
|
local utils = require "luacheck.utils"
describe("utils", function()
describe("read_file", function()
it("returns contents of a file", function()
assert.equal("contents\n", utils.read_file("spec/folder/foo"))
end)
it("removes UTF-8 BOM", function()
assert.equal("foo\nbar\n", utils.read_file("spec/folder/bom"))
end)
it("returns nil for non-existent paths", function()
assert.is_nil(utils.read_file("spec/folder/non-existent"))
end)
it("returns nil for directories", function()
assert.is_nil(utils.read_file("spec/folder"))
end)
end)
describe("load", function()
it("loads function in an environment", function()
local f = utils.load("return g", {g = "foo"})
assert.is_function(f)
assert.is_equal("foo", f())
end)
it("returns nil on syntax error", function()
assert.is_nil(utils.load("return return", {}))
end)
end)
describe("load_config", function()
it("loads config from a file and returns it", function()
assert.same({foo = "bar"}, (utils.load_config("spec/folder/config")))
end)
it("passes second argument as environment", function()
local function bar() return "bar" end
assert.same({
foo = "bar",
bar = bar
}, (utils.load_config("spec/folder/env_config", {bar = bar})))
end)
it("returns nil, \"I/O\" for non-existent paths", function()
local ok, err = utils.load_config("spec/folder/non-existent")
assert.is_nil(ok)
assert.equal("I/O", err)
end)
it("returns nil, \"syntax\" for configs with syntax errors", function()
local ok, err = utils.load_config("spec/folder/bad_config")
assert.is_nil(ok)
assert.equal("syntax", err)
end)
it("returns nil, \"runtime\" for configs with run-time errors", function()
local ok, err = utils.load_config("spec/folder/env_config")
assert.is_nil(ok)
assert.equal("runtime", err)
end)
end)
describe("array_to_set", function()
it("converts array to set and returns it", function()
assert.same({foo = 3, bar = 2}, utils.array_to_set({"foo", "bar", "foo"}))
end)
end)
describe("concat_arrays", function()
it("returns concatenated arrays", function()
assert.same({1, 2, 3, 4}, utils.concat_arrays({{}, {1}, {2, 3, 4}, {}}))
end)
end)
describe("update", function()
it("updates first table with entries from second", function()
local t1 = {k1 = 1, k2 = 2}
local t2 = {k2 = 3, k3 = 4}
local ret = utils.update(t1, t2)
assert.same({k1 = 1, k2 = 3, k3 = 4}, t1)
assert.equal(t1, ret)
end)
end)
describe("class", function()
it("returns an object creator", function()
local cl = utils.class()
assert.is_table(cl)
cl.field = "foo"
local obj = cl()
assert.is_table(obj)
obj.field2 = "bar"
assert.equal("foo", obj.field)
assert.is_nil(cl.field2)
end)
it("calls __init on object creation", function()
local cl = utils.class()
cl.__init = spy.new(function() end)
local obj = cl("foo", "bar")
assert.spy(cl.__init).was_called(1)
assert.spy(cl.__init).was_called_with(obj, "foo", "bar")
end)
end)
describe("Stack", function()
it("supports push/pop operations and top/size fields", function()
local stack = utils.Stack()
assert.equal(0, stack.size)
assert.is_nil(stack.top)
stack:push(7)
stack:push(8)
assert.equal(2, stack.size)
assert.equal(8, stack.top)
assert.equal(8, stack:pop())
assert.equal(1, stack.size)
assert.equal(7, stack.top)
stack:push(4)
assert.equal(2, stack.size)
assert.equal(4, stack.top)
assert.equal(4, stack:pop())
assert.equal(7, stack:pop())
assert.equal(0, stack.size)
assert.is_nil(stack.top)
end)
end)
describe("pcall", function()
it("calls f with arg", function()
assert.equal(3, utils.pcall(math.sqrt, 9))
end)
it("returns nil, table if f throws a table", function()
local t = {"foo"}
local res, err = utils.pcall(function(x)
if x == 9 then
error(t)
else
return true
end
end, 9)
assert.is_nil(res)
assert.is_equal(t, err)
end)
it("rethrows if f crashes (throws not a table)", function()
assert.has_error(function() utils.pcall(error, "msg") end, "msg\nstack traceback:")
end)
end)
describe("ripairs", function()
it("returns reversed ipairs", function()
local arr = {foo = "bar", 5, 6, 7}
local iterated = {}
for i, v in utils.ripairs(arr) do
table.insert(iterated, {i, v})
end
assert.same({{3, 7}, {2, 6}, {1, 5}}, iterated)
end)
end)
describe("after", function()
it("returns substring after match", function()
assert.equal("foo bar: baz", utils.after("bar: foo bar: baz", "bar:%s*"))
end)
it("returns nil when there is no match", function()
assert.is_nil(utils.after("bar: foo bar: baz", "baz:%s*"))
end)
end)
describe("strip", function()
it("returns string without whitespace on ends", function()
assert.equal("foo bar", utils.strip("\tfoo bar\n "))
end)
end)
describe("split", function()
it("without separator, returns non-whitespace substrings", function()
assert.same({"foo", "bar", "baz"}, utils.split(" foo bar\n baz "))
end)
it("with separator, returns substrings between them", function()
assert.same({"", "foo", " bar", "", " baz "}, utils.split(",foo, bar,, baz ", ","))
end)
end)
describe("map", function()
it("maps function over an array", function()
assert.same({3, 1, 2}, utils.map(math.sqrt, {9, 1, 4}))
end)
end)
end)
|
local utils = require "luacheck.utils"
describe("utils", function()
describe("read_file", function()
it("returns contents of a file", function()
assert.equal("contents\n", utils.read_file("spec/folder/foo"))
end)
it("removes UTF-8 BOM", function()
assert.equal("foo\nbar\n", utils.read_file("spec/folder/bom"))
end)
it("returns nil for non-existent paths", function()
assert.is_nil(utils.read_file("spec/folder/non-existent"))
end)
it("returns nil for directories", function()
assert.is_nil(utils.read_file("spec/folder"))
end)
end)
describe("load", function()
it("loads function in an environment", function()
local f = utils.load("return g", {g = "foo"})
assert.is_function(f)
assert.is_equal("foo", f())
end)
it("returns nil on syntax error", function()
assert.is_nil(utils.load("return return", {}))
end)
end)
describe("load_config", function()
it("loads config from a file and returns it", function()
assert.same({foo = "bar"}, (utils.load_config("spec/folder/config")))
end)
it("passes second argument as environment", function()
local function bar() return "bar" end
assert.same({
foo = "bar",
bar = bar
}, (utils.load_config("spec/folder/env_config", {bar = bar})))
end)
it("returns nil, \"I/O\" for non-existent paths", function()
local ok, err = utils.load_config("spec/folder/non-existent")
assert.is_nil(ok)
assert.equal("I/O", err)
end)
it("returns nil, \"syntax\" for configs with syntax errors", function()
local ok, err = utils.load_config("spec/folder/bad_config")
assert.is_nil(ok)
assert.equal("syntax", err)
end)
it("returns nil, \"runtime\" for configs with run-time errors", function()
local ok, err = utils.load_config("spec/folder/env_config")
assert.is_nil(ok)
assert.equal("runtime", err)
end)
end)
describe("array_to_set", function()
it("converts array to set and returns it", function()
assert.same({foo = 3, bar = 2}, utils.array_to_set({"foo", "bar", "foo"}))
end)
end)
describe("concat_arrays", function()
it("returns concatenated arrays", function()
assert.same({1, 2, 3, 4}, utils.concat_arrays({{}, {1}, {2, 3, 4}, {}}))
end)
end)
describe("update", function()
it("updates first table with entries from second", function()
local t1 = {k1 = 1, k2 = 2}
local t2 = {k2 = 3, k3 = 4}
local ret = utils.update(t1, t2)
assert.same({k1 = 1, k2 = 3, k3 = 4}, t1)
assert.equal(t1, ret)
end)
end)
describe("class", function()
it("returns an object creator", function()
local cl = utils.class()
assert.is_table(cl)
cl.field = "foo"
local obj = cl()
assert.is_table(obj)
obj.field2 = "bar"
assert.equal("foo", obj.field)
assert.is_nil(cl.field2)
end)
it("calls __init on object creation", function()
local cl = utils.class()
cl.__init = spy.new(function() end)
local obj = cl("foo", "bar")
assert.spy(cl.__init).was_called(1)
assert.spy(cl.__init).was_called_with(obj, "foo", "bar")
end)
end)
describe("Stack", function()
it("supports push/pop operations and top/size fields", function()
local stack = utils.Stack()
assert.equal(0, stack.size)
assert.is_nil(stack.top)
stack:push(7)
stack:push(8)
assert.equal(2, stack.size)
assert.equal(8, stack.top)
assert.equal(8, stack:pop())
assert.equal(1, stack.size)
assert.equal(7, stack.top)
stack:push(4)
assert.equal(2, stack.size)
assert.equal(4, stack.top)
assert.equal(4, stack:pop())
assert.equal(7, stack:pop())
assert.equal(0, stack.size)
assert.is_nil(stack.top)
end)
end)
describe("pcall", function()
it("calls f with arg", function()
assert.equal(3, utils.pcall(math.sqrt, 9))
end)
it("returns nil, table if f throws a table", function()
local t = {"foo"}
local res, err = utils.pcall(function(x)
if x == 9 then
error(t)
else
return true
end
end, 9)
assert.is_nil(res)
assert.is_equal(t, err)
end)
it("rethrows if f crashes (throws not a table)", function()
local ok, err = pcall(utils.pcall, error, "msg")
assert.is_false(ok)
assert.matches("msg\nstack traceback:", err)
end)
end)
describe("ripairs", function()
it("returns reversed ipairs", function()
local arr = {foo = "bar", 5, 6, 7}
local iterated = {}
for i, v in utils.ripairs(arr) do
table.insert(iterated, {i, v})
end
assert.same({{3, 7}, {2, 6}, {1, 5}}, iterated)
end)
end)
describe("after", function()
it("returns substring after match", function()
assert.equal("foo bar: baz", utils.after("bar: foo bar: baz", "bar:%s*"))
end)
it("returns nil when there is no match", function()
assert.is_nil(utils.after("bar: foo bar: baz", "baz:%s*"))
end)
end)
describe("strip", function()
it("returns string without whitespace on ends", function()
assert.equal("foo bar", utils.strip("\tfoo bar\n "))
end)
end)
describe("split", function()
it("without separator, returns non-whitespace substrings", function()
assert.same({"foo", "bar", "baz"}, utils.split(" foo bar\n baz "))
end)
it("with separator, returns substrings between them", function()
assert.same({"", "foo", " bar", "", " baz "}, utils.split(",foo, bar,, baz ", ","))
end)
end)
describe("map", function()
it("maps function over an array", function()
assert.same({3, 1, 2}, utils.map(math.sqrt, {9, 1, 4}))
end)
end)
end)
|
Fix spec to work with latest luassert
|
Fix spec to work with latest luassert
|
Lua
|
mit
|
mpeterv/luacheck,linuxmaniac/luacheck,mpeterv/luacheck,mpeterv/luacheck,tst2005/luacheck,tst2005/luacheck,adan830/luacheck,adan830/luacheck,xpol/luacheck,linuxmaniac/luacheck,kidaa/luacheck,xpol/luacheck,xpol/luacheck,kidaa/luacheck
|
0b1fed4a41cf17dd97a8d9abbd7c81c21c9c3bc5
|
core/sessionmanager.lua
|
core/sessionmanager.lua
|
local tonumber, tostring = tonumber, tostring;
local ipairs, pairs, print= ipairs, pairs, print;
local collectgarbage = collectgarbage;
local m_random = import("math", "random");
local format = import("string", "format");
local hosts = hosts;
local sessions = sessions;
local modulemanager = require "core.modulemanager";
local log = require "util.logger".init("sessionmanager");
local error = error;
local uuid_generate = require "util.uuid".uuid_generate;
local rm_load_roster = require "core.rostermanager".load_roster;
local newproxy = newproxy;
local getmetatable = getmetatable;
module "sessionmanager"
local open_sessions = 0;
function new_session(conn)
local session = { conn = conn, priority = 0, type = "c2s_unauthed" };
if true then
session.trace = newproxy(true);
getmetatable(session.trace).__gc = function () open_sessions = open_sessions - 1; print("Session got collected, now "..open_sessions.." sessions are allocated") end;
end
open_sessions = open_sessions + 1;
local w = conn.write;
session.send = function (t) w(tostring(t)); end
return session;
end
function destroy_session(session)
session.log("info", "Destroying session");
if session.username then
if session.resource then
hosts[session.host].sessions[session.username].sessions[session.resource] = nil;
end
if not next(hosts[session.host].sessions[session.username], nil) then
hosts[session.host].sessions[session.username] = nil;
end
end
session.conn = nil;
session.disconnect = nil;
for k in pairs(session) do
if k ~= "trace" then
session[k] = nil;
end
end
end
function send_to_session(session, data)
log("debug", "Sending: %s", tostring(data));
session.conn.write(tostring(data));
end
function make_authenticated(session, username)
session.username = username;
if session.type == "c2s_unauthed" then
session.type = "c2s";
end
return true;
end
function bind_resource(session, resource)
if not session.username then return false, "auth"; end
if session.resource then return false, "constraint"; end -- We don't support binding multiple resources
resource = resource or uuid_generate();
--FIXME: Randomly-generated resources must be unique per-user, and never conflict with existing
if not hosts[session.host].sessions[session.username] then
hosts[session.host].sessions[session.username] = { sessions = {} };
else
if hosts[session.host].sessions[session.username].sessions[resource] then
-- Resource conflict
return false, "conflict"; -- TODO kick old resource
end
end
session.resource = resource;
session.full_jid = session.username .. '@' .. session.host .. '/' .. resource;
hosts[session.host].sessions[session.username].sessions[resource] = session;
session.roster = rm_load_roster(session.username, session.host);
return true;
end
function streamopened(session, attr)
local send = session.send;
session.host = attr.to or error("Client failed to specify destination hostname");
session.version = tonumber(attr.version) or 0;
session.streamid = m_random(1000000, 99999999);
print(session, session.host, "Client opened stream");
send("<?xml version='1.0'?>");
send(format("<stream:stream xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' id='%s' from='%s' version='1.0'>", session.streamid, session.host));
local features = {};
modulemanager.fire_event("stream-features", session, features);
send("<stream:features>");
for _, feature in ipairs(features) do
send_to_session(session, tostring(feature));
end
send("</stream:features>");
log("info", "Stream opened successfully");
session.notopen = nil;
end
return _M;
|
local tonumber, tostring = tonumber, tostring;
local ipairs, pairs, print, next= ipairs, pairs, print, next;
local collectgarbage = collectgarbage;
local m_random = import("math", "random");
local format = import("string", "format");
local hosts = hosts;
local sessions = sessions;
local modulemanager = require "core.modulemanager";
local log = require "util.logger".init("sessionmanager");
local error = error;
local uuid_generate = require "util.uuid".uuid_generate;
local rm_load_roster = require "core.rostermanager".load_roster;
local newproxy = newproxy;
local getmetatable = getmetatable;
module "sessionmanager"
local open_sessions = 0;
function new_session(conn)
local session = { conn = conn, priority = 0, type = "c2s_unauthed" };
if true then
session.trace = newproxy(true);
getmetatable(session.trace).__gc = function () open_sessions = open_sessions - 1; print("Session got collected, now "..open_sessions.." sessions are allocated") end;
end
open_sessions = open_sessions + 1;
local w = conn.write;
session.send = function (t) w(tostring(t)); end
return session;
end
function destroy_session(session)
session.log("info", "Destroying session");
if session.username then
if session.resource then
hosts[session.host].sessions[session.username].sessions[session.resource] = nil;
end
if not next(hosts[session.host].sessions[session.username].sessions) then
log("debug", "All resources of %s are now offline", session.username);
hosts[session.host].sessions[session.username] = nil;
end
end
session.conn = nil;
session.disconnect = nil;
for k in pairs(session) do
if k ~= "trace" then
session[k] = nil;
end
end
end
function send_to_session(session, data)
log("debug", "Sending: %s", tostring(data));
session.conn.write(tostring(data));
end
function make_authenticated(session, username)
session.username = username;
if session.type == "c2s_unauthed" then
session.type = "c2s";
end
return true;
end
function bind_resource(session, resource)
if not session.username then return false, "auth"; end
if session.resource then return false, "constraint"; end -- We don't support binding multiple resources
resource = resource or uuid_generate();
--FIXME: Randomly-generated resources must be unique per-user, and never conflict with existing
if not hosts[session.host].sessions[session.username] then
hosts[session.host].sessions[session.username] = { sessions = {} };
else
if hosts[session.host].sessions[session.username].sessions[resource] then
-- Resource conflict
return false, "conflict"; -- TODO kick old resource
end
end
session.resource = resource;
session.full_jid = session.username .. '@' .. session.host .. '/' .. resource;
hosts[session.host].sessions[session.username].sessions[resource] = session;
session.roster = rm_load_roster(session.username, session.host);
return true;
end
function streamopened(session, attr)
local send = session.send;
session.host = attr.to or error("Client failed to specify destination hostname");
session.version = tonumber(attr.version) or 0;
session.streamid = m_random(1000000, 99999999);
print(session, session.host, "Client opened stream");
send("<?xml version='1.0'?>");
send(format("<stream:stream xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' id='%s' from='%s' version='1.0'>", session.streamid, session.host));
local features = {};
modulemanager.fire_event("stream-features", session, features);
send("<stream:features>");
for _, feature in ipairs(features) do
send_to_session(session, tostring(feature));
end
send("</stream:features>");
log("info", "Stream opened successfully");
session.notopen = nil;
end
return _M;
|
Final fix for marking user offline when all resources are gone :)
|
Final fix for marking user offline when all resources are gone :)
|
Lua
|
mit
|
sarumjanuch/prosody,sarumjanuch/prosody
|
44f12b0d97eb87e190e7642412e1d1b94002256b
|
tests/test-tls-sni-server-client.lua
|
tests/test-tls-sni-server-client.lua
|
--[[
Copyright 2012-2015 The Luvit Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
require('tap')(function (test)
local fixture = require('./fixture-tls')
local table = require('table')
local tls = require('tls')
local options = {
key = fixture.loadPEM('agent2-key'),
cert = fixture.loadPEM('agent2-cert')
}
local SNIContexts = {}
SNIContexts['a.example.com'] = {
key = fixture.loadPEM('agent1-key'),
cert = fixture.loadPEM('agent1-cert')
}
SNIContexts['asterisk.test.com'] = {
key = fixture.loadPEM('agent3-key'),
cert = fixture.loadPEM('agent3-cert')
}
local clientsOptions = {
{
port = fixture.commonPort,
key = fixture.loadPEM('agent1-key'),
cert = fixture.loadPEM('agent1-cert'),
ca = fixture.loadPEM('ca1-cert'),
servername = 'a.example.com'
},{
port = fixture.commonPort,
key = fixture.loadPEM('agent2-key'),
cert = fixture.loadPEM('agent2-cert'),
ca = fixture.loadPEM('ca2-cert'),
servername = 'b.test.com'
},{
port = fixture.commonPort,
key = fixture.loadPEM('agent3-key'),
cert = fixture.loadPEM('agent3-cert'),
ca = fixture.loadPEM('ca1-cert'),
servername = 'c.wrong.com'
}
}
local serverResults = {}
local clientResults = {}
test("tls sni server cleint", function()
local server
server = tls.createServer(options, function(conn)
p(conn.ssl:get('hostname'))
table.insert(serverResults, conn.serverName)
end)
local function connectClient(options, callback)
local client
options.host = '127.0.0.1'
client = tls.connect(options)
client:on('connect', function()
table.insert(clientResults, client.authorized)
client:destroy()
callback()
end)
end
server:listen(fixture.commonPort, '127.0.0.1', function()
server:sni({
['a.example.com']=SNIContexts['a.example.com'],
['b.test.com']=SNIContexts['asterisk.test.com']
});
connectClient(clientsOptions[1], function()
connectClient(clientsOptions[2], function()
connectClient(clientsOptions[3], function()
server:close()
end)
end)
end)
end)
end)
end)
|
--[[
Copyright 2012-2015 The Luvit Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
require('tap')(function (test)
local fixture = require('./fixture-tls')
local table = require('table')
local tls = require('tls')
local options = {
key = fixture.loadPEM('agent2-key'),
cert = fixture.loadPEM('agent2-cert')
}
local SNIContexts = {}
SNIContexts['a.example.com'] = {
key = fixture.loadPEM('agent1-key'),
cert = fixture.loadPEM('agent1-cert')
}
SNIContexts['asterisk.test.com'] = {
key = fixture.loadPEM('agent3-key'),
cert = fixture.loadPEM('agent3-cert')
}
local clientsOptions = {
{
port = fixture.commonPort,
key = fixture.loadPEM('agent1-key'),
cert = fixture.loadPEM('agent1-cert'),
ca = fixture.loadPEM('ca1-cert'),
servername = 'a.example.com'
},{
port = fixture.commonPort,
key = fixture.loadPEM('agent2-key'),
cert = fixture.loadPEM('agent2-cert'),
ca = fixture.loadPEM('ca2-cert'),
servername = 'b.test.com'
},{
port = fixture.commonPort,
key = fixture.loadPEM('agent3-key'),
cert = fixture.loadPEM('agent3-cert'),
ca = fixture.loadPEM('ca1-cert'),
servername = 'c.wrong.com'
}
}
local serverResults = {}
local clientResults = {}
test("tls sni server cleint", function()
local server
server = tls.createServer(options, function(conn)
p(conn.ssl:get('hostname'))
table.insert(serverResults, conn.serverName)
conn:destroy()
end)
local function connectClient(options, callback)
local client
options.host = '127.0.0.1'
client = tls.connect(options)
clientResults[options.servername] = false
client:on('secureConnection', function()
clientResults[options.servername] = client.authorized
end)
client:on("_socketEnd", function ()
client:destroy()
callback()
end)
end
server:listen(fixture.commonPort, '127.0.0.1', function()
server:sni({
['a.example.com']=SNIContexts['a.example.com'],
['b.test.com']=SNIContexts['asterisk.test.com']
});
connectClient(clientsOptions[1], function()
connectClient(clientsOptions[2], function()
connectClient(clientsOptions[3], function()
p(clientResults)
assert(clientResults['a.example.com'])
assert(clientResults['b.test.com'])
assert(not clientResults['c.wrong.com'])
server:close()
end)
end)
end)
end)
end)
end)
|
Fix sni test to actually test something and not race and leak
|
Fix sni test to actually test something and not race and leak
|
Lua
|
apache-2.0
|
zhaozg/luvit,luvit/luvit,zhaozg/luvit,luvit/luvit
|
61b0f54731d3922b7e88a196f7140a2cf6101dec
|
includes/bootstrap.lua
|
includes/bootstrap.lua
|
local version = ('Ophal (ophal.org);version:0.1-alpha11')
-- Jailed environment functions and modules
env = {
io = io,
os = os,
tonumber = tonumber,
type = type,
module = module,
pcall = pcall,
loadstring = loadstring,
setfenv = setfenv,
getfenv = getfenv,
assert = assert,
table = table,
require = require,
unpack = unpack,
pairs = pairs,
ipairs = ipairs,
rawset = rawset,
rawget = rawget,
error = error,
debug = debug,
package = package,
string = string,
math = math,
next = next,
tostring = tostring,
setmetatable = setmetatable,
getmetatable = getmetatable,
select = select,
_SERVER = os.getenv,
_SESSION = nil,
lfs = nil,
lpeg = nil,
uuid = nil,
socket = nil,
theme = {},
mobile = {},
base = {
system_root = '',
route = '/',
url = '',
path = '',
},
output_buffer = {},
ophal = {
version = version,
modules = {},
routes = {},
aliases = {},
blocks = {},
regions = {},
title = '',
header_title = '',
cookies = {},
header = nil,
session = nil,
},
}
-- Load settings
settings = {
slash = string.sub(package.config,1,1),
modules = {},
}
do
local _, vault = pcall(require, 'vault')
local _, settings_builder = pcall(require, 'settings')
settings_builder(settings, vault)
env.settings = settings
end
-- Detect nginx
if ngx then
env.ngx = ngx
for k, v in pairs(getfenv(0, ngx)) do
env[k] = v
end
end
-- The actual module
local setfenv, type, env = setfenv, type, env
module 'ophal'
function bootstrap(phase, main)
if type(main) ~= 'function' then main = function() end end
local status, err, exit_bootstrap
-- Jail
setfenv(0, env) -- global environment
setfenv(1, env) -- bootstrap environment
setfenv(main, env) -- script environment
env._G = env
env.env = env
local phases = {
-- 1. Lua and Seawolf libraries
function ()
env.lfs = require 'lfs'
env.lpeg = require 'lpeg'
env.uuid = require 'uuid'
env.socket = require 'socket'
env.socket.url = require 'socket.url'
require 'seawolf.variable'
require 'seawolf.fs'
require 'seawolf.text'
require 'seawolf.behaviour'
require 'seawolf.contrib'
end,
-- 2. Debug API
function ()
if settings.debugapi then
require 'includes.debug'
end
end,
-- 3. Load native server API
function ()
if ngx then
require 'includes.server.nginx'
else
require 'includes.server.cgi'
end
end,
-- 4. Mobile API,
function ()
if settings.mobile then
require 'includes.mobile'
end
end,
-- 5. Load Ophal server API
function ()
require 'includes.server.init'
end,
-- 6. Check installer
function ()
if (_SERVER 'SCRIPT_NAME' or '/index.cgi') == base.route .. 'index.cgi' and not seawolf.fs.is_file 'settings.lua' then
redirect(('%s%sinstall.cgi'):format(base.system_root, base.route))
require 'includes.common'
return -1
end
end,
-- 7. Session API,
function ()
if settings.sessionapi then
require 'includes.session'
session_start()
end
end,
-- 8. Route API,
function ()
require 'includes.route'
build_base()
end,
-- 9. Core API,
function ()
require 'includes.common'
require 'includes.module'
require 'includes.theme'
require 'includes.pager'
if settings.formapi then
require 'includes.form'
require 'includes.file'
end
end,
-- 10. Modules,
function ()
local status, err
for k, v in pairs(settings.modules) do
if v then
status, err = pcall(require, 'modules.' .. k .. '.init')
if not status then
print('bootstrap: ' .. err)
end
end
end
end,
-- 11. Boot,
function ()
module_invoke_all 'boot'
end,
-- 12. Database API,
function ()
if settings.db ~= nil then
require 'includes.database'
if settings.db.default ~= nil then
db_connect()
if settings.route_aliases_storage then
route_aliases_load()
end
end
end
end,
-- 13. Init,
function ()
module_invoke_all 'init'
end,
-- 14. Full,
function ()
-- call hook route to load handlers
-- TODO: implement route cache
ophal.routes = route_build_routes()
theme_blocks_load()
theme_regions_load()
-- process current route
init_route()
end,
}
-- Loop over phase
for p = 1, (phase or #phases) do
status, err = pcall(phases[p])
if not status then
io.write(([[
bootstrap[%s]: %s]]):format(p, err or ''))
exit_bootstrap = true
break
elseif err == -1 then
exit_bootstrap = true
break
end
end
-- execute script
if not exit_bootstrap then
status, err = pcall(main)
if not status then
io.write([[
bootstrap[main]: ]] .. (err or ''))
end
end
-- The end
exit_ophal()
end
|
local version = ('Ophal (ophal.org);version:0.1-alpha11')
-- Jailed environment functions and modules
env = {
io = io,
os = os,
tonumber = tonumber,
type = type,
module = module,
pcall = pcall,
loadstring = loadstring,
setfenv = setfenv,
getfenv = getfenv,
assert = assert,
table = table,
require = require,
unpack = unpack,
pairs = pairs,
ipairs = ipairs,
rawset = rawset,
rawget = rawget,
error = error,
debug = debug,
package = package,
string = string,
math = math,
next = next,
tostring = tostring,
setmetatable = setmetatable,
getmetatable = getmetatable,
select = select,
_SERVER = os.getenv,
_SESSION = nil,
lfs = nil,
lpeg = nil,
uuid = nil,
socket = nil,
theme = {},
mobile = {},
base = {
system_root = '',
route = '/',
url = '',
path = '',
},
output_buffer = {},
ophal = {
version = version,
modules = {},
routes = {},
aliases = {},
blocks = {},
regions = {},
title = '',
header_title = '',
cookies = {},
header = nil,
session = nil,
},
}
-- Load settings
settings = {
slash = string.sub(package.config,1,1),
modules = {},
}
do
local _, vault = pcall(require, 'vault')
local _, settings_builder = pcall(require, 'settings')
if type(settings_builder) == 'function' then
settings_builder(settings, vault)
end
env.settings = settings
end
-- Detect nginx
if ngx then
env.ngx = ngx
for k, v in pairs(getfenv(0, ngx)) do
env[k] = v
end
end
-- The actual module
local setfenv, type, env = setfenv, type, env
module 'ophal'
function bootstrap(phase, main)
if type(main) ~= 'function' then main = function() end end
local status, err, exit_bootstrap
-- Jail
setfenv(0, env) -- global environment
setfenv(1, env) -- bootstrap environment
setfenv(main, env) -- script environment
env._G = env
env.env = env
local phases = {
-- 1. Lua and Seawolf libraries
function ()
env.lfs = require 'lfs'
env.lpeg = require 'lpeg'
env.uuid = require 'uuid'
env.socket = require 'socket'
env.socket.url = require 'socket.url'
require 'seawolf.variable'
require 'seawolf.fs'
require 'seawolf.text'
require 'seawolf.behaviour'
require 'seawolf.contrib'
end,
-- 2. Debug API
function ()
if settings.debugapi then
require 'includes.debug'
end
end,
-- 3. Load native server API
function ()
if ngx then
require 'includes.server.nginx'
else
require 'includes.server.cgi'
end
end,
-- 4. Mobile API,
function ()
if settings.mobile then
require 'includes.mobile'
end
end,
-- 5. Load Ophal server API
function ()
require 'includes.server.init'
end,
-- 6. Check installer
function ()
if (_SERVER 'SCRIPT_NAME' or '/index.cgi') == base.route .. 'index.cgi' and not seawolf.fs.is_file 'settings.lua' then
redirect(('%s%sinstall.cgi'):format(base.system_root, base.route))
require 'includes.common'
return -1
end
end,
-- 7. Session API,
function ()
if settings.sessionapi then
require 'includes.session'
session_start()
end
end,
-- 8. Route API,
function ()
require 'includes.route'
build_base()
end,
-- 9. Core API,
function ()
require 'includes.common'
require 'includes.module'
require 'includes.theme'
require 'includes.pager'
if settings.formapi then
require 'includes.form'
require 'includes.file'
end
end,
-- 10. Modules,
function ()
local status, err
for k, v in pairs(settings.modules) do
if v then
status, err = pcall(require, 'modules.' .. k .. '.init')
if not status then
print('bootstrap: ' .. err)
end
end
end
end,
-- 11. Boot,
function ()
module_invoke_all 'boot'
end,
-- 12. Database API,
function ()
if settings.db ~= nil then
require 'includes.database'
if settings.db.default ~= nil then
db_connect()
if settings.route_aliases_storage then
route_aliases_load()
end
end
end
end,
-- 13. Init,
function ()
module_invoke_all 'init'
end,
-- 14. Full,
function ()
-- call hook route to load handlers
-- TODO: implement route cache
ophal.routes = route_build_routes()
theme_blocks_load()
theme_regions_load()
-- process current route
init_route()
end,
}
-- Loop over phase
for p = 1, (phase or #phases) do
status, err = pcall(phases[p])
if not status then
io.write(([[
bootstrap[%s]: %s]]):format(p, err or ''))
exit_bootstrap = true
break
elseif err == -1 then
exit_bootstrap = true
break
end
end
-- execute script
if not exit_bootstrap then
status, err = pcall(main)
if not status then
io.write([[
bootstrap[main]: ]] .. (err or ''))
end
end
-- The end
exit_ophal()
end
|
Bug fix: bootstrap breaks when settings.lua is missing.
|
Bug fix: bootstrap breaks when settings.lua is missing.
|
Lua
|
agpl-3.0
|
ophal/core,coinzen/coinage,coinzen/coinage,coinzen/coinage,ophal/core,ophal/core
|
c28c94dae509421ae71ebac3e4d66f36d6690a48
|
kong/plugins/oauth2/migrations/001_14_to_15.lua
|
kong/plugins/oauth2/migrations/001_14_to_15.lua
|
return {
postgres = {
up = [[
DO $$
BEGIN
ALTER TABLE IF EXISTS ONLY "oauth2_credentials" ADD "redirect_uris" TEXT[];
EXCEPTION WHEN DUPLICATE_COLUMN THEN
-- Do nothing, accept existing state
END$$;
DO $$
BEGIN
UPDATE "oauth2_credentials"
SET "redirect_uris" = TRANSLATE("redirect_uri", '[]', '{}')::TEXT[];
EXCEPTION WHEN UNDEFINED_COLUMN THEN
-- Do nothing, accept existing state
END$$;
DO $$
BEGIN
ALTER TABLE IF EXISTS ONLY "oauth2_authorization_codes" ADD "ttl" TIMESTAMP WITH TIME ZONE;
EXCEPTION WHEN DUPLICATE_COLUMN THEN
-- Do nothing, accept existing state
END$$;
UPDATE "oauth2_authorization_codes"
SET "ttl" = "created_at" + INTERVAL '300 seconds';
DO $$
BEGIN
ALTER TABLE IF EXISTS ONLY "oauth2_tokens" ADD "ttl" TIMESTAMP WITH TIME ZONE;
EXCEPTION WHEN DUPLICATE_COLUMN THEN
-- Do nothing, accept existing state
END$$;
UPDATE "oauth2_tokens"
SET "ttl" = "created_at" + (COALESCE("expires_in", 0)::TEXT || ' seconds')::INTERVAL;
ALTER TABLE IF EXISTS ONLY "oauth2_credentials"
ALTER "created_at" TYPE TIMESTAMP WITH TIME ZONE USING "created_at" AT TIME ZONE 'UTC',
ALTER "created_at" SET DEFAULT CURRENT_TIMESTAMP(0) AT TIME ZONE 'UTC';
ALTER TABLE IF EXISTS ONLY "oauth2_authorization_codes"
ALTER "created_at" TYPE TIMESTAMP WITH TIME ZONE USING "created_at" AT TIME ZONE 'UTC',
ALTER "created_at" SET DEFAULT CURRENT_TIMESTAMP(0) AT TIME ZONE 'UTC';
ALTER TABLE IF EXISTS ONLY "oauth2_tokens"
ALTER "created_at" TYPE TIMESTAMP WITH TIME ZONE USING "created_at" AT TIME ZONE 'UTC',
ALTER "created_at" SET DEFAULT CURRENT_TIMESTAMP(0) AT TIME ZONE 'UTC';
CREATE INDEX IF NOT EXISTS "oauth2_authorization_credential_id_idx" ON "oauth2_authorization_codes" ("credential_id");
CREATE INDEX IF NOT EXISTS "oauth2_authorization_service_id_idx" ON "oauth2_authorization_codes" ("service_id");
CREATE INDEX IF NOT EXISTS "oauth2_authorization_api_id_idx" ON "oauth2_authorization_codes" ("api_id");
CREATE INDEX IF NOT EXISTS "oauth2_tokens_credential_id_idx" ON "oauth2_tokens" ("credential_id");
CREATE INDEX IF NOT EXISTS "oauth2_tokens_service_id_idx" ON "oauth2_tokens" ("service_id");
CREATE INDEX IF NOT EXISTS "oauth2_tokens_api_id_idx" ON "oauth2_tokens" ("api_id");
DO $$
BEGIN
ALTER INDEX IF EXISTS "oauth2_credentials_consumer_idx" RENAME TO "oauth2_credentials_consumer_id_idx";
EXCEPTION WHEN DUPLICATE_TABLE THEN
-- Do nothing, accept existing state
END;
$$;
DO $$
BEGIN
ALTER INDEX IF EXISTS "oauth2_authorization_userid_idx" RENAME TO "oauth2_authorization_codes_authenticated_userid_idx";
EXCEPTION WHEN DUPLICATE_TABLE THEN
-- Do nothing, accept existing state
END;
$$;
DO $$
BEGIN
ALTER INDEX IF EXISTS "oauth2_token_userid_idx" RENAME TO "oauth2_tokens_authenticated_userid_idx";
EXCEPTION WHEN DUPLICATE_TABLE THEN
-- Do nothing, accept existing state
END;
$$;
-- Unique constraint on "client_id" already adds btree index
DROP INDEX IF EXISTS "oauth2_credentials_client_idx";
-- Unique constraint on "code" already adds btree index
DROP INDEX IF EXISTS "oauth2_autorization_code_idx";
-- Unique constraint on "access_token" already adds btree index
DROP INDEX IF EXISTS "oauth2_accesstoken_idx";
-- Unique constraint on "refresh_token" already adds btree index
DROP INDEX IF EXISTS "oauth2_token_refresh_idx";
]],
teardown = function(connector)
assert(connector:query [[
DO $$
BEGIN
ALTER TABLE "oauth2_credentials" DROP "redirect_uri";
EXCEPTION WHEN UNDEFINED_COLUMN THEN
-- Do nothing, accept existing state
END$$;
]])
end,
},
cassandra = {
up = [[
ALTER TABLE oauth2_credentials ADD redirect_uris set<text>;
]],
teardown = function(connector)
local cjson = require "cjson"
local coordinator = assert(connector:connect_migrations())
for rows, err in coordinator:iterate([[
SELECT id, redirect_uri FROM oauth2_credentials]]) do
if err then
return nil, err
end
for _, row in ipairs(rows) do
local uris = cjson.decode(row.redirect_uri)
local buffer = {}
for i, uri in ipairs(uris) do
buffer[i] = "'" .. uri .. "'"
end
local q = string.format([[
UPDATE oauth2_credentials
SET redirect_uris = {%s} WHERE id = %s
]], table.concat(buffer, ","), row.id)
assert(connector:query(q))
end
end
assert(connector:query([[
ALTER TABLE oauth2_credentials DROP redirect_uri
]]))
end,
},
}
|
return {
postgres = {
up = [[
DO $$
BEGIN
ALTER TABLE IF EXISTS ONLY "oauth2_credentials" ADD "redirect_uris" TEXT[];
EXCEPTION WHEN DUPLICATE_COLUMN THEN
-- Do nothing, accept existing state
END$$;
DO $$
BEGIN
UPDATE "oauth2_credentials"
SET "redirect_uris" = TRANSLATE("redirect_uri", '[]', '{}')::TEXT[];
EXCEPTION WHEN UNDEFINED_COLUMN THEN
-- Do nothing, accept existing state
END$$;
DO $$
BEGIN
ALTER TABLE IF EXISTS ONLY "oauth2_authorization_codes" ADD "ttl" TIMESTAMP WITH TIME ZONE;
EXCEPTION WHEN DUPLICATE_COLUMN THEN
-- Do nothing, accept existing state
END$$;
UPDATE "oauth2_authorization_codes"
SET "ttl" = "created_at" + INTERVAL '300 seconds';
DO $$
BEGIN
ALTER TABLE IF EXISTS ONLY "oauth2_tokens" ADD "ttl" TIMESTAMP WITH TIME ZONE;
EXCEPTION WHEN DUPLICATE_COLUMN THEN
-- Do nothing, accept existing state
END$$;
UPDATE "oauth2_tokens"
SET "ttl" = "created_at" + (COALESCE("expires_in", 0)::TEXT || ' seconds')::INTERVAL;
ALTER TABLE IF EXISTS ONLY "oauth2_credentials"
ALTER "created_at" TYPE TIMESTAMP WITH TIME ZONE USING "created_at" AT TIME ZONE 'UTC',
ALTER "created_at" SET DEFAULT CURRENT_TIMESTAMP(0) AT TIME ZONE 'UTC';
ALTER TABLE IF EXISTS ONLY "oauth2_authorization_codes"
ALTER "created_at" TYPE TIMESTAMP WITH TIME ZONE USING "created_at" AT TIME ZONE 'UTC',
ALTER "created_at" SET DEFAULT CURRENT_TIMESTAMP(0) AT TIME ZONE 'UTC';
ALTER TABLE IF EXISTS ONLY "oauth2_tokens"
ALTER "created_at" TYPE TIMESTAMP WITH TIME ZONE USING "created_at" AT TIME ZONE 'UTC',
ALTER "created_at" SET DEFAULT CURRENT_TIMESTAMP(0) AT TIME ZONE 'UTC';
CREATE INDEX IF NOT EXISTS "oauth2_authorization_credential_id_idx" ON "oauth2_authorization_codes" ("credential_id");
CREATE INDEX IF NOT EXISTS "oauth2_authorization_service_id_idx" ON "oauth2_authorization_codes" ("service_id");
CREATE INDEX IF NOT EXISTS "oauth2_authorization_api_id_idx" ON "oauth2_authorization_codes" ("api_id");
CREATE INDEX IF NOT EXISTS "oauth2_tokens_credential_id_idx" ON "oauth2_tokens" ("credential_id");
CREATE INDEX IF NOT EXISTS "oauth2_tokens_service_id_idx" ON "oauth2_tokens" ("service_id");
CREATE INDEX IF NOT EXISTS "oauth2_tokens_api_id_idx" ON "oauth2_tokens" ("api_id");
DO $$
BEGIN
ALTER INDEX IF EXISTS "oauth2_credentials_consumer_idx" RENAME TO "oauth2_credentials_consumer_id_idx";
EXCEPTION WHEN DUPLICATE_TABLE THEN
-- Do nothing, accept existing state
END;
$$;
DO $$
BEGIN
ALTER INDEX IF EXISTS "oauth2_authorization_userid_idx" RENAME TO "oauth2_authorization_codes_authenticated_userid_idx";
EXCEPTION WHEN DUPLICATE_TABLE THEN
-- Do nothing, accept existing state
END;
$$;
DO $$
BEGIN
ALTER INDEX IF EXISTS "oauth2_token_userid_idx" RENAME TO "oauth2_tokens_authenticated_userid_idx";
EXCEPTION WHEN DUPLICATE_TABLE THEN
-- Do nothing, accept existing state
END;
$$;
-- Unique constraint on "client_id" already adds btree index
DROP INDEX IF EXISTS "oauth2_credentials_client_idx";
-- Unique constraint on "code" already adds btree index
DROP INDEX IF EXISTS "oauth2_autorization_code_idx";
-- Unique constraint on "access_token" already adds btree index
DROP INDEX IF EXISTS "oauth2_accesstoken_idx";
-- Unique constraint on "refresh_token" already adds btree index
DROP INDEX IF EXISTS "oauth2_token_refresh_idx";
]],
teardown = function(connector)
assert(connector:query [[
DO $$
BEGIN
ALTER TABLE "oauth2_credentials" DROP "redirect_uri";
EXCEPTION WHEN UNDEFINED_COLUMN THEN
-- Do nothing, accept existing state
END$$;
]])
end,
},
cassandra = {
up = [[
ALTER TABLE oauth2_credentials ADD redirect_uris set<text>;
]],
teardown = function(connector)
local cjson = require "cjson"
local coordinator = assert(connector:connect_migrations())
for rows, err in coordinator:iterate([[
SELECT id, redirect_uri FROM oauth2_credentials]]) do
if err then
return nil, err
end
for _, row in ipairs(rows) do
if row.redirect_uri then
local uris = cjson.decode(row.redirect_uri)
local buffer = {}
for i, uri in ipairs(uris) do
buffer[i] = "'" .. uri .. "'"
end
local q = string.format([[
UPDATE oauth2_credentials
SET redirect_uris = {%s} WHERE id = %s
]], table.concat(buffer, ","), row.id)
assert(connector:query(q))
end
end
end
assert(connector:query([[
ALTER TABLE oauth2_credentials DROP redirect_uri
]]))
end,
},
}
|
hotfix(oauth2) make Cassandra migration more resilient (#4112)
|
hotfix(oauth2) make Cassandra migration more resilient (#4112)
Avoid a crash if, during a Blue/Green migration, a new credential
is inserted by the Blue cluster.
|
Lua
|
apache-2.0
|
Kong/kong,Kong/kong,Kong/kong,Mashape/kong
|
d2e68068bf050eeecbb9e13775317929df7685c1
|
profiles/car.lua
|
profiles/car.lua
|
-- Begin of globals
require("lib/access")
barrier_whitelist = { ["cattle_grid"] = true, ["border_control"] = true, ["toll_booth"] = true, ["sally_port"] = true, ["gate"] = true, ["no"] = true, ["entrance"] = true}
access_tag_whitelist = { ["yes"] = true, ["motorcar"] = true, ["motor_vehicle"] = true, ["vehicle"] = true, ["permissive"] = true, ["designated"] = true }
access_tag_blacklist = { ["no"] = true, ["private"] = true, ["agricultural"] = true, ["forestry"] = true }
access_tag_restricted = { ["destination"] = true, ["delivery"] = true }
access_tags = { "motorcar", "motor_vehicle", "vehicle" }
access_tags_hierachy = { "motorcar", "motor_vehicle", "vehicle", "access" }
service_tag_restricted = { ["parking_aisle"] = true }
ignore_in_grid = { ["ferry"] = true }
restriction_exception_tags = { "motorcar", "motor_vehicle", "vehicle" }
speed_profile = {
["motorway"] = 90,
["motorway_link"] = 75,
["trunk"] = 85,
["trunk_link"] = 70,
["primary"] = 65,
["primary_link"] = 60,
["secondary"] = 55,
["secondary_link"] = 50,
["tertiary"] = 40,
["tertiary_link"] = 30,
["unclassified"] = 25,
["residential"] = 25,
["living_street"] = 10,
["service"] = 15,
-- ["track"] = 5,
["ferry"] = 5,
["shuttle_train"] = 10,
["default"] = 50
}
take_minimum_of_speeds = false
obey_oneway = true
obey_bollards = true
use_restrictions = true
ignore_areas = true -- future feature
traffic_signal_penalty = 2
u_turn_penalty = 20
-- End of globals
function get_exceptions(vector)
for i,v in ipairs(restriction_exception_tags) do
vector:Add(v)
end
end
local function parse_maxspeed(source)
if source == nil then
return 0
end
local n = tonumber(source:match("%d*"))
if n == nil then
n = 0
end
if string.match(source, "mph") or string.match(source, "mp/h") then
n = (n*1609)/1000;
end
return math.abs(n)
end
function node_function (node)
local barrier = node.tags:Find ("barrier")
local access = Access.find_access_tag(node, access_tags_hierachy)
local traffic_signal = node.tags:Find("highway")
--flag node if it carries a traffic light
if traffic_signal == "traffic_signals" then
node.traffic_light = true;
end
-- parse access and barrier tags
if access and access ~= "" then
if access_tag_blacklist[access] then
node.bollard = true
end
elseif barrier and barrier ~= "" then
if barrier_whitelist[barrier] then
return
else
node.bollard = true
end
end
return 1
end
function way_function (way)
-- we dont route over areas
local area = way.tags:Find("area")
if ignore_areas and ("yes" == area) then
return 0
end
-- check if oneway tag is unsupported
local oneway = way.tags:Find("oneway")
if "reversible" == oneway then
return 0
end
-- Check if we are allowed to access the way
local access = Access.find_access_tag(way, access_tags_hierachy)
if access_tag_blacklist[access] then
return 0
end
-- Second, parse the way according to these properties
local highway = way.tags:Find("highway")
local name = way.tags:Find("name")
local ref = way.tags:Find("ref")
local junction = way.tags:Find("junction")
local route = way.tags:Find("route")
local maxspeed = parse_maxspeed(way.tags:Find ( "maxspeed") )
local maxspeed_forward = parse_maxspeed(way.tags:Find( "maxspeed:forward"))
local maxspeed_backward = parse_maxspeed(way.tags:Find( "maxspeed:backward"))
local barrier = way.tags:Find("barrier")
local cycleway = way.tags:Find("cycleway")
local duration = way.tags:Find("duration")
local service = way.tags:Find("service")
-- Set the name that will be used for instructions
if "" ~= ref then
way.name = ref
elseif "" ~= name then
way.name = name
-- else
-- way.name = highway -- if no name exists, use way type
end
if "roundabout" == junction then
way.roundabout = true;
end
-- Handling ferries and piers
if (speed_profile[route] ~= nil and speed_profile[route] > 0) then
if durationIsValid(duration) then
way.duration = math.max( parseDuration(duration), 1 );
end
way.direction = Way.bidirectional
if speed_profile[route] ~= nil then
highway = route;
end
if tonumber(way.duration) < 0 then
way.speed = speed_profile[highway]
end
end
-- Set the avg speed on the way if it is accessible by road class
if (speed_profile[highway] ~= nil and way.speed == -1 ) then
if maxspeed > speed_profile[highway] then
way.speed = maxspeed
else
if 0 == maxspeed then
maxspeed = math.huge
end
way.speed = math.min(speed_profile[highway], maxspeed)
end
end
-- Set the avg speed on ways that are marked accessible
if "" ~= highway and access_tag_whitelist[access] and way.speed == -1 then
if 0 == maxspeed then
maxspeed = math.huge
end
way.speed = math.min(speed_profile["default"], maxspeed)
end
-- Set access restriction flag if access is allowed under certain restrictions only
if access ~= "" and access_tag_restricted[access] then
way.is_access_restricted = true
end
-- Set access restriction flag if service is allowed under certain restrictions only
if service ~= "" and service_tag_restricted[service] then
way.is_access_restricted = true
end
-- Set direction according to tags on way
way.direction = Way.bidirectional
if obey_oneway then
if oneway == "-1" then
way.direction = Way.opposite
elseif oneway == "yes" or oneway == "1" or oneway == "true" or junction == "roundabout" or highway == "motorway_link" or highway == "motorway" then
way.direction = Way.oneway
end
end
-- Override speed settings if explicit forward/backward maxspeeds are given
if maxspeed_forward ~= nil and maxspeed_forward > 0 then
if Way.bidirectional == way.direction then
way.backward_speed = way.speed
end
way.speed = maxspeed_forward
end
if maxspeed_backward ~= nil and maxspeed_backward > 0 then
way.backward_speed = maxspeed_backward
end
-- Override general direction settings of there is a specific one for our mode of travel
if ignore_in_grid[highway] ~= nil and ignore_in_grid[highway] then
way.ignore_in_grid = true
end
way.type = 1
return 1
end
-- These are wrappers to parse vectors of nodes and ways and thus to speed up any tracing JIT
function node_vector_function(vector)
for v in vector.nodes do
node_function(v)
end
end
|
-- Begin of globals
require("lib/access")
barrier_whitelist = { ["cattle_grid"] = true, ["border_control"] = true, ["toll_booth"] = true, ["sally_port"] = true, ["gate"] = true, ["no"] = true, ["entrance"] = true}
access_tag_whitelist = { ["yes"] = true, ["motorcar"] = true, ["motor_vehicle"] = true, ["vehicle"] = true, ["permissive"] = true, ["designated"] = true }
access_tag_blacklist = { ["no"] = true, ["private"] = true, ["agricultural"] = true, ["forestry"] = true }
access_tag_restricted = { ["destination"] = true, ["delivery"] = true }
access_tags = { "motorcar", "motor_vehicle", "vehicle" }
access_tags_hierachy = { "motorcar", "motor_vehicle", "vehicle", "access" }
service_tag_restricted = { ["parking_aisle"] = true }
ignore_in_grid = { ["ferry"] = true }
restriction_exception_tags = { "motorcar", "motor_vehicle", "vehicle" }
speed_profile = {
["motorway"] = 90,
["motorway_link"] = 75,
["trunk"] = 85,
["trunk_link"] = 70,
["primary"] = 65,
["primary_link"] = 60,
["secondary"] = 55,
["secondary_link"] = 50,
["tertiary"] = 40,
["tertiary_link"] = 30,
["unclassified"] = 25,
["residential"] = 25,
["living_street"] = 10,
["service"] = 15,
-- ["track"] = 5,
["ferry"] = 5,
["shuttle_train"] = 10,
["default"] = 50
}
take_minimum_of_speeds = false
obey_oneway = true
obey_bollards = true
use_restrictions = true
ignore_areas = true -- future feature
traffic_signal_penalty = 2
u_turn_penalty = 20
-- End of globals
function get_exceptions(vector)
for i,v in ipairs(restriction_exception_tags) do
vector:Add(v)
end
end
local function parse_maxspeed(source)
if source == nil then
return 0
end
local n = tonumber(source:match("%d*"))
if n == nil then
n = 0
end
if string.match(source, "mph") or string.match(source, "mp/h") then
n = (n*1609)/1000;
end
return math.abs(n)
end
function node_function (node)
local barrier = node.tags:Find ("barrier")
local access = Access.find_access_tag(node, access_tags_hierachy)
local traffic_signal = node.tags:Find("highway")
--flag node if it carries a traffic light
if traffic_signal == "traffic_signals" then
node.traffic_light = true;
end
-- parse access and barrier tags
if access and access ~= "" then
if access_tag_blacklist[access] then
node.bollard = true
end
elseif barrier and barrier ~= "" then
if barrier_whitelist[barrier] then
return
else
node.bollard = true
end
end
return 1
end
function way_function (way)
-- we dont route over areas
local area = way.tags:Find("area")
if ignore_areas and ("yes" == area) then
return 0
end
-- check if oneway tag is unsupported
local oneway = way.tags:Find("oneway")
if "reversible" == oneway then
return 0
end
-- Check if we are allowed to access the way
local access = Access.find_access_tag(way, access_tags_hierachy)
if access_tag_blacklist[access] then
return 0
end
-- Second, parse the way according to these properties
local highway = way.tags:Find("highway")
local name = way.tags:Find("name")
local ref = way.tags:Find("ref")
local junction = way.tags:Find("junction")
local route = way.tags:Find("route")
local maxspeed = parse_maxspeed(way.tags:Find ( "maxspeed") )
local maxspeed_forward = parse_maxspeed(way.tags:Find( "maxspeed:forward"))
local maxspeed_backward = parse_maxspeed(way.tags:Find( "maxspeed:backward"))
local barrier = way.tags:Find("barrier")
local cycleway = way.tags:Find("cycleway")
local duration = way.tags:Find("duration")
local service = way.tags:Find("service")
-- Set the name that will be used for instructions
if "" ~= ref then
way.name = ref
elseif "" ~= name then
way.name = name
-- else
-- way.name = highway -- if no name exists, use way type
end
if "roundabout" == junction then
way.roundabout = true;
end
-- Handling ferries and piers
if (speed_profile[route] ~= nil and speed_profile[route] > 0) then
if durationIsValid(duration) then
way.duration = math.max( parseDuration(duration), 1 );
end
way.direction = Way.bidirectional
if speed_profile[route] ~= nil then
highway = route;
end
if tonumber(way.duration) < 0 then
way.speed = speed_profile[highway]
end
end
-- Set the avg speed on the way if it is accessible by road class
if (speed_profile[highway] ~= nil and way.speed == -1 ) then
if maxspeed > speed_profile[highway] then
way.speed = maxspeed
else
if 0 == maxspeed then
maxspeed = math.huge
end
way.speed = math.min(speed_profile[highway], maxspeed)
end
end
-- Set the avg speed on ways that are marked accessible
if "" ~= highway and access_tag_whitelist[access] and way.speed == -1 then
if 0 == maxspeed then
maxspeed = math.huge
end
way.speed = math.min(speed_profile["default"], maxspeed)
end
-- Set access restriction flag if access is allowed under certain restrictions only
if access ~= "" and access_tag_restricted[access] then
way.is_access_restricted = true
end
-- Set access restriction flag if service is allowed under certain restrictions only
if service ~= "" and service_tag_restricted[service] then
way.is_access_restricted = true
end
-- Set direction according to tags on way
way.direction = Way.bidirectional
if obey_oneway then
if oneway == "-1" then
way.direction = Way.opposite
elseif oneway == "yes" or
oneway == "1" or
oneway == "true" or
junction == "roundabout" or
(highway == "motorway_link" and oneway ~="no") or
(highway == "motorway" and oneway ~= "no")
then
way.direction = Way.oneway
end
end
-- Override speed settings if explicit forward/backward maxspeeds are given
if maxspeed_forward ~= nil and maxspeed_forward > 0 then
if Way.bidirectional == way.direction then
way.backward_speed = way.speed
end
way.speed = maxspeed_forward
end
if maxspeed_backward ~= nil and maxspeed_backward > 0 then
way.backward_speed = maxspeed_backward
end
-- Override general direction settings of there is a specific one for our mode of travel
if ignore_in_grid[highway] ~= nil and ignore_in_grid[highway] then
way.ignore_in_grid = true
end
way.type = 1
return 1
end
-- These are wrappers to parse vectors of nodes and ways and thus to speed up any tracing JIT
function node_vector_function(vector)
for v in vector.nodes do
node_function(v)
end
end
|
fixes #659
|
fixes #659
|
Lua
|
bsd-2-clause
|
raymond0/osrm-backend,jpizarrom/osrm-backend,deniskoronchik/osrm-backend,yuryleb/osrm-backend,oxidase/osrm-backend,atsuyim/osrm-backend,Conggge/osrm-backend,alex85k/Project-OSRM,oxidase/osrm-backend,neilbu/osrm-backend,antoinegiret/osrm-backend,Carsten64/OSRM-aux-git,beemogmbh/osrm-backend,deniskoronchik/osrm-backend,arnekaiser/osrm-backend,neilbu/osrm-backend,keesklopt/matrix,bjtaylor1/osrm-backend,Carsten64/OSRM-aux-git,arnekaiser/osrm-backend,antoinegiret/osrm-geovelo,stevevance/Project-OSRM,bjtaylor1/osrm-backend,bitsteller/osrm-backend,ammeurer/osrm-backend,bitsteller/osrm-backend,felixguendling/osrm-backend,neilbu/osrm-backend,keesklopt/matrix,Project-OSRM/osrm-backend,Tristramg/osrm-backend,beemogmbh/osrm-backend,ramyaragupathy/osrm-backend,alex85k/Project-OSRM,bjtaylor1/Project-OSRM-Old,yuryleb/osrm-backend,Conggge/osrm-backend,bjtaylor1/Project-OSRM-Old,ammeurer/osrm-backend,skyborla/osrm-backend,atsuyim/osrm-backend,KnockSoftware/osrm-backend,stevevance/Project-OSRM,frodrigo/osrm-backend,Tristramg/osrm-backend,bjtaylor1/osrm-backend,KnockSoftware/osrm-backend,raymond0/osrm-backend,Carsten64/OSRM-aux-git,Project-OSRM/osrm-backend,keesklopt/matrix,duizendnegen/osrm-backend,Conggge/osrm-backend,raymond0/osrm-backend,nagyistoce/osrm-backend,ammeurer/osrm-backend,agruss/osrm-backend,tkhaxton/osrm-backend,Conggge/osrm-backend,arnekaiser/osrm-backend,agruss/osrm-backend,neilbu/osrm-backend,raymond0/osrm-backend,chaupow/osrm-backend,frodrigo/osrm-backend,beemogmbh/osrm-backend,stevevance/Project-OSRM,hydrays/osrm-backend,prembasumatary/osrm-backend,deniskoronchik/osrm-backend,bjtaylor1/Project-OSRM-Old,oxidase/osrm-backend,prembasumatary/osrm-backend,duizendnegen/osrm-backend,hydrays/osrm-backend,hydrays/osrm-backend,antoinegiret/osrm-geovelo,bjtaylor1/osrm-backend,jpizarrom/osrm-backend,tkhaxton/osrm-backend,frodrigo/osrm-backend,ramyaragupathy/osrm-backend,chaupow/osrm-backend,KnockSoftware/osrm-backend,duizendnegen/osrm-backend,ammeurer/osrm-backend,Carsten64/OSRM-aux-git,oxidase/osrm-backend,agruss/osrm-backend,yuryleb/osrm-backend,antoinegiret/osrm-backend,Tristramg/osrm-backend,skyborla/osrm-backend,Project-OSRM/osrm-backend,ammeurer/osrm-backend,KnockSoftware/osrm-backend,deniskoronchik/osrm-backend,hydrays/osrm-backend,ammeurer/osrm-backend,frodrigo/osrm-backend,nagyistoce/osrm-backend,ammeurer/osrm-backend,skyborla/osrm-backend,beemogmbh/osrm-backend,antoinegiret/osrm-geovelo,yuryleb/osrm-backend,arnekaiser/osrm-backend,prembasumatary/osrm-backend,antoinegiret/osrm-backend,alex85k/Project-OSRM,tkhaxton/osrm-backend,chaupow/osrm-backend,ramyaragupathy/osrm-backend,atsuyim/osrm-backend,stevevance/Project-OSRM,nagyistoce/osrm-backend,felixguendling/osrm-backend,keesklopt/matrix,bjtaylor1/Project-OSRM-Old,Project-OSRM/osrm-backend,duizendnegen/osrm-backend,bitsteller/osrm-backend,jpizarrom/osrm-backend,felixguendling/osrm-backend
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.