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
ca784e3fbdaacf00b740da9106618458f4f92c4e
share/lua/util/content_type.lua
share/lua/util/content_type.lua
-- libquvi-scripts -- Copyright (C) 2010 Toni Gundogdu <legatvs@gmail.com> -- -- 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 -- -- Parse file suffix (extension) from content-type string. function suffix_from_contenttype(ctype) -- Ideally, we'd parse these from /etc/mime-types. -- In reality, we need a more cross-platform solution. if ctype:find("text/html") then error('content-type cannot be "' ..ctype.. '" for a video. ' ..'The script for this website is either buggy or ' ..'incomplete.') end local _,_,s = ctype:find("/(.-)$") s = s or error ("no match: content type") s = s:gsub("^x%-","") if s:find("octet") or s:find("swf") or s:find("flash") or s:find("plain") then s = "flv" end return s end -- vim: set ts=4 sw=4 tw=72 expandtab:
-- libquvi-scripts -- Copyright (C) 2010 Toni Gundogdu <legatvs@gmail.com> -- -- 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 -- -- Parse file suffix (extension) from content-type string. function suffix_from_contenttype(ctype) -- Ideally, we'd parse these from /etc/mime-types. -- In reality, we need a more cross-platform solution. if ctype:find("text/html") then error('content-type cannot be "' ..ctype.. '" for a video. ' ..'The script for this website is either buggy or ' ..'incomplete.') end if ctype:find("audio/mpeg") then return "mp3" end local _,_,s = ctype:find("/(.-)$") s = s or error ("no match: content type") s = s:gsub("^x%-","") if s:find("octet") or s:find("swf") or s:find("flash") or s:find("plain") then s = "flv" end return s end -- vim: set ts=4 sw=4 tw=72 expandtab:
Add special-case suffix for audio/mpeg
Add special-case suffix for audio/mpeg It's not mpeg, it's mp3.
Lua
lgpl-2.1
DangerCove/libquvi-scripts,hadess/libquvi-scripts-iplayer,legatvs/libquvi-scripts,DangerCove/libquvi-scripts,alech/libquvi-scripts,hadess/libquvi-scripts-iplayer,alech/libquvi-scripts,legatvs/libquvi-scripts
d25ab62379f1c9b72cca6ea787e3a37a17fa9b6d
deps/coro-fs.lua
deps/coro-fs.lua
--[[lit-meta name = "creationix/coro-fs" version = "2.2.3" homepage = "https://github.com/luvit/lit/blob/master/deps/coro-fs.lua" description = "A coro style interface to the filesystem." tags = {"coro", "fs"} license = "MIT" dependencies = { "creationix/pathjoin@2.0.0" } author = { name = "Tim Caswell" } contributors = {"Tim Caswell", "Alex Iverson"} ]] local uv = require('uv') local fs = {} local pathJoin = require('pathjoin').pathJoin local function noop() end local function makeCallback() local thread = coroutine.running() return function (err, value, ...) if err then assert(coroutine.resume(thread, nil, err)) else assert(coroutine.resume(thread, value == nil and true or value, ...)) end end end function fs.mkdir(path, mode) uv.fs_mkdir(path, mode or 511, makeCallback()) return coroutine.yield() end function fs.open(path, flags, mode) uv.fs_open(path, flags or "r", mode or 438, makeCallback()) return coroutine.yield() end function fs.unlink(path) uv.fs_unlink(path, makeCallback()) return coroutine.yield() end function fs.stat(path) uv.fs_stat(path, makeCallback()) return coroutine.yield() end function fs.lstat(path) uv.fs_lstat(path, makeCallback()) return coroutine.yield() end function fs.symlink(target, path) uv.fs_symlink(target, path, makeCallback()) return coroutine.yield() end function fs.readlink(path) uv.fs_readlink(path, makeCallback()) return coroutine.yield() end function fs.fstat(fd) uv.fs_fstat(fd, makeCallback()) return coroutine.yield() end function fs.chmod(fd, path) uv.fs_chmod(fd, path, makeCallback()) return coroutine.yield() end function fs.fchmod(fd, mode) uv.fs_fchmod(fd, mode, makeCallback()) return coroutine.yield() end function fs.read(fd, length, offset) uv.fs_read(fd, length or 1024*48, offset or -1, makeCallback()) return coroutine.yield() end function fs.write(fd, data, offset) uv.fs_write(fd, data, offset or -1, makeCallback()) return coroutine.yield() end function fs.close(fd) uv.fs_close(fd, makeCallback()) return coroutine.yield() end function fs.access(path, flags) uv.fs_access(path, flags or "", makeCallback()) return coroutine.yield() end function fs.rename(path, newPath) uv.fs_rename(path, newPath, makeCallback()) return coroutine.yield() end function fs.rmdir(path) uv.fs_rmdir(path, makeCallback()) return coroutine.yield() end function fs.rmrf(path) local success, err success, err = fs.rmdir(path) if success then return success end if err:match("^ENOTDIR:") then return fs.unlink(path) end if not err:match("^ENOTEMPTY:") then return success, err end for entry in assert(fs.scandir(path)) do local subPath = pathJoin(path, entry.name) if entry.type == "directory" then success, err = fs.rmrf(pathJoin(path, entry.name)) else success, err = fs.unlink(subPath) end if not success then return success, err end end return fs.rmdir(path) end function fs.scandir(path) uv.fs_scandir(path, makeCallback()) local req, err = coroutine.yield() if not req then return nil, err end return function () local name, typ = uv.fs_scandir_next(req) if not name then return name, typ end if type(name) == "table" then return name end return { name = name, type = typ } end end function fs.readFile(path) local fd, stat, data, err fd, err = fs.open(path) if err then return nil, err end stat, err = fs.fstat(fd) if stat then --special case files on virtual filesystem if stat.size == 0 and stat.birthtime.sec == 0 and stat.birthtime.nsec == 0 then -- handle magic files the kernel generates as requested. -- hopefully the heuristic works everywhere local buffs = {} local offs = 0 local size = 1024 * 48 repeat data, err = fs.read(fd, size, offs) table.insert(buffs, data or "") until err or #data < size return table.concat(buffs), err else -- normal case for normal files. data, err = fs.read(fd, stat.size) end end uv.fs_close(fd, noop) return data, err end function fs.writeFile(path, data, mkdir) local fd, success, err fd, err = fs.open(path, "w") if err then if mkdir and string.match(err, "^ENOENT:") then success, err = fs.mkdirp(pathJoin(path, "..")) if success then return fs.writeFile(path, data) end end return nil, err end success, err = fs.write(fd, data) uv.fs_close(fd, noop) return success, err end function fs.mkdirp(path, mode) local success, err = fs.mkdir(path, mode) if success or string.match(err, "^EEXIST") then return true end if string.match(err, "^ENOENT:") then success, err = fs.mkdirp(pathJoin(path, ".."), mode) if not success then return nil, err end return fs.mkdir(path, mode) end return nil, err end function fs.chroot(base) local chroot = { base = base, fstat = fs.fstat, fchmod = fs.fchmod, read = fs.read, write = fs.write, close = fs.close, } local function resolve(path) assert(path, "path missing") return pathJoin(base, pathJoin("./".. path)) end function chroot.mkdir(path, mode) return fs.mkdir(resolve(path), mode) end function chroot.mkdirp(path, mode) return fs.mkdirp(resolve(path), mode) end function chroot.open(path, flags, mode) return fs.open(resolve(path), flags, mode) end function chroot.unlink(path) return fs.unlink(resolve(path)) end function chroot.stat(path) return fs.stat(resolve(path)) end function chroot.lstat(path) return fs.lstat(resolve(path)) end function chroot.symlink(target, path) -- TODO: should we resolve absolute target paths or treat it as opaque data? return fs.symlink(target, resolve(path)) end function chroot.readlink(path) return fs.readlink(resolve(path)) end function chroot.chmod(path, mode) return fs.chmod(resolve(path), mode) end function chroot.access(path, flags) return fs.access(resolve(path), flags) end function chroot.rename(path, newPath) return fs.rename(resolve(path), resolve(newPath)) end function chroot.rmdir(path) return fs.rmdir(resolve(path)) end function chroot.rmrf(path) return fs.rmrf(resolve(path)) end function chroot.scandir(path, iter) return fs.scandir(resolve(path), iter) end function chroot.readFile(path) return fs.readFile(resolve(path)) end function chroot.writeFile(path, data, mkdir) return fs.writeFile(resolve(path), data, mkdir) end return chroot end return fs
--[[lit-meta name = "creationix/coro-fs" version = "2.2.3" homepage = "https://github.com/luvit/lit/blob/master/deps/coro-fs.lua" description = "A coro style interface to the filesystem." tags = {"coro", "fs"} license = "MIT" dependencies = { "creationix/pathjoin@2.0.0" } author = { name = "Tim Caswell" } contributors = {"Tim Caswell", "Alex Iverson"} ]] local uv = require('uv') local fs = {} local pathJoin = require('pathjoin').pathJoin local function noop() end local function makeCallback() local thread = coroutine.running() return function (err, value, ...) if err then assert(coroutine.resume(thread, nil, err)) else assert(coroutine.resume(thread, value == nil and true or value, ...)) end end end function fs.mkdir(path, mode) uv.fs_mkdir(path, mode or 511, makeCallback()) return coroutine.yield() end function fs.open(path, flags, mode) uv.fs_open(path, flags or "r", mode or 438, makeCallback()) return coroutine.yield() end function fs.unlink(path) uv.fs_unlink(path, makeCallback()) return coroutine.yield() end function fs.stat(path) uv.fs_stat(path, makeCallback()) return coroutine.yield() end function fs.lstat(path) uv.fs_lstat(path, makeCallback()) return coroutine.yield() end function fs.symlink(target, path) uv.fs_symlink(target, path, makeCallback()) return coroutine.yield() end function fs.readlink(path) uv.fs_readlink(path, makeCallback()) return coroutine.yield() end function fs.fstat(fd) uv.fs_fstat(fd, makeCallback()) return coroutine.yield() end function fs.chmod(fd, path) uv.fs_chmod(fd, path, makeCallback()) return coroutine.yield() end function fs.fchmod(fd, mode) uv.fs_fchmod(fd, mode, makeCallback()) return coroutine.yield() end function fs.read(fd, length, offset) uv.fs_read(fd, length or 1024*48, offset or -1, makeCallback()) return coroutine.yield() end function fs.write(fd, data, offset) uv.fs_write(fd, data, offset or -1, makeCallback()) return coroutine.yield() end function fs.close(fd) uv.fs_close(fd, makeCallback()) return coroutine.yield() end function fs.access(path, flags) uv.fs_access(path, flags or "", makeCallback()) return coroutine.yield() end function fs.rename(path, newPath) uv.fs_rename(path, newPath, makeCallback()) return coroutine.yield() end function fs.rmdir(path) uv.fs_rmdir(path, makeCallback()) return coroutine.yield() end function fs.rmrf(path) local success, err success, err = fs.rmdir(path) if success then return success end if err:match("^ENOTDIR:") then return fs.unlink(path) end if not err:match("^ENOTEMPTY:") then return success, err end for entry in assert(fs.scandir(path)) do local subPath = pathJoin(path, entry.name) if entry.type == "directory" then success, err = fs.rmrf(pathJoin(path, entry.name)) else success, err = fs.unlink(subPath) end if not success then return success, err end end return fs.rmdir(path) end function fs.scandir(path) uv.fs_scandir(path, makeCallback()) local req, err = coroutine.yield() if not req then return nil, err end return function () local name, typ = uv.fs_scandir_next(req) if not name then return name, typ end if type(name) == "table" then return name end return { name = name, type = typ } end end function fs.readFile(path) local fd, stat, data, err fd, err = fs.open(path) if err then return nil, err end stat, err = fs.fstat(fd) if stat then --special case files on virtual filesystem if stat.size == 0 and stat.birthtime.sec == 0 and stat.birthtime.nsec == 0 then -- handle magic files the kernel generates as requested. -- hopefully the heuristic works everywhere local buffs = {} local offs = 0 local size = 1024 * 48 repeat data, err = fs.read(fd, size, offs) table.insert(buffs, data) offs = offs + (data and #data or 0) until err or #data < size if not err then data = table.concat(buffs) end else -- normal case for normal files. data, err = fs.read(fd, stat.size) end end uv.fs_close(fd, noop) return data, err end function fs.writeFile(path, data, mkdir) local fd, success, err fd, err = fs.open(path, "w") if err then if mkdir and string.match(err, "^ENOENT:") then success, err = fs.mkdirp(pathJoin(path, "..")) if success then return fs.writeFile(path, data) end end return nil, err end success, err = fs.write(fd, data) uv.fs_close(fd, noop) return success, err end function fs.mkdirp(path, mode) local success, err = fs.mkdir(path, mode) if success or string.match(err, "^EEXIST") then return true end if string.match(err, "^ENOENT:") then success, err = fs.mkdirp(pathJoin(path, ".."), mode) if not success then return nil, err end return fs.mkdir(path, mode) end return nil, err end function fs.chroot(base) local chroot = { base = base, fstat = fs.fstat, fchmod = fs.fchmod, read = fs.read, write = fs.write, close = fs.close, } local function resolve(path) assert(path, "path missing") return pathJoin(base, pathJoin("./".. path)) end function chroot.mkdir(path, mode) return fs.mkdir(resolve(path), mode) end function chroot.mkdirp(path, mode) return fs.mkdirp(resolve(path), mode) end function chroot.open(path, flags, mode) return fs.open(resolve(path), flags, mode) end function chroot.unlink(path) return fs.unlink(resolve(path)) end function chroot.stat(path) return fs.stat(resolve(path)) end function chroot.lstat(path) return fs.lstat(resolve(path)) end function chroot.symlink(target, path) -- TODO: should we resolve absolute target paths or treat it as opaque data? return fs.symlink(target, resolve(path)) end function chroot.readlink(path) return fs.readlink(resolve(path)) end function chroot.chmod(path, mode) return fs.chmod(resolve(path), mode) end function chroot.access(path, flags) return fs.access(resolve(path), flags) end function chroot.rename(path, newPath) return fs.rename(resolve(path), resolve(newPath)) end function chroot.rmdir(path) return fs.rmdir(resolve(path)) end function chroot.rmrf(path) return fs.rmrf(resolve(path)) end function chroot.scandir(path, iter) return fs.scandir(resolve(path), iter) end function chroot.readFile(path) return fs.readFile(resolve(path)) end function chroot.writeFile(path, data, mkdir) return fs.writeFile(resolve(path), data, mkdir) end return chroot end return fs
fix bugs reading large virtual files in coro-fs.readFile.
fix bugs reading large virtual files in coro-fs.readFile.
Lua
apache-2.0
zhaozg/lit,luvit/lit
586d78c0c115be560c15b18aa0f65e4b8966e409
Hydra/textgrid.lua
Hydra/textgrid.lua
api.doc.textgrid.textgrids = {"api.textgrid.textgrids = {}", "All currently open textgrid windows; do not mutate this at all."} api.textgrid.textgrids = {} api.textgrid.textgrids.n = 0 api.doc.textgrid.open = {"api.textgrid.open() -> textgrid", "Opens a new textgrid window."} function api.textgrid.open() local tg = api.textgrid._open() local id = api.textgrid.textgrids.n + 1 tg.__id = id api.textgrid.textgrids[id] = tg api.textgrid.textgrids.n = id return tg end api.doc.textgrid.close = {"api.textgrid:close()", "Closes the given textgrid window."} function api.textgrid:close() api.textgrid.textgrids[self.__id] = nil return self:_close() end api.doc.textgrid.livelong = {"api.textgrid:livelong()", "Prevents the textgrid from closing when your config is reloaded."} function api.textgrid:livelong() api.textgrid.textgrids[self.__id] = nil self.__id = nil end api.doc.textgrid.closeall = {"api.textgrid.closeall()", "Closes all non-protected textgrids; called automatically when user config is reloaded."} function api.textgrid.closeall() for i, tg in pairs(api.textgrid.textgrids) do if i ~= "n" and tg ~= nil then api.textgrid.textgrids[i] = tg tg:close() end end end
api.doc.textgrid.textgrids = {"api.textgrid.textgrids = {}", "All currently open textgrid windows; do not mutate this at all."} api.textgrid.textgrids = {} api.textgrid.textgrids.n = 0 api.doc.textgrid.open = {"api.textgrid.open() -> textgrid", "Opens a new textgrid window."} function api.textgrid.open() local tg = api.textgrid._open() local id = api.textgrid.textgrids.n + 1 tg.__id = id api.textgrid.textgrids[id] = tg api.textgrid.textgrids.n = id return tg end api.doc.textgrid.close = {"api.textgrid:close()", "Closes the given textgrid window."} function api.textgrid:close() api.textgrid.textgrids[self.__id] = nil return self:_close() end api.doc.textgrid.livelong = {"api.textgrid:livelong()", "Prevents the textgrid from closing when your config is reloaded."} function api.textgrid:livelong() api.textgrid.textgrids[self.__id] = nil self.__id = nil end api.doc.textgrid.closeall = {"api.textgrid.closeall()", "Closes all non-protected textgrids; called automatically when user config is reloaded."} function api.textgrid.closeall() for i, tg in pairs(api.textgrid.textgrids) do if i ~= "n" and tg ~= nil then api.textgrid.textgrids[i] = tg tg:close() end end api.textgrid.textgrids.n = 0 end
Fixing bug in api.textgrid.closeall()
Fixing bug in api.textgrid.closeall()
Lua
mit
latenitefilms/hammerspoon,kkamdooong/hammerspoon,Stimim/hammerspoon,zzamboni/hammerspoon,tmandry/hammerspoon,wvierber/hammerspoon,ocurr/hammerspoon,asmagill/hammerspoon,heptal/hammerspoon,CommandPost/CommandPost-App,asmagill/hammerspoon,nkgm/hammerspoon,chrisjbray/hammerspoon,chrisjbray/hammerspoon,cmsj/hammerspoon,nkgm/hammerspoon,nkgm/hammerspoon,bradparks/hammerspoon,cmsj/hammerspoon,peterhajas/hammerspoon,junkblocker/hammerspoon,dopcn/hammerspoon,tmandry/hammerspoon,asmagill/hammerspoon,zzamboni/hammerspoon,knl/hammerspoon,Hammerspoon/hammerspoon,emoses/hammerspoon,emoses/hammerspoon,chrisjbray/hammerspoon,asmagill/hammerspoon,lowne/hammerspoon,heptal/hammerspoon,junkblocker/hammerspoon,wvierber/hammerspoon,knl/hammerspoon,tmandry/hammerspoon,cmsj/hammerspoon,bradparks/hammerspoon,chrisjbray/hammerspoon,heptal/hammerspoon,peterhajas/hammerspoon,joehanchoi/hammerspoon,nkgm/hammerspoon,junkblocker/hammerspoon,peterhajas/hammerspoon,dopcn/hammerspoon,knu/hammerspoon,wvierber/hammerspoon,Hammerspoon/hammerspoon,Stimim/hammerspoon,emoses/hammerspoon,zzamboni/hammerspoon,kkamdooong/hammerspoon,bradparks/hammerspoon,dopcn/hammerspoon,kkamdooong/hammerspoon,ocurr/hammerspoon,hypebeast/hammerspoon,emoses/hammerspoon,lowne/hammerspoon,knu/hammerspoon,dopcn/hammerspoon,chrisjbray/hammerspoon,ocurr/hammerspoon,emoses/hammerspoon,Hammerspoon/hammerspoon,latenitefilms/hammerspoon,TimVonsee/hammerspoon,joehanchoi/hammerspoon,Hammerspoon/hammerspoon,lowne/hammerspoon,nkgm/hammerspoon,TimVonsee/hammerspoon,wsmith323/hammerspoon,Stimim/hammerspoon,TimVonsee/hammerspoon,kkamdooong/hammerspoon,latenitefilms/hammerspoon,cmsj/hammerspoon,wsmith323/hammerspoon,chrisjbray/hammerspoon,heptal/hammerspoon,knu/hammerspoon,Habbie/hammerspoon,peterhajas/hammerspoon,asmagill/hammerspoon,wvierber/hammerspoon,Hammerspoon/hammerspoon,hypebeast/hammerspoon,knu/hammerspoon,TimVonsee/hammerspoon,Habbie/hammerspoon,latenitefilms/hammerspoon,lowne/hammerspoon,latenitefilms/hammerspoon,knu/hammerspoon,Habbie/hammerspoon,CommandPost/CommandPost-App,knu/hammerspoon,dopcn/hammerspoon,CommandPost/CommandPost-App,cmsj/hammerspoon,Habbie/hammerspoon,ocurr/hammerspoon,lowne/hammerspoon,wsmith323/hammerspoon,hypebeast/hammerspoon,bradparks/hammerspoon,zzamboni/hammerspoon,joehanchoi/hammerspoon,Habbie/hammerspoon,trishume/hammerspoon,cmsj/hammerspoon,joehanchoi/hammerspoon,zzamboni/hammerspoon,hypebeast/hammerspoon,knl/hammerspoon,zzamboni/hammerspoon,wsmith323/hammerspoon,CommandPost/CommandPost-App,heptal/hammerspoon,hypebeast/hammerspoon,Stimim/hammerspoon,CommandPost/CommandPost-App,wsmith323/hammerspoon,peterhajas/hammerspoon,latenitefilms/hammerspoon,Stimim/hammerspoon,trishume/hammerspoon,CommandPost/CommandPost-App,trishume/hammerspoon,junkblocker/hammerspoon,junkblocker/hammerspoon,knl/hammerspoon,bradparks/hammerspoon,kkamdooong/hammerspoon,joehanchoi/hammerspoon,Hammerspoon/hammerspoon,Habbie/hammerspoon,ocurr/hammerspoon,asmagill/hammerspoon,TimVonsee/hammerspoon,wvierber/hammerspoon,knl/hammerspoon
8095712d81e5e5c362306ce9d9e8583c78ee65d9
Libs/Core/premake5.lua
Libs/Core/premake5.lua
project "Core" kind "StaticLib" language "C++" targetdir "../../Bin/%{cfg.buildcfg}" includedirs { "Include", "../../3rdParty/dbghelp/include" } links { "Test", "GoogleTest" } files { "../FlourishConfig.h", "Include/**.h", "Include/**.inl", "Source/**.c", "Source/**.cpp", -- Add the Premake bat files for easy project rebuilding (Use -- http://stackoverflow.com/questions/5605885/how-to-run-a-bat-from-inside-the-ide to launch from IDE) "Premake/*" } -- Link to the correct dbghelp.lib on windows debug filter {"system:windows", "configurations:Debug", "architecture:x32"} links { "../../3rdParty/dbghelp/lib/x86/dbghelp" } filter {"system:windows", "configurations:Debug", "architecture:x64"} links { "../../3rdParty/dbghelp/lib/x64/dbghelp" } filter {"system:macosx"} linkoptions { "-std=c++11", "-stdlib=libc++" } buildoptions { "-std=c++11", "-stdlib=libc++" }
project "Core" kind "StaticLib" language "C++" targetdir "../../Bin/%{cfg.buildcfg}" includedirs { "Include", "../../3rdParty/dbghelp/include" } links { "Test", "GoogleTest" } files { "../FlourishConfig.h", "Include/**.h", "Include/**.inl", "Source/**.c", "Source/**.cpp", -- Add the Premake bat files for easy project rebuilding (Use -- http://stackoverflow.com/questions/5605885/how-to-run-a-bat-from-inside-the-ide to launch from IDE) "Premake/*" } -- Link to the correct dbghelp.lib on windows debug filter {"system:windows", "configurations:Debug", "architecture:x32"} libdirs { "../../3rdParty/dbghelp/lib/x86/" } links { "DbgHelp" } filter {"system:windows", "configurations:Debug", "architecture:x64"} libdirs { "../../3rdParty/dbghelp/lib/x64/" } links { "DbgHelp" } filter {"system:macosx"} linkoptions { "-std=c++11", "-stdlib=libc++" } buildoptions { "-std=c++11", "-stdlib=libc++" }
Fixed Issues with lib paths in cmake projects when using relative paths to libraries
Fixed Issues with lib paths in cmake projects when using relative paths to libraries
Lua
mit
Flourish-Team/Flourish,Flourish-Team/Flourish,Flourish-Team/Flourish,Flourish-Team/Flourish,Flourish-Team/Flourish
56fc37892f5e3bdf37751cb7156062d13b0ea237
src/main/resources/std/math.lua
src/main/resources/std/math.lua
-- Copyright (c) 2018. tangzx(love.tangzx@qq.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); you may not -- use this file except in compliance with the License. You may obtain a copy of -- the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -- WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -- License for the specific language governing permissions and limitations under -- the License. math = {} --- --- Returns the absolute value of `x`. (integer/float) ---@param x number ---@return number function math.abs(x) return 0 end --- --- Returns the arc cosine of `x` (in radians). ---@param x number ---@return number function math.acos(x) return 0 end --- --- Returns the arc sine of `x` (in radians). ---@param x number ---@return number function math.asin(x) return 0 end --- --- Returns the arc tangent of `y/x` (in radians), but uses the signs of both --- parameters to find the quadrant of the result. (It also handles correctly --- the case of `x` being zero.) --- --- The default value for `x` is 1, so that the call `math.atan(y)`` returns the --- arc tangent of `y`. ---@param y number ---@param optional x number ---@return number function math.atan(y, x) return 0 end --- --- Returns the smallest integer larger than or equal to `x`. ---@param x number ---@return number function math.ceil(x) return 0 end --- --- Returns the cosine of `x` (assumed to be in radians). ---@param x number ---@return number function math.cos(x) return 0 end --- --- Converts the angle `x` from radians to degrees. ---@param x number ---@return number function math.deg(x) return 0 end --- --- Returns the value *e^x* (where e is the base of natural logarithms). ---@param x number ---@return number function math.exp(x) end --- --- Returns the largest integer smaller than or equal to `x`. ---@param x number ---@return number function math.floor(x) end --- --- Returns the remainder of the division of `x` by `y` that rounds the --- quotient towards zero. (integer/float) ---@param x number ---@param y number ---@return number function math.fmod(x, y) end --- --- The float value `HUGE_VAL`, a value larger than any other numeric value. math.huge = "" --- --- Returns the logarithm of `x` in the given base. The default for `base` is --- *e* (so that the function returns the natural logarithm of `x`). ---@param x number ---@param optional base number ---@return number function math.log(x, base) end --- --- Returns the argument with the maximum value, according to the Lua operator --- `<`. (integer/float) ---@param x number ---@return number function math.max(x, ...) end --- --- An integer with the maximum value for an integer. math.maxinteger = "" --- --- Returns the argument with the minimum value, according to the Lua operator --- `<`. (integer/float) ---@param x number ---@return number function math.min(x, ...) end --- --- An integer with the minimum value for an integer. math.mininteger = "" --- --- Returns the integral part of `x` and the fractional part of `x`. Its second --- result is always a float. ---@param x number ---@return number|number function math.modf(x) end --- --- The value of π. math.pi = 3.1415 --- --- Converts the angle `x` from degrees to radians. ---@param x number ---@return number function math.rad(x) end --- --- When called without arguments, returns a pseudo-random float with uniform --- distribution in the range *[0,1)*. When called with two integers `m` and --- `n`, `math.random` returns a pseudo-random integer with uniform distribution --- in the range *[m, n]*. The call `math.random(n)` is equivalent to `math --- .random`(1,n). ---@overload fun():number ---@param optional m number ---@param optional n number ---@return number function math.random(m, n) end --- --- Sets `x` as the "seed" for the pseudo-random generator: equal seeds --- produce equal sequences of numbers. ---@param x number function math.randomseed(x) end --- --- Returns the sine of `x` (assumed to be in radians). ---@param x number ---@return number function math.sin(x) return 0 end --- --- Returns the square root of `x`. (You can also use the expression `x^0.5` to --- compute this value.) ---@param x number ---@return number function math.sqrt(x) return 0 end --- --- Returns the tangent of `x` (assumed to be in radians). ---@param x number ---@return number function math.tan(x) return 0 end --- --- If the value `x` is convertible to an integer, returns that integer. --- Otherwise, returns `nil`. ---@param x number ---@return number function math.tointeger(x) end --- --- Returns "`integer`" if `x` is an integer, "`float`" if it is a float, or --- **nil** if `x` is not a number. ---@param x number ---@return number function math.type(x) end --- --- Returns a boolean, true if and only if integer `m` is below integer `n` when --- they are compared as unsigned integers. ---@param m number ---@param n number ---@return boolean function math.ult(m, n) end return math
-- Copyright (c) 2018. tangzx(love.tangzx@qq.com) -- -- Licensed under the Apache License, Version 2.0 (the "License"); you may not -- use this file except in compliance with the License. You may obtain a copy of -- the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -- WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -- License for the specific language governing permissions and limitations under -- the License. math = {} --- --- Returns the absolute value of `x`. (integer/float) ---@param x number ---@return number function math.abs(x) return 0 end --- --- Returns the arc cosine of `x` (in radians). ---@param x number ---@return number function math.acos(x) return 0 end --- --- Returns the arc sine of `x` (in radians). ---@param x number ---@return number function math.asin(x) return 0 end --- --- Returns the arc tangent of `y/x` (in radians), but uses the signs of both --- parameters to find the quadrant of the result. (It also handles correctly --- the case of `x` being zero.) --- --- The default value for `x` is 1, so that the call `math.atan(y)`` returns the --- arc tangent of `y`. ---@overload fun(y:number):number ---@param y number ---@param x number ---@return number function math.atan(y, x) return 0 end --- --- Returns the smallest integer larger than or equal to `x`. ---@param x number ---@return number function math.ceil(x) return 0 end --- --- Returns the cosine of `x` (assumed to be in radians). ---@param x number ---@return number function math.cos(x) return 0 end --- --- Converts the angle `x` from radians to degrees. ---@param x number ---@return number function math.deg(x) return 0 end --- --- Returns the value *e^x* (where e is the base of natural logarithms). ---@param x number ---@return number function math.exp(x) end --- --- Returns the largest integer smaller than or equal to `x`. ---@param x number ---@return number function math.floor(x) end --- --- Returns the remainder of the division of `x` by `y` that rounds the --- quotient towards zero. (integer/float) ---@param x number ---@param y number ---@return number function math.fmod(x, y) end --- --- The float value `HUGE_VAL`, a value larger than any other numeric value. math.huge = "" --- --- Returns the logarithm of `x` in the given base. The default for `base` is --- *e* (so that the function returns the natural logarithm of `x`). ---@overload fun(x:number):number ---@param x number ---@param base number ---@return number function math.log(x, base) end --- --- Returns the argument with the maximum value, according to the Lua operator --- `<`. (integer/float) ---@param x number ---@return number function math.max(x, ...) end --- --- An integer with the maximum value for an integer. math.maxinteger = "" --- --- Returns the argument with the minimum value, according to the Lua operator --- `<`. (integer/float) ---@param x number ---@return number function math.min(x, ...) end --- --- An integer with the minimum value for an integer. math.mininteger = "" --- --- Returns the integral part of `x` and the fractional part of `x`. Its second --- result is always a float. ---@param x number ---@return number|number function math.modf(x) end --- --- The value of π. math.pi = 3.1415 --- --- Converts the angle `x` from degrees to radians. ---@param x number ---@return number function math.rad(x) end --- --- When called without arguments, returns a pseudo-random float with uniform --- distribution in the range *[0,1)*. When called with two integers `m` and --- `n`, `math.random` returns a pseudo-random integer with uniform distribution --- in the range *[m, n]*. The call `math.random(n)` is equivalent to `math --- .random`(1,n). ---@overload fun():number ---@param m number ---@param n number ---@return number function math.random(m, n) end --- --- Sets `x` as the "seed" for the pseudo-random generator: equal seeds --- produce equal sequences of numbers. ---@param x number function math.randomseed(x) end --- --- Returns the sine of `x` (assumed to be in radians). ---@param x number ---@return number function math.sin(x) return 0 end --- --- Returns the square root of `x`. (You can also use the expression `x^0.5` to --- compute this value.) ---@param x number ---@return number function math.sqrt(x) return 0 end --- --- Returns the tangent of `x` (assumed to be in radians). ---@param x number ---@return number function math.tan(x) return 0 end --- --- If the value `x` is convertible to an integer, returns that integer. --- Otherwise, returns `nil`. ---@param x number ---@return number function math.tointeger(x) end --- --- Returns "`integer`" if `x` is an integer, "`float`" if it is a float, or --- **nil** if `x` is not a number. ---@param x number ---@return number function math.type(x) end --- --- Returns a boolean, true if and only if integer `m` is below integer `n` when --- they are compared as unsigned integers. ---@param m number ---@param n number ---@return boolean function math.ult(m, n) end return math
fix optional params
fix optional params
Lua
apache-2.0
EmmyLua/IntelliJ-EmmyLua,EmmyLua/IntelliJ-EmmyLua,tangzx/IntelliJ-EmmyLua,EmmyLua/IntelliJ-EmmyLua,tangzx/IntelliJ-EmmyLua,EmmyLua/IntelliJ-EmmyLua,tangzx/IntelliJ-EmmyLua,tangzx/IntelliJ-EmmyLua
f08379327a9d41adee7d32cbf99a24d820ce9c96
ffi/freetype.lua
ffi/freetype.lua
--[[ Freetype library interface (text rendering) --]] local ffi = require("ffi") local Blitbuffer = require("ffi/blitbuffer") -- the header definitions require("ffi/freetype_h") local ft2 = ffi.load("libs/libfreetype.so.6") local freetypelib = ffi.new("FT_Library[1]") assert(ft2.FT_Init_FreeType(freetypelib) == 0, "Couldn't initialize Freetype!") freetypelib = freetypelib[0] local FT = {} -- metatable for BlitBuffer objects: local FTFace_mt = {__index={}} function FTFace_mt.__index:checkGlyph(char) if ft2.FT_Get_Char_Index(self, char) == 0 then return 0 else return 1 end end function FTFace_mt.__index:renderGlyph(char, background, foreground) assert(ft2.FT_Load_Char(self, char, ft2.FT_LOAD_RENDER) == 0, "freetype error") local bitmap = self.glyph.bitmap local glyph = { bb = Blitbuffer.new(bitmap.width, bitmap.rows), l = self.glyph.bitmap_left, t = self.glyph.bitmap_top, r = tonumber(self.glyph.metrics.horiAdvance / 64), ax = tonumber(self.glyph.advance.x / 64), ay = tonumber(self.glyph.advance.y / 64) } for y = 0, bitmap.rows-1 do for x = 0, bitmap.width-1 do glyph.bb:setPixel(x, y, bit.rshift(bitmap.buffer[y * bitmap.pitch + x], 4)) end end return glyph end function FTFace_mt.__index:hasKerning() if bit.band(self.face_flags, ft2.FT_FACE_FLAG_KERNING) ~= 0 then return 1 else return 0 end end function FTFace_mt.__index:getKerning(leftcharcode, rightcharcode) local kerning = ffi.new("FT_Vector") assert(ft2.FT_Get_Kerning(self, leftcharcode, rightcharcode, ft2.FT_KERNING_DEFAULT, kerning) == 0, "freetype error when getting kerning.") return tonumber(kerning.x / 64) end function FTFace_mt.__index:getHeightAndAscender() local y_scale = self.size.metrics.y_ppem / self.units_per_EM return self.height * y_scale, self.ascender * y_scale end function FTFace_mt.__index:done() assert(ft2.FT_Done_Face(self) == 0, "freetype error when freeing face") end FTFace_mt.__gc = FTFace_mt.__index.done; local FTFaceType = ffi.metatype("struct FT_FaceRec_", FTFace_mt) function FT.newFace(filename, pxsize) if pxsize == nil then pxsize = 16*64 end local facept = ffi.new("FT_Face[1]") assert(ft2.FT_New_Face(freetypelib, filename, 0, facept) == 0, "freetype error") face = facept[0] err = ft2.FT_Set_Pixel_Sizes(face, 0, pxsize) if err ~= 0 then FT_Done_Face(face) error("freetype error") end if face.charmap == nil then --TODO end return face; end return FT
--[[ Freetype library interface (text rendering) --]] local ffi = require("ffi") local Blitbuffer = require("ffi/blitbuffer") -- the header definitions require("ffi/freetype_h") local ft2 = ffi.load("libs/libfreetype.so.6") local freetypelib = ffi.new("FT_Library[1]") assert(ft2.FT_Init_FreeType(freetypelib) == 0, "Couldn't initialize Freetype!") freetypelib = freetypelib[0] local FT = {} -- metatable for BlitBuffer objects: local FTFace_mt = {__index={}} function FTFace_mt.__index:checkGlyph(char) if ft2.FT_Get_Char_Index(self, char) == 0 then return 0 else return 1 end end function FTFace_mt.__index:renderGlyph(char, bgcolor, fgcolor) assert(ft2.FT_Load_Char(self, char, ft2.FT_LOAD_RENDER) == 0, "freetype error") local bitmap = self.glyph.bitmap local glyph = { bb = Blitbuffer.new(bitmap.width, bitmap.rows), l = self.glyph.bitmap_left, t = self.glyph.bitmap_top, r = tonumber(self.glyph.metrics.horiAdvance / 64), ax = tonumber(self.glyph.advance.x / 64), ay = tonumber(self.glyph.advance.y / 64) } for y = 0, bitmap.rows-1 do for x = 0, bitmap.width-1 do local pix = bitmap.buffer[y * bitmap.pitch + x] glyph.bb:setPixel(x, y, bit.rshift(0xFF * bgcolor - pix * (bgcolor - fgcolor), 4)) end end return glyph end function FTFace_mt.__index:hasKerning() if bit.band(self.face_flags, ft2.FT_FACE_FLAG_KERNING) ~= 0 then return 1 else return 0 end end function FTFace_mt.__index:getKerning(leftcharcode, rightcharcode) local kerning = ffi.new("FT_Vector") assert(ft2.FT_Get_Kerning(self, leftcharcode, rightcharcode, ft2.FT_KERNING_DEFAULT, kerning) == 0, "freetype error when getting kerning.") return tonumber(kerning.x / 64) end function FTFace_mt.__index:getHeightAndAscender() local y_scale = self.size.metrics.y_ppem / self.units_per_EM return self.height * y_scale, self.ascender * y_scale end function FTFace_mt.__index:done() assert(ft2.FT_Done_Face(self) == 0, "freetype error when freeing face") end FTFace_mt.__gc = FTFace_mt.__index.done; local FTFaceType = ffi.metatype("struct FT_FaceRec_", FTFace_mt) function FT.newFace(filename, pxsize) if pxsize == nil then pxsize = 16*64 end local facept = ffi.new("FT_Face[1]") assert(ft2.FT_New_Face(freetypelib, filename, 0, facept) == 0, "freetype error") face = facept[0] err = ft2.FT_Set_Pixel_Sizes(face, 0, pxsize) if err ~= 0 then FT_Done_Face(face) error("freetype error") end if face.charmap == nil then --TODO end return face; end return FT
fix bg- and fgcolor support in freetype ffi module
fix bg- and fgcolor support in freetype ffi module
Lua
agpl-3.0
frankyifei/koreader-base,apletnev/koreader-base,frankyifei/koreader-base,Frenzie/koreader-base,frankyifei/koreader-base,houqp/koreader-base,apletnev/koreader-base,Frenzie/koreader-base,houqp/koreader-base,Hzj-jie/koreader-base,apletnev/koreader-base,Frenzie/koreader-base,koreader/koreader-base,houqp/koreader-base,houqp/koreader-base,frankyifei/koreader-base,Hzj-jie/koreader-base,Hzj-jie/koreader-base,NiLuJe/koreader-base,Frenzie/koreader-base,Hzj-jie/koreader-base,NiLuJe/koreader-base,NiLuJe/koreader-base,NiLuJe/koreader-base,apletnev/koreader-base,koreader/koreader-base,koreader/koreader-base,koreader/koreader-base
a6e30390f384a5dd6446542436d45fd983af565b
test/lua/unit/expressions.lua
test/lua/unit/expressions.lua
-- Expressions unit tests context("Rspamd expressions", function() local rspamd_expression = require "rspamd_expression" local rspamd_mempool = require "rspamd_mempool" local _ = require "fun" local function parse_func(str) -- extract token till the first space character local token = table.join('', take_while(function(s) return s ~= ' ' end, str)) -- Return token name return token end test("Expression creation function", function() local function process_func(token, task) -- Do something using token and task end local pool = rspamd_mempool.create() local cases = { {'A & B | !C', 'A B & C ! |'} } for _,c in ipairs(cases) do local expr,err = rspamd_expression.create(c[1], {parse_func, process_func}, pool) if c[2] then assert_not_null(expr, "Cannot parse " .. c[1] ": " .. err) else assert_equal(expr:to_string(), c[2], string.format("Evaluated expr to '%s', expected: '%s'", expr:to_string(), c[2])) end end -- Expression is destroyed when the corresponding pool is destroyed pool:destroy() end) end)
-- Expressions unit tests context("Rspamd expressions", function() local rspamd_expression = require "rspamd_expression" local rspamd_mempool = require "rspamd_mempool" local rspamd_regexp = require "rspamd_regexp" local split_re = rspamd_regexp.create('/\\s+/') local function parse_func(str) -- extract token till the first space character local token = split_re:split(str)[1] -- Return token name return token end test("Expression creation function", function() local function process_func(token, task) -- Do something using token and task end local pool = rspamd_mempool.create() local cases = { {'A & B | !C', 'A B & C ! |'} } for _,c in ipairs(cases) do local expr,err = rspamd_expression.create(c[1], {parse_func, process_func}, pool) if c[2] then assert_not_nil(expr, "Cannot parse " .. c[1] ": " .. err) else assert_equal(expr:to_string(), c[2], string.format("Evaluated expr to '%s', expected: '%s'", expr:to_string(), c[2])) end end -- Expression is destroyed when the corresponding pool is destroyed pool:destroy() end) end)
Fix expressions unit test.
Fix expressions unit test.
Lua
apache-2.0
minaevmike/rspamd,amohanta/rspamd,dark-al/rspamd,AlexeySa/rspamd,AlexeySa/rspamd,amohanta/rspamd,andrejzverev/rspamd,andrejzverev/rspamd,AlexeySa/rspamd,AlexeySa/rspamd,andrejzverev/rspamd,awhitesong/rspamd,minaevmike/rspamd,awhitesong/rspamd,amohanta/rspamd,minaevmike/rspamd,minaevmike/rspamd,andrejzverev/rspamd,dark-al/rspamd,AlexeySa/rspamd,minaevmike/rspamd,minaevmike/rspamd,AlexeySa/rspamd,minaevmike/rspamd,dark-al/rspamd,andrejzverev/rspamd,AlexeySa/rspamd,amohanta/rspamd,andrejzverev/rspamd,minaevmike/rspamd,minaevmike/rspamd,amohanta/rspamd,AlexeySa/rspamd,andrejzverev/rspamd,awhitesong/rspamd,AlexeySa/rspamd,awhitesong/rspamd,dark-al/rspamd,andrejzverev/rspamd,dark-al/rspamd
f4737d7f3e244f59cf52ffc6a951cc8cb1eed89d
lua/plugins/lsp.lua
lua/plugins/lsp.lua
-- local nvim = require('nvim') local plugs = require('nvim').plugs local sys = require('sys') local executable = require('nvim').fn.executable local isdirectory = require('nvim').fn.isdirectory local nvim_set_autocmd = require('nvim').nvim_set_autocmd -- local nvim_set_command = require('nvim').nvim_set_command local ok, lsp = pcall(require, 'nvim_lsp') if not ok then return nil end local servers = { sh = { bashls = { name = 'bash-language-server'}, }, rust = { rust_analyzer = { name = 'rust_analyzer'}, }, go = { gopls = { name = 'gopls'}, }, tex = { texlab = { name = 'texlab'}, }, vim = { vimls = { name = 'vimls'}, }, dockerfile = { dockerls = { name = 'docker-langserver'}, }, lua = { sumneko_lua = { name = 'sumneko_lua', options = { settings = { Lua = { diagnostics = { globals = { 'vim', } }, }, }, }, }, }, python = { pyls = { name = 'pyls', options = { cmd = { 'pyls', '--log-file=' .. sys.tmp('pyls.log'), }, settings = { pyls = { plugins = { mccabe = { threshold = 20 }, pycodestyle = { maxLineLength = 120 }, }, }, }, }, }, }, c = { ccls = { name = 'ccls', options = { cmd = { 'ccls', '--log-file=' .. sys.tmp('ccls.log') }, init_options = { cache = { directory = sys.cache..'/ccls' }, highlight = { lsRanges = true; }, completion = { filterAndSort = true, caseSensitivity = 1, detailedLabel = false, }, }, }, }, clangd = { name = 'clangd', options = { cmd = { 'clangd', '--index', '--background-index', '--suggest-missing-includes', '--clang-tidy', }, } }, }, } local available_languages = {} for language,options in pairs(servers) do for option,server in pairs(options) do if executable(server['name']) == 1 or isdirectory(sys.home .. '/.cache/nvim/nvim_lsp/' .. server['name']) == 1 then local init = server['options'] ~= nil and server['options'] or {} lsp[option].setup(init) available_languages[#available_languages + 1] = language if language == 'c' then available_languages[#available_languages + 1] = 'cpp' available_languages[#available_languages + 1] = 'objc' available_languages[#available_languages + 1] = 'objcpp' elseif language == 'dockerfile' then available_languages[#available_languages + 1] = 'Dockerfile' elseif language == 'tex' then available_languages[#available_languages + 1] = 'bib' end break end end end nvim_set_autocmd('FileType', available_languages, 'setlocal omnifunc=v:lua.vim.lsp.omnifunc', {group = 'NvimLSP', create = true}) nvim_set_autocmd('FileType', available_languages, 'nnoremap <buffer><silent> <c-]> :lua vim.lsp.buf.definition()<CR>', {group = 'NvimLSP'}) nvim_set_autocmd('FileType', available_languages, 'nnoremap <buffer><silent> gd :lua vim.lsp.buf.declaration()<CR>', {group = 'NvimLSP'}) nvim_set_autocmd('FileType', available_languages, 'nnoremap <buffer><silent> gD :lua vim.lsp.buf.implementation()<CR>', {group = 'NvimLSP'}) nvim_set_autocmd('FileType', available_languages, 'nnoremap <buffer><silent> gr :lua vim.lsp.buf.references()<CR>', {group = 'NvimLSP'}) nvim_set_autocmd('FileType', available_languages, 'nnoremap <buffer><silent> K :lua vim.lsp.buf.hover()<CR>', {group = 'NvimLSP'}) nvim_set_autocmd( 'FileType', available_languages, "lua require'nvim'.nvim_set_command('Declaration', 'lua vim.lsp.buf.declaration()', {buffer = true, force = true})", {group = 'NvimLSP'} ) nvim_set_autocmd( 'FileType', available_languages, "lua require'nvim'.nvim_set_command('Definition', 'lua vim.lsp.buf.definition()', {buffer = true, force = true})", {group = 'NvimLSP'} ) nvim_set_autocmd( 'FileType', available_languages, "lua require'nvim'.nvim_set_command('References', 'lua vim.lsp.buf.references()', {buffer = true, force = true})", {group = 'NvimLSP'} ) nvim_set_autocmd( 'FileType', available_languages, "lua require'nvim'.nvim_set_command('Hover', 'lua vim.lsp.buf.hover()', {buffer = true, force = true})", {group = 'NvimLSP'} ) nvim_set_autocmd( 'FileType', available_languages, "autocmd CursorHold <buffer> lua vim.lsp.buf.hover()", {group = 'NvimLSP', nested = true} ) nvim_set_autocmd( 'FileType', available_languages, "lua require'nvim'.nvim_set_command('Implementation', 'lua vim.lsp.buf.implementation()', {buffer = true, force = true})", {group = 'NvimLSP'} ) nvim_set_autocmd( 'FileType', available_languages, "lua require'nvim'.nvim_set_command('Signature', 'lua vim.lsp.buf.signature_help()', {buffer = true, force = true})", {group = 'NvimLSP'} ) nvim_set_autocmd( 'FileType', available_languages, "lua require'nvim'.nvim_set_command('Type' , 'lua vim.lsp.buf.type_definition()', {buffer = true, force = true})", {group = 'NvimLSP'} ) -- Disable neomake for lsp buffers if plugs['neomake'] ~= nil then nvim_set_autocmd( 'FileType', available_languages, "call neomake#cmd#disable(b:)", {group = 'NvimLSP'} ) end do local method = 'textDocument/publishDiagnostics' local default_callback = vim.lsp.callbacks[method] vim.lsp.callbacks[method] = function(err, method, result, client_id) default_callback(err, method, result, client_id) if result and result.diagnostics then for _, v in ipairs(result.diagnostics) do v.uri = v.uri or result.uri end vim.lsp.util.set_loclist(result.diagnostics) end end end
-- local nvim = require('nvim') local plugs = require('nvim').plugs local sys = require('sys') local executable = require('nvim').fn.executable local isdirectory = require('nvim').fn.isdirectory local nvim_set_autocmd = require('nvim').nvim_set_autocmd -- local nvim_set_command = require('nvim').nvim_set_command local ok, lsp = pcall(require, 'nvim_lsp') if not ok then return nil end local servers = { sh = { bashls = { name = 'bash-language-server'}, }, rust = { rust_analyzer = { name = 'rust_analyzer'}, }, go = { gopls = { name = 'gopls'}, }, tex = { texlab = { name = 'texlab'}, }, dockerfile = { dockerls = { name = 'docker-langserver'}, }, vim = { vimls = { name = 'vimls', executable = 'vim-language-server', }, }, lua = { sumneko_lua = { name = 'sumneko_lua', options = { settings = { Lua = { diagnostics = { globals = { 'vim', } }, }, }, }, }, }, python = { pyls = { name = 'pyls', options = { cmd = { 'pyls', '--log-file=' .. sys.tmp('pyls.log'), }, settings = { pyls = { plugins = { mccabe = { threshold = 20 }, pycodestyle = { maxLineLength = 120 }, }, }, }, }, }, }, c = { ccls = { name = 'ccls', options = { cmd = { 'ccls', '--log-file=' .. sys.tmp('ccls.log') }, init_options = { cache = { directory = sys.cache..'/ccls' }, highlight = { lsRanges = true; }, completion = { filterAndSort = true, caseSensitivity = 1, detailedLabel = false, }, }, }, }, clangd = { name = 'clangd', options = { cmd = { 'clangd', '--index', '--background-index', '--suggest-missing-includes', '--clang-tidy', }, } }, }, } local available_languages = {} for language,options in pairs(servers) do for option,server in pairs(options) do local dir = isdirectory(sys.home .. '/.cache/nvim/nvim_lsp/' .. server['name']) == 1 local exec = executable(server['name']) == 1 or (server['executable'] ~= nil and executable(server['executable'])) if exec or dir then local init = server['options'] ~= nil and server['options'] or {} lsp[option].setup(init) available_languages[#available_languages + 1] = language if language == 'c' then available_languages[#available_languages + 1] = 'cpp' available_languages[#available_languages + 1] = 'objc' available_languages[#available_languages + 1] = 'objcpp' elseif language == 'dockerfile' then available_languages[#available_languages + 1] = 'Dockerfile' elseif language == 'tex' then available_languages[#available_languages + 1] = 'bib' end break end end end nvim_set_autocmd('FileType', available_languages, 'setlocal omnifunc=v:lua.vim.lsp.omnifunc', {group = 'NvimLSP', create = true}) nvim_set_autocmd('FileType', available_languages, 'nnoremap <buffer><silent> <c-]> :lua vim.lsp.buf.definition()<CR>', {group = 'NvimLSP'}) nvim_set_autocmd('FileType', available_languages, 'nnoremap <buffer><silent> gd :lua vim.lsp.buf.declaration()<CR>', {group = 'NvimLSP'}) nvim_set_autocmd('FileType', available_languages, 'nnoremap <buffer><silent> gD :lua vim.lsp.buf.implementation()<CR>', {group = 'NvimLSP'}) nvim_set_autocmd('FileType', available_languages, 'nnoremap <buffer><silent> gr :lua vim.lsp.buf.references()<CR>', {group = 'NvimLSP'}) nvim_set_autocmd('FileType', available_languages, 'nnoremap <buffer><silent> K :lua vim.lsp.buf.hover()<CR>', {group = 'NvimLSP'}) nvim_set_autocmd( 'FileType', available_languages, "lua require'nvim'.nvim_set_command('Declaration', 'lua vim.lsp.buf.declaration()', {buffer = true, force = true})", {group = 'NvimLSP'} ) nvim_set_autocmd( 'FileType', available_languages, "lua require'nvim'.nvim_set_command('Definition', 'lua vim.lsp.buf.definition()', {buffer = true, force = true})", {group = 'NvimLSP'} ) nvim_set_autocmd( 'FileType', available_languages, "lua require'nvim'.nvim_set_command('References', 'lua vim.lsp.buf.references()', {buffer = true, force = true})", {group = 'NvimLSP'} ) nvim_set_autocmd( 'FileType', available_languages, "lua require'nvim'.nvim_set_command('Hover', 'lua vim.lsp.buf.hover()', {buffer = true, force = true})", {group = 'NvimLSP'} ) nvim_set_autocmd( 'FileType', available_languages, "autocmd CursorHold <buffer> lua vim.lsp.buf.hover()", {group = 'NvimLSP', nested = true} ) nvim_set_autocmd( 'FileType', available_languages, "lua require'nvim'.nvim_set_command('Implementation', 'lua vim.lsp.buf.implementation()', {buffer = true, force = true})", {group = 'NvimLSP'} ) nvim_set_autocmd( 'FileType', available_languages, "lua require'nvim'.nvim_set_command('Signature', 'lua vim.lsp.buf.signature_help()', {buffer = true, force = true})", {group = 'NvimLSP'} ) nvim_set_autocmd( 'FileType', available_languages, "lua require'nvim'.nvim_set_command('Type' , 'lua vim.lsp.buf.type_definition()', {buffer = true, force = true})", {group = 'NvimLSP'} ) -- Disable neomake for lsp buffers if plugs['neomake'] ~= nil then nvim_set_autocmd( 'FileType', available_languages, "call neomake#cmd#disable(b:)", {group = 'NvimLSP'} ) end do local method = 'textDocument/publishDiagnostics' local default_callback = vim.lsp.callbacks[method] vim.lsp.callbacks[method] = function(err, method, result, client_id) default_callback(err, method, result, client_id) if result and result.diagnostics then for _, v in ipairs(result.diagnostics) do v.uri = v.uri or result.uri end vim.lsp.util.set_loclist(result.diagnostics) end end end
fix: Check for executable name in some language servers
fix: Check for executable name in some language servers Allow to set custom executable name for language servers Set name for vimls to vim-language-server
Lua
mit
Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim
59a63c11b14bf948c4d26243b3c1bcbcd8edb985
frontend/ui/widget/radiobuttontable.lua
frontend/ui/widget/radiobuttontable.lua
local Blitbuffer = require("ffi/blitbuffer") local CheckButton = require("ui/widget/checkbutton") local Device = require("device") local FocusManager = require("ui/widget/focusmanager") local Font = require("ui/font") local Geom = require("ui/geometry") local HorizontalGroup = require("ui/widget/horizontalgroup") local LineWidget = require("ui/widget/linewidget") local Size = require("ui/size") local VerticalGroup = require("ui/widget/verticalgroup") local VerticalSpan = require("ui/widget/verticalspan") local dbg = require("dbg") local Screen = Device.screen local RadioButtonTable = FocusManager:new{ width = Screen:getWidth(), radio_buttons = { { {text="Cancel", enabled=false, callback=nil}, {text="OK", enabled=true, callback=nil}, }, }, sep_width = Size.line.medium, padding = Size.padding.button, zero_sep = false, face = Font:getFace("cfont", 22), _first_button = nil, checked_button = nil, button_select_callback = nil, } function RadioButtonTable:init() self.selected = { x = 1, y = 1 } self.radio_buttons_layout = {} self.container = VerticalGroup:new{ width = self.width } table.insert(self, self.container) if self.zero_sep then -- If we're asked to add a first line, don't add a vspan before: caller -- must do its own padding before. -- Things look better when the first line is gray like the others. self:addHorizontalSep(false, true, true) else self:addHorizontalSep(false, false, true) end local row_cnt = #self.radio_buttons for i = 1, row_cnt do self.radio_buttons_layout[i] = {} local horizontal_group = HorizontalGroup:new{} local row = self.radio_buttons[i] local column_cnt = #row local sizer_space = (self.sep_width + 2 * self.padding) * (column_cnt - 1) for j = 1, column_cnt do local btn_entry = row[j] local button = CheckButton:new{ text = btn_entry.text, checkable = btn_entry.checkable, checked = btn_entry.checked, enabled = btn_entry.enabled, radio = true, provider = btn_entry.provider, width = (self.width - sizer_space) / column_cnt, bordersize = 0, margin = 0, padding = 0, face = self.face, show_parent = self.show_parent or self, parent = self.parent or self, } local button_callback = function() self:_checkButton(button) if self.button_select_callback then self.button_select_callback(btn_entry) end end button.callback = button_callback if i == 1 and j == 1 then self._first_button = button end if button.checked and not self.checked_button then self.checked_button = button elseif dbg.is_on and button.checked and self.checked_button then error("RadioButtonGroup: multiple checked RadioButtons") end local button_dim = button:getSize() local vertical_sep = LineWidget:new{ background = Blitbuffer.COLOR_DARK_GRAY, dimen = Geom:new{ w = self.sep_width, h = button_dim.h, } } self.radio_buttons_layout[i][j] = button table.insert(horizontal_group, button) if j < column_cnt then table.insert(horizontal_group, vertical_sep) end end -- end for each button table.insert(self.container, horizontal_group) --if i < row_cnt then --self:addHorizontalSep(true, true, true) --end end -- end for each button line self:addHorizontalSep(true, false, false) -- check first entry unless otherwise specified if not self.checked_button then self._first_button:toggleCheck() self.checked_button = self._first_button end if Device:hasDPad() or Device:hasKeyboard() then self.layout = self.radio_buttons_layout self.layout[1][1]:onFocus() self.key_events.SelectByKeyPress = { {{"Press"}} } else self.key_events = {} -- deregister all key press event listeners end end function RadioButtonTable:addHorizontalSep(vspan_before, add_line, vspan_after, black_line) if vspan_before then table.insert(self.container, VerticalSpan:new{ width = Size.span.vertical_default }) end if add_line then table.insert(self.container, LineWidget:new{ background = black_line and Blitbuffer.COLOR_BLACK or Blitbuffer.COLOR_DARK_GRAY, dimen = Geom:new{ w = self.width, h = self.sep_width, } }) end if vspan_after then table.insert(self.container, VerticalSpan:new{ width = Size.span.vertical_default }) end end function RadioButtonTable:onSelectByKeyPress() local item = self:getFocusItem() if item then item.callback() return true end return false end function RadioButtonTable:_checkButton(button) -- nothing to do if button.checked then return end self.checked_button:toggleCheck() button:toggleCheck() self.checked_button = button end return RadioButtonTable
local Blitbuffer = require("ffi/blitbuffer") local CheckButton = require("ui/widget/checkbutton") local Device = require("device") local FocusManager = require("ui/widget/focusmanager") local Font = require("ui/font") local Geom = require("ui/geometry") local HorizontalGroup = require("ui/widget/horizontalgroup") local LineWidget = require("ui/widget/linewidget") local Size = require("ui/size") local VerticalGroup = require("ui/widget/verticalgroup") local VerticalSpan = require("ui/widget/verticalspan") local dbg = require("dbg") local Screen = Device.screen local RadioButtonTable = FocusManager:new{ width = Screen:getWidth(), radio_buttons = { { {text="Cancel", enabled=false, callback=nil}, {text="OK", enabled=true, callback=nil}, }, }, sep_width = Size.line.medium, padding = Size.padding.button, zero_sep = false, face = Font:getFace("cfont", 22), _first_button = nil, checked_button = nil, button_select_callback = nil, } function RadioButtonTable:init() self.selected = { x = 1, y = 1 } self.radio_buttons_layout = {} self.container = VerticalGroup:new{ width = self.width } table.insert(self, self.container) if self.zero_sep then -- If we're asked to add a first line, don't add a vspan before: caller -- must do its own padding before. -- Things look better when the first line is gray like the others. self:addHorizontalSep(false, true, true) else self:addHorizontalSep(false, false, true) end local row_cnt = #self.radio_buttons for i = 1, row_cnt do self.radio_buttons_layout[i] = {} local horizontal_group = HorizontalGroup:new{} local row = self.radio_buttons[i] local column_cnt = #row local sizer_space = (self.sep_width + 2 * self.padding) * (column_cnt - 1) for j = 1, column_cnt do local btn_entry = row[j] local button = CheckButton:new{ text = btn_entry.text, checkable = btn_entry.checkable, checked = btn_entry.checked, enabled = btn_entry.enabled, radio = true, provider = btn_entry.provider, width = (self.width - sizer_space) / column_cnt, bordersize = 0, margin = 0, padding = 0, face = self.face, show_parent = self.show_parent or self, parent = self.parent or self, } local button_callback = function() self:_checkButton(button) if self.button_select_callback then self.button_select_callback(btn_entry) end end button.callback = button_callback if i == 1 and j == 1 then self._first_button = button end if button.checked and not self.checked_button then self.checked_button = button elseif dbg.is_on and button.checked and self.checked_button then error("RadioButtonGroup: multiple checked RadioButtons") end local button_dim = button:getSize() local vertical_sep = LineWidget:new{ background = Blitbuffer.COLOR_DARK_GRAY, dimen = Geom:new{ w = self.sep_width, h = button_dim.h, } } self.radio_buttons_layout[i][j] = button table.insert(horizontal_group, button) if j < column_cnt then table.insert(horizontal_group, vertical_sep) end end -- end for each button table.insert(self.container, horizontal_group) --if i < row_cnt then --self:addHorizontalSep(true, true, true) --end end -- end for each button line self:addHorizontalSep(true, false, false) -- check first entry unless otherwise specified if not self.checked_button then self._first_button:toggleCheck() self.checked_button = self._first_button end if Device:hasDPad() or Device:hasKeyboard() then self.layout = self.radio_buttons_layout self.key_events.SelectByKeyPress = { {{"Press"}} } else self.key_events = {} -- deregister all key press event listeners end end function RadioButtonTable:addHorizontalSep(vspan_before, add_line, vspan_after, black_line) if vspan_before then table.insert(self.container, VerticalSpan:new{ width = Size.span.vertical_default }) end if add_line then table.insert(self.container, LineWidget:new{ background = black_line and Blitbuffer.COLOR_BLACK or Blitbuffer.COLOR_DARK_GRAY, dimen = Geom:new{ w = self.width, h = self.sep_width, } }) end if vspan_after then table.insert(self.container, VerticalSpan:new{ width = Size.span.vertical_default }) end end function RadioButtonTable:onSelectByKeyPress() local item = self:getFocusItem() if item then item.callback() return true end return false end function RadioButtonTable:_checkButton(button) -- nothing to do if button.checked then return end self.checked_button:toggleCheck() button:toggleCheck() self.checked_button = button end return RadioButtonTable
RadioButtonTable: CheckButton does not have onFocus (#8847)
RadioButtonTable: CheckButton does not have onFocus (#8847) Fixes #8841
Lua
agpl-3.0
Frenzie/koreader,Frenzie/koreader,poire-z/koreader,NiLuJe/koreader,koreader/koreader,poire-z/koreader,koreader/koreader,NiLuJe/koreader
05a0ab572ce6a5b9e668de103bb0438024550c21
Shilke2D/Utils/CollisionKit.lua
Shilke2D/Utils/CollisionKit.lua
--[[--- Helper for image collision detection. It's based on flash functions logic. --]] --[[--- Checks pixel perfect overlap of 2 raw images (MOAIImage). Depending on __USE_SIMULATION_COORDS__ the point 0,0 of the image is considered the top or the bottom left point @param i1 image 1 @param p1 top/bottom left position (vec2) of image1 @param a1 alpha treshold to consider image1 pixel transparent @param i2 image 2 @param p2 top/bottom left position (vec2) of image2 @param a2 alpha treshold to consider image2 pixel transparent --]] function imageHitTest(i1,p1,a1,i2,p2,a2) local w1,h1 = i1:getSize() local w2,h2 = i2:getSize() --alpha values are [0,255] local a1 = a1/255 local a2 = a2/255 local r1 = Rect(p1.x,p1.y,w1,h1) local r2 = Rect(p2.x,p2.y,w2,h2) if not r1:intersects(r2) then return false end if p1.x <= p2.x then r1.x = p2.x - p1.x r2.x = 0 r1.w = r1.w - r1.x else r1.x = 0 r2.x = p1.x - p2.x r1.w = r2.w - r2.x end if p1.y <= p2.y then r1.y = p2.y - p1.y r2.y = 0 r1.h = r1.h - r1.y else r1.y = 0 r2.y = p1.y - p2.y r1.h = r2.h - r2.y end if r1.w == 0 or r1.h == 0 then return false end if not __USE_SIMULATION_COORDS__ then for i = 1,r1.w do for j = 1,r1.h do local _,_,_,a = i1:getRGBA(r1.x + i, r1.y + j) if a > a1 then _,_,_,a = i1:getRGBA(r2.x + i, r2.y + j) if a > a2 then return true end end end end else r1.y = h1 - r1.y r2.y = h2 - r2.y for i = 1,r1.w do for j = 1,r1.h do local _,_,_,a = i1:getRGBA(r1.x + i, r1.y -j) if a > a1 then _,_,_,a = i1:getRGBA(r2.x + i, r2.y - j) if a > a2 then return true end end end end end return false end --[[--- Checks pixel perfect overlap of 2 images Depending on __USE_SIMULATION_COORDS__ the point 0,0 of the image is considered the top or the bottom left point @param i1 image 1 @param p1 top/bottom left position (vec2) of image1 @param a1 alpha treshold to consider image1 pixel transparent @param i2 image 2 @param p2 top/bottom left position (vec2) of image2 @param a2 alpha treshold to consider image2 pixel transparent @param rect1 (optional) can define a sub region over image1 (position and size) @param rect2 (optional) can define a sub region over image2 (position and size) @param rot1 (optional) if true rect1 must be considered rotated 90* anticlock wise @param rot2 (optional) if true rect2 must be considered rotated 90* anticlock wise --]] function imageHitTestEx(i1,p1,a1,i2,p2,a2,rect1,rect2,rot1,rot2) local w1,h1,w2,h2,o1x,o1y,o2x,o2y if rect1 then w1,h1 = rect1.w, rect1.h o1x,o1y = rect1.x, rect1.y else w1,h1 = i1:getSize() o1x,o1y = 0,0 end if rect2 then w2,h2 = rect2.w, rect2.h o2x,o2y = rect2.x, rect2.y else w2,h2 = i2:getSize() o2x,o2y = 0,0 end if rot1 then w1,h1 = h1,w1 end if rot2 then w2,h2 = h2,w2 end --alpha values are [0,255] local a1 = a1/255 local a2 = a2/255 local r1 = Rect(p1.x,p1.y,w1,h1) local r2 = Rect(p2.x,p2.y,w2,h2) if not r1:intersects(r2) then return false end if p1.x <= p2.x then r1.x = p2.x - p1.x r2.x = 0 r1.w = r1.w - r1.x else r1.x = 0 r2.x = p1.x - p2.x r1.w = r2.w - r2.x end if p1.y <= p2.y then r1.y = p2.y - p1.y r2.y = 0 r1.h = r1.h - r1.y else r1.y = 0 r2.y = p1.y - p2.y r1.h = r2.h - r2.y end if r1.w == 0 or r1.h == 0 then return false end if not __USE_SIMULATION_COORDS__ then if not rot1 and not rot2 then local _x1,_y1 = (o1x + r1.x), (o1y + r1.y) local _x2,_y2 = (o2x + r2.x), (o2y + r2.y) for i = 1,r1.w do for j = 1,r1.h do local _,_,_,a = i1:getRGBA(_x1 + i, _y1 + j) if a > a1 then _,_,_,a = i1:getRGBA(_x2 + i, _y2 + j) if a > a2 then return true end end end end elseif not rot1 and rot2 then local _x1,_y1 = (o1x + r1.x), (o1y + r1.y) local _x2,_y2 = (o2x + h2 - r2.y), (o2y + r2.x) for i = 1,r1.w do for j = 1,r1.h do local _,_,_,a = i1:getRGBA(_x1 + i, _y1 + j) if a > a1 then _,_,_,a = i2:getRGBA(_x2 - j, _y2 + i) if a > a2 then return true end end end end elseif rot1 and not rot2 then local _x1,_y1 = (o1x + h1 - r1.y), (o1y + r1.x) local _x2,_y2 = (o2x + r2.x), (o2y + r2.y) for i = 1,r1.w do for j = 1,r1.h do local _,_,_,a = i1:getRGBA(_x1 - j, _y1 + i) if a > a1 then _,_,_,a = i1:getRGBA(_x2 + i, _y2 + j) if a > a2 then return true end end end end elseif rot1 and rot2 then local _x1,_y1 = (o1x + h1 - r1.y), (o1y + r1.x) local _x2,_y2 = (o2x + h2 - r2.y), (o2y + r2.x) for i = 1,r1.w do for j = 1,r1.h do local _,_,_,a = i1:getRGBA(_x1 - j, _y1 + i) if a > a1 then _,_,_,a = i2:getRGBA(_x2 - j, _y2 + i) if a > a2 then return true end end end end end else if not rot1 and not rot2 then local _x1,_y1 = (o1x + r1.x), (o1y + h1 - r1.y) local _x2,_y2 = (o2x + r2.x), (o2y + h2 - r2.y) for i = 1,r1.w do for j = 1,r1.h do local _,_,_,a = i1:getRGBA(_x1 + i, _y1 -j) if a > a1 then _,_,_,a = i1:getRGBA(_x2 + i, _y2 - j) if a > a2 then return true end end end end elseif not rot1 and rot2 then local _x1,_y1 = (o1x + r1.x), (o1y + h1 - r1.y) local _x2,_y2 = (o2x + r2.y), (o2y + r2.x) for i = 1,r1.w do for j = 1,r1.h do local _,_,_,a = i1:getRGBA(_x1 + i, _y1 -j) if a > a1 then _,_,_,a = i2:getRGBA(_x2 + j, _y2 + i) if a > a2 then return true end end end end elseif rot1 and not rot2 then local _x1,_y1 = (o1x + r1.y), (o1y + r1.x) local _x2,_y2 = (o2x + r2.x), (o2y + h2 - r2.y) for i = 1,r1.w do for j = 1,r1.h do local _,_,_,a = i1:getRGBA(_x1 + j, _y1 + i) if a > a1 then _,_,_,a = i1:getRGBA(_x2 + i, _y2 - j) if a > a2 then return true end end end end elseif rot1 and rot2 then local _x1,_y1 = (o1x + r1.y), (o1y + r1.x) local _x2,_y2 = (o2x + r2.y), (o2y + r2.x) for i = 1,r1.w do for j = 1,r1.h do local _,_,_,a = i1:getRGBA(_x1 + j, _y1 + i) if a > a1 then _,_,_,a = i2:getRGBA(_x2 + j, _y2 + i) if a > a2 then return true end end end end end end return false end
--[[--- Helper for image collision detection. It's based on flash functions logic. --]] --[[--- Checks pixel perfect overlap of 2 raw images (MOAIImage). Depending on __USE_SIMULATION_COORDS__ the point 0,0 of the image is considered the top or the bottom left point @param i1 image 1 @param p1 top/bottom left position (vec2) of image1 @param a1 alpha treshold to consider image1 pixel transparent @param i2 image 2 @param p2 top/bottom left position (vec2) of image2 @param a2 alpha treshold to consider image2 pixel transparent --]] function imageHitTest(i1,p1,a1,i2,p2,a2) local w1,h1 = i1:getSize() local w2,h2 = i2:getSize() --alpha values are [0,255] local a1 = a1/255 local a2 = a2/255 local r1 = Rect(p1.x,p1.y,w1,h1) local r2 = Rect(p2.x,p2.y,w2,h2) --check for rect intersection if not r1:intersects(r2) then return false end --adjust r1,r2 to be intersection of the original rects if p1.x <= p2.x then r1.x = p2.x - p1.x r2.x = 0 r1.w = r1.w - r1.x else r1.x = 0 r2.x = p1.x - p2.x r1.w = r2.w - r2.x end if p1.y <= p2.y then r1.y = p2.y - p1.y r2.y = 0 r1.h = r1.h - r1.y else r1.y = 0 r2.y = p1.y - p2.y r1.h = r2.h - r2.y end --skip cases of edge collision if r1.w == 0 or r1.h == 0 then return false end if not __USE_SIMULATION_COORDS__ then for i = 1,r1.w do for j = 1,r1.h do local _,_,_,a = i1:getRGBA(r1.x + i, r1.y + j) if a > a1 then _,_,_,a = i2:getRGBA(r2.x + i, r2.y + j) if a > a2 then return true end end end end else --__USE_SIMULATION_COORDS__ r1.y = h1 - r1.y r2.y = h2 - r2.y for i = 1,r1.w do for j = 1,r1.h do local _,_,_,a = i1:getRGBA(r1.x + i, r1.y -j) if a > a1 then _,_,_,a = i2:getRGBA(r2.x + i, r2.y - j) if a > a2 then return true end end end end end return false end --[[--- Checks pixel perfect overlap of 2 images Depending on __USE_SIMULATION_COORDS__ the point 0,0 of the image is considered the top or the bottom left point @param i1 image 1 @param p1 top/bottom left position (vec2) of image1 @param a1 alpha treshold to consider image1 pixel transparent @param i2 image 2 @param p2 top/bottom left position (vec2) of image2 @param a2 alpha treshold to consider image2 pixel transparent @param rect1 (optional) can define a sub region over image1 (position and size) @param rect2 (optional) can define a sub region over image2 (position and size) @param rot1 (optional) if true rect1 must be considered rotated 90* anticlock wise @param rot2 (optional) if true rect2 must be considered rotated 90* anticlock wise --]] function imageHitTestEx(i1,p1,a1,i2,p2,a2,rect1,rect2,rot1,rot2) local w1,h1,w2,h2,o1x,o1y,o2x,o2y if rect1 then w1,h1 = rect1.w, rect1.h o1x,o1y = rect1.x, rect1.y else w1,h1 = i1:getSize() o1x,o1y = 0,0 end if rect2 then w2,h2 = rect2.w, rect2.h o2x,o2y = rect2.x, rect2.y else w2,h2 = i2:getSize() o2x,o2y = 0,0 end if rot1 then w1,h1 = h1,w1 end if rot2 then w2,h2 = h2,w2 end --alpha values are [0,255] local a1 = a1/255 local a2 = a2/255 local r1 = Rect(p1.x,p1.y,w1,h1) local r2 = Rect(p2.x,p2.y,w2,h2) --check for intersection if not r1:intersects(r2) then return false end --adjust r1,r2 to be intersection of the original rects if p1.x <= p2.x then r1.x = p2.x - p1.x r2.x = 0 r1.w = r1.w - r1.x else r1.x = 0 r2.x = p1.x - p2.x r1.w = r2.w - r2.x end if p1.y <= p2.y then r1.y = p2.y - p1.y r2.y = 0 r1.h = r1.h - r1.y else r1.y = 0 r2.y = p1.y - p2.y r1.h = r2.h - r2.y end --skip cases of edge collision if r1.w == 0 or r1.h == 0 then return false end if not __USE_SIMULATION_COORDS__ then if not rot1 and not rot2 then local _x1,_y1 = (o1x + r1.x), (o1y + r1.y) local _x2,_y2 = (o2x + r2.x), (o2y + r2.y) for i = 1,r1.w do for j = 1,r1.h do local _,_,_,a = i1:getRGBA(_x1 + i, _y1 + j) if a > a1 then _,_,_,a = i2:getRGBA(_x2 + i, _y2 + j) if a > a2 then return true end end end end elseif not rot1 and rot2 then local _x1,_y1 = (o1x + r1.x), (o1y + r1.y) local _x2,_y2 = (o2x + h2 - r2.y), (o2y + r2.x) for i = 1,r1.w do for j = 1,r1.h do local _,_,_,a = i1:getRGBA(_x1 + i, _y1 + j) if a > a1 then _,_,_,a = i2:getRGBA(_x2 - j, _y2 + i) if a > a2 then return true end end end end elseif rot1 and not rot2 then local _x1,_y1 = (o1x + h1 - r1.y), (o1y + r1.x) local _x2,_y2 = (o2x + r2.x), (o2y + r2.y) for i = 1,r1.w do for j = 1,r1.h do local _,_,_,a = i1:getRGBA(_x1 - j, _y1 + i) if a > a1 then _,_,_,a = i2:getRGBA(_x2 + i, _y2 + j) if a > a2 then return true end end end end elseif rot1 and rot2 then local _x1,_y1 = (o1x + h1 - r1.y), (o1y + r1.x) local _x2,_y2 = (o2x + h2 - r2.y), (o2y + r2.x) for i = 1,r1.w do for j = 1,r1.h do local _,_,_,a = i1:getRGBA(_x1 - j, _y1 + i) if a > a1 then _,_,_,a = i2:getRGBA(_x2 - j, _y2 + i) if a > a2 then return true end end end end end else --__USE_SIMULATION_COORDS__ if not rot1 and not rot2 then local _x1,_y1 = (o1x + r1.x), (o1y + h1 - r1.y) local _x2,_y2 = (o2x + r2.x), (o2y + h2 - r2.y) for i = 1,r1.w do for j = 1,r1.h do local _,_,_,a = i1:getRGBA(_x1 + i, _y1 -j) if a > a1 then _,_,_,a = i2:getRGBA(_x2 + i, _y2 - j) if a > a2 then return true end end end end elseif not rot1 and rot2 then local _x1,_y1 = (o1x + r1.x), (o1y + h1 - r1.y) local _x2,_y2 = (o2x + r2.y), (o2y + r2.x) for i = 1,r1.w do for j = 1,r1.h do local _,_,_,a = i1:getRGBA(_x1 + i, _y1 -j) if a > a1 then _,_,_,a = i2:getRGBA(_x2 + j, _y2 + i) if a > a2 then return true end end end end elseif rot1 and not rot2 then local _x1,_y1 = (o1x + r1.y), (o1y + r1.x) local _x2,_y2 = (o2x + r2.x), (o2y + h2 - r2.y) for i = 1,r1.w do for j = 1,r1.h do local _,_,_,a = i1:getRGBA(_x1 + j, _y1 + i) if a > a1 then _,_,_,a = i2:getRGBA(_x2 + i, _y2 - j) if a > a2 then return true end end end end elseif rot1 and rot2 then local _x1,_y1 = (o1x + r1.y), (o1y + r1.x) local _x2,_y2 = (o2x + r2.y), (o2y + r2.x) for i = 1,r1.w do for j = 1,r1.h do local _,_,_,a = i1:getRGBA(_x1 + j, _y1 + i) if a > a1 then _,_,_,a = i2:getRGBA(_x2 + j, _y2 + i) if a > a2 then return true end end end end end end return false end
fix on hitTest algorithms
fix on hitTest algorithms
Lua
mit
Shrike78/Shilke2D
0d758896071fc00e0105898844abc6a4752f68f9
tools/utils/BPE.lua
tools/utils/BPE.lua
local unicode = require 'tools.utils.unicode' local BPE = torch.class('BPE') function BPE:__init(opt) self.split = string.split -- to be able to run the code without torch if not self.split then self.split = function(t, sep) local fields = {} local pattern = string.format("([^%s]+)", sep) t:gsub(pattern, function(c) fields[#fields+1] = c end) return fields end end self.codes = {} local f = assert(io.open(opt.bpe_model, "r")) self.EOT_marker = opt.EOT_marker self.BOT_marker = opt.BOT_marker self.joiner_new = opt.joiner_new self.joiner_annotate = opt.joiner_annotate local t = f:read("*line") local options = self.split(t, ";") if (#options == 4) then self.prefix = options[1] == "true" self.suffix = options[2] == "true" self.case_insensitive = options[3] == "true" t = f:read("*line") else self.prefix = opt.bpe_prefix self.suffix = opt.bpe_suffix self.case_insensitive = opt.bpe_case_insensitive end local i = 1 while not(t == nil) do local l = self.split(t, " ") if #l == 2 then self.codes[t] = i i = i + 1 end t=f:read("*line") end end local function getPairs(word) local pairs = {} for i = 1, #word-1, 1 do table.insert(pairs, word[i] .. ' ' .. word[i+1]) end return pairs end local function str2word(l, case_insensitive) local word = {} for v, c in unicode.utf8_iter(l) do if (case_insensitive) then local lu, lc = unicode.getLower(v) if lu then c = lc end end table.insert(word, c) end return word end function BPE:minPair(pairsTable) local mintmp = 100000 local minpair = '' for i = 1, #pairsTable, 1 do local pair_cur = pairsTable[i] if self.codes[pair_cur] then local scoretmp = self.codes[pair_cur] if (scoretmp < mintmp) then mintmp = scoretmp minpair = pair_cur end end end return minpair end function BPE:encode(l) local word = str2word(l, self.case_insensitive) if #word == 1 then word[1] = l return word end if self.prefix then table.insert(word, 1, self.BOT_marker) end if self.suffix then table.insert(word, self.EOT_marker) end local pairs = getPairs(word) while true do local bigram = self:minPair(pairs) if bigram == '' then break end bigram = self.split(bigram, ' ') local new_word = {} local merge = false for _, xx in ipairs(word) do if (merge) then if xx == bigram[2] then table.insert(new_word, bigram[1] .. bigram[2]) merge = false elseif xx == bigram[1] then table.insert(new_word, bigram[1]) else table.insert(new_word, bigram[1]) table.insert(new_word, xx) merge = false end else if bigram[1] == xx then merge = true else table.insert(new_word, xx) end end end word = new_word if #word == 1 then break else pairs = getPairs(word) end end if self.suffix then if word[#word] == self.EOT_marker then table.remove(word, #word) elseif string.sub(word[#word],-string.len(self.EOT_marker)) == self.EOT_marker then word[#word] = string.sub(word[#word], 1, -string.len(self.EOT_marker)-1) end end if self.prefix then if word[1] == self.BOT_marker then table.remove(word, 1) elseif string.sub(word[1], 1, string.len(self.BOT_marker)) == self.BOT_marker then word[1] = string.sub(word[1], string.len(self.BOT_marker)+1) end end if (self.case_insensitive) then local tcword = {} local prev_idx = 1 for i = 1, #word do local curr_idx = prev_idx+unicode.utf8len(word[i]) table.insert(tcword, unicode.utf8substr(l, prev_idx, curr_idx - 1)) prev_idx = curr_idx end word = tcword end return word end function BPE:segment(tokens, separator) local bpeSegment = {} for i=1, #tokens do local token = tokens[i] local left_sep = false local right_sep = false if self.joiner_annotate and not self.joiner_new then if token:sub(1, #separator) == separator then token = token:sub(#separator + 1) left_sep = true end if token:sub(-#separator, -1) == separator then token = token:sub(1, -#separator-1) right_sep = true end end local bpeTokens = self:encode(token) if self.joiner_annotate and not self.joiner_new then if left_sep then bpeTokens[1] = separator .. bpeTokens[1] end if right_sep then bpeTokens[#bpeTokens] = bpeTokens[#bpeTokens] .. separator end end for j=1, #bpeTokens-1 do if self.joiner_annotate then if not self.joiner_new then table.insert(bpeSegment, bpeTokens[j] .. separator) else table.insert(bpeSegment, bpeTokens[j]) table.insert(bpeSegment, separator) end else table.insert(bpeSegment, bpeTokens[j]) end end table.insert(bpeSegment, bpeTokens[#bpeTokens]) end return bpeSegment end return BPE
local unicode = require 'tools.utils.unicode' local BPE = torch.class('BPE') function BPE:__init(opt) self.split = string.split -- to be able to run the code without torch if not self.split then self.split = function(t, sep) local fields = {} local pattern = string.format("([^%s]+)", sep) t:gsub(pattern, function(c) fields[#fields+1] = c end) return fields end end self.codes = {} local f = assert(io.open(opt.bpe_model, "r")) self.EOT_marker = opt.EOT_marker self.BOT_marker = opt.BOT_marker self.joiner_new = opt.joiner_new self.joiner_annotate = opt.joiner_annotate local t = f:read("*line") local options = self.split(t, ";") if (#options == 4) then self.prefix = options[1] == "true" self.suffix = options[2] == "true" self.case_insensitive = options[3] == "true" t = f:read("*line") else self.prefix = opt.bpe_prefix self.suffix = opt.bpe_suffix self.case_insensitive = opt.bpe_case_insensitive end local i = 1 while not(t == nil) do local l = self.split(t, " ") if #l == 2 then self.codes[t] = i i = i + 1 end t=f:read("*line") end end local function getPairs(word) local pairs = {} for i = 1, #word-1, 1 do table.insert(pairs, word[i] .. ' ' .. word[i+1]) end return pairs end local function str2word(l, case_insensitive) local word = {} for v, c in unicode.utf8_iter(l) do if (case_insensitive) then local lu, lc = unicode.getLower(v) if lu then c = lc end end table.insert(word, c) end return word end function BPE:minPair(pairsTable) local mintmp = 100000 local minpair = '' for i = 1, #pairsTable, 1 do local pair_cur = pairsTable[i] if self.codes[pair_cur] then local scoretmp = self.codes[pair_cur] if (scoretmp < mintmp) then mintmp = scoretmp minpair = pair_cur end end end return minpair end function BPE:encode(l) local word = str2word(l, self.case_insensitive) if #word == 1 then word[1] = l return word end if self.prefix then table.insert(word, 1, self.BOT_marker) end if self.suffix then table.insert(word, self.EOT_marker) end local pairs = getPairs(word) while true do local bigram = self:minPair(pairs) if bigram == '' then break end bigram = self.split(bigram, ' ') local new_word = {} local merge = false for _, xx in ipairs(word) do if (merge) then if xx == bigram[2] then table.insert(new_word, bigram[1] .. bigram[2]) merge = false elseif xx == bigram[1] then table.insert(new_word, bigram[1]) else table.insert(new_word, bigram[1]) table.insert(new_word, xx) merge = false end else if bigram[1] == xx then merge = true else table.insert(new_word, xx) end end end if merge then table.insert(new_word, bigram[1]) end word = new_word if #word == 1 then break else pairs = getPairs(word) end end if self.suffix then if word[#word] == self.EOT_marker then table.remove(word, #word) elseif string.sub(word[#word],-string.len(self.EOT_marker)) == self.EOT_marker then word[#word] = string.sub(word[#word], 1, -string.len(self.EOT_marker)-1) end end if self.prefix then if word[1] == self.BOT_marker then table.remove(word, 1) elseif string.sub(word[1], 1, string.len(self.BOT_marker)) == self.BOT_marker then word[1] = string.sub(word[1], string.len(self.BOT_marker)+1) end end if (self.case_insensitive) then local tcword = {} local prev_idx = 1 for i = 1, #word do local curr_idx = prev_idx+unicode.utf8len(word[i]) table.insert(tcword, unicode.utf8substr(l, prev_idx, curr_idx - 1)) prev_idx = curr_idx end word = tcword end return word end function BPE:segment(tokens, separator) local bpeSegment = {} for i=1, #tokens do local token = tokens[i] local left_sep = false local right_sep = false if self.joiner_annotate and not self.joiner_new then if token:sub(1, #separator) == separator then token = token:sub(#separator + 1) left_sep = true end if token:sub(-#separator, -1) == separator then token = token:sub(1, -#separator-1) right_sep = true end end local bpeTokens = self:encode(token) if self.joiner_annotate and not self.joiner_new then if left_sep then bpeTokens[1] = separator .. bpeTokens[1] end if right_sep then bpeTokens[#bpeTokens] = bpeTokens[#bpeTokens] .. separator end end for j=1, #bpeTokens-1 do if self.joiner_annotate then if not self.joiner_new then table.insert(bpeSegment, bpeTokens[j] .. separator) else table.insert(bpeSegment, bpeTokens[j]) table.insert(bpeSegment, separator) end else table.insert(bpeSegment, bpeTokens[j]) end end table.insert(bpeSegment, bpeTokens[#bpeTokens]) end return bpeSegment end return BPE
fix noffix missing last subtoken problem for BPE.lua
fix noffix missing last subtoken problem for BPE.lua
Lua
mit
jsenellart/OpenNMT,jsenellart-systran/OpenNMT,monsieurzhang/OpenNMT,jsenellart/OpenNMT,jungikim/OpenNMT,monsieurzhang/OpenNMT,da03/OpenNMT,jsenellart/OpenNMT,OpenNMT/OpenNMT,OpenNMT/OpenNMT,jsenellart-systran/OpenNMT,jsenellart-systran/OpenNMT,monsieurzhang/OpenNMT,da03/OpenNMT,OpenNMT/OpenNMT,da03/OpenNMT,jungikim/OpenNMT,jungikim/OpenNMT
f2a6f2d1d52dc0d6b376c4b55fa50e1a91884264
lua/plugins/lsp.lua
lua/plugins/lsp.lua
local nvim = require('nvim') local executable = require('nvim').fn.executable local nvim_set_autocmd = require('nvim').nvim_set_autocmd local nvim_set_command = require('nvim').nvim_set_command local ok, lsp = pcall(require, 'nvim_lsp') if not ok then print('Failed to initialize LSP') print('LSP Error '..lsp) return nil end local servers = { sh = { bashls = 'bash-language-server', }, docker = { dockerls = 'docker-language-server', }, rust = { rust_analyzer = 'rust_analyzer', }, go = { gopls = 'gopls', }, latex = { texlab = 'texlab', }, python = { pyls = 'pyls', }, c = { ccls = 'ccls', clangd = 'clangd', }, cpp = { ccls = 'ccls', clangd = 'clangd', }, } local available_languages = {} for language,options in pairs(servers) do for option,server in pairs(options) do if executable(server) then lsp[option].setup({}) available_languages[#available_languages + 1] = language break end end end nvim_set_autocmd('FileType', available_languages, 'setlocal omnifunc=v:lua.vim.lsp.omnifunc', {group = 'NvimLSP', create = true}) nvim_set_autocmd('FileType', available_languages, 'nnoremap <buffer><silent> gD :lua vim.lsp.buf.definition()<CR>', {group = 'NvimLSP'}) nvim_set_autocmd('FileType', available_languages, 'nnoremap <buffer><silent> K :lua vim.lsp.buf.hover()<CR>', {group = 'NvimLSP'}) nvim_set_autocmd( 'FileType', available_languages, "lua require'nvim'.nvim_set_command('Declaration', 'lua vim.lsp.buf.declaration()', {buffer = true, force = true})", {group = 'NvimLSP'} ) nvim_set_autocmd( 'FileType', available_languages, "lua require'nvim'.nvim_set_command('Definition', 'lua vim.lsp.buf.definition()', {buffer = true, force = true})", {group = 'NvimLSP'} ) nvim_set_autocmd( 'FileType', available_languages, "lua require'nvim'.nvim_set_command('Hover', 'lua vim.lsp.buf.hover()', {buffer = true, force = true})", {group = 'NvimLSP'} ) nvim_set_autocmd( 'FileType', available_languages, "lua require'nvim'.nvim_set_command('Implementation', 'lua vim.lsp.buf.implementation()', {buffer = true, force = true})", {group = 'NvimLSP'} ) nvim_set_autocmd( 'FileType', available_languages, "lua require'nvim'.nvim_set_command('Signature', 'lua vim.lsp.buf.signature_help()', {buffer = true, force = true})", {group = 'NvimLSP'} ) nvim_set_autocmd( 'FileType', available_languages, "lua require'nvim'.nvim_set_command('Type' , 'lua vim.lsp.buf.type_definition()', {buffer = true, force = true})", {group = 'NvimLSP'} )
local nvim = require('nvim') local executable = require('nvim').fn.executable local nvim_set_autocmd = require('nvim').nvim_set_autocmd local nvim_set_command = require('nvim').nvim_set_command local ok, lsp = pcall(require, 'nvim_lsp') if not ok then return nil end local servers = { sh = { bashls = 'bash-language-server', }, docker = { dockerls = 'docker-language-server', }, rust = { rust_analyzer = 'rust_analyzer', }, go = { gopls = 'gopls', }, latex = { texlab = 'texlab', }, python = { pyls = 'pyls', }, c = { ccls = 'ccls', clangd = 'clangd', }, cpp = { ccls = 'ccls', clangd = 'clangd', }, } local available_languages = {} for language,options in pairs(servers) do for option,server in pairs(options) do if executable(server) then lsp[option].setup({}) available_languages[#available_languages + 1] = language break end end end nvim_set_autocmd('FileType', available_languages, 'setlocal omnifunc=v:lua.vim.lsp.omnifunc', {group = 'NvimLSP', create = true}) nvim_set_autocmd('FileType', available_languages, 'nnoremap <buffer><silent> gD :lua vim.lsp.buf.definition()<CR>', {group = 'NvimLSP'}) nvim_set_autocmd('FileType', available_languages, 'nnoremap <buffer><silent> K :lua vim.lsp.buf.hover()<CR>', {group = 'NvimLSP'}) nvim_set_autocmd( 'FileType', available_languages, "lua require'nvim'.nvim_set_command('Declaration', 'lua vim.lsp.buf.declaration()', {buffer = true, force = true})", {group = 'NvimLSP'} ) nvim_set_autocmd( 'FileType', available_languages, "lua require'nvim'.nvim_set_command('Definition', 'lua vim.lsp.buf.definition()', {buffer = true, force = true})", {group = 'NvimLSP'} ) nvim_set_autocmd( 'FileType', available_languages, "lua require'nvim'.nvim_set_command('Hover', 'lua vim.lsp.buf.hover()', {buffer = true, force = true})", {group = 'NvimLSP'} ) nvim_set_autocmd( 'FileType', available_languages, "lua require'nvim'.nvim_set_command('Implementation', 'lua vim.lsp.buf.implementation()', {buffer = true, force = true})", {group = 'NvimLSP'} ) nvim_set_autocmd( 'FileType', available_languages, "lua require'nvim'.nvim_set_command('Signature', 'lua vim.lsp.buf.signature_help()', {buffer = true, force = true})", {group = 'NvimLSP'} ) nvim_set_autocmd( 'FileType', available_languages, "lua require'nvim'.nvim_set_command('Type' , 'lua vim.lsp.buf.type_definition()', {buffer = true, force = true})", {group = 'NvimLSP'} )
fix: Remove prints
fix: Remove prints
Lua
mit
Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim
0e9afcfd6798412ef354a455d528ecf43e3c24db
plugins/mod_http.lua
plugins/mod_http.lua
-- Prosody IM -- Copyright (C) 2008-2012 Matthew Wild -- Copyright (C) 2008-2012 Waqas Hussain -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- module:set_global(); local parse_url = require "socket.url".parse; local server = require "net.http.server"; local function normalize_path(path) if path:sub(1,1) ~= "/" then path = "/"..path; end if path:sub(-1,-1) == "/" then path = path:sub(1, -2); end return path; end local function get_http_event(host, app_path, key) local method, path = key:match("^(%S+)%s+(.+)$"); if not method and key:sub(1,1) == "/" then method, path = "GET", key; else return nil; end path = normalize_path(path); return method:upper().." "..host..app_path..path; end function module.add_host(module) local host = module.host; local apps = {}; module.environment.apps = apps; local function http_app_added(event) local app_name = event.item.name; local default_app_path = event.item.default_path or "/"..app_name; local app_path = normalize_path(module:get_option_string(app_name.."_http_path", default_app_path)); if not app_name then -- TODO: Link to docs module:log("error", "HTTP app has no 'name', add one or use module:provides('http', app)"); return; end apps[app_name] = apps[app_name] or {}; local app_handlers = apps[app_name]; for key, handler in pairs(event.item.route or {}) do local event_name = get_http_event(host, app_path, key); if event_name then if event_name:sub(-2, -1) == "/*" then local base_path = event_name:match("/(.+)/*$"); local _handler = handler; handler = function (event) local path = event.request.path:sub(#base_path+1); return _handler(event, path); end; end if not app_handlers[event_name] then app_handlers[event_name] = handler; server.add_handler(event_name, handler); else module:log("warn", "App %s added handler twice for '%s', ignoring", app_name, event_name); end else module:log("error", "Invalid route in %s: %q", app_name, key); end end end local function http_app_removed(event) local app_handlers = apps[event.item.name]; apps[event.item.name] = nil; for event, handler in pairs(app_handlers) do server.remove_handler(event, handler); end end module:handle_items("http-provider", http_app_added, http_app_removed); end module:add_item("net-provider", { name = "http"; listener = server.listener; default_port = 5280; multiplex = { pattern = "^[A-Z]"; }; }); module:add_item("net-provider", { name = "https"; listener = server.listener; default_port = 5281; encryption = "ssl"; multiplex = { pattern = "^[A-Z]"; }; });
-- Prosody IM -- Copyright (C) 2008-2012 Matthew Wild -- Copyright (C) 2008-2012 Waqas Hussain -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- module:set_global(); local parse_url = require "socket.url".parse; local server = require "net.http.server"; local function normalize_path(path) if path:sub(1,1) ~= "/" then path = "/"..path; end if path:sub(-1,-1) == "/" then path = path:sub(1, -2); end return path; end local function get_http_event(host, app_path, key) local method, path = key:match("^(%S+)%s+(.+)$"); if not method then if key:sub(1,1) ~= "/" then return nil; end method, path = "GET", key; end path = normalize_path(path); return method:upper().." "..host..app_path..path; end function module.add_host(module) local host = module.host; local apps = {}; module.environment.apps = apps; local function http_app_added(event) local app_name = event.item.name; local default_app_path = event.item.default_path or "/"..app_name; local app_path = normalize_path(module:get_option_string(app_name.."_http_path", default_app_path)); if not app_name then -- TODO: Link to docs module:log("error", "HTTP app has no 'name', add one or use module:provides('http', app)"); return; end apps[app_name] = apps[app_name] or {}; local app_handlers = apps[app_name]; for key, handler in pairs(event.item.route or {}) do local event_name = get_http_event(host, app_path, key); if event_name then if event_name:sub(-2, -1) == "/*" then local base_path = event_name:match("/(.+)/*$"); local _handler = handler; handler = function (event) local path = event.request.path:sub(#base_path+1); return _handler(event, path); end; end if not app_handlers[event_name] then app_handlers[event_name] = handler; server.add_handler(event_name, handler); else module:log("warn", "App %s added handler twice for '%s', ignoring", app_name, event_name); end else module:log("error", "Invalid route in %s: %q", app_name, key); end end end local function http_app_removed(event) local app_handlers = apps[event.item.name]; apps[event.item.name] = nil; for event, handler in pairs(app_handlers) do server.remove_handler(event, handler); end end module:handle_items("http-provider", http_app_added, http_app_removed); end module:add_item("net-provider", { name = "http"; listener = server.listener; default_port = 5280; multiplex = { pattern = "^[A-Z]"; }; }); module:add_item("net-provider", { name = "https"; listener = server.listener; default_port = 5281; encryption = "ssl"; multiplex = { pattern = "^[A-Z]"; }; });
mod_http: Fix specifying method in app route keys
mod_http: Fix specifying method in app route keys
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
0d4fd9173c789566481e6976417cc7b68fc6dc0b
admin/server/player_admin.lua
admin/server/player_admin.lua
addCommandHandler( { "getpos", "pos", "getposition", "getxyz", "getloc", "loc", "getlocation" }, function( player, cmd, targetPlayer ) if ( exports.common:isPlayerServerTrialAdmin( player ) ) then if ( targetPlayer ) then targetPlayer = exports.common:getPlayerFromPartialName( targetPlayer, player ) if ( not targetPlayer ) then outputChatBox( "Could not find a player with that identifier.", player, 230, 95, 95, false ) return end else targetPlayer = player end local x, y, z = getElementPosition( targetPlayer ) local rotation = getPedRotation( targetPlayer ) local interior, dimension = getElementInterior( targetPlayer ), getElementDimension( targetPlayer ) x, y, z = math.floor( x * 100 ) / 100, math.floor( y * 100 ) / 100, math.floor( z * 100 ) / 100 rotation = math.floor( rotation * 100 ) / 100 local playerName = exports.common:getRealPlayerName( targetPlayer ) outputChatBox( ( targetPlayer ~= player and exports.common:formatPlayerName( playerName ) or "Your" ) .. " position:", player, 230, 180, 95, false ) outputChatBox( " Position: " .. x .. ", " .. y .. ", " .. z, player, 230, 180, 95, false ) outputChatBox( " Rotation: " .. rotation .. ", Interior: " .. interior .. ", Dimension: " .. dimension, player, 230, 180, 95, false ) end end ) addCommandHandler( { "makeadmin", "setlevel", "setadminlevel" }, function( player, cmd, targetPlayer, level ) if ( exports.common:isPlayerServerSeniorAdmin( player ) ) then if ( not targetPlayer ) or ( not level ) then outputChatBox( "SYNTAX: /" .. cmd .. " [partial player name] [level]", player, 230, 180, 95, false ) return end targetPlayer = exports.common:getPlayerFromPartialName( targetPlayer, player ) if ( not targetPlayer ) then outputChatBox( "Could not find a player with that identifier.", player, 230, 95, 95, false ) return end local levelName = exports.common:getLevelName( tonumber( level ) ) if ( levelName ~= "" ) then exports.security:modifyElementData( targetPlayer, "account:level", level, true ) exports.database:query( "UPDATE `accounts` SET `level` = ? WHERE `id` = ?", level, getElementData( targetPlayer, "database:id" ) ) if ( level > 0 ) then triggerClientEvent( targetPlayer, "admin:showHUD", targetPlayer ) triggerClientEvent( root, "admin:updateHUD", root ) else triggerClientEvent( targetPlayer, "admin:hideHUD", targetPlayer ) end outputChatBox( "Updated " .. exports.common:formatString( exports.common:getRealPlayerName( targetPlayer ) ) .. " level to " .. level .. " (" .. levelName .. ").", player, 95, 230, 95, false ) else outputChatBox( "Such level does not exist.", player, 230, 95, 95, false ) end end end ) addCommandHandler( "setskin", function( player, cmd, targetPlayer, skinID ) if ( exports.common:isPlayerServerTrialAdmin( player ) ) then if ( not targetPlayer ) or ( not skinID ) then outputChatBox( "SYNTAX: /" .. cmd .. " [partial player name] [skin id]", player, 230, 180, 95, false ) return end targetPlayer = exports.common:getPlayerFromPartialName( targetPlayer, player ) if ( not targetPlayer ) then outputChatBox( "Could not find a player with that identifier.", player, 230, 95, 95, false ) return end local skinID = tonumber( skinID ) local foundSkin = false for _, _skinID in ipairs( getValidPedModels( ) ) do if ( _skinID == skinID ) then foundSkin = true end end if ( foundSkin ) then exports.database:query( "UPDATE `characters` SET `skin_id` = ? WHERE `id` = ?", skinID, getElementData( targetPlayer, "database:id" ) ) setElementModel( targetPlayer, skinID ) outputChatBox( "Updated " .. exports.common:formatString( exports.common:getRealPlayerName( targetPlayer ) ) .. " skin ID to " .. skinID .. ".", player, 95, 230, 95, false ) else outputChatBox( "Such skin does not exist.", player, 230, 95, 95, false ) end end end ) addCommandHandler( { "toggleduty", "adminduty", "toggleadminduty", "togduty", "aduty", "admin" }, function( player, cmd ) if ( exports.common:isPlayerServerTrialAdmin( player ) ) then local newStatus = not exports.common:isOnDuty( player ) exports.security:modifyElementData( player, "account:duty", newStatus, true ) triggerClientEvent( player, "admin:updateHUD", player ) outputChatBox( "You are now " .. ( newStatus and "on" or "off" ) .. " admin duty mode.", player, 230, 180, 95, false ) end end ) addCommandHandler( { "announce", "announcement", "message" }, function( player, cmd, ... ) if ( exports.common:isPlayerServerTrialAdmin( player ) ) then exports.messages:createMessage( root, table.concat( { ... }, " " ), getTickCount( ) ) end end )
addCommandHandler( { "getpos", "pos", "getposition", "getxyz", "getloc", "loc", "getlocation" }, function( player, cmd, targetPlayer ) if ( exports.common:isPlayerServerTrialAdmin( player ) ) then if ( targetPlayer ) then targetPlayer = exports.common:getPlayerFromPartialName( targetPlayer, player ) if ( not targetPlayer ) then outputChatBox( "Could not find a player with that identifier.", player, 230, 95, 95, false ) return end else targetPlayer = player end local x, y, z = getElementPosition( targetPlayer ) local rotation = getPedRotation( targetPlayer ) local interior, dimension = getElementInterior( targetPlayer ), getElementDimension( targetPlayer ) x, y, z = math.floor( x * 100 ) / 100, math.floor( y * 100 ) / 100, math.floor( z * 100 ) / 100 rotation = math.floor( rotation * 100 ) / 100 local playerName = exports.common:getRealPlayerName( targetPlayer ) outputChatBox( ( targetPlayer ~= player and exports.common:formatPlayerName( playerName ) or "Your" ) .. " position:", player, 230, 180, 95, false ) outputChatBox( " Position: " .. x .. ", " .. y .. ", " .. z, player, 230, 180, 95, false ) outputChatBox( " Rotation: " .. rotation .. ", Interior: " .. interior .. ", Dimension: " .. dimension, player, 230, 180, 95, false ) end end ) addCommandHandler( { "makeadmin", "setlevel", "setadminlevel" }, function( player, cmd, targetPlayer, level ) if ( exports.common:isPlayerServerSeniorAdmin( player ) ) then local level = tonumber( level ) if ( not targetPlayer ) or ( not level ) then outputChatBox( "SYNTAX: /" .. cmd .. " [partial player name] [level]", player, 230, 180, 95, false ) return end targetPlayer = exports.common:getPlayerFromPartialName( targetPlayer, player ) if ( not targetPlayer ) then outputChatBox( "Could not find a player with that identifier.", player, 230, 95, 95, false ) return end local levelName = exports.common:getLevelName( tonumber( level ) ) if ( levelName ~= "" ) then exports.security:modifyElementData( targetPlayer, "account:level", level, true ) exports.database:query( "UPDATE `accounts` SET `level` = ? WHERE `id` = ?", level, getElementData( targetPlayer, "database:id" ) ) if ( level > 0 ) then triggerClientEvent( targetPlayer, "admin:showHUD", targetPlayer ) triggerClientEvent( root, "admin:updateHUD", root ) else triggerClientEvent( targetPlayer, "admin:hideHUD", targetPlayer ) end outputChatBox( "Updated " .. exports.common:formatString( exports.common:getRealPlayerName( targetPlayer ) ) .. " level to " .. level .. " (" .. levelName .. ").", player, 95, 230, 95, false ) else outputChatBox( "Such level does not exist.", player, 230, 95, 95, false ) end end end ) addCommandHandler( "setskin", function( player, cmd, targetPlayer, skinID ) if ( exports.common:isPlayerServerTrialAdmin( player ) ) then if ( not targetPlayer ) or ( not skinID ) then outputChatBox( "SYNTAX: /" .. cmd .. " [partial player name] [skin id]", player, 230, 180, 95, false ) return end targetPlayer = exports.common:getPlayerFromPartialName( targetPlayer, player ) if ( not targetPlayer ) then outputChatBox( "Could not find a player with that identifier.", player, 230, 95, 95, false ) return end local skinID = tonumber( skinID ) local foundSkin = false for _, _skinID in ipairs( getValidPedModels( ) ) do if ( _skinID == skinID ) then foundSkin = true end end if ( foundSkin ) then exports.database:query( "UPDATE `characters` SET `skin_id` = ? WHERE `id` = ?", skinID, getElementData( targetPlayer, "database:id" ) ) setElementModel( targetPlayer, skinID ) outputChatBox( "Updated " .. exports.common:formatString( exports.common:getRealPlayerName( targetPlayer ) ) .. " skin ID to " .. skinID .. ".", player, 95, 230, 95, false ) else outputChatBox( "Such skin does not exist.", player, 230, 95, 95, false ) end end end ) addCommandHandler( { "toggleduty", "adminduty", "toggleadminduty", "togduty", "aduty", "admin" }, function( player, cmd ) if ( exports.common:isPlayerServerTrialAdmin( player ) ) then local newStatus = not exports.common:isOnDuty( player ) exports.security:modifyElementData( player, "account:duty", newStatus, true ) triggerClientEvent( player, "admin:updateHUD", player ) outputChatBox( "You are now " .. ( newStatus and "on" or "off" ) .. " admin duty mode.", player, 230, 180, 95, false ) end end ) addCommandHandler( { "announce", "announcement", "message" }, function( player, cmd, ... ) if ( exports.common:isPlayerServerTrialAdmin( player ) ) then exports.messages:createMessage( root, table.concat( { ... }, " " ), getTickCount( ) ) end end )
admin: fixed issue with makeadmin
admin: fixed issue with makeadmin
Lua
mit
smile-tmb/lua-mta-fairplay-roleplay
7d09bd30e225dc0d3d7ffd8b59d878ca073b86dd
spatialhash.lua
spatialhash.lua
--[[ Copyright (c) 2011 Matthias Richter Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. Except as contained in this notice, the name(s) of the above copyright holders shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization. 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 floor = math.floor local min, max = math.min, math.max local _PACKAGE = (...):match("^(.+)%.[^%.]+") if not (common and common.class and common.instance) then class_commons = true require(_PACKAGE .. '.class') end -- transparent cell accessor methods -- cells = {[0] = {[0] = <>, [1] = <>, ... }, [1] = {...}, ...} local cells_meta = {} function cells_meta.__newindex(tbl, key, val) print('newindex') local cell = rawget(tbl, key.x) if not cell then rawset(tbl, key.x, {[key.y] = val}) else rawset(cell, key.y, val) end end function cells_meta.__index(tbl, key) local cell = rawget(tbl, key.x) if not cell then local ret = setmetatable({}, {__mode = "kv"}) cell = {[key.y] = ret} rawset(tbl, key.x, cell) return ret end local ret = rawget(cell, key.y) if not ret then ret = setmetatable({}, {__mode = "kv"}) rawset(cell, key.y, ret) end return ret end local Spatialhash = {} function Spatialhash:init(cell_size) self.cell_size = cell_size or 100 self.cells = setmetatable({}, cells_meta) end function Spatialhash:cellCoords(v) return {x=floor(v.x / self.cell_size), y=floor(v.y / self.cell_size)} end function Spatialhash:cell(v) return self.cells[ self:cellCoords(v) ] end function Spatialhash:insert(obj, ul, lr) local ul = self:cellCoords(ul) local lr = self:cellCoords(lr) for i = ul.x,lr.x do for k = ul.y,lr.y do end end end function Spatialhash:remove(obj, ul, lr) -- no bbox given. => must check all cells if not ul or not lr then for _,cell in pairs(self.cells) do rawset(cell, obj, nil) end return end local ul = self:cellCoords(ul) local lr = self:cellCoords(lr) -- else: remove only from bbox for i = ul.x,lr.x do for k = ul.y,lr.y do rawset(self.cells[{x=i,y=k}], obj, nil) end end end -- update an objects position function Spatialhash:update(obj, ul_old, lr_old, ul_new, lr_new) local ul_old, lr_old = self:cellCoords(ul_old), self:cellCoords(lr_old) local ul_new, lr_new = self:cellCoords(ul_new), self:cellCoords(lr_new) if ul_old.x == ul_new.x and ul_old.y == ul_new.y and lr_old.x == lr_new.x and lr_old.y == lr_new.y then return end for i = ul_old.x,lr_old.x do for k = ul_old.y,lr_old.y do rawset(self.cells[{x=i,y=k}], obj, nil) end end for i = ul_new.x,lr_new.x do for k = ul_new.y,lr_new.y do rawset(self.cells[{x=i,y=k}], obj, obj) end end end function Spatialhash:getNeighbors(obj, ul, lr) local ul = self:cellCoords(ul) local lr = self:cellCoords(lr) local set = {} for i = ul.x,lr.x do for k = ul.y,lr.y do local cell = self.cells[{x=i,y=k}] or {} for other,_ in pairs(cell) do rawset(set, other, other) end end end rawset(set, obj, nil) return set end function Spatialhash:draw(how, show_empty, print_key) if show_empty == nil then show_empty = true end for k,cell in pairs(self.cells) do local empty = true (function() for _ in pairs(cell) do empty = false; return end end)() if show_empty or not empty then local x,y = k:match("([^,]+),([^,]+)") x = x * self.cell_size y = y * self.cell_size love.graphics.rectangle(how, x,y, self.cell_size, self.cell_size) if print_key then love.graphics.print(k, x+3,y+3) end end end end return common.class('Spatialhash', Spatialhash)
--[[ Copyright (c) 2011 Matthias Richter Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. Except as contained in this notice, the name(s) of the above copyright holders shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization. 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 floor = math.floor local min, max = math.min, math.max local _PACKAGE = (...):match("^(.+)%.[^%.]+") if not (common and common.class and common.instance) then class_commons = true require(_PACKAGE .. '.class') end -- transparent cell accessor methods -- cells = {[0] = {[0] = <>, [1] = <>, ... }, [1] = {...}, ...} local cells_meta = {} function cells_meta.__newindex(tbl, key, val) local cell = rawget(tbl, key.x) if not cell then rawset(tbl, key.x, {[key.y] = val}) else rawset(cell, key.y, val) end end function cells_meta.__index(tbl, key) local cell = rawget(tbl, key.x) if not cell then local ret = setmetatable({}, {__mode = "kv"}) cell = {[key.y] = ret} rawset(tbl, key.x, cell) return ret end local ret = rawget(cell, key.y) if not ret then ret = setmetatable({}, {__mode = "kv"}) rawset(cell, key.y, ret) end return ret end local Spatialhash = {} function Spatialhash:init(cell_size) self.cell_size = cell_size or 100 self.cells = setmetatable({}, cells_meta) end function Spatialhash:cellCoords(v) return {x=floor(v.x / self.cell_size), y=floor(v.y / self.cell_size)} end function Spatialhash:cell(v) return self.cells[ self:cellCoords(v) ] end function Spatialhash:insert(obj, ul, lr) local ul = self:cellCoords(ul) local lr = self:cellCoords(lr) for i = ul.x,lr.x do for k = ul.y,lr.y do rawset(self.cells[{x=i,y=k}], obj, obj) end end end function Spatialhash:remove(obj, ul, lr) -- no bbox given. => must check all cells if not ul or not lr then for _,cell in pairs(self.cells) do rawset(cell, obj, nil) end return end local ul = self:cellCoords(ul) local lr = self:cellCoords(lr) -- else: remove only from bbox for i = ul.x,lr.x do for k = ul.y,lr.y do rawset(self.cells[{x=i,y=k}], obj, nil) end end end -- update an objects position function Spatialhash:update(obj, ul_old, lr_old, ul_new, lr_new) print('hash:update', obj) local ul_old, lr_old = self:cellCoords(ul_old), self:cellCoords(lr_old) local ul_new, lr_new = self:cellCoords(ul_new), self:cellCoords(lr_new) if ul_old.x == ul_new.x and ul_old.y == ul_new.y and lr_old.x == lr_new.x and lr_old.y == lr_new.y then return end for i = ul_old.x,lr_old.x do for k = ul_old.y,lr_old.y do rawset(self.cells[{x=i,y=k}], obj, nil) end end for i = ul_new.x,lr_new.x do for k = ul_new.y,lr_new.y do rawset(self.cells[{x=i,y=k}], obj, obj) end end end function Spatialhash:getNeighbors(obj, ul, lr) local ul = self:cellCoords(ul) local lr = self:cellCoords(lr) local set = {} for i = ul.x,lr.x do for k = ul.y,lr.y do local cell = self.cells[{x=i,y=k}] or {} for other,_ in pairs(cell) do rawset(set, other, other) end end end rawset(set, obj, nil) return set end function Spatialhash:draw(how, show_empty, print_key) if show_empty == nil then show_empty = true end for k1,v in pairs(self.cells) do for k2,cell in pairs(v) do local empty = true (function() for _ in pairs(cell) do empty = false; return end end)() if show_empty or not empty then local x = k1 * self.cell_size local y = k2 * self.cell_size love.graphics.rectangle(how or 'line', x,y, self.cell_size, self.cell_size) if print_key then love.graphics.print(("%d:%d"):format(k1,k2), x+3,y+3) end end end end end return common.class('Spatialhash', Spatialhash)
Fix issue #10. Fix spatialhash drawing.
Fix issue #10. Fix spatialhash drawing. Shapes were not inserted into the spatial hash when not moved. Shapes set to passive directly after creation would not be in the hash, resulting in no collision reports. Spatialhash drawing updated to the new cell indexing method.
Lua
mit
aswyk/botrot
9aaee24c50b20f3cd87cad6c782fee1e953a1208
src/cli/cli.lua
src/cli/cli.lua
--[[ @cond ___LICENSE___ -- Copyright (c) 2017 Zefiros Software. -- -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -- copies of the Software, and to permit persons to whom the Software is -- furnished to do so, subject to the following conditions: -- -- The above copyright notice and this permission notice shall be included in -- all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -- THE SOFTWARE. -- -- @endcond --]] zpm.cli = {} function zpm.cli.verbose() return _OPTIONS["verbose"] ~= nil end function zpm.cli.showVersion() return _OPTIONS["version"] ~= nil end function zpm.cli.showHelp() return _OPTIONS["help"] ~= nil end function zpm.cli.ci() return _OPTIONS["ci"] or os.getenv("TRAVIS") or os.getenv("APPVEYOR") or os.getenv("CI") end newoption { trigger = "ci", description = "Mark this as an CI build" } if zpm.cli.showHelp() then zpm.util.disableMainScript() end newoption { trigger = "ignore-lock", description = "Act as if there is no lock file available" } newoption { trigger = "skip-lock", description = "Alias for --ignore-lock" } function zpm.cli.force() return _OPTIONS["force"] end newoption { trigger = "force", description = "Force installation of already extracted dependencies" } function zpm.cli.ignoreLock() return _OPTIONS["ignore-lock"] or _OPTIONS["skip-lock"] end newoption { trigger = "cached-only", description = "Only use the cached repositories (usefull on slow connections)" } function zpm.cli.cachedOnly() return _OPTIONS["cached-only"] end newoption { trigger = "update", description = "Updates the dependencies to the newest version given the constraints" } function zpm.cli.update() return _OPTIONS["update"] ~= nil end function zpm.cli.profile() if (_OPTIONS["profile"] ~= "none" or _ACTION == "profile") then return _OPTIONS["profile"] end return false end newoption { trigger = "profile", description = "Profiles the given commands", value = "pepper_fish", default = "none", allowed = { {"none", "no profiling"}, {"pepper_fish", "the default profiler"}, {"ProFi", ""} } } if zpm.cli.profile() then newaction { trigger = "profile", description = "Profiles" } end newoption { trigger = "always-trust", description = "Allow trust execution of new repository code" } function zpm.cli.askTrustStoreConfirmation(question, yesFunc, noFunc) interactf("%s Use '--always-trust' to always accept (Y [enter]/n)?", question) local answer = not zpm.cli.n() and (zpm.cli.y() or zpm.cli.noInteractive() or _OPTIONS["allow-trust"] or io.read()) interactf(answer) print(answer == "Y" or answer == "y" or answer == "" or answer == true) interactf(type(answer)) if answer == "Y" or answer == "y" or answer == "" or answer == true then return yesFunc() else return noFunc() end end newoption { trigger = "allow-module", description = "Allow modules to install" } function zpm.cli.askModuleConfirmation(question, yesFunc, noFunc) interactf("%s, use '--allow-module' to always accept (Y [enter]/n)?", question) local answer = not zpm.cli.n() and (zpm.cli.y() or zpm.cli.noInteractive() or _OPTIONS["allow-module"] or io.read()) interactf(answer) if answer == "Y" or answer == "y" or answer == "" or answer == true then return yesFunc() else return noFunc() end end newoption { trigger = "y", description = "Always use 'y' to accept CLI interactions" } function zpm.cli.y() return _OPTIONS["y"] or zpm.cli.ci() end newoption { trigger = "n", description = "Always use 'n' to decline CLI interactions" } function zpm.cli.n() return _OPTIONS["n"] end newoption { trigger = "no-interactive", description = "Use this option if you can't interact with zpm" } function zpm.cli.noInteractive() return _OPTIONS["no-interactive"] or zpm.cli.ci() end function zpm.cli.askConfirmation(question, yesFunc, noFunc, pred) pred = iif(pred ~= nil, pred, function() return false end) if not (zpm.cli.y() or zpm.cli.n() or zpm.cli.noInteractive()) then interactf("\n%s (Y [enter]/n)\nUse '--y' or '--no-interactive' to always accept or '--n' to decline.", question) end local answer = not zpm.cli.n() and (zpm.cli.y() or zpm.cli.noInteractive() or pred() or io.read()) interactf(answer) if answer == true or answer == "Y" or answer == "y" or answer == "" then return yesFunc() else return noFunc() end end
--[[ @cond ___LICENSE___ -- Copyright (c) 2017 Zefiros Software. -- -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -- copies of the Software, and to permit persons to whom the Software is -- furnished to do so, subject to the following conditions: -- -- The above copyright notice and this permission notice shall be included in -- all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -- THE SOFTWARE. -- -- @endcond --]] zpm.cli = {} function zpm.cli.verbose() return _OPTIONS["verbose"] ~= nil end function zpm.cli.showVersion() return _OPTIONS["version"] ~= nil end function zpm.cli.showHelp() return _OPTIONS["help"] ~= nil end function zpm.cli.ci() return _OPTIONS["ci"] or os.getenv("TRAVIS") or os.getenv("APPVEYOR") or os.getenv("CI") end newoption { trigger = "ci", description = "Mark this as an CI build" } if zpm.cli.showHelp() then zpm.util.disableMainScript() end newoption { trigger = "ignore-lock", description = "Act as if there is no lock file available" } newoption { trigger = "skip-lock", description = "Alias for --ignore-lock" } function zpm.cli.force() return _OPTIONS["force"] end newoption { trigger = "force", description = "Force installation of already extracted dependencies" } function zpm.cli.ignoreLock() return _OPTIONS["ignore-lock"] or _OPTIONS["skip-lock"] end newoption { trigger = "cached-only", description = "Only use the cached repositories (usefull on slow connections)" } function zpm.cli.cachedOnly() return _OPTIONS["cached-only"] end newoption { trigger = "update", description = "Updates the dependencies to the newest version given the constraints" } function zpm.cli.update() return _OPTIONS["update"] ~= nil end function zpm.cli.profile() if (_OPTIONS["profile"] ~= "none" or _ACTION == "profile") then return _OPTIONS["profile"] end return false end newoption { trigger = "profile", description = "Profiles the given commands", value = "pepper_fish", default = "none", allowed = { {"none", "no profiling"}, {"pepper_fish", "the default profiler"}, {"ProFi", ""} } } if zpm.cli.profile() then newaction { trigger = "profile", description = "Profiles" } end newoption { trigger = "always-trust", description = "Allow trust execution of new repository code" } function zpm.cli.askTrustStoreConfirmation(question, yesFunc, noFunc) interactf("%s Use '--always-trust' to always accept (Y [enter]/n)?", question) local answer = not zpm.cli.n() and (zpm.cli.y() or zpm.cli.noInteractive() or _OPTIONS["allow-trust"] or io.read()) if answer == "Y" or answer == "y" or answer == "" or answer == true or answer == "true" then return yesFunc() else return noFunc() end end newoption { trigger = "allow-module", description = "Allow modules to install" } function zpm.cli.askModuleConfirmation(question, yesFunc, noFunc) interactf("%s, use '--allow-module' to always accept (Y [enter]/n)?", question) local answer = not zpm.cli.n() and (zpm.cli.y() or zpm.cli.noInteractive() or _OPTIONS["allow-module"] or io.read()) interactf(answer) if answer == "Y" or answer == "y" or answer == "" or answer == true or answer == "true" then return yesFunc() else return noFunc() end end newoption { trigger = "y", description = "Always use 'y' to accept CLI interactions" } function zpm.cli.y() return _OPTIONS["y"] or zpm.cli.ci() end newoption { trigger = "n", description = "Always use 'n' to decline CLI interactions" } function zpm.cli.n() return _OPTIONS["n"] end newoption { trigger = "no-interactive", description = "Use this option if you can't interact with zpm" } function zpm.cli.noInteractive() return _OPTIONS["no-interactive"] or zpm.cli.ci() end function zpm.cli.askConfirmation(question, yesFunc, noFunc, pred) pred = iif(pred ~= nil, pred, function() return false end) if not (zpm.cli.y() or zpm.cli.n() or zpm.cli.noInteractive()) then interactf("\n%s (Y [enter]/n)\nUse '--y' or '--no-interactive' to always accept or '--n' to decline.", question) end local answer = not zpm.cli.n() and (zpm.cli.y() or zpm.cli.noInteractive() or pred() or io.read()) interactf(answer) if answer == true or answer == "true" or answer == "Y" or answer == "y" or answer == "" then return yesFunc() else return noFunc() end end
Fix the string casting
Fix the string casting
Lua
mit
Zefiros-Software/ZPM
46a851b286581f05b3d8d77fa63f522bbab53ad3
packages/bidi.lua
packages/bidi.lua
SILE.registerCommand("thisframeLTR", function(options, content) SILE.typesetter.frame.direction = "LTR" SILE.typesetter:leaveHmode() SILE.typesetter.frame:newLine() end); SILE.registerCommand("thisframedirection", function(options, content) SILE.typesetter.frame.direction = SU.required(options, "direction", "frame direction") SILE.typesetter:leaveHmode() SILE.typesetter.frame:init() end); SILE.registerCommand("thisframeRTL", function(options, content) SILE.typesetter.frame.direction = "RTL" SILE.typesetter:leaveHmode() SILE.typesetter.frame:newLine() end); local bidi = require("unicode-bidi-algorithm") local bidiBoxupNodes = function (self) local nl = self.state.nodes local newNl = {} for i=1,#nl do if nl[i]:isUnshaped() then local chunks = SU.splitUtf8(nl[i].text) for j = 1,#chunks do newNl[#newNl+1] = SILE.nodefactory.newUnshaped({text = chunks[j], options = nl[i].options }) end else newNl[#newNl+1] = nl[i] end end nl = bidi.process(newNl, self.frame) -- Reconstitute. This code is a bit dodgy. Currently we have a bunch of nodes -- each with one Unicode character in them. Sending that to the shaper one-at-a-time -- will cause, e.g. Arabic letters to all come out as isolated forms. But equally, -- we can't send the whole lot to the shaper at once because Harfbuzz doesn't itemize -- them for us, spaces have already been converted to glue, and so on. So we combine -- characters with equivalent options/character sets into a single node. newNL = {nl[1]} local ncount = 1 -- small optimization, save indexing newNL every time for i=2,#nl do local this = nl[i] local prev = newNL[ncount] if not this:isUnshaped() or not prev:isUnshaped() then ncount = ncount + 1 newNL[ncount] = this -- now both are unshaped, compare them elseif SILE.font._key(this.options) == SILE.font._key(prev.options) then -- same font prev.text = prev.text .. this.text else ncount = ncount + 1 newNL[ncount] = this end end self.state.nodes = newNL return SILE.defaultTypesetter.boxUpNodes(self) end SILE.typesetter.boxUpNodes = bidiBoxupNodes SILE.registerCommand("bidi-on", function(options, content) SILE.typesetter.boxUpNodes = bidiBoxupNodes end) SILE.registerCommand("bidi-off", function(options, content) SILE.typesetter.boxUpNodes = SILE.defaultTypesetter.boxUpNodes end) return { documentation = [[\begin{document} Scripts like the Latin alphabet you are currently reading are normally written left to right; however, some scripts, such as Arabic and Hebrew, are written right to left. The \code{bidi} package, which is loaded by default, provides SILE with the ability to correctly typeset right-to-left text and also documents which mix right-to-left and left-to-right typesetting. Because it is loaded by default, you can use both LTR and RTL text within a paragraph and SILE will ensure that the output characters appear in the correct order. The \code{bidi} package provides two commands, \command{\\thisframeLTR} and \command{\\thisframeRTL}, which set the default text direction for the current frame. That is, if you tell SILE that a frame is RTL, the text will start in the right margin and proceed leftward. It also provides the commands \command{\\bidi-off} and \command{\\bidi-on}, which allow you to trade off bidirectional support for a dubious increase in speed. \end{document}]] }
SILE.registerCommand("thisframeLTR", function(options, content) SILE.typesetter.frame.direction = "LTR" SILE.typesetter:leaveHmode() SILE.typesetter.frame:newLine() end); SILE.registerCommand("thisframedirection", function(options, content) SILE.typesetter.frame.direction = SU.required(options, "direction", "frame direction") SILE.typesetter:leaveHmode() SILE.typesetter.frame:init() end); SILE.registerCommand("thisframeRTL", function(options, content) SILE.typesetter.frame.direction = "RTL" SILE.typesetter:leaveHmode() SILE.typesetter.frame:newLine() end); local bidi = require("unicode-bidi-algorithm") local function has_mixed_direction_material(v) local linetext = {} if not v.nodes then return false end for i = 1,#(v.nodes) do linetext[#linetext+1] = v.nodes[i].text end linetext = table.concat(linetext, "") chunks = SU.splitUtf8(linetext) local linedir for i = 1,#chunks do local d = bidi.get_bidi_type(SU.codepoint(chunks[i])) if d == "r" or d == "l" or d == "al" or d == "en" then if not linedir then linedir = d end if d ~= linedir then return true end end end return false end local reorder = function(n, self) local nl = n.nodes local newNl = {} for i=1,#nl do if not nl[i].text then newNl[#newNl+1] = nl[i] else local chunks = SU.splitUtf8(nl[i].text) for j = 1,#chunks do newNl[#newNl+1] = SILE.nodefactory.newUnshaped({text = chunks[j], options = nl[i].options }) end end end nl = bidi.process(newNl, self.frame) -- Reconstitute. This code is a bit dodgy. Currently we have a bunch of nodes -- each with one Unicode character in them. Sending that to the shaper one-at-a-time -- will cause, e.g. Arabic letters to all come out as isolated forms. But equally, -- we can't send the whole lot to the shaper at once because Harfbuzz doesn't itemize -- them for us, spaces have already been converted to glue, and so on. So we combine -- characters with equivalent options/character sets into a single node. newNL = {nl[1]} local ncount = 1 -- small optimization, save indexing newNL every time for i=2,#nl do local this = nl[i] local prev = newNL[ncount] if not this:isUnshaped() or not prev:isUnshaped() then ncount = ncount + 1 newNL[ncount] = this -- now both are unshaped, compare them elseif SILE.font._key(this.options) == SILE.font._key(prev.options) then -- same font prev.text = prev.text .. this.text else ncount = ncount + 1 newNL[ncount] = this end end for i = 1,#newNL do if newNL[i]:isUnshaped() then newNL[i] = newNL[i]:shape() end end n.nodes = newNL -- XXX Fix line ratio? end local bidiBoxupNodes = function (self) local vboxlist = SILE.defaultTypesetter.boxUpNodes(self) -- Scan for out-of-direction material for i=1,#vboxlist do local v = vboxlist[i] if has_mixed_direction_material(v) then reorder(v, self) end end return vboxlist end SILE.typesetter.boxUpNodes = bidiBoxupNodes SILE.registerCommand("bidi-on", function(options, content) SILE.typesetter.boxUpNodes = bidiBoxupNodes end) SILE.registerCommand("bidi-off", function(options, content) SILE.typesetter.boxUpNodes = SILE.defaultTypesetter.boxUpNodes end) return { documentation = [[\begin{document} Scripts like the Latin alphabet you are currently reading are normally written left to right; however, some scripts, such as Arabic and Hebrew, are written right to left. The \code{bidi} package, which is loaded by default, provides SILE with the ability to correctly typeset right-to-left text and also documents which mix right-to-left and left-to-right typesetting. Because it is loaded by default, you can use both LTR and RTL text within a paragraph and SILE will ensure that the output characters appear in the correct order. The \code{bidi} package provides two commands, \command{\\thisframeLTR} and \command{\\thisframeRTL}, which set the default text direction for the current frame. That is, if you tell SILE that a frame is RTL, the text will start in the right margin and proceed leftward. It also provides the commands \command{\\bidi-off} and \command{\\bidi-on}, which allow you to trade off bidirectional support for a dubious increase in speed. \end{document}]] }
Attempted reworking of bidi to fix line break problem. (See #137)
Attempted reworking of bidi to fix line break problem. (See #137)
Lua
mit
simoncozens/sile,alerque/sile,neofob/sile,alerque/sile,alerque/sile,simoncozens/sile,simoncozens/sile,neofob/sile,alerque/sile,neofob/sile,neofob/sile,simoncozens/sile
0d82a4f3c5c248b2cc1a5e8aacd8b8245c4d4162
config/nvim/lua/init/null_ls.lua
config/nvim/lua/init/null_ls.lua
local null_ls = require("null-ls") null_ls.setup({ sources = { null_ls.builtins.completion.spell, null_ls.builtins.diagnostics.eslint, null_ls.builtins.formatting.black, null_ls.builtins.formatting.clang_format, null_ls.builtins.formatting.elm_format, null_ls.builtins.formatting.eslint, null_ls.builtins.formatting.pg_format, null_ls.builtins.formatting.prettier, null_ls.builtins.formatting.rubocop, null_ls.builtins.formatting.shfmt.with({ extra_args = { "-i", "2" } }), null_ls.builtins.formatting.stylua, null_ls.builtins.formatting.taplo, null_ls.builtins.formatting.terraform_fmt, }, })
local null_ls = require("null-ls") null_ls.setup({ sources = { null_ls.builtins.completion.spell, null_ls.builtins.diagnostics.eslint, null_ls.builtins.formatting.black, null_ls.builtins.formatting.clang_format, null_ls.builtins.formatting.elm_format, null_ls.builtins.formatting.eslint, null_ls.builtins.formatting.pg_format, null_ls.builtins.formatting.prettier, null_ls.builtins.formatting.rubocop, null_ls.builtins.formatting.shfmt.with({ extra_args = { "-i", "2" }, extra_filetypes = { "zsh" }, }), null_ls.builtins.formatting.stylua, null_ls.builtins.formatting.taplo, null_ls.builtins.formatting.terraform_fmt, }, })
Fix zsh formatting
Fix zsh formatting
Lua
unlicense
raviqqe/dotfiles
71b32cb698baa79ece2b29196a07a2debd7b910d
kong/dao/schemas/upstreams.lua
kong/dao/schemas/upstreams.lua
local Errors = require "kong.dao.errors" local utils = require "kong.tools.utils" local DEFAULT_SLOTS = 100 local SLOTS_MIN, SLOTS_MAX = 10, 2^16 local SLOTS_MSG = "number of slots must be between " .. SLOTS_MIN .. " and " .. SLOTS_MAX return { table = "upstreams", primary_key = {"id"}, fields = { id = { type = "id", dao_insert_value = true, required = true, }, created_at = { type = "timestamp", immutable = true, dao_insert_value = true, required = true, }, name = { -- name is a hostname like name that can be referenced in an `upstream_url` field type = "string", unique = true, required = true, }, hash_on = { -- primary hash-key type = "string", default = "none", enum = { "none", "consumer", "ip", "header", }, }, hash_fallback = { -- secondary key, if primary fails type = "string", default = "none", enum = { "none", "consumer", "ip", "header", }, }, hash_on_header = { -- header name, if `hash_on == "header"` type = "string", }, hash_fallback_header = { -- header name, if `hash_fallback == "header"` type = "string", }, slots = { -- the number of slots in the loadbalancer algorithm type = "number", default = DEFAULT_SLOTS, }, }, self_check = function(schema, config, dao, is_updating) -- check the name local p = utils.normalize_ip(config.name) if not p then return false, Errors.schema("Invalid name; must be a valid hostname") end if p.type ~= "name" then return false, Errors.schema("Invalid name; no ip addresses allowed") end if p.port then return false, Errors.schema("Invalid name; no port allowed") end if config.hash_on_header then local ok, err = utils.validate_header_name(config.hash_on_header) if not ok then return false, Errors.schema("Header: " .. err) end end if config.hash_fallback_header then local ok, err = utils.validate_header_name(config.hash_fallback_header) if not ok then return false, Errors.schema("Header: " .. err) end end if (config.hash_on == "header" and not config.hash_on_header) or (config.hash_fallback == "header" and not config.hash_fallback_header) then return false, Errors.schema("Hashing on 'header', " .. "but no header name provided") end if config.hash_on == "none" then if config.hash_fallback ~= "none" then return false, Errors.schema("Cannot set fallback if primary " .. "'hash_on' is not set") end else if config.hash_on == config.hash_fallback then if config.hash_on ~= "header" then return false, Errors.schema("Cannot set fallback and primary " .. "hashes to the same value") else local upper_hash_on = config.hash_on_header:upper() local upper_hash_fallback = config.hash_fallback_header:upper() if upper_hash_on == upper_hash_fallback then return false, Errors.schema("Cannot set fallback and primary ".. "hashes to the same value") end end end end -- check the slots number if config.slots < SLOTS_MIN or config.slots > SLOTS_MAX then return false, Errors.schema(SLOTS_MSG) end return true end, }
local Errors = require "kong.dao.errors" local utils = require "kong.tools.utils" local DEFAULT_SLOTS = 100 local SLOTS_MIN, SLOTS_MAX = 10, 2^16 local SLOTS_MSG = "number of slots must be between " .. SLOTS_MIN .. " and " .. SLOTS_MAX return { table = "upstreams", primary_key = {"id"}, fields = { id = { type = "id", dao_insert_value = true, required = true, }, created_at = { type = "timestamp", immutable = true, dao_insert_value = true, required = true, }, name = { -- name is a hostname like name that can be referenced in an `upstream_url` field type = "string", unique = true, required = true, }, hash_on = { -- primary hash-key type = "string", default = "none", enum = { "none", "consumer", "ip", "header", }, }, hash_fallback = { -- secondary key, if primary fails type = "string", default = "none", enum = { "none", "consumer", "ip", "header", }, }, hash_on_header = { -- header name, if `hash_on == "header"` type = "string", }, hash_fallback_header = { -- header name, if `hash_fallback == "header"` type = "string", }, slots = { -- the number of slots in the loadbalancer algorithm type = "number", default = DEFAULT_SLOTS, }, }, self_check = function(schema, config, dao, is_updating) -- check the name if config.name then local p = utils.normalize_ip(config.name) if not p then return false, Errors.schema("Invalid name; must be a valid hostname") end if p.type ~= "name" then return false, Errors.schema("Invalid name; no ip addresses allowed") end if p.port then return false, Errors.schema("Invalid name; no port allowed") end end if config.hash_on_header then local ok, err = utils.validate_header_name(config.hash_on_header) if not ok then return false, Errors.schema("Header: " .. err) end end if config.hash_fallback_header then local ok, err = utils.validate_header_name(config.hash_fallback_header) if not ok then return false, Errors.schema("Header: " .. err) end end if (config.hash_on == "header" and not config.hash_on_header) or (config.hash_fallback == "header" and not config.hash_fallback_header) then return false, Errors.schema("Hashing on 'header', " .. "but no header name provided") end if config.hash_on and config.hash_fallback then if config.hash_on == "none" then if config.hash_fallback ~= "none" then return false, Errors.schema("Cannot set fallback if primary " .. "'hash_on' is not set") end else if config.hash_on == config.hash_fallback then if config.hash_on ~= "header" then return false, Errors.schema("Cannot set fallback and primary " .. "hashes to the same value") else local upper_hash_on = config.hash_on_header:upper() local upper_hash_fallback = config.hash_fallback_header:upper() if upper_hash_on == upper_hash_fallback then return false, Errors.schema("Cannot set fallback and primary ".. "hashes to the same value") end end end end end if config.slots then -- check the slots number if config.slots < SLOTS_MIN or config.slots > SLOTS_MAX then return false, Errors.schema(SLOTS_MSG) end end return true end, }
fix(dao) support self_check() on incomplete upstream objects
fix(dao) support self_check() on incomplete upstream objects
Lua
apache-2.0
Kong/kong,Mashape/kong,Kong/kong,Kong/kong,jebenexer/kong
8079ff172577e07dbb0a9606e617d3740159159b
framework/db/redis/cluster.lua
framework/db/redis/cluster.lua
local redis_client = require "framework.db.redis.client" local flexihash = require "framework.libs.flexihash" local DEFAULT_CONNECT_TIMEOUT = 2000 local Cluster = { flexihash = flexihash:instance() } Cluster.__index = Cluster local clusters = {} function Cluster:instance(name, config) if clusters[name] then return clusters[name] end local instance = setmetatable({ clients = {}, }, Cluster) for i, v in pairs(config) do local client = redis_client:new(v.host, v.port, v.conn_timeout, v.pool_size, v.keepalive_time, v.pwd) instance.clients[tostring(client)] = client end for i, client in pairs(instance.clients) do self.flexihash:add_target(tostring(client)) end clusters[name] = instance return instance end function Cluster:query(cmd, ...) local key = select(1, ...) local target = self.flexihash:lookup(key) local client = self.clients[target] res = client:query(cmd, ...) return res end return Cluster
local redis_client = require "framework.db.redis.client" local flexihash = require "framework.libs.flexihash" local DEFAULT_CONNECT_TIMEOUT = 2000 local Cluster = {} Cluster.__index = Cluster local clusters = {} function Cluster:instance(name, config) if clusters[name] then return clusters[name] end local instance = setmetatable({ clients = {}, flexihash = flexihash:instance(), }, Cluster) for i, v in pairs(config) do local client = redis_client:new(v.host, v.port, v.conn_timeout, v.pool_size, v.keepalive_time, v.pwd) instance.clients[tostring(client)] = client end for i, client in pairs(instance.clients) do instance.flexihash:add_target(tostring(client)) end clusters[name] = instance return instance end function Cluster:query(cmd, ...) local key = select(1, ...) local target = self.flexihash:lookup(key) local client = self.clients[target] res = client:query(cmd, ...) return res end return Cluster
fix bug: move flexihash to instance
fix bug: move flexihash to instance
Lua
bsd-2-clause
nicholaskh/strawberry,nicholaskh/strawberry
ce7097edbfaaa32d64d2355ec9d746998f34ee45
vanilla/v/router.lua
vanilla/v/router.lua
-- perf local error = error local tconcat = table.concat local function tappend(t, v) t[#t+1] = v end -- init Router and set routes local Router = {} function Router:new(request) local instance = { routes = {require('vanilla.v.routes.simple'):new(request)}, request = request } setmetatable(instance, {__index = self}) return instance end function Router:addRoute(route, only_one) if route ~= nil then if only_one then self.routes = {} end tappend(self.routes, route) end end function Router:removeRoute(route_name) for i,route in ipairs(self.routes) do if (tostring(route) == route_name) then self.routes[i] = nil end end end function Router:getRoutes() return self.routes end function Router:getCurrentRoute() return self.current_route end function Router:getCurrentRouteName() return tostring(self.current_route) end local function route_match(route) return route:match() end function Router:route() if #self.routes >= 1 then local route_err = {} for k,route in ipairs(self.routes) do local ok, controller_name_or_error, action = pcall(route_match, route) if ok and controller_name_or_error then self.current_route = route return controller_name_or_error, action else route_err[k] = controller_name_or_error end end error({ code = 201, msg = { Routes_No_Match = #self.routes .. "Routes All Didn't Match. Errs Like: " .. tconcat( route_err, ", ")}}) end error({ code = 201, msg = {Empty_Routes = 'Null routes added.'}}) end return Router
-- perf local error = error local tconcat = table.concat local function tappend(t, v) t[#t+1] = v end -- init Router and set routes local Router = {} function Router:new(request) local instance = { routes = {require('vanilla.v.routes.simple'):new(request)}, request = request } setmetatable(instance, {__index = self}) return instance end function Router:addRoute(route, only_one) if route ~= nil then if only_one then self.routes = {} end tappend(self.routes, route) end end function Router:removeRoute(route_name) for i,route in ipairs(self.routes) do if (tostring(route) == route_name) then self.routes[i] = false end end end function Router:getRoutes() return self.routes end function Router:getCurrentRoute() return self.current_route end function Router:getCurrentRouteName() return tostring(self.current_route) end local function route_match(route) return route:match() end function Router:route() if #self.routes >= 1 then local alive_route_num = 0 local route_err = {} for k,route in ipairs(self.routes) do if route then alive_route_num = alive_route_num + 1 local ok, controller_name_or_error, action = pcall(route_match, route) if ok and controller_name_or_error then self.current_route = route return controller_name_or_error, action else route_err[k] = controller_name_or_error end end end error({ code = 201, msg = { Routes_No_Match = alive_route_num .. "Routes All Didn't Match. Errs Like: " .. tconcat( route_err, ", ")}}) end error({ code = 201, msg = {Empty_Routes = 'Null routes added.'}}) end return Router
fix a bug in router for route remove
fix a bug in router for route remove self.routes[i] = nil bring a empty hole to the routes table
Lua
mit
lhmwzy/vanilla,idevz/vanilla,lhmwzy/vanilla,idevz/vanilla,lhmwzy/vanilla,lhmwzy/vanilla
44ea28c8acc91dfcc970e100f063ccb5ca46e711
src/cosy/helper.lua
src/cosy/helper.lua
local _ = require "cosy.util.string" local ignore = require "cosy.util.ignore" local Data = require "cosy.data" local Tag = require "cosy.tag" local INSTANCE = Tag.INSTANCE local POSITION = Tag.POSITION local SELECTED = Tag.SELECTED local HIGHLIGHTED = Tag.HIGHLIGHTED local global = _ENV or _G local meta = global.meta local cosy = global.cosy local Helper = {} function Helper.configure_editor (url) meta.editor = url end function Helper.configure_server (url, data) -- Remove trailing slash: if url [#url] == "/" then url = url:sub (1, #url-1) end -- Store: meta.servers [url] = { username = data.username, password = data.password, } end function Helper.resource (url) return cosy [url] end function Helper.id (x) assert (Data.is (x)) while true do local y = Data.dereference (x) if not Data.is (y) then return tostring (x) end x = y end end function Helper.model (url) return cosy [url] end function Helper.instantiate (model, target_type, data) assert (Data.is (target_type)) model [#model + 1] = target_type * { [INSTANCE] = true, } local result = model [#model] for k, v in pairs (data) do result [k] = v end return result end function Helper.create (model, source, link_type, target_type, data) ignore (link_type, target_type) local place_type = model.place_type local transition_type = model.transition_type local arc_type = model.arc_type local target if Helper.is_place (source) then model [#model + 1] = transition_type * {} target = model [#model] elseif Helper.is_transition (source) then model [#model + 1] = place_type * {} target = model [#model] else return end for k, v in pairs (data) do target [k] = v end model [#model + 1] = arc_type * { source = source, target = target, } return target end function Helper.remove (target) local model = target / 2 if Helper.is_place (target) or Helper.is_transition (target) then for _, x in pairs (model) do if Data.dereference (x.source) == target or Data.dereference (x.target) == target then Data.clear (x) end end Data.clear (target) elseif Helper.is_arc (target) then Data.clear (target) end end function Helper.types (model) return { place_type = model.place_type, transition_type = model.transition_type, arc_type = model.arc_type, } end function Helper.is (x, y) return Data.value (x [tostring (y)]) end function Helper.is_place (x) return Helper.is (x, (x / 2).place_type) end function Helper.is_transition (x) return Helper.is (x, (x / 2).transition_type) end function Helper.is_arc (x) return Helper.is (x, (x / 2).arc_type) end function Helper.get_name (x) return Data.value (x.name) end function Helper.set_name (x, value) x.name = value end function Helper.get_token (x) return Data.value (x.token) end function Helper.set_token (x, value) x.token = value end function Helper.get_position (x) return Data.value (x [POSITION]) end function Helper.set_position (x, value) x [POSITION] = value end function Helper.is_selected (x) return Data.value (x [SELECTED]) -- FIXME end function Helper.select (x) x [SELECTED] = true end function Helper.deselect (x) x [SELECTED] = nil end function Helper.is_highlighted (x) return Data.value (x [HIGHLIGHTED]) -- FIXME end function Helper.highlight (x) x [HIGHLIGHTED] = true end function Helper.unhighlight (x) x [HIGHLIGHTED] = nil end function Helper.source (x) return x.source end function Helper.target (x) return x.target end return Helper
local _ = require "cosy.util.string" local ignore = require "cosy.util.ignore" local Data = require "cosy.data" local Tag = require "cosy.tag" local INSTANCE = Tag.INSTANCE local POSITION = Tag.POSITION local SELECTED = Tag.SELECTED local HIGHLIGHTED = Tag.HIGHLIGHTED local global = _ENV or _G local meta = global.meta local cosy = global.cosy local Helper = {} function Helper.configure_editor (url) meta.editor = url end function Helper.configure_server (url, data) -- Remove trailing slash: if url [#url] == "/" then url = url:sub (1, #url-1) end -- Store: meta.servers [url] = { username = data.username, password = data.password, } end function Helper.resource (url) return cosy [url] end function Helper.id (x) assert (Data.is (x)) while true do local y = Data.dereference (x) if not Data.is (y) then return tostring (x) end x = y end end function Helper.model (url) return cosy [url] end function Helper.instantiate (model, target_type, data) assert (Data.is (target_type)) model [#model + 1] = target_type * { [INSTANCE] = true, } local result = model [#model] for k, v in pairs (data or {}) do result [k] = v end return result end function Helper.create (model, source, link_type, target_type, data) ignore (link_type, target_type) local place_type = model.place_type local transition_type = model.transition_type local arc_type = model.arc_type local target if Helper.is_place (source) then model [#model + 1] = transition_type * {} target = model [#model] elseif Helper.is_transition (source) then model [#model + 1] = place_type * {} target = model [#model] else return end for k, v in pairs (data or {}) do target [k] = v end model [#model + 1] = arc_type * { source = source, target = target, } return target end function Helper.remove (target) local model = target / 2 if Helper.is_place (target) or Helper.is_transition (target) then for _, x in pairs (model) do if Helper.source (x) == target or Helper.target (x) == target then Data.clear (x) end end Data.clear (target) elseif Helper.is_arc (target) then Data.clear (target) end end function Helper.types (model) return { place_type = model.place_type, transition_type = model.transition_type, arc_type = model.arc_type, } end function Helper.is (x, y) return Data.value (x [tostring (y)]) end function Helper.is_place (x) return Helper.is (x, (x / 2).place_type) end function Helper.is_transition (x) return Helper.is (x, (x / 2).transition_type) end function Helper.is_arc (x) return Helper.is (x, (x / 2).arc_type) end function Helper.get_name (x) return Data.value (x.name) end function Helper.set_name (x, value) x.name = value end function Helper.get_token (x) return Data.value (x.token) end function Helper.set_token (x, value) x.token = value end function Helper.get_position (x) return Data.value (x [POSITION]) end function Helper.set_position (x, value) x [POSITION] = value end function Helper.is_selected (x) return Data.value (x [SELECTED]) -- FIXME end function Helper.select (x) x [SELECTED] = true end function Helper.deselect (x) x [SELECTED] = nil end function Helper.is_highlighted (x) return Data.value (x [HIGHLIGHTED]) -- FIXME end function Helper.highlight (x) x [HIGHLIGHTED] = true end function Helper.unhighlight (x) x [HIGHLIGHTED] = nil end function Helper.source (x) return Data.dereference (x.source) end function Helper.target (x) return Data.dereference (x.target) end return Helper
Trying to fix remove.
Trying to fix remove.
Lua
mit
CosyVerif/library,CosyVerif/library,CosyVerif/library
43ab66729fbfa2404fd03ed445b4a976b79f93bd
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 -- 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') -- List of enemies enemies = {} -- 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 -- Etc. evil_instrument = 2 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 end elseif dir == Direction.RIGHT then if ship.x < love.graphics.getWidth() - ship.w then ship.x = ship.x + SHIP_SPEED end end -- Move enemies for i,enemy in ipairs(enemies) do enemy.y = enemy.y + ENEMY_SPEED 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 enemies for i,enemy in ipairs(enemies) do anim = enemy.anim 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 enemy animations: ' .. #enemies, 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 = (note * love.graphics.getWidth()) / 128 --x = x * 4 - 800 if x < 0 then x = 0 elseif x > love.graphics.getWidth() then x = love.graphics.getWidth() end --print('note',note,'x',x) 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 local dirty = true while dirty do --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) break end dirty = false end end end ---- function row_changed(row) 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 -- 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') -- List of enemies enemies = {} -- 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 -- Etc. evil_instrument = 2 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 end elseif dir == Direction.RIGHT then if ship.x < love.graphics.getWidth() - ship.w then ship.x = ship.x + SHIP_SPEED end end -- Move enemies for i,enemy in ipairs(enemies) do enemy.y = enemy.y + ENEMY_SPEED 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 enemies for i,enemy in ipairs(enemies) do anim = enemy.anim 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 enemy animations: ' .. #enemies, 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 = (note * love.graphics.getWidth()) / 128 --x = x * 4 - 800 if x < 0 then x = 0 elseif x > love.graphics.getWidth() then x = love.graphics.getWidth() end --print('note',note,'x',x) 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 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) end ---- function tempo_changed(tempo) end
fixed bug where game locked up in pattern change
fixed bug where game locked up in pattern change
Lua
bsd-3-clause
MrEricSir/Modipulate,MrEricSir/Modipulate
c660e1fd2a05682c3aad9a67b903da9692e9f59e
pud/ui/Frame.lua
pud/ui/Frame.lua
local Class = require 'lib.hump.class' local Rect = getClass 'pud.kit.Rect' local MousePressedEvent = getClass 'pud.event.MousePressedEvent' local MouseReleasedEvent = getClass 'pud.event.MouseReleasedEvent' local math_max = math.max local getMousePosition = love.mouse.getPosition local newFramebuffer = love.graphics.newFramebuffer local setColor = love.graphics.setColor local rectangle = love.graphics.rectangle local draw = love.graphics.draw local pushRenderTarget = pushRenderTarget local popRenderTarget = popRenderTarget local nearestPO2 = nearestPO2 local colors = colors local FRAME_UPDATE_TICK = 1/60 -- Frame -- Basic UI Element local Frame = Class{name='Frame', inherits=Rect, function(self, ...) Rect.construct(self, ...) self._children = {} self._accum = 0 self:_drawFB() InputEvents:register(self, {MousePressedEvent, MouseReleasedEvent}) end } -- destructor function Frame:destroy() for k,v in pairs(self._children) do self._children[k]:destroy() self._children[k] = nil end self._children = nil self._ffb = nil self._bfb = nil self._curStyle = nil if self._normalStyle then self._normalStyle:destroy() self._normalStyle = nil end if self._hoverStyle then self._hoverStyle:destroy() self._hoverStyle = nil end if self._activeStyle then self._activeStyle:destroy() self._activeStyle = nil end self._hovered = nil self._mouseDown = nil self._accum = nil Rect.destroy(self) end -- MousePressedEvent - check if the event occurred within this frame function Frame:MousePressedEvent(e) self._mouseDown = true local x, y = e:getPosition() if self:containsPoint(x, y) then local button = e:getButton() local mods = e:getModifiers() self:onPress(button, mods) end end -- MouseReleasedEvent - check if the event occurred within this frame function Frame:MouseReleasedEvent(e) self._mouseDown = false local x, y = e:getPosition() local button = e:getButton() local mods = e:getModifiers() self:onRelease(button, mods, self:containsPoint(x, y)) end -- add a child function Frame:addChild(frame) verifyClass(Frame, frame) local num = #self._children self._children[num+1] = frame end -- remove a child function Frame:removeChild(frame) local num = #self._children local newChildren = {} local count = 0 for i=1,num do local child = self._children[i] if child ~= frame then count = count + 1 newChildren[count] = child end self._children[i] = nil end self._children = newChildren end -- get an appropriately sized PO2 framebuffer function Frame:_getFramebuffer() local size = nearestPO2(math_max(self:getWidth(), self:getHeight())) local fb = newFramebuffer(size, size) return fb end -- update - check for mouse hover function Frame:update(dt, x, y) self._accum = self._accum + dt if self._accum > FRAME_UPDATE_TICK then self._accum = 0 if nil == x or nil == y then x, y = getMousePosition() end if self:containsPoint(x, y) then if not self._hovered then self:onHoverIn(x, y) end self._hovered = true else if self._hovered then self:onHoverOut(x, y) end self._hovered = false end local num = #self._children for i = 1,num do local child = self._children[i] child:update(dt, x, y) end end end -- onHoverIn - called when the mouse starts hovering over the frame function Frame:onHoverIn(x, y) self._curStyle = self._hoverStyle or self._normalStyle self:_drawFB() end -- onHoverOut - called when the mouse stops hovering over the frame function Frame:onHoverOut(x, y) if not self._mouseDown then self._curStyle = self._normalStyle end self:_drawFB() end -- onPress - called when the mouse is pressed inside the frame function Frame:onPress(button, mods) self._curStyle = self._activeStyle or self._hoverStyle or self._normalStyle self:_drawFB() end -- onRelease - called when the mouse is released inside the frame function Frame:onRelease(button, mods, wasInside) if self._hovered then self._curStyle = self._hoverStyle or self._normalStyle else self._curStyle = self._normalStyle end self:_drawFB() end -- set the given style function Frame:_setStyle(which, style) verifyClass('pud.ui.Style', style) self[which] = style self._curStyle = self._curStyle or style self:_drawFB() end -- set/get normal style function Frame:setNormalStyle(style) self:_setStyle('_normalStyle', style) end function Frame:getNormalStyle() return self._normalStyle end -- set/get hover style function Frame:setHoverStyle(style) self:_setStyle('_hoverStyle', style) end function Frame:getHoverStyle() return self._hoverStyle end -- set/get active style function Frame:setActiveStyle(style) self:_setStyle('_activeStyle', style) end function Frame:getActiveStyle() return self._activeStyle end -- draw the frame to framebuffer (including all children) function Frame:_drawFB() self._bfb = self._bfb or self:_getFramebuffer() pushRenderTarget(self._bfb) self:_drawBackground() popRenderTarget() self._ffb, self._bfb = self._bfb, self._ffb end function Frame:_drawBackground() if self._curStyle then local color = self._curStyle:getColor() local image = self._curStyle:getImage() if color then setColor(color) if image then -- TODO: draw image else -- draw background rectangle if color was specified rectangle('fill', 0, 0, self._w, self._h) end end end end -- draw the framebuffer and all child framebuffers function Frame:draw(offsetX, offsetY) if self._ffb then offsetX = offsetX or 0 offsetY = offsetY or 0 local drawX, drawY = self._x + offsetX, self._y + offsetY setColor(colors.WHITE) draw(self._ffb, drawX, drawY) love.graphics.setFont(GameFont.console) local coords = love.mouse.getX()..','..love.mouse.getY() love.graphics.print(coords, 0, 0) local num = #self._children for i=1,num do local child = self._children[i] child:draw(drawX, drawY) end end end -- the class return Frame
local Class = require 'lib.hump.class' local Rect = getClass 'pud.kit.Rect' local MousePressedEvent = getClass 'pud.event.MousePressedEvent' local MouseReleasedEvent = getClass 'pud.event.MouseReleasedEvent' local math_max = math.max local getMousePosition = love.mouse.getPosition local newFramebuffer = love.graphics.newFramebuffer local setColor = love.graphics.setColor local rectangle = love.graphics.rectangle local draw = love.graphics.draw local pushRenderTarget = pushRenderTarget local popRenderTarget = popRenderTarget local nearestPO2 = nearestPO2 local colors = colors local FRAME_UPDATE_TICK = 1/60 -- Frame -- Basic UI Element local Frame = Class{name='Frame', inherits=Rect, function(self, ...) Rect.construct(self, ...) self._children = {} self._accum = 0 self:_drawFB() InputEvents:register(self, {MousePressedEvent, MouseReleasedEvent}) end } -- destructor function Frame:destroy() InputEvents:unregisterAll(self) for k,v in pairs(self._children) do self._children[k]:destroy() self._children[k] = nil end self._children = nil self._ffb = nil self._bfb = nil self._curStyle = nil if self._normalStyle then self._normalStyle:destroy() self._normalStyle = nil end if self._hoverStyle then self._hoverStyle:destroy() self._hoverStyle = nil end if self._activeStyle then self._activeStyle:destroy() self._activeStyle = nil end self._hovered = nil self._mouseDown = nil self._accum = nil Rect.destroy(self) end -- MousePressedEvent - check if the event occurred within this frame function Frame:MousePressedEvent(e) self._mouseDown = true local x, y = e:getPosition() if self:containsPoint(x, y) then local button = e:getButton() local mods = e:getModifiers() self:onPress(button, mods) end end -- MouseReleasedEvent - check if the event occurred within this frame function Frame:MouseReleasedEvent(e) self._mouseDown = false local x, y = e:getPosition() local button = e:getButton() local mods = e:getModifiers() self:onRelease(button, mods, self:containsPoint(x, y)) end -- add a child function Frame:addChild(frame) verifyClass(Frame, frame) local num = #self._children self._children[num+1] = frame end -- remove a child function Frame:removeChild(frame) local num = #self._children local newChildren = {} local count = 0 for i=1,num do local child = self._children[i] if child ~= frame then count = count + 1 newChildren[count] = child end self._children[i] = nil end self._children = newChildren end -- get an appropriately sized PO2 framebuffer function Frame:_getFramebuffer() local size = nearestPO2(math_max(self:getWidth(), self:getHeight())) local fb = newFramebuffer(size, size) return fb end -- update - check for mouse hover function Frame:update(dt, x, y) self._accum = self._accum + dt if self._accum > FRAME_UPDATE_TICK then self._accum = 0 if nil == x or nil == y then x, y = getMousePosition() end if self:containsPoint(x, y) then if not self._hovered then self:onHoverIn(x, y) end self._hovered = true else if self._hovered then self:onHoverOut(x, y) end self._hovered = false end local num = #self._children for i = 1,num do local child = self._children[i] child:update(dt, x, y) end end end -- onHoverIn - called when the mouse starts hovering over the frame function Frame:onHoverIn(x, y) self._curStyle = self._hoverStyle or self._normalStyle self:_drawFB() end -- onHoverOut - called when the mouse stops hovering over the frame function Frame:onHoverOut(x, y) if not self._mouseDown then self._curStyle = self._normalStyle end self:_drawFB() end -- onPress - called when the mouse is pressed inside the frame function Frame:onPress(button, mods) self._curStyle = self._activeStyle or self._hoverStyle or self._normalStyle self:_drawFB() end -- onRelease - called when the mouse is released inside the frame function Frame:onRelease(button, mods, wasInside) if self._hovered then self._curStyle = self._hoverStyle or self._normalStyle else self._curStyle = self._normalStyle end self:_drawFB() end -- set the given style function Frame:_setStyle(which, style) verifyClass('pud.ui.Style', style) self[which] = style self._curStyle = self._curStyle or style self:_drawFB() end -- set/get normal style function Frame:setNormalStyle(style) self:_setStyle('_normalStyle', style) end function Frame:getNormalStyle() return self._normalStyle end -- set/get hover style function Frame:setHoverStyle(style) self:_setStyle('_hoverStyle', style) end function Frame:getHoverStyle() return self._hoverStyle end -- set/get active style function Frame:setActiveStyle(style) self:_setStyle('_activeStyle', style) end function Frame:getActiveStyle() return self._activeStyle end -- draw the frame to framebuffer (including all children) function Frame:_drawFB() self._bfb = self._bfb or self:_getFramebuffer() pushRenderTarget(self._bfb) self:_drawBackground() popRenderTarget() self._ffb, self._bfb = self._bfb, self._ffb end function Frame:_drawBackground() if self._curStyle then local color = self._curStyle:getColor() local image = self._curStyle:getImage() if color then setColor(color) if image then -- TODO: draw image else -- draw background rectangle if color was specified rectangle('fill', 0, 0, self._w, self._h) end end end end -- draw the framebuffer and all child framebuffers function Frame:draw(offsetX, offsetY) if self._ffb then offsetX = offsetX or 0 offsetY = offsetY or 0 local drawX, drawY = self._x + offsetX, self._y + offsetY setColor(colors.WHITE) draw(self._ffb, drawX, drawY) love.graphics.setFont(GameFont.console) local coords = love.mouse.getX()..','..love.mouse.getY() love.graphics.print(coords, 0, 0) local num = #self._children for i=1,num do local child = self._children[i] child:draw(drawX, drawY) end end end -- the class return Frame
fix Frame to unregister input events on destroy()
fix Frame to unregister input events on destroy()
Lua
mit
scottcs/wyx
3ca3b3a2c284a829ee0286baf60a36186305c61a
extensions/hints/init.lua
extensions/hints/init.lua
--- === hs.hints === --- --- Switch focus with a transient per-application hotkey local hints = require "hs.hints.internal" local screen = require "hs.screen" local window = require "hs.window" local hotkey = require "hs.hotkey" local modal_hotkey = hotkey.modal --- hs.hints.hintChars --- Variable --- This controls the set of characters that will be used for window hints. They must be characters found in hs.keycodes.map --- The default is the letters A-Z, the numbers 0-9, and the punctuation characters: -=[];'\\,./\` hints.hintChars = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"} --- hs.hints.style --- Variable --- If this is set to "vimperator", every window hint starts with the first character --- of the parent application's title hints.style = "default" --- hs.hints.fontName --- Variable --- A fully specified family-face name, preferrably the PostScript name, such as Helvetica-BoldOblique or Times-Roman. (The Font Book app displays PostScript names of fonts in the Font Info panel.) --- The default value is the system font hints.fontName = nil --- hs.hints.fontSize --- Variable --- The size of font that should be used. A value of 0.0 will use the default size. hints.fontSize = 0.0 local openHints = {} local takenPositions = {} local hintDict = {} local modalKey = nil local bumpThresh = 40^2 local bumpMove = 80 function hints.bumpPos(x,y) for i, pos in ipairs(takenPositions) do if ((pos.x-x)^2 + (pos.y-y)^2) < bumpThresh then return hints.bumpPos(x,y+bumpMove) end end return {x = x,y = y} end function hints.addWindow(dict, win) local n = dict['count'] if n == nil then dict['count'] = 0 n = 0 end local m = (n % #hints.hintChars) + 1 local char = hints.hintChars[m] if n < #hints.hintChars then dict[char] = win else if type(dict[char]) == "userdata" then -- dict[m] is already occupied by another window -- which me must convert into a new dictionary local otherWindow = dict[char] dict[char] = {} hints.addWindow(dict, otherWindow) end hints.addWindow(dict[char], win) end dict['count'] = dict['count'] + 1 end function hints.displayHintsForDict(dict, prefixstring) for key, val in pairs(dict) do if type(val) == "userdata" then -- this is a window local win = val local app = win:application() local fr = win:frame() local sfr = win:screen():frame() if app and win:title() ~= "" and win:isStandard() then local c = {x = fr.x + (fr.w/2) - sfr.x, y = fr.y + (fr.h/2) - sfr.y} c = hints.bumpPos(c.x, c.y) if c.y < 0 then print("hs.hints: Skipping offscreen window: "..win:title()) else -- print(win:title().." x:"..c.x.." y:"..c.y) -- debugging local hint = hints.new(c.x, c.y, prefixstring .. key, app:bundleID(), win:screen(), hints.fontName, hints.fontSize) table.insert(takenPositions, c) table.insert(openHints, hint) end end elseif type(val) == "table" then -- this is another window dict hints.displayHintsForDict(val, prefixstring .. key) end end end function hints.processChar(char) if hintDict[char] ~= nil then hints.closeHints() if type(hintDict[char]) == "userdata" then if hintDict[char] then hintDict[char]:focus() end modalKey:exit() elseif type(hintDict[char]) == "table" then hintDict = hintDict[char] takenPositions = {} hints.displayHintsForDict(hintDict, "") end end end function hints.setupModal() k = modal_hotkey.new(nil, nil) k:bind({}, 'escape', function() hints.closeHints(); k:exit() end) for _, c in ipairs(hints.hintChars) do k:bind({}, c, function() hints.processChar(c) end) end return k end --- hs.hints.windowHints() --- Function --- Displays a keyboard hint for switching focus to each window --- --- Parameters: --- * None --- --- Returns: --- * None --- --- Notes: --- * If there are more windows open than there are characters available in hs.hints.hintChars, --- we resort to multi-character hints --- * If hints.style is set to "vimperator", every window hint is prefixed with the first --- character of the parent application's name function hints.windowHints() if (modalKey == nil) then modalKey = hints.setupModal() end hints.closeHints() hintDict = {} for i, win in ipairs(window.allWindows()) do local app = win:application() if app and win:title() ~= "" and win:isStandard() then if hints.style == "vimperator" then if app and win:title() ~= "" and win:isStandard() then local appchar = string.upper(string.sub(app:title(), 1, 1)) modalKey:bind({}, appchar, function() hints.processChar(appchar) end) if hintDict[appchar] == nil then hintDict[appchar] = {} end hints.addWindow(hintDict[appchar], win) end else hints.addWindow(hintDict, win) end end end takenPositions = {} if next(hintDict) ~= nil then hints.displayHintsForDict(hintDict, "") modalKey:enter() end end function hints.closeHints() for _, hint in ipairs(openHints) do hint:close() end openHints = {} takenPositions = {} end return hints
--- === hs.hints === --- --- Switch focus with a transient per-application hotkey local hints = require "hs.hints.internal" local screen = require "hs.screen" local window = require "hs.window" local hotkey = require "hs.hotkey" local modal_hotkey = hotkey.modal --- hs.hints.hintChars --- Variable --- This controls the set of characters that will be used for window hints. They must be characters found in hs.keycodes.map --- The default is the letters A-Z. hints.hintChars = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"} --- hs.hints.style --- Variable --- If this is set to "vimperator", every window hint starts with the first character --- of the parent application's title hints.style = "default" --- hs.hints.fontName --- Variable --- A fully specified family-face name, preferrably the PostScript name, such as Helvetica-BoldOblique or Times-Roman. (The Font Book app displays PostScript names of fonts in the Font Info panel.) --- The default value is the system font hints.fontName = nil --- hs.hints.fontSize --- Variable --- The size of font that should be used. A value of 0.0 will use the default size. hints.fontSize = 0.0 local openHints = {} local takenPositions = {} local hintDict = {} local modalKey = nil local bumpThresh = 40^2 local bumpMove = 80 function hints.bumpPos(x,y) for i, pos in ipairs(takenPositions) do if ((pos.x-x)^2 + (pos.y-y)^2) < bumpThresh then return hints.bumpPos(x,y+bumpMove) end end return {x = x,y = y} end function hints.addWindow(dict, win) local n = dict['count'] if n == nil then dict['count'] = 0 n = 0 end local m = (n % #hints.hintChars) + 1 local char = hints.hintChars[m] if n < #hints.hintChars then dict[char] = win else if type(dict[char]) == "userdata" then -- dict[m] is already occupied by another window -- which me must convert into a new dictionary local otherWindow = dict[char] dict[char] = {} hints.addWindow(dict, otherWindow) end hints.addWindow(dict[char], win) end dict['count'] = dict['count'] + 1 end function hints.displayHintsForDict(dict, prefixstring) for key, val in pairs(dict) do if type(val) == "userdata" then -- this is a window local win = val local app = win:application() local fr = win:frame() local sfr = win:screen():frame() if app and win:title() ~= "" and win:isStandard() then local c = {x = fr.x + (fr.w/2) - sfr.x, y = fr.y + (fr.h/2) - sfr.y} c = hints.bumpPos(c.x, c.y) if c.y < 0 then print("hs.hints: Skipping offscreen window: "..win:title()) else -- print(win:title().." x:"..c.x.." y:"..c.y) -- debugging local hint = hints.new(c.x, c.y, prefixstring .. key, app:bundleID(), win:screen(), hints.fontName, hints.fontSize) table.insert(takenPositions, c) table.insert(openHints, hint) end end elseif type(val) == "table" then -- this is another window dict hints.displayHintsForDict(val, prefixstring .. key) end end end function hints.processChar(char) if hintDict[char] ~= nil then hints.closeHints() if type(hintDict[char]) == "userdata" then if hintDict[char] then hintDict[char]:focus() end modalKey:exit() elseif type(hintDict[char]) == "table" then hintDict = hintDict[char] takenPositions = {} hints.displayHintsForDict(hintDict, "") end end end function hints.setupModal() k = modal_hotkey.new(nil, nil) k:bind({}, 'escape', function() hints.closeHints(); k:exit() end) for _, c in ipairs(hints.hintChars) do k:bind({}, c, function() hints.processChar(c) end) end return k end --- hs.hints.windowHints() --- Function --- Displays a keyboard hint for switching focus to each window --- --- Parameters: --- * None --- --- Returns: --- * None --- --- Notes: --- * If there are more windows open than there are characters available in hs.hints.hintChars, --- we resort to multi-character hints --- * If hints.style is set to "vimperator", every window hint is prefixed with the first --- character of the parent application's name function hints.windowHints() if (modalKey == nil) then modalKey = hints.setupModal() end hints.closeHints() hintDict = {} for i, win in ipairs(window.allWindows()) do local app = win:application() if app and win:title() ~= "" and win:isStandard() then if hints.style == "vimperator" then if app and win:title() ~= "" and win:isStandard() then local appchar = string.upper(string.sub(app:title(), 1, 1)) modalKey:bind({}, appchar, function() hints.processChar(appchar) end) if hintDict[appchar] == nil then hintDict[appchar] = {} end hints.addWindow(hintDict[appchar], win) end else hints.addWindow(hintDict, win) end end end takenPositions = {} if next(hintDict) ~= nil then hints.displayHintsForDict(hintDict, "") modalKey:enter() end end function hints.closeHints() for _, hint in ipairs(openHints) do hint:close() end openHints = {} takenPositions = {} end return hints
fix hintChars documentation
fix hintChars documentation
Lua
mit
heptal/hammerspoon,Stimim/hammerspoon,knu/hammerspoon,lowne/hammerspoon,dopcn/hammerspoon,CommandPost/CommandPost-App,wsmith323/hammerspoon,joehanchoi/hammerspoon,zzamboni/hammerspoon,zzamboni/hammerspoon,hypebeast/hammerspoon,bradparks/hammerspoon,cmsj/hammerspoon,dopcn/hammerspoon,latenitefilms/hammerspoon,ocurr/hammerspoon,chrisjbray/hammerspoon,knl/hammerspoon,dopcn/hammerspoon,trishume/hammerspoon,lowne/hammerspoon,asmagill/hammerspoon,emoses/hammerspoon,knu/hammerspoon,junkblocker/hammerspoon,tmandry/hammerspoon,hypebeast/hammerspoon,knu/hammerspoon,chrisjbray/hammerspoon,heptal/hammerspoon,lowne/hammerspoon,zzamboni/hammerspoon,Stimim/hammerspoon,dopcn/hammerspoon,kkamdooong/hammerspoon,CommandPost/CommandPost-App,Hammerspoon/hammerspoon,Stimim/hammerspoon,latenitefilms/hammerspoon,asmagill/hammerspoon,latenitefilms/hammerspoon,knl/hammerspoon,joehanchoi/hammerspoon,heptal/hammerspoon,wvierber/hammerspoon,wsmith323/hammerspoon,asmagill/hammerspoon,peterhajas/hammerspoon,ocurr/hammerspoon,emoses/hammerspoon,lowne/hammerspoon,latenitefilms/hammerspoon,nkgm/hammerspoon,latenitefilms/hammerspoon,ocurr/hammerspoon,TimVonsee/hammerspoon,chrisjbray/hammerspoon,wsmith323/hammerspoon,cmsj/hammerspoon,junkblocker/hammerspoon,Habbie/hammerspoon,wsmith323/hammerspoon,trishume/hammerspoon,knl/hammerspoon,ocurr/hammerspoon,CommandPost/CommandPost-App,tmandry/hammerspoon,nkgm/hammerspoon,joehanchoi/hammerspoon,knu/hammerspoon,Hammerspoon/hammerspoon,ocurr/hammerspoon,Habbie/hammerspoon,Habbie/hammerspoon,nkgm/hammerspoon,knl/hammerspoon,emoses/hammerspoon,heptal/hammerspoon,knu/hammerspoon,peterhajas/hammerspoon,latenitefilms/hammerspoon,knl/hammerspoon,wvierber/hammerspoon,emoses/hammerspoon,nkgm/hammerspoon,dopcn/hammerspoon,kkamdooong/hammerspoon,Stimim/hammerspoon,emoses/hammerspoon,bradparks/hammerspoon,peterhajas/hammerspoon,TimVonsee/hammerspoon,asmagill/hammerspoon,knu/hammerspoon,hypebeast/hammerspoon,wvierber/hammerspoon,Habbie/hammerspoon,CommandPost/CommandPost-App,CommandPost/CommandPost-App,Hammerspoon/hammerspoon,joehanchoi/hammerspoon,Habbie/hammerspoon,TimVonsee/hammerspoon,wvierber/hammerspoon,junkblocker/hammerspoon,nkgm/hammerspoon,CommandPost/CommandPost-App,Hammerspoon/hammerspoon,zzamboni/hammerspoon,lowne/hammerspoon,junkblocker/hammerspoon,Hammerspoon/hammerspoon,TimVonsee/hammerspoon,heptal/hammerspoon,joehanchoi/hammerspoon,hypebeast/hammerspoon,junkblocker/hammerspoon,asmagill/hammerspoon,bradparks/hammerspoon,cmsj/hammerspoon,kkamdooong/hammerspoon,hypebeast/hammerspoon,chrisjbray/hammerspoon,kkamdooong/hammerspoon,zzamboni/hammerspoon,wsmith323/hammerspoon,bradparks/hammerspoon,wvierber/hammerspoon,cmsj/hammerspoon,Stimim/hammerspoon,Hammerspoon/hammerspoon,cmsj/hammerspoon,TimVonsee/hammerspoon,cmsj/hammerspoon,zzamboni/hammerspoon,chrisjbray/hammerspoon,peterhajas/hammerspoon,Habbie/hammerspoon,asmagill/hammerspoon,trishume/hammerspoon,peterhajas/hammerspoon,tmandry/hammerspoon,chrisjbray/hammerspoon,kkamdooong/hammerspoon,bradparks/hammerspoon
60596581dd7ab3c9f7008b13caf15f019ad0f80a
source/networking/server.lua
source/networking/server.lua
local flower = flower -- LuaSocket should come with zerobrane local socket = require("socket") Server = flower.class() function Server:init(t) self.port = t.port or 48310 self.server, self.servError = socket.bind("*", self.port) if self.server then self.client = {} self.server:settimeout(0) local serverThread = MOAIThread.new() serverThread:run(function() self:run() coroutine.yield() end) print("Network connection info:") print(self.server:getsockname()) end end function Server:run() if self.server then local set = {self.server} local readable = socket.select(set) for i, input in ipairs(readable) do input:settimeout(0) local new = input:accept() if new then new:settimeout(0) self.client[new] = new self.connected = true end end -- local newClient = self.server:accept() -- table.insert(self.client, newClient) --print(#tempClients .. " client(s) connected") end end function Server:stop() if self:isConnected() then for client, _ in pairs(self.client) do client:close() end if self.server then self.server:close() end end self.client = nil self.server = nil end function Server:isConnected() if self.connected then return self.connected end return false, (self.servError or "Unknown error") end function Server:stopIfClosed(e) if e == "closed" then self.servError = e self:stop() end end function Server:talker(text) if self:isConnected() then for client, _ in pairs(self.client) do local b, e = client:send(text .. "\n") end --self:stopIfClosed(e) end end function Server:listener() local l = {} local e = nil if self:isConnected() then for client, _ in pairs(self.client) do local tempData = client:receive() table.insert(l, tempData) --self:stopIfClosed(e) end return l end end
local flower = flower -- LuaSocket should come with zerobrane local socket = require("socket") Server = flower.class() function Server:init(t) self.port = t.port or 48310 self.server, self.servError = socket.bind("*", self.port) if self.server then self.server:settimeout(0) self.client = {} local serverThread = MOAIThread.new() serverThread:run(function() while 1 do self:run() coroutine.yield() end end) print("Network connection info:") print(self.server:getsockname()) end end function Server:run() local new = self.server:accept() if new then print("New client connected") new:settimeout(0) table.insert(self.client, new) end end function Server:stop() if self:isConnected() then for i, client in ipairs(self.client) do client:close() end if self.server then self.server:close() end end self.client = nil self.server = nil end function Server:isConnected(connections) connections = connections or 1 if #self.client >= connections then return true end return false, (self.servError or "Unknown error") end function Server:stopIfClosed(e) if e == "closed" then self.servError = e self:stop() end end function Server:talker(text) if self:isConnected() then for i, client in ipairs(self.client) do local b, e = client:send(text .. "\n") end --self:stopIfClosed(e) end end function Server:listener() local l = {} local e = nil if self:isConnected() then for i, client in ipairs(self.client) do local tempData = client:receive() table.insert(l, tempData) --self:stopIfClosed(e) end return l end end
Fixed server behavior. Multiple clients can now connect to the server.
Fixed server behavior. Multiple clients can now connect to the server.
Lua
mit
BryceMehring/Hexel
c1d21df35e8bb6614e10f434ab048871e1c33d10
src/gui/Button.lua
src/gui/Button.lua
-------------------------------------------------------------------------------- -- -- -- -------------------------------------------------------------------------------- local Group = require("core.Group") local Event = require("core.Event") local UIEvent = require("gui.UIEvent") local UIObjectBase = require("gui.UIObjectBase") local ButtonAnimations = require("gui.ButtonAnimations") local Button = class(UIObjectBase, Group) --- -- Example usage -- Button can be initialized in declarative way -- Button { -- normalSprite = Sprite("normal.png"), -- activeSprite = Sprite("active.png"), -- disabledSprite = Sprite("disabled.png"), -- label = Label("Button", 200, 100, "Verdana.ttf", 24), -- onClick = function(e) print("click") end, -- animations = {ButtonAnimations.Bounce()}, -- toggle = false, -- } Button.propertyOrder = { size = 2, label = 2, layer = 3, } function Button:init(params) Group.init(self) UIObjectBase.init(self, params) assert(self.normalSprite) if table.empty(self.animations) then self:addAnimation(ButtonAnimations.Change()) end self:initEventListeners() self:setEnabled(true) self:setActive(false) end function Button:initEventListeners() self:addEventListener(Event.TOUCH_DOWN, self.onTouchDown, self) self:addEventListener(Event.TOUCH_UP, self.onTouchUp, self) self:addEventListener(Event.TOUCH_MOVE, self.onTouchMove, self) self:addEventListener(Event.TOUCH_CANCEL, self.onTouchCancel, self) end --- -- -- function Button:setNormalSprite(sprite) if self.normalSprite then self:removeChild(self.normalSprite) self.normalSprite = nil end if sprite then self:addChild(sprite) self.normalSprite = sprite end end --- -- -- function Button:setActiveSprite(sprite) if self.activeSprite then self:removeChild(self.activeSprite) self.activeSprite = nil end if sprite then self:addChild(sprite) self.activeSprite = sprite end end --- -- -- function Button:setDisabledSprite(sprite) if self.disabledSprite then self:removeChild(self.disabledSprite) self.disabledSprite = nil end if sprite then self:addChild(sprite) self.disabledSprite = sprite end end --- -- Set hit area for button -- @param width -- @param height -- -- @overload -- @param xMin -- @param yMin -- @apram xMax -- @param yMax function Button:setHitArea(width, height, xMax, yMax) local xMin = xMax and width or -0.5 * width local yMin = yMax and height or -0.5 * height xMax = xMax or 0.5 * width yMax = yMax or 0.5 * height self:setBounds(xMin, yMin, xMax, yMax) if self.normalSprite then self.normalSprite:setBounds(xMin, yMin, 0, xMax, yMax, 0) end if self.activeSprite then self.activeSprite:setBounds(xMin, yMin, 0, xMax, yMax, 0) end end --- -- -- function Button:setLabel(label) if self.label then self:removeChild(self.label) self.label = nil end if label then self:addChild(label) self.label = label end end --- -- -- function Button:setEnabled(value) self.enabled = value if value then self:dispatchEvent(UIEvent.ENABLE) else self:dispatchEvent(UIEvent.DISABLE) end end --- -- -- function Button:setActive(value) self.active = value if value then self:dispatchEvent(UIEvent.DOWN) else self:dispatchEvent(UIEvent.UP) end end --- -- -- function Button:setAnimations(...) local animList = {...} if self.animations then for animCalss, anim in pairs(self.animations) do anim:setButton(nil) end end self.animations = {} for i, anim in ipairs(animList) do self:addAnimation(anim) end end --- -- -- function Button:addAnimation(animation) -- use animation class as key -- so there are only one animation of each type if not self.animations then self.animations = {} end if self.animations[animation] then self:removeAnimation(animation) end animation:setButton(self) self.animations[animation.__class] = animation end --- -- -- function Button:removeAnimation(animation) self.animations[animation]:setButton(nil) end --- -- -- function Button:onTouchDown(event) event:stop() if not self.enabled or self._touchDownIdx ~= nil then return end if not self.normalSprite:inside(event.wx, event.wy, 0) then return end self._touchDownIdx = event.idx self:setActive(true) end --- -- -- function Button:onTouchMove(event) event:stop() if self._touchDownIdx ~= event.idx then return end local inside = self.normalSprite:inside(event.wx, event.wy, 0) if inside ~= self.active then self:setActive(inside) end if inside then return end self:dispatchEvent(UIEvent.CANCEL) end --- -- -- function Button:onTouchUp(event) event:stop() if self._touchDownIdx ~= event.idx then return end self._touchDownIdx = nil self:setActive(false) if not self.normalSprite:inside(event.wx, event.wy, 0) then return end if self.toggle then self:setEnabled(not self.enabled) if self.onToggle then self.onToggle(self.enabled) end else self:dispatchEvent(UIEvent.CLICK) if self.onClick then self.onClick() end end end --- -- -- function Button:onTouchCancel(event) event:stop() if self._touchDownIdx ~= event.idx then return end self._touchDownIdx = nil if not self.toggle then self:dispatchEvent(UIEvent.CANCEL) end end return Button
-------------------------------------------------------------------------------- -- -- -- -------------------------------------------------------------------------------- local Group = require("core.Group") local Event = require("core.Event") local UIEvent = require("gui.UIEvent") local UIObjectBase = require("gui.UIObjectBase") local ButtonAnimations = require("gui.ButtonAnimations") local Button = class(UIObjectBase, Group) --- -- Example usage -- Button can be initialized in declarative way -- Button { -- normalSprite = Sprite("normal.png"), -- activeSprite = Sprite("active.png"), -- disabledSprite = Sprite("disabled.png"), -- label = Label("Button", 200, 100, "Verdana.ttf", 24), -- onClick = function(e) print("click") end, -- animations = {ButtonAnimations.Bounce()}, -- toggle = false, -- } Button.propertyOrder = { size = 2, label = 2, layer = 3, } function Button:init(params) Group.init(self) UIObjectBase.init(self, params) assert(self.normalSprite) if table.empty(self.animations) then self:addAnimation(ButtonAnimations.Change()) end self:initEventListeners() self:setEnabled(true) self:setActive(false) end function Button:initEventListeners() self:addEventListener(Event.TOUCH_DOWN, self.onTouchDown, self) self:addEventListener(Event.TOUCH_UP, self.onTouchUp, self) self:addEventListener(Event.TOUCH_MOVE, self.onTouchMove, self) self:addEventListener(Event.TOUCH_CANCEL, self.onTouchCancel, self) end --- -- -- function Button:setNormalSprite(sprite) if self.normalSprite then self:removeChild(self.normalSprite) self.normalSprite = nil end if sprite then self:addChild(sprite) self.normalSprite = sprite end end --- -- -- function Button:setActiveSprite(sprite) if self.activeSprite then self:removeChild(self.activeSprite) self.activeSprite = nil end if sprite then self:addChild(sprite) self.activeSprite = sprite end end --- -- -- function Button:setDisabledSprite(sprite) if self.disabledSprite then self:removeChild(self.disabledSprite) self.disabledSprite = nil end if sprite then self:addChild(sprite) self.disabledSprite = sprite end end --- -- Set hit area for button -- @param width -- @param height -- -- @overload -- @param xMin -- @param yMin -- @apram xMax -- @param yMax function Button:setHitArea(width, height, xMax, yMax) local xMin = xMax and width or -0.5 * width local yMin = yMax and height or -0.5 * height xMax = xMax or 0.5 * width yMax = yMax or 0.5 * height self:setBounds(xMin, yMin, xMax, yMax) if self.normalSprite then self.normalSprite:setBounds(xMin, yMin, 0, xMax, yMax, 0) end if self.activeSprite then self.activeSprite:setBounds(xMin, yMin, 0, xMax, yMax, 0) end end --- -- -- function Button:setLabel(label) if self.label then self:removeChild(self.label) self.label = nil end if label then self:addChild(label) self.label = label end end --- -- -- function Button:setEnabled(value) self.enabled = value if value then self:dispatchEvent(UIEvent.ENABLE) else self:dispatchEvent(UIEvent.DISABLE) end end --- -- -- function Button:setActive(value) self.active = value if value then self:dispatchEvent(UIEvent.DOWN) else self:dispatchEvent(UIEvent.UP) end end --- -- -- function Button:setAnimations(...) local animList = {...} if self.animations then for animCalss, anim in pairs(self.animations) do anim:setButton(nil) end end self.animations = {} for i, anim in ipairs(animList) do self:addAnimation(anim) end end --- -- -- function Button:addAnimation(animation) -- use animation class as key -- so there are only one animation of each type if not self.animations then self.animations = {} end if self.animations[animation] then self:removeAnimation(animation) end animation:setButton(self) self.animations[animation.__class] = animation end --- -- -- function Button:removeAnimation(animation) self.animations[animation]:setButton(nil) end --- -- -- function Button:onTouchDown(event) event:stop() if self._touchDownIdx ~= nil then return end if not self.enabled and not self.toggle then print("not toggle") return end if not self.normalSprite:inside(event.wx, event.wy, 0) then return end self._touchDownIdx = event.idx self:setActive(true) end --- -- -- function Button:onTouchMove(event) event:stop() if self._touchDownIdx ~= event.idx then return end local inside = self.normalSprite:inside(event.wx, event.wy, 0) if inside ~= self.active then self:setActive(inside) end if inside then return end self:dispatchEvent(UIEvent.CANCEL) end --- -- -- function Button:onTouchUp(event) event:stop() if self._touchDownIdx ~= event.idx then return end self._touchDownIdx = nil self:setActive(false) if not self.normalSprite:inside(event.wx, event.wy, 0) then return end if self.toggle then self:setEnabled(not self.enabled) if self.onToggle then self.onToggle(self.enabled) end else self:dispatchEvent(UIEvent.CLICK) if self.onClick then self.onClick() end end end --- -- -- function Button:onTouchCancel(event) event:stop() if self._touchDownIdx ~= event.idx then return end self._touchDownIdx = nil if not self.toggle then self:dispatchEvent(UIEvent.CANCEL) end end return Button
fix toggle button
fix toggle button
Lua
mit
Vavius/moai-framework,Vavius/moai-framework
589818d7c95116f046b8af9cd9066a1579da1177
vrp/client/basic_garage.lua
vrp/client/basic_garage.lua
local vehicles = {} function tvRP.spawnGarageVehicle(vtype,name) -- vtype is the vehicle type (one vehicle per type allowed at the same time) local vehicle = vehicles[vtype] if vehicle and not IsVehicleDriveable(vehicle[3]) then -- precheck if vehicle is undriveable -- despawn vehicle Citizen.InvokeNative(0xEA386986E786A54F, Citizen.PointerValueIntInitialized(vehicle[3])) vehicles[vtype] = nil end vehicle = vehicles[vtype] if vehicle == nil then -- load vehicle model local mhash = GetHashKey(name) local i = 0 while not HasModelLoaded(mhash) and i < 10000 do RequestModel(mhash) Citizen.Wait(10) i = i+1 end -- spawn car if HasModelLoaded(mhash) then local x,y,z = tvRP.getPosition() local nveh = CreateVehicle(mhash, x,y,z+0.5, 0.0, true, false) SetVehicleOnGroundProperly(nveh) SetEntityInvincible(nveh,false) SetPedIntoVehicle(GetPlayerPed(-1),nveh,-1) -- put player inside SetVehicleNumberPlateText(nveh, "P "..tvRP.getRegistrationNumber()) Citizen.InvokeNative(0xAD738C3085FE7E11, nveh, true, true) -- set as mission entity vehicles[vtype] = {vtype,name,nveh} -- set current vehicule SetModelAsNoLongerNeeded(mhash) end else tvRP.notify("You can only have one "..vtype.." vehicule out.") end end function tvRP.despawnGarageVehicle(vtype,max_range) local vehicle = vehicles[vtype] if vehicle then local x,y,z = table.unpack(GetEntityCoords(vehicle[3],true)) local px,py,pz = tvRP.getPosition() if GetDistanceBetweenCoords(x,y,z,px,py,pz,true) < max_range then -- check distance with the vehicule -- remove vehicle Citizen.InvokeNative(0xEA386986E786A54F, Citizen.PointerValueIntInitialized(vehicle[3])) vehicles[vtype] = nil tvRP.notify("Vehicle stored.") else tvRP.notify("Too far away from the vehicle.") end end end -- (experimental) this function return the nearest vehicle -- (don't work with all vehicles, but aim to) function tvRP.getNearestVehicle(radius) local x,y,z = tvRP.getPosition() local ped = GetPlayerPed(-1) if IsPedSittingInAnyVehicle(ped) then return GetVehiclePedIsIn(ped, true) else return GetClosestVehicle(x+0.0001,y+0.0001,z+0.0001, radius+0.0001, 0, 7) end end -- try to get a vehicle at a specific position (using raycast) function tvRP.getVehicleAtPosition(x,y,z) x = x+0.0001 y = y+0.0001 z = z+0.0001 local ray = CastRayPointToPoint(x,y,z,x,y,z+4,10,GetPlayerPed(-1),0) local a, b, c, d, ent = GetRaycastResult(ray) return ent end -- return ok,vtype,name function tvRP.getNearestOwnedVehicle(radius) local px,py,pz = tvRP.getPosition() for k,v in pairs(vehicles) do local x,y,z = table.unpack(GetEntityCoords(v[3],true)) local dist = GetDistanceBetweenCoords(x,y,z,px,py,pz,true) if dist <= radius+0.0001 then return true,v[1],v[2] end end return false,"","" end -- return ok,x,y,z function tvRP.getAnyOwnedVehiclePosition() for k,v in pairs(vehicles) do if IsEntityAVehicle(v[3]) then local x,y,z = table.unpack(GetEntityCoords(v[3],true)) return true,x,y,z end end return false,0,0,0 end -- return x,y,z function tvRP.getOwnedVehiclePosition(vtype) local vehicle = vehicles[vtype] local x,y,z = 0,0,0 if vehicle then x,y,z = table.unpack(GetEntityCoords(vehicle[3],true)) end return x,y,z end -- return ok, vehicule network id function tvRP.getOwnedVehicleId(vtype) local vehicle = vehicles[vtype] if vehicle then return true, NetworkGetNetworkIdFromEntity(vehicle[3]) else return false, 0 end end -- eject the ped from the vehicle function tvRP.ejectVehicle() local ped = GetPlayerPed(-1) if IsPedSittingInAnyVehicle(ped) then local veh = GetVehiclePedIsIn(ped,false) TaskLeaveVehicle(ped, veh, 4160) end end -- vehicle commands function tvRP.vc_openDoor(vtype, door_index) local vehicle = vehicles[vtype] if vehicle then SetVehicleDoorOpen(vehicle[3],door_index,0,false) end end function tvRP.vc_closeDoor(vtype, door_index) local vehicle = vehicles[vtype] if vehicle then SetVehicleDoorShut(vehicle[3],door_index) end end function tvRP.vc_detachTrailer(vtype) local vehicle = vehicles[vtype] if vehicle then DetachVehicleFromTrailer(vehicle[3]) end end
local vehicles = {} function tvRP.spawnGarageVehicle(vtype,name) -- vtype is the vehicle type (one vehicle per type allowed at the same time) local vehicle = vehicles[vtype] if vehicle and not IsVehicleDriveable(vehicle[3]) then -- precheck if vehicle is undriveable -- despawn vehicle Citizen.InvokeNative(0xEA386986E786A54F, Citizen.PointerValueIntInitialized(vehicle[3])) vehicles[vtype] = nil end vehicle = vehicles[vtype] if vehicle == nil then -- load vehicle model local mhash = GetHashKey(name) local i = 0 while not HasModelLoaded(mhash) and i < 10000 do RequestModel(mhash) Citizen.Wait(10) i = i+1 end -- spawn car if HasModelLoaded(mhash) then local x,y,z = tvRP.getPosition() local nveh = CreateVehicle(mhash, x,y,z+0.5, 0.0, true, false) SetVehicleOnGroundProperly(nveh) SetEntityInvincible(nveh,false) SetPedIntoVehicle(GetPlayerPed(-1),nveh,-1) -- put player inside SetVehicleNumberPlateText(nveh, "P "..tvRP.getRegistrationNumber()) Citizen.InvokeNative(0xAD738C3085FE7E11, nveh, true, true) -- set as mission entity vehicles[vtype] = {vtype,name,nveh} -- set current vehicule SetModelAsNoLongerNeeded(mhash) end else tvRP.notify("You can only have one "..vtype.." vehicule out.") end end function tvRP.despawnGarageVehicle(vtype,max_range) local vehicle = vehicles[vtype] if vehicle then local x,y,z = table.unpack(GetEntityCoords(vehicle[3],true)) local px,py,pz = tvRP.getPosition() if GetDistanceBetweenCoords(x,y,z,px,py,pz,true) < max_range then -- check distance with the vehicule -- remove vehicle Citizen.InvokeNative(0xEA386986E786A54F, Citizen.PointerValueIntInitialized(vehicle[3])) vehicles[vtype] = nil tvRP.notify("Vehicle stored.") else tvRP.notify("Too far away from the vehicle.") end end end -- (experimental) this function return the nearest vehicle -- (don't work with all vehicles, but aim to) function tvRP.getNearestVehicle(radius) local x,y,z = tvRP.getPosition() local ped = GetPlayerPed(-1) if IsPedSittingInAnyVehicle(ped) then return GetVehiclePedIsIn(ped, true) else -- flags used: --- 8192: boat --- 4096: helicos --- 4,2,1: cars (with police) local veh = GetClosestVehicle(x+0.0001,y+0.0001,z+0.0001, radius+0.0001, 0, 8192+4096+4+2+1) -- boats, helicos if not IsEntityAVehicle(veh) then veh = GetClosestVehicle(x+0.0001,y+0.0001,z+0.0001, radius+0.0001, 0, 4+2+1) end -- cars return veh end end -- try to get a vehicle at a specific position (using raycast) function tvRP.getVehicleAtPosition(x,y,z) x = x+0.0001 y = y+0.0001 z = z+0.0001 local ray = CastRayPointToPoint(x,y,z,x,y,z+4,10,GetPlayerPed(-1),0) local a, b, c, d, ent = GetRaycastResult(ray) return ent end -- return ok,vtype,name function tvRP.getNearestOwnedVehicle(radius) local px,py,pz = tvRP.getPosition() for k,v in pairs(vehicles) do local x,y,z = table.unpack(GetEntityCoords(v[3],true)) local dist = GetDistanceBetweenCoords(x,y,z,px,py,pz,true) if dist <= radius+0.0001 then return true,v[1],v[2] end end return false,"","" end -- return ok,x,y,z function tvRP.getAnyOwnedVehiclePosition() for k,v in pairs(vehicles) do if IsEntityAVehicle(v[3]) then local x,y,z = table.unpack(GetEntityCoords(v[3],true)) return true,x,y,z end end return false,0,0,0 end -- return x,y,z function tvRP.getOwnedVehiclePosition(vtype) local vehicle = vehicles[vtype] local x,y,z = 0,0,0 if vehicle then x,y,z = table.unpack(GetEntityCoords(vehicle[3],true)) end return x,y,z end -- return ok, vehicule network id function tvRP.getOwnedVehicleId(vtype) local vehicle = vehicles[vtype] if vehicle then return true, NetworkGetNetworkIdFromEntity(vehicle[3]) else return false, 0 end end -- eject the ped from the vehicle function tvRP.ejectVehicle() local ped = GetPlayerPed(-1) if IsPedSittingInAnyVehicle(ped) then local veh = GetVehiclePedIsIn(ped,false) TaskLeaveVehicle(ped, veh, 4160) end end -- vehicle commands function tvRP.vc_openDoor(vtype, door_index) local vehicle = vehicles[vtype] if vehicle then SetVehicleDoorOpen(vehicle[3],door_index,0,false) end end function tvRP.vc_closeDoor(vtype, door_index) local vehicle = vehicles[vtype] if vehicle then SetVehicleDoorShut(vehicle[3],door_index) end end function tvRP.vc_detachTrailer(vtype) local vehicle = vehicles[vtype] if vehicle then DetachVehicleFromTrailer(vehicle[3]) end end
Fix put in vehicle for police cars, helicos and boats
Fix put in vehicle for police cars, helicos and boats
Lua
mit
ENDrain/vRP-plusplus,ENDrain/vRP-plusplus,ImagicTheCat/vRP,ENDrain/vRP-plusplus,ImagicTheCat/vRP
045a660149ecaab79b37fb51aea108077e46122c
modules/title/sites/spotify.lua
modules/title/sites/spotify.lua
local simplehttp = require'simplehttp' local html2unicode = require'html' customHosts['open.spotify.com'] = function(queue, info) local path = info.path if(path and path:match'/(%w+)/(.+)') then simplehttp( info.url, function(data, url, response) local title = html2unicode(data:match'<title>(.-) on Spotify</title>') local uri = data:match('property="og:audio" content="([^"]+)"') queue:done(string.format('%s: %s | http://play.spotify.com%s', title, uri, info.path)) end ) return true end end customHosts['play.spotify.com'] = function(queue, info) local path = info.path if(path and path:match'/(%w+)/(.+)') then simplehttp( info.url:gsub("play%.spotify", "open.spotify"), function(data, url, response) local title = html2unicode(data:match'<title>(.-) on Spotify</title>') local uri = data:match('property="og:audio" content="([^"]+)"') queue:done(string.format('%s: %s | http://open.spotify.com%s', title, uri, info.path)) end ) return true end end
local simplehttp = require'simplehttp' local html2unicode = require'html' customHosts['open.spotify.com'] = function(queue, info) local path = info.path if(path and path:match'/(%w+)/(.+)') then simplehttp( info.url, function(data, url, response) local title = html2unicode(data:match'<title>(.-)</title>') --local uri = data:match('property="al:android:url" content="([^"]+)"') queue:done(string.format('%s | http://play.spotify.com%s', title, info.path)) end ) return true end end customHosts['play.spotify.com'] = function(queue, info) local path = info.path if(path and path:match'/(%w+)/(.+)') then simplehttp( info.url:gsub("play%.spotify", "open.spotify"), function(data, url, response) local title = html2unicode(data:match'<title>(.-)/title>') local uri = data:match('property="og:audio" content="([^"]+)"') queue:done(string.format('%s | http://open.spotify.com%s', title, info.path)) end ) return true end end
title: fix spotify
title: fix spotify
Lua
mit
torhve/ivar2,torhve/ivar2,torhve/ivar2
ac06d2aa0eb76a933a843aa37878535a427e8599
tests/plugins/project/test.lua
tests/plugins/project/test.lua
import("detect.sdks.find_vstudio") import("core.project.config") import("core.platform.environment") function test_vsxmake(t) if os.host() ~= "windows" then return t:skip("wrong host platform") end -- build project local vs = find_vstudio() local arch = os.getenv("platform") or "x86" os.cd("c") for name, data in pairs(vs) do local vstype = "vsxmake" .. name local path = os.getenv("path") os.setenv("path", data.vcvarsall[arch].path) environment.enter("toolchains") os.execv("xmake", {"project", "-k", vstype, "-a", arch}) os.cd(vstype) os.exec("msbuild /t:show") os.exec("msbuild") environment.leave("toolchains") os.setenv("path", path) os.cd("..") os.tryrm(vstype) end os.cd("..") end
import("detect.sdks.find_vstudio") import("core.project.config") import("core.platform.platform") import("core.platform.environment") function test_vsxmake(t) if os.host() ~= "windows" then return t:skip("wrong host platform") end -- build project local vs = find_vstudio() local arch = os.getenv("platform") or "x86" os.cd("c") for name, _ in pairs(vs) do -- set config config.set("arch", arch) config.set("vs", name) config.check() platform.load(config.plat()) environment.enter("toolchains") local vstype = "vsxmake" .. name -- create sln & vcxproj os.execv("xmake", {"project", "-k", vstype, "-a", arch}) os.cd(vstype) -- run msbuild os.exec("msbuild /t:show") os.exec("msbuild") environment.leave("toolchains") -- clean up os.cd("..") os.tryrm(vstype) end os.cd("..") end
fix env
fix env
Lua
apache-2.0
waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake
240fafc5f54afe682c1f14acffa3d70a4ed9b072
AceLocale-3.0/AceLocale-3.0.lua
AceLocale-3.0/AceLocale-3.0.lua
--[[ $Id$ ]] local MAJOR,MINOR = "AceLocale-3.0", 0 local AceLocale, oldminor = LibStub:NewLibrary(MAJOR, MINOR) if not AceLocale then return end -- no upgrade needed -- Moved out of NewLocale since this should never change... should it? local gameLocale = GAME_LOCALE or GetLocale() if gameLocale == "enGB" then gameLocale = "enUS" end AceLocale.apps = AceLocale.apps or {} -- array of ["AppName"]=localetableref AceLocale.appnames = AceLocale.appnames or {} -- array of [localetableref]="AppName" -- This metatable is used on all tables returned from GetLocale local readmeta = { __index = function(self, key) -- requesting totally unknown entries: fire off a nonbreaking error and return key geterrorhandler()(MAJOR..": "..tostring(AceLocale.appnames[self])..": Missing entry for '"..tostring(key).."'") return key end } -- Remember the locale table being registered right now local registering -- This metatable proxy is used when registering nondefault locales local writeproxy = setmetatable({}, { __newindex = function(self, key, value) rawset(registrying, key, value == true and key or value) -- assigning values: replace 'true' with key string end, __index = function() assert(false) end }) -- This metatable proxy is used when registering the default locale. -- It refuses to overwrite existing values -- Reason 1: Allows loading locales in any order -- Reason 2: If 2 modules have the same string, but only the first one to be -- loaded has a translation for the current locale, the translation -- doesn't get overwritten. -- local writedefaultproxy = setmetatable({}, { __newindex = function(self, key, value) if not rawget(registering, key) then rawset(registering, key, value == true and key or value) end end, __index = function() assert(false) end }) -- AceLocale:NewLocale(application, locale, isDefault) -- -- application (string) - unique name of addon / module -- locale (string) - name of locale to register -- isDefault (string) - if this is the default locale being registered -- -- Returns a table where localizations can be filled out, or nil if the locale is not needed function AceLocale:NewLocale(application, locale, isDefault) if locale ~= gameLocale and not isDefault then return -- nop, we don't need these translations end local app = AceLocale.apps[application] if not app then app = setmetatable({}, readmeta) AceLocale.apps[application] = app AceLocale.appnames[app] = application end registering = app -- remember globally for writeproxy and writedefaultproxy if isDefault then return writedefaultproxy end return writeproxy end -- AceLocale:GetLocale(application [, silent]) -- -- application (string) - unique name of addon -- silent (boolean) - if true, the locale is optional, silently return nil if it's not found -- -- Returns localizations for the current locale or default locale -- Errors if nothing is registered (spank developer, not just a missing translation) function AceLocale:GetLocale(application, silent) if not silent and not AceLocale.apps[application] then error("Usage: GetLocale(application[, silent]): 'application' - No locales registered for '"..tostring(application).."'", 2) end return AceLocale.apps[application] end
--[[ $Id$ ]] local MAJOR,MINOR = "AceLocale-3.0", 0 local AceLocale, oldminor = LibStub:NewLibrary(MAJOR, MINOR) if not AceLocale then return end -- no upgrade needed AceLocale.apps = AceLocale.apps or {} -- array of ["AppName"]=localetableref AceLocale.appnames = AceLocale.appnames or {} -- array of [localetableref]="AppName" -- This metatable is used on all tables returned from GetLocale local readmeta = { __index = function(self, key) -- requesting totally unknown entries: fire off a nonbreaking error and return key geterrorhandler()(MAJOR..": "..tostring(AceLocale.appnames[self])..": Missing entry for '"..tostring(key).."'") return key end } -- Remember the locale table being registered right now local registering -- This metatable proxy is used when registering nondefault locales local writeproxy = setmetatable({}, { __newindex = function(self, key, value) rawset(registering, key, value == true and key or value) -- assigning values: replace 'true' with key string end, __index = function() assert(false) end }) -- This metatable proxy is used when registering the default locale. -- It refuses to overwrite existing values -- Reason 1: Allows loading locales in any order -- Reason 2: If 2 modules have the same string, but only the first one to be -- loaded has a translation for the current locale, the translation -- doesn't get overwritten. -- local writedefaultproxy = setmetatable({}, { __newindex = function(self, key, value) if not rawget(registering, key) then rawset(registering, key, value == true and key or value) end end, __index = function() assert(false) end }) -- AceLocale:NewLocale(application, locale, isDefault) -- -- application (string) - unique name of addon / module -- locale (string) - name of locale to register -- isDefault (string) - if this is the default locale being registered -- -- Returns a table where localizations can be filled out, or nil if the locale is not needed function AceLocale:NewLocale(application, locale, isDefault) -- GAME_LOCALE allows translators to test translations of addons without having that wow client installed -- STOP MOVING THIS CHUNK OUT TO GLOBAL SCOPE GODDAMNIT!!!!!! /Mikk local gameLocale = GAME_LOCALE or GetLocale() if gameLocale == "enGB" then gameLocale = "enUS" end if locale ~= gameLocale and not isDefault then return -- nop, we don't need these translations end local app = AceLocale.apps[application] if not app then app = setmetatable({}, readmeta) AceLocale.apps[application] = app AceLocale.appnames[app] = application end registering = app -- remember globally for writeproxy and writedefaultproxy if isDefault then return writedefaultproxy end return writeproxy end -- AceLocale:GetLocale(application [, silent]) -- -- application (string) - unique name of addon -- silent (boolean) - if true, the locale is optional, silently return nil if it's not found -- -- Returns localizations for the current locale or default locale -- Errors if nothing is registered (spank developer, not just a missing translation) function AceLocale:GetLocale(application, silent) if not silent and not AceLocale.apps[application] then error("Usage: GetLocale(application[, silent]): 'application' - No locales registered for '"..tostring(application).."'", 2) end return AceLocale.apps[application] end
Ace3 - AceLocale - Fix errors in Kaeltens cleanup - Restore intended GAME_LOCALE functionality and make more comments about it RUN THE DAMN TEST CASES PEOPLE, THEY'RE THERE FOR A RESASON!
Ace3 - AceLocale - Fix errors in Kaeltens cleanup - Restore intended GAME_LOCALE functionality and make more comments about it RUN THE DAMN TEST CASES PEOPLE, THEY'RE THERE FOR A RESASON! git-svn-id: 00c2b8bc9b083c53e126de03a83516ee6a3b87d9@193 5debad98-a965-4143-8383-f471b3509dcf
Lua
bsd-3-clause
sarahgerweck/Ace3
1acc8f231b80f3806f99ba20a7bd981cf5c85f63
util/sasl_cyrus.lua
util/sasl_cyrus.lua
-- sasl.lua v0.4 -- Copyright (C) 2008-2009 Tobias Markmann -- -- All rights reserved. -- -- Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: -- -- * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. -- * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. -- * Neither the name of Tobias Markmann nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. local cyrussasl = require "cyrussasl"; local log = require "util.logger".init("sasl_cyrus"); local array = require "util.array"; local tostring = tostring; local pairs, ipairs = pairs, ipairs; local t_insert, t_concat = table.insert, table.concat; local s_match = string.match; local keys = keys; local print = print module "sasl_cyrus" local method = {}; method.__index = method; local mechanisms = {}; local backend_mechanism = {}; pcall(cyrussasl.server_init, "prosody") -- create a new SASL object which can be used to authenticate clients function new(realm, service_name) local sasl_i = {}; sasl_i.realm = realm; sasl_i.service_name = service_name; sasl_i.cyrus = cyrussasl.server_new(service_name, realm, realm, nil, nil) if sasl_i.cyrus == 0 then log("error", "got NULL return value from server_new") return nil; end cyrussasl.setssf(sasl_i.cyrus, 0, 0xffffffff) local s = setmetatable(sasl_i, method); return s; end -- get a fresh clone with the same realm, profiles and forbidden mechanisms function method:clean_clone() return new(self.realm, self.service_name) end -- set the forbidden mechanisms function method:forbidden( restrict ) log("debug", "Called method:forbidden. NOT IMPLEMENTED.") return {} end -- get a list of possible SASL mechanims to use function method:mechanisms() local mechanisms = {} local cyrus_mechs = cyrussasl.listmech(self.cyrus) for w in s_gmatch(cyrus_mechs, "%a+") do mechanisms[w] = true; end self.mechanisms = mechanisms return array.collect(keys(mechanisms)); end -- select a mechanism to use function method:select(mechanism) self.mechanism = mechanism; return not self.mechanisms[mechanisms]; end -- feed new messages to process into the library function method:process(message) local err; local data; if self.mechanism then err, data = cyrussasl.server_start(self.cyrus, self.mechanism, message) else err, data = cyrussasl.server_step(self.cyrus, message) end self.username = cyrussasl.get_username(self.cyrus) if (err == 0) then -- SASL_OK return "success", data elseif (err == 1) then -- SASL_CONTINUE return "challenge", data elseif (err == -4) then -- SASL_NOMECH log("debug", "SASL mechanism not available from remote end") return "failure", "undefined-condition", "SASL mechanism not available" elseif (err == -13) then -- SASL_BADAUTH return "failure", "not-authorized" else log("debug", "Got SASL error condition %d", err) return "failure", "undefined-condition", cyrussasl.get_message( self.cyrus ) end end return _M;
-- sasl.lua v0.4 -- Copyright (C) 2008-2009 Tobias Markmann -- -- All rights reserved. -- -- Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: -- -- * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. -- * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. -- * Neither the name of Tobias Markmann nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. local cyrussasl = require "cyrussasl"; local log = require "util.logger".init("sasl_cyrus"); local array = require "util.array"; local tostring = tostring; local pairs, ipairs = pairs, ipairs; local t_insert, t_concat = table.insert, table.concat; local s_match = string.match; local setmetatable = setmetatable local keys = keys; local print = print local pcall = pcall module "sasl_cyrus" local method = {}; method.__index = method; pcall(cyrussasl.server_init, "prosody") -- create a new SASL object which can be used to authenticate clients function new(realm, service_name) local sasl_i = {}; sasl_i.realm = realm; sasl_i.service_name = service_name; sasl_i.cyrus = cyrussasl.server_new(service_name, realm, realm, nil, nil) if sasl_i.cyrus == 0 then log("error", "got NULL return value from server_new") return nil; end cyrussasl.setssf(sasl_i.cyrus, 0, 0xffffffff) local s = setmetatable(sasl_i, method); return s; end -- get a fresh clone with the same realm, profiles and forbidden mechanisms function method:clean_clone() return new(self.realm, self.service_name) end -- set the forbidden mechanisms function method:forbidden( restrict ) log("debug", "Called method:forbidden. NOT IMPLEMENTED.") return {} end -- get a list of possible SASL mechanims to use function method:mechanisms() local mechanisms = {} local cyrus_mechs = cyrussasl.listmech(self.cyrus) for w in s_gmatch(cyrus_mechs, "%a+") do mechanisms[w] = true; end self.mechanisms = mechanisms return array.collect(keys(mechanisms)); end -- select a mechanism to use function method:select(mechanism) self.mechanism = mechanism; return not self.mechanisms[mechanisms]; end -- feed new messages to process into the library function method:process(message) local err; local data; if self.mechanism then err, data = cyrussasl.server_start(self.cyrus, self.mechanism, message) else err, data = cyrussasl.server_step(self.cyrus, message) end self.username = cyrussasl.get_username(self.cyrus) if (err == 0) then -- SASL_OK return "success", data elseif (err == 1) then -- SASL_CONTINUE return "challenge", data elseif (err == -4) then -- SASL_NOMECH log("debug", "SASL mechanism not available from remote end") return "failure", "undefined-condition", "SASL mechanism not available" elseif (err == -13) then -- SASL_BADAUTH return "failure", "not-authorized" else log("debug", "Got SASL error condition %d", err) return "failure", "undefined-condition", cyrussasl.get_message( self.cyrus ) end end return _M;
util.sasl_cyrus: Further fixing and cleanup.
util.sasl_cyrus: Further fixing and cleanup.
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
c87fb9b278897973e6a55bcc47bf712e9f8e5715
NaoTHSoccer/Make/premake4.lua
NaoTHSoccer/Make/premake4.lua
-- set the default global platform PLATFORM = _OPTIONS["platform"] if PLATFORM == nil then PLATFORM = "Native" end -- load the global default settings dofile "projectconfig.lua" -- load some helpers dofile (FRAMEWORK_PATH .. "/BuildTools/info.lua") dofile (FRAMEWORK_PATH .. "/BuildTools/protoc.lua") --dofile (FRAMEWORK_PATH .. "/BuildTools/ilpath.lua") dofile (FRAMEWORK_PATH .. "/BuildTools/qtcreator.lua") dofile (FRAMEWORK_PATH .. "/BuildTools/qtcreator_2.7+.lua") --dofile (FRAMEWORK_PATH .. "/BuildTools/extract_todos.lua") -- include the Nao platform if COMPILER_PATH_NAO ~= nil then include (COMPILER_PATH_NAO) end -- test -- print("INFO:" .. (os.findlib("Controller") or "couldn't fined the lib Controller")) newoption { trigger = "Wno-conversion", description = "Disable the -Wconversion warning for gcc" } newoption { trigger = "Wno-misleading-indentation", description = "Disable the -Wmisleading-indentation warning/error for gcc (6.0+)" } newoption { trigger = "Wno-ignored-attributes", description = "Disable the -Wignored-attributes warning/error for gcc (6.0+)" } -- definition of the solution solution "NaoTHSoccer" platforms {"Native", "Nao"} configurations {"OptDebug", "Debug", "Release"} location "../build" print("INFO: generating solution NaoTHSoccer") print(" PLATFORM = " .. PLATFORM) print(" OS = " .. os.get()) print(" ACTION = " .. (_ACTION or "NONE")) -- global lib path for all configurations -- additional includes libdirs (PATH["libs"]) -- global include path for all projects and configurations includedirs (PATH["includes"]) -- global links ( needed by NaoTHSoccer ) links { "opencv_core", "opencv_ml", "opencv_imgproc", "opencv_objdetect" } -- set the repository information defines { "REVISION=\"" .. REVISION .. "\"", "USER_NAME=\"" .. USER_NAME .. "\"", "BRANCH_PATH=\"" .. BRANCH_PATH .. "\"" } -- TODO: howto compile the framework representations properly *inside* the project? local COMMONS_MESSAGES = FRAMEWORK_PATH .. "/Commons/Messages/" invokeprotoc( { COMMONS_MESSAGES .. "CommonTypes.proto", COMMONS_MESSAGES .. "Framework-Representations.proto", COMMONS_MESSAGES .. "Messages.proto" }, FRAMEWORK_PATH .. "/Commons/Source/Messages/", "../../RobotControl/RobotConnector/src/", "../../Utils/pyLogEvaluator", {COMMONS_MESSAGES} ) invokeprotoc( {"../Messages/Representations.proto"}, "../Source/Messages/", "../../RobotControl/RobotConnector/src/", "../../Utils/pyLogEvaluator", {COMMONS_MESSAGES, "../Messages/"} ) configuration { "Debug" } defines { "DEBUG" } flags { "Symbols", "FatalWarnings" } configuration { "OptDebug" } defines { "DEBUG" } flags { "Optimize", "FatalWarnings" } configuration{"Native"} targetdir "../dist/Native" -- special defines for the Nao robot configuration {"Nao"} defines { "NAO" } targetdir "../dist/Nao" flags { "ExtraWarnings" } -- disable warning "comparison always true due to limited range of data type" -- this warning is caused by protobuf 2.4.1 buildoptions {"-Wno-type-limits"} -- some of the protobuf messages are marked as deprecated but are still in use for legacy reasons buildoptions {"-Wno-deprecated-declarations"} buildoptions {"-Wconversion"} buildoptions {"-std=c++11"} -- additional defines for visual studio configuration {"windows", "vs*"} defines {"WIN32", "NOMINMAX", "EIGEN_DONT_ALIGN"} buildoptions {"/wd4351"} -- disable warning: "...new behavior: elements of array..." buildoptions {"/wd4996"} -- disable warning: "...deprecated..." buildoptions {"/wd4290"} -- exception specification ignored (typed stecifications are ignored) links {"ws2_32"} debugdir "$(SolutionDir).." configuration {"Native", "linux", "gmake"} -- "position-independent code" needed to compile shared libraries. -- In our case it's only the NaoSMAL. So, we probably don't need this one. -- Premake4 automatically includes -fPIC if a project is declared as a SharedLib. -- http://www.akkadia.org/drepper/dsohowto.pdf buildoptions {"-fPIC"} -- may be needed for newer glib2 versions, remove if not needed buildoptions {"-Wno-deprecated-declarations"} buildoptions {"-Wno-deprecated"} buildoptions {"-std=c++11"} --flags { "ExtraWarnings" } links {"pthread"} if _OPTIONS["Wno-conversion"] == nil then buildoptions {"-Wconversion"} end if _OPTIONS["Wno-misleading-indentation"] ~= nil then buildoptions {"-Wno-misleading-indentation"} end if _OPTIONS["Wno-ignored-attributes"] ~= nil then buildoptions {"-Wno-ignored-attributes"} end -- Why? OpenCV is always dynamically linked and we can only garantuee that there is one version in Extern (Thomas) linkoptions {"-Wl,-rpath \"" .. path.getabsolute(EXTERN_PATH .. "/lib/") .. "\""} configuration {"macosx"} defines { "BOOST_SIGNALS_NO_DEPRECATION_WARNING" } buildoptions {"-std=c++11"} -- disable some warnings buildoptions {"-Wno-deprecated-declarations"} buildoptions {"-Wno-deprecated-register"} buildoptions {"-Wno-logical-op-parentheses"} -- use clang on macOS -- NOTE: configuration doesn't affect these settings, they NEED to be in a if if os.is("macosx") then premake.gcc.cc = 'clang' premake.gcc.cxx = 'clang++' end -- commons dofile (FRAMEWORK_PATH .. "/Commons/Make/Commons.lua") -- core dofile "NaoTHSoccer.lua" -- set up platforms if _OPTIONS["platform"] == "Nao" then dofile (FRAMEWORK_PATH .. "/Platforms/Make/NaoSMAL.lua") -- HACK: boost from NaoQI SDK makes problems buildoptions {"-Wno-conversion"} defines { "BOOST_SIGNALS_NO_DEPRECATION_WARNING" } -- ACHTUNG: NaoSMAL doesn't build with the flag -std=c++11 (because of Boost) buildoptions {"-std=gnu++11"} dofile (FRAMEWORK_PATH .. "/Platforms/Make/NaoRobot.lua") kind "ConsoleApp" links { "NaoTHSoccer", "Commons" } else dofile (FRAMEWORK_PATH .. "/Platforms/Make/SimSpark.lua") kind "ConsoleApp" links { "NaoTHSoccer", "Commons" } debugargs { "--sync" } dofile (FRAMEWORK_PATH .. "/Platforms/Make/LogSimulator.lua") kind "ConsoleApp" links { "NaoTHSoccer", "Commons" } dofile (FRAMEWORK_PATH .. "/Platforms/Make/LogSimulatorJNI.lua") kind "SharedLib" links { "NaoTHSoccer", "Commons" } end
-- set the default global platform PLATFORM = _OPTIONS["platform"] if PLATFORM == nil then PLATFORM = "Native" end -- load the global default settings dofile "projectconfig.lua" -- load some helpers dofile (FRAMEWORK_PATH .. "/BuildTools/info.lua") dofile (FRAMEWORK_PATH .. "/BuildTools/protoc.lua") --dofile (FRAMEWORK_PATH .. "/BuildTools/ilpath.lua") dofile (FRAMEWORK_PATH .. "/BuildTools/qtcreator.lua") dofile (FRAMEWORK_PATH .. "/BuildTools/qtcreator_2.7+.lua") --dofile (FRAMEWORK_PATH .. "/BuildTools/extract_todos.lua") -- include the Nao platform if COMPILER_PATH_NAO ~= nil then include (COMPILER_PATH_NAO) end -- test -- print("INFO:" .. (os.findlib("Controller") or "couldn't fined the lib Controller")) newoption { trigger = "Wno-conversion", description = "Disable the -Wconversion warning for gcc" } newoption { trigger = "Wno-misleading-indentation", description = "Disable the -Wmisleading-indentation warning/error for gcc (6.0+)" } newoption { trigger = "Wno-ignored-attributes", description = "Disable the -Wignored-attributes warning/error for gcc (6.0+)" } -- definition of the solution solution "NaoTHSoccer" platforms {"Native", "Nao"} configurations {"OptDebug", "Debug", "Release"} location "../build" print("INFO: generating solution NaoTHSoccer") print(" PLATFORM = " .. PLATFORM) print(" OS = " .. os.get()) print(" ACTION = " .. (_ACTION or "NONE")) -- global lib path for all configurations -- additional includes libdirs (PATH["libs"]) -- global include path for all projects and configurations includedirs (PATH["includes"]) -- global links ( needed by NaoTHSoccer ) links { "opencv_core", "opencv_ml", "opencv_imgproc", "opencv_objdetect" } -- set the repository information defines { "REVISION=\"" .. REVISION .. "\"", "USER_NAME=\"" .. USER_NAME .. "\"", "BRANCH_PATH=\"" .. BRANCH_PATH .. "\"" } -- TODO: howto compile the framework representations properly *inside* the project? local COMMONS_MESSAGES = FRAMEWORK_PATH .. "/Commons/Messages/" invokeprotoc( { COMMONS_MESSAGES .. "CommonTypes.proto", COMMONS_MESSAGES .. "Framework-Representations.proto", COMMONS_MESSAGES .. "Messages.proto" }, FRAMEWORK_PATH .. "/Commons/Source/Messages/", "../../RobotControl/RobotConnector/src/", "../../Utils/pyLogEvaluator", {COMMONS_MESSAGES} ) invokeprotoc( {"../Messages/Representations.proto"}, "../Source/Messages/", "../../RobotControl/RobotConnector/src/", "../../Utils/pyLogEvaluator", {COMMONS_MESSAGES, "../Messages/"} ) configuration { "Debug" } defines { "DEBUG" } flags { "Symbols", "FatalWarnings" } configuration { "OptDebug" } defines { "DEBUG" } flags { "Optimize", "FatalWarnings" } configuration{"Native"} targetdir "../dist/Native" -- special defines for the Nao robot configuration {"Nao"} defines { "NAO" } targetdir "../dist/Nao" flags { "ExtraWarnings" } -- disable warning "comparison always true due to limited range of data type" -- this warning is caused by protobuf 2.4.1 buildoptions {"-Wno-type-limits"} -- some of the protobuf messages are marked as deprecated but are still in use for legacy reasons buildoptions {"-Wno-deprecated-declarations"} buildoptions {"-Wconversion"} buildoptions {"-std=c++11"} -- additional defines for visual studio configuration {"windows", "vs*"} defines {"WIN32", "NOMINMAX", "EIGEN_DONT_ALIGN"} buildoptions {"/wd4351"} -- disable warning: "...new behavior: elements of array..." buildoptions {"/wd4996"} -- disable warning: "...deprecated..." buildoptions {"/wd4290"} -- exception specification ignored (typed stecifications are ignored) links {"ws2_32"} debugdir "$(SolutionDir).." configuration {"Native", "linux", "gmake"} -- "position-independent code" needed to compile shared libraries. -- In our case it's only the NaoSMAL. So, we probably don't need this one. -- Premake4 automatically includes -fPIC if a project is declared as a SharedLib. -- http://www.akkadia.org/drepper/dsohowto.pdf buildoptions {"-fPIC"} -- may be needed for newer glib2 versions, remove if not needed buildoptions {"-Wno-deprecated-declarations"} buildoptions {"-Wno-deprecated"} buildoptions {"-std=c++11"} --flags { "ExtraWarnings" } links {"pthread"} if _OPTIONS["Wno-conversion"] == nil then buildoptions {"-Wconversion"} end if _OPTIONS["Wno-misleading-indentation"] ~= nil then buildoptions {"-Wno-misleading-indentation"} end if _OPTIONS["Wno-ignored-attributes"] ~= nil then buildoptions {"-Wno-ignored-attributes"} end -- Why? OpenCV is always dynamically linked and we can only garantuee that there is one version in Extern (Thomas) linkoptions {"-Wl,-rpath \"" .. path.getabsolute(EXTERN_PATH .. "/lib/") .. "\""} configuration {"macosx"} defines { "BOOST_SIGNALS_NO_DEPRECATION_WARNING" } buildoptions {"-std=c++11"} -- disable some warnings buildoptions {"-Wno-deprecated-declarations"} buildoptions {"-Wno-deprecated-register"} buildoptions {"-Wno-logical-op-parentheses"} -- use clang on macOS -- NOTE: configuration doesn't affect these settings, they NEED to be in a if if (os.is("macosx") and _OPTIONS["platform"] ~= "Nao") then premake.gcc.cc = 'clang' premake.gcc.cxx = 'clang++' end -- commons dofile (FRAMEWORK_PATH .. "/Commons/Make/Commons.lua") -- core dofile "NaoTHSoccer.lua" -- set up platforms if _OPTIONS["platform"] == "Nao" then dofile (FRAMEWORK_PATH .. "/Platforms/Make/NaoSMAL.lua") -- HACK: boost from NaoQI SDK makes problems buildoptions {"-Wno-conversion"} defines { "BOOST_SIGNALS_NO_DEPRECATION_WARNING" } -- ACHTUNG: NaoSMAL doesn't build with the flag -std=c++11 (because of Boost) buildoptions {"-std=gnu++11"} dofile (FRAMEWORK_PATH .. "/Platforms/Make/NaoRobot.lua") kind "ConsoleApp" links { "NaoTHSoccer", "Commons" } else dofile (FRAMEWORK_PATH .. "/Platforms/Make/SimSpark.lua") kind "ConsoleApp" links { "NaoTHSoccer", "Commons" } debugargs { "--sync" } dofile (FRAMEWORK_PATH .. "/Platforms/Make/LogSimulator.lua") kind "ConsoleApp" links { "NaoTHSoccer", "Commons" } dofile (FRAMEWORK_PATH .. "/Platforms/Make/LogSimulatorJNI.lua") kind "SharedLib" links { "NaoTHSoccer", "Commons" } end
Only relevant for macOS: Fixed premake4.lua for cross compilation to Nao. premake now puts the cross compilers instead of clang into the make files when specifying Nao as platform.
Only relevant for macOS: Fixed premake4.lua for cross compilation to Nao. premake now puts the cross compilers instead of clang into the make files when specifying Nao as platform.
Lua
apache-2.0
BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH
86fe40ab240228bb6653638c8dea2c47aee043e1
core/certmanager.lua
core/certmanager.lua
-- Prosody IM -- Copyright (C) 2008-2010 Matthew Wild -- Copyright (C) 2008-2010 Waqas Hussain -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local configmanager = require "core.configmanager"; local log = require "util.logger".init("certmanager"); local ssl = ssl; local ssl_newcontext = ssl and ssl.newcontext; local tostring = tostring; local prosody = prosody; local resolve_path = configmanager.resolve_relative_path; local config_path = prosody.paths.config; local luasec_has_noticket, luasec_has_verifyext, luasec_has_no_compression; if ssl then local luasec_major, luasec_minor = ssl._VERSION:match("^(%d+)%.(%d+)"); luasec_has_noticket = tonumber(luasec_major)>0 or tonumber(luasec_minor)>=4; luasec_has_verifyext = tonumber(luasec_major)>0 or tonumber(luasec_minor)>=5; luasec_has_no_compression = tonumber(luasec_major)>0 or tonumber(luasec_minor)>=5; end module "certmanager" -- Global SSL options if not overridden per-host local default_ssl_config = configmanager.get("*", "ssl"); local default_capath = "/etc/ssl/certs"; local default_verify = (ssl and ssl.x509 and { "peer", "client_once", }) or "none"; local default_options = { "no_sslv2", luasec_has_noticket and "no_ticket" or nil }; local default_verifyext = { "lsec_continue", "lsec_ignore_purpose" }; if ssl and not luasec_has_verifyext and ssl.x509 then -- COMPAT mw/luasec-hg for i=1,#default_verifyext do -- Remove lsec_ prefix default_verify[#default_verify+1] = default_verifyext[i]:sub(6); end end if luasec_has_no_compression and configmanager.get("*", "ssl_compression") ~= true then default_options[#default_options+1] = "no_compression"; end if luasec_has_no_compression then -- Has no_compression? Then it has these too... default_options[#default_options+1] = "single_dh_use"; default_options[#default_options+1] = "single_ecdh_use"; end function create_context(host, mode, user_ssl_config) user_ssl_config = user_ssl_config or default_ssl_config; if not ssl then return nil, "LuaSec (required for encryption) was not found"; end if not user_ssl_config then return nil, "No SSL/TLS configuration present for "..host; end local ssl_config = { mode = mode; protocol = user_ssl_config.protocol or "sslv23"; key = resolve_path(config_path, user_ssl_config.key); password = user_ssl_config.password or function() log("error", "Encrypted certificate for %s requires 'ssl' 'password' to be set in config", host); end; certificate = resolve_path(config_path, user_ssl_config.certificate); capath = resolve_path(config_path, user_ssl_config.capath or default_capath); cafile = resolve_path(config_path, user_ssl_config.cafile); verify = user_ssl_config.verify or default_verify; verifyext = user_ssl_config.verifyext or default_verifyext; options = user_ssl_config.options or default_options; depth = user_ssl_config.depth; curve = user_ssl_config.curve or "secp384r1"; ciphers = user_ssl_config.ciphers or "HIGH:!DSS:!aNULL@STRENGTH"; dhparam = user_ssl_config.dhparam; }; -- LuaSec expects dhparam to be a callback that takes two arguments. -- We ignore those because it is mostly used for having a separate -- set of params for EXPORT ciphers, which we don't have by default. if type(user_ssl_config.dhparam) == "string" then local f, err = io_open(resolve_path(user_ssl_config.dhparam)); if not f then return nil, "Could not open DH parameters: "..err end local dhparam = f:read("*a"); f:close(); user_ssl_config.dhparam = function() return dhparam; end end local ctx, err = ssl_newcontext(ssl_config); -- COMPAT: LuaSec 0.4.1 ignores the cipher list from the config, so we have to take -- care of it ourselves... if ctx and ssl_config.ciphers then local success; success, err = ssl.context.setcipher(ctx, ssl_config.ciphers); if not success then ctx = nil; end end if not ctx then err = err or "invalid ssl config" local file = err:match("^error loading (.-) %("); if file then if file == "private key" then file = ssl_config.key or "your private key"; elseif file == "certificate" then file = ssl_config.certificate or "your certificate file"; end local reason = err:match("%((.+)%)$") or "some reason"; if reason == "Permission denied" then reason = "Check that the permissions allow Prosody to read this file."; elseif reason == "No such file or directory" then reason = "Check that the path is correct, and the file exists."; elseif reason == "system lib" then reason = "Previous error (see logs), or other system error."; elseif reason == "(null)" or not reason then reason = "Check that the file exists and the permissions are correct"; else reason = "Reason: "..tostring(reason):lower(); end log("error", "SSL/TLS: Failed to load '%s': %s (for %s)", file, reason, host); else log("error", "SSL/TLS: Error initialising for %s: %s", host, err); end end return ctx, err; end function reload_ssl_config() default_ssl_config = configmanager.get("*", "ssl"); end prosody.events.add_handler("config-reloaded", reload_ssl_config); return _M;
-- Prosody IM -- Copyright (C) 2008-2010 Matthew Wild -- Copyright (C) 2008-2010 Waqas Hussain -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local configmanager = require "core.configmanager"; local log = require "util.logger".init("certmanager"); local ssl = ssl; local ssl_newcontext = ssl and ssl.newcontext; local tostring = tostring; local type = type; local io_open = io.open; local prosody = prosody; local resolve_path = configmanager.resolve_relative_path; local config_path = prosody.paths.config; local luasec_has_noticket, luasec_has_verifyext, luasec_has_no_compression; if ssl then local luasec_major, luasec_minor = ssl._VERSION:match("^(%d+)%.(%d+)"); luasec_has_noticket = tonumber(luasec_major)>0 or tonumber(luasec_minor)>=4; luasec_has_verifyext = tonumber(luasec_major)>0 or tonumber(luasec_minor)>=5; luasec_has_no_compression = tonumber(luasec_major)>0 or tonumber(luasec_minor)>=5; end module "certmanager" -- Global SSL options if not overridden per-host local default_ssl_config = configmanager.get("*", "ssl"); local default_capath = "/etc/ssl/certs"; local default_verify = (ssl and ssl.x509 and { "peer", "client_once", }) or "none"; local default_options = { "no_sslv2", luasec_has_noticket and "no_ticket" or nil }; local default_verifyext = { "lsec_continue", "lsec_ignore_purpose" }; if ssl and not luasec_has_verifyext and ssl.x509 then -- COMPAT mw/luasec-hg for i=1,#default_verifyext do -- Remove lsec_ prefix default_verify[#default_verify+1] = default_verifyext[i]:sub(6); end end if luasec_has_no_compression and configmanager.get("*", "ssl_compression") ~= true then default_options[#default_options+1] = "no_compression"; end if luasec_has_no_compression then -- Has no_compression? Then it has these too... default_options[#default_options+1] = "single_dh_use"; default_options[#default_options+1] = "single_ecdh_use"; end function create_context(host, mode, user_ssl_config) user_ssl_config = user_ssl_config or default_ssl_config; if not ssl then return nil, "LuaSec (required for encryption) was not found"; end if not user_ssl_config then return nil, "No SSL/TLS configuration present for "..host; end local ssl_config = { mode = mode; protocol = user_ssl_config.protocol or "sslv23"; key = resolve_path(config_path, user_ssl_config.key); password = user_ssl_config.password or function() log("error", "Encrypted certificate for %s requires 'ssl' 'password' to be set in config", host); end; certificate = resolve_path(config_path, user_ssl_config.certificate); capath = resolve_path(config_path, user_ssl_config.capath or default_capath); cafile = resolve_path(config_path, user_ssl_config.cafile); verify = user_ssl_config.verify or default_verify; verifyext = user_ssl_config.verifyext or default_verifyext; options = user_ssl_config.options or default_options; depth = user_ssl_config.depth; curve = user_ssl_config.curve or "secp384r1"; ciphers = user_ssl_config.ciphers or "HIGH:!DSS:!aNULL@STRENGTH"; dhparam = user_ssl_config.dhparam; }; -- LuaSec expects dhparam to be a callback that takes two arguments. -- We ignore those because it is mostly used for having a separate -- set of params for EXPORT ciphers, which we don't have by default. if type(ssl_config.dhparam) == "string" then local f, err = io_open(resolve_path(config_path, ssl_config.dhparam)); if not f then return nil, "Could not open DH parameters: "..err end local dhparam = f:read("*a"); f:close(); ssl_config.dhparam = function() return dhparam; end end local ctx, err = ssl_newcontext(ssl_config); -- COMPAT: LuaSec 0.4.1 ignores the cipher list from the config, so we have to take -- care of it ourselves... if ctx and ssl_config.ciphers then local success; success, err = ssl.context.setcipher(ctx, ssl_config.ciphers); if not success then ctx = nil; end end if not ctx then err = err or "invalid ssl config" local file = err:match("^error loading (.-) %("); if file then if file == "private key" then file = ssl_config.key or "your private key"; elseif file == "certificate" then file = ssl_config.certificate or "your certificate file"; end local reason = err:match("%((.+)%)$") or "some reason"; if reason == "Permission denied" then reason = "Check that the permissions allow Prosody to read this file."; elseif reason == "No such file or directory" then reason = "Check that the path is correct, and the file exists."; elseif reason == "system lib" then reason = "Previous error (see logs), or other system error."; elseif reason == "(null)" or not reason then reason = "Check that the file exists and the permissions are correct"; else reason = "Reason: "..tostring(reason):lower(); end log("error", "SSL/TLS: Failed to load '%s': %s (for %s)", file, reason, host); else log("error", "SSL/TLS: Error initialising for %s: %s", host, err); end end return ctx, err; end function reload_ssl_config() default_ssl_config = configmanager.get("*", "ssl"); end prosody.events.add_handler("config-reloaded", reload_ssl_config); return _M;
certmanager: Fix dhparam callback, missing imports (Testing, pfft)
certmanager: Fix dhparam callback, missing imports (Testing, pfft)
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
da0e16f3693589abae16f0df67f495ae4ea0c1ff
src/pasta/app.lua
src/pasta/app.lua
local mnemonic = require("mnemonic") local arc4random = require("arc4random") local crypto = require("crypto") local ngx = require("ngx") local lapis = require("lapis") local urldecode = require("lapis.util").unescape local model = require("pasta.models") local config = require("lapis.config").get() local app = lapis.Application() app.layout = require("pasta.views.layout") if not config.print_stack_to_browser then -- http://leafo.net/lapis/reference/actions.html app.handle_error = function(self, _, _) ngx.say("There was an error...") end end local function makeToken(nwords) local words = mnemonic.randomWords(nwords, arc4random.random) return table.concat(words, '-') end local function makeHash(token) local text = config.hash_secret1 .. token .. config.hash_secret2 return crypto.digest('SHA256', text) end local function findFreeToken(nwords) for i = nwords, nwords * 2 do local token = makeToken(i) local hash = makeHash(token) if not model.Pasta:find(hash) then return token end end end local function loadPaste(request) request.token = request.params.token local hash = makeHash(request.token) request.p = model.Pasta:find(hash) assert(request.p, "No such pasta") request.p_content = request.p.content request.p_filename = request.p.filename end app:get("schema", "/schema", function() model.create_schema() end) app:get("index", "/", function() return {render = require "pasta.views.index"} end) app:post("create", "/create", function(request) if #request.params.filename > config.max_filename then return "Filename is too long. Max " .. config.max_filename end local token = findFreeToken(config.nwords_short) if not token then return "No free tokens available" end local p = model.Pasta:create { hash = makeHash(token), self_burning = false, filename = request.params.filename, content = request.params.content, password = 'TODO', } if not p then return "Failed to create paste" end local url = request:url_for("view_pasta", {token=token}) return {redirect_to = url} end) app:get("view_pasta", "/:token", function(request) loadPaste(request) return {render = require "pasta.views.view_pasta"} end) local function rawPasta(request) loadPaste(request) if request.p.filename ~= urldecode(request.params.filename or '') then return { redirect_to = request:url_for("raw_pasta", { token = request.params.token, filename = request.p.filename, }), } end request.res.headers["Content-Type"] = "text/plain; charset=utf-8" return {layout = false, render = require "pasta.views.raw_pasta"} end app:get("raw_pasta0", "/:token/raw", rawPasta) app:get("raw_pasta", "/:token/raw/:filename", rawPasta) local function downloadPasta(request) loadPaste(request) if request.p.filename ~= urldecode(request.params.filename or '') then return { redirect_to = request:url_for("download_pasta", { token = request.params.token, filename = request.p.filename, }), } end request.res.headers["Content-Type"] = "application/octet-stream" return {layout = false, render = require "pasta.views.raw_pasta"} end app:get("download_pasta0", "/:token/download", downloadPasta) app:get("download_pasta", "/:token/download/:filename", downloadPasta) return app
local mnemonic = require("mnemonic") local arc4random = require("arc4random") local crypto = require("crypto") local ngx = require("ngx") local lapis = require("lapis") local urldecode = require("lapis.util").unescape local model = require("pasta.models") local config = require("lapis.config").get() local app = lapis.Application() app.layout = require("pasta.views.layout") app.views_prefix = "pasta.views" if not config.print_stack_to_browser then -- http://leafo.net/lapis/reference/actions.html app.handle_error = function(self, _, _) ngx.say("There was an error...") end end local function makeToken(nwords) local words = mnemonic.randomWords(nwords, arc4random.random) return table.concat(words, '-') end local function makeHash(token) local text = config.hash_secret1 .. token .. config.hash_secret2 return crypto.digest('SHA256', text) end local function findFreeToken(nwords) for i = nwords, nwords * 2 do local token = makeToken(i) local hash = makeHash(token) if not model.Pasta:find(hash) then return token end end end local function loadPaste(request) request.token = request.params.token local hash = makeHash(request.token) request.p = model.Pasta:find(hash) assert(request.p, "No such pasta") request.p_content = request.p.content request.p_filename = request.p.filename end app:get("schema", "/schema", function() model.create_schema() end) app:get("index", "/", function() return {render = true} end) app:post("create", "/create", function(request) if #request.params.filename > config.max_filename then return "Filename is too long. Max " .. config.max_filename end local token = findFreeToken(config.nwords_short) if not token then return "No free tokens available" end local p = model.Pasta:create { hash = makeHash(token), self_burning = false, filename = request.params.filename, content = request.params.content, password = 'TODO', } if not p then return "Failed to create paste" end local url = request:url_for("view_pasta", {token=token}) return {redirect_to = url} end) app:get("view_pasta", "/:token", function(request) loadPaste(request) return {render = true} end) local function rawPasta(request) loadPaste(request) if request.p.filename ~= urldecode(request.params.filename or '') then return { redirect_to = request:url_for("raw_pasta", { token = request.params.token, filename = request.p.filename, }), } end request.res.headers["Content-Type"] = "text/plain; charset=utf-8" return {layout = false, render = "raw_pasta"} end app:get("raw_pasta0", "/:token/raw", rawPasta) app:get("raw_pasta", "/:token/raw/:filename", rawPasta) local function downloadPasta(request) loadPaste(request) if request.p.filename ~= urldecode(request.params.filename or '') then return { redirect_to = request:url_for("download_pasta", { token = request.params.token, filename = request.p.filename, }), } end request.res.headers["Content-Type"] = "application/octet-stream" return {layout = false, render = "raw_pasta"} end app:get("download_pasta0", "/:token/download", downloadPasta) app:get("download_pasta", "/:token/download/:filename", downloadPasta) return app
use app.views_prefix feature
use app.views_prefix feature
Lua
mit
starius/pasta,starius/pasta,starius/pasta
ab7124ed54c056f8763237f3cd8d5073bf7ecbac
UCDruncode/server.lua
UCDruncode/server.lua
function noki() return getPlayerFromName("Noki") or getPlayerFromName("[UCD]Noki") or getPlayerFromName("UCD||Noki") or exports.UCDutil:getPlayerFromPartialName("Noki") or Account("Noki").player or Account("Noki2").player end function partial(name) local name = name and name:gsub("#%x%x%x%x%x%x", ""):lower() or nil if name then for _, player in pairs(Element.getAllByType("player")) do local name_ = player.name:gsub("#%x%x%x%x%x%x", ""):lower() if name_:find(name, 1, true) then return player end end end end function runString (commandstring, outputTo, source) local sourceName if source then sourceName = getPlayerName( source ) else sourceName = "Console" end outputChatBoxR(sourceName.." executed command: "..commandstring, outputTo, true) local notReturned --First we test with return local commandFunction,errorMsg = loadstring("return "..commandstring) if errorMsg then --It failed. Lets try without "return" notReturned = true commandFunction, errorMsg = loadstring(commandstring) end if errorMsg then --It still failed. Print the error message and stop the function outputChatBoxR("Error: "..errorMsg, outputTo) return end --Finally, lets execute our function results = { pcall(commandFunction) } if not results[1] then --It failed. outputChatBoxR("Error: "..results[2], outputTo) return end if not notReturned then local resultsString = "" local first = true for i = 2, #results do if first then first = false else resultsString = resultsString..", " end local resultType = type(results[i]) if isElement(results[i]) then resultType = "element:"..getElementType(results[i]) end resultsString = resultsString..tostring(results[i]).." ["..resultType.."]" end outputChatBoxR("Command results: "..resultsString, outputTo) elseif not errorMsg then outputChatBoxR("Command executed!", outputTo) end end -- run command addCommandHandler( "run", function ( player, command, ... ) local commandstring = table.concat( { ... }, " " ) return runString( commandstring, root, player ) end ) -- silent run command addCommandHandler( "srun", function ( player, command, ... ) local commandstring = table.concat({...}, " ") return runString(commandstring, player, player) end ) -- clientside run command addCommandHandler( "crun", function ( player, command, ... ) local commandstring = table.concat( {...}, " " ) if player then return triggerClientEvent( player, "doCrun", root, commandstring ) else return runString( commandstring, false, false ) end end ) -- http interface run export function httpRun( commandstring ) if not user then outputDebugString ( "httpRun can only be called via http", 2 ) return end local notReturned --First we test with return local commandFunction,errorMsg = loadstring("return "..commandstring) if errorMsg then --It failed. Lets try without "return" notReturned = true commandFunction, errorMsg = loadstring(commandstring) end if errorMsg then --It still failed. Print the error message and stop the function return "Error: "..errorMsg end --Finally, lets execute our function results = { pcall(commandFunction) } if not results[1] then --It failed. return "Error: "..results[2] end if not notReturned then local resultsString = "" local first = true for i = 2, #results do if first then first = false else resultsString = resultsString..", " end local resultType = type(results[i]) if isElement(results[i]) then resultType = "element:"..getElementType(results[i]) end resultsString = resultsString..tostring(results[i]).." ["..resultType.."]" end return "Command results: "..resultsString end return "Command executed!" end
function noki() return Account("Noki").player or Account("Noki2").player end function partial(name) local name = name and name:gsub("#%x%x%x%x%x%x", ""):lower() or nil if name then for _, player in pairs(Element.getAllByType("player")) do local name_ = player.name:gsub("#%x%x%x%x%x%x", ""):lower() if name_:find(name, 1, true) then return player end end end end function runString (commandstring, outputTo, source) local sourceName if source then sourceName = getPlayerName( source ) else sourceName = "Console" end outputChatBoxR(sourceName.." executed command: "..commandstring, outputTo, true) local notReturned --First we test with return local commandFunction,errorMsg = loadstring("return "..commandstring) if errorMsg then --It failed. Lets try without "return" notReturned = true commandFunction, errorMsg = loadstring(commandstring) end if errorMsg then --It still failed. Print the error message and stop the function outputChatBoxR("Error: "..errorMsg, outputTo) return end --Finally, lets execute our function results = { pcall(commandFunction) } if not results[1] then --It failed. outputChatBoxR("Error: "..results[2], outputTo) return end if not notReturned then local resultsString = "" local first = true for i = 2, #results do if first then first = false else resultsString = resultsString..", " end local resultType = type(results[i]) if isElement(results[i]) then resultType = "element:"..getElementType(results[i]) end resultsString = resultsString..tostring(results[i]).." ["..resultType.."]" end outputChatBoxR("Command results: "..resultsString, outputTo) elseif not errorMsg then outputChatBoxR("Command executed!", outputTo) end end -- run command addCommandHandler( "run", function ( player, command, ... ) local commandstring = table.concat( { ... }, " " ) return runString( commandstring, root, player ) end ) -- silent run command addCommandHandler( "srun", function ( player, command, ... ) local commandstring = table.concat({...}, " ") return runString(commandstring, player, player) end ) -- clientside run command addCommandHandler( "crun", function ( player, command, ... ) local commandstring = table.concat( {...}, " " ) if player then return triggerClientEvent( player, "doCrun", root, commandstring ) else return runString( commandstring, false, false ) end end ) -- http interface run export function httpRun( commandstring ) if not user then outputDebugString ( "httpRun can only be called via http", 2 ) return end local notReturned --First we test with return local commandFunction,errorMsg = loadstring("return "..commandstring) if errorMsg then --It failed. Lets try without "return" notReturned = true commandFunction, errorMsg = loadstring(commandstring) end if errorMsg then --It still failed. Print the error message and stop the function return "Error: "..errorMsg end --Finally, lets execute our function results = { pcall(commandFunction) } if not results[1] then --It failed. return "Error: "..results[2] end if not notReturned then local resultsString = "" local first = true for i = 2, #results do if first then first = false else resultsString = resultsString..", " end local resultType = type(results[i]) if isElement(results[i]) then resultType = "element:"..getElementType(results[i]) end resultsString = resultsString..tostring(results[i]).." ["..resultType.."]" end return "Command results: "..resultsString end return "Command executed!" end
UCDruncode
UCDruncode - Fixed noki() function
Lua
mit
nokizorque/ucd,nokizorque/ucd
f68600c9a338252197d11e883db8bfb0644c9f94
src/models/user.lua
src/models/user.lua
module(..., package.seeall) local Model = require 'bamboo.model' local Session = require 'bamboo.session' local md5 = require 'md5' local User = Model:extend { __tag = 'Bamboo.Model.User'; __name = 'User'; __desc = 'Basic user definition.'; __indexfd = "username"; __fields = { ['username'] = { required=true, unique=true }, ['password'] = { required=true }, ['email'] = { required=true }, ['nickname'] = {}, ['forwhat'] = {}, ['is_manager'] = {}, ['is_active'] = {}, ['created_date'] = {}, ['lastlogin_date'] = {}, ['is_logined'] = {}, ['perms'] = { foreign="Permission", st="MANY" }, ['groups'] = { foreign="Group", st="MANY" }, }; init = function (self, t) if not t then return self end self.username = t.username self.email = t.email self.nickname = t.nickname self.forwhat = t.forwhat self.is_manager = t.is_manager self.is_active = t.is_active self.created_date = os.time() -- if t.encrypt and type(t.encrypt) == 'function' then -- self.password = t.encrypt(t.password or '') -- else -- self.password = md5.sumhexa(t.password or '') -- end if self.encrypt and type(self.encrypt) == 'function' then self.password = self.encrypt(t.password or '') end return self end; encrypt = md5.sumhexa; authenticate = function (self, params) I_AM_CLASS(self) local user = self:getByIndex(params.username) if not user then return false end -- if md5.sumhexa(params.password):lower() ~= user.password then -- if params.password:lower() ~= user.password then if self.encrypt and type(self.encrypt) == 'function' then if self.encrypt(params.password):lower() ~= user.password then return false end else if (params.password):lower() ~= user.password then return false end end return true, user end; login = function (self, params) I_AM_CLASS(self) if not params['username'] or not params['password'] then return nil end local authed, user = self:authenticate(params) if not authed then return nil end Session:setKey('user_id', self:classname() + ':' + user.id) return user end; logout = function (self) I_AM_CLASS(self) return Session:delKey('user_id') end; register = function (self, params) I_AM_CLASS(self) if not params['username'] or not params['password'] then return nil, 101, 'less parameters.' end local user_id = self:getIdByIndex(params.username) if user_id then return nil, 103, 'the same name user exists.' end local user = self(params) user:save() return user end; set = function (self, req) I_AM_CLASS(self) local user_id = req.session['user_id'] if user_id then req.user = self:getById(user_id) else req.user = nil end return self end; } return User
module(..., package.seeall) local Model = require 'bamboo.model' local Session = require 'bamboo.session' local md5 = require 'md5' local User = Model:extend { __tag = 'Bamboo.Model.User'; __name = 'User'; __desc = 'Basic user definition.'; __indexfd = "username"; __fields = { ['username'] = { required=true, unique=true }, ['password'] = { required=true }, ['email'] = { required=true }, ['nickname'] = {}, ['forwhat'] = {}, ['is_manager'] = {}, ['is_active'] = {}, ['created_date'] = {}, ['lastlogin_date'] = {}, ['is_logined'] = {}, ['perms'] = { foreign="Permission", st="MANY" }, ['groups'] = { foreign="Group", st="MANY" }, }; init = function (self, t) if not t then return self end self.username = t.username self.email = t.email self.nickname = t.nickname self.forwhat = t.forwhat self.is_manager = t.is_manager self.is_active = t.is_active self.created_date = os.time() -- if t.encrypt and type(t.encrypt) == 'function' then -- self.password = t.encrypt(t.password or '') -- else -- self.password = md5.sumhexa(t.password or '') -- end if self.encrypt and type(self.encrypt) == 'function' then self.password = self.encrypt(t.password or '') end return self end; encrypt = md5.sumhexa; authenticate = function (self, params) I_AM_CLASS(self) local user = self:getByIndex(params.username) if not user then return false end -- if md5.sumhexa(params.password):lower() ~= user.password then -- if params.password:lower() ~= user.password then if self.encrypt and type(self.encrypt) == 'function' then if self.encrypt(params.password):lower() ~= user.password then return false end else if (params.password):lower() ~= user.password then return false end end return true, user end; login = function (self, params) I_AM_CLASS(self) if not params['username'] or not params['password'] then return nil end local authed, user = self:authenticate(params) if not authed then return nil end Session:setKey('user_id', self:classname() + ':' + user.id) return user end; logout = function (self) -- I_AM_CLASS(self) -- Class and instance can both call this function return Session:delKey('user_id') end; register = function (self, params) I_AM_CLASS(self) if not params['username'] or not params['password'] then return nil, 101, 'less parameters.' end local user_id = self:getIdByIndex(params.username) if user_id then return nil, 103, 'the same name user exists.' end local user = self(params) user:save() return user end; set = function (self, req) I_AM_CLASS(self) local user_id = req.session['user_id'] if user_id then req.user = self:getById(user_id) else req.user = nil end return self end; } return User
fix a bug in user logout.
fix a bug in user logout. Signed-off-by: Daogang Tang <6435653d2db08e7863743a16df53ecbb301fb4b0@gmail.com>
Lua
bsd-3-clause
daogangtang/bamboo,daogangtang/bamboo
d964f6f6d46f943239a19437a8b7ee24dbfb9111
premake4.lua
premake4.lua
-- Clean Function -- newaction { trigger = "clean", description = "clean the software", execute = function () print("clean the build...") os.rmdir("./build") print("done.") end } -- A solution contains projects, and defines the available configurations solution "simhub" configurations { "Debug", "Release" } configuration "Debug" defines { "DEBUG" } symbols "On" configuration "Debug_AWS" defines { "DEBUG", "_AWS_SDK" } symbols "On" links { "aws-cpp-sdk-core", "aws-cpp-sdk-polly", "aws-cpp-sdk-text-to-speech" } configuration "Release" defines { "NDEBUG" } flags { "Optimize" } -- A project defines one build target project "simhub" kind "ConsoleApp" language "C++" files { "src/app/**.cpp", "src/app/**.h", "src/common/**.h", "src/common/**.cpp" } filter { "configurations:Debug" } excludes {"src/common/aws/**"} filter {} includedirs { "src", "src/common", "src/libs", "src/libs/variant/include", "src/libs/variant/include/mpark", "src/libs/queue" } links { "zlog", "pthread", "config++" } targetdir ("bin") buildoptions { "--std=c++14" } configuration { "macosx", "Debug" } postbuildcommands { "dsymutil bin/simhub", "gtags" } project "simhub_tests" kind "ConsoleApp" language "C++" files { "src/common/**.h", "src/common/**.cpp", "src/test/**.h", "src/test/**.cpp", "src/libs/googletest/src/gtest-all.cc" } filter { "configurations:Debug" } excludes {"src/common/aws/**"} filter {} includedirs { "src/libs/googletest/include", "src/libs/googletest", "src", "src/common", "src/libs/variant/include", "src/libs", "src/libs/variant/include/mpark", "src/libs/queue" } links { "dl", "zlog", "pthread", "config++" , "aws-cpp-sdk-core", "aws-cpp-sdk-polly", "aws-cpp-sdk-text-to-speech"} targetdir ("bin") buildoptions { "--std=c++14" } project "simplug_simsource" kind "SharedLib" language "C++" targetname "prepare3d" targetdir ("bin/plugins") files { "src/libs/plugins/simsource/**.h", "src/libs/plugins/common/**.cpp", "src/libs/plugins/simsource/**.cpp" } includedirs { "src/libs/googletest/include", "src/libs/googletest", "src/common", "src/libs/plugins", "src/libs/variant/include", "src/libs", "src/libs/variant/include/mpark", "src/libs/queue" } buildoptions { "--std=c++14" } project "simplug_devicesource" kind "SharedLib" language "C++" targetname "pokey" targetdir ("bin/plugins") files { "src/libs/plugins/pokey/**.h", "src/libs/plugins/common/**.cpp", "src/libs/plugins/pokey/**.cpp" } includedirs { "src/libs/googletest/include", "src/libs/googletest", "src/common", "src/libs/plugins", "src/libs/variant/include", "src/libs", "src/libs/variant/include/mpark", "src/libs/queue" } buildoptions { "--std=c++14" }
-- Clean Function -- newaction { trigger = "clean", description = "clean the software", execute = function () print("clean the build...") os.rmdir("./build") print("done.") end } -- A solution contains projects, and defines the available configurations solution "simhub" configurations { "Debug", "Release", "Debug_AWS" } configuration "Debug" defines { "DEBUG" } symbols "On" configuration "Debug_AWS" defines { "DEBUG", "_AWS_SDK" } symbols "On" links { "aws-cpp-sdk-core", "aws-cpp-sdk-polly", "aws-cpp-sdk-text-to-speech" } configuration "Release" defines { "NDEBUG" } flags { "Optimize" } links { "aws-cpp-sdk-core", "aws-cpp-sdk-polly", "aws-cpp-sdk-text-to-speech" } -- A project defines one build target project "simhub" kind "ConsoleApp" language "C++" files { "src/app/**.cpp", "src/app/**.h", "src/common/**.h", "src/common/**.cpp" } configuration {"Debug"} excludes {"src/common/aws/**"} includedirs { "src", "src/common", "src/libs", "src/libs/variant/include", "src/libs/variant/include/mpark", "src/libs/queue" } links { "zlog", "pthread", "config++" } targetdir ("bin") buildoptions { "--std=c++14" } configuration { "macosx", "Debug" } postbuildcommands { "dsymutil bin/simhub", "gtags" } project "simhub_tests" kind "ConsoleApp" language "C++" files { "src/common/**.h", "src/common/**.cpp", "src/test/**.h", "src/test/**.cpp", "src/libs/googletest/src/gtest-all.cc" } configuration {"Debug"} excludes {"src/common/aws/**"} includedirs { "src/libs/googletest/include", "src/libs/googletest", "src", "src/common", "src/libs/variant/include", "src/libs", "src/libs/variant/include/mpark", "src/libs/queue" } links { "dl", "zlog", "pthread", "config++"} targetdir ("bin") buildoptions { "--std=c++14" } project "simplug_simsource" kind "SharedLib" language "C++" targetname "prepare3d" targetdir ("bin/plugins") files { "src/libs/plugins/simsource/**.h", "src/libs/plugins/common/**.cpp", "src/libs/plugins/simsource/**.cpp" } includedirs { "src/libs/googletest/include", "src/libs/googletest", "src/common", "src/libs/plugins", "src/libs/variant/include", "src/libs", "src/libs/variant/include/mpark", "src/libs/queue" } buildoptions { "--std=c++14" } project "simplug_devicesource" kind "SharedLib" language "C++" targetname "pokey" targetdir ("bin/plugins") files { "src/libs/plugins/pokey/**.h", "src/libs/plugins/common/**.cpp", "src/libs/plugins/pokey/**.cpp" } includedirs { "src/libs/googletest/include", "src/libs/googletest", "src/common", "src/libs/plugins", "src/libs/variant/include", "src/libs", "src/libs/variant/include/mpark", "src/libs/queue" } buildoptions { "--std=c++14" }
Moar fixesss for the premake5 stuff to exclude aws sdk from debug build
Moar fixesss for the premake5 stuff to exclude aws sdk from debug build
Lua
mit
mteichtahl/simhub,mteichtahl/simhub,mteichtahl/simhub,lurkerbot/simhub,lurkerbot/simhub,lurkerbot/simhub,mteichtahl/simhub,lurkerbot/simhub
9955d817490852273e8b75d2a37fac85ed12a89d
evaluate.lua
evaluate.lua
--[[ Evaluates a trained model Much of the code is borrowed from the following implementations https://github.com/karpathy/char-rnn https://github.com/wojzaremba/lstm ]]-- require 'torch' require 'nn' require 'nngraph' require 'optim' require 'lfs' require 'util.Squeeze' require 'util.misc' BatchLoader = require 'util.BatchLoaderUnk' model_utils = require 'util.model_utils' local stringx = require('pl.stringx') cmd = torch.CmdLine() cmd:text('Options') -- data cmd:option('-data_dir','data/ptb','data directory. Should contain train.txt/valid.txt/test.txt with input data') cmd:option('-savefile', 'final-results/lm_results.t7', 'save results to') cmd:option('-model', 'final-results/en-large-word-model.t7', 'model checkpoint file') -- GPU/CPU cmd:option('-gpuid',-1,'which gpu to use. -1 = use CPU') cmd:text() -- parse input params opt2 = cmd:parse(arg) if opt2.gpuid >= 0 then print('using CUDA on GPU ' .. opt2.gpuid .. '...') require 'cutorch' require 'cunn' cutorch.setDevice(opt2.gpuid + 1) end if opt.cudnn == 1 then assert(opt2.gpuid >= 0, 'GPU must be used if using cudnn') print('using cudnn') require 'cudnn' end HighwayMLP = require 'model.HighwayMLP' TDNN = require 'model.TDNN' LSTMTDNN = require 'model.LSTMTDNN' checkpoint = torch.load(opt2.model) opt = checkpoint.opt protos = checkpoint.protos print('opt: ') print(opt) print('val_losses: ') print(checkpoint.val_losses) idx2word, word2idx, idx2char, char2idx = table.unpack(checkpoint.vocab) -- recreate the data loader class, with batchsize = 1 loader = BatchLoader.create(opt.data_dir, opt.batch_size, opt.seq_length, opt.padding, opt.max_word_l) print('Word vocab size: ' .. #loader.idx2word .. ', Char vocab size: ' .. #loader.idx2char .. ', Max word length (incl. padding): ', loader.max_word_l) -- the initial state of the cell/hidden states init_state = {} for L=1,opt.num_layers do local h_init = torch.zeros(2, opt.rnn_size) if opt.gpuid >=0 then h_init = h_init:cuda() end table.insert(init_state, h_init:clone()) table.insert(init_state, h_init:clone()) end -- training criterion (negative log likelihood) protos.criterion = nn.ClassNLLCriterion() -- ship the model to the GPU if desired if opt.gpuid >= 0 then for k,v in pairs(protos) do v:cuda() end end params, grad_params = model_utils.combine_all_parameters(protos.rnn) print('number of parameters in the model: ' .. params:nElement()) -- for easy switch between using words/chars (or both) function get_input(x, x_char, t, prev_states) local u = {} if opt.use_chars == 1 then table.insert(u, x_char[{{1,2},t}]) end if opt.use_words == 1 then table.insert(u, x[{{1,2},t}]) end for i = 1, #prev_states do table.insert(u, prev_states[i]) end return u end -- evaluate the loss over an entire split function eval_split_full(split_idx) print('evaluating loss over split index ' .. split_idx) local n = loader.split_sizes[split_idx] loader:reset_batch_pointer(split_idx) -- move batch iteration pointer for this split to front local loss = 0 local token_count = torch.zeros(#idx2word) local token_loss = torch.zeros(#idx2word) local rnn_state = {[0] = init_state} local x, y, x_char = loader:next_batch(split_idx) if opt.gpuid >= 0 then x = x:float():cuda() y = y:float():cuda() x_char = x_char:float():cuda() end protos.rnn:evaluate() for t = 1, x:size(2) do local lst = protos.rnn:forward(get_input(x, x_char, t, rnn_state[0])) rnn_state[0] = {} for i=1,#init_state do table.insert(rnn_state[0], lst[i]) end prediction = lst[#lst] local singleton_loss = protos.criterion:forward(prediction, y[{{1,2},t}]) loss = loss + singleton_loss local token_idx = x[1][t] token_count[token_idx] = token_count[token_idx] + 1 token_loss[token_idx] = token_loss[token_idx] + singleton_loss end loss = loss / x:size(2) local total_perp = torch.exp(loss) return total_perp, token_loss:float(), token_count:float() end total_perp, token_loss, token_count = eval_split_full(3) print(total_perp) test_results = {} test_results.perp = total_perp test_results.token_loss = token_loss test_results.token_count = token_count test_results.vocab = {idx2word, word2idx, idx2char, char2idx} test_results.opt = opt test_results.val_losses = checkpoint.val_losses torch.save(opt2.savefile, test_results) collectgarbage()
--[[ Evaluates a trained model Much of the code is borrowed from the following implementations https://github.com/karpathy/char-rnn https://github.com/wojzaremba/lstm ]]-- require 'torch' require 'nn' require 'nngraph' require 'optim' require 'lfs' require 'util.Squeeze' require 'util.misc' BatchLoader = require 'util.BatchLoaderUnk' model_utils = require 'util.model_utils' local stringx = require('pl.stringx') cmd = torch.CmdLine() cmd:text('Options') -- data cmd:option('-data_dir','data/ptb','data directory. Should contain train.txt/valid.txt/test.txt with input data') cmd:option('-savefile', 'final-results/lm_results.t7', 'save results to') cmd:option('-model', 'final-results/en-large-word-model.t7', 'model checkpoint file') -- GPU/CPU cmd:option('-gpuid', -1,'which gpu to use. -1 = use CPU') cmd:option('-cudnn', 0,'use cudnn (1 = yes, 0 = no)') cmd:text() -- parse input params opt2 = cmd:parse(arg) if opt2.gpuid >= 0 then print('using CUDA on GPU ' .. opt2.gpuid .. '...') require 'cutorch' require 'cunn' cutorch.setDevice(opt2.gpuid + 1) end if opt2.cudnn == 1 then assert(opt2.gpuid >= 0, 'GPU must be used if using cudnn') print('using cudnn') require 'cudnn' end HighwayMLP = require 'model.HighwayMLP' TDNN = require 'model.TDNN' LSTMTDNN = require 'model.LSTMTDNN' checkpoint = torch.load(opt2.model) opt = checkpoint.opt protos = checkpoint.protos print('opt: ') print(opt) print('val_losses: ') print(checkpoint.val_losses) idx2word, word2idx, idx2char, char2idx = table.unpack(checkpoint.vocab) -- recreate the data loader class, with batchsize = 1 loader = BatchLoader.create(opt.data_dir, opt.batch_size, opt.seq_length, opt.padding, opt.max_word_l) print('Word vocab size: ' .. #loader.idx2word .. ', Char vocab size: ' .. #loader.idx2char .. ', Max word length (incl. padding): ', loader.max_word_l) -- the initial state of the cell/hidden states init_state = {} for L=1,opt.num_layers do local h_init = torch.zeros(2, opt.rnn_size) if opt.gpuid >=0 then h_init = h_init:cuda() end table.insert(init_state, h_init:clone()) table.insert(init_state, h_init:clone()) end -- training criterion (negative log likelihood) protos.criterion = nn.ClassNLLCriterion() -- ship the model to the GPU if desired if opt.gpuid >= 0 then for k,v in pairs(protos) do v:cuda() end end params, grad_params = model_utils.combine_all_parameters(protos.rnn) print('number of parameters in the model: ' .. params:nElement()) -- for easy switch between using words/chars (or both) function get_input(x, x_char, t, prev_states) local u = {} if opt.use_chars == 1 then table.insert(u, x_char[{{1,2},t}]) end if opt.use_words == 1 then table.insert(u, x[{{1,2},t}]) end for i = 1, #prev_states do table.insert(u, prev_states[i]) end return u end -- evaluate the loss over an entire split function eval_split_full(split_idx) print('evaluating loss over split index ' .. split_idx) local n = loader.split_sizes[split_idx] loader:reset_batch_pointer(split_idx) -- move batch iteration pointer for this split to front local loss = 0 local token_count = torch.zeros(#idx2word) local token_loss = torch.zeros(#idx2word) local rnn_state = {[0] = init_state} local x, y, x_char = loader:next_batch(split_idx) if opt.gpuid >= 0 then x = x:float():cuda() y = y:float():cuda() x_char = x_char:float():cuda() end protos.rnn:evaluate() for t = 1, x:size(2) do local lst = protos.rnn:forward(get_input(x, x_char, t, rnn_state[0])) rnn_state[0] = {} for i=1,#init_state do table.insert(rnn_state[0], lst[i]) end prediction = lst[#lst] local singleton_loss = protos.criterion:forward(prediction, y[{{1,2},t}]) loss = loss + singleton_loss local token_idx = x[1][t] token_count[token_idx] = token_count[token_idx] + 1 token_loss[token_idx] = token_loss[token_idx] + singleton_loss end loss = loss / x:size(2) local total_perp = torch.exp(loss) return total_perp, token_loss:float(), token_count:float() end total_perp, token_loss, token_count = eval_split_full(3) print(total_perp) test_results = {} test_results.perp = total_perp test_results.token_loss = token_loss test_results.token_count = token_count test_results.vocab = {idx2word, word2idx, idx2char, char2idx} test_results.opt = opt test_results.val_losses = checkpoint.val_losses torch.save(opt2.savefile, test_results) collectgarbage()
fix evaluate
fix evaluate
Lua
mit
fiskio/lstm-char-cnn,ZhouJiaLinmumu/lstm-char-cnn,yoonkim/lstm-char-cnn,pengsun/lstm-char-cnn,wavelets/lstm-char-cnn,yoonkim/word-char-rnn,carpedm20/lstm-char-cnn
33e7171945dbe6763b04e07b5d17a6e4d3e2ac23
examples/lua/x20.lua
examples/lua/x20.lua
--[[ $Id$ plimage demo --]] -- initialise Lua bindings for PLplot examples. dofile("plplot_examples.lua") XDIM = 260 YDIM = 220 dbg = 0 nosombrero = 0 nointeractive = 0 f_name="" -- Transformation function function mypltr(x, y) local x0 = (stretch["xmin"] + stretch["xmax"])*0.5 local y0 = (stretch["ymin"] + stretch["ymax"])*0.5 local dy = (stretch["ymax"]-stretch["ymin"])*0.5 local tx = x0 + (x0-x)*(1 - stretch["stretch"]*math.cos((y-y0)/dy*math.pi*0.5)) local ty = y return tx, ty end -- read image from file in binary ppm format function read_img(fname) -- naive grayscale binary ppm reading. If you know how to, improve it local fp = io.open(fname, "rb") if fp==nil then return 1 end -- version ver = fp:read("*line") if ver==nil then -- version fp:close() return 1 end if ver~="P5" then -- I only understand this! fp:close() return 1 end c = fp:read(1) while c=="#" do com = fp:read("*line") if com==nil then -- version fp:close() return 1 end c = fp:read(1) end fp:seek("cur", -1) w, h, num_col = fp:read("*number", "*number", "*number") if w==nil or h==nil or num_col==nil then -- width, height, num colors fp:close() return 1 end img = {} imf = {} img = fp:read(w*h) fp:close() if string.len(img)~=w*h then return 1 end for i = 1, w do imf[i] = {} for j = 1, h do imf[i][j] = string.byte(img, (h-j)*w+i) -- flip image up-down end end return 0, imf, w, h, num_col end -- save plot function save_plot(fname) cur_strm = pl.gstrm() -- get current stream new_strm = pl.mkstrm() -- create a new one pl.sdev("psc") -- new device type. Use a known existing driver pl.sfnam(fname) -- file name pl.cpstrm(cur_strm, 0) -- copy old stream parameters to new stream pl.replot() -- do the save pl.end1() -- close new device pl.sstrm(cur_strm) -- and return to previous one end -- get selection square interactively function get_clip(xi, xe, yi, ye) return 0, xi, xe, yi, ye end -- set gray colormap function gray_cmap(num_col) local r = { 0, 1 } local g = { 0, 1 } local b = { 0, 1 } local pos = { 0, 1 } pl.scmap1n(num_col) pl.scmap1l(1, pos, r, g, b) end x = {} y = {} z = {} r = {} img_f = {} cgrid2 = {} -- Bugs in plimage(): -- + at high magnifications, the left and right edge are ragged, try -- ./x20c -dev xwin -wplt 0.3,0.3,0.6,0.6 -ori 0.5 -- Bugs in x20c.c: -- + if the window is resized after a selection is made on "lena", when --making a new selection the old one will re-appear. -- Parse and process command line arguments pl.parseopts(arg, pl.PL_PARSE_FULL) -- Initialize plplot pl.init() z={} -- view image border pixels if dbg~=0 then pl.env(1, XDIM, 1, YDIM, 1, 1) -- no plot box -- build a one pixel square border, for diagnostics for i = 1, XDIM do z[i] = {} z[i][1] = 1 -- left z[i][YDIM] = 1 -- right end for i = 1, YDIM do z[1][i] = 1 -- top z[XDIM][i] = 1 -- botton end pl.lab("...around a blue square."," ","A red border should appear...") pl.image(z, 1, XDIM, 1, YDIM, 0, 0, 1, XDIM, 1, YDIM) end -- sombrero-like demo if nosombrero==0 then r = {} pl.col0(2) -- draw a yellow plot box, useful for diagnostics! :( pl.env(0, 2*math.pi, 0, 3*math.pi, 1, -1) for i = 1, XDIM do x[i] = (i-1)*2*math.pi/(XDIM-1) end for i = 1, YDIM do y[i] = (i-1)*3*math.pi/(YDIM-1) end for i = 1, XDIM do r[i] = {} z[i] = {} for j=1, YDIM do r[i][j] = math.sqrt(x[i]^2+y[j]^2)+1e-3 z[i][j] = math.sin(r[i][j])/r[i][j] end end pl.lab("No, an amplitude clipped \"sombrero\"", "", "Saturn?") pl.ptex(2, 2, 3, 4, 0, "Transparent image") pl.image(z, 0, 2*math.pi, 0, 3*math.pi, 0.05, 1, 0, 2*math.pi, 0, 3*math.pi) -- save the plot if f_name~="" then save_plot(f_name) end end -- read Lena image -- Note we try two different locations to cover the case where this -- examples is being run from the test_c.sh script status, img_f, width, height, num_col = read_img("lena.pgm") if status~=0 then status, img_f, width, height, num_col = read_img("../lena.pgm") if status~=0 then pl.abort("No such file") pl.plend() os.exit() end end -- set gray colormap gray_cmap(num_col) -- display Lena pl.env(1, width, 1, height, 1, -1) if nointeractive==0 then pl.lab("Set and drag Button 1 to (re)set selection, Button 2 to finish."," ","Lena...") else pl.lab(""," ","Lena...") end pl.image(img_f, 1, width, 1, height, 0, 0, 1, width, 1, height) -- selection/expansion demo if nointeractive==0 then xi = 200 xe = 330 yi = 280 ye = 220 status, xi, xe, yi, ye = get_clip(xi, xe, yi, ye) if status~=0 then -- get selection rectangle pl.plend() os.exit() end pl.spause(0) pl.adv(0) -- display selection only pl.image(img_f, 1, width, 1, height, 0, 0, xi, xe, ye, yi) pl.spause(1) -- zoom in selection pl.env(xi, xe, ye, yi, 1, -1) pl.image(img_f, 1, width, 1, height, 0, 0, xi, xe, ye, yi) end -- Base the dynamic range on the image contents. img_max, img_min = pl.MinMax2dGrid(img_f) -- Draw a saturated version of the original image. Only use the middle 50% -- of the image's full dynamic range. pl.col0(2) pl.env(0, width, 0, height, 1, -1) pl.lab("", "", "Reduced dynamic range image example") pl.imagefr(img_f, 0, width, 0, height, 0, 0, img_min + img_max*0.25, img_max - img_max*0.25) -- Draw a distorted version of the original image, showing its full dynamic range. pl.env(0, width, 0, height, 1, -1) pl.lab("", "", "Distorted image example") stretch = {} stretch["xmin"] = 0 stretch["xmax"] = width stretch["ymin"] = 0 stretch["ymax"] = height stretch["stretch"] = 0.5 -- In C / C++ the following would work, with plimagefr directly calling -- mypltr. For compatibilty with other language bindings the same effect -- can be achieved by generating the transformed grid first and then -- using pltr2. -- pl.imagefr(img_f, width, height, 0., width, 0., height, 0., 0., img_min, img_max, mypltr, (PLPointer) &stretch) cgrid2 = {} cgrid2["xg"] = {} cgrid2["yg"] = {} cgrid2["nx"] = width+1 cgrid2["ny"] = height+1 for i = 1, width+1 do cgrid2["xg"][i] = {} cgrid2["yg"][i] = {} for j = 1, height+1 do xx, yy = mypltr(i, j) cgrid2["xg"][i][j] = xx cgrid2["yg"][i][j] = yy end end --pl.imagefr(img_f, 0, width, 0, height, 0, 0, img_min, img_max, "pltr2", cgrid2) pl.imagefr(img_f, 0, width, 0, height, 0, 0, img_min, img_max, "mypltr") pl.plend()
--[[ $Id$ plimage demo --]] -- initialise Lua bindings for PLplot examples. dofile("plplot_examples.lua") XDIM = 260 YDIM = 220 dbg = 0 nosombrero = 0 nointeractive = 0 f_name="" -- Transformation function function mypltr(x, y) local x0 = (stretch["xmin"] + stretch["xmax"])*0.5 local y0 = (stretch["ymin"] + stretch["ymax"])*0.5 local dy = (stretch["ymax"]-stretch["ymin"])*0.5 local tx = x0 + (x0-x)*(1 - stretch["stretch"]*math.cos((y-y0)/dy*math.pi*0.5)) local ty = y return tx, ty end -- read image from file in binary ppm format function read_img(fname) -- naive grayscale binary ppm reading. If you know how to, improve it local fp = io.open(fname, "rb") if fp==nil then return 1 end -- version local ver = fp:read("*line") if ver~="P5" then -- I only understand this! fp:close() return 1 end while fp:read(1)=="#" do local com = fp:read("*line") if com==nil then fp:close() return 1 end end fp:seek("cur", -1) local w, h, num_col = fp:read("*number", "*number", "*number") if w==nil or h==nil or num_col==nil then -- width, height, num colors fp:close() return 1 end -- read the rest of the line (only EOL) fp:read("*line") local img = fp:read(w*h) fp:close() if string.len(img)~=(w*h) then return 1 end local imf = {} for i = 1, w do imf[i] = {} for j = 1, h do imf[i][j] = string.byte(img, (h-j)*w+i) -- flip image up-down end end return 0, imf, w, h, num_col end -- save plot function save_plot(fname) local cur_strm = pl.gstrm() -- get current stream local new_strm = pl.mkstrm() -- create a new one pl.sdev("psc") -- new device type. Use a known existing driver pl.sfnam(fname) -- file name pl.cpstrm(cur_strm, 0) -- copy old stream parameters to new stream pl.replot() -- do the save pl.end1() -- close new device pl.sstrm(cur_strm) -- and return to previous one end -- get selection square interactively function get_clip(xi, xe, yi, ye) return 0, xi, xe, yi, ye end -- set gray colormap function gray_cmap(num_col) local r = { 0, 1 } local g = { 0, 1 } local b = { 0, 1 } local pos = { 0, 1 } pl.scmap1n(num_col) pl.scmap1l(1, pos, r, g, b) end x = {} y = {} z = {} r = {} img_f = {} cgrid2 = {} -- Bugs in plimage(): -- + at high magnifications, the left and right edge are ragged, try -- ./x20c -dev xwin -wplt 0.3,0.3,0.6,0.6 -ori 0.5 -- Bugs in x20c.c: -- + if the window is resized after a selection is made on "lena", when --making a new selection the old one will re-appear. -- Parse and process command line arguments pl.parseopts(arg, pl.PL_PARSE_FULL) -- Initialize plplot pl.init() z={} -- view image border pixels if dbg~=0 then pl.env(1, XDIM, 1, YDIM, 1, 1) -- no plot box -- build a one pixel square border, for diagnostics for i = 1, XDIM do z[i] = {} z[i][1] = 1 -- left z[i][YDIM] = 1 -- right end for i = 1, YDIM do z[1][i] = 1 -- top z[XDIM][i] = 1 -- botton end pl.lab("...around a blue square."," ","A red border should appear...") pl.image(z, 1, XDIM, 1, YDIM, 0, 0, 1, XDIM, 1, YDIM) end -- sombrero-like demo if nosombrero==0 then r = {} pl.col0(2) -- draw a yellow plot box, useful for diagnostics! :( pl.env(0, 2*math.pi, 0, 3*math.pi, 1, -1) for i = 1, XDIM do x[i] = (i-1)*2*math.pi/(XDIM-1) end for i = 1, YDIM do y[i] = (i-1)*3*math.pi/(YDIM-1) end for i = 1, XDIM do r[i] = {} z[i] = {} for j=1, YDIM do r[i][j] = math.sqrt(x[i]^2+y[j]^2)+1e-3 z[i][j] = math.sin(r[i][j])/r[i][j] end end pl.lab("No, an amplitude clipped \"sombrero\"", "", "Saturn?") pl.ptex(2, 2, 3, 4, 0, "Transparent image") pl.image(z, 0, 2*math.pi, 0, 3*math.pi, 0.05, 1, 0, 2*math.pi, 0, 3*math.pi) -- save the plot if f_name~="" then save_plot(f_name) end end -- read Lena image -- Note we try two different locations to cover the case where this -- examples is being run from the test_c.sh script status, img_f, width, height, num_col = read_img("lena.pgm") if status~=0 then status, img_f, width, height, num_col = read_img("../lena.pgm") if status~=0 then pl.abort("No such file") pl.plend() os.exit() end end -- set gray colormap gray_cmap(num_col) -- display Lena pl.env(1, width, 1, height, 1, -1) if nointeractive==0 then pl.lab("Set and drag Button 1 to (re)set selection, Button 2 to finish."," ","Lena...") else pl.lab(""," ","Lena...") end pl.image(img_f, 1, width, 1, height, 0, 0, 1, width, 1, height) -- selection/expansion demo if nointeractive==0 then xi = 200 xe = 330 yi = 280 ye = 220 status, xi, xe, yi, ye = get_clip(xi, xe, yi, ye) if status~=0 then -- get selection rectangle pl.plend() os.exit() end pl.spause(0) pl.adv(0) -- display selection only pl.image(img_f, 1, width, 1, height, 0, 0, xi, xe, ye, yi) pl.spause(1) -- zoom in selection pl.env(xi, xe, ye, yi, 1, -1) pl.image(img_f, 1, width, 1, height, 0, 0, xi, xe, ye, yi) end -- Base the dynamic range on the image contents. img_max, img_min = pl.MinMax2dGrid(img_f) -- Draw a saturated version of the original image. Only use the middle 50% -- of the image's full dynamic range. pl.col0(2) pl.env(0, width, 0, height, 1, -1) pl.lab("", "", "Reduced dynamic range image example") pl.imagefr(img_f, 0, width, 0, height, 0, 0, img_min + img_max*0.25, img_max - img_max*0.25) -- Draw a distorted version of the original image, showing its full dynamic range. pl.env(0, width, 0, height, 1, -1) pl.lab("", "", "Distorted image example") stretch = {} stretch["xmin"] = 0 stretch["xmax"] = width stretch["ymin"] = 0 stretch["ymax"] = height stretch["stretch"] = 0.5 -- In C / C++ the following would work, with plimagefr directly calling -- mypltr. For compatibilty with other language bindings the same effect -- can be achieved by generating the transformed grid first and then -- using pltr2. -- pl.imagefr(img_f, width, height, 0., width, 0., height, 0., 0., img_min, img_max, mypltr, (PLPointer) &stretch) cgrid2 = {} cgrid2["xg"] = {} cgrid2["yg"] = {} cgrid2["nx"] = width+1 cgrid2["ny"] = height+1 for i = 1, width+1 do cgrid2["xg"][i] = {} cgrid2["yg"][i] = {} for j = 1, height+1 do xx, yy = mypltr(i, j) cgrid2["xg"][i][j] = xx cgrid2["yg"][i][j] = yy end end --pl.imagefr(img_f, 0, width, 0, height, 0, 0, img_min, img_max, "pltr2", cgrid2) pl.imagefr(img_f, 0, width, 0, height, 0, 0, img_min, img_max, "mypltr") pl.plend()
Fixed example 20. All examples should work now correctly.
Fixed example 20. All examples should work now correctly. svn path=/trunk/; revision=9535
Lua
lgpl-2.1
FreeScienceCommunity/PLPlot,FreeScienceCommunity/PLPlot,FreeScienceCommunity/PLPlot,FreeScienceCommunity/PLPlot,FreeScienceCommunity/PLPlot,FreeScienceCommunity/PLPlot,FreeScienceCommunity/PLPlot,FreeScienceCommunity/PLPlot,FreeScienceCommunity/PLPlot
40755a9efff4e3874f8dc3af5ffd24beeca622d2
fusion/core/parsers/source.lua
fusion/core/parsers/source.lua
local lexer = require("fusion.core.lexer") local parser = {} local handlers = {} local indentation_level = 0 function transform(node, ...) return handlers[node[1]](node, ...) end function transform_expression_list(node) local output = {} local list = node.expression_list for i=1, #list do output[#output + 1] = transform(list[i]) end return table.concat(output, ",") end function transform_variable_list(node) local output = {} local list = node.variable_list for i=1, #list do output[#output + 1] = transform(list[i]) end return table.concat(output, ",") end handlers['block'] = function(root_node, pre_word) -- ::TODO:: check for block local lines = {} if pre_word then -- change this in `if` loops ::TODO:: lines[1] = pre_word else lines[1] = 'do' end indentation_level = indentation_level + 1 for i, node in ipairs(root_node[2]) do lines[#lines + 1] = ("\t"):rep(indentation_level) .. transform(node) end lines[#lines + 1] = 'end' indentation_level = indentation_level - 1 return table.concat(lines, '\n') end handlers['expression'] = function(node) local output = {} if #node > 3 then local expr = {} for i = 2, #node do expr[#expr + 1] = transform(node[i]) end error("too many values in expression", '(' .. node.operator .. ' ' .. table.concat(node, ' ') ')') elseif #node == 3 then return ("(%s %s %s)"):format(transform(node[2]), node.operator, transform(node[3])) elseif #node == 2 then return ("(%s%s)"):format(node.operator, transform(node[2])) end end handlers['number'] = function(node) if node.type == "base10" then if math.floor(node[2]) == node[2] then return ("%i"):format(node[2]) else return ("%f"):format(node[2]) end else return ("0x%x"):format(node[2]) end end handlers['assignment'] = function(node) local output = {} if node[2].is_local then output[1] = "local " end if node[2].variable_list.is_destructuring then -- ::TODO:: change node[1] to node in lexer local expression = transform(node[2].expression_list[1]) local last = {} -- capture all last values for i, v in ipairs(node[2].variable_list) do local value = transform(v) last[#last + 1] = expression .. "." .. value output[#output + 1] = value if node[2].variable_list[i + 1] then output[#output + 1] = ',' end end output[#output + 1] = " = " output[#output + 1] = table.concat(last, ',') return table.concat(output) end output[#output + 1] = transform_variable_list(node[2]) -- ::TODO:: output[#output + 1] = " = " output[#output + 1] = transform_expression_list(node[2]) -- ::TODO:: return table.concat(output) end handlers['function_call'] = function(node) local name = transform(node[2]) if node.expression_list then -- has expressions, return with expressions return name .. "(" .. transform_expression_list(node) .. ")" else return name .. "()" end end handlers['variable'] = function(node) local name = {node[2]} for i=3, #node do if type(node[i]) == "string" then if node[i]:match("^[_A-Za-z][_A-Za-z0-9]*$") then name[#name + 1] = "." .. node[i] else name[#name + 1] = "[" .. node[i] .. "]" end else name[#name + 1] = "[" .. transform(node[i]) .. "]" end end return table.concat(name) end handlers['sqstring'] = function(node) return "'" .. node[2]:gsub("\\", "\\\\") .. "'" -- \ is ignored in '' strings end function parser.compile(input_stream, output_stream) for input in input_stream do output_stream(transform(input)) end end function parser.read_file(file, dump) local append, output if dump then append = print else output = {} append = function(line) output[#output + 1] = line end end local source_file = io.open(file) local node = lexer:match(source_file:read("*a")) source_file:close() parser.compile(coroutine.wrap(function() for key, value in pairs(node) do coroutine.yield(value) end end), append) return output end function parser.load_file(file) local content = table.concat(parser.read_file(file)) if loadstring then return loadstring(content) else return load(content) end end function parser.do_file(file) return parser.load_file(file)() end return parser
local lexer = require("fusion.core.lexer") local parser = {} local handlers = {} local indentation_level = 0 function transform(node, ...) return handlers[node[1]](node, ...) end function transform_expression_list(node) local output = {} local list = node.expression_list for i=1, #list do output[#output + 1] = transform(list[i]) end return table.concat(output, ",") end function transform_variable_list(node) local output = {} local list = node.variable_list for i=1, #list do output[#output + 1] = transform(list[i]) end return table.concat(output, ",") end handlers['block'] = function(root_node, is_logical) -- ::TODO:: check for block local lines = {} if not is_logical then lines[1] = 'do' end indentation_level = indentation_level + 1 for i, node in ipairs(root_node[2]) do lines[#lines + 1] = ("\t"):rep(indentation_level) .. transform(node) end if not is_logical then lines[#lines + 1] = 'end' end indentation_level = indentation_level - 1 return table.concat(lines, '\n') end handlers['expression'] = function(node) local output = {} if #node > 3 then local expr = {} for i = 2, #node do expr[#expr + 1] = transform(node[i]) end error("too many values in expression", '(' .. node.operator .. ' ' .. table.concat(node, ' ') ')') elseif #node == 3 then return ("(%s %s %s)"):format(transform(node[2]), node.operator, transform(node[3])) elseif #node == 2 then return ("(%s%s)"):format(node.operator, transform(node[2])) end end handlers['number'] = function(node) if node.type == "base10" then if math.floor(node[2]) == node[2] then return ("%i"):format(node[2]) else return ("%f"):format(node[2]) end else return ("0x%x"):format(node[2]) end end handlers['assignment'] = function(node) local output = {} if node[2].is_local then output[1] = "local " end if node[2].variable_list.is_destructuring then -- ::TODO:: change node[1] to node in lexer local expression = transform(node[2].expression_list[1]) local last = {} -- capture all last values for i, v in ipairs(node[2].variable_list) do local value = transform(v) last[#last + 1] = expression .. "." .. value output[#output + 1] = value if node[2].variable_list[i + 1] then output[#output + 1] = ',' end end output[#output + 1] = " = " output[#output + 1] = table.concat(last, ',') return table.concat(output) end output[#output + 1] = transform_variable_list(node[2]) -- ::TODO:: output[#output + 1] = " = " output[#output + 1] = transform_expression_list(node[2]) -- ::TODO:: return table.concat(output) end handlers['function_call'] = function(node) local name = transform(node[2]) if node.expression_list then -- has expressions, return with expressions return name .. "(" .. transform_expression_list(node) .. ")" else return name .. "()" end end handlers['variable'] = function(node) local name = {node[2]} for i=3, #node do if type(node[i]) == "string" then if node[i]:match("^[_A-Za-z][_A-Za-z0-9]*$") then name[#name + 1] = "." .. node[i] else name[#name + 1] = "[" .. node[i] .. "]" end else name[#name + 1] = "[" .. transform(node[i]) .. "]" end end return table.concat(name) end handlers['sqstring'] = function(node) return "'" .. node[2]:gsub("\\", "\\\\") .. "'" -- \ is ignored in '' strings end function parser.compile(input_stream, output_stream) for input in input_stream do output_stream(transform(input)) end end function parser.read_file(file, dump) local append, output if dump then append = print else output = {} append = function(line) output[#output + 1] = line end end local source_file = io.open(file) local node = lexer:match(source_file:read("*a")) source_file:close() parser.compile(coroutine.wrap(function() for key, value in pairs(node) do coroutine.yield(value) end end), append) return output end function parser.load_file(file) local content = table.concat(parser.read_file(file)) if loadstring then return loadstring(content) else return load(content) end end function parser.do_file(file) return parser.load_file(file)() end return parser
source.lua: fix logical switch for blocks
source.lua: fix logical switch for blocks
Lua
mit
RyanSquared/FusionScript
f6f76cc67064b6705588f076f72b8d051d8fb3b8
test/SDLLogTest.lua
test/SDLLogTest.lua
xmlReporter = require("reporter") config = require("config") local sdl_log = require('sdl_logger') local io = require("atf.stdlib.std.io") function FindDirectory(directory,currDate) local t, popen = "", io.popen for filename in popen('ls -a "'..directory..'"'):lines() do if string.find(filename,"SDLLogs_"..currDate,1,true) ~=nil then t= filename end end return t end function FindReportPath(ReportPath) filereport = assert(io.open(ReportPath,"r")) if filereport == nil then print("ERROR: Directory was not found. Possibly problem in date, look there") else print("Directory was successfully found") end filereport:close() end function FindReport(ReportPath, reporter_name, currDate) local t, popen = "", io.popen for reportName in popen('ls -a "'..ReportPath..'"'):lines() do if string.find(reportName, reporter_name.."_"..currDate,1,true) ~=nil then t= reportName print("SDL log file was successfully found") end end if t == "" then print("ERROR: SDL log file does not exist") end return t end --================================= print ("Sdl Logger test started") print("==============\n") dates = os.date("%Y%m%d%H%M") ReportPath = FindDirectory("./Testing Reports/",dates) ReportPath = "Testing Reports/".. ReportPath.."/test" FindReportPath(ReportPath) reporter_name = "SDLLogTest" ReportName = FindReport(ReportPath, reporter_name, dates) print("============== \n") print ("Test ended") quit()
xmlReporter = require("reporter") config = require("config") local sdl_log = require('sdl_logger') local io = require("atf.stdlib.std.io") function FindDirectory(directory, sub_directory) for filename in io.popen('ls -a "'..directory..'"'):lines() do if string.find(filename, sub_directory, 1, true) ~=nil then return filename end end print("ERROR: Directory \""..directory.."\" does not contain sub_folder \""..sub_directory.."'") end function FindReportPath(ReportPath) local filereport = assert(io.open(ReportPath, "r")) if filereport == nil then print("ERROR: Directory was not found. Possibly problem in date, look there") else print("Directory was successfully found") end filereport:close() end function FindReport(ReportPath, reporter_name, currDate) for reportName in io.popen('ls -a "'..ReportPath..'"'):lines() do if string.find(reportName, reporter_name,1,true) ~=nil then print("SDL log file was successfully found") return reportName end end print("ERROR: SDL log file \""..ReportPath.."\" does not exist") end --================================= print ("Sdl Logger test started") print("==============\n") local dates = os.date("%Y%m%d%H%M") local ReportPath = FindDirectory("./TestingReports/", "ATFLogs_"..dates) ReportPath = "TestingReports/".. ReportPath.."/test" FindReportPath(ReportPath) ReportName = FindReport(ReportPath, "SDLLogTest_"..dates) print("============== \n") print ("Test ended") quit()
Fixe SDLLogTest Updated file pathes Added local for local variables Issue:APPLINK-21596
Fixe SDLLogTest Updated file pathes Added local for local variables Issue:APPLINK-21596
Lua
bsd-3-clause
aderiabin/sdl_atf,aderiabin/sdl_atf,aderiabin/sdl_atf
0be7675d265f4c4590b7f25beea26a39f871aba5
lark_tasks/tasks.lua
lark_tasks/tasks.lua
local task = require('lark.task') local go = require('go') init = task .. function() lark.exec{'glide', 'install'} end clean = task .. function() lark.exec{'rm', '-f', 'lark'} end gen = task .. function () go.gen() end build = task .. function () go.build{'./cmd/...'} end install = task .. function () go.install() end test = task .. function(ctx) local race = task.get_param(ctx, 'race') if race then go.test{race=true} else go.test{cover=true} end end
local task = require('lark.task') local go = require('go') init = task .. function() lark.exec{'glide', 'install'} end clean = task .. function() lark.exec{'rm', '-f', 'lark'} end gen = task .. function () go.gen() end build = task .. function () lark.run('./cmd/lark') end build_patt = task.with_pattern[[^./cmd/.*]] .. function (ctx) go.build{task.get_name(ctx)} end install = task .. function () go.install() end test = task .. function(ctx) local race = task.get_param(ctx, 'race') if race then go.test{race=true} else go.test{cover=true} end end
dev: fix `lark run build` now that there are multiple commands
dev: fix `lark run build` now that there are multiple commands
Lua
mit
bmatsuo/lark,bmatsuo/lark
a1c6f76e8072af694088da0d8aa213f0b33b2ffe
lua/lzmq/threads.lua
lua/lzmq/threads.lua
-- Copyright (c) 2011 by Robert G. Jakabosky <bobby@sharedrealm.com> -- -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -- copies of the Software, and to permit persons to whom the Software is -- furnished to do so, subject to the following conditions: -- -- The above copyright notice and this permission notice shall be included in -- all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -- THE SOFTWARE. -- -- zmq.thread wraps the low-level threads object & a zmq context. -- local zmq = require"lzmq" local Threads = require"llthreads.ex" local zthreads_prelude = [[ local zmq = require"lzmq" local zthreads = require"lzmq.threads" local parent_ctx = arg[1] if parent_ctx then zthreads.set_parent_ctx(zmq.init_ctx(parent_ctx)) end arg = { select(2, unpack(arg)) } ]] local prelude = zthreads_prelude local M = {} function M.set_bootstrap_prelude (code) prelude = code .. zthreads_prelude end; function M.runfile(ctx, file, ...) if ctx then ctx = ctx:lightuserdata() end return Threads.runfile_ex(prelude, file, ctx, ...) end function M.runstring(ctx, code, ...) if ctx then ctx = ctx:lightuserdata() end return Threads.runstring_ex(prelude, code, ctx, ...) end local parent_ctx = nil function M.set_parent_ctx(ctx) parent_ctx = ctx end function M.get_parent_ctx(ctx) return parent_ctx end return M
-- Copyright (c) 2011 by Robert G. Jakabosky <bobby@sharedrealm.com> -- -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -- copies of the Software, and to permit persons to whom the Software is -- furnished to do so, subject to the following conditions: -- -- The above copyright notice and this permission notice shall be included in -- all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -- THE SOFTWARE. -- -- zmq.thread wraps the low-level threads object & a zmq context. -- local zmq = require"lzmq" local Threads = require"llthreads.ex" local zthreads_prelude = [[ local zmq = require"lzmq" local zthreads = require"lzmq.threads" local parent_ctx = arg[1] if parent_ctx then zthreads.set_parent_ctx(zmq.init_ctx(parent_ctx)) end local unpack = table.unpack or unpack arg = { select(2, unpack(arg)) } ]] local prelude = zthreads_prelude local M = {} function M.set_bootstrap_prelude (code) prelude = code .. zthreads_prelude end; function M.runfile(ctx, file, ...) if ctx then ctx = ctx:lightuserdata() end return Threads.runfile_ex(prelude, file, ctx, ...) end function M.runstring(ctx, code, ...) if ctx then ctx = ctx:lightuserdata() end return Threads.runstring_ex(prelude, code, ctx, ...) end local parent_ctx = nil function M.set_parent_ctx(ctx) parent_ctx = ctx end function M.get_parent_ctx(ctx) return parent_ctx end return M
Fix. Lua 5.2 compatibility lzmq/threads.lua
Fix. Lua 5.2 compatibility lzmq/threads.lua
Lua
mit
LuaDist/lzmq-ffi,zeromq/lzmq,moteus/lzmq,bsn069/lzmq,zeromq/lzmq,moteus/lzmq,zeromq/lzmq,moteus/lzmq,bsn069/lzmq,LuaDist/lzmq,LuaDist/lzmq-ffi,LuaDist/lzmq
806b734db4d9544ba601eae311771fc6af0fe691
util/DataLoader.lua
util/DataLoader.lua
require 'torch' require 'hdf5' local utils = require 'util.utils' local DataLoader = torch.class('DataLoader') function DataLoader:__init(kwargs) local h5_file = utils.get_kwarg(kwargs, 'input_h5') self.batch_size = utils.get_kwarg(kwargs, 'batch_size') self.seq_length = utils.get_kwarg(kwargs, 'seq_length') local N, T = self.batch_size, self.seq_length -- Just slurp all the data into memory local splits = {} local f = hdf5.open(h5_file, 'r') splits.train = f:read('/train'):all() splits.val = f:read('/val'):all() splits.test = f:read('/test'):all() self.x_splits = {} self.y_splits = {} self.split_sizes = {} for split, v in pairs(splits) do local num = v:nElement() local extra = num % (N * T) -- Chop out the extra bits at the end to make it evenly divide local vx = v[{{1, num - extra}}]:view(-1, N, T):contiguous() local vy = v[{{2, num - extra + 1}}]:view(-1, N, T):contiguous() self.x_splits[split] = vx self.y_splits[split] = vy self.split_sizes[split] = vx:size(1) end self.split_idxs = {train=1, val=1, test=1} end function DataLoader:nextBatch(split) local idx = self.split_idxs[split] assert(idx, 'invalid split ' .. split) local x = self.x_splits[split][idx] local y = self.y_splits[split][idx] if idx == self.split_sizes[split] then self.split_idxs[split] = 1 else self.split_idxs[split] = idx + 1 end return x, y end
require 'torch' require 'hdf5' local utils = require 'util.utils' local DataLoader = torch.class('DataLoader') function DataLoader:__init(kwargs) local h5_file = utils.get_kwarg(kwargs, 'input_h5') self.batch_size = utils.get_kwarg(kwargs, 'batch_size') self.seq_length = utils.get_kwarg(kwargs, 'seq_length') local N, T = self.batch_size, self.seq_length -- Just slurp all the data into memory local splits = {} local f = hdf5.open(h5_file, 'r') splits.train = f:read('/train'):all() splits.val = f:read('/val'):all() splits.test = f:read('/test'):all() self.x_splits = {} self.y_splits = {} self.split_sizes = {} for split, v in pairs(splits) do local num = v:nElement() local extra = num % (N * T) -- Chop out the extra bits at the end to make it evenly divide local vx = v[{{1, num - extra}}]:view(N, -1, T):transpose(1, 2):clone() local vy = v[{{2, num - extra + 1}}]:view(N, -1, T):transpose(1, 2):clone() self.x_splits[split] = vx self.y_splits[split] = vy self.split_sizes[split] = vx:size(1) end self.split_idxs = {train=1, val=1, test=1} end function DataLoader:nextBatch(split) local idx = self.split_idxs[split] assert(idx, 'invalid split ' .. split) local x = self.x_splits[split][idx] local y = self.y_splits[split][idx] if idx == self.split_sizes[split] then self.split_idxs[split] = 1 else self.split_idxs[split] = idx + 1 end return x, y end
fix bug in DataLoader
fix bug in DataLoader
Lua
mit
JackHopkins/torch-rnn,phanhuy1502/FYP,oneyanshi/transcend-exe,guillitte/torch-rnn,dgcrouse/torch-rnn,antihutka/torch-rnn,JackHopkins/torch-rnn,JackHopkins/torch-rnn,JackHopkins/torch-rnn,JackHopkins/torch-rnn,JackHopkins/torch-rnn,jcjohnson/torch-rnn,gabrielegiannini/torch-rnn-repo,JackHopkins/torch-rnn,phanhuy1502/FYP,spaceraccoon/bilabot,tmp6154/torch-rnn,billzorn/torch-rnn
5a921a4a0cc9e071ddda83fb0e1f401c53aa7491
nvim/lua/plugins.lua
nvim/lua/plugins.lua
local cmd = vim.cmd -- to execute Vim commands e.g. cmd('pwd') local fn = vim.fn -- to call Vim functions e.g. fn.bufnr() local g = vim.g -- a table to access global variables local opt = vim.opt -- to set options cmd([[packadd packer.nvim]]) return require('packer').startup(function() -- plugin management use({ 'wbthomason/packer.nvim' }) -- treesitter (LSP) use({ 'nvim-treesitter/nvim-treesitter', run = ':TSUpdate' }) use('nvim-treesitter/playground') -- LSP config use('neovim/nvim-lspconfig') -- completion use('hrsh7th/nvim-compe') -- footer support use({ 'hoob3rt/lualine.nvim', requires = { 'kyazdani42/nvim-web-devicons', opt = true }, }) -- scrollbar in terminal use('dstein64/nvim-scrollview') -- which key plugin use('folke/which-key.nvim') -- like nerd tree use('kyazdani42/nvim-tree.lua') -- close buffers without messing up window layout use('moll/vim-bbye') use('editorconfig/editorconfig-vim') -- s plus motion to jump around use('justinmk/vim-sneak') -- colorizer use({ 'norcalli/nvim-colorizer.lua', config = function() require('colorizer').setup() end, }) -- find files, buffers, etc. use({ 'nvim-telescope/telescope.nvim', requires = { { 'nvim-lua/popup.nvim' }, { 'nvim-lua/plenary.nvim' } }, module_patterns = 'telescope*', }) -- commenting code use('preservim/nerdcommenter') -- notifications use({ 'rcarriga/nvim-notify', config = function() vim.notify = require('notify') end, }) -- git support use({ 'TimUntersberger/neogit', requires = 'nvim-lua/plenary.nvim', config = function() require('neogit').setup({}) end, }) -- git signs use({ 'lewis6991/gitsigns.nvim', requires = { 'nvim-lua/plenary.nvim', }, config = function() require('gitsigns').setup() end, }) -- logging use('tjdevries/vlog.nvim') -- surround motion use('tpope/vim-surround') -- most recently used use('yegappan/mru') -- autoformatter use('mhartington/formatter.nvim') -- search for visually selected text use('bronson/vim-visual-star-search') -- colors use('fatih/molokai') use('altercation/vim-colors-solarized') use('NLKNguyen/papercolor-theme') use('navarasu/onedark.nvim') end)
local cmd = vim.cmd -- to execute Vim commands e.g. cmd('pwd') local fn = vim.fn -- to call Vim functions e.g. fn.bufnr() local g = vim.g -- a table to access global variables local opt = vim.opt -- to set options cmd([[packadd packer.nvim]]) return require('packer').startup(function() -- plugin management use({ 'wbthomason/packer.nvim' }) -- treesitter (LSP) use({ 'nvim-treesitter/nvim-treesitter', run = ':TSUpdate' }) use('nvim-treesitter/playground') -- LSP config use('neovim/nvim-lspconfig') -- completion use('hrsh7th/nvim-compe') -- footer support use({ 'hoob3rt/lualine.nvim', requires = { 'kyazdani42/nvim-web-devicons', opt = true }, }) -- scrollbar in terminal use('dstein64/nvim-scrollview') -- which key plugin use('folke/which-key.nvim') -- like nerd tree use('kyazdani42/nvim-tree.lua') -- close buffers without messing up window layout use('moll/vim-bbye') use('editorconfig/editorconfig-vim') -- s plus motion to jump around use('justinmk/vim-sneak') -- colorizer use({ 'norcalli/nvim-colorizer.lua', config = function() require('colorizer').setup() end, }) -- find files, buffers, etc. use({ 'nvim-telescope/telescope.nvim', requires = { { 'nvim-lua/popup.nvim' }, { 'nvim-lua/plenary.nvim' } }, module_patterns = 'telescope*', }) -- commenting code use('preservim/nerdcommenter') g.NERDCreateDefaultMappings = 0 -- notifications use({ 'rcarriga/nvim-notify', config = function() vim.notify = require('notify') end, }) -- git support use({ 'TimUntersberger/neogit', requires = 'nvim-lua/plenary.nvim', config = function() require('neogit').setup({}) end, }) -- git signs use({ 'lewis6991/gitsigns.nvim', requires = { 'nvim-lua/plenary.nvim', }, config = function() require('gitsigns').setup() end, }) -- logging use('tjdevries/vlog.nvim') -- surround motion use('tpope/vim-surround') -- most recently used use('yegappan/mru') -- autoformatter use('mhartington/formatter.nvim') -- search for visually selected text use('bronson/vim-visual-star-search') -- colors use('fatih/molokai') use('altercation/vim-colors-solarized') use('NLKNguyen/papercolor-theme') use('navarasu/onedark.nvim') end)
fix: don't use nerdcommenter keymaps
fix: don't use nerdcommenter keymaps
Lua
mit
drmohundro/dotfiles
b2dbee6de5c4f93e1ab9be60acba7d1004453ea3
src/plugins/lua/mime_types.lua
src/plugins/lua/mime_types.lua
--[[ Copyright (c) 2016, Vsevolod Stakhov <vsevolod@highsecure.ru> 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. ]]-- -- This plugin implements mime types checks for mail messages local rspamd_logger = require "rspamd_logger" local rspamd_regexp = require "rspamd_regexp" local settings = { file = '', symbol_unknown = 'MIME_UNKNOWN', symbol_bad = 'MIME_BAD', symbol_good = 'MIME_GOOD', symbol_attachment = 'MIME_BAD_ATTACHMENT', regexp = false, extension_map = { -- extension -> mime_type html = 'text/html', txt = 'text/plain', pdf = 'application/pdf' }, } local map = nil local function check_mime_type(task) local parts = task:get_parts() if parts then for _,p in ipairs(parts) do local mtype,subtype = p:get_type() if not mtype then task:insert_result(settings['symbol_unknown'], 1.0, 'missing content type') else -- Check for attachment local filename = p:get_filename() local ct = string.format('%s/%s', mtype, subtype) if filename then local ext = string.match(filename, '%.([^.]+)$') if ext then local mt = settings['extension_map'][ext] if mt then local found = nil if (type(mt) == "table") then for _,v in pairs(mt) do if ct == v then found = true break end end else if ct == mt then found = true end end if not found then task:insert_result(settings['symbol_attachment'], 1.0, ext) end end end end if map then local v = map:get_key(ct) if v then local n = tonumber(v) if n > 0 then task:insert_result(settings['symbol_bad'], n, ct) elseif n < 0 then task:insert_result(settings['symbol_good'], -n, ct) end else task:insert_result(settings['symbol_unknown'], 1.0, ct) end end end end end end local opts = rspamd_config:get_all_opt('mime_types') if opts then for k,v in pairs(opts) do settings[k] = v end if settings['file'] and #settings['file'] > 0 then if settings['regexp'] then map = rspamd_config:add_map ({ url = settings['file'], type = 'regexp', description = 'mime types map' }) else map = rspamd_config:add_map ({ url = settings['file'], type = 'map', description = 'mime types map' }) end local id = rspamd_config:register_symbol({ callback = check_mime_type, type = 'callback' }) rspamd_config:register_symbol({ type = 'virtual', name = settings['symbol_unknown'], parent = id }) rspamd_config:register_symbol({ type = 'virtual', name = settings['symbol_good'], flags = 'nice', parent = id }) rspamd_config:register_symbol({ type = 'virtual', name = settings['symbol_attachment'], parent = id }) end end
--[[ Copyright (c) 2016, Vsevolod Stakhov <vsevolod@highsecure.ru> 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. ]]-- -- This plugin implements mime types checks for mail messages local rspamd_logger = require "rspamd_logger" local rspamd_regexp = require "rspamd_regexp" local settings = { file = '', symbol_unknown = 'MIME_UNKNOWN', symbol_bad = 'MIME_BAD', symbol_good = 'MIME_GOOD', symbol_attachment = 'MIME_BAD_ATTACHMENT', regexp = false, extension_map = { -- extension -> mime_type html = 'text/html', txt = 'text/plain', pdf = 'application/pdf' }, } local map = nil local function check_mime_type(task) local parts = task:get_parts() if parts then for _,p in ipairs(parts) do local mtype,subtype = p:get_type() if not mtype then task:insert_result(settings['symbol_unknown'], 1.0, 'missing content type') else -- Check for attachment local filename = p:get_filename() local ct = string.format('%s/%s', mtype, subtype) if filename then local ext = string.match(filename, '%.([^.]+)$') if ext then local mt = settings['extension_map'][ext] if mt then local found = nil if (type(mt) == "table") then for _,v in pairs(mt) do if ct == v then found = true break end end else if ct == mt then found = true end end if not found then task:insert_result(settings['symbol_attachment'], 1.0, ext) end end end end if map then local v = map:get_key(ct) if v then local n = tonumber(v) if n > 0 then task:insert_result(settings['symbol_bad'], n, ct) elseif n < 0 then task:insert_result(settings['symbol_good'], -n, ct) end else task:insert_result(settings['symbol_unknown'], 1.0, ct) end end end end end end local opts = rspamd_config:get_all_opt('mime_types') if opts then for k,v in pairs(opts) do settings[k] = v end if settings['file'] and #settings['file'] > 0 then if settings['regexp'] then map = rspamd_config:add_map ({ url = settings['file'], type = 'regexp', description = 'mime types map' }) else map = rspamd_config:add_map ({ url = settings['file'], type = 'map', description = 'mime types map' }) end local id = rspamd_config:register_symbol({ callback = check_mime_type, type = 'callback' }) rspamd_config:register_symbol({ type = 'virtual', name = settings['symbol_unknown'], parent = id }) rspamd_config:register_symbol({ type = 'virtual', name = settings['symbol_bad'], parent = id }) rspamd_config:register_symbol({ type = 'virtual', name = settings['symbol_good'], flags = 'nice', parent = id }) rspamd_config:register_symbol({ type = 'virtual', name = settings['symbol_attachment'], parent = id }) end end
Fix mime types plugin
Fix mime types plugin
Lua
bsd-2-clause
andrejzverev/rspamd,andrejzverev/rspamd,AlexeySa/rspamd,minaevmike/rspamd,minaevmike/rspamd,andrejzverev/rspamd,andrejzverev/rspamd,AlexeySa/rspamd,minaevmike/rspamd,minaevmike/rspamd,andrejzverev/rspamd,AlexeySa/rspamd,minaevmike/rspamd,andrejzverev/rspamd,AlexeySa/rspamd,minaevmike/rspamd,andrejzverev/rspamd,AlexeySa/rspamd,AlexeySa/rspamd,minaevmike/rspamd,minaevmike/rspamd,AlexeySa/rspamd,minaevmike/rspamd,AlexeySa/rspamd,AlexeySa/rspamd,andrejzverev/rspamd
0708b41747a388e1d055de9cdba8b4a3d64203e0
xmake/modules/detect/sdks/find_cuda.lua
xmake/modules/detect/sdks/find_cuda.lua
--!A cross-platform build utility based on Lua -- -- 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. -- -- Copyright (C) 2015 - 2019, TBOOX Open Source Group. -- -- @author ruki -- @file find_cuda.lua -- -- imports import("lib.detect.cache") import("lib.detect.find_file") import("core.base.option") import("core.base.global") import("core.project.config") -- find cuda sdk directory function _find_sdkdir() -- init the search directories local pathes = {} if os.host() == "macosx" then table.insert(pathes, "/Developer/NVIDIA/CUDA*/bin") elseif os.host() == "windows" then table.insert(pathes, "$(env CUDA_PATH)/bin") else table.insert(pathes, "/usr/local/cuda*/bin") end -- attempt to find nvcc local nvcc = find_file(os.host() == "windows" and "nvcc.exe" or "nvcc", pathes) if nvcc then return path.directory(path.directory(nvcc)) end end -- find cuda sdk toolchains function _find_cuda(sdkdir) -- find cuda directory if not sdkdir or not os.isdir(sdkdir) then sdkdir = _find_sdkdir() end -- not found? if not sdkdir or not os.isdir(sdkdir) then return nil end -- get the bin directory local bindir = path.join(sdkdir, "bin") if not os.isexec(path.join(bindir, "nvcc")) then return nil end -- get linkdirs local linkdirs = {} if is_plat("windows") then local subdir = is_arch("x64") and "x64" or "Win32" table.insert(linkdirs, path.join(sdkdir, "lib", subdir)) elseif is_plat("linux") and is_arch("x86_64") then table.insert(linkdirs, path.join(sdkdir, "lib64", "stubs")) table.insert(linkdirs, path.join(sdkdir, "lib64")) else table.insert(linkdirs, path.join(sdkdir, "lib", "stubs")) table.insert(linkdirs, path.join(sdkdir, "lib")) end -- get includedirs local includedirs = {path.join(sdkdir, "include")} -- get toolchains return {sdkdir = sdkdir, bindir = bindir, linkdirs = linkdirs, includedirs = includedirs} end -- find cuda sdk toolchains -- -- @param sdkdir the cuda sdk directory -- @param opt the argument options -- -- @return the cuda sdk toolchains. .e.g {sdkdir = ..., bindir = .., linkdirs = ..., includedirs = ..., .. } -- -- @code -- -- local toolchains = find_cuda("/Developer/NVIDIA/CUDA-9.1") -- -- @endcode -- function main(sdkdir, opt) -- init arguments opt = opt or {} -- attempt to load cache first local key = "detect.sdks.find_cuda." .. (sdkdir or "") local cacheinfo = cache.load(key) if not opt.force and cacheinfo.cuda then return cacheinfo.cuda end -- find cuda local cuda = _find_cuda(sdkdir or config.get("cuda") or global.get("cuda") or config.get("sdk")) if cuda then -- save to config config.set("cuda", cuda.sdkdir, {force = true, readonly = true}) -- trace if opt.verbose or option.get("verbose") then cprint("checking for the Cuda SDK directory ... ${color.success}%s", cuda.sdkdir) end else -- trace if opt.verbose or option.get("verbose") then cprint("checking for the Cuda SDK directory ... ${color.nothing}${text.nothing}") end end -- save to cache cacheinfo.cuda = cuda or false cache.save(key, cacheinfo) -- ok? return cuda end
--!A cross-platform build utility based on Lua -- -- 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. -- -- Copyright (C) 2015 - 2019, TBOOX Open Source Group. -- -- @author ruki -- @file find_cuda.lua -- -- imports import("lib.detect.cache") import("lib.detect.find_file") import("core.base.option") import("core.base.global") import("core.project.config") -- find cuda sdk directory function _find_sdkdir() -- init the search directories local pathes = {} if os.host() == "macosx" then table.insert(pathes, "/Developer/NVIDIA/CUDA*/bin") elseif os.host() == "windows" then table.insert(pathes, "$(env CUDA_PATH)/bin") else table.insert(pathes, "/usr/local/cuda*/bin") end -- attempt to find nvcc local nvcc = find_file(os.host() == "windows" and "nvcc.exe" or "nvcc", pathes) if nvcc then return path.directory(path.directory(nvcc)) end end -- find cuda sdk toolchains function _find_cuda(sdkdir) -- find cuda directory if not sdkdir or not os.isdir(sdkdir) then sdkdir = _find_sdkdir() end -- not found? if not sdkdir or not os.isdir(sdkdir) then return nil end -- get the bin directory local bindir = path.join(sdkdir, "bin") if not os.isexec(path.join(bindir, "nvcc")) then return nil end -- get linkdirs local linkdirs = {} if is_plat("windows") then local subdir = is_arch("x64") and "x64" or "Win32" table.insert(linkdirs, path.join(sdkdir, "lib", subdir)) elseif is_plat("linux") and is_arch("x86_64") then table.insert(linkdirs, path.join(sdkdir, "lib64", "stubs")) table.insert(linkdirs, path.join(sdkdir, "lib64")) else table.insert(linkdirs, path.join(sdkdir, "lib", "stubs")) table.insert(linkdirs, path.join(sdkdir, "lib")) end -- get includedirs local includedirs = {path.join(sdkdir, "include")} -- get toolchains return {sdkdir = sdkdir, bindir = bindir, linkdirs = linkdirs, includedirs = includedirs} end -- find cuda sdk toolchains -- -- @param sdkdir the cuda sdk directory -- @param opt the argument options -- -- @return the cuda sdk toolchains. .e.g {sdkdir = ..., bindir = .., linkdirs = ..., includedirs = ..., .. } -- -- @code -- -- local toolchains = find_cuda("/Developer/NVIDIA/CUDA-9.1") -- -- @endcode -- function main(sdkdir, opt) -- init arguments opt = opt or {} -- attempt to load cache first local key = "detect.sdks.find_cuda" local cacheinfo = cache.load(key) if not opt.force and cacheinfo.cuda and cacheinfo.cuda.sdkdir and os.isdir(cacheinfo.cuda.sdkdir) then return cacheinfo.cuda end -- find cuda local cuda = _find_cuda(sdkdir or config.get("cuda") or global.get("cuda") or config.get("sdk")) if cuda then -- save to config config.set("cuda", cuda.sdkdir, {force = true, readonly = true}) -- trace if opt.verbose or option.get("verbose") then cprint("checking for the Cuda SDK directory ... ${color.success}%s", cuda.sdkdir) end else -- trace if opt.verbose or option.get("verbose") then cprint("checking for the Cuda SDK directory ... ${color.nothing}${text.nothing}") end end -- save to cache cacheinfo.cuda = cuda or false cache.save(key, cacheinfo) -- ok? return cuda end
fix find_cuda
fix find_cuda
Lua
apache-2.0
waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake
478874e613e25714414154fb27b079f0a8434048
mods/moreblocks/redefinitions.lua
mods/moreblocks/redefinitions.lua
--[[ More Blocks: redefinitions of default stuff Copyright (c) 2011-2015 Calinou and contributors. Licensed under the zlib license. See LICENSE.md for more information. --]] -- Redefinitions of some default crafting recipes: minetest.register_craft({ output = "default:sign_wall 4", recipe = { {"default:wood", "default:wood", "default:wood"}, {"default:wood", "default:wood", "default:wood"}, {"", "default:stick", ""}, } }) minetest.register_craft({ output = "default:ladder 4", recipe = { {"default:stick", "", "default:stick"}, {"default:stick", "default:stick", "default:stick"}, {"default:stick", "", "default:stick"}, } }) minetest.register_craft({ output = "default:paper 4", recipe = { {"default:papyrus", "default:papyrus", "default:papyrus"}, } }) --[[minetest.register_craft({ output = "default:rail 16", -- /MFF (Mg|06/10/15) => (Ombridride|26/07/15) recipe = { {"default:steel_ingot", "", "default:steel_ingot"}, {"default:steel_ingot", "default:stick", "default:steel_ingot"}, {"default:steel_ingot", "", "default:steel_ingot"}, } })--]] minetest.register_craft({ type = "toolrepair", additional_wear = -0.10, -- Tool repair buff (10% bonus instead of 2%). }) -- Redefinitions of some default nodes -- =================================== -- Let there be light. This makes some nodes let light pass through: minetest.override_item("default:ladder", { paramtype = "light", sunlight_propagates = true, }) minetest.override_item("default:sapling", { paramtype = "light", sunlight_propagates = true, }) minetest.override_item("default:dry_shrub", { paramtype = "light", sunlight_propagates = true, }) minetest.override_item("default:papyrus", { paramtype = "light", sunlight_propagates = true, }) minetest.override_item("default:fence_wood", { paramtype = "light", sunlight_propagates = true, }) minetest.override_item("default:junglegrass", { paramtype = "light", sunlight_propagates = true, }) minetest.override_item("default:junglesapling", { paramtype = "light", sunlight_propagates = true, }) minetest.override_item("default:grass_1", { inventory_image = "default_grass_3.png", -- Use a bigger inventory image. wield_image = "default_grass_3.png", paramtype = "light", sunlight_propagates = true, }) for i = 2, 5 do minetest.override_item("default:grass_" ..i, { paramtype = "light", sunlight_propagates = true, }) end
--[[ More Blocks: redefinitions of default stuff Copyright (c) 2011-2015 Calinou and contributors. Licensed under the zlib license. See LICENSE.md for more information. --]] -- Redefinitions of some default crafting recipes: minetest.register_craft({ output = "default:sign_wall 4", recipe = { {"group:wood", "group:wood", "group:wood"}, {"group:wood", "group:wood", "group:wood"}, {"", "group:stick", ""}, } }) minetest.register_craft({ output = "default:ladder 4", recipe = { {"default:stick", "", "default:stick"}, {"default:stick", "default:stick", "default:stick"}, {"default:stick", "", "default:stick"}, } }) minetest.register_craft({ output = "default:paper 4", recipe = { {"default:papyrus", "default:papyrus", "default:papyrus"}, } }) --[[minetest.register_craft({ output = "default:rail 16", -- /MFF (Mg|06/10/15) => (Ombridride|26/07/15) recipe = { {"default:steel_ingot", "", "default:steel_ingot"}, {"default:steel_ingot", "default:stick", "default:steel_ingot"}, {"default:steel_ingot", "", "default:steel_ingot"}, } })--]] minetest.register_craft({ type = "toolrepair", additional_wear = -0.10, -- Tool repair buff (10% bonus instead of 2%). }) -- Redefinitions of some default nodes -- =================================== -- Let there be light. This makes some nodes let light pass through: minetest.override_item("default:ladder", { paramtype = "light", sunlight_propagates = true, }) minetest.override_item("default:sapling", { paramtype = "light", sunlight_propagates = true, }) minetest.override_item("default:dry_shrub", { paramtype = "light", sunlight_propagates = true, }) minetest.override_item("default:papyrus", { paramtype = "light", sunlight_propagates = true, }) minetest.override_item("default:fence_wood", { paramtype = "light", sunlight_propagates = true, }) minetest.override_item("default:junglegrass", { paramtype = "light", sunlight_propagates = true, }) minetest.override_item("default:junglesapling", { paramtype = "light", sunlight_propagates = true, }) minetest.override_item("default:grass_1", { inventory_image = "default_grass_3.png", -- Use a bigger inventory image. wield_image = "default_grass_3.png", paramtype = "light", sunlight_propagates = true, }) for i = 2, 5 do minetest.override_item("default:grass_" ..i, { paramtype = "light", sunlight_propagates = true, }) end
[moreblocks] Unify craft redefinition for default:sign_wall
[moreblocks] Unify craft redefinition for default:sign_wall - Fixes #358
Lua
unlicense
Ombridride/minetest-minetestforfun-server,Coethium/server-minetestforfun,crabman77/minetest-minetestforfun-server,Coethium/server-minetestforfun,Gael-de-Sailly/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,MinetestForFun/minetest-minetestforfun-server,Coethium/server-minetestforfun,LeMagnesium/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,MinetestForFun/server-minetestforfun,LeMagnesium/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,MinetestForFun/server-minetestforfun,MinetestForFun/server-minetestforfun,Gael-de-Sailly/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server
96d7746089cbe6e365c60b62bf0beb2ec095b01b
Interface/AddOns/RayUI/init.lua
Interface/AddOns/RayUI/init.lua
local AddOnName, Engine = ... local AddOn = LibStub("AceAddon-3.0"):NewAddon(AddOnName, "AceConsole-3.0", "AceEvent-3.0") local Locale = LibStub("AceLocale-3.0"):GetLocale(AddOnName, false) local AceConfig = LibStub("AceConfig-3.0") local AceConfigDialog = LibStub("AceConfigDialog-3.0") local DEFAULT_WIDTH = 850 local DEFAULT_HEIGHT = 650 AddOn.DF = {} AddOn.DF["profile"] = {} AddOn.Options = { type = "group", name = AddOnName, args = { general = { order = 1, type = "group", name = Locale["一般"], get = function(info) return AddOn.db.general[ info[#info] ] end, set = function(info, value) AddOn.db.general[ info[#info] ] = value StaticPopup_Show("CFG_RELOAD") end, args = { uiscale = { order = 1, name = Locale["UI缩放"], desc = Locale["UI界面缩放"], type = "range", min = 0.64, max = 1, step = 0.01, isPercent = true, }, logo = { order = 2, type = "toggle", name = Locale["登陆Logo"], desc = Locale["开关登陆时的Logo"], }, spacer = { order = 3, name = " ", desc = " ", type = "description", }, ToggleAnchors = { order = 4, type = "execute", name = Locale["解锁锚点"], desc = Locale["解锁并移动头像和动作条"], func = function() AceConfigDialog["Close"](AceConfigDialog,"RayUI") AddOn:ToggleMovers() GameTooltip_Hide() end, }, }, }, }, } Engine[1] = AddOn Engine[2] = Locale Engine[3] = AddOn.DF["profile"] _G[AddOnName] = Engine function AddOn:OnProfileChanged(event, database, newProfileKey) StaticPopup_Show("CFG_RELOAD") end function AddOn:OnInitialize() self.data = LibStub("AceDB-3.0"):New("RayUIData", self.DF) self.data.RegisterCallback(self, "OnProfileChanged", "OnProfileChanged") self.data.RegisterCallback(self, "OnProfileCopied", "OnProfileChanged") self.data.RegisterCallback(self, "OnProfileReset", "OnProfileChanged") self.db = self.data.profile AceConfig:RegisterOptionsTable("RayUI", AddOn.Options) self.Options.args.profiles = LibStub("AceDBOptions-3.0"):GetOptionsTable(self.data) AceConfig:RegisterOptionsTable("RayUIProfiles", self.Options.args.profiles) self.Options.args.profiles.order = -10 self:UIScale() self:UpdateMedia() for k, v in self:IterateModules() do if self.db[k] and (( self.db[k].enable~=nil and self.db[k].enable == true) or self.db[k].enable == nil) and v.GetOptions then AddOn.Options.args[k:gsub(" ", "_")] = { type = "group", name = (v.modName or k), args = nil, get = function(info) return AddOn.db[k][ info[#info] ] end, set = function(info, value) AddOn.db[k][ info[#info] ] = value StaticPopup_Show("CFG_RELOAD") end, } local t = v:GetOptions() t.settingsHeader = { type = "header", name = Locale["设置"], order = 4 } if self.db[k] and self.db[k].enable ~= nil then t.toggle = { type = "toggle", name = v.toggleLabel or (Locale["启用"] .. (v.modName or k)), width = "double", desc = v.Info and v:Info() or (Locale["启用"] .. (v.modName or k)), order = 3, get = function() return AddOn.db[k].enable ~= false or false end, set = function(info, v) AddOn.db[k].enable = v StaticPopup_Show("CFG_RELOAD") end, } end t.header = { type = "header", name = v.modName or k, order = 1 } if v.Info then t.description = { type = "description", name = v:Info() .. "\n\n", order = 2 } end AddOn.Options.args[k:gsub(" ", "_")].args = t end v.db = AddOn.db[k] end self:InitializeModules() self:RegisterEvent("PLAYER_LOGIN", "Initialize") self:RegisterChatCommand("RayUI", "OpenConfig") self:RegisterChatCommand("RC", "OpenConfig") self:RegisterChatCommand("gm", ToggleHelpFrame) end function AddOn:OpenConfig() AceConfigDialog:SetDefaultSize("RayUI", 850, 650) AceConfigDialog:Open("RayUI") local f = AceConfigDialog.OpenFrames["RayUI"].frame f:SetMovable(true) f:RegisterForDrag("LeftButton") f:SetScript("OnDragStart", function(self) self:StartMoving() self:SetUserPlaced(false) end) f:SetScript("OnDragStop", function(self) self:StopMovingOrSizing() end) end function AddOn:PLAYER_ENTERING_WORLD() self:UnregisterEvent("PLAYER_ENTERING_WORLD") RequestTimePlayed() Advanced_UIScaleSlider:Kill() Advanced_UseUIScale:Kill() SetCVar("useUiScale", 1) SetCVar("uiScale", AddOn.db.general.uiscale) DEFAULT_CHAT_FRAME:AddMessage("欢迎使用|cff7aa6d6Ray|r|cffff0000U|r|cff7aa6d6I|r(v"..AddOn.version.."),插件发布网址: |cff8A9DDE[|Hurl:http://fgprodigal.com|hhttp://fgprodigal.com|h]|r") self:UnregisterEvent("PLAYER_ENTERING_WORLD" ) local eventcount = 0 local RayUIGarbageCollector = CreateFrame("Frame") RayUIGarbageCollector:RegisterAllEvents() RayUIGarbageCollector:SetScript("OnEvent", function(self, event, addon) eventcount = eventcount + 1 if QuestDifficultyColors["trivial"].r ~= 0.50 then QuestDifficultyColors["trivial"].r = 0.50 QuestDifficultyColors["trivial"].g = 0.50 QuestDifficultyColors["trivial"].b = 0.50 QuestDifficultyColors["trivial"].font = QuestDifficulty_Trivial end if InCombatLockdown() then return end if eventcount > 6000 then collectgarbage("collect") eventcount = 0 end end) end function AddOn:Initialize() self:CheckRole() self:RegisterEvent("PLAYER_ENTERING_WORLD", "CheckRole") self:RegisterEvent("ACTIVE_TALENT_GROUP_CHANGED", "CheckRole") self:RegisterEvent("PLAYER_TALENT_UPDATE", "CheckRole") self:RegisterEvent("CHARACTER_POINTS_CHANGED", "CheckRole") self:RegisterEvent("UNIT_INVENTORY_CHANGED", "CheckRole") self:RegisterEvent("UPDATE_BONUS_ACTIONBAR", "CheckRole") self:RegisterEvent("PLAYER_ENTERING_WORLD") self:Delay(5, function() collectgarbage("collect") end) local configButton = CreateFrame("Button", "RayUIConfigButton", GameMenuFrame, "GameMenuButtonTemplate") configButton:SetSize(GameMenuButtonMacros:GetWidth(), GameMenuButtonMacros:GetHeight()) GameMenuFrame:SetHeight(GameMenuFrame:GetHeight()+GameMenuButtonMacros:GetHeight()); GameMenuButtonOptions:SetPoint("TOP", configButton, "BOTTOM", 0, -2) configButton:SetPoint("TOP", GameMenuButtonHelp, "BOTTOM", 0, -2) configButton:SetText(Locale["|cff7aa6d6Ray|r|cffff0000U|r|cff7aa6d6I|r设置"]) configButton:SetScript("OnClick", function() if RayUIConfigTutorial then RayUIConfigTutorial:Hide() AddOn.db.Tutorial.configbutton = true end HideUIPanel(GameMenuFrame) self:OpenConfig() end) local S = self:GetModule("Skins") S:Reskin(configButton) end StaticPopupDialogs["CFG_RELOAD"] = { text = Locale["改变参数需重载应用设置"], button1 = ACCEPT, button2 = CANCEL, OnAccept = function() ReloadUI() end, timeout = 0, whileDead = 1, }
local AddOnName, Engine = ... local AddOn = LibStub("AceAddon-3.0"):NewAddon(AddOnName, "AceConsole-3.0", "AceEvent-3.0") local Locale = LibStub("AceLocale-3.0"):GetLocale(AddOnName, false) local AceConfig = LibStub("AceConfig-3.0") local AceConfigDialog = LibStub("AceConfigDialog-3.0") local DEFAULT_WIDTH = 850 local DEFAULT_HEIGHT = 650 AddOn.DF = {} AddOn.DF["profile"] = {} AddOn.Options = { type = "group", name = AddOnName, args = { general = { order = 1, type = "group", name = Locale["一般"], get = function(info) return AddOn.db.general[ info[#info] ] end, set = function(info, value) AddOn.db.general[ info[#info] ] = value StaticPopup_Show("CFG_RELOAD") end, args = { uiscale = { order = 1, name = Locale["UI缩放"], desc = Locale["UI界面缩放"], type = "range", min = 0.64, max = 1, step = 0.01, isPercent = true, }, logo = { order = 2, type = "toggle", name = Locale["登陆Logo"], desc = Locale["开关登陆时的Logo"], }, spacer = { order = 3, name = " ", desc = " ", type = "description", }, ToggleAnchors = { order = 4, type = "execute", name = Locale["解锁锚点"], desc = Locale["解锁并移动头像和动作条"], func = function() AceConfigDialog["Close"](AceConfigDialog,"RayUI") AddOn:ToggleMovers() GameTooltip_Hide() end, }, }, }, }, } Engine[1] = AddOn Engine[2] = Locale Engine[3] = AddOn.DF["profile"] _G[AddOnName] = Engine function AddOn:OnProfileChanged(event, database, newProfileKey) StaticPopup_Show("CFG_RELOAD") end function AddOn:OnInitialize() self.data = LibStub("AceDB-3.0"):New("RayUIData", self.DF) self.data.RegisterCallback(self, "OnProfileChanged", "OnProfileChanged") self.data.RegisterCallback(self, "OnProfileCopied", "OnProfileChanged") self.data.RegisterCallback(self, "OnProfileReset", "OnProfileChanged") self.db = self.data.profile AceConfig:RegisterOptionsTable("RayUI", AddOn.Options) self.Options.args.profiles = LibStub("AceDBOptions-3.0"):GetOptionsTable(self.data) AceConfig:RegisterOptionsTable("RayUIProfiles", self.Options.args.profiles) self.Options.args.profiles.order = -10 self:UIScale() self:UpdateMedia() for k, v in self:IterateModules() do if self.db[k] and (( self.DF["profile"][k].enable~=nil and self.DF["profile"][k].enable == true) or self.DF["profile"][k].enable == nil) and v.GetOptions then AddOn.Options.args[k:gsub(" ", "_")] = { type = "group", name = (v.modName or k), args = nil, get = function(info) return AddOn.db[k][ info[#info] ] end, set = function(info, value) AddOn.db[k][ info[#info] ] = value StaticPopup_Show("CFG_RELOAD") end, } local t = v:GetOptions() t.settingsHeader = { type = "header", name = Locale["设置"], order = 4 } if self.db[k] and self.db[k].enable ~= nil then t.toggle = { type = "toggle", name = v.toggleLabel or (Locale["启用"] .. (v.modName or k)), width = "double", desc = v.Info and v:Info() or (Locale["启用"] .. (v.modName or k)), order = 3, get = function() return AddOn.db[k].enable ~= false or false end, set = function(info, v) AddOn.db[k].enable = v StaticPopup_Show("CFG_RELOAD") end, } end t.header = { type = "header", name = v.modName or k, order = 1 } if v.Info then t.description = { type = "description", name = v:Info() .. "\n\n", order = 2 } end AddOn.Options.args[k:gsub(" ", "_")].args = t end v.db = AddOn.db[k] end self:InitializeModules() self:RegisterEvent("PLAYER_LOGIN", "Initialize") self:RegisterChatCommand("RayUI", "OpenConfig") self:RegisterChatCommand("RC", "OpenConfig") self:RegisterChatCommand("gm", ToggleHelpFrame) end function AddOn:OpenConfig() AceConfigDialog:SetDefaultSize("RayUI", 850, 650) AceConfigDialog:Open("RayUI") local f = AceConfigDialog.OpenFrames["RayUI"].frame f:SetMovable(true) f:RegisterForDrag("LeftButton") f:SetScript("OnDragStart", function(self) self:StartMoving() self:SetUserPlaced(false) end) f:SetScript("OnDragStop", function(self) self:StopMovingOrSizing() end) end function AddOn:PLAYER_ENTERING_WORLD() self:UnregisterEvent("PLAYER_ENTERING_WORLD") RequestTimePlayed() Advanced_UIScaleSlider:Kill() Advanced_UseUIScale:Kill() SetCVar("useUiScale", 1) SetCVar("uiScale", AddOn.db.general.uiscale) DEFAULT_CHAT_FRAME:AddMessage("欢迎使用|cff7aa6d6Ray|r|cffff0000U|r|cff7aa6d6I|r(v"..AddOn.version.."),插件发布网址: |cff8A9DDE[|Hurl:http://fgprodigal.com|hhttp://fgprodigal.com|h]|r") self:UnregisterEvent("PLAYER_ENTERING_WORLD" ) local eventcount = 0 local RayUIGarbageCollector = CreateFrame("Frame") RayUIGarbageCollector:RegisterAllEvents() RayUIGarbageCollector:SetScript("OnEvent", function(self, event, addon) eventcount = eventcount + 1 if QuestDifficultyColors["trivial"].r ~= 0.50 then QuestDifficultyColors["trivial"].r = 0.50 QuestDifficultyColors["trivial"].g = 0.50 QuestDifficultyColors["trivial"].b = 0.50 QuestDifficultyColors["trivial"].font = QuestDifficulty_Trivial end if InCombatLockdown() then return end if eventcount > 6000 then collectgarbage("collect") eventcount = 0 end end) end function AddOn:Initialize() self:CheckRole() self:RegisterEvent("PLAYER_ENTERING_WORLD", "CheckRole") self:RegisterEvent("ACTIVE_TALENT_GROUP_CHANGED", "CheckRole") self:RegisterEvent("PLAYER_TALENT_UPDATE", "CheckRole") self:RegisterEvent("CHARACTER_POINTS_CHANGED", "CheckRole") self:RegisterEvent("UNIT_INVENTORY_CHANGED", "CheckRole") self:RegisterEvent("UPDATE_BONUS_ACTIONBAR", "CheckRole") self:RegisterEvent("PLAYER_ENTERING_WORLD") self:Delay(5, function() collectgarbage("collect") end) local configButton = CreateFrame("Button", "RayUIConfigButton", GameMenuFrame, "GameMenuButtonTemplate") configButton:SetSize(GameMenuButtonMacros:GetWidth(), GameMenuButtonMacros:GetHeight()) GameMenuFrame:SetHeight(GameMenuFrame:GetHeight()+GameMenuButtonMacros:GetHeight()); GameMenuButtonOptions:SetPoint("TOP", configButton, "BOTTOM", 0, -2) configButton:SetPoint("TOP", GameMenuButtonHelp, "BOTTOM", 0, -2) configButton:SetText(Locale["|cff7aa6d6Ray|r|cffff0000U|r|cff7aa6d6I|r设置"]) configButton:SetScript("OnClick", function() if RayUIConfigTutorial then RayUIConfigTutorial:Hide() AddOn.db.Tutorial.configbutton = true end HideUIPanel(GameMenuFrame) self:OpenConfig() end) local S = self:GetModule("Skins") S:Reskin(configButton) end StaticPopupDialogs["CFG_RELOAD"] = { text = Locale["改变参数需重载应用设置"], button1 = ACCEPT, button2 = CANCEL, OnAccept = function() ReloadUI() end, timeout = 0, whileDead = 1, }
GUI fix
GUI fix
Lua
mit
fgprodigal/RayUI
4c00a7c4ce3af269ce62a9775cdbeeb316c1037a
hash.lua
hash.lua
local ffi = require 'ffi' local tds = require 'tds.env' local C = tds.C local hash = {} function hash.new() local self = C.tds_hash_new() if self == nil then error('unable to allocate hash') end ffi.gc(self, C.tds_hash_free) return self end local function lua2Celem(lelem) local elem if type(lelem) == 'string' then elem = C.tds_elem_string_new(lelem, #lelem) elseif type(lelem) == 'number' then elem = C.tds_elem_number_new(lelem) else error('string or number key/value expected') end if elem == nil then error('unable to allocate C key/value') end return elem end local function lkey2obj(self, lkey) local obj if type(lkey) == 'string' then obj = C.tds_hash_search_string(self, lkey, #lkey) elseif type(lkey) == 'number' then obj = C.tds_hash_search_number(self, lkey) else error('string or number key expected') end return obj end function hash:__newindex(lkey, lval) assert(self) local obj = lkey2obj(self, lkey) if obj ~= nil then if lval then local val = lua2Celem(lval) C.tds_hash_object_set_value(obj, val) else C.tds_hash_remove(self, obj) C.tds_hash_object_free(obj) end else local key = lua2Celem(lkey) local val = lua2Celem(lval) local obj = C.tds_hash_object_new(key, val) C.tds_hash_insert(self, obj) end end local function objelem2lua(val) assert(val) local valtyp = ffi.string(C.tds_elem_typename(val)) if valtyp == 'number' then return ffi.cast('tds_number*', val).value elseif valtyp == 'string' then val = ffi.cast('tds_string*', val) return ffi.string(val.data, val.size) else error(string.format('value type <%s> not supported yet', valtyp)) end end function hash:__index(lkey) assert(self) local obj = lkey2obj(self, lkey) if obj ~= nil then local val = C.tds_hash_object_value(obj) return objelem2lua(val) end end function hash:__len() assert(self) return tonumber(C.tds_hash_size(self)) end function hash:__pairs() assert(self) local iterator = C.tds_hash_iterator_new(self) ffi.gc(iterator, C.tds_hash_iterator_free) return function() local obj = C.tds_hash_iterator_next(iterator) if obj ~= nil then local key = C.tds_hash_object_key(obj) local val = C.tds_hash_object_value(obj) return objelem2lua(key), objelem2lua(val) end end end hash.pairs = hash.__pairs ffi.metatype('tds_hash', hash) -- table constructor local hash_ctr = {} setmetatable( hash_ctr, { __index = hash, __newindex = hash, __call = hash.new } ) tds.hash = hash_ctr return hash_ctr
local ffi = require 'ffi' local tds = require 'tds.env' local C = tds.C local hash = {} function hash.new() local self = C.tds_hash_new() if self == nil then error('unable to allocate hash') end ffi.gc(self, C.tds_hash_free) return self end local function lua2Celem(lelem) local elem if type(lelem) == 'string' then elem = C.tds_elem_string_new(lelem, #lelem) elseif type(lelem) == 'number' then elem = C.tds_elem_number_new(lelem) else error('string or number key/value expected') end if elem == nil then error('unable to allocate C key/value') end return elem end local function lkey2obj(self, lkey) local obj if type(lkey) == 'string' then obj = C.tds_hash_search_string(self, lkey, #lkey) elseif type(lkey) == 'number' then obj = C.tds_hash_search_number(self, lkey) else error('string or number key expected') end return obj end function hash:__newindex(lkey, lval) assert(self) local obj = lkey2obj(self, lkey) if obj ~= nil then if lval then local val = lua2Celem(lval) C.tds_hash_object_set_value(obj, val) else C.tds_hash_remove(self, obj) C.tds_hash_object_free(obj) end else if lval then local key = lua2Celem(lkey) local val = lua2Celem(lval) local obj = C.tds_hash_object_new(key, val) C.tds_hash_insert(self, obj) end end end local function objelem2lua(val) assert(val) local valtyp = ffi.string(C.tds_elem_typename(val)) if valtyp == 'number' then return ffi.cast('tds_number*', val).value elseif valtyp == 'string' then val = ffi.cast('tds_string*', val) return ffi.string(val.data, val.size) else error(string.format('value type <%s> not supported yet', valtyp)) end end function hash:__index(lkey) assert(self) local obj = lkey2obj(self, lkey) if obj ~= nil then local val = C.tds_hash_object_value(obj) return objelem2lua(val) end end function hash:__len() assert(self) return tonumber(C.tds_hash_size(self)) end function hash:__pairs() assert(self) local iterator = C.tds_hash_iterator_new(self) ffi.gc(iterator, C.tds_hash_iterator_free) return function() local obj = C.tds_hash_iterator_next(iterator) if obj ~= nil then local key = C.tds_hash_object_key(obj) local val = C.tds_hash_object_value(obj) return objelem2lua(key), objelem2lua(val) end end end hash.pairs = hash.__pairs ffi.metatype('tds_hash', hash) -- table constructor local hash_ctr = {} setmetatable( hash_ctr, { __index = hash, __newindex = hash, __call = hash.new } ) tds.hash = hash_ctr return hash_ctr
hash: fix case where value is nil and key does not exist
hash: fix case where value is nil and key does not exist
Lua
bsd-3-clause
torch/tds,jakezhaojb/tds,jakezhaojb/tds,jakezhaojb/tds,Moodstocks/tds,jakezhaojb/tds
c7f8c682f4eddb35faa6cc6c4f5d8bb096e495f1
test/test_metadata.lua
test/test_metadata.lua
local function zap_handler(pipe) local function recv_zap(sok) local msg, err = sok:recv_all() if not msg then return nil, err end local req = { version = msg[1]; -- Version number, must be "1.0" sequence = msg[2]; -- Sequence number of request domain = msg[3]; -- Server socket domain address = msg[4]; -- Client IP address identity = msg[5]; -- Server socket idenntity mechanism = msg[6]; -- Security mechansim } if req.mechanism == "PLAIN" then req.username = msg[7]; -- PLAIN user name req.password = msg[8]; -- PLAIN password, in clear text elseif req.mechanism == "CURVE" then req.client_key = msg[7]; -- CURVE client public key end return req end local function send_zap(sok, req, status, text, user, meta) return sok:sendx(req.version, req.sequence, status, text, user or "", meta or "") end local function mpair(k, v) -- mpair support values shorter than 255 return string.char(#k) .. k .. "\000\000\000" .. string.char(#v) .. v end --=========================================================================== local zmq = require "lzmq" local ctx = pipe:context() local handler, err = ctx:socket{zmq.REP, bind = "inproc://zeromq.zap.01", linger = 0, } zmq.assert(handler, err) pipe:send("start") local metadata = mpair("Hello", "World") .. mpair("World", "Hello") print("Start ZAP handler") -- Process ZAP requests forever while true do local req, err = recv_zap(handler) if not req then break end --Terminating assert (req.version == "1.0" ) assert (req.mechanism == "NULL") if req.domain == "DOMAIN" then send_zap(handler, req, "200", "OK", "anonymous", metadata ) else send_zap(handler, req.version, "400", "BAD DOMAIN", "", "" ) end end ctx:destroy() print("Stop ZAP handler") end local function main() local zmq = require "lzmq" local zthreads = require "lzmq.threads" local zassert = zmq.assert local msg = zmq.msg_init() if not msg.gets then print("This version does not support zmq_msg_gets version!") return end local ctx = zassert(zmq.context()) local zap_thread, pipe = zthreads.fork(ctx, string.dump(zap_handler)) assert(zap_thread, pipe) pipe:set_rcvtimeo(500) assert(zap_thread:start()) assert(pipe:recv() == "start") local server, err = ctx:socket{zmq.DEALER, zap_domain = "DOMAIN", bind = "tcp://127.0.0.1:9001", } zassert (server, err) local client, err = ctx:socket{zmq.DEALER, connect = "tcp://127.0.0.1:9001", } zassert (client, err) client:send("This is a message") local msg = zassert(server:recv_new_msg()) assert(msg:gets("Hello") == "World") assert(msg:gets("World") == "Hello") assert(msg:gets("Socket-Type") == "DEALER") assert(msg:gets("User-Id") == "anonymous") msg:close() ctx:destroy() -- Wait until ZAP handler terminates zap_thread:join() end main() print("Done!")
local function zap_handler(pipe) local function recv_zap(sok) local msg, err = sok:recv_all() if not msg then return nil, err end local req = { version = msg[1]; -- Version number, must be "1.0" sequence = msg[2]; -- Sequence number of request domain = msg[3]; -- Server socket domain address = msg[4]; -- Client IP address identity = msg[5]; -- Server socket idenntity mechanism = msg[6]; -- Security mechansim } if req.mechanism == "PLAIN" then req.username = msg[7]; -- PLAIN user name req.password = msg[8]; -- PLAIN password, in clear text elseif req.mechanism == "CURVE" then req.client_key = msg[7]; -- CURVE client public key end return req end local function mpair(k, v) -- mpair support values shorter than 255 return string.char(#k) .. k .. "\000\000\000" .. string.char(#v) .. v end local function zmeta(t) if not t then return "" end if type(t) == "string" then return t end local s = "" for k, v in pairs(t) do s = s .. mpair(k,v) end return s end local function send_zap(sok, req, status, text, user, meta) return sok:sendx(req.version, req.sequence, status, text, user or "", zmeta(meta)) end --=========================================================================== local zmq = require "lzmq" local ctx = pipe:context() local handler, err = ctx:socket{zmq.REP, bind = "inproc://zeromq.zap.01", linger = 0, } zmq.assert(handler, err) pipe:send("start") local metadata = { Hello = "World"; World = "Hello"; } print("Start ZAP handler") -- Process ZAP requests forever while true do local req, err = recv_zap(handler) if not req then break end --Terminating assert (req.version == "1.0" ) assert (req.mechanism == "NULL") if req.domain == "DOMAIN" then send_zap(handler, req, "200", "OK", "anonymous", metadata ) else send_zap(handler, req.version, "400", "BAD DOMAIN", "", "" ) end end print("Stop ZAP handler") end local ctx, zap_thread local function main() local zmq = require "lzmq" local zthreads = require "lzmq.threads" local zassert = zmq.assert local msg = zmq.msg_init() if not msg.gets then print("This version does not support zmq_msg_gets version!") return end ctx = zassert(zmq.context()) local pipe zap_thread, pipe = zthreads.fork(ctx, string.dump(zap_handler)) assert(zap_thread, pipe) pipe:set_rcvtimeo(500) assert(zap_thread:start()) assert(pipe:recv() == "start") local server, err = ctx:socket{zmq.DEALER, zap_domain = "DOMAIN", bind = "tcp://127.0.0.1:9001", } zassert (server, err) local client, err = ctx:socket{zmq.DEALER, connect = "tcp://127.0.0.1:9001", } zassert (client, err) client:send("This is a message") local msg = zassert(server:recv_new_msg()) assert(msg:gets("Hello") == "World") assert(msg:gets("World") == "Hello") assert(msg:gets("Socket-Type") == "DEALER") assert(msg:gets("User-Id") == "anonymous") msg:close() end local ok, err = pcall(main) if ctx then ctx:shutdown() end if zap_thread then zap_thread:join() end if ctx then ctx:destroy() end if not ok then print("Fail:", err) os.exit(-1) end print("Done!")
Fix. `test_metadata` hangup on test failure.
Fix. `test_metadata` hangup on test failure.
Lua
mit
zeromq/lzmq,zeromq/lzmq,LuaDist/lzmq-ffi,moteus/lzmq,bsn069/lzmq,bsn069/lzmq,LuaDist/lzmq-ffi,moteus/lzmq,moteus/lzmq,zeromq/lzmq,LuaDist/lzmq,LuaDist/lzmq
d0fd38a5802193db77045d940c7f0f31de0ac35d
init.lua
init.lua
local init = {} function init.getfiles() print("initializing files...") local repo = nil for line in io.lines("init.files") do if repo == nil do repo = line print("repo " .. repo) else print("getting " .. line) os.execute("wget https://raw.githubusercontent.com/" .. repo .. "/master/" .. line .. " " .. line) end end print("done") end function init.clone(repo) os.execute("wget https://raw.githubusercontent.com/" .. repo .. "/master/init.files init.files") end if arg[1] ~= nil then init.clone(arg[1]) end return init
local init = {} function init.getfiles() print("initializing files...") local repo = nil for line in io.lines(os.getenv("PWD") .. "/init.files") do if repo == nil do repo = line print("repo " .. repo) else print("getting " .. line) os.execute("wget -f https://raw.githubusercontent.com/" .. repo .. "/master/" .. line .. " " .. line) end end print("done") end function init.clone(repo) os.execute("wget -f https://raw.githubusercontent.com/" .. repo .. "/master/init.files init.files") init.getfiles() end if arg[1] ~= nil then init.clone(arg[1]) end return init
fixes init issues
fixes init issues
Lua
apache-2.0
InfinitiesLoop/oclib
712bc925dfc1601111922d4bd9089ad161867020
packages/unichar.lua
packages/unichar.lua
SILE.registerCommand("unichar", function(_, content) local cp = content[1] if type(cp) ~= "string" then SU.error("Bad argument to \\unicode") end SILE.typesetter:typeset(SU.utf8charfromcodepoint(cp)) end) return { documentation = [[\begin{document} \script[src=packages/unichar] SILE is Unicode compatible, and expects its input files to be in the UTF-8 encoding. (The actual range of Unicode characters supported will depend on the supported ranges of the fonts that SILE is using to typeset.) Some Unicode characters are hard to locate on a standard keyboard, and so are difficult to enter into SILE documents. The \code{unichar} package helps with this problem by providing a command to enter Unicode codepoints. After loading \code{unichar}, the \code{\\unichar} command becomes available: \begin{verbatim} \line \\unichar\{U+263A\} \% produces \font[family=Symbola]{\unichar{U+263A}} \line \end{verbatim} If the argument to \code{\\unichar} begins \code{U+}, \code{u+}, \code{0x} or \code{0X}, then it is assumed to be a hexadecimal value. Otherwise it is assumed to be a decimal codepoint. \end{document}]] }
SILE.registerCommand("unichar", function(_, content) local cp = content[1] if type(cp) ~= "string" then SU.error("Bad argument to \\unicode") end local hlist = SILE.typesetter.state.nodes local char = SU.utf8charfromcodepoint(cp) if #hlist > 1 and hlist[#hlist].is_unshaped then hlist[#hlist].text = hlist[#hlist].text .. char else SILE.typesetter:typeset(char) end end) return { documentation = [[\begin{document} \script[src=packages/unichar] SILE is Unicode compatible, and expects its input files to be in the UTF-8 encoding. (The actual range of Unicode characters supported will depend on the supported ranges of the fonts that SILE is using to typeset.) Some Unicode characters are hard to locate on a standard keyboard, and so are difficult to enter into SILE documents. The \code{unichar} package helps with this problem by providing a command to enter Unicode codepoints. After loading \code{unichar}, the \code{\\unichar} command becomes available: \begin{verbatim} \line \\unichar\{U+263A\} \% produces \font[family=Symbola]{\unichar{U+263A}} \line \end{verbatim} If the argument to \code{\\unichar} begins \code{U+}, \code{u+}, \code{0x} or \code{0X}, then it is assumed to be a hexadecimal value. Otherwise it is assumed to be a decimal codepoint. \end{document}]] }
fix(packages): Combine unichar output with existing unshaped node
fix(packages): Combine unichar output with existing unshaped node
Lua
mit
alerque/sile,alerque/sile,alerque/sile,alerque/sile
420564820c69cbaf65095f706035d34cfb5c1002
usefulFunctions.lua
usefulFunctions.lua
-- Requires ------------------------------------------------------------------ require 'sys' -- Functions ----------------------------------------------------------------- -- LS - unix listing command function eex.ls(path) return sys.split(sys.ls(path),'\n') end -- datasetPath - getting the environmental $DATASET variable function eex.datasetPath() local ds ds = os.getenv("EEX_DATASETS") if not ds then io.write [[ ****************************************************************************** WARNING - $DATASET environment variable is not defined ****************************************************************************** Please define an environment $DATASET variable $ export EEX_DATASETS='datasetDirectoryOnCurrentMachine' and add it to your <.bashrc> configuration file in order to do not visualise this WARNING message again ****************************************************************************** Please, type the dataset directory path for the current machine: ]] ds = io.read() end return ds end
-- Requires ------------------------------------------------------------------ require 'sys' -- Functions ----------------------------------------------------------------- -- eex.ls - unix listing command function eex.ls(path) return sys.split(sys.ls(path),'\n') end -- eex.datasetPath - getting the environmental $EEX_DATASETS variable function eex.datasetsPath() local ds ds = os.getenv("EEX_DATASETS") if not ds then io.write [[ ****************************************************************************** WARNING - $EEX_DATASETS environment variable is not defined ****************************************************************************** Please define an environment $EEX_DATASETS variable $ export EEX_DATASETS='datasetsDirectoryOnCurrentMachine' and add it to your <.bashrc> configuration file in order to do not visualise this WARNING message again ****************************************************************************** Please, type the dataset directory path for the current machine: ]] ds = io.read() io.write '\n' end return ds end
Cleaning up the code
Cleaning up the code Changed comments adding the <eex.> prefix Corrected $EEX_DATASETS spelling Added an <s> to whatever <dataset> was missing it
Lua
bsd-3-clause
e-lab/eex
7c4053b23be9be7df1a5827adcc1194aa08f3f58
src/dns.resolvers.lua
src/dns.resolvers.lua
local loader = function(loader, ...) local resolver = require"cqueues.dns.resolver" local config = require"cqueues.dns.config" local condition = require"cqueues.condition" local monotime = require"cqueues".monotime local random = require"cqueues.dns".random local errno = require"cqueues.errno" local ETIMEDOUT = errno.ETIMEDOUT local function todeadline(timeout) return (timeout and (monotime() + timeout)) or nil end -- todeadline local function totimeout(deadline) return (deadline and math.max(0, deadline - monotime())) or nil end -- totimeout -- -- NOTE: Keep track of an unordered collection of objects, and in -- particular a count of objects in the collection. If an object is -- garbage collected automatically decrement the count and signal -- the condition variable. -- local alive = {} function alive.new(condvar) local self = setmetatable({}, { __index = alive }) self.n = 0 self.table = setmetatable({}, { __mode = "k" }) self.condvar = condvar self.hooks = {} self.hookmt = { __gc = function (hook) self.n = self.n - 1 self.condvar:signal() end } return self end -- alive.new function alive:add(x) if not self.table[x] then local hook = self.hooks[#self.hooks] if hook then self.hooks[#self.hooks] = nil else hook = setmetatable({}, self.hookmt) end self.table[x] = hook self.n = self.n + 1 end end -- alive:add function alive:delete(x) if self.table[x] then self.hooks[#self.hooks + 1] = self.table[x] self.table[x] = nil self.n = self.n - 1 self.condvar:signal() end end -- alive:delete function alive:check() local n = 0 for _ in pairs(self.table) do n = n + 1 end return assert(n == self.n, "resolver registry corrupt") end -- alive:check local pool = {} local function tryget(self) local res, why local cache_len = #self.cache if cache_len > 1 then res = self.cache[cache_len] self.cache[cache_len] = nil elseif self.alive.n < self.hiwat then res, why = resolver.new(self.resconf, self.hosts, self.hints) if not res then return nil, why end end self.alive:add(res) return res end -- tryget local function getby(self, deadline) local res, why = tryget(self) while not res and not why do if deadline and deadline <= monotime() then return nil, ETIMEDOUT else self.condvar:wait(totimeout(deadline)) res, why = tryget(self) end end return res, why end -- getby function pool:get(timeout) return getby(self, todeadline(timeout)) end -- pool:get function pool:put(res) self.alive:delete(res) local cache_len = #self.cache if cache_len < self.lowat and res:stat().queries < self.querymax then if not self.lifo and cache_len > 0 then local i = random(cache_len+1) + 1 self.cache[cache_len+1] = self.cache[i] self.cache[i] = res else self.cache[cache_len+1] = res end else res:close() end end -- pool:put function pool:signal() self.condvar:signal() end -- pool:signal function pool:query(name, type, class, timeout) local deadline = todeadline(timeout or self.timeout) local res, why = getby(self, deadline) if not res then return nil, why end local pkt, why = res:query(name, type, class, totimeout(deadline)) if not self.debug then self:put(res) end return pkt, why end -- pool:query local resolvers = {} resolvers.lowat = 1 resolvers.hiwat = 32 resolvers.querymax = 2048 resolvers.debug = nil resolvers.lifo = false function resolvers.new(resconf, hosts, hints) local self = {} self.resconf = (type(resconf) == "table" and config.new(resconf)) or resconf self.hosts = hosts self.hints = hints self.condvar = condition.new() self.lowat = resolvers.lowat self.hiwat = resolvers.hiwat self.timeout = resolvers.timeout self.querymax = resolvers.querymax self.debug = resolvers.debug self.lifo = resolvers.lifo self.cache = {} self.alive = alive.new(self.condvar) return setmetatable(self, { __index = pool }) end -- resolvers.new function resolvers.stub(cfg) return resolvers.new(config.stub(cfg)) end -- resolvers.stub function resolvers.root(cfg) return resolvers.new(config.root(cfg)) end -- resolvers.root function resolvers.type(o) local mt = getmetatable(o) if mt and mt.__index == pool then return "dns resolver pool" end end -- resolvers.type resolvers.loader = loader return resolvers end return loader(loader, ...)
local loader = function(loader, ...) local resolver = require"cqueues.dns.resolver" local config = require"cqueues.dns.config" local condition = require"cqueues.condition" local monotime = require"cqueues".monotime local random = require"cqueues.dns".random local errno = require"cqueues.errno" local ETIMEDOUT = errno.ETIMEDOUT local function todeadline(timeout) return (timeout and (monotime() + timeout)) or nil end -- todeadline local function totimeout(deadline) return (deadline and math.max(0, deadline - monotime())) or nil end -- totimeout -- -- NOTE: Keep track of an unordered collection of objects, and in -- particular a count of objects in the collection. If an object is -- garbage collected automatically decrement the count and signal -- the condition variable. -- local new_hook if _G._VERSION == "Lua 5.1" then -- Lua 5.1 does not support __gc on tables, so we need to use newproxy new_hook = function(mt) local u = newproxy(false) debug.setmetatable(u, mt) return u end else new_hook = function(mt) return setmetatable({}, mt) end end local alive = {} function alive.new(condvar) local self = setmetatable({}, { __index = alive }) self.n = 0 self.table = setmetatable({}, { __mode = "k" }) self.condvar = condvar self.hooks = {} self.hookmt = { __gc = function (hook) self.n = self.n - 1 self.condvar:signal() end } return self end -- alive.new function alive:add(x) if not self.table[x] then local hook = self.hooks[#self.hooks] if hook then self.hooks[#self.hooks] = nil else hook = new_hook(self.hookmt) end self.table[x] = hook self.n = self.n + 1 end end -- alive:add function alive:delete(x) if self.table[x] then self.hooks[#self.hooks + 1] = self.table[x] self.table[x] = nil self.n = self.n - 1 self.condvar:signal() end end -- alive:delete function alive:check() local n = 0 for _ in pairs(self.table) do n = n + 1 end return assert(n == self.n, "resolver registry corrupt") end -- alive:check local pool = {} local function tryget(self) local res, why local cache_len = #self.cache if cache_len > 1 then res = self.cache[cache_len] self.cache[cache_len] = nil elseif self.alive.n < self.hiwat then res, why = resolver.new(self.resconf, self.hosts, self.hints) if not res then return nil, why end end self.alive:add(res) return res end -- tryget local function getby(self, deadline) local res, why = tryget(self) while not res and not why do if deadline and deadline <= monotime() then return nil, ETIMEDOUT else self.condvar:wait(totimeout(deadline)) res, why = tryget(self) end end return res, why end -- getby function pool:get(timeout) return getby(self, todeadline(timeout)) end -- pool:get function pool:put(res) self.alive:delete(res) local cache_len = #self.cache if cache_len < self.lowat and res:stat().queries < self.querymax then if not self.lifo and cache_len > 0 then local i = random(cache_len+1) + 1 self.cache[cache_len+1] = self.cache[i] self.cache[i] = res else self.cache[cache_len+1] = res end else res:close() end end -- pool:put function pool:signal() self.condvar:signal() end -- pool:signal function pool:query(name, type, class, timeout) local deadline = todeadline(timeout or self.timeout) local res, why = getby(self, deadline) if not res then return nil, why end local pkt, why = res:query(name, type, class, totimeout(deadline)) if not self.debug then self:put(res) end return pkt, why end -- pool:query local resolvers = {} resolvers.lowat = 1 resolvers.hiwat = 32 resolvers.querymax = 2048 resolvers.debug = nil resolvers.lifo = false function resolvers.new(resconf, hosts, hints) local self = {} self.resconf = (type(resconf) == "table" and config.new(resconf)) or resconf self.hosts = hosts self.hints = hints self.condvar = condition.new() self.lowat = resolvers.lowat self.hiwat = resolvers.hiwat self.timeout = resolvers.timeout self.querymax = resolvers.querymax self.debug = resolvers.debug self.lifo = resolvers.lifo self.cache = {} self.alive = alive.new(self.condvar) return setmetatable(self, { __index = pool }) end -- resolvers.new function resolvers.stub(cfg) return resolvers.new(config.stub(cfg)) end -- resolvers.stub function resolvers.root(cfg) return resolvers.new(config.root(cfg)) end -- resolvers.root function resolvers.type(o) local mt = getmetatable(o) if mt and mt.__index == pool then return "dns resolver pool" end end -- resolvers.type resolvers.loader = loader return resolvers end return loader(loader, ...)
src/dns.resolvers: Work around no __gc on tables in 5.1
src/dns.resolvers: Work around no __gc on tables in 5.1 Fixes issue #44
Lua
mit
wahern/cqueues,daurnimator/cqueues,daurnimator/cqueues,bigcrush/cqueues,wahern/cqueues,bigcrush/cqueues
4974cda1860cdde942b3c6cc4347c23153a7f8bb
tools/premake/app_template.lua
tools/premake/app_template.lua
local function add_osx_links() links { "Cocoa.framework", "OpenGL.framework", "GameController.framework", "iconv", "fmod" } end local function add_linux_links() links { "pthread", "GLEW", "GLU", "GL", "X11", "fmod" } end local function add_win32_links() links { "d3d11.lib", "dxguid.lib", "winmm.lib", "comctl32.lib", "fmod64_vc.lib", "Shlwapi.lib" } end local function add_ios_links() links { "OpenGLES.framework", "Foundation.framework", "UIKit.framework", "GLKit.framework", "QuartzCore.framework", } end local function add_ios_files(project_name, root_directory) files { (pmtech_dir .. "/template/ios/**.*"), "bin/ios/data" } excludes { ("**.DS_Store") } xcodebuildresources { "bin/ios/data" } end local function setup_android() files { pmtech_dir .. "/template/android/manifest/**.*", pmtech_dir .. "/template/android/activity/**.*" } androidabis { "armeabi-v7a", "x86" } end local function setup_platform(project_name, root_directory) if platform_dir == "win32" then systemversion(windows_sdk_version()) disablewarnings { "4800", "4305", "4018", "4244", "4267", "4996" } add_win32_links() elseif platform_dir == "osx" then add_osx_links() elseif platform_dir == "ios" then add_ios_links() add_ios_files(project_name, root_directory) elseif platform_dir == "linux" then add_linux_links() elseif platform_dir == "android" then setup_android() end end local function setup_bullet() bullet_lib = "bullet_monolithic" bullet_lib_debug = "bullet_monolithic_d" bullet_lib_dir = "osx" if platform_dir == "linux" then bullet_lib_dir = "linux" end if _ACTION == "vs2017" or _ACTION == "vs2015" then bullet_lib_dir = _ACTION bullet_lib = (bullet_lib .. "_x64") bullet_lib_debug = (bullet_lib_debug .. "_x64") end libdirs { (pmtech_dir .. "third_party/bullet/lib/" .. bullet_lib_dir) } configuration "Debug" links { bullet_lib_debug } configuration "Release" links { bullet_lib } configuration {} end local function setup_fmod() libdirs { (pmtech_dir .. "third_party/fmod/lib/" .. platform_dir) } end function setup_modules() setup_bullet() setup_fmod() end function create_app(project_name, source_directory, root_directory) project ( project_name ) kind "WindowedApp" language "C++" dependson { "pen", "put" } includedirs { pmtech_dir .. "pen/include", pmtech_dir .. "pen/include/common", pmtech_dir .. "pen/include/" .. platform_dir, pmtech_dir .. "pen/include/" .. renderer_dir, pmtech_dir .. "put/include/", pmtech_dir .. "third_party/", "include/", } files { (root_directory .. "code/" .. source_directory .. "/**.cpp"), (root_directory .. "code/" .. source_directory .. "/**.c"), (root_directory .. "code/" .. source_directory .. "/**.h"), (root_directory .. "code/" .. source_directory .. "/**.m"), (root_directory .. "code/" .. source_directory .. "/**.mm") } libdirs { pmtech_dir .. "pen/lib/" .. platform_dir, pmtech_dir .. "put/lib/" .. platform_dir, } setup_env() setup_platform(project_name, root_directory) setup_modules() location (root_directory .. "/build/" .. platform_dir) targetdir (root_directory .. "/bin/" .. platform_dir) debugdir (root_directory .. "/bin/" .. platform_dir) configuration "Debug" defines { "DEBUG" } flags { "WinMain" } symbols "On" targetname (project_name .. "_d") architecture "x64" configuration "Release" defines { "NDEBUG" } flags { "WinMain", "OptimizeSpeed" } targetname (project_name) architecture "x64" end function create_app_example( project_name, root_directory ) create_app( project_name, project_name, root_directory ) end
function add_gnu_make_links() if _ACTION == "gmake" configuration "Debug" links { "pen_d", "put_d" } configuration "Release" links { "pen", "put" } configuration {} end end local function add_osx_links() links { "Cocoa.framework", "OpenGL.framework", "GameController.framework", "iconv", "fmod" } add_gnu_make_links() end local function add_linux_links() links { "pthread", "GLEW", "GLU", "GL", "X11", "fmod" } add_gnu_make_links() end local function add_win32_links() links { "d3d11.lib", "dxguid.lib", "winmm.lib", "comctl32.lib", "fmod64_vc.lib", "Shlwapi.lib" } end local function add_ios_links() links { "OpenGLES.framework", "Foundation.framework", "UIKit.framework", "GLKit.framework", "QuartzCore.framework", } end local function add_ios_files(project_name, root_directory) files { (pmtech_dir .. "/template/ios/**.*"), "bin/ios/data" } excludes { ("**.DS_Store") } xcodebuildresources { "bin/ios/data" } end local function setup_android() files { pmtech_dir .. "/template/android/manifest/**.*", pmtech_dir .. "/template/android/activity/**.*" } androidabis { "armeabi-v7a", "x86" } end local function setup_platform(project_name, root_directory) if platform_dir == "win32" then systemversion(windows_sdk_version()) disablewarnings { "4800", "4305", "4018", "4244", "4267", "4996" } add_win32_links() elseif platform_dir == "osx" then add_osx_links() elseif platform_dir == "ios" then add_ios_links() add_ios_files(project_name, root_directory) elseif platform_dir == "linux" then add_linux_links() elseif platform_dir == "android" then setup_android() end end local function setup_bullet() bullet_lib = "bullet_monolithic" bullet_lib_debug = "bullet_monolithic_d" bullet_lib_dir = "osx" if platform_dir == "linux" then bullet_lib_dir = "linux" end if _ACTION == "vs2017" or _ACTION == "vs2015" then bullet_lib_dir = _ACTION bullet_lib = (bullet_lib .. "_x64") bullet_lib_debug = (bullet_lib_debug .. "_x64") end libdirs { (pmtech_dir .. "third_party/bullet/lib/" .. bullet_lib_dir) } configuration "Debug" links { bullet_lib_debug } configuration "Release" links { bullet_lib } configuration {} end local function setup_fmod() libdirs { (pmtech_dir .. "third_party/fmod/lib/" .. platform_dir) } end function setup_modules() setup_bullet() setup_fmod() end function create_app(project_name, source_directory, root_directory) project ( project_name ) kind "WindowedApp" language "C++" dependson { "pen", "put" } includedirs { pmtech_dir .. "pen/include", pmtech_dir .. "pen/include/common", pmtech_dir .. "pen/include/" .. platform_dir, pmtech_dir .. "pen/include/" .. renderer_dir, pmtech_dir .. "put/include/", pmtech_dir .. "third_party/", "include/", } files { (root_directory .. "code/" .. source_directory .. "/**.cpp"), (root_directory .. "code/" .. source_directory .. "/**.c"), (root_directory .. "code/" .. source_directory .. "/**.h"), (root_directory .. "code/" .. source_directory .. "/**.m"), (root_directory .. "code/" .. source_directory .. "/**.mm") } libdirs { pmtech_dir .. "pen/lib/" .. platform_dir, pmtech_dir .. "put/lib/" .. platform_dir, } setup_env() setup_platform(project_name, root_directory) setup_modules() location (root_directory .. "/build/" .. platform_dir) targetdir (root_directory .. "/bin/" .. platform_dir) debugdir (root_directory .. "/bin/" .. platform_dir) configuration "Debug" defines { "DEBUG" } flags { "WinMain" } symbols "On" targetname (project_name .. "_d") architecture "x64" configuration "Release" defines { "NDEBUG" } flags { "WinMain", "OptimizeSpeed" } targetname (project_name) architecture "x64" end function create_app_example( project_name, root_directory ) create_app( project_name, project_name, root_directory ) end
fix build for gmake
fix build for gmake
Lua
mit
polymonster/pmtech,polymonster/pmtech,polymonster/pmtech,polymonster/pmtech,polymonster/pmtech,polymonster/pmtech
69b826781a5c32d3a314f93ed60c840009b835da
frontend/gettext.lua
frontend/gettext.lua
local isAndroid, android = pcall(require, "android") local logger = require("logger") local GetText = { translation = {}, current_lang = "C", dirname = "l10n", textdomain = "koreader" } local GetText_mt = { __index = {} } function GetText_mt.__call(gettext, string) return gettext.translation[string] or string end local function c_escape(what) if what == "\n" then return "" elseif what == "a" then return "\a" elseif what == "b" then return "\b" elseif what == "f" then return "\f" elseif what == "n" then return "\n" elseif what == "r" then return "\r" elseif what == "t" then return "\t" elseif what == "v" then return "\v" elseif what == "0" then return "\0" -- shouldn't happen, though else return what end end -- for PO file syntax, see -- https://www.gnu.org/software/gettext/manual/html_node/PO-Files.html -- we only implement a sane subset for now function GetText_mt.__index.changeLang(new_lang) GetText.translation = {} GetText.current_lang = "C" -- the "C" locale disables localization alltogether if new_lang == "C" or new_lang == nil then return end -- strip encoding suffix in locale like "zh_CN.utf8" new_lang = new_lang:sub(1, new_lang:find(".%.")) local file = GetText.dirname .. "/" .. new_lang .. "/" .. GetText.textdomain .. ".po" local po = io.open(file, "r") if not po then logger.err("cannot open translation file:", file) return end local data = {} local what = nil while true do local line = po:read("*l") if line == nil or line == "" then if data.msgid and data.msgstr and data.msgstr ~= "" then GetText.translation[data.msgid] = string.gsub(data.msgstr, "\\(.)", c_escape) end -- stop at EOF: if line == nil then break end data = {} what = nil else -- comment if not line:match("^#") then -- new data item (msgid, msgstr, ... local w, s = line:match("^%s*(%a+)%s+\"(.*)\"%s*$") if w then what = w else -- string continuation s = line:match("^%s*\"(.*)\"%s*$") end if what and s then -- unescape \n or msgid won't match s = s:gsub("\\n", "\n") data[what] = (data[what] or "") .. s end end end end GetText.current_lang = new_lang end setmetatable(GetText, GetText_mt) if os.getenv("LANGUAGE") then GetText.changeLang(os.getenv("LANGUAGE")) elseif os.getenv("LC_ALL") then GetText.changeLang(os.getenv("LC_ALL")) elseif os.getenv("LC_MESSAGES") then GetText.changeLang(os.getenv("LC_MESSAGES")) elseif os.getenv("LANG") then GetText.changeLang(os.getenv("LANG")) end if isAndroid then local ffi = require("ffi") local buf = ffi.new("char[?]", 16) ffi.C.AConfiguration_getLanguage(android.app.config, buf) local lang = ffi.string(buf) ffi.C.AConfiguration_getCountry(android.app.config, buf) local country = ffi.string(buf) if lang and country then GetText.changeLang(lang.."_"..country) end end return GetText
local isAndroid, android = pcall(require, "android") local logger = require("logger") local GetText = { translation = {}, current_lang = "C", dirname = "l10n", textdomain = "koreader" } local GetText_mt = { __index = {} } function GetText_mt.__call(gettext, string) return gettext.translation[string] or string end local function c_escape(what) if what == "\n" then return "" elseif what == "a" then return "\a" elseif what == "b" then return "\b" elseif what == "f" then return "\f" elseif what == "n" then return "\n" elseif what == "r" then return "\r" elseif what == "t" then return "\t" elseif what == "v" then return "\v" elseif what == "0" then return "\0" -- shouldn't happen, though else return what end end -- for PO file syntax, see -- https://www.gnu.org/software/gettext/manual/html_node/PO-Files.html -- we only implement a sane subset for now function GetText_mt.__index.changeLang(new_lang) GetText.translation = {} GetText.current_lang = "C" -- the "C" locale disables localization alltogether if new_lang == "C" or new_lang == nil then return end -- strip encoding suffix in locale like "zh_CN.utf8" new_lang = new_lang:sub(1, new_lang:find(".%.")) local file = GetText.dirname .. "/" .. new_lang .. "/" .. GetText.textdomain .. ".po" local po = io.open(file, "r") if not po then logger.err("cannot open translation file:", file) return end local data = {} local what = nil while true do local line = po:read("*l") if line == nil or line == "" then if data.msgid and data.msgstr and data.msgstr ~= "" then GetText.translation[data.msgid] = string.gsub(data.msgstr, "\\(.)", c_escape) end -- stop at EOF: if line == nil then break end data = {} what = nil else -- comment if not line:match("^#") then -- new data item (msgid, msgstr, ... local w, s = line:match("^%s*(%a+)%s+\"(.*)\"%s*$") if w then what = w else -- string continuation s = line:match("^%s*\"(.*)\"%s*$") end if what and s then -- unescape \n or msgid won't match s = s:gsub("\\n", "\n") -- unescape " or msgid won't match s = s:gsub('\\"', '"') data[what] = (data[what] or "") .. s end end end end GetText.current_lang = new_lang end setmetatable(GetText, GetText_mt) if os.getenv("LANGUAGE") then GetText.changeLang(os.getenv("LANGUAGE")) elseif os.getenv("LC_ALL") then GetText.changeLang(os.getenv("LC_ALL")) elseif os.getenv("LC_MESSAGES") then GetText.changeLang(os.getenv("LC_MESSAGES")) elseif os.getenv("LANG") then GetText.changeLang(os.getenv("LANG")) end if isAndroid then local ffi = require("ffi") local buf = ffi.new("char[?]", 16) ffi.C.AConfiguration_getLanguage(android.app.config, buf) local lang = ffi.string(buf) ffi.C.AConfiguration_getCountry(android.app.config, buf) local country = ffi.string(buf) if lang and country then GetText.changeLang(lang.."_"..country) end end return GetText
gettext: unescape quotation mark
gettext: unescape quotation mark Fixes #2718.
Lua
agpl-3.0
Frenzie/koreader,mwoz123/koreader,poire-z/koreader,Hzj-jie/koreader,koreader/koreader,mihailim/koreader,apletnev/koreader,koreader/koreader,NiLuJe/koreader,poire-z/koreader,Frenzie/koreader,pazos/koreader,lgeek/koreader,houqp/koreader,Markismus/koreader,NiLuJe/koreader,robert00s/koreader
1b91f9de36e426768e6c02d15e6e2f743009d786
dock/dock.lua
dock/dock.lua
-- -- Ion-devel dock module configuration -- -- create a new dock on screen 0 dock = dockmod.create_dock(0, { name="dock", -- name for use in target="..." winprops hpos="right", -- horizontal position left|center|right vpos="bottom", -- vertical position top|middle|bottom grow="left", -- growth direction up|down|left|right is_auto=true, -- whether new dockapps should be added automatically }) defcmd("global", "toggle_dock", function() WDock.toggle(dock) -- toggle map/unmapped state end) defbindings("WScreen", { kpress(DEFAULT_MOD.."space", "toggle_dock") }) -- dockapp ordering -- Use the dockposition winprop to enforce an ordering on dockapps. The value is -- arbitrary and relative to other dockapps only. The default is 0. -- Unfortunately, many dockapps do not set their class/instance/role so they -- cannot be used with the winprop system. -- dockapp borders -- Use dockappborder=false to disable the drawing of a border around a dockapp. -- This is only effective if outline_style="each" (see dock-draw.lua). defwinprop{ instance="gkrellm2", dockposition=-100, -- place first dockborder=false, -- do not draw border if outline_style="each" } -- kludges defwinprop{ instance="wmxmms", target="dock", }
-- -- Ion-devel dock module configuration -- -- create a new dock on screen 0 dock = dockmod.create_dock(0, { name="dock", -- name for use in target="..." winprops hpos="right", -- horizontal position left|center|right vpos="bottom", -- vertical position top|middle|bottom grow="left", -- growth direction up|down|left|right is_auto=true, -- whether new dockapps should be added automatically }) function toggle_dock() WDock.toggle(dock) -- toggle map/unmapped state end defbindings("WScreen", { kpress(MOD1.."space", "toggle_dock()") }) -- dockapp ordering -- Use the dockposition winprop to enforce an ordering on dockapps. The value is -- arbitrary and relative to other dockapps only. The default is 0. -- Unfortunately, many dockapps do not set their class/instance/role so they -- cannot be used with the winprop system. -- dockapp borders -- Use dockappborder=false to disable the drawing of a border around a dockapp. -- This is only effective if outline_style="each" (see dock-draw.lua). defwinprop{ instance="gkrellm2", dockposition=-100, -- place first dockborder=false, -- do not draw border if outline_style="each" } -- kludges defwinprop{ instance="wmxmms", target="dock", }
trunk: changeset 1347
trunk: changeset 1347 Fixed dock configuration file for new binding system. darcs-hash:20040306230832-e481e-2d71d192dc3da859fc12096bad45316f9d5b50eb.gz
Lua
lgpl-2.1
raboof/notion,dkogan/notion,neg-serg/notion,anoduck/notion,dkogan/notion,anoduck/notion,knixeur/notion,neg-serg/notion,p5n/notion,raboof/notion,p5n/notion,p5n/notion,anoduck/notion,knixeur/notion,knixeur/notion,p5n/notion,neg-serg/notion,dkogan/notion,raboof/notion,knixeur/notion,knixeur/notion,dkogan/notion,anoduck/notion,dkogan/notion.xfttest,anoduck/notion,dkogan/notion.xfttest,p5n/notion,neg-serg/notion,dkogan/notion.xfttest,dkogan/notion.xfttest,dkogan/notion,raboof/notion
9e5f96f6f319729c5322f88f16f46e5b08a70437
pud/ui/TextEntry.lua
pud/ui/TextEntry.lua
local Class = require 'lib.hump.class' local Text = getClass 'pud.ui.Text' local KeyboardEvent = getClass 'pud.event.KeyboardEvent' local string_len = string.len local string_sub = string.sub local format = string.format -- TextEntry -- A text frame that gathers keyboard input. local TextEntry = Class{name='TextEntry', inherits=Text, function(self, ...) Text.construct(self, ...) InputEvents:register(self, KeyboardEvent) end } -- destructor function TextEntry:destroy() self._isEnteringText = nil -- Frame will unregister all InputEvents Text.destroy(self) end -- override Frame:onRelease() function TextEntry:onRelease(button, mods, wasInside) if wasInside and 'l' == button then self._isEnteringText = not self._isEnteringText end if self._isEnteringText then self._curStyle = self._activeStyle or self._hoverStyle or self._normalStyle elseif self._hovered then self._curStyle = self._hoverStyle or self._normalStyle else self._curStyle = self._normalStyle end self:_drawFB() end -- override Frame:onHoverIn() function TextEntry:onHoverIn(x, y) if self._isEnteringText then return end Text.onHoverIn(self, x, y) end -- override TextEntry:onHoverOut() function TextEntry:onHoverOut(x, y) if self._isEnteringText then return end Text.onHoverOut(self, x, y) end -- capture text input if in editing mode function TextEntry:KeyboardEvent(e) if not self._isEnteringText then return end if self._text then local text local line = #self._text + 1 repeat line = line - 1 text = self._text[line] until string.len(text) ~= 0 or line < 1 if line < 1 then line = 1 end text = text or self._text[line] local key = e:getKey() switch(key) { backspace = function() text = string_sub(text, 1, -2) end, escape = function() self._isEnteringText = false self:onRelease() end, default = function() local unicode = e:getUnicode() if unicode then text = format('%s%s', text, unicode) end end, } self._text[line] = text self:_drawFB() else warning('Text is missing!') end end -- the class return TextEntry
local Class = require 'lib.hump.class' local Text = getClass 'pud.ui.Text' local KeyboardEvent = getClass 'pud.event.KeyboardEvent' local string_len = string.len local string_sub = string.sub local format = string.format -- TextEntry -- A text frame that gathers keyboard input. local TextEntry = Class{name='TextEntry', inherits=Text, function(self, ...) Text.construct(self, ...) InputEvents:register(self, KeyboardEvent) end } -- destructor function TextEntry:destroy() self._isEnteringText = nil -- Frame will unregister all InputEvents Text.destroy(self) end -- override Frame:onRelease() function TextEntry:onRelease(button, mods, wasInside) if wasInside and 'l' == button then self._isEnteringText = not self._isEnteringText end if self._isEnteringText then self._curStyle = self._activeStyle or self._hoverStyle or self._normalStyle elseif self._hovered then self._curStyle = self._hoverStyle or self._normalStyle else self._curStyle = self._normalStyle end self:_drawFB() end -- override Frame:onHoverIn() function TextEntry:onHoverIn(x, y) if self._isEnteringText then return end Text.onHoverIn(self, x, y) end -- override TextEntry:onHoverOut() function TextEntry:onHoverOut(x, y) if self._isEnteringText then return end Text.onHoverOut(self, x, y) end -- capture text input if in editing mode function TextEntry:KeyboardEvent(e) if not self._isEnteringText then return end if self._text then -- copy the entire text local text = {} local numLines = #self._text for i=1,numLines do text[i] = self._text[i] end local line local lineNum = numLines + 1 repeat lineNum = lineNum - 1 line = text[lineNum] until string.len(line) ~= 0 or lineNum < 1 if lineNum < 1 then lineNum = 1 end line = line or text[lineNum] local key = e:getKey() switch(key) { backspace = function() line = string_sub(line, 1, -2) end, escape = function() self._isEnteringText = false self:onRelease() end, default = function() local unicode = e:getUnicode() if unicode then line = format('%s%s', line, unicode) end end, } text[lineNum] = line self:setText(text) self:_drawFB() else warning('Text is missing!') end end -- the class return TextEntry
fix entry to call setText() to ensure wrapping and truncating
fix entry to call setText() to ensure wrapping and truncating
Lua
mit
scottcs/wyx
239b7323da729e03f20e029640f218b2c8ffb3a2
core/certmanager.lua
core/certmanager.lua
-- Prosody IM -- Copyright (C) 2008-2010 Matthew Wild -- Copyright (C) 2008-2010 Waqas Hussain -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local configmanager = require "core.configmanager"; local log = require "util.logger".init("certmanager"); local ssl = ssl; local ssl_newcontext = ssl and ssl.newcontext; local setmetatable, tostring = setmetatable, tostring; local prosody = prosody; local resolve_path = configmanager.resolve_relative_path; local config_path = prosody.paths.config; module "certmanager" -- Global SSL options if not overridden per-host local default_ssl_config = configmanager.get("*", "core", "ssl"); local default_capath = "/etc/ssl/certs"; local default_verify = (ssl and ssl.x509 and { "peer", "client_once", "continue", "ignore_purpose" }) or "none"; local default_options = { "no_sslv2" }; function create_context(host, mode, user_ssl_config) user_ssl_config = user_ssl_config or default_ssl_config; if not ssl then return nil, "LuaSec (required for encryption) was not found"; end if not user_ssl_config then return nil, "No SSL/TLS configuration present for "..host; end local ssl_config = { mode = mode; protocol = user_ssl_config.protocol or "sslv23"; key = resolve_path(config_path, user_ssl_config.key); password = user_ssl_config.password; certificate = resolve_path(config_path, user_ssl_config.certificate); capath = resolve_path(config_path, user_ssl_config.capath or default_capath); cafile = resolve_path(config_path, user_ssl_config.cafile); verify = user_ssl_config.verify or default_verify; options = user_ssl_config.options or default_options; depth = user_ssl_config.depth; }; local ctx, err = ssl_newcontext(ssl_config); -- LuaSec ignores the cipher list from the config, so we have to take care -- of it ourselves (W/A for #x) if ctx and user_ssl_config.ciphers then local success; success, err = ssl.context.setcipher(ctx, user_ssl_config.ciphers); if not success then ctx = nil; end end if not ctx then err = err or "invalid ssl config" local file = err:match("^error loading (.-) %("); if file then if file == "private key" then file = ssl_config.key or "your private key"; elseif file == "certificate" then file = ssl_config.certificate or "your certificate file"; end local reason = err:match("%((.+)%)$") or "some reason"; if reason == "Permission denied" then reason = "Check that the permissions allow Prosody to read this file."; elseif reason == "No such file or directory" then reason = "Check that the path is correct, and the file exists."; elseif reason == "system lib" then reason = "Previous error (see logs), or other system error."; elseif reason == "(null)" or not reason then reason = "Check that the file exists and the permissions are correct"; else reason = "Reason: "..tostring(reason):lower(); end log("error", "SSL/TLS: Failed to load %s: %s (host: %s)", file, reason, host); else log("error", "SSL/TLS: Error initialising for host %s: %s (host: %s)", host, err, host); end end return ctx, err; end function reload_ssl_config() default_ssl_config = configmanager.get("*", "core", "ssl"); end prosody.events.add_handler("config-reloaded", reload_ssl_config); return _M;
-- Prosody IM -- Copyright (C) 2008-2010 Matthew Wild -- Copyright (C) 2008-2010 Waqas Hussain -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local configmanager = require "core.configmanager"; local log = require "util.logger".init("certmanager"); local ssl = ssl; local ssl_newcontext = ssl and ssl.newcontext; local setmetatable, tostring = setmetatable, tostring; local prosody = prosody; local resolve_path = configmanager.resolve_relative_path; local config_path = prosody.paths.config; module "certmanager" -- Global SSL options if not overridden per-host local default_ssl_config = configmanager.get("*", "core", "ssl"); local default_capath = "/etc/ssl/certs"; local default_verify = (ssl and ssl.x509 and { "peer", "client_once", "continue", "ignore_purpose" }) or "none"; local default_options = { "no_sslv2" }; function create_context(host, mode, user_ssl_config) user_ssl_config = user_ssl_config or default_ssl_config; if not ssl then return nil, "LuaSec (required for encryption) was not found"; end if not user_ssl_config then return nil, "No SSL/TLS configuration present for "..host; end local ssl_config = { mode = mode; protocol = user_ssl_config.protocol or "sslv23"; key = resolve_path(config_path, user_ssl_config.key); password = user_ssl_config.password or function() log("error", "Encrypted certificate for %s requires 'ssl' 'password' to be set in config", host); end; certificate = resolve_path(config_path, user_ssl_config.certificate); capath = resolve_path(config_path, user_ssl_config.capath or default_capath); cafile = resolve_path(config_path, user_ssl_config.cafile); verify = user_ssl_config.verify or default_verify; options = user_ssl_config.options or default_options; depth = user_ssl_config.depth; }; local ctx, err = ssl_newcontext(ssl_config); -- LuaSec ignores the cipher list from the config, so we have to take care -- of it ourselves (W/A for #x) if ctx and user_ssl_config.ciphers then local success; success, err = ssl.context.setcipher(ctx, user_ssl_config.ciphers); if not success then ctx = nil; end end if not ctx then err = err or "invalid ssl config" local file = err:match("^error loading (.-) %("); if file then if file == "private key" then file = ssl_config.key or "your private key"; elseif file == "certificate" then file = ssl_config.certificate or "your certificate file"; end local reason = err:match("%((.+)%)$") or "some reason"; if reason == "Permission denied" then reason = "Check that the permissions allow Prosody to read this file."; elseif reason == "No such file or directory" then reason = "Check that the path is correct, and the file exists."; elseif reason == "system lib" then reason = "Previous error (see logs), or other system error."; elseif reason == "(null)" or not reason then reason = "Check that the file exists and the permissions are correct"; else reason = "Reason: "..tostring(reason):lower(); end log("error", "SSL/TLS: Failed to load %s: %s (host: %s)", file, reason, host); else log("error", "SSL/TLS: Error initialising for host %s: %s (host: %s)", host, err, host); end end return ctx, err; end function reload_ssl_config() default_ssl_config = configmanager.get("*", "core", "ssl"); end prosody.events.add_handler("config-reloaded", reload_ssl_config); return _M;
core.certmanager: Log a message when a password is required but not supplied. fixes #214
core.certmanager: Log a message when a password is required but not supplied. fixes #214
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
79801d48671701a92a7603dcba1fb084b37c0240
fimbul/v35/weapon.lua
fimbul/v35/weapon.lua
--- @module fimbul.v35.weapon local base = _G local table = require('table') local magical_item = require('fimbul.v35.magical_item') local item = require('fimbul.v35.item') local util = require('fimbul.util') local logger = require('fimbul.logger') local weapon = magical_item:new() weapon.SIMPLE = 'simple' weapon.MARTIAL = 'martial' weapon.EXOTIC = 'exotic' function weapon:new(y) local neu = magical_item:new(y) setmetatable(neu, self) self.__index = self self.slot = item.WEAPON return neu end function weapon:is_ranged() return self.ranged or false end function weapon:is_double() return self.double or false end function weapon:is_simple() return self:category() == weapon.SIMPLE end function weapon:is_martial() return self:category() == weapon.MARTIAL end function weapon:is_exotic() return self:category() == weapon.EXOTIC end function weapon:base_damage(size) local s = size or self:size() return self._damage[s] end function weapon:price() local p, pr = magical_item.price(self) local base = self.cost or 0 if self.material then if self:is_double() then p, new = self.material:additional_cost('double', self) else p, new = self.material:additional_cost(self.class, self) end if new then p = p - base end if p ~= 0 then pr:add(p, 'material') end end return pr:value(), pr end function weapon:damage(size) local b = self:base_damage(size) if self.modifier > 0 then b = b .. '+' .. self.modifier end return b end function weapon:_check_ability(r, a) -- Call super method magical_item._check_ability(self, r, a) -- Nothing to check if a.weapon == nil then return end -- Check if we have 'ranged' only ability if a.weapon.ranged then if not a.weapon.ranged and self:is_ranged() then error('The ability "' .. a.name .. '" does not apply to ' .. 'ranged weapons.') elseif a.weapon.ranged and not self:is_ranged() then error('The ability "' .. a.name .. '" only applies to ' .. 'ranged weapons.') end end -- Damage types local found = false if a.weapon.damagetypes then for _, dt in base.ipairs(self.damagetypes) do if util.contains(a.weapon.damagetypes, dt) then found = true break end end end if not found then error('The ability "' .. a.name .. '" only applies to weapons ' .. 'dealing the following damage types: [' .. table.concat(a.weapon.damagetypes, ',') .. '] but this ' .. 'weapon only deals the following damage types: [' .. table.concat(self.damagetypes, ',') .. '].') end end function weapon:_parse_attributes(r, str) local tbl = util.split(str) local ret = false -- Call base class function to do basic resolving ret = magical_item._parse_attributes(self, r, str) return ret end function weapon:spawn(r, t) local neu = weapon:new() neu.name = t.name if t.type == nil then neu.type = t.name else neu.type = t.type end neu._category = t.category neu.class = t.class -- Damage neu.damagetypes = util.deepcopy(t.damage.types) neu._damage = util.deepcopy(t.damage) neu.threat = util.deepcopy(t.threat) or {20} neu.multiplier = t.multiplier or 2 -- Cost & Weight neu.cost = t.cost or 0 neu._weight = t.weight or 0 -- Misc. neu.reach = t.reach or 5 neu.double = t.double or false -- Ranged stuff neu.ranged = t.ranged or false neu.increment = t.increment or 10 -- Amount or how many neu.amount = 0 return neu end function weapon:string(extended) local e = extended or false local fmt = magical_item._string(self, e) local str = '' if e then str = str .. self:damage() str = str .. ' [' .. util.join(self.threat, ',') .. ']x' .. self.multiplier end return string.format(fmt, str) end return weapon
--- @module fimbul.v35.weapon local base = _G local table = require('table') local magical_item = require('fimbul.v35.magical_item') local item = require('fimbul.v35.item') local util = require('fimbul.util') local logger = require('fimbul.logger') local weapon = magical_item:new() weapon.SIMPLE = 'simple' weapon.MARTIAL = 'martial' weapon.EXOTIC = 'exotic' function weapon:new(y) local neu = magical_item:new(y) setmetatable(neu, self) self.__index = self self.slot = item.WEAPON return neu end function weapon:is_ranged() return self.ranged or false end function weapon:is_double() return self.double or false end function weapon:is_simple() return self:category() == weapon.SIMPLE end function weapon:is_martial() return self:category() == weapon.MARTIAL end function weapon:is_exotic() return self:category() == weapon.EXOTIC end function weapon:base_damage(size) local s = size or self:size() return self._damage[s] end function weapon:price() local p, pr = magical_item.price(self) local base = self.cost or 0 if self.material then if self:is_double() then p, new = self.material:additional_cost('double', self) else p, new = self.material:additional_cost(self.class, self) end if new then p = p - base end if p ~= 0 then pr:add(p, 'material') end end return pr:value(), pr end function weapon:damage(size) local b = self:base_damage(size) if self.modifier > 0 then b = b .. '+' .. self.modifier end return b end function weapon:_check_ability(r, a) local found = false -- Call super method magical_item._check_ability(self, r, a) -- Nothing to check if a.weapon == nil then return end -- Check if we have 'ranged' only ability if a.weapon.ranged ~= nil then if a.weapon.ranged == false and self:is_ranged() then error('The ability "' .. a.name .. '" does not apply to ' .. 'ranged weapons.') elseif a.weapon.ranged == true and not self:is_ranged() then error('The ability "' .. a.name .. '" only applies to ' .. 'ranged weapons.') end end -- Types if a.weapon.categories then if not util.contains(a.weapon.categories, self._category) then error('The ability "' .. a.name .. '" only works on the ' .. 'following weapon categories: [' .. table.concat(a.weapon.categories, ', ') .. '].') end end -- Types if a.weapon.types then if not util.contains(a.weapon.types, self.type) then error('The ability "' .. a.name .. '" only works on the ' .. 'following weapons: [' .. table.concat(a.weapon.types, ', ') .. '].') end end -- Classes if a.weapon.classes then if not util.contains(a.weapon.classes, self.class) then error('The ability "' .. a.name .. '" only works on the ' .. 'following weapon classes : [' .. table.concat(a.weapon.classes, ', ') .. '].') end end -- Damage types if a.weapon.damagetypes then found = false for _, dt in base.ipairs(self.damagetypes) do if util.contains(a.weapon.damagetypes, dt) then found = true break end end if not found then error('The ability "' .. a.name .. '" only applies to ' .. 'weapons dealing the following damage types: [' .. table.concat(a.weapon.damagetypes, ',') .. '] but this weapon only deals the following damage ' .. 'types: [' .. table.concat(self.damagetypes, ',') .. '].') end end end function weapon:_parse_attributes(r, str) local tbl = util.split(str) local ret = false -- Call base class function to do basic resolving ret = magical_item._parse_attributes(self, r, str) return ret end function weapon:spawn(r, t) local neu = weapon:new() neu.name = t.name if t.type == nil then neu.type = t.name else neu.type = t.type end neu._category = t.category neu.class = t.class -- Damage neu.damagetypes = util.deepcopy(t.damage.types) neu._damage = util.deepcopy(t.damage) neu.threat = util.deepcopy(t.threat) or {20} neu.multiplier = t.multiplier or 2 -- Cost & Weight neu.cost = t.cost or 0 neu._weight = t.weight or 0 -- Misc. neu.reach = t.reach or 5 neu.double = t.double or false -- Ranged stuff neu.ranged = t.ranged or false neu.increment = t.increment or 10 -- Amount or how many neu.amount = 0 return neu end function weapon:string(extended) local e = extended or false local fmt = magical_item._string(self, e) local str = '' if e then str = str .. self:damage() str = str .. ' [' .. util.join(self.threat, ',') .. ']x' .. self.multiplier end return string.format(fmt, str) end return weapon
Fix and add additional ability checks.
Fix and add additional ability checks.
Lua
bsd-2-clause
n0la/fimbul
39b21e86afcec7237913b65e2fb05f582e862609
modules/http/http.lua
modules/http/http.lua
module("http", package.seeall) local function str(char) return string.char(char) end local function getchar(stream) local char while true do char = stream:getchar() if char == -1 then coroutine.yield() else break end end return char end local function read_line(stream) local line = "" local char, c local read = 0 while true do c = getchar(stream) read = read+1 char = str(c) if c == 0xd then c = getchar(stream) read = read+1 if c == 0xa then return line, read else line = line .. char char = str(c) end elseif c == 0xa then return line, read end line = line .. char end end function sorted_pairs(t) local a = {} for n in pairs(t) do table.insert(a, n) end table.sort(a) local i = 0 local iter = function () -- iterator function i = i + 1 if a[i] == nil then return nil else return a[i], t[a[i]] end end return iter end local function dump(t, indent) for n, v in sorted_pairs(t) do if type(v) == "table" then print(indent, n) dump(v, indent .. " ") elseif type(v) ~= "thread" and type(v) ~= "userdata" and type(v) ~= "function" then print(indent, n, "=", v) end end end local function parse_header(stream, http) local total_len = 0 http.headers = {} http._headers_order = {} line, len = read_line(stream) total_len = total_len + len while #line > 0 do local name, value = line:match("([^%s]+):%s*(.+)") if not name then http._invalid = string.format("invalid header '%s'", line) return end http.headers[name] = value table.insert(http._headers_order, name) line, len = read_line(stream) total_len = total_len + len end return total_len end local function parse_request(stream, http) local len, total_len local line, len = read_line(stream) total_len = len http.method, http.uri, http.version = line:match("([^%s]+) ([^%s]+) (.+)") if not http.method then http._invalid = string.format("invalid request '%s'", line) return end total_len = total_len + parse_header(stream, http) http.data = stream http._length = total_len http.dump = function (self) dump(self, "") end return true end local function parse_response(stream, http) local len, total_len local line, len = read_line(stream) total_len = len http.version, http.status, http.reason = line:match("([^%s]+) ([^%s]+) (.+)") if not http.version then http._invalid = string.format("invalid response '%s'", line) return end total_len = total_len + parse_header(stream, http) http.data = stream http._length = total_len http.dump = function (self) dump(self, "") end return true end local function build_headers(stream, headers, headers_order) local copy = headers for _, name in pairs(headers_order) do local value = copy[name] if value then copy[name] = nil stream:insert(name) stream:insert(": ") stream:insert(value) stream:insert("\r\n") end end for name, value in pairs(copy) do if value then stream:insert(name) stream:insert(": ") stream:insert(value) stream:insert("\r\n") end end end local function forge(http) local tcp = http._tcp_stream if tcp then if http._state == 2 and tcp.direction then http._state = 3 tcp.stream:seek(http.request._mark, true) http.request._mark = nil tcp.stream:erase(http.request._length) tcp.stream:insert(http.request.method) tcp.stream:insert(" ") tcp.stream:insert(http.request.uri) tcp.stream:insert(" ") tcp.stream:insert(http.request.version) tcp.stream:insert("\r\n") build_headers(tcp.stream, http.request.headers, http.request._headers_order) tcp.stream:insert("\r\n") elseif http._state == 5 and not tcp.direction then http._state = 0 tcp.stream:seek(http.response._mark, true) http.response._mark = nil tcp.stream:erase(http.response._length) tcp.stream:insert(http.response.version) tcp.stream:insert(" ") tcp.stream:insert(http.response.status) tcp.stream:insert(" ") tcp.stream:insert(http.response.reason) tcp.stream:insert("\r\n") build_headers(tcp.stream, http.response.headers, http.response._headers_order) tcp.stream:insert("\r\n") end http._tcp_stream = nil end return tcp end local function parse(http, context, f, name, next_state) if not context._co then context._mark = http._tcp_stream.stream:mark() context._co = coroutine.create(function () f(http._tcp_stream.stream, context) end) end coroutine.resume(context._co) if coroutine.status(context._co) == "dead" then if not context._invalid then http._state = next_state if haka.rule_hook("http-".. name, http) then return nil end context.next_dissector = http.next_dissector else haka.log.error("http", context._invalid) http._tcp_stream:drop() return nil end end end haka.dissector { name = "http", dissect = function (stream) if not stream.connection.data._http then local http = {} http.dissector = "http" http.next_dissector = nil http.valid = function (self) return self._tcp_stream:valid() end http.drop = function (self) return self._tcp_stream:drop() end http.forge = forge http._state = 0 stream.connection.data._http = http end local http = stream.connection.data._http http._tcp_stream = stream if stream.direction then if http._state == 0 or http._state == 1 then if stream.stream:available() > 0 then if http._state == 0 then http.request = {} http.response = nil http._state = 1 end parse(http, http.request, parse_request, "request", 2) end elseif http.request then http.next_dissector = http.request.next_dissector end else if http._state == 3 or http._state == 4 then if stream.stream:available() > 0 then if http._state == 3 then http.response = {} http._state = 4 end parse(http, http.response, parse_response, "response", 5) end elseif http.response then http.next_dissector = http.response.next_dissector end end return http end }
module("http", package.seeall) local function str(char) return string.char(char) end local function getchar(stream) local char while true do char = stream:getchar() if char == -1 then coroutine.yield() else break end end return char end local function read_line(stream) local line = "" local char, c local read = 0 while true do c = getchar(stream) read = read+1 char = str(c) if c == 0xd then c = getchar(stream) read = read+1 if c == 0xa then return line, read else line = line .. char char = str(c) end elseif c == 0xa then return line, read end line = line .. char end end -- The comparison is broken in Lua 5.1, so we need to reimplement the -- string comparison local function string_compare(a, b) if type(a) == "string" and type(b) == "string" then local i = 1 local sa = #a local sb = #b while true do if i > sa then return false elseif i > sb then return true end if a:byte(i) < b:byte(i) then return true elseif a:byte(i) > b:byte(i) then return false end i = i+1 end return false else return a < b end end function sorted_pairs(t) local a = {} for n in pairs(t) do table.insert(a, n) end table.sort(a, string_compare) local i = 0 local iter = function () -- iterator function i = i + 1 if a[i] == nil then return nil else return a[i], t[a[i]] end end return iter end local function dump(t, indent) for n, v in sorted_pairs(t) do if type(v) == "table" then print(indent, n) dump(v, indent .. " ") elseif type(v) ~= "thread" and type(v) ~= "userdata" and type(v) ~= "function" then print(indent, n, "=", v) end end end local function parse_header(stream, http) local total_len = 0 http.headers = {} http._headers_order = {} line, len = read_line(stream) total_len = total_len + len while #line > 0 do local name, value = line:match("([^%s]+):%s*(.+)") if not name then http._invalid = string.format("invalid header '%s'", line) return end http.headers[name] = value table.insert(http._headers_order, name) line, len = read_line(stream) total_len = total_len + len end return total_len end local function parse_request(stream, http) local len, total_len local line, len = read_line(stream) total_len = len http.method, http.uri, http.version = line:match("([^%s]+) ([^%s]+) (.+)") if not http.method then http._invalid = string.format("invalid request '%s'", line) return end total_len = total_len + parse_header(stream, http) http.data = stream http._length = total_len http.dump = function (self) dump(self, "") end return true end local function parse_response(stream, http) local len, total_len local line, len = read_line(stream) total_len = len http.version, http.status, http.reason = line:match("([^%s]+) ([^%s]+) (.+)") if not http.version then http._invalid = string.format("invalid response '%s'", line) return end total_len = total_len + parse_header(stream, http) http.data = stream http._length = total_len http.dump = function (self) dump(self, "") end return true end local function build_headers(stream, headers, headers_order) local copy = headers for _, name in pairs(headers_order) do local value = copy[name] if value then copy[name] = nil stream:insert(name) stream:insert(": ") stream:insert(value) stream:insert("\r\n") end end for name, value in pairs(copy) do if value then stream:insert(name) stream:insert(": ") stream:insert(value) stream:insert("\r\n") end end end local function forge(http) local tcp = http._tcp_stream if tcp then if http._state == 2 and tcp.direction then http._state = 3 tcp.stream:seek(http.request._mark, true) http.request._mark = nil tcp.stream:erase(http.request._length) tcp.stream:insert(http.request.method) tcp.stream:insert(" ") tcp.stream:insert(http.request.uri) tcp.stream:insert(" ") tcp.stream:insert(http.request.version) tcp.stream:insert("\r\n") build_headers(tcp.stream, http.request.headers, http.request._headers_order) tcp.stream:insert("\r\n") elseif http._state == 5 and not tcp.direction then http._state = 0 tcp.stream:seek(http.response._mark, true) http.response._mark = nil tcp.stream:erase(http.response._length) tcp.stream:insert(http.response.version) tcp.stream:insert(" ") tcp.stream:insert(http.response.status) tcp.stream:insert(" ") tcp.stream:insert(http.response.reason) tcp.stream:insert("\r\n") build_headers(tcp.stream, http.response.headers, http.response._headers_order) tcp.stream:insert("\r\n") end http._tcp_stream = nil end return tcp end local function parse(http, context, f, name, next_state) if not context._co then context._mark = http._tcp_stream.stream:mark() context._co = coroutine.create(function () f(http._tcp_stream.stream, context) end) end coroutine.resume(context._co) if coroutine.status(context._co) == "dead" then if not context._invalid then http._state = next_state if haka.rule_hook("http-".. name, http) then return nil end context.next_dissector = http.next_dissector else haka.log.error("http", context._invalid) http._tcp_stream:drop() return nil end end end haka.dissector { name = "http", dissect = function (stream) if not stream.connection.data._http then local http = {} http.dissector = "http" http.next_dissector = nil http.valid = function (self) return self._tcp_stream:valid() end http.drop = function (self) return self._tcp_stream:drop() end http.forge = forge http._state = 0 stream.connection.data._http = http end local http = stream.connection.data._http http._tcp_stream = stream if stream.direction then if http._state == 0 or http._state == 1 then if stream.stream:available() > 0 then if http._state == 0 then http.request = {} http.response = nil http._state = 1 end parse(http, http.request, parse_request, "request", 2) end elseif http.request then http.next_dissector = http.request.next_dissector end else if http._state == 3 or http._state == 4 then if stream.stream:available() > 0 then if http._state == 3 then http.response = {} http._state = 4 end parse(http, http.response, parse_response, "response", 5) end elseif http.response then http.next_dissector = http.response.next_dissector end end return http end }
Fix Lua string comparison operator
Fix Lua string comparison operator The operator is different between Lua 5.1 and LuaJit.
Lua
mpl-2.0
haka-security/haka,Wingless-Archangel/haka,lcheylus/haka,lcheylus/haka,LubyRuffy/haka,nabilbendafi/haka,Wingless-Archangel/haka,haka-security/haka,lcheylus/haka,nabilbendafi/haka,LubyRuffy/haka,haka-security/haka,nabilbendafi/haka
fc82cc7cd9ba249084575c946174ab2772edb12b
Modules/qSystems/DataTypes/qColor3.lua
Modules/qSystems/DataTypes/qColor3.lua
local ReplicatedStorage = game:GetService("ReplicatedStorage") local HttpService = game:GetService("HttpService") local NevermoreEngine = require(ReplicatedStorage:WaitForChild("NevermoreEngine")) local LoadCustomLibrary = NevermoreEngine.LoadLibrary local qSystems = LoadCustomLibrary("qSystems") local qString = LoadCustomLibrary("qString") local qMath = LoadCustomLibrary("qMath") local Easing = LoadCustomLibrary("Easing") local Round = qSystems.Round local RbxUtility = LoadLibrary("RbxUtility") local lib = {} --- Manipulation and seralization of Color3 Values -- @author Quenty -- Last modified September 6th, 2014 local function EncodeColor3(Color3) --- Encodes a Color3 in JSON -- @param Color3 The Color3 to encode -- @return String The string representation in JSON of the Color3 value. local NewData = { Color3.r; Color3.g; Color3.b; } return HttpService:JSONEncode(NewData) end lib.EncodeColor3 = EncodeColor3 lib.encodeColor3 = EncodeColor3 lib.Encode = EncodeColor3 lib.encode = EncodeColor3 local function DecodeColor3(Data) --- decode's a previously encoded Color3. -- @param Data String of JSON, that was encoded. -- @return Color3 if it could be decoded, otherwise, nil if Data then local DecodedData = HttpService:JSONDecode(Data) --RbxUtility.DecodeJSON(Data) if DecodedData then return Color3.new(unpack(DecodedData)) else return nil end else return nil end end lib.DecodeColor3 = DecodeColor3 lib.decodeColor3 = DecodeColor3 lib.Decode = DecodeColor3 lib.decode = DecodeColor3 local LerpNumber = qMath.LerpNumber local function LerpColor3(ColorOne, ColorTwo, Alpha) --- Interpolates between two color3 values. -- @param ColorOne The first Color -- @param ColorTwo The second color -- @param Alpha The amount to interpolate between -- @return The resultent Color3 value. return Color3.new(LerpNumber(ColorOne.r, ColorTwo.r, Alpha), LerpNumber(ColorOne.g, ColorTwo.g, Alpha), LerpNumber(ColorOne.b, ColorTwo.b, Alpha)) end lib.LerpColor3 = LerpColor3 lib.lerpColor3 = LerpColor3 -- Code from Anaminus -- -- http://asset-markotaris.rhcloud.com/45860975 local function Color3ToByte(ColorOne) return Round(ColorOne.r*255), Round(ColorOne.g*255), Round(ColorOne.b*255) end lib.Color3ToByte = Color3ToByte local function RGBtoHSL(R,G,B) -- Converts an RGB color from RGB to HSL (Hue, Saturation, Luminance) -- @param R number [0, 1], the red value -- @param G number [0, 1], the green value -- @param B number [0, 1], the blue value local Min,Max = math.min(R,G,B), math.max(R,G,B) local dMax = Max - Min local H,S,L = 0,0,(Max + Min)/2 if dMax ~= 0 then if L < 0.5 then S = dMax/(Max + Min) else S = dMax/(2 - Max - Min) end local dR = (((Max-R)/6)+(dMax/2))/dMax local dG = (((Max-G)/6)+(dMax/2))/dMax local dB = (((Max-B)/6)+(dMax/2))/dMax if R == Max then H = dB - dG elseif G == Max then H = (1/3)+dR-dB elseif B == Max then H = (2/3)+dG-dR end if H < 0 then H = H+1 end if H > 1 then H = H-1 end end return H,S,L end lib.RGBtoHSL = RGBtoHSL local function Color3ToHSL3(Color) -- @return A Color3 version, but in HSL (numbers range) [0, 1] return Color3.new(RGBtoHSL(Color.r, Color.g, Color.b)) end lib.Color3ToHSL3 = Color3ToHSL3 local function Color3ToHSL(Color) -- @return A Color3 version, but in HSL (numbers range) [0, 1] return RGBtoHSL(Color.r, Color.g, Color.b) end lib.Color3ToHSL = Color3ToHSL local function HueToRGB(v1,v2,vH) if vH < 0 then vH = vH + 1 end if vH > 1 then vH = vH - 1 end if 6*vH < 1 then return v1+(v2-v1)*6*vH end if 2*vH < 1 then return v2 end if 3*vH < 2 then return v1+(v2-v1)*((2/3)-vH)*6 end return v1 end lib.HueToRGB = HueToRGB local function HSLtoRGB(H,S,L) --- Converts HSL to Color3 local R,G,B if S == 0 then return L,L,L else local v2 = L < 0.5 and L*(1+S) or (L+S)-(S*L) local v1 = 2*L-v2 return HueToRGB(v1,v2,H+(1/3)), HueToRGB(v1,v2,H), HueToRGB(v1,v2,H-(1/3)) end end lib.HSLtoRGB = HSLtoRGB local function HSL3toColor3(ColorHSL) -- @return A Color3 version of the HSL return Color3.new(HSLtoRGB(ColorHSL.r, ColorHSL.g, ColorHSL.b)) end lib.HSL3toColor3 = HSL3toColor3 -- written by Quenty local function SetSaturation(Color, Saturation) -- @param Color The color to desaturate -- @param Saturation A number from 0 to 1 of how saturated it should be. 0 will be complete desaturation. local H, S, L = Color3ToHSL(Color) return Color3.new(HSLtoRGB(H, Saturation, L)) end lib.SetSaturation = SetSaturation local function SetLuminance(Color, Luminance) -- @param Color The color to set brightness -- @param [Luminance] A number from 0 to 1 of how bright it should be. 0 will be complete dark. local H, S, L = Color3ToHSL(Color) return Color3.new(HSLtoRGB(H, S, Luminance)) end lib.SetLuminance = SetLuminance local function AdjustColorTowardsWhite(Color) --- We'll use this to try to make text more readable. Mess with saturation and Luminance, while keeping hue -- @param CloseToWhite [0, 1] 1 is the closest to white, I think? local H, S, L = Color3ToHSL(Color) local LightningFactor = 0.75-- The LightningFactor determines how bright it is. 1 = white, 0 = no change. local Difference = 1 - L L = L + Difference * (1-S) * LightningFactor -- We're only lighting desaturated stuff... -- Problem: Darker colors are hard to see. L indicates darkness. So we'll modify L based upon saturation (that is, how much color). -- We'll then desaturate bright colors, but we want to saturate nonsaturated ones. And... black has to stay saturation 0. --S = S * 0.8 S = Easing.inOutCubic(S, 0, 1, 0.8) -- Uh... I... ok. this will do. return Color3.new(HSLtoRGB(H, S, L)) end lib.AdjustColorTowardsWhite = AdjustColorTowardsWhite local function SetSaturationAndLuminance(Color, Saturation, Luminance) local H, S, L = Color3ToHSL(Color) return Color3.new(HSLtoRGB(H, Saturation, Luminance)) end lib.SetSaturationAndLuminance = SetSaturationAndLuminance return lib
local ReplicatedStorage = game:GetService("ReplicatedStorage") local HttpService = game:GetService("HttpService") local NevermoreEngine = require(ReplicatedStorage:WaitForChild("NevermoreEngine")) local LoadCustomLibrary = NevermoreEngine.LoadLibrary local qSystems = LoadCustomLibrary("qSystems") local qString = LoadCustomLibrary("qString") local qMath = LoadCustomLibrary("qMath") local Easing = LoadCustomLibrary("Easing") local Round = qSystems.Round local RbxUtility = LoadLibrary("RbxUtility") local lib = {} --- Manipulation and seralization of Color3 Values -- @author Quenty -- Last modified September 6th, 2014 local function EncodeColor3(Color3) --- Encodes a Color3 in JSON -- @param Color3 The Color3 to encode -- @return String The string representation in JSON of the Color3 value. local NewData = { Color3.r; Color3.g; Color3.b; } return HttpService:JSONEncode(NewData) end lib.EncodeColor3 = EncodeColor3 lib.encodeColor3 = EncodeColor3 lib.Encode = EncodeColor3 lib.encode = EncodeColor3 local function DecodeColor3(Data) --- decode's a previously encoded Color3. -- @param Data String of JSON, that was encoded. -- @return Color3 if it could be decoded, otherwise, nil if Data then local DecodedData = HttpService:JSONDecode(Data) --RbxUtility.DecodeJSON(Data) if DecodedData then return Color3.new(unpack(DecodedData)) else return nil end else return nil end end lib.DecodeColor3 = DecodeColor3 lib.decodeColor3 = DecodeColor3 lib.Decode = DecodeColor3 lib.decode = DecodeColor3 local LerpNumber = qMath.LerpNumber local function LerpColor3(ColorOne, ColorTwo, Alpha) --- Interpolates between two color3 values. -- @param ColorOne The first Color -- @param ColorTwo The second color -- @param Alpha The amount to interpolate between -- @return The resultent Color3 value. return Color3.new(LerpNumber(ColorOne.r, ColorTwo.r, Alpha), LerpNumber(ColorOne.g, ColorTwo.g, Alpha), LerpNumber(ColorOne.b, ColorTwo.b, Alpha)) end lib.LerpColor3 = LerpColor3 lib.lerpColor3 = LerpColor3 local function LerpColor3HSL(ColorOne, ColorTwo, Alpha) --- Interpolates between two color3 values using HSL. -- @param ColorOne The first Color -- @param ColorTwo The second color -- @param Alpha The amount to interpolate between -- @return The resultent Color3 value. local H1, S1, L1 = lib.RGBtoHSL(ColorOne.r, ColorOne.g, ColorOne.b) local H2, S2, L2 = lib.RGBtoHSL(ColorTwo.r, ColorTwo.g, ColorTwo.b) return Color3.new(lib.HSLtoRGB(LerpNumber(H1, H2, Alpha), LerpNumber(S1, S2, Alpha), LerpNumber(L1, L2, Alpha))) end lib.LerpColor3HSL = LerpColor3HSL -- Code from Anaminus -- -- http://asset-markotaris.rhcloud.com/45860975 local function Color3ToByte(ColorOne) return Round(ColorOne.r*255), Round(ColorOne.g*255), Round(ColorOne.b*255) end lib.Color3ToByte = Color3ToByte local function RGBtoHSL(R,G,B) -- Converts an RGB color from RGB to HSL (Hue, Saturation, Luminance) -- @param R number [0, 1], the red value -- @param G number [0, 1], the green value -- @param B number [0, 1], the blue value local Min,Max = math.min(R,G,B), math.max(R,G,B) local dMax = Max - Min local H,S,L = 0,0,(Max + Min)/2 if dMax ~= 0 then if L < 0.5 then S = dMax/(Max + Min) else S = dMax/(2 - Max - Min) end local dR = (((Max-R)/6)+(dMax/2))/dMax local dG = (((Max-G)/6)+(dMax/2))/dMax local dB = (((Max-B)/6)+(dMax/2))/dMax if R == Max then H = dB - dG elseif G == Max then H = (1/3)+dR-dB elseif B == Max then H = (2/3)+dG-dR end if H < 0 then H = H+1 end if H > 1 then H = H-1 end end return H,S,L end lib.RGBtoHSL = RGBtoHSL local function Color3ToHSL3(Color) -- @return A Color3 version, but in HSL (numbers range) [0, 1] return Color3.new(RGBtoHSL(Color.r, Color.g, Color.b)) end lib.Color3ToHSL3 = Color3ToHSL3 local function Color3ToHSL(Color) -- @return A Color3 version, but in HSL (numbers range) [0, 1] return RGBtoHSL(Color.r, Color.g, Color.b) end lib.Color3ToHSL = Color3ToHSL local function HueToRGB(v1,v2,vH) if vH < 0 then vH = vH + 1 end if vH > 1 then vH = vH - 1 end if 6*vH < 1 then return v1+(v2-v1)*6*vH end if 2*vH < 1 then return v2 end if 3*vH < 2 then return v1+(v2-v1)*((2/3)-vH)*6 end return v1 end lib.HueToRGB = HueToRGB local function HSLtoRGB(H,S,L) --- Converts HSL to Color3 local R,G,B if S == 0 then return L,L,L else local v2 = L < 0.5 and L*(1+S) or (L+S)-(S*L) local v1 = 2*L-v2 return HueToRGB(v1,v2,H+(1/3)), HueToRGB(v1,v2,H), HueToRGB(v1,v2,H-(1/3)) end end lib.HSLtoRGB = HSLtoRGB local function HSL3toColor3(ColorHSL) -- @return A Color3 version of the HSL return Color3.new(HSLtoRGB(ColorHSL.r, ColorHSL.g, ColorHSL.b)) end lib.HSL3toColor3 = HSL3toColor3 -- written by Quenty local function SetSaturation(Color, Saturation) -- @param Color The color to desaturate -- @param Saturation A number from 0 to 1 of how saturated it should be. 0 will be complete desaturation. local H, S, L = Color3ToHSL(Color) return Color3.new(HSLtoRGB(H, Saturation, L)) end lib.SetSaturation = SetSaturation local function SetLuminance(Color, Luminance) -- @param Color The color to set brightness -- @param [Luminance] A number from 0 to 1 of how bright it should be. 0 will be complete dark. local H, S, L = Color3ToHSL(Color) return Color3.new(HSLtoRGB(H, S, Luminance)) end lib.SetLuminance = SetLuminance local function SetHue(Color, Hue) -- @param Color The color to set hue -- @param [Hue] A number from 0 to 1 of what hue it should be local H, S, L = Color3ToHSL(Color) return Color3.new(HSLtoRGB(H, S, Hue)) end lib.SetHue = SetHue local function AdjustColorTowardsWhite(Color) --- We'll use this to try to make text more readable. Mess with saturation and Luminance, while keeping hue -- @param CloseToWhite [0, 1] 1 is the closest to white, I think? local H, S, L = Color3ToHSL(Color) local LightningFactor = 0.75-- The LightningFactor determines how bright it is. 1 = white, 0 = no change. local Difference = 1 - L L = L + Difference * (1-S) * LightningFactor -- We're only lighting desaturated stuff... -- Problem: Darker colors are hard to see. L indicates darkness. So we'll modify L based upon saturation (that is, how much color). -- We'll then desaturate bright colors, but we want to saturate nonsaturated ones. And... black has to stay saturation 0. --S = S * 0.8 S = Easing.inOutCubic(S, 0, 1, 0.8) -- Uh... I... ok. this will do. return Color3.new(HSLtoRGB(H, S, L)) end lib.AdjustColorTowardsWhite = AdjustColorTowardsWhite local function SetSaturationAndLuminance(Color, Saturation, Luminance) local H, S, L = Color3ToHSL(Color) return Color3.new(HSLtoRGB(H, Saturation, Luminance)) end lib.SetSaturationAndLuminance = SetSaturationAndLuminance return lib
Reprogrammed RotatingCharacter to fix memory / thread leak
Reprogrammed RotatingCharacter to fix memory / thread leak
Lua
mit
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
18d5b00bd28c5504ae5816d5759a2b5464630692
packages/counters.lua
packages/counters.lua
if not SILE.scratch.counters then SILE.scratch.counters = {} end romans = { {1000, "M"}, {900, "CM"}, {500, "D"}, {400, "CD"}, {100, "C"}, {90, "XC"}, {50, "L"}, {40, "XL"}, {10, "X"}, {9, "IX"}, {5, "V"}, {4, "IV"}, {1, "I"} } local function romanize(k) str = "" k = k + 0 for _, v in ipairs(romans) do val, let = unpack(v) while k >= val do k = k - val str = str..let end end return str end local function alpha(n) local out = "" local a = string.byte("a") repeat n = n - 1 out = string.char(n%26 + a) .. out n = (n - n%26)/26 until n < 1 return out end local icu pcall( function () icu = require("justenoughicu") end) SILE.formatCounter = function(counter) -- If there is a language-specific formatter, use that. local lang = SILE.settings.get("document.language") if SILE.languageSupport.languages[lang] and SILE.languageSupport.languages[lang].counter then local res = SILE.languageSupport.languages[lang].counter(counter) if res then return res end -- allow them to pass. end -- If we have ICU, try that if icu then local display = counter.display -- Translate numbering style names which are different in ICU if display == "roman" then display = "romanlow" elseif display == "Roman" then display = "roman" end local ok, res = pcall(function() return icu.format_number(counter.value, display) end) if ok then return res end end if (counter.display == "roman") then return romanize(counter.value):lower() end if (counter.display == "Roman") then return romanize(counter.value) end if (counter.display == "alpha") then return alpha(counter.value) end return tostring(counter.value) end local function getCounter(id) local counter = SILE.scratch.counters[id] if not counter then counter = {} SILE.scratch.counters[id] = { value= 0, display= "arabic", format = SILE.formatCounter } end return counter end SILE.registerCommand("increment-counter", function (options, _) local counter = getCounter(options.id) if (options["set-to"]) then counter.value = tonumber(options["set-to"]) else counter.value = counter.value + 1 end if options.display then counter.display = options.display end end, "Increments the counter named by the <id> option") SILE.registerCommand("set-counter", function (options, _) local counter = getCounter(options.id) if options.value then counter.value = tonumber(options.value) end if options.display then counter.display = options.display end end, "Sets the counter named by the <id> option to <value>; sets its display type (roman/Roman/arabic) to type <display>.") SILE.registerCommand("show-counter", function (options, _) local counter = getCounter(options.id) if options.display then counter.display = options.display end SILE.typesetter:setpar(SILE.formatCounter(counter)) end, "Outputs the value of counter <id>, optionally displaying it with the <display> format.") SILE.formatMultilevelCounter = function(counter, options) local maxlevel = options and options.level or #counter.value local minlevel = options and options.minlevel or 1 local out = {} for x = minlevel, maxlevel do out[x - minlevel + 1] = SILE.formatCounter({ display = counter.display[x], value = counter.value[x] }) end return table.concat( out, "." ) end local function getMultilevelCounter(id) local counter = SILE.scratch.counters[id] if not counter then counter = { value= {0}, display= {"arabic"}, format = SILE.formatMultilevelCounter } SILE.scratch.counters[id] = counter end return counter end SILE.registerCommand("increment-multilevel-counter", function (options, _) local counter = getMultilevelCounter(options.id) local currentLevel = #counter.value local level = tonumber(options.level) or currentLevel if level == currentLevel then counter.value[level] = counter.value[level] + 1 elseif level > currentLevel then while level > currentLevel do currentLevel = currentLevel + 1 counter.value[currentLevel] = (options.reset == false) and counter.value[currentLevel -1 ] or 1 counter.display[currentLevel] = counter.display[currentLevel - 1] end else -- level < currentLevel counter.value[level] = counter.value[level] + 1 while currentLevel > level do if not (options.reset == false) then counter.value[currentLevel] = nil end counter.display[currentLevel] = nil currentLevel = currentLevel - 1 end end if options.display then counter.display[currentLevel] = options.display end end) SILE.registerCommand("show-multilevel-counter", function (options, _) local counter = getMultilevelCounter(options.id) if options.display then counter.display[#counter.value] = options.display end SILE.typesetter:typeset(SILE.formatMultilevelCounter(counter, options)) end, "Outputs the value of the multilevel counter <id>, optionally displaying it with the <display> format.") return { exports = { getCounter = getCounter, getMultilevelCounter = getMultilevelCounter }, documentation = [[\begin{document} Various parts of SILE such as the \code{footnotes} package and the sectioning commands keep a counter of things going on: the current footnote number, the chapter number, and so on. The counters package allows you to set up, increment and typeset named counters. It provides the following commands: • \code{\\set-counter[id=\em{<counter-name>},value=\em{<value}]} — sets the counter called \code{<counter-name>} to the value given. • \code{\\increment-counter[id=\em{<counter-name>}]} — does the same as \code{\\set-counter} except that when no \code{value} parameter is given, the counter is incremented by one. • \code{\\show-counter[id=\em{<counter-name>}]} — this typesets the value of the counter according to the counter’s declared display type. \note{All of the commands in the counters package take an optional \code{display=\em{<display-type>}} parameter to set the \em{display type} of the counter. The available built-in display types are: \code{arabic}, the default; \code{alpha}, for alphabetic counting; \code{roman}, for lower-case Roman numerals; and \code{Roman} for upper-case Roman numerals. The ICU library also provides ways of formatting numbers in global (non-Latin) scripts. You can use any of the display types in this list: \url{http://www.unicode.org/repos/cldr/tags/latest/common/bcp47/number.xml}. For example, \code{display=beng} will format your numbers in Bengali digits. } So, for example, the following SILE code: \begin{verbatim} \line \\set-counter[id=mycounter, value=2] \\show-counter[id=mycounter] \\increment-counter[id=mycounter] \\show-counter[id=mycounter, display=roman] \line \end{verbatim} produces: \line \examplefont{2 \noindent{}iii} \line \end{document}]] }
if not SILE.scratch.counters then SILE.scratch.counters = {} end romans = { {1000, "M"}, {900, "CM"}, {500, "D"}, {400, "CD"}, {100, "C"}, {90, "XC"}, {50, "L"}, {40, "XL"}, {10, "X"}, {9, "IX"}, {5, "V"}, {4, "IV"}, {1, "I"} } local function romanize(k) str = "" k = k + 0 for _, v in ipairs(romans) do val, let = unpack(v) while k >= val do k = k - val str = str..let end end return str end local function alpha(n) local out = "" local a = string.byte("a") repeat n = n - 1 out = string.char(n%26 + a) .. out n = (n - n%26)/26 until n < 1 return out end local icu pcall( function () icu = require("justenoughicu") end) SILE.formatCounter = function(counter) -- If there is a language-specific formatter, use that. local lang = SILE.settings.get("document.language") if SILE.languageSupport.languages[lang] and SILE.languageSupport.languages[lang].counter then local res = SILE.languageSupport.languages[lang].counter(counter) if res then return res end -- allow them to pass. end -- If we have ICU, try that if icu then local display = counter.display -- Translate numbering style names which are different in ICU if display == "roman" then display = "romanlow" elseif display == "Roman" then display = "roman" end local ok, res = pcall(function() return icu.format_number(counter.value, display) end) if ok then return res end end if (counter.display == "roman") then return romanize(counter.value):lower() end if (counter.display == "Roman") then return romanize(counter.value) end if (counter.display == "alpha") then return alpha(counter.value) end return tostring(counter.value) end local function getCounter(id) if not SILE.scratch.counters[id] then SILE.scratch.counters[id] = { value = 0, display = "arabic", format = SILE.formatCounter } end return SILE.scratch.counters[id] end SILE.registerCommand("increment-counter", function (options, content) local counter = getCounter(options.id) if (options["set-to"]) then counter.value = tonumber(options["set-to"]) else counter.value = counter.value + 1 end if options.display then counter.display = options.display end end, "Increments the counter named by the <id> option") SILE.registerCommand("set-counter", function (options, content) local counter = getCounter(options.id) if options.value then counter.value = tonumber(options.value) end if options.display then counter.display = options.display end end, "Sets the counter named by the <id> option to <value>; sets its display type (roman/Roman/arabic) to type <display>.") SILE.registerCommand("show-counter", function (options, content) local counter = getCounter(options.id) if options.display then counter.display = options.display end SILE.typesetter:setpar(SILE.formatCounter(counter)) end, "Outputs the value of counter <id>, optionally displaying it with the <display> format.") SILE.formatMultilevelCounter = function(counter, options) local maxlevel = options and options.level or #counter.value local minlevel = options and options.minlevel or 1 local out = {} for x = minlevel, maxlevel do out[x - minlevel + 1] = SILE.formatCounter({ display = counter.display[x], value = counter.value[x] }) end return table.concat( out, "." ) end local function getMultilevelCounter(id) local counter = SILE.scratch.counters[id] if not counter then counter = { value= {0}, display= {"arabic"}, format = SILE.formatMultilevelCounter } SILE.scratch.counters[id] = counter end return counter end SILE.registerCommand("increment-multilevel-counter", function (options, content) local counter = getMultilevelCounter(options.id) local currentLevel = #counter.value local level = tonumber(options.level) or currentLevel if level == currentLevel then counter.value[level] = counter.value[level] + 1 elseif level > currentLevel then while level > currentLevel do currentLevel = currentLevel + 1 counter.value[currentLevel] = (options.reset == false) and counter.value[currentLevel -1 ] or 1 counter.display[currentLevel] = counter.display[currentLevel - 1] end else -- level < currentLevel counter.value[level] = counter.value[level] + 1 while currentLevel > level do if not (options.reset == false) then counter.value[currentLevel] = nil end counter.display[currentLevel] = nil currentLevel = currentLevel - 1 end end if options.display then counter.display[currentLevel] = options.display end end) SILE.registerCommand("show-multilevel-counter", function (options, content) local counter = getMultilevelCounter(options.id) if options.display then counter.display[#counter.value] = options.display end SILE.typesetter:typeset(SILE.formatMultilevelCounter(counter, options)) end, "Outputs the value of the multilevel counter <id>, optionally displaying it with the <display> format.") return { exports = { getCounter = getCounter, getMultilevelCounter = getMultilevelCounter }, documentation = [[\begin{document} Various parts of SILE such as the \code{footnotes} package and the sectioning commands keep a counter of things going on: the current footnote number, the chapter number, and so on. The counters package allows you to set up, increment and typeset named counters. It provides the following commands: • \code{\\set-counter[id=\em{<counter-name>},value=\em{<value}]} — sets the counter called \code{<counter-name>} to the value given. • \code{\\increment-counter[id=\em{<counter-name>}]} — does the same as \code{\\set-counter} except that when no \code{value} parameter is given, the counter is incremented by one. • \code{\\show-counter[id=\em{<counter-name>}]} — this typesets the value of the counter according to the counter’s declared display type. \note{All of the commands in the counters package take an optional \code{display=\em{<display-type>}} parameter to set the \em{display type} of the counter. The available built-in display types are: \code{arabic}, the default; \code{alpha}, for alphabetic counting; \code{roman}, for lower-case Roman numerals; and \code{Roman} for upper-case Roman numerals. The ICU library also provides ways of formatting numbers in global (non-Latin) scripts. You can use any of the display types in this list: \url{http://www.unicode.org/repos/cldr/tags/latest/common/bcp47/number.xml}. For example, \code{display=beng} will format your numbers in Bengali digits. } So, for example, the following SILE code: \begin{verbatim} \line \\set-counter[id=mycounter, value=2] \\show-counter[id=mycounter] \\increment-counter[id=mycounter] \\show-counter[id=mycounter, display=roman] \line \end{verbatim} produces: \line \examplefont{2 \noindent{}iii} \line \end{document}]] }
fix(counters): Restore variable passing to refactored counter code
fix(counters): Restore variable passing to refactored counter code
Lua
mit
simoncozens/sile,alerque/sile,alerque/sile,alerque/sile,simoncozens/sile,simoncozens/sile,simoncozens/sile,alerque/sile
c2c2fd08bf1a7b9a7325c4081727cf2225097feb
plugins/database.lua
plugins/database.lua
local function callback_group_database(extra, success, result) local database = extra.database local chat_id = result.peer_id -- save group info if database["groups"][tostring(chat_id)] then database["groups"][tostring(chat_id)] = { print_name = result.print_name:gsub("_"," "), lang = get_lang(result.peer_id), old_print_names = database["groups"][tostring(chat_id)].old_print_names .. ' ### ' .. result.print_name:gsub("_"," "), long_id = result.id } else database["groups"][tostring(chat_id)] = { print_name = result.print_name:gsub("_"," "), lang = get_lang(result.peer_id), old_print_names = result.print_name:gsub("_"," "), long_id = result.id } end -- save users info for k, v in pairs(result.members) do if database["users"][tostring(v.peer_id)] then if not database["users"][tostring(v.peer_id)].groups[tostring(chat_id)] then database["users"][tostring(v.peer_id)].groups[tostring(chat_id)] = tonumber(chat_id) end database["users"][tostring(v.peer_id)] = { print_name = v.print_name:gsub("_"," "), username = v.username or 'NOUSER', old_print_names = database["users"][tostring(v.peer_id)].old_print_names .. ' ### ' .. v.print_name:gsub("_"," "), old_usernames = database["users"][tostring(v.peer_id)].old_usernames .. ' ### ' ..(v.username or 'NOUSER'), long_id = v.id } else database["users"][tostring(v.peer_id)] = { print_name = v.print_name:gsub("_"," "), username = v.username or 'NOUSER', old_print_names = v.print_name:gsub("_"," "), old_usernames = v.username or 'NOUSER', long_id = v.id } database["users"][tostring(v.peer_id)].groups = { } database["users"][tostring(v.peer_id)].groups[tostring(chat_id)] = tonumber(chat_id) end end save_data(_config.database.db, database) send_large_msg(extra.receiver, langs[get_lang(result.peer_id)].dataLeaked) end local function callback_supergroup_database(extra, success, result) local database = extra.database local chat_id = string.match(extra.receiver, '%d+') -- save supergroup info if database["groups"][tostring(chat_id)] then database["groups"][tostring(chat_id)] = { print_name = extra.print_name:gsub("_"," "), username = extra.username or 'NOUSER', lang = get_lang(string.match(extra.receiver,'%d+')), old_print_names = database["groups"][tostring(chat_id)].old_print_names .. ' ### ' .. extra.print_name:gsub("_"," "), old_usernames = database["groups"][tostring(chat_id)].old_usernames .. ' ### ' ..(extra.username or 'NOUSER'), long_id = extra.id } else database["groups"][tostring(chat_id)] = { print_name = extra.print_name:gsub("_"," "), username = extra.username or 'NOUSER', lang = get_lang(string.match(extra.receiver,'%d+')), old_print_names = extra.print_name:gsub("_"," "), old_usernames = extra.username or 'NOUSER', long_id = extra.id } end -- save users info for k, v in pairsByKeys(result) do if database["users"][tostring(v.peer_id)] then if not database["users"][tostring(v.peer_id)].groups[tostring(chat_id)] then database["users"][tostring(v.peer_id)].groups[tostring(chat_id)] = tonumber(chat_id) end database["users"][tostring(v.peer_id)] = { print_name = v.print_name:gsub("_"," "), username = v.username or 'NOUSER', old_print_names = database["users"][tostring(v.peer_id)].old_print_names .. ' ### ' .. v.print_name:gsub("_"," "), old_usernames = database["users"][tostring(v.peer_id)].old_usernames .. ' ### ' ..(v.username or 'NOUSER'), long_id = v.id } else database["users"][tostring(v.peer_id)] = { print_name = v.print_name:gsub("_"," "), username = v.username or 'NOUSER', old_print_names = v.print_name:gsub("_"," "), old_usernames = v.username or 'NOUSER', long_id = v.id } database["users"][tostring(v.peer_id)].groups = { } database["users"][tostring(v.peer_id)].groups[tostring(chat_id)] = tonumber(chat_id) end end save_data(_config.database.db, database) send_large_msg(extra.receiver, langs[get_lang(string.match(extra.receiver, '%d+'))].dataLeaked) end local function run(msg, matches) if is_sudo(msg) then if matches[1]:lower() == 'createdatabase' then local f = io.open(_config.database.db, 'w+') f:write('{"groups":{},"users":{}}') f:close() reply_msg(msg.id, langs[msg.lang].dbCreated, ok_cb, false) return end local database = load_data(_config.database.db) if matches[1]:lower() == 'database' or matches[1]:lower() == 'sasha database' then local receiver = get_receiver(msg) if msg.to.type == 'channel' then channel_get_users(receiver, callback_supergroup_database, { receiver = receiver, database = database, print_name = msg.to.print_name, username = (msg.to.username or nil), id = msg.to.peer_id }) elseif msg.to.type == 'chat' then chat_info(receiver, callback_group_database, { receiver = receiver, database = database }) else return end end else return langs[msg.lang].require_sudo end end return { description = "DATABASE", patterns = { "^[#!/]([Cc][Rr][Ee][Aa][Tt][Ee][Dd][Aa][Tt][Aa][Bb][Aa][Ss][Ee])$", "^[#!/]([Dd][Aa][Tt][Aa][Bb][Aa][Ss][Ee])$", -- database "^([Ss][Aa][Ss][Hh][Aa] [Dd][Aa][Tt][Aa][Bb][Aa][Ss][Ee])$", }, run = run, min_rank = 5 -- usage -- SUDO -- #createdatabase -- (#database|[sasha] database) }
local function callback_group_database(extra, success, result) local database = extra.database local chat_id = result.peer_id -- save group info if database["groups"][tostring(chat_id)] then database["groups"][tostring(chat_id)] = { print_name = result.print_name:gsub("_"," "), lang = get_lang(result.peer_id), old_print_names = database["groups"][tostring(chat_id)].old_print_names .. ' ### ' .. result.print_name:gsub("_"," "), long_id = result.id } else database["groups"][tostring(chat_id)] = { print_name = result.print_name:gsub("_"," "), lang = get_lang(result.peer_id), old_print_names = result.print_name:gsub("_"," "), long_id = result.id } end -- save users info for k, v in pairs(result.members) do if database["users"][tostring(v.peer_id)] then if not database["users"][tostring(v.peer_id)].groups then database["users"][tostring(v.peer_id)].groups = { } end if not database["users"][tostring(v.peer_id)].groups[tostring(chat_id)] then database["users"][tostring(v.peer_id)].groups[tostring(chat_id)] = tonumber(chat_id) end database["users"][tostring(v.peer_id)] = { print_name = v.print_name:gsub("_"," "), username = v.username or 'NOUSER', old_print_names = database["users"][tostring(v.peer_id)].old_print_names .. ' ### ' .. v.print_name:gsub("_"," "), old_usernames = database["users"][tostring(v.peer_id)].old_usernames .. ' ### ' ..(v.username or 'NOUSER'), long_id = v.id } else database["users"][tostring(v.peer_id)] = { print_name = v.print_name:gsub("_"," "), username = v.username or 'NOUSER', old_print_names = v.print_name:gsub("_"," "), old_usernames = v.username or 'NOUSER', long_id = v.id } database["users"][tostring(v.peer_id)].groups = { } database["users"][tostring(v.peer_id)].groups[tostring(chat_id)] = tonumber(chat_id) end end save_data(_config.database.db, database) send_large_msg(extra.receiver, langs[get_lang(result.peer_id)].dataLeaked) end local function callback_supergroup_database(extra, success, result) local database = extra.database local chat_id = string.match(extra.receiver, '%d+') -- save supergroup info if database["groups"][tostring(chat_id)] then database["groups"][tostring(chat_id)] = { print_name = extra.print_name:gsub("_"," "), username = extra.username or 'NOUSER', lang = get_lang(string.match(extra.receiver,'%d+')), old_print_names = database["groups"][tostring(chat_id)].old_print_names .. ' ### ' .. extra.print_name:gsub("_"," "), old_usernames = database["groups"][tostring(chat_id)].old_usernames .. ' ### ' ..(extra.username or 'NOUSER'), long_id = extra.id } else database["groups"][tostring(chat_id)] = { print_name = extra.print_name:gsub("_"," "), username = extra.username or 'NOUSER', lang = get_lang(string.match(extra.receiver,'%d+')), old_print_names = extra.print_name:gsub("_"," "), old_usernames = extra.username or 'NOUSER', long_id = extra.id } end -- save users info for k, v in pairsByKeys(result) do if database["users"][tostring(v.peer_id)] then if not database["users"][tostring(v.peer_id)].groups then database["users"][tostring(v.peer_id)].groups = { } end if not database["users"][tostring(v.peer_id)].groups[tostring(chat_id)] then database["users"][tostring(v.peer_id)].groups[tostring(chat_id)] = tonumber(chat_id) end database["users"][tostring(v.peer_id)] = { print_name = v.print_name:gsub("_"," "), username = v.username or 'NOUSER', old_print_names = database["users"][tostring(v.peer_id)].old_print_names .. ' ### ' .. v.print_name:gsub("_"," "), old_usernames = database["users"][tostring(v.peer_id)].old_usernames .. ' ### ' ..(v.username or 'NOUSER'), long_id = v.id } else database["users"][tostring(v.peer_id)] = { print_name = v.print_name:gsub("_"," "), username = v.username or 'NOUSER', old_print_names = v.print_name:gsub("_"," "), old_usernames = v.username or 'NOUSER', long_id = v.id } database["users"][tostring(v.peer_id)].groups = { } database["users"][tostring(v.peer_id)].groups[tostring(chat_id)] = tonumber(chat_id) end end save_data(_config.database.db, database) send_large_msg(extra.receiver, langs[get_lang(string.match(extra.receiver, '%d+'))].dataLeaked) end local function run(msg, matches) if is_sudo(msg) then if matches[1]:lower() == 'createdatabase' then local f = io.open(_config.database.db, 'w+') f:write('{"groups":{},"users":{}}') f:close() reply_msg(msg.id, langs[msg.lang].dbCreated, ok_cb, false) return end local database = load_data(_config.database.db) if matches[1]:lower() == 'database' or matches[1]:lower() == 'sasha database' then local receiver = get_receiver(msg) if msg.to.type == 'channel' then channel_get_users(receiver, callback_supergroup_database, { receiver = receiver, database = database, print_name = msg.to.print_name, username = (msg.to.username or nil), id = msg.to.peer_id }) elseif msg.to.type == 'chat' then chat_info(receiver, callback_group_database, { receiver = receiver, database = database }) else return end end else return langs[msg.lang].require_sudo end end return { description = "DATABASE", patterns = { "^[#!/]([Cc][Rr][Ee][Aa][Tt][Ee][Dd][Aa][Tt][Aa][Bb][Aa][Ss][Ee])$", "^[#!/]([Dd][Aa][Tt][Aa][Bb][Aa][Ss][Ee])$", -- database "^([Ss][Aa][Ss][Hh][Aa] [Dd][Aa][Tt][Aa][Bb][Aa][Ss][Ee])$", }, run = run, min_rank = 5 -- usage -- SUDO -- #createdatabase -- (#database|[sasha] database) }
fix database
fix database
Lua
agpl-3.0
xsolinsx/AISasha
02ce8957125fde677fbd5b7c9f1c9fc814c589dc
scen_edit/view/asset_view.lua
scen_edit/view/asset_view.lua
SB.Include(Path.Join(SB_VIEW_DIR, "grid_view.lua")) AssetView = GridView:extends{} SB._assetViews = {} setmetatable(SB._assetViews, { __mode = 'v' }) function AssetView:init(tbl) table.insert(SB._assetViews, self) local defaults = { showDirs = true, imageFolderUp = nil, imageFolder = nil, showPath = true, } tbl = Table.Merge(defaults, tbl) GridView.init(self, tbl) self.rootDir = tbl.rootDir self.showDirs = tbl.showDirs self.imageFolder = tbl.imageFolder or self._fakeControl.imageFolder self.imageFolderUp = tbl.imageFolderUp or self._fakeControl.imageFolderUp self.layoutPanel.MouseDblClick = function(ctrl, x, y, button, mods) if button ~= 1 then return end local cx,cy = ctrl:LocalToClient(x,y) local itemIdx = ctrl:GetItemIndexAt(cx,cy) if itemIdx < 0 then return end local item = self.items[itemIdx] if item.isFolder then self:SetDir(item.path) return ctrl else ctrl:CallListeners(ctrl.OnDblClickItem, item, itemIdx) return ctrl end end if self.showPath then self.scrollPanel:SetPos(nil, 20) self.lblPath = Label:New { x = 35, y = 3, width = 100, height = 20, caption = "", parent = self.holderControl, font = { color = {0.7, 0.7, 0.7, 1.0}, }, } self.btnUp = Button:New { x = 5, y = 2, width = 18, height = 18, caption = "", parent = self.holderControl, padding = {0, 0, 0, 0}, children = { Image:New { x = 0, y = 0, width = "100%", height = "100%", margin = {0, 0, 0, 0}, file = self.imageFolderUp, } }, OnClick = { function() self:SetDir(Path.GetParentDir(self.dir)) end }, } if self.rootDir then self.lblRootDir = Label:New { right = 5, y = 3, width = 100, height = 20, caption = "Root: " .. tostring(self.rootDir), parent = self.holderControl, font = { color = {0.7, 0.7, 0.7, 1.0}, }, } end end self:SetDir(tbl.dir or '') end function AssetView:SetDir(directory) self.layoutPanel:DeselectAll() self.dir = directory if self.lblPath then self.lblPath:SetCaption(self.dir) end -- MaterialBrowser.lastDir = self.dir self:ScanDir() end function AssetView:ScanDir() self:ScanDirStarted() local files = self:_DirList() self.files = {} for _, file in pairs(files) do local ext = (Path.GetExt(file) or ""):lower() if self:FilterFile(file) then table.insert(self.files, file) end end self.dirs = self:_SubDirs() self:ScanDirFinished() self:StartMultiModify() self:ClearItems() --// add dirs at top if self.showDirs then for _, dir in pairs(self.dirs) do self:AddFolder(dir) end end self:PopulateItems() self:EndMultiModify() end function AssetView:SelectAsset(path) if path == nil then self:DeselectAll() return end local assetPath = self:_ToAssetPath(path) local dir = Path.GetParentDir(assetPath) self:SetDir(dir) for itemIdx, item in pairs(self:GetAllItems()) do if item.path == path then self:SelectItem(itemIdx) end end end function AssetView:_DirList() if self.rootDir then return SB.model.assetsManager:DirList(self.rootDir, self.dir, "*") else return VFS.DirList(self.dir, "*") end end function AssetView:_SubDirs() if self.rootDir then return SB.model.assetsManager:SubDirs(self.rootDir, self.dir, "*") else return VFS.SubDirs(self.dir, "*") end end function AssetView:_ToAssetPath(path) if self.rootDir then return SB.model.assetsManager:ToAssetPath(self.rootDir, path) else return path end end -- Override function AssetView:ScanDirStarted() end function AssetView:ScanDirFinished() end function AssetView:FilterFile(file) return true end function AssetView:AddFolder(folder) local tooltip local image = self.imageFolder if SB.DirIsProject(folder) then local sbInfoPath = Path.Join(folder, "sb_project.lua") if VFS.FileExists(sbInfoPath, VFS.RAW) then local sbInfoStr = VFS.LoadFile(sbInfoPath, VFS.RAW) local sbInfo = loadstring(sbInfoStr)() local game, mapName = sbInfo.game, sbInfo.mapName local randomMapOptions = sbInfo.randomMapOptions local mutators = sbInfo.mutators or {} local mapStr = mapName if randomMapOptions ~= nil then mapStr = mapStr .. " (generated: " .. randomMapOptions.new_map_x .. "x" .. randomMapOptions.new_map_z .. ")" end if #mutators ~= 0 then mapStr = mapStr .. "\nMutators: " for i, mutator in ipairs(mutators) do mapStr = mapStr .. mutator if i ~= #mutators then mapStr = mapStr .. ", " end end end tooltip = string.format("Game: %s %s\nMap: %s", game.name, game.version, mapStr ) else Log.Warning("Missing sb_project.lua for project: " .. tostring(folder)) end local imgPath = Path.Join(folder, SB_SCREENSHOT_FILE) if VFS.FileExists(imgPath, VFS.RAW) then image = imgPath end end local item = self:AddItem(Path.ExtractFileName(folder), image, tooltip) item.path = folder item.isFolder = true end function AssetView:AddFile(file) local ext = (Path.GetExt(file) or ""):lower() local texturePath if table.ifind(SB_IMG_EXTS, ext) then texturePath = ':clr' .. self.itemWidth .. ',' .. self.itemHeight .. ':' .. tostring(file) -- FIXME: why not just use the file directly? it works -- What is the performance/caching difference, if any? -- texturePath = file end local name = Path.ExtractFileName(file) local item = self:AddItem(name, texturePath, "") item.path = file item.isFile = true end function AssetView:PopulateItems() for _, file in pairs(self.files) do self:AddFile(file) end end
SB.Include(Path.Join(SB_VIEW_DIR, "grid_view.lua")) AssetView = GridView:extends{} SB._assetViews = {} setmetatable(SB._assetViews, { __mode = 'v' }) function AssetView:init(tbl) table.insert(SB._assetViews, self) local defaults = { showDirs = true, imageFolderUp = nil, imageFolder = nil, showPath = true, } tbl = Table.Merge(defaults, tbl) GridView.init(self, tbl) self.rootDir = tbl.rootDir self.showDirs = tbl.showDirs self.imageFolder = tbl.imageFolder or self._fakeControl.imageFolder self.imageFolderUp = tbl.imageFolderUp or self._fakeControl.imageFolderUp self.layoutPanel.MouseDblClick = function(ctrl, x, y, button, mods) if button ~= 1 then return end local cx,cy = ctrl:LocalToClient(x,y) local itemIdx = ctrl:GetItemIndexAt(cx,cy) if itemIdx < 0 then return end local item = self.items[itemIdx] if item.isFolder then self:SetDir(item.path) return ctrl else ctrl:CallListeners(ctrl.OnDblClickItem, item, itemIdx) return ctrl end end if self.showPath then self.scrollPanel:SetPos(nil, 20) self.lblPath = Label:New { x = 35, y = 3, width = 100, height = 20, caption = "", parent = self.holderControl, font = { color = {0.7, 0.7, 0.7, 1.0}, }, } self.btnUp = Button:New { x = 5, y = 2, width = 18, height = 18, caption = "", parent = self.holderControl, padding = {0, 0, 0, 0}, children = { Image:New { x = 0, y = 0, width = "100%", height = "100%", margin = {0, 0, 0, 0}, file = self.imageFolderUp, } }, OnClick = { function() self:SetDir(Path.GetParentDir(self.dir)) end }, } if self.rootDir then self.lblRootDir = Label:New { right = 5, y = 3, width = 100, height = 20, caption = "Root: " .. tostring(self.rootDir), parent = self.holderControl, font = { color = {0.7, 0.7, 0.7, 1.0}, }, } end end self:SetDir(tbl.dir or '') end function AssetView:SetDir(directory) self.layoutPanel:DeselectAll() self.dir = directory if self.lblPath then self.lblPath:SetCaption(self.dir) end -- MaterialBrowser.lastDir = self.dir self:ScanDir() end function AssetView:ScanDir() self:ScanDirStarted() local files = self:_DirList() self.files = {} for _, file in pairs(files) do local ext = (Path.GetExt(file) or ""):lower() if self:FilterFile(file) then table.insert(self.files, file) end end self.dirs = self:_SubDirs() self:ScanDirFinished() self:StartMultiModify() self:ClearItems() --// add dirs at top if self.showDirs then for _, dir in pairs(self.dirs) do self:AddFolder(dir) end end self:PopulateItems() self:EndMultiModify() end function AssetView:SelectAsset(path) if path == nil then self:DeselectAll() return end local assetPath = self:_ToAssetPath(path) local dir = Path.GetParentDir(assetPath) self:SetDir(dir) for itemIdx, item in pairs(self:GetAllItems()) do if item.path == path then self:SelectItem(itemIdx) end end end function AssetView:_DirList() if self.rootDir then return SB.model.assetsManager:DirList(self.rootDir, self.dir, "*") else return VFS.DirList(self.dir, "*") end end function AssetView:_SubDirs() if self.rootDir then return SB.model.assetsManager:SubDirs(self.rootDir, self.dir, "*") else return VFS.SubDirs(self.dir, "*") end end function AssetView:_ToAssetPath(path) if self.rootDir then return SB.model.assetsManager:ToAssetPath(self.rootDir, path) else return path end end -- Override function AssetView:ScanDirStarted() end function AssetView:ScanDirFinished() end function AssetView:FilterFile(file) return true end function AssetView:AddFolder(folder) local tooltip local image = self.imageFolder if SB.DirIsProject(folder) then local sbInfoPath = Path.Join(folder, "sb_project.lua") if VFS.FileExists(sbInfoPath, VFS.RAW) then local sbInfoStr = VFS.LoadFile(sbInfoPath, VFS.RAW) local sbInfo = loadstring(sbInfoStr)() local game, mapName = sbInfo.game, sbInfo.mapName local randomMapOptions = sbInfo.randomMapOptions local mutators = sbInfo.mutators or {} local mapStr = mapName if randomMapOptions ~= nil and randomMapOptions.new_map_x ~= nil and randomMapOptions.new_map_z ~= nil then mapStr = mapStr .. " (generated: " .. randomMapOptions.new_map_x .. "x" .. randomMapOptions.new_map_z .. ")" end if #mutators ~= 0 then mapStr = mapStr .. "\nMutators: " for i, mutator in ipairs(mutators) do mapStr = mapStr .. mutator if i ~= #mutators then mapStr = mapStr .. ", " end end end tooltip = string.format("Game: %s %s\nMap: %s", game.name, game.version, mapStr ) else Log.Warning("Missing sb_project.lua for project: " .. tostring(folder)) end local imgPath = Path.Join(folder, SB_SCREENSHOT_FILE) if VFS.FileExists(imgPath, VFS.RAW) then image = imgPath end end local item = self:AddItem(Path.ExtractFileName(folder), image, tooltip) item.path = folder item.isFolder = true end function AssetView:AddFile(file) local ext = (Path.GetExt(file) or ""):lower() local texturePath if table.ifind(SB_IMG_EXTS, ext) then texturePath = ':clr' .. self.itemWidth .. ',' .. self.itemHeight .. ':' .. tostring(file) -- FIXME: why not just use the file directly? it works -- What is the performance/caching difference, if any? -- texturePath = file end local name = Path.ExtractFileName(file) local item = self:AddItem(name, texturePath, "") item.path = file item.isFile = true end function AssetView:PopulateItems() for _, file in pairs(self.files) do self:AddFile(file) end end
fix listing non-blank maps with asset view
fix listing non-blank maps with asset view
Lua
mit
Spring-SpringBoard/SpringBoard-Core,Spring-SpringBoard/SpringBoard-Core
cedd3dee70fbf30a6617141e09da9f2b4abe4850
src/event/Event.lua
src/event/Event.lua
---------------------------------------------------------------------------------------------------- -- @type Event -- -- A class for events, which are communicated to, and handled by, event handlers -- Holds the data of the Event. ---------------------------------------------------------------------------------------------------- local Event = class() Event.ENTER_FRAME = "enterFrame" Event.ENTER = "enter" Event.EXIT = "exit" Event.WILL_ENTER = "willEnter" Event.DID_EXIT = "didExit" Event.UPDATE = "update" Event.TOUCH_EVENT = "touch" Event.TOUCH_DOWN = "touchDown" Event.TOUCH_UP = "touchUp" Event.TOUCH_MOVE = "touchMove" Event.TOUCH_CANCEL = "touchCancel" Event.KEY_DOWN = "keyDown" Event.KEY_UP = "keyUp" --- -- Event's constructor. -- @param eventType (option)The type of event. function Event:init(eventType) self.type = eventType self.stopFlag = false end --- -- INTERNAL USE ONLY -- Sets the event listener via EventDispatcher. -- @param callback callback function -- @param source source object. function Event:setListener(callback, source) self.callback = callback self.source = source end --- -- Stop the propagation of the event. function Event:stop() self.stopFlag = true end return Event
---------------------------------------------------------------------------------------------------- -- @type Event -- -- A class for events, which are communicated to, and handled by, event handlers -- Holds the data of the Event. ---------------------------------------------------------------------------------------------------- local Event = class() Event.ENTER_FRAME = "enterFrame" Event.ENTER = "enter" Event.EXIT = "exit" Event.WILL_ENTER = "willEnter" Event.DID_EXIT = "didExit" Event.UPDATE = "update" Event.TOUCH_EVENT = "touch" Event.TOUCH_DOWN = "touchDown" Event.TOUCH_UP = "touchUp" Event.TOUCH_MOVE = "touchMove" Event.TOUCH_CANCEL = "touchCancel" Event.KEY_DOWN = "keyDown" Event.KEY_UP = "keyUp" Event.RESIZE = "resize" --- -- Event's constructor. -- @param eventType (option)The type of event. function Event:init(eventType) self.type = eventType self.stopFlag = false end --- -- INTERNAL USE ONLY -- Sets the event listener via EventDispatcher. -- @param callback callback function -- @param source source object. function Event:setListener(callback, source) self.callback = callback self.source = source end --- -- Stop the propagation of the event. function Event:stop() self.stopFlag = true end return Event
Fix resize event
Fix resize event
Lua
mit
Vavius/moai-framework,Vavius/moai-framework
a2f1e7729f2e065d73f283c9ea1a5f5bcaec0418
lua/TailTools.lua
lua/TailTools.lua
do -- range(from, to, increment) local function _recursiverange(i,b,c,...) if c > 0 and i > b then return ... elseif c < 0 and i <= b then return ... end -- we're adding things to the start of ..., so ... is backwards -- this is why we need the wrapper/abstraction below -- NO we CAN NOT use "..., i" here, because the Lua reference -- manual says "..., i" keeps only the first thing on ... and -- drops everything else return _recursiverange(i+c,b,c,i,...) end function recursiverange(a,b,c) -- because range(1,3,1) is 1, 2, 3, not 3, 2, 1. return _recursiverange(b,a,-(c or 1)) end end do -- recursivecopy(originalTable, recursionTable, copyKeys) local function _recursivecopy(ot, nt, r, ck, k) local nk, v = next(ot, k) if nk == nil then return nt end if ck and type(nk) == "table" then nk = _recursivecopy(nk, {}, r, ck) end if type(v) == "table" then v = _recursivecopy(v, {}, r, ck) end rawset(nt, nk, v) return _recursivecopy(ot, nt, r, ck, nk) end function recursivecopy(t, r, ck) return _recursivecopy(ot, {}, r, ck) end end
do -- range(from, to, increment) local function _recursiverange(i,b,c,...) if c > 0 and i > b then return ... elseif c < 0 and i <= b then return ... end -- we're adding things to the start of ..., so ... is backwards -- this is why we need the wrapper/abstraction below -- NO we CAN NOT use "..., i" here, because the Lua reference -- manual says "..., i" keeps only the first thing on ... and -- drops everything else return _recursiverange(i+c,b,c,i,...) end function recursiverange(a,b,c) -- because range(1,3,1) is 1, 2, 3, not 3, 2, 1. return _recursiverange(b,a,-(c or 1)) end end do -- recursivecopy(originalTable, recursionTable, copyKeys) local function _recursivecopy(ot, nt, r, ck, k) nt = nt or {} r = r or {} if r[ot] == nil then r[ot] = nt end local nk, v = next(ot, k) if nk == nil then return nt end if ck and type(nk) == "table" then nk = r[nk] or _recursivecopy(nk, {}, r, ck) end if type(v) == "table" then v = r[v] or _recursivecopy(v, {}, r, ck) end rawset(nt, nk, v) return _recursivecopy(ot, nt, r, ck, nk) end function recursivecopy(t, r, ck) return _recursivecopy(ot, {}, r, ck) end end
Update TailTools.lua
Update TailTools.lua Fixed derp...
Lua
mit
SoniEx2/Stuff,SoniEx2/Stuff
e11685b211f46f423fabc243946348474eafef7d
modules/gcalc.lua
modules/gcalc.lua
local simplehttp = require'simplehttp' local html2unicode = require'html' local urlEncode = function(str) return str:gsub( '([^%w ])', function (c) return string.format ("%%%02X", string.byte(c)) end ):gsub(' ', '+') end local parseData = function(source, destination, data) local ans = data:match('<h2 .-><b>(.-)</b></h2><div') if(ans) then ans = ans:gsub('<sup>(.-)</sup>', '^%1'):gsub('<[^>]+> ?', '') ivar2:Msg('privmsg', destination, source, '%s: %s', source.nick, html2unicode(ans)) else ivar2:Msg('privmsg', destination, source, '%s: %s', source.nick, 'Do you want some air with that fail?') end end local handle = function(self, source, destination, input) local search = urlEncode(input) simplehttp( ('http://www.google.com/search?q=%s'):format(search), function(data) parseData(source, destination, data) end ) end return { PRIVMSG = { ['^!gcalc (.+)$'] = handle, ['^!calc (.+)$'] = handle, ['^!galc (.+)$'] = handle, }, }
local simplehttp = require'simplehttp' local html2unicode = require'html' local urlEncode = function(str) return str:gsub( '([^%w ])', function (c) return string.format ("%%%02X", string.byte(c)) end ):gsub(' ', '+') end local parseData = function(source, destination, data) local ans = data:match('<h2 class="r".->(.-)</h2>') if(ans) then ans = ans:gsub('<sup>(.-)</sup>', '^%1'):gsub('<[^>]+> ?', ''):gsub('%s+', ' ') ivar2:Msg('privmsg', destination, source, '%s: %s', source.nick, html2unicode(ans)) else ivar2:Msg('privmsg', destination, source, '%s: %s', source.nick, 'Do you want some air with that fail?') end end local handle = function(self, source, destination, input) local search = urlEncode(input) simplehttp( ('http://www.google.com/search?q=%s'):format(search), function(data) parseData(source, destination, data) end ) end return { PRIVMSG = { ['^!gcalc (.+)$'] = handle, ['^!calc (.+)$'] = handle, ['^!galc (.+)$'] = handle, }, }
gcalc: Update HTML matching to work after update.
gcalc: Update HTML matching to work after update. This fixes issue #37.
Lua
mit
torhve/ivar2,torhve/ivar2,haste/ivar2,torhve/ivar2
e355c27a3b5902b89f7f35139813efdbe0014fa4
durden/menus/target/clipboard.lua
durden/menus/target/clipboard.lua
local function pastefun(wnd, msg) local dst = wnd.clipboard_out; if (not dst) then local dst = alloc_surface(1, 1); -- this approach triggers an interesting bug that may be worthwhile to explore -- wnd.clipboard_out = define_recordtarget(alloc_surface(1, 1), -- wnd.external, "", {null_surface(1,1)}, {}, -- RENDERTARGET_DETACH, RENDERTARGET_NOSCALE, 0, function() -- end); wnd.clipboard_out = define_nulltarget(wnd.external, function() end); end msg = wnd.pastefilter ~= nil and wnd.pastefilter(msg) or msg; if (msg and string.len(msg) > 0) then target_input(wnd.clipboard_out, msg); end end local function clipboard_paste() local wnd = active_display().selected; pastefun(wnd, CLIPBOARD.globals[1]); end local function clipboard_paste_local() local wnd = active_display().selected; pastefun(wnd, CLIPBOARD:list_local(wnd.clipboard)[1]); end -- can shorten further by dropping vowels and characters -- in beginning and end as we match more on those local function shorten(s) if (s == nil or string.len(s) == 0) then return ""; end local r = string.gsub( string.gsub(s, " ", ""), "\n", "" ); return r and r or ""; end local function clipboard_histgen(wnd, lst, promote) local res = {}; for k, v in ipairs(lst) do table.insert(res, { name = "hist_" .. tostring(k), label = string.format("%d:%s", k, string.sub(shorten(v), 1, 20)), kind = "action", handler = function() if (promote) then CLIPBOARD:set_global(v); else local m1, m2 = dispatch_meta(); pastefun(wnd, v); end end }); end return res; end local function clipboard_local_history() local wnd = active_display().selected; return clipboard_histgen(wnd, CLIPBOARD:list_local(wnd.clipboard)); end local function clipboard_history() return clipboard_histgen(active_display().selected, CLIPBOARD.globals); end local function clipboard_urls() local res = {}; for k,v in ipairs(CLIPBOARD.urls) do table.insert(res, { name = "url_" .. tostring(k), label = shorten(v), kind = "action", handler = function() local m1, m2 = dispatch_meta(); pastefun(active_display().selected, v); end }); end return res; end register_shared("paste_global", clipboard_paste); return { { name = "paste", label = "Paste", kind = "action", eval = function() return valid_vid( active_display().selected.external, TYPE_FRAMESERVER); end, handler = clipboard_paste }, { name = "lpaste", label = "Paste-Local", kind = "action", eval = function() return valid_vid( active_display().selected.external, TYPE_FRAMESERVER); end, handler = clipboard_paste_local }, { name = "lhist", label = "History-Local", kind = "action", eval = function() local wnd = active_display().selected; return wnd.clipboard ~= nil and #CLIPBOARD:list_local(wnd.clipboard) > 0; end, submenu = true, handler = function() local wnd = active_display().selected; return clipboard_histgen(wnd, CLIPBOARD:list_local(wnd.clipboard)); end }, { name = "lhistprom", label = "Promote", kind = "action", eval = function() local wnd = active_display().selected; return wnd.clipboard ~= nil and #CLIPBOARD:list_local(wnd.clipboard) > 0; end, submenu = true, handler = function() local wnd = active_display().selected; return clipboard_histgen(wnd, CLIPBOARD:list_local(wnd.clipboard), true); end }, { name = "hist", label = "History", kind = "action", submenu = true, eval = function() return valid_vid( active_display().selected.external, TYPE_FRAMESERVER); end, handler = clipboard_history }, { name = "url", label = "URLs", kind = "action", submenu = true, eval = function() return valid_vid( active_display().selected.external, TYPE_FRAMESERVER) and #CLIPBOARD.urls > 0; end, handler = clipboard_urls }, { name = "mode", label = "Mode", kind = "value", initial = function() local wnd = active_display().selected; return wnd.pastemode and wnd.pastemode or ""; end, set = CLIPBOARD:pastemodes(), handler = function(ctx, val) local wnd = active_display().selected; local f, l = CLIPBOARD:pastemodes(val); wnd.pastemode = l; wnd.pastefilter = f; end } }
local function pastefun(wnd, msg) local dst = wnd.clipboard_out; if (not dst) then local dst = alloc_surface(1, 1); -- this approach triggers an interesting bug that may be worthwhile to explore -- wnd.clipboard_out = define_recordtarget(alloc_surface(1, 1), -- wnd.external, "", {null_surface(1,1)}, {}, -- RENDERTARGET_DETACH, RENDERTARGET_NOSCALE, 0, function() -- end); wnd.clipboard_out = define_nulltarget(wnd.external, function(source, status) if (status.kind == "terminated") then delete_image(source); wnd.clipboard_out = nil; end end); link_image(wnd.clipboard_out, wnd.anchor); end msg = wnd.pastefilter ~= nil and wnd.pastefilter(msg) or msg; if (msg and string.len(msg) > 0) then target_input(wnd.clipboard_out, msg); end end local function clipboard_paste() local wnd = active_display().selected; pastefun(wnd, CLIPBOARD.globals[1]); end local function clipboard_paste_local() local wnd = active_display().selected; pastefun(wnd, CLIPBOARD:list_local(wnd.clipboard)[1]); end -- can shorten further by dropping vowels and characters -- in beginning and end as we match more on those local function shorten(s) if (s == nil or string.len(s) == 0) then return ""; end local r = string.gsub( string.gsub(s, " ", ""), "\n", "" ); return r and r or ""; end local function clipboard_histgen(wnd, lst, promote) local res = {}; for k, v in ipairs(lst) do table.insert(res, { name = "hist_" .. tostring(k), label = string.format("%d:%s", k, string.sub(shorten(v), 1, 20)), kind = "action", handler = function() if (promote) then CLIPBOARD:set_global(v); else local m1, m2 = dispatch_meta(); pastefun(wnd, v); end end }); end return res; end local function clipboard_local_history() local wnd = active_display().selected; return clipboard_histgen(wnd, CLIPBOARD:list_local(wnd.clipboard)); end local function clipboard_history() return clipboard_histgen(active_display().selected, CLIPBOARD.globals); end local function clipboard_urls() local res = {}; for k,v in ipairs(CLIPBOARD.urls) do table.insert(res, { name = "url_" .. tostring(k), label = shorten(v), kind = "action", handler = function() local m1, m2 = dispatch_meta(); pastefun(active_display().selected, v); end }); end return res; end register_shared("paste_global", clipboard_paste); return { { name = "paste", label = "Paste", kind = "action", eval = function() return valid_vid( active_display().selected.external, TYPE_FRAMESERVER); end, handler = clipboard_paste }, { name = "lpaste", label = "Paste-Local", kind = "action", eval = function() return valid_vid( active_display().selected.external, TYPE_FRAMESERVER); end, handler = clipboard_paste_local }, { name = "lhist", label = "History-Local", kind = "action", eval = function() local wnd = active_display().selected; return wnd.clipboard ~= nil and #CLIPBOARD:list_local(wnd.clipboard) > 0; end, submenu = true, handler = function() local wnd = active_display().selected; return clipboard_histgen(wnd, CLIPBOARD:list_local(wnd.clipboard)); end }, { name = "lhistprom", label = "Promote", kind = "action", eval = function() local wnd = active_display().selected; return wnd.clipboard ~= nil and #CLIPBOARD:list_local(wnd.clipboard) > 0; end, submenu = true, handler = function() local wnd = active_display().selected; return clipboard_histgen(wnd, CLIPBOARD:list_local(wnd.clipboard), true); end }, { name = "hist", label = "History", kind = "action", submenu = true, eval = function() return valid_vid( active_display().selected.external, TYPE_FRAMESERVER); end, handler = clipboard_history }, { name = "url", label = "URLs", kind = "action", submenu = true, eval = function() return valid_vid( active_display().selected.external, TYPE_FRAMESERVER) and #CLIPBOARD.urls > 0; end, handler = clipboard_urls }, { name = "mode", label = "Mode", kind = "value", initial = function() local wnd = active_display().selected; return wnd.pastemode and wnd.pastemode or ""; end, set = CLIPBOARD:pastemodes(), handler = function(ctx, val) local wnd = active_display().selected; local f, l = CLIPBOARD:pastemodes(val); wnd.pastemode = l; wnd.pastefilter = f; end } }
fix pasteboard- leak
fix pasteboard- leak
Lua
bsd-3-clause
letoram/durden
4068d4dd52a9b4f600480476411c17adda7f1c35
gga.lua
gga.lua
solution "gga" configurations {"Release", "Debug" } location (_OPTIONS["to"]) ------------------------------------- -- glfw static lib ------------------------------------- project "glfw_proj" language "C" kind "StaticLib" defines { "_CRT_SECURE_NO_WARNINGS" } includedirs { "./3rdParty/glfw/include" } files { "./3rdParty/glfw/src/internal.h", "./3rdParty/glfw/src/glfw_config.h", "./3rdParty/glfw/include/GLFW/glfw3.h", "./3rdParty/glfw/include/GLFW/glfw3native.h", "./3rdParty/glfw/src/context.c", "./3rdParty/glfw/src/init.c", "./3rdParty/glfw/src/input.c", "./3rdParty/glfw/src/monitor.c", "./3rdParty/glfw/src/window.c" } configuration "windows" defines { "_GLFW_WIN32" } configuration { "windows", "gmake" } includedirs { "./3rdParty/glfw/deps/mingw" } files { "./3rdParty/glfw/src/vulkan.c", "./3rdParty/glfw/src/win32_platform.h", "./3rdParty/glfw/src/win32_joystick.h", "./3rdParty/glfw/src/wgl_context.h", "./3rdParty/glfw/src/egl_context.c", "./3rdParty/glfw/src/win32_init.c", "./3rdParty/glfw/src/win32_joystick.c", "./3rdParty/glfw/src/win32_monitor.c", "./3rdParty/glfw/src/win32_time.c", "./3rdParty/glfw/src/win32_tls.c", "./3rdParty/glfw/src/win32_window.c", "./3rdParty/glfw/src/wgl_context.c", "./3rdParty/glfw/src/egl_context.c" } targetdir "./lib" configuration "Debug" defines { "_DEBUG" } flags { "Symbols" } targetdir "./lib/debug" targetname "glfwd" configuration "Release" defines { "NDEBUG" } flags { "OptimizeSize" } targetdir "./lib/release" targetname "glfw" ------------------------------------- -- glew static lib ------------------------------------- project "glew_proj" language "C" kind "StaticLib" includedirs { "./3rdParty/glew/include" } files { "./3rdParty/glew/src/**.h", "./3rdParty/glew/src/**.c", "./3rdParty/glew/include/GL/**.h" } configuration "windows" defines { "WIN32", "_LIB", "WIN32_LEAN_AND_MEAN", "GLEW_STATIC", "_CRT_SECURE_NO_WARNINGS" } targetdir "./lib" configuration "Debug" defines { "_DEBUG" } flags { "Symbols" } targetdir "./lib/debug" targetname "glewd" configuration "Release" defines { "NDEBUG" } flags { "OptimizeSize" } targetdir "./lib/release" targetname "glew" ------------------------------------- -- top level gga project ------------------------------------- project "gga" targetname "gga" language "C++" kind "ConsoleApp" flags { "No64BitChecks", "StaticRuntime" } includedirs { "./lib", "./3rdParty/glew/include", "./3rdParty/glfw/include/" } libdirs { "./lib" } links { "glfw_proj", "glew_proj" } files { "./src/**.h", "./src/**.cpp" } configuration "Debug" defines { "_DEBUG" } flags { "Symbols" } libdirs { "./lib/debug" } links { "msvcrtd", "gdi32", "opengl32", "glewd", "glfwd" } configuration "Release" defines { "NDEBUG" } flags { "OptimizeSize" } libdirs { "./lib/release" } links { "msvcrt", "gdi32", "opengl32", "glew", "glfw" } configuration "windows" defines { "_WIN32" } targetdir "./bin/windows" if _ACTION == "clean" then os.rmdir("bin") os.rmdir("build") end newoption { trigger = "to", value = "path", description = "Set the output location for the generated files" }
solution "gga" configurations {"Release", "Debug" } location (_OPTIONS["to"]) ------------------------------------- -- glfw static lib ------------------------------------- project "glfw_proj" language "C" kind "StaticLib" defines { "_CRT_SECURE_NO_WARNINGS" } includedirs { "./3rdParty/glfw/include" } files { "./3rdParty/glfw/src/internal.h", "./3rdParty/glfw/src/glfw_config.h", "./3rdParty/glfw/include/GLFW/glfw3.h", "./3rdParty/glfw/include/GLFW/glfw3native.h", "./3rdParty/glfw/src/context.c", "./3rdParty/glfw/src/init.c", "./3rdParty/glfw/src/input.c", "./3rdParty/glfw/src/monitor.c", "./3rdParty/glfw/src/window.c" } configuration "windows" defines { "_GLFW_WIN32" } files { "./3rdParty/glfw/src/vulkan.c", "./3rdParty/glfw/src/win32_platform.h", "./3rdParty/glfw/src/win32_joystick.h", "./3rdParty/glfw/src/wgl_context.h", "./3rdParty/glfw/src/egl_context.c", "./3rdParty/glfw/src/win32_init.c", "./3rdParty/glfw/src/win32_joystick.c", "./3rdParty/glfw/src/win32_monitor.c", "./3rdParty/glfw/src/win32_time.c", "./3rdParty/glfw/src/win32_tls.c", "./3rdParty/glfw/src/win32_window.c", "./3rdParty/glfw/src/wgl_context.c", "./3rdParty/glfw/src/egl_context.c" } targetdir "./lib" configuration { "windows", "gmake" } includedirs { "./3rdParty/glfw/deps/mingw" } configuration "Debug" defines { "_DEBUG" } flags { "Symbols" } targetdir "./lib/debug" targetname "glfwd" configuration "Release" defines { "NDEBUG" } flags { "OptimizeSize" } targetdir "./lib/release" targetname "glfw" ------------------------------------- -- glew static lib ------------------------------------- project "glew_proj" language "C" kind "StaticLib" includedirs { "./3rdParty/glew/include" } files { "./3rdParty/glew/src/**.h", "./3rdParty/glew/src/**.c", "./3rdParty/glew/include/GL/**.h" } configuration "windows" defines { "WIN32", "_LIB", "WIN32_LEAN_AND_MEAN", "GLEW_STATIC", "_CRT_SECURE_NO_WARNINGS" } targetdir "./lib" configuration "Debug" defines { "_DEBUG" } flags { "Symbols" } targetdir "./lib/debug" targetname "glewd" configuration "Release" defines { "NDEBUG" } flags { "OptimizeSize" } targetdir "./lib/release" targetname "glew" ------------------------------------- -- top level gga project ------------------------------------- project "gga" targetname "gga" language "C++" kind "ConsoleApp" flags { "No64BitChecks", "StaticRuntime" } includedirs { "./lib", "./3rdParty/glew/include", "./3rdParty/glfw/include/" } libdirs { "./lib" } links { "glfw_proj", "glew_proj" } files { "./src/**.h", "./src/**.cpp" } configuration "Debug" defines { "_DEBUG" } flags { "Symbols" } libdirs { "./lib/debug" } links { "msvcrtd", "gdi32", "opengl32", "glewd", "glfwd" } configuration "Release" defines { "NDEBUG" } flags { "OptimizeSize" } libdirs { "./lib/release" } links { "msvcrt", "gdi32", "opengl32", "glew", "glfw" } configuration "windows" defines { "_WIN32" } targetdir "./bin/windows" if _ACTION == "clean" then os.rmdir("bin") os.rmdir("build") end newoption { trigger = "to", value = "path", description = "Set the output location for the generated files" }
further fixes in project generation. Project compiles on mingw and vs2015
further fixes in project generation. Project compiles on mingw and vs2015
Lua
mit
mrTag/GreatGreenArkleseizure,mrTag/GreatGreenArkleseizure
345cc4a318bd72d87e301fa7292a69d2a1064623
tests/test-thread.lua
tests/test-thread.lua
return require('lib/tap')(function (test) --thread not return anything test("test thread sleep msecs in loop thread", function(print,p,expect,uv) local b = os.clock() uv.sleep(500) local e = os.clock() local cost = (e-b)*1000 p("stdout", {sleep=500,cost=cost}) assert(cost>=500,"should equals") end) test("test thread create", function(print,p,expect,uv) local thread_id = uv.new_thread() local b = os.clock() uv.thread_create(thread_id,function(step,...) local uv = require('luv') uv.sleep(500) end) uv.thread_join(thread_id) local e = os.clock() local cost = (e-b)*1000 p("stdout", {sleep=500,cost=cost}) assert(cost>=500,"should equals") end) test("test thread create with arguments", function(print,p,expect,uv) local thread_id = uv.new_thread() local b = os.clock() uv.thread_create(thread_id,function(num,s,null,bool,five,hw) assert(type(num)=="number") assert(type(s)=="string") assert(null==nil) assert(bool==false) assert(five==5) assert(hw=='helloworld') end, 500, 'string', nil, false, 5, "helloworld") uv.thread_join(thread_id) end) end)
return require('lib/tap')(function (test) --thread not return anything test("test thread sleep msecs in loop thread", function(print,p,expect,uv) local sleep = 1000 local b = os.time() uv.sleep(sleep) local e = os.time() local cost = (e-b) p("stdout", {sleep=string.format('sleep %d ms',1000),string.format('cost %d seconds',cost)}) assert(cost>=sleep/1000,"should equals") end) test("test thread create", function(print,p,expect,uv) local sleep = 1000 local thread_id = uv.new_thread() local b = os.time() uv.thread_create(thread_id,function(sleep,...) local uv = require('luv') uv.sleep(sleep) end,sleep) uv.thread_join(thread_id) local e = os.time() print(e,b) local cost = (e-b) p("stdout", {sleep=string.format('sleep %d ms',1000),string.format('cost %d seconds',cost)}) assert(cost>=sleep/1000,"should equals") end) test("test thread create with arguments", function(print,p,expect,uv) local thread_id = uv.new_thread() local b = os.clock() uv.thread_create(thread_id,function(num,s,null,bool,five,hw) assert(type(num)=="number") assert(type(s)=="string") assert(null==nil) assert(bool==false) assert(five==5) assert(hw=='helloworld') end, 500, 'string', nil, false, 5, "helloworld") uv.thread_join(thread_id) end) end)
fix bugs in test
fix bugs in test
Lua
apache-2.0
kidaa/luv,mkschreder/luv,leecrest/luv,joerg-krause/luv,xpol/luv,luvit/luv,mkschreder/luv,DBarney/luv,luvit/luv,joerg-krause/luv,zhaozg/luv,kidaa/luv,DBarney/luv,xpol/luv,RomeroMalaquias/luv,daurnimator/luv,daurnimator/luv,zhaozg/luv,RomeroMalaquias/luv,leecrest/luv,daurnimator/luv,RomeroMalaquias/luv,NanXiao/luv,NanXiao/luv
1c4956120546a2b8f25ff1fceeea7e0acea379f7
module/util/pack.lua
module/util/pack.lua
--[[! \file \brief Módulo que define una función que permite realizar la operación inversa a unpack: toma una serie de parámetros y los empaqueta en una tabla. ]] --[[! Empaqueta varios valores en una tabla. @param ... Los valores a empaquetar. @return Devuelve una tabla con los valores pasados como argumento tomados en orden en el que se especificaron. ]] function pack(...) return {...}; end; --[[! Igual que pack pero solo empaqueta los n primeros valores tomados como argumentos. @param n El número de elementos a empaquetar. Debe ser mayor o igual 1 y menor o igual al número de argumentos (en ese caso sería igual que pack) @param ... Los argumentos a empaquetar. @return Devuelve como primer valor, una tabla con los n primeros valores empaquetados, y una lista con los valores restantes no empaquetados. ]] function halfpack(n, ...) local args = pack(...); assert((type(n) == "number") and (n >= 1) and (n <= #args)); if n < #args then local packedArgs = {}; local unpackedArgs = {}; for i = 1,n,1 do packedArgs[i] = args[i]; end; for i = n+1,#args,1 do unpackedArgs[i-n] = args[i]; end; return packedArgs, unpack(unpackedArgs); end; return args; end; --[[! Es igual que pack solo que los argumentos se empaquetan en una tabla en orden inverso al especificado ]] function reversepack(...) local args = pack(...); local reversedArgs = {}; for i = 1, #args, 1 do reversedArgs[#args-i+1] = args[i]; end; return reversedArgs; end; --[[! Esta función invierte el orden de los argumentos en una lista. Es igual que unpack(reversepack(...)) @param ... Son los argumentos @return Devuelve una lista de valores que serán los argumentos con el orden invertido ]] function invertargs(...) return unpack(reversepack(...)); end; --[[! Igual que pack pero solo empaqueta los últimos valores que anteceden a los n primeros argumentos tomados como argumentos. @param n El número de elementos a empaquetar. Debe ser mayor o igual 1 y menor o igual al número de argumentos (en ese caso sería igual que pack) @param ... Los argumentos a empaquetar. @return Devuelve primero, una lista de valores sin empaquetar, y como último valor, una tabla con los argumentos empaquetados. ]] function reversehalfpack(n, ...) local args = {...}; return invertargs(halfpack(#args-n, invertargs(...))); end; --[[! Empaqueta los argumentos en diferentes grupos(tablas) de tamaño n. @param n Es el tamaño del grupo, mayor o igual que 1. @param ... Es una lista con los argumentos a empaquetar @return Devuelve una lista de tablas donde cada una de estas contiene n elementos. La primera tabla contiene el 1º argumento, el 2º, 3º, hasta el nº argumento. La segunda, el n+1º, n+2º, 2nº, ... Si la lista de argumentos es vacía, se develve nil. Si la lista de argumentos tiene un número de elementos que no es múltiplo de n, el último grupo devuelto no tendrá n elementos; Tendrá los elementos restantes que faltan por empaquetar (que no se han tomado en los otros grupos) Si el número de argumentos pasados como argumento es menor o igual que n, el valor de retorno es igual que pack(...) ]] function makegroups(n, ...) assert(n > 0, "Bad argument to makegroups"); local args = pack(...); local groups = {}; for i=1,#args / n,1 do groups[#groups+1] = {}; end; if (#args % n) ~= 0 then groups[#groups+1] = {}; end; for i=1,#args,1 do local j = math.floor((i-1)/n)+1; local group = groups[j]; group[#group+1] = args[i]; end; return unpack(groups); end; --[[! Empaqueta los argumentos por pares de elementos. Es igual que makegroups con el argumento n igual a 2. @param ... Es una lista de argumentos a empaquetar por pares. @return Devuelve una lista de tablas con los argumentos empaquetados. @see makegroups ]] function makepairs(...) return makegroups(2, ...); end;
--[[! \file \brief Módulo que define una función que permite realizar la operación inversa a unpack: toma una serie de parámetros y los empaqueta en una tabla. ]] --[[! Empaqueta varios valores en una tabla. @param ... Los valores a empaquetar. @return Devuelve una tabla con los valores pasados como argumento tomados en orden en el que se especificaron. ]] function pack(...) return {...}; end; --[[! Igual que pack pero solo empaqueta los n primeros valores tomados como argumentos. @param n El número de elementos a empaquetar. Debe ser mayor o igual 1 y menor o igual al número de argumentos (en ese caso sería igual que pack) @param ... Los argumentos a empaquetar. @return Devuelve como primer valor, una tabla con los n primeros valores empaquetados, y una lista con los valores restantes no empaquetados. ]] function halfpack(n, ...) local args = pack(...); assert((type(n) == "number") and (n >= 1) and (n <= #args)); if n < #args then local packedArgs = {}; local unpackedArgs = {}; for i = 1,n,1 do packedArgs[i] = args[i]; end; for i = n+1,#args,1 do unpackedArgs[i-n] = args[i]; end; return packedArgs, unpack(unpackedArgs); end; return args; end; --[[! Es igual que pack solo que los argumentos se empaquetan en una tabla en orden inverso al especificado ]] function reversepack(...) local args = pack(...); local reversedArgs = {}; for i = 1, #args, 1 do reversedArgs[#args-i+1] = args[i]; end; return reversedArgs; end; --[[! Esta función invierte el orden de los argumentos en una lista. Es igual que unpack(reversepack(...)) @param ... Son los argumentos @return Devuelve una lista de valores que serán los argumentos con el orden invertido ]] function invertargs(...) return unpack(reversepack(...)); end; --[[! Igual que pack pero solo empaqueta los últimos valores que anteceden a los n primeros argumentos tomados como argumentos. @param n El número de elementos a empaquetar. Debe ser mayor o igual 1 y menor o igual al número de argumentos (en ese caso sería igual que pack) @param ... Los argumentos a empaquetar. @return Devuelve primero, una lista de valores sin empaquetar, y como último valor, una tabla con los argumentos empaquetados. ]] function reversehalfpack(n, ...) local args = pack(...); assert((type(n) == "number") and (n >= 1) and (n <= #args)); if n < #args then local packedArgs = {}; local unpackedArgs = {}; for i = 1,n,1 do unpackedArgs[i] = args[i]; end; for i = n+1,#args,1 do packedArgs[i-n] = args[i]; end; unpackedArgs[#unpackedArgs+1] = packedArgs; return unpack(unpackedArgs); end; return args; end; --[[! Empaqueta los argumentos en diferentes grupos(tablas) de tamaño n. @param n Es el tamaño del grupo, mayor o igual que 1. @param ... Es una lista con los argumentos a empaquetar @return Devuelve una lista de tablas donde cada una de estas contiene n elementos. La primera tabla contiene el 1º argumento, el 2º, 3º, hasta el nº argumento. La segunda, el n+1º, n+2º, 2nº, ... Si la lista de argumentos es vacía, se develve nil. Si la lista de argumentos tiene un número de elementos que no es múltiplo de n, el último grupo devuelto no tendrá n elementos; Tendrá los elementos restantes que faltan por empaquetar (que no se han tomado en los otros grupos) Si el número de argumentos pasados como argumento es menor o igual que n, el valor de retorno es igual que pack(...) ]] function makegroups(n, ...) assert(n > 0, "Bad argument to makegroups"); local args = pack(...); local groups = {}; for i=1,#args / n,1 do groups[#groups+1] = {}; end; if (#args % n) ~= 0 then groups[#groups+1] = {}; end; for i=1,#args,1 do local j = math.floor((i-1)/n)+1; local group = groups[j]; group[#group+1] = args[i]; end; return unpack(groups); end; --[[! Empaqueta los argumentos por pares de elementos. Es igual que makegroups con el argumento n igual a 2. @param ... Es una lista de argumentos a empaquetar por pares. @return Devuelve una lista de tablas con los argumentos empaquetados. @see makegroups ]] function makepairs(...) return makegroups(2, ...); end;
Arreglado bug en el módulo util/pack
Arreglado bug en el módulo util/pack
Lua
mit
morfeo642/mta_plr_server
d69a10dd7fb8fea463d25c196550779efceb9aab
mod_muc_restrict_rooms/mod_muc_restrict_rooms.lua
mod_muc_restrict_rooms/mod_muc_restrict_rooms.lua
local st = require "util.stanza"; local nodeprep = require "util.encodings".stringprep.nodeprep; local rooms = module:shared "muc/rooms"; if not rooms then module:log("error", "This module only works on MUC components!"); return; end local admins = module:get_option_set("admins", {}); local restrict_patterns = module:get_option("muc_restrict_matching", {}); local restrict_excepts = module:get_option_set("muc_restrict_exceptions", {}); local restrict_allow_admins = module:get_option_set("muc_restrict_allow_admins", false); local function is_restricted(room, who) -- If admins can join prohibited rooms, we allow them to if (restrict_allow_admins == true) and (admins:contains(who)) then module:log("debug", "Admins are allowed to enter restricted rooms (%s on %s)", who, room) return false; end -- Don't evaluate exceptions if restrict_excepts:contains(room:lower()) then module:log("debug", "Room %s is amongst restriction exceptions", room:lower()) return false; end -- Evaluate regexps of restricted patterns for pattern,reason in pairs(restrict_patterns) do if room:match(pattern) then module:log("debug", "Room %s is restricted by pattern %s, user %s is not allowed to join (%s)", room, pattern, who, reason) return reason; end end return nil end module:hook("presence/full", function(event) local stanza = event.stanza; if stanza.name == "presence" and stanza.attr.type == "unavailable" then -- Leaving events get discarded return; end -- Get the room local room = stanza.attr.from:match("([^@]+)@[^@]+") if not room then return; end -- Get who has tried to join it local who = stanza.attr.to:match("([^\/]+)\/[^\/]+") -- Checking whether room is restricted local check_restricted = is_restricted(room, who) if check_restricted ~= nil then event.allowed = false; event.stanza.attr.type = 'error'; return event.origin.send(st.error_reply(event.stanza, "cancel", "forbidden", "You're not allowed to enter this room: " .. check_restricted)); end end, 10);
local st = require "util.stanza"; local jid = require "util.jid"; local nodeprep = require "util.encodings".stringprep.nodeprep; local rooms = module:shared "muc/rooms"; if not rooms then module:log("error", "This module only works on MUC components!"); return; end local restrict_patterns = module:get_option("muc_restrict_matching", {}); local restrict_excepts = module:get_option_set("muc_restrict_exceptions", {}); local restrict_allow_admins = module:get_option_boolean("muc_restrict_allow_admins", false); local function is_restricted(room, who) -- If admins can join prohibited rooms, we allow them to if restrict_allow_admins and usermanager.is_admin(who, module.host) then module:log("debug", "Admins are allowed to enter restricted rooms (%s on %s)", who, room) return nil; end -- Don't evaluate exceptions if restrict_excepts:contains(room) then module:log("debug", "Room %s is amongst restriction exceptions", room()) return nil; end -- Evaluate regexps of restricted patterns for pattern,reason in pairs(restrict_patterns) do if room:match(pattern) then module:log("debug", "Room %s is restricted by pattern %s, user %s is not allowed to join (%s)", room, pattern, who, reason) return reason; end end return nil end module:hook("presence/full", function(event) local stanza = event.stanza; if stanza.name == "presence" and stanza.attr.type == "unavailable" then -- Leaving events get discarded return; end -- Get the room local room = jid.split(stanza.attr.from); if not room then return; end -- Get who has tried to join it local who = jid.bare(stanza.attr.to) -- Checking whether room is restricted local check_restricted = is_restricted(room, who) if check_restricted ~= nil then event.allowed = false; event.stanza.attr.type = 'error'; return event.origin.send(st.error_reply(event.stanza, "cancel", "forbidden", "You're not allowed to enter this room: " .. check_restricted)); end end, 10);
mod_muc_restrict_rooms: Some fixes based on Matthew's comments + a few more
mod_muc_restrict_rooms: Some fixes based on Matthew's comments + a few more
Lua
mit
Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules
2484f0f3bcf22b7df635912b9ba482522d1bc345
frontend/ui/data/css_tweaks.lua
frontend/ui/data/css_tweaks.lua
--[[-- CSS tweaks must have the following attributes: - id: unique ID identifying this tweak, to be stored in settings - title: menu item title (must not be too long) - css: stylesheet text to append to external stylesheet They may have the following optional attributes: - description: text displayed when holding on menu item - priority: higher numbers are appended after lower numbers (if not specified, default to 0) ]] local _ = require("gettext") local CssTweaks = { { title = _("Page"), { id = "margin_body_0"; title = _("Ignore publisher page margins"), description = _("Force page margins to be 0, and may allow KOReader's margin settings to work on books where they would not."), css = [[body { margin: 0 !important; }]], }, { id = "margin_all_0"; title = _("Ignore all publisher margins"), priority = 2, css = [[* { margin: 0 !important; }]], }, { id = "titles_page-break-before_avoid "; title = _("Avoid blank page on chapter start"), css = [[h1, h2, h3, .title, .title1, .title2, .title3 { page-break-before: avoid !important; }]], }, }, { title = _("Text"), { title = _("Links color and weight"), { id = "a_black"; title = _("Links always black"), css = [[a { color: black !important; }]], }, { id = "a_blue"; title = _("Links always blue"), css = [[a { color: blue !important; }]], separator = true, }, { id = "a_bold"; title = _("Links always bold"), css = [[a { font-weight: bold !important; }]], }, { id = "a_not_bold"; title = _("Links never bold"), css = [[a { font-weight: normal !important; }]], }, }, { title = _("Text alignment"), { id = "text_align_most_left", title = _("Left align most text"), description = _("Enforce left alignment of text in common text elements."), css = [[body, p, li { text-align: left !important; }]], priority = 2, -- so it overrides the justify below }, { id = "text_align_all_left", title = _("Left align all elements"), description = _("Enforce left alignment of text in all elements."), css = [[* { text-align: left !important; }]], priority = 2, -- so it overrides the justify below separator = true, }, { id = "text_align_most_justify", title = _("Justify most text"), description = _("Text justification is the default, but it may be overridden by publisher styles. This will re-enable it for most common text elements."), css = [[body, p, li { text-align: justify !important; }]], }, { id = "text_align_all_justify", title = _("Justify all elements"), description = _("Text justification is the default, but it may be overridden by publisher styles. This will re-enable it for all elements, which may lose centering in some of them."), css = [[* { text-align: justify !important; }]], }, }, { id = "sub_sup_smaller"; title = _("Smaller sub- and superscript"), description = _("Prevent sub- and superscript from affecting line-height."), priority = 5, -- so we can override "font_size_all_inherit" -- https://friendsofepub.github.io/eBookTricks/ -- https://github.com/koreader/koreader/issues/3923#issuecomment-386510294 css = [[ sup { font-size: 50% !important; vertical-align: super !important; } sub { font-size: 50% !important; vertical-align: middle !important; } ]], separator = true, }, { id = "lineheight_all_inherit"; title = _("Ignore publisher line heights"), description = _("Disable line-height specified in embedded styles, and may allow KOReader's line spacing settings to work on books where they would not."), css = [[* { line-height: inherit !important; }]], }, { id = "font_family_all_inherit"; title = _("Ignore publisher font families"), description = _("Disable font-family specified in embedded styles."), -- we have to use this trick, font-family handling by crengine is a bit complex css = [[* { font-family: "NoSuchFont" !important; }]], }, { id = "font_size_all_inherit"; title = _("Ignore publisher font sizes"), description = _("Disable font-size specified in embedded styles."), css = [[* { font-size: inherit !important; }]], separator = true, }, }, { title = _("Miscellaneous"), { id = "table_row_odd_even"; title = _("Alternate background color of table rows"), css = [[ tr:nth-child(odd) { background-color: #EEE !important; } tr:nth-child(even) { background-color: #CCC !important; } ]], }, { id = "table_force_border"; title = _("Show borders on all tables"), css = [[ table, tcaption, tr, th, td { border: black solid 1px; border-collapse: collapse; } ]], separator = true, }, { id = "image_full_width"; title = _("Make images full width"), description = _("Useful for books containing only images, when they are smaller than your screen. May stretch images in some cases."), -- This helped me once with a book. Will mess with aspect ratio -- when images have a style="width: NNpx; heigh: NNpx" css = [[ img { text-align: center !important; text-indent: 0px !important; display: block !important; width: 100% !important; } ]], }, }, -- No current need for workarounds -- { -- title = _("Workarounds"), -- }, } return CssTweaks
--[[-- CSS tweaks must have the following attributes: - id: unique ID identifying this tweak, to be stored in settings - title: menu item title (must not be too long) - css: stylesheet text to append to external stylesheet They may have the following optional attributes: - description: text displayed when holding on menu item - priority: higher numbers are appended after lower numbers (if not specified, default to 0) ]] local _ = require("gettext") local CssTweaks = { { title = _("Page"), { id = "margin_body_0"; title = _("Ignore publisher page margins"), description = _("Force page margins to be 0, and may allow KOReader's margin settings to work on books where they would not."), css = [[body { margin: 0 !important; }]], }, { id = "margin_all_0"; title = _("Ignore all publisher margins"), priority = 2, css = [[* { margin: 0 !important; }]], }, { id = "titles_page-break-before_avoid "; title = _("Avoid blank page on chapter start"), css = [[h1, h2, h3, .title, .title1, .title2, .title3 { page-break-before: avoid !important; }]], }, }, { title = _("Text"), { title = _("Links color and weight"), { id = "a_black"; title = _("Links always black"), css = [[a { color: black !important; }]], }, { id = "a_blue"; title = _("Links always blue"), css = [[a { color: blue !important; }]], separator = true, }, { id = "a_bold"; title = _("Links always bold"), css = [[a { font-weight: bold !important; }]], }, { id = "a_not_bold"; title = _("Links never bold"), css = [[a { font-weight: normal !important; }]], }, }, { title = _("Text alignment"), { id = "text_align_most_left", title = _("Left align most text"), description = _("Enforce left alignment of text in common text elements."), css = [[body, p, li { text-align: left !important; }]], priority = 2, -- so it overrides the justify below }, { id = "text_align_all_left", title = _("Left align all elements"), description = _("Enforce left alignment of text in all elements."), css = [[* { text-align: left !important; }]], priority = 2, -- so it overrides the justify below separator = true, }, { id = "text_align_most_justify", title = _("Justify most text"), description = _("Text justification is the default, but it may be overridden by publisher styles. This will re-enable it for most common text elements."), css = [[body, p, li { text-align: justify !important; }]], }, { id = "text_align_all_justify", title = _("Justify all elements"), description = _("Text justification is the default, but it may be overridden by publisher styles. This will re-enable it for all elements, which may lose centering in some of them."), css = [[* { text-align: justify !important; }]], }, }, { id = "hyphenate_all_auto"; title = _("Allow hyphenation on all text"), description = _("Allow hyphenation to happen on all text (except headings), in case the publisher has disabled it."), css = [[ * { hyphenate: auto !important; } h1, h2, h3, h4, h5, h6 { hyphenate: none !important; } ]], }, { id = "sub_sup_smaller"; title = _("Smaller sub- and superscript"), description = _("Prevent sub- and superscript from affecting line-height."), priority = 5, -- so we can override "font_size_all_inherit" -- https://friendsofepub.github.io/eBookTricks/ -- https://github.com/koreader/koreader/issues/3923#issuecomment-386510294 css = [[ sup { font-size: 50% !important; vertical-align: super !important; } sub { font-size: 50% !important; vertical-align: sub !important; } ]], separator = true, }, { id = "lineheight_all_inherit"; title = _("Ignore publisher line heights"), description = _("Disable line-height specified in embedded styles, and may allow KOReader's line spacing settings to work on books where they would not."), css = [[* { line-height: inherit !important; }]], }, { id = "font_family_all_inherit"; title = _("Ignore publisher font families"), description = _("Disable font-family specified in embedded styles."), -- we have to use this trick, font-family handling by crengine is a bit complex css = [[* { font-family: "NoSuchFont" !important; }]], }, { id = "font_size_all_inherit"; title = _("Ignore publisher font sizes"), description = _("Disable font-size specified in embedded styles."), css = [[* { font-size: inherit !important; }]], separator = true, }, }, { title = _("Miscellaneous"), { id = "table_row_odd_even"; title = _("Alternate background color of table rows"), css = [[ tr:nth-child(odd) { background-color: #EEE !important; } tr:nth-child(even) { background-color: #CCC !important; } ]], }, { id = "table_force_border"; title = _("Show borders on all tables"), css = [[ table, tcaption, tr, th, td { border: black solid 1px; border-collapse: collapse; } ]], separator = true, }, { id = "image_full_width"; title = _("Make images full width"), description = _("Useful for books containing only images, when they are smaller than your screen. May stretch images in some cases."), -- This helped me once with a book. Will mess with aspect ratio -- when images have a style="width: NNpx; heigh: NNpx" css = [[ img { text-align: center !important; text-indent: 0px !important; display: block !important; width: 100% !important; } ]], }, }, -- No current need for workarounds -- { -- title = _("Workarounds"), -- }, } return CssTweaks
Style tweaks: adds Allow hyphenation on all text (#4047)
Style tweaks: adds Allow hyphenation on all text (#4047) Also fix vertical-align for sub in 'Smaller sub- and superscript'
Lua
agpl-3.0
poire-z/koreader,mwoz123/koreader,pazos/koreader,mihailim/koreader,Markismus/koreader,houqp/koreader,poire-z/koreader,koreader/koreader,Frenzie/koreader,NiLuJe/koreader,Frenzie/koreader,NiLuJe/koreader,Hzj-jie/koreader,koreader/koreader
80c07b040d5bd45b16dd188f5c01bda1adb1d334
src_trunk/resources/realism-system/s_reload.lua
src_trunk/resources/realism-system/s_reload.lua
local noReloadGuns = { [25]=true, [33]=true, [34]=true, [35]=true, [36]=true, [37]=true } function reloadWeapon(thePlayer) local weapon = getPlayerWeapon(thePlayer) local ammo = getPlayerTotalAmmo(thePlayer) local reloading = getElementData(thePlayer, "reloading") local jammed = getElementData(thePlayer, "jammed") if (reloading==false) and not (isPedInVehicle(thePlayer)) and ((jammed==0) or not jammed) then if (weapon) and (ammo) then if (weapon>21) and (weapon<35) and not (noReloadGuns[weapon]) then toggleControl(thePlayer, "fire", false) toggleControl(thePlayer, "next_weapon", false) toggleControl(thePlayer, "previous_weapon", false) setElementData(thePlayer, "reloading", true) setTimer(checkFalling, 100, 10, thePlayer) if not (isPedDucked(thePlayer)) then setPedAnimation(thePlayer, "BUDDY", "buddy_reload", 1000, false, false, false) end setTimer(giveReload, 1001, 1, thePlayer, weapon, ammo) triggerClientEvent(thePlayer, "cleanupUI", thePlayer) end end end end addCommandHandler("reload", reloadWeapon) function checkFalling(thePlayer) local reloading = getElementData(thePlayer, "reloading") if not (isPedOnGround(thePlayer)) and (reloading) then setElementData(thePlayer, "reloading.timer", nil) -- reset state setElementData(thePlayer, "reloading.timer", nil) setPedAnimation(thePlayer) setElementData(thePlayer, "reloading", false) toggleControl(thePlayer, "fire", true) toggleControl(thePlayer, "next_weapon", true) toggleControl(thePlayer, "previous_weapon", true) end end function giveReload(thePlayer, weapon, ammo) setElementData(thePlayer, "reloading.timer", nil) setPedAnimation(thePlayer) takeWeapon(thePlayer, weapon) giveWeapon(thePlayer, weapon, ammo, true) setElementData(thePlayer, "reloading", false) toggleControl(thePlayer, "fire", true) toggleControl(thePlayer, "next_weapon", true) toggleControl(thePlayer, "previous_weapon", true) exports.global:givePlayerAchievement(thePlayer, 14) exports.global:sendLocalMeAction(thePlayer, "reloads their " .. getWeaponNameFromID(weapon) .. ".") end -- Bind Keys required function bindKeys() local players = exports.pool:getPoolElementsByType("player") for k, arrayPlayer in ipairs(players) do if not(isKeyBound(arrayPlayer, "r", "down", reloadWeapon)) then bindKey(arrayPlayer, "r", "down", reloadWeapon) end end end function bindKeysOnJoin() bindKey(source, "r", "down", reloadWeapon) end addEventHandler("onResourceStart", getRootElement(), bindKeys) addEventHandler("onPlayerJoin", getRootElement(), bindKeysOnJoin) function giveFakeBullet(weapon, ammo) setWeaponAmmo(source, weapon, ammo, 1) end addEvent("addFakeBullet", true) addEventHandler("addFakeBullet", getRootElement(), giveFakeBullet) function giveWeaponAmmoOnSwitch(weapon, ammo, ammoInClip) setWeaponAmmo(source, weapon, ammo, ammoInClip) -- weapon skill fixes setPedStat(source, 77, 999) setPedStat(source, 78, 999) setPedStat(source, 71, 999) setPedStat(source, 72, 999) end addEvent("giveWeaponOnSwitch", true) addEventHandler("giveWeaponOnSwitch", getRootElement(), giveWeaponAmmoOnSwitch)
local noReloadGuns = { [25]=true, [33]=true, [34]=true, [35]=true, [36]=true, [37]=true } function reloadWeapon(thePlayer) local weapon = getPlayerWeapon(thePlayer) local ammo = getPlayerTotalAmmo(thePlayer) local reloading = getElementData(thePlayer, "reloading") local jammed = getElementData(thePlayer, "jammed") if (reloading==false) and not (isPedInVehicle(thePlayer)) and ((jammed==0) or not jammed) then if (weapon) and (ammo) then if (weapon>21) and (weapon<35) and not (noReloadGuns[weapon]) then toggleControl(thePlayer, "fire", false) toggleControl(thePlayer, "next_weapon", false) toggleControl(thePlayer, "previous_weapon", false) setElementData(thePlayer, "reloading", true) setTimer(checkFalling, 100, 10, thePlayer) if not (isPedDucked(thePlayer)) then exports.global:applyAnimation(thePlayer, "BUDDY", "buddy_reload", 1000, false, false) end setTimer(giveReload, 1001, 1, thePlayer, weapon, ammo) triggerClientEvent(thePlayer, "cleanupUI", thePlayer) end end end end addCommandHandler("reload", reloadWeapon) function checkFalling(thePlayer) local reloading = getElementData(thePlayer, "reloading") if not (isPedOnGround(thePlayer)) and (reloading) then setElementData(thePlayer, "reloading.timer", nil) -- reset state setElementData(thePlayer, "reloading.timer", nil) exports.global:removeAnimation(thePlayer) setElementData(thePlayer, "reloading", false) toggleControl(thePlayer, "fire", true) toggleControl(thePlayer, "next_weapon", true) toggleControl(thePlayer, "previous_weapon", true) end end function giveReload(thePlayer, weapon, ammo) setElementData(thePlayer, "reloading.timer", nil) exports.global:removeAnimation(thePlayer) takeWeapon(thePlayer, weapon) giveWeapon(thePlayer, weapon, ammo, true) setElementData(thePlayer, "reloading", false) toggleControl(thePlayer, "fire", true) toggleControl(thePlayer, "next_weapon", true) toggleControl(thePlayer, "previous_weapon", true) exports.global:givePlayerAchievement(thePlayer, 14) exports.global:sendLocalMeAction(thePlayer, "reloads their " .. getWeaponNameFromID(weapon) .. ".") end -- Bind Keys required function bindKeys() local players = exports.pool:getPoolElementsByType("player") for k, arrayPlayer in ipairs(players) do if not(isKeyBound(arrayPlayer, "r", "down", reloadWeapon)) then bindKey(arrayPlayer, "r", "down", reloadWeapon) end end end function bindKeysOnJoin() bindKey(source, "r", "down", reloadWeapon) end addEventHandler("onResourceStart", getRootElement(), bindKeys) addEventHandler("onPlayerJoin", getRootElement(), bindKeysOnJoin) function giveFakeBullet(weapon, ammo) setWeaponAmmo(source, weapon, ammo, 1) end addEvent("addFakeBullet", true) addEventHandler("addFakeBullet", getRootElement(), giveFakeBullet) function giveWeaponAmmoOnSwitch(weapon, ammo, ammoInClip) setWeaponAmmo(source, weapon, ammo, ammoInClip) -- weapon skill fixes setPedStat(source, 77, 999) setPedStat(source, 78, 999) setPedStat(source, 71, 999) setPedStat(source, 72, 999) end addEvent("giveWeaponOnSwitch", true) addEventHandler("giveWeaponOnSwitch", getRootElement(), giveWeaponAmmoOnSwitch)
Animation fix for reloading
Animation fix for reloading git-svn-id: 8769cb08482c9977c94b72b8e184ec7d2197f4f7@185 64450a49-1f69-0410-a0a2-f5ebb52c4f5b
Lua
bsd-3-clause
valhallaGaming/uno,valhallaGaming/uno,valhallaGaming/uno
e7d3d73fa2d39af177fd0f5b9e1b7717cf39a850
util/dataforms.lua
util/dataforms.lua
local setmetatable = setmetatable; local pairs, ipairs = pairs, ipairs; local st = require "util.stanza"; module "dataforms" local xmlns_forms = 'jabber:x:data'; local form_t = {}; local form_mt = { __index = form_t }; function new(layout) return setmetatable(layout, form_mt); end local form_x_attr = { xmlns = xmlns_forms }; function form_t.form(layout, data) local form = st.stanza("x", form_x_attr); if layout.title then form:tag("title"):text(layout.title):up(); end if layout.instructions then form:tag("instructions"):text(layout.instructions):up(); end for n, field in ipairs(layout) do local field_type = field.type or "text-single"; -- Add field tag form:tag("field", { type = field_type, var = field.name, label = field.label }); local value = data[field.name]; -- Add value, depending on type if field_type == "hidden" then if type(value) == "table" then -- Assume an XML snippet form:add_child(value); elseif value then form:tag("value"):text(tostring(value)); end elseif field_type == "boolean" then form:tag("value"):text((value and "1") or "0"):up(); elseif field_type == "fixed" then elseif field_type == "jid-multi" then for _, jid in ipairs(value) do form:tag("value"):text(jid):up(); end elseif field_type == "jid-single" then form:tag("value"):text(value):up(); elseif field_type == "text-single" or field_type == "text-private" then form:tag("value"):text(value):up(); elseif field_type == "text-multi" then -- Split into multiple <value> tags, one for each line for line in value:gmatch("([^\r\n]+)\r?\n*") do form:tag("value"):text(line):up(); end end if field.required then form:tag("required"):up(); end -- Jump back up to list of fields form:up(); end return form; end function form_t.data(layout, stanza) end return _M; --[=[ Layout: { title = "MUC Configuration", instructions = [[Use this form to configure options for this MUC room.]], { name = "FORM_TYPE", type = "hidden", required = true }; { name = "field-name", type = "field-type", required = false }; } --]=]
local setmetatable = setmetatable; local pairs, ipairs = pairs, ipairs; local tostring, type = tostring, type; local t_concat = table.concat; local st = require "util.stanza"; module "dataforms" local xmlns_forms = 'jabber:x:data'; local form_t = {}; local form_mt = { __index = form_t }; function new(layout) return setmetatable(layout, form_mt); end local form_x_attr = { xmlns = xmlns_forms }; function form_t.form(layout, data) local form = st.stanza("x", form_x_attr); if layout.title then form:tag("title"):text(layout.title):up(); end if layout.instructions then form:tag("instructions"):text(layout.instructions):up(); end for n, field in ipairs(layout) do local field_type = field.type or "text-single"; -- Add field tag form:tag("field", { type = field_type, var = field.name, label = field.label }); local value = data[field.name]; -- Add value, depending on type if field_type == "hidden" then if type(value) == "table" then -- Assume an XML snippet form:tag("value") :add_child(value) :up(); elseif value then form:tag("value"):text(tostring(value)):up(); end elseif field_type == "boolean" then form:tag("value"):text((value and "1") or "0"):up(); elseif field_type == "fixed" then elseif field_type == "jid-multi" then for _, jid in ipairs(value) do form:tag("value"):text(jid):up(); end elseif field_type == "jid-single" then form:tag("value"):text(value):up(); elseif field_type == "text-single" or field_type == "text-private" then form:tag("value"):text(value):up(); elseif field_type == "text-multi" then -- Split into multiple <value> tags, one for each line for line in value:gmatch("([^\r\n]+)\r?\n*") do form:tag("value"):text(line):up(); end end if field.required then form:tag("required"):up(); end -- Jump back up to list of fields form:up(); end return form; end function form_t.data(layout, stanza) end return _M; --[=[ Layout: { title = "MUC Configuration", instructions = [[Use this form to configure options for this MUC room.]], { name = "FORM_TYPE", type = "hidden", required = true }; { name = "field-name", type = "field-type", required = false }; } --]=]
util.dataforms: Fixes for hidden field type
util.dataforms: Fixes for hidden field type
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
539a4a29ddc142f19357d8b5bad5c98753b92b0d
yoshi/node.lua
yoshi/node.lua
gl.setup(NATIVE_WIDTH/2, NATIVE_HEIGHT/2) local r = util.auto_loader() local function mk_sprite(s) s.y = (s.y + 256) * 2 return s end local sprites = { mk_sprite{img="oam20", x=0, y=-256, z=-30}, -- big mountain mk_sprite{img="oam22", x=0, y=-170, z=-30}, -- house big mountain mk_sprite{img="oam24", x=35, y=-256, z=-40}, mk_sprite{img="oam24", x=35, y=-256, z=0}, mk_sprite{img="oam24", x=-20, y=-256, z=-60}, -- mountain mk_sprite{img="oam8", x=-40, y=-256, z=0}, mk_sprite{img="oam8", x=20, y=-256, z=-70}, -- green talus mk_sprite{img="oam3", x=-40, y=-256, z=-25}, -- red tower mk_sprite{img="oam51", x=-40, y=-256, z=-25, gr=1}, -- ground mk_sprite{img="oam5", x=-25, y=-256, z=-95}, -- volcano mk_sprite{img="oam32", x=60, y=-256, z=-60}, mk_sprite{img="oam32", x=50, y=-256, z=40}, mk_sprite{img="oam32", x=-40, y=-256, z=40}, -- hill mk_sprite{img="oam19", x=80, y=-256, z=-70}, mk_sprite{img="oam19", x=80, y=-256, z=-40}, mk_sprite{img="oam19", x=60, y=-256, z=60}, mk_sprite{img="oam19", x=-60, y=-256, z=50}, mk_sprite{img="oam19", x=-60, y=-256, z=20}, -- small hill mk_sprite{img="oam52", x=80, y=-256, z=-70, gr=1}, mk_sprite{img="oam52", x=60, y=-256, z=60, gr=1}, mk_sprite{img="oam52", x=-60, y=-256, z=50, gr=1}, -- green ground mk_sprite{img="oam14", x=50, y=-256, z=-20}, -- grey donjon mk_sprite{img="oam51", x=50, y=-256, z=-20, gr=1}, -- ground mk_sprite{img="oam14", x=0, y=-256, z=10}, -- grey donjon mk_sprite{img="oam50", x=0, y=-256, z=10, gr=1}, -- castle water mk_sprite{img="oam11", x=-12, y=-256, z=10}, mk_sprite{img="oam11", x=12, y=-256, z=10}, mk_sprite{img="oam11", x=0, y=-256, z=-2}, mk_sprite{img="oam11", x=0, y=-256, z=22}, -- grey towers mk_sprite{img="oam28", x=60, y=-256, z=15}, -- towers with red roof mk_sprite{img="oam17", x=50, y=-256, z=-80}, -- dolmen mk_sprite{img="oam25", x=65, y=-256, z=30}, mk_sprite{img="oam25", x=85, y=-256, z=30}, mk_sprite{img="oam25", x=70, y=-256, z=10}, mk_sprite{img="oam25", x=70, y=-256, z=-20}, -- oranges mk_sprite{img="oam10", x=0, y=-200, z=-70}, mk_sprite{img="oam10", x=20, y=-180, z=-70}, mk_sprite{img="oam10", x=40, y=-170, z=-50}, mk_sprite{img="oam10", x=40, y=-190, z=-30}, -- cloud mk_sprite{img="oam35", x=-50, y=-160, z=-10}, -- cloud castle mk_sprite{img="oam2", x=-65, y=-256, z=-50}, mk_sprite{img="oam2", x=-45, y=-256, z=-50}, mk_sprite{img="oam2", x=-40, y=-256, z=-70}, mk_sprite{img="oam2", x=-65, y=-256, z=-30}, mk_sprite{img="oam2", x=-80, y=-256, z=-80}, mk_sprite{img="oam2", x=-80, y=-256, z=-20}, mk_sprite{img="oam2", x=-90, y=-256, z=0}, -- fir mk_sprite{img="oam1", x=-60, y=-256, z=-40}, mk_sprite{img="oam1", x=-90, y=-256, z=-40}, mk_sprite{img="oam1", x=-100, y=-256, z=-20}, mk_sprite{img="oam1", x=-90, y=-256, z=-60}, mk_sprite{img="oam1", x=-40, y=-256, z=-80}, mk_sprite{img="oam1", x=-60, y=-256, z=-60}, mk_sprite{img="oam1", x=-60, y=-256, z=-90}, -- small fir mk_sprite{img="oam23", x=60, y=-256, z=-40}, mk_sprite{img="oam23", x=60, y=-256, z=-30}, mk_sprite{img="oam23", x=60, y=-256, z=-90}, mk_sprite{img="oam23", x=70, y=-256, z=-90}, mk_sprite{img="oam23", x=50, y=-256, z=-95}, mk_sprite{img="oam23", x=90, y=-256, z=-40},-- flower mk_sprite{img="oam23", x=95, y=-256, z=-50}, mk_sprite{img="oam23", x=95, y=-256, z=-30}, mk_sprite{img="oam23", x=80, y=-256, z=-20}, mk_sprite{img="oam23", x=80, y=-256, z=-10}, mk_sprite{img="oam23", x=100, y=-256, z=-10}, mk_sprite{img="oam23", x=100, y=-256, z=0}, -- flower mk_sprite{img="oam6", x=30, y=-256, z=30}, mk_sprite{img="oam6", x=20, y=-256, z=40}, mk_sprite{img="oam6", x=20, y=-256, z=60}, mk_sprite{img="oam6", x=-20, y=-256, z=30}, mk_sprite{img="oam6", x=-20, y=-256, z=50}, mk_sprite{img="oam6", x=-30, y=-256, z=60}, mk_sprite{img="oam6", x=-10, y=-256, z=90}, -- tree mk_sprite{img="oam9", x=30, y=-256, z=45}, mk_sprite{img="oam9", x=35, y=-256, z=60}, mk_sprite{img="oam9", x=45, y=-256, z=70}, mk_sprite{img="oam9", x=50, y=-256, z=90}, mk_sprite{img="oam9", x=-20, y=-256, z=90}, mk_sprite{img="oam9", x=-15, y=-256, z=70}, mk_sprite{img="oam9", x=-10, y=-256, z=35}, -- small tree mk_sprite{img="oam16", x=0, y=-256, z=30}, mk_sprite{img="oam16", x=0, y=-256, z=40}, mk_sprite{img="oam16", x=0, y=-256, z=50}, mk_sprite{img="oam16", x=0, y=-256, z=60}, mk_sprite{img="oam16", x=0, y=-256, z=70}, -- plots mk_sprite{img="oam4", x=-25, y=-220, z=-95, mz=20}, mk_sprite{img="oam4", x=-25, y=-210, z=-95, mz=20}, -- volcano smoke mk_sprite{img="oam33", x=-10, y=-172, z=-23}, mk_sprite{img="oam33", x=-15, y=-169, z=-21}, mk_sprite{img="oam33", x=-20, y=-166, z=-19}, mk_sprite{img="oam33", x=-25, y=-163, z=-17}, mk_sprite{img="oam33", x=-30, y=-160, z=-15}, -- chain mk_sprite{img="oam38", x=20, y=-200, z=40, mz=2}, -- seagull mk_sprite{img="oam18", x=20, y=-256, z=50} -- Yoshi } for i = 1, 30 do local r = math.random() * 120 local a = math.random() * math.pi * 2 sprites[#sprites+1] = mk_sprite{ img = "oam27", x = r * math.cos(a), y = -256, z = r * math.sin(a), } end local function prepare() for i = 1, #sprites do local s = sprites[i] local img = r[s.img] if not s.sw then if img:state() == "loaded" then s.sw, s.sh = img:size() if s.gr then s.sh = s.sh / 1.5 end else return false end end end return true end local function update() local now = sys.now() local sin = math.sin(now) local cos = math.cos(now) local cx = WIDTH / 2 local cy = HEIGHT / 1.5 for i = 1, #sprites do local s = sprites[i] local img = r[s.img] local x = (s.x * cos - s.z * sin) * 2.5 local z = (s.z * cos + s.x * sin) * 2.5 local step_y = 0 if s.mz then step_y = math.floor((now * 60) % s.mz) * 2 end s.draw_x = cx + x - s.sw/2 s.draw_y = cy - s.y - s.sh - z/3 - step_y s.z_index = z + i*0.01 if s.gr then s.z_index = 100000 s.draw_y = s.draw_y + s.sh/2 end end table.sort(sprites, function(s1, s2) return s1.z_index > s2.z_index end) end local function draw() for i = 1, #sprites do local s = sprites[i] r[s.img]:draw(s.draw_x, s.draw_y, s.draw_x + s.sw, s.draw_y + s.sh) end end -- r.map = resource.create_colored_texture(1, 0, 0, 1) function node.render() gl.clear(0, 0, 0, 0) local lft = (sys.now() * 90) % WIDTH r.map:draw(-lft, HEIGHT/5, -lft + WIDTH, HEIGHT/5*2) r.map:draw(-lft + WIDTH, HEIGHT/5, -lft + WIDTH*2, HEIGHT/5*2) if prepare() then update() draw() end end
gl.setup(NATIVE_WIDTH/2, NATIVE_HEIGHT/2) local r = util.auto_loader() local function mk_sprite(s) s.y = (s.y + 256) * 2 return s end local sprites = { mk_sprite{img="oam20", x=0, y=-256, z=-30}, -- big mountain mk_sprite{img="oam22", x=0, y=-170, z=-30}, -- house big mountain mk_sprite{img="oam24", x=35, y=-256, z=-40}, mk_sprite{img="oam24", x=35, y=-256, z=0}, mk_sprite{img="oam24", x=-20, y=-256, z=-60}, -- mountain mk_sprite{img="oam8", x=-40, y=-256, z=0}, mk_sprite{img="oam8", x=20, y=-256, z=-70}, -- green talus mk_sprite{img="oam3", x=-40, y=-256, z=-25}, -- red tower mk_sprite{img="oam51", x=-40, y=-256, z=-25, gr=1}, -- ground mk_sprite{img="oam5", x=-25, y=-256, z=-95}, -- volcano mk_sprite{img="oam32", x=60, y=-256, z=-60}, mk_sprite{img="oam32", x=50, y=-256, z=40}, mk_sprite{img="oam32", x=-40, y=-256, z=40}, -- hill mk_sprite{img="oam19", x=80, y=-256, z=-70}, mk_sprite{img="oam19", x=80, y=-256, z=-40}, mk_sprite{img="oam19", x=60, y=-256, z=60}, mk_sprite{img="oam19", x=-60, y=-256, z=50}, mk_sprite{img="oam19", x=-60, y=-256, z=20}, -- small hill mk_sprite{img="oam52", x=80, y=-256, z=-70, gr=1}, mk_sprite{img="oam52", x=60, y=-256, z=60, gr=1}, mk_sprite{img="oam52", x=-60, y=-256, z=50, gr=1}, -- green ground mk_sprite{img="oam14", x=50, y=-256, z=-20}, -- grey donjon mk_sprite{img="oam51", x=50, y=-256, z=-20, gr=1}, -- ground mk_sprite{img="oam14", x=0, y=-256, z=10}, -- grey donjon mk_sprite{img="oam50", x=0, y=-256, z=10, gr=1}, -- castle water mk_sprite{img="oam11", x=-12, y=-256, z=10}, mk_sprite{img="oam11", x=12, y=-256, z=10}, mk_sprite{img="oam11", x=0, y=-256, z=-2}, mk_sprite{img="oam11", x=0, y=-256, z=22}, -- grey towers mk_sprite{img="oam28", x=60, y=-256, z=15}, -- towers with red roof mk_sprite{img="oam17", x=50, y=-256, z=-80}, -- dolmen mk_sprite{img="oam25", x=65, y=-256, z=30}, mk_sprite{img="oam25", x=85, y=-256, z=30}, mk_sprite{img="oam25", x=70, y=-256, z=10}, mk_sprite{img="oam25", x=70, y=-256, z=-20}, -- oranges mk_sprite{img="oam10", x=0, y=-200, z=-70}, mk_sprite{img="oam10", x=20, y=-180, z=-70}, mk_sprite{img="oam10", x=40, y=-170, z=-50}, mk_sprite{img="oam10", x=40, y=-190, z=-30}, -- cloud mk_sprite{img="oam35", x=-50, y=-160, z=-10}, -- cloud castle mk_sprite{img="oam2", x=-65, y=-256, z=-50}, mk_sprite{img="oam2", x=-45, y=-256, z=-50}, mk_sprite{img="oam2", x=-40, y=-256, z=-70}, mk_sprite{img="oam2", x=-65, y=-256, z=-30}, mk_sprite{img="oam2", x=-80, y=-256, z=-80}, mk_sprite{img="oam2", x=-80, y=-256, z=-20}, mk_sprite{img="oam2", x=-90, y=-256, z=0}, -- fir mk_sprite{img="oam1", x=-60, y=-256, z=-40}, mk_sprite{img="oam1", x=-90, y=-256, z=-40}, mk_sprite{img="oam1", x=-100, y=-256, z=-20}, mk_sprite{img="oam1", x=-90, y=-256, z=-60}, mk_sprite{img="oam1", x=-40, y=-256, z=-80}, mk_sprite{img="oam1", x=-60, y=-256, z=-60}, mk_sprite{img="oam1", x=-60, y=-256, z=-90}, -- small fir mk_sprite{img="oam23", x=60, y=-256, z=-40}, mk_sprite{img="oam23", x=60, y=-256, z=-30}, mk_sprite{img="oam23", x=60, y=-256, z=-90}, mk_sprite{img="oam23", x=70, y=-256, z=-90}, mk_sprite{img="oam23", x=50, y=-256, z=-95}, mk_sprite{img="oam23", x=90, y=-256, z=-40},-- flower mk_sprite{img="oam23", x=95, y=-256, z=-50}, mk_sprite{img="oam23", x=95, y=-256, z=-30}, mk_sprite{img="oam23", x=80, y=-256, z=-20}, mk_sprite{img="oam23", x=80, y=-256, z=-10}, mk_sprite{img="oam23", x=100, y=-256, z=-10}, mk_sprite{img="oam23", x=100, y=-256, z=0}, -- flower mk_sprite{img="oam6", x=30, y=-256, z=30}, mk_sprite{img="oam6", x=20, y=-256, z=40}, mk_sprite{img="oam6", x=20, y=-256, z=60}, mk_sprite{img="oam6", x=-20, y=-256, z=30}, mk_sprite{img="oam6", x=-20, y=-256, z=50}, mk_sprite{img="oam6", x=-30, y=-256, z=60}, mk_sprite{img="oam6", x=-10, y=-256, z=90}, -- tree mk_sprite{img="oam9", x=30, y=-256, z=45}, mk_sprite{img="oam9", x=35, y=-256, z=60}, mk_sprite{img="oam9", x=45, y=-256, z=70}, mk_sprite{img="oam9", x=50, y=-256, z=90}, mk_sprite{img="oam9", x=-20, y=-256, z=90}, mk_sprite{img="oam9", x=-15, y=-256, z=70}, mk_sprite{img="oam9", x=-10, y=-256, z=35}, -- small tree mk_sprite{img="oam16", x=0, y=-256, z=30}, mk_sprite{img="oam16", x=0, y=-256, z=40}, mk_sprite{img="oam16", x=0, y=-256, z=50}, mk_sprite{img="oam16", x=0, y=-256, z=60}, mk_sprite{img="oam16", x=0, y=-256, z=70}, -- plots mk_sprite{img="oam4", x=-25, y=-220, z=-95, mz=20}, mk_sprite{img="oam4", x=-25, y=-210, z=-95, mz=20}, -- volcano smoke mk_sprite{img="oam33", x=-10, y=-172, z=-23}, mk_sprite{img="oam33", x=-15, y=-169, z=-21}, mk_sprite{img="oam33", x=-20, y=-166, z=-19}, mk_sprite{img="oam33", x=-25, y=-163, z=-17}, mk_sprite{img="oam33", x=-30, y=-160, z=-15}, -- chain mk_sprite{img="oam38", x=20, y=-200, z=40, mz=2}, -- seagull mk_sprite{img="oam18", x=20, y=-256, z=50} -- Yoshi } for i = 1, 30 do local r = math.random() * 120 local a = math.random() * math.pi * 2 sprites[#sprites+1] = mk_sprite{ img = "oam27", x = r * math.cos(a), y = -256, z = r * math.sin(a), } end local function prepare() for i = 1, #sprites do local s = sprites[i] local img = r[s.img] if not s.sw then local w, h = img:size() if w > 1 and h > 1 then s.sw, s.sh = w, h if s.gr then s.sh = s.sh / 1.5 end else return false end end end return true end local function update() local now = sys.now() local sin = math.sin(now) local cos = math.cos(now) local cx = WIDTH / 2 local cy = HEIGHT / 1.5 for i = 1, #sprites do local s = sprites[i] local img = r[s.img] local x = (s.x * cos - s.z * sin) * 2.5 local z = (s.z * cos + s.x * sin) * 2.5 local step_y = 0 if s.mz then step_y = math.floor((now * 60) % s.mz) * 2 end s.draw_x = cx + x - s.sw/2 s.draw_y = cy - s.y - s.sh - z/3 - step_y s.z_index = z + i*0.01 if s.gr then s.z_index = 100000 s.draw_y = s.draw_y + s.sh/2 end end table.sort(sprites, function(s1, s2) return s1.z_index > s2.z_index end) end local function draw() for i = 1, #sprites do local s = sprites[i] r[s.img]:draw(s.draw_x, s.draw_y, s.draw_x + s.sw, s.draw_y + s.sh) end end -- r.map = resource.create_colored_texture(1, 0, 0, 1) function node.render() gl.clear(0, 0, 0, 0) local lft = (sys.now() * 90) % WIDTH r.map:draw(-lft, HEIGHT/5, -lft + WIDTH, HEIGHT/5*2) r.map:draw(-lft + WIDTH, HEIGHT/5, -lft + WIDTH*2, HEIGHT/5*2) if prepare() then update() draw() end end
Fixed detection of loaded images.
Fixed detection of loaded images. state == "loaded" was not correct, since the autoloader uses dummy 1x1 images for all images that are not loaded yet.
Lua
bsd-2-clause
dividuum/info-beamer-nodes,dividuum/info-beamer-nodes
4764cfad5c250e947994e3e5ec05bbbdc149fa12
quest/explorerguild_320_questlog.lua
quest/explorerguild_320_questlog.lua
-- INSERT INTO "quests" ("qst_id", "qst_script") VALUES (230, 'quest.explorerguild_320_questlog'); require("base.common") module("quest.explorerguild_320_questlog", package.seeall) GERMAN = Player.german ENGLISH = Player.english -- Insert the quest title here, in both languages Title = {} Title[GERMAN] = "Abenteurergilde" Title[ENGLISH] = "Explorerguild" -- For each status insert a list of positions where the quest will continue, i.e. a new status can be reached there QuestTarget = {} -- Insert the quest status which is reached at the end of the quest FINAL_QUEST_STATUS = 3 function QuestTitle(user) return base.common.GetNLS(user, Title[GERMAN], Title[ENGLISH]) end function QuestDescription(user, status) local german = "Du hast bereits "..quest.explorerguild.CoutStones(user).." Markierungssteine der Abenteurergilde gefunden. Weiter so!" local english = "You already found "..quest.explorerguild.CoutStones(user).." marker stones of the explorerguild. Keep it up!" return base.common.GetNLS(user, german, english) end function QuestTargets(user, status) return QuestTarget[status] end function QuestFinalStatus() return FINAL_QUEST_STATUS end
-- INSERT INTO "quests" ("qst_id", "qst_script") VALUES (230, 'quest.explorerguild_320_questlog'); require("base.common") require("quest.explorersguild") module("quest.explorerguild_320_questlog", package.seeall) GERMAN = Player.german ENGLISH = Player.english -- Insert the quest title here, in both languages Title = {} Title[GERMAN] = "Abenteurergilde" Title[ENGLISH] = "Explorersguild" -- For each status insert a list of positions where the quest will continue, i.e. a new status can be reached there QuestTarget = {} -- Insert the quest status which is reached at the end of the quest FINAL_QUEST_STATUS = 3 function QuestTitle(user) return base.common.GetNLS(user, Title[GERMAN], Title[ENGLISH]) end function QuestDescription(user, status) local german = "Du hast bereits "..quest.explorersguild.CoutStones(user).." Markierungssteine der Abenteurergilde gefunden. Weiter so!" local english = "You already found "..quest.explorersguild.CoutStones(user).." marker stones of the explorersguild. Keep it up!" return base.common.GetNLS(user, german, english) end function QuestTargets(user, status) return QuestTarget[status] end function QuestFinalStatus() return FINAL_QUEST_STATUS end
require fix
require fix
Lua
agpl-3.0
Illarion-eV/Illarion-Content,KayMD/Illarion-Content,vilarion/Illarion-Content,LaFamiglia/Illarion-Content,Baylamon/Illarion-Content
b5cbd2b1a7eb35489d73ac97527db622bf08ab66
scripts/thistle_custom.lua
scripts/thistle_custom.lua
-- -- To run: -- Copy a recipe from the output of the Thistle Mode -- Update expected_gardens equal to the number you have opened and pinned -- Gardens must all have their buttons visible, can overlap as long as the -- row with "asc" is visible regardlesss of which window was clicked last -- Update "last sun" to be what it is now (0 if night, -- 99 if daylight and open lid, 33 if daylight and closed lid) -- dofile("screen_reader_common.inc"); dofile("ui_utils.inc"); per_click_delay = 0; local expected_gardens = 33; local last_sun = 99; instructions = { 0,0,2,1,99, 0,0,0,1,99, 0,0,0,0,99, 0,0,0,1,99, 0,0,0,1,99, 0,0,2,0,99, 0,0,0,0,33, 0,0,0,0,33, 0,0,0,0,33, 0,0,2,1,99, 0,0,0,1,99, 0,0,0,0,33, 0,0,0,0,33, 0,0,2,1,99, 0,0,0,1,99, 0,0,0,0,99, 0,0,0,2,33, 0,0,2,0,99, 0,0,1,1,99, 0,0,0,0,33, 0,0,0,1,33, 0,0,0,0,33, 0,0,0,0,33, 0,0,0,0,33, 0,0,0,1,33, 0,0,0,0,33, 0,0,1,0,33, 0,0,0,0,99, 0,0,0,0,99, 0,0,4,2,99, 0,0,1,0,33, 0,0,0,0,33, 0,0,0,1,33, 0,0,0,0,33, 0,0,0,1,99, 0,0,0,0,33, 0,0,2,0,33, 0,0,0,1,33, 0,0,0,2,33, 0,0,0,0,99, 0,0,0,0,99, }; function clickAll(image_name, up) if nil then lsPrintln("Would click '".. image_name .. "'"); return; -- not clicking buttons for debugging end -- Find buttons and click them! srReadScreen(); xyWindowSize = srGetWindowSize(); local buttons = findAllImages(image_name); if #buttons == 0 then statusScreen("Could not find specified buttons..."); lsSleep(1500); else statusScreen("Clicking " .. #buttons .. "button(s)..."); if up then for i=#buttons, 1, -1 do srClickMouseNoMove(buttons[i][0]+5, buttons[i][1]+3); lsSleep(per_click_delay); end else for i=1, #buttons do srClickMouseNoMove(buttons[i][0]+5, buttons[i][1]+3); lsSleep(per_click_delay); end end statusScreen("Done clicking (" .. #buttons .. " clicks)."); lsSleep(100); end end button_names = {"ThistleNit.png", "ThistlePot.png", "ThistleH2O.png", "ThistleOxy.png", "ThistleSun.png"}; local z = 2; -- Initialize last_mon local mon_w = 10; local mon_h = 152; local last_mon = {}; for x=1, mon_w do last_mon[x] = {}; for y=1, mon_h do last_mon[x][y] = 0; end end function waitForMonChange(message) if not first_nit then first_nit = srFindImage("ThistleNit.png"); end if not first_nit then error "Could not find first Nit"; end mon_x = first_nit[0] - 25; mon_y = first_nit[1] + 13; local different = nil; local skip_next = nil; while not different do srReadScreen(); for x=1, mon_w do for y=1, mon_h do newvalue = srReadPixelFromBuffer(mon_x + x, mon_y + y); if not (newvalue == last_mon[x][y]) then different = 1; end last_mon[x][y] = newvalue; end end if different then -- Make sure the screen was done refreshing and update again lsSleep(60); srReadScreen(); for x=1, mon_w do for y=1, mon_h do last_mon[x][y] = srReadPixelFromBuffer(mon_x + x, mon_y + y); end end end if (different and skip_next) then skip_next = nil; different = nil; end lsPrintWrapped(10, 5, 0, lsScreenX - 20, 1, 1, 0xFFFFFFff, message); lsPrintWrapped(10, 60, 0, lsScreenX - 20, 1, 1, 0xFFFFFFff, "Waiting for change..."); if lsButtonText(lsScreenX - 110, lsScreenY - 30, z, 100, 0xFFFFFFff, "End script") then error "Clicked End Script button"; end if lsButtonText(40, lsScreenY - 60, z, 200, 0xFFFFFFff, "Force tick") then different = 1; end if lsButtonText(40, lsScreenY - 90, z, 200, 0xFFFFFFff, "Skip tick") then skip_next = 1; end if lsButtonText(40, lsScreenY - 120, z, 200, 0xFFFFFFff, "Finish up") then finish_up = 1; end -- display mon pixels for x=1, mon_w do for y=1, mon_h do local size = 2; lsDisplaySystemSprite(1, 10+x*size, 90+y*size, 0, size, size, last_mon[x][y]); end end lsDoFrame(); lsSleep(100); end end function test() local loop=0; while 1 do waitForMonChange("tick " .. loop); statusScreen('Changed!'); lsSleep(1000); loop = loop + 1; end error 'done'; end function refillWater() lsSleep(100); srReadScreen(); FindWater = srFindImage("iconWaterJugSmall.png"); if FindWater then statusScreen("Refilling water..."); srClickMouseNoMove(FindWater[0]+3,FindWater[1]-5, right_click); lsSleep(500); srReadScreen(); FindMaxButton = srFindImage("Maxbutton.png"); if FindMaxButton then srClickMouseNoMove(FindMaxButton[0]+3,FindMaxButton[1]+3, right_click); lsSleep(500); end end end function refillWaterBarrel() lsSleep(100); srReadScreen(); FindWater = findText("Draw Water"); if FindWater then statusScreen("Refilling water..."); srClickMouseNoMove(FindWater[0]+30,FindWater[1]+5, right_click); lsSleep(500); srReadScreen(); FindMaxButton = srFindImage("Maxbutton.png", 5000); if FindMaxButton then srClickMouseNoMove(FindMaxButton[0]+3,FindMaxButton[1]+3, right_click); lsSleep(500); end end end function doit() num_loops = promptNumber("How many passes ?", 1); askForWindow("Pin any number of thistle gardens, edit thistle_custom with recipe. Macro will always look for water icon to refill jugs. You can optionally pin the Water Barrel menu to refill jugs."); if not ( #instructions == 41*5) then error 'Invalid instruction length'; end refillWater(); refillWaterBarrel(); -- test(); for loops=1, num_loops do clickAll("ThistleAsc.png", nil); lsSleep(100); srReadScreen(); local buttons = findAllImages("ThistleNit.png"); -- Sanity check if not (#buttons == expected_gardens) then error "Did not find expected number of thistle gardens"; end local buttons2 = findAllImages("ThistlePlantACrop.png"); if not (#buttons2 == #buttons) then error ("Some PlantACrop obscured, found " .. #buttons2 .. ", expected " .. #buttons); end for i=1, #button_names do local buttons2 = findAllImages(button_names[i]); if not (#buttons2 == #buttons) then error ("Some " .. button_names[i] .. " obscured, found " .. #buttons2 .. ", expected " .. #buttons); end end clickAll("ThistlePlantACrop.png", 1); statusScreen("(" .. loops .. "/" .. num_loops .. ") Doing initial 2s wait..."); lsSleep(2000); waitForMonChange("Getting initial image..."); for i=0, 39 do for j=0, 3 do for k=1, instructions[i*5 + j + 1] do clickAll(button_names[j+1], 1); end end if not (instructions[i*5 + 5] == last_sun) then last_sun = instructions[i*5 + 5]; clickAll(button_names[5], 1); end waitForMonChange("(" .. loops .. "/" .. num_loops .. ") Tick " .. i .. " done."); if finish_up then num_loops = loops; end lsSleep(1000); -- Wait a moment after image changes before doing the next tick end lsSleep(100); clickAll("ThistleAsc.png", nil); lsSleep(500); clickAll("Harvest.png", nil); lsSleep(500); refillWater(); refillWaterBarrel(); if finish_up then break; end end lsPlaySound("Complete.wav"); end
-- -- To run: -- Copy a recipe from the output of the Thistle Mode -- Update expected_gardens equal to the number you have opened and pinned -- Gardens must all have their buttons visible, can overlap as long as the -- row with "asc" is visible regardlesss of which window was clicked last -- Update "last sun" to be what it is now (0 if night, -- 99 if daylight and open lid, 33 if daylight and closed lid) -- dofile("common.inc"); per_click_delay = 0; local expected_gardens = 33; local last_sun = 99; instructions = { 0,0,2,1,99, 0,0,0,1,99, 0,0,0,0,99, 0,0,0,1,99, 0,0,0,1,99, 0,0,2,0,99, 0,0,0,0,33, 0,0,0,0,33, 0,0,0,0,33, 0,0,2,1,99, 0,0,0,1,99, 0,0,0,0,33, 0,0,0,0,33, 0,0,2,1,99, 0,0,0,1,99, 0,0,0,0,99, 0,0,0,2,33, 0,0,2,0,99, 0,0,1,1,99, 0,0,0,0,33, 0,0,0,1,33, 0,0,0,0,33, 0,0,0,0,33, 0,0,0,0,33, 0,0,0,1,33, 0,0,0,0,33, 0,0,1,0,33, 0,0,0,0,99, 0,0,0,0,99, 0,0,4,2,99, 0,0,1,0,33, 0,0,0,0,33, 0,0,0,1,33, 0,0,0,0,33, 0,0,0,1,99, 0,0,0,0,33, 0,0,2,0,33, 0,0,0,1,33, 0,0,0,2,33, 0,0,0,0,99, 0,0,0,0,99, }; function clickAll(image_name, up) if nil then lsPrintln("Would click '".. image_name .. "'"); return; -- not clicking buttons for debugging end -- Find buttons and click them! srReadScreen(); xyWindowSize = srGetWindowSize(); local buttons = findAllImages(image_name); if #buttons == 0 then statusScreen("Could not find specified buttons..."); lsSleep(1500); else statusScreen("Clicking " .. #buttons .. "button(s)..."); if up then for i=#buttons, 1, -1 do srClickMouseNoMove(buttons[i][0]+5, buttons[i][1]+3); lsSleep(per_click_delay); end else for i=1, #buttons do srClickMouseNoMove(buttons[i][0]+5, buttons[i][1]+3); lsSleep(per_click_delay); end end statusScreen("Done clicking (" .. #buttons .. " clicks)."); lsSleep(100); end end button_names = {"ThistleNit.png", "ThistlePot.png", "ThistleH2O.png", "ThistleOxy.png", "ThistleSun.png"}; local z = 2; -- Initialize last_mon local mon_w = 10; local mon_h = 152; local last_mon = {}; for x=1, mon_w do last_mon[x] = {}; for y=1, mon_h do last_mon[x][y] = 0; end end function waitForMonChange(message) if not first_nit then first_nit = srFindImage("ThistleNit.png"); end if not first_nit then error "Could not find first Nit"; end mon_x = first_nit[0] - 25; mon_y = first_nit[1] + 13; local different = nil; local skip_next = nil; while not different do srReadScreen(); for x=1, mon_w do for y=1, mon_h do newvalue = srReadPixelFromBuffer(mon_x + x, mon_y + y); if not (newvalue == last_mon[x][y]) then different = 1; end last_mon[x][y] = newvalue; end end if different then -- Make sure the screen was done refreshing and update again lsSleep(60); srReadScreen(); for x=1, mon_w do for y=1, mon_h do last_mon[x][y] = srReadPixelFromBuffer(mon_x + x, mon_y + y); end end end if (different and skip_next) then skip_next = nil; different = nil; end lsPrintWrapped(10, 5, 0, lsScreenX - 20, 1, 1, 0xFFFFFFff, message); lsPrintWrapped(10, 60, 0, lsScreenX - 20, 1, 1, 0xFFFFFFff, "Waiting for change..."); if lsButtonText(lsScreenX - 110, lsScreenY - 30, z, 100, 0xFFFFFFff, "End script") then error "Clicked End Script button"; end if lsButtonText(40, lsScreenY - 60, z, 200, 0xFFFFFFff, "Force tick") then different = 1; end if lsButtonText(40, lsScreenY - 90, z, 200, 0xFFFFFFff, "Skip tick") then skip_next = 1; end if lsButtonText(40, lsScreenY - 120, z, 200, 0xFFFFFFff, "Finish up") then finish_up = 1; end -- display mon pixels for x=1, mon_w do for y=1, mon_h do local size = 2; lsDisplaySystemSprite(1, 10+x*size, 90+y*size, 0, size, size, last_mon[x][y]); end end lsDoFrame(); lsSleep(100); end end function test() local loop=0; while 1 do waitForMonChange("tick " .. loop); statusScreen('Changed!'); lsSleep(1000); loop = loop + 1; end error 'done'; end function refillWater() lsSleep(100); srReadScreen(); FindWater = srFindImage("iconWaterJugSmall.png"); if FindWater then statusScreen("Refilling water..."); srClickMouseNoMove(FindWater[0]+3,FindWater[1]-5, right_click); lsSleep(500); srReadScreen(); FindMaxButton = srFindImage("Maxbutton.png"); if FindMaxButton then srClickMouseNoMove(FindMaxButton[0]+3,FindMaxButton[1]+3, right_click); lsSleep(500); end end end function refillWaterBarrel() lsSleep(100); srReadScreen(); FindWater = findText("Draw Water"); if FindWater then statusScreen("Refilling water..."); srClickMouseNoMove(FindWater[0]+30,FindWater[1]+5, right_click); lsSleep(500); srReadScreen(); FindMaxButton = srFindImage("Maxbutton.png", 5000); if FindMaxButton then srClickMouseNoMove(FindMaxButton[0]+3,FindMaxButton[1]+3, right_click); lsSleep(500); end end end function doit() num_loops = promptNumber("How many passes ?", 1); askForWindow("Pin any number of thistle gardens, edit thistle_custom with recipe. Macro will always look for water icon to refill jugs. You can optionally pin the Water Barrel menu to refill jugs."); if not ( #instructions == 41*5) then error 'Invalid instruction length'; end refillWater(); refillWaterBarrel(); -- test(); for loops=1, num_loops do clickAll("ThistleAsc.png", nil); lsSleep(100); srReadScreen(); local buttons = findAllImages("ThistleNit.png"); -- Sanity check if not (#buttons == expected_gardens) then error "Did not find expected number of thistle gardens"; end local buttons2 = findAllImages("ThistlePlantACrop.png"); if not (#buttons2 == #buttons) then error ("Some PlantACrop obscured, found " .. #buttons2 .. ", expected " .. #buttons); end for i=1, #button_names do local buttons2 = findAllImages(button_names[i]); if not (#buttons2 == #buttons) then error ("Some " .. button_names[i] .. " obscured, found " .. #buttons2 .. ", expected " .. #buttons); end end clickAll("ThistlePlantACrop.png", 1); statusScreen("(" .. loops .. "/" .. num_loops .. ") Doing initial 2s wait..."); lsSleep(2000); waitForMonChange("Getting initial image..."); for i=0, 39 do for j=0, 3 do for k=1, instructions[i*5 + j + 1] do clickAll(button_names[j+1], 1); end end if not (instructions[i*5 + 5] == last_sun) then last_sun = instructions[i*5 + 5]; clickAll(button_names[5], 1); end waitForMonChange("(" .. loops .. "/" .. num_loops .. ") Tick " .. i .. " done."); if finish_up then num_loops = loops; end lsSleep(1000); -- Wait a moment after image changes before doing the next tick end lsSleep(100); clickAll("ThistleAsc.png", nil); lsSleep(500); clickAll("Harvest.png", nil); lsSleep(500); refillWater(); refillWaterBarrel(); if finish_up then break; end end lsPlaySound("Complete.wav"); end
Use modern include statements - bugfix missing function
Use modern include statements - bugfix missing function
Lua
mit
DashingStrike/Automato-ATITD,wzydhek/Automato-ATITD,DashingStrike/Automato-ATITD,TheRealMaxion/Automato-ATITD,TheRealMaxion/Automato-ATITD,wzydhek/Automato-ATITD
6387240fc183505ae1011484f35972966b183693
pud/component/AIInputComponent.lua
pud/component/AIInputComponent.lua
local Class = require 'lib.hump.class' local InputComponent = getClass 'pud.component.InputComponent' local message = require 'pud.component.message' local property = require 'pud.component.property' -- tables to translate direction strings to coordinates local _x = {l=-1, r=1, u=0, d=0, ul=-1, ur=1, dl=-1, dr=1} local _y = {l=0, r=0, u=-1, d=1, ul=-1, ur=-1, dl=1, dr=1} -- AIInputComponent -- local AIInputComponent = Class{name='AIInputComponent', inherits=InputComponent, function(self, properties) InputComponent.construct(self, properties) self:_addMessages( 'TIME_PRETICK', 'TIME_POSTEXECUTE', 'COLLIDE_BLOCKED', 'COLLIDE_NONE') self._directions = {} self:_allowAllDirections() end } -- destructor function AIInputComponent:destroy() for dir in pairs(self._directions) do self._directions[dir] = nil end self._directions = nil InputComponent.destroy(self) end -- figure out what to do on next tick function AIInputComponent:_determineNextAction(ap) local moveCost = self._mediator:query(property('MoveCost')) local allowed = self:_getAllowedDirections() if allowed then local dir = allowed[Random(#allowed)] local x, y = _x[dir], _y[dir] self:_attemptMove(x, y) end end -- disallow attempting to move in the given direction function AIInputComponent:_denyDirection(node, nodeX, nodeY) local pos = self._mediator:query(property('Position')) local x, y = nodeX-pos[1], nodeY-pos[2] local dir = '' if y > 0 then dir = dir..'d' elseif y < 0 then dir = dir..'u' end if x > 0 then dir = dir..'r' elseif x < 0 then dir = dir..'l' end if self._directions[dir] ~= nil then self._directions[dir] = false end end -- get currently allowed directions function AIInputComponent:_getAllowedDirections() local allowed = {} local count = 0 for dir in pairs(self._directions) do if self._directions[dir] then count = count + 1 allowed[count] = dir end end return count > 0 and allowed or nil end -- allow traveling in all directions function AIInputComponent:_allowAllDirections() self._directions.l = true self._directions.r = true self._directions.u = true self._directions.d = true self._directions.ul = true self._directions.ur = true self._directions.dl = true self._directions.dr = true end function AIInputComponent:receive(msg, ...) if msg == message('TIME_PRETICK') or msg == message('TIME_POSTEXECUTE') then self:_determineNextAction(...) elseif msg == message('COLLIDE_BLOCKED') then self:_denyDirection(...) elseif msg == message('COLLIDE_NONE') then self:_allowAllDirections(...) end InputComponent.receive(self, msg, ...) end -- the class return AIInputComponent
local Class = require 'lib.hump.class' local InputComponent = getClass 'pud.component.InputComponent' local message = require 'pud.component.message' local property = require 'pud.component.property' -- tables to translate direction strings to coordinates local _x = {l=-1, r=1, u=0, d=0, ul=-1, ur=1, dl=-1, dr=1} local _y = {l=0, r=0, u=-1, d=1, ul=-1, ur=-1, dl=1, dr=1} -- AIInputComponent -- local AIInputComponent = Class{name='AIInputComponent', inherits=InputComponent, function(self, properties) InputComponent.construct(self, properties) self:_addMessages( 'TIME_PRETICK', 'TIME_POSTEXECUTE', 'COLLIDE_BLOCKED', 'COLLIDE_NONE') self._directions = {} self:_allowAllDirections() end } -- destructor function AIInputComponent:destroy() for dir in pairs(self._directions) do self._directions[dir] = nil end self._directions = nil InputComponent.destroy(self) end -- figure out what to do on next tick function AIInputComponent:_determineNextAction(ap) local moveCost = self._mediator:query(property('MoveCost')) if ap >= moveCost then local allowed = self:_getAllowedDirections() if allowed then local dir = allowed[Random(#allowed)] local x, y = _x[dir], _y[dir] self:_attemptMove(x, y) end end end -- disallow attempting to move in the given direction function AIInputComponent:_denyDirection(node, nodeX, nodeY) local pos = self._mediator:query(property('Position')) local x, y = nodeX-pos[1], nodeY-pos[2] local dir = '' if y > 0 then dir = dir..'d' elseif y < 0 then dir = dir..'u' end if x > 0 then dir = dir..'r' elseif x < 0 then dir = dir..'l' end if self._directions[dir] ~= nil then self._directions[dir] = false end end -- get currently allowed directions function AIInputComponent:_getAllowedDirections() local allowed = {} local count = 0 for dir in pairs(self._directions) do if self._directions[dir] then count = count + 1 allowed[count] = dir end end return count > 0 and allowed or nil end -- allow traveling in all directions function AIInputComponent:_allowAllDirections() self._directions.l = true self._directions.r = true self._directions.u = true self._directions.d = true self._directions.ul = true self._directions.ur = true self._directions.dl = true self._directions.dr = true end function AIInputComponent:receive(msg, ...) if msg == message('TIME_PRETICK') or msg == message('TIME_POSTEXECUTE') then self:_determineNextAction(...) elseif msg == message('COLLIDE_BLOCKED') then self:_denyDirection(...) elseif msg == message('COLLIDE_NONE') then self:_allowAllDirections(...) end InputComponent.receive(self, msg, ...) end -- the class return AIInputComponent
fix AI trying to move when no AP for it
fix AI trying to move when no AP for it
Lua
mit
scottcs/wyx
a0b80011be49a2393de496a3fa01699527c53bf2
core/portmanager.lua
core/portmanager.lua
local multitable = require "util.multitable"; local fire_event = prosody.events.fire_event; --- Config local default_interfaces = { "*" }; local default_local_interfaces = { "127.0.0.1" }; if config.get("*", "use_ipv6") then table.insert(default_interfaces, "::"); table.insert(default_local_interfaces, "::1"); end --- Private state -- service_name -> { service_info, ... } local services = setmetatable({}, { __index = function (t, k) rawset(t, k, {}); return rawget(t, k); end }); -- service_name, interface (string), port (number) local active_services = multitable.new(); --- Private helpers local function error_to_friendly_message(service_name, port, err) local friendly_message = err; if err:match(" in use") then -- FIXME: Use service_name here if port == 5222 or port == 5223 or port == 5269 then friendly_message = "check that Prosody or another XMPP server is " .."not already running and using this port"; elseif port == 80 or port == 81 then friendly_message = "check that a HTTP server is not already using " .."this port"; elseif port == 5280 then friendly_message = "check that Prosody or a BOSH connection manager " .."is not already running"; else friendly_message = "this port is in use by another application"; end elseif err:match("permission") then friendly_message = "Prosody does not have sufficient privileges to use this port"; elseif err == "no ssl context" then if not config.get("*", "core", "ssl") then friendly_message = "there is no 'ssl' config under Host \"*\" which is " .."require for legacy SSL ports"; else friendly_message = "initializing SSL support failed, see previous log entries"; end end return friendly_message; end module("portmanager", package.seeall); prosody.events.add_handler("item-added/net-provider", function (event) local item = event.item; register_service(item.name, item); end); prosody.events.add_handler("item-removed/net-provider", function (event) local item = event.item; unregister_service(item.name, item); end); --- Public API function activate_service(service_name) local service_info = services[service_name][1]; if not service_info then return nil, "Unknown service: "..service_name; end local bind_interfaces = set.new(config.get("*", service_name.."_interfaces") or config.get("*", service_name.."_interface") -- COMPAT w/pre-0.9 or (service_info.private and default_local_interfaces) or config.get("*", "interfaces") or config.get("*", "interface") -- COMPAT w/pre-0.9 or service_info.default_interface -- COMPAT w/pre0.9 or default_interfaces); local bind_ports = set.new(config.get("*", service_name.."_ports") or (service_info.multiplex and config.get("*", "ports")) or service_info.default_ports or {service_info.default_port}); local listener = service_info.listener; local mode = listener.default_mode or "*a"; local ssl; if service_info.encryption == "ssl" then ssl = prosody.global_ssl_ctx; if not ssl then return nil, "global-ssl-context-required"; end end for interface in bind_interfaces do for port in bind_ports do if not service_info.multiplex and #active_services:search(nil, interface, port) > 0 then log("error", "Multiple services configured to listen on the same port ([%s]:%d): %s, %s", interface, port, active_services:search(nil, interface, port)[1][1].service.name or "<unnamed>", service_name or "<unnamed>"); else local handler, err = server.addserver(interface, port, listener, mode, ssl); if not handler then log("error", "Failed to open server port %d on %s, %s", port, interface, error_to_friendly_message(service_name, port, err)); else log("debug", "Added listening service %s to [%s]:%d", service_name, interface, port); active_services:add(service_name, interface, port, { server = handler; service = service_info; }); end end end end log("info", "Activated service '%s'", service_name); return true; end function deactivate(service_name) local active = active_services:search(service_name)[1]; if not active then return; end for interface, ports in pairs(active) do for port, active_service in pairs(ports) do active_service:close(); active_services:remove(service_name, interface, port, active_service); log("debug", "Removed listening service %s from [%s]:%d", service_name, interface, port); end end log("info", "Deactivated service '%s'", service_name); end function register_service(service_name, service_info) table.insert(services[service_name], service_info); if not active_services:get(service_name) then log("debug", "No active service for %s, activating...", service_name); local ok, err = activate_service(service_name); if not ok then log("error", "Failed to activate service '%s': %s", service_name, err or "unknown error"); end end fire_event("service-added", { name = service_name, service = service_info }); return true; end function unregister_service(service_name, service_info) local service_info_list = services[service_name]; for i, service in ipairs(service_info_list) do if service == service_info then table.remove(service_info_list, i); end end if active_services[service_name] == service_info then deactivate(service_name); if #service_info_list > 0 then -- Other services registered with this name activate(service_name); -- Re-activate with the next available one end end fire_event("service-removed", { name = service_name, service = service_info }); end function get_service(service_name) return services[service_name]; end function get_active_services(...) return active_services; end return _M;
local multitable = require "util.multitable"; local fire_event = prosody.events.fire_event; --- Config local default_interfaces = { "*" }; local default_local_interfaces = { "127.0.0.1" }; if config.get("*", "use_ipv6") then table.insert(default_interfaces, "::"); table.insert(default_local_interfaces, "::1"); end --- Private state -- service_name -> { service_info, ... } local services = setmetatable({}, { __index = function (t, k) rawset(t, k, {}); return rawget(t, k); end }); -- service_name, interface (string), port (number) local active_services = multitable.new(); --- Private helpers local function error_to_friendly_message(service_name, port, err) local friendly_message = err; if err:match(" in use") then -- FIXME: Use service_name here if port == 5222 or port == 5223 or port == 5269 then friendly_message = "check that Prosody or another XMPP server is " .."not already running and using this port"; elseif port == 80 or port == 81 then friendly_message = "check that a HTTP server is not already using " .."this port"; elseif port == 5280 then friendly_message = "check that Prosody or a BOSH connection manager " .."is not already running"; else friendly_message = "this port is in use by another application"; end elseif err:match("permission") then friendly_message = "Prosody does not have sufficient privileges to use this port"; elseif err == "no ssl context" then if not config.get("*", "core", "ssl") then friendly_message = "there is no 'ssl' config under Host \"*\" which is " .."require for legacy SSL ports"; else friendly_message = "initializing SSL support failed, see previous log entries"; end end return friendly_message; end module("portmanager", package.seeall); prosody.events.add_handler("item-added/net-provider", function (event) local item = event.item; register_service(item.name, item); end); prosody.events.add_handler("item-removed/net-provider", function (event) local item = event.item; unregister_service(item.name, item); end); --- Public API function activate_service(service_name) local service_info = services[service_name][1]; if not service_info then return nil, "Unknown service: "..service_name; end local config_prefix = (service_info.config_prefix or service_name).."_"; if config_prefix == "_" then config_prefix = ""; end local bind_interfaces = set.new(config.get("*", config_prefix.."interfaces") or config.get("*", config_prefix.."interface") -- COMPAT w/pre-0.9 or (service_info.private and default_local_interfaces) or config.get("*", "interfaces") or config.get("*", "interface") -- COMPAT w/pre-0.9 or service_info.default_interface -- COMPAT w/pre0.9 or default_interfaces); or service_info.default_ports or {service_info.default_port}); local bind_ports = set.new(config.get("*", config_prefix.."ports") local listener = service_info.listener; local mode = listener.default_mode or "*a"; local ssl; if service_info.encryption == "ssl" then ssl = prosody.global_ssl_ctx; if not ssl then return nil, "global-ssl-context-required"; end end for interface in bind_interfaces do for port in bind_ports do if not service_info.multiplex and #active_services:search(nil, interface, port) > 0 then log("error", "Multiple services configured to listen on the same port ([%s]:%d): %s, %s", interface, port, active_services:search(nil, interface, port)[1][1].service.name or "<unnamed>", service_name or "<unnamed>"); else local handler, err = server.addserver(interface, port, listener, mode, ssl); if not handler then log("error", "Failed to open server port %d on %s, %s", port, interface, error_to_friendly_message(service_name, port, err)); else log("debug", "Added listening service %s to [%s]:%d", service_name, interface, port); active_services:add(service_name, interface, port, { server = handler; service = service_info; }); end end end end log("info", "Activated service '%s'", service_name); return true; end function deactivate(service_name) local active = active_services:search(service_name)[1]; if not active then return; end for interface, ports in pairs(active) do for port, active_service in pairs(ports) do active_service:close(); active_services:remove(service_name, interface, port, active_service); log("debug", "Removed listening service %s from [%s]:%d", service_name, interface, port); end end log("info", "Deactivated service '%s'", service_name); end function register_service(service_name, service_info) table.insert(services[service_name], service_info); if not active_services:get(service_name) then log("debug", "No active service for %s, activating...", service_name); local ok, err = activate_service(service_name); if not ok then log("error", "Failed to activate service '%s': %s", service_name, err or "unknown error"); end end fire_event("service-added", { name = service_name, service = service_info }); return true; end function unregister_service(service_name, service_info) local service_info_list = services[service_name]; for i, service in ipairs(service_info_list) do if service == service_info then table.remove(service_info_list, i); end end if active_services[service_name] == service_info then deactivate(service_name); if #service_info_list > 0 then -- Other services registered with this name activate(service_name); -- Re-activate with the next available one end end fire_event("service-removed", { name = service_name, service = service_info }); end function get_service(service_name) return services[service_name]; end function get_active_services(...) return active_services; end return _M;
portmanager: Allow services to specify their config option prefix
portmanager: Allow services to specify their config option prefix
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
6c87eeebbf8fb25812bb7f6973d1351f66f45de8
core/portmanager.lua
core/portmanager.lua
local multitable = require "util.multitable"; local fire_event = prosody.events.fire_event; --- Config local default_interfaces = { "*" }; local default_local_interfaces = { "127.0.0.1" }; if config.get("*", "use_ipv6") then table.insert(default_interfaces, "::"); table.insert(default_local_interfaces, "::1"); end --- Private state -- service_name -> { service_info, ... } local services = setmetatable({}, { __index = function (t, k) rawset(t, k, {}); return rawget(t, k); end }); -- service_name, interface (string), port (number) local active_services = multitable.new(); --- Private helpers local function error_to_friendly_message(service_name, port, err) local friendly_message = err; if err:match(" in use") then -- FIXME: Use service_name here if port == 5222 or port == 5223 or port == 5269 then friendly_message = "check that Prosody or another XMPP server is " .."not already running and using this port"; elseif port == 80 or port == 81 then friendly_message = "check that a HTTP server is not already using " .."this port"; elseif port == 5280 then friendly_message = "check that Prosody or a BOSH connection manager " .."is not already running"; else friendly_message = "this port is in use by another application"; end elseif err:match("permission") then friendly_message = "Prosody does not have sufficient privileges to use this port"; elseif err == "no ssl context" then if not config.get("*", "core", "ssl") then friendly_message = "there is no 'ssl' config under Host \"*\" which is " .."require for legacy SSL ports"; else friendly_message = "initializing SSL support failed, see previous log entries"; end end return friendly_message; end module("portmanager", package.seeall); prosody.events.add_handler("item-added/net-provider", function (event) local item = event.item; register_service(item.name, item); end); prosody.events.add_handler("item-removed/net-provider", function (event) local item = event.item; unregister_service(item.name, item); end); --- Public API function activate_service(service_name) local service_info = services[service_name][1]; if not service_info then return nil, "Unknown service: "..service_name; end local config_prefix = (service_info.config_prefix or service_name).."_"; if config_prefix == "_" then config_prefix = ""; end local bind_interfaces = set.new(config.get("*", config_prefix.."interfaces") or config.get("*", config_prefix.."interface") -- COMPAT w/pre-0.9 or (service_info.private and default_local_interfaces) or config.get("*", "interfaces") or config.get("*", "interface") -- COMPAT w/pre-0.9 or service_info.default_interface -- COMPAT w/pre0.9 or default_interfaces); or service_info.default_ports or {service_info.default_port}); local bind_ports = set.new(config.get("*", config_prefix.."ports") local listener = service_info.listener; local mode = listener.default_mode or "*a"; local ssl; if service_info.encryption == "ssl" then ssl = prosody.global_ssl_ctx; if not ssl then return nil, "global-ssl-context-required"; end end for interface in bind_interfaces do for port in bind_ports do if not service_info.multiplex and #active_services:search(nil, interface, port) > 0 then log("error", "Multiple services configured to listen on the same port ([%s]:%d): %s, %s", interface, port, active_services:search(nil, interface, port)[1][1].service.name or "<unnamed>", service_name or "<unnamed>"); else local handler, err = server.addserver(interface, port, listener, mode, ssl); if not handler then log("error", "Failed to open server port %d on %s, %s", port, interface, error_to_friendly_message(service_name, port, err)); else log("debug", "Added listening service %s to [%s]:%d", service_name, interface, port); active_services:add(service_name, interface, port, { server = handler; service = service_info; }); end end end end log("info", "Activated service '%s'", service_name); return true; end function deactivate(service_name) local active = active_services:search(service_name)[1]; if not active then return; end for interface, ports in pairs(active) do for port, active_service in pairs(ports) do active_service:close(); active_services:remove(service_name, interface, port, active_service); log("debug", "Removed listening service %s from [%s]:%d", service_name, interface, port); end end log("info", "Deactivated service '%s'", service_name); end function register_service(service_name, service_info) table.insert(services[service_name], service_info); if not active_services:get(service_name) then log("debug", "No active service for %s, activating...", service_name); local ok, err = activate_service(service_name); if not ok then log("error", "Failed to activate service '%s': %s", service_name, err or "unknown error"); end end fire_event("service-added", { name = service_name, service = service_info }); return true; end function unregister_service(service_name, service_info) local service_info_list = services[service_name]; for i, service in ipairs(service_info_list) do if service == service_info then table.remove(service_info_list, i); end end if active_services[service_name] == service_info then deactivate(service_name); if #service_info_list > 0 then -- Other services registered with this name activate(service_name); -- Re-activate with the next available one end end fire_event("service-removed", { name = service_name, service = service_info }); end function get_service(service_name) return services[service_name]; end function get_active_services(...) return active_services; end return _M;
local multitable = require "util.multitable"; local fire_event = prosody.events.fire_event; --- Config local default_interfaces = { "*" }; local default_local_interfaces = { "127.0.0.1" }; if config.get("*", "use_ipv6") then table.insert(default_interfaces, "::"); table.insert(default_local_interfaces, "::1"); end --- Private state -- service_name -> { service_info, ... } local services = setmetatable({}, { __index = function (t, k) rawset(t, k, {}); return rawget(t, k); end }); -- service_name, interface (string), port (number) local active_services = multitable.new(); --- Private helpers local function error_to_friendly_message(service_name, port, err) local friendly_message = err; if err:match(" in use") then -- FIXME: Use service_name here if port == 5222 or port == 5223 or port == 5269 then friendly_message = "check that Prosody or another XMPP server is " .."not already running and using this port"; elseif port == 80 or port == 81 then friendly_message = "check that a HTTP server is not already using " .."this port"; elseif port == 5280 then friendly_message = "check that Prosody or a BOSH connection manager " .."is not already running"; else friendly_message = "this port is in use by another application"; end elseif err:match("permission") then friendly_message = "Prosody does not have sufficient privileges to use this port"; elseif err == "no ssl context" then if not config.get("*", "core", "ssl") then friendly_message = "there is no 'ssl' config under Host \"*\" which is " .."require for legacy SSL ports"; else friendly_message = "initializing SSL support failed, see previous log entries"; end end return friendly_message; end module("portmanager", package.seeall); prosody.events.add_handler("item-added/net-provider", function (event) local item = event.item; register_service(item.name, item); end); prosody.events.add_handler("item-removed/net-provider", function (event) local item = event.item; unregister_service(item.name, item); end); --- Public API function activate_service(service_name) local service_info = services[service_name][1]; if not service_info then return nil, "Unknown service: "..service_name; end local listener = service_info.listener; local config_prefix = (service_info.config_prefix or service_name).."_"; if config_prefix == "_" then config_prefix = ""; end local bind_interfaces = set.new(config.get("*", config_prefix.."interfaces") or config.get("*", config_prefix.."interface") -- COMPAT w/pre-0.9 or (service_info.private and default_local_interfaces) or config.get("*", "interfaces") or config.get("*", "interface") -- COMPAT w/pre-0.9 or listener.default_interface -- COMPAT w/pre0.9 or default_interfaces); local bind_ports = set.new(config.get("*", config_prefix.."ports") or service_info.default_ports or {listener.default_port}); -- COMPAT w/pre-0.9 local mode = listener.default_mode or "*a"; local ssl; if service_info.encryption == "ssl" then ssl = prosody.global_ssl_ctx; if not ssl then return nil, "global-ssl-context-required"; end end for interface in bind_interfaces do for port in bind_ports do if not service_info.multiplex and #active_services:search(nil, interface, port) > 0 then log("error", "Multiple services configured to listen on the same port ([%s]:%d): %s, %s", interface, port, active_services:search(nil, interface, port)[1][1].service.name or "<unnamed>", service_name or "<unnamed>"); else local handler, err = server.addserver(interface, port, listener, mode, ssl); if not handler then log("error", "Failed to open server port %d on %s, %s", port, interface, error_to_friendly_message(service_name, port, err)); else log("debug", "Added listening service %s to [%s]:%d", service_name, interface, port); active_services:add(service_name, interface, port, { server = handler; service = service_info; }); end end end end log("info", "Activated service '%s'", service_name); return true; end function deactivate(service_name) local active = active_services:search(service_name)[1]; if not active then return; end for interface, ports in pairs(active) do for port, active_service in pairs(ports) do active_service:close(); active_services:remove(service_name, interface, port, active_service); log("debug", "Removed listening service %s from [%s]:%d", service_name, interface, port); end end log("info", "Deactivated service '%s'", service_name); end function register_service(service_name, service_info) table.insert(services[service_name], service_info); if not active_services:get(service_name) then log("debug", "No active service for %s, activating...", service_name); local ok, err = activate_service(service_name); if not ok then log("error", "Failed to activate service '%s': %s", service_name, err or "unknown error"); end end fire_event("service-added", { name = service_name, service = service_info }); return true; end function unregister_service(service_name, service_info) local service_info_list = services[service_name]; for i, service in ipairs(service_info_list) do if service == service_info then table.remove(service_info_list, i); end end if active_services[service_name] == service_info then deactivate(service_name); if #service_info_list > 0 then -- Other services registered with this name activate(service_name); -- Re-activate with the next available one end end fire_event("service-removed", { name = service_name, service = service_info }); end function get_service(service_name) return services[service_name]; end function get_active_services(...) return active_services; end return _M;
portmanager: Fix pre-0.9 compatibility by taking default_interface and default_port from the listener instead of service table
portmanager: Fix pre-0.9 compatibility by taking default_interface and default_port from the listener instead of service table
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
e778af8bb60ba6a67c47e8b30c175874726414ee
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( 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 vlc.msg.err("Couldn't extract the video URL from dailymotion") return { } end if string.match( line, "\"sequence\",") then line = vlc.strings.decode_uri(line):gsub("\\/", "/") arturl = find( line, "\"videoPreviewURL\":\"([^\"]*)\"") name = find( line, "\"videoTitle\":\"([^\"]*)\"") description = find( line, "\"videoDescription\":\"([^\"]*)\"") --[[ we get a list of different streams available, at various codecs and resolutions: 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 ]]-- -- FIXME: the hd/hq versions (in mp4) cause a lot of seeks, -- for now we only get the sd (in flv) URL -- if not path then path = find( line, "\"hqURL\":\"([^\"]*)\"") end -- if not path then path = find( line, "\"hdURL\":\"([^\"]*)\"") end if not path then path = find( line, "\"sdURL\":\"([^\"]*)\"") end return { { path = path; name = name; description = description; url = vlc.path; arturl = arturl } } end end end
fixes dailymotion parser
fixes dailymotion parser get the SD video (in flv), the HD and HQ videos (in mp4) causes seeking back and forth and the video is unplayable
Lua
lgpl-2.1
vlc-mirror/vlc-2.1,xkfz007/vlc,krichter722/vlc,vlc-mirror/vlc,krichter722/vlc,xkfz007/vlc,vlc-mirror/vlc,vlc-mirror/vlc-2.1,krichter722/vlc,jomanmuk/vlc-2.1,shyamalschandra/vlc,vlc-mirror/vlc,shyamalschandra/vlc,shyamalschandra/vlc,jomanmuk/vlc-2.2,jomanmuk/vlc-2.2,jomanmuk/vlc-2.1,xkfz007/vlc,xkfz007/vlc,xkfz007/vlc,vlc-mirror/vlc,vlc-mirror/vlc,vlc-mirror/vlc,krichter722/vlc,vlc-mirror/vlc-2.1,shyamalschandra/vlc,jomanmuk/vlc-2.1,vlc-mirror/vlc-2.1,vlc-mirror/vlc-2.1,shyamalschandra/vlc,jomanmuk/vlc-2.2,vlc-mirror/vlc,jomanmuk/vlc-2.2,shyamalschandra/vlc,jomanmuk/vlc-2.2,xkfz007/vlc,jomanmuk/vlc-2.1,jomanmuk/vlc-2.1,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.1,jomanmuk/vlc-2.2,krichter722/vlc,jomanmuk/vlc-2.2,jomanmuk/vlc-2.1,xkfz007/vlc,vlc-mirror/vlc-2.1,krichter722/vlc,krichter722/vlc,shyamalschandra/vlc
994309451d4aa193387907a131681200dc60eff9
agents/monitoring/lua/lib/info.lua
agents/monitoring/lua/lib/info.lua
local Object = require('core').Object local JSON = require('json') --[[ Info ]]-- local Info = Object:extend() function Info:initialize() self._s = sigar:new() self._params = {} end function Info:serialize() return { jsonPayload = JSON.stringify(self._params) } end local NilInfo = Info:extend() --[[ CPUInfo ]]-- local CPUInfo = Info:extend() function CPUInfo:initialize() Info.initialize(self) local cpus = self._s:cpus() self._params = {} for i=1, #cpus do local info = cpus[i]:info() local data = cpus[i]:data() local bucket = 'cpu.' .. i - 1 self._params[bucket] = {} for k, v in pairs(info) do self._params[bucket][k] = v end for k, v in pairs(data) do self._params[bucket][k] = v end end end --[[ DiskInfo ]]-- local DiskInfo = Info:extend() function DiskInfo:initialize() Info.initialize(self) local disks = self._s:disks() local name, usage for i=1, #disks do name = disks[i]:name() usage = disks[i]:usage() if usage then self._params[name] = {} for key, value in pairs(usage) do self._params[name][key] = value end end end end --[[ MemoryInfo ]]-- local MemoryInfo = Info:extend() function MemoryInfo:initialize() Info.initialize(self) local meminfo = self._s:mem() for key, value in pairs(meminfo) do self._params[key] = value end end --[[ NetworkInfo ]]-- local NetworkInfo = Info:extend() function NetworkInfo:initialize() Info.initialize(self) local netifs = self._s:netifs() for i=1,#netifs do self._params.netifs[i] = {} self._params.netifs[i].info = netifs[i]:info() self._params.netifs[i].usage = netifs[i]:usage() end end --[[ Factory ]]-- function create(infoType) if infoType == 'CPU' then return CPUInfo:new() elseif infoType == 'MEMORY' then return MemoryInfo:new() elseif infoType == 'NETWORK' then return NetworkInfo:new() elseif infoType == 'DISK' then return DiskInfo:new() end return NilInfo:new() end --[[ Exports ]]-- local info = {} info.CPUInfo = CPUInfo info.DiskInfo = DiskInfo info.MemoryInfo = MemoryInfo info.NetworkInfo = NetworkInfo info.create = create return info
local Object = require('core').Object local JSON = require('json') --[[ Info ]]-- local Info = Object:extend() function Info:initialize() self._s = sigar:new() self._params = {} end function Info:serialize() return { jsonPayload = JSON.stringify(self._params) } end local NilInfo = Info:extend() --[[ CPUInfo ]]-- local CPUInfo = Info:extend() function CPUInfo:initialize() Info.initialize(self) local cpus = self._s:cpus() self._params = {} for i=1, #cpus do local info = cpus[i]:info() local data = cpus[i]:data() local bucket = 'cpu.' .. i - 1 self._params[bucket] = {} for k, v in pairs(info) do self._params[bucket][k] = v end for k, v in pairs(data) do self._params[bucket][k] = v end end end --[[ DiskInfo ]]-- local DiskInfo = Info:extend() function DiskInfo:initialize() Info.initialize(self) local disks = self._s:disks() local name, usage for i=1, #disks do name = disks[i]:name() usage = disks[i]:usage() if usage then self._params[name] = {} for key, value in pairs(usage) do self._params[name][key] = value end end end end --[[ MemoryInfo ]]-- local MemoryInfo = Info:extend() function MemoryInfo:initialize() Info.initialize(self) local meminfo = self._s:mem() for key, value in pairs(meminfo) do self._params[key] = value end end --[[ NetworkInfo ]]-- local NetworkInfo = Info:extend() function NetworkInfo:initialize() Info.initialize(self) local netifs = self._s:netifs() for i=1,#netifs do local info = netifs[i]:info() local usage = netifs[i]:usage() local name = info.name self._params[name] = {} for k, v in pairs(info) do self._params[name][k] = v end for k, v in pairs(usage) do self._params[name][k] = v end end end --[[ Factory ]]-- function create(infoType) if infoType == 'CPU' then return CPUInfo:new() elseif infoType == 'MEMORY' then return MemoryInfo:new() elseif infoType == 'NETWORK' then return NetworkInfo:new() elseif infoType == 'DISK' then return DiskInfo:new() end return NilInfo:new() end --[[ Exports ]]-- local info = {} info.CPUInfo = CPUInfo info.DiskInfo = DiskInfo info.MemoryInfo = MemoryInfo info.NetworkInfo = NetworkInfo info.create = create return info
fix network info
fix network info
Lua
apache-2.0
christopherjwang/rackspace-monitoring-agent,virgo-agent-toolkit/rackspace-monitoring-agent,kaustavha/rackspace-monitoring-agent,cp16net/virgo-base,kaustavha/rackspace-monitoring-agent,virgo-agent-toolkit/rackspace-monitoring-agent,cp16net/virgo-base,AlphaStaxLLC/rackspace-monitoring-agent,christopherjwang/rackspace-monitoring-agent,cp16net/virgo-base,AlphaStaxLLC/rackspace-monitoring-agent,cp16net/virgo-base,cp16net/virgo-base
838bddcced4e17e421d284ef72be5c96839a0122
cparser/lexrule.lua
cparser/lexrule.lua
--- Definition of 'lexical rules' - functions which, given a CharStream, -- either consumes some input (ie. advances the stream) and succeeds (returns -- true) or fails (returns false) having consumed no input. local LexRule = { metatable = {} } function LexRule.metatable.__call(t, ...) return t.__call(...) end --- Given a function, wraps it into an object with convenient operators. function LexRule.new(x) if type(x) == "function" then return setmetatable({ __call = x }, LexRule.metatable) elseif type(x) == "string" then return LexRule.string(x) else error("expected function or string, got " .. type(x)) end end setmetatable(LexRule, { __call = function(LexRule, ...) return LexRule.new(...) end }) --- A LexRule that accepts any character. -- TODO should this be a character class (ie. have __class)? LexRule.any = LexRule(function(stream) if stream:eof() then return false else stream:advance() return true end end) --- Returns a LexRule that accepts any of the given characters. -- Character ranges can be specified with eg. "A-Z". function LexRule.class(...) local ranges = table.pack(...) local lookup = {} for _, range in ipairs(ranges) do if type(range) == "table" then assert(range.__class, "non-class table as element of class") for k, v in pairs(range.__class) do if type(k) == "string" and type(v) == "boolean" then lookup[k] = v end end else assert(type(range) == "string", "expected string or class as argument to LexRule.class, got " .. type(range)) if #range == 1 then lookup[range] = true elseif #range == 3 and string.sub(range, 2, 2) == "-" then local a, b = string.byte(range, 1), string.byte(range, 3) for c = a, b do lookup[string.char(c)] = true end else error("invalid string '" .. tostring(range) .. "' in character class") end end end local rule = LexRule(function(stream) if lookup[stream:peek()] then stream:advance() return true else return false end end) rule.__class = lookup return rule end function LexRule.string(str) if #str == 1 then return LexRule(function(stream) if stream:peek() == str then stream:advance() return true end return false end) elseif #str > 1 then return LexRule(function(stream) local pos = stream:pos() for i= 1, #str do if stream:peek() ~= string.sub(str, i, i) then stream:backtrack(pos) return false end stream:advance() end return true end) else error("empty LexRule.string") end end --- Return a LexRule that fails whenever self succeeds, and succeeds -- (consuming no input) when self fails function LexRule.metatable:__unm() -- TODO use self.__class when negating a character class return LexRule(function(stream) local pos = stream:pos() if self(stream) then stream:backtrack(pos) return false else return true end end) end --- Returns a LexRule that tries self, and if it succeeds also tries other. function LexRule.metatable.__concat(left, right) return LexRule(function(stream) local pos = stream:pos() return left(stream) and (right(stream) or stream:backtrack(pos) and false) end) end --- Returns a LexRule that tries self, and if it fails then tries other. function LexRule.metatable.__div(left, right) -- TODO use self.__class and other.__class when handling character classes return LexRule(function(stream) return left(stream) or right(stream) end) end --- Returns a LexRule that succeeds on left, as long as it couldn't succeed on right. function LexRule.metatable.__sub(left, right) return (-right) .. left end --- Try rule repeatedly until it stops succeeding. Always return true. function LexRule.many(rule) return LexRule(function(stream) while rule(stream) do end return true end) end --- Try rule, succeed regardless of whether rule succeeded. function LexRule.optional(rule) return LexRule(function(stream) rule(stream) return true end) end return LexRule
--- Definition of 'lexical rules' - functions which, given a CharStream, -- either consumes some input (ie. advances the stream) and succeeds (returns -- true) or fails (returns false) having consumed no input. local LexRule = { metatable = {} } function LexRule.metatable.__call(t, ...) return t.__call(...) end --- Given a function, wraps it into an object with convenient operators. function LexRule.new(x) if type(x) == "function" then return setmetatable({ __call = x }, LexRule.metatable) elseif type(x) == "string" then return LexRule.string(x) else error("expected function or string, got " .. type(x)) end end setmetatable(LexRule, { __call = function(LexRule, ...) return LexRule.new(...) end }) --- A LexRule that accepts any character. -- TODO should this be a character class (ie. have __class)? LexRule.any = LexRule(function(stream) if stream:eof() then return false else stream:advance() return true end end) --- Returns a LexRule that accepts any of the given characters. -- Character ranges can be specified with eg. "A-Z". function LexRule.class(...) local lookup = {} for i = 1, select('#', ...) do local range = select(i, ...) if type(range) == "table" then assert(range.__class, "non-class table as element of class") for k, v in pairs(range.__class) do if type(k) == "string" and type(v) == "boolean" then lookup[k] = v end end else assert(type(range) == "string", "expected string or class as argument to LexRule.class, got " .. type(range)) if #range == 1 then lookup[range] = true elseif #range == 3 and string.sub(range, 2, 2) == "-" then local a, b = string.byte(range, 1), string.byte(range, 3) for c = a, b do lookup[string.char(c)] = true end else error("invalid string '" .. tostring(range) .. "' in character class") end end end local rule = LexRule(function(stream) if lookup[stream:peek()] then stream:advance() return true else return false end end) rule.__class = lookup return rule end function LexRule.string(str) if #str == 1 then return LexRule(function(stream) if stream:peek() == str then stream:advance() return true end return false end) elseif #str > 1 then return LexRule(function(stream) local pos = stream:pos() for i= 1, #str do if stream:peek() ~= string.sub(str, i, i) then stream:backtrack(pos) return false end stream:advance() end return true end) else error("empty LexRule.string") end end --- Return a LexRule that fails whenever self succeeds, and succeeds -- (consuming no input) when self fails function LexRule.metatable:__unm() -- TODO use self.__class when negating a character class return LexRule(function(stream) local pos = stream:pos() if self(stream) then stream:backtrack(pos) return false else return true end end) end --- Returns a LexRule that tries self, and if it succeeds also tries other. function LexRule.metatable.__concat(left, right) return LexRule(function(stream) local pos = stream:pos() return left(stream) and (right(stream) or stream:backtrack(pos) and false) end) end --- Returns a LexRule that tries self, and if it fails then tries other. function LexRule.metatable.__div(left, right) -- TODO use self.__class and other.__class when handling character classes return LexRule(function(stream) return left(stream) or right(stream) end) end --- Returns a LexRule that succeeds on left, as long as it couldn't succeed on right. function LexRule.metatable.__sub(left, right) return (-right) .. left end --- Try rule repeatedly until it stops succeeding. Always return true. function LexRule.many(rule) return LexRule(function(stream) while rule(stream) do end return true end) end --- Try rule, succeed regardless of whether rule succeeded. function LexRule.optional(rule) return LexRule(function(stream) rule(stream) return true end) end return LexRule
Fix building on Lua < 5.2
Fix building on Lua < 5.2
Lua
mit
AbigailBuccaneer/cparser.lua,AbigailBuccaneer/cparser.lua
19f41f03ff3cb70742f8ea7b3ed3c7a03b2cfaa0
core/src/ffluci/sgi/webuci.lua
core/src/ffluci/sgi/webuci.lua
--[[ FFLuCI - SGI-Module for Haserl Description: Server Gateway Interface for Haserl FileId: $Id$ License: Copyright 2008 Steven Barth <steven@midlink.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ]]-- module("ffluci.sgi.webuci", package.seeall) -- HTTP interface -- Returns a table of all COOKIE, GET and POST Parameters function ffluci.http.formvalues() return webuci.vars end -- Gets form value from key function ffluci.http.formvalue(key, default) return ffluci.http.formvalues()[key] or default end -- Gets a table of values with a certain prefix function ffluci.http.formvaluetable(prefix) local vals = {} prefix = prefix and prefix .. "." or "." for k, v in pairs(ffluci.http.formvalues()) do if k:find(prefix, 1, true) == 1 then vals[k:sub(#prefix + 1)] = v end end return vals end -- Returns the path info function ffluci.http.get_path_info() return webuci.PATH_INFO end -- Returns the User's IP function ffluci.http.get_remote_addr() return webuci.REMOTE_ADDR end -- Returns the request URI function ffluci.http.get_request_uri() return webuci.REQUEST_URI end -- Returns the script name function ffluci.http.get_script_name() return webuci.SCRIPT_NAME end -- Asks the browser to redirect to "url" function ffluci.http.redirect(url, qs) if qs then url = url .. "?" .. qs end ffluci.http.set_status(302, "Found") print("Location: " .. url .. "\n") end -- Set Content-Type function ffluci.http.set_content_type(type) print("Content-Type: "..type.."\n") end -- Sets HTTP-Status-Header function ffluci.http.set_status(code, message) print(webuci.REQUEST_METHOD .. " " .. tostring(code) .. " " .. message) end
--[[ FFLuCI - SGI-Module for Haserl Description: Server Gateway Interface for Haserl FileId: $Id$ License: Copyright 2008 Steven Barth <steven@midlink.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ]]-- module("ffluci.sgi.webuci", package.seeall) local status_set = false -- HTTP interface -- Returns a table of all COOKIE, GET and POST Parameters function ffluci.http.formvalues() return webuci.vars end -- Gets form value from key function ffluci.http.formvalue(key, default) return ffluci.http.formvalues()[key] or default end -- Gets a table of values with a certain prefix function ffluci.http.formvaluetable(prefix) local vals = {} prefix = prefix and prefix .. "." or "." for k, v in pairs(ffluci.http.formvalues()) do if k:find(prefix, 1, true) == 1 then vals[k:sub(#prefix + 1)] = v end end return vals end -- Returns the path info function ffluci.http.get_path_info() return webuci.PATH_INFO end -- Returns the User's IP function ffluci.http.get_remote_addr() return webuci.REMOTE_ADDR end -- Returns the request URI function ffluci.http.get_request_uri() return webuci.REQUEST_URI end -- Returns the script name function ffluci.http.get_script_name() return webuci.SCRIPT_NAME end -- Asks the browser to redirect to "url" function ffluci.http.redirect(url, qs) if qs then url = url .. "?" .. qs end ffluci.http.set_status(302, "Found") print("Location: " .. url .. "\n") end -- Set Content-Type function ffluci.http.set_content_type(type) if not status_set then ffluci.http.set_status(200, "OK") end print("Content-Type: "..type.."\n") end -- Sets HTTP-Status-Header function ffluci.http.set_status(code, message) print(webuci.SERVER_PROTOCOL .. " " .. tostring(code) .. " " .. message) status_set = true end
* Fixed ffluci.sgi.webuci
* Fixed ffluci.sgi.webuci
Lua
apache-2.0
maxrio/luci981213,taiha/luci,david-xiao/luci,opentechinstitute/luci,forward619/luci,MinFu/luci,ff94315/luci-1,jorgifumi/luci,db260179/openwrt-bpi-r1-luci,RedSnake64/openwrt-luci-packages,cshore-firmware/openwrt-luci,lcf258/openwrtcn,openwrt-es/openwrt-luci,jorgifumi/luci,teslamint/luci,openwrt/luci,shangjiyu/luci-with-extra,keyidadi/luci,Sakura-Winkey/LuCI,NeoRaider/luci,florian-shellfire/luci,jchuang1977/luci-1,tcatm/luci,cappiewu/luci,mumuqz/luci,florian-shellfire/luci,teslamint/luci,maxrio/luci981213,openwrt-es/openwrt-luci,lbthomsen/openwrt-luci,florian-shellfire/luci,taiha/luci,Wedmer/luci,db260179/openwrt-bpi-r1-luci,palmettos/cnLuCI,dismantl/luci-0.12,lcf258/openwrtcn,remakeelectric/luci,LuttyYang/luci,opentechinstitute/luci,urueedi/luci,daofeng2015/luci,slayerrensky/luci,kuoruan/lede-luci,jlopenwrtluci/luci,jchuang1977/luci-1,shangjiyu/luci-with-extra,opentechinstitute/luci,marcel-sch/luci,kuoruan/luci,shangjiyu/luci-with-extra,slayerrensky/luci,Hostle/luci,ReclaimYourPrivacy/cloak-luci,lbthomsen/openwrt-luci,marcel-sch/luci,zhaoxx063/luci,sujeet14108/luci,artynet/luci,openwrt/luci,bright-things/ionic-luci,LuttyYang/luci,RedSnake64/openwrt-luci-packages,marcel-sch/luci,palmettos/cnLuCI,openwrt/luci,aa65535/luci,lbthomsen/openwrt-luci,LazyZhu/openwrt-luci-trunk-mod,mumuqz/luci,Wedmer/luci,keyidadi/luci,ReclaimYourPrivacy/cloak-luci,thesabbir/luci,db260179/openwrt-bpi-r1-luci,zhaoxx063/luci,kuoruan/lede-luci,dismantl/luci-0.12,taiha/luci,chris5560/openwrt-luci,maxrio/luci981213,lbthomsen/openwrt-luci,harveyhu2012/luci,jorgifumi/luci,RedSnake64/openwrt-luci-packages,tobiaswaldvogel/luci,sujeet14108/luci,MinFu/luci,aircross/OpenWrt-Firefly-LuCI,jlopenwrtluci/luci,jorgifumi/luci,thess/OpenWrt-luci,Hostle/openwrt-luci-multi-user,jchuang1977/luci-1,ff94315/luci-1,NeoRaider/luci,oneru/luci,Noltari/luci,Kyklas/luci-proto-hso,urueedi/luci,joaofvieira/luci,obsy/luci,keyidadi/luci,wongsyrone/luci-1,deepak78/new-luci,oyido/luci,lcf258/openwrtcn,nmav/luci,Wedmer/luci,urueedi/luci,fkooman/luci,jorgifumi/luci,bright-things/ionic-luci,dwmw2/luci,openwrt-es/openwrt-luci,lcf258/openwrtcn,slayerrensky/luci,hnyman/luci,harveyhu2012/luci,LuttyYang/luci,male-puppies/luci,Kyklas/luci-proto-hso,openwrt-es/openwrt-luci,Hostle/luci,nwf/openwrt-luci,harveyhu2012/luci,obsy/luci,david-xiao/luci,Sakura-Winkey/LuCI,aa65535/luci,ollie27/openwrt_luci,deepak78/new-luci,Hostle/openwrt-luci-multi-user,Wedmer/luci,fkooman/luci,bittorf/luci,maxrio/luci981213,lcf258/openwrtcn,Noltari/luci,shangjiyu/luci-with-extra,tobiaswaldvogel/luci,tobiaswaldvogel/luci,Hostle/openwrt-luci-multi-user,joaofvieira/luci,bright-things/ionic-luci,forward619/luci,cshore-firmware/openwrt-luci,bright-things/ionic-luci,remakeelectric/luci,tcatm/luci,marcel-sch/luci,Hostle/openwrt-luci-multi-user,mumuqz/luci,hnyman/luci,jlopenwrtluci/luci,cappiewu/luci,ff94315/luci-1,male-puppies/luci,lbthomsen/openwrt-luci,dismantl/luci-0.12,Noltari/luci,taiha/luci,rogerpueyo/luci,daofeng2015/luci,tcatm/luci,RuiChen1113/luci,kuoruan/luci,bright-things/ionic-luci,Sakura-Winkey/LuCI,thess/OpenWrt-luci,florian-shellfire/luci,nwf/openwrt-luci,oneru/luci,dwmw2/luci,tcatm/luci,cshore/luci,wongsyrone/luci-1,Noltari/luci,openwrt/luci,LuttyYang/luci,joaofvieira/luci,dismantl/luci-0.12,Sakura-Winkey/LuCI,LuttyYang/luci,fkooman/luci,mumuqz/luci,jchuang1977/luci-1,Hostle/luci,tobiaswaldvogel/luci,artynet/luci,palmettos/test,teslamint/luci,daofeng2015/luci,remakeelectric/luci,rogerpueyo/luci,opentechinstitute/luci,zhaoxx063/luci,jchuang1977/luci-1,florian-shellfire/luci,male-puppies/luci,NeoRaider/luci,palmettos/cnLuCI,david-xiao/luci,palmettos/test,nmav/luci,forward619/luci,male-puppies/luci,urueedi/luci,openwrt/luci,maxrio/luci981213,RuiChen1113/luci,obsy/luci,bittorf/luci,cshore-firmware/openwrt-luci,nmav/luci,MinFu/luci,ff94315/luci-1,wongsyrone/luci-1,bittorf/luci,thess/OpenWrt-luci,Hostle/luci,bittorf/luci,joaofvieira/luci,wongsyrone/luci-1,opentechinstitute/luci,lbthomsen/openwrt-luci,LazyZhu/openwrt-luci-trunk-mod,keyidadi/luci,opentechinstitute/luci,keyidadi/luci,palmettos/test,lcf258/openwrtcn,Hostle/luci,obsy/luci,jlopenwrtluci/luci,db260179/openwrt-bpi-r1-luci,joaofvieira/luci,LuttyYang/luci,urueedi/luci,marcel-sch/luci,kuoruan/luci,shangjiyu/luci-with-extra,ff94315/luci-1,chris5560/openwrt-luci,Sakura-Winkey/LuCI,oyido/luci,kuoruan/lede-luci,thess/OpenWrt-luci,cappiewu/luci,Wedmer/luci,obsy/luci,nmav/luci,schidler/ionic-luci,cshore/luci,openwrt/luci,deepak78/new-luci,tcatm/luci,schidler/ionic-luci,schidler/ionic-luci,forward619/luci,cshore-firmware/openwrt-luci,openwrt-es/openwrt-luci,cshore/luci,lcf258/openwrtcn,zhaoxx063/luci,palmettos/cnLuCI,nwf/openwrt-luci,cshore-firmware/openwrt-luci,palmettos/test,artynet/luci,Noltari/luci,jchuang1977/luci-1,jorgifumi/luci,NeoRaider/luci,Wedmer/luci,kuoruan/luci,ReclaimYourPrivacy/cloak-luci,palmettos/cnLuCI,oyido/luci,wongsyrone/luci-1,palmettos/test,hnyman/luci,thess/OpenWrt-luci,oneru/luci,tobiaswaldvogel/luci,db260179/openwrt-bpi-r1-luci,MinFu/luci,LazyZhu/openwrt-luci-trunk-mod,forward619/luci,kuoruan/luci,lbthomsen/openwrt-luci,palmettos/test,deepak78/new-luci,daofeng2015/luci,cshore-firmware/openwrt-luci,aircross/OpenWrt-Firefly-LuCI,kuoruan/lede-luci,aircross/OpenWrt-Firefly-LuCI,schidler/ionic-luci,Noltari/luci,LazyZhu/openwrt-luci-trunk-mod,nmav/luci,nmav/luci,hnyman/luci,david-xiao/luci,Hostle/luci,oneru/luci,keyidadi/luci,marcel-sch/luci,cappiewu/luci,marcel-sch/luci,maxrio/luci981213,RuiChen1113/luci,rogerpueyo/luci,981213/luci-1,lbthomsen/openwrt-luci,ollie27/openwrt_luci,oneru/luci,nwf/openwrt-luci,NeoRaider/luci,zhaoxx063/luci,hnyman/luci,florian-shellfire/luci,lcf258/openwrtcn,harveyhu2012/luci,male-puppies/luci,artynet/luci,dwmw2/luci,bright-things/ionic-luci,981213/luci-1,deepak78/new-luci,Hostle/openwrt-luci-multi-user,MinFu/luci,daofeng2015/luci,thesabbir/luci,db260179/openwrt-bpi-r1-luci,Wedmer/luci,Hostle/luci,mumuqz/luci,palmettos/test,dismantl/luci-0.12,RuiChen1113/luci,aa65535/luci,nwf/openwrt-luci,remakeelectric/luci,Hostle/luci,kuoruan/lede-luci,oyido/luci,Hostle/openwrt-luci-multi-user,NeoRaider/luci,sujeet14108/luci,RedSnake64/openwrt-luci-packages,LuttyYang/luci,taiha/luci,dismantl/luci-0.12,chris5560/openwrt-luci,david-xiao/luci,ReclaimYourPrivacy/cloak-luci,teslamint/luci,hnyman/luci,shangjiyu/luci-with-extra,kuoruan/lede-luci,artynet/luci,aircross/OpenWrt-Firefly-LuCI,bright-things/ionic-luci,Noltari/luci,harveyhu2012/luci,slayerrensky/luci,taiha/luci,kuoruan/luci,RuiChen1113/luci,openwrt-es/openwrt-luci,fkooman/luci,981213/luci-1,cappiewu/luci,Noltari/luci,dwmw2/luci,NeoRaider/luci,hnyman/luci,nmav/luci,deepak78/new-luci,kuoruan/luci,aa65535/luci,deepak78/new-luci,zhaoxx063/luci,Kyklas/luci-proto-hso,Sakura-Winkey/LuCI,Sakura-Winkey/LuCI,thesabbir/luci,nwf/openwrt-luci,cshore/luci,fkooman/luci,LazyZhu/openwrt-luci-trunk-mod,aircross/OpenWrt-Firefly-LuCI,lcf258/openwrtcn,david-xiao/luci,slayerrensky/luci,shangjiyu/luci-with-extra,david-xiao/luci,LazyZhu/openwrt-luci-trunk-mod,thess/OpenWrt-luci,openwrt-es/openwrt-luci,Kyklas/luci-proto-hso,florian-shellfire/luci,bittorf/luci,fkooman/luci,kuoruan/lede-luci,thesabbir/luci,tcatm/luci,forward619/luci,opentechinstitute/luci,ollie27/openwrt_luci,schidler/ionic-luci,ReclaimYourPrivacy/cloak-luci,tcatm/luci,teslamint/luci,RuiChen1113/luci,db260179/openwrt-bpi-r1-luci,sujeet14108/luci,jorgifumi/luci,fkooman/luci,dwmw2/luci,jlopenwrtluci/luci,oneru/luci,chris5560/openwrt-luci,teslamint/luci,palmettos/cnLuCI,taiha/luci,sujeet14108/luci,Noltari/luci,harveyhu2012/luci,daofeng2015/luci,shangjiyu/luci-with-extra,oyido/luci,artynet/luci,florian-shellfire/luci,981213/luci-1,981213/luci-1,dismantl/luci-0.12,opentechinstitute/luci,zhaoxx063/luci,harveyhu2012/luci,fkooman/luci,deepak78/new-luci,mumuqz/luci,Hostle/openwrt-luci-multi-user,RedSnake64/openwrt-luci-packages,thesabbir/luci,male-puppies/luci,mumuqz/luci,slayerrensky/luci,tcatm/luci,ollie27/openwrt_luci,ollie27/openwrt_luci,chris5560/openwrt-luci,RuiChen1113/luci,male-puppies/luci,rogerpueyo/luci,ff94315/luci-1,hnyman/luci,thess/OpenWrt-luci,obsy/luci,dwmw2/luci,joaofvieira/luci,cappiewu/luci,bittorf/luci,marcel-sch/luci,Kyklas/luci-proto-hso,rogerpueyo/luci,wongsyrone/luci-1,urueedi/luci,remakeelectric/luci,taiha/luci,oyido/luci,NeoRaider/luci,jchuang1977/luci-1,schidler/ionic-luci,Sakura-Winkey/LuCI,cshore/luci,LazyZhu/openwrt-luci-trunk-mod,aa65535/luci,db260179/openwrt-bpi-r1-luci,thesabbir/luci,oneru/luci,tobiaswaldvogel/luci,MinFu/luci,jlopenwrtluci/luci,thesabbir/luci,tobiaswaldvogel/luci,oyido/luci,urueedi/luci,aa65535/luci,981213/luci-1,sujeet14108/luci,joaofvieira/luci,MinFu/luci,nwf/openwrt-luci,thess/OpenWrt-luci,rogerpueyo/luci,bittorf/luci,schidler/ionic-luci,palmettos/cnLuCI,artynet/luci,rogerpueyo/luci,ReclaimYourPrivacy/cloak-luci,nwf/openwrt-luci,aircross/OpenWrt-Firefly-LuCI,RedSnake64/openwrt-luci-packages,obsy/luci,bright-things/ionic-luci,cappiewu/luci,RuiChen1113/luci,chris5560/openwrt-luci,cshore/luci,daofeng2015/luci,jlopenwrtluci/luci,palmettos/test,daofeng2015/luci,teslamint/luci,joaofvieira/luci,maxrio/luci981213,david-xiao/luci,Kyklas/luci-proto-hso,keyidadi/luci,slayerrensky/luci,tobiaswaldvogel/luci,jchuang1977/luci-1,cshore/luci,bittorf/luci,forward619/luci,Kyklas/luci-proto-hso,nmav/luci,cshore/luci,kuoruan/luci,ollie27/openwrt_luci,remakeelectric/luci,slayerrensky/luci,chris5560/openwrt-luci,forward619/luci,urueedi/luci,artynet/luci,ollie27/openwrt_luci,aa65535/luci,wongsyrone/luci-1,wongsyrone/luci-1,schidler/ionic-luci,cshore-firmware/openwrt-luci,jorgifumi/luci,Hostle/openwrt-luci-multi-user,zhaoxx063/luci,ff94315/luci-1,keyidadi/luci,artynet/luci,remakeelectric/luci,chris5560/openwrt-luci,LuttyYang/luci,cshore-firmware/openwrt-luci,nmav/luci,cappiewu/luci,ReclaimYourPrivacy/cloak-luci,dwmw2/luci,ollie27/openwrt_luci,mumuqz/luci,Wedmer/luci,openwrt-es/openwrt-luci,obsy/luci,palmettos/cnLuCI,981213/luci-1,dwmw2/luci,male-puppies/luci,sujeet14108/luci,remakeelectric/luci,oyido/luci,MinFu/luci,openwrt/luci,jlopenwrtluci/luci,thesabbir/luci,aa65535/luci,aircross/OpenWrt-Firefly-LuCI,teslamint/luci,openwrt/luci,lcf258/openwrtcn,sujeet14108/luci,RedSnake64/openwrt-luci-packages,ff94315/luci-1,rogerpueyo/luci,oneru/luci,ReclaimYourPrivacy/cloak-luci,LazyZhu/openwrt-luci-trunk-mod,kuoruan/lede-luci,maxrio/luci981213
ace5fd3e1d4bad863730b99cfc3a5bf97a157ef3
MM.lua
MM.lua
--[[ Module to perform matrix multiplication on two minibatch inputs, producing a minibatch. ]] local MM, parent = torch.class('nn.MM', 'nn.Module') --[[ The constructor takes two optional arguments, specifying whether or not transpose any of the input matrices before perfoming the multiplication. ]] function MM:__init(transA, transB) parent.__init(self) self.transA = transA or false self.transB = transB or false self.gradInput = {torch.Tensor(), torch.Tensor()} end function MM:updateOutput(input) assert(#input == 2, 'input must be a pair of minibatch matrices') local a, b = table.unpack(input) assert(a:nDimension() == 2 or a:nDimension() == 3, 'input tensors must be 2D or 3D') if a:nDimension() == 2 then assert(b:nDimension() == 2, 'second input tensor must be 2D') if self.transA then a = a:t() end if self.transB then b = b:t() end assert(a:size(2) == b:size(1), 'matrix sizes do not match') self.output:resize(a:size(1), b:size(2)) self.output:mm(a, b) else assert(b:nDimension() == 3, 'second input tensor must be 3D') assert(a:size(1) == b:size(1), 'inputs must contain the same number of minibatches') if self.transA then a = a:transpose(2, 3) end if self.transB then b = b:transpose(2, 3) end assert(a:size(3) == b:size(2), 'matrix sizes do not match') self.output:resize(a:size(1), a:size(2), b:size(3)) self.output:bmm(a, b) end return self.output end function MM:updateGradInput(input, gradOutput) assert(#input == 2, 'input must be a pair of tensors') local a, b = table.unpack(input) self.gradInput[1]:resizeAs(a) self.gradInput[2]:resizeAs(b) assert(gradOutput:nDimension() == 2 or gradOutput:nDimension() == 3, 'arguments must be a 2D or 3D Tensor') local h_dim, w_dim, f if gradOutput:nDimension() == 2 then assert(a:nDimension() == 2, 'first input tensor must be 2D') assert(b:nDimension() == 2, 'second input tensor must be 2D') h_dim, w_dim = 1, 2 f = "mm" else assert(a:nDimension() == 3, 'first input tensor must be 3D') assert(b:nDimension() == 3, 'second input tensor must be 3D') h_dim, w_dim = 2, 3 f = "bmm" end if self.transA == self.transB then a = a:transpose(h_dim, w_dim) b = b:transpose(h_dim, w_dim) end if self.transA then self.gradInput[1][f](self.gradInput[1], b, gradOutput:transpose(h_dim, w_dim)) else self.gradInput[1][f](self.gradInput[1], gradOutput, b) end if self.transB then self.gradInput[2][f](self.gradInput[2], gradOutput:transpose(h_dim, w_dim), a) else self.gradInput[2][f](self.gradInput[2], a, gradOutput) end return self.gradInput end
--[[ Module to perform matrix multiplication on two minibatch inputs, producing a minibatch. ]] local MM, parent = torch.class('nn.MM', 'nn.Module') --[[ The constructor takes two optional arguments, specifying whether or not transpose any of the input matrices before perfoming the multiplication. ]] function MM:__init(transA, transB) parent.__init(self) self.transA = transA or false self.transB = transB or false self.gradInput = {torch.Tensor(), torch.Tensor()} end function MM:updateOutput(input) assert(#input == 2, 'input must be a pair of minibatch matrices') local a, b = table.unpack(input) assert(a:nDimension() == 2 or a:nDimension() == 3, 'input tensors must be 2D or 3D') if a:nDimension() == 2 then assert(b:nDimension() == 2, 'second input tensor must be 2D') if self.transA then a = a:t() end if self.transB then b = b:t() end assert(a:size(2) == b:size(1), 'matrix sizes do not match') self.output:resize(a:size(1), b:size(2)) self.output:mm(a, b) else assert(b:nDimension() == 3, 'second input tensor must be 3D') assert(a:size(1) == b:size(1), 'inputs must contain the same number of minibatches') if self.transA then a = a:transpose(2, 3) end if self.transB then b = b:transpose(2, 3) end assert(a:size(3) == b:size(2), 'matrix sizes do not match') self.output:resize(a:size(1), a:size(2), b:size(3)) self.output:bmm(a, b) end return self.output end function MM:updateGradInput(input, gradOutput) self.gradInput[1] = self.gradInput[1] or input[1].new() self.gradInput[2] = self.gradInput[2] or input[2].new() assert(#input == 2, 'input must be a pair of tensors') local a, b = table.unpack(input) self.gradInput[1]:resizeAs(a) self.gradInput[2]:resizeAs(b) assert(gradOutput:nDimension() == 2 or gradOutput:nDimension() == 3, 'arguments must be a 2D or 3D Tensor') local h_dim, w_dim, f if gradOutput:nDimension() == 2 then assert(a:nDimension() == 2, 'first input tensor must be 2D') assert(b:nDimension() == 2, 'second input tensor must be 2D') h_dim, w_dim = 1, 2 f = "mm" else assert(a:nDimension() == 3, 'first input tensor must be 3D') assert(b:nDimension() == 3, 'second input tensor must be 3D') h_dim, w_dim = 2, 3 f = "bmm" end if self.transA == self.transB then a = a:transpose(h_dim, w_dim) b = b:transpose(h_dim, w_dim) end if self.transA then self.gradInput[1][f](self.gradInput[1], b, gradOutput:transpose(h_dim, w_dim)) else self.gradInput[1][f](self.gradInput[1], gradOutput, b) end if self.transB then self.gradInput[2][f](self.gradInput[2], gradOutput:transpose(h_dim, w_dim), a) else self.gradInput[2][f](self.gradInput[2], a, gradOutput) end return self.gradInput end
fix MM after :clearState() has been called
fix MM after :clearState() has been called
Lua
bsd-3-clause
kmul00/nn,sagarwaghmare69/nn,nicholas-leonard/nn,apaszke/nn,diz-vara/nn,joeyhng/nn,colesbury/nn,eriche2016/nn,PraveerSINGH/nn,jonathantompson/nn
8a2de15f8d23f64d27c24448ac2db2be218c0a06
lib/lux/oo/class.lua
lib/lux/oo/class.lua
--[[ -- -- Copyright (c) 2013-2014 Wilson Kazuo Mizutani -- -- This software is provided 'as-is', without any express or implied -- warranty. In no event will the authors be held liable for any damages -- arising from the use of this software. -- -- Permission is granted to anyone to use this software for any purpose, -- including commercial applications, and to alter it and redistribute it -- freely, subject to the following restrictions: -- -- 1. The origin of this software must not be misrepresented; you must not -- claim that you wrote the original software. If you use this software -- in a product, an acknowledgment in the product documentation would be -- appreciated but is not required. -- -- 2. Altered source versions must be plainly marked as such, and must not be -- misrepresented as being the original software. -- -- 3. This notice may not be removed or altered from any source -- distribution. -- --]] --- LUX's object-oriented feature module. -- This module provides some basic functionalities for object-oriented -- programming in Lua. It is divided in two parts, which you can @{require} -- separately. -- -- <h2><code>lux.oo.prototype</code></h2> -- -- This part provides a prototype-based implementation. It returns the root -- prototype object, with which you can create new objects using -- @{prototype:new}. Objects created this way automatically inherit fields and -- methods from their parent, but may override them. It is not possible to -- inherit from multiple objects. For usage instructions, refer to -- @{prototype}. -- -- <h2><code>lux.oo.class</code></h2> -- -- This part provides a class-based implementation. It returns a special table -- @{class} through which you can define classes. As of the current version of -- LUX, there is no support for inheritance. -- -- @module lux.oo --- A special table for defining classes. -- By defining a named method in it, a new class is created. It uses the given -- method to create its instances. Once defined, the class can be retrieved by -- using accessing the @{class} table with its name. -- -- Since the fields are declared in a scope of -- their own, local variables are kept their closures. Thus, it is -- possible to have private members. Public member can be created by not using -- the <code>local</code> keyword or explicitly referring to <code>self</code> -- within the class definition. -- -- Inheritance is possible through a special field in the classes, 'inheritAs'. -- You use it the same way you the declare classes with @{class}. -- -- @feature class -- @usage -- local class = require 'lux.oo.class' -- function class:MyClass() -- local a_number = 42 -- function show () -- print(a_number) -- end -- end -- function class.MyClass.inheritAs:MyChildClass() -- local a_string = "foo" -- function show_twice () -- show() -- show() -- end -- end -- local class = {} local port = require 'lux.portable' local lambda = require 'lux.functional' local classes = {} local definition_scope = {} local no_op = function () end local function makeEmptyObject (the_class) return { __inherit = class, __class = the_class, __meta = { __index = _G }, } end local function construct (the_class, obj, ...) if not obj or obj == class then obj = makeEmptyObject(the_class) end setmetatable(obj, definition_scope) assert(port.loadWithEnv(the_class.definition, obj)) (obj, ...) rawset(obj, the_class.name, lambda.bindLeft(construct, the_class, nil)) -- Call constructor if available setmetatable(obj, obj.__meta); return obj end definition_scope.__index = _G function definition_scope.__newindex (obj, key, value) if type(value) == 'function' then rawset(obj, key, function(_, ...) return value(...) end) end end function class:define (name, definition) assert(not classes[name], "Redefinition of class '"..name.."'") local new_class = { name = name, definition = definition, __isclass = true } setmetatable(new_class, { __call = construct }) classes[name] = new_class end function class:forName (name) return classes[name] end setmetatable(class, { __index = class.forName, __newindex = class.define }) return class
--[[ -- -- Copyright (c) 2013-2014 Wilson Kazuo Mizutani -- -- This software is provided 'as-is', without any express or implied -- warranty. In no event will the authors be held liable for any damages -- arising from the use of this software. -- -- Permission is granted to anyone to use this software for any purpose, -- including commercial applications, and to alter it and redistribute it -- freely, subject to the following restrictions: -- -- 1. The origin of this software must not be misrepresented; you must not -- claim that you wrote the original software. If you use this software -- in a product, an acknowledgment in the product documentation would be -- appreciated but is not required. -- -- 2. Altered source versions must be plainly marked as such, and must not be -- misrepresented as being the original software. -- -- 3. This notice may not be removed or altered from any source -- distribution. -- --]] --- LUX's object-oriented feature module. -- This module provides some basic functionalities for object-oriented -- programming in Lua. It is divided in two parts, which you can @{require} -- separately. -- -- <h2><code>lux.oo.prototype</code></h2> -- -- This part provides a prototype-based implementation. It returns the root -- prototype object, with which you can create new objects using -- @{prototype:new}. Objects created this way automatically inherit fields and -- methods from their parent, but may override them. It is not possible to -- inherit from multiple objects. For usage instructions, refer to -- @{prototype}. -- -- <h2><code>lux.oo.class</code></h2> -- -- This part provides a class-based implementation. It returns a special table -- @{class} through which you can define classes. As of the current version of -- LUX, there is no support for inheritance. -- -- @module lux.oo --- A special table for defining classes. -- By defining a named method in it, a new class is created. It uses the given -- method to create its instances. Once defined, the class can be retrieved by -- using accessing the @{class} table with its name. -- -- Since the fields are declared in a scope of -- their own, local variables are kept their closures. Thus, it is -- possible to have private members. Public member can be created by not using -- the <code>local</code> keyword or explicitly referring to <code>self</code> -- within the class definition. -- -- Inheritance is possible through a special field in the classes, '__inherit'. -- You use it inside the class definition passing self as the first parameter. -- -- @feature class -- @usage -- local class = require 'lux.oo.class' -- function class:MyClass() -- local a_number = 42 -- function show () -- print(a_number) -- end -- end -- function class:MyChildClass() -- __inherit.MyClass(self) -- local a_string = "foo" -- function show_twice () -- show() -- show() -- end -- end -- local class = {} local port = require 'lux.portable' local lambda = require 'lux.functional' local classes = {} local definition_scope = {} local no_op = function () end local function makeEmptyObject (the_class) return { __inherit = class, __class = the_class, __meta = { __index = _G }, } end local function construct (the_class, obj, ...) if not obj or obj == class then obj = makeEmptyObject(the_class) end setmetatable(obj, definition_scope) assert(port.loadWithEnv(the_class.definition, obj)) (obj, ...) rawset(obj, the_class.name, lambda.bindLeft(construct, the_class, nil)) -- Call constructor if available setmetatable(obj, obj.__meta); return obj end definition_scope.__index = _G function definition_scope.__newindex (obj, key, value) if type(value) == 'function' then rawset(obj, key, function(_, ...) return value(...) end) end end function class:define (name, definition) assert(not classes[name], "Redefinition of class '"..name.."'") local new_class = { name = name, definition = definition, __isclass = true } setmetatable(new_class, { __call = construct }) classes[name] = new_class end function class:forName (name) return classes[name] end setmetatable(class, { __index = class.forName, __newindex = class.define }) return class
[oo] Minor reference fix
[oo] Minor reference fix
Lua
mit
Kazuo256/luxproject
05bfd00d1f3b699451143dbb18e069fdb3acac7c
modules/game_interface/widgets/uiitem.lua
modules/game_interface/widgets/uiitem.lua
function UIItem:onDragEnter(mousePos) if self:isVirtual() then return false end local item = self:getItem() if not item then return false end self:setBorderWidth(1) self.currentDragThing = item g_mouse.setTargetCursor() return true end function UIItem:onDragLeave(droppedWidget, mousePos) if self:isVirtual() then return false end self.currentDragThing = nil g_mouse.restoreCursor() self:setBorderWidth(0) return true end function UIItem:onDrop(widget, mousePos) if self:isVirtual() then return false end if not widget or not widget.currentDragThing then return false end local item = widget.currentDragThing if not item:isItem() then return false end local toPos = self.position local itemPos = item:getPosition() if itemPos.x == toPos.x and itemPos.y == toPos.y and itemPos.z == toPos.z then return false end if item:getCount() > 1 then modules.game_interface.moveStackableItem(item, toPos) else g_game.move(item, toPos, 1) end self:setBorderWidth(0) return true end function UIItem:onHoverChange(hovered) UIWidget.onHoverChange(self, hovered) if self:isVirtual() then return end local draggingWidget = g_ui.getDraggingWidget() if draggingWidget and self ~= draggingWidget then local gotMap = draggingWidget:getClassName() == 'UIMap' local gotItem = draggingWidget:getClassName() == 'UIItem' and not draggingWidget:isVirtual() if hovered and (gotItem or gotMap) then self:setBorderWidth(1) else self:setBorderWidth(0) end end end function UIItem:onMouseRelease(mousePosition, mouseButton) if self.cancelNextRelease then self.cancelNextRelease = false return true end if self:isVirtual() then return false end local item = self:getItem() if not item or not self:containsPoint(mousePosition) then return false end if Options.getOption('classicControl') and ((g_mouse.isPressed(MouseLeftButton) and mouseButton == MouseRightButton) or (g_mouse.isPressed(MouseRightButton) and mouseButton == MouseLeftButton)) then g_game.look(item) self.cancelNextRelease = true return true elseif modules.game_interface.processMouseAction(mousePosition, mouseButton, nil, item, item, nil, item) then return true end return false end
function UIItem:onDragEnter(mousePos) if self:isVirtual() then return false end local item = self:getItem() if not item then return false end self:setBorderWidth(1) self.currentDragThing = item g_mouse.setTargetCursor() return true end function UIItem:onDragLeave(droppedWidget, mousePos) if self:isVirtual() then return false end self.currentDragThing = nil g_mouse.restoreCursor() self:setBorderWidth(0) self.hoveredWho = nil return true end function UIItem:onDrop(widget, mousePos) if self:isVirtual() then return false end if not widget or not widget.currentDragThing then return false end local item = widget.currentDragThing if not item:isItem() then return false end local toPos = self.position local itemPos = item:getPosition() if itemPos.x == toPos.x and itemPos.y == toPos.y and itemPos.z == toPos.z then return false end if item:getCount() > 1 then modules.game_interface.moveStackableItem(item, toPos) else g_game.move(item, toPos, 1) end self:setBorderWidth(0) return true end function UIItem:onDestroy() if self == g_ui.getDraggingWidget() and self.hoveredWho then self.hoveredWho:setBorderWidth(0) self.hoveredWho = nil end end function UIItem:onHoverChange(hovered) UIWidget.onHoverChange(self, hovered) if self:isVirtual() then return end local draggingWidget = g_ui.getDraggingWidget() if draggingWidget and self ~= draggingWidget then local gotMap = draggingWidget:getClassName() == 'UIMap' local gotItem = draggingWidget:getClassName() == 'UIItem' and not draggingWidget:isVirtual() if hovered and (gotItem or gotMap) then self:setBorderWidth(1) draggingWidget.hoveredWho = self else self:setBorderWidth(0) draggingWidget.hoveredWho = nil end end end function UIItem:onMouseRelease(mousePosition, mouseButton) if self.cancelNextRelease then self.cancelNextRelease = false return true end if self:isVirtual() then return false end local item = self:getItem() if not item or not self:containsPoint(mousePosition) then return false end if Options.getOption('classicControl') and ((g_mouse.isPressed(MouseLeftButton) and mouseButton == MouseRightButton) or (g_mouse.isPressed(MouseRightButton) and mouseButton == MouseLeftButton)) then g_game.look(item) self.cancelNextRelease = true return true elseif modules.game_interface.processMouseAction(mousePosition, mouseButton, nil, item, item, nil, item) then return true end return false end
Fixed a hover bug with UIItem
Fixed a hover bug with UIItem
Lua
mit
gpedro/otclient,EvilHero90/otclient,dreamsxin/otclient,Radseq/otclient,gpedro/otclient,dreamsxin/otclient,kwketh/otclient,dreamsxin/otclient,Cavitt/otclient_mapgen,EvilHero90/otclient,kwketh/otclient,Cavitt/otclient_mapgen,gpedro/otclient,Radseq/otclient
8412532479f60ad6987f8a98dc6f0847bb17feaa
fontchooser.lua
fontchooser.lua
require "rendertext" require "keys" require "graphics" FontChooser = { -- font for displaying file/dir names face = freetype.newBuiltinFace("sans", 25), fhash = "s25", -- font for page title tface = freetype.newBuiltinFace("Helvetica-BoldOblique", 32), tfhash = "hbo32", -- font for paging display sface = freetype.newBuiltinFace("sans", 16), sfhash = "s16", -- spacing between lines spacing = 40, -- state buffer fonts = {"sans", "cjk", "mono", "Courier", "Courier-Bold", "Courier-Oblique", "Courier-BoldOblique", "Helvetica", "Helvetica-Oblique", "Helvetica-BoldOblique", "Times-Roman", "Times-Bold", "Times-Italic", "Times-BoldItalic",}, items = 14, page = 1, current = 2, oldcurrent = 1, } function FontChooser:init() self.items = #self.fonts table.sort(self.fonts) end function FontChooser:choose(ypos, height) local perpage = math.floor(height / self.spacing) - 1 local pagedirty = true local markerdirty = false local prevItem = function () if self.current == 2 then if self.page > 1 then self.current = perpage self.page = self.page - 1 pagedirty = true end else self.current = self.current - 1 markerdirty = true end end local nextItem = function () if self.current == perpage then if self.page < (self.items / perpage) then self.current = 1 self.page = self.page + 1 pagedirty = true end else if self.page ~= math.floor(self.items / perpage) + 1 or self.current + (self.page-1)*perpage < self.items then self.current = self.current + 1 markerdirty = true end end end while true do if pagedirty then fb.bb:paintRect(0, ypos, fb.bb:getWidth(), height, 0) renderUtf8Text(fb.bb, 30, ypos + self.spacing, self.tface, self.tfhash, "[ Fonts Menu ]", true) local c for c = 2, perpage do local i = (self.page - 1) * perpage + c if i <= self.items then renderUtf8Text(fb.bb, 50, ypos + self.spacing*c, self.face, self.fhash, self.fonts[i], true) end end renderUtf8Text(fb.bb, 39, ypos + self.spacing * perpage + 32, self.sface, self.sfhash, "Page "..self.page.." of "..(math.floor(self.items / perpage)+1), true) markerdirty = true end if markerdirty then if not pagedirty then if self.oldcurrent > 0 then fb.bb:paintRect(30, ypos + self.spacing*self.oldcurrent + 10, fb.bb:getWidth() - 60, 3, 0) fb:refresh(1, 30, ypos + self.spacing*self.oldcurrent + 10, fb.bb:getWidth() - 60, 3) end end fb.bb:paintRect(30, ypos + self.spacing*self.current + 10, fb.bb:getWidth() - 60, 3, 15) if not pagedirty then fb:refresh(1, 30, ypos + self.spacing*self.current + 10, fb.bb:getWidth() - 60, 3) end self.oldcurrent = self.current markerdirty = false end if pagedirty then fb:refresh(0, 0, ypos, fb.bb:getWidth(), height) pagedirty = false end local ev = input.waitForEvent() if ev.type == EV_KEY and ev.value == EVENT_VALUE_KEY_PRESS then if ev.code == KEY_FW_UP then prevItem() elseif ev.code == KEY_FW_DOWN then nextItem() elseif ev.code == KEY_PGFWD then if self.page < (self.items / perpage) then if self.current + self.page*perpage > self.items then self.current = self.items - self.page*perpage end self.page = self.page + 1 pagedirty = true else self.current = self.items - (self.page-1)*perpage markerdirty = true end elseif ev.code == KEY_PGBCK then if self.page > 1 then self.page = self.page - 1 pagedirty = true else self.current = 2 markerdirty = true end elseif ev.code == KEY_ENTER or ev.code == KEY_FW_PRESS then local newface = self.fonts[perpage*(self.page-1)+self.current] return newface elseif ev.code == KEY_BACK then return nil end end end end
require "rendertext" require "keys" require "graphics" FontChooser = { -- font for displaying file/dir names face = freetype.newBuiltinFace("sans", 25), fhash = "s25", -- font for page title tface = freetype.newBuiltinFace("Helvetica-BoldOblique", 32), tfhash = "hbo32", -- font for paging display sface = freetype.newBuiltinFace("sans", 16), sfhash = "s16", -- title height title_H = 45, -- spacing between lines spacing = 40, -- foot height foot_H = 27, -- state buffer fonts = {"sans", "cjk", "mono", "Courier", "Courier-Bold", "Courier-Oblique", "Courier-BoldOblique", "Helvetica", "Helvetica-Oblique", "Helvetica-BoldOblique", "Times-Roman", "Times-Bold", "Times-Italic", "Times-BoldItalic",}, items = 14, page = 1, current = 2, oldcurrent = 1, } function FontChooser:init() self.items = #self.fonts table.sort(self.fonts) end function FontChooser:choose(ypos, height) local perpage = math.floor(height / self.spacing) - 2 local pagedirty = true local markerdirty = false local prevItem = function () if self.current == 1 then if self.page > 1 then self.current = perpage self.page = self.page - 1 pagedirty = true end else self.current = self.current - 1 markerdirty = true end end local nextItem = function () if self.current == perpage then if self.page < (self.items / perpage) then self.current = 1 self.page = self.page + 1 pagedirty = true end else if self.page ~= math.floor(self.items / perpage) + 1 or self.current + (self.page-1)*perpage < self.items then self.current = self.current + 1 markerdirty = true end end end -- draw menu title fb.bb:paintRect(0, ypos, fb.bb:getWidth(), height, 0) renderUtf8Text(fb.bb, 30, ypos + self.spacing, self.tface, self.tfhash, "[ Fonts Menu ]", true) fb:refresh(0, 0, ypos, fb.bb:getWidth(), self.title_H) while true do if pagedirty then fb.bb:paintRect(0, ypos, fb.bb:getWidth(), height, 0) --renderUtf8Text(fb.bb, 30, ypos + self.spacing, self.tface, self.tfhash, "[ Fonts Menu ]", true) local c for c = 1, perpage do local i = (self.page - 1) * perpage + c if i <= self.items then y = ypos + self.title_H + (self.spacing * c) renderUtf8Text(fb.bb, 50, y, self.face, self.fhash, self.fonts[i], true) end end y = ypos + self.title_H + (self.spacing * perpage) + self.foot_H x = (fb.bb:getWidth() / 2) - 50 renderUtf8Text(fb.bb, x, y, self.sface, self.sfhash, "Page "..self.page.." of "..(math.floor(self.items / perpage)+1), true) markerdirty = true end if markerdirty then if not pagedirty then if self.oldcurrent > 0 then y = ypos + self.title_H + (self.spacing * self.oldcurrent) + 10 fb.bb:paintRect(30, y, fb.bb:getWidth() - 60, 3, 0) fb:refresh(1, 30, y, fb.bb:getWidth() - 60, 3) end end y = ypos + self.title_H + (self.spacing * self.current) + 10 fb.bb:paintRect(30, y, fb.bb:getWidth() - 60, 3, 15) if not pagedirty then fb:refresh(1, 30, y, fb.bb:getWidth() - 60, 3) end self.oldcurrent = self.current markerdirty = false end if pagedirty then fb:refresh(0, 0, ypos + self.title_H, fb.bb:getWidth(), height - self.title_H) pagedirty = false end local ev = input.waitForEvent() if ev.type == EV_KEY and ev.value == EVENT_VALUE_KEY_PRESS then if ev.code == KEY_FW_UP then prevItem() elseif ev.code == KEY_FW_DOWN then nextItem() elseif ev.code == KEY_PGFWD then if self.page < (self.items / perpage) then if self.current + self.page*perpage > self.items then self.current = self.items - self.page*perpage end self.page = self.page + 1 pagedirty = true else self.current = self.items - (self.page-1)*perpage markerdirty = true end elseif ev.code == KEY_PGBCK then if self.page > 1 then self.page = self.page - 1 pagedirty = true else self.current = 2 markerdirty = true end elseif ev.code == KEY_ENTER or ev.code == KEY_FW_PRESS then local newface = self.fonts[perpage*(self.page-1)+self.current] return newface elseif ev.code == KEY_BACK then return nil end end end end
fix: adjust perpage item according to title height
fix: adjust perpage item according to title height
Lua
agpl-3.0
houqp/koreader-base,chihyang/koreader,frankyifei/koreader-base,NiLuJe/koreader-base,Frenzie/koreader-base,houqp/koreader,NiLuJe/koreader,lgeek/koreader,noname007/koreader,poire-z/koreader,ashhher3/koreader,koreader/koreader,houqp/koreader-base,NiLuJe/koreader,Frenzie/koreader,apletnev/koreader,Frenzie/koreader-base,frankyifei/koreader-base,Hzj-jie/koreader,apletnev/koreader-base,koreader/koreader-base,Frenzie/koreader-base,NiLuJe/koreader-base,frankyifei/koreader,Hzj-jie/koreader-base,Hzj-jie/koreader-base,Hzj-jie/koreader-base,koreader/koreader-base,frankyifei/koreader-base,Frenzie/koreader-base,NiLuJe/koreader-base,apletnev/koreader-base,ashang/koreader,apletnev/koreader-base,koreader/koreader-base,frankyifei/koreader-base,Frenzie/koreader,Markismus/koreader,koreader/koreader-base,mihailim/koreader,mwoz123/koreader,koreader/koreader,pazos/koreader,houqp/koreader-base,houqp/koreader-base,Hzj-jie/koreader-base,chrox/koreader,poire-z/koreader,robert00s/koreader,NiLuJe/koreader-base,apletnev/koreader-base,NickSavage/koreader
461cbc17066956026ae7a94be04361ac1d40b48e
nyagos.d/catalog/subcomplete.lua
nyagos.d/catalog/subcomplete.lua
local maincmds = {} local githelp=io.popen("git help -a 2>nul","r") if githelp then local gitcmds={} for line in githelp:lines() do if string.match(line,"^ %S") then for word in string.gmatch(line,"%S+") do gitcmds[ #gitcmds+1 ] = word end end end githelp:close() if #gitcmds > 1 then maincmds["git"] = gitcmds end end local svnhelp=io.popen("svn help 2>nul","r") if svnhelp then local svncmds={} for line in svnhelp:lines() do local m=string.match(line,"^ ([a-z]+)") if m then svncmds[ #svncmds+1 ] = m end end svnhelp:close() if #svncmds > 1 then maincmds["svn"] = svncmds end end local hghelp=io.popen("hg debugcomplete 2>nul","r") if hghelp then local hgcmds={} for line in hghelp:lines() do for word in string.gmatch(line,"[a-z]+") do hgcmds[#hgcmds+1] = word end end hghelp:close() if #hgcmds > 1 then maincmds["hg"] = hgcmds end end if next(maincmds) then nyagos.completion_hook = function(c) if c.pos <= 1 then return nil end local cmdname = string.match(c.text,"^%S+") if not cmdname then return nil end local subcmds = maincmds[cmdname] if not subcmds then return nil end for i=1,#subcmds do table.insert(c.list,subcmds[i]) end return c.list end end
share.maincmds = {} local githelp=io.popen("git help -a 2>nul","r") if githelp then local gitcmds={} for line in githelp:lines() do if string.match(line,"^ %S") then for word in string.gmatch(line,"%S+") do gitcmds[ #gitcmds+1 ] = word end end end githelp:close() if #gitcmds > 1 then local maincmds = share.maincmds maincmds["git"] = gitcmds share.maincmds = maincmds end end local svnhelp=io.popen("svn help 2>nul","r") if svnhelp then local svncmds={} for line in svnhelp:lines() do local m=string.match(line,"^ ([a-z]+)") if m then svncmds[ #svncmds+1 ] = m end end svnhelp:close() if #svncmds > 1 then local maincmds = share.maincmds maincmds["svn"] = svncmds share.maincmds = maincmds end end local hghelp=io.popen("hg debugcomplete 2>nul","r") if hghelp then local hgcmds={} for line in hghelp:lines() do for word in string.gmatch(line,"[a-z]+") do hgcmds[#hgcmds+1] = word end end hghelp:close() if #hgcmds > 1 then local maincmds=share.maincmds maincmds["hg"] = hgcmds share.maincmds = maincmds end end if next(share.maincmds) then nyagos.completion_hook = function(c) if c.pos <= 1 then return nil end local cmdname = string.match(c.text,"^%S+") if not cmdname then return nil end local subcmds = share.maincmds[cmdname] if not subcmds then return nil end for i=1,#subcmds do table.insert(c.list,subcmds[i]) end return c.list end end
Fix that subcomplete.lua used local-scope function, which is not able to be called after 4.1 (#135)
Fix that subcomplete.lua used local-scope function, which is not able to be called after 4.1 (#135)
Lua
bsd-3-clause
tsuyoshicho/nyagos,tyochiai/nyagos,zetamatta/nyagos,nocd5/nyagos
25d68a70b73f1d151301b15b8455619065fad4ac
script/c81587028.lua
script/c81587028.lua
--Box of Friends function c81587028.initial_effect(c) --spsummon local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(81587028,1)) e2:SetCategory(CATEGORY_SPECIAL_SUMMON) e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e2:SetProperty(EFFECT_FLAG_DAMAGE_STEP+EFFECT_FLAG_DELAY) e2:SetCode(EVENT_TO_GRAVE) e2:SetCondition(c81587028.spcon) e2:SetCost(c81587028.spcost) e2:SetTarget(c81587028.sptg) e2:SetOperation(c81587028.spop) c:RegisterEffect(e2) end function c81587028.spcon(e,tp,eg,ep,ev,re,r,rp) return e:GetHandler():IsReason(REASON_DESTROY) end function c81587028.spcost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetFlagEffect(tp,81587028)==0 end Duel.RegisterFlagEffect(tp,81587028,RESET_PHASE+PHASE_END,EFFECT_FLAG_OATH,1) end function c81587028.filter(c,e,tp) return c:IsType(TYPE_NORMAL) and (c:GetAttack()==0 or c:GetDefence()==0) and c:IsCanBeSpecialSummoned(e,0,tp,false,false) and Duel.IsExistingMatchingCard(c81587028.filter2,tp,LOCATION_DECK,0,1,nil,e,tp,c:GetCode()) end function c81587028.filter2(c,e,tp,code) return c:IsType(TYPE_NORMAL) and (c:GetAttack()==0 or c:GetDefence()==0) and c:IsCanBeSpecialSummoned(e,0,tp,false,false) and not c:IsCode(code) end function c81587028.sptg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>1 and Duel.IsExistingMatchingCard(c81587028.filter,tp,LOCATION_DECK,0,1,nil,e,tp) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,2,tp,LOCATION_DECK) end function c81587028.spop(e,tp,eg,ep,ev,re,r,rp) if Duel.GetLocationCount(tp,LOCATION_MZONE)<2 then return end if not Duel.IsExistingMatchingCard(c81587028.filter,tp,LOCATION_DECK,0,1,nil,e,tp) then return end local tc1=Duel.SelectMatchingCard(tp,c81587028.filter,tp,LOCATION_DECK,0,1,1,nil,e,tp):GetFirst() local tc2=Duel.SelectMatchingCard(tp,c81587028.filter2,tp,LOCATION_DECK,0,1,1,nil,e,tp,tc1:GetCode()):GetFirst() local sg=Group.FromCards(tc1,tc2) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) Duel.SpecialSummonStep(tc1,0,tp,tp,false,false,POS_FACEUP_DEFENCE) Duel.SpecialSummonStep(tc2,0,tp,tp,false,false,POS_FACEUP_DEFENCE) tc1:RegisterFlagEffect(81587028,RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END,0,1) tc2:RegisterFlagEffect(81587028,RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END,0,1) Duel.SpecialSummonComplete() sg:KeepAlive() local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS) e1:SetCode(EVENT_PHASE+PHASE_END) e1:SetReset(RESET_PHASE+PHASE_END) e1:SetCountLimit(1) e1:SetLabelObject(sg) e1:SetOperation(c81587028.desop) Duel.RegisterEffect(e1,tp) local e2=Effect.CreateEffect(e:GetHandler()) e2:SetType(EFFECT_TYPE_SINGLE) e2:SetCode(EFFECT_CANNOT_BE_SYNCHRO_MATERIAL) e2:SetProperty(EFFECT_FLAG_UNCOPYABLE) e2:SetValue(1) e2:SetReset(RESET_EVENT+0x1fe0000) tc1:RegisterEffect(e2,true) tc2:RegisterEffect(e2,true) end function c81587028.desfilter(c) return c:GetFlagEffect(81587028)>0 end function c81587028.desop(e,tp,eg,ep,ev,re,r,rp) local g=e:GetLabelObject() local tg=g:Filter(c81587028.desfilter,nil) g:DeleteGroup() Duel.Destroy(tg,REASON_EFFECT) end
--Box of Friends function c81587028.initial_effect(c) --spsummon local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(81587028,1)) e2:SetCategory(CATEGORY_SPECIAL_SUMMON) e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e2:SetProperty(EFFECT_FLAG_DAMAGE_STEP+EFFECT_FLAG_DELAY) e2:SetCode(EVENT_TO_GRAVE) e2:SetCondition(c81587028.spcon) e2:SetCost(c81587028.spcost) e2:SetTarget(c81587028.sptg) e2:SetOperation(c81587028.spop) c:RegisterEffect(e2) end function c81587028.spcon(e,tp,eg,ep,ev,re,r,rp) return e:GetHandler():IsReason(REASON_DESTROY) end function c81587028.spcost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetFlagEffect(tp,81587028)==0 end Duel.RegisterFlagEffect(tp,81587028,RESET_PHASE+PHASE_END,EFFECT_FLAG_OATH,1) end function c81587028.filter(c,e,tp) return c:IsType(TYPE_NORMAL) and (c:GetAttack()==0 or c:GetDefence()==0) and c:IsCanBeSpecialSummoned(e,0,tp,false,false) and Duel.IsExistingMatchingCard(c81587028.filter2,tp,LOCATION_DECK,0,1,nil,e,tp,c:GetCode()) end function c81587028.filter2(c,e,tp,code) return c:IsType(TYPE_NORMAL) and (c:GetAttack()==0 or c:GetDefence()==0) and c:IsCanBeSpecialSummoned(e,0,tp,false,false) and not c:IsCode(code) end function c81587028.sptg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>1 and Duel.IsExistingMatchingCard(c81587028.filter,tp,LOCATION_DECK,0,1,nil,e,tp) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,2,tp,LOCATION_DECK) end function c81587028.spop(e,tp,eg,ep,ev,re,r,rp) if Duel.GetLocationCount(tp,LOCATION_MZONE)<2 then return end if not Duel.IsExistingMatchingCard(c81587028.filter,tp,LOCATION_DECK,0,1,nil,e,tp) then return end local tc1=Duel.SelectMatchingCard(tp,c81587028.filter,tp,LOCATION_DECK,0,1,1,nil,e,tp):GetFirst() local tc2=Duel.SelectMatchingCard(tp,c81587028.filter2,tp,LOCATION_DECK,0,1,1,nil,e,tp,tc1:GetCode()):GetFirst() local sg=Group.FromCards(tc1,tc2) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) Duel.SpecialSummonStep(tc1,0,tp,tp,false,false,POS_FACEUP_DEFENCE) Duel.SpecialSummonStep(tc2,0,tp,tp,false,false,POS_FACEUP_DEFENCE) Duel.SpecialSummonComplete() sg:KeepAlive() local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS) e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE) e1:SetCode(EVENT_PHASE+PHASE_END) e1:SetCountLimit(1) e1:SetLabelObject(sg) e1:SetCondition(c81587028.descon) e1:SetOperation(c81587028.desop) if Duel.GetCurrentPhase()==PHASE_END and Duel.GetTurnPlayer()==tp then e1:SetLabel(1) e1:SetReset(RESET_PHASE+PHASE_END+RESET_SELF_TURN,2) tc1:RegisterFlagEffect(81587028,RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END+RESET_SELF_TURN,0,2) tc2:RegisterFlagEffect(81587028,RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END+RESET_SELF_TURN,0,2) else e1:SetReset(RESET_PHASE+PHASE_END+RESET_SELF_TURN) tc1:RegisterFlagEffect(81587028,RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END+RESET_SELF_TURN,0,1) tc2:RegisterFlagEffect(81587028,RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END+RESET_SELF_TURN,0,1) end Duel.RegisterEffect(e1,tp) local e2=Effect.CreateEffect(e:GetHandler()) e2:SetType(EFFECT_TYPE_SINGLE) e2:SetCode(EFFECT_CANNOT_BE_SYNCHRO_MATERIAL) e2:SetProperty(EFFECT_FLAG_UNCOPYABLE) e2:SetValue(1) e2:SetReset(RESET_EVENT+0x1fe0000) tc1:RegisterEffect(e2,true) tc2:RegisterEffect(e2,true) end function c81587028.descon(e,tp) return Duel.GetTurnPlayer()==tp end function c81587028.desfilter(c) return c:GetFlagEffect(81587028)>0 end function c81587028.desop(e,tp,eg,ep,ev,re,r,rp) if e:GetLabel()==0 then local g=e:GetLabelObject() local tg=g:Filter(c81587028.desfilter,nil) g:DeleteGroup() Duel.Destroy(tg,REASON_EFFECT) else e:SetLabel(0) end end
Update c81587028.lua
Update c81587028.lua fix
Lua
mit
SuperAndroid17/DevProLauncher,sidschingis/DevProLauncher,Tic-Tac-Toc/DevProLauncher
c5c844960ffc68bf7b701b0fbb1577b79fd2b15c
xmake/core/main.lua
xmake/core/main.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 ruki -- @file main.lua -- -- define module: main local main = main or {} -- load modules local os = require("base/os") local path = require("base/path") local utils = require("base/utils") local option = require("base/option") local profiler = require("base/profiler") local deprecated = require("base/deprecated") local task = require("project/task") local history = require("project/history") -- init the option menu local menu = { -- title title = "XMake v" .. xmake._VERSION .. ", The Make-like Build Utility based on Lua" -- copyright , copyright = "Copyright (C) 2015-2016 Ruki Wang, ${underline}tboox.org${clear}, ${underline}xmake.io${clear}\nCopyright (C) 2005-2015 Mike Pall, ${underline}luajit.org${clear}" -- the tasks: xmake [task] , task.menu } -- done help function main._help() -- done help if option.get("help") then -- print menu option.show_menu(option.taskname()) -- ok return true -- done version elseif option.get("version") then -- print title if menu.title then utils.cprint(menu.title) end -- print copyright if menu.copyright then utils.cprint(menu.copyright) end -- ok return true end end -- the init function for main function main._init() -- init the project directory local projectdir = option.find(xmake._ARGV, "project", "P") or xmake._PROJECT_DIR if projectdir and not path.is_absolute(projectdir) then projectdir = path.absolute(projectdir) elseif projectdir then projectdir = path.translate(projectdir) end xmake._PROJECT_DIR = projectdir assert(projectdir) -- init the xmake.lua file path local projectfile = option.find(xmake._ARGV, "file", "F") or xmake._PROJECT_FILE if projectfile and not path.is_absolute(projectfile) then projectfile = path.absolute(projectfile, projectdir) end xmake._PROJECT_FILE = projectfile assert(projectfile) -- xmake.lua not found? attempt to find it from the parent directory if not os.isfile(projectfile) then -- make all parent directories local dirs = {} local dir = path.directory(projectfile) while os.isdir(dir) do table.insert(dirs, 1, dir) local parentdir = path.directory(dir) if parentdir ~= dir then dir = parentdir else break end end -- find the first `xmake.lua` for _, dir in ipairs(dirs) do local file = path.join(dir, "xmake.lua") if os.isfile(file) then -- switch to the project directory xmake._PROJECT_DIR = dir xmake._PROJECT_FILE = file os.cd(dir) break end end end end -- check run command as root function main._check_root() -- TODO not check if xmake._HOST == "windows" then return true end -- check it local ok, code = os.iorun("id -u") if ok and code and code:trim() == '0' then return false, [[Running xmake as root is extremely dangerous and no longer supported. As xmake does not drop privileges on installation you would be giving all build scripts full access to your system.]] end -- not root return true end -- the main function function main.done() -- init main._init() -- init option local ok, errors = option.init(menu) if not ok then utils.error(errors) return -1 end -- check run command as root if not option.get("root") then local ok, errors = main._check_root() if not ok then utils.error(errors) return -1 end end -- start profiling if option.get("profile") then profiler:start() end -- run help? if main._help() then return 0 end -- save command lines to history history.save("cmdlines", option.cmdline()) -- run task ok, errors = task.run(option.taskname() or "build") if not ok then utils.error(errors) return -1 end -- dump deprecated entries deprecated.dump() -- stop profiling if option.get("profile") then profiler:stop() end -- ok return 0 end -- return module: main return main
--!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 ruki -- @file main.lua -- -- define module: main local main = main or {} -- load modules local os = require("base/os") local path = require("base/path") local utils = require("base/utils") local option = require("base/option") local profiler = require("base/profiler") local deprecated = require("base/deprecated") local task = require("project/task") local history = require("project/history") -- init the option menu local menu = { -- title title = "XMake v" .. xmake._VERSION .. ", The Make-like Build Utility based on Lua" -- copyright , copyright = "Copyright (C) 2015-2016 Ruki Wang, ${underline}tboox.org${clear}, ${underline}xmake.io${clear}\nCopyright (C) 2005-2015 Mike Pall, ${underline}luajit.org${clear}" -- the tasks: xmake [task] , task.menu } -- done help function main._help() -- done help if option.get("help") then -- print menu option.show_menu(option.taskname()) -- ok return true -- done version elseif option.get("version") then -- print title if menu.title then utils.cprint(menu.title) end -- print copyright if menu.copyright then utils.cprint(menu.copyright) end -- ok return true end end -- the init function for main function main._init() -- init the project directory local projectdir = option.find(xmake._ARGV, "project", "P") or xmake._PROJECT_DIR if projectdir and not path.is_absolute(projectdir) then projectdir = path.absolute(projectdir) elseif projectdir then projectdir = path.translate(projectdir) end xmake._PROJECT_DIR = projectdir assert(projectdir) -- init the xmake.lua file path local projectfile = option.find(xmake._ARGV, "file", "F") or xmake._PROJECT_FILE if projectfile and not path.is_absolute(projectfile) then projectfile = path.absolute(projectfile, projectdir) end xmake._PROJECT_FILE = projectfile assert(projectfile) -- make all parent directories local dirs = {} local dir = path.directory(projectfile) while os.isdir(dir) do table.insert(dirs, 1, dir) local parentdir = path.directory(dir) if parentdir ~= dir then dir = parentdir else break end end -- find the first `xmake.lua` from it's parent directory for _, dir in ipairs(dirs) do local file = path.join(dir, "xmake.lua") if os.isfile(file) then -- switch to the project directory xmake._PROJECT_DIR = dir xmake._PROJECT_FILE = file os.cd(dir) break end end end -- check run command as root function main._check_root() -- TODO not check if xmake._HOST == "windows" then return true end -- check it local ok, code = os.iorun("id -u") if ok and code and code:trim() == '0' then return false, [[Running xmake as root is extremely dangerous and no longer supported. As xmake does not drop privileges on installation you would be giving all build scripts full access to your system.]] end -- not root return true end -- the main function function main.done() -- init main._init() -- init option local ok, errors = option.init(menu) if not ok then utils.error(errors) return -1 end -- check run command as root if not option.get("root") then local ok, errors = main._check_root() if not ok then utils.error(errors) return -1 end end -- start profiling if option.get("profile") then profiler:start() end -- run help? if main._help() then return 0 end -- save command lines to history history.save("cmdlines", option.cmdline()) -- run task ok, errors = task.run(option.taskname() or "build") if not ok then utils.error(errors) return -1 end -- dump deprecated entries deprecated.dump() -- stop profiling if option.get("profile") then profiler:stop() end -- ok return 0 end -- return module: main return main
fix find xmake.lua in subdirs
fix find xmake.lua in subdirs
Lua
apache-2.0
waruqi/xmake,waruqi/xmake,tboox/xmake,tboox/xmake,tboox/xmake,tboox/xmake,waruqi/xmake,waruqi/xmake,tboox/xmake,waruqi/xmake,waruqi/xmake,tboox/xmake,tboox/xmake,waruqi/xmake
a93fb478cf3f89a48f2f9c9987c05fa461e7ac74
modules/self-test/test_runner.lua
modules/self-test/test_runner.lua
--- -- self-test/test_runner.lua -- -- Execute unit tests and test suites. -- -- Author Jason Perkins -- Copyright (c) 2008-2016 Jason Perkins and the Premake project. --- local p = premake local m = p.modules.self_test local _ = {} function m.runTest(test) local scopedTestCall if test.testFunction then scopedTestCall = _.runTest elseif test.suite then scopedTestCall = _.runTestSuite else scopedTestCall = _.runAllTests end return scopedTestCall(test) end function _.runAllTests() local passed = 0 local failed = 0 local suites = m.getSuites() for suiteName, suite in pairs(suites) do if not m.isSuppressed(suiteName) then local test = {} test.suiteName = suiteName test.suite = suite local suitePassed, suiteFailed = _.runTestSuite(test) passed = passed + suitePassed failed = failed + suiteFailed end end return passed, failed end function _.runTestSuite(test) local passed = 0 local failed = 0 for testName, testFunction in pairs(test.suite) do test.testName = testName test.testFunction = testFunction if m.isValid(test) and not m.isSuppressed(test.suiteName .. "." .. test.testName) then local np, nf = _.runTest(test) passed = passed + np failed = failed + nf end end return passed, failed end function _.runTest(test) local cwd = os.getcwd() local hooks = _.installTestingHooks() _TESTS_DIR = test.suite._TESTS_DIR _SCRIPT_DIR = test.suite._SCRIPT_DIR m.suiteName = test.suiteName m.testName = test.testName local ok, err = _.setupTest(test) if ok then ok, err = _.executeTest(test) end local tok, terr = _.teardownTest(test) ok = ok and tok err = err or terr _.removeTestingHooks(hooks) os.chdir(cwd) if ok then return 1, 0 else m.print(string.format("%s.%s: %s", test.suiteName, test.testName, err)) return 0, 1 end end function _.installTestingHooks() local hooks = {} hooks.action = _ACTION hooks.options = _OPTIONS hooks.targetOs = _TARGET_OS hooks.io_open = io.open hooks.io_output = io.output hooks.os_writefile_ifnotequal = os.writefile_ifnotequal hooks.p_utf8 = p.utf8 hooks.print = print hooks.setTextColor = term.setTextColor local mt = getmetatable(io.stderr) _.builtin_write = mt.write mt.write = _.stub_stderr_write _OPTIONS = table.shallowcopy(_OPTIONS) or {} setmetatable(_OPTIONS, getmetatable(hooks.options)) io.open = _.stub_io_open io.output = _.stub_io_output os.writefile_ifnotequal = _.stub_os_writefile_ifnotequal print = _.stub_print p.utf8 = _.stub_utf8 term.setTextColor = _.stub_setTextColor stderr_capture = nil p.clearWarnings() p.eol("\n") p.escaper(nil) p.indent("\t") p.api.reset() m.stderr_capture = nil m.value_openedfilename = nil m.value_openedfilemode = nil m.value_closedfile = false return hooks end function _.removeTestingHooks(hooks) p.action.set(hooks.action) _OPTIONS = hooks.options _TARGET_OS = hooks.targetOs io.open = hooks.io_open io.output = hooks.io_output os.writefile_ifnotequal = hooks.os_writefile_ifnotequal p.utf8 = hooks.p_utf8 print = hooks.print term.setTextColor = hooks.setTextColor local mt = getmetatable(io.stderr) mt.write = _.builtin_write end function _.setupTest(test) if type(test.suite.setup) == "function" then return xpcall(test.suite.setup, _.errorHandler) else return true end end function _.executeTest(test) local result, err p.capture(function() result, err = xpcall(test.testFunction, _.errorHandler) end) return result, err end function _.teardownTest(test) if type(test.suite.teardown) == "function" then return xpcall(test.suite.teardown, _.errorHandler) else return true end end function _.errorHandler(err) local msg = err -- if the error doesn't include a stack trace, add one if not msg:find("stack traceback:", 1, true) then msg = debug.traceback(err, 2) end -- trim of the trailing context of the originating xpcall local i = msg:find("[C]: in function 'xpcall'", 1, true) if i then msg = msg:sub(1, i - 3) end -- if the resulting stack trace is only one level deep, ignore it local n = select(2, msg:gsub('\n', '\n')) if n == 2 then msg = msg:sub(1, msg:find('\n', 1, true) - 1) end return msg end function _.stub_io_open(fname, mode) m.value_openedfilename = fname m.value_openedfilemode = mode return { read = function() end, close = function() m.value_closedfile = true end } end function _.stub_io_output(f) end function _.stub_os_writefile_ifnotequal(content, fname) m.value_openedfilename = fname m.value_closedfile = true return 0 end function _.stub_print(s) end function _.stub_stderr_write(...) if select(1, ...) == io.stderr then m.stderr_capture = (m.stderr_capture or "") .. select(2, ...) else return _.builtin_write(...) end end function _.stub_utf8() end function _.stub_setTextColor() end
--- -- self-test/test_runner.lua -- -- Execute unit tests and test suites. -- -- Author Jason Perkins -- Copyright (c) 2008-2016 Jason Perkins and the Premake project. --- local p = premake local m = p.modules.self_test local _ = {} function m.runTest(test) local scopedTestCall if test.testFunction then scopedTestCall = _.runTest elseif test.suite then scopedTestCall = _.runTestSuite else scopedTestCall = _.runAllTests end return scopedTestCall(test) end function _.runAllTests() local passed = 0 local failed = 0 local suites = m.getSuites() for suiteName, suite in pairs(suites) do if not m.isSuppressed(suiteName) then local test = {} test.suiteName = suiteName test.suite = suite local suitePassed, suiteFailed = _.runTestSuite(test) passed = passed + suitePassed failed = failed + suiteFailed end end return passed, failed end function _.runTestSuite(test) local passed = 0 local failed = 0 if test.suite ~= nil then for testName, testFunction in pairs(test.suite) do test.testName = testName test.testFunction = testFunction if m.isValid(test) and not m.isSuppressed(test.suiteName .. "." .. test.testName) then local np, nf = _.runTest(test) passed = passed + np failed = failed + nf end end end return passed, failed end function _.runTest(test) local cwd = os.getcwd() local hooks = _.installTestingHooks() _TESTS_DIR = test.suite._TESTS_DIR _SCRIPT_DIR = test.suite._SCRIPT_DIR m.suiteName = test.suiteName m.testName = test.testName local ok, err = _.setupTest(test) if ok then ok, err = _.executeTest(test) end local tok, terr = _.teardownTest(test) ok = ok and tok err = err or terr _.removeTestingHooks(hooks) os.chdir(cwd) if ok then return 1, 0 else m.print(string.format("%s.%s: %s", test.suiteName, test.testName, err)) return 0, 1 end end function _.installTestingHooks() local hooks = {} hooks.action = _ACTION hooks.options = _OPTIONS hooks.targetOs = _TARGET_OS hooks.io_open = io.open hooks.io_output = io.output hooks.os_writefile_ifnotequal = os.writefile_ifnotequal hooks.p_utf8 = p.utf8 hooks.print = print hooks.setTextColor = term.setTextColor local mt = getmetatable(io.stderr) _.builtin_write = mt.write mt.write = _.stub_stderr_write _OPTIONS = table.shallowcopy(_OPTIONS) or {} setmetatable(_OPTIONS, getmetatable(hooks.options)) io.open = _.stub_io_open io.output = _.stub_io_output os.writefile_ifnotequal = _.stub_os_writefile_ifnotequal print = _.stub_print p.utf8 = _.stub_utf8 term.setTextColor = _.stub_setTextColor stderr_capture = nil p.clearWarnings() p.eol("\n") p.escaper(nil) p.indent("\t") p.api.reset() m.stderr_capture = nil m.value_openedfilename = nil m.value_openedfilemode = nil m.value_closedfile = false return hooks end function _.removeTestingHooks(hooks) p.action.set(hooks.action) _OPTIONS = hooks.options _TARGET_OS = hooks.targetOs io.open = hooks.io_open io.output = hooks.io_output os.writefile_ifnotequal = hooks.os_writefile_ifnotequal p.utf8 = hooks.p_utf8 print = hooks.print term.setTextColor = hooks.setTextColor local mt = getmetatable(io.stderr) mt.write = _.builtin_write end function _.setupTest(test) if type(test.suite.setup) == "function" then return xpcall(test.suite.setup, _.errorHandler) else return true end end function _.executeTest(test) local result, err p.capture(function() result, err = xpcall(test.testFunction, _.errorHandler) end) return result, err end function _.teardownTest(test) if type(test.suite.teardown) == "function" then return xpcall(test.suite.teardown, _.errorHandler) else return true end end function _.errorHandler(err) local msg = err -- if the error doesn't include a stack trace, add one if not msg:find("stack traceback:", 1, true) then msg = debug.traceback(err, 2) end -- trim of the trailing context of the originating xpcall local i = msg:find("[C]: in function 'xpcall'", 1, true) if i then msg = msg:sub(1, i - 3) end -- if the resulting stack trace is only one level deep, ignore it local n = select(2, msg:gsub('\n', '\n')) if n == 2 then msg = msg:sub(1, msg:find('\n', 1, true) - 1) end return msg end function _.stub_io_open(fname, mode) m.value_openedfilename = fname m.value_openedfilemode = mode return { read = function() end, close = function() m.value_closedfile = true end } end function _.stub_io_output(f) end function _.stub_os_writefile_ifnotequal(content, fname) m.value_openedfilename = fname m.value_closedfile = true return 0 end function _.stub_print(s) end function _.stub_stderr_write(...) if select(1, ...) == io.stderr then m.stderr_capture = (m.stderr_capture or "") .. select(2, ...) else return _.builtin_write(...) end end function _.stub_utf8() end function _.stub_setTextColor() end
small fix in self-test module.
small fix in self-test module.
Lua
bsd-3-clause
Zefiros-Software/premake-core,dcourtois/premake-core,Zefiros-Software/premake-core,noresources/premake-core,soundsrc/premake-core,soundsrc/premake-core,premake/premake-core,noresources/premake-core,starkos/premake-core,LORgames/premake-core,tvandijck/premake-core,premake/premake-core,starkos/premake-core,starkos/premake-core,LORgames/premake-core,mandersan/premake-core,aleksijuvani/premake-core,Blizzard/premake-core,premake/premake-core,premake/premake-core,dcourtois/premake-core,Blizzard/premake-core,dcourtois/premake-core,TurkeyMan/premake-core,sleepingwit/premake-core,tvandijck/premake-core,sleepingwit/premake-core,Blizzard/premake-core,noresources/premake-core,aleksijuvani/premake-core,LORgames/premake-core,aleksijuvani/premake-core,Blizzard/premake-core,Blizzard/premake-core,soundsrc/premake-core,mandersan/premake-core,sleepingwit/premake-core,TurkeyMan/premake-core,soundsrc/premake-core,Zefiros-Software/premake-core,tvandijck/premake-core,dcourtois/premake-core,noresources/premake-core,Blizzard/premake-core,LORgames/premake-core,mandersan/premake-core,premake/premake-core,tvandijck/premake-core,aleksijuvani/premake-core,dcourtois/premake-core,Zefiros-Software/premake-core,TurkeyMan/premake-core,starkos/premake-core,sleepingwit/premake-core,starkos/premake-core,aleksijuvani/premake-core,soundsrc/premake-core,noresources/premake-core,Zefiros-Software/premake-core,TurkeyMan/premake-core,LORgames/premake-core,tvandijck/premake-core,noresources/premake-core,premake/premake-core,noresources/premake-core,mandersan/premake-core,TurkeyMan/premake-core,starkos/premake-core,premake/premake-core,dcourtois/premake-core,dcourtois/premake-core,starkos/premake-core,sleepingwit/premake-core,mandersan/premake-core
90856253c30619ebce104813f9d1b22b4d35197c
database/redis.lua
database/redis.lua
-- Copyright (C) 2013 doujiang24, MaMa Inc. local redis = require "resty.redis" local corehelper = require "helper.core" local log_error = corehelper.log_error local log_debug = corehelper.log_debug local setmetatable = setmetatable local unpack = unpack local get_instance = get_instance local insert = table.insert local _M = { _VERSION = '0.01' } local commands = { 'subscribe', 'psubscribe', 'unsubscribe', 'punsubscribe', } local mt = { __index = _M } function _M.connect(self, config) local red = setmetatable({ conn = redis:new(), config = config }, mt); local conn = red.conn local host = config.host local port = config.port local timeout = config.timeout conn:set_timeout(timeout) local ok, err = conn:connect(host, port) if not ok then log_error("failed to connect redis: ", err) return end if config.password then local res, err = red:auth(config.password) if not res then log_error("failed to authenticate: ", err) return end end return red end function close(self) local conn = self.conn local ok, err = conn:close() if not ok then log_error("failed to close redis: ", err) end end _M.close = close function _M.keepalive(self) local conn, config = self.conn, self.config if not config.idle_timeout or not config.max_keepalive then log_error("not set idle_timeout and max_keepalive in config; turn to close") return close(self) end local ok, err = conn:set_keepalive(config.idle_timeout, config.max_keepalive) if not ok then log_error("failed to set redis keepalive, turn to close, error: ", err) return close(self) end end function _M.commit_pipeline(self) local conn, ret = self.conn, {} local results, err = conn:commit_pipeline() if not results then log_error("failed to commit the pipelined requests: ", err) return ret end for i, res in ipairs(results) do if type(res) == "table" then if not res[1] then log_error("failed to run command: ", i, "; err:", res[2]) insert(ret, false) else insert(ret, res[1]) end else insert(ret, res) end end return ret end for i = 1, #commands do local cmd = commands[i] _M[cmd] = function (self, ...) local conn = self.conn local res, err = conn[cmd](conn, ...) if not res then log_error("failed to query pubsub command redis, error:", err, "operater:", cmd, channel, another, ...) end local nch = select("#", ...) if 1 == nch then return res, err end local results = { res } for i = 1, nch - 1 do local res, err = conn:read_reply() if not res then log_error("failed to read_reply for pubsub command redis, error:", err, "operater:", cmd, channel, another, ...) end results[#results + 1] = res end return results, err end end local class_mt = { __index = function (table, key) return function (self, ...) local conn = self.conn local res, err = conn[key](conn, ...) if not res and err then local args = { ... } if "read_reply" == key and "timeout" == err then --log_debug("failed to query redis, error:", err, "operater:", key, unpack(args)) else log_error("failed to query redis, error:", err, "operater:", key, unpack(args)) end return false, err end return res end end } setmetatable(_M, class_mt) return _M
-- Copyright (C) 2013 doujiang24, MaMa Inc. local redis = require "resty.redis" local corehelper = require "helper.core" local log_error = corehelper.log_error local log_debug = corehelper.log_debug local setmetatable = setmetatable local unpack = unpack local get_instance = get_instance local insert = table.insert local _M = { _VERSION = '0.01' } local commands = { 'subscribe', 'psubscribe', 'unsubscribe', 'punsubscribe', } local mt = { __index = _M } function _M.connect(self, config) local red = setmetatable({ conn = redis:new(), config = config }, mt); local conn = red.conn local host = config.host local port = config.port local timeout = config.timeout conn:set_timeout(timeout) local ok, err = conn:connect(host, port) if not ok then log_error("failed to connect redis: ", err) return end if config.password then local res, err = red:auth(config.password) if not res then log_error("failed to authenticate: ", err) return end end return red end function close(self) local conn = self.conn local ok, err = conn:close() if not ok then log_error("failed to close redis: ", err) end end _M.close = close function _M.keepalive(self) local conn, config = self.conn, self.config if not config.idle_timeout or not config.max_keepalive then log_error("not set idle_timeout and max_keepalive in config; turn to close") return close(self) end local ok, err = conn:set_keepalive(config.idle_timeout, config.max_keepalive) if not ok then log_error("failed to set redis keepalive: ", err) end end function _M.commit_pipeline(self) local conn, ret = self.conn, {} local results, err = conn:commit_pipeline() if not results then log_error("failed to commit the pipelined requests: ", err) return ret end for i, res in ipairs(results) do if type(res) == "table" then if not res[1] then log_error("failed to run command: ", i, "; err:", res[2]) insert(ret, false) else insert(ret, res[1]) end else insert(ret, res) end end return ret end for i = 1, #commands do local cmd = commands[i] _M[cmd] = function (self, ...) local conn = self.conn local res, err = conn[cmd](conn, ...) if not res then log_error("failed to query pubsub command redis, error:", err, "operater:", cmd, channel, another, ...) end local nch = select("#", ...) if 1 == nch then return res, err end local results = { res } for i = 1, nch - 1 do local res, err = conn:read_reply() if not res then log_error("failed to read_reply for pubsub command redis, error:", err, "operater:", cmd, channel, another, ...) end results[#results + 1] = res end return results, err end end local class_mt = { __index = function (table, key) return function (self, ...) local conn = self.conn local res, err = conn[key](conn, ...) if not res and err then local args = { ... } if "read_reply" == key and "timeout" == err then --log_debug("failed to query redis, error:", err, "operater:", key, unpack(args)) else log_error("failed to query redis, error:", err, "operater:", key, unpack(args)) end return false, err end return res end end } setmetatable(_M, class_mt) return _M
bugfix: no need to manually call the close method when keepalive failed
bugfix: no need to manually call the close method when keepalive failed
Lua
mit
doujiang24/durap-system
45ca50458bee4475230e51ec0a9af088b2660f53
frontend/ui/device/kindlepowerd.lua
frontend/ui/device/kindlepowerd.lua
local BasePowerD = require("ui/device/basepowerd") -- liblipclua, see require below local KindlePowerD = BasePowerD:new{ fl_min = 0, fl_max = 24, -- FIXME: Check how to handle this on the PW2, initial reports on IRC suggest that this isn't possible anymore kpw_frontlight = "/sys/devices/system/fl_tps6116x/fl_tps6116x0/fl_intensity", kt_kpw_capacity = "/sys/devices/system/yoshi_battery/yoshi_battery0/battery_capacity", kpw_charging = "/sys/devices/platform/aplite_charger.0/charging", kt_charging = "/sys/devices/platform/fsl-usb2-udc/charging", flIntensity = nil, battCapacity = nil, is_charging = nil, lipc_handle = nil, } function KindlePowerD:new(o) local o = o or {} setmetatable(o, self) self.__index = self if o.init then o:init(o.model) end return o end function KindlePowerD:init(model) local lipc = require("liblipclua") if lipc then self.lipc_handle = lipc.init("com.github.koreader") end if model == "KindleTouch" then self.batt_capacity_file = self.kt_kpw_capacity self.is_charging_file = self.kt_charging elseif model == "KindlePaperWhite" or model == "KindlePaperWhite2" then self.fl_intensity_file = self.kpw_frontlight self.batt_capacity_file = self.kt_kpw_capacity self.is_charging_file = self.kpw_charging end if self.lipc_handle then self.flIntensity = self.lipc_handle:get_int_property("com.lab126.powerd", "flIntensity") else self.flIntensity = self:read_int_file(self.fl_intensity_file) end end function KindlePowerD:toggleFrontlight() local sysint = self:read_int_file(self.fl_intensity_file) if sysint == 0 then self:setIntensity(self.flIntensity) else os.execute("echo -n 0 > " .. self.fl_intensity_file) end end function KindlePowerD:setIntensityHW() if self.lipc_handle ~= nil then self.lipc_handle:set_int_property("com.lab126.powerd", "flIntensity", self.flIntensity) else os.execute("echo -n ".. self.flIntensity .." > " .. self.fl_intensity_file) end end function KindlePowerD:getCapacityHW() if self.lipc_handle ~= nil then self.battCapacity = self.lipc_handle:get_int_property("com.lab126.powerd", "battLevel") else self.battCapacity = self:read_int_file(self.batt_capacity_file) end return self.battCapacity end function KindlePowerD:isChargingHW() if self.lipc_handle ~= nil then self.is_charging = self.lipc_handle:get_int_property("com.lab126.powerd", "isCharging") else self.is_charging = self:read_int_file(self.is_charging_file) end return self.is_charging == 1 end return KindlePowerD
local BasePowerD = require("ui/device/basepowerd") -- liblipclua, see require below local KindlePowerD = BasePowerD:new{ fl_min = 0, fl_max = 24, kpw1_frontlight = "/sys/devices/system/fl_tps6116x/fl_tps6116x0/fl_intensity", kpw2_frontlight = "/sys/class/backlight/max77696-bl/brightness", kt_kpw_capacity = "/sys/devices/system/yoshi_battery/yoshi_battery0/battery_capacity", kpw_charging = "/sys/devices/platform/aplite_charger.0/charging", kt_charging = "/sys/devices/platform/fsl-usb2-udc/charging", flIntensity = nil, battCapacity = nil, is_charging = nil, lipc_handle = nil, } function KindlePowerD:new(o) local o = o or {} setmetatable(o, self) self.__index = self if o.init then o:init(o.model) end return o end function KindlePowerD:init(model) local lipc = require("liblipclua") if lipc then self.lipc_handle = lipc.init("com.github.koreader") end if model == "KindleTouch" then self.batt_capacity_file = self.kt_kpw_capacity self.is_charging_file = self.kt_charging elseif model == "KindlePaperWhite" then self.fl_intensity_file = self.kpw1_frontlight self.batt_capacity_file = self.kt_kpw_capacity self.is_charging_file = self.kpw_charging elseif model == "KindlePaperWhite2" then self.fl_intensity_file = self.kpw2_frontlight self.batt_capacity_file = self.kt_kpw_capacity self.is_charging_file = self.kpw_charging end if self.lipc_handle then self.flIntensity = self.lipc_handle:get_int_property("com.lab126.powerd", "flIntensity") else self.flIntensity = self:read_int_file(self.fl_intensity_file) end end function KindlePowerD:toggleFrontlight() local sysint = self:read_int_file(self.fl_intensity_file) if sysint == 0 then self:setIntensity(self.flIntensity) else os.execute("echo -n 0 > " .. self.fl_intensity_file) end end function KindlePowerD:setIntensityHW() if self.lipc_handle ~= nil then self.lipc_handle:set_int_property("com.lab126.powerd", "flIntensity", self.flIntensity) else os.execute("echo -n ".. self.flIntensity .." > " .. self.fl_intensity_file) end end function KindlePowerD:getCapacityHW() if self.lipc_handle ~= nil then self.battCapacity = self.lipc_handle:get_int_property("com.lab126.powerd", "battLevel") else self.battCapacity = self:read_int_file(self.batt_capacity_file) end return self.battCapacity end function KindlePowerD:isChargingHW() if self.lipc_handle ~= nil then self.is_charging = self.lipc_handle:get_int_property("com.lab126.powerd", "isCharging") else self.is_charging = self:read_int_file(self.is_charging_file) end return self.is_charging == 1 end return KindlePowerD
fix broken toggle frontlight on kpw2
fix broken toggle frontlight on kpw2
Lua
agpl-3.0
houqp/koreader,NickSavage/koreader,poire-z/koreader,noname007/koreader,Frenzie/koreader,frankyifei/koreader,ashang/koreader,robert00s/koreader,mwoz123/koreader,mihailim/koreader,apletnev/koreader,pazos/koreader,koreader/koreader,Hzj-jie/koreader,Markismus/koreader,poire-z/koreader,Frenzie/koreader,NiLuJe/koreader,chihyang/koreader,lgeek/koreader,koreader/koreader,ashhher3/koreader,chrox/koreader,NiLuJe/koreader
bb0bf21d0b39fdae2df72d167a90f06235feb773
lua/entities/gmod_wire_gimbal.lua
lua/entities/gmod_wire_gimbal.lua
AddCSLuaFile() DEFINE_BASECLASS( "base_wire_entity" ) ENT.PrintName = "Wire Gimbal" ENT.WireDebugName = "Gimbal" if CLIENT then return end -- No more client function ENT:Initialize() self:PhysicsInit( SOLID_VPHYSICS ) self:SetMoveType( MOVETYPE_VPHYSICS ) self:SetSolid( SOLID_VPHYSICS ) self:GetPhysicsObject():EnableGravity(false) self.Inputs = WireLib.CreateInputs(self,{"On", "X", "Y", "Z", "Target [VECTOR]", "Direction [VECTOR]", "Angle [ANGLE]"}) self.XYZ = Vector() end function ENT:TriggerInput(name,value) if name == "On" then self.On = value ~= 0 else self.TargetPos = nil self.TargetDir = nil self.TargetAng = nil if name == "X" then self.XYZ.x = value self.TargetPos = self.XYZ elseif name == "Y" then self.XYZ.y = value self.TargetPos = self.XYZ elseif name == "Z" then self.XYZ.z = value self.TargetPos = self.XYZ elseif name == "Target" then self.XYZ = Vector(value.x, value.y, value.z) self.TargetPos = self.XYZ elseif name == "Direction" then self.TargetDir = value elseif name == "Angle" then self.TargetAng = value end end self:ShowOutput() return true end function ENT:Think() if self.On then local ang if self.TargetPos then ang = (self.TargetPos - self:GetPos()):Angle() elseif self.TargetDir then ang = self.TargetDir:Angle() elseif self.TargetAng then ang = self.TargetAng end if ang then self:SetAngles(ang + Angle(90,0,0)) end -- TODO: Put an option in the CPanel for Angle(90,0,0), and other useful directions self:GetPhysicsObject():Wake() end self:NextThink(CurTime()) return true end function ENT:ShowOutput() if not self.On then self:SetOverlayText("Off") elseif self.TargetPos then self:SetOverlayText(string.format("Aiming towards (%.2f, %.2f, %.2f)", self.XYZ.x, self.XYZ.y, self.XYZ.z)) elseif self.TargetDir then self:SetOverlayText(string.format("Aiming (%.4f, %.4f, %.4f)", self.TargetDir.x, self.TargetDir.y, self.TargetDir.z)) elseif self.TargetAng then self:SetOverlayText(string.format("Aiming (%.1f, %.1f, %.1f)", self.TargetAng.pitch, self.TargetAng.yaw, self.TargetAng.roll)) end end duplicator.RegisterEntityClass("gmod_wire_gimbal", WireLib.MakeWireEnt, "Data")
AddCSLuaFile() DEFINE_BASECLASS( "base_wire_entity" ) ENT.PrintName = "Wire Gimbal" ENT.WireDebugName = "Gimbal" if CLIENT then return end -- No more client function ENT:Initialize() self:PhysicsInit( SOLID_VPHYSICS ) self:SetMoveType( MOVETYPE_VPHYSICS ) self:SetSolid( SOLID_VPHYSICS ) self:GetPhysicsObject():EnableGravity(false) self.Inputs = WireLib.CreateInputs(self,{"On", "X", "Y", "Z", "Target [VECTOR]", "Direction [VECTOR]", "Angle [ANGLE]", "AngleOffset [ANGLE]"}) self.XYZ = Vector() self.TargetAngOffset = Matrix() self.TargetAngOffset:SetAngles(Angle(90,0,0)) end function ENT:TriggerInput(name,value) if name == "On" then self.On = value ~= 0 else self.TargetPos = nil self.TargetDir = nil self.TargetAng = nil if name == "X" then self.XYZ.x = value self.TargetPos = self.XYZ elseif name == "Y" then self.XYZ.y = value self.TargetPos = self.XYZ elseif name == "Z" then self.XYZ.z = value self.TargetPos = self.XYZ elseif name == "Target" then self.XYZ = Vector(value.x, value.y, value.z) self.TargetPos = self.XYZ elseif name == "Direction" then self.TargetDir = value elseif name == "Angle" then self.TargetAng = value elseif name == "AngleOffset" then self.TargetAngOffset = Matrix() self.TargetAngOffset:SetAngles(value) end end self:ShowOutput() return true end function ENT:Think() if self.On then local ang if self.TargetPos then ang = (self.TargetPos - self:GetPos()):Angle() elseif self.TargetDir then ang = self.TargetDir:Angle() elseif self.TargetAng then ang = self.TargetAng end if ang then local m = Matrix() m:SetAngles(ang) m = m * self.TargetAngOffset self:SetAngles(m:GetAngles()) end -- TODO: Put an option in the CPanel for Angle(90,0,0), and other useful directions self:GetPhysicsObject():Wake() end self:NextThink(CurTime()) return true end function ENT:ShowOutput() if not self.On then self:SetOverlayText("Off") elseif self.TargetPos then self:SetOverlayText(string.format("Aiming towards (%.2f, %.2f, %.2f)", self.XYZ.x, self.XYZ.y, self.XYZ.z)) elseif self.TargetDir then self:SetOverlayText(string.format("Aiming (%.4f, %.4f, %.4f)", self.TargetDir.x, self.TargetDir.y, self.TargetDir.z)) elseif self.TargetAng then self:SetOverlayText(string.format("Aiming (%.1f, %.1f, %.1f)", self.TargetAng.pitch, self.TargetAng.yaw, self.TargetAng.roll)) end end duplicator.RegisterEntityClass("gmod_wire_gimbal", WireLib.MakeWireEnt, "Data")
Fix gimble lock
Fix gimble lock
Lua
apache-2.0
wiremod/wire,garrysmodlua/wire,Grocel/wire,sammyt291/wire,dvdvideo1234/wire,NezzKryptic/Wire
56ee65e45007dd983f38646103c91728dd7dd194
lib/luanode/__private_luastate.lua
lib/luanode/__private_luastate.lua
-- Copyright (c) 2011-2012 by Robert G. Jakabosky <bobby@neoawareness.com> -- -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -- copies of the Software, and to permit persons to whom the Software is -- furnished to do so, subject to the following conditions: -- -- The above copyright notice and this permission notice shall be included in -- all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -- THE SOFTWARE. local ltraverse = require("luanode.__private_traverse") local have_getsize = false local getsize = function() return 0 end if not jit then --getsize = require"getsize" --have_getsize = true end --[[ local inspect = require("luanode.utils").inspect local pp = function(v) return inspect(v, true) end --]] -- helpers for collecting strings to be used when assembling the final output --[[ local Dumper = {} local Dumper_mt = { __index = Dumper } Dumper.new = function() local t = setmetatable({ lines = {} }, Dumper_mt) return t end function Dumper:add (text) self.lines[#self.lines + 1] = text end function Dumper:add_f (fmt, ...) self:add(fmt:format(...)) end function Dumper:concat_lines () return table.concat(self.lines) end --]] local _M = { _NAME = "luanode.__private_luastate", _PACKAGE = "luanode." } function _M.dump_stats (options) options = options or {} local type_cnts = {} local function type_inc(t) type_cnts[t] = (type_cnts[t] or 0) + 1 end local type_mem = {} local function type_mem_inc(v) if not have_getsize then return end local t = type(v) local s = getsize(v) type_mem[t] = (type_mem[t] or 0) + s end -- build metatable->type map for userdata type detection. local ud_types = {} local reg = debug.getregistry() for k,v in pairs(reg) do --print(type(k)) if type(k) == 'string' and type(v) == 'table' then ud_types[v] = k elseif type(k) == "userdata" then local __name, __type = rawget(v.__name), rawget(v.__type) if __name then ud_types[v] = __name elseif __type then ud_types[v] = __type end --print(tostring(k), tostring(v), pp(v)) --ud_types[v] = "coso" --else --print("what??", k, pp(v), pp(getmetatable(v))) end end local function ud_type(ud) --print("ud_type", ud, debug.getmetatable(ud)) return ud_types[debug.getmetatable(ud)] or "<unknown>" end local str_data = 0 local funcs = { ["edge"] = function(from, to, how, name) --[[ if type(from) == "userdata" then if how == "environment" then if to == package then print("From (".. pp(from) .. ") -> _G.package <" .. how .. ">", name or "") elseif to == _G then print("From ("..pp(from) .. ") -> _G <" .. how .. ">", name or "") else print("From ("..pp(from) .. ") -> ".. pp(to) .. " <" .. how .. ">", name or "") --print("++", from, pp(to), how, name or "") end else --print("edge", how) end --print("From", inspect(from), pp(to)) end --]] type_inc"edges" end, ["table"] = function(v) local t = debug.getmetatable(v) if t then local __name, __type = rawget(t.__name), rawget(t.__type) if type(__name) == "string" then type_inc(__name) elseif type(__type) == "string" then type_inc(__type) else type_inc("table") end else type_inc("table") end type_mem_inc(v) end, ["string"] = function(v) type_inc"string" str_data = str_data + #v type_mem_inc(v) end, ["userdata"] = function(v) --print(pp(v), pp(debug.getmetatable(v)) ) type_inc"userdata" type_inc(ud_type(v)) type_mem_inc(v) end, ["cdata"] = function(v) type_inc"cdata" end, ["func"] = function(v) --print(inspect(v), inspect(debug.getinfo(v)) ) type_inc"function" type_mem_inc(v) end, ["thread"] = function(v) type_inc"thread" type_mem_inc(v) end, } local ignores = {} for k,v in pairs(funcs) do ignores[#ignores + 1] = k ignores[#ignores + 1] = v end ignores[#ignores + 1] = type_cnts ignores[#ignores + 1] = funcs ignores[#ignores + 1] = ignores --ignores[#ignores + 1] = Dumper -- process additional elements to ignore if type(options.ignore) == "table" then for _,v in ipairs(options.ignore) do ignores[#ignores + 1] = v end end ltraverse.traverse(funcs, ignores) local results = {} results.memory = collectgarbage("count") * 1024 results.str_data = str_data results.object_counts = {} for t,cnt in pairs(type_cnts) do results.object_counts[t] = cnt end if have_getsize then results.per_type_memory_usage = {} local total = 0 for t,mem in pairs(type_mem) do total = total + mem results.per_type_memory_usage[t] = mem end results.per_type_memory_usage.total = total end return results --[=[ local dumper = Dumper:new() dumper:add_f("memory = %i bytes\n", results.memory) dumper:add_f("str_data = %i\n", results.str_data) dumper:add("object type counts:\n") for t,cnt in pairs(type_cnts) do dumper:add_f(" %9s = %9i\n", t, cnt) end if have_getsize then dumper:add("per type memory usage:\n") local total = 0 for t,mem in pairs(type_mem) do total = total + mem dumper:add_f(" %9s = %9i bytes\n", t, mem) end dumper:add_f("total: %9i bytes\n", total) end --[[ fd:write("LUA_REGISTRY dump:\n") for k,v in pairs(reg) do fd:write(tostring(k),'=', tostring(v),'\n') end --]] return dumper:concat_lines() --]=] end return _M
-- Copyright (c) 2011-2012 by Robert G. Jakabosky <bobby@neoawareness.com> -- -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -- copies of the Software, and to permit persons to whom the Software is -- furnished to do so, subject to the following conditions: -- -- The above copyright notice and this permission notice shall be included in -- all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -- THE SOFTWARE. local ltraverse = require("luanode.__private_traverse") local have_getsize = false local getsize = function() return 0 end if not jit then --getsize = require"getsize" --have_getsize = true end local rawget = rawget --[[ local inspect = require("luanode.utils").inspect local pp = function(v) return inspect(v, true) end --]] -- helpers for collecting strings to be used when assembling the final output --[[ local Dumper = {} local Dumper_mt = { __index = Dumper } Dumper.new = function() local t = setmetatable({ lines = {} }, Dumper_mt) return t end function Dumper:add (text) self.lines[#self.lines + 1] = text end function Dumper:add_f (fmt, ...) self:add(fmt:format(...)) end function Dumper:concat_lines () return table.concat(self.lines) end --]] local _M = { _NAME = "luanode.__private_luastate", _PACKAGE = "luanode." } function _M.dump_stats (options) options = options or {} local type_cnts = {} local function type_inc(t) type_cnts[t] = (type_cnts[t] or 0) + 1 end local type_mem = {} local function type_mem_inc(v) if not have_getsize then return end local t = type(v) local s = getsize(v) type_mem[t] = (type_mem[t] or 0) + s end -- build metatable->type map for userdata type detection. local ud_types = {} local reg = debug.getregistry() for k,v in pairs(reg) do --print(type(k)) if type(k) == 'string' and type(v) == 'table' then ud_types[v] = k elseif type(k) == "userdata" then local __name, __type = rawget(v, "__name"), rawget(v, "__type") if __name then ud_types[v] = __name elseif __type then ud_types[v] = __type end --print(tostring(k), tostring(v), pp(v)) --ud_types[v] = "coso" --else --print("what??", k, pp(v), pp(getmetatable(v))) end end local function ud_type(ud) --print("ud_type", ud, debug.getmetatable(ud)) return ud_types[debug.getmetatable(ud)] or "<unknown>" end local str_data = 0 local funcs = { ["edge"] = function(from, to, how, name) --[[ if type(from) == "userdata" then if how == "environment" then if to == package then print("From (".. pp(from) .. ") -> _G.package <" .. how .. ">", name or "") elseif to == _G then print("From ("..pp(from) .. ") -> _G <" .. how .. ">", name or "") else print("From ("..pp(from) .. ") -> ".. pp(to) .. " <" .. how .. ">", name or "") --print("++", from, pp(to), how, name or "") end else --print("edge", how) end --print("From", inspect(from), pp(to)) end --]] type_inc"edges" end, ["table"] = function(v) local t = debug.getmetatable(v) if t then local __name, __type = rawget(t, "__name"), rawget(t, "__type") if type(__name) == "string" then type_inc(__name) elseif type(__type) == "string" then type_inc(__type) else type_inc("table") end else type_inc("table") end type_mem_inc(v) end, ["string"] = function(v) type_inc"string" str_data = str_data + #v type_mem_inc(v) end, ["userdata"] = function(v) --print(pp(v), pp(debug.getmetatable(v)) ) type_inc"userdata" type_inc(ud_type(v)) type_mem_inc(v) end, ["cdata"] = function(v) type_inc"cdata" end, ["func"] = function(v) --print(inspect(v), inspect(debug.getinfo(v)) ) type_inc"function" type_mem_inc(v) end, ["thread"] = function(v) type_inc"thread" type_mem_inc(v) end, } local ignores = {} for k,v in pairs(funcs) do ignores[#ignores + 1] = k ignores[#ignores + 1] = v end ignores[#ignores + 1] = type_cnts ignores[#ignores + 1] = funcs ignores[#ignores + 1] = ignores --ignores[#ignores + 1] = Dumper -- process additional elements to ignore if type(options.ignore) == "table" then for _,v in ipairs(options.ignore) do ignores[#ignores + 1] = v end end ltraverse.traverse(funcs, ignores) local results = {} results.memory = collectgarbage("count") * 1024 results.str_data = str_data results.object_counts = {} for t,cnt in pairs(type_cnts) do results.object_counts[t] = cnt end if have_getsize then results.per_type_memory_usage = {} local total = 0 for t,mem in pairs(type_mem) do total = total + mem results.per_type_memory_usage[t] = mem end results.per_type_memory_usage.total = total end return results --[=[ local dumper = Dumper:new() dumper:add_f("memory = %i bytes\n", results.memory) dumper:add_f("str_data = %i\n", results.str_data) dumper:add("object type counts:\n") for t,cnt in pairs(type_cnts) do dumper:add_f(" %9s = %9i\n", t, cnt) end if have_getsize then dumper:add("per type memory usage:\n") local total = 0 for t,mem in pairs(type_mem) do total = total + mem dumper:add_f(" %9s = %9i bytes\n", t, mem) end dumper:add_f("total: %9i bytes\n", total) end --[[ fd:write("LUA_REGISTRY dump:\n") for k,v in pairs(reg) do fd:write(tostring(k),'=', tostring(v),'\n') end --]] return dumper:concat_lines() --]=] end return _M
Fix improper use of rawget
Fix improper use of rawget
Lua
mit
ichramm/LuaNode,ignacio/LuaNode,ignacio/LuaNode,ichramm/LuaNode,ichramm/LuaNode,ichramm/LuaNode,ignacio/LuaNode,ignacio/LuaNode