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
|
|---|---|---|---|---|---|---|---|---|---|
10c4815964c8903f8e2e1f44ec154f6790a5ac29
|
util/datetime.lua
|
util/datetime.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.
--
-- XEP-0082: XMPP Date and Time Profiles
local os_date = os.date;
local os_time = os.time;
local os_difftime = os.difftime;
local error = error;
local tonumber = tonumber;
module "datetime"
function date(t)
return os_date("!%Y-%m-%d", t);
end
function datetime(t)
return os_date("!%Y-%m-%dT%H:%M:%SZ", t);
end
function time(t)
return os_date("!%H:%M:%S", t);
end
function legacy(t)
return os_date("!%Y%m%dT%H:%M:%S", t);
end
function parse(s)
if s then
local year, month, day, hour, min, sec, tzd;
year, month, day, hour, min, sec, tzd = s:match("^(%d%d%d%d)-?(%d%d)-?(%d%d)T(%d%d):(%d%d):(%d%d)%.?%d*([Z+%-].*)$");
if year then
local time_offset = os_difftime(os_time(os_date("*t")), os_time(os_date("!*t"))); -- to deal with local timezone
local tzd_offset = 0;
if tzd ~= "" and tzd ~= "Z" then
local sign, h, m = tzd:match("([+%-])(%d%d):(%d%d)");
if not sign then return; end
h, m = tonumber(h), tonumber(m);
tzd_offset = h * 60 * 60 + m * 60;
if sign == "-" then tzd_offset = -tzd_offset; end
end
sec = sec + time_offset + tzd_offset;
return os_time({year=year, month=month, day=day, hour=hour, min=min, sec=sec});
end
end
end
return _M;
|
-- Prosody IM
-- Copyright (C) 2008-2010 Matthew Wild
-- Copyright (C) 2008-2010 Waqas Hussain
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
-- XEP-0082: XMPP Date and Time Profiles
local os_date = os.date;
local os_time = os.time;
local os_difftime = os.difftime;
local error = error;
local tonumber = tonumber;
module "datetime"
function date(t)
return os_date("!%Y-%m-%d", t);
end
function datetime(t)
return os_date("!%Y-%m-%dT%H:%M:%SZ", t);
end
function time(t)
return os_date("!%H:%M:%S", t);
end
function legacy(t)
return os_date("!%Y%m%dT%H:%M:%S", t);
end
function parse(s)
if s then
local year, month, day, hour, min, sec, tzd;
year, month, day, hour, min, sec, tzd = s:match("^(%d%d%d%d)-?(%d%d)-?(%d%d)T(%d%d):(%d%d):(%d%d)%.?%d*([Z+%-].*)$");
if year then
local time_offset = os_difftime(os_time(os_date("*t")), os_time(os_date("!*t"))); -- to deal with local timezone
local tzd_offset = 0;
if tzd ~= "" and tzd ~= "Z" then
local sign, h, m = tzd:match("([+%-])(%d%d):?(%d*)");
if not sign then return; end
if #m ~= 2 then m = "0"; end
h, m = tonumber(h), tonumber(m);
tzd_offset = h * 60 * 60 + m * 60;
if sign == "-" then tzd_offset = -tzd_offset; end
end
sec = sec + time_offset + tzd_offset;
return os_time({year=year, month=month, day=day, hour=hour, min=min, sec=sec});
end
end
end
return _M;
|
util.datetime: Fixes for more liberal timezone parsing - colon and minutes are both (independantly) optional (thanks Zash)
|
util.datetime: Fixes for more liberal timezone parsing - colon and minutes are both (independantly) optional (thanks Zash)
|
Lua
|
mit
|
sarumjanuch/prosody,sarumjanuch/prosody
|
9af59d903455acaf68a44951b1478601f9a093ad
|
code/scripts/genie.lua
|
code/scripts/genie.lua
|
-- Solution definition
solution "IntroToGraphicsCPP"
location "../build"
-- Only Debug and Release configurations
configurations {
"Debug",
"Release",
}
-- Support for X86, X64 and 'native' (for other OSes)
platforms {
"x32",
"x64",
"Native",
}
-- C++
language "C++"
-- Folder for the 'workspace'
WORKSPACE_DIR = path.getabsolute("..")
-- For when we have a 3rd party library set (AssImp, any font libs, etc)
local THIRD_PARTY_DIR = path.join(WORKSPACE_DIR, "3rdparty")
-- Add in the toolchain.lua scrip and fire off the main script
-- to set up the build environment
dofile (path.join(WORKSPACE_DIR, "scripts/toolchain.lua"))
if not toolchain(WORKSPACE_DIR, THIRD_PARTY_DIR) then
return -- no action specified
end
-- configureations for Debug
configuration "Debug"
defines { "WIN32", "_DEBUG", "_WINDOWS", "_UNICODE", "UNICODE", "%(PreprocessorDefinitions)" }
links {"D3D11", "D3DCompiler"}
links {"kernel32","user32","gdi32","winspool","comdlg32","advapi32","shell32","ole32","oleaut32","uuid","odbc32","odbccp32"}
-- configuration for Release
configuration "Release"
defines { "WIN32", "NDEBUG", "_WINDOWS", "_UNICODE", "UNICODE", "%(PreprocessorDefinitions)" }
links {"D3D11", "D3DCompiler"}
links {"kernel32","user32","gdi32","winspool","comdlg32","advapi32","shell32","ole32","oleaut32","uuid","odbc32","odbccp32"}
project "dummy"
kind "ConsoleApp"
files { "dummy.c" }
excludes { "dummy.c" }
-- our first project
project "intro01"
PROJ_DIR = path.join(WORKSPACE_DIR, "intro01")
flags { "WinMain"}
kind "WindowedApp"
includedirs {
path.join(PROJ_DIR, "src"),
path.join(THIRD_PARTY_DIR, "EASTL/include"),
}
files {
path.join(PROJ_DIR, "src/**.h"),
path.join(PROJ_DIR, "src/**.cpp"),
path.join(PROJ_DIR, "src/Intro01.rc"),
path.join(THIRD_PARTY_DIR, "EASTL/source/*.cpp")
}
resoptions {
"CPPD3DIntroduction.rc"
}
|
-- Solution definition
solution "IntroToGraphicsCPP"
location "../build"
-- Only Debug and Release configurations
configurations {
"Debug",
"Release",
}
-- Support for X86, X64 and 'native' (for other OSes)
platforms {
"x32",
"x64",
"Native",
}
-- C++
language "C++"
-- Folder for the 'workspace'
WORKSPACE_DIR = path.getabsolute("..")
-- For when we have a 3rd party library set (AssImp, any font libs, etc)
local THIRD_PARTY_DIR = path.join(WORKSPACE_DIR, "3rdparty")
-- Add in the toolchain.lua scrip and fire off the main script
-- to set up the build environment
dofile (path.join(WORKSPACE_DIR, "scripts/toolchain.lua"))
if not toolchain(WORKSPACE_DIR, THIRD_PARTY_DIR) then
return -- no action specified
end
local PDB_DIR = path.join(path.join(path.join(WORKSPACE_DIR,"projects"), _ACTION), "pdbs")
os.mkdir(PDB_DIR)
-- configureations for Debug
configuration {"Debug", "x32"}
defines { "WIN32", "_DEBUG", "_WINDOWS", "_UNICODE", "UNICODE", "%(PreprocessorDefinitions)" }
links {"D3D11", "D3DCompiler"}
links {"kernel32","user32","gdi32","winspool","comdlg32","advapi32","shell32","ole32","oleaut32","uuid","odbc32","odbccp32"}
flags {"ExtraWarnings"}
-- To reproduce the linker bug reported in https://github.com/bkaradzic/GENie/issues/266
-- comment out the two lines below.
linkoptions {"/PDB:pdbs/output-dx32.pdb"}
targetsuffix "-d"
configuration {"Debug", "x64"}
defines { "WIN32", "_DEBUG", "_WINDOWS", "_UNICODE", "UNICODE", "%(PreprocessorDefinitions)" }
links {"D3D11", "D3DCompiler"}
links {"kernel32","user32","gdi32","winspool","comdlg32","advapi32","shell32","ole32","oleaut32","uuid","odbc32","odbccp32"}
flags {"ExtraWarnings"}
-- To reproduce the linker bug reported in https://github.com/bkaradzic/GENie/issues/266
-- comment out the two lines below.
linkoptions {"/PDB:pdbs/output-dx64.pdb"}
targetsuffix "-d"
-- configuration for Release
configuration {"Release", "x32"}
defines { "WIN32", "NDEBUG", "_WINDOWS", "_UNICODE", "UNICODE", "%(PreprocessorDefinitions)" }
links {"D3D11", "D3DCompiler"}
links {"kernel32","user32","gdi32","winspool","comdlg32","advapi32","shell32","ole32","oleaut32","uuid","odbc32","odbccp32"}
flags {"Optimize", "ExtraWarnings"}
configuration {"Release", "x64"}
defines { "WIN32", "NDEBUG", "_WINDOWS", "_UNICODE", "UNICODE", "%(PreprocessorDefinitions)" }
links {"D3D11", "D3DCompiler"}
links {"kernel32","user32","gdi32","winspool","comdlg32","advapi32","shell32","ole32","oleaut32","uuid","odbc32","odbccp32"}
flags {"Optimize", "ExtraWarnings"}
-- our first project
project "intro01"
PROJ_DIR = path.join(WORKSPACE_DIR, "intro01")
flags { "WinMain", "NoExceptions"}
kind "WindowedApp"
includedirs {
path.join(PROJ_DIR, "src"),
path.join(THIRD_PARTY_DIR, "EASTL/include"),
}
files {
path.join(PROJ_DIR, "src/**.h"),
path.join(PROJ_DIR, "src/**.cpp"),
path.join(PROJ_DIR, "src/Intro01.rc"),
path.join(THIRD_PARTY_DIR, "EASTL/source/*.cpp")
}
resoptions {
"CPPD3DIntroduction.rc"
}
|
hack-fix for genie linker issues
|
hack-fix for genie linker issues
|
Lua
|
mit
|
Nuclearfossil/IntroToCPPGraphics,Nuclearfossil/IntroToCPPGraphics
|
b2a64a7b4d2e44ba8fdd4055d2b11eefceae92f9
|
src/lua/bcc/ld.lua
|
src/lua/bcc/ld.lua
|
--[[
Copyright 2016 GitHub, Inc
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]
local ffi = require("ffi")
local _find_library_cache = {}
local function _find_library(name)
if _find_library_cache[name] ~= nil then
return _find_library_cache[name]
end
local arch = ffi.arch
local abi_type = "libc6"
if ffi.abi("64bit") then
if arch == "x64" then
abi_type = abi_type .. ",x86-64"
elseif arch == "ppc" or arch == "mips" then
abi_type = abi_type .. ",64bit"
end
end
local pattern = "%s+lib" .. name:escape() .. "%.%S+ %(" .. abi_type:escape() .. ".-%) => (%S+)"
local f = assert(io.popen("/sbin/ldconfig -p"))
local path = nil
for line in f:lines() do
path = line:match(pattern)
if path then break end
end
f:close()
if path then
_find_library_cache[name] = path
end
return path
end
local _find_load_address_cache = {}
local function _find_load_address(path)
if _find_load_address_cache[path] ~= nil then
return _find_load_address_cache[path]
end
local addr = os.spawn(
[[/usr/bin/objdump -x %s | awk '$1 == "LOAD" && $3 ~ /^[0x]*$/ { print $5 }']],
path)
if addr then
_find_load_address_cache[path] = addr
end
return addr
end
local _find_symbol_cache = {}
local function _find_symbol(path, sym)
assert(path and sym)
if _find_symbol_cache[path] == nil then
_find_symbol_cache[path] = {}
end
local symbols = _find_symbol_cache[path]
if symbols[sym] ~= nil then
return symbols[sym]
end
local addr = os.spawn(
[[/usr/bin/objdump -tT %s | awk -v sym=%s '$NF == sym && $4 == ".text" { print $1; exit }']],
path, sym)
if addr then
symbols[sym] = addr
end
return addr
end
local function _check_path_symbol(name, sym, addr)
assert(name)
local path = name:sub(1,1) == "/" and name or _find_library(name)
assert(path, "could not find library "..name)
-- TODO: realpath
local load_addr = _find_load_address(path)
assert(load_addr, "could not find load address for "..path)
if addr == nil and sym ~= nil then
addr = _find_symbol(path, sym)
end
assert(addr, "could not find address of symbol "..sym)
return path, (addr - load_addr)
end
return {
check_path_symbol=_check_path_symbol,
find_symbol=_find_symbol,
find_load_address=_find_load_address,
find_library=_find_library
}
|
--[[
Copyright 2016 GitHub, Inc
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]
local ffi = require("ffi")
local _find_library_cache = {}
local function _find_library(name)
if _find_library_cache[name] ~= nil then
return _find_library_cache[name]
end
local arch = ffi.arch
local abi_type = "libc6"
if ffi.abi("64bit") then
if arch == "x64" then
abi_type = abi_type .. ",x86-64"
elseif arch == "ppc" or arch == "mips" then
abi_type = abi_type .. ",64bit"
end
end
local pattern = "%s+lib" .. name:escape() .. "%.%S+ %(" .. abi_type:escape() .. ".-%) => (%S+)"
local f = assert(io.popen("/sbin/ldconfig -p"))
local path = nil
for line in f:lines() do
path = line:match(pattern)
if path then break end
end
f:close()
if path then
_find_library_cache[name] = path
end
return path
end
local _find_load_address_cache = {}
local function _find_load_address(path)
if _find_load_address_cache[path] ~= nil then
return _find_load_address_cache[path]
end
local addr = os.spawn(
[[/usr/bin/objdump -x %s | awk '$1 == "LOAD" && $3 ~ /^[0x]*$/ { print $5 }']],
path)
if addr then
addr = tonumber(addr, 16)
_find_load_address_cache[path] = addr
end
return addr
end
local _find_symbol_cache = {}
local function _find_symbol(path, sym)
assert(path and sym)
if _find_symbol_cache[path] == nil then
_find_symbol_cache[path] = {}
end
local symbols = _find_symbol_cache[path]
if symbols[sym] ~= nil then
return symbols[sym]
end
local addr = os.spawn(
[[/usr/bin/objdump -tT %s | awk -v sym=%s '$NF == sym && $4 == ".text" { print $1; exit }']],
path, sym)
if addr then
addr = tonumber(addr, 16)
symbols[sym] = addr
end
return addr
end
local function _check_path_symbol(name, sym, addr)
assert(name)
local path = name:sub(1,1) == "/" and name or _find_library(name)
assert(path, "could not find library "..name)
-- TODO: realpath
local load_addr = _find_load_address(path)
assert(load_addr, "could not find load address for "..path)
if addr == nil and sym ~= nil then
addr = _find_symbol(path, sym)
end
assert(addr, "could not find address of symbol "..sym)
return path, (addr - load_addr)
end
return {
check_path_symbol=_check_path_symbol,
find_symbol=_find_symbol,
find_load_address=_find_load_address,
find_library=_find_library
}
|
ld.lua: fix parsing of base16 addresses
|
ld.lua: fix parsing of base16 addresses
|
Lua
|
apache-2.0
|
mkacik/bcc,zaafar/bcc,iovisor/bcc,zaafar/bcc,mcaleavya/bcc,iovisor/bcc,romain-intel/bcc,zaafar/bcc,mkacik/bcc,iovisor/bcc,shodoco/bcc,zaafar/bcc,zaafar/bcc,brendangregg/bcc,brendangregg/bcc,tuxology/bcc,brendangregg/bcc,tuxology/bcc,shodoco/bcc,romain-intel/bcc,tuxology/bcc,mcaleavya/bcc,romain-intel/bcc,mcaleavya/bcc,tuxology/bcc,brendangregg/bcc,romain-intel/bcc,mkacik/bcc,mkacik/bcc,mcaleavya/bcc,iovisor/bcc,iovisor/bcc,shodoco/bcc,romain-intel/bcc,mcaleavya/bcc,shodoco/bcc,mkacik/bcc,shodoco/bcc,tuxology/bcc,brendangregg/bcc
|
32366612085688061eeb3d0e59a40c30bb77cbc0
|
commands/init.lua
|
commands/init.lua
|
return function ()
local core = require("core")()
local prompt = require("prompt")(require("pretty-print"))
local fs = require("coro-fs")
local env = require("env")
local log = require("log").log
local pathJoin = require("luvi").path.join
local cwd = require('uv').cwd()
local sprintf = require("string").format
local config = core.config
local function getOutput()
local output = prompt("Output to package.lua (1), or a init.lua (2)?")
-- response was blank, run again
if not output then
return getOutput()
end
-- fail on any other options
if not output:match('[1-2]') then
log("Error", "You must select a valid option. [1 or 2]")
return getOutput()
else
if output == "1" then
output = "package.lua"
log("Creating", "package.lua")
elseif output == "2" then
output = "init.lua"
log("Creating", "init.lua")
end
end
return output
end
local output = getOutput()
local home = env.get("HOME") or (env.get("HOMEDRIVE") and env.get("HOMEPATH") and (env.get("HOMEDRIVE") .. env.get("HOMEPATH"))) or env.get("HOMEPATH") or ""
local ini
local function getConfig(name)
ini = ini or fs.readFile(pathJoin(home, ".gitconfig"))
if not ini then return end
local section
for line in ini:gmatch("[^\n]+") do
local s = line:match("^%[([^%]]+)%]$")
if s then
section = s
else
local key, value = line:match("^%s*(%w+)%s*=%s*(.+)$")
if key and section .. "." .. key == name then
if tonumber(value) then return tonumber(value) end
if value == "true" then return true end
if value == "false" then return false end
return value
end
end
end
end
-- trim and wrap words in quotes
function makeTags(csv)
local tags = "{ "
for word in csv:gmatch('([^,]+)') do
tags = tags .. "\"" .. word:gsub("^%s*(.-)%s*$", "%1") .. "\", "
end
-- trim trailing comma and space
tags = tags:sub(0, (#tags - 2))
return tags .. " }"
end
local projectName = prompt("Project Name", config["username"] .. "/project-name")
local projectVersion = prompt("Version", "0.0.1")
local projectDescription = prompt("Description", "A simple description of my little package.")
local projectTags = makeTags(prompt("Tags (Comma Separated)", "lua, lit, luvit"))
local authorName = prompt("Author Name", getConfig("user.name"))
local authorEmail = prompt("Author Email", getConfig("user.email"))
local projectLicense = prompt("License", "MIT")
local projectHomepage = prompt("Homepage", "https://github.com/" .. projectName)
local data = ""
if output == "init.lua" then
local init = [=[
--[[lit-meta
name = %q
version = %q
dependencies = {}
description = %q
tags = %s
license = %q
author = { name = %q, email = %q }
homepage = %q
]]
]=]
data = sprintf(init, projectName, projectVersion, projectDescription, projectTags, projectLicense, authorName, authorEmail, projectHomepage)
elseif output == "package.lua" then
local package = [[
return {
name = %q,
version = %q,
description = %q,
tags = %s,
license = %q,
author = { name = %q, email = %q },
homepage = %q,
dependencies = {},
files = {
"**.lua",
"!test*"
}
}
]]
data = sprintf(package, projectName, projectVersion, projectDescription, projectTags, projectLicense, authorName, authorEmail, projectHomepage)
end
-- give us a preview
print("\n" .. data .. "\n")
local message = "Enter to continue"
local finish = prompt("Is this ok?", message)
if finish == message then
local data, err = fs.writeFile(cwd .. "/" .. output, data)
if err == nil then
log("Complete", "Created a new " .. output .. " file.")
else
log("Error", "Could not write file.")
end
else
log("Aborted", "No files will be written")
end
end
|
return function ()
local core = require("core")()
local prompt = require("prompt")(require("pretty-print"))
local fs = require("coro-fs")
local env = require("env")
local log = require("log").log
local pathJoin = require("luvi").path.join
local cwd = require('uv').cwd()
local sprintf = require("string").format
local config = core.config
local function getOutput()
local output = prompt("Output to package.lua (1), or a init.lua (2)?")
-- response was blank, run again
if not output then
return getOutput()
end
-- fail on any other options
if not output:match('[1-2]') then
log("Error", "You must select a valid option. [1 or 2]")
return getOutput()
else
if output == "1" then
output = "package.lua"
log("Creating", "package.lua")
elseif output == "2" then
output = "init.lua"
log("Creating", "init.lua")
end
end
return output
end
local output = getOutput()
local home = env.get("HOME") or (env.get("HOMEDRIVE") and env.get("HOMEPATH") and (env.get("HOMEDRIVE") .. env.get("HOMEPATH"))) or env.get("HOMEPATH") or ""
local ini
local function getConfig(name)
ini = ini or fs.readFile(pathJoin(home, ".gitconfig"))
if not ini then return end
local section
for line in ini:gmatch("[^\n]+") do
local s = line:match("^%[([^%]]+)%]$")
if s then
section = s
else
local key, value = line:match("^%s*(%w+)%s*=%s*(.+)$")
if key and section .. "." .. key == name then
if tonumber(value) then return tonumber(value) end
if value == "true" then return true end
if value == "false" then return false end
return value
end
end
end
end
-- trim and wrap words in quotes
function makeTags(csv)
local tags = "{ "
for word in csv:gmatch('([^,]+)') do
tags = tags .. "\"" .. word:gsub("^%s*(.-)%s*$", "%1") .. "\", "
end
-- trim trailing comma and space
tags = tags:sub(0, (#tags - 2))
return tags .. " }"
end
local userName = prompt("Username", config["username"])
local projectName = prompt("Project Name", userName .. "/project-name")
local projectVersion = prompt("Version", "0.0.1")
local projectDescription = prompt("Description", "A simple description of my little package.")
local projectTags = makeTags(prompt("Tags (Comma Separated)", "lua, lit, luvit"))
local authorName = prompt("Author Name", getConfig("user.name"))
local authorEmail = prompt("Author Email", getConfig("user.email"))
local projectLicense = prompt("License", "MIT")
local projectHomepage = prompt("Homepage", "https://github.com/" .. projectName)
local data = ""
if output == "init.lua" then
local init = [=[
--[[lit-meta
name = %q
version = %q
dependencies = {}
description = %q
tags = %s
license = %q
author = { name = %q, email = %q }
homepage = %q
]]
]=]
data = sprintf(init, projectName, projectVersion, projectDescription, projectTags, projectLicense, authorName, authorEmail, projectHomepage)
elseif output == "package.lua" then
local package = [[
return {
name = %q,
version = %q,
description = %q,
tags = %s,
license = %q,
author = { name = %q, email = %q },
homepage = %q,
dependencies = {},
files = {
"**.lua",
"!test*"
}
}
]]
data = sprintf(package, projectName, projectVersion, projectDescription, projectTags, projectLicense, authorName, authorEmail, projectHomepage)
end
-- give us a preview
print("\n" .. data .. "\n")
local message = "Enter to continue"
local finish = prompt("Is this ok?", message)
if finish == message then
local data, err = fs.writeFile(cwd .. "/" .. output, data)
if err == nil then
log("Complete", "Created a new " .. output .. " file.")
else
log("Error", "Could not write file.")
end
else
log("Aborted", "No files will be written")
end
end
|
fix error where not having a username would cause lit init to crash. closes #156
|
fix error where not having a username would cause lit init to crash. closes #156
|
Lua
|
apache-2.0
|
zhaozg/lit,squeek502/lit,james2doyle/lit,luvit/lit
|
48ab75719c351496ccf5f05358c9f83cebc313d7
|
TemporalConvolution.lua
|
TemporalConvolution.lua
|
local TemporalConvolution, parent =
torch.class('cudnn.TemporalConvolution', 'nn.TemporalConvolution')
--use cudnn to perform temporal convolutions
--note: if padH parameter is not passed, no padding will be performed, as in parent TemporalConvolution
--however, instead of separately padding data, as is required now for nn.TemporalConvolution,
--it is recommended to pass padding parameter to this routine and use cudnn implicit padding facilities.
--limitation is that padding will be equal on both sides.
function TemporalConvolution:__init(inputFrameSize, outputFrameSize,
kH, dH, padH)
local delayedReset = self.reset
local kW = inputFrameSize
local nInputPlane = 1 -- single channel
local nOutputPlane = outputFrameSize
self.inputFrameSize = inputFrameSize
self.outputFrameSize = outputFrameSize
cudnn.SpatialConvolution.__init(self, nInputPlane, nOutputPlane, kW, kH, 1, dH,0,padH)
self.weight = self.weight:view(nOutputPlane,inputFrameSize*kH)
self.gradWeight = self.gradWeight:view(outputFrameSize, inputFrameSize*kH)
--self.dW and self.kW now have different meaning than in nn.TemporalConvolution, because
--W and H are switched in temporal and spatial
end
function TemporalConvolution:createIODescriptors(input)
local sizeChanged = false
if not self.iDesc or not self.oDesc or
input:size(1) ~= self.iSize[1] or input:size(2) ~= self.iSize[2]
or input:size(3) ~= self.iSize[3] or input:size(4) ~= self.iSize[4] then
sizeChanged = true
end
cudnn.SpatialConvolution.createIODescriptors(self,input)
if sizeChanged then
self.oSize = self.output:size()
end
end
function TemporalConvolution:fastest(mode)
self = cudnn.SpatialConvolution.fastest(self,mode)
return self
end
function TemporalConvolution:resetWeightDescriptors()
cudnn.SpatialConvolution.resetWeightDescriptors(self)
end
local function inputview(input)
local _input = input
if input:dim()==2 then
_input = input:view(1,input:size(1),input:size(2))
end
return _input:view(_input:size(1),1,_input:size(2),_input:size(3))
end
function TemporalConvolution:updateOutput(input)
local _input = inputview(input)
assert(_input:size(4) == self.inputFrameSize,'invalid input frame size')
self.buffer = self.buffer or torch.CudaTensor()
self._output = self._output or torch.CudaTensor()
if self.output:storage() then self._output:set(self.output:storage()) else self._output = self.output end
if self.buffer:storage() then self.output:set(self.buffer:storage()) else self.output = self.buffer end
cudnn.SpatialConvolution.updateOutput(self,_input)
self.buffer = self.output:view(self.oSize):transpose(2,3)
self.output = self._output:resize(self.buffer:size()):copy(self.buffer)
-- self.output here is always 4D, use input dimensions to properly view output
if input:dim()==3 then
self.output=self.output:view(self.oSize[1], self.oSize[3],self.oSize[2])
else
self.output=self.output:view(self.oSize[3], self.oSize[2])
end
return self.output
end
local function transposeGradOutput(src,dst)
assert(src:dim() == 2 or src:dim() == 3, 'gradOutput has to be 2D or 3D');
local srctransposed = src:transpose(src:dim(),src:dim()-1)
dst:resize(srctransposed:size())
dst:copy(srctransposed)
if src:dim()==3 then
dst = dst:view(dst:size(1),dst:size(2),dst:size(3),1)
else
dst = dst:view(dst:size(1),dst:size(2),1)
end
return dst
end
function TemporalConvolution:updateGradInput(input, gradOutput)
if not self.gradInput then return end
local _gradOutput = transposeGradOutput(gradOutput,self.buffer)
local _input = inputview(input)
if input:dim()==3 and self.gradInput:dim() == 3 then
self.gradInput = self.gradInput:view(self.gradInput:size(1), 1, self.gradInput:size(2),self.gradInput:size(3))
elseif input:dim() == 2 and self.gradInput:dim() == 2 then
self.gradInput = self.gradInput:view(1, 1, self.gradInput:size(1),self.gradInput:size(2))
end
self.gradInput = cudnn.SpatialConvolution.updateGradInput(self,_input, _gradOutput)
if input:dim()==3 then
self.gradInput = self.gradInput:view(self.gradInput:size(1),self.gradInput:size(3),self.gradInput:size(4))
else
self.gradInput = self.gradInput:view(self.gradInput:size(3),self.gradInput:size(4))
end
return self.gradInput
end
function TemporalConvolution:accGradParameters(input,gradOutput,scale)
--2d (4d) view of input
local _input = inputview(input)
-- transpose gradOutput (it will likely be transposed twice, hopefully, no big deal
local _gradOutput = transposeGradOutput(gradOutput,self.buffer)
cudnn.SpatialConvolution.accGradParameters(self,_input,_gradOutput,scale)
end
function TemporalConvolution:clearDesc()
self.buffer = nil
self._ouptut = nil
self.oSize = nil
end
function TemporalConvolution:write(f)
self:clearDesc()
cudnn.SpatialConvolution.clearDesc(self)
local var = {}
for k,v in pairs(self) do
var[k] = v
end
f:writeObject(var)
end
function TemporalConvolution:clearState()
self:clearDesc()
return parent.clearState(self)
end
|
local TemporalConvolution, parent =
torch.class('cudnn.TemporalConvolution', 'nn.TemporalConvolution')
--use cudnn to perform temporal convolutions
--note: if padH parameter is not passed, no padding will be performed, as in parent TemporalConvolution
--however, instead of separately padding data, as is required now for nn.TemporalConvolution,
--it is recommended to pass padding parameter to this routine and use cudnn implicit padding facilities.
--limitation is that padding will be equal on both sides.
function TemporalConvolution:__init(inputFrameSize, outputFrameSize,
kH, dH, padH)
local delayedReset = self.reset
local kW = inputFrameSize
local nInputPlane = 1 -- single channel
local nOutputPlane = outputFrameSize
self.inputFrameSize = inputFrameSize
self.outputFrameSize = outputFrameSize
cudnn.SpatialConvolution.__init(self, nInputPlane, nOutputPlane, kW, kH, 1, dH,0,padH)
self.weight = self.weight:view(nOutputPlane,inputFrameSize*kH)
self.gradWeight = self.gradWeight:view(outputFrameSize, inputFrameSize*kH)
--self.dW and self.kW now have different meaning than in nn.TemporalConvolution, because
--W and H are switched in temporal and spatial
end
function TemporalConvolution:createIODescriptors(input)
local sizeChanged = false
if not self.iDesc or not self.oDesc or
input:size(1) ~= self.iSize[1] or input:size(2) ~= self.iSize[2]
or input:size(3) ~= self.iSize[3] or input:size(4) ~= self.iSize[4] then
sizeChanged = true
end
cudnn.SpatialConvolution.createIODescriptors(self,input)
if sizeChanged then
self.oSize = self.output:size()
end
end
function TemporalConvolution:fastest(mode)
self = cudnn.SpatialConvolution.fastest(self,mode)
return self
end
function TemporalConvolution:resetWeightDescriptors()
cudnn.SpatialConvolution.resetWeightDescriptors(self)
end
local function inputview(input)
local _input = input
if input:dim()==2 then
_input = input:view(1,input:size(1),input:size(2))
end
return _input:view(_input:size(1),1,_input:size(2),_input:size(3))
end
function TemporalConvolution:updateOutput(input)
local _input = inputview(input)
assert(_input:size(4) == self.inputFrameSize,'invalid input frame size')
self.buffer = self.buffer or torch.CudaTensor()
self._output = self._output or torch.CudaTensor()
if self.output:storage() then self._output:set(self.output:storage()) else self._output = self.output end
if self.buffer:storage() then self.output:set(self.buffer:storage()) else self.output = self.buffer end
cudnn.SpatialConvolution.updateOutput(self,_input)
self.buffer = self.output:view(self.oSize):transpose(2,3)
self.output = self._output:resize(self.buffer:size()):copy(self.buffer)
-- self.output here is always 4D, use input dimensions to properly view output
if input:dim()==3 then
self.output=self.output:view(self.oSize[1], self.oSize[3],self.oSize[2])
else
self.output=self.output:view(self.oSize[3], self.oSize[2])
end
return self.output
end
local function transposeGradOutput(src,dst)
assert(src:dim() == 2 or src:dim() == 3, 'gradOutput has to be 2D or 3D');
local srctransposed = src:transpose(src:dim(),src:dim()-1)
dst:resize(srctransposed:size())
dst:copy(srctransposed)
if src:dim()==3 then
dst = dst:view(dst:size(1),dst:size(2),dst:size(3),1)
else
dst = dst:view(dst:size(1),dst:size(2),1)
end
return dst
end
function TemporalConvolution:updateGradInput(input, gradOutput)
if not self.gradInput then return end
local _gradOutput = transposeGradOutput(gradOutput,self.buffer)
local _input = inputview(input)
self.gradInput = cudnn.SpatialConvolution.updateGradInput(self,_input, _gradOutput)
if input:dim()==3 then
self.gradInput = self.gradInput:view(self.iSize[1],self.iSize[3],self.iSize[4])
else
self.gradInput = self.gradInput:view(self.iSize[3],self.iSize[4])
end
return self.gradInput
end
function TemporalConvolution:accGradParameters(input,gradOutput,scale)
--2d (4d) view of input
local _input = inputview(input)
-- transpose gradOutput (it will likely be transposed twice, hopefully, no big deal
local _gradOutput = transposeGradOutput(gradOutput,self.buffer)
cudnn.SpatialConvolution.accGradParameters(self,_input,_gradOutput,scale)
end
function TemporalConvolution:clearDesc()
self.buffer = nil
self._output = nil
self.oSize = nil
end
function TemporalConvolution:write(f)
self:clearDesc()
cudnn.SpatialConvolution.clearDesc(self)
local var = {}
for k,v in pairs(self) do
var[k] = v
end
f:writeObject(var)
end
function TemporalConvolution:clearState()
self:clearDesc()
return parent.clearState(self)
end
|
Update TemporalConvolution.lua
|
Update TemporalConvolution.lua
Cleaner way of what fbesse was doing (thans fbesse!) and typo fix
|
Lua
|
bsd-3-clause
|
phunghx/phnn.torch,phunghx/phnn.torch,phunghx/phnn.torch
|
5feacc9bf8b95e0b13ec0a0e40bd9cea8f16eb2d
|
src_trunk/resources/anticheat-system/c_anticheat.lua
|
src_trunk/resources/anticheat-system/c_anticheat.lua
|
local cooldown = false
local localPlayer = getLocalPlayer()
function checkSpeedHacks()
local vehicle = getPedOccupiedVehicle(localPlayer)
if (vehicle) and not (cooldown) then
local speedx, speedy, speedz = getElementVelocity(vehicle)
local actualspeed = math.ceil(((speedx^2 + speedy^2 + speedz^2)^(0.5)*100))
if (actualspeed>151) then
cooldown = true
setTimer(resetCD, 5000, 1)
triggerServerEvent("alertAdminsOfSpeedHacks", localPlayer, actualspeed)
end
end
end
addEventHandler("onClientRender", getRootElement(), checkSpeedHacks)
function resetCD()
cooldown = false
end
local timer = false
local kills = 0
function checkDM(killer)
if (killer==localPlayer) then
kills = kills + 1
if (kills>=3) then
triggerServerEvent("alertAdminsOfDM", localPlayer, kills)
end
if not (timer) then
timer = true
setTimer(resetDMCD, 120000, 1)
end
end
end
addEventHandler("onClientPlayerWasted", getRootElement(), checkDM)
function resetDMCD()
kills = 0
timer = false
end
-- [WEAPON HACKS]
local strikes = 0
function resetWeaponTimer()
if weapontimer then
killTimer(weapontimer)
end
weapontimer = setTimer(checkWeapons, 15000, 0)
end
function checkWeapons()
for i = 0, 47 do
local onslot = getSlotFromWeapon(i)
if getPedWeapon(localPlayer, onslot) == i then
local ammo = getElementData(localPlayer, "ACweapon" .. i) or 0
local totalAmmo = getPedTotalAmmo(localPlayer, onslot)
if totalAmmo > ammo then
strikes = strikes + 1
triggerServerEvent("notifyWeaponHacks", localPlayer, i, totalAmmo, ammo, strikes)
elseif totalAmmo < ammo then
-- update the new ammo count
setElementData(localPlayer, "ACweapon" .. i, false, totalAmmo)
end
else -- weapon on that slot, but not the current one
setElementData(localPlayer, "ACweapon" .. i, false, nil)
end
end
end
addCommandHandler("fwc", checkWeapons)
function giveSafeWeapon(weapon, ammo)
resetWeaponTimer()
setElementData(localPlayer, "ACweapon" .. weapon, false, (getElementData(localPlayer, "ACweapon" .. weapon) or 0) + ammo)
end
addEvent("giveSafeWeapon", true)
addEventHandler("giveSafeWeapon", getLocalPlayer(), giveSafeWeapon)
function setSafeWeaponAmmo(weapon, ammo)
resetWeaponTimer()
setElementData(localPlayer, "ACweapon" .. weapon, false, ammo)
end
addEvent("setSafeWeaponAmmo", true)
addEventHandler("setSafeWeaponAmmo", getLocalPlayer(), setSafeWeaponAmmo)
function takeAllWeaponsSafe()
resetWeaponTimer()
for weapon = 0, 47 do
setElementData(localPlayer, "ACweapon" .. weapon, false, nil)
end
end
addEvent("takeAllWeaponsSafe", true)
addEventHandler("takeAllWeaponsSafe", getLocalPlayer(), takeAllWeaponsSafe)
function takeWeaponSafe(weapon)
resetWeaponTimer()
setElementData(localPlayer, "ACweapon" .. weapon, false, nil)
end
addEvent("takeWeaponSafe", true)
addEventHandler("takeWeaponSafe", getLocalPlayer(), takeWeaponSafe)
addEventHandler("onClientResourceStart", getResourceRootElement(), resetWeaponTimer)
function updateWeaponOnFire(weapon, ammo)
setElementData(localPlayer, "ACweapon" .. weapon, false, (getElementData(localPlayer, "ACweapon" .. weapon) or 0) - 1)
end
addEventHandler("onClientPlayerWeaponFire", localPlayer, updateWeaponOnFire)
|
local cooldown = false
local localPlayer = getLocalPlayer()
function checkSpeedHacks()
local vehicle = getPedOccupiedVehicle(localPlayer)
if (vehicle) and not (cooldown) then
local speedx, speedy, speedz = getElementVelocity(vehicle)
local actualspeed = math.ceil(((speedx^2 + speedy^2 + speedz^2)^(0.5)*100))
if (actualspeed>151) then
cooldown = true
setTimer(resetCD, 5000, 1)
triggerServerEvent("alertAdminsOfSpeedHacks", localPlayer, actualspeed)
end
end
end
addEventHandler("onClientRender", getRootElement(), checkSpeedHacks)
function resetCD()
cooldown = false
end
local timer = false
local kills = 0
function checkDM(killer)
if (killer==localPlayer) then
kills = kills + 1
if (kills>=3) then
triggerServerEvent("alertAdminsOfDM", localPlayer, kills)
end
if not (timer) then
timer = true
setTimer(resetDMCD, 120000, 1)
end
end
end
addEventHandler("onClientPlayerWasted", getRootElement(), checkDM)
function resetDMCD()
kills = 0
timer = false
end
-- [WEAPON HACKS]
local strikes = 0
function resetWeaponTimer()
if weapontimer then
killTimer(weapontimer)
end
weapontimer = setTimer(checkWeapons, 15000, 0)
end
function checkWeapons()
for i = 1, 47 do
local onslot = getSlotFromWeapon(i)
if getPedWeapon(localPlayer, onslot) == i then
local ammo = getElementData(localPlayer, "ACweapon" .. i) or 0
local totalAmmo = getPedTotalAmmo(localPlayer, onslot)
if totalAmmo >= 60000 and (i <= 15 or i >= 44) then -- fix for melee with 60k+ ammo
totalAmmo = 1
end
if totalAmmo > ammo then
strikes = strikes + 1
triggerServerEvent("notifyWeaponHacks", localPlayer, i, totalAmmo, ammo, strikes)
elseif totalAmmo < ammo then
-- update the new ammo count
setElementData(localPlayer, "ACweapon" .. i, false, totalAmmo)
end
else -- weapon on that slot, but not the current one
setElementData(localPlayer, "ACweapon" .. i, false, nil)
end
end
end
addCommandHandler("fwc", checkWeapons)
function giveSafeWeapon(weapon, ammo)
resetWeaponTimer()
setElementData(localPlayer, "ACweapon" .. weapon, false, (getElementData(localPlayer, "ACweapon" .. weapon) or 0) + ammo)
end
addEvent("giveSafeWeapon", true)
addEventHandler("giveSafeWeapon", getLocalPlayer(), giveSafeWeapon)
function setSafeWeaponAmmo(weapon, ammo)
resetWeaponTimer()
setElementData(localPlayer, "ACweapon" .. weapon, false, ammo)
end
addEvent("setSafeWeaponAmmo", true)
addEventHandler("setSafeWeaponAmmo", getLocalPlayer(), setSafeWeaponAmmo)
function takeAllWeaponsSafe()
resetWeaponTimer()
for weapon = 0, 47 do
setElementData(localPlayer, "ACweapon" .. weapon, false, nil)
end
end
addEvent("takeAllWeaponsSafe", true)
addEventHandler("takeAllWeaponsSafe", getLocalPlayer(), takeAllWeaponsSafe)
function takeWeaponSafe(weapon)
resetWeaponTimer()
setElementData(localPlayer, "ACweapon" .. weapon, false, nil)
end
addEvent("takeWeaponSafe", true)
addEventHandler("takeWeaponSafe", getLocalPlayer(), takeWeaponSafe)
addEventHandler("onClientResourceStart", getResourceRootElement(), resetWeaponTimer)
function updateWeaponOnFire(weapon, ammo)
setElementData(localPlayer, "ACweapon" .. weapon, false, (getElementData(localPlayer, "ACweapon" .. weapon) or 0) - 1)
end
addEventHandler("onClientPlayerWeaponFire", localPlayer, updateWeaponOnFire)
|
ac fix
|
ac fix
git-svn-id: 8769cb08482c9977c94b72b8e184ec7d2197f4f7@1227 64450a49-1f69-0410-a0a2-f5ebb52c4f5b
|
Lua
|
bsd-3-clause
|
valhallaGaming/uno,valhallaGaming/uno,valhallaGaming/uno
|
fa21096392b3f6ce5a60330cb1c3d5c65858d262
|
content/elementDrop.lua
|
content/elementDrop.lua
|
--[[
Illarion Server
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License as published by the Free
Software Foundation, either version 3 of the License, or (at your option) any
later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU Affero General Public License for more
details.
You should have received a copy of the GNU Affero General Public License along
with this program. If not, see <http://www.gnu.org/licenses/>.
]]
-- This script handles fairy events in Elstree Forest.
-- The functions are hooked in the various scripts with the actual entry points.
local common = require("base.common")
local scheduledFunction = require("scheduled.scheduledFunction")
local M = {}
local function _isNumber(value)
return type(value) == "number"
end
local function _isTable(value)
return type(value) == "table"
end
local function fairyBlinkenlights(centerPos, counter, itemID, gfxID)
local amount = math.random(3, 7)
local radius = 15
-- show a few fairy lights around
for _ = 1, amount do
local dropPos = common.getFreePos(centerPos, radius)
world:gfx(gfxID, dropPos)
end
-- create a random item (i.e. flame)
if itemID ~= nil then
local dropPos = common.getFreePos(centerPos, radius)
local item = world:createItemFromId(itemID, 1, dropPos, true, 333, nil)
item.wear = 1
world:changeItem(item)
end
-- repeat effect a few times
counter = counter - 1
if counter > 0 then
scheduledFunction.registerFunction(math.random(2, 5), function() fairyBlinkenlights(centerPos, counter, itemID, gfxID) end)
end
end
local function elementNoDrop(User, itemID, gfxID)
-- player get informed s/he missed chance after a while
scheduledFunction.registerFunction(math.random(5, 10), function()
User:inform("Es sieht nicht danach aus als wrde eine Fee heute ein Element verlieren.", "It does not look like as any fairy would drop an element today.")
end)
-- register effect
local centerPos = position(User.pos.x, User.pos.y, User.pos.z) -- deep copy original position
local counter = math.random(10, 20)
scheduledFunction.registerFunction(math.random(2, 5), function() fairyBlinkenlights(centerPos, counter, itemID, gfxID) end)
end
local function getTextForDirection(direction)
if direction == Character.dir_north then
return "nrdlich von dir", "north of you"
elseif direction == Character.dir_northeast then
return "nordstlich von dir", "northeast of you"
elseif direction == Character.dir_east then
return "stlich von dir", "east of you"
elseif direction == Character.dir_southeast then
return "sdstlich von dir", "southeast of you"
elseif direction == Character.dir_south then
return "sdlich von dir", "south of you"
elseif direction == Character.dir_southwest then
return "sdwestlich von dir", "southwest of you"
elseif direction == Character.dir_west then
return "westlich von dir", "west of you"
elseif direction == Character.dir_northwest then
return "nordwestlich von dir", "northwest of you"
else
return "unter deinen Beinen", "underneath your feet"
end
end
local function elementDrop(User, itemID, gfxID)
local radius = 10
local dropPos = common.getFreePos(User.pos, radius)
-- drop item after a while and inform user
scheduledFunction.registerFunction(math.random(1, 4), function()
world:createItemFromId(itemID, 1, dropPos, true, 333, nil)
world:gfx(gfxID, dropPos)
local directionTextDe, directionTextEn = getTextForDirection(common.GetDirection(User.pos, dropPos))
User:inform(
"Ah! Eine Fee hat " .. world:getItemName(itemID, Player.german) .. " " .. directionTextDe .. " verloren.",
"Ah! A fairy lost " .. world:getItemName(itemID, Player.english) .. " " .. directionTextEn .. ".")
end)
end
function M.chanceForElementDrop(User, params)
if params ~= nil and not _isTable(params) then
error("The function requires parameters as a table.")
end
-- check if character has already logged out
if not isValidChar(User) then
return
end
-- chance check if quest cooled down and character is player
if User:getType() ~= Character.player or User:getQuestProgress(661) ~= 0 then
return
end
-- set cooldown
User:setQuestProgress(661, math.random(60, 100))
-- fill default parameters
local probability
local successItemID
local successGfxID
local failItemID
local failGfxID
if params.probability ~= nil then
if _isNumber(params.probability) then
probability = tonumber(params.probability)
if (probability <= 0) or (probability > 1) then
error("The probability is set to a illegal value.")
end
else
error("The probability was set to something, but not to a number.")
end
else
probability = 0.1 -- 10%
end
if params.successItemID ~= nil then
if _isNumber(params.successItemID) then
successItemID = tonumber(params.successItemID)
else
error("successItemID was set to something, but not to a number.")
end
else
local elements = {2551, 2552, 2553, 2554, 3607}
successItemID = elements[math.random(1, #elements)] -- random pure element
end
if params.successGfxID ~= nil then
if _isNumber(params.successGfxID) then
successGfxID = tonumber(params.successGfxID)
else
error("successGfxID was set to something, but not to a number.")
end
else
successGfxID = 46 -- light (beam me up)
end
if params.failItemID ~= nil then
if _isNumber(params.failItemID) then
failItemID = tonumber(params.failItemID)
else
error("failItemID was set to something, but not to a number.")
end
else
-- nothing
end
if params.failGfxID ~= nil then
if _isNumber(params.failGfxID) then
failGfxID = tonumber(params.failGfxID)
else
error("failGfxID was set to something, but not to a number.")
end
else
failGfxID = 53 -- light (blue glitter)
end
-- chance to receive a nice item
if math.random() <= probability then
elementDrop(User, successItemID, successGfxID)
else
elementNoDrop(User, failItemID, failGfxID)
end
end
return M
|
--[[
Illarion Server
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License as published by the Free
Software Foundation, either version 3 of the License, or (at your option) any
later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU Affero General Public License for more
details.
You should have received a copy of the GNU Affero General Public License along
with this program. If not, see <http://www.gnu.org/licenses/>.
]]
-- This script handles fairy events in Elstree Forest.
-- The functions are hooked in the various scripts with the actual entry points.
local common = require("base.common")
local scheduledFunction = require("scheduled.scheduledFunction")
local M = {}
local function _isNumber(value)
return type(value) == "number"
end
local function _isTable(value)
return type(value) == "table"
end
local function fairyBlinkenlights(centerPos, counter, itemID, gfxID)
local amount = math.random(3, 7)
local radius = 15
-- show a few fairy lights around
for _ = 1, amount do
local dropPos = common.getFreePos(centerPos, radius)
world:gfx(gfxID, dropPos)
end
-- create a random item (i.e. flame)
if itemID ~= nil then
local dropPos = common.getFreePos(centerPos, radius)
local item = world:createItemFromId(itemID, 1, dropPos, true, 333, nil)
item.wear = 1
world:changeItem(item)
end
-- repeat effect a few times
counter = counter - 1
if counter > 0 then
scheduledFunction.registerFunction(math.random(2, 5), function() fairyBlinkenlights(centerPos, counter, itemID, gfxID) end)
end
end
local function elementNoDrop(User, itemID, gfxID)
-- player get informed s/he missed chance after a while
scheduledFunction.registerFunction(math.random(5, 10), function()
-- check if character has already logged out
if not isValidChar(User) then
return
end
User:inform("Es sieht nicht danach aus als wrde eine Fee heute ein Element verlieren.", "It does not look like as any fairy would drop an element today.")
end)
-- register effect
local centerPos = position(User.pos.x, User.pos.y, User.pos.z) -- deep copy original position
local counter = math.random(10, 20)
scheduledFunction.registerFunction(math.random(2, 5), function() fairyBlinkenlights(centerPos, counter, itemID, gfxID) end)
end
local function getTextForDirection(direction)
if direction == Character.dir_north then
return "nrdlich von dir", "north of you"
elseif direction == Character.dir_northeast then
return "nordstlich von dir", "northeast of you"
elseif direction == Character.dir_east then
return "stlich von dir", "east of you"
elseif direction == Character.dir_southeast then
return "sdstlich von dir", "southeast of you"
elseif direction == Character.dir_south then
return "sdlich von dir", "south of you"
elseif direction == Character.dir_southwest then
return "sdwestlich von dir", "southwest of you"
elseif direction == Character.dir_west then
return "westlich von dir", "west of you"
elseif direction == Character.dir_northwest then
return "nordwestlich von dir", "northwest of you"
else
return "unter deinen Beinen", "underneath your feet"
end
end
local function elementDrop(User, itemID, gfxID)
local radius = 10
local dropPos = common.getFreePos(User.pos, radius)
-- drop item after a while and inform user
scheduledFunction.registerFunction(math.random(1, 4), function()
-- check if character has already logged out
if not isValidChar(User) then
return
end
world:createItemFromId(itemID, 1, dropPos, true, 333, nil)
world:gfx(gfxID, dropPos)
local directionTextDe, directionTextEn = getTextForDirection(common.GetDirection(User.pos, dropPos))
User:inform(
"Ah! Eine Fee hat " .. world:getItemName(itemID, Player.german) .. " " .. directionTextDe .. " verloren.",
"Ah! A fairy lost " .. world:getItemName(itemID, Player.english) .. " " .. directionTextEn .. ".")
end)
end
function M.chanceForElementDrop(User, params)
if params ~= nil and not _isTable(params) then
error("The function requires parameters as a table.")
end
-- chance check if quest cooled down and character is player
if User:getType() ~= Character.player or User:getQuestProgress(661) ~= 0 then
return
end
-- set cooldown
User:setQuestProgress(661, math.random(60, 100))
-- fill default parameters
local probability
local successItemID
local successGfxID
local failItemID
local failGfxID
if params.probability ~= nil then
if _isNumber(params.probability) then
probability = tonumber(params.probability)
if (probability <= 0) or (probability > 1) then
error("The probability is set to a illegal value.")
end
else
error("The probability was set to something, but not to a number.")
end
else
probability = 0.1 -- 10%
end
if params.successItemID ~= nil then
if _isNumber(params.successItemID) then
successItemID = tonumber(params.successItemID)
else
error("successItemID was set to something, but not to a number.")
end
else
local elements = {2551, 2552, 2553, 2554, 3607}
successItemID = elements[math.random(1, #elements)] -- random pure element
end
if params.successGfxID ~= nil then
if _isNumber(params.successGfxID) then
successGfxID = tonumber(params.successGfxID)
else
error("successGfxID was set to something, but not to a number.")
end
else
successGfxID = 46 -- light (beam me up)
end
if params.failItemID ~= nil then
if _isNumber(params.failItemID) then
failItemID = tonumber(params.failItemID)
else
error("failItemID was set to something, but not to a number.")
end
else
-- nothing
end
if params.failGfxID ~= nil then
if _isNumber(params.failGfxID) then
failGfxID = tonumber(params.failGfxID)
else
error("failGfxID was set to something, but not to a number.")
end
else
failGfxID = 53 -- light (blue glitter)
end
-- chance to receive a nice item
if math.random() <= probability then
elementDrop(User, successItemID, successGfxID)
else
elementNoDrop(User, failItemID, failGfxID)
end
end
return M
|
fix last commit
|
fix last commit
|
Lua
|
agpl-3.0
|
Illarion-eV/Illarion-Content,vilarion/Illarion-Content,KayMD/Illarion-Content,Baylamon/Illarion-Content
|
833b46de6a4d82f8b724f0c83dd55065c67739a6
|
applications/luci-wol/luasrc/model/cbi/wol.lua
|
applications/luci-wol/luasrc/model/cbi/wol.lua
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id: olsrd.lua 5560 2009-11-21 00:22:35Z jow $
]]--
local sys = require "luci.sys"
local fs = require "nixio.fs"
m = SimpleForm("wol", translate("Wake on LAN"),
translate("Wake on LAN is a mechanism to remotely boot computers in the local network."))
m.submit = translate("Wake up host")
m.reset = false
local has_ewk = fs.access("/usr/bin/etherwake")
local has_wol = fs.access("/usr/bin/wol")
if luci.http.formvalue("cbi.submit") then
local host = luci.http.formvalue("cbid.wol.1.mac")
if host and #host > 0 then
local cmd
local util = luci.http.formvalue("cbid.wol.1.binary") or (
has_ewk and "/usr/bin/etherwake" or "/usr/bin/wol"
)
if util == "/usr/bin/etherwake" then
local iface = luci.http.formvalue("cbid.wol.1.iface")
cmd = "%s -D%s %q" %{
util, (iface ~= "" and " -i %q" % iface or ""), host
}
else
cmd = "%s -v %q" %{ util, host }
end
is = m:section(SimpleSection)
function is.render()
luci.http.write(
"<p><br /><strong>%s</strong><br /><br /><code>%s<br /><br />" %{
translate("Starting WoL utility:"), cmd
}
)
local p = io.popen(cmd .. " 2>&1")
if p then
while true do
local l = p:read("*l")
if l then
if #l > 100 then l = l:sub(1, 100) .. "..." end
luci.http.write(l .. "<br />")
else
break
end
end
p:close()
end
luci.http.write("</code><br /></p>")
end
end
end
s = m:section(SimpleSection)
local arp = { }
local e, ip, mac, name
if has_ewk and has_wol then
bin = s:option(ListValue, "binary", translate("WoL program"),
translate("Sometimes only one of both tools work. If one of fails, try the other one"))
bin:value("/usr/bin/etherwake", "Etherwake")
bin:value("/usr/bin/wol", "WoL")
end
if has_ewk then
iface = s:option(ListValue, "iface", translate("Network interface to use"),
translate("Specifies the interface the WoL packet is sent on"))
if has_wol then
iface:depends("binary", "/usr/bin/etherwake")
end
iface:value("", translate("Broadcast on all interfaces"))
for _, e in ipairs(sys.net.devices()) do
if e ~= "lo" then iface:value(e) end
end
end
for _, e in ipairs(sys.net.arptable()) do
arp[e["HW address"]] = { e["IP address"] }
end
for e in io.lines("/etc/ethers") do
mac, ip = e:match("^([a-f0-9]%S+) (%S+)")
if mac and ip then arp[mac] = { ip } end
end
for e in io.lines("/var/dhcp.leases") do
mac, ip, name = e:match("^%d+ (%S+) (%S+) (%S+)")
if mac and ip then arp[mac] = { ip, name ~= "*" and name } end
end
host = s:option(Value, "mac", translate("Host to wake up"),
translate("Choose the host to wake up or enter a custom MAC address to use"))
for mac, ip in pairs(arp) do
host:value(mac, "%s (%s)" %{ mac, ip[2] or ip[1] })
end
return m
|
--[[
LuCI - Lua Configuration Interface
Copyright 2010 Jo-Philipp Wich <xm@subsignal.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
]]--
local sys = require "luci.sys"
local fs = require "nixio.fs"
m = SimpleForm("wol", translate("Wake on LAN"),
translate("Wake on LAN is a mechanism to remotely boot computers in the local network."))
m.submit = translate("Wake up host")
m.reset = false
local has_ewk = fs.access("/usr/bin/etherwake")
local has_wol = fs.access("/usr/bin/wol")
if luci.http.formvalue("cbi.submit") then
local host = luci.http.formvalue("cbid.wol.1.mac")
if host and #host > 0 then
local cmd
local util = luci.http.formvalue("cbid.wol.1.binary") or (
has_ewk and "/usr/bin/etherwake" or "/usr/bin/wol"
)
if util == "/usr/bin/etherwake" then
local iface = luci.http.formvalue("cbid.wol.1.iface")
cmd = "%s -D%s %q" %{
util, (iface ~= "" and " -i %q" % iface or ""), host
}
else
cmd = "%s -v %q" %{ util, host }
end
is = m:section(SimpleSection)
function is.render()
luci.http.write(
"<p><br /><strong>%s</strong><br /><br /><code>%s<br /><br />" %{
translate("Starting WoL utility:"), cmd
}
)
local p = io.popen(cmd .. " 2>&1")
if p then
while true do
local l = p:read("*l")
if l then
if #l > 100 then l = l:sub(1, 100) .. "..." end
luci.http.write(l .. "<br />")
else
break
end
end
p:close()
end
luci.http.write("</code><br /></p>")
end
end
end
s = m:section(SimpleSection)
local arp = { }
local e, ip, mac, name
if has_ewk and has_wol then
bin = s:option(ListValue, "binary", translate("WoL program"),
translate("Sometimes only one of both tools work. If one of fails, try the other one"))
bin:value("/usr/bin/etherwake", "Etherwake")
bin:value("/usr/bin/wol", "WoL")
end
if has_ewk then
iface = s:option(ListValue, "iface", translate("Network interface to use"),
translate("Specifies the interface the WoL packet is sent on"))
if has_wol then
iface:depends("binary", "/usr/bin/etherwake")
end
iface:value("", translate("Broadcast on all interfaces"))
for _, e in ipairs(sys.net.devices()) do
if e ~= "lo" then iface:value(e) end
end
end
for _, e in ipairs(sys.net.arptable()) do
arp[e["HW address"]] = { e["IP address"] }
end
for e in io.lines("/etc/ethers") do
mac, ip = e:match("^([a-f0-9]%S+) (%S+)")
if mac and ip then arp[mac] = { ip } end
end
for e in io.lines("/var/dhcp.leases") do
mac, ip, name = e:match("^%d+ (%S+) (%S+) (%S+)")
if mac and ip then arp[mac] = { ip, name ~= "*" and name } end
end
host = s:option(Value, "mac", translate("Host to wake up"),
translate("Choose the host to wake up or enter a custom MAC address to use"))
for mac, ip in pairs(arp) do
host:value(mac, "%s (%s)" %{ mac, ip[2] or ip[1] })
end
return m
|
applications/luci-wol: fix copyright
|
applications/luci-wol: fix copyright
|
Lua
|
apache-2.0
|
8devices/luci,deepak78/luci,deepak78/luci,deepak78/luci,8devices/luci,deepak78/luci,8devices/luci,deepak78/luci,deepak78/luci,8devices/luci,8devices/luci,deepak78/luci,8devices/luci,deepak78/luci
|
dbcf05997630f6cbe4250c167da96520239a0667
|
demo/SVM.lua
|
demo/SVM.lua
|
--[[
A translated demo from here:
http://docs.opencv.org/3.0.0/d1/d73/tutorial_introduction_to_svm.html
Original version by @szagoruyko
--]]
require 'cv.imgproc'
require 'cv.imgcodecs'
require 'cv.highgui'
require 'cv.ml'
-- Data for visual representation
local width, height = 512, 512
local im = torch.ByteTensor(height, width, 3):zero()
-- Set up training data
local labelsMat = torch.IntTensor{1, -1, -1, -1}
local trainingDataMat = torch.FloatTensor{ {501, 10}, {255, 10}, {501, 255}, {10, 501} }
-- Set up SVM's parameters
local svm = cv.SVM()
svm:setType {cv.ml.SVM_C_SVC}
svm:setKernel {cv.ml.SVM_LINEAR}
svm:setTermCriteria {cv.TermCriteria{cv.TermCriteria_MAX_ITER, 100, 1e-6}}
-- Train the SVM
svm:train{trainingDataMat, cv.ml.ROW_SAMPLE, labelsMat}
-- Show the decision regions given by the SVM
local green, blue = torch.ByteTensor{0,255,0}, torch.ByteTensor{255,0,0}
for i=1,im:size(1) do
for j=1,im:size(2) do
local response, _ = svm:predict{torch.FloatTensor{{j, i}}}
im[{i,j,{}}]:copy(response == 1 and green or blue)
end
end
-- Show the training data
local thickness = -1
local lineType = 8
cv.circle{ im, {501, 10}, 5, { 0, 0, 0}, thickness, lineType }
cv.circle{ im, {255, 10}, 5, {255, 255, 255}, thickness, lineType }
cv.circle{ im, {501, 255}, 5, {255, 255, 255}, thickness, lineType }
cv.circle{ im, { 10, 501}, 5, {255, 255, 255}, thickness, lineType }
-- Show support vectors
thickness = 2
lineType = 8
local sv = svm:getSupportVectors()
for i=1,sv:size(1) do
cv.circle{im, {sv[i][1], sv[i][2]}, 6, {128,128,128}, thickness, lineType}
end
cv.imwrite{"result.png", im} -- save the image
cv.imshow{"SVM Simple Example", im} -- show it to the user
cv.waitKey{0}
|
--[[
A translated demo from here:
http://docs.opencv.org/3.0.0/d1/d73/tutorial_introduction_to_svm.html
When running the above example in C++ (OpenCV 3.0.0), for some reason .getSupportVectors()
outputs [-0.008130081, 0.008163265]. That's why here I've set kernel type to quadratic.
Original version by @szagoruyko
--]]
require 'cv.imgproc'
require 'cv.imgcodecs'
require 'cv.highgui'
require 'cv.ml'
-- Data for visual representation
local width, height = 512, 512
local im = torch.ByteTensor(height, width, 3):zero()
-- Set up training data
local labelsMat = torch.IntTensor{1, -1, -1, -1}
local trainingDataMat = torch.FloatTensor{ {501, 10}, {255, 10}, {501, 255}, {10, 501} }
-- Set up SVM's parameters
local svm = cv.SVM()
svm:setType {cv.ml.SVM_C_SVC}
svm:setKernel {cv.ml.SVM_POLY}
svm:setDegree {2}
svm:setTermCriteria {cv.TermCriteria{cv.TermCriteria_MAX_ITER, 100, 1e-6}}
-- Train the SVM
svm:train{trainingDataMat, cv.ml.ROW_SAMPLE, labelsMat}
-- Show the decision regions given by the SVM
local green, blue = torch.ByteTensor{0,255,0}, torch.ByteTensor{255,0,0}
for i=1,im:size(1) do
for j=1,im:size(2) do
local response, _ = svm:predict{torch.FloatTensor{{j, i}}}
im[{i,j,{}}]:copy(response == 1 and green or blue)
end
end
-- Show the training data
local thickness = -1
local lineType = 8
cv.circle{ im, {501, 10}, 5, { 0, 0, 0}, thickness, lineType }
cv.circle{ im, {255, 10}, 5, {255, 255, 255}, thickness, lineType }
cv.circle{ im, {501, 255}, 5, {255, 255, 255}, thickness, lineType }
cv.circle{ im, { 10, 501}, 5, {255, 255, 255}, thickness, lineType }
-- Show support vectors
thickness = 2
lineType = 8
local sv = svm:getSupportVectors()
for i=1,sv:size(1) do
cv.circle{im, {sv[i][1], sv[i][2]}, 6, {128,128,128}, thickness, lineType}
end
cv.imwrite{"result.png", im} -- save the image
cv.imshow{"SVM Simple Example", im} -- show it to the user
cv.waitKey{0}
|
Modify SVM demo to hide (probably) OpenCV bug
|
Modify SVM demo to hide (probably) OpenCV bug
|
Lua
|
mit
|
VisionLabs/torch-opencv
|
ee025a47479d4401b21325663a42ca78a8554052
|
lua/entities/gmod_wire_freezer.lua
|
lua/entities/gmod_wire_freezer.lua
|
AddCSLuaFile()
DEFINE_BASECLASS( "base_wire_entity" )
ENT.PrintName = "Freezer"
ENT.WireDebugName = "Freezer"
if CLIENT then return end -- No more client
function ENT:Initialize()
self:PhysicsInit( SOLID_VPHYSICS )
self:SetMoveType( MOVETYPE_VPHYSICS )
self:SetSolid( SOLID_VPHYSICS )
self.State = false
self.CollisionState = 0
self.Marks = {}
self.Inputs = WireLib.CreateInputs(self, {"Activate", "Disable Collisions"})
self:UpdateOutputs()
end
function ENT:TriggerInput(name, value)
if name == "Activate" then
self.State = value ~= 0
for _, ent in pairs(self.Marks) do
if ent:IsValid() then
local phys = ent:GetPhysicsObject()
if phys:IsValid() then
if self.State then
-- Garry's Mod provides an OnPhysgunFreeze hook, which will
-- unfreeze the object if prop protection allows it...
gamemode.Call("OnPhysgunFreeze", self, phys, ent, self:GetPlayer())
else
-- ...and a CanPlayerUnfreeze hook, which will return whether
-- prop protection allows it, but won't unfreeze do the unfreezing.
if not gamemode.Call("CanPlayerUnfreeze", self:GetPlayer(), ent, phys) then return end
phys:EnableMotion(true)
phys:Wake()
end
end
end
end
elseif name == "Disable Collisions" then
self.CollisionState = math.Clamp(math.Round(value), 0, 4)
for _, ent in pairs(self.Marks) do
if ent:IsValid() then
local phys = ent:GetPhysicsObject()
if phys:IsValid() and gamemode.Call("CanTool", self:GetPlayer(), WireLib.dummytrace(ent), "nocollide") then
if self.CollisionState == 0 then
ent:SetCollisionGroup( COLLISION_GROUP_NONE )
phys:EnableCollisions(true)
elseif self.CollisionState == 1 then
ent:SetCollisionGroup( COLLISION_GROUP_WORLD )
phys:EnableCollisions(true)
elseif self.CollisionState == 2 then
ent:SetCollisionGroup( COLLISION_GROUP_NONE )
phys:EnableCollisions(false)
elseif self.CollisionState == 3 then
ent:SetCollisionGroup( COLLISION_GROUP_WEAPON )
phys:EnableCollisions(true)
elseif self.CollisionState == 4 then
ent:SetCollisionGroup( COLLISION_GROUP_WEAPON )
phys:EnableCollisions(false)
end
end
end
end
end
self:UpdateOverlay()
end
local collisionDescriptions = {
[0] = "Normal Collisions",
[1] = "Disabled prop/player Collisions",
[2] = "Disabled prop/world Collisions",
[3] = "Disabled player Collisions",
[4] = "Disabled prop/world/player Collisions"
}
function ENT:UpdateOverlay()
self:SetOverlayText(
(self.State and "Frozen" or "Unfrozen") .. "\n" ..
collisionDescriptions[self.CollisionState] .. "\n" ..
"Linked Entities: " .. #self.Marks)
end
function ENT:UpdateOutputs()
self:UpdateOverlay()
WireLib.SendMarks(self) -- Stool's yellow lines
end
function ENT:CheckEnt( ent )
if IsValid(ent) then
for index, e in pairs( self.Marks ) do
if (e == ent) then return true, index end
end
end
return false, 0
end
function ENT:LinkEnt( ent )
if (self:CheckEnt( ent )) then return false end
self.Marks[#self.Marks+1] = ent
ent:CallOnRemove("AdvEMarker.Unlink", function(ent)
if self:IsValid() then self:UnlinkEnt(ent) end
end)
self:UpdateOutputs()
return true
end
function ENT:UnlinkEnt( ent )
local bool, index = self:CheckEnt( ent )
if (bool) then
table.remove( self.Marks, index )
self:UpdateOutputs()
end
return bool
end
function ENT:ClearEntities()
self.Marks = {}
self:UpdateOutputs()
end
duplicator.RegisterEntityClass( "gmod_wire_freezer", WireLib.MakeWireEnt, "Data" )
function ENT:BuildDupeInfo()
local info = BaseClass.BuildDupeInfo(self) or {}
if next(self.Marks) then
local tbl = {}
for index, e in pairs( self.Marks ) do
tbl[index] = e:EntIndex()
end
info.marks = tbl
end
return info
end
function ENT:ApplyDupeInfo(ply, ent, info, GetEntByID)
BaseClass.ApplyDupeInfo(self, ply, ent, info, GetEntByID)
if info.Ent1 then
-- Old wire-extras dupe support
table.insert(self.Marks, GetEntByID(info.Ent1))
end
if info.marks then
for index, entindex in pairs(info.marks) do
self.Marks[index] = GetEntByID(entindex)
end
end
self:TriggerInput("Disable Collisions", self.Inputs["Disable Collisions"].Value)
self:UpdateOutputs()
end
|
AddCSLuaFile()
DEFINE_BASECLASS( "base_wire_entity" )
ENT.PrintName = "Freezer"
ENT.WireDebugName = "Freezer"
if CLIENT then return end -- No more client
function ENT:Initialize()
self:PhysicsInit( SOLID_VPHYSICS )
self:SetMoveType( MOVETYPE_VPHYSICS )
self:SetSolid( SOLID_VPHYSICS )
self.State = false
self.CollisionState = 0
self.Marks = {}
self.Inputs = WireLib.CreateInputs(self, {"Activate", "Disable Collisions"})
self:UpdateOutputs()
end
function ENT:TriggerInput(name, value)
local ply = self:GetPlayer()
if not ply:IsValid() then return end
if name == "Activate" then
self.State = value ~= 0
for _, ent in pairs(self.Marks) do
if ent:IsValid() then
local phys = ent:GetPhysicsObject()
if phys:IsValid() then
if self.State then
-- Garry's Mod provides an OnPhysgunFreeze hook, which will
-- unfreeze the object if prop protection allows it...
gamemode.Call("OnPhysgunFreeze", self, phys, ent, ply)
else
-- ...and a CanPlayerUnfreeze hook, which will return whether
-- prop protection allows it, but won't unfreeze do the unfreezing.
if not gamemode.Call("CanPlayerUnfreeze", ply, ent, phys) then return end
phys:EnableMotion(true)
phys:Wake()
end
end
end
end
elseif name == "Disable Collisions" then
self.CollisionState = math.Clamp(math.Round(value), 0, 4)
for _, ent in pairs(self.Marks) do
if ent:IsValid() then
local phys = ent:GetPhysicsObject()
if phys:IsValid() and gamemode.Call("CanTool", ply, WireLib.dummytrace(ent), "nocollide") then
if self.CollisionState == 0 then
ent:SetCollisionGroup( COLLISION_GROUP_NONE )
phys:EnableCollisions(true)
elseif self.CollisionState == 1 then
ent:SetCollisionGroup( COLLISION_GROUP_WORLD )
phys:EnableCollisions(true)
elseif self.CollisionState == 2 then
ent:SetCollisionGroup( COLLISION_GROUP_NONE )
phys:EnableCollisions(false)
elseif self.CollisionState == 3 then
ent:SetCollisionGroup( COLLISION_GROUP_WEAPON )
phys:EnableCollisions(true)
elseif self.CollisionState == 4 then
ent:SetCollisionGroup( COLLISION_GROUP_WEAPON )
phys:EnableCollisions(false)
end
end
end
end
end
self:UpdateOverlay()
end
local collisionDescriptions = {
[0] = "Normal Collisions",
[1] = "Disabled prop/player Collisions",
[2] = "Disabled prop/world Collisions",
[3] = "Disabled player Collisions",
[4] = "Disabled prop/world/player Collisions"
}
function ENT:UpdateOverlay()
self:SetOverlayText(
(self.State and "Frozen" or "Unfrozen") .. "\n" ..
collisionDescriptions[self.CollisionState] .. "\n" ..
"Linked Entities: " .. #self.Marks)
end
function ENT:UpdateOutputs()
self:UpdateOverlay()
WireLib.SendMarks(self) -- Stool's yellow lines
end
function ENT:CheckEnt( ent )
if IsValid(ent) then
for index, e in pairs( self.Marks ) do
if (e == ent) then return true, index end
end
end
return false, 0
end
function ENT:LinkEnt( ent )
if (self:CheckEnt( ent )) then return false end
self.Marks[#self.Marks+1] = ent
ent:CallOnRemove("AdvEMarker.Unlink", function(ent)
if self:IsValid() then self:UnlinkEnt(ent) end
end)
self:UpdateOutputs()
return true
end
function ENT:UnlinkEnt( ent )
local bool, index = self:CheckEnt( ent )
if (bool) then
table.remove( self.Marks, index )
self:UpdateOutputs()
end
return bool
end
function ENT:ClearEntities()
self.Marks = {}
self:UpdateOutputs()
end
duplicator.RegisterEntityClass( "gmod_wire_freezer", WireLib.MakeWireEnt, "Data" )
function ENT:BuildDupeInfo()
local info = BaseClass.BuildDupeInfo(self) or {}
if next(self.Marks) then
local tbl = {}
for index, e in pairs( self.Marks ) do
tbl[index] = e:EntIndex()
end
info.marks = tbl
end
return info
end
function ENT:ApplyDupeInfo(ply, ent, info, GetEntByID)
BaseClass.ApplyDupeInfo(self, ply, ent, info, GetEntByID)
if info.Ent1 then
-- Old wire-extras dupe support
table.insert(self.Marks, GetEntByID(info.Ent1))
end
if info.marks then
for index, entindex in pairs(info.marks) do
self.Marks[index] = GetEntByID(entindex)
end
end
self:TriggerInput("Disable Collisions", self.Inputs["Disable Collisions"].Value)
self:UpdateOutputs()
end
|
Fix freezer causing error when unfreezing without owner (#2479)
|
Fix freezer causing error when unfreezing without owner (#2479)
* Update gmod_wire_freezer.lua
* change check to be at beginning and localize ply
|
Lua
|
apache-2.0
|
wiremod/wire
|
8a49bb4fceaa2532bcaaa94f0282a4a2dc7f1b40
|
src/luarocks/cmd/config.lua
|
src/luarocks/cmd/config.lua
|
--- Module implementing the LuaRocks "config" command.
-- Queries information about the LuaRocks configuration.
local config_cmd = {}
local cfg = require("luarocks.core.cfg")
local util = require("luarocks.util")
local dir = require("luarocks.dir")
local fun = require("luarocks.fun")
config_cmd.help_summary = "Query information about the LuaRocks configuration."
config_cmd.help_arguments = "<flag>"
config_cmd.help = [[
--lua-incdir Path to Lua header files.
--lua-libdir Path to Lua library files.
--lua-ver Lua version (in major.minor format). e.g. 5.1
--system-config Location of the system config file.
--user-config Location of the user config file.
--rock-trees Rocks trees in use. First the user tree, then the system tree.
]]
config_cmd.help_see_also = [[
https://github.com/luarocks/luarocks/wiki/Config-file-format
for detailed information on the LuaRocks config file format.
]]
local function config_file(conf)
print(dir.normalize(conf.file))
if conf.ok then
return true
else
return nil, "file not found"
end
end
local function printf(fmt, ...)
print((fmt):format(...))
end
local cfg_maps = {
external_deps_patterns = true,
external_deps_subdirs = true,
rocks_provided = true,
rocks_provided_3_0 = true,
runtime_external_deps_patterns = true,
runtime_external_deps_subdirs = true,
upload = true,
variables = true,
}
local cfg_arrays = {
disabled_servers = true,
external_deps_dirs = true,
rocks_trees = true,
rocks_servers = true,
}
local cfg_skip = {
errorcodes = true,
flags = true,
platforms = true,
root_dir = true,
upload_servers = true,
}
local function print_config(cfg)
for k, v in util.sortedpairs(cfg) do
k = tostring(k)
if type(v) == "string" or type(v) == "boolean" or type(v) == "number" then
printf("%s = %q", k, v)
elseif type(v) == "function" or cfg_skip[k] then
-- skip
elseif cfg_maps[k] then
printf("%s = {", k)
for kk, vv in util.sortedpairs(v) do
local keyfmt = kk:match("^[a-zA-Z_][a-zA-Z0-9_]*$") and "%s" or "[%q]"
if type(vv) == "table" then
local qvs = fun.map(vv, function(e) return string.format("%q", e) end)
printf(" "..keyfmt.." = {%s},", kk, table.concat(qvs, ", "))
else
printf(" "..keyfmt.." = %q,", kk, vv)
end
end
printf("}")
elseif cfg_arrays[k] then
if #v == 0 then
printf("%s = {}", k)
else
printf("%s = {", k)
for _, vv in ipairs(v) do
if type(vv) == "string" then
printf(" %q,", vv)
elseif type(vv) == "table" then
printf(" {")
if next(vv) == 1 then
for _, v3 in ipairs(vv) do
printf(" %q,", v3)
end
else
for k3, v3 in util.sortedpairs(vv) do
local keyfmt = tostring(k3):match("^[a-zA-Z_][a-zA-Z0-9_]*$") and "%s" or "[%q]"
printf(" "..keyfmt.." = %q,", k3, v3)
end
end
printf(" },")
end
end
printf("}")
end
end
end
end
--- Driver function for "config" command.
-- @return boolean: True if succeeded, nil on errors.
function config_cmd.command(flags)
if flags["lua-incdir"] then
print(cfg.variables.LUA_INCDIR)
return true
end
if flags["lua-libdir"] then
print(cfg.variables.LUA_LIBDIR)
return true
end
if flags["lua-ver"] then
print(cfg.lua_version)
return true
end
local conf = cfg.which_config()
if flags["system-config"] then
return config_file(conf.system)
end
if flags["user-config"] then
return config_file(conf.user)
end
if flags["rock-trees"] then
for _, tree in ipairs(cfg.rocks_trees) do
if type(tree) == "string" then
util.printout(dir.normalize(tree))
else
local name = tree.name and "\t"..tree.name or ""
util.printout(dir.normalize(tree.root)..name)
end
end
return true
end
print_config(cfg)
return true
end
return config_cmd
|
--- Module implementing the LuaRocks "config" command.
-- Queries information about the LuaRocks configuration.
local config_cmd = {}
local cfg = require("luarocks.core.cfg")
local util = require("luarocks.util")
local dir = require("luarocks.dir")
local fun = require("luarocks.fun")
config_cmd.help_summary = "Query information about the LuaRocks configuration."
config_cmd.help_arguments = "<flag>"
config_cmd.help = [[
--lua-incdir Path to Lua header files.
--lua-libdir Path to Lua library files.
--lua-ver Lua version (in major.minor format). e.g. 5.1
--system-config Location of the system config file.
--user-config Location of the user config file.
--rock-trees Rocks trees in use. First the user tree, then the system tree.
]]
config_cmd.help_see_also = [[
https://github.com/luarocks/luarocks/wiki/Config-file-format
for detailed information on the LuaRocks config file format.
]]
local function config_file(conf)
print(dir.normalize(conf.file))
if conf.ok then
return true
else
return nil, "file not found"
end
end
local function printf(fmt, ...)
print((fmt):format(...))
end
local cfg_maps = {
external_deps_patterns = true,
external_deps_subdirs = true,
rocks_provided = true,
rocks_provided_3_0 = true,
runtime_external_deps_patterns = true,
runtime_external_deps_subdirs = true,
upload = true,
variables = true,
}
local cfg_arrays = {
disabled_servers = true,
external_deps_dirs = true,
rocks_trees = true,
rocks_servers = true,
}
local cfg_skip = {
errorcodes = true,
flags = true,
platforms = true,
root_dir = true,
upload_servers = true,
}
local function print_config(cfg)
for k, v in util.sortedpairs(cfg) do
k = tostring(k)
if type(v) == "string" or type(v) == "number" then
printf("%s = %q", k, v)
elseif type(v) == "boolean" then
printf("%s = %s", k, tostring(v))
elseif type(v) == "function" or cfg_skip[k] then
-- skip
elseif cfg_maps[k] then
printf("%s = {", k)
for kk, vv in util.sortedpairs(v) do
local keyfmt = kk:match("^[a-zA-Z_][a-zA-Z0-9_]*$") and "%s" or "[%q]"
if type(vv) == "table" then
local qvs = fun.map(vv, function(e) return string.format("%q", e) end)
printf(" "..keyfmt.." = {%s},", kk, table.concat(qvs, ", "))
else
printf(" "..keyfmt.." = %q,", kk, vv)
end
end
printf("}")
elseif cfg_arrays[k] then
if #v == 0 then
printf("%s = {}", k)
else
printf("%s = {", k)
for _, vv in ipairs(v) do
if type(vv) == "string" then
printf(" %q,", vv)
elseif type(vv) == "table" then
printf(" {")
if next(vv) == 1 then
for _, v3 in ipairs(vv) do
printf(" %q,", v3)
end
else
for k3, v3 in util.sortedpairs(vv) do
local keyfmt = tostring(k3):match("^[a-zA-Z_][a-zA-Z0-9_]*$") and "%s" or "[%q]"
printf(" "..keyfmt.." = %q,", k3, v3)
end
end
printf(" },")
end
end
printf("}")
end
end
end
end
--- Driver function for "config" command.
-- @return boolean: True if succeeded, nil on errors.
function config_cmd.command(flags)
if flags["lua-incdir"] then
print(cfg.variables.LUA_INCDIR)
return true
end
if flags["lua-libdir"] then
print(cfg.variables.LUA_LIBDIR)
return true
end
if flags["lua-ver"] then
print(cfg.lua_version)
return true
end
local conf = cfg.which_config()
if flags["system-config"] then
return config_file(conf.system)
end
if flags["user-config"] then
return config_file(conf.user)
end
if flags["rock-trees"] then
for _, tree in ipairs(cfg.rocks_trees) do
if type(tree) == "string" then
util.printout(dir.normalize(tree))
else
local name = tree.name and "\t"..tree.name or ""
util.printout(dir.normalize(tree.root)..name)
end
end
return true
end
print_config(cfg)
return true
end
return config_cmd
|
config: Lua 5.1/5.2 compatibility fix
|
config: Lua 5.1/5.2 compatibility fix
|
Lua
|
mit
|
keplerproject/luarocks,keplerproject/luarocks,tarantool/luarocks,luarocks/luarocks,tarantool/luarocks,keplerproject/luarocks,luarocks/luarocks,keplerproject/luarocks,tarantool/luarocks,luarocks/luarocks
|
375f06fa84ee8664ca4c898e032241f6f928b6cb
|
interface/configenv/range.lua
|
interface/configenv/range.lua
|
return function(env)
function env.range(start, limit, step)
step = step or 1
if not limit then
return function()
local v = start
start = start + step
return v
end
end
local val = start
return function()
local v = val
val = val + step
if val > limit then
val = start
end
return v
end
end
function env.list(tbl)
local index, len = 1, #tbl
return function()
local v = tbl[index]
index = index + 1
if index > len then
index = 1
end
return v
end
end
end
|
return function(env)
function env.range(start, limit, step)
step = step or 1
local v = start
if not limit then
return function()
start = start + step
return v
end
end
return function()
v = v + step
if v > limit then
v = start
end
return v
end
end
function env.list(tbl)
local index, len = 1, #tbl
return function()
local v = tbl[index]
index = index + 1
if index > len then
index = 1
end
return v
end
end
end
|
Fix range.
|
Fix range.
|
Lua
|
mit
|
scholzd/MoonGen,dschoeffm/MoonGen,emmericp/MoonGen,scholzd/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen,emmericp/MoonGen,dschoeffm/MoonGen,scholzd/MoonGen,dschoeffm/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen,emmericp/MoonGen,gallenmu/MoonGen
|
5fcf835794e618a23bdacdaf349423f7688fd9ff
|
lw-replay.lua
|
lw-replay.lua
|
package.path = package.path..";./?.lua;./?/init.lua;"
require 'config'
require 'irc'
cjson = require 'cjson'
require 'quotes'
local sleep = require 'socket'.sleep
local s = irc.new{nick = config.nick, username = config.username, realname = config.realname}
s:hook('OnChat', function(user, channel, message)
if message:match('%.ff') then
local newspeed = tonumber(message:match(' (%d*)'))
newUtcAdjust = -os.clock()*speed+utcAdjust+os.clock()*newspeed
speed = newspeed
elseif message:match('%.skip') then
local offset = tonumber(message:match(' (%d*)'))
--local cur = logs:seek('cur', offset)
for i = 1, offset do
m = cjson.decode(logs:read('*l'))
end
elseif message:lower():match('%.setutc') then
local utc = tonumber(message:match(' (.*)'))
utcAdjust=utc-os.clock()*speed
while utc>m[2] do
logs:seek('cur', 10000)
logs:read('*l')
m = cjson.decode(logs:read('*l'))
end
while utc < m[2] do
logs:seek('cur', -10000)
logs:read('*l')
m = cjson.decode(logs:read('*l'))
end
while utc > m[2] do
m = cjson.decode(logs:read('*l'))
end
elseif message:match('%.utc') then
s:sendChat(channel, tostring(os.clock()*speed+utcAdjust))
elseif message:match('%topic') then
setTopic()
elseif message:match('%.help') then
s:sendChat(channel, 'Available Commands: ff, .skip, .setutc, .utc, .topic')
end
end)
function setTopic()
local topic = ('TOPIC %s #lesswrong history, replayed by a bot. "%s" https://github.com/Houshalter/lw-replay'):format(config.mainChannel, quotes[math.random(#quotes)])
print(topic)
s:send(topic)
end
s:connect(config.server)
for i, channel in ipairs(config.channels) do
s:join(channel)
end
s:sendChat('NickServ', 'identify '..config.password)
logs = io.open(config.dataFileName, "r")
m = cjson.decode(logs:read('*l'))
utcAdjust = os.clock()+20+m[2]
speed = 1
setTopic()
while true do
s:think()
if os.clock()*speed > m[2]-utcAdjust then
s:sendChat(config.mainChannel, m[3]:match('(.-)!')..': '..m[4])
sleep(config.refeshRate)
m = cjson.decode(logs:read('*l'))
end
end
|
package.path = package.path..";./?.lua;./?/init.lua;"
require 'config'
require 'irc'
cjson = require 'cjson'
require 'quotes'
local sleep = require 'socket'.sleep
local s = irc.new{nick = config.nick, username = config.username, realname = config.realname}
s:hook('OnChat', function(user, channel, message)
if message:match('%.ff') then
local newspeed = tonumber(message:match(' (%d*)'))
newUtcAdjust = -os.clock()*speed+utcAdjust+os.clock()*newspeed
speed = newspeed
elseif message:match('%.skip') then
local offset = tonumber(message:match(' (%d*)'))
--local cur = logs:seek('cur', offset)
for i = 1, offset do
m = cjson.decode(logs:read('*l'))
end
elseif message:lower():match('%.setutc') then
local utc = tonumber(message:match(' (.*)'))
utcAdjust=utc-os.clock()*speed
while utc>m[2] do
if not logs:seek('cur', 10000) then error("Gone to far, bug that needs fixed") end
logs:read('*l')
m = cjson.decode(logs:read('*l'))
end
while utc < m[2] do
if not logs:seek('cur', -10000) then
logs:seek('set')
end
logs:read('*l')
m = cjson.decode(logs:read('*l'))
end
while utc > m[2] do
m = cjson.decode(logs:read('*l'))
end
elseif message:match('%.utc') then
s:sendChat(channel, tostring(os.clock()*speed+utcAdjust))
elseif message:match('%topic') then
setTopic()
elseif message:match('%.help') then
s:sendChat(channel, 'Available Commands: ff, .skip, .setutc, .utc, .topic')
end
end)
function setTopic()
local topic = ('TOPIC %s :#lesswrong history, replayed by a bot. "%s" https://github.com/Houshalter/lw-replay'):format(config.mainChannel, quotes[math.random(#quotes)])
print(topic)
s:send(topic)
end
s:connect(config.server)
for i, channel in ipairs(config.channels) do
s:join(channel)
end
s:sendChat('NickServ', 'identify '..config.password)
logs = io.open(config.dataFileName, "r")
m = cjson.decode(logs:read('*l'))
utcAdjust = os.clock()+20+m[2]
speed = 1
topicTime = os.clock()-60*60+20
while true do
s:think()
if os.clock()*speed > m[2]-utcAdjust then
s:sendChat(config.mainChannel, m[3]:match('(.-)!')..': '..m[4])
sleep(config.refeshRate)
m = cjson.decode(logs:read('*l'))
end
if os.clock > topicTime+60*60 then
topicTime = os.clock()
setTopic()
end
end
|
bug fixes
|
bug fixes
|
Lua
|
mit
|
Houshalter/lw-replay,Houshalter/lw-replay,Houshalter/lw-replay
|
50e6530ceffdfc83ef6433c24f9a52850afa84fc
|
applications/luci-ddns/luasrc/model/cbi/ddns/ddns.lua
|
applications/luci-ddns/luasrc/model/cbi/ddns/ddns.lua
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
local is_mini = (luci.dispatcher.context.path[1] == "mini")
m = Map("ddns", translate("Dynamic DNS"),
translate("Dynamic DNS allows that your router can be reached with " ..
"a fixed hostname while having a dynamically changing " ..
"IP address."))
s = m:section(TypedSection, "service", "")
s.addremove = true
s.anonymous = false
s:option(Flag, "enabled", translate("Enable"))
svc = s:option(ListValue, "service_name", translate("Service"))
svc.rmempty = true
local services = { }
local fd = io.open("/usr/lib/ddns/services", "r")
if fd then
local ln
repeat
ln = fd:read("*l")
local s = ln and ln:match('^%s*"([^"]+)"')
if s then services[#services+1] = s end
until not ln
fd:close()
end
local v
for _, v in luci.util.vspairs(services) do
svc:value(v)
end
svc:value("", "-- "..translate("custom").." --")
url = s:option(Value, "update_url", translate("Custom update-URL"))
url:depends("service_name", "")
url.rmempty = true
s:option(Value, "domain", translate("Hostname")).rmempty = true
s:option(Value, "username", translate("Username")).rmempty = true
pw = s:option(Value, "password", translate("Password"))
pw.rmempty = true
pw.password = true
if is_mini then
s.defaults.ip_source = "network"
s.defaults.ip_network = "wan"
else
require("luci.tools.webadmin")
src = s:option(ListValue, "ip_source",
translate("Source of IP address"))
src:value("network", translate("network"))
src:value("interface", translate("interface"))
src:value("web", translate("URL"))
iface = s:option(ListValue, "ip_network", translate("Network"))
iface:depends("ip_source", "network")
iface.rmempty = true
luci.tools.webadmin.cbi_add_networks(iface)
iface = s:option(ListValue, "ip_interface", translate("Interface"))
iface:depends("ip_source", "interface")
iface.rmempty = true
for k, v in pairs(luci.sys.net.devices()) do
iface:value(v)
end
web = s:option(Value, "ip_url", translate("URL"))
web:depends("ip_source", "web")
web.rmempty = true
end
s:option(Value, "check_interval",
translate("Check for changed IP every")).default = 10
unit = s:option(ListValue, "check_unit", translate("Check-time unit"))
unit.default = "minutes"
unit:value("minutes", translate("min"))
unit:value("hours", translate("h"))
s:option(Value, "force_interval", translate("Force update every")).default = 72
unit = s:option(ListValue, "force_unit", translate("Force-time unit"))
unit.default = "hours"
unit:value("minutes", translate("min"))
unit:value("hours", translate("h"))
return m
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
local is_mini = (luci.dispatcher.context.path[1] == "mini")
m = Map("ddns", translate("Dynamic DNS"),
translate("Dynamic DNS allows that your router can be reached with " ..
"a fixed hostname while having a dynamically changing " ..
"IP address."))
s = m:section(TypedSection, "service", "")
s.addremove = true
s.anonymous = false
s:option(Flag, "enabled", translate("Enable"))
svc = s:option(ListValue, "service_name", translate("Service"))
svc.rmempty = false
local services = { }
local fd = io.open("/usr/lib/ddns/services", "r")
if fd then
local ln
repeat
ln = fd:read("*l")
local s = ln and ln:match('^%s*"([^"]+)"')
if s then services[#services+1] = s end
until not ln
fd:close()
end
local v
for _, v in luci.util.vspairs(services) do
svc:value(v)
end
function svc.cfgvalue(...)
local v = Value.cfgvalue(...)
if not v or #v == 0 then
return "-"
else
return v
end
end
function svc.write(self, section, value)
if value == "-" then
m.uci:delete("ddns", section, self.option)
else
Value.write(self, section, value)
end
end
svc:value("-", "-- "..translate("custom").." --")
url = s:option(Value, "update_url", translate("Custom update-URL"))
url:depends("service_name", "-")
url.rmempty = true
s:option(Value, "domain", translate("Hostname")).rmempty = true
s:option(Value, "username", translate("Username")).rmempty = true
pw = s:option(Value, "password", translate("Password"))
pw.rmempty = true
pw.password = true
if is_mini then
s.defaults.ip_source = "network"
s.defaults.ip_network = "wan"
else
require("luci.tools.webadmin")
src = s:option(ListValue, "ip_source",
translate("Source of IP address"))
src:value("network", translate("network"))
src:value("interface", translate("interface"))
src:value("web", translate("URL"))
iface = s:option(ListValue, "ip_network", translate("Network"))
iface:depends("ip_source", "network")
iface.rmempty = true
luci.tools.webadmin.cbi_add_networks(iface)
iface = s:option(ListValue, "ip_interface", translate("Interface"))
iface:depends("ip_source", "interface")
iface.rmempty = true
for k, v in pairs(luci.sys.net.devices()) do
iface:value(v)
end
web = s:option(Value, "ip_url", translate("URL"))
web:depends("ip_source", "web")
web.rmempty = true
end
s:option(Value, "check_interval",
translate("Check for changed IP every")).default = 10
unit = s:option(ListValue, "check_unit", translate("Check-time unit"))
unit.default = "minutes"
unit:value("minutes", translate("min"))
unit:value("hours", translate("h"))
s:option(Value, "force_interval", translate("Force update every")).default = 72
unit = s:option(ListValue, "force_unit", translate("Force-time unit"))
unit.default = "hours"
unit:value("minutes", translate("min"))
unit:value("hours", translate("h"))
return m
|
applications/luci-ddns: fix selection of custom update_url
|
applications/luci-ddns: fix selection of custom update_url
git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@6588 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
|
Lua
|
apache-2.0
|
projectbismark/luci-bismark,jschmidlapp/luci,ThingMesh/openwrt-luci,8devices/carambola2-luci,saraedum/luci-packages-old,jschmidlapp/luci,stephank/luci,8devices/carambola2-luci,freifunk-gluon/luci,yeewang/openwrt-luci,ThingMesh/openwrt-luci,ch3n2k/luci,stephank/luci,eugenesan/openwrt-luci,ch3n2k/luci,ch3n2k/luci,Flexibity/luci,gwlim/luci,phi-psi/luci,phi-psi/luci,ThingMesh/openwrt-luci,ch3n2k/luci,ch3n2k/luci,gwlim/luci,ReclaimYourPrivacy/cloak-luci,stephank/luci,zwhfly/openwrt-luci,dtaht/cerowrt-luci-3.3,freifunk-gluon/luci,phi-psi/luci,gwlim/luci,freifunk-gluon/luci,jschmidlapp/luci,yeewang/openwrt-luci,dtaht/cerowrt-luci-3.3,Canaan-Creative/luci,ReclaimYourPrivacy/cloak-luci,Canaan-Creative/luci,dtaht/cerowrt-luci-3.3,freifunk-gluon/luci,projectbismark/luci-bismark,ThingMesh/openwrt-luci,8devices/carambola2-luci,vhpham80/luci,zwhfly/openwrt-luci,vhpham80/luci,eugenesan/openwrt-luci,jschmidlapp/luci,phi-psi/luci,stephank/luci,eugenesan/openwrt-luci,Flexibity/luci,yeewang/openwrt-luci,ReclaimYourPrivacy/cloak-luci,eugenesan/openwrt-luci,Canaan-Creative/luci,projectbismark/luci-bismark,saraedum/luci-packages-old,zwhfly/openwrt-luci,jschmidlapp/luci,projectbismark/luci-bismark,ReclaimYourPrivacy/cloak-luci,projectbismark/luci-bismark,ch3n2k/luci,saraedum/luci-packages-old,phi-psi/luci,yeewang/openwrt-luci,projectbismark/luci-bismark,zwhfly/openwrt-luci,Flexibity/luci,ThingMesh/openwrt-luci,jschmidlapp/luci,dtaht/cerowrt-luci-3.3,vhpham80/luci,Flexibity/luci,freifunk-gluon/luci,eugenesan/openwrt-luci,phi-psi/luci,eugenesan/openwrt-luci,Canaan-Creative/luci,jschmidlapp/luci,saraedum/luci-packages-old,Canaan-Creative/luci,ReclaimYourPrivacy/cloak-luci,gwlim/luci,freifunk-gluon/luci,ReclaimYourPrivacy/cloak-luci,8devices/carambola2-luci,projectbismark/luci-bismark,projectbismark/luci-bismark,ReclaimYourPrivacy/cloak-luci,8devices/carambola2-luci,saraedum/luci-packages-old,freifunk-gluon/luci,ch3n2k/luci,phi-psi/luci,saraedum/luci-packages-old,jschmidlapp/luci,zwhfly/openwrt-luci,dtaht/cerowrt-luci-3.3,Canaan-Creative/luci,zwhfly/openwrt-luci,zwhfly/openwrt-luci,Flexibity/luci,dtaht/cerowrt-luci-3.3,ThingMesh/openwrt-luci,gwlim/luci,Flexibity/luci,Flexibity/luci,Canaan-Creative/luci,vhpham80/luci,8devices/carambola2-luci,gwlim/luci,stephank/luci,yeewang/openwrt-luci,stephank/luci,ThingMesh/openwrt-luci,freifunk-gluon/luci,yeewang/openwrt-luci,saraedum/luci-packages-old,yeewang/openwrt-luci,zwhfly/openwrt-luci,vhpham80/luci,8devices/carambola2-luci,Flexibity/luci,Canaan-Creative/luci,vhpham80/luci,eugenesan/openwrt-luci,zwhfly/openwrt-luci,gwlim/luci,ReclaimYourPrivacy/cloak-luci
|
6832197e797dda3801e8fff801b9048db0d77d0e
|
settings/Category.lua
|
settings/Category.lua
|
--
-- A category of game settings.
-- This inherits from Expander so that it can be included directly in the
-- settings edit tree.
--
local Category = ui.Expander:subclass {
per_game = false; -- If true, will be included in the save file
save = true; -- If false, will not be saved to disk at all
hidden = false; -- If true, won't show up in the settings UI
_settings = {};
}
function Category:__tostring()
return 'Category[%s]' % self.name
end
function Category:__index(k)
if Category[k] ~= nil then
return Category[k]
elseif rawget(self, 'settings') and self._settings[k] then
-- category.foo is equivalent to category.settings.foo(), i.e. it returns
-- the value of that setting.
return self._settings[k]()
end
end
function Category:__newindex(k, v)
if rawget(self, 'settings') and self._settings[k] then
-- Similar to the above, setting a field on a category calls the setter for
-- that setting if it exists.
return self._settings[k](v)
end
return rawset(self, k, v)
end
function Category:__init(init)
init.text = init.name
init.content = ui.VList { name = "Category[%s]$internalList" % init.name }
init._settings = {}
ui.Expander.__init(self, init)
settings.categories[self.name] = self
table.insert(settings.categories, self)
local key = self.name:gsub('[^a-zA-Z0-9_]+', '_'):lower()
if key ~= self.name then
if settings.categories[key] then
error('fast-access key for category %s conflicts with existing category %s',
self.name, settings.categories[key].name)
end
settings.categories[key] = self
end
end
function Category:settings()
return self.content:children()
end
function Category:save()
log.info('Saving configuration file %s.cfg', self.name)
return game.saveObject(
'%s.cfg' % self.name,
table.mapv(self._settings, f's => s.value'),
game.name() and self.per_game)
end
function Category:load()
log.info('Loading configuration file %s.cfg', self.name)
local saved = game.loadOptional('%s.cfg' % self.name, game.name() and self.per_game)
for k,v in pairs(saved or {}) do
if self._settings[k] then
log.debug('Setting %s=%s', k, repr(v))
self._settings[k].value = v
else
log.info('Discarding saved value for obsolete setting %s::%s',
self.name, k)
end
end
end
function Category:add(setting)
assertf(not self._settings[setting.name],
"multiple registrations of configuration key %s.%s", self.name, setting.name)
self._settings[setting.name] = setting
local key = setting.name:gsub('[^a-zA-Z0-9_]+', '_'):lower()
if key ~= setting.name then
assertf(not self._settings[key],
'fast-access key for setting %s.%s conflicts with existing setting %s.%s',
self.name, setting.name, self.name, (self._settings[key] or {}).name)
self._settings[key] = setting
end
self.content:attach(setting)
end
return Category
|
--
-- A category of game settings.
-- This inherits from Expander so that it can be included directly in the
-- settings edit tree.
--
local Category = ui.Expander:subclass {
per_game = false; -- If true, will be included in the save file
save = true; -- If false, will not be saved to disk at all
hidden = false; -- If true, won't show up in the settings UI
_settings = {};
}
function Category:__tostring()
return 'Category[%s]' % self.name
end
function Category:__index(k)
if Category[k] ~= nil then
return Category[k]
elseif rawget(self, 'settings') and self._settings[k] then
-- category.foo is equivalent to category.settings.foo(), i.e. it returns
-- the value of that setting.
return self._settings[k]()
end
end
function Category:__newindex(k, v)
if rawget(self, 'settings') and self._settings[k] then
-- Similar to the above, setting a field on a category calls the setter for
-- that setting if it exists.
return self._settings[k](v)
end
return rawset(self, k, v)
end
function Category:__init(init)
init.text = init.name
init.content = ui.VList { name = "Category[%s]$internalList" % init.name }
init._settings = {}
ui.Expander.__init(self, init)
settings.categories[self.name] = self
table.insert(settings.categories, self)
local key = self.name:gsub('[^a-zA-Z0-9_]+', '_'):lower()
if key ~= self.name then
if settings.categories[key] then
error('fast-access key for category %s conflicts with existing category %s',
self.name, settings.categories[key].name)
end
settings.categories[key] = self
end
end
function Category:settings()
return self.content:children()
end
function Category:save()
log.info('Saving configuration file %s.cfg', self.name)
return game.saveObject(
'%s.cfg' % self.name,
table.mapv(self._settings, f's => s.value'),
game.name() and self.per_game)
end
function Category:load()
log.info('Loading configuration file %s.cfg', self.name)
local saved = game.loadOptional('%s.cfg' % self.name, game.name() and self.per_game)
for k,v in pairs(saved or {}) do
if self._settings[k] then
log.debug('Setting %s=%s', k, repr(v))
self._settings[k].value = v
else
log.info('Discarding saved value for obsolete setting %s::%s',
self.name, k)
end
end
end
function Category:add(setting)
assertf(not self._settings[setting.name],
"multiple registrations of configuration key %s.%s", self.name, setting.name)
local key = setting.name:gsub('[^a-zA-Z0-9_]+', '_'):lower()
self._settings[key] = setting
self.content:attach(setting)
end
return Category
|
Fix issue with settings getting double stored
|
Fix issue with settings getting double stored
|
Lua
|
mit
|
ToxicFrog/ttymor
|
12f588a6368ed26f8f274f4950a1c586f469e812
|
zmq.nobj.lua
|
zmq.nobj.lua
|
-- make generated variable nicer.
set_variable_format "%s"
c_module "zmq" {
-- module settings.
use_globals = false,
hide_meta_info = true,
luajit_ffi = true,
sys_include "string.h",
include "zmq.h",
ffi_load "zmq",
c_source[[
#define OBJ_UDATA_CTX_SHOULD_FREE (OBJ_UDATA_LAST_FLAG << 1)
]],
ffi_source[[
local OBJ_UDATA_CTX_SHOULD_FREE = (OBJ_UDATA_LAST_FLAG * 2)
]],
c_source[[
/*
* This wrapper function is to make the EAGAIN/ETERM error messages more like
* what is returned by LuaSocket.
*/
static const char *get_zmq_strerror() {
int err = zmq_errno();
switch(err) {
case EAGAIN:
return "timeout";
break;
case ETERM:
return "closed";
break;
default:
break;
}
return zmq_strerror(err);
}
]],
-- export helper function 'get_zmq_strerror' to FFI code.
ffi_export_function "const char *" "get_zmq_strerror" "()",
ffi_source[[
local C_get_zmq_strerror = get_zmq_strerror
-- make nicer wrapper for exported error function.
local function get_zmq_strerror()
return ffi.string(C_get_zmq_strerror())
end
]],
--
-- Module constants
--
constants {
MAX_VSM_SIZE = 30,
-- message types
DELIMITER = 31,
VSM = 32,
-- message flags
MSG_MORE = 1,
MSG_SHARED = 128,
-- socket types
PAIR = 0,
PUB = 1,
SUB = 2,
REQ = 3,
REP = 4,
XREQ = 5,
XREP = 6,
PULL = 7,
PUSH = 8,
-- socket options
HWM = 1,
SWAP = 3,
AFFINITY = 4,
IDENTITY = 5,
SUBSCRIBE = 6,
UNSUBSCRIBE = 7,
RATE = 8,
RECOVERY_IVL = 9,
MCAST_LOOP = 10,
SNDBUF = 11,
RCVBUF = 12,
RCVMORE = 13,
FD = 14,
EVENTS = 15,
TYPE = 16,
LINGER = 17,
RECONNECT_IVL = 18,
BACKLOG = 19,
-- send/recv flags
NOBLOCK = 1,
SNDMORE = 2,
-- poll events
POLLIN = 1,
POLLOUT = 2,
POLLERR = 4,
-- devices
STREAMER = 1,
FORWARDER = 2,
QUEUE = 3,
},
subfiles {
"src/error.nobj.lua",
"src/msg.nobj.lua",
"src/socket.nobj.lua",
"src/ctx.nobj.lua",
},
--
-- Module static functions
--
c_function "version" {
var_out{ "<any>", "ver" },
c_source[[
int major, minor, patch;
zmq_version(&(major), &(minor), &(patch));
/* return version as a table: { major, minor, patch } */
lua_createtable(L, 3, 0);
lua_pushinteger(L, major);
lua_rawseti(L, -2, 1);
lua_pushinteger(L, minor);
lua_rawseti(L, -2, 2);
lua_pushinteger(L, patch);
lua_rawseti(L, -2, 3);
]],
},
c_function "init" {
c_call "!ZMQ_Ctx" "zmq_init" { "int", "io_threads" },
},
c_function "init_ctx" {
var_in{ "<any>", "ptr" },
var_out{ "ZMQ_Ctx", "!ctx" },
c_source[[
if(lua_isuserdata(L, ${ptr::idx})) {
${ctx} = lua_touserdata(L, ${ptr::idx});
} else {
/* check if value is a LuaJIT 'cdata' */
int type = lua_type(L, ${ptr::idx});
const char *typename = lua_typename(L, type);
if(strncmp(typename, "cdata", sizeof("cdata")) == 0) {
${ctx} = (void *)lua_topointer(L, ${ptr::idx});
} else {
return luaL_argerror(L, ${ptr::idx}, "(expected userdata)");
}
}
]],
},
c_function "device" {
c_call "ZMQ_Error" "zmq_device"
{ "int", "device", "ZMQ_Socket", "insock", "ZMQ_Socket", "outsock" },
},
--
-- This dump function is for getting a copy of the FFI-based bindings code and is
-- only for debugging.
--
c_function "dump_ffi" {
var_out{ "const char *", "ffi_code", has_length = true, },
c_source[[
${ffi_code} = ${module_c_name}_ffi_lua_code;
${ffi_code_len} = sizeof(${module_c_name}_ffi_lua_code) - 1;
]],
},
}
|
-- make generated variable nicer.
set_variable_format "%s"
c_module "zmq" {
-- module settings.
use_globals = false,
hide_meta_info = true,
luajit_ffi = true,
sys_include "string.h",
include "zmq.h",
ffi_load "zmq",
c_source[[
#define OBJ_UDATA_CTX_SHOULD_FREE (OBJ_UDATA_LAST_FLAG << 1)
]],
ffi_source[[
local OBJ_UDATA_CTX_SHOULD_FREE = (OBJ_UDATA_LAST_FLAG * 2)
]],
c_source[[
/*
* This wrapper function is to make the EAGAIN/ETERM error messages more like
* what is returned by LuaSocket.
*/
static const char *get_zmq_strerror() {
int err = zmq_errno();
switch(err) {
case EAGAIN:
return "timeout";
break;
case ETERM:
return "closed";
break;
default:
break;
}
return zmq_strerror(err);
}
]],
-- export helper function 'get_zmq_strerror' to FFI code.
ffi_export_function "const char *" "get_zmq_strerror" "()",
ffi_source[[
local C_get_zmq_strerror = get_zmq_strerror
-- make nicer wrapper for exported error function.
local function get_zmq_strerror()
return ffi.string(C_get_zmq_strerror())
end
]],
--
-- Module constants
--
constants {
MAX_VSM_SIZE = 30,
-- message types
DELIMITER = 31,
VSM = 32,
-- message flags
MSG_MORE = 1,
MSG_SHARED = 128,
-- socket types
PAIR = 0,
PUB = 1,
SUB = 2,
REQ = 3,
REP = 4,
XREQ = 5,
XREP = 6,
PULL = 7,
PUSH = 8,
-- socket options
HWM = 1,
SWAP = 3,
AFFINITY = 4,
IDENTITY = 5,
SUBSCRIBE = 6,
UNSUBSCRIBE = 7,
RATE = 8,
RECOVERY_IVL = 9,
MCAST_LOOP = 10,
SNDBUF = 11,
RCVBUF = 12,
RCVMORE = 13,
FD = 14,
EVENTS = 15,
TYPE = 16,
LINGER = 17,
RECONNECT_IVL = 18,
BACKLOG = 19,
-- send/recv flags
NOBLOCK = 1,
SNDMORE = 2,
-- poll events
POLLIN = 1,
POLLOUT = 2,
POLLERR = 4,
-- devices
STREAMER = 1,
FORWARDER = 2,
QUEUE = 3,
},
subfiles {
"src/error.nobj.lua",
"src/msg.nobj.lua",
"src/socket.nobj.lua",
"src/ctx.nobj.lua",
},
--
-- Module static functions
--
c_function "version" {
var_out{ "<any>", "ver" },
c_source[[
int major, minor, patch;
zmq_version(&(major), &(minor), &(patch));
/* return version as a table: { major, minor, patch } */
lua_createtable(L, 3, 0);
lua_pushinteger(L, major);
lua_rawseti(L, -2, 1);
lua_pushinteger(L, minor);
lua_rawseti(L, -2, 2);
lua_pushinteger(L, patch);
lua_rawseti(L, -2, 3);
]],
},
c_function "init" {
c_call "!ZMQ_Ctx" "zmq_init" { "int", "io_threads" },
},
c_function "init_ctx" {
var_in{ "<any>", "ptr" },
var_out{ "ZMQ_Ctx", "!ctx" },
c_source[[
if(lua_isuserdata(L, ${ptr::idx})) {
${ctx} = lua_touserdata(L, ${ptr::idx});
} else {
return luaL_argerror(L, ${ptr::idx}, "expected lightuserdata");
}
]],
ffi_source[[
local p_type = type(${ptr})
if p_type == 'userdata' then
${ctx} = ffi.cast('void *', ${ptr});
elseif p_type == 'cdata' then
${ctx} = ${ptr};
else
return error("expected lightuserdata/cdata<void *>");
end
]],
},
c_function "device" {
c_call "ZMQ_Error" "zmq_device"
{ "int", "device", "ZMQ_Socket", "insock", "ZMQ_Socket", "outsock" },
},
--
-- This dump function is for getting a copy of the FFI-based bindings code and is
-- only for debugging.
--
c_function "dump_ffi" {
var_out{ "const char *", "ffi_code", has_length = true, },
c_source[[
${ffi_code} = ${module_c_name}_ffi_lua_code;
${ffi_code_len} = sizeof(${module_c_name}_ffi_lua_code) - 1;
]],
},
}
|
Fixed context initialization from FFI cdata value.
|
Fixed context initialization from FFI cdata value.
|
Lua
|
mit
|
azukiapp/lua-zmq,Neopallium/lua-zmq
|
03530b4afa571e82d0b55945ef58cfdd82f9283a
|
src/plugins/colorfinale/tangent.lua
|
src/plugins/colorfinale/tangent.lua
|
--- === plugins.colorfinale.tangent ===
---
--- This plugin basically just disables CP's Tangent Manager when ColorFinale is running.
local require = require
--local log = require "hs.logger".new "ColorFinale"
local application = require "hs.application"
local fcp = require "cp.apple.finalcutpro"
local prop = require "cp.prop"
local tools = require "cp.tools"
local infoForBundleID = application.infoForBundleID
local startsWith = tools.startsWith
local mod = {}
-- APP_BUNDLE_ID -> string
-- Constant
-- ColorFinale Bundle ID
local APP_BUNDLE_IDS = {
"com.colorfinale.LUTManager", -- Color Finale
"com.colorfinale.app", -- Color Finale 2
}
-- WINDOW_TITLE -> string
-- Constant
-- ColorFinale Window Title
local WINDOW_TITLE = "Color Finale"
--- plugins.colorfinale.tangent.init(tangentManager) -> module
--- Function
--- Initialise the module.
---
--- Parameters:
--- * tangentManager - The Tangent Manager
---
--- Returns:
--- * The ColorFinale Tangent Module.
function mod.init(tangentManager)
mod._tangentManager = tangentManager
--------------------------------------------------------------------------------
-- Watch for FCP opening or closing:
--------------------------------------------------------------------------------
fcp.isFrontmost:watch(function()
if mod.colorFinaleInstalled() then
mod.colorFinaleWindowUI:update()
end
end)
--------------------------------------------------------------------------------
-- Add an interruption to Tangent Manager:
--------------------------------------------------------------------------------
mod._tangentManager.interruptWhen(mod.colorFinaleActive)
return mod
end
local colorFinaleWindowUI = fcp.windowsUI:mutate(function(original)
local windows = original()
if windows then
for _,w in ipairs(fcp:windowsUI()) do
if startsWith(w:attributeValue("AXTitle"), WINDOW_TITLE) then
return w
end
end
end
return nil
end)
prop.bind(mod) {
--- plugins.colorfinale.tangent.colorFinaleWindowUI <cp.prop: hs._asm.axuielement; read-only>
--- Variable
--- Returns the `axuielement` for the ColorFinale window, if present.
colorFinaleWindowUI = colorFinaleWindowUI,
--- plugins.colorfinale.tangent.colorFinaleVisible <cp.prop: boolean; read-only; live>
--- Variable
--- Checks to see if an object is a Color Finale window.
colorFinaleVisible = colorFinaleWindowUI:mutate(function(original)
local windows = original()
if windows then
for _,w in ipairs(windows) do
if startsWith(w:attributeValue("AXTitle"), WINDOW_TITLE) then
return true
end
end
end
return false
end),
--- plugins.colorfinale.tangent.colorFinaleInstalled <cp.prop: boolean; read-only; live>
--- Variable
--- Checks to see if ColorFinale is installed.
colorFinaleInstalled = prop(function()
for _, id in pairs(APP_BUNDLE_IDS) do
local info = infoForBundleID(id)
if info then
return true
end
end
return false
end),
}
prop.bind(mod) {
--- plugins.colorfinale.tangent.colorFinaleActive <cp.prop: boolean; read-only; live>
--- Variable
--- Checks to see if ColorFinale is active.
colorFinaleActive = mod.colorFinaleInstalled:AND(mod.colorFinaleVisible),
}
local plugin = {
id = "colorfinale.tangent",
group = "colorfinale",
dependencies = {
["core.tangent.manager"] = "tangentManager",
}
}
function plugin.init(deps)
return mod.init(deps.tangentManager)
end
return plugin
|
--- === plugins.colorfinale.tangent ===
---
--- This plugin basically just disables CP's Tangent Manager when ColorFinale is running.
local require = require
--local log = require "hs.logger".new "ColorFinale"
local application = require "hs.application"
local fcp = require "cp.apple.finalcutpro"
local prop = require "cp.prop"
local tools = require "cp.tools"
local infoForBundleID = application.infoForBundleID
local startsWith = tools.startsWith
local mod = {}
-- APP_BUNDLE_ID -> string
-- Constant
-- ColorFinale Bundle ID
local APP_BUNDLE_IDS = {
"com.colorfinale.LUTManager", -- Color Finale
"com.colorfinale.app", -- Color Finale 2
}
-- WINDOW_TITLE -> string
-- Constant
-- ColorFinale Window Title
local WINDOW_TITLE = "Color Finale"
--- plugins.colorfinale.tangent.init(tangentManager) -> module
--- Function
--- Initialise the module.
---
--- Parameters:
--- * tangentManager - The Tangent Manager
---
--- Returns:
--- * The ColorFinale Tangent Module.
function mod.init(tangentManager)
mod._tangentManager = tangentManager
--------------------------------------------------------------------------------
-- Watch for FCP opening or closing:
--------------------------------------------------------------------------------
fcp.isFrontmost:watch(function()
if mod.colorFinaleInstalled() then
mod.colorFinaleWindowUI:update()
end
end)
--------------------------------------------------------------------------------
-- Add an interruption to Tangent Manager:
--------------------------------------------------------------------------------
mod._tangentManager.interruptWhen(mod.colorFinaleActive)
return mod
end
local colorFinaleWindowUI = fcp.windowsUI:mutate(function(original)
local windows = original()
if windows then
for _,w in ipairs(fcp:windowsUI()) do
if startsWith(w:attributeValue("AXTitle"), WINDOW_TITLE) then
return w
end
end
end
return nil
end)
prop.bind(mod) {
--- plugins.colorfinale.tangent.colorFinaleWindowUI <cp.prop: hs._asm.axuielement; read-only>
--- Variable
--- Returns the `axuielement` for the ColorFinale window, if present.
colorFinaleWindowUI = colorFinaleWindowUI,
--- plugins.colorfinale.tangent.colorFinaleVisible <cp.prop: boolean; read-only; live>
--- Variable
--- Checks to see if an object is a Color Finale window.
colorFinaleVisible = colorFinaleWindowUI:mutate(function(original)
local window = original()
return window ~= nil and startsWith(window:attributeValue("AXTitle"), WINDOW_TITLE)
end),
--- plugins.colorfinale.tangent.colorFinaleInstalled <cp.prop: boolean; read-only; live>
--- Variable
--- Checks to see if ColorFinale is installed.
colorFinaleInstalled = prop(function()
for _, id in ipairs(APP_BUNDLE_IDS) do
local info = infoForBundleID(id)
if info then
return true
end
end
return false
end),
}
prop.bind(mod) {
--- plugins.colorfinale.tangent.colorFinaleActive <cp.prop: boolean; read-only; live>
--- Variable
--- Checks to see if ColorFinale is active.
colorFinaleActive = mod.colorFinaleInstalled:AND(mod.colorFinaleVisible),
}
local plugin = {
id = "colorfinale.tangent",
group = "colorfinale",
dependencies = {
["core.tangent.manager"] = "tangentManager",
}
}
function plugin.init(deps)
return mod.init(deps.tangentManager)
end
return plugin
|
#2169 Fixed detection of CF1 being active.
|
#2169 Fixed detection of CF1 being active.
|
Lua
|
mit
|
CommandPost/CommandPost,fcpxhacks/fcpxhacks,CommandPost/CommandPost,fcpxhacks/fcpxhacks,CommandPost/CommandPost
|
21a46b39e30596cc3b49c843b3d6522adbe743d8
|
tests/config/test_links.lua
|
tests/config/test_links.lua
|
--
-- tests/config/test_links.lua
-- Test the list of linked objects retrieval function.
-- Copyright (c) 2012 Jason Perkins and the Premake project
--
T.config_links = { }
local suite = T.config_links
local project = premake5.project
local config = premake5.config
--
-- Setup and teardown
--
local sln, prj, cfg
function suite.setup()
_ACTION = "test"
sln, prj = test.createsolution()
system "macosx"
end
local function prepare(kind, part)
cfg = project.getconfig(prj, "Debug")
return config.getlinks(cfg, kind, part)
end
--
-- If no links are present, should return an empty table.
--
function suite.emptyResult_onNoLinks()
local r = prepare("all", "object")
test.isequal(0, #r)
end
--
-- System libraries which include path information are made project relative.
--
function suite.pathMadeRelative_onSystemLibWithPath()
location "build"
links { "../libs/z" }
local r = prepare("all", "fullpath")
test.isequal({ "../../libs/z" }, r)
end
--
-- On Windows, system libraries get the ".lib" file extensions.
--
function suite.libAdded_onWindowsSystemLibs()
system "windows"
links { "user32" }
local r = prepare("all", "fullpath")
test.isequal({ "user32.lib" }, r)
end
function suite.libAdded_onWindowsSystemLibs()
system "windows"
links { "user32.lib" }
local r = prepare("all", "fullpath")
test.isequal({ "user32.lib" }, r)
end
--
-- Check handling of shell variables in library paths.
--
function suite.variableMaintained_onLeadingVariable()
system "windows"
location "build"
links { "$(SN_PS3_PATH)/sdk/lib/PS3TMAPI" }
local r = prepare("all", "fullpath")
test.isequal({ "$(SN_PS3_PATH)/sdk/lib/PS3TMAPI.lib" }, r)
end
function suite.variableMaintained_onQuotedVariable()
system "windows"
location "build"
links { '"$(SN_PS3_PATH)/sdk/lib/PS3TMAPI.lib"' }
local r = prepare("all", "fullpath")
test.isequal({ '"$(SN_PS3_PATH)/sdk/lib/PS3TMAPI.lib"' }, r)
end
|
--
-- tests/config/test_links.lua
-- Test the list of linked objects retrieval function.
-- Copyright (c) 2012 Jason Perkins and the Premake project
--
T.config_links = { }
local suite = T.config_links
local project = premake5.project
local config = premake5.config
--
-- Setup and teardown
--
local sln, prj, cfg
function suite.setup()
_ACTION = "test"
sln, prj = test.createsolution()
system "macosx"
end
local function prepare(kind, part)
cfg = project.getconfig(prj, "Debug")
return config.getlinks(cfg, kind, part)
end
--
-- If no links are present, should return an empty table.
--
function suite.emptyResult_onNoLinks()
local r = prepare("all", "object")
test.isequal(0, #r)
end
--
-- System libraries which include path information are made project relative.
--
function suite.pathMadeRelative_onSystemLibWithPath()
location "build"
links { "../libs/z" }
local r = prepare("all", "fullpath")
test.isequal({ "../../libs/z" }, r)
end
--
-- On Windows, system libraries get the ".lib" file extensions.
--
function suite.libAdded_onWindowsSystemLibs()
system "windows"
links { "user32" }
local r = prepare("all", "fullpath")
test.isequal({ "user32.lib" }, r)
end
function suite.libAdded_onWindowsSystemLibs()
system "windows"
links { "user32.lib" }
local r = prepare("all", "fullpath")
test.isequal({ "user32.lib" }, r)
end
--
-- Check handling of shell variables in library paths.
--
function suite.variableMaintained_onLeadingVariable()
system "windows"
location "build"
links { "$(SN_PS3_PATH)/sdk/lib/PS3TMAPI" }
local r = prepare("all", "fullpath")
test.isequal({ "$(SN_PS3_PATH)/sdk/lib/PS3TMAPI.lib" }, r)
end
function suite.variableMaintained_onQuotedVariable()
system "windows"
location "build"
links { '"$(SN_PS3_PATH)/sdk/lib/PS3TMAPI.lib"' }
local r = prepare("all", "fullpath")
test.isequal({ '"$(SN_PS3_PATH)/sdk/lib/PS3TMAPI.lib"' }, r)
end
--
-- If fetching directories, the libdirs should be included in the result.
--
function suite.includesLibDirs_onDirectories()
libdirs { "../libs" }
local r = prepare("all", "directory")
test.isequal({ "../libs" }, r)
end
|
Added test for libdirs fix
|
Added test for libdirs fix
|
Lua
|
bsd-3-clause
|
annulen/premake-dev-rgeary,annulen/premake-dev-rgeary,annulen/premake-dev-rgeary
|
4e91e0d220f0f4ea42cc5d7db6f3a73f72eea60d
|
src/tools/msc.lua
|
src/tools/msc.lua
|
--
-- msc.lua
-- Interface for the MS C/C++ compiler.
-- Copyright (c) 2009-2013 Jason Perkins and the Premake project
--
premake.tools.msc = {}
local msc = premake.tools.msc
local project = premake.project
local config = premake.config
--
-- Returns list of C preprocessor flags for a configuration.
--
function msc.getcppflags(cfg)
return {}
end
--
-- Returns list of C compiler flags for a configuration.
--
msc.cflags = {
flags = {
SEH = "/EHa /EHsc",
Symbols = "/Z7",
},
optimize = {
Off = "/Od",
Speed = "/O2",
}
}
function msc.getcflags(cfg)
local flags = config.mapFlags(cfg, msc.cflags)
local runtime = iif(cfg.flags.StaticRuntime, "/MT", "/MD")
if config.isDebugBuild(cfg) then
runtime = runtime .. "d"
end
table.insert(flags, runtime)
return flags
end
--
-- Returns list of C++ compiler flags for a configuration.
--
msc.cxxflags = {
}
function msc.getcxxflags(cfg)
return table.translate(cfg.flags, msc.cxxflags)
end
msc.ldflags = {
Symbols = "/DEBUG",
}
--
-- Decorate defines for the MSVC command line.
--
function msc.getdefines(defines)
local result = {}
for _, define in ipairs(defines) do
table.insert(result, '-D' .. define)
end
return result
end
--
-- Returns a list of forced include files, decorated for the compiler
-- command line.
--
-- @param cfg
-- The project configuration.
-- @return
-- An array of force include files with the appropriate flags.
--
function msc.getforceincludes(cfg)
local result = {}
table.foreachi(cfg.forceincludes, function(value)
local fn = project.getrelative(cfg.project, value)
table.insert(result, "/FI" .. premake.quoted(fn))
end)
return result
end
--
-- Decorate include file search paths for the MSVC command line.
--
function msc.getincludedirs(cfg, dirs)
local result = {}
for _, dir in ipairs(dirs) do
dir = project.getrelative(cfg.project, dir)
table.insert(result, '-I' .. premake.quoted(dir))
end
return result
end
--
-- Return a list of linker flags for a specific configuration.
--
msc.ldflags = {
Symbols = "/DEBUG",
}
function msc.getldflags(cfg)
local flags = table.translate(cfg.flags, msc.ldflags)
if not cfg.flags.NoManifest and cfg.kind ~= premake.STATICLIB then
table.insert(flags, "/MANIFEST")
end
if config.isOptimizedBuild(cfg) then
table.insert(flags, "/OPT:REF /OPT:ICF")
end
for _, libdir in ipairs(project.getrelative(cfg.project, cfg.libdirs)) do
table.insert(flags, '/LIBPATH:"' .. libdir .. '"')
end
return flags
end
--
-- Return the list of libraries to link, decorated with flags as needed.
--
function msc.getlinks(cfg)
local links = config.getlinks(cfg, "system", "fullpath")
return links
end
--
-- Returns makefile-specific configuration rules.
--
function msc.getmakesettings(cfg)
return nil
end
--
-- Retrieves the executable command name for a tool, based on the
-- provided configuration and the operating environment.
--
-- @param cfg
-- The configuration to query.
-- @param tool
-- The tool to fetch, one of "cc" for the C compiler, "cxx" for
-- the C++ compiler, or "ar" for the static linker.
-- @return
-- The executable command name for a tool, or nil if the system's
-- default value should be used.
--
function msc.gettoolname(cfg, tool)
return nil
end
|
--
-- msc.lua
-- Interface for the MS C/C++ compiler.
-- Copyright (c) 2009-2013 Jason Perkins and the Premake project
--
premake.tools.msc = {}
local msc = premake.tools.msc
local project = premake.project
local config = premake.config
--
-- Returns list of C preprocessor flags for a configuration.
--
function msc.getcppflags(cfg)
return {}
end
--
-- Returns list of C compiler flags for a configuration.
--
msc.cflags = {
flags = {
SEH = "/EHa",
Symbols = "/Z7",
},
optimize = {
Off = "/Od",
Speed = "/O2",
}
}
function msc.getcflags(cfg)
local flags = config.mapFlags(cfg, msc.cflags)
local runtime = iif(cfg.flags.StaticRuntime, "/MT", "/MD")
if config.isDebugBuild(cfg) then
runtime = runtime .. "d"
end
table.insert(flags, runtime)
if not cfg.flags.SEH then
table.insert(flags, "/EHsc")
end
return flags
end
--
-- Returns list of C++ compiler flags for a configuration.
--
msc.cxxflags = {
}
function msc.getcxxflags(cfg)
return table.translate(cfg.flags, msc.cxxflags)
end
msc.ldflags = {
Symbols = "/DEBUG",
}
--
-- Decorate defines for the MSVC command line.
--
function msc.getdefines(defines)
local result = {}
for _, define in ipairs(defines) do
table.insert(result, '-D' .. define)
end
return result
end
--
-- Returns a list of forced include files, decorated for the compiler
-- command line.
--
-- @param cfg
-- The project configuration.
-- @return
-- An array of force include files with the appropriate flags.
--
function msc.getforceincludes(cfg)
local result = {}
table.foreachi(cfg.forceincludes, function(value)
local fn = project.getrelative(cfg.project, value)
table.insert(result, "/FI" .. premake.quoted(fn))
end)
return result
end
--
-- Decorate include file search paths for the MSVC command line.
--
function msc.getincludedirs(cfg, dirs)
local result = {}
for _, dir in ipairs(dirs) do
dir = project.getrelative(cfg.project, dir)
table.insert(result, '-I' .. premake.quoted(dir))
end
return result
end
--
-- Return a list of linker flags for a specific configuration.
--
msc.ldflags = {
Symbols = "/DEBUG",
}
function msc.getldflags(cfg)
local flags = table.translate(cfg.flags, msc.ldflags)
if not cfg.flags.NoManifest and cfg.kind ~= premake.STATICLIB then
table.insert(flags, "/MANIFEST")
end
if config.isOptimizedBuild(cfg) then
table.insert(flags, "/OPT:REF /OPT:ICF")
end
for _, libdir in ipairs(project.getrelative(cfg.project, cfg.libdirs)) do
table.insert(flags, '/LIBPATH:"' .. libdir .. '"')
end
return flags
end
--
-- Return the list of libraries to link, decorated with flags as needed.
--
function msc.getlinks(cfg)
local links = config.getlinks(cfg, "system", "fullpath")
return links
end
--
-- Returns makefile-specific configuration rules.
--
function msc.getmakesettings(cfg)
return nil
end
--
-- Retrieves the executable command name for a tool, based on the
-- provided configuration and the operating environment.
--
-- @param cfg
-- The configuration to query.
-- @param tool
-- The tool to fetch, one of "cc" for the C compiler, "cxx" for
-- the C++ compiler, or "ar" for the static linker.
-- @return
-- The executable command name for a tool, or nil if the system's
-- default value should be used.
--
function msc.gettoolname(cfg, tool)
return nil
end
|
Fix broken MSC exception handling flag
|
Fix broken MSC exception handling flag
|
Lua
|
bsd-3-clause
|
dimitarcl/premake-dev,dimitarcl/premake-dev,dimitarcl/premake-dev
|
31df5d9604681af8c75afa82b572e56ac6590a26
|
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 hooks = _.installTestingHooks()
_TESTS_DIR = test.suite._TESTS_DIR
_SCRIPT_DIR = test.suite._SCRIPT_DIR
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)
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)
_ACTION = 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 {
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
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
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)
_ACTION = 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 {
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
|
fix bug in testing framework leaving tests in random working folders.
|
fix bug in testing framework leaving tests in random working folders.
|
Lua
|
bsd-3-clause
|
sleepingwit/premake-core,TurkeyMan/premake-core,mendsley/premake-core,Blizzard/premake-core,Blizzard/premake-core,Blizzard/premake-core,tvandijck/premake-core,Zefiros-Software/premake-core,Blizzard/premake-core,tvandijck/premake-core,mandersan/premake-core,TurkeyMan/premake-core,premake/premake-core,sleepingwit/premake-core,TurkeyMan/premake-core,mandersan/premake-core,dcourtois/premake-core,LORgames/premake-core,premake/premake-core,starkos/premake-core,Zefiros-Software/premake-core,noresources/premake-core,soundsrc/premake-core,sleepingwit/premake-core,Zefiros-Software/premake-core,aleksijuvani/premake-core,TurkeyMan/premake-core,noresources/premake-core,LORgames/premake-core,starkos/premake-core,premake/premake-core,mendsley/premake-core,sleepingwit/premake-core,starkos/premake-core,dcourtois/premake-core,Blizzard/premake-core,LORgames/premake-core,premake/premake-core,premake/premake-core,soundsrc/premake-core,starkos/premake-core,mendsley/premake-core,dcourtois/premake-core,tvandijck/premake-core,soundsrc/premake-core,sleepingwit/premake-core,aleksijuvani/premake-core,noresources/premake-core,mandersan/premake-core,dcourtois/premake-core,aleksijuvani/premake-core,premake/premake-core,premake/premake-core,aleksijuvani/premake-core,tvandijck/premake-core,mendsley/premake-core,tvandijck/premake-core,Zefiros-Software/premake-core,Blizzard/premake-core,noresources/premake-core,noresources/premake-core,starkos/premake-core,LORgames/premake-core,noresources/premake-core,LORgames/premake-core,aleksijuvani/premake-core,mendsley/premake-core,dcourtois/premake-core,noresources/premake-core,dcourtois/premake-core,Zefiros-Software/premake-core,starkos/premake-core,soundsrc/premake-core,TurkeyMan/premake-core,starkos/premake-core,dcourtois/premake-core,mandersan/premake-core,mandersan/premake-core,soundsrc/premake-core
|
208e6b083392672f7c2b47bb62ccebe975f90bf4
|
mod_blocking/mod_blocking.lua
|
mod_blocking/mod_blocking.lua
|
local jid_split = require "util.jid".split;
local st = require "util.stanza";
local xmlns_blocking = "urn:xmpp:blocking";
module:add_feature("urn:xmpp:blocking");
-- Add JID to default privacy list
function add_blocked_jid(username, host, jid)
local privacy_lists = datamanager.load(username, host, "privacy") or {lists = {}};
local default_list_name = privacy_lists.default;
if not default_list_name then
default_list_name = "blocklist";
privacy_lists.default = default_list_name;
end
local default_list = privacy_lists.lists[default_list_name];
if not default_list then
default_list = { name = default_list_name, items = {} };
privacy_lists.lists[default_list_name] = default_list;
end
local items = default_list.items;
local order = items[1] and items[1].order or 0; -- Must come first
for i=1,#items do -- order must be unique
local item = items[i];
item.order = item.order + 1;
if item.type == "jid" and item.action == "deny" and item.value == jid then
return false;
end
end
table.insert(items, 1, { type = "jid"
, action = "deny"
, value = jid
, message = false
, ["presence-out"] = false
, ["presence-in"] = false
, iq = false
, order = order
});
datamanager.store(username, host, "privacy", privacy_lists);
return true;
end
-- Remove JID from default privacy list
function remove_blocked_jid(username, host, jid)
local privacy_lists = datamanager.load(username, host, "privacy") or {};
local default_list_name = privacy_lists.default;
if not default_list_name then return; end
local default_list = privacy_lists.lists[default_list_name];
if not default_list then return; end
local items = default_list.items;
local item, removed = nil, false;
for i=1,#items do -- order must be unique
item = items[i];
if item.type == "jid" and item.action == "deny" and item.value == jid then
table.remove(items, i);
removed = true;
break;
end
end
if removed then
datamanager.store(username, host, "privacy", privacy_lists);
end
return removed;
end
function remove_all_blocked_jids(username, host)
local privacy_lists = datamanager.load(username, host, "privacy") or {};
local default_list_name = privacy_lists.default;
if not default_list_name then return; end
local default_list = privacy_lists.lists[default_list_name];
if not default_list then return; end
local items = default_list.items;
local item;
for i=#items,1,-1 do -- order must be unique
item = items[i];
if item.type == "jid" and item.action == "deny" then
table.remove(items, i);
end
end
datamanager.store(username, host, "privacy", privacy_lists);
return true;
end
function get_blocked_jids(username, host)
-- Return array of blocked JIDs in default privacy list
local privacy_lists = datamanager.load(username, host, "privacy") or {};
local default_list_name = privacy_lists.default;
if not default_list_name then return {}; end
local default_list = privacy_lists.lists[default_list_name];
if not default_list then return {}; end
local items = default_list.items;
local item;
local jid_list = {};
for i=1,#items do -- order must be unique
item = items[i];
if item.type == "jid" and item.action == "deny" then
jid_list[#jid_list+1] = item.value;
end
end
return jid_list;
end
function handle_blocking_command(event)
local session, stanza = event.origin, event.stanza;
local username, host = jid_split(stanza.attr.from);
if stanza.attr.type == "set" then
if stanza.tags[1].name == "block" then
local block = stanza.tags[1];
local block_jid_list = {};
for item in block:childtags() do
block_jid_list[#block_jid_list+1] = item.attr.jid;
end
if #block_jid_list == 0 then
session.send(st.error_reply(stanza, "modify", "bad-request"));
else
for _, jid in ipairs(block_jid_list) do
add_blocked_jid(username, host, jid);
end
session.send(st.reply(stanza));
end
return true;
elseif stanza.tags[1].name == "unblock" then
remove_all_blocked_jids(username, host);
session.send(st.reply(stanza));
return true;
end
elseif stanza.attr.type == "get" and stanza.tags[1].name == "blocklist" then
local reply = st.reply(stanza):tag("blocklist", { xmlns = xmlns_blocking });
local blocked_jids = get_blocked_jids(username, host);
for _, jid in ipairs(blocked_jids) do
reply:tag("item", { jid = jid }):up();
end
session.send(reply);
return true;
end
end
module:hook("iq/self/urn:xmpp:blocking:blocklist", handle_blocking_command);
module:hook("iq/self/urn:xmpp:blocking:block", handle_blocking_command);
module:hook("iq/self/urn:xmpp:blocking:unblock", handle_blocking_command);
|
local jid_split = require "util.jid".split;
local st = require "util.stanza";
local xmlns_blocking = "urn:xmpp:blocking";
module:add_feature("urn:xmpp:blocking");
-- Add JID to default privacy list
function add_blocked_jid(username, host, jid)
local privacy_lists = datamanager.load(username, host, "privacy") or {lists = {}};
local default_list_name = privacy_lists.default;
if not default_list_name then
default_list_name = "blocklist";
privacy_lists.default = default_list_name;
end
local default_list = privacy_lists.lists[default_list_name];
if not default_list then
default_list = { name = default_list_name, items = {} };
privacy_lists.lists[default_list_name] = default_list;
end
local items = default_list.items;
local order = items[1] and items[1].order or 0; -- Must come first
for i=1,#items do -- order must be unique
local item = items[i];
item.order = item.order + 1;
if item.type == "jid" and item.action == "deny" and item.value == jid then
return false;
end
end
table.insert(items, 1, { type = "jid"
, action = "deny"
, value = jid
, message = false
, ["presence-out"] = false
, ["presence-in"] = false
, iq = false
, order = order
});
datamanager.store(username, host, "privacy", privacy_lists);
return true;
end
-- Remove JID from default privacy list
function remove_blocked_jid(username, host, jid)
local privacy_lists = datamanager.load(username, host, "privacy") or {};
local default_list_name = privacy_lists.default;
if not default_list_name then return; end
local default_list = privacy_lists.lists[default_list_name];
if not default_list then return; end
local items = default_list.items;
local item, removed = nil, false;
for i=1,#items do -- order must be unique
item = items[i];
if item.type == "jid" and item.action == "deny" and item.value == jid then
table.remove(items, i);
removed = true;
break;
end
end
if removed then
datamanager.store(username, host, "privacy", privacy_lists);
end
return removed;
end
function remove_all_blocked_jids(username, host)
local privacy_lists = datamanager.load(username, host, "privacy") or {};
local default_list_name = privacy_lists.default;
if not default_list_name then return; end
local default_list = privacy_lists.lists[default_list_name];
if not default_list then return; end
local items = default_list.items;
local item;
for i=#items,1,-1 do -- order must be unique
item = items[i];
if item.type == "jid" and item.action == "deny" then
table.remove(items, i);
end
end
datamanager.store(username, host, "privacy", privacy_lists);
return true;
end
function get_blocked_jids(username, host)
-- Return array of blocked JIDs in default privacy list
local privacy_lists = datamanager.load(username, host, "privacy") or {};
local default_list_name = privacy_lists.default;
if not default_list_name then return {}; end
local default_list = privacy_lists.lists[default_list_name];
if not default_list then return {}; end
local items = default_list.items;
local item;
local jid_list = {};
for i=1,#items do -- order must be unique
item = items[i];
if item.type == "jid" and item.action == "deny" then
jid_list[#jid_list+1] = item.value;
end
end
return jid_list;
end
local function send_push_iqs(username, host, command_type, jids)
local bare_jid = username.."@"..host;
local stanza_content = st.stanza(command_type, { xmlns = xmlns_blocking });
for _, jid in ipairs(jids) do
stanza_content:tag("item", { jid = jid }):up();
end
for resource, session in pairs(prosody.bare_sessions[bare_jid].sessions) do
local iq_push_stanza = st.iq({ type = "set", to = bare_jid.."/"..resource });
iq_push_stanza:add_child(stanza_content);
session.send(iq_push_stanza);
end
end
function handle_blocking_command(event)
local session, stanza = event.origin, event.stanza;
local username, host = jid_split(stanza.attr.from);
if stanza.attr.type == "set" then
if stanza.tags[1].name == "block" then
local block = stanza.tags[1];
local block_jid_list = {};
for item in block:childtags() do
block_jid_list[#block_jid_list+1] = item.attr.jid;
end
if #block_jid_list == 0 then
session.send(st.error_reply(stanza, "modify", "bad-request"));
else
for _, jid in ipairs(block_jid_list) do
add_blocked_jid(username, host, jid);
end
session.send(st.reply(stanza));
send_push_iqs(username, host, "block", block_jid_list);
end
return true;
elseif stanza.tags[1].name == "unblock" then
local unblock = stanza.tags[1];
local unblock_jid_list = {};
for item in unblock:childtags() do
unblock_jid_list[#unblock_jid_list+1] = item.attr.jid;
end
if #unblock_jid_list == 0 then
remove_all_blocked_jids(username, host);
else
for _, jid_to_unblock in ipairs(unblock_jid_list) do
remove_blocked_jid(username, host, jid_to_unblock);
end
end
session.send(st.reply(stanza));
send_push_iqs(username, host, "unblock", unblock_jid_list);
return true;
end
elseif stanza.attr.type == "get" and stanza.tags[1].name == "blocklist" then
local reply = st.reply(stanza):tag("blocklist", { xmlns = xmlns_blocking });
local blocked_jids = get_blocked_jids(username, host);
for _, jid in ipairs(blocked_jids) do
reply:tag("item", { jid = jid }):up();
end
session.send(reply);
return true;
end
end
module:hook("iq/self/urn:xmpp:blocking:blocklist", handle_blocking_command);
module:hook("iq/self/urn:xmpp:blocking:block", handle_blocking_command);
module:hook("iq/self/urn:xmpp:blocking:unblock", handle_blocking_command);
|
mod_blocking: Fix handling of unblocking command. Send out un-/block pushes to all resources.
|
mod_blocking: Fix handling of unblocking command. Send out un-/block pushes to all resources.
|
Lua
|
mit
|
obelisk21/prosody-modules,apung/prosody-modules,prosody-modules/import,BurmistrovJ/prosody-modules,mmusial/prosody-modules,prosody-modules/import,Craige/prosody-modules,vince06fr/prosody-modules,stephen322/prosody-modules,stephen322/prosody-modules,jkprg/prosody-modules,asdofindia/prosody-modules,LanceJenkinZA/prosody-modules,NSAKEY/prosody-modules,mardraze/prosody-modules,vfedoroff/prosody-modules,brahmi2/prosody-modules,1st8/prosody-modules,1st8/prosody-modules,NSAKEY/prosody-modules,drdownload/prosody-modules,drdownload/prosody-modules,syntafin/prosody-modules,BurmistrovJ/prosody-modules,NSAKEY/prosody-modules,olax/prosody-modules,1st8/prosody-modules,syntafin/prosody-modules,cryptotoad/prosody-modules,either1/prosody-modules,Craige/prosody-modules,obelisk21/prosody-modules,mmusial/prosody-modules,obelisk21/prosody-modules,olax/prosody-modules,amenophis1er/prosody-modules,syntafin/prosody-modules,olax/prosody-modules,vfedoroff/prosody-modules,cryptotoad/prosody-modules,vince06fr/prosody-modules,mardraze/prosody-modules,Craige/prosody-modules,jkprg/prosody-modules,either1/prosody-modules,drdownload/prosody-modules,prosody-modules/import,vince06fr/prosody-modules,asdofindia/prosody-modules,dhotson/prosody-modules,BurmistrovJ/prosody-modules,dhotson/prosody-modules,softer/prosody-modules,mmusial/prosody-modules,either1/prosody-modules,guilhem/prosody-modules,joewalker/prosody-modules,BurmistrovJ/prosody-modules,brahmi2/prosody-modules,brahmi2/prosody-modules,vfedoroff/prosody-modules,either1/prosody-modules,Craige/prosody-modules,joewalker/prosody-modules,softer/prosody-modules,dhotson/prosody-modules,crunchuser/prosody-modules,crunchuser/prosody-modules,amenophis1er/prosody-modules,brahmi2/prosody-modules,Craige/prosody-modules,asdofindia/prosody-modules,asdofindia/prosody-modules,obelisk21/prosody-modules,heysion/prosody-modules,LanceJenkinZA/prosody-modules,syntafin/prosody-modules,1st8/prosody-modules,apung/prosody-modules,stephen322/prosody-modules,prosody-modules/import,apung/prosody-modules,iamliqiang/prosody-modules,LanceJenkinZA/prosody-modules,LanceJenkinZA/prosody-modules,crunchuser/prosody-modules,mardraze/prosody-modules,vince06fr/prosody-modules,dhotson/prosody-modules,vfedoroff/prosody-modules,prosody-modules/import,guilhem/prosody-modules,jkprg/prosody-modules,either1/prosody-modules,olax/prosody-modules,BurmistrovJ/prosody-modules,apung/prosody-modules,heysion/prosody-modules,softer/prosody-modules,amenophis1er/prosody-modules,guilhem/prosody-modules,LanceJenkinZA/prosody-modules,syntafin/prosody-modules,cryptotoad/prosody-modules,joewalker/prosody-modules,asdofindia/prosody-modules,guilhem/prosody-modules,mmusial/prosody-modules,NSAKEY/prosody-modules,joewalker/prosody-modules,mmusial/prosody-modules,guilhem/prosody-modules,drdownload/prosody-modules,stephen322/prosody-modules,softer/prosody-modules,1st8/prosody-modules,mardraze/prosody-modules,iamliqiang/prosody-modules,jkprg/prosody-modules,vince06fr/prosody-modules,heysion/prosody-modules,amenophis1er/prosody-modules,heysion/prosody-modules,crunchuser/prosody-modules,obelisk21/prosody-modules,joewalker/prosody-modules,iamliqiang/prosody-modules,amenophis1er/prosody-modules,jkprg/prosody-modules,stephen322/prosody-modules,NSAKEY/prosody-modules,dhotson/prosody-modules,mardraze/prosody-modules,cryptotoad/prosody-modules,drdownload/prosody-modules,vfedoroff/prosody-modules,iamliqiang/prosody-modules,cryptotoad/prosody-modules,crunchuser/prosody-modules,iamliqiang/prosody-modules,brahmi2/prosody-modules,olax/prosody-modules,heysion/prosody-modules,softer/prosody-modules,apung/prosody-modules
|
fdaf61c1989acdaac7b91c983e04c4198fa8273b
|
packages/lime-system/files/usr/lib/lua/lime/proto/ieee80211s.lua
|
packages/lime-system/files/usr/lib/lua/lime/proto/ieee80211s.lua
|
#!/usr/bin/lua
local ieee80211s_mode = require("lime.mode.ieee80211s")
local ieee80211s = {}
ieee80211s.configured = false
function ieee80211s.configure(args)
ieee80211s.configured = true
end
function ieee80211s.setup_interface(ifname, args)
if ifname:match("^wlan%d+_"..ieee80211s_mode.wifi_mode) then
local libuci = require "uci"
local uci = libuci:cursor()
local networkInterfaceName = network.limeIfNamePrefix..ifname
uci:set("network", networkInterfaceName, "interface")
uci:set("network", networkInterfaceName, "proto", "none")
uci:set("network", networkInterfaceName, "mtu", "1536")
uci:set("network", networkInterfaceName, "auto", "1")
uci:save("network")
end
end
return ieee80211s
|
#!/usr/bin/lua
local ieee80211s_mode = require("lime.mode.ieee80211s")
local ieee80211s = {}
ieee80211s.configured = false
function ieee80211s.configure(args)
ieee80211s.configured = true
end
function ieee80211s.setup_interface(ifname, args)
if ifname:match("^wlan%d+."..ieee80211s_mode.wifi_mode) then
local libuci = require "uci"
local uci = libuci:cursor()
--! sanitize passed ifname for constructing uci section name
--! because only alphanumeric and underscores are allowed
local networkInterfaceName = network.limeIfNamePrefix..ifname:gsub("[^%w_]", "_")
uci:set("network", networkInterfaceName, "interface")
uci:set("network", networkInterfaceName, "proto", "none")
uci:set("network", networkInterfaceName, "mtu", "1536")
uci:set("network", networkInterfaceName, "auto", "1")
uci:save("network")
end
end
return ieee80211s
|
lime-system: fix ieee80211s proto, correctly construct ifnames
|
lime-system: fix ieee80211s proto, correctly construct ifnames
This is essentially the same as 42749618f37d7f17cfd8879dd78e96525be73e02
"lime-system: construct ifnames using '_' as protoVlanSeparator and '-' as wifiModeSeparator"
in that commit, i forgot to update ieee80211s.lua in addition to adhoc.lua
|
Lua
|
agpl-3.0
|
p4u/lime-packages,libremesh/lime-packages,p4u/lime-packages,p4u/lime-packages,libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages,p4u/lime-packages,libremesh/lime-packages,libremesh/lime-packages,p4u/lime-packages
|
8886ff37c9d612f318a95a98ea61cbce4898de0d
|
extensions/caffeinate/init.lua
|
extensions/caffeinate/init.lua
|
--- === hs.caffeinate ===
---
--- Control system power states (sleeping, preventing sleep, screen locking, etc)
---
--- **NOTE**: Any sleep preventions will be removed when hs.reload() is called. A future version of the module will save/restore state across reloads.
local caffeinate = require "hs.caffeinate.internal"
caffeinate.watcher = require "hs.caffeinate.watcher"
local applescript = require "hs.applescript"
--- hs.caffeinate.set(sleepType, aValue, acAndBattery)
--- Function
--- Configures the sleep prevention settings
---
--- Parameters:
--- * sleepType - A string containing the type of sleep to be configured. The value should be one of:
--- * displayIdle - Controls whether the screen will be allowed to sleep (and also the system) if the user is idle.
--- * systemIdle - Controls whether the system will be allowed to sleep if the user is idle (display may still sleep).
--- * system - Controls whether the system will be allowed to sleep for any reason.
--- * aValue - A boolean, true if the specified type of sleep should be prevented, false if it should be allowed
--- * acAndBattery - A boolean, true if the sleep prevention should apply to both AC power and battery power, false if it should only apply to AC power
---
--- Returns:
--- * None
---
--- Notes:
--- * These calls are not guaranteed to prevent the system sleep behaviours described above. The OS may override them if it feels it must (e.g. if your CPU temperature becomes dangerously high).
--- * The acAndBattery argument only applies to the `system` sleep type.
--- * You can toggle the acAndBattery state by calling `hs.caffeinate.set()` again and altering the acAndBattery value.
function caffeinate.set(aType, aValue, acAndBattery)
if (aType == "displayIdle") then
if (aValue == true) then
caffeinate.preventIdleDisplaySleep()
else
caffeinate.allowIdleDisplaySleep()
end
elseif (aType == "systemIdle") then
if (aValue == true) then
caffeinate.preventIdleSystemSleep()
else
caffeinate.allowIdleSystemSleep()
end
elseif (aType == "system") then
if (aValue == true) then
caffeinate.preventSystemSleep(acAndBattery)
else
caffeinate.allowSystemSleep()
end
else
print("Unknown type: " .. aType)
end
end
--- hs.caffeinate.get(sleepType) -> bool or nil
--- Function
--- Queries whether a particular sleep type is being prevented
---
--- Parameters:
--- * sleepType - A string containing the type of sleep to inspect (see [hs.caffeinate.set()](#set) for information about the possible values)
---
--- Returns:
--- * True if the specified type of sleep is being prevented, false if not. nil if sleepType was an invalid value
function caffeinate.get(aType)
if (aType == nil) then
print("No sleepType specified")
return nil
end
if (aType == "displayIdle") then
return caffeinate.isIdleDisplaySleepPrevented()
elseif (aType == "systemIdle") then
return caffeinate.isIdleSystemSleepPrevented()
elseif (aType == "system") then
return caffeinate.isSystemSleepPrevented()
else
print("Unknown type: " .. aType)
end
return nil
end
--- hs.caffeinate.toggle(sleepType) -> bool or nil
--- Function
--- Toggles the current state of the specified type of sleep
---
--- Parameters:
--- * sleepType - A string containing the type of sleep to toggle (see [hs.caffeinate.set()](#set) for information about the possible values)
---
--- Returns:
--- * True if the specified type of sleep is being prevented, false if not. nil if sleepType was an invalid value
---
--- Notes:
--- * If systemIdle is toggled to on, it will apply to AC only
function caffeinate.toggle(aType)
local current = caffeinate.get(aType)
if (current == nil) then
return nil
end
caffeinate.set(aType, not current)
return caffeinate.get(aType)
end
function caffeinate.preventSystemSleep(acAndBattery)
acAndBattery = acAndBattery or false
caffeinate._preventSystemSleep(acAndBattery)
end
--- hs.caffeinate.lockScreen()
--- Function
--- Request the system lock the displays
---
--- Parameters:
--- * None
---
--- Returns:
--- * None
function caffeinate.lockScreen()
os.execute("/System/Library/CoreServices/Menu\\ Extras/User.menu/Contents/Resources/CGSession -suspend")
end
--- hs.caffeinate.startScreensaver()
--- Function
--- Request the system start the screensaver (which may lock the screen if the OS is configured to do so)
---
--- Parameters:
--- * None
---
--- Returns:
--- * None
function caffeinate.startScreensaver()
os.execute("open /System/Library/Frameworks/ScreenSaver.framework/Versions/A/Resources/ScreenSaverEngine.app")
end
--- hs.caffeinate.logOut()
--- Function
--- Request the system log out the current user
---
--- Parameters:
--- * None
---
--- Returns:
--- * None
function caffeinate.logOut()
applescript('tell application "System Events" to log out')
end
--- hs.caffeinate.restartSystem()
--- Function
--- Request the system reboot
---
--- Parameters:
--- * None
---
--- Returns:
--- * None
function caffeinate.restartSystem()
applescript('tell application "System Events" to restart')
end
--- hs.caffeinate.shutdownSystem()
--- Function
--- Request the system log out and power down
---
--- Parameters:
--- * None
---
--- Returns:
--- * None
function caffeinate.shutdownSystem()
applescript('tell application "System Events" to shut down')
end
-- allow reverse lookups of numeric values passed into callback function
local watcherMT = getmetatable(caffeinate.watcher)
watcherMT.__index = function(self, key)
if math.type(key) == "integer" then
local answer = nil
for k, v in pairs(self) do
if math.type(v) == "integer" and key == v then
answer = k
break
end
end
return answer
else
return nil
end
end
caffeinate.watcher = setmetatable(caffeinate.watcher, watcherMT)
return caffeinate
|
--- === hs.caffeinate ===
---
--- Control system power states (sleeping, preventing sleep, screen locking, etc)
---
--- **NOTE**: Any sleep preventions will be removed when hs.reload() is called. A future version of the module will save/restore state across reloads.
local caffeinate = require "hs.caffeinate.internal"
caffeinate.watcher = require "hs.caffeinate.watcher"
local applescript = require "hs.applescript"
--- hs.caffeinate.set(sleepType, aValue, acAndBattery)
--- Function
--- Configures the sleep prevention settings
---
--- Parameters:
--- * sleepType - A string containing the type of sleep to be configured. The value should be one of:
--- * displayIdle - Controls whether the screen will be allowed to sleep (and also the system) if the user is idle.
--- * systemIdle - Controls whether the system will be allowed to sleep if the user is idle (display may still sleep).
--- * system - Controls whether the system will be allowed to sleep for any reason.
--- * aValue - A boolean, true if the specified type of sleep should be prevented, false if it should be allowed
--- * acAndBattery - A boolean, true if the sleep prevention should apply to both AC power and battery power, false if it should only apply to AC power
---
--- Returns:
--- * None
---
--- Notes:
--- * These calls are not guaranteed to prevent the system sleep behaviours described above. The OS may override them if it feels it must (e.g. if your CPU temperature becomes dangerously high).
--- * The acAndBattery argument only applies to the `system` sleep type.
--- * You can toggle the acAndBattery state by calling `hs.caffeinate.set()` again and altering the acAndBattery value.
function caffeinate.set(aType, aValue, acAndBattery)
if (aType == "displayIdle") then
if (aValue == true) then
caffeinate.preventIdleDisplaySleep()
else
caffeinate.allowIdleDisplaySleep()
end
elseif (aType == "systemIdle") then
if (aValue == true) then
caffeinate.preventIdleSystemSleep()
else
caffeinate.allowIdleSystemSleep()
end
elseif (aType == "system") then
if (aValue == true) then
caffeinate.preventSystemSleep(acAndBattery)
else
caffeinate.allowSystemSleep()
end
else
print("Unknown type: " .. aType)
end
end
--- hs.caffeinate.get(sleepType) -> bool or nil
--- Function
--- Queries whether a particular sleep type is being prevented
---
--- Parameters:
--- * sleepType - A string containing the type of sleep to inspect (see [hs.caffeinate.set()](#set) for information about the possible values)
---
--- Returns:
--- * True if the specified type of sleep is being prevented, false if not. nil if sleepType was an invalid value
function caffeinate.get(aType)
if (aType == nil) then
print("No sleepType specified")
return nil
end
if (aType == "displayIdle") then
return caffeinate.isIdleDisplaySleepPrevented()
elseif (aType == "systemIdle") then
return caffeinate.isIdleSystemSleepPrevented()
elseif (aType == "system") then
return caffeinate.isSystemSleepPrevented()
else
print("Unknown type: " .. aType)
end
return nil
end
--- hs.caffeinate.toggle(sleepType) -> bool or nil
--- Function
--- Toggles the current state of the specified type of sleep
---
--- Parameters:
--- * sleepType - A string containing the type of sleep to toggle (see [hs.caffeinate.set()](#set) for information about the possible values)
---
--- Returns:
--- * True if the specified type of sleep is being prevented, false if not. nil if sleepType was an invalid value
---
--- Notes:
--- * If systemIdle is toggled to on, it will apply to AC only
function caffeinate.toggle(aType)
local current = caffeinate.get(aType)
if (current == nil) then
return nil
end
caffeinate.set(aType, not current)
return caffeinate.get(aType)
end
function caffeinate.preventSystemSleep(acAndBattery)
acAndBattery = acAndBattery or false
caffeinate._preventSystemSleep(acAndBattery)
end
--- hs.caffeinate.lockScreen()
--- Function
--- Request the system lock the displays
---
--- Parameters:
--- * None
---
--- Returns:
--- * None
function caffeinate.lockScreen()
os.execute("/System/Library/CoreServices/Menu\\ Extras/User.menu/Contents/Resources/CGSession -suspend")
end
--- hs.caffeinate.startScreensaver()
--- Function
--- Request the system start the screensaver (which may lock the screen if the OS is configured to do so)
---
--- Parameters:
--- * None
---
--- Returns:
--- * None
function caffeinate.startScreensaver()
os.execute("open -a ScreenSaverEngine")
end
--- hs.caffeinate.logOut()
--- Function
--- Request the system log out the current user
---
--- Parameters:
--- * None
---
--- Returns:
--- * None
function caffeinate.logOut()
applescript('tell application "System Events" to log out')
end
--- hs.caffeinate.restartSystem()
--- Function
--- Request the system reboot
---
--- Parameters:
--- * None
---
--- Returns:
--- * None
function caffeinate.restartSystem()
applescript('tell application "System Events" to restart')
end
--- hs.caffeinate.shutdownSystem()
--- Function
--- Request the system log out and power down
---
--- Parameters:
--- * None
---
--- Returns:
--- * None
function caffeinate.shutdownSystem()
applescript('tell application "System Events" to shut down')
end
-- allow reverse lookups of numeric values passed into callback function
local watcherMT = getmetatable(caffeinate.watcher)
watcherMT.__index = function(self, key)
if math.type(key) == "integer" then
local answer = nil
for k, v in pairs(self) do
if math.type(v) == "integer" and key == v then
answer = k
break
end
end
return answer
else
return nil
end
end
caffeinate.watcher = setmetatable(caffeinate.watcher, watcherMT)
return caffeinate
|
Fix caffeinate.startScreensaver() to work under High Sierra
|
Fix caffeinate.startScreensaver() to work under High Sierra
The path in High Sierra has changed, so this no longer works. Calling
the ScreenSaverEngine application seems to be a more stable and correct
way to trigger the screensaver that works across versions.
|
Lua
|
mit
|
CommandPost/CommandPost-App,CommandPost/CommandPost-App,latenitefilms/hammerspoon,asmagill/hammerspoon,Hammerspoon/hammerspoon,latenitefilms/hammerspoon,Hammerspoon/hammerspoon,asmagill/hammerspoon,Hammerspoon/hammerspoon,Hammerspoon/hammerspoon,Habbie/hammerspoon,latenitefilms/hammerspoon,Hammerspoon/hammerspoon,cmsj/hammerspoon,asmagill/hammerspoon,Habbie/hammerspoon,latenitefilms/hammerspoon,cmsj/hammerspoon,CommandPost/CommandPost-App,Hammerspoon/hammerspoon,Habbie/hammerspoon,asmagill/hammerspoon,cmsj/hammerspoon,cmsj/hammerspoon,asmagill/hammerspoon,Habbie/hammerspoon,CommandPost/CommandPost-App,CommandPost/CommandPost-App,cmsj/hammerspoon,latenitefilms/hammerspoon,Habbie/hammerspoon,latenitefilms/hammerspoon,cmsj/hammerspoon,CommandPost/CommandPost-App,Habbie/hammerspoon,asmagill/hammerspoon
|
5fd0e619d1d41623caba259a4f11e2750493a363
|
lua/spam.lua
|
lua/spam.lua
|
spam_cooldown = {}
function spam_callback(event, origin, params)
if spam_cooldown[origin] ~= nil and spam_cooldown[origin] > os.time() - 120 then
irc_msg(params[1], "Don't get too excited, " .. origin)
return
end
if event == "!spam" then
spam(params[2], origin, params[1])
elseif event == "!rainbow" then
rainbow(params[2], origin, params[1])
elseif event == "!bigrainbow" then
bigrainbow(params[2], origin, params[1])
elseif event == "!biggerrainbow" then
biggerrainbow(params[2], origin, params[1])
elseif event == "!warning" then
warning(params[2], origin, params[1])
end
spam_cooldown[origin] = os.time()
end
register_command("spam", "spam_callback")
register_command("rainbow", "spam_callback")
register_command("bigrainbow", "spam_callback")
register_command("biggerrainbow", "spam_callback")
register_command("warning", "spam_callback")
function spam(word,user,target)
local buffer,buffer2 = "",""
while buffer2:len() < 400 do
for i,v in pairs(str_split(word," ")) do
local c1,c2 = math.random(0,15),math.random(0,15)
while c1==c2 do
c2 = math.random(0,15)
end
buffer2 = buffer2 .. string.char(3) .. c1 .. "," .. c2 .. v .. string.char(15) .. " "
end
end
irc_msg(target,buffer2:gsub("^%s*(.-)%s*$","%1"))
end
function rainbow(word,user,target)
local f = io.popen("toilet -f term -F gay --irc -w " .. get_config("bot:spamwidth") .. " > /tmp/denice_rainbow","w")
f:write(word)
f:close()
local f = io.open("/tmp/denice_rainbow", "r")
for line in f:lines() do
irc_raw("PRIVMSG "..target.." :"..line)
end
end
function bigrainbow(word,user,target)
if word:len() > 256 then
word=user.." is a big gay fag!"
end
local f = io.popen("toilet -f future -F gay --irc -w " .. get_config("bot:spamwidth") .. " > /tmp/denice_rainbow","w")
f:write(word)
f:close()
local f = io.open("/tmp/denice_rainbow", "r")
for line in f:lines() do
irc_raw("PRIVMSG "..target.." :"..line)
end
f:close()
end
function biggerrainbow(word,user,target)
if word:len() > 128 then
word=user.." is a big gay fag!"
end
local f = io.popen("toilet -f mono9 -F gay --irc -w " .. get_config("bot:spamwidth") .. " > /tmp/denice_rainbow","w")
f:write(word)
f:close()
local f = io.open("/tmp/denice_rainbow", "r")
for line in f:lines() do
irc_raw("PRIVMSG "..target.." :"..line)
--irc_msg(target,line:gsub("\n",""))
end
f:close()
end
function warning(word,user,target)
irc_msg(target, irc_color("[B][I][U]/!\\[/U] " .. word .. " [U]/!\\[/U][/I][/B]"))
end
|
spam_cooldown = {}
function spam_callback(event, origin, params)
if spam_cooldown[origin] ~= nil and spam_cooldown[origin] > os.time() - 120 then
irc_msg(params[1], "Don't get too excited, " .. origin)
return
end
if event == "!spam" then
spam(params[2], origin, params[1])
elseif event == "!rainbow" then
rainbow(params[2], origin, params[1])
elseif event == "!bigrainbow" then
bigrainbow(params[2], origin, params[1])
elseif event == "!biggerrainbow" then
biggerrainbow(params[2], origin, params[1])
elseif event == "!warning" then
warning(params[2], origin, params[1])
end
spam_cooldown[origin] = os.time()
end
register_command("spam", "spam_callback")
register_command("rainbow", "spam_callback")
register_command("bigrainbow", "spam_callback")
register_command("biggerrainbow", "spam_callback")
register_command("warning", "spam_callback")
function spam(word,user,target)
local buffer,buffer2 = "",""
while buffer2:len() < 400 do
for i,v in pairs(str_split(word," ")) do
local c1,c2 = math.random(0,15),math.random(0,15)
while c1==c2 do
c2 = math.random(0,15)
end
if c1 < 10 then
c1 = "0" .. c1
end
if c2 < 10 then
c2 = "0" .. c2
end
buffer2 = buffer2 .. string.char(3) .. c1 .. "," .. c2 .. v .. string.char(15) .. " "
end
end
irc_msg(target,buffer2:gsub("^%s*(.-)%s*$","%1"))
end
function rainbow(word,user,target)
local f = io.popen("toilet -f term -F gay --irc -w " .. get_config("bot:spamwidth") .. " > /tmp/denice_rainbow","w")
f:write(word)
f:close()
local f = io.open("/tmp/denice_rainbow", "r")
for line in f:lines() do
irc_raw("PRIVMSG "..target.." :"..line)
end
end
function bigrainbow(word,user,target)
if word:len() > 256 then
word=user.." is a big gay fag!"
end
local f = io.popen("toilet -f future -F gay --irc -w " .. get_config("bot:spamwidth") .. " > /tmp/denice_rainbow","w")
f:write(word)
f:close()
local f = io.open("/tmp/denice_rainbow", "r")
for line in f:lines() do
irc_raw("PRIVMSG "..target.." :"..line)
end
f:close()
end
function biggerrainbow(word,user,target)
if word:len() > 128 then
word=user.." is a big gay fag!"
end
local f = io.popen("toilet -f mono9 -F gay --irc -w " .. get_config("bot:spamwidth") .. " > /tmp/denice_rainbow","w")
f:write(word)
f:close()
local f = io.open("/tmp/denice_rainbow", "r")
for line in f:lines() do
irc_raw("PRIVMSG "..target.." :"..line)
--irc_msg(target,line:gsub("\n",""))
end
f:close()
end
function warning(word,user,target)
irc_msg(target, irc_color("[B][I][U]/!\\[/U] " .. word .. " [U]/!\\[/U][/I][/B]"))
end
|
fix !spam sometimes dropping first character if it is an integer (it was being considered as part of the color code)
|
fix !spam sometimes dropping first character if it is an integer (it was being considered as part of the color code)
|
Lua
|
mit
|
wetfish/denice
|
02fa4572494b8b317db6dc06183e1e8ea4a5235c
|
.hammerspoon/init.lua
|
.hammerspoon/init.lua
|
local mash = {"cmd", "alt", "ctrl"}
local smash = {"cmd", "alt", "ctrl", "shift"}
function current_app()
return hs.application.frontmostApplication()
end
-- Application shortcuts
-- local safari_esc = hs.hotkey.new({}, "escape", function() end, function()
-- if current_app():name() == "Safari" then
-- hs.eventtap.keyStroke({"alt"}, "escape")
-- end
-- end)
local safari_close_tab = hs.hotkey.new({"cmd"}, "w", function() end, function()
if current_app():name() == "Safari" then
current_app():selectMenuItem({"File", "Close Tab"})
end
end)
local wf = hs.window.filter
wf.new("Safari"):subscribe(wf.windowFocused, function()
-- safari_esc:enable()
safari_close_tab:enable()
end):subscribe(wf.windowUnfocused, function()
-- safari_esc:disable()
safari_close_tab:disable()
end)
-- hs.hotkey.bind({"cmd", "shift"}, "[", function()
-- current_app():selectMenuItem({"Window", "Select Previous Tab"})
-- end)
-- hs.hotkey.bind({"cmd", "shift"}, "]", function()
-- current_app():selectMenuItem({"Window", "Select Next Tab"})
-- end)
-- Window management
local throw_left = function()
local win = hs.window.focusedWindow()
local f = win:frame()
local screen = win:screen()
local max = screen:frame()
f.x = max.x
f.y = max.y
f.w = max.w / 2
f.h = max.h
win:setFrame(f)
end
local throw_right = function()
local win = hs.window.focusedWindow()
local f = win:frame()
local screen = win:screen()
local max = screen:frame()
f.x = max.x + (max.w / 2)
f.y = max.y
f.w = max.w / 2
f.h = max.h
win:setFrame(f)
end
hs.hotkey.bind(mash, "h", throw_left)
hs.hotkey.bind(mash, "left", throw_left)
hs.hotkey.bind(mash, "l", throw_right)
hs.hotkey.bind(mash, "right", throw_right)
hs.pathwatcher.new(os.getenv("HOME") .. "/.hammerspoon/", function()
hs.reload()
end):start()
hs.alert.show("Config loaded")
|
local mash = {"cmd", "alt", "ctrl"}
local smash = {"cmd", "alt", "ctrl", "shift"}
function current_app()
return hs.application.frontmostApplication()
end
-- Application shortcuts
-- local safari_esc = hs.hotkey.new({}, "escape", function() end, function()
-- if current_app():name() == "Safari" then
-- hs.eventtap.keyStroke({"alt"}, "escape")
-- end
-- end)
-- local safari_close_tab = hs.hotkey.new({"cmd"}, "w", function() end, function()
-- if current_app():name() == "Safari" then
-- current_app():selectMenuItem({"File", "Close Tab"})
-- end
-- end)
-- local wf = hs.window.filter
-- wf.new("Safari"):subscribe(wf.windowFocused, function()
-- -- safari_esc:enable()
-- safari_close_tab:enable()
-- end):subscribe(wf.windowUnfocused, function()
-- -- safari_esc:disable()
-- safari_close_tab:disable()
-- end)
-- hs.hotkey.bind({"cmd", "shift"}, "[", function()
-- current_app():selectMenuItem({"Window", "Select Previous Tab"})
-- end)
-- hs.hotkey.bind({"cmd", "shift"}, "]", function()
-- current_app():selectMenuItem({"Window", "Select Next Tab"})
-- end)
-- Window management
local throw_left = function()
local win = hs.window.focusedWindow()
local f = win:frame()
local screen = win:screen()
local max = screen:frame()
f.x = max.x
f.y = max.y
f.w = max.w / 2
f.h = max.h
win:setFrame(f)
end
local throw_right = function()
local win = hs.window.focusedWindow()
local f = win:frame()
local screen = win:screen()
local max = screen:frame()
f.x = max.x + (max.w / 2)
f.y = max.y
f.w = max.w / 2
f.h = max.h
win:setFrame(f)
end
hs.hotkey.bind(mash, "h", throw_left)
hs.hotkey.bind(mash, "left", throw_left)
hs.hotkey.bind(mash, "l", throw_right)
hs.hotkey.bind(mash, "right", throw_right)
hs.pathwatcher.new(os.getenv("HOME") .. "/.hammerspoon/", function()
hs.reload()
end):start()
hs.alert.show("Config loaded")
|
[hammerspoon] disable attempt at fixing esc in fullscreen safari
|
[hammerspoon] disable attempt at fixing esc in fullscreen safari
|
Lua
|
mit
|
kejadlen/dotfiles,kejadlen/dotfiles
|
bd79b5e8c4ff4e0b29f2b0be73d1bacdc2dac416
|
.hammerspoon/init.lua
|
.hammerspoon/init.lua
|
local logger = hs.logger.new('init', 'info')
local eventTypes = hs.eventtap.event.types
local eventProps = hs.eventtap.event.properties
-- Fix deadkey 'n' on my internal keyboard
hs.eventtap.new({eventTypes.keyDown}, function(event)
local keyCode = event:getProperty(eventProps.keyboardEventKeycode)
local keyboardType = event:getProperty(eventProps.keyboardEventKeyboardType)
local modifiers = hs.eventtap.checkKeyboardModifiers()
logger.d(
"keyDown [keyCode: " .. keyCode ..
", keyboardType: " .. keyboardType ..
-- ", modifiers: " .. modifiers["alt"] ..
"]")
-- 43 is the internal keyboard
if keyboardType == 43 and keyCode == hs.keycodes.map["\\"] then
local e = event:copy()
if modifiers["alt"] then
-- Unless the 'option' key is down, clear the flag so it is still
-- '\\', but passing through other modifiers such as
-- 'shift'. Doesn't work well with repeat but it's fine for me
modifiers["alt"] = nil
e:setFlags(modifiers)
return true, {e}
end
e:setKeyCode(hs.keycodes.map["n"])
return true, {e}
end
end):start()
function focus_prev()
local windows = hs.window.filter.default:getWindows(
hs.window.filter.sortByLastFocused
)
windows[2]:focus()
end
hs.hotkey.bind({"option"}, "j", function()
hs.hints.windowHints()
-- expose:show()
end)
hs.hotkey.bind({"option"}, "k", focus_prev, nil, focus_prev)
hs.hotkey.bind({"option"}, "r", function()
hs.alert('Reloading')
hs.timer.delayed.new(0.4, hs.fnutils.partial(hs.reload, self)):start()
end)
|
local logger = hs.logger.new('init', 'info')
function focus_prev()
local windows = hs.window.filter.default:getWindows(
hs.window.filter.sortByLastFocused
)
windows[2]:focus()
end
hs.hotkey.bind({"option"}, "j", function()
hs.hints.windowHints()
-- expose:show()
end)
hs.hotkey.bind({"option"}, "k", focus_prev, nil, focus_prev)
hs.hotkey.bind({"option"}, "r", function()
hs.alert('Reloading')
hs.timer.delayed.new(0.4, hs.fnutils.partial(hs.reload, self)):start()
end)
|
I get my keyboard fixed, yay! :)
|
I get my keyboard fixed, yay! :)
|
Lua
|
bsd-3-clause
|
tungd/dotfiles-lean,tungd/dotfiles-lean,tungd/dotfiles-lean
|
0a572ae94016d206066036fb34380a1c16634a92
|
aspects/nvim/files/.config/nvim/lua/wincent/lsp.lua
|
aspects/nvim/files/.config/nvim/lua/wincent/lsp.lua
|
local nnoremap = wincent.vim.nnoremap
local lsp = {}
local on_attach = function ()
nnoremap('<Leader>ld', "<cmd>lua require'lspsaga.diagnostic'.show_line_diagnostics()<CR>", {silent = true})
nnoremap('<c-]>', '<cmd>lua vim.lsp.buf.definition()<CR>', {silent = true})
nnoremap('K', "<cmd>lua require'lspsaga.hover'.render_hover_doc()<CR>", {silent = true})
nnoremap('gd', '<cmd>lua vim.lsp.buf.declaration()<CR>', {silent = true})
vim.wo.signcolumn = 'yes'
end
lsp.init = function ()
require'lspconfig'.clangd.setup{
cmd = {'clangd', '--background-index'},
on_attach = on_attach,
}
-- If you're feeling brave after reading:
--
-- https://github.com/neovim/nvim-lspconfig/issues/319
--
-- Install:
--
-- :LspInstall sumneko_lua
--
-- After marvelling at the horror that is the installation script:
--
-- https://github.com/neovim/nvim-lspconfig/blob/master/lua/lspconfig/sumneko_lua.lua
--
-- To see path:
--
-- :LspInstallInfo sumneko_lua
--
-- See: https://github.com/neovim/nvim-lspconfig#sumneko_lua
--
-- Failing that; you can install by hand:
--
-- https://github.com/sumneko/lua-language-server/wiki/Build-and-Run-(Standalone)
--
local cmd = nil
if vim.fn.has('mac') == 1 then
cmd = vim.fn.expand('~/code/lua-language-server/bin/macOS/lua-language-server')
if vim.fn.executable(cmd) == 1 then
cmd = {cmd, '-E', vim.fn.expand('~/code/lua-language-server/main.lua')}
else
cmd = nil
end
elseif vim.fn.has('unix') == 1 then
cmd = '/usr/bin/lua-language-server'
if vim.fn.executable(cmd) == 1 then
cmd = {cmd}
else
cmd = nil
end
else
cmd = 'lua-language-server'
if vim.fn.executable(cmd) == 1 then
cmd = {cmd}
else
cmd = nil
end
end
if cmd ~= nil then
require'lspconfig'.sumneko_lua.setup{
cmd = cmd,
on_attach = on_attach,
settings = {
Lua = {
diagnostics = {
enable = true,
globals = {'vim'},
},
filetypes = {'lua'},
runtime = {
path = vim.split(package.path, ';'),
version = 'LuaJIT',
},
}
},
}
end
require'lspconfig'.ocamlls.setup{
on_attach = on_attach,
}
require'lspconfig'.tsserver.setup{
-- cmd = {
-- "typescript-language-server",
-- "--stdio",
-- "--tsserver-log-file",
-- "tslog"
-- },
on_attach = on_attach,
}
require'lspconfig'.vimls.setup{
on_attach = on_attach,
}
end
lsp.set_up_highlights = function ()
local pinnacle = require'wincent.pinnacle'
vim.cmd('highlight LspDiagnosticsDefaultError ' .. pinnacle.decorate('italic,underline', 'ModeMsg'))
vim.cmd('highlight LspDiagnosticsDefaultHint ' .. pinnacle.decorate('bold,italic,underline', 'Type'))
vim.cmd('highlight LspDiagnosticsSignHint ' .. pinnacle.highlight({
bg = pinnacle.extract_bg('ColorColumn'),
fg = pinnacle.extract_fg('Type'),
}))
vim.cmd('highlight LspDiagnosticsSignError ' .. pinnacle.highlight({
bg = pinnacle.extract_bg('ColorColumn'),
fg = pinnacle.extract_fg('ErrorMsg'),
}))
vim.cmd('highlight LspDiagnosticsSignInformation ' .. pinnacle.highlight({
bg = pinnacle.extract_bg('ColorColumn'),
fg = pinnacle.extract_fg('LspDiagnosticsDefaultHint'),
}))
vim.cmd('highlight LspDiagnosticsSignWarning ' .. pinnacle.highlight({
bg = pinnacle.extract_bg('ColorColumn'),
fg = pinnacle.extract_fg('LspDiagnosticsDefaultHint'),
}))
end
return lsp
|
local nnoremap = wincent.vim.nnoremap
local lsp = {}
local on_attach = function ()
nnoremap('<Leader>ld', "<cmd>lua require'lspsaga.diagnostic'.show_line_diagnostics()<CR>", {buffer = true, silent = true})
nnoremap('<c-]>', '<cmd>lua vim.lsp.buf.definition()<CR>', {buffer = true, silent = true})
nnoremap('K', "<cmd>lua require'lspsaga.hover'.render_hover_doc()<CR>", {buffer = true, silent = true})
nnoremap('gd', '<cmd>lua vim.lsp.buf.declaration()<CR>', {buffer = true, silent = true})
vim.wo.signcolumn = 'yes'
end
lsp.init = function ()
require'lspconfig'.clangd.setup{
cmd = {'clangd', '--background-index'},
on_attach = on_attach,
}
-- If you're feeling brave after reading:
--
-- https://github.com/neovim/nvim-lspconfig/issues/319
--
-- Install:
--
-- :LspInstall sumneko_lua
--
-- After marvelling at the horror that is the installation script:
--
-- https://github.com/neovim/nvim-lspconfig/blob/master/lua/lspconfig/sumneko_lua.lua
--
-- To see path:
--
-- :LspInstallInfo sumneko_lua
--
-- See: https://github.com/neovim/nvim-lspconfig#sumneko_lua
--
-- Failing that; you can install by hand:
--
-- https://github.com/sumneko/lua-language-server/wiki/Build-and-Run-(Standalone)
--
local cmd = nil
if vim.fn.has('mac') == 1 then
cmd = vim.fn.expand('~/code/lua-language-server/bin/macOS/lua-language-server')
if vim.fn.executable(cmd) == 1 then
cmd = {cmd, '-E', vim.fn.expand('~/code/lua-language-server/main.lua')}
else
cmd = nil
end
elseif vim.fn.has('unix') == 1 then
cmd = '/usr/bin/lua-language-server'
if vim.fn.executable(cmd) == 1 then
cmd = {cmd}
else
cmd = nil
end
else
cmd = 'lua-language-server'
if vim.fn.executable(cmd) == 1 then
cmd = {cmd}
else
cmd = nil
end
end
if cmd ~= nil then
require'lspconfig'.sumneko_lua.setup{
cmd = cmd,
on_attach = on_attach,
settings = {
Lua = {
diagnostics = {
enable = true,
globals = {'vim'},
},
filetypes = {'lua'},
runtime = {
path = vim.split(package.path, ';'),
version = 'LuaJIT',
},
}
},
}
end
require'lspconfig'.ocamlls.setup{
on_attach = on_attach,
}
require'lspconfig'.tsserver.setup{
-- cmd = {
-- "typescript-language-server",
-- "--stdio",
-- "--tsserver-log-file",
-- "tslog"
-- },
on_attach = on_attach,
}
require'lspconfig'.vimls.setup{
on_attach = on_attach,
}
end
lsp.set_up_highlights = function ()
local pinnacle = require'wincent.pinnacle'
vim.cmd('highlight LspDiagnosticsDefaultError ' .. pinnacle.decorate('italic,underline', 'ModeMsg'))
vim.cmd('highlight LspDiagnosticsDefaultHint ' .. pinnacle.decorate('bold,italic,underline', 'Type'))
vim.cmd('highlight LspDiagnosticsSignHint ' .. pinnacle.highlight({
bg = pinnacle.extract_bg('ColorColumn'),
fg = pinnacle.extract_fg('Type'),
}))
vim.cmd('highlight LspDiagnosticsSignError ' .. pinnacle.highlight({
bg = pinnacle.extract_bg('ColorColumn'),
fg = pinnacle.extract_fg('ErrorMsg'),
}))
vim.cmd('highlight LspDiagnosticsSignInformation ' .. pinnacle.highlight({
bg = pinnacle.extract_bg('ColorColumn'),
fg = pinnacle.extract_fg('LspDiagnosticsDefaultHint'),
}))
vim.cmd('highlight LspDiagnosticsSignWarning ' .. pinnacle.highlight({
bg = pinnacle.extract_bg('ColorColumn'),
fg = pinnacle.extract_fg('LspDiagnosticsDefaultHint'),
}))
end
return lsp
|
fix(nvim): make LSP mappings buffer-local
|
fix(nvim): make LSP mappings buffer-local
I only noticed this was broken a few days ago, but I feel like it
probably was broken for a while. We don't want to bind `<C-]>` to
`vim.lsp.buf.definition()` in some filetypes (eg. `help`) because that
will break tag-based navigation.
|
Lua
|
unlicense
|
wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent
|
541bd632e17fa91605afda3bd2942c4fbebd0b5a
|
onmt/train/Checkpoint.lua
|
onmt/train/Checkpoint.lua
|
-- Class for saving and loading models during training.
local Checkpoint = torch.class('Checkpoint')
local options = {
{
'-train_from', '',
[[Path to a checkpoint.]],
{
valid = onmt.utils.ExtendedCmdLine.fileNullOrExists
}
},
{
'-continue', false,
[[If set, continue the training where it left off.]]
}
}
function Checkpoint.declareOpts(cmd)
cmd:setCmdLineOptions(options, 'Checkpoint')
end
function Checkpoint:__init(opt, model, optim, dicts)
self.options = opt
self.model = model
self.optim = optim
self.dicts = dicts
self.savePath = self.options.save_model
end
function Checkpoint:save(filePath, info)
info.learningRate = self.optim:getLearningRate()
info.optimStates = self.optim:getStates()
info.rngStates = onmt.utils.Cuda.getRNGStates()
local data = {
models = {},
options = self.options,
info = info,
dicts = self.dicts
}
for k, v in pairs(self.model.models) do
if v.serialize then
data.models[k] = v:serialize()
else
data.models[k] = v
end
end
torch.save(filePath, data)
end
--[[ Save the model and data in the middle of an epoch sorting the iteration. ]]
function Checkpoint:saveIteration(iteration, epochState, batchOrder, verbose)
local info = {}
info.iteration = iteration + 1
info.epoch = epochState.epoch
info.batchOrder = batchOrder
local filePath = string.format('%s_checkpoint.t7', self.savePath)
if verbose then
_G.logger:info('Saving checkpoint to \'' .. filePath .. '\'...')
end
-- Succeed serialization before overriding existing file
self:save(filePath .. '.tmp', info)
os.rename(filePath .. '.tmp', filePath)
end
function Checkpoint:saveEpoch(validPpl, epochState, verbose)
local info = {}
info.validPpl = validPpl
info.epoch = epochState.epoch + 1
info.iteration = 1
info.trainTimeInMinute = epochState:getTime() / 60
local filePath = string.format('%s_epoch%d_%.2f.t7', self.savePath, epochState.epoch, validPpl)
if verbose then
_G.logger:info('Saving checkpoint to \'' .. filePath .. '\'...')
end
self:save(filePath, info)
end
function Checkpoint.loadFromCheckpoint(opt)
local checkpoint = {}
local paramChanges = {}
if opt.train_from:len() > 0 then
_G.logger:info('Loading checkpoint \'' .. opt.train_from .. '\'...')
checkpoint = torch.load(opt.train_from)
-- Reload and check options.
for k, v in pairs(opt) do
if k:sub(1, 1) ~= '_' then
if opt.continue and opt._train_state[k] then
-- Training states should be retrieved when continuing a training.
opt[k] = checkpoint.options[k] or opt[k]
elseif opt._structural[k] or opt._init_only[k] then
-- If an option was set by the user, check that we can actually change it.
local valueChanged = not opt._is_default[k] and v ~= checkpoint.options[k]
if valueChanged then
if opt._init_only[k] then
_G.logger:warning('Cannot change initialization option -%s. Ignoring.', k)
opt[k] = checkpoint.options[k] or opt[k]
elseif opt._structural[k] and opt._structural[k] == 0 then
_G.logger:warning('Cannot change dynamically option -%s. Ignoring.', k)
opt[k] = checkpoint.options[k] or opt[k]
elseif opt._structural[k] and opt._structural[k] == 1 then
paramChanges[k] = v
end
else
opt[k] = checkpoint.options[k] or opt[k]
end
end
end
end
if opt.continue then
-- When continuing, some options are initialized with their last known value.
opt.learning_rate = checkpoint.info.learningRate
opt.start_epoch = checkpoint.info.epoch
opt.start_iteration = checkpoint.info.iteration
_G.logger:info('Resuming training from epoch ' .. opt.start_epoch
.. ' at iteration ' .. opt.start_iteration .. '...')
else
-- Otherwise, we can drop previous training information.
checkpoint.info = nil
end
end
return checkpoint, opt, paramChanges
end
return Checkpoint
|
-- Class for saving and loading models during training.
local Checkpoint = torch.class('Checkpoint')
local options = {
{
'-train_from', '',
[[Path to a checkpoint.]],
{
valid = onmt.utils.ExtendedCmdLine.fileNullOrExists
}
},
{
'-continue', false,
[[If set, continue the training where it left off.]]
}
}
function Checkpoint.declareOpts(cmd)
cmd:setCmdLineOptions(options, 'Checkpoint')
end
function Checkpoint:__init(opt, model, optim, dicts)
self.options = opt
self.model = model
self.optim = optim
self.dicts = dicts
self.savePath = self.options.save_model
end
function Checkpoint:save(filePath, info)
info.learningRate = self.optim:getLearningRate()
info.optimStates = self.optim:getStates()
info.rngStates = onmt.utils.Cuda.getRNGStates()
local data = {
models = {},
options = self.options,
info = info,
dicts = self.dicts
}
for k, v in pairs(self.model.models) do
if v.serialize then
data.models[k] = v:serialize()
else
data.models[k] = v
end
end
torch.save(filePath, data)
end
--[[ Save the model and data in the middle of an epoch sorting the iteration. ]]
function Checkpoint:saveIteration(iteration, epochState, batchOrder, verbose)
local info = {}
info.iteration = iteration + 1
info.epoch = epochState.epoch
info.batchOrder = batchOrder
local filePath = string.format('%s_checkpoint.t7', self.savePath)
if verbose then
_G.logger:info('Saving checkpoint to \'' .. filePath .. '\'...')
end
-- Succeed serialization before overriding existing file
self:save(filePath .. '.tmp', info)
os.rename(filePath .. '.tmp', filePath)
end
function Checkpoint:saveEpoch(validPpl, epochState, verbose)
local info = {}
info.validPpl = validPpl
info.epoch = epochState.epoch + 1
info.iteration = 1
info.trainTimeInMinute = epochState:getTime() / 60
local filePath = string.format('%s_epoch%d_%.2f.t7', self.savePath, epochState.epoch, validPpl)
if verbose then
_G.logger:info('Saving checkpoint to \'' .. filePath .. '\'...')
end
self:save(filePath, info)
end
function Checkpoint.loadFromCheckpoint(opt)
local checkpoint = {}
local paramChanges = {}
if opt.train_from:len() > 0 then
_G.logger:info('Loading checkpoint \'' .. opt.train_from .. '\'...')
checkpoint = torch.load(opt.train_from)
local function restoreOption(name)
if checkpoint.options[name] ~= nil then
opt[name] = checkpoint.options[name]
end
end
-- Reload and check options.
for k, v in pairs(opt) do
if k:sub(1, 1) ~= '_' then
if opt.continue and opt._train_state[k] then
-- Training states should be retrieved when continuing a training.
restoreOption(k)
elseif opt._structural[k] or opt._init_only[k] then
-- If an option was set by the user, check that we can actually change it.
local valueChanged = not opt._is_default[k] and v ~= checkpoint.options[k]
if valueChanged then
if opt._init_only[k] then
_G.logger:warning('Cannot change initialization option -%s. Ignoring.', k)
restoreOption(k)
elseif opt._structural[k] and opt._structural[k] == 0 then
_G.logger:warning('Cannot change dynamically option -%s. Ignoring.', k)
restoreOption(k)
elseif opt._structural[k] and opt._structural[k] == 1 then
paramChanges[k] = v
end
else
restoreOption(k)
end
end
end
end
if opt.continue then
-- When continuing, some options are initialized with their last known value.
opt.learning_rate = checkpoint.info.learningRate
opt.start_epoch = checkpoint.info.epoch
opt.start_iteration = checkpoint.info.iteration
_G.logger:info('Resuming training from epoch ' .. opt.start_epoch
.. ' at iteration ' .. opt.start_iteration .. '...')
else
-- Otherwise, we can drop previous training information.
checkpoint.info = nil
end
end
return checkpoint, opt, paramChanges
end
return Checkpoint
|
Fix options restoring that could fail with boolean flags
|
Fix options restoring that could fail with boolean flags
|
Lua
|
mit
|
jungikim/OpenNMT,jungikim/OpenNMT,jungikim/OpenNMT,da03/OpenNMT,jsenellart-systran/OpenNMT,jsenellart/OpenNMT,OpenNMT/OpenNMT,jsenellart/OpenNMT,jsenellart-systran/OpenNMT,monsieurzhang/OpenNMT,jsenellart/OpenNMT,da03/OpenNMT,OpenNMT/OpenNMT,monsieurzhang/OpenNMT,jsenellart-systran/OpenNMT,OpenNMT/OpenNMT,da03/OpenNMT,monsieurzhang/OpenNMT
|
7626b3bb6a09d99234c44129ab0b90319fe52f31
|
src/lfs/variables_build.lua
|
src/lfs/variables_build.lua
|
local module = ...
local function build_list(objects)
local out = {}
for key, value in pairs(objects) do
if type(value) == 'table' then
if type(key) == 'string' then
table.insert(out, key .. "=")
end
table.insert(out, "{")
table.insert(out, build_list(value))
table.insert(out, "},")
elseif value == sjson.NULL then
-- skip it
else
table.insert(out, key)
table.insert(out, "=")
if type(value) == 'string' then
table.insert(out, "\"")
table.insert(out, value)
table.insert(out, "\"")
elseif type(value) == 'boolean' then
table.insert(out, tostring(value))
else
table.insert(out, value)
end
table.insert(out, ",")
end
end
return table.concat(out)
end
local function build(objects)
if not objects then return nil end
local out = {}
table.insert(out, "{")
table.insert(out, build_list(objects))
table.insert(out, "}")
return table.concat(out)
end
return function(objects)
package.loaded[module] = nil
module = nil
return build(objects)
end
|
local module = ...
local function build_list(objects)
local out = {}
for key, value in pairs(objects) do
if type(value) == 'table' then
if type(key) == 'string' then
table.insert(out, key .. "=")
end
table.insert(out, "{")
table.insert(out, build_list(value))
table.insert(out, "},")
elseif value == sjson.NULL or type(value) == "lightfunction" then
-- skip it
else
table.insert(out, key)
table.insert(out, "=")
if type(value) == 'string' then
table.insert(out, "\"")
table.insert(out, value)
table.insert(out, "\"")
elseif type(value) == 'boolean' then
table.insert(out, tostring(value))
else
table.insert(out, value)
end
table.insert(out, ",")
end
end
return table.concat(out)
end
local function build(objects)
if not objects then return nil end
local out = {}
table.insert(out, "{")
table.insert(out, build_list(objects))
table.insert(out, "}")
return table.concat(out)
end
return function(objects)
package.loaded[module] = nil
module = nil
return build(objects)
end
|
Fix panic when settings value is null.
|
Fix panic when settings value is null.
This fixes a panic that is triggered when a null value provided in a the settings sent.
In 3.0 if the value in the table is null (without quotes) it returns a "lightfunction" instead of "nil".
This adds a check for this to prevent corrupting the settings table.
|
Lua
|
apache-2.0
|
konnected-io/konnected-security,konnected-io/konnected-security
|
59845a6b3ba162e65b5f118abc4acb7b552e520c
|
src/npge/util/configGenerator.lua
|
src/npge/util/configGenerator.lua
|
-- lua-npge, Nucleotide PanGenome explorer (Lua module)
-- Copyright (C) 2014-2015 Boris Nagaev
-- See the LICENSE file for terms of use.
local function serialize(value)
local format
if type(value) == "number" then
format = "%d"
elseif type(value) == "boolean" then
value = tostring(value)
format = "%s"
elseif type(value) == "string" then
format = "%q"
end
return format:format(value)
end
return function()
local config = require 'npge.config'
local lines = {}
for section_name, section in pairs(config) do
for name, value in pairs(section) do
local about = config.about[section_name][name]
table.insert(lines, "-- " .. about)
local line = "%s.%s = %s"
table.insert(lines, line:format(section_name,
name, serialize(value)))
table.insert(lines, "")
end
end
return table.concat(lines, "\n")
end
|
-- lua-npge, Nucleotide PanGenome explorer (Lua module)
-- Copyright (C) 2014-2015 Boris Nagaev
-- See the LICENSE file for terms of use.
local function serialize(value)
local format
if type(value) == "number" or type(value) == "boolean"then
value = tostring(value)
format = "%s"
elseif type(value) == "string" then
format = "%q"
end
return format:format(value)
end
return function()
local config = require 'npge.config'
local lines = {}
for section_name, section in pairs(config) do
for name, value in pairs(section) do
local about = config.about[section_name][name]
table.insert(lines, "-- " .. about)
local line = "%s.%s = %s"
table.insert(lines, line:format(section_name,
name, serialize(value)))
table.insert(lines, "")
end
end
return table.concat(lines, "\n")
end
|
configGenerator: fix float serialization (Lua 5.3)
|
configGenerator: fix float serialization (Lua 5.3)
See https://travis-ci.org/npge/lua-npge/jobs/61230776#L1644
See https://ci.appveyor.com/project/starius/lua-npge/build/0.0.1.23-test/job/ta4fsqv17o9ewre0#L1238
|
Lua
|
mit
|
starius/lua-npge,npge/lua-npge,starius/lua-npge,npge/lua-npge,starius/lua-npge,npge/lua-npge
|
7ad2f448ae03cc108dad90159da7559b0805465f
|
packages/lime-system/files/usr/lib/lua/lime/config.lua
|
packages/lime-system/files/usr/lib/lua/lime/config.lua
|
#!/usr/bin/lua
--! LibreMesh is modular but this doesn't mean parallel, modules are executed
--! sequencially, so we don't need to worry about transactionality and all other
--! stuff that affects parrallels database, at moment we don't need parallelism
--! as this is just some configuration stuff and is not performance critical.
local libuci = require("uci")
config = {}
config.uci = libuci:cursor()
function config.get(sectionname, option, default)
local limeconf = config.uci:get("lime", sectionname, option)
if limeconf then return limeconf end
local defcnf = config.uci:get("lime-defaults", sectionname, option, default)
if ( defcnf ~= nil ) then
config.set(sectionname, option, defcnf)
else
local cfn = sectionname.."."..option
print("WARNING: Attempt to access undeclared default for: "..cfn)
print(debug.traceback())
end
return defcnf
end
--! Execute +callback+ for each config of type +configtype+ found in
--! +/etc/config/lime+.
--! beware this function doesn't look in +/etc/config/lime-default+ for default
--! values as it is designed for use with specific sections only
function config.foreach(configtype, callback)
return config.uci:foreach("lime", configtype, callback)
end
function config.get_all(sectionname)
local lime_section = config.uci:get_all("lime", sectionname)
local lime_def_section = config.uci:get_all("lime-defaults", sectionname)
if lime_section or lime_def_section then
local ret = lime_section or {}
if lime_def_section then
for key,value in pairs(lime_def_section) do
if (ret[key] == nil) then
config.set(sectionname, key, value)
ret[key] = value
end
end
end
return ret
end
return nil
end
function config.get_bool(sectionname, option, default)
local val = config.get(sectionname, option, default)
return (val and ((val == '1') or (val == 'on') or (val == 'true') or (val == 'enabled')))
end
config.batched = false
function config.init_batch()
config.batched = true
end
function config.set(...)
config.uci:set("lime", unpack(arg))
if(not config.batched) then config.uci:save("lime") end
end
function config.delete(...)
config.uci:delete("lime", unpack(arg))
if(not config.batched) then config.uci:save("lime") end
end
function config.end_batch()
if(config.batched) then
config.uci:save("lime")
config.batched = false
end
end
function config.autogenerable(section_name)
return ( (not config.get_all(section_name)) or config.get_bool(section_name, "autogenerated") )
end
return config
|
#!/usr/bin/lua
--! LibreMesh is modular but this doesn't mean parallel, modules are executed
--! sequencially, so we don't need to worry about transactionality and all other
--! stuff that affects parrallels database, at moment we don't need parallelism
--! as this is just some configuration stuff and is not performance critical.
local libuci = require("uci")
config = {}
config.uci = libuci:cursor()
function config.get(sectionname, option, default)
local limeconf = config.uci:get("lime", sectionname, option)
if limeconf then return limeconf end
local defcnf = config.uci:get("lime-defaults", sectionname, option, default)
if ( defcnf ~= nil ) then
config.set(sectionname, option, defcnf)
else
local cfn = sectionname.."."..option
print("WARNING: Attempt to access undeclared default for: "..cfn)
print(debug.traceback())
end
return defcnf
end
--! Execute +callback+ for each config of type +configtype+ found in
--! +/etc/config/lime+.
--! beware this function doesn't look in +/etc/config/lime-default+ for default
--! values as it is designed for use with specific sections only
function config.foreach(configtype, callback)
return config.uci:foreach("lime", configtype, callback)
end
function config.get_all(sectionname)
local lime_section = config.uci:get_all("lime", sectionname)
local lime_def_section = config.uci:get_all("lime-defaults", sectionname)
if lime_section or lime_def_section then
local ret = lime_section or {}
if lime_def_section then
for key,value in pairs(lime_def_section) do
if (ret[key] == nil) then
config.set(sectionname, key, value)
ret[key] = value
end
end
end
return ret
end
return nil
end
function config.get_bool(sectionname, option, default)
if(type(default) == 'boolean') then default = tostring(default) end
local val = config.get(sectionname, option, default)
return (val and ((val == '1') or (val == 'on') or (val == 'true') or (val == 'enabled')))
end
config.batched = false
function config.init_batch()
config.batched = true
end
function config.set(...)
config.uci:set("lime", unpack(arg))
if(not config.batched) then config.uci:save("lime") end
end
function config.delete(...)
config.uci:delete("lime", unpack(arg))
if(not config.batched) then config.uci:save("lime") end
end
function config.end_batch()
if(config.batched) then
config.uci:save("lime")
config.batched = false
end
end
function config.autogenerable(section_name)
return ( (not config.get_all(section_name)) or config.get_bool(section_name, "autogenerated") )
end
return config
|
Fix config.get_bool in case default is passed
|
Fix config.get_bool in case default is passed
|
Lua
|
agpl-3.0
|
libremesh/lime-packages,p4u/lime-packages,p4u/lime-packages,p4u/lime-packages,libremesh/lime-packages,libremesh/lime-packages,p4u/lime-packages,libremesh/lime-packages,p4u/lime-packages,libremesh/lime-packages,libremesh/lime-packages
|
c486936898887aab61e79d090f8eeedbbc0a6935
|
net/http.lua
|
net/http.lua
|
local socket = require "socket"
local mime = require "mime"
local url = require "socket.url"
local server = require "net.server"
local connlisteners_get = require "net.connlisteners".get;
local listener = connlisteners_get("httpclient") or error("No httpclient listener!");
local t_insert, t_concat = table.insert, table.concat;
local tonumber, tostring, pairs, xpcall, select, debug_traceback =
tonumber, tostring, pairs, xpcall, select, debug.traceback;
local log = require "util.logger".init("http");
local print = function () end
local urlcodes = setmetatable({}, { __index = function (t, k) t[k] = char(tonumber("0x"..k)); return t[k]; end });
local urlencode = function (s) return s and (s:gsub("%W", function (c) return string.format("%%%02x", c:byte()); end)); end
module "http"
local function expectbody(reqt, code)
if reqt.method == "HEAD" then return nil end
if code == 204 or code == 304 then return nil end
if code >= 100 and code < 200 then return nil end
return 1
end
local function request_reader(request, data, startpos)
if not data then
if request.body then
log("debug", "Connection closed, but we have data, calling callback...");
request.callback(t_concat(request.body), request.code, request);
elseif request.state ~= "completed" then
-- Error.. connection was closed prematurely
request.callback("connection-closed", 0, request);
end
destroy_request(request);
return;
end
if request.state == "body" then
print("Reading body...")
if not request.body then request.body = {}; request.havebodylength, request.bodylength = 0, tonumber(request.responseheaders["content-length"]); end
if startpos then
data = data:sub(startpos, -1)
end
t_insert(request.body, data);
if request.bodylength then
request.havebodylength = request.havebodylength + #data;
if request.havebodylength >= request.bodylength then
-- We have the body
log("debug", "Have full body, calling callback");
if request.callback then
request.callback(t_concat(request.body), request.code, request);
end
request.body = nil;
request.state = "completed";
else
print("", "Have "..request.havebodylength.." bytes out of "..request.bodylength);
end
end
elseif request.state == "headers" then
print("Reading headers...")
local pos = startpos;
local headers = request.responseheaders or {};
for line in data:sub(startpos, -1):gmatch("(.-)\r\n") do
startpos = startpos + #line + 2;
local k, v = line:match("(%S+): (.+)");
if k and v then
headers[k:lower()] = v;
print("Header: "..k:lower().." = "..v);
elseif #line == 0 then
request.responseheaders = headers;
break;
else
print("Unhandled header line: "..line);
end
end
-- Reached the end of the headers
request.state = "body";
if #data > startpos then
return request_reader(request, data, startpos);
end
elseif request.state == "status" then
print("Reading status...")
local http, code, text, linelen = data:match("^HTTP/(%S+) (%d+) (.-)\r\n()", startpos);
code = tonumber(code);
if not code then
return request.callback("invalid-status-line", 0, request);
end
request.code, request.responseversion = code, http;
if request.onlystatus or not expectbody(request, code) then
if request.callback then
request.callback(nil, code, request);
end
destroy_request(request);
return;
end
request.state = "headers";
if #data > linelen then
return request_reader(request, data, linelen);
end
end
end
local function handleerr(err) log("error", "Traceback[http]: %s: %s", tostring(err), debug_traceback()); end
function request(u, ex, callback)
local req = url.parse(u);
local custom_headers, body;
local default_headers = { ["Host"] = req.host, ["User-Agent"] = "Prosody XMPP Server" }
if req.userinfo then
default_headers["Authorization"] = "Basic "..mime.b64(req.userinfo);
end
if ex then
custom_headers = ex.custom_headers;
req.onlystatus = ex.onlystatus;
body = ex.body;
if body then
req.method = "POST ";
default_headers["Content-Length"] = tostring(#body);
default_headers["Content-Type"] = "application/x-www-form-urlencoded";
end
if ex.method then req.method = ex.method; end
end
req.handler, req.conn = server.wraptcpclient(listener, socket.tcp(), req.host, req.port or 80, 0, "*a");
req.write = req.handler.write;
req.conn:settimeout(0);
local ok, err = req.conn:connect(req.host, req.port or 80);
if not ok and err ~= "timeout" then
return nil, err;
end
req.write((req.method or "GET ")..req.path.." HTTP/1.0\r\n");
local t = { [2] = ": ", [4] = "\r\n" };
if custom_headers then
for k, v in pairs(custom_headers) do
t[1], t[3] = k, v;
req.write(t_concat(t));
default_headers[k] = nil;
end
end
for k, v in pairs(default_headers) do
t[1], t[3] = k, v;
req.write(t_concat(t));
default_headers[k] = nil;
end
req.write("\r\n");
if body then
req.write(body);
end
req.callback = function (content, code, request) log("debug", "Calling callback, code %s content: %s", code or "---", content or "---"); return select(2, xpcall(function () return callback(content, code, request) end, handleerr)); end
req.reader = request_reader;
req.state = "status";
listener.register_request(req.handler, req);
return req;
end
function destroy_request(request)
if request.conn then
request.handler.close()
listener.disconnect(request.conn, "closed");
end
end
_M.urlencode = urlencode;
return _M;
|
local socket = require "socket"
local mime = require "mime"
local url = require "socket.url"
local server = require "net.server"
local connlisteners_get = require "net.connlisteners".get;
local listener = connlisteners_get("httpclient") or error("No httpclient listener!");
local t_insert, t_concat = table.insert, table.concat;
local tonumber, tostring, pairs, xpcall, select, debug_traceback =
tonumber, tostring, pairs, xpcall, select, debug.traceback;
local log = require "util.logger".init("http");
local print = function () end
local urlcodes = setmetatable({}, { __index = function (t, k) t[k] = char(tonumber("0x"..k)); return t[k]; end });
local urlencode = function (s) return s and (s:gsub("%W", function (c) return string.format("%%%02x", c:byte()); end)); end
module "http"
local function expectbody(reqt, code)
if reqt.method == "HEAD" then return nil end
if code == 204 or code == 304 then return nil end
if code >= 100 and code < 200 then return nil end
return 1
end
local function request_reader(request, data, startpos)
if not data then
if request.body then
log("debug", "Connection closed, but we have data, calling callback...");
request.callback(t_concat(request.body), request.code, request);
elseif request.state ~= "completed" then
-- Error.. connection was closed prematurely
request.callback("connection-closed", 0, request);
end
destroy_request(request);
request.body = nil;
request.state = "completed";
return;
end
if request.state == "body" and request.state ~= "completed" then
print("Reading body...")
if not request.body then request.body = {}; request.havebodylength, request.bodylength = 0, tonumber(request.responseheaders["content-length"]); end
if startpos then
data = data:sub(startpos, -1)
end
t_insert(request.body, data);
if request.bodylength then
request.havebodylength = request.havebodylength + #data;
if request.havebodylength >= request.bodylength then
-- We have the body
log("debug", "Have full body, calling callback");
if request.callback then
request.callback(t_concat(request.body), request.code, request);
end
request.body = nil;
request.state = "completed";
else
print("", "Have "..request.havebodylength.." bytes out of "..request.bodylength);
end
end
elseif request.state == "headers" then
print("Reading headers...")
local pos = startpos;
local headers = request.responseheaders or {};
for line in data:sub(startpos, -1):gmatch("(.-)\r\n") do
startpos = startpos + #line + 2;
local k, v = line:match("(%S+): (.+)");
if k and v then
headers[k:lower()] = v;
print("Header: "..k:lower().." = "..v);
elseif #line == 0 then
request.responseheaders = headers;
break;
else
print("Unhandled header line: "..line);
end
end
-- Reached the end of the headers
request.state = "body";
if #data > startpos then
return request_reader(request, data, startpos);
end
elseif request.state == "status" then
print("Reading status...")
local http, code, text, linelen = data:match("^HTTP/(%S+) (%d+) (.-)\r\n()", startpos);
code = tonumber(code);
if not code then
return request.callback("invalid-status-line", 0, request);
end
request.code, request.responseversion = code, http;
if request.onlystatus or not expectbody(request, code) then
if request.callback then
request.callback(nil, code, request);
end
destroy_request(request);
return;
end
request.state = "headers";
if #data > linelen then
return request_reader(request, data, linelen);
end
end
end
local function handleerr(err) log("error", "Traceback[http]: %s: %s", tostring(err), debug_traceback()); end
function request(u, ex, callback)
local req = url.parse(u);
local custom_headers, body;
local default_headers = { ["Host"] = req.host, ["User-Agent"] = "Prosody XMPP Server" }
if req.userinfo then
default_headers["Authorization"] = "Basic "..mime.b64(req.userinfo);
end
if ex then
custom_headers = ex.custom_headers;
req.onlystatus = ex.onlystatus;
body = ex.body;
if body then
req.method = "POST ";
default_headers["Content-Length"] = tostring(#body);
default_headers["Content-Type"] = "application/x-www-form-urlencoded";
end
if ex.method then req.method = ex.method; end
end
req.handler, req.conn = server.wraptcpclient(listener, socket.tcp(), req.host, req.port or 80, 0, "*a");
req.write = req.handler.write;
req.conn:settimeout(0);
local ok, err = req.conn:connect(req.host, req.port or 80);
if not ok and err ~= "timeout" then
return nil, err;
end
req.write((req.method or "GET ")..req.path.." HTTP/1.0\r\n");
local t = { [2] = ": ", [4] = "\r\n" };
if custom_headers then
for k, v in pairs(custom_headers) do
t[1], t[3] = k, v;
req.write(t_concat(t));
default_headers[k] = nil;
end
end
for k, v in pairs(default_headers) do
t[1], t[3] = k, v;
req.write(t_concat(t));
default_headers[k] = nil;
end
req.write("\r\n");
if body then
req.write(body);
end
req.callback = function (content, code, request) log("debug", "Calling callback, code %s content: %s", code or "---", content or "---"); return select(2, xpcall(function () return callback(content, code, request) end, handleerr)); end
req.reader = request_reader;
req.state = "status";
listener.register_request(req.handler, req);
return req;
end
function destroy_request(request)
if request.conn then
request.handler.close()
listener.disconnect(request.conn, "closed");
end
end
_M.urlencode = urlencode;
return _M;
|
net.http: Fix for callbacks being triggered multiple times for the same request
|
net.http: Fix for callbacks being triggered multiple times for the same request
|
Lua
|
mit
|
sarumjanuch/prosody,sarumjanuch/prosody
|
b5204f0887b60a8a794f2c709f07861bfc9947a6
|
libs/httpd/luasrc/httpd.lua
|
libs/httpd/luasrc/httpd.lua
|
--[[
HTTP server implementation for LuCI - core
(c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net>
(c) 2008 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
module("luci.httpd", package.seeall)
require("socket")
THREAD_IDLEWAIT = 0.01
THREAD_TIMEOUT = 90
THREAD_LIMIT = nil
local reading = {}
local clhandler = {}
local erhandler = {}
local threadc = 0
local threads = {}
local threadm = {}
local threadi = {}
local _meta = {__mode = "k"}
setmetatable(threads, _meta)
setmetatable(threadm, _meta)
setmetatable(threadi, _meta)
function Socket(ip, port)
local sock, err = socket.bind( ip, port )
if sock then
sock:settimeout( 0, "t" )
end
return sock, err
end
function corecv(socket, ...)
threadi[socket] = true
while true do
local chunk, err, part = socket:receive(...)
if err ~= "timeout" then
threadi[socket] = false
return chunk, err, part
end
coroutine.yield()
end
end
function cosend(socket, chunk, i, ...)
threadi[socket] = true
i = i or 1
while true do
local stat, err, sent = socket:send(chunk, i, ...)
if err ~= "timeout" then
threadi[socket] = false
return stat, err, sent
else
i = sent and (sent + 1) or i
end
coroutine.yield()
end
end
function register(socket, s_clhandler, s_errhandler)
table.insert(reading, socket)
clhandler[socket] = s_clhandler
erhandler[socket] = s_errhandler
end
function run()
while true do
step()
end
end
function step()
print(collectgarbage("count"))
local idle = true
if not THREAD_LIMIT or threadc < THREAD_LIMIT then
local now = os.time()
for i, server in ipairs(reading) do
local client = server:accept()
if client then
threadm[client] = now
threadc = threadc + 1
threads[client] = coroutine.create(clhandler[server])
end
end
end
for client, thread in pairs(threads) do
coroutine.resume(thread, client)
local now = os.time()
if coroutine.status(thread) == "dead" then
threadc = threadc - 1
elseif threadm[client] and threadm[client] + THREAD_TIMEOUT < now then
threads[client] = nil
threadc = threadc - 1
client:close()
elseif not threadi[client] then
threadm[client] = now
idle = false
end
end
if idle then
socket.sleep(THREAD_IDLEWAIT)
end
end
|
--[[
HTTP server implementation for LuCI - core
(c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net>
(c) 2008 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
module("luci.httpd", package.seeall)
require("socket")
THREAD_IDLEWAIT = 0.01
THREAD_TIMEOUT = 90
THREAD_LIMIT = nil
local reading = {}
local clhandler = {}
local erhandler = {}
local threadc = 0
local threads = {}
local threadm = {}
local threadi = {}
local _meta = {__mode = "k"}
setmetatable(threads, _meta)
setmetatable(threadm, _meta)
setmetatable(threadi, _meta)
function Socket(ip, port)
local sock, err = socket.bind( ip, port )
if sock then
sock:settimeout( 0, "t" )
end
return sock, err
end
function corecv(socket, ...)
threadi[socket] = true
while true do
local chunk, err, part = socket:receive(...)
if err ~= "timeout" then
threadi[socket] = false
return chunk, err, part
end
coroutine.yield()
end
end
function cosend(socket, chunk, i, ...)
threadi[socket] = true
i = i or 1
while true do
local stat, err, sent = socket:send(chunk, i, ...)
if err ~= "timeout" then
threadi[socket] = false
return stat, err, sent
else
i = sent and (sent + 1) or i
end
coroutine.yield()
end
end
function register(socket, s_clhandler, s_errhandler)
table.insert(reading, socket)
clhandler[socket] = s_clhandler
erhandler[socket] = s_errhandler
end
function run()
while true do
step()
end
end
function step()
local idle = true
if not THREAD_LIMIT or threadc < THREAD_LIMIT then
local now = os.time()
for i, server in ipairs(reading) do
local client = server:accept()
if client then
threadm[client] = now
threadc = threadc + 1
threads[client] = coroutine.create(clhandler[server])
end
end
end
for client, thread in pairs(threads) do
coroutine.resume(thread, client)
local now = os.time()
if coroutine.status(thread) == "dead" then
threadc = threadc - 1
elseif threadm[client] and threadm[client] + THREAD_TIMEOUT < now then
threads[client] = nil
threadc = threadc - 1
client:close()
elseif not threadi[client] then
threadm[client] = now
idle = false
end
end
if idle then
socket.sleep(THREAD_IDLEWAIT)
end
end
|
* libs/httpd: Fixed last commit
|
* libs/httpd: Fixed last commit
|
Lua
|
apache-2.0
|
male-puppies/luci,teslamint/luci,palmettos/test,palmettos/test,oyido/luci,thesabbir/luci,rogerpueyo/luci,chris5560/openwrt-luci,nwf/openwrt-luci,aircross/OpenWrt-Firefly-LuCI,sujeet14108/luci,marcel-sch/luci,wongsyrone/luci-1,remakeelectric/luci,dwmw2/luci,teslamint/luci,teslamint/luci,thess/OpenWrt-luci,bittorf/luci,daofeng2015/luci,palmettos/cnLuCI,Hostle/luci,LazyZhu/openwrt-luci-trunk-mod,LazyZhu/openwrt-luci-trunk-mod,obsy/luci,Hostle/openwrt-luci-multi-user,LuttyYang/luci,harveyhu2012/luci,LazyZhu/openwrt-luci-trunk-mod,tcatm/luci,NeoRaider/luci,Kyklas/luci-proto-hso,Wedmer/luci,RuiChen1113/luci,cappiewu/luci,keyidadi/luci,lbthomsen/openwrt-luci,david-xiao/luci,LuttyYang/luci,harveyhu2012/luci,kuoruan/luci,thesabbir/luci,oneru/luci,db260179/openwrt-bpi-r1-luci,teslamint/luci,daofeng2015/luci,keyidadi/luci,maxrio/luci981213,daofeng2015/luci,zhaoxx063/luci,kuoruan/lede-luci,oyido/luci,sujeet14108/luci,lbthomsen/openwrt-luci,florian-shellfire/luci,Hostle/luci,MinFu/luci,zhaoxx063/luci,joaofvieira/luci,teslamint/luci,981213/luci-1,rogerpueyo/luci,harveyhu2012/luci,fkooman/luci,Sakura-Winkey/LuCI,LuttyYang/luci,nwf/openwrt-luci,thesabbir/luci,Kyklas/luci-proto-hso,palmettos/cnLuCI,deepak78/new-luci,cshore/luci,mumuqz/luci,oyido/luci,ReclaimYourPrivacy/cloak-luci,lcf258/openwrtcn,Sakura-Winkey/LuCI,jlopenwrtluci/luci,harveyhu2012/luci,NeoRaider/luci,oneru/luci,cshore/luci,zhaoxx063/luci,jchuang1977/luci-1,981213/luci-1,aa65535/luci,marcel-sch/luci,fkooman/luci,chris5560/openwrt-luci,artynet/luci,obsy/luci,obsy/luci,jchuang1977/luci-1,aa65535/luci,RuiChen1113/luci,deepak78/new-luci,Wedmer/luci,openwrt/luci,artynet/luci,dwmw2/luci,Hostle/openwrt-luci-multi-user,palmettos/cnLuCI,aa65535/luci,Wedmer/luci,david-xiao/luci,LuttyYang/luci,urueedi/luci,Hostle/openwrt-luci-multi-user,male-puppies/luci,tcatm/luci,tcatm/luci,lbthomsen/openwrt-luci,oneru/luci,mumuqz/luci,florian-shellfire/luci,dismantl/luci-0.12,marcel-sch/luci,cshore-firmware/openwrt-luci,Noltari/luci,lbthomsen/openwrt-luci,palmettos/test,ReclaimYourPrivacy/cloak-luci,urueedi/luci,jorgifumi/luci,tobiaswaldvogel/luci,slayerrensky/luci,openwrt/luci,lcf258/openwrtcn,oyido/luci,Wedmer/luci,keyidadi/luci,forward619/luci,ollie27/openwrt_luci,teslamint/luci,obsy/luci,deepak78/new-luci,oyido/luci,LazyZhu/openwrt-luci-trunk-mod,bright-things/ionic-luci,jorgifumi/luci,nwf/openwrt-luci,schidler/ionic-luci,ff94315/luci-1,maxrio/luci981213,cappiewu/luci,ReclaimYourPrivacy/cloak-luci,shangjiyu/luci-with-extra,keyidadi/luci,openwrt-es/openwrt-luci,ollie27/openwrt_luci,nmav/luci,Kyklas/luci-proto-hso,Noltari/luci,bright-things/ionic-luci,MinFu/luci,bittorf/luci,Hostle/openwrt-luci-multi-user,cshore/luci,jchuang1977/luci-1,remakeelectric/luci,palmettos/test,shangjiyu/luci-with-extra,lbthomsen/openwrt-luci,kuoruan/luci,thess/OpenWrt-luci,nwf/openwrt-luci,NeoRaider/luci,cshore-firmware/openwrt-luci,bittorf/luci,Hostle/luci,RedSnake64/openwrt-luci-packages,thesabbir/luci,sujeet14108/luci,marcel-sch/luci,tcatm/luci,aa65535/luci,deepak78/new-luci,shangjiyu/luci-with-extra,Hostle/luci,ollie27/openwrt_luci,cappiewu/luci,wongsyrone/luci-1,lcf258/openwrtcn,db260179/openwrt-bpi-r1-luci,fkooman/luci,db260179/openwrt-bpi-r1-luci,david-xiao/luci,forward619/luci,nwf/openwrt-luci,Noltari/luci,ff94315/luci-1,Kyklas/luci-proto-hso,tobiaswaldvogel/luci,male-puppies/luci,ollie27/openwrt_luci,wongsyrone/luci-1,MinFu/luci,openwrt-es/openwrt-luci,chris5560/openwrt-luci,slayerrensky/luci,kuoruan/luci,jlopenwrtluci/luci,bright-things/ionic-luci,Hostle/luci,thess/OpenWrt-luci,bittorf/luci,Sakura-Winkey/LuCI,marcel-sch/luci,981213/luci-1,aircross/OpenWrt-Firefly-LuCI,jlopenwrtluci/luci,db260179/openwrt-bpi-r1-luci,aircross/OpenWrt-Firefly-LuCI,tobiaswaldvogel/luci,openwrt/luci,jorgifumi/luci,Sakura-Winkey/LuCI,jchuang1977/luci-1,cappiewu/luci,openwrt-es/openwrt-luci,daofeng2015/luci,RedSnake64/openwrt-luci-packages,slayerrensky/luci,cshore/luci,urueedi/luci,keyidadi/luci,Kyklas/luci-proto-hso,teslamint/luci,nmav/luci,ff94315/luci-1,deepak78/new-luci,cshore/luci,oneru/luci,LuttyYang/luci,Noltari/luci,remakeelectric/luci,openwrt-es/openwrt-luci,david-xiao/luci,daofeng2015/luci,thesabbir/luci,sujeet14108/luci,981213/luci-1,taiha/luci,jlopenwrtluci/luci,rogerpueyo/luci,david-xiao/luci,oneru/luci,daofeng2015/luci,Sakura-Winkey/LuCI,sujeet14108/luci,openwrt/luci,thesabbir/luci,Noltari/luci,openwrt-es/openwrt-luci,joaofvieira/luci,nmav/luci,rogerpueyo/luci,taiha/luci,forward619/luci,zhaoxx063/luci,db260179/openwrt-bpi-r1-luci,NeoRaider/luci,opentechinstitute/luci,sujeet14108/luci,MinFu/luci,fkooman/luci,obsy/luci,981213/luci-1,wongsyrone/luci-1,kuoruan/lede-luci,bright-things/ionic-luci,Wedmer/luci,RuiChen1113/luci,aircross/OpenWrt-Firefly-LuCI,thess/OpenWrt-luci,dismantl/luci-0.12,dwmw2/luci,tcatm/luci,rogerpueyo/luci,bittorf/luci,bright-things/ionic-luci,ReclaimYourPrivacy/cloak-luci,cshore-firmware/openwrt-luci,shangjiyu/luci-with-extra,zhaoxx063/luci,dwmw2/luci,wongsyrone/luci-1,forward619/luci,kuoruan/luci,florian-shellfire/luci,lcf258/openwrtcn,palmettos/test,RuiChen1113/luci,aircross/OpenWrt-Firefly-LuCI,opentechinstitute/luci,male-puppies/luci,jorgifumi/luci,ff94315/luci-1,nwf/openwrt-luci,Wedmer/luci,Sakura-Winkey/LuCI,openwrt/luci,RedSnake64/openwrt-luci-packages,lcf258/openwrtcn,schidler/ionic-luci,maxrio/luci981213,dismantl/luci-0.12,david-xiao/luci,cshore-firmware/openwrt-luci,aircross/OpenWrt-Firefly-LuCI,dismantl/luci-0.12,lcf258/openwrtcn,lbthomsen/openwrt-luci,artynet/luci,schidler/ionic-luci,mumuqz/luci,dismantl/luci-0.12,harveyhu2012/luci,harveyhu2012/luci,thess/OpenWrt-luci,981213/luci-1,981213/luci-1,Hostle/openwrt-luci-multi-user,taiha/luci,RedSnake64/openwrt-luci-packages,joaofvieira/luci,ollie27/openwrt_luci,MinFu/luci,teslamint/luci,ollie27/openwrt_luci,opentechinstitute/luci,palmettos/cnLuCI,ff94315/luci-1,cshore/luci,oyido/luci,oneru/luci,Sakura-Winkey/LuCI,fkooman/luci,chris5560/openwrt-luci,thess/OpenWrt-luci,keyidadi/luci,Wedmer/luci,Hostle/luci,joaofvieira/luci,nmav/luci,fkooman/luci,opentechinstitute/luci,jchuang1977/luci-1,ollie27/openwrt_luci,remakeelectric/luci,nwf/openwrt-luci,cappiewu/luci,Noltari/luci,LazyZhu/openwrt-luci-trunk-mod,slayerrensky/luci,lcf258/openwrtcn,artynet/luci,schidler/ionic-luci,LazyZhu/openwrt-luci-trunk-mod,bittorf/luci,mumuqz/luci,NeoRaider/luci,hnyman/luci,daofeng2015/luci,obsy/luci,male-puppies/luci,sujeet14108/luci,slayerrensky/luci,jorgifumi/luci,tcatm/luci,kuoruan/luci,tcatm/luci,jchuang1977/luci-1,florian-shellfire/luci,jorgifumi/luci,bright-things/ionic-luci,ReclaimYourPrivacy/cloak-luci,aa65535/luci,jlopenwrtluci/luci,urueedi/luci,thesabbir/luci,dismantl/luci-0.12,NeoRaider/luci,dwmw2/luci,remakeelectric/luci,taiha/luci,remakeelectric/luci,tobiaswaldvogel/luci,male-puppies/luci,aa65535/luci,opentechinstitute/luci,tobiaswaldvogel/luci,wongsyrone/luci-1,nmav/luci,chris5560/openwrt-luci,tobiaswaldvogel/luci,zhaoxx063/luci,rogerpueyo/luci,thesabbir/luci,jchuang1977/luci-1,jlopenwrtluci/luci,marcel-sch/luci,nmav/luci,kuoruan/luci,kuoruan/lede-luci,jorgifumi/luci,hnyman/luci,fkooman/luci,maxrio/luci981213,aircross/OpenWrt-Firefly-LuCI,cappiewu/luci,rogerpueyo/luci,schidler/ionic-luci,david-xiao/luci,RuiChen1113/luci,oyido/luci,florian-shellfire/luci,NeoRaider/luci,urueedi/luci,ff94315/luci-1,maxrio/luci981213,palmettos/cnLuCI,schidler/ionic-luci,remakeelectric/luci,bright-things/ionic-luci,urueedi/luci,opentechinstitute/luci,hnyman/luci,joaofvieira/luci,dismantl/luci-0.12,nmav/luci,schidler/ionic-luci,remakeelectric/luci,bittorf/luci,cshore/luci,cshore-firmware/openwrt-luci,forward619/luci,ReclaimYourPrivacy/cloak-luci,mumuqz/luci,jlopenwrtluci/luci,bright-things/ionic-luci,taiha/luci,Hostle/openwrt-luci-multi-user,shangjiyu/luci-with-extra,taiha/luci,keyidadi/luci,nmav/luci,Kyklas/luci-proto-hso,kuoruan/luci,cshore-firmware/openwrt-luci,openwrt/luci,lcf258/openwrtcn,slayerrensky/luci,daofeng2015/luci,NeoRaider/luci,shangjiyu/luci-with-extra,hnyman/luci,kuoruan/lede-luci,zhaoxx063/luci,MinFu/luci,openwrt-es/openwrt-luci,forward619/luci,opentechinstitute/luci,nmav/luci,RedSnake64/openwrt-luci-packages,artynet/luci,deepak78/new-luci,male-puppies/luci,taiha/luci,cshore-firmware/openwrt-luci,urueedi/luci,chris5560/openwrt-luci,LuttyYang/luci,nwf/openwrt-luci,artynet/luci,kuoruan/lede-luci,aa65535/luci,RuiChen1113/luci,male-puppies/luci,LazyZhu/openwrt-luci-trunk-mod,florian-shellfire/luci,lbthomsen/openwrt-luci,openwrt-es/openwrt-luci,lbthomsen/openwrt-luci,Wedmer/luci,kuoruan/lede-luci,harveyhu2012/luci,mumuqz/luci,kuoruan/lede-luci,ReclaimYourPrivacy/cloak-luci,wongsyrone/luci-1,tobiaswaldvogel/luci,obsy/luci,palmettos/test,hnyman/luci,openwrt/luci,david-xiao/luci,mumuqz/luci,artynet/luci,LuttyYang/luci,db260179/openwrt-bpi-r1-luci,openwrt/luci,ff94315/luci-1,Noltari/luci,MinFu/luci,joaofvieira/luci,openwrt-es/openwrt-luci,shangjiyu/luci-with-extra,dwmw2/luci,ReclaimYourPrivacy/cloak-luci,MinFu/luci,hnyman/luci,RedSnake64/openwrt-luci-packages,Hostle/luci,palmettos/test,Kyklas/luci-proto-hso,tcatm/luci,dwmw2/luci,lcf258/openwrtcn,kuoruan/luci,db260179/openwrt-bpi-r1-luci,deepak78/new-luci,bittorf/luci,ollie27/openwrt_luci,jlopenwrtluci/luci,tobiaswaldvogel/luci,mumuqz/luci,urueedi/luci,maxrio/luci981213,slayerrensky/luci,chris5560/openwrt-luci,schidler/ionic-luci,RedSnake64/openwrt-luci-packages,sujeet14108/luci,maxrio/luci981213,RuiChen1113/luci,cappiewu/luci,cshore-firmware/openwrt-luci,thess/OpenWrt-luci,fkooman/luci,cshore/luci,db260179/openwrt-bpi-r1-luci,forward619/luci,cappiewu/luci,joaofvieira/luci,dwmw2/luci,zhaoxx063/luci,marcel-sch/luci,RuiChen1113/luci,thess/OpenWrt-luci,hnyman/luci,Sakura-Winkey/LuCI,deepak78/new-luci,ff94315/luci-1,florian-shellfire/luci,Hostle/openwrt-luci-multi-user,shangjiyu/luci-with-extra,kuoruan/lede-luci,joaofvieira/luci,artynet/luci,hnyman/luci,Hostle/openwrt-luci-multi-user,oneru/luci,forward619/luci,Noltari/luci,obsy/luci,rogerpueyo/luci,palmettos/cnLuCI,aa65535/luci,florian-shellfire/luci,opentechinstitute/luci,Hostle/luci,chris5560/openwrt-luci,palmettos/cnLuCI,marcel-sch/luci,LazyZhu/openwrt-luci-trunk-mod,maxrio/luci981213,lcf258/openwrtcn,jorgifumi/luci,wongsyrone/luci-1,taiha/luci,oyido/luci,artynet/luci,slayerrensky/luci,Noltari/luci,jchuang1977/luci-1,palmettos/cnLuCI,oneru/luci,LuttyYang/luci,palmettos/test,keyidadi/luci
|
56214f1955767f0db1aad5d2f3b786a31470a475
|
kong/plugins/http-log/migrations/001_280_to_300.lua
|
kong/plugins/http-log/migrations/001_280_to_300.lua
|
local operations = require "kong.db.migrations.operations.280_to_300"
local function ws_migration_teardown(ops)
return function(connector)
return ops:fixup_plugin_config(connector, "http-log", function(config)
local updated = false
if type(config) == "table" then -- not required, but let's be defensive here
local headers = config.headers
if type(headers) == "table" then
for header_name, value_array in pairs(headers) do
if type(value_array) == "table" then
-- only update if it's still a table, so it is reentrant
headers[header_name] = value_array[1] or "empty header value"
updated = true
end
end
end
end
return updated
end)
end
end
return {
postgres = {
up = "",
teardown = ws_migration_teardown(operations.postgres.teardown),
},
cassandra = {
up = "",
teardown = ws_migration_teardown(operations.cassandra.teardown),
},
}
|
local operations = require "kong.db.migrations.operations.280_to_300"
local function ws_migration_teardown(ops)
return function(connector)
return ops:fixup_plugin_config(connector, "http-log", function(config)
local updated = false
if type(config) == "table" then -- not required, but let's be defensive here
local headers = config.headers
if type(headers) == "table" then
for header_name, value_array in pairs(headers) do
if type(value_array) == "table" then
-- only update if it's still a table, so it is reentrant
if not next(value_array) then
-- In <=2.8, while it is possible to set a header with an empty
-- array of values, the gateway won't send the header with no
-- value to the defined HTTP endpoint. To match this behavior,
-- we'll remove the header.
headers[header_name] = nil
else
-- When multiple header values were provided, the gateway would
-- send all values, deliminated by a comma & space characters.
headers[header_name] = table.concat(value_array, ", ")
end
updated = true
end
end
-- When there are no headers set after the modifications, set to null
-- in order to avoid setting to an empty object.
if updated and not next(headers) then
local cjson = require "cjson"
config.headers = cjson.null
end
end
end
return updated
end)
end
end
return {
postgres = {
up = "",
teardown = ws_migration_teardown(operations.postgres.teardown),
},
cassandra = {
up = "",
teardown = ws_migration_teardown(operations.cassandra.teardown),
},
}
|
fix(http-log) properly migrate headers when multiple values are provided
|
fix(http-log) properly migrate headers when multiple values are provided
In Kong <=2.8, the `http-log` plugin supports providing multiple header values
in the array, and will automatically concatenate them (delimited by `, `) when
sent over the wire to the defined HTTP log endpoint.
Prior to these code changes, if someone has `{"some-header": ["test1", "test2"]}`
set as the headers on their plugin config, when migrating from 2.8 to 3.0, it’d
re-write the headers config to `{"some-header": "test1"}`. These code changes
allow to retain the same behavior as prior versions.
Given the example headers config above, the headers sent by the gateway in a
manual integration test are below:
```
Content-Length: 1556
User-Agent: lua-resty-http/0.16.1 (Lua) ngx_lua/10020
Content-Type: application/json
some-header: test1, test2
```
The DB migration was manually tested from 2.8 -> 3.0. Below is the state of the
plugin in 2.8 (before the migration) and in 3.0 (after the migration):
```
// One header defined with two values.
//
// v2.8 plugin config:
{
"method": "POST",
"headers": {
"some-header": [
"test1",
"test2"
]
},
"timeout": 10000,
"keepalive": 60000,
"queue_size": 1,
"retry_count": 10,
"content_type": "application/json",
"flush_timeout": 2,
"http_endpoint": "http://127.0.0.1:8081",
"custom_fields_by_lua": null
}
// v3.0 plugin config:
{
"method": "POST",
"headers": {
"some-header": "test1, test2"
},
"timeout": 10000,
"keepalive": 60000,
"queue_size": 1,
"retry_count": 10,
"content_type": "application/json",
"flush_timeout": 2,
"http_endpoint": "http://127.0.0.1:8081",
"custom_fields_by_lua": null
}
// One header defined with one value.
//
// v2.8 plugin config:
{
"method": "POST",
"headers": {
"some-header": [
"test1"
]
},
"timeout": 10000,
"keepalive": 60000,
"queue_size": 1,
"retry_count": 10,
"content_type": "application/json",
"flush_timeout": 2,
"http_endpoint": "http://127.0.0.1:8081",
"custom_fields_by_lua": null
}
// v3.0 plugin config:
{
"method": "POST",
"headers": {
"some-header": "test1"
},
"timeout": 10000,
"keepalive": 60000,
"queue_size": 1,
"retry_count": 10,
"content_type": "application/json",
"flush_timeout": 2,
"http_endpoint": "http://127.0.0.1:8081",
"custom_fields_by_lua": null
}
// One header defined with no value.
//
// v2.8 plugin config:
{
"method": "POST",
"headers": {
"some-header": {}
},
"timeout": 10000,
"keepalive": 60000,
"queue_size": 1,
"retry_count": 10,
"content_type": "application/json",
"flush_timeout": 2,
"http_endpoint": "http://127.0.0.1:8081",
"custom_fields_by_lua": null
}
// v3.0 plugin config:
{
"method": "POST",
"headers": null,
"timeout": 10000,
"keepalive": 60000,
"queue_size": 1,
"retry_count": 10,
"content_type": "application/json",
"flush_timeout": 2,
"http_endpoint": "http://127.0.0.1:8081",
"custom_fields_by_lua": null
}
// One header defined with one value, another with no value.
//
// v2.8 plugin config:
{
"method": "POST",
"headers": {
"some-header": {},
"another-header": [
"test1"
]
},
"timeout": 10000,
"keepalive": 60000,
"queue_size": 1,
"retry_count": 10,
"content_type": "application/json",
"flush_timeout": 2,
"http_endpoint": "http://127.0.0.1:8081",
"custom_fields_by_lua": null
}
// v3.0 plugin config:
{
"method": "POST",
"headers": {
"another-header": "test1"
},
"timeout": 10000,
"keepalive": 60000,
"queue_size": 1,
"retry_count": 10,
"content_type": "application/json",
"flush_timeout": 2,
"http_endpoint": "http://127.0.0.1:8081",
"custom_fields_by_lua": null
}
// No headers defined.
//
// v2.8 plugin config:
{
"method": "POST",
"headers": null,
"timeout": 10000,
"keepalive": 60000,
"queue_size": 1,
"retry_count": 10,
"content_type": "application/json",
"flush_timeout": 2,
"http_endpoint": "http://127.0.0.1:8081",
"custom_fields_by_lua": null
}
// v3.0 plugin config:
{
"method": "POST",
"headers": null,
"timeout": 10000,
"keepalive": 60000,
"queue_size": 1,
"retry_count": 10,
"content_type": "application/json",
"flush_timeout": 2,
"http_endpoint": "http://127.0.0.1:8081",
"custom_fields_by_lua": null
}
```
|
Lua
|
apache-2.0
|
Kong/kong,Kong/kong,Kong/kong
|
bba762a27a6985c51e2240d4f6e3ca4c20f826fb
|
kong/plugins/datadog/schema.lua
|
kong/plugins/datadog/schema.lua
|
local typedefs = require "kong.db.schema.typedefs"
local STAT_NAMES = {
"kong_latency",
"latency",
"request_count",
"request_size",
"response_size",
"upstream_latency",
}
local STAT_TYPES = {
"counter",
"gauge",
"histogram",
"meter",
"set",
"timer",
"distribution",
}
local CONSUMER_IDENTIFIERS = {
"consumer_id",
"custom_id",
"username",
}
local DEFAULT_METRICS = {
{
name = "request_count",
stat_type = "counter",
sample_rate = 1,
tags = {"app:kong" },
consumer_identifier = "custom_id"
},
{
name = "latency",
stat_type = "timer",
tags = {"app:kong"},
consumer_identifier = "custom_id"
},
{
name = "request_size",
stat_type = "timer",
tags = {"app:kong"},
consumer_identifier = "custom_id"
},
{
name = "response_size",
stat_type = "timer",
tags = {"app:kong"},
consumer_identifier = "custom_id"
},
{
name = "upstream_latency",
stat_type = "timer",
tags = {"app:kong"},
consumer_identifier = "custom_id"
},
{
name = "kong_latency",
stat_type = "timer",
tags = {"app:kong"},
consumer_identifier = "custom_id"
},
}
return {
name = "datadog",
fields = {
{ protocols = typedefs.protocols },
{ config = {
type = "record",
default = { metrics = DEFAULT_METRICS },
fields = {
{ host = typedefs.host({ default = "localhost" }), },
{ port = typedefs.port({ default = 8125 }), },
{ prefix = { type = "string", default = "kong" }, },
{ service_name_tag = { type = "string", default = "name" }, },
{ status_tag = { type = "string", default = "status" }, },
{ consumer_tag = { type = "string", default = "consumer" }, },
{ metrics = {
type = "array",
required = true,
default = DEFAULT_METRICS,
elements = {
type = "record",
fields = {
{ name = { type = "string", required = true, one_of = STAT_NAMES }, },
{ stat_type = { type = "string", required = true, one_of = STAT_TYPES }, },
{ tags = { type = "array", elements = { type = "string", match = "^.*[^:]$" }, }, },
{ sample_rate = { type = "number", between = { 0, 1 }, }, },
{ consumer_identifier = { type = "string", one_of = CONSUMER_IDENTIFIERS }, },
},
entity_checks = {
{ conditional = {
if_field = "stat_type",
if_match = { one_of = { "counter", "gauge" }, },
then_field = "sample_rate",
then_match = { required = true },
}, }, }, }, }, },
},
},
},
},
}
|
local typedefs = require "kong.db.schema.typedefs"
local STAT_NAMES = {
"kong_latency",
"latency",
"request_count",
"request_size",
"response_size",
"upstream_latency",
}
local STAT_TYPES = {
"counter",
"gauge",
"histogram",
"meter",
"set",
"timer",
"distribution",
}
local CONSUMER_IDENTIFIERS = {
"consumer_id",
"custom_id",
"username",
}
local DEFAULT_METRICS = {
{
name = "request_count",
stat_type = "counter",
sample_rate = 1,
tags = {"app:kong" },
consumer_identifier = "custom_id"
},
{
name = "latency",
stat_type = "timer",
tags = {"app:kong"},
consumer_identifier = "custom_id"
},
{
name = "request_size",
stat_type = "timer",
tags = {"app:kong"},
consumer_identifier = "custom_id"
},
{
name = "response_size",
stat_type = "timer",
tags = {"app:kong"},
consumer_identifier = "custom_id"
},
{
name = "upstream_latency",
stat_type = "timer",
tags = {"app:kong"},
consumer_identifier = "custom_id"
},
{
name = "kong_latency",
stat_type = "timer",
tags = {"app:kong"},
consumer_identifier = "custom_id"
},
}
return {
name = "datadog",
fields = {
{ protocols = typedefs.protocols },
{ config = {
type = "record",
fields = {
{ host = typedefs.host({ default = "localhost" }), },
{ port = typedefs.port({ default = 8125 }), },
{ prefix = { type = "string", default = "kong" }, },
{ service_name_tag = { type = "string", default = "name" }, },
{ status_tag = { type = "string", default = "status" }, },
{ consumer_tag = { type = "string", default = "consumer" }, },
{ metrics = {
type = "array",
required = true,
default = DEFAULT_METRICS,
elements = {
type = "record",
fields = {
{ name = { type = "string", required = true, one_of = STAT_NAMES }, },
{ stat_type = { type = "string", required = true, one_of = STAT_TYPES }, },
{ tags = { type = "array", elements = { type = "string", match = "^.*[^:]$" }, }, },
{ sample_rate = { type = "number", between = { 0, 1 }, }, },
{ consumer_identifier = { type = "string", one_of = CONSUMER_IDENTIFIERS }, },
},
entity_checks = {
{ conditional = {
if_field = "stat_type",
if_match = { one_of = { "counter", "gauge" }, },
then_field = "sample_rate",
then_match = { required = true },
}, }, }, }, }, },
},
},
},
},
}
|
fix(datadog) default value for metrics specified twice (#8315)
|
fix(datadog) default value for metrics specified twice (#8315)
|
Lua
|
apache-2.0
|
Kong/kong,Kong/kong,Kong/kong
|
dff5065fcb90ad8310d298c26bd1a4fb98f4e929
|
lua/entities/gmod_wire_latch.lua
|
lua/entities/gmod_wire_latch.lua
|
AddCSLuaFile()
DEFINE_BASECLASS( "base_wire_entity" )
ENT.PrintName = "Wire Constraint Latch"
ENT.Purpose = "Controllable weld and nocollide between two selected entities"
ENT.WireDebugName = "Latch"
if CLIENT then return end -- No more client
function ENT:Initialize()
self:PhysicsInit( SOLID_VPHYSICS )
self:SetMoveType( MOVETYPE_VPHYSICS )
self:SetSolid( SOLID_VPHYSICS )
self.Inputs = Wire_CreateInputs( self, { "Activate", "NoCollide", "Strength" } )
self.Outputs = Wire_CreateOutputs( self, { "Welded" } )
-- masks containing all current states
self.nocollide_masks = {
-- Ent1, Ent2 , nocollide between the two
{ false, false, true }, -- 1 nocollide between the two
{ true , false, false }, -- 2 nocollide Ent1 with all
{ false, true , false }, -- 3 nocollide Ent2 with all
{ true , true , false } -- 4 nocollide both with all
-- all other values: { false, false, false }
}
self.nocollide_description = {
"NoCollided",
"Ent1 has collisions disabled",
"Ent2 has collisions disabled",
"All collisions disabled"
}
self.Nocollide = nil
self:TriggerInput("NoCollide", 0)
self.IsPasting = false
end
-- Run if weld is removed (will run *after* Create_Weld)
local function Weld_Removed( weld, ent )
if IsValid(ent) then
if !ent.Constraint or ent.Constraint == weld then
ent.Constraint = nil
Wire_TriggerOutput( ent, "Welded", 0 )
ent:UpdateOverlay()
end
end
end
function ENT:Remove_Weld()
if self.IsPasting then self.ConstrainAfterDupe = nil return end
if self.Constraint then
if self.Constraint:IsValid() then
self.Constraint:Remove()
end
self.Constraint = nil
end
end
function ENT:Create_Weld()
if self.IsPasting then self.ConstrainAfterDupe = true return end
self:Remove_Weld()
self.Constraint = MakeWireLatch( self.Ent1, self.Ent2, self.Bone1, self.Bone2, self.weld_strength or 0 )
if self.Constraint then
self.Constraint:CallOnRemove( "Weld Latch Removed", Weld_Removed, self )
end
end
-- This function is called by the STOOL
function ENT:SendVars( Ent1, Ent2, Bone1, Bone2, const )
self.Ent1 = Ent1
self.Ent2 = Ent2
self.Bone1 = Bone1
self.Bone2 = Bone2
self.Constraint = const
end
function ENT:TriggerInput( iname, value )
if iname == "Activate" then
if value == 0 then
self:Remove_Weld()
elseif not self.Constraint then
self:Create_Weld()
Wire_TriggerOutput( self, "Welded", 1 )
end
elseif iname == "NoCollide" then
self.nocollide_status = value
local mask = self.nocollide_masks[value] or {false, false, false}
if IsValid( self.Ent1 ) then
local phys = self.Ent1:GetPhysicsObject()
if phys:IsValid() then phys:EnableCollisions(not mask[1]) end
end
if IsValid( self.Ent2 ) then
local phys = self.Ent2:GetPhysicsObject()
if phys:IsValid() then phys:EnableCollisions(not mask[2]) end
end
if mask[3] then
if not self.Nocollide then
if self.Ent1 and self.Ent2 then
-- enable NoCollide between the two entities
self.Nocollide = constraint.NoCollide( self.Ent1, self.Ent2, self.Bone1, self.Bone2 )
end
end
else
if self.Nocollide then
if self.Nocollide:IsValid() then
-- disable NoCollide between the two entities
self.Nocollide:Input("EnableCollisions", nil, nil, nil)
self.Nocollide:Remove()
end
self.Nocollide = nil
end
end
elseif iname == "Strength" then
local newvalue = math.max( value, 0 )
if newvalue ~= self.weld_strength then
self.weld_strength = newvalue
if self.Constraint then
self:Create_Weld()
end
end
end
self:UpdateOverlay()
end
function ENT:OnRemove()
self:TriggerInput("Activate", 0)
self:TriggerInput("NoCollide", 0)
end
function ENT:UpdateOverlay()
local desc = self.nocollide_description[self.nocollide_status]
if not desc then
if IsValid( self.Constraint ) then
self:SetOverlayText( "Welded" )
else
self:SetOverlayText( "Deactivated" )
end
return
end
local text = self.Constraint and "Welded and " or "Not welded but "
text = text .. desc
self:SetOverlayText( text )
end
-- duplicator support
function ENT:BuildDupeInfo()
local info = BaseClass.BuildDupeInfo(self) or {}
if IsValid( self.Ent1 ) then
info.Ent1 = self.Ent1:EntIndex()
info.Bone1 = self.Bone1
end
if IsValid( self.Ent2 ) then
info.Ent2 = self.Ent2:EntIndex()
info.Bone2 = self.Bone2
end
info.Activate = self.Constraint and 1 or 0
info.NoCollide = self.nocollide_status
info.weld_strength = self.weld_strength
return info
end
function ENT:ApplyDupeInfo(ply, ent, info, GetEntByID)
BaseClass.ApplyDupeInfo(self, ply, ent, info, GetEntByID)
self.Ent1 = GetEntByID(info.Ent1, game.GetWorld())
if IsValid(self.Ent1) then
self.Bone1 = info.Bone1
end
self.Ent2 = GetEntByID(info.Ent2, game.GetWorld())
if IsValid(self.Ent2) then
self.Bone2 = info.Bone2
end
self.IsPasting = true
self:TriggerInput("Strength", info.weld_strength or 0)
self:TriggerInput("Activate", info.Activate)
self:TriggerInput("NoCollide", info.NoCollide)
end
hook.Add("AdvDupe_FinishPasting", "Wire_Latch", function(TimedPasteData, TimedPasteDataCurrent)
for k, v in pairs(TimedPasteData[TimedPasteDataCurrent].CreatedEntities) do
if IsValid(v) and v:GetClass() == "gmod_wire_latch" then
v.IsPasting = false
if v.ConstrainAfterDupe then
v:TriggerInput("Activate", 1)
end
end
end
end)
duplicator.RegisterEntityClass("gmod_wire_latch", WireLib.MakeWireEnt, "Data")
function MakeWireLatch( Ent1, Ent2, Bone1, Bone2, forcelimit )
if ( !constraint.CanConstrain( Ent1, Bone1 ) ) then return false end
if ( !constraint.CanConstrain( Ent2, Bone2 ) ) then return false end
local Phys1 = Ent1:GetPhysicsObjectNum( Bone1 )
local Phys2 = Ent2:GetPhysicsObjectNum( Bone2 )
if ( Phys1 == Phys2 ) then return false end
local const = constraint.Weld( Ent1, Ent2, Bone1, Bone2, forcelimit or 0 )
if !IsValid(const) then return nil end
const.Type = "" -- prevents the duplicator from copying this weld
return const
end
|
AddCSLuaFile()
DEFINE_BASECLASS( "base_wire_entity" )
ENT.PrintName = "Wire Constraint Latch"
ENT.Purpose = "Controllable weld and nocollide between two selected entities"
ENT.WireDebugName = "Latch"
if CLIENT then return end -- No more client
function ENT:Initialize()
self:PhysicsInit( SOLID_VPHYSICS )
self:SetMoveType( MOVETYPE_VPHYSICS )
self:SetSolid( SOLID_VPHYSICS )
self.Inputs = Wire_CreateInputs( self, { "Activate", "NoCollide", "Strength" } )
self.Outputs = Wire_CreateOutputs( self, { "Welded" } )
-- masks containing all current states
self.nocollide_masks = {
-- Ent1, Ent2 , nocollide between the two
{ false, false, true }, -- 1 nocollide between the two
{ true , false, false }, -- 2 nocollide Ent1 with all
{ false, true , false }, -- 3 nocollide Ent2 with all
{ true , true , false } -- 4 nocollide both with all
-- all other values: { false, false, false }
}
self.nocollide_description = {
"NoCollided",
"Ent1 has collisions disabled",
"Ent2 has collisions disabled",
"All collisions disabled"
}
self.Nocollide = nil
self:TriggerInput("NoCollide", 0)
end
-- Run if weld is removed (will run *after* Create_Weld)
local function Weld_Removed( weld, ent )
if IsValid(ent) then
if !ent.Constraint or ent.Constraint == weld then
ent.Constraint = nil
Wire_TriggerOutput( ent, "Welded", 0 )
ent:UpdateOverlay()
end
end
end
function ENT:Remove_Weld()
if self.Constraint then
if self.Constraint:IsValid() then
self.Constraint:Remove()
end
self.Constraint = nil
end
end
function ENT:Create_Weld()
self:Remove_Weld()
self.Constraint = MakeWireLatch( self.Ent1, self.Ent2, self.Bone1, self.Bone2, self.weld_strength or 0 )
if self.Constraint then
self.Constraint:CallOnRemove( "Weld Latch Removed", Weld_Removed, self )
end
end
-- This function is called by the STOOL
function ENT:SendVars( Ent1, Ent2, Bone1, Bone2, const )
self.Ent1 = Ent1
self.Ent2 = Ent2
self.Bone1 = Bone1
self.Bone2 = Bone2
self.Constraint = const
end
function ENT:TriggerInput( iname, value )
if iname == "Activate" then
if value == 0 and self.Constraint then
self:Remove_Weld()
elseif value ~= 0 and not self.Constraint then
self:Create_Weld()
Wire_TriggerOutput( self, "Welded", 1 )
end
elseif iname == "NoCollide" then
self.nocollide_status = value
local mask = self.nocollide_masks[value] or {false, false, false}
if IsValid( self.Ent1 ) then
local phys = self.Ent1:GetPhysicsObject()
if phys:IsValid() then phys:EnableCollisions(not mask[1]) end
end
if IsValid( self.Ent2 ) then
local phys = self.Ent2:GetPhysicsObject()
if phys:IsValid() then phys:EnableCollisions(not mask[2]) end
end
if mask[3] then
if not self.Nocollide then
if self.Ent1 and self.Ent2 then
-- enable NoCollide between the two entities
self.Nocollide = constraint.NoCollide( self.Ent1, self.Ent2, self.Bone1, self.Bone2 )
end
end
else
if self.Nocollide then
if self.Nocollide:IsValid() then
-- disable NoCollide between the two entities
self.Nocollide:Input("EnableCollisions", nil, nil, nil)
self.Nocollide:Remove()
end
self.Nocollide = nil
end
end
elseif iname == "Strength" then
local newvalue = math.max( value, 0 )
if newvalue ~= self.weld_strength then
self.weld_strength = newvalue
if self.Constraint then
self:Create_Weld()
end
end
end
self:UpdateOverlay()
end
function ENT:OnRemove()
self:TriggerInput("Activate", 0)
self:TriggerInput("NoCollide", 0)
end
function ENT:UpdateOverlay()
local desc = self.nocollide_description[self.nocollide_status]
if not desc then
if IsValid( self.Constraint ) then
self:SetOverlayText( "Welded" )
else
self:SetOverlayText( "Deactivated" )
end
return
end
local text = self.Constraint and "Welded and " or "Not welded but "
text = text .. desc
self:SetOverlayText( text )
end
-- duplicator support
function ENT:BuildDupeInfo()
local info = BaseClass.BuildDupeInfo(self) or {}
if IsValid( self.Ent1 ) then
info.Ent1 = self.Ent1:EntIndex()
info.Bone1 = self.Bone1
end
if IsValid( self.Ent2 ) then
info.Ent2 = self.Ent2:EntIndex()
info.Bone2 = self.Bone2
end
info.Activate = self.Constraint and 1 or 0
info.NoCollide = self.nocollide_status
info.weld_strength = self.weld_strength
return info
end
function ENT:ApplyDupeInfo(ply, ent, info, GetEntByID)
BaseClass.ApplyDupeInfo(self, ply, ent, info, GetEntByID)
self.Ent1 = GetEntByID(info.Ent1, game.GetWorld())
if IsValid(self.Ent1) then
self.Bone1 = info.Bone1
end
self.Ent2 = GetEntByID(info.Ent2, game.GetWorld())
if IsValid(self.Ent2) then
self.Bone2 = info.Bone2
end
self:TriggerInput("Strength", info.weld_strength or 0)
self:TriggerInput("Activate", info.Activate)
self:TriggerInput("NoCollide", info.NoCollide)
end
duplicator.RegisterEntityClass("gmod_wire_latch", WireLib.MakeWireEnt, "Data")
function MakeWireLatch( Ent1, Ent2, Bone1, Bone2, forcelimit )
if ( !constraint.CanConstrain( Ent1, Bone1 ) ) then return false end
if ( !constraint.CanConstrain( Ent2, Bone2 ) ) then return false end
local Phys1 = Ent1:GetPhysicsObjectNum( Bone1 )
local Phys2 = Ent2:GetPhysicsObjectNum( Bone2 )
if ( Phys1 == Phys2 ) then return false end
local const = constraint.Weld( Ent1, Ent2, Bone1, Bone2, forcelimit or 0 )
if !IsValid(const) then return nil end
const.Type = "" -- prevents the duplicator from copying this weld
return const
end
|
Revert "Merge pull request #1826 from thegrb93/fix-latch-running-too-soon"
|
Revert "Merge pull request #1826 from thegrb93/fix-latch-running-too-soon"
This reverts commit eb4194e52c3b3aaafbeafdd1a42fac9de6529870, reversing
changes made to 121f0ff3f1ccc1579d311a79d3878d21861edfe3.
|
Lua
|
apache-2.0
|
NezzKryptic/Wire,garrysmodlua/wire,wiremod/wire,dvdvideo1234/wire,sammyt291/wire,Grocel/wire
|
9697aee2b99cdc95e35c87d9ae561f669dda0633
|
kong/plugins/oauth2/migrations/001_14_to_15.lua
|
kong/plugins/oauth2/migrations/001_14_to_15.lua
|
return {
postgres = {
up = [[
DO $$
BEGIN
ALTER TABLE IF EXISTS ONLY "oauth2_credentials" ADD "redirect_uris" TEXT[];
EXCEPTION WHEN DUPLICATE_COLUMN THEN
-- Do nothing, accept existing state
END$$;
DO $$
BEGIN
UPDATE "oauth2_credentials"
SET "redirect_uris" = TRANSLATE("redirect_uri", '[]', '{}')::TEXT[];
EXCEPTION WHEN UNDEFINED_COLUMN THEN
-- Do nothing, accept existing state
END$$;
DO $$
BEGIN
ALTER TABLE IF EXISTS ONLY "oauth2_authorization_codes" ADD "ttl" TIMESTAMP WITH TIME ZONE;
EXCEPTION WHEN DUPLICATE_COLUMN THEN
-- Do nothing, accept existing state
END$$;
UPDATE "oauth2_authorization_codes"
SET "ttl" = "created_at" + INTERVAL '300 seconds';
DO $$
BEGIN
ALTER TABLE IF EXISTS ONLY "oauth2_tokens" ADD "ttl" TIMESTAMP WITH TIME ZONE;
EXCEPTION WHEN DUPLICATE_COLUMN THEN
-- Do nothing, accept existing state
END$$;
UPDATE "oauth2_tokens"
SET "ttl" = "created_at" + (COALESCE("expires_in", 0)::TEXT || ' seconds')::INTERVAL;
ALTER TABLE IF EXISTS ONLY "oauth2_credentials"
ALTER "created_at" TYPE TIMESTAMP WITH TIME ZONE USING "created_at" AT TIME ZONE 'UTC',
ALTER "created_at" SET DEFAULT CURRENT_TIMESTAMP(0) AT TIME ZONE 'UTC';
ALTER TABLE IF EXISTS ONLY "oauth2_authorization_codes"
ALTER "created_at" TYPE TIMESTAMP WITH TIME ZONE USING "created_at" AT TIME ZONE 'UTC',
ALTER "created_at" SET DEFAULT CURRENT_TIMESTAMP(0) AT TIME ZONE 'UTC';
ALTER TABLE IF EXISTS ONLY "oauth2_tokens"
ALTER "created_at" TYPE TIMESTAMP WITH TIME ZONE USING "created_at" AT TIME ZONE 'UTC',
ALTER "created_at" SET DEFAULT CURRENT_TIMESTAMP(0) AT TIME ZONE 'UTC';
CREATE INDEX IF NOT EXISTS "oauth2_authorization_credential_id_idx" ON "oauth2_authorization_codes" ("credential_id");
CREATE INDEX IF NOT EXISTS "oauth2_authorization_service_id_idx" ON "oauth2_authorization_codes" ("service_id");
CREATE INDEX IF NOT EXISTS "oauth2_authorization_api_id_idx" ON "oauth2_authorization_codes" ("api_id");
CREATE INDEX IF NOT EXISTS "oauth2_tokens_credential_id_idx" ON "oauth2_tokens" ("credential_id");
CREATE INDEX IF NOT EXISTS "oauth2_tokens_service_id_idx" ON "oauth2_tokens" ("service_id");
CREATE INDEX IF NOT EXISTS "oauth2_tokens_api_id_idx" ON "oauth2_tokens" ("api_id");
DO $$
BEGIN
ALTER INDEX IF EXISTS "oauth2_credentials_consumer_idx" RENAME TO "oauth2_credentials_consumer_id_idx";
EXCEPTION WHEN DUPLICATE_TABLE THEN
-- Do nothing, accept existing state
END;
$$;
DO $$
BEGIN
ALTER INDEX IF EXISTS "oauth2_authorization_userid_idx" RENAME TO "oauth2_authorization_codes_authenticated_userid_idx";
EXCEPTION WHEN DUPLICATE_TABLE THEN
-- Do nothing, accept existing state
END;
$$;
DO $$
BEGIN
ALTER INDEX IF EXISTS "oauth2_token_userid_idx" RENAME TO "oauth2_tokens_authenticated_userid_idx";
EXCEPTION WHEN DUPLICATE_TABLE THEN
-- Do nothing, accept existing state
END;
$$;
-- Unique constraint on "client_id" already adds btree index
DROP INDEX IF EXISTS "oauth2_credentials_client_idx";
-- Unique constraint on "code" already adds btree index
DROP INDEX IF EXISTS "oauth2_autorization_code_idx";
-- Unique constraint on "access_token" already adds btree index
DROP INDEX IF EXISTS "oauth2_accesstoken_idx";
-- Unique constraint on "refresh_token" already adds btree index
DROP INDEX IF EXISTS "oauth2_token_refresh_idx";
]],
teardown = function(connector)
assert(connector:connect_migrations())
assert(connector:query [[
DO $$
BEGIN
ALTER TABLE IF EXISTS ONLY "oauth2_credentials" DROP "redirect_uri";
EXCEPTION WHEN UNDEFINED_COLUMN THEN
-- Do nothing, accept existing state
END$$;
]])
end,
},
cassandra = {
up = [[
ALTER TABLE oauth2_credentials ADD redirect_uris set<text>;
]],
teardown = function(connector)
local cjson = require "cjson"
local coordinator = assert(connector:connect_migrations())
for rows, err in coordinator:iterate([[
SELECT id, redirect_uri FROM oauth2_credentials]]) do
if err then
return nil, err
end
for _, row in ipairs(rows) do
if row.redirect_uri then
local uris = cjson.decode(row.redirect_uri)
local buffer = {}
for i, uri in ipairs(uris) do
buffer[i] = "'" .. uri .. "'"
end
local q = string.format([[
UPDATE oauth2_credentials
SET redirect_uris = {%s} WHERE id = %s
]], table.concat(buffer, ","), row.id)
assert(connector:query(q))
end
end
end
assert(connector:query([[
ALTER TABLE oauth2_credentials DROP redirect_uri
]]))
end,
},
}
|
return {
postgres = {
up = [[
DO $$
BEGIN
ALTER TABLE IF EXISTS ONLY "oauth2_credentials" ADD "redirect_uris" TEXT[];
EXCEPTION WHEN DUPLICATE_COLUMN THEN
-- Do nothing, accept existing state
END$$;
DO $$
BEGIN
UPDATE "oauth2_credentials"
SET "redirect_uris" = TRANSLATE("redirect_uri", '[]', '{}')::TEXT[];
EXCEPTION WHEN UNDEFINED_COLUMN THEN
-- Do nothing, accept existing state
END$$;
DO $$
BEGIN
ALTER TABLE IF EXISTS ONLY "oauth2_authorization_codes" ADD "ttl" TIMESTAMP WITH TIME ZONE;
EXCEPTION WHEN DUPLICATE_COLUMN THEN
-- Do nothing, accept existing state
END$$;
UPDATE "oauth2_authorization_codes"
SET "ttl" = "created_at" + INTERVAL '300 seconds';
DO $$
BEGIN
ALTER TABLE IF EXISTS ONLY "oauth2_tokens" ADD "ttl" TIMESTAMP WITH TIME ZONE;
EXCEPTION WHEN DUPLICATE_COLUMN THEN
-- Do nothing, accept existing state
END$$;
UPDATE "oauth2_tokens"
SET "ttl" = "created_at" + ("expires_in"::TEXT || ' seconds')::INTERVAL
WHERE "expires_in" > 0;
ALTER TABLE IF EXISTS ONLY "oauth2_credentials"
ALTER "created_at" TYPE TIMESTAMP WITH TIME ZONE USING "created_at" AT TIME ZONE 'UTC',
ALTER "created_at" SET DEFAULT CURRENT_TIMESTAMP(0) AT TIME ZONE 'UTC';
ALTER TABLE IF EXISTS ONLY "oauth2_authorization_codes"
ALTER "created_at" TYPE TIMESTAMP WITH TIME ZONE USING "created_at" AT TIME ZONE 'UTC',
ALTER "created_at" SET DEFAULT CURRENT_TIMESTAMP(0) AT TIME ZONE 'UTC';
ALTER TABLE IF EXISTS ONLY "oauth2_tokens"
ALTER "created_at" TYPE TIMESTAMP WITH TIME ZONE USING "created_at" AT TIME ZONE 'UTC',
ALTER "created_at" SET DEFAULT CURRENT_TIMESTAMP(0) AT TIME ZONE 'UTC';
CREATE INDEX IF NOT EXISTS "oauth2_authorization_credential_id_idx" ON "oauth2_authorization_codes" ("credential_id");
CREATE INDEX IF NOT EXISTS "oauth2_authorization_service_id_idx" ON "oauth2_authorization_codes" ("service_id");
CREATE INDEX IF NOT EXISTS "oauth2_authorization_api_id_idx" ON "oauth2_authorization_codes" ("api_id");
CREATE INDEX IF NOT EXISTS "oauth2_tokens_credential_id_idx" ON "oauth2_tokens" ("credential_id");
CREATE INDEX IF NOT EXISTS "oauth2_tokens_service_id_idx" ON "oauth2_tokens" ("service_id");
CREATE INDEX IF NOT EXISTS "oauth2_tokens_api_id_idx" ON "oauth2_tokens" ("api_id");
DO $$
BEGIN
ALTER INDEX IF EXISTS "oauth2_credentials_consumer_idx" RENAME TO "oauth2_credentials_consumer_id_idx";
EXCEPTION WHEN DUPLICATE_TABLE THEN
-- Do nothing, accept existing state
END;
$$;
DO $$
BEGIN
ALTER INDEX IF EXISTS "oauth2_authorization_userid_idx" RENAME TO "oauth2_authorization_codes_authenticated_userid_idx";
EXCEPTION WHEN DUPLICATE_TABLE THEN
-- Do nothing, accept existing state
END;
$$;
DO $$
BEGIN
ALTER INDEX IF EXISTS "oauth2_token_userid_idx" RENAME TO "oauth2_tokens_authenticated_userid_idx";
EXCEPTION WHEN DUPLICATE_TABLE THEN
-- Do nothing, accept existing state
END;
$$;
-- Unique constraint on "client_id" already adds btree index
DROP INDEX IF EXISTS "oauth2_credentials_client_idx";
-- Unique constraint on "code" already adds btree index
DROP INDEX IF EXISTS "oauth2_autorization_code_idx";
-- Unique constraint on "access_token" already adds btree index
DROP INDEX IF EXISTS "oauth2_accesstoken_idx";
-- Unique constraint on "refresh_token" already adds btree index
DROP INDEX IF EXISTS "oauth2_token_refresh_idx";
]],
teardown = function(connector)
assert(connector:connect_migrations())
assert(connector:query [[
DO $$
BEGIN
ALTER TABLE IF EXISTS ONLY "oauth2_credentials" DROP "redirect_uri";
EXCEPTION WHEN UNDEFINED_COLUMN THEN
-- Do nothing, accept existing state
END$$;
]])
end,
},
cassandra = {
up = [[
ALTER TABLE oauth2_credentials ADD redirect_uris set<text>;
]],
teardown = function(connector)
local cjson = require "cjson"
local coordinator = assert(connector:connect_migrations())
for rows, err in coordinator:iterate([[
SELECT id, redirect_uri FROM oauth2_credentials]]) do
if err then
return nil, err
end
for _, row in ipairs(rows) do
if row.redirect_uri then
local uris = cjson.decode(row.redirect_uri)
local buffer = {}
for i, uri in ipairs(uris) do
buffer[i] = "'" .. uri .. "'"
end
local q = string.format([[
UPDATE oauth2_credentials
SET redirect_uris = {%s} WHERE id = %s
]], table.concat(buffer, ","), row.id)
assert(connector:query(q))
end
end
end
assert(connector:query([[
ALTER TABLE oauth2_credentials DROP redirect_uri
]]))
end,
},
}
|
fix(migrations) fix migration of not-expiring ttls in oauth2 tokens (#4588)
|
fix(migrations) fix migration of not-expiring ttls in oauth2 tokens (#4588)
Fixes an issue reported at #4572, where migrations could set a 0 ttl for oauth2_tokens that have never expiring 0 tokens, leading to deletion of such tokens.
Fixes #4572.
|
Lua
|
apache-2.0
|
Kong/kong,Mashape/kong,Kong/kong,Kong/kong
|
08c4139c65b9d297c022619fdda37482bc107886
|
test/autobahn_server_test.lua
|
test/autobahn_server_test.lua
|
local uv = require "lluv"
local websocket = require "lluv.websocket"
local Autobahn = require "./autobahn"
websocket.deflate = require "lluv.websocket.extensions.permessage-deflate"
local ctx do
local ok, ssl = pcall(require, "lluv.ssl")
if ok then
ctx = assert(ssl.context{
protocol = "tlsv1",
key = "./wss/server.key",
certificate = "./wss/server.crt",
})
end
end
local reportDir = "./reports/servers"
local url = arg[1] or "ws://127.0.0.1:9000"
local agent = string.format("lluv-websocket (%s / %s)",
jit and jit.version or _VERSION,
url:lower():match("^wss:") and "WSS" or "WS"
)
local exitCode = -1
local read_pat = arg[2] or "*s"
local decode_mode = arg[3] or "pos"
local verbose = false
local config = {
outdir = reportDir,
servers = {
{ agent = agent, url = url},
},
-- cases = {"9.*"}, -- perfomance
cases = {"1.*", "2.*", "3.*", "4.*", "5.*", "6.*", "6.2.*", "7.*","10.*","12.1.1"},
["exclude-cases"] = {"6.4.2", "6.4.3", "6.4.4"},
["exclude-agent-cases"] = {},
}
if os.getenv('TRAVIS') == 'true' then
-- wstest 0.7.1
----
-- it takes too long to execute this test on Travis
-- so wstest start next test `7.3.1` and get handshake timeout
-- and it fails
table.insert(config["exclude-cases"], "7.1.6")
end
if read_pat == '*f' then
-- wstest 0.7.1
----
-- Remote side detect invalid utf8 earlier than me
-- Problem in ut8 validator which detect it too late
--
table.insert(config["exclude-cases"], "6.3.2")
end
function wstest(args, cb)
return uv.spawn({
file = "wstest",
args = args,
stdio = {{}, verbose and 1 or {}, verbose and 2 or {}}
}, function(handle, err, status, signal)
handle:close()
if err then error("Error spawn:" .. tostring(err)) end
cb(status, signal)
end)
end
function isWSEOF(err)
return err:name() == 'EOF' and err.cat and err:cat() == 'WEBSOCKET'
end
function runTest(cb)
print(" URL:", url)
print("MODE:", read_pat .. "/" .. decode_mode)
local currentCaseId = 0
local server = websocket.new{ssl = ctx, utf8 = true}
server:register(websocket.deflate)
server:bind(url, "echo", function(self, err)
if err then
print("Server error:", err)
return server:close()
end
wstest({"-m" ,"fuzzingclient", "-s", "fuzzingclient.json"}, function(code, status)
server:close(function()
cb(code, status)
end)
end)
server:listen(function(self, err)
if err then
print("Server listen:", err)
return server:close()
end
local cli = server:accept()
if decode_mode == "chunk" then
cli._on_raw_data = assert(websocket.__on_raw_data_by_chunk)
end
currentCaseId = currentCaseId + 1
if verbose then
print("Handshake test case " .. tostring(currentCaseId))
end
cli:handshake(function(self, err, protocol)
if err then
print("Server handshake error:", err)
return cli:close()
end
print("Executing test case " .. tostring(currentCaseId))
cli:start_read(read_pat, function(self, err, message, opcode, fin)
if err then
if not isWSEOF(err) then
print("Server read error:", err)
end
return cli:close()
end
if opcode == websocket.CONTINUATION or opcode == websocket.TEXT or opcode == websocket.BINARY then
cli:write(message, opcode, fin)
end
end)
end)
end)
end)
end
Autobahn.cleanReports(reportDir)
Autobahn.Utils.writeJson("fuzzingclient.json", config)
runTest(function()
if not Autobahn.verifyReport(reportDir, agent, true) then
exitCode = -1
else
exitCode = 0
end
print"DONE"
end)
uv.run()
os.exit(exitCode)
|
local uv = require "lluv"
local websocket = require "lluv.websocket"
local Autobahn = require "./autobahn"
deflate = require "websocket.extensions.permessage-deflate"
local ctx do
local ok, ssl = pcall(require, "lluv.ssl")
if ok then
ctx = assert(ssl.context{
protocol = "tlsv1",
key = "./wss/server.key",
certificate = "./wss/server.crt",
})
end
end
local reportDir = "./reports/servers"
local url = arg[1] or "ws://127.0.0.1:9000"
local agent = string.format("lluv-websocket (%s / %s)",
jit and jit.version or _VERSION,
url:lower():match("^wss:") and "WSS" or "WS"
)
local exitCode = -1
local read_pat = arg[2] or "*s"
local decode_mode = arg[3] or "pos"
local verbose = false
local config = {
outdir = reportDir,
servers = {
{ agent = agent, url = url},
},
-- cases = {"9.*"}, -- perfomance
cases = {"1.*", "2.*", "3.*", "4.*", "5.*", "6.*", "6.2.*", "7.*","10.*","12.1.1"},
["exclude-cases"] = {"6.4.2", "6.4.3", "6.4.4"},
["exclude-agent-cases"] = {},
}
if os.getenv('TRAVIS') == 'true' then
-- wstest 0.7.1
----
-- it takes too long to execute this test on Travis
-- so wstest start next test `7.3.1` and get handshake timeout
-- and it fails
table.insert(config["exclude-cases"], "7.1.6")
end
if read_pat == '*f' then
-- wstest 0.7.1
----
-- Remote side detect invalid utf8 earlier than me
-- Problem in ut8 validator which detect it too late
--
table.insert(config["exclude-cases"], "6.3.2")
end
function wstest(args, cb)
return uv.spawn({
file = "wstest",
args = args,
stdio = {{}, verbose and 1 or {}, verbose and 2 or {}}
}, function(handle, err, status, signal)
handle:close()
if err then error("Error spawn:" .. tostring(err)) end
cb(status, signal)
end)
end
function isWSEOF(err)
return err:name() == 'EOF' and err.cat and err:cat() == 'WEBSOCKET'
end
function runTest(cb)
print(" URL:", url)
print("MODE:", read_pat .. "/" .. decode_mode)
local currentCaseId = 0
local server = websocket.new{ssl = ctx, utf8 = true}
server:register(deflate)
server:bind(url, "echo", function(self, err)
if err then
print("Server error:", err)
return server:close()
end
wstest({"-m" ,"fuzzingclient", "-s", "fuzzingclient.json"}, function(code, status)
server:close(function()
cb(code, status)
end)
end)
server:listen(function(self, err)
if err then
print("Server listen:", err)
return server:close()
end
local cli = server:accept()
if decode_mode == "chunk" then
cli._on_raw_data = assert(websocket.__on_raw_data_by_chunk)
end
currentCaseId = currentCaseId + 1
if verbose then
print("Handshake test case " .. tostring(currentCaseId))
end
cli:handshake(function(self, err, protocol)
if err then
print("Server handshake error:", err)
return cli:close()
end
print("Executing test case " .. tostring(currentCaseId))
cli:start_read(read_pat, function(self, err, message, opcode, fin)
if err then
if not isWSEOF(err) then
print("Server read error:", err)
end
return cli:close()
end
if opcode == websocket.CONTINUATION or opcode == websocket.TEXT or opcode == websocket.BINARY then
cli:write(message, opcode, fin)
end
end)
end)
end)
end)
end
Autobahn.cleanReports(reportDir)
Autobahn.Utils.writeJson("fuzzingclient.json", config)
runTest(function()
if not Autobahn.verifyReport(reportDir, agent, true) then
exitCode = -1
else
exitCode = 0
end
print"DONE"
end)
uv.run()
os.exit(exitCode)
|
Fix. server test test use correct deflate module
|
Fix. server test test use correct deflate module
|
Lua
|
mit
|
moteus/lua-lluv-websocket,moteus/lua-lluv-websocket,moteus/lua-lluv-websocket
|
aa64f58e1c533582385e33c3055e0626f7bc244a
|
example.lua
|
example.lua
|
package.cpath = "./?.so"
local gumbo = require "gumbo"
local filename = ...
assert(filename, "A filename argument is required")
local document = assert(gumbo.parse_file(filename))
local depth = 1
local function write(text, depth, quoted)
local indent = string.rep(" ", depth*4)
local text = text:match("^%s*(.*)")
local format = (quoted and #text > 1) and '%s"%s"\n' or '%s%s\n'
io.write(string.format(format, indent, text))
end
local function dump(node)
if node.tag then
write(node.tag, depth)
depth = depth + 1
for i = 1, node.length do
dump(node[i])
end
depth = depth - 1
else
write(node, depth, true)
end
end
dump(document.root)
|
package.cpath = "./?.so"
local gumbo = require "gumbo"
local filename = ...
assert(filename, "A filename argument is required")
local document = assert(gumbo.parse_file(filename))
local depth = 1
local function write(text, depth, quoted)
local indent = string.rep(" ", depth*4)
local text = text:match("^%s*(.*)")
local format = (quoted and #text > 1) and '%s"%s"\n' or '%s%s\n'
io.write(string.format(format, indent, text))
end
local function dump(node)
if node.tag then
write(node.tag, depth)
depth = depth + 1
for i = 1, node.length do
dump(node[i])
end
depth = depth - 1
elseif node.comment then
return
else
write(node, depth, true)
end
end
dump(document.root)
|
Fix example.lua
|
Fix example.lua
|
Lua
|
apache-2.0
|
craigbarnes/lua-gumbo,craigbarnes/lua-gumbo,craigbarnes/lua-gumbo
|
1085049310cce11728f74dd7d46571bc579d7afb
|
core/inputs-common.lua
|
core/inputs-common.lua
|
SILE.inputs.common = {
init = function (_, tree)
local dclass = tree.options.class or "plain"
tree.options.papersize = tree.options.papersize or "a4"
SILE.documentState.documentClass = SILE.require(dclass, "classes")
for k, v in pairs(tree.options) do
if SILE.documentState.documentClass.options[k] then
SILE.documentState.documentClass.options[k](v)
end
end
-- Prepend the dirname of the input file to the Lua search path
local dirname = SILE.masterFilename:match("(.-)[^%/]+$")
package.path = dirname.."?;"..dirname.."?.lua;"..package.path
if not SILE.outputFilename and SILE.masterFilename then
-- TODO: This hack works on *nix systems because /dev/stdout is usable as
-- a filename to refer to STDOUT. Libtexpdf works fine with this, but it's
-- not going to work on Windows quite the same way. Normal filnames will
-- still work but explicitly using piped streams won't.
if SILE.masterFilename == "-" then
SILE.outputFilename = "/dev/stdout"
end
end
local ff = SILE.documentState.documentClass:init()
SILE.typesetter:init(ff)
end
}
local function debugAST(ast, level)
local out = string.rep(" ", 1+level)
if level == 0 then SU.debug("ast", "["..SILE.currentlyProcessingFile) end
if type(ast) == "function" then SU.debug("ast", out.."(function)") end
if not ast then SU.error("SILE.process called with nil", true) end
for i=1, #ast do
local content = ast[i]
if type(content) == "string" then
SU.debug("ast", out.."["..content.."]")
elseif SILE.Commands[content.command] then
local options = pl.tablex.size(content.options) > 0 and content.options or ""
SU.debug("ast", out.."\\"..content.command..options)
if (#content>=1) then debugAST(content, level+1) end
elseif content.id == "texlike_stuff" or (not content.command and not content.id) then
debugAST(content, level+1)
else
SU.debug("ast", out.."?\\"..(content.command or content.id))
end
end
if level == 0 then SU.debug("ast", "]") end
end
SILE.process = function (input)
if not input then SU.error("SILE.process called with nil", true) end
if type(input) == "function" then return input() end
if SU.debugging("ast") then
debugAST(input, 0)
end
for i=1, #input do
local content = input[i]
if type(content) == "string" then
SILE.typesetter:typeset(content)
elseif type(content) == "function" then
content()
elseif SILE.Commands[content.command] then
SILE.call(content.command, content.options, content)
elseif content.id == "texlike_stuff" or (not content.command and not content.id) then
local pId = SILE.traceStack:pushContent(content, "texlike_stuff")
SILE.process(content)
SILE.traceStack:pop(pId)
else
local pId = SILE.traceStack:pushContent(content)
SU.error("Unknown command "..(content.command or content.id))
SILE.traceStack:pop(pId)
end
end
end
-- Just a simple one-level find. We're not reimplementing XPath here.
SILE.findInTree = function (tree, command)
for i=1, #tree do
if type(tree[i]) == "table" and tree[i].command == command then
return tree[i]
end
end
end
|
SILE.inputs.common = {
init = function (_, tree)
local dclass = tree.options.class or "plain"
tree.options.papersize = tree.options.papersize or "a4"
SILE.documentState.documentClass = SILE.require(dclass, "classes")
for k, v in pairs(tree.options) do
if SILE.documentState.documentClass.options[k] then
SILE.documentState.documentClass.options[k](v)
end
end
-- Prepend the dirname of the input file to the Lua search path
local dirname = SILE.masterFilename:match("(.-)[^%/]+$")
package.path = dirname.."?;"..dirname.."?.lua;"..package.path
if not SILE.outputFilename and SILE.masterFilename then
-- TODO: This hack works on *nix systems because /dev/stdout is usable as
-- a filename to refer to STDOUT. Libtexpdf works fine with this, but it's
-- not going to work on Windows quite the same way. Normal filnames will
-- still work but explicitly using piped streams won't.
if SILE.masterFilename == "-" then
SILE.outputFilename = "/dev/stdout"
end
end
local ff = SILE.documentState.documentClass:init()
SILE.typesetter:init(ff)
end
}
local function debugAST(ast, level)
if not ast then SU.error("debugAST called with nil", true) end
local out = string.rep(" ", 1+level)
if level == 0 then SU.debug("ast", "["..SILE.currentlyProcessingFile) end
if type(ast) == "function" then SU.debug("ast", out.."(function)") end
for i=1, #ast do
local content = ast[i]
if type(content) == "string" then
SU.debug("ast", out.."["..content.."]")
elseif SILE.Commands[content.command] then
local options = pl.tablex.size(content.options) > 0 and content.options or ""
SU.debug("ast", out.."\\"..content.command..options)
if (#content>=1) then debugAST(content, level+1) end
elseif content.id == "texlike_stuff" or (not content.command and not content.id) then
debugAST(content, level+1)
else
SU.debug("ast", out.."?\\"..(content.command or content.id))
end
end
if level == 0 then SU.debug("ast", "]") end
end
SILE.process = function (input)
if not input then return end
if type(input) == "function" then return input() end
if SU.debugging("ast") then
debugAST(input, 0)
end
for i=1, #input do
local content = input[i]
if type(content) == "string" then
SILE.typesetter:typeset(content)
elseif type(content) == "function" then
content()
elseif SILE.Commands[content.command] then
SILE.call(content.command, content.options, content)
elseif content.id == "texlike_stuff" or (not content.command and not content.id) then
local pId = SILE.traceStack:pushContent(content, "texlike_stuff")
SILE.process(content)
SILE.traceStack:pop(pId)
else
local pId = SILE.traceStack:pushContent(content)
SU.error("Unknown command "..(content.command or content.id))
SILE.traceStack:pop(pId)
end
end
end
-- Just a simple one-level find. We're not reimplementing XPath here.
SILE.findInTree = function (tree, command)
for i=1, #tree do
if type(tree[i]) == "table" and tree[i].command == command then
return tree[i]
end
end
end
|
fix(core): Gracefully do nothing when SILE.process() passed nothing
|
fix(core): Gracefully do nothing when SILE.process() passed nothing
|
Lua
|
mit
|
alerque/sile,alerque/sile,alerque/sile,alerque/sile
|
1d4c213b32b69e20c462618b8edc893772b8edfd
|
scheduled/factionLeader.lua
|
scheduled/factionLeader.lua
|
--Checks if the playable faction leaders is logged in and thus the NPC needs to be out of player sight
require("base.common")
module("scheduled.factionLeader", package.seeall)
function checkFactionLeader()
informationTable = {["Rosaline Edwards"] = {usualPosition=position(122, 521, 0), newPosition=position(237, 104, 0)}, ["Valerio Guilianni"] = {usualPosition=position(337, 215, 0), newPosition=position(238, 104, 0)}, ["Elvaine Morgan"] = {usualPosition=position(898, 775, 2), newPosition=position(239, 104, 0)}}
alsaya = base.common.CheckIfOnline("Alsaya")
for i=1, #(informationTable) do
charObject = base.common.CheckIfOnline(informationTable[i])
base.common.InformNLS(alsaya,"name: "..informationTable[i].." ende",".."); --sending the message
if charObject.name ~= nil then
updatePosition(npcPositions)
end
end
end
function updatePosition(npcPositions)
if world:isCharacterOnField(npcPositions.usualPosition) == true then
npcCharObject = world:getCharacterOnField(npcPositions.usualPosition);
npcCharObject:forceWarp(npcPositions.newPosition);
end
end
|
--Checks if the playable faction leaders is logged in and thus the NPC needs to be out of player sight
require("base.common")
module("scheduled.factionLeader", package.seeall)
local informationTable = {
["Rosaline Edwards"] = {usualPosition=position(122, 521, 0), newPosition=position(237, 104, 0)},
["Valerio Guilianni"] = {usualPosition=position(337, 215, 0), newPosition=position(238, 104, 0)},
["Elvaine Morgan"] = {usualPosition=position(898, 775, 2), newPosition=position(239, 104, 0)}}
function checkFactionLeader()
alsaya = base.common.CheckIfOnline("Alsaya")
for i=1, #(informationTable) do
charObject = base.common.CheckIfOnline(informationTable[i])
base.common.InformNLS(alsaya,"name: "..informationTable[i].." ende","..");
if charObject.name ~= nil then
updatePosition(informationTable[i].usualPosition, informationTable[i].newPosition)
end
end
end
function updatePosition(usualPosition, newPosition)
if world:isCharacterOnField(usualPosition) == true then
npcCharObject = world:getCharacterOnField(usualPosition);
if npcCharObject:getType() == 2 then
npcCharObject:forceWarp(newPosition);
end
end
end
|
moved table outside of function and fixed a mistake in if statement
|
moved table outside of function and fixed a mistake in if statement
|
Lua
|
agpl-3.0
|
vilarion/Illarion-Content,KayMD/Illarion-Content,Illarion-eV/Illarion-Content,Baylamon/Illarion-Content,LaFamiglia/Illarion-Content
|
fd06a47d569becd8d1be7e935a7cea1a75dc5e71
|
lib/srcnn.lua
|
lib/srcnn.lua
|
require 'w2nn'
-- ref: http://arxiv.org/abs/1502.01852
-- ref: http://arxiv.org/abs/1501.00092
local srcnn = {}
function nn.SpatialConvolutionMM:reset(stdv)
stdv = math.sqrt(2 / ((1.0 + 0.1 * 0.1) * self.kW * self.kH * self.nOutputPlane))
self.weight:normal(0, stdv)
self.bias:zero()
end
if cudnn and cudnn.SpatialConvolution then
function cudnn.SpatialConvolution:reset(stdv)
stdv = math.sqrt(2 / ((1.0 + 0.1 * 0.1) * self.kW * self.kH * self.nOutputPlane))
self.weight:normal(0, stdv)
self.bias:zero()
end
end
function nn.SpatialConvolutionMM:clearState()
if self.gradWeight then
self.gradWeight = torch.Tensor(self.nOutputPlane, self.nInputPlane * self.kH * self.kW):typeAs(self.gradWeight):zero()
end
if self.gradBias then
self.gradBias = torch.Tensor(self.nOutputPlane):typeAs(self.gradBias):zero()
end
return nn.utils.clear(self, 'finput', 'fgradInput', '_input', '_gradOutput', 'output', 'gradInput')
end
function srcnn.channels(model)
return model:get(model:size() - 1).weight:size(1)
end
function srcnn.waifu2x_cunn(ch)
local model = nn.Sequential()
model:add(nn.SpatialConvolutionMM(ch, 32, 3, 3, 1, 1, 0, 0))
model:add(w2nn.LeakyReLU(0.1))
model:add(nn.SpatialConvolutionMM(32, 32, 3, 3, 1, 1, 0, 0))
model:add(w2nn.LeakyReLU(0.1))
model:add(nn.SpatialConvolutionMM(32, 64, 3, 3, 1, 1, 0, 0))
model:add(w2nn.LeakyReLU(0.1))
model:add(nn.SpatialConvolutionMM(64, 64, 3, 3, 1, 1, 0, 0))
model:add(w2nn.LeakyReLU(0.1))
model:add(nn.SpatialConvolutionMM(64, 128, 3, 3, 1, 1, 0, 0))
model:add(w2nn.LeakyReLU(0.1))
model:add(nn.SpatialConvolutionMM(128, 128, 3, 3, 1, 1, 0, 0))
model:add(w2nn.LeakyReLU(0.1))
model:add(nn.SpatialConvolutionMM(128, ch, 3, 3, 1, 1, 0, 0))
model:add(nn.View(-1):setNumInputDims(3))
--model:cuda()
--print(model:forward(torch.Tensor(32, ch, 92, 92):uniform():cuda()):size())
return model
end
function srcnn.waifu2x_cudnn(ch)
local model = nn.Sequential()
model:add(cudnn.SpatialConvolution(ch, 32, 3, 3, 1, 1, 0, 0))
model:add(w2nn.LeakyReLU(0.1))
model:add(cudnn.SpatialConvolution(32, 32, 3, 3, 1, 1, 0, 0))
model:add(w2nn.LeakyReLU(0.1))
model:add(cudnn.SpatialConvolution(32, 64, 3, 3, 1, 1, 0, 0))
model:add(w2nn.LeakyReLU(0.1))
model:add(cudnn.SpatialConvolution(64, 64, 3, 3, 1, 1, 0, 0))
model:add(w2nn.LeakyReLU(0.1))
model:add(cudnn.SpatialConvolution(64, 128, 3, 3, 1, 1, 0, 0))
model:add(w2nn.LeakyReLU(0.1))
model:add(cudnn.SpatialConvolution(128, 128, 3, 3, 1, 1, 0, 0))
model:add(w2nn.LeakyReLU(0.1))
model:add(cudnn.SpatialConvolution(128, ch, 3, 3, 1, 1, 0, 0))
model:add(nn.View(-1):setNumInputDims(3))
--model:cuda()
--print(model:forward(torch.Tensor(32, ch, 92, 92):uniform():cuda()):size())
return model
end
function srcnn.create(model_name, backend, color)
local ch = 3
if color == "rgb" then
ch = 3
elseif color == "y" then
ch = 1
else
error("unsupported color: " + color)
end
if backend == "cunn" then
return srcnn.waifu2x_cunn(ch)
elseif backend == "cudnn" then
return srcnn.waifu2x_cudnn(ch)
else
error("unsupported backend: " + backend)
end
end
return srcnn
|
require 'w2nn'
-- ref: http://arxiv.org/abs/1502.01852
-- ref: http://arxiv.org/abs/1501.00092
local srcnn = {}
function nn.SpatialConvolutionMM:reset(stdv)
stdv = math.sqrt(2 / ((1.0 + 0.1 * 0.1) * self.kW * self.kH * self.nOutputPlane))
self.weight:normal(0, stdv)
self.bias:zero()
end
if cudnn and cudnn.SpatialConvolution then
function cudnn.SpatialConvolution:reset(stdv)
stdv = math.sqrt(2 / ((1.0 + 0.1 * 0.1) * self.kW * self.kH * self.nOutputPlane))
self.weight:normal(0, stdv)
self.bias:zero()
end
end
function nn.SpatialConvolutionMM:clearState()
if self.gradWeight then
self.gradWeight:resize(self.nOutputPlane, self.nInputPlane * self.kH * self.kW):zero()
end
if self.gradBias then
self.gradBias:resize(self.nOutputPlane):zero()
end
return nn.utils.clear(self, 'finput', 'fgradInput', '_input', '_gradOutput', 'output', 'gradInput')
end
function srcnn.channels(model)
return model:get(model:size() - 1).weight:size(1)
end
function srcnn.waifu2x_cunn(ch)
local model = nn.Sequential()
model:add(nn.SpatialConvolutionMM(ch, 32, 3, 3, 1, 1, 0, 0))
model:add(w2nn.LeakyReLU(0.1))
model:add(nn.SpatialConvolutionMM(32, 32, 3, 3, 1, 1, 0, 0))
model:add(w2nn.LeakyReLU(0.1))
model:add(nn.SpatialConvolutionMM(32, 64, 3, 3, 1, 1, 0, 0))
model:add(w2nn.LeakyReLU(0.1))
model:add(nn.SpatialConvolutionMM(64, 64, 3, 3, 1, 1, 0, 0))
model:add(w2nn.LeakyReLU(0.1))
model:add(nn.SpatialConvolutionMM(64, 128, 3, 3, 1, 1, 0, 0))
model:add(w2nn.LeakyReLU(0.1))
model:add(nn.SpatialConvolutionMM(128, 128, 3, 3, 1, 1, 0, 0))
model:add(w2nn.LeakyReLU(0.1))
model:add(nn.SpatialConvolutionMM(128, ch, 3, 3, 1, 1, 0, 0))
model:add(nn.View(-1):setNumInputDims(3))
--model:cuda()
--print(model:forward(torch.Tensor(32, ch, 92, 92):uniform():cuda()):size())
return model
end
function srcnn.waifu2x_cudnn(ch)
local model = nn.Sequential()
model:add(cudnn.SpatialConvolution(ch, 32, 3, 3, 1, 1, 0, 0))
model:add(w2nn.LeakyReLU(0.1))
model:add(cudnn.SpatialConvolution(32, 32, 3, 3, 1, 1, 0, 0))
model:add(w2nn.LeakyReLU(0.1))
model:add(cudnn.SpatialConvolution(32, 64, 3, 3, 1, 1, 0, 0))
model:add(w2nn.LeakyReLU(0.1))
model:add(cudnn.SpatialConvolution(64, 64, 3, 3, 1, 1, 0, 0))
model:add(w2nn.LeakyReLU(0.1))
model:add(cudnn.SpatialConvolution(64, 128, 3, 3, 1, 1, 0, 0))
model:add(w2nn.LeakyReLU(0.1))
model:add(cudnn.SpatialConvolution(128, 128, 3, 3, 1, 1, 0, 0))
model:add(w2nn.LeakyReLU(0.1))
model:add(cudnn.SpatialConvolution(128, ch, 3, 3, 1, 1, 0, 0))
model:add(nn.View(-1):setNumInputDims(3))
--model:cuda()
--print(model:forward(torch.Tensor(32, ch, 92, 92):uniform():cuda()):size())
return model
end
function srcnn.create(model_name, backend, color)
local ch = 3
if color == "rgb" then
ch = 3
elseif color == "y" then
ch = 1
else
error("unsupported color: " + color)
end
if backend == "cunn" then
return srcnn.waifu2x_cunn(ch)
elseif backend == "cudnn" then
return srcnn.waifu2x_cudnn(ch)
else
error("unsupported backend: " + backend)
end
end
return srcnn
|
Fix clearState
|
Fix clearState
|
Lua
|
mit
|
nagadomi/waifu2x,nagadomi/waifu2x,Spitfire1900/upscaler,zyhkz/waifu2x,nagadomi/waifu2x,zyhkz/waifu2x,nagadomi/waifu2x,nagadomi/waifu2x,zyhkz/waifu2x,Spitfire1900/upscaler,zyhkz/waifu2x
|
cf1884c357462cba0aaa9dc15ce07f4a480d1c72
|
src/bot.lua
|
src/bot.lua
|
local bot = {}
local api = require("api")
local utils = require("utils")
local soul = require("soul")
function bot.analyzeMessageType(upd)
if upd.message then
local msg = upd.message
if msg.audio then
return "Audio"
elseif msg.video then
return "Video"
elseif msg.document then
return "Document"
elseif msg.game then
return "Game"
elseif msg.photo then
return "Photo"
elseif msg.sticker then
return "Sticker"
elseif msg.video_note then
return "VideoNote"
elseif msg.contact then
return "Contact"
elseif msg.location then
return "Location"
elseif msg.venue then
return "Venue"
elseif msg.new_chat_members then
return "NewChatMembers"
elseif msg.left_chat_member then
return "LeftChatMembers"
elseif msg.new_chat_title then
return "NewChatTitle"
elseif msg.new_chat_photo then
return "NewChatPhoto"
elseif msg.delete_chat_title then
return "DeleteChatPhoto"
elseif msg.group_chat_created then
return "GroupChatCreated"
elseif msg.supergroup_chat_created then
return "SupergroupChatCreated"
elseif msg.channel_chat_created then
return "ChannelChatCreated"
elseif msg.migrate_to_chat_id or msg.migrate_from_chat_id then
return "MigrateToChat"
elseif msg.pinned_message then
return "PinnedMessage"
elseif msg.invoice then
return "Invoice"
elseif msg.successful_payment then
return "SuccessfulPayment"
elseif msg.chat.type == "channel" then
return "ChannelMessage"
else
return "Message"
end
elseif upd.edited_message then
return "EditedMessage"
elseif upd.channel_post then
return "ChannelPost"
elseif upd.edited_channel_post then
return "EditedChannelPost"
elseif upd.inline_query then
return "InlineQuery"
elseif upd.chosen_inline_result then
return "ChosenInlineResult"
elseif upd.callback_query then
return "CallbackQuery"
elseif upd.shipping_query then
return "ShippingQuery"
elseif upd.pre_checkout_query then
return "PreCheckoutQuery"
else
return "Unknown"
end
end
function bot.reload()
package.loaded.soul = nil
package.loaded.bot = nil
package.loaded.api = nil
package.loaded.utils = nil
package.loaded.conversation = nil
soul = require("soul")
bot = require("bot")
api = require("api")
return true
end
function bot.downloadFile(file_id, path)
logger:warn(tostring(bot.getFile))
local ret = bot.getFile(file_id)
if ret and ret.ok then
os.execute(string.format("wget --timeout=5 -O %s https://api.telegram.org/file/bot%s/%s", path or "tmp", config.token, ret.result.file_path))
end
end
function bot.getUpdates(offset, limit, timeout, allowed_updates)
local body = {}
body.offset = offset
body.limit = limit
body.timeout = timeout
body.allowed_updates = allowed_updates
return api.makeRequest("getUpdates", body)
end
function bot.run()
logger:info("link start.")
local t = api.fetch()
for k, v in pairs(t) do
bot[k] = v
end
local ret = bot.getMe()
if ret then
bot.info = ret.result
logger:info("bot online. I am " .. bot.info.first_name .. ".")
end
local offset = 0
local threads = {}
while true do
local updates = bot.getUpdates(offset, config.limit, config.timeout)
if updates and updates.result then
for key, upd in pairs(updates.result) do
threads[upd.update_id] = coroutine.create(function()
soul[("on%sReceive"):format(bot.analyzeMessageType(upd))](
upd.message or upd.edited_message or upd.channel_post or upd.edited_channel_post
or upd.inline_query or upd.chosen_inline_result or upd.callback_query
or upd.shipping_query or upd.pre_checkout_query
)
end)
offset = upd.update_id + 1
end
end
for uid, thread in pairs(threads) do
local status, res = coroutine.resume(thread)
if not status then
threads[uid] = nil
if (res ~= "cannot resume dead coroutine") then
logger:error("coroutine #" .. uid .. " crashed, reason: " .. res)
end
end
end
end
end
setmetatable(bot, {
__index = function(t, key)
logger:warn("called undefined method " .. key)
end
})
return bot
|
local bot = {}
local api = require("api")
local utils = require("utils")
local soul = require("soul")
function bot.analyzeMessageType(upd)
if upd.message then
local msg = upd.message
if msg.audio then
return "Audio"
elseif msg.video then
return "Video"
elseif msg.document then
return "Document"
elseif msg.game then
return "Game"
elseif msg.photo then
return "Photo"
elseif msg.sticker then
return "Sticker"
elseif msg.video_note then
return "VideoNote"
elseif msg.contact then
return "Contact"
elseif msg.location then
return "Location"
elseif msg.venue then
return "Venue"
elseif msg.new_chat_members then
return "NewChatMembers"
elseif msg.left_chat_member then
return "LeftChatMembers"
elseif msg.new_chat_title then
return "NewChatTitle"
elseif msg.new_chat_photo then
return "NewChatPhoto"
elseif msg.delete_chat_title then
return "DeleteChatPhoto"
elseif msg.group_chat_created then
return "GroupChatCreated"
elseif msg.supergroup_chat_created then
return "SupergroupChatCreated"
elseif msg.channel_chat_created then
return "ChannelChatCreated"
elseif msg.migrate_to_chat_id or msg.migrate_from_chat_id then
return "MigrateToChat"
elseif msg.pinned_message then
return "PinnedMessage"
elseif msg.invoice then
return "Invoice"
elseif msg.successful_payment then
return "SuccessfulPayment"
elseif msg.chat.type == "channel" then
return "ChannelMessage"
else
return "Message"
end
elseif upd.edited_message then
return "EditedMessage"
elseif upd.channel_post then
return "ChannelPost"
elseif upd.edited_channel_post then
return "EditedChannelPost"
elseif upd.inline_query then
return "InlineQuery"
elseif upd.chosen_inline_result then
return "ChosenInlineResult"
elseif upd.callback_query then
return "CallbackQuery"
elseif upd.shipping_query then
return "ShippingQuery"
elseif upd.pre_checkout_query then
return "PreCheckoutQuery"
else
return "Unknown"
end
end
function bot.reload()
package.loaded.soul = nil
package.loaded.bot = nil
package.loaded.api = nil
package.loaded.utils = nil
package.loaded.conversation = nil
soul = require("soul")
bot = require("bot")
api = require("api")
return true
end
function bot.getUpdates(offset, limit, timeout, allowed_updates)
local body = {}
body.offset = offset
body.limit = limit
body.timeout = timeout
body.allowed_updates = allowed_updates
return api.makeRequest("getUpdates", body)
end
function bot.run()
logger:info("link start.")
local t = api.fetch()
for k, v in pairs(t) do
bot[k] = v
end
bot.downloadFile = function(file_id, path)
local ret = bot.getFile(file_id)
if ret and ret.ok then
os.execute(string.format("wget --timeout=5 -O %s https://api.telegram.org/file/bot%s/%s", path or "tmp", config.token, ret.result.file_path))
end
end
local ret = bot.getMe()
if ret then
bot.info = ret.result
logger:info("bot online. I am " .. bot.info.first_name .. ".")
end
local offset = 0
local threads = {}
while true do
local updates = bot.getUpdates(offset, config.limit, config.timeout)
if updates and updates.result then
for key, upd in pairs(updates.result) do
threads[upd.update_id] = coroutine.create(function()
soul[("on%sReceive"):format(bot.analyzeMessageType(upd))](
upd.message or upd.edited_message or upd.channel_post or upd.edited_channel_post
or upd.inline_query or upd.chosen_inline_result or upd.callback_query
or upd.shipping_query or upd.pre_checkout_query
)
end)
offset = upd.update_id + 1
end
end
for uid, thread in pairs(threads) do
local status, res = coroutine.resume(thread)
if not status then
threads[uid] = nil
if (res ~= "cannot resume dead coroutine") then
logger:error("coroutine #" .. uid .. " crashed, reason: " .. res)
end
end
end
end
end
setmetatable(bot, {
__index = function(t, key)
logger:warn("called undefined method " .. key)
end
})
return bot
|
fix: move bot.downloadFile into bot.run
|
fix: move bot.downloadFile into bot.run
|
Lua
|
apache-2.0
|
SJoshua/Project-Small-R
|
03c5655779fd3c8d232be92246fc69dfaa64b84c
|
t/iolua.lua
|
t/iolua.lua
|
-- This script runs on both lua.exe and nyagos' lua_f
local tmpfn = os.getenv("TEMP") .. "\\tmp.txt"
local fd = assert(io.open(tmpfn,"w"))
assert(fd:write('HOGEHOGE\n'))
assert(fd:flush())
fd:close()
local ok=false
for line in io.lines(tmpfn) do
if line == 'HOGEHOGE' then
ok = true
end
end
if ok then
print("OK: write-open,write-flush,write-close,io-lines")
else
print("NG: write-open,write-flush,write-close,io-lines")
end
local fd,err = io.open(":::","w")
if fd then
print("NG: invalid-open")
else
print("OK: invalid-open:",err)
end
local fd,err = io.open(tmpfn,"r")
local line = fd:read("*l")
if line == "HOGEHOGE" then
print("OK: io.read('*l')",line)
else
print("NG: io.read('*l')",line)
end
fd:seek("set",0)
for line in fd:lines() do
if line == "HOGEHOGE" then
print("OK: io.open: ",line)
else
print("NG: io.open: ",line)
end
end
fd:close()
local fd,err = io.popen("cmd.exe /c \"echo AHAHA\"","r")
if fd then
for line in fd:lines() do
print("OK>",line)
end
fd:close()
else
print("NG: ",err)
end
local sample=string.gsub(arg[0],"%.lua$",".txt")
print(sample)
local fd,err = io.open(sample,"r")
local line,num,crlf,rest = fd:read("*l","*n",1,"*a")
if io.type(fd) == "file" then
print "OK: iotype()==\"file\""
else
print("NG: iotype()==\""..io.type(fd).."\"")
end
if io.type("") == nil then
print "OK: iotype()==nil"
else
print("NG: iotype()==\""..io.type("").."\"")
end
if line == "ONELINE" then
print"OK: read('*l')"
else
print("NG: read('*l'):[",line,"]")
end
if num == 4 then
print "OK: read('*n')"
else
print("NG: read('*n')",num)
end
if crlf == "\n" then
print "OK: read(1)"
else
print ("NG: read(1):",crlf)
end
if rest == "AHAHA\nIHIHI\nUFUFU" then
print "OK: read('*a')"
else
print("NG: read('*a'):[",rest,"]")
end
local pos,err = fd:seek('set', 0)
if pos == 0 then
local line = fd:read('*l')
if line == "ONELINE" then
print "OK: seek('set',0)"
else
print("NG: seek('set',0)", line)
end
else
print("NG: seek('set',0)",pos,err)
end
local pos,err = fd:seek('set', 9)
if pos == 9 then
local line = fd:read('*l')
if line == '4' then
print "OK: seek('set',9)==9 read('*l')==4"
else
print("NG: seek('set',9)==9 read('*l')==4:",line)
end
else
print("NG: seek('set',9)==9:",pos)
end
local pos,err = fd:seek('cur')
if pos == 12 then
local line = fd:read('*l')
if line == 'AHAHA' then
print "OK: seek('cur')==12 read('*l')=='AHAHA'"
else
print("NG: seek('cur')==12 read('*l')=='AHAHA'",line)
end
else
print("NG: seek('cur')==12:", pos)
end
local pos,err = fd:seek('cur',2)
if pos == 21 then
local line = fd:read('*l')
if line == 'IHI' then
print "OK: seek('cur',2)==21 read('*l')=='IHI'"
else
print("NG: seek('cur',2)==21 read('*l')=='IHI'",line)
end
else
print("NG: seek('cur',2)==21:",pos)
end
local pos,err = fd:seek('end')
if pos == 31 then
local empty = fd:read('*a')
if empty == '' then
print "OK: seek('end')==31 read('*a')==''"
else
print("NG: seek('end')==31 read('*a')==''",empty)
end
else
print("NG: seek('end')==31",pos)
end
local size,err = fd:seek('end')
fd:seek('set',0)
rest,err = fd:read(size + 1)
if rest == "ONELINE\n4\nAHAHA\nIHIHI\nUFUFU" then
print "OK: read(number) number > file size"
else
print("NG: read(number) number > file size:", rest)
end
fd:seek('set',0)
local all = fd:read('*a')
local before = all:match('.*\n'):gsub('\n','\r\n')
fd:seek('set',#before)
local line = fd:read('*l')
if line == 'UFUFU' then
print "OK: read('*l') on line without line break"
else
print("NG: read('*l') on line without line break:",line)
end
fd:seek('end')
local eof = fd:read('*a')
if eof == '' then
print "OK: read('*a') on EOF"
else
print("NG: read('*a') on EOF:",eof)
end
local eof = fd:read('*l')
if eof == nil then
print "OK: read('*l') on EOF"
else
print("NG: read('*l') on EOF:["..eof..']')
end
local eof = fd:read('*n')
if eof == nil then
print "OK: read('*n') on EOF"
else
print("NG: read('*n') on EOF:["..eof..']')
end
local eof = fd:read(1)
if eof == nil then
print "OK: read(number) on EOF"
else
print("NG: read('number') on EOF:["..eof.."]")
end
fd:seek('set',0)
local empty = fd:read(0)
if empty == '' then
print "OK: read(0) on not EOF"
else
print("NG: read(0) on not EOF:",eof)
end
local _, eof = fd:read('*a', 0)
if eof == nil then
print "OK: read(0) on EOF"
else
print("NG: read(0) on EOF:",eof)
end
fd:close()
if io.type(fd) == "closed file" then
print "OK: iotype()==\"closed file\""
else
print("NG: iotype()==\""..io.type(fd).."\"")
end
local tmpfn = os.getenv("TEMP") .. "\\tmp2.txt"
local fd = assert(io.open(tmpfn,"w"))
fd:write("12345678")
fd:close()
fd = io.open(tmpfn,"r+")
fd:write("abcd")
fd:close()
for line in io.lines(tmpfn) do
if line == "abcd5678" then
print "OK: io.write(r+)"
else
print("NG: io.write(r+)",line)
end
break
end
fd = io.open(tmpfn,"r+")
fd:write("ABCD")
fd:close()
for line in io.lines(tmpfn) do
if line == "ABCD5678" then
print "OK: io.write(w+)"
else
print("NG: io.write(w+)",line)
end
break
end
io.stdout:setvbuf("no")
|
-- This script runs on both lua.exe and nyagos' lua_f
local tmpfn = os.tmpname()
local fd = assert(io.open(tmpfn,"w"))
assert(fd:write('HOGEHOGE\n'))
assert(fd:flush())
fd:close()
local ok=false
for line in io.lines(tmpfn) do
if line == 'HOGEHOGE' then
ok = true
end
end
if ok then
print("OK: write-open,write-flush,write-close,io-lines")
else
print("NG: write-open,write-flush,write-close,io-lines")
end
local fd,err = io.open("./notexistdir/cantopenfile","w")
if fd then
print("NG: invalid-open")
fd:close()
else
print("OK: invalid-open:",err)
end
local fd,err = io.open(tmpfn,"r")
local line = fd:read("*l")
if line == "HOGEHOGE" then
print("OK: io.read('*l')",line)
else
print("NG: io.read('*l')",line)
end
fd:seek("set",0)
for line in fd:lines() do
if line == "HOGEHOGE" then
print("OK: io.open: ",line)
else
print("NG: io.open: ",line)
end
end
fd:close()
local fd,err = io.popen("echo AHAHA","r")
if fd then
for line in fd:lines() do
print("OK>",line)
end
fd:close()
else
print("NG: ",err)
end
local sample=string.gsub(arg[0],"%.lua$",".txt")
print(sample)
local fd,err = io.open(sample,"r")
local line,num,crlf,rest = fd:read("*l","*n",1,"*a")
if io.type(fd) == "file" then
print "OK: iotype()==\"file\""
else
print("NG: iotype()==\""..io.type(fd).."\"")
end
if io.type("") == nil then
print "OK: iotype()==nil"
else
print("NG: iotype()==\""..io.type("").."\"")
end
if line == "ONELINE" then
print"OK: read('*l')"
else
print("NG: read('*l'):[",line,"]")
end
if num == 4 then
print "OK: read('*n')"
else
print("NG: read('*n')",num)
end
if crlf == "\n" then
print "OK: read(1)"
else
print ("NG: read(1):",crlf)
end
if rest == "AHAHA\nIHIHI\nUFUFU" then
print "OK: read('*a')"
else
print("NG: read('*a'):[",rest,"]")
end
local pos,err = fd:seek('set', 0)
if pos == 0 then
local line = fd:read('*l')
if line == "ONELINE" then
print "OK: seek('set',0)"
else
print("NG: seek('set',0)", line)
end
else
print("NG: seek('set',0)",pos,err)
end
local pos,err = fd:seek('set', 9)
if pos == 9 then
local line = fd:read('*l')
if line == '4' then
print "OK: seek('set',9)==9 read('*l')==4"
else
print("NG: seek('set',9)==9 read('*l')==4:",line)
end
else
print("NG: seek('set',9)==9:",pos)
end
local pos,err = fd:seek('cur')
if pos == 12 then
local line = fd:read('*l')
if line == 'AHAHA' then
print "OK: seek('cur')==12 read('*l')=='AHAHA'"
else
print("NG: seek('cur')==12 read('*l')=='AHAHA'",line)
end
else
print("NG: seek('cur')==12:", pos)
end
local pos,err = fd:seek('cur',2)
if pos == 21 then
local line = fd:read('*l')
if line == 'IHI' then
print "OK: seek('cur',2)==21 read('*l')=='IHI'"
else
print("NG: seek('cur',2)==21 read('*l')=='IHI'",line)
end
else
print("NG: seek('cur',2)==21:",pos)
end
local pos,err = fd:seek('end')
if pos == 31 then
local empty = fd:read('*a')
if empty == '' then
print "OK: seek('end')==31 read('*a')==''"
else
print("NG: seek('end')==31 read('*a')==''",empty)
end
else
print("NG: seek('end')==31",pos)
end
local size,err = fd:seek('end')
fd:seek('set',0)
rest,err = fd:read(size + 1)
if rest == "ONELINE\n4\nAHAHA\nIHIHI\nUFUFU" then
print "OK: read(number) number > file size"
else
print("NG: read(number) number > file size:", rest)
end
fd:seek('set',0)
local all = fd:read('*a')
local before = all:match('.*\n'):gsub('\n','\r\n')
fd:seek('set',#before)
local line = fd:read('*l')
if line == 'UFUFU' then
print "OK: read('*l') on line without line break"
else
print("NG: read('*l') on line without line break:",line)
end
fd:seek('end')
local eof = fd:read('*a')
if eof == '' then
print "OK: read('*a') on EOF"
else
print("NG: read('*a') on EOF:",eof)
end
local eof = fd:read('*l')
if eof == nil then
print "OK: read('*l') on EOF"
else
print("NG: read('*l') on EOF:["..eof..']')
end
local eof = fd:read('*n')
if eof == nil then
print "OK: read('*n') on EOF"
else
print("NG: read('*n') on EOF:["..eof..']')
end
local eof = fd:read(1)
if eof == nil then
print "OK: read(number) on EOF"
else
print("NG: read('number') on EOF:["..eof.."]")
end
fd:seek('set',0)
local empty = fd:read(0)
if empty == '' then
print "OK: read(0) on not EOF"
else
print("NG: read(0) on not EOF:",eof)
end
local _, eof = fd:read('*a', 0)
if eof == nil then
print "OK: read(0) on EOF"
else
print("NG: read(0) on EOF:",eof)
end
fd:close()
if io.type(fd) == "closed file" then
print "OK: iotype()==\"closed file\""
else
print("NG: iotype()==\""..io.type(fd).."\"")
end
local tmpfn = os.tmpname()
local fd = assert(io.open(tmpfn,"w"))
fd:write("12345678")
fd:close()
fd = io.open(tmpfn,"r+")
fd:write("abcd")
fd:close()
for line in io.lines(tmpfn) do
if line == "abcd5678" then
print "OK: io.write(r+)"
else
print("NG: io.write(r+)",line)
end
break
end
fd = io.open(tmpfn,"r+")
fd:write("ABCD")
fd:close()
for line in io.lines(tmpfn) do
if line == "ABCD5678" then
print "OK: io.write(w+)"
else
print("NG: io.write(w+)",line)
end
break
end
io.stdout:setvbuf("no")
|
Fix: t/iolua.lua could not run on Linux
|
Fix: t/iolua.lua could not run on Linux
|
Lua
|
bsd-3-clause
|
tsuyoshicho/nyagos,nocd5/nyagos,zetamatta/nyagos
|
34a43d0aa8c8d3a6fef5b634f2d3cb010e1b9020
|
scen_edit/display_util.lua
|
scen_edit/display_util.lua
|
DisplayUtil = LCS.class{}
local fontSize = 12
function DisplayUtil:init(isWidget)
self.isWidget = isWidget
self.texts = {}
self.unitSays = {}
end
function DisplayUtil:AddText(text, coords, color, time)
table.insert(self.texts, {
text = text,
coords = coords,
color = color,
time = time,
})
end
local function GetTipDimensions(unitID, str, height, invert)
local textHeight, _, numLines = gl.GetTextHeight(str)
textHeight = textHeight*fontSize*numLines
local textWidth = gl.GetTextWidth(str)*fontSize + 4
local x, y, z = -1, -1, -1
if Spring.IsUnitInView(unitID) and height ~= nil then
local ux, uy, uz = Spring.GetUnitBasePosition(unitID)
uy = uy + height
x,y,z = Spring.WorldToScreenCoords(ux, uy, uz)
if not invert then
y = screen0.height - y
end
end
return textWidth, textHeight, x, y, height
end
function DisplayUtil:AddUnitSay(text, unitId, time)
local height = Spring.GetUnitHeight(unitId)
local textWidth, textHeight, x, y = GetTipDimensions(unitId, text, height)
local img = Image:New {
width = textWidth + 4,
height = textHeight + 4 + fontSize,
x = x - (textWidth+8)/2,
y = y - textHeight - 4 - fontSize,
keepAspect = false,
file = "LuaUI/images/scenedit/speechbubble.png",
parent = screen0,
}
local textBox = TextBox:New {
parent = img,
text = text,
height = textHeight,
width = textWidth,
x = 4,
y = 4,
valign = "center",
align = "left",
font = {
--font = font,
size = fontSize,
color = {0,0,0,1},
},
}
if x == -1 and y == -1 and z == -1 and not img.hidden then
screen0:RemoveChild(img)
img.hidden = true
end
table.insert(self.unitSays, {
text = text,
unitId = unitId,
time = time,
img = img,
height = height,
})
end
function DisplayUtil:Update()
if self.follow then
if not Spring.ValidUnitID or Spring.GetUnitIsDead(self.follow) then
self.follow = nil
else--if Spring.IsUnitVisible(self.follow) then
local x, y, z = Spring.GetUnitViewPosition(self.follow)
Spring.SetCameraTarget(x, y, z)
end
end
end
function DisplayUtil:OnFrame()
local toDelete = {}
for i = 1, #self.texts do
local text = self.texts[i]
text.time = text.time - 1
if text.time <= 0 then
table.insert(toDelete, i)
end
end
for i = #toDelete, 1, -1 do
table.remove(self.texts, toDelete[i])
end
toDelete = {}
for i = 1, #self.unitSays do
local text = self.unitSays[i]
text.time = text.time - 1
if text.time <= 0 then
table.insert(toDelete, i)
end
end
for i = #toDelete, 1, -1 do
local del = toDelete[i]
if self.unitSays[del].img then
self.unitSays[del].img:Dispose()
end
table.remove(self.unitSays, i)
end
-- chili code
for _, unitSay in pairs(self.unitSays) do
if Spring.IsUnitInView(unitSay.unitId) then
local textWidth, textHeight, x, y = GetTipDimensions(unitSay.unitId, unitSay.text, unitSay.height)
local img = unitSay.img
if img.hidden then
screen0:AddChild(img)
img.hidden = false
end
img:SetPos(x - (textWidth+8)/2, y - textHeight - 4 - fontSize)
elseif not unitSay.img.hidden then
screen0:RemoveChild(unitSay.img)
unitSay.img.hidden = true
end
end
end
function DisplayUtil:Draw()
if SCEN_EDIT.view == nil or not SCEN_EDIT.view.displayDevelop then
return
end
for i = 1, #self.texts do
local text = self.texts[i]
gl.PushMatrix()
gl.Translate(text.coords[1], text.coords[2], text.coords[3])
gl.Color(text.color.r, text.color.g, text.color.b, 1)
gl.Text(text.text, 0, 300 - text.time, 12)
gl.PopMatrix()
end
end
function DisplayUtil:displayText(text, coords, color)
if self.isWidget then
self:AddText(text, coords, color, 300)
else
local cmd = WidgetDisplayTextCommand(text, coords, color)
SCEN_EDIT.commandManager:execute(cmd, true)
end
end
function DisplayUtil:unitSay(unit, text)
if self.isWidget then
self:AddUnitSay(text, unit, 300)
else
local cmd = WidgetUnitSayCommand(unit, text)
SCEN_EDIT.commandManager:execute(cmd, true)
end
end
function DisplayUtil:followUnit(unit)
if self.isWidget then
self.follow = unit
else
local cmd = WidgetFollowUnitCommand(unit)
SCEN_EDIT.commandManager:execute(cmd, true)
end
end
|
DisplayUtil = LCS.class{}
local fontSize = 12
function DisplayUtil:init(isWidget)
self.isWidget = isWidget
self.texts = {}
self.unitSays = {}
end
function DisplayUtil:AddText(text, coords, color, time)
table.insert(self.texts, {
text = text,
coords = coords,
color = color,
time = time,
})
end
local function GetTipDimensions(unitID, str, height, invert)
local textHeight, _, numLines = gl.GetTextHeight(str)
textHeight = textHeight*fontSize*numLines
local textWidth = gl.GetTextWidth(str)*fontSize + 4
local x, y, z = -1, -1, -1
if Spring.IsUnitInView(unitID) and height ~= nil then
local ux, uy, uz = Spring.GetUnitBasePosition(unitID)
uy = uy + height
x,y,z = Spring.WorldToScreenCoords(ux, uy, uz)
if not invert then
y = screen0.height - y
end
end
return textWidth, textHeight, x, y, height
end
function DisplayUtil:AddUnitSay(text, unitId, time)
local height = Spring.GetUnitHeight(unitId)
local textWidth, textHeight, x, y = GetTipDimensions(unitId, text, height)
local img = Image:New {
width = textWidth + 4,
height = textHeight + 4 + fontSize,
x = x - (textWidth+8)/2,
y = y - textHeight - 4 - fontSize,
keepAspect = false,
file = "LuaUI/images/scenedit/speechbubble.png",
parent = screen0,
}
local textBox = TextBox:New {
parent = img,
text = text,
height = textHeight,
width = textWidth,
x = 4,
y = 4,
valign = "center",
align = "left",
font = {
--font = font,
size = fontSize,
color = {0,0,0,1},
},
}
if x == -1 and y == -1 and z == -1 and not img.hidden then
screen0:RemoveChild(img)
img.hidden = true
end
table.insert(self.unitSays, {
text = text,
unitId = unitId,
time = time,
img = img,
height = height,
})
end
function DisplayUtil:Update()
if self.follow then
if not Spring.ValidUnitID or Spring.GetUnitIsDead(self.follow) then
self.follow = nil
else--if Spring.IsUnitVisible(self.follow) then
local x, y, z = Spring.GetUnitViewPosition(self.follow)
Spring.SetCameraTarget(x, y, z)
Spring.SelectUnitArray({self.follow})
end
end
end
function DisplayUtil:OnFrame()
local toDelete = {}
for i = 1, #self.texts do
local text = self.texts[i]
text.time = text.time - 1
if text.time <= 0 then
table.insert(toDelete, i)
end
end
for i = #toDelete, 1, -1 do
table.remove(self.texts, toDelete[i])
end
toDelete = {}
for i = 1, #self.unitSays do
local text = self.unitSays[i]
text.time = text.time - 1
if text.time <= 0 then
table.insert(toDelete, i)
end
end
for i = #toDelete, 1, -1 do
local del = toDelete[i]
if self.unitSays[del].img then
self.unitSays[del].img:Dispose()
end
table.remove(self.unitSays, i)
end
-- chili code
for _, unitSay in pairs(self.unitSays) do
if Spring.IsUnitInView(unitSay.unitId) then
local textWidth, textHeight, x, y = GetTipDimensions(unitSay.unitId, unitSay.text, unitSay.height)
local img = unitSay.img
if img.hidden then
screen0:AddChild(img)
img.hidden = false
end
img:SetPos(x - (textWidth+8)/2, y - textHeight - 4 - fontSize)
elseif not unitSay.img.hidden then
screen0:RemoveChild(unitSay.img)
unitSay.img.hidden = true
end
end
end
function DisplayUtil:Draw()
if SCEN_EDIT.view == nil or not SCEN_EDIT.view.displayDevelop then
return
end
for i = 1, #self.texts do
local text = self.texts[i]
gl.PushMatrix()
gl.Translate(text.coords[1], text.coords[2], text.coords[3])
gl.Color(text.color.r, text.color.g, text.color.b, 1)
gl.Text(text.text, 0, 300 - text.time, 12)
gl.PopMatrix()
end
end
function DisplayUtil:displayText(text, coords, color)
if self.isWidget then
self:AddText(text, coords, color, 300)
else
local cmd = WidgetDisplayTextCommand(text, coords, color)
SCEN_EDIT.commandManager:execute(cmd, true)
end
end
function DisplayUtil:unitSay(unit, text)
if self.isWidget then
self:AddUnitSay(text, unit, 300)
else
local cmd = WidgetUnitSayCommand(unit, text)
SCEN_EDIT.commandManager:execute(cmd, true)
end
end
function DisplayUtil:followUnit(unit)
if self.isWidget then
self.follow = unit
else
local cmd = WidgetFollowUnitCommand(unit)
SCEN_EDIT.commandManager:execute(cmd, true)
end
end
|
always select followable unit FIXME
|
always select followable unit FIXME
|
Lua
|
mit
|
Spring-SpringBoard/SpringBoard-Core,Spring-SpringBoard/SpringBoard-Core
|
b35dba590d3c1e2369ac734870d54c94cc641008
|
src/plugins/core/quit/quit.lua
|
src/plugins/core/quit/quit.lua
|
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- Q U I T --
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--
-- EXTENSIONS:
--
--------------------------------------------------------------------------------
local application = require("hs.application")
local config = require("cp.config")
--------------------------------------------------------------------------------
--
-- CONSTANTS:
--
--------------------------------------------------------------------------------
local PRIORITY = 9999999
--------------------------------------------------------------------------------
--
-- THE MODULE:
--
--------------------------------------------------------------------------------
local mod = {}
function mod.quit()
application.applicationsForBundleID(hs.processInfo["bundleID"])[1]:kill()
end
--------------------------------------------------------------------------------
--
-- THE PLUGIN:
--
--------------------------------------------------------------------------------
local plugin = {
id = "core.quit",
group = "core",
dependencies = {
["core.menu.bottom"] = "bottom",
}
}
--------------------------------------------------------------------------------
-- INITIALISE PLUGIN:
--------------------------------------------------------------------------------
function plugin.init(deps)
deps.bottom:addSeparator(9999998):addItem(PRIORITY, function()
return { title = i18n("quit"), fn = mod.quit }
end)
return mod
end
return plugin
|
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- Q U I T --
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--
-- EXTENSIONS:
--
--------------------------------------------------------------------------------
local application = require("hs.application")
local config = require("cp.config")
--------------------------------------------------------------------------------
--
-- CONSTANTS:
--
--------------------------------------------------------------------------------
local PRIORITY = 9999999
--------------------------------------------------------------------------------
--
-- THE MODULE:
--
--------------------------------------------------------------------------------
local mod = {}
function mod.quit()
config.application():kill()
end
--------------------------------------------------------------------------------
--
-- THE PLUGIN:
--
--------------------------------------------------------------------------------
local plugin = {
id = "core.quit",
group = "core",
dependencies = {
["core.menu.bottom"] = "bottom",
}
}
--------------------------------------------------------------------------------
-- INITIALISE PLUGIN:
--------------------------------------------------------------------------------
function plugin.init(deps)
deps.bottom:addSeparator(9999998):addItem(PRIORITY, function()
return { title = i18n("quit"), fn = mod.quit }
end)
return mod
end
return plugin
|
Fixed Quit Plugin
|
Fixed Quit Plugin
|
Lua
|
mit
|
cailyoung/CommandPost,cailyoung/CommandPost,fcpxhacks/fcpxhacks,CommandPost/CommandPost,cailyoung/CommandPost,CommandPost/CommandPost,CommandPost/CommandPost,fcpxhacks/fcpxhacks
|
bcb1f4361736bdac551079c8a9ea279e1f014e2d
|
plugins/reddit.lua
|
plugins/reddit.lua
|
local command = 'reddit [r/subreddit | query]'
local doc = [[```
/reddit [r/subreddit | query]
Returns the four (if group) or eight (if private message) top posts for the given subreddit or query, or from the frontpage.
Aliases: /r, /r/[subreddit]
```]]
local triggers = {
'^/reddit[@'..bot.username..']*',
'^/r[@'..bot.username..']*$',
'^/r[@'..bot.username..']* ',
'^/r/'
}
local action = function(msg)
msg.text_lower = msg.text_lower:gsub('/r/', '/r r/')
local input = msg.text_lower:input()
local url
local limit = 4
if msg.chat.id == msg.from.id then
limit = 8
end
local source
if input then
if input:match('^r/.') then
url = 'http://www.reddit.com/' .. input .. '/.json?limit=' .. limit
source = '*/r/' .. input:match('^r/(.+)') .. '*\n'
else
url = 'http://www.reddit.com/search.json?q=' .. input .. '&limit=' .. limit
source = '*reddit results for* _' .. input .. '_ *:*\n'
end
else
url = 'http://www.reddit.com/.json?limit=' .. limit
source = '*/r/all*\n'
end
local jstr, res = HTTP.request(url)
if res ~= 200 then
sendReply(msg, config.errors.connection)
return
end
local jdat = JSON.decode(jstr)
if #jdat.data.children == 0 then
sendReply(msg, config.errors.results)
return
end
local output = ''
for i,v in ipairs(jdat.data.children) do
local title = v.data.title:gsub('%[.+%]', ''):gsub('&', '&')
if title:len() > 48 then
title = title:sub(1,45) .. '...'
end
if v.data.over_18 then
v.data.is_self = true
end
local short_url = 'redd.it/' .. v.data.id
output = output .. '• [' .. title .. '](' .. short_url .. ')\n'
if not v.data.is_self then
output = output .. v.data.url:gsub('_', '\\_') .. '\n'
end
end
output = source .. output
sendMessage(msg.chat.id, output, true, nil, true)
end
return {
action = action,
triggers = triggers,
doc = doc,
command = command
}
|
local command = 'reddit [r/subreddit | query]'
local doc = [[```
/reddit [r/subreddit | query]
Returns the four (if group) or eight (if private message) top posts for the given subreddit or query, or from the frontpage.
Aliases: /r, /r/[subreddit]
```]]
local triggers = {
'^/reddit[@'..bot.username..']*',
'^/r[@'..bot.username..']*$',
'^/r[@'..bot.username..']* ',
'^/r/'
}
local action = function(msg)
msg.text_lower = msg.text_lower:gsub('/r/', '/r r/')
local input = msg.text_lower:input()
if msg.text_lower:match('^/r/') then
msg.text_lower = msg.text_lower:gsub('/r/', '/r r/')
input = get_word(msg.text_lower, 1)
else
input = msg.text_lower:input()
end
local url
local limit = 4
if msg.chat.id == msg.from.id then
limit = 8
end
local source
if input then
if input:match('^r/.') then
url = 'http://www.reddit.com/' .. URL.escape(input) .. '/.json?limit=' .. limit
source = '*/r/' .. input:match('^r/(.+)') .. '*\n'
else
url = 'http://www.reddit.com/search.json?q=' .. URL.escape(input) .. '&limit=' .. limit
source = '*reddit results for* _' .. input .. '_ *:*\n'
end
else
url = 'http://www.reddit.com/.json?limit=' .. limit
source = '*/r/all*\n'
end
local jstr, res = HTTP.request(url)
if res ~= 200 then
sendReply(msg, config.errors.connection)
return
end
local jdat = JSON.decode(jstr)
if #jdat.data.children == 0 then
sendReply(msg, config.errors.results)
return
end
local output = ''
for i,v in ipairs(jdat.data.children) do
local title = v.data.title:gsub('%[', '('):gsub('%]', ')'):gsub('&', '&')
if title:len() > 48 then
title = title:sub(1,45) .. '...'
end
if v.data.over_18 then
v.data.is_self = true
end
local short_url = 'redd.it/' .. v.data.id
output = output .. '• [' .. title .. '](' .. short_url .. ')\n'
if not v.data.is_self then
output = output .. v.data.url:gsub('_', '\\_') .. '\n'
end
end
output = source .. output
sendMessage(msg.chat.id, output, true, nil, true)
end
return {
action = action,
triggers = triggers,
doc = doc,
command = command
}
|
Fixed reddit.lua bug.
|
Fixed reddit.lua bug.
|
Lua
|
agpl-3.0
|
bb010g/otouto,Brawl345/Brawlbot-v2,TiagoDanin/SiD,topkecleon/otouto,barreeeiroo/BarrePolice
|
aee4fcd6be2d961a6d0427948f168b7127cb0741
|
mod_lastlog/mod_lastlog.lua
|
mod_lastlog/mod_lastlog.lua
|
local datamanager = require "util.datamanager";
local jid = require "util.jid";
local time = os.time;
local log_ip = module:get_option_boolean("lastlog_ip_address", false);
local host = module.host;
module:hook("authentication-success", function(event)
local session = event.session;
if session.username then
datamanager.store(session.username, host, "lastlog", {
event = "login";
timestamp = time(),
ip = log_ip and session.ip or nil,
});
end
end);
module:hook("resource-unbind", function(event)
local session = event.session;
if session.username then
datamanager.store(session.username, host, "lastlog", {
event = "logout";
timestamp = time(),
ip = log_ip and session.ip or nil,
});
end
end);
module:hook("user-registered", function(event)
local session = event.session;
datamanager.store(event.username, host, "lastlog", {
event = "registered";
timestamp = time(),
ip = log_ip and session.ip or nil,
});
end);
if module:get_host_type() == "component" then
module:hook("message/bare", function(event)
local room = jid.split(event.stanza.attr.to);
if room then
datamanager.store(room, module.host, "lastlog", {
event = "message";
timestamp = time(),
});
end
end);
elseif module:get_option_boolean("lastlog_stamp_offline") then
local datetime = require"util.datetime".datetime;
local function offline_stamp(event)
local stanza = event.stanza;
local node, to_host = jid.split(stanza.attr.from);
if to_host == host and event.origin == hosts[host] and stanza.attr.type == "unavailable" then
local data = datamanager.load(node, host, "lastlog");
local timestamp = data and data.timestamp;
if timestamp then
stanza:tag("delay", {
xmlns = "urn:xmpp:delay",
from = host,
stamp = datetime(timestamp),
}):up();
end
end
end
module:hook("pre-presence/bare", offline_stamp);
module:hook("pre-presence/full", offline_stamp);
end
function module.command(arg)
if not arg[1] or arg[1] == "--help" then
require"util.prosodyctl".show_usage([[mod_lastlog <user@host>]], [[Show when user last logged in or out]]);
return 1;
end
local user, host = jid.prepped_split(table.remove(arg, 1));
require"core.storagemanager".initialize_host(host);
local lastlog = datamanager.load(user, host, "lastlog");
if lastlog then
print(("Last %s: %s"):format(lastlog.event or "login",
lastlog.timestamp and os.date("%Y-%m-%d %H:%M:%S", lastlog.timestamp) or "<unknown>"));
if lastlog.ip then
print("IP address: "..lastlog.ip);
end
else
print("No record found");
return 1;
end
return 0;
end
|
local datamanager = require "util.datamanager";
local jid = require "util.jid";
local time = os.time;
local log_ip = module:get_option_boolean("lastlog_ip_address", false);
local host = module.host;
module:hook("authentication-success", function(event)
local session = event.session;
if session.username then
datamanager.store(session.username, host, "lastlog", {
event = "login";
timestamp = time(),
ip = log_ip and session and session.ip or nil,
});
end
end);
module:hook("resource-unbind", function(event)
local session = event.session;
if session.username then
datamanager.store(session.username, host, "lastlog", {
event = "logout";
timestamp = time(),
ip = log_ip and session and session.ip or nil,
});
end
end);
module:hook("user-registered", function(event)
local session = event.session;
datamanager.store(event.username, host, "lastlog", {
event = "registered";
timestamp = time(),
ip = log_ip and session and session.ip or nil,
});
end);
if module:get_host_type() == "component" then
module:hook("message/bare", function(event)
local room = jid.split(event.stanza.attr.to);
if room then
datamanager.store(room, module.host, "lastlog", {
event = "message";
timestamp = time(),
});
end
end);
elseif module:get_option_boolean("lastlog_stamp_offline") then
local datetime = require"util.datetime".datetime;
local function offline_stamp(event)
local stanza = event.stanza;
local node, to_host = jid.split(stanza.attr.from);
if to_host == host and event.origin == hosts[host] and stanza.attr.type == "unavailable" then
local data = datamanager.load(node, host, "lastlog");
local timestamp = data and data.timestamp;
if timestamp then
stanza:tag("delay", {
xmlns = "urn:xmpp:delay",
from = host,
stamp = datetime(timestamp),
}):up();
end
end
end
module:hook("pre-presence/bare", offline_stamp);
module:hook("pre-presence/full", offline_stamp);
end
function module.command(arg)
if not arg[1] or arg[1] == "--help" then
require"util.prosodyctl".show_usage([[mod_lastlog <user@host>]], [[Show when user last logged in or out]]);
return 1;
end
local user, host = jid.prepped_split(table.remove(arg, 1));
require"core.storagemanager".initialize_host(host);
local lastlog = datamanager.load(user, host, "lastlog");
if lastlog then
print(("Last %s: %s"):format(lastlog.event or "login",
lastlog.timestamp and os.date("%Y-%m-%d %H:%M:%S", lastlog.timestamp) or "<unknown>"));
if lastlog.ip then
print("IP address: "..lastlog.ip);
end
else
print("No record found");
return 1;
end
return 0;
end
|
mod_lastlog: Fix traceback if no session included with event (eg from mod_register_web) (thanks biszkopcik)
|
mod_lastlog: Fix traceback if no session included with event (eg from mod_register_web) (thanks biszkopcik)
|
Lua
|
mit
|
Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules
|
347457032df45bf4b4bf5ac6970d72bd34eca4c7
|
lua/starfall/libs_sh/net.lua
|
lua/starfall/libs_sh/net.lua
|
-------------------------------------------------------------------------------
-- Networking library.
-------------------------------------------------------------------------------
local net = net
--- Net message library. Used for sending data from the server to the client and back
local net_library, _ = SF.Libraries.Register("net")
local function can_send( instance, noupdate )
if instance.data.net.lasttime < CurTime() - 1 then
if not noupdate then
instance.data.net.lasttime = CurTime()
end
return true
else
return false
end
end
local function write( instance, type, value, setting )
instance.data.net.data[#instance.data.net.data+1] = { "Write" .. type, value, setting }
end
SF.Libraries.AddHook( "initialize", function( instance )
instance.data.net = {
started = false,
lasttime = 0,
data = {},
}
end)
SF.Libraries.AddHook( "deinitialize", function( instance )
if instance.data.net.started then
instance.data.net.started = false
end
end)
if SERVER then
util.AddNetworkString( "SF_netmessage" )
local function checktargets( target )
if target then
if SF.GetType(target) == "table" then
local newtarget = {}
for i=1,#target do
SF.CheckType( SF.Entities.Unwrap(target[i]), "Player", 1 )
newtarget[i] = SF.Entities.Unwrap(target[i])
end
return net.Send, newtarget
else
SF.CheckType( SF.Entities.Unwrap(target), "Player", 1 ) -- TODO: unhacky this
return net.Send, SF.Entities.Unwrap(target)
end
else
return net.Broadcast
end
end
function net_library.send( target )
local instance = SF.instance
if not instance.data.net.started then error("net message not started",2) end
local sendfunc, newtarget = checktargets( target )
local data = instance.data.net.data
if #data == 0 then return false end
net.Start( "SF_netmessage" )
for i=1,#data do
local writefunc = data[i][1]
local writevalue = data[i][2]
local writesetting = data[i][3]
net[writefunc]( writevalue, writesetting )
end
sendfunc( newtarget )
end
else
function net_library.send()
local instance = SF.instance
if not instance.data.net.started then error("net message not started",2) end
local data = instance.data.net.data
if #data == 0 then return false end
net.Start( "SF_netmessage" )
for i=1,#data do
local writefunc = data[i][1]
local writevalue = data[i][2]
local writesetting = data[i][3]
net[writefunc]( writevalue, writesetting )
end
net.SendToServer()
end
end
function net_library.start( name )
SF.CheckType( name, "string" )
local instance = SF.instance
if not can_send( instance ) then return error("can't send net messages that often",2) end
instance.data.net.started = true
instance.data.net.data = {}
write( instance, "String", name )
end
function net_library.writeTable( t )
local instance = SF.instance
if not instance.data.net.started then error("net message not started",2) end
SF.CheckType( t, "table" )
write( instance, "Table", SF.Unsanitize(t) )
return true
end
function net_library.readTable()
return SF.Sanitize(net.ReadTable())
end
function net_library.writeString( t )
local instance = SF.instance
if not instance.data.net.started then error("net message not started",2) end
SF.CheckType( t, "string" )
write( instance, "String", t )
return true
end
function net_library.readString()
return net.ReadString()
end
function net_library.writeInt( t, n )
local instance = SF.instance
if not instance.data.net.started then error("net message not started",2) end
SF.CheckType( t, "number" )
SF.CheckType( n, "number" )
write( instance, "Int", t, n )
return true
end
function net_library.readInt(n)
SF.CheckType( n, "number" )
return net.ReadInt(n)
end
function net_library.writeUInt( t, n )
local instance = SF.instance
if not instance.data.net.started then error("net message not started",2) end
SF.CheckType( t, "number" )
SF.CheckType( n, "number" )
write( instance, "UInt", t, n )
return true
end
function net_library.readUInt(n)
SF.CheckType( n, "number" )
return net.ReadUInt(n)
end
function net_library.writeBit( t )
local instance = SF.instance
if not instance.data.net.started then error("net message not started",2) end
SF.CheckType( t, "boolean" )
write( instance, "Bit", t )
return true
end
function net_library.readBit()
return net.ReadBit()
end
function net_library.writeDouble( t )
local instance = SF.instance
if not instance.data.net.started then error("net message not started",2) end
SF.CheckType( t, "number" )
write( instance, "Double", t )
return true
end
function net_library.readDouble()
return net.ReadDouble()
end
function net_library.writeFloat( t )
local instance = SF.instance
if not instance.data.net.started then error("net message not started",2) end
SF.CheckType( t, "number" )
write( instance, "Float", t )
return true
end
function net_library.readFloat()
return net.ReadFloat()
end
function net_library.bytesWritten()
local instance = SF.instance
if not instance.data.net.started then error("net message not started",2) end
return net.BytesWritten()
end
function net_library.canSend()
return can_send(SF.instance, true)
end
net.Receive( "SF_netmessage", function( len )
SF.RunScriptHook( "net", net.ReadString(), len )
end)
|
-------------------------------------------------------------------------------
-- Networking library.
-------------------------------------------------------------------------------
local net = net
--- Net message library. Used for sending data from the server to the client and back
local net_library, _ = SF.Libraries.Register("net")
local function can_send( instance, noupdate )
if instance.data.net.lasttime < CurTime() - 1 then
if not noupdate then
instance.data.net.lasttime = CurTime()
end
return true
else
return false
end
end
local function write( instance, type, value, setting )
instance.data.net.data[#instance.data.net.data+1] = { "Write" .. type, value, setting }
end
SF.Libraries.AddHook( "initialize", function( instance )
instance.data.net = {
started = false,
lasttime = 0,
data = {},
}
end)
SF.Libraries.AddHook( "deinitialize", function( instance )
if instance.data.net.started then
instance.data.net.started = false
end
end)
if SERVER then
util.AddNetworkString( "SF_netmessage" )
local function checktargets( target )
if target then
if SF.GetType(target) == "table" then
local newtarget = {}
for i=1,#target do
SF.CheckType( SF.Entities.Unwrap(target[i]), "Player", 1 )
newtarget[i] = SF.Entities.Unwrap(target[i])
end
return net.Send, newtarget
else
SF.CheckType( SF.Entities.Unwrap(target), "Player", 1 ) -- TODO: unhacky this
return net.Send, SF.Entities.Unwrap(target)
end
else
return net.Broadcast
end
end
function net_library.send( target )
local instance = SF.instance
if not instance.data.net.started then error("net message not started",2) end
local sendfunc, newtarget = checktargets( target )
local data = instance.data.net.data
if #data == 0 then return false end
net.Start( "SF_netmessage" )
for i=1,#data do
local writefunc = data[i][1]
local writevalue = data[i][2]
local writesetting = data[i][3]
net[writefunc]( writevalue, writesetting )
end
sendfunc( newtarget )
end
else
function net_library.send()
local instance = SF.instance
if not instance.data.net.started then error("net message not started",2) end
local data = instance.data.net.data
if #data == 0 then return false end
net.Start( "SF_netmessage" )
for i=1,#data do
local writefunc = data[i][1]
local writevalue = data[i][2]
local writesetting = data[i][3]
net[writefunc]( writevalue, writesetting )
end
net.SendToServer()
end
end
function net_library.start( name )
SF.CheckType( name, "string" )
local instance = SF.instance
if not can_send( instance ) then return error("can't send net messages that often",2) end
instance.data.net.started = true
instance.data.net.data = {}
write( instance, "String", name )
end
function net_library.writeTable( t )
local instance = SF.instance
if not instance.data.net.started then error("net message not started",2) end
SF.CheckType( t, "table" )
write( instance, "Table", SF.Unsanitize(t) )
return true
end
function net_library.readTable()
return SF.Sanitize(net.ReadTable())
end
function net_library.writeString( t )
local instance = SF.instance
if not instance.data.net.started then error("net message not started",2) end
SF.CheckType( t, "string" )
write( instance, "String", t )
return true
end
function net_library.readString()
return net.ReadString()
end
function net_library.writeInt( t, n )
local instance = SF.instance
if not instance.data.net.started then error("net message not started",2) end
SF.CheckType( t, "number" )
SF.CheckType( n, "number" )
write( instance, "Int", t, n )
return true
end
function net_library.readInt(n)
SF.CheckType( n, "number" )
return net.ReadInt(n)
end
function net_library.writeUInt( t, n )
local instance = SF.instance
if not instance.data.net.started then error("net message not started",2) end
SF.CheckType( t, "number" )
SF.CheckType( n, "number" )
write( instance, "UInt", t, n )
return true
end
function net_library.readUInt(n)
SF.CheckType( n, "number" )
return net.ReadUInt(n)
end
function net_library.writeBit( t )
local instance = SF.instance
if not instance.data.net.started then error("net message not started",2) end
SF.CheckType( t, "boolean" )
write( instance, "Bit", t )
return true
end
function net_library.readBit()
return net.ReadBit()
end
function net_library.writeDouble( t )
local instance = SF.instance
if not instance.data.net.started then error("net message not started",2) end
SF.CheckType( t, "number" )
write( instance, "Double", t )
return true
end
function net_library.readDouble()
return net.ReadDouble()
end
function net_library.writeFloat( t )
local instance = SF.instance
if not instance.data.net.started then error("net message not started",2) end
SF.CheckType( t, "number" )
write( instance, "Float", t )
return true
end
function net_library.readFloat()
return net.ReadFloat()
end
function net_library.bytesWritten()
local instance = SF.instance
if not instance.data.net.started then error("net message not started",2) end
return net.BytesWritten()
end
function net_library.canSend()
return can_send(SF.instance, true)
end
net.Receive( "SF_netmessage", function( len, ply )
SF.RunScriptHook( "net", net.ReadString(), len, ply and SF.WrapObject( ply ) )
end)
|
[Fixed] client->server net messages not telling you which player sent it
|
[Fixed] client->server net messages not telling you which player sent it
|
Lua
|
bsd-3-clause
|
Xandaros/Starfall,Jazzelhawk/Starfall,Jazzelhawk/Starfall,Ingenious-Gaming/Starfall,Ingenious-Gaming/Starfall,INPStarfall/Starfall,INPStarfall/Starfall,Xandaros/Starfall
|
10dc776d2019ac9eb373a134fba3ae3ab10b0d2e
|
src_trunk/resources/chat-system/c_chat_icon.lua
|
src_trunk/resources/chat-system/c_chat_icon.lua
|
function checkForChat()
local chatting = getElementData(getLocalPlayer(), "chatting")
if (isChatBoxInputActive() and chatting==0) then
setElementData(getLocalPlayer(), "chatting", true, 1)
elseif (not isChatBoxInputActive() and chatting==1) then
setElementData(getLocalPlayer(), "chatting", true, 0)
end
end
setTimer(checkForChat, 50, 0)
setElementData(getLocalPlayer(), "chatting", true, 0)
function render()
local x, y, z = getElementPosition(getLocalPlayer())
for key, value in ipairs(getElementsByType("player")) do
if (value~=getLocalPlayer()) then
local chatting = getElementData(value, "chatting")
if (chatting==1) then
local px, py, pz = getElementPosition(value)
local dist = getDistanceBetweenPoints3D(x, y, z, px, py, pz)
if (dist < 1000) then
if (isLineOfSightClear(x, y, z, px, py, pz, true, false, false, false )) then
local screenX, screenY = getScreenFromWorldPosition(px, py, pz+1.2)
local draw = dxDrawImage(screenX, screenY, 70, 70, "chat.png")
end
end
end
end
end
end
addEventHandler("onClientRender", getRootElement(), render)
chaticon = true
function toggleChatIcon()
if (chaticon) then
outputChatBox("Chat icons are now disabled.", 255, 0, 0)
chaticon = false
removeEventHandler("onClientRender", getRootElement(), render)
else
outputChatBox("Chat icons are now enabled.", 0, 255, 0)
chaticon = true
addEventHandler("onClientRender", getRootElement(), render)
end
end
addCommandHandler("togglechaticons", toggleChatIcon, false)
addCommandHandler("togchaticons", toggleChatIcon, false)
|
function checkForChat()
local chatting = getElementData(getLocalPlayer(), "chatting")
if (isChatBoxInputActive() and chatting==0) then
setElementData(getLocalPlayer(), "chatting", true, 1)
elseif (not isChatBoxInputActive() and chatting==1) then
setElementData(getLocalPlayer(), "chatting", true, 0)
end
end
setTimer(checkForChat, 50, 0)
setElementData(getLocalPlayer(), "chatting", true, 0)
function render()
local x, y, z = getElementPosition(getLocalPlayer())
for key, value in ipairs(getElementsByType("player")) do
if (value~=getLocalPlayer()) then
local chatting = getElementData(value, "chatting")
if (chatting==1) then
local px, py, pz = getElementPosition(value)
local dist = getDistanceBetweenPoints3D(x, y, z, px, py, pz)
if (dist < 1000) then
if (isLineOfSightClear(x, y, z, px, py, pz, true, false, false, false ) and isElementOnScreen(value)) then
local screenX, screenY = getScreenFromWorldPosition(px, py, pz+1.2)
if (screenX and screenY) then
local draw = dxDrawImage(screenX, screenY, 70, 70, "chat.png")
end
end
end
end
end
end
end
addEventHandler("onClientRender", getRootElement(), render)
chaticon = true
function toggleChatIcon()
if (chaticon) then
outputChatBox("Chat icons are now disabled.", 255, 0, 0)
chaticon = false
removeEventHandler("onClientRender", getRootElement(), render)
else
outputChatBox("Chat icons are now enabled.", 0, 255, 0)
chaticon = true
addEventHandler("onClientRender", getRootElement(), render)
end
end
addCommandHandler("togglechaticons", toggleChatIcon, false)
addCommandHandler("togchaticons", toggleChatIcon, false)
|
Fixed a bug with the chat image when the element is not on screen
|
Fixed a bug with the chat image when the element is not on screen
git-svn-id: 8769cb08482c9977c94b72b8e184ec7d2197f4f7@332 64450a49-1f69-0410-a0a2-f5ebb52c4f5b
|
Lua
|
bsd-3-clause
|
valhallaGaming/uno,valhallaGaming/uno,valhallaGaming/uno
|
833feff04e2f5d132d032138ca6d967bd005f24f
|
nyagos.d/brace.lua
|
nyagos.d/brace.lua
|
local orgfilter = nyagos.filter
nyagos.filter = function(cmdline)
if orgfilter then
local cmdline_ = orgfilter(cmdline)
if cmdline_ then
cmdline = cmdline_
end
end
repeat
local last = true
cmdline = cmdline:gsub("(%S*)(%b{})(%S*)", function(left,mid,right)
local contents = string.sub(mid,2,-2)
local result
local init = 1
while true do
local comma=string.find(contents,",",init,true)
local value=left .. string.sub(contents,init,(comma or 0)-1) .. right
if result then
result = result .. " " .. value
else
result = value
end
if not comma then
break
end
init = comma + 1
end
if init > 1 then
last = false
return result
else
return nil
end
end)
until last
return cmdline
end
|
local orgfilter = nyagos.filter
nyagos.filter = function(cmdline)
if orgfilter then
local cmdline_ = orgfilter(cmdline)
if cmdline_ then
cmdline = cmdline_
end
end
local save={}
cmdline = cmdline:gsub("((['\"])[^%2]*%2)", function(s,_)
local i=#save+1
save[i] = s
return '\a('..i..')'
end)
repeat
local last = true
cmdline = cmdline:gsub("(%S*)(%b{})(%S*)", function(left,mid,right)
local contents = string.sub(mid,2,-2)
local result
local init = 1
while true do
local comma=string.find(contents,",",init,true)
local value=left .. string.sub(contents,init,(comma or 0)-1) .. right
if result then
result = result .. " " .. value
else
result = value
end
if not comma then
break
end
init = comma + 1
end
if init > 1 then
last = false
return result
else
return nil
end
end)
until last
cmdline = cmdline:gsub("\a%((%d+)%)",function(s)
return save[s+0]
end)
return cmdline
end
|
Fixed #77: echo "{a,b}" -> "a b" is printed.
|
Fixed #77: echo "{a,b}" -> "a b" is printed.
|
Lua
|
bsd-3-clause
|
tyochiai/nyagos,hattya/nyagos,kissthink/nyagos,tsuyoshicho/nyagos,zetamatta/nyagos,hattya/nyagos,kissthink/nyagos,kissthink/nyagos,hattya/nyagos,nocd5/nyagos
|
c790172736b60b32d62356013c9837cadba783b6
|
src/lua/sancus/template/init.lua
|
src/lua/sancus/template/init.lua
|
-- This file is part of sancus-lua-template
-- <https://github.com/sancus-project/sancus-lua-template>
--
-- Copyright (c) 2012, Alejandro Mery <amery@geeks.cl>
--
local utils = assert(require"sancus.utils")
local Class = assert(require"sancus.object").Class
local generator = assert(require"sancus.template.generator")
local assert, loadstring, type = assert, loadstring, type
local setfenv = setfenv
local coroutine, io = coroutine, io
local pp, stderr = utils.pprint, utils.stderr
local _M = { _NAME = ...}
setfenv(1, _M)
local function yield(self, s)
if s ~= nil then
coroutine.yield(s)
end
end
Template = Class{
yield = yield,
yield_expr = yield,
}
-- returns path to template by name
function Template:lookup(name)
if type(name) == "string" then
return "./" .. name
end
end
function Template:iter(name, context)
local f,g
if self.templates == nil then
self.templates = {}
end
f = self:get(name)()
setfenv(f, context)
return function() f(self, context) end
end
function Template:load(key)
local data
local filename = assert(self:lookup(key))
local f = assert(io.open(filename, "r"))
data = assert(f:read("*all"))
f:close()
data = assert(generator(data))
if self.templates == nil then
self.templates = {}
end
self.templates[key] = data
return data
end
function Template:get(key)
assert(type(key) == "string", "key must be an string value")
if self.templates == nil then
self.templates = {}
end
return self.templates[key] or self:load(key)
end
function Template:include(context, args)
if args and type(args.file) == "string" then
local f = self:get(args.file)()
setfenv(f, context)
return f(self, context)
end
end
return _M
|
-- This file is part of sancus-lua-template
-- <https://github.com/sancus-project/sancus-lua-template>
--
-- Copyright (c) 2012, Alejandro Mery <amery@geeks.cl>
--
local utils = assert(require"sancus.utils")
local Class = assert(require"sancus.object").Class
local generator = assert(require"sancus.template.generator")
local assert, loadstring, type = assert, loadstring, type
local tostring = tostring
local setfenv = setfenv
local coroutine, io = coroutine, io
local pp, stderr = utils.pprint, utils.stderr
local _M = { _NAME = ...}
setfenv(1, _M)
local function yield(self, s)
if s ~= nil then
coroutine.yield(tostring(s))
end
end
Template = Class{
yield = yield,
yield_expr = yield,
}
-- returns path to template by name
function Template:lookup(name)
if type(name) == "string" then
return "./" .. name
end
end
function Template:iter(name, context)
local f,g
if self.templates == nil then
self.templates = {}
end
f = self:get(name)()
setfenv(f, context)
return function() f(self, context) end
end
function Template:load(key)
local data
local filename = assert(self:lookup(key))
local f = assert(io.open(filename, "r"))
data = assert(f:read("*all"))
f:close()
data = assert(generator(data))
if self.templates == nil then
self.templates = {}
end
self.templates[key] = data
return data
end
function Template:get(key)
assert(type(key) == "string", "key must be an string value")
if self.templates == nil then
self.templates = {}
end
return self.templates[key] or self:load(key)
end
function Template:include(context, args)
if args and type(args.file) == "string" then
local f = self:get(args.file)()
setfenv(f, context)
return f(self, context)
end
end
return _M
|
template:yield: fix to be sure to be passing strings along
|
template:yield: fix to be sure to be passing strings along
|
Lua
|
bsd-2-clause
|
sancus-project/sancus-lua-template
|
11051ce01b2e3ba21b79d517875d3b8c90d389be
|
pud/level/TileLevelView.lua
|
pud/level/TileLevelView.lua
|
local Class = require 'lib.hump.class'
local LevelView = require 'pud.level.LevelView'
local MapUpdateFinishedEvent = require 'pud.event.MapUpdateFinishedEvent'
-- TileLevelView
-- draws tiles for each node in the level map to a framebuffer, which is then
-- drawn to screen
local TileLevelView = Class{name='TileLevelView',
inherits=LevelView,
function(self, mapW, mapH)
LevelView.construct(self)
verify('number', mapW, mapH)
self._tileW, self._tileH = 32, 32
self._set = Image.dungeon
local w, h = nearestPO2(mapW*self._tileW), nearestPO2(mapH*self._tileH)
self._fb = love.graphics.newFramebuffer(w, h)
self:_setupQuads()
end
}
-- destructor
function TileLevelView:destroy()
self:_clearQuads()
self._set = nil
GameEvent:unregisterAll(self)
LevelView.destroy(self)
end
-- make a quad from the given tile position
function TileLevelView:_makeQuad(mapType, variant, x, y)
variant = tostring(variant)
self._quads[mapType] = self._quads[mapType] or {}
self._quads[mapType][variant] = love.graphics.newQuad(
self._tileW*(x-1),
self._tileH*(y-1),
self._tileW,
self._tileH,
self._set:getWidth(),
self._set:getHeight())
end
function TileLevelView:_getQuad(node)
if self._quads then
local mapType = node:getMapType()
if not mapType:isType('empty') then
local mtype, variant = mapType:get()
if not variant then
if mapType:isType('wall') then
mtype = 'wall'
variant = 'V'
elseif mapType:isType('torch') then
mtype = 'torch'
variant = 'A'
elseif mapType:isType('trap') then
mtype = 'trap'
variant = 'A'
end
end
variant = variant or ''
variant = variant .. '1'
if self._quads[mtype] then
return self._quads[mtype][variant]
end
end
end
return nil
end
-- clear the quads table
function TileLevelView:_clearQuads()
if self._quads then
for k,v in pairs(self._quads) do self._quads[k] = nil end
self._quads = nil
end
end
-- set up the quads
function TileLevelView:_setupQuads()
self:_clearQuads()
self._quads = {}
for i=1,4 do
self:_makeQuad('wall', 'H'..i, 1, i)
self:_makeQuad('wall', 'HWorn'..i, 2, i)
self:_makeQuad('wall', 'V'..i, 3, i)
self:_makeQuad('torch', 'A'..i, 4, i)
self:_makeQuad('torch', 'B'..i, 5, i)
self:_makeQuad('floor', i, 6, i)
self:_makeQuad('floor', 'Worn'..i, 7, i)
self:_makeQuad('floor', 'X'..i, 8, i)
self:_makeQuad('floor', 'Rug'..i, 9, i)
self:_makeQuad('stairUp', i, 10, i)
self:_makeQuad('stairDown', i, 11, i)
end
for i=1,5 do
self:_makeQuad('doorClosed', i, i+(i-1), 5)
self:_makeQuad('doorOpen', i, i*2, 5)
end
for i=1,6 do
self:_makeQuad('trap', 'A'..i, i+(i-1), 6)
self:_makeQuad('trap', 'B'..i, i*2, 6)
end
end
-- register for events that will cause this view to redraw
function TileLevelView:registerEvents()
local events = {
MapUpdateFinishedEvent,
}
GameEvent:register(self, events)
end
-- handle registered events as they are fired
function TileLevelView:onEvent(e, ...)
if e:is_a(MapUpdateFinishedEvent) then
self:drawToFB(e:getMap())
end
end
-- draw to the framebuffer
function TileLevelView:drawToFB(map)
if self._fb and self._set and map then
self._isDrawing = true
love.graphics.setRenderTarget(self._fb)
love.graphics.setColor(1,1,1)
for y=1,map:getHeight() do
local drawY = (y-1)*self._tileH
for x=1,map:getWidth() do
local node = map:getLocation(x, y)
local quad = self:_getQuad(node)
if quad then
local drawX = (x-1)*self._tileW
love.graphics.drawq(self._set, quad, drawX, drawY)
elseif not node:getMapType():isType('empty') then
warning('no quad found for %s', tostring(node:getMapType()))
end
end
end
love.graphics.setRenderTarget()
self._isDrawing = false
end
end
-- draw the framebuffer to the screen
function TileLevelView:draw()
if self._fb and self._isDrawing == false then
love.graphics.setColor(1,1,1)
love.graphics.draw(self._fb)
end
end
-- the class
return TileLevelView
|
local Class = require 'lib.hump.class'
local LevelView = require 'pud.level.LevelView'
local Map = require 'pud.level.Map'
local MapUpdateFinishedEvent = require 'pud.event.MapUpdateFinishedEvent'
-- TileLevelView
-- draws tiles for each node in the level map to a framebuffer, which is then
-- drawn to screen
local TileLevelView = Class{name='TileLevelView',
inherits=LevelView,
function(self, mapW, mapH)
LevelView.construct(self)
verify('number', mapW, mapH)
self._tileW, self._tileH = 32, 32
self._set = Image.dungeon
local w, h = nearestPO2(mapW*self._tileW), nearestPO2(mapH*self._tileH)
self._fb = love.graphics.newFramebuffer(w, h)
self:_setupQuads()
end
}
-- destructor
function TileLevelView:destroy()
self:_clearQuads()
self._set = nil
GameEvent:unregisterAll(self)
LevelView.destroy(self)
end
-- make a quad from the given tile position
function TileLevelView:_makeQuad(mapType, variant, x, y)
variant = tostring(variant)
self._quads[mapType] = self._quads[mapType] or {}
self._quads[mapType][variant] = love.graphics.newQuad(
self._tileW*(x-1),
self._tileH*(y-1),
self._tileW,
self._tileH,
self._set:getWidth(),
self._set:getHeight())
end
function TileLevelView:_getQuad(node)
if self._quads then
local mapType = node:getMapType()
if not mapType:isType('empty') then
local mtype, variant = mapType:get()
if not variant then
if mapType:isType('wall') then
mtype = 'wall'
variant = 'V'
elseif mapType:isType('torch') then
mtype = 'torch'
variant = 'A'
elseif mapType:isType('trap') then
mtype = 'trap'
variant = 'A'
end
end
variant = variant or ''
variant = variant .. '1'
if self._quads[mtype] then
return self._quads[mtype][variant]
end
end
end
return nil
end
-- clear the quads table
function TileLevelView:_clearQuads()
if self._quads then
for k,v in pairs(self._quads) do self._quads[k] = nil end
self._quads = nil
end
end
-- set up the quads
function TileLevelView:_setupQuads()
self:_clearQuads()
self._quads = {}
for i=1,4 do
self:_makeQuad('wall', 'H'..i, 1, i)
self:_makeQuad('wall', 'HWorn'..i, 2, i)
self:_makeQuad('wall', 'V'..i, 3, i)
self:_makeQuad('torch', 'A'..i, 4, i)
self:_makeQuad('torch', 'B'..i, 5, i)
self:_makeQuad('floor', i, 6, i)
self:_makeQuad('floor', 'Worn'..i, 7, i)
self:_makeQuad('floor', 'X'..i, 8, i)
self:_makeQuad('floor', 'Rug'..i, 9, i)
self:_makeQuad('stairUp', i, 10, i)
self:_makeQuad('stairDown', i, 11, i)
end
for i=1,5 do
self:_makeQuad('doorClosed', i, i+(i-1), 5)
self:_makeQuad('doorOpen', i, i*2, 5)
end
for i=1,6 do
self:_makeQuad('trap', 'A'..i, i+(i-1), 6)
self:_makeQuad('trap', 'B'..i, i*2, 6)
end
end
-- register for events that will cause this view to redraw
function TileLevelView:registerEvents()
local events = {
MapUpdateFinishedEvent,
}
GameEvent:register(self, events)
end
-- handle registered events as they are fired
function TileLevelView:onEvent(e, ...)
if e:is_a(MapUpdateFinishedEvent) then
self:drawToFB(e:getMap())
end
end
-- draw to the framebuffer
function TileLevelView:drawToFB(map)
if self._fb and self._set
and map and map.is_a and map:is_a(Map) and map:getHeight()
then
self._isDrawing = true
love.graphics.setRenderTarget(self._fb)
love.graphics.setColor(1,1,1)
for y=1,map:getHeight() do
local drawY = (y-1)*self._tileH
for x=1,map:getWidth() do
local node = map:getLocation(x, y)
local quad = self:_getQuad(node)
if quad then
local drawX = (x-1)*self._tileW
love.graphics.drawq(self._set, quad, drawX, drawY)
elseif not node:getMapType():isType('empty') then
warning('no quad found for %s', tostring(node:getMapType()))
end
end
end
love.graphics.setRenderTarget()
self._isDrawing = false
end
end
-- draw the framebuffer to the screen
function TileLevelView:draw()
if self._fb and self._isDrawing == false then
love.graphics.setColor(1,1,1)
love.graphics.draw(self._fb)
end
end
-- the class
return TileLevelView
|
fix map sometimes not having size when drawn
|
fix map sometimes not having size when drawn
|
Lua
|
mit
|
scottcs/wyx
|
d5075d8a3f560928762307613fd2c0b5f15e035e
|
tests/test-http-stream-finish.lua
|
tests/test-http-stream-finish.lua
|
local http = require("http")
require('tap')(function(test)
test('http stream end', function(expect)
local server
server = http.createServer(function (req, res)
local body = "Hello world\n"
res:on("finish", expect(function()
p('sending resp finished')
server:close()
end))
res:writeHead(200, {
["Content-Type"] = "text/plain",
["Content-Length"] = #body
})
res:finish(body)
end):listen(8080)
http.get('http://127.0.0.1:8080', expect(function(resp)
resp:on('end', expect(function(data)
p('Get response ended')
end))
end))
end)
end)
|
local http = require("http")
require('tap')(function(test)
test('http stream end', function(expect)
local server
server = http.createServer(function (req, res)
local body = "Hello world\n"
res:writeHead(200, {
["Content-Type"] = "text/plain",
["Content-Length"] = #body
})
res:finish(body)
end):listen(8080)
http.get('http://127.0.0.1:8080', expect(function(resp)
resp:on('end', expect(function(data)
p('Get response ended')
server:close()
end))
end))
end)
end)
|
fix stream finish
|
fix stream finish
|
Lua
|
apache-2.0
|
bsn069/luvit,bsn069/luvit,kaustavha/luvit,zhaozg/luvit,GabrielNicolasAvellaneda/luvit-upstream,GabrielNicolasAvellaneda/luvit-upstream,kaustavha/luvit,GabrielNicolasAvellaneda/luvit-upstream,GabrielNicolasAvellaneda/luvit-upstream,bsn069/luvit,zhaozg/luvit,kaustavha/luvit,luvit/luvit,luvit/luvit
|
0b354cb9fdbb8ef6784d3c4ce63e052e47cddb25
|
tests/podcast/main3.lua
|
tests/podcast/main3.lua
|
require "sprite"
require "theme"
require "timer"
local W, H = theme.scr.w(), theme.scr.h()
local tiles = {}
local WX, HY = 64, 64
local WW, HH = math.floor(W / WX), math.floor(H / HY)
local pad = 2
local book_spr = sprite.new "book.png"
local wh1_spr = sprite.new "wheel1.png"
local wh2_spr = sprite.new "wheel2.png"
local instead_spr = sprite.new "instead.png"
local shadow_spr = { sprite.new "shadow.png", sprite.new "shadow2.png" }
local rotate = 0
local rotate_spr = {}
function logo_init()
for r = 1, 359 do
local a = r
rotate_spr[r] = {}
rotate_spr[r][1] = wh1_spr:rotate(-a)
rotate_spr[r][2] = wh2_spr:rotate(a * 2)
end
end
function logo()
local w, h = instead_spr:size()
local ww, hh = theme.scr.w(), theme.scr.h()
-- instead_spr:draw(sprite.scr(), (ww - w) / 2, (hh - h)/ 2 - 122)
local book, wh1, wh2 = book_spr, wh1_spr, wh2_spr
local r = math.floor(rotate)
local x, y = (theme.scr.w() - 250) / 2, (theme.scr.h() - 256) / 2
if r > 0 then
wh1, wh2 = rotate_spr[r][1], rotate_spr[r][2]
end
book:draw(sprite.scr(), x, 92 + y)
local w, h = wh1:size()
for _ = 1, 3 do
shadow_spr[rnd(2)]:draw(sprite.scr(), x - 20, y - 16)
end
wh1:draw(sprite.scr(), x + 86 - w/ 2, 92 + y - 16 - h / 2)
local w, h = wh2:size()
wh2:draw(sprite.scr(), x + 174 - w / 2, 92 + y + 12 - h /2)
rotate = rotate + 1
if rotate >= 360 then rotate = 0 end
end
function draw_tiles()
for y = 1, HY do
for x = 1, WX do
local a = tiles[y][x].lev / 255
local COL = tiles[y][x].col
local col = string.format("#%02x%02x%02x", COL[1] * a, COL[2] * a, COL[3] * a)
sprite.scr():fill((x - 1) * WX + pad, (y - 1) * HY + pad, WX - pad * 2, HY - pad * 2, col)
end
end
end
local DIST = 6
local slides = {}
function scale_slide(v)
local x, y
local distance = rnd(10000) / 10000
v.dist = distance
local scale = 1 / 8 + (1 - v.dist) * 1 / 2
local smooth = true
v.spr = sprite.new(v.nam):scale(scale, scale, smooth)
v.w, v.h = v.spr:size()
v.dir = rnd(4)
if v.dir == 1 then
x = - (v.w + rnd(v.w))
y = rnd(theme.scr.h()) - rnd(v.h)
elseif v.dir == 2 then
x = theme.scr.w() + rnd(v.w)
y = rnd(theme.scr.h()) - rnd(v.h)
elseif v.dir == 3 then
x = rnd(theme.scr.w()) - rnd(v.w)
y = -(v.h + rnd(v.h))
else
x = rnd(theme.scr.w()) - rnd(v.w)
y = theme.scr.h() + (v.h + rnd(v.h))
end
v.x, v.y = x, y
end
function process_slides()
local x, y, once
for k, v in ipairs(slides) do
if v.dir == 1 then
v.x = v.x + (1 * (1 - v.dist) + 1)
elseif v.dir == 2 then
v.x = v.x - (1 * (1 - v.dist) + 1)
elseif v.dir == 3 then
v.y = v.y + (1 * (1 - v.dist) + 1)
else
v.y = v.y - (1 * (1 - v.dist) + 1)
end
if not once and (v.x > theme.scr.w() and v.dir == 1 or v.x < -v.w and v.dir == 2
or v.y > theme.scr.h() and v.dir == 3 or v.y < - v.h and v.dir == 4) then
once = true
scale_slide(v)
end
-- v.spr:copy(sprite.scr(), v.x, v.y)
end
if once then
table.sort(slides, function(a, b) return a.dist > b.dist end)
end
end
function draw_slides()
for k, v in ipairs(slides) do
v.spr:copy(sprite.scr(), v.x, v.y)
end
end
function load_slides()
scandir()
DIST = #slides
for k, v in ipairs(slides) do
scale_slide(v)
end
table.sort(slides, function(a, b) return a.dist > b.dist end)
end
function process_tiles()
local y = rnd(HH)
local x = rnd(WW)
local cell = tiles[y][x]
if cell.dir == 1 then
cell.lev = cell.lev + (rnd(64) + 32)
else
cell.lev = cell.lev - (rnd(64) + 32)
end
if cell.lev > 255 then
cell.dir = 2
cell.lev = 255
color(x, y)
elseif cell.lev < 0 then
cell.dir = 1
cell.lev = 0
color(x, y)
end
end
function color(x, y)
local COL = tiles[y][x].col
COL[1] = 0 -- rnd(255)
COL[2] = 255 -- rnd(255)
COL[3] = 255 -- rnd(255)
end
local last_t = 0
function game:timer()
process_tiles()
process_slides()
local t = instead.ticks()
if t - last_t > 20 then
last_t = instead.ticks()
return
end
sprite.scr():fill 'black'
draw_tiles()
draw_slides()
logo(0, 0)
last_t = instead.ticks()
end
function scandir()
for d in std.readdir 'screen' do
if d:find("%.png$") then
table.insert(slides, { nam = "screen/"..d })
end
dprint("Scan: ", d)
end
end
function start()
if not sprite.direct(true) then
error("Включите собственные темы игр")
end
sprite.scr():fill 'black'
for y = 1, HY do
if not tiles[y] then
tiles[y] = {}
end
for x = 1, WX do
tiles[y][x] = { lev = rnd(128), dir = rnd(2), col = {} }
color(x, y)
end
end
load_slides()
logo_init()
timer:set(20)
end
|
require "sprite"
require "theme"
require "timer"
local W, H = theme.scr.w(), theme.scr.h()
local tiles = {}
local WX, HY = 64, 64
local WW, HH = math.floor(W / WX), math.floor(H / HY)
local pad = 2
local book_spr = sprite.new "book.png"
local wh1_spr = sprite.new "wheel1.png"
local wh2_spr = sprite.new "wheel2.png"
local instead_spr = sprite.new "instead.png"
local shadow_spr = { sprite.new "shadow.png", sprite.new "shadow2.png" }
local rotate = 0
local rotate_spr = {}
function logo_init()
for r = 1, 359 do
local a = r
rotate_spr[r] = {}
rotate_spr[r][1] = wh1_spr:rotate(-a)
rotate_spr[r][2] = wh2_spr:rotate(a * 2)
end
end
function logo()
local w, h = instead_spr:size()
local ww, hh = theme.scr.w(), theme.scr.h()
-- instead_spr:draw(sprite.scr(), (ww - w) / 2, (hh - h)/ 2 - 122)
local book, wh1, wh2 = book_spr, wh1_spr, wh2_spr
local r = math.floor(rotate)
local x, y = (theme.scr.w() - 250) / 2, (theme.scr.h() - 256) / 2
if r > 0 then
wh1, wh2 = rotate_spr[r][1], rotate_spr[r][2]
end
book:draw(sprite.scr(), x, 92 + y)
local w, h = wh1:size()
for _ = 1, 3 do
shadow_spr[rnd(2)]:draw(sprite.scr(), x - 20, y - 16)
end
wh1:draw(sprite.scr(), x + 86 - w/ 2, 92 + y - 16 - h / 2)
local w, h = wh2:size()
wh2:draw(sprite.scr(), x + 174 - w / 2, 92 + y + 12 - h /2)
rotate = rotate + 1
if rotate >= 360 then rotate = 0 end
end
function draw_tiles()
for y = 1, HY do
for x = 1, WX do
local a = tiles[y][x].lev / 255
local COL = tiles[y][x].col
local col = string.format("#%02x%02x%02x", COL[1] * a, COL[2] * a, COL[3] * a)
sprite.scr():fill((x - 1) * WX + pad, (y - 1) * HY + pad, WX - pad * 2, HY - pad * 2, col)
end
end
end
local DIST = 6
local slides = {}
local slides_pool = {}
function scale_slide(v)
local x, y
local distance = rnd(10000) / 10000
v.dist = distance
local scale = 1 / 8 + (1 - v.dist) * 1 / 2
local smooth = true
v.spr = sprite.new(v.nam):scale(scale, scale, smooth)
v.w, v.h = v.spr:size()
v.dir = rnd(4)
if v.dir == 1 then
x = - (v.w + rnd(v.w))
y = rnd(theme.scr.h()) - rnd(v.h)
elseif v.dir == 2 then
x = theme.scr.w() + rnd(v.w)
y = rnd(theme.scr.h()) - rnd(v.h)
elseif v.dir == 3 then
x = rnd(theme.scr.w()) - rnd(v.w)
y = -(v.h + rnd(v.h))
else
x = rnd(theme.scr.w()) - rnd(v.w)
y = theme.scr.h() + (v.h + rnd(v.h))
end
v.x, v.y = x, y
end
function process_slides()
local x, y, once
for k, v in ipairs(slides) do
if v.dir == 1 then
v.x = v.x + (1 * (1 - v.dist) + 1)
elseif v.dir == 2 then
v.x = v.x - (1 * (1 - v.dist) + 1)
elseif v.dir == 3 then
v.y = v.y + (1 * (1 - v.dist) + 1)
else
v.y = v.y - (1 * (1 - v.dist) + 1)
end
if not once and (v.x > theme.scr.w() and v.dir == 1 or v.x < -v.w and v.dir == 2
or v.y > theme.scr.h() and v.dir == 3 or v.y < - v.h and v.dir == 4) then
once = k
end
-- v.spr:copy(sprite.scr(), v.x, v.y)
end
if once then
local v = slides[once]
table.remove(slides, once)
table.insert(slides_pool, v)
local n = rnd(#slides_pool)
v = slides_pool[n]
scale_slide(v)
table.insert(slides, v)
table.remove(slides_pool, n)
table.sort(slides, function(a, b) return a.dist > b.dist end)
end
end
function draw_slides()
for k, v in ipairs(slides) do
v.spr:copy(sprite.scr(), v.x, v.y)
end
end
local SLIDES_NR = 8
function load_slides()
scandir()
for _ = 1, SLIDES_NR do
if #slides_pool == 0 then
break
end
local n = rnd(#slides_pool)
table.insert(slides, slides_pool[n])
table.remove(slides_pool, n)
end
DIST = #slides
for k, v in ipairs(slides) do
scale_slide(v)
end
table.sort(slides, function(a, b) return a.dist > b.dist end)
end
function process_tiles()
local y = rnd(HH)
local x = rnd(WW)
local cell = tiles[y][x]
if cell.dir == 1 then
cell.lev = cell.lev + (rnd(64) + 32)
else
cell.lev = cell.lev - (rnd(64) + 32)
end
if cell.lev > 255 then
cell.dir = 2
cell.lev = 255
color(x, y)
elseif cell.lev < 0 then
cell.dir = 1
cell.lev = 0
color(x, y)
end
end
function color(x, y)
local COL = tiles[y][x].col
COL[1] = 0 -- rnd(255)
COL[2] = 255 -- rnd(255)
COL[3] = 255 -- rnd(255)
end
local last_t = 0
local frames = 0
local frames_t = {}
local function add_frame()
frames = frames + 1
if frames > 1000 then
frames = frames - 1
table.remove(frames_t, 1)
end
frames_t[frames] = instead.ticks()
end
function game:timer()
local t = instead.ticks()
-- if frames >= 1000 then
-- t = t - frames_t[1]
-- end
-- local fps = frames * 1000 / t
-- if fps > 41 then
-- return
-- end
process_tiles()
process_slides()
-- if fps < 40 then
-- add_frame()
-- return
-- end
-- add_frame()
sprite.scr():fill 'black'
draw_tiles()
draw_slides()
logo(0, 0)
end
function scandir()
for d in std.readdir 'screen' do
if d:find("%.png$") then
table.insert(slides_pool, { nam = "screen/"..d })
end
dprint("Scan: ", d)
end
end
function start()
if not sprite.direct(true) then
error("Включите собственные темы игр")
end
sprite.scr():fill 'black'
for y = 1, HY do
if not tiles[y] then
tiles[y] = {}
end
for x = 1, WX do
tiles[y][x] = { lev = rnd(128), dir = rnd(2), col = {} }
color(x, y)
end
end
load_slides()
logo_init()
timer:set(20)
end
|
fixes in podcast demo
|
fixes in podcast demo
|
Lua
|
mit
|
gl00my/stead3
|
64051b0ab47f71efdeb723aee145553496b17b38
|
script/c80800067.lua
|
script/c80800067.lua
|
--オノマト連攜
function c80800067.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_TOHAND+CATEGORY_SEARCH)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetCost(c80800067.cost)
e1:SetTarget(c80800067.target)
e1:SetOperation(c80800067.activate)
c:RegisterEffect(e1)
end
function c80800067.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetFlagEffect(tp,80800067)==0 end
Duel.RegisterFlagEffect(tp,80800067,RESET_PHASE+PHASE_END,EFFECT_FLAG_OATH,1)
end
function c80800067.filter(c)
return c:IsType(TYPE_MONSTER) and (c:IsSetCard(0x54) or c:IsSetCard(0x59) or c:IsSetCard(0x82) or c:IsSetCard(0x92)) and c:IsAbleToHand()
end
function c80800067.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c80800067.filter,tp,LOCATION_DECK,0,1,nil) end
Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK)
end
function c80800067.refilter(c,cd,cod)
return c==cd and c:IsSetCard(cod)
end
function c80800067.activate(e,tp,eg,ep,ev,re,r,rp)
local g=Duel.GetMatchingGroup(c80800067.filter,tp,LOCATION_DECK,0,nil)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g1=g:Select(tp,1,1,nil)
local sc=0
local cod=nil
while sc<4 do
if(sc==0)then cod=0x54 end
if(sc==1)then cod=0x59 end
if(sc==2)then cod=0x82 end
if(sc==3)then cod=0x92 end
if g:IsExists(c80800067.refilter,1,nil,g1:GetFirst(),cod) then
g:Remove(Card.IsSetCard,nil,cod)
end
sc=sc+1
end
if g:GetCount()>0 and Duel.SelectYesNo(tp,aux.Stringid(80800067,0)) then
local g2=g:Select(tp,1,1,nil)
g1:Merge(g2)
end
Duel.SendtoHand(g1,nil,REASON_EFFECT)
Duel.ConfirmCards(1-tp,g1)
end
|
--オノマト連攜
function c80800067.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_TOHAND+CATEGORY_SEARCH)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetCost(c80800067.cost)
e1:SetTarget(c80800067.target)
e1:SetOperation(c80800067.activate)
c:RegisterEffect(e1)
end
function c80800067.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetFlagEffect(tp,80800067)==0 and
Duel.IsExistingMatchingCard(Card.IsAbleToGraveAsCost,tp,LOCATION_HAND,0,1,e:GetHandler()) end
local g=Duel.SelectMatchingCard(tp,Card.IsAbleToGraveAsCost,tp,LOCATION_HAND,0,1,1,nil)
Duel.SendtoGrave(g,REASON_COST)
Duel.RegisterFlagEffect(tp,80800067,RESET_PHASE+PHASE_END,EFFECT_FLAG_OATH,1)
end
function c80800067.filter(c)
return c:IsType(TYPE_MONSTER) and (c:IsSetCard(0x54) or c:IsSetCard(0x59) or c:IsSetCard(0x82) or c:IsSetCard(0x92)) and c:IsAbleToHand()
end
function c80800067.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c80800067.filter,tp,LOCATION_DECK,0,1,nil) end
Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK)
end
function c80800067.refilter(c,cd,cod)
return c==cd and c:IsSetCard(cod)
end
function c80800067.activate(e,tp,eg,ep,ev,re,r,rp)
local g=Duel.GetMatchingGroup(c80800067.filter,tp,LOCATION_DECK,0,nil)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g1=g:Select(tp,1,1,nil)
local sc=0
local cod=nil
while sc<4 do
if(sc==0)then cod=0x54 end
if(sc==1)then cod=0x59 end
if(sc==2)then cod=0x82 end
if(sc==3)then cod=0x92 end
if g:IsExists(c80800067.refilter,1,nil,g1:GetFirst(),cod) then
g:Remove(Card.IsSetCard,nil,cod)
end
sc=sc+1
end
if g:GetCount()>0 and Duel.SelectYesNo(tp,aux.Stringid(80800067,0)) then
local g2=g:Select(tp,1,1,nil)
g1:Merge(g2)
end
Duel.SendtoHand(g1,nil,REASON_EFFECT)
Duel.ConfirmCards(1-tp,g1)
end
|
fix add cost
|
fix add cost
|
Lua
|
mit
|
Tic-Tac-Toc/DevProLauncher,sidschingis/DevProLauncher,SuperAndroid17/DevProLauncher
|
e2b2312333675cea0de7c5abcad2686321338b89
|
Roster.lua
|
Roster.lua
|
-------------------------------------------------------------------------------
-- Roster handling code
-------------------------------------------------------------------------------
function EPGP:GetRoster()
if (not self.roster) then
self.roster = { }
end
return self.roster
end
function EPGP:GetAlts()
if (not self.alts) then
self.alts = { }
end
return self.alts
end
function EPGP:SetRoster(r)
assert(r and type(r) == "table", "Roster is not a table!")
self.roster = r
end
-- Reads roster from server
function EPGP:PullRoster()
-- Figure out alts
local alts = GetGuildInfoText() or ""
local alts_table = self:GetAlts()
for from, to in string.gfind(alts, "(%a+):(%a+)\n") do
self:Debug("Adding %s as an alt for %s", to, from)
alts_table[to] = from
end
-- Update roster
for i = 1, GetNumGuildMembers(true) do
local name, _, _, _, class, _, note, officernote, _, _ = GetGuildRosterInfo(i)
local roster = self:GetRoster()
if (name) then
roster[name] = {
class, self:PointString2Table(note), self:PointString2Table(officernote)
}
end
end
end
-- Writes roster to server
function EPGP:PushRoster()
for i = 1, GetNumGuildMembers(true) do
local name, _, _, _, _, _, _, _, _, _ = GetGuildRosterInfo(i)
local roster = self:GetRoster()
if (name and roster[name]) then
local _, ep, gp = unpack(roster[name])
local note = self:PointTable2String(ep)
local officernote = self:PointTable2String(gp)
GuildRosterSetPublicNote(i, note)
GuildRosterSetOfficerNote(i, officernote)
end
end
end
-------------------------------------------------------------------------------
-- EP/GP manipulation
--
-- We use public/officers notes to keep track of EP/GP. Each note has storage
-- for a string of max length of 31. So with two bytes for each score, we can
-- have up to 15 numbers in it, which gives a max raid window of 15.
--
-- NOTE: Each number is in hex which means that we can have max 256 GP/EP for
-- each raid. This needs to be improved to raise the limit.
--
-- EPs are stored in the public note. The first byte is the EPs gathered for
-- the current raid. The second is the EPs gathered in the previous raid (of
-- the guild not the membeer). Ditto for the rest.
--
-- GPs are stored in the officers note, in a similar manner as the EPs.
--
-- Bonus EPs are added to the last/current raid.
function EPGP:PointString2Table(s)
if (string.len(s) == 0) then
local EMPTY_POINTS = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }
return EMPTY_POINTS
end
local t = { }
for i = 1, string.len(s), 2 do
local val = self:Decode(string.sub(s, i, i+1))
table.insert(t, val)
end
return t
end
function EPGP:PointTable2String(t)
local s = ""
for k, v in pairs(t) do
local ss = string.format("%02s", self:Encode(v))
assert(string.len(ss) == 2)
s = s .. ss
end
return s
end
function EPGP:GetEPGP(name)
assert(name and type(name) == "string")
local roster = self:GetRoster()
assert(roster[name], "Cannot find member record to update!")
local _, ep, gp = unpack(roster[name])
assert(ep and gp, "Member record corrupted!")
return ep, gp
end
function EPGP:SetEPGP(name, ep, gp)
assert(name and type(name) == "string")
assert(ep and type(ep) == "table")
assert(gp and type(gp) == "table")
local roster = self:GetRoster()
assert(roster[name], "Cannot find member record to update!")
local class, _, _ = unpack(roster[name])
roster[name] = { class, ep, gp }
end
-- Sets all EP/GP to 0
function EPGP:ResetEPGP()
for i = 1, GetNumGuildMembers(true) do
GuildRosterSetPublicNote(i, "")
GuildRosterSetOfficerNote(i, "")
end
GuildRoster()
self:Report("All EP/GP are reset.")
end
function EPGP:NewRaid()
local roster = self:GetRoster()
for n, t in pairs(roster) do
local name, _, ep, gp = n, unpack(t)
table.remove(ep)
table.insert(ep, 1, 0)
table.remove(gp)
table.insert(gp, 1, 0)
self:SetEPGP(name, ep, gp)
end
self:PushRoster()
self:Report("Created new raid.")
end
function EPGP:ResolveMember(member)
local alts = self:GetAlts()
while (alts[member]) do
member = alts[member]
end
return member
end
function EPGP:AddEP2Member(member, points)
member = self:ResolveMember(member)
local ep, gp = self:GetEPGP(member)
ep[1] = ep[1] + tonumber(points)
self:SetEPGP(member, ep, gp)
self:PushRoster()
self:Report("Added " .. tostring(points) .. " EPs to " .. member .. ".")
end
function EPGP:AddEP2Raid(points)
local raid = { }
for i = 1, GetNumRaidMembers() do
local name, _, _, _, _, _, zone, _, _ = GetRaidRosterInfo(i)
if (zone == self.current_zone) then
self:AddEP2Member(name, points)
end
end
self:PushRoster()
end
function EPGP:AddGP2Member(member, points)
member = self:ResolveMember(member)
local ep, gp = self:GetEPGP(member)
gp[1] = gp[1] + tonumber(points)
self:SetEPGP(member, ep, gp)
self:PushRoster()
self:Report("Added " .. tostring(points) .. " GPs to " .. member .. ".")
end
|
-------------------------------------------------------------------------------
-- Roster handling code
-------------------------------------------------------------------------------
function EPGP:GetRoster()
if (not self.roster) then
self.roster = { }
end
return self.roster
end
function EPGP:GetAlts()
if (not self.alts) then
self.alts = { }
end
return self.alts
end
function EPGP:SetRoster(r)
assert(r and type(r) == "table", "Roster is not a table!")
self.roster = r
end
-- Reads roster from server
function EPGP:PullRoster()
-- Figure out alts
local alts = GetGuildInfoText() or ""
local alts_table = self:GetAlts()
for from, to in string.gfind(alts, "(%a+):(%a+)\n") do
self:Debug("Adding %s as an alt for %s", to, from)
alts_table[to] = from
end
-- Update roster
for i = 1, GetNumGuildMembers(true) do
local name, _, _, _, class, _, note, officernote, _, _ = GetGuildRosterInfo(i)
local roster = self:GetRoster()
if (name) then
roster[name] = {
class, self:PointString2Table(note), self:PointString2Table(officernote)
}
end
end
end
-- Writes roster to server
function EPGP:PushRoster()
for i = 1, GetNumGuildMembers(true) do
local name, _, _, _, _, _, _, _, _, _ = GetGuildRosterInfo(i)
local roster = self:GetRoster()
if (name and roster[name]) then
local _, ep, gp = unpack(roster[name])
local note = self:PointTable2String(ep)
local officernote = self:PointTable2String(gp)
GuildRosterSetPublicNote(i, note)
GuildRosterSetOfficerNote(i, officernote)
end
end
-- Cause the roster to be pulled from server
GuildRoster()
end
-------------------------------------------------------------------------------
-- EP/GP manipulation
--
-- We use public/officers notes to keep track of EP/GP. Each note has storage
-- for a string of max length of 31. So with two bytes for each score, we can
-- have up to 15 numbers in it, which gives a max raid window of 15.
--
-- NOTE: Each number is in hex which means that we can have max 256 GP/EP for
-- each raid. This needs to be improved to raise the limit.
--
-- EPs are stored in the public note. The first byte is the EPs gathered for
-- the current raid. The second is the EPs gathered in the previous raid (of
-- the guild not the membeer). Ditto for the rest.
--
-- GPs are stored in the officers note, in a similar manner as the EPs.
--
-- Bonus EPs are added to the last/current raid.
function EPGP:PointString2Table(s)
if (string.len(s) == 0) then
local EMPTY_POINTS = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }
return EMPTY_POINTS
end
local t = { }
for i = 1, string.len(s), 2 do
local val = self:Decode(string.sub(s, i, i+1))
table.insert(t, val)
end
return t
end
function EPGP:PointTable2String(t)
local s = ""
for k, v in pairs(t) do
local ss = string.format("%02s", self:Encode(v))
assert(string.len(ss) == 2)
s = s .. ss
end
return s
end
function EPGP:GetEPGP(name)
assert(name and type(name) == "string")
local roster = self:GetRoster()
assert(roster[name], "Cannot find member record to update!")
local _, ep, gp = unpack(roster[name])
assert(ep and gp, "Member record corrupted!")
return ep, gp
end
function EPGP:SetEPGP(name, ep, gp)
assert(name and type(name) == "string")
assert(ep and type(ep) == "table")
assert(gp and type(gp) == "table")
local roster = self:GetRoster()
assert(roster[name], "Cannot find member record to update!")
local class, _, _ = unpack(roster[name])
roster[name] = { class, ep, gp }
end
-- Sets all EP/GP to 0
function EPGP:ResetEPGP()
for i = 1, GetNumGuildMembers(true) do
GuildRosterSetPublicNote(i, "")
GuildRosterSetOfficerNote(i, "")
end
GuildRoster()
self:Report("All EP/GP are reset.")
end
function EPGP:NewRaid()
local roster = self:GetRoster()
for n, t in pairs(roster) do
local name, _, ep, gp = n, unpack(t)
table.remove(ep)
table.insert(ep, 1, 0)
table.remove(gp)
table.insert(gp, 1, 0)
self:SetEPGP(name, ep, gp)
end
self:PushRoster()
self:Report("Created new raid.")
end
function EPGP:ResolveMember(member)
local alts = self:GetAlts()
while (alts[member]) do
member = alts[member]
end
return member
end
function EPGP:AddEP2Member(member, points)
member = self:ResolveMember(member)
local ep, gp = self:GetEPGP(member)
ep[1] = ep[1] + tonumber(points)
self:SetEPGP(member, ep, gp)
self:PushRoster()
self:Report("Added " .. tostring(points) .. " EPs to " .. member .. ".")
end
function EPGP:AddEP2Raid(points)
local raid = { }
for i = 1, GetNumRaidMembers() do
local name, _, _, _, _, _, zone, _, _ = GetRaidRosterInfo(i)
if (zone == self.current_zone) then
self:AddEP2Member(name, points)
end
end
self:PushRoster()
end
function EPGP:AddGP2Member(member, points)
member = self:ResolveMember(member)
local ep, gp = self:GetEPGP(member)
gp[1] = gp[1] + tonumber(points)
self:SetEPGP(member, ep, gp)
self:PushRoster()
self:Report("Added " .. tostring(points) .. " GPs to " .. member .. ".")
end
|
Fix immediate refresh of roster when a change in EP or GP happens.
|
Fix immediate refresh of roster when a change in EP or GP happens.
|
Lua
|
bsd-3-clause
|
hayword/tfatf_epgp,ceason/epgp-tfatf,ceason/epgp-tfatf,sheldon/epgp,protomech/epgp-dkp-reloaded,hayword/tfatf_epgp,protomech/epgp-dkp-reloaded,sheldon/epgp
|
63d1eedade9a4a393d681bacd91610c4ec70cbf8
|
lua/sendScan.lua
|
lua/sendScan.lua
|
local geolyzer = require('component').geolyzer;
dofile 'tcp.lua'; -- todo: properly package this stuff
dofile 'trackPosition.lua';
function weightedAverage(n1, w1, n2, w2)
return (n1*w1 + n2*w2)/(w1 + w2);
end
function scanVolume(x, z, y, w, d, h, times)
-- default to 0 (which is true in lua)
times = (times - 1) or 0;
local pos = getPosition();
local result = {
x = x + pos.x,
y = y + pos.y,
z = z + pos.z,
w=w,
d=d,
data=geolyzer.scan(x, z, y, w, d, h)};
local weight = 1;
for i = 1, times do
local newScan = geolyzer.scan(x, z, y, w, d, h);
-- average all data points using weights
for j = 1, result.data.n do
result.data[j] = weightedAverage(result.data[j], weight, newScan[j], 1);
end
weight = weight + 1;
end
tcpWrite({['map data']=result});
end
function scanPlane(y, times)
times = (times - 1) or 0;
for x = -32, 32 do
scanVolume(x, -32, y, 1, 64, 1, times);
end
end
|
local geolyzer = require('component').geolyzer;
dofile 'tcp.lua'; -- todo: properly package this stuff
dofile 'trackPosition.lua';
function weightedAverage(n1, w1, n2, w2)
return (n1*w1 + n2*w2)/(w1 + w2);
end
function scanVolume(x, z, y, w, d, h, times)
-- default to 0 (which is true in lua)
if times then
times = times - 1;
else
times = 0;
end
local pos = getPosition();
local result = {
x = x + pos.x,
y = y + pos.y,
z = z + pos.z,
w=w,
d=d,
data=geolyzer.scan(x, z, y, w, d, h)};
local weight = 1;
for i = 1, times do
local newScan = geolyzer.scan(x, z, y, w, d, h);
-- average all data points using weights
for j = 1, result.data.n do
result.data[j] = weightedAverage(result.data[j], weight, newScan[j], 1);
end
weight = weight + 1;
end
tcpWrite({['map data']=result});
end
function scanPlane(y, times)
for x = -32, 32 do
scanVolume(x, -32, y, 1, 64, 1, times);
end
-- max shape volume is 64, but we can scan from -32 to 32, inclusive
-- that's 65, so we have one row we miss in the previous loop to scan
scanVolume(-32, 32, y, 64, 1, 1, times);
end
|
fixed the default value times parameter, scanPlane now scans one additional row it was missing before
|
fixed the default value times parameter, scanPlane now scans one additional row it was missing before
|
Lua
|
mit
|
dunstad/roboserver,dunstad/roboserver
|
79d8f8026c3e6fcd9c9e78f58d7cc5e6d7a9997c
|
premake.lua
|
premake.lua
|
project.name = "Premake4"
-- Project options
addoption("no-tests", "Build without automated tests")
-- Output directories
project.config["Debug"].bindir = "bin/debug"
project.config["Release"].bindir = "bin/release"
-- Packages
dopackage("src")
-- Cleanup code
function doclean(cmd, arg)
docommand(cmd, arg)
os.rmdir("bin")
os.rmdir("doc")
end
-- Release code
REPOS = "https://premake.svn.sourceforge.net/svnroot/premake"
TRUNK = "/trunk"
BRANCHES = "/branches/4.0-alpha/"
function dorelease(cmd, arg)
if (not arg) then
error "You must specify a version"
end
-------------------------------------------------------------------
-- Make sure everything is good before I start
-------------------------------------------------------------------
print("")
print("PRE-FLIGHT CHECKLIST")
print(" * is README up-to-date?")
print(" * is CHANGELOG up-to-date?")
print(" * did you test build with GCC?")
print(" * did you test build with Doxygen?")
print(" * are 'svn' (all) and '7z' (Windows) available?")
print("")
print("Press [Enter] to continue or [^C] to quit.")
io.stdin:read("*l")
-------------------------------------------------------------------
-- Set up environment
-------------------------------------------------------------------
local version = arg
os.mkdir("releases")
local folder = "premake-"..version
local trunk = REPOS..TRUNK
local branch = REPOS..BRANCHES..version
-------------------------------------------------------------------
-- Build and run all automated tests on working copy
-------------------------------------------------------------------
print("Building tests on working copy...")
os.execute("premake --target gnu >releases/release.log")
result = os.execute("make CONFIG=Release >releases/release.log")
if (result ~= 0) then
error("Test build failed; see release.log for details")
end
-------------------------------------------------------------------
-- Look for a release branch in SVN, and create one from trunk if necessary
-------------------------------------------------------------------
print("Checking for release branch...")
os.chdir("releases")
result = os.execute(string.format("svn ls %s >release.log 2>&1", branch))
if (result ~= 0) then
print("Creating release branch...")
result = os.execute(string.format('svn copy %s %s -m "Creating release branch for %s" >release.log', trunk, branch, version))
if (result ~= 0) then
error("Failed to create release branch at "..branch)
end
end
-------------------------------------------------------------------
-- Checkout a local copy of the release branch
-------------------------------------------------------------------
print("Getting source code from release branch...")
os.execute(string.format("svn co %s %s >release.log", branch, folder))
if (not os.fileexists(folder.."/README.txt")) then
error("Unable to checkout from repository at "..branch)
end
-------------------------------------------------------------------
-- Embed version numbers into the files
-------------------------------------------------------------------
-- (embed version #s)
-- (check into branch)
-------------------------------------------------------------------
-- Build the release binary for this platform
-------------------------------------------------------------------
print("Building release version...")
os.chdir(folder)
os.execute("premake --clean --no-tests --target gnu >../release.log")
os.chdir("bin/release")
if (windows) then
os.execute("make CONFIG=Release >../release.log")
result = os.execute(string.format("7z a -tzip ..\\..\\..\\premake-win32-%s.zip premake4.exe >../release.log", version))
elseif (macosx) then
os.execute('TARGET_ARCH="-arch i386 -arch ppc" make CONFIG=Release >../release.log')
result = os.execute(string.format("tar czvf ../../../premake-macosx-%s.tar.gz premake4 >../release.log", version))
else
os.execute("make CONFIG=Release >../release.log")
result = os.execute(string.format("tar czvf ../../../premake-linux-%s.tar.gz bin/release/premake4 >../release.log", version))
end
if (result ~= 0) then
error("Failed to build binary package; see release.log for details")
end
os.chdir("../../..")
-------------------------------------------------------------------
-- Build the source code package (MacOSX only)
-------------------------------------------------------------------
if (macosx) then
result = os.execute(string.format("zip -r9 premake-src-%s.zip %s/* >release.log", version, folder))
if (result ~= 0) then
error("Failed to build source code package; see release.log for details")
end
end
-------------------------------------------------------------------
-- Clean up
-------------------------------------------------------------------
print("Cleaning up...")
os.rmdir(folder)
os.remove("release.log")
-------------------------------------------------------------------
-- Next steps
-------------------------------------------------------------------
if (windows) then
print("DONE - now run release script under Linux")
elseif (linux) then
print("DONE - now run release script under Mac OS X")
else
print("DONE - really this time")
end
end
|
project.name = "Premake4"
-- Project options
addoption("no-tests", "Build without automated tests")
-- Output directories
project.config["Debug"].bindir = "bin/debug"
project.config["Release"].bindir = "bin/release"
-- Packages
dopackage("src")
-- Cleanup code
function doclean(cmd, arg)
docommand(cmd, arg)
os.rmdir("bin")
os.rmdir("doc")
end
-- Release code
REPOS = "https://premake.svn.sourceforge.net/svnroot/premake"
TRUNK = "/trunk"
BRANCHES = "/branches/4.0-alpha/"
function dorelease(cmd, arg)
if (not arg) then
error "You must specify a version"
end
-------------------------------------------------------------------
-- Make sure everything is good before I start
-------------------------------------------------------------------
print("")
print("PRE-FLIGHT CHECKLIST")
print(" * is README up-to-date?")
print(" * is CHANGELOG up-to-date?")
print(" * did you test build with GCC?")
print(" * did you test build with Doxygen?")
print(" * are 'svn' (all) and '7z' (Windows) available?")
print("")
print("Press [Enter] to continue or [^C] to quit.")
io.stdin:read("*l")
-------------------------------------------------------------------
-- Set up environment
-------------------------------------------------------------------
local version = arg
os.mkdir("releases")
local folder = "premake-"..version
local trunk = REPOS..TRUNK
local branch = REPOS..BRANCHES..version
-------------------------------------------------------------------
-- Build and run all automated tests on working copy
-------------------------------------------------------------------
print("Building tests on working copy...")
os.execute("premake --target gnu >releases/release.log")
result = os.execute("make CONFIG=Release >releases/release.log")
if (result ~= 0) then
error("Test build failed; see release.log for details")
end
-------------------------------------------------------------------
-- Look for a release branch in SVN, and create one from trunk if necessary
-------------------------------------------------------------------
print("Checking for release branch...")
os.chdir("releases")
result = os.execute(string.format("svn ls %s >release.log 2>&1", branch))
if (result ~= 0) then
print("Creating release branch...")
result = os.execute(string.format('svn copy %s %s -m "Creating release branch for %s" >release.log', trunk, branch, version))
if (result ~= 0) then
error("Failed to create release branch at "..branch)
end
end
-------------------------------------------------------------------
-- Checkout a local copy of the release branch
-------------------------------------------------------------------
print("Getting source code from release branch...")
os.execute(string.format("svn co %s %s >release.log", branch, folder))
if (not os.fileexists(folder.."/README.txt")) then
error("Unable to checkout from repository at "..branch)
end
-------------------------------------------------------------------
-- Embed version numbers into the files
-------------------------------------------------------------------
-- (embed version #s)
-- (check into branch)
-------------------------------------------------------------------
-- Build the release binary for this platform
-------------------------------------------------------------------
print("Building release version...")
os.chdir(folder)
os.execute("premake --clean --no-tests --target gnu >../release.log")
if (windows) then
os.execute("make CONFIG=Release >../release.log")
os.chdir("bin/release")
result = os.execute(string.format("7z a -tzip ..\\..\\..\\premake-win32-%s.zip premake4.exe >../release.log", version))
elseif (macosx) then
os.execute('TARGET_ARCH="-arch i386 -arch ppc" make CONFIG=Release >../release.log')
os.chdir("bin/release")
result = os.execute(string.format("tar czvf ../../../premake-macosx-%s.tar.gz premake4 >../release.log", version))
else
os.execute("make CONFIG=Release >../release.log")
os.chdir("bin/release")
result = os.execute(string.format("tar czvf ../../../premake-linux-%s.tar.gz bin/release/premake4 >../release.log", version))
end
if (result ~= 0) then
error("Failed to build binary package; see release.log for details")
end
os.chdir("../../..")
-------------------------------------------------------------------
-- Build the source code package (MacOSX only)
-------------------------------------------------------------------
if (macosx) then
result = os.execute(string.format("zip -r9 premake-src-%s.zip %s/* >release.log", version, folder))
if (result ~= 0) then
error("Failed to build source code package; see release.log for details")
end
end
-------------------------------------------------------------------
-- Clean up
-------------------------------------------------------------------
print("Cleaning up...")
os.rmdir(folder)
os.remove("release.log")
-------------------------------------------------------------------
-- Next steps
-------------------------------------------------------------------
if (windows) then
print("DONE - now run release script under Linux")
elseif (linux) then
print("DONE - now run release script under Mac OS X")
else
print("DONE - really this time")
end
end
|
Another fix to my fix
|
Another fix to my fix
|
Lua
|
bsd-3-clause
|
soundsrc/premake-stable,grbd/premake-core,sleepingwit/premake-core,tvandijck/premake-core,dcourtois/premake-core,tvandijck/premake-core,starkos/premake-core,prapin/premake-core,prapin/premake-core,bravnsgaard/premake-core,alarouche/premake-core,noresources/premake-core,starkos/premake-core,dcourtois/premake-core,sleepingwit/premake-core,Yhgenomics/premake-core,jstewart-amd/premake-core,PlexChat/premake-core,tvandijck/premake-core,kankaristo/premake-core,premake/premake-core,LORgames/premake-core,tritao/premake-core,bravnsgaard/premake-core,lizh06/premake-core,akaStiX/premake-core,aleksijuvani/premake-core,martin-traverse/premake-core,TurkeyMan/premake-core,tritao/premake-core,alarouche/premake-core,noresources/premake-core,CodeAnxiety/premake-core,Meoo/premake-core,dcourtois/premake-core,prapin/premake-core,LORgames/premake-core,soundsrc/premake-core,premake/premake-core,Tiger66639/premake-core,CodeAnxiety/premake-core,LORgames/premake-core,resetnow/premake-core,premake/premake-core,CodeAnxiety/premake-core,resetnow/premake-core,jsfdez/premake-core,mandersan/premake-core,felipeprov/premake-core,felipeprov/premake-core,lizh06/premake-core,lizh06/premake-4.x,TurkeyMan/premake-core,alarouche/premake-core,mendsley/premake-core,starkos/premake-core,dcourtois/premake-core,grbd/premake-core,soundsrc/premake-core,mandersan/premake-core,tritao/premake-core,Blizzard/premake-core,LORgames/premake-core,resetnow/premake-core,martin-traverse/premake-core,CodeAnxiety/premake-core,soundsrc/premake-stable,CodeAnxiety/premake-core,TurkeyMan/premake-core,ryanjmulder/premake-4.x,felipeprov/premake-core,jstewart-amd/premake-core,mandersan/premake-core,lizh06/premake-core,noresources/premake-core,saberhawk/premake-core,dcourtois/premake-core,Zefiros-Software/premake-core,starkos/premake-core,Tiger66639/premake-core,saberhawk/premake-core,noresources/premake-core,Blizzard/premake-core,mendsley/premake-core,lizh06/premake-4.x,aleksijuvani/premake-core,mandersan/premake-core,Meoo/premake-core,Yhgenomics/premake-core,premake/premake-core,jsfdez/premake-core,mandersan/premake-core,soundsrc/premake-stable,aleksijuvani/premake-core,kankaristo/premake-core,lizh06/premake-4.x,tvandijck/premake-core,akaStiX/premake-core,premake/premake-core,aleksijuvani/premake-core,alarouche/premake-core,starkos/premake-core,premake/premake-4.x,ryanjmulder/premake-4.x,Tiger66639/premake-core,xriss/premake-core,jstewart-amd/premake-core,sleepingwit/premake-core,PlexChat/premake-core,tvandijck/premake-core,Blizzard/premake-core,tritao/premake-core,martin-traverse/premake-core,Meoo/premake-core,premake/premake-core,soundsrc/premake-core,xriss/premake-core,mendsley/premake-core,premake/premake-4.x,akaStiX/premake-core,sleepingwit/premake-core,Zefiros-Software/premake-core,jstewart-amd/premake-core,PlexChat/premake-core,soundsrc/premake-core,saberhawk/premake-core,bravnsgaard/premake-core,Tiger66639/premake-core,bravnsgaard/premake-core,jstewart-amd/premake-core,kankaristo/premake-core,grbd/premake-core,resetnow/premake-core,lizh06/premake-4.x,soundsrc/premake-core,soundsrc/premake-stable,sleepingwit/premake-core,kankaristo/premake-core,TurkeyMan/premake-core,noresources/premake-core,Zefiros-Software/premake-core,xriss/premake-core,mendsley/premake-core,Zefiros-Software/premake-core,ryanjmulder/premake-4.x,dcourtois/premake-core,ryanjmulder/premake-4.x,jsfdez/premake-core,akaStiX/premake-core,xriss/premake-core,aleksijuvani/premake-core,LORgames/premake-core,grbd/premake-core,starkos/premake-core,felipeprov/premake-core,jsfdez/premake-core,Yhgenomics/premake-core,Blizzard/premake-core,premake/premake-4.x,saberhawk/premake-core,prapin/premake-core,Zefiros-Software/premake-core,dcourtois/premake-core,martin-traverse/premake-core,Blizzard/premake-core,TurkeyMan/premake-core,Yhgenomics/premake-core,PlexChat/premake-core,xriss/premake-core,premake/premake-4.x,noresources/premake-core,lizh06/premake-core,bravnsgaard/premake-core,noresources/premake-core,resetnow/premake-core,starkos/premake-core,Blizzard/premake-core,mendsley/premake-core,premake/premake-core,Meoo/premake-core
|
3fd27251225acaaac9cb2e4a2accf7fdb139844e
|
profile.lua
|
profile.lua
|
-- Begin of globals
bollards_whitelist = { [""] = true, ["cattle_grid"] = true, ["border_control"] = true, ["toll_booth"] = true, ["no"] = true}
access_tag_whitelist = { ["yes"] = true, ["motorcar"] = true, ["motor_vehicle"] = true, ["vehicle"] = true, ["permissive"] = true, ["designated"] = true }
access_tag_blacklist = { ["no"] = true, ["private"] = true, ["agricultural"] = true, ["forestery"] = true }
access_tag_restricted = { ["destination"] = true, ["delivery"] = true }
access_tags = { "motorcar", "motor_vehicle", "vehicle" }
service_tag_restricted = { ["parking_aisle"] = true }
ignore_in_grid = { ["ferry"] = true, ["pier"] = true }
speed_profile = {
["motorway"] = 90,
["motorway_link"] = 75,
["trunk"] = 85,
["trunk_link"] = 70,
["primary"] = 65,
["primary_link"] = 60,
["secondary"] = 55,
["secondary_link"] = 50,
["tertiary"] = 40,
["tertiary_link"] = 30,
["unclassified"] = 25,
["residential"] = 25,
["living_street"] = 10,
["service"] = 15,
-- ["track"] = 5,
["ferry"] = 5,
["pier"] = 5,
["default"] = 50
}
take_minimum_of_speeds = true
obey_oneway = true
-- End of globals
function node_function (node)
local barrier = node.tags:Find ("barrier")
local access = node.tags:Find ("access")
local traffic_signal = node.tags:Find("highway")
--flag node if it carries a traffic light
if traffic_signal == "traffic_signals" then
node.traffic_light = true;
end
--flag node as unpassable if it black listed as unpassable
if access_tag_blacklist[barrier] then
node.bollard = true;
end
--reverse the previous flag if there is an access tag specifying entrance
if node.bollard and not bollards_whitelist[barrier] and not access_tag_whitelist[barrier] then
node.bollard = false;
end
return 1
end
function way_function (way, numberOfNodesInWay)
-- A way must have two nodes or more
if(numberOfNodesInWay < 2) then
return 0;
end
-- First, get the properties of each way that we come across
local highway = way.tags:Find("highway")
local name = way.tags:Find("name")
local ref = way.tags:Find("ref")
local junction = way.tags:Find("junction")
local route = way.tags:Find("route")
local maxspeed = parseMaxspeed(way.tags:Find ( "maxspeed") )
local man_made = way.tags:Find("man_made")
local barrier = way.tags:Find("barrier")
local oneway = way.tags:Find("oneway")
local cycleway = way.tags:Find("cycleway")
local duration = way.tags:Find("duration")
local service = way.tags:Find("service")
local area = way.tags:Find("area")
local access = way.tags:Find("access")
-- Second parse the way according to these properties
if("yes" == area) then
return 0
end
-- Check if we are allowed to access the way
if access_tag_blacklist[access] ~=nil and access_tag_blacklist[access] then
return 0;
end
-- Check if our vehicle types are forbidden
for i,v in ipairs(access_tags) do
local mode_value = way.tags:Find(v)
if nil ~= mode_value and "no" == mode_value then
return 0;
end
end
-- Set the name that will be used for instructions
if "" ~= ref then
way.name = ref
elseif "" ~= name then
way.name = name
end
if "roundabout" == junction then
way.roundabout = true;
end
-- Handling ferries and piers
if (speed_profile[route] ~= nil and speed_profile[route] > 0) or
(speed_profile[man_made] ~= nil and speed_profile[man_made] > 0)
then
if durationIsValid(duration) then
way.speed = parseDuration / math.max(1, numberOfSegments-1);
way.is_duration_set = true;
end
way.direction = Way.bidirectional;
if speed_profile[route] ~= nil then
highway = route;
elseif speed_profile[man_made] ~= nil then
highway = man_made;
end
if not way.is_duration_set then
way.speed = speed_profile[highway]
end
end
-- Set the avg speed on the way if it is accessible by road class
if (speed_profile[highway] ~= nil and way.speed == -1 ) then
if (0 < maxspeed and not take_minimum_of_speeds) or (maxspeed == 0) then
maxspeed = math.huge
end
way.speed = math.min(speed_profile[highway], maxspeed)
end
-- Set the avg speed on ways that are marked accessible
if access_tag_whitelist[access] and way.speed == -1 then
if (0 < maxspeed and not take_minimum_of_speeds) or maxspeed == 0 then
maxspeed = math.huge
end
way.speed = math.min(speed_profile["default"], maxspeed)
end
-- Set access restriction flag if access is allowed under certain restrictions only
if access ~= "" and access_tag_restricted[access] then
way.is_access_restricted = true
end
-- Set access restriction flag if service is allowed under certain restrictions only
if service ~= "" and service_tag_restricted[service] then
way.is_access_restricted = true
end
-- Set direction according to tags on way
if obey_oneway then
if oneway == "no" or oneway == "0" or oneway == "false" then
way.direction = Way.bidirectional
elseif oneway == "-1" then
way.direction = Way.opposite
elseif oneway == "yes" or oneway == "1" or oneway == "true" or junction == "roundabout" or highway == "motorway_link" or highway == "motorway" then
way.direction = Way.oneway
else
way.direction = Way.bidirectional
end
else
way.direction = Way.bidirectional
end
-- Override general direction settings of there is a specific one for our mode of travel
if ignore_in_grid[highway] ~= nil and ignore_in_grid[highway] then
way.ignore_in_grid = true
end
way.type = 1
return 1
end
|
-- Begin of globals
bollards_whitelist = { [""] = true, ["cattle_grid"] = true, ["border_control"] = true, ["toll_booth"] = true, ["no"] = true, ["sally_port"] = true, ["gate"] = true}
access_tag_whitelist = { ["yes"] = true, ["motorcar"] = true, ["motor_vehicle"] = true, ["vehicle"] = true, ["permissive"] = true, ["designated"] = true }
access_tag_blacklist = { ["no"] = true, ["private"] = true, ["agricultural"] = true, ["forestery"] = true }
access_tag_restricted = { ["destination"] = true, ["delivery"] = true }
access_tags = { "motorcar", "motor_vehicle", "vehicle" }
service_tag_restricted = { ["parking_aisle"] = true }
ignore_in_grid = { ["ferry"] = true, ["pier"] = true }
speed_profile = {
["motorway"] = 90,
["motorway_link"] = 75,
["trunk"] = 85,
["trunk_link"] = 70,
["primary"] = 65,
["primary_link"] = 60,
["secondary"] = 55,
["secondary_link"] = 50,
["tertiary"] = 40,
["tertiary_link"] = 30,
["unclassified"] = 25,
["residential"] = 25,
["living_street"] = 10,
["service"] = 15,
-- ["track"] = 5,
["ferry"] = 5,
["pier"] = 5,
["default"] = 50
}
take_minimum_of_speeds = true
obey_oneway = true
-- End of globals
function node_function (node)
local barrier = node.tags:Find ("barrier")
local access = node.tags:Find ("access")
local traffic_signal = node.tags:Find("highway")
--flag node if it carries a traffic light
if traffic_signal == "traffic_signals" then
node.traffic_light = true;
end
--flag node as unpassable if it black listed as unpassable
if access_tag_blacklist[barrier] then
node.bollard = true;
end
--reverse the previous flag if there is an access tag specifying entrance
if node.bollard and not bollards_whitelist[barrier] and not access_tag_whitelist[barrier] then
node.bollard = false;
end
return 1
end
function way_function (way, numberOfNodesInWay)
-- A way must have two nodes or more
if(numberOfNodesInWay < 2) then
return 0;
end
-- First, get the properties of each way that we come across
local highway = way.tags:Find("highway")
local name = way.tags:Find("name")
local ref = way.tags:Find("ref")
local junction = way.tags:Find("junction")
local route = way.tags:Find("route")
local maxspeed = parseMaxspeed(way.tags:Find ( "maxspeed") )
local man_made = way.tags:Find("man_made")
local barrier = way.tags:Find("barrier")
local oneway = way.tags:Find("oneway")
local cycleway = way.tags:Find("cycleway")
local duration = way.tags:Find("duration")
local service = way.tags:Find("service")
local area = way.tags:Find("area")
local access = way.tags:Find("access")
-- Second parse the way according to these properties
if("yes" == area) then
return 0
end
-- Check if we are allowed to access the way
if access_tag_blacklist[access] ~=nil and access_tag_blacklist[access] then
return 0;
end
-- Check if our vehicle types are forbidden
for i,v in ipairs(access_tags) do
local mode_value = way.tags:Find(v)
if nil ~= mode_value and "no" == mode_value then
return 0;
end
end
-- Set the name that will be used for instructions
if "" ~= ref then
way.name = ref
elseif "" ~= name then
way.name = name
end
if "roundabout" == junction then
way.roundabout = true;
end
-- Handling ferries and piers
if (speed_profile[route] ~= nil and speed_profile[route] > 0) or
(speed_profile[man_made] ~= nil and speed_profile[man_made] > 0)
then
if durationIsValid(duration) then
way.speed = parseDuration / math.max(1, numberOfSegments-1);
way.is_duration_set = true;
end
way.direction = Way.bidirectional;
if speed_profile[route] ~= nil then
highway = route;
elseif speed_profile[man_made] ~= nil then
highway = man_made;
end
if not way.is_duration_set then
way.speed = speed_profile[highway]
end
end
-- Set the avg speed on the way if it is accessible by road class
if (speed_profile[highway] ~= nil and way.speed == -1 ) then
if (0 < maxspeed and not take_minimum_of_speeds) or (maxspeed == 0) then
maxspeed = math.huge
end
way.speed = math.min(speed_profile[highway], maxspeed)
end
-- Set the avg speed on ways that are marked accessible
if access_tag_whitelist[access] and way.speed == -1 then
if (0 < maxspeed and not take_minimum_of_speeds) or maxspeed == 0 then
maxspeed = math.huge
end
way.speed = math.min(speed_profile["default"], maxspeed)
end
-- Set access restriction flag if access is allowed under certain restrictions only
if access ~= "" and access_tag_restricted[access] then
way.is_access_restricted = true
end
-- Set access restriction flag if service is allowed under certain restrictions only
if service ~= "" and service_tag_restricted[service] then
way.is_access_restricted = true
end
-- Set direction according to tags on way
if obey_oneway then
if oneway == "no" or oneway == "0" or oneway == "false" then
way.direction = Way.bidirectional
elseif oneway == "-1" then
way.direction = Way.opposite
elseif oneway == "yes" or oneway == "1" or oneway == "true" or junction == "roundabout" or highway == "motorway_link" or highway == "motorway" then
way.direction = Way.oneway
else
way.direction = Way.bidirectional
end
else
way.direction = Way.bidirectional
end
-- Override general direction settings of there is a specific one for our mode of travel
if ignore_in_grid[highway] ~= nil and ignore_in_grid[highway] then
way.ignore_in_grid = true
end
way.type = 1
return 1
end
|
Fixes issue #400
|
Fixes issue #400
|
Lua
|
bsd-2-clause
|
deniskoronchik/osrm-backend,hydrays/osrm-backend,ramyaragupathy/osrm-backend,bjtaylor1/osrm-backend,ibikecph/osrm-backend,Project-OSRM/osrm-backend,antoinegiret/osrm-backend,bjtaylor1/osrm-backend,raymond0/osrm-backend,duizendnegen/osrm-backend,nagyistoce/osrm-backend,frodrigo/osrm-backend,bitsteller/osrm-backend,keesklopt/matrix,neilbu/osrm-backend,ammeurer/osrm-backend,stevevance/Project-OSRM,hydrays/osrm-backend,antoinegiret/osrm-geovelo,Project-OSRM/osrm-backend,hydrays/osrm-backend,tkhaxton/osrm-backend,keesklopt/matrix,ibikecph/osrm-backend,Tristramg/osrm-backend,yuryleb/osrm-backend,yuryleb/osrm-backend,bjtaylor1/Project-OSRM-Old,chaupow/osrm-backend,chaupow/osrm-backend,Carsten64/OSRM-aux-git,bitsteller/osrm-backend,chaupow/osrm-backend,Conggge/osrm-backend,Tristramg/osrm-backend,ammeurer/osrm-backend,stevevance/Project-OSRM,agruss/osrm-backend,tkhaxton/osrm-backend,jpizarrom/osrm-backend,atsuyim/osrm-backend,Project-OSRM/osrm-backend,ramyaragupathy/osrm-backend,deniskoronchik/osrm-backend,KnockSoftware/osrm-backend,ammeurer/osrm-backend,atsuyim/osrm-backend,keesklopt/matrix,frodrigo/osrm-backend,jpizarrom/osrm-backend,felixguendling/osrm-backend,alex85k/Project-OSRM,nagyistoce/osrm-backend,bjtaylor1/osrm-backend,frodrigo/osrm-backend,frodrigo/osrm-backend,nagyistoce/osrm-backend,beemogmbh/osrm-backend,yuryleb/osrm-backend,alex85k/Project-OSRM,neilbu/osrm-backend,Project-OSRM/osrm-backend,ibikecph/osrm-backend,prembasumatary/osrm-backend,deniskoronchik/osrm-backend,Carsten64/OSRM-aux-git,antoinegiret/osrm-geovelo,ammeurer/osrm-backend,bjtaylor1/Project-OSRM-Old,duizendnegen/osrm-backend,arnekaiser/osrm-backend,skyborla/osrm-backend,agruss/osrm-backend,skyborla/osrm-backend,felixguendling/osrm-backend,Tristramg/osrm-backend,atsuyim/osrm-backend,yuryleb/osrm-backend,raymond0/osrm-backend,stevevance/Project-OSRM,bjtaylor1/Project-OSRM-Old,neilbu/osrm-backend,stevevance/Project-OSRM,Conggge/osrm-backend,ammeurer/osrm-backend,Carsten64/OSRM-aux-git,felixguendling/osrm-backend,oxidase/osrm-backend,KnockSoftware/osrm-backend,beemogmbh/osrm-backend,antoinegiret/osrm-backend,arnekaiser/osrm-backend,Conggge/osrm-backend,Carsten64/OSRM-aux-git,ramyaragupathy/osrm-backend,KnockSoftware/osrm-backend,KnockSoftware/osrm-backend,ammeurer/osrm-backend,oxidase/osrm-backend,Conggge/osrm-backend,bitsteller/osrm-backend,tkhaxton/osrm-backend,duizendnegen/osrm-backend,oxidase/osrm-backend,bjtaylor1/Project-OSRM-Old,duizendnegen/osrm-backend,keesklopt/matrix,oxidase/osrm-backend,agruss/osrm-backend,raymond0/osrm-backend,neilbu/osrm-backend,alex85k/Project-OSRM,prembasumatary/osrm-backend,arnekaiser/osrm-backend,antoinegiret/osrm-geovelo,prembasumatary/osrm-backend,raymond0/osrm-backend,beemogmbh/osrm-backend,antoinegiret/osrm-backend,arnekaiser/osrm-backend,deniskoronchik/osrm-backend,ammeurer/osrm-backend,jpizarrom/osrm-backend,bjtaylor1/osrm-backend,beemogmbh/osrm-backend,skyborla/osrm-backend,hydrays/osrm-backend
|
440f90f42a636a3f1cf17393e7d3360050aa7d41
|
kong/plugins/jwt/handler.lua
|
kong/plugins/jwt/handler.lua
|
local singletons = require "kong.singletons"
local BasePlugin = require "kong.plugins.base_plugin"
local cache = require "kong.tools.database_cache"
local responses = require "kong.tools.responses"
local constants = require "kong.constants"
local jwt_decoder = require "kong.plugins.jwt.jwt_parser"
local string_format = string.format
local ngx_re_gmatch = ngx.re.gmatch
local JwtHandler = BasePlugin:extend()
JwtHandler.PRIORITY = 1000
--- Retrieve a JWT in a request.
-- Checks for the JWT in URI parameters, then in the `Authorization` header.
-- @param request ngx request object
-- @param conf Plugin configuration
-- @return token JWT token contained in request or nil
-- @return err
local function retrieve_token(request, conf)
local uri_parameters = request.get_uri_args()
for _, v in ipairs(conf.uri_param_names) do
if uri_parameters[v] then
return uri_parameters[v]
end
end
local authorization_header = request.get_headers()["authorization"]
if authorization_header then
local iterator, iter_err = ngx_re_gmatch(authorization_header, "\\s*[Bb]earer\\s+(.+)")
if not iterator then
return nil, iter_err
end
local m, err = iterator()
if err then
return nil, err
end
if m and #m > 0 then
return m[1]
end
end
end
function JwtHandler:new()
JwtHandler.super.new(self, "jwt")
end
function JwtHandler:access(conf)
JwtHandler.super.access(self)
local token, err = retrieve_token(ngx.req, conf)
if err then
return responses.send_HTTP_INTERNAL_SERVER_ERROR(err)
end
if not token then
return responses.send_HTTP_UNAUTHORIZED()
end
-- Decode token to find out who the consumer is
local jwt, err = jwt_decoder:new(token)
if err then
return responses.send_HTTP_INTERNAL_SERVER_ERROR()
end
local claims = jwt.claims
local jwt_secret_key = claims[conf.key_claim_name]
if not jwt_secret_key then
return responses.send_HTTP_UNAUTHORIZED("No mandatory '"..conf.key_claim_name.."' in claims")
end
-- Retrieve the secret
local jwt_secret = cache.get_or_set(cache.jwtauth_credential_key(jwt_secret_key), function()
local rows, err = singletons.dao.jwt_secrets:find_all {key = jwt_secret_key}
if err then
return responses.send_HTTP_INTERNAL_SERVER_ERROR()
elseif #rows > 0 then
return rows[1]
end
end)
if not jwt_secret then
return responses.send_HTTP_FORBIDDEN("No credentials found for given '"..conf.key_claim_name.."'")
end
-- Verify "alg"
if jwt.header.alg ~= jwt_secret.algorithm then
return responses.send_HTTP_FORBIDDEN("Invalid algorithm")
end
local jwt_secret_value = jwt_secret.algorithm == "HS256" and jwt_secret.secret or jwt_secret.rsa_public_key
if conf.secret_is_base64 then
jwt_secret_value = jwt:b64_decode(jwt_secret_value)
end
-- Now verify the JWT signature
if not jwt:verify_signature(jwt_secret_value) then
return responses.send_HTTP_FORBIDDEN("Invalid signature")
end
-- Verify the JWT registered claims
local ok_claims, errors = jwt:verify_registered_claims(conf.claims_to_verify)
if not ok_claims then
return responses.send_HTTP_FORBIDDEN(errors)
end
-- Retrieve the consumer
local consumer = cache.get_or_set(cache.consumer_key(jwt_secret_key), function()
local consumer, err = singletons.dao.consumers:find {id = jwt_secret.consumer_id}
if err then
return responses.send_HTTP_INTERNAL_SERVER_ERROR(err)
end
return consumer
end)
-- However this should not happen
if not consumer then
return responses.send_HTTP_FORBIDDEN(string_format("Could not find consumer for '%s=%s'", conf.key_claim_name, jwt_secret_key))
end
ngx.req.set_header(constants.HEADERS.CONSUMER_ID, consumer.id)
ngx.req.set_header(constants.HEADERS.CONSUMER_CUSTOM_ID, consumer.custom_id)
ngx.req.set_header(constants.HEADERS.CONSUMER_USERNAME, consumer.username)
ngx.ctx.authenticated_credential = jwt_secret
end
return JwtHandler
|
local singletons = require "kong.singletons"
local BasePlugin = require "kong.plugins.base_plugin"
local cache = require "kong.tools.database_cache"
local responses = require "kong.tools.responses"
local constants = require "kong.constants"
local jwt_decoder = require "kong.plugins.jwt.jwt_parser"
local string_format = string.format
local ngx_re_gmatch = ngx.re.gmatch
local JwtHandler = BasePlugin:extend()
JwtHandler.PRIORITY = 1000
--- Retrieve a JWT in a request.
-- Checks for the JWT in URI parameters, then in the `Authorization` header.
-- @param request ngx request object
-- @param conf Plugin configuration
-- @return token JWT token contained in request or nil
-- @return err
local function retrieve_token(request, conf)
local uri_parameters = request.get_uri_args()
for _, v in ipairs(conf.uri_param_names) do
if uri_parameters[v] then
return uri_parameters[v]
end
end
local authorization_header = request.get_headers()["authorization"]
if authorization_header then
local iterator, iter_err = ngx_re_gmatch(authorization_header, "\\s*[Bb]earer\\s+(.+)")
if not iterator then
return nil, iter_err
end
local m, err = iterator()
if err then
return nil, err
end
if m and #m > 0 then
return m[1]
end
end
end
function JwtHandler:new()
JwtHandler.super.new(self, "jwt")
end
function JwtHandler:access(conf)
JwtHandler.super.access(self)
local token, err = retrieve_token(ngx.req, conf)
if err then
return responses.send_HTTP_INTERNAL_SERVER_ERROR(err)
end
if not token then
return responses.send_HTTP_UNAUTHORIZED()
end
-- Decode token to find out who the consumer is
local jwt, err = jwt_decoder:new(token)
if err then
return responses.send_HTTP_INTERNAL_SERVER_ERROR()
end
local claims = jwt.claims
local jwt_secret_key = claims[conf.key_claim_name]
if not jwt_secret_key then
return responses.send_HTTP_UNAUTHORIZED("No mandatory '"..conf.key_claim_name.."' in claims")
end
-- Retrieve the secret
local jwt_secret = cache.get_or_set(cache.jwtauth_credential_key(jwt_secret_key), function()
local rows, err = singletons.dao.jwt_secrets:find_all {key = jwt_secret_key}
if err then
return responses.send_HTTP_INTERNAL_SERVER_ERROR()
elseif #rows > 0 then
return rows[1]
end
end)
if not jwt_secret then
return responses.send_HTTP_FORBIDDEN("No credentials found for given '"..conf.key_claim_name.."'")
end
local algorithm = jwt_secret.algorithm or "HS256"
-- Verify "alg"
if jwt.header.alg ~= algorithm then
return responses.send_HTTP_FORBIDDEN("Invalid algorithm")
end
local jwt_secret_value = algorithm == "HS256" and jwt_secret.secret or jwt_secret.rsa_public_key
if conf.secret_is_base64 then
jwt_secret_value = jwt:b64_decode(jwt_secret_value)
end
-- Now verify the JWT signature
if not jwt:verify_signature(jwt_secret_value) then
return responses.send_HTTP_FORBIDDEN("Invalid signature")
end
-- Verify the JWT registered claims
local ok_claims, errors = jwt:verify_registered_claims(conf.claims_to_verify)
if not ok_claims then
return responses.send_HTTP_FORBIDDEN(errors)
end
-- Retrieve the consumer
local consumer = cache.get_or_set(cache.consumer_key(jwt_secret_key), function()
local consumer, err = singletons.dao.consumers:find {id = jwt_secret.consumer_id}
if err then
return responses.send_HTTP_INTERNAL_SERVER_ERROR(err)
end
return consumer
end)
-- However this should not happen
if not consumer then
return responses.send_HTTP_FORBIDDEN(string_format("Could not find consumer for '%s=%s'", conf.key_claim_name, jwt_secret_key))
end
ngx.req.set_header(constants.HEADERS.CONSUMER_ID, consumer.id)
ngx.req.set_header(constants.HEADERS.CONSUMER_CUSTOM_ID, consumer.custom_id)
ngx.req.set_header(constants.HEADERS.CONSUMER_USERNAME, consumer.username)
ngx.ctx.authenticated_credential = jwt_secret
end
return JwtHandler
|
fix(jwt) default algorithm to 'HS256'
|
fix(jwt) default algorithm to 'HS256'
When migrating from an older version of Kong, the 'algorithm' field is
left empty. Better to include it in the code rather than in the
migration to resolve the issue for users who already migrated.
Fix #1233
|
Lua
|
apache-2.0
|
beauli/kong,ccyphers/kong,salazar/kong,Kong/kong,Kong/kong,Mashape/kong,shiprabehera/kong,Kong/kong,icyxp/kong,akh00/kong,Vermeille/kong,jebenexer/kong,li-wl/kong,jerizm/kong,smanolache/kong
|
ce8ac69aa22088b6894ec49e3a9d9990c1a8a884
|
Peripherals/GPU/modules/window.lua
|
Peripherals/GPU/modules/window.lua
|
--GPU: Window and canvas creation.
--luacheck: push ignore 211
local Config, GPU, yGPU, GPUVars, DevKit = ...
--luacheck: pop
local events = require("Engine.events")
local RenderVars = GPUVars.Render
local WindowVars = GPUVars.Window
--==Localized Lua Library==--
local mathFloor = math.floor
--==Local Variables==--
local CPUKit = Config.CPUKit
local _Mobile = love.system.getOS() == "Android" or love.system.getOS() == "iOS" or Config._Mobile
local _LIKO_W, _LIKO_H = Config._LIKO_W or 192, Config._LIKO_H or 128 --LIKO-12 screen dimensions.
WindowVars.LIKO_X, WindowVars.LIKO_Y = 0,0 --LIKO-12 screen padding in the HOST screen.
local _PixelPerfect = Config._PixelPerfect --If the LIKO-12 screen must be scaled pixel perfect.
WindowVars.LIKOScale = mathFloor(Config._LIKOScale or 3) --The LIKO12 screen scale to the host screen scale.
WindowVars.Width, WindowVars.Height = _LIKO_W*WindowVars.LIKOScale, _LIKO_H*WindowVars.LIKOScale --The host window size.
if _Mobile then WindowVars.Width, WindowVars.Height = 0,0 end
--==Window creation==--
if not love.window.isOpen() then
love.window.setMode(WindowVars.Width,WindowVars.Height,{
vsync = 1,
resizable = true,
minwidth = _LIKO_W,
minheight = _LIKO_H
})
if Config.title then
love.window.setTitle(Config.title)
else
love.window.setTitle("LIKO-12 ".._LVERSION)
end
love.window.setIcon(love.image.newImageData("icon.png"))
end
--Incase if the host operating system decided to give us different window dimensions.
WindowVars.Width, WindowVars.Height = love.graphics.getDimensions()
--==Window termination==--
events.register("love:quit", function()
if love.window.isOpen() then
love.graphics.setCanvas()
love.window.close()
end
return false
end)
--==Window Events==--
--Hook the resize function
events.register("love:resize",function(w,h) --Do some calculations
WindowVars.Width, WindowVars.Height = w, h
local TSX, TSY = w/_LIKO_W, h/_LIKO_H --TestScaleX, TestScaleY
WindowVars.LIKOScale = (TSX < TSY) and TSX or TSY
if _PixelPerfect then WindowVars.LIKOScale = mathFloor(WindowVars.LIKOScale) end
WindowVars.LIKO_X, WindowVars.LIKO_Y = (WindowVars.Width-_LIKO_W*WindowVars.LIKOScale)/2, (WindowVars.Height-_LIKO_H*WindowVars.LIKOScale)/2
if _Mobile then WindowVars.LIKO_Y, RenderVars.AlwaysDrawTimer = 0, 1 end
RenderVars.ShouldDraw = true
end)
--Hook to some functions to redraw (when the window is moved, got focus, etc ...)
events.register("love:focus",function(f) if f then RenderVars.ShouldDraw = true end end) --Window got focus.
events.register("love:visible",function(v) if v then RenderVars.ShouldDraw = true end end) --Window got visible.
--File drop hook
events.register("love:filedropped", function(file)
file:open("r")
local data = file:read()
file:close()
if CPUKit then CPUKit.triggerEvent("filedropped",file:getFilename(),data) end
end)
--==Graphics Initializations==--
love.graphics.clear(0,0,0,1) --Clear the host screen.
events.trigger("love:resize", WindowVars.Width, WindowVars.Height) --Calculate LIKO12 scale to the host window for the first time.
--==GPU Window API==--
function GPU.screenSize() return _LIKO_W, _LIKO_H end
function GPU.screenWidth() return _LIKO_W end
function GPU.screenHeight() return _LIKO_H end
--==Helper functions for WindowVars==--
function WindowVars.HostToLiko(x,y) --Convert a position from HOST screen to LIKO12 screen.
return mathFloor((x - WindowVars.LIKO_X)/WindowVars.LIKOScale), mathFloor((y - WindowVars.LIKO_Y)/WindowVars.LIKOScale)
end
function WindowVars.LikoToHost(x,y) --Convert a position from LIKO12 screen to HOST
return mathFloor(x*WindowVars.LIKOScale + WindowVars.LIKO_X), mathFloor(y*WindowVars.LIKOScale + WindowVars.LIKO_Y)
end
--==GPUVars Exports==--
WindowVars.LIKO_W, WindowVars.LIKO_H = _LIKO_W, _LIKO_H
--==DevKit Exports==--
DevKit._LIKO_W = _LIKO_W
DevKit._LIKO_H = _LIKO_H
function DevKit.DevKitDraw(bool)
RenderVars.DevKitDraw = bool
end
|
--GPU: Window and canvas creation.
--luacheck: push ignore 211
local Config, GPU, yGPU, GPUVars, DevKit = ...
--luacheck: pop
local events = require("Engine.events")
local RenderVars = GPUVars.Render
local WindowVars = GPUVars.Window
--==Localized Lua Library==--
local mathFloor = math.floor
--==Local Variables==--
local CPUKit = Config.CPUKit
local _Mobile = love.system.getOS() == "Android" or love.system.getOS() == "iOS" or Config._Mobile
local _LIKO_W, _LIKO_H = Config._LIKO_W or 192, Config._LIKO_H or 128 --LIKO-12 screen dimensions.
WindowVars.LIKO_X, WindowVars.LIKO_Y = 0,0 --LIKO-12 screen padding in the HOST screen.
local _PixelPerfect = Config._PixelPerfect --If the LIKO-12 screen must be scaled pixel perfect.
WindowVars.LIKOScale = mathFloor(Config._LIKOScale or 3) --The LIKO12 screen scale to the host screen scale.
WindowVars.Width, WindowVars.Height = _LIKO_W*WindowVars.LIKOScale, _LIKO_H*WindowVars.LIKOScale --The host window size.
if _Mobile then WindowVars.Width, WindowVars.Height = 0,0 end
--==Window creation==--
if not love.window.isOpen() then
love.window.setMode(WindowVars.Width,WindowVars.Height,{
vsync = 1,
resizable = true,
minwidth = _LIKO_W,
minheight = _LIKO_H
})
if Config.title then
love.window.setTitle(Config.title)
else
love.window.setTitle("LIKO-12 ".._LVERSION)
end
love.window.setIcon(love.image.newImageData("icon.png"))
end
--Incase if the host operating system decided to give us different window dimensions.
WindowVars.Width, WindowVars.Height = love.graphics.getDimensions()
--==Window termination==--
events.register("love:quit", function()
if love.window.isOpen() then
love.graphics.setCanvas()
love.window.close()
end
return false
end)
--==Window Events==--
--Hook the resize function
events.register("love:resize",function(w,h) --Do some calculations
WindowVars.Width, WindowVars.Height = w, h
local TSX, TSY = w/_LIKO_W, h/_LIKO_H --TestScaleX, TestScaleY
WindowVars.LIKOScale = (TSX < TSY) and TSX or TSY
if _PixelPerfect then WindowVars.LIKOScale = mathFloor(WindowVars.LIKOScale) end
WindowVars.LIKO_X, WindowVars.LIKO_Y = (WindowVars.Width-_LIKO_W*WindowVars.LIKOScale)/2, (WindowVars.Height-_LIKO_H*WindowVars.LIKOScale)/2
if _Mobile then WindowVars.LIKO_Y, RenderVars.AlwaysDrawTimer = 0, 1 end
RenderVars.ShouldDraw = true
end)
--Hook to some functions to redraw (when the window is moved, got focus, etc ...)
events.register("love:focus",function(f) if f then RenderVars.ShouldDraw = true end end) --Window got focus.
events.register("love:visible",function(v) if v then RenderVars.ShouldDraw = true end end) --Window got visible.
--File drop hook
events.register("love:filedropped", function(file)
file:open("r")
local data = file:read()
file:close()
if CPUKit then CPUKit.triggerEvent("filedropped",file:getFilename(),data) end
end)
--Alt-Return (Fullscreen toggle) hook
local raltDown, lastWidth, lastHeight = false, 0, 0
events.register("love:keypressed", function(key, scancode,isrepeat)
if key == "ralt" then
raltDown = true --Had to use a workaround, for some reason isDown("ralt") is not working at Rami's laptop
elseif key == "return" and raltDown and not isrepeat then
local screenshot = GPU.screenshot():image()
local canvas = love.graphics.getCanvas() --Backup the canvas.
love.graphics.setCanvas() --Deactivate the canvas.
if love.window.getFullscreen() then --Go windowed
love.window.setMode(lastWidth,lastHeight,{
fullscreen = false,
vsync = 1,
resizable = true,
minwidth = _LIKO_W,
minheight = _LIKO_H
})
else --Go fullscreen
lastWidth, lastHeight = love.window.getMode()
love.window.setMode(0,0,{fullscreen=true})
end
events.trigger("love:resize", love.graphics.getDimensions()) --Make sure the canvas is scaled correctly
love.graphics.setCanvas{canvas,stencil=true} --Reactivate the canvas.
screenshot:draw() --Restore the backed up screenshot
end
end)
events.register("love:keyreleased", function(key, scancode)
if key == "ralt" then raltDown = false end
end)
--==Graphics Initializations==--
love.graphics.clear(0,0,0,1) --Clear the host screen.
events.trigger("love:resize", WindowVars.Width, WindowVars.Height) --Calculate LIKO12 scale to the host window for the first time.
--==GPU Window API==--
function GPU.screenSize() return _LIKO_W, _LIKO_H end
function GPU.screenWidth() return _LIKO_W end
function GPU.screenHeight() return _LIKO_H end
--==Helper functions for WindowVars==--
function WindowVars.HostToLiko(x,y) --Convert a position from HOST screen to LIKO12 screen.
return mathFloor((x - WindowVars.LIKO_X)/WindowVars.LIKOScale), mathFloor((y - WindowVars.LIKO_Y)/WindowVars.LIKOScale)
end
function WindowVars.LikoToHost(x,y) --Convert a position from LIKO12 screen to HOST
return mathFloor(x*WindowVars.LIKOScale + WindowVars.LIKO_X), mathFloor(y*WindowVars.LIKOScale + WindowVars.LIKO_Y)
end
--==GPUVars Exports==--
WindowVars.LIKO_W, WindowVars.LIKO_H = _LIKO_W, _LIKO_H
--==DevKit Exports==--
DevKit._LIKO_W = _LIKO_W
DevKit._LIKO_H = _LIKO_H
function DevKit.DevKitDraw(bool)
RenderVars.DevKitDraw = bool
end
|
Fix #253
|
Fix #253
|
Lua
|
mit
|
RamiLego4Game/LIKO-12
|
3fcd60fc2be0381d958f7a7909658d6f5404af4d
|
BN-absorber/BN-absorber.lua
|
BN-absorber/BN-absorber.lua
|
require('nn')
local absorb_bn_conv = function (w, b, mean, invstd, affine, gamma, beta)
w:cmul(invstd:view(w:size(1),1):repeatTensor(1,w:nElement()/w:size(1)))
b:add(-mean):cmul(invstd)
if affine then
w:cmul(gamma:view(w:size(1),1):repeatTensor(1,w:nElement()/w:size(1)))
b:cmul(gamma):add(beta)
end
end
local absorb_bn_deconv = function (w, b, mean, invstd, affine, gamma, beta)
w:cmul(invstd:view(b:size(1),1):repeatTensor(w:size(1),w:nElement()/w:size(1)/b:nElement()))
b:add(-mean):cmul(invstd)
if affine then
w:cmul(gamma:view(b:size(1),1):repeatTensor(w:size(1),w:nElement()/w:size(1)/b:nElement()))
b:cmul(gamma):add(beta)
end
end
local function BN_absorber(x)
local i = 1
while (i <= #x.modules) do
if x.modules[i].__typename == 'nn.Sequential' then
BN_absorber(x.modules[i])
elseif x.modules[i].__typename == 'nn.Parallel' then
BN_absorber(x.modules[i])
elseif x.modules[i].__typename == 'nn.Concat' then
BN_absorber(x.modules[i])
elseif x.modules[i].__typename == 'nn.DataParallel' then
BN_absorber(x.modules[i])
elseif x.modules[i].__typename == 'nn.ModelParallel' then
BN_absorber(x.modules[i])
elseif x.modules[i].__typename == 'nn.ConcatTable' then
BN_absorber(x.modules[i])
else
-- check BN
if x.modules[i].__typename == 'nn.SpatialBatchNormalization' then
if x.modules[i-1] and
(x.modules[i-1].__typename == 'nn.SpatialConvolution' or
x.modules[i-1].__typename == 'nn.SpatialConvolutionMM') then
absorb_bn_conv(x.modules[i-1].weight,
x.modules[i-1].bias,
x.modules[i].running_mean,
x.modules[i].running_var:clone():sqrt():add(x.modules[i].eps):pow(-1),
x.modules[i].affine,
x.modules[i].weight,
x.modules[i].bias)
x:remove(i)
i = i - 1
elseif x.modules[i-1] and
(x.modules[i-1].__typename == 'nn.SpatialFullConvolution') then
absorb_bn_deconv(x.modules[i-1].weight,
x.modules[i-1].bias,
x.modules[i].running_mean,
x.modules[i].running_var:clone():sqrt():add(x.modules[i].eps):pow(-1),
x.modules[i].affine,
x.modules[i].weight,
x.modules[i].bias)
x:remove(i)
i = i - 1
else
assert(false, 'Convolution module must exist right before batch normalization layer')
end
elseif x.modules[i].__typename == 'nn.BatchNormalization' then
if x.modules[i-1] and
(x.modules[i-1].__typename == 'nn.Linear') then
absorb_bn_conv(x.modules[i-1].weight,
x.modules[i-1].bias,
x.modules[i].running_mean,
x.modules[i].running_std,
x.modules[i].affine,
x.modules[i].weight,
x.modules[i].bias)
x:remove(i)
i = i - 1
else
assert(false, 'Convolution module must exist right before batch normalization layer')
end
end
end
i = i + 1
end
collectgarbage()
return x
end
return BN_absorber
|
require('nn')
local absorb_bn_conv = function (w, b, mean, invstd, affine, gamma, beta)
w:cmul(invstd:view(w:size(1),1):repeatTensor(1,w:nElement()/w:size(1)))
b:add(-mean):cmul(invstd)
if affine then
w:cmul(gamma:view(w:size(1),1):repeatTensor(1,w:nElement()/w:size(1)))
b:cmul(gamma):add(beta)
end
end
local absorb_bn_deconv = function (w, b, mean, invstd, affine, gamma, beta)
w:cmul(invstd:view(b:size(1),1):repeatTensor(w:size(1),w:nElement()/w:size(1)/b:nElement()))
b:add(-mean):cmul(invstd)
if affine then
w:cmul(gamma:view(b:size(1),1):repeatTensor(w:size(1),w:nElement()/w:size(1)/b:nElement()))
b:cmul(gamma):add(beta)
end
end
local backward_compat_running_std = function(x, i)
if x.modules[i].running_std then
x.modules[i].running_var = x.modules[i].running_std:pow(-2):add(-x.modules[i].eps)
x.modules[i].running_std = nil
end
end
local function BN_absorber(x)
local i = 1
while (i <= #x.modules) do
if x.modules[i].__typename == 'nn.Sequential' then
BN_absorber(x.modules[i])
elseif x.modules[i].__typename == 'nn.Parallel' then
BN_absorber(x.modules[i])
elseif x.modules[i].__typename == 'nn.Concat' then
BN_absorber(x.modules[i])
elseif x.modules[i].__typename == 'nn.DataParallel' then
BN_absorber(x.modules[i])
elseif x.modules[i].__typename == 'nn.ModelParallel' then
BN_absorber(x.modules[i])
elseif x.modules[i].__typename == 'nn.ConcatTable' then
BN_absorber(x.modules[i])
else
-- check BN
if x.modules[i].__typename == 'nn.SpatialBatchNormalization' then
backward_compat_running_std(x, i)
if x.modules[i-1] and
(x.modules[i-1].__typename == 'nn.SpatialConvolution' or
x.modules[i-1].__typename == 'nn.SpatialConvolutionMM') then
absorb_bn_conv(x.modules[i-1].weight,
x.modules[i-1].bias,
x.modules[i].running_mean,
x.modules[i].running_var:clone():add(x.modules[i].eps):pow(-0.5),
x.modules[i].affine,
x.modules[i].weight,
x.modules[i].bias)
x:remove(i)
i = i - 1
elseif x.modules[i-1] and
(x.modules[i-1].__typename == 'nn.SpatialFullConvolution') then
absorb_bn_deconv(x.modules[i-1].weight,
x.modules[i-1].bias,
x.modules[i].running_mean,
x.modules[i].running_var:clone():add(x.modules[i].eps):pow(-0.5),
x.modules[i].affine,
x.modules[i].weight,
x.modules[i].bias)
x:remove(i)
i = i - 1
else
assert(false, 'Convolution module must exist right before batch normalization layer')
end
elseif x.modules[i].__typename == 'nn.BatchNormalization' then
backward_compat_running_std(x, i)
if x.modules[i-1] and
(x.modules[i-1].__typename == 'nn.Linear') then
absorb_bn_conv(x.modules[i-1].weight,
x.modules[i-1].bias,
x.modules[i].running_mean,
x.modules[i].running_var:clone():add(x.modules[i].eps):pow(-0.5),
x.modules[i].affine,
x.modules[i].weight,
x.modules[i].bias)
x:remove(i)
i = i - 1
else
assert(false, 'Convolution module must exist right before batch normalization layer')
end
end
end
i = i + 1
end
collectgarbage()
return x
end
return BN_absorber
|
Fix broken BN-absorber due to nn package update
|
Fix broken BN-absorber due to nn package update
the latest BN implementation uses running_var to calculate running average
while the old implementation has running_std
|
Lua
|
bsd-3-clause
|
e-lab/torch-toolbox,e-lab/torch-toolbox,e-lab/torch-toolbox
|
a793f7c02b541bc6e60cb78197351ae16e36c3fc
|
gateway/src/resty/http_ng/headers.lua
|
gateway/src/resty/http_ng/headers.lua
|
local insert = table.insert
local concat = table.concat
local assert = assert
local pairs = pairs
local rawset = rawset
local rawget = rawget
local setmetatable = setmetatable
local getmetatable = getmetatable
local type = type
local lower = string.lower
local upper = string.upper
local ngx_re = ngx.re
local re_gsub = ngx_re.gsub
local normalize_exceptions = {
etag = 'ETag'
}
local headers = {}
local headers_mt = {
__newindex = function(table, key, value)
rawset(table, headers.normalize_key(key), headers.normalize_value(value))
return value
end,
__index = function(table, key)
return rawget(table, headers.normalize_key(key))
end
}
local capitalize = function(m)
return upper(m[0])
end
local letter = [[\b([a-z])]]
local capitalize_header = function(key)
key = re_gsub(key, '_', '-', 'jo')
key = re_gsub(key, letter, capitalize, 'jo')
return key
end
headers.normalize_key = function(key)
local exception = normalize_exceptions[lower(key)]
if exception then
return exception
end
return capitalize_header(key)
end
local header_mt = {
__tostring = function(t)
local tmp = {}
for k,v in pairs(t) do
if type(k) == 'string' then
insert(tmp, k)
elseif type(v) == 'string' then
insert(tmp, v)
end
end
return concat(tmp, ', ')
end
}
headers.normalize_value = function(value)
if type(value) == 'table' and getmetatable(value) == nil then
return setmetatable(value, header_mt)
else
return value
end
end
headers.normalize = function(http_headers)
http_headers = http_headers or {}
local normalized = {}
for k,v in pairs(http_headers) do
normalized[headers.normalize_key(k)] = headers.normalize_value(v)
end
return normalized
end
headers.new = function(h)
local normalized = assert(headers.normalize(h or {}))
return setmetatable(normalized, headers_mt)
end
return headers
|
local insert = table.insert
local concat = table.concat
local assert = assert
local pairs = pairs
local rawset = rawset
local rawget = rawget
local setmetatable = setmetatable
local getmetatable = getmetatable
local type = type
local lower = string.lower
local upper = string.upper
local ngx_re = ngx.re
local re_gsub = ngx_re.gsub
local tablex_pairmap = require('pl.tablex').pairmap
local tablex_sort = require('pl.tablex').sort
local normalize_exceptions = {
etag = 'ETag'
}
local headers = {}
local headers_mt = {
__newindex = function(table, key, value)
rawset(table, headers.normalize_key(key), headers.normalize_value(value))
return value
end,
__index = function(table, key)
return rawget(table, headers.normalize_key(key))
end
}
local capitalize = function(m)
return upper(m[0])
end
local letter = [[\b([a-z])]]
local capitalize_header = function(key)
key = re_gsub(key, '_', '-', 'jo')
key = re_gsub(key, letter, capitalize, 'jo')
return key
end
headers.normalize_key = function(key)
local exception = normalize_exceptions[lower(key)]
if exception then
return exception
end
return capitalize_header(key)
end
local header_mt = {
__tostring = function(t)
local tmp = {}
for k,v in tablex_sort(t) do
if type(k) == 'string' then
insert(tmp, k)
elseif type(v) == 'string' then
insert(tmp, v)
end
end
return concat(tmp, ', ')
end
}
headers.normalize_value = function(value)
if type(value) == 'table' and getmetatable(value) == nil then
return setmetatable(value, header_mt)
else
return value
end
end
headers.normalize = function(http_headers)
http_headers = http_headers or {}
local serialize = function(k,v)
return headers.normalize_value(v), headers.normalize_key(k)
end
-- Use tablex because it uses the same order as defined
return tablex_pairmap(serialize, http_headers)
end
headers.new = function(h)
local normalized = assert(headers.normalize(h or {}))
return setmetatable(normalized, headers_mt)
end
return headers
|
Openresty Update: Fix headers ordering issues
|
Openresty Update: Fix headers ordering issues
When setting headers, the order is important in case of duplication,
using tablex that keep the order as it was set.
Signed-off-by: Eloy Coto <2a8acc28452926ceac4d9db555411743254cf5f9@acalustra.com>
|
Lua
|
mit
|
3scale/docker-gateway,3scale/docker-gateway
|
7430260d600bdf8a9a5c3f28d4f9364d172dee03
|
lib/switchboard_modules/lua_script_debugger/premade_scripts/benchmarking_tests/low_level_speed_test-dio.lua
|
lib/switchboard_modules/lua_script_debugger/premade_scripts/benchmarking_tests/low_level_speed_test-dio.lua
|
print("Benchmarking Test: Low-Level toggle of FIO3/DIO3 (FIO5/DIO5 on T4) as fast as possible.")
--This example will output a digital waveform at at 20-25kHz on FIO3
--Note: Most commonly users should throttle their code execution using the functions:
--"LJ.IntervalConfig(0, 1000)", and "if LJ.CheckInterval(0) then" ...
local outDIO = 3--FIO3. Changed if T4 instead of T7
devType = MB.R(60000, 3)
if devType == 4 then
outDIO = 5--FIO5
end
--The throttle setting can correspond roughly with the length of the Lua script.
--A rule of thumb for deciding a throttle setting is Throttle = (3*NumLinesCode) + 20
ThrottleSetting = 40 --Default throttle setting is 10 instructions
LJ.DIO_D_W(outDIO, 1) --Change FIO3 direction _D_ to output. Low level IO number is 3
LJ.setLuaThrottle(ThrottleSetting)
ThrottleSetting = LJ.getLuaThrottle()
print ("Current Lua Throttle Setting: ", ThrottleSetting)
Print_interval_ms = 2000
c = 0
LJ.IntervalConfig(0, Print_interval_ms)
while true do
LJ.DIO_S_W(outDIO, 0) --Change the state _S_ of FIO to 0
LJ.DIO_S_W(outDIO, 1) --Change the state _S_ of FIO to 1
c = c + 1
if LJ.CheckInterval(0) then
c = c / (Print_interval_ms / 1000)
print ("Frequency in Hz: ", c)
c = 0
end
end
|
--[[
Name: low_level_speed_test-dio.lua
Desc: This example will output a digital waveform at at 20-25kHz on outdio
Note: In most cases, users should throttle their code execution using the
functions: "interval_config(0, 1000)", and "if check_interval(0)"
--]]
-- Assign functions locally for faster processing
local modbus_read_name = MB.readName
local set_lua_throttle = LJ.setLuaThrottle
local get_lua_throttle = LJ.getLuaThrottle
local dio_direction_write = LJ.DIO_D_W
local dio_state_write = LJ.DIO_S_W
local interval_config = LJ.IntervalConfig
local check_interval = LJ.CheckInterval
print("Benchmarking Test: Low-Level toggle of outdio/DIO3 (FIO5/DIO5 on T4) as fast as possible.")
-- Change the DIO pin if using a T4 instead of a T7
local outdio = 3
local devtype = modbus_read_name("PRODUCT_NAME")
if devtype == 4 then
outdio = 5--FIO5
end
--Change outdio direction to output
dio_direction_write(outdio, 1)
-- The throttle setting can correspond roughly with the length of the Lua
-- script. A rule of thumb for deciding a throttle setting is
-- Throttle = (3*NumLinesCode)+20. Default throttle setting is 10 instructions
local throttle = 40
set_lua_throttle(throttle)
throttle = get_lua_throttle()
print ("Current Lua Throttle Setting: ", throttle)
-- Use an interval of 2000ms
local interval = 2000
local numwrites = 0
interval_config(0, interval)
while true do
--Change the state of outdio to 0
dio_state_write(outdio, 0)
--Change the state of outdio to 1
dio_state_write(outdio, 1)
numwrites = numwrites + 1
-- If the 2000ms interval is done
if check_interval(0) then
-- Convert the number of writes per interval into a frequency
numwrites = numwrites / (interval / 1000)
print ("Frequency in Hz: ", numwrites)
numwrites = 0
end
end
|
Fixed up formatting of the low level dio speed test
|
Fixed up formatting of the low level dio speed test
|
Lua
|
mit
|
chrisJohn404/ljswitchboard-module_manager,chrisJohn404/ljswitchboard-module_manager,chrisJohn404/ljswitchboard-module_manager
|
0d95765fe508ae08a68753241988706e9cfc5c75
|
Quadtastic/AppLogic.lua
|
Quadtastic/AppLogic.lua
|
local unpack = unpack or table.unpack
local quit = love.event.quit or os.exit
local AppLogic = {}
local function run(self, f, ...)
assert(type(f) == "function")
local co = coroutine.create(f)
local ret = {coroutine.resume(co, self._state.data, ...)}
-- Print errors if there are any
assert(ret[1], ret[2])
-- If the coroutine yielded then we will issue a state switch based
-- on the returned values.
if coroutine.status(co) == "suspended" then
local new_state = ret[2]
-- Save the coroutine so that it can be resumed later
self._state.coroutine = co
self:push_state(new_state)
else
assert(coroutine.status(co) == "dead")
-- If values were returned, then they will be returned to the
-- next state higher up in the state stack.
-- If this is the only state, then the app will exit with the
-- returned integer as exit code.
if #ret > 0 then
if #self._state_stack > 0 then
self:pop_state(select(2, unpack(ret)))
else
quit(ret[1])
end
end
end
end
setmetatable(AppLogic, {
__call = function(_, initial_state)
local application = {}
application._state = initial_state
application._state_stack = {}
application._event_queue = {}
setmetatable(application, {
__index = function(self, key)
if rawget(AppLogic, key) then return rawget(AppLogic, key)
-- If this is a call for the current state, return that state
elseif key == self._state.name then
-- return a function that executes the command in a subroutine,
-- and captures the function's return values
return setmetatable({}, {__index = function(_, event)
local f = self._state.transitions[event]
return function(...)
run(self, f, ...)
end
end})
-- Otherwise queue that call for later if we have a queue for it
elseif self._event_queue[key] then
return function(...)
table.insert(self._event_queue[key], ...)
end
else
error(string.format("There is no state %s in the current application.", key))
end
end
})
return application
end
})
function AppLogic.push_state(self, new_state)
assert(string.sub(new_state.name, 1, 1) ~= "_",
"State name cannot start with underscore")
-- Push the current state onto the state stack
table.insert(self._state_stack, self._state)
-- Create a new event queue for the pushed state
self._event_queue[self._state.name] = {}
-- Switch states
self._state = new_state
end
function AppLogic.pop_state(self, ...)
-- Return to previous state
self._state = table.remove(self._state_stack)
-- Resume state's current coroutine with the passed event
if self._state.coroutine and
coroutine.status(self._state.coroutine) == "suspended"
then
coroutine.resume(self._state.coroutine, ...)
end
-- Catch up on events that happened for that state while we were in a
-- different state
for _,event_bundle in ipairs(self._event_queue[self.state.name]) do
local event = event_bundle[1]
self._state.process(event, select(2, unpack(event_bundle)))
end
end
function AppLogic.get_states(self)
local states = {}
for i,state in ipairs(self._state_stack) do
states[i] = state
end
-- Add the current state
table.insert(states, self._state)
return states
end
function AppLogic.get_current_state(self)
return self._state.name
end
return AppLogic
|
local unpack = unpack or table.unpack
local quit = love.event.quit or os.exit
local AppLogic = {}
local function run(self, f, ...)
assert(type(f) == "function")
local co = coroutine.create(f)
local ret = {coroutine.resume(co, self._state.data, ...)}
-- Print errors if there are any
assert(ret[1], ret[2])
-- If the coroutine yielded then we will issue a state switch based
-- on the returned values.
if coroutine.status(co) == "suspended" then
local new_state = ret[2]
-- Save the coroutine so that it can be resumed later
self._state.coroutine = co
self:push_state(new_state)
else
assert(coroutine.status(co) == "dead")
-- If values were returned, then they will be returned to the
-- next state higher up in the state stack.
-- If this is the only state, then the app will exit with the
-- returned integer as exit code.
if #ret > 0 then
if #self._state_stack > 0 then
self:pop_state(select(2, unpack(ret)))
else
quit(ret[1])
end
end
end
end
setmetatable(AppLogic, {
__call = function(_, initial_state)
local application = {}
application._state = initial_state
application._state_stack = {}
application._event_queue = {}
setmetatable(application, {
__index = function(self, key)
if rawget(AppLogic, key) then return rawget(AppLogic, key)
-- If this is a call for the current state, return that state
elseif key == self._state.name then
-- return a function that executes the command in a subroutine,
-- and captures the function's return values
return setmetatable({}, {__index = function(_, event)
local f = self._state.transitions[event]
return function(...)
run(self, f, ...)
end
end})
-- Otherwise queue that call for later if we have a queue for it
elseif self._event_queue[key] then
return setmetatable({}, {__index = function(_, event)
local f = self._state.transitions[event]
return function(...)
table.insert(self._event_queue[key], {f, ...})
end
end})
else
error(string.format("There is no state %s in the current application.", key))
end
end
})
return application
end
})
function AppLogic.push_state(self, new_state)
assert(string.sub(new_state.name, 1, 1) ~= "_",
"State name cannot start with underscore")
-- Push the current state onto the state stack
table.insert(self._state_stack, self._state)
-- Create a new event queue for the pushed state
self._event_queue[self._state.name] = {}
-- Switch states
self._state = new_state
end
function AppLogic.pop_state(self, ...)
-- Return to previous state
self._state = table.remove(self._state_stack)
-- Resume state's current coroutine with the passed event
if self._state.coroutine and
coroutine.status(self._state.coroutine) == "suspended"
then
coroutine.resume(self._state.coroutine, ...)
end
-- Catch up on events that happened for that state while we were in a
-- different state
for _,event_bundle in ipairs(self._event_queue[self.state.name]) do
local f = event_bundle[1]
f(self._state.data, unpack(event_bundle[2]))
end
end
function AppLogic.get_states(self)
local states = {}
for i,state in ipairs(self._state_stack) do
states[i] = state
end
-- Add the current state
table.insert(states, self._state)
return states
end
function AppLogic.get_current_state(self)
return self._state.name
end
return AppLogic
|
Fix how calls on inactive states are queued
|
Fix how calls on inactive states are queued
|
Lua
|
mit
|
25A0/Quadtastic,25A0/Quadtastic
|
2c17b0e213f134d84e3d4b825ee831eccd335bc3
|
OS/DiskOS/Programs/apis.lua
|
OS/DiskOS/Programs/apis.lua
|
if select(1,...) == "-?" then
printUsage(
"apis","Prints the available peripherals functions",
"apis <peripheral>","Prints the functions of a specific peripheral"
)
return
end
--Print the list of functions for a peripheral, or all peripherals
local _,perlist = coroutine.yield("BIOS:listPeripherals")
palt(0,false) --Make black opaque
local peri = select(1,...)
local function waitkey()
while true do
local name, a = pullEvent()
if name == "keypressed" then
return false
elseif name == "textinput" then
if string.lower(a) == "q" then return true else return end
elseif name == "touchpressed" then
textinput(true)
end
end
end
local tw, th = termSize()
local sw, sh = screenSize()
local msg = "[press any key to continue, q to quit]"
local msglen = msg:len()
local function sprint(text)
local cx, cy = printCursor()
if cy < th-2 then print(text.." ",false) return end
local tlen = text:len()+1
if cx+tlen+1 >= tw then
print("") pushColor() color(9)
print(msg,false) popColor()
flip()
local quit = waitkey()
printCursor(1,th)
rect(0,sh-9,sw,8,false,0)
if quit then return true end
screenshot():image():draw(0,-8)
printCursor(cx, th-3)
print(text.." ",false) return
else
print(text.." ",false) return
end
end
if peri then
if not perlist[peri] then
color(8) print("Peripheral '"..peri.."' doesn't exists") return
end
color(11) if sprint(peri..":") then return end color(7)
for k, name in pairs(perlist[peri]) do
if sprint(name) then return end
end
else
for per, funcs in pairs(perlist) do
color(11) print("---"..per.."---") color(7)
for k, name in pairs(funcs) do
if sprint(name) then return end
end
print("") print("")
end
end
|
if select(1,...) == "-?" then
printUsage(
"apis","Prints the available peripherals functions",
"apis <peripheral>","Prints the functions of a specific peripheral"
)
return
end
--Print the list of functions for a peripheral, or all peripherals
local perlist = BIOS.HandledAPIS()
palt(0,false) --Make black opaque
local peri = select(1,...)
local function waitkey()
while true do
local name, a = pullEvent()
if name == "keypressed" then
return false
elseif name == "textinput" then
if string.lower(a) == "q" then return true else return end
elseif name == "touchpressed" then
textinput(true)
end
end
end
local tw, th = termSize()
local sw, sh = screenSize()
local msg = "[press any key to continue, q to quit]"
local msglen = msg:len()
local function sprint(text)
local cx, cy = printCursor()
if cy < th-2 then print(text.." ",false) return end
local tlen = text:len()+1
if cx+tlen+1 >= tw then
print("") pushColor() color(9)
print(msg,false) popColor()
flip()
local quit = waitkey()
printCursor(1,th)
rect(0,sh-9,sw,8,false,0)
if quit then return true end
screenshot():image():draw(0,-8)
printCursor(cx, th-3)
print(text.." ",false) return
else
print(text.." ",false) return
end
end
if peri then
if not perlist[peri] then
color(8) print("Peripheral '"..peri.."' doesn't exists") return
end
color(11) if sprint(peri..":") then return end color(7)
for name, f in pairs(perlist[peri]) do
if sprint(name) then return end
end
else
for per, funcs in pairs(perlist) do
color(11) print("---"..per.."---") color(7)
for name,f in pairs(funcs) do
if sprint(name) then return end
end
print("") print("")
end
end
|
Fix #140
|
Fix #140
Former-commit-id: 682d30b4abc8296c002380885eb936f20d8d677f
|
Lua
|
mit
|
RamiLego4Game/LIKO-12
|
7f7a390ad8d060d3eac41fb91de5631084901996
|
NLBL/src/main/resources/vnstead/modules/paginator.lua
|
NLBL/src/main/resources/vnstead/modules/paginator.lua
|
-- paginator module
require "kbd"
require "click"
require "theme"
require "modules/dice"
require "modules/vn"
hook_keys('space', 'right ctrl', 'left ctrl')
iface.cmd = stead.hook(iface.cmd, function(f, s, cmd, ...)
if vn:add_all_missing_children() then
vn:invalidate_all();
vn:start();
else
vn:invalidate_all();
end
return paginatorIfaceCmd(f, s, cmd, ...);
end)
instead.get_title = stead.hook(instead.get_title, function(f, s, cmd, ...)
return paginatorGetTitle(f, s, cmd, ...);
end)
click.bg = true
local clickInInvArea = function(x, y)
local invx, invy, invw, invh =
tonumber(theme.get("inv.x")),
tonumber(theme.get("inv.y")),
tonumber(theme.get("inv.w")),
tonumber(theme.get("inv.h"));
if ((x >= invx) and (x <= invx + invw) and (y >= invy) and (y <= invy + invh)) then
-- Click in inventory area
return true;
end
return false;
end
paginatorClick = function(x, y, a, b, c, d)
if here().debug then
return
end
if clickInInvArea(x, y) or vn:test_click(x, y) then
-- Click in inventory area or inside some gobj in vn
vn:click(x, y, a, b, c, d);
return
end
if (paginator._last and here().walk_to) or not paginator._last then
return paginatorKbd(true, 'space')
end
end
paginatorKbd = function(down, key)
if here().debug then
return
end
if key:find("ctrl") then
vn.skip_mode = down
end
if down and key == 'space' then
if vn:finish() then
return
end
dice:hide(true);
-- Use code below if you want smooth rollout animation and text change on next step
--if dice:hide() then
-- return
--end
if paginator._last then
if here().walk_to then
vn:request_full_clear();
return walk(here().walk_to)
end
return
end
paginator.process = true
RAW_TEXT = true
return game._realdisp
end
end
local text_page = function(txt)
local s, e
local pg = paginator
local ss = pg._page
local res = ''
if not txt then
return nil;
end
txt = txt:gsub("[ \t\n]+$", ""):gsub("^[ \t\n]+", "");
s, e = txt:find(pg.delim, ss)
if s then
res = txt:sub(ss, s)
pg._page = e + 1
else
pg._last = true
res = txt:sub(ss)
end
res = res:gsub("%$[^%$]+%$", function(s)
s = s:gsub("^%$", ""):gsub("%$$", "");
local f = stead.eval(s)
if not f then
print("Error in expression: ", s)
error("Bug in expression:" .. s);
end
f();
return ''
end)
res = res:gsub("[ \t\n]+$", ""):gsub("^[ \t\n]+", "");
local loc = here();
if loc.nextsnd ~= nil and res ~= '' then
loc.nextsnd(loc);
end
return res .. '\n'
end
paginator = obj {
nam = 'paginator';
system_type = true;
w = 0;
h = 0;
_page = 1;
var { process = false; on = true; },
delim = '\n\n';
turnon = function(s)
s.on = true;
end,
turnoff = function(s)
s.on = false;
end
}
paginatorIfaceCmd = function(f, s, cmd, ...)
local r, v = f(s, cmd, ...)
if here().debug or not paginator.on then
return r, v
end
if type(r) == 'string' and (stead.state or RAW_TEXT) then
if not RAW_TEXT then -- and player_moved() then
if player_moved() then
paginator._page = 1
paginator._last = false
end
game._realdisp = game._lastdisp
end
if RAW_TEXT and not paginator.process and
--- timer:get() == 0 and r:find("^[ \t\n]*$") and not paginator._last then
r:find("^[ \t\n]*$") and not paginator._last then
paginator.process = true
r = game._realdisp
end
if paginator.process or not RAW_TEXT then
while true do
r = text_page(r)
if not r then
paginator._last = true;
game._lastdisp = "\n";
return "\n", v;
end
--- if timer:get() ~= 0 or not r:find("^[ \t\n]*$") or paginator._last then
if not r:find("^[ \t\n]*$") or paginator._last then
break
end
r = game._realdisp
end
end
paginator.process = false
game._lastdisp = r
end
return r, v
end
stead.module_init(function()
game.click = function(s, x, y, a, b, c, d)
local result;
if paginator.on then
result = paginatorClick(x, y, a, b, c, d);
else
vn:click(x, y, a, b, c, d);
return;
end
return result;
end
game.kbd = function(s, down, key)
local result;
if paginator.on then
result = paginatorKbd(down, key);
else
return;
end
return result;
end
end)
paginatorGetTitle = function(f, s, cmd, ...)
if not paginator.on then
return f(s, cmd, ...)
end
-- else no title
end
stead.phrase_prefix = ''
|
-- paginator module
require "kbd"
require "click"
require "theme"
require "modules/dice"
require "modules/vn"
iface.cmd = stead.hook(iface.cmd, function(f, s, cmd, ...)
if vn:add_all_missing_children() then
vn:invalidate_all();
vn:start();
else
vn:invalidate_all();
end
return paginatorIfaceCmd(f, s, cmd, ...);
end)
instead.get_title = stead.hook(instead.get_title, function(f, s, cmd, ...)
return paginatorGetTitle(f, s, cmd, ...);
end)
click.bg = true
local clickInInvArea = function(x, y)
local invx, invy, invw, invh =
tonumber(theme.get("inv.x")),
tonumber(theme.get("inv.y")),
tonumber(theme.get("inv.w")),
tonumber(theme.get("inv.h"));
if ((x >= invx) and (x <= invx + invw) and (y >= invy) and (y <= invy + invh)) then
-- Click in inventory area
return true;
end
return false;
end
paginatorClick = function(x, y, a, b, c, d)
if here().debug then
return
end
if clickInInvArea(x, y) or vn:test_click(x, y) then
-- Click in inventory area or inside some gobj in vn
vn:click(x, y, a, b, c, d);
return
end
if (paginator._last and here().walk_to) or not paginator._last then
return paginatorKbd(true, 'space')
end
end
paginatorKbd = function(down, key)
if here().debug then
return
end
if key:find("ctrl") then
vn.skip_mode = down
end
if down and key == 'space' then
if vn:finish() then
return
end
dice:hide(true);
-- Use code below if you want smooth rollout animation and text change on next step
--if dice:hide() then
-- return
--end
if paginator._last then
if here().walk_to then
vn:request_full_clear();
return walk(here().walk_to)
end
return
end
paginator.process = true
RAW_TEXT = true
return game._realdisp
end
end
local text_page = function(txt)
local s, e
local pg = paginator
local ss = pg._page
local res = ''
if not txt then
return nil;
end
txt = txt:gsub("[ \t\n]+$", ""):gsub("^[ \t\n]+", "");
s, e = txt:find(pg.delim, ss)
if s then
res = txt:sub(ss, s)
pg._page = e + 1
else
pg._last = true
res = txt:sub(ss)
end
res = res:gsub("%$[^%$]+%$", function(s)
s = s:gsub("^%$", ""):gsub("%$$", "");
local f = stead.eval(s)
if not f then
print("Error in expression: ", s)
error("Bug in expression:" .. s);
end
f();
return ''
end)
res = res:gsub("[ \t\n]+$", ""):gsub("^[ \t\n]+", "");
local loc = here();
if loc.nextsnd ~= nil and res ~= '' then
loc.nextsnd(loc);
end
return res .. '\n'
end
paginator = obj {
nam = 'paginator';
system_type = true;
w = 0;
h = 0;
_page = 1;
var { process = false; on = true; },
delim = '\n\n';
turnon = function(s)
s.on = true;
end,
turnoff = function(s)
s.on = false;
end
}
paginatorIfaceCmd = function(f, s, cmd, ...)
local r, v = f(s, cmd, ...)
if here().debug or not paginator.on then
return r, v
end
if type(r) == 'string' and (stead.state or RAW_TEXT) then
if not RAW_TEXT then -- and player_moved() then
if player_moved() then
paginator._page = 1
paginator._last = false
end
game._realdisp = game._lastdisp
end
if RAW_TEXT and not paginator.process and
--- timer:get() == 0 and r:find("^[ \t\n]*$") and not paginator._last then
r:find("^[ \t\n]*$") and not paginator._last then
paginator.process = true
r = game._realdisp
end
if paginator.process or not RAW_TEXT then
while true do
r = text_page(r)
if not r then
paginator._last = true;
game._lastdisp = "\n";
return "\n", v;
end
--- if timer:get() ~= 0 or not r:find("^[ \t\n]*$") or paginator._last then
if not r:find("^[ \t\n]*$") or paginator._last then
break
end
r = game._realdisp
end
end
paginator.process = false
game._lastdisp = r
end
return r, v
end
stead.module_init(function()
hook_keys('space', 'right ctrl', 'left ctrl');
game.click = function(s, x, y, a, b, c, d)
local result;
if paginator.on then
result = paginatorClick(x, y, a, b, c, d);
else
vn:click(x, y, a, b, c, d);
return;
end
return result;
end
game.kbd = function(s, down, key)
local result;
if paginator.on then
result = paginatorKbd(down, key);
else
return;
end
return result;
end
end)
paginatorGetTitle = function(f, s, cmd, ...)
if not paginator.on then
return f(s, cmd, ...)
end
-- else no title
end
stead.phrase_prefix = ''
|
dev::NLB-186::Bugfixing & Improvement
|
dev::NLB-186::Bugfixing & Improvement
|
Lua
|
agpl-3.0
|
Antokolos/NLB,Antokolos/NLB,Antokolos/NLB,Antokolos/NLB
|
46a4edf0c7cacc04b9ed84498f4ec66daeeb3b58
|
OS/DiskOS/Programs/save.lua
|
OS/DiskOS/Programs/save.lua
|
local destination = select(1,...)
local flag = select(2,...) or ""
local ctype = select(3,...) or "lz4"
local clvl = tonumber(select(4,...) or "-1")
local term = require("terminal")
local eapi = require("Editors")
if destination and destination ~= "@clip" and destination ~= "-?" then
destination = term.resolve(destination)
if destination:sub(-5,-1) ~= ".lk12" then destination = destination..".lk12" end
elseif destination ~= "@clip" and destination ~= "-?" then
destination = eapi.filePath
end
if not destination then
printUsage(
"save <file>","Saves the current loaded game",
"save <file> -c","Saves with compression",
"save","Saves on the last known file",
"save @clip","Saves into the clipboard",
"save <image> --sheet","Saves the spritesheet as external .lk12 image"
)
return
end
if destination ~= "@clip" and fs.exists(destination) and fs.isDirectory(destination) then color(8) print("Destination must not be a directory") return end
local sw, sh = screenSize()
if string.lower(flag) == "--sheet" then --Sheet export
local data = eapi.leditors[eapi.editors.sprite]:export(true)
if destination == "@clip" then clipboard(data) else fs.write(destination,data) end
color(11) print("Exported Spritesheet successfully")
return
elseif string.lower(flag) == "--code" then
local data = eapi.leditors[eapi.editors["lua"]]:export(true)
if destination == "@clip" then clipboard(data) else fs.write(destination:sub(0,-6),data) end
color(11) print("Exported Lua code successfully")
return
end
eapi.filePath = destination
local data = eapi:export()
-- LK12;OSData;OSName;DataType;Version;Compression;CompressLevel;data"
local header = "LK12;OSData;DiskOS;DiskGame;V".._DiskVer..";"..sw.."x"..sh..";C:"
if string.lower(flag) == "-c" then
data = math.b64enc(math.compress(data, ctype, clvl))
header = header..ctype..";CLvl:"..tostring(clvl)..";"
else
header = header.."none;CLvl:0;"
end
if destination == "@clip" then
clipboard(header.."\n"..data)
else
fs.write(destination,header.."\n"..data)
end
color(11) print(destination == "@clip" and "Saved to clipboard successfully" or "Saved successfully")
|
local destination = select(1,...)
local flag = select(2,...) or ""
local ctype = select(3,...) or "glib"
local clvl = tonumber(select(4,...) or "9")
local term = require("terminal")
local eapi = require("Editors")
if destination and destination ~= "@clip" and destination ~= "-?" then
destination = term.resolve(destination)
if destination:sub(-5,-1) ~= ".lk12" then destination = destination..".lk12" end
elseif destination ~= "@clip" and destination ~= "-?" then
destination = eapi.filePath
end
if not destination then
printUsage(
"save <file>","Saves the current loaded game",
"save <file> -c","Saves with compression",
"save","Saves on the last known file",
"save @clip","Saves into the clipboard",
"save <image> --sheet","Saves the spritesheet as external .lk12 image",
"save <filename> --code","Saves the code as a .lua file"
)
return
end
if destination ~= "@clip" and fs.exists(destination) and fs.isDirectory(destination) then color(8) print("Destination must not be a directory") return end
local sw, sh = screenSize()
if string.lower(flag) == "--sheet" then --Sheet export
local data = eapi.leditors[eapi.editors.sprite]:export(true)
if destination == "@clip" then clipboard(data) else fs.write(destination,data) end
color(11) print("Exported Spritesheet successfully")
return
elseif string.lower(flag) == "--code" then
local data = eapi.leditors[eapi.editors.code]:export(true)
if destination == "@clip" then clipboard(data) else fs.write(destination:sub(1,-6)..".lua",data) end
color(11) print("Exported Lua code successfully")
return
end
eapi.filePath = destination
local data = eapi:export()
-- LK12;OSData;OSName;DataType;Version;Compression;CompressLevel;data"
local header = "LK12;OSData;DiskOS;DiskGame;V".._DiskVer..";"..sw.."x"..sh..";C:"
if string.lower(flag) == "-c" then
data = math.b64enc(math.compress(data, ctype, clvl))
header = header..ctype..";CLvl:"..tostring(clvl)..";"
else
header = header.."none;CLvl:0;"
end
if destination == "@clip" then
clipboard(header.."\n"..data)
else
fs.write(destination,header.."\n"..data)
end
color(11) print(destination == "@clip" and "Saved to clipboard successfully" or "Saved successfully")
|
Bugfix #113
|
Bugfix #113
|
Lua
|
mit
|
RamiLego4Game/LIKO-12
|
97a742133c41e33c6d0fe0a20024b98d00f2274e
|
torch7/benchmark.lua
|
torch7/benchmark.lua
|
require 'nn'
require 'xlua'
require 'pl'
opt = lapp[[
-t,--threads (default 6) number of threads
-p,--type (default float) float or cuda
-i,--devid (default 1) device ID (if using CUDA)
]]
p = xlua.Profiler()
torch.setnumthreads(opt.threads)
torch.manualSeed(1)
if opt.type == 'cuda' then
require 'cunn'
cutorch.setDevice(opt.devid)
print('==> using GPU #' .. cutorch.getDevice())
end
batchSize = 128
iH = 128
iW = 128
fin = 3
fout = 96
kH = 11
kW = 11
if opt.type == 'cuda' then
input = torch.CudaTensor(fin,iH,iW,batchSize)
model = nn.SpatialConvolutionCUDA(fin, fout, kH, kW, 1, 1):cuda()
else
input = torch.FloatTensor(batchSize,fin,iH,iW)
model = nn.SpatialConvolution(fin, fout, kH, kW)
end
p:start('spatialconv')
output = model:forward(input)
if opt.type == 'cuda' then cutorch.synchronize() end
p:lap('spatialconv')
p:printAll{}
print('Gops/s:', ( batchSize*fin*fout*kH*kW*((iH-kH)+1)*((iW-kW)+1)*2 ) / p:cpu('spatialconv') / 1e9 ) -- 2 operations MUL, ACC
|
require 'nn'
require 'xlua'
require 'pl'
opt = lapp[[
-t,--threads (default 6) number of threads
-p,--type (default float) float or cuda
-i,--devid (default 1) device ID (if using CUDA)
]]
p = xlua.Profiler()
torch.setnumthreads(opt.threads)
torch.manualSeed(1)
torch.setdefaulttensortype('torch.FloatTensor')
if opt.type == 'cuda' then
require 'cunn'
cutorch.setDevice(opt.devid)
print('==> using GPU #' .. cutorch.getDevice())
end
batchSize = 128
iH = 128
iW = 128
fin = 3
fout = 96
kH = 11
kW = 11
if opt.type == 'cuda' then
input = torch.CudaTensor(fin,iH,iW,batchSize)
model = nn.SpatialConvolutionCUDA(fin, fout, kH, kW, 1, 1):cuda()
else
input = torch.FloatTensor(batchSize,fin,iH,iW)
model = nn.SpatialConvolution(fin, fout, kH, kW)
end
p:start('spatialconv')
output = model:forward(input)
if opt.type == 'cuda' then cutorch.synchronize() end
p:lap('spatialconv')
p:printAll{}
print('Gops/s:', ( batchSize*fin*fout*kH*kW*((iH-kH)+1)*((iW-kW)+1)*2 ) / p:cpu('spatialconv') / 1e9 ) -- 2 operations MUL, ACC
|
float fix
|
float fix
|
Lua
|
mit
|
soumith/convnet-benchmarks,soumith/convnet-benchmarks,soumith/convnet-benchmarks,soumith/convnet-benchmarks,soumith/convnet-benchmarks
|
b613fc71ffcf2bbcdbc119dec1ef1251ce1cb801
|
frontend/ui/reader/readerdogear.lua
|
frontend/ui/reader/readerdogear.lua
|
local InputContainer = require("ui/widget/container/inputcontainer")
local RightContainer = require("ui/widget/container/rightcontainer")
local ImageWidget = require("ui/widget/imagewidget")
local GestureRange = require("ui/gesturerange")
local UIManager = require("ui/uimanager")
local Device = require("ui/device")
local Geom = require("ui/geometry")
local Screen = require("ui/screen")
local Event = require("ui/event")
local ReaderDogear = InputContainer:new{}
function ReaderDogear:init()
local widget = ImageWidget:new{
file = "resources/icons/dogear.png",
}
self[1] = RightContainer:new{
dimen = Geom:new{w = Screen:getWidth(), h = widget:getSize().h},
widget,
}
if Device:isTouchDevice() then
self.ges_events = {
Tap = {
GestureRange:new{
ges = "tap",
range = Geom:new{
x = Screen:getWidth()*DTAP_ZONE_BOOKMARK.x,
y = Screen:getHeight()*DTAP_ZONE_BOOKMARK.y,
w = Screen:getWidth()*DTAP_ZONE_BOOKMARK.w,
h = Screen:getHeight()*DTAP_ZONE_BOOKMARK.h
}
}
},
Hold = {
GestureRange:new{
ges = "hold",
range = Geom:new{
x = Screen:getWidth()*DTAP_ZONE_BOOKMARK.x,
y = Screen:getHeight()*DTAP_ZONE_BOOKMARK.y,
w = Screen:getWidth()*DTAP_ZONE_BOOKMARK.w,
h = Screen:getHeight()*DTAP_ZONE_BOOKMARK.h
}
}
}
}
end
end
function ReaderDogear:onTap()
self.ui:handleEvent(Event:new("ToggleBookmark"))
return true
end
function ReaderDogear:onHold()
self.ui:handleEvent(Event:new("ToggleBookmarkFlipping"))
return true
end
function ReaderDogear:onSetDogearVisibility(visible)
self.view.dogear_visible = visible
UIManager:setDirty(self.view.dialog, "partial")
return true
end
return ReaderDogear
|
local InputContainer = require("ui/widget/container/inputcontainer")
local RightContainer = require("ui/widget/container/rightcontainer")
local ImageWidget = require("ui/widget/imagewidget")
local GestureRange = require("ui/gesturerange")
local UIManager = require("ui/uimanager")
local Device = require("ui/device")
local Geom = require("ui/geometry")
local Screen = require("ui/screen")
local Event = require("ui/event")
local ReaderDogear = InputContainer:new{}
function ReaderDogear:init()
local widget = ImageWidget:new{
file = "resources/icons/dogear.png",
}
self[1] = RightContainer:new{
dimen = Geom:new{w = Screen:getWidth(), h = widget:getSize().h},
widget,
}
if Device:isTouchDevice() then
self.ges_events = {
Tap = {
GestureRange:new{
ges = "tap",
range = Geom:new{
x = Screen:getWidth()*DTAP_ZONE_BOOKMARK.x,
y = Screen:getHeight()*DTAP_ZONE_BOOKMARK.y,
w = Screen:getWidth()*DTAP_ZONE_BOOKMARK.w,
h = Screen:getHeight()*DTAP_ZONE_BOOKMARK.h
}
}
},
Hold = {
GestureRange:new{
ges = "hold",
range = Geom:new{
x = Screen:getWidth()*DTAP_ZONE_BOOKMARK.x,
y = Screen:getHeight()*DTAP_ZONE_BOOKMARK.y,
w = Screen:getWidth()*DTAP_ZONE_BOOKMARK.w,
h = Screen:getHeight()*DTAP_ZONE_BOOKMARK.h
}
}
}
}
end
end
function ReaderDogear:onTap()
self.ui:handleEvent(Event:new("ToggleBookmark"))
return true
end
function ReaderDogear:onHold()
self.ui:handleEvent(Event:new("ToggleBookmarkFlipping"))
return true
end
function ReaderDogear:onSetDogearVisibility(visible)
self.view.dogear_visible = visible
return true
end
return ReaderDogear
|
fix won't get full refresh in EPUB document Since each position update will set dogear visibility
|
fix won't get full refresh in EPUB document
Since each position update will set dogear visibility
|
Lua
|
agpl-3.0
|
koreader/koreader,chihyang/koreader,ashhher3/koreader,apletnev/koreader,mwoz123/koreader,poire-z/koreader,chrox/koreader,Frenzie/koreader,mihailim/koreader,frankyifei/koreader,robert00s/koreader,NiLuJe/koreader,lgeek/koreader,poire-z/koreader,Markismus/koreader,Frenzie/koreader,Hzj-jie/koreader,noname007/koreader,NickSavage/koreader,koreader/koreader,houqp/koreader,ashang/koreader,pazos/koreader,NiLuJe/koreader
|
609da63b0fb0290d62aa1423c4ad706f3ac37f63
|
src/core/App.lua
|
src/core/App.lua
|
--------------------------------------------------------------------------------
--
--
--
--------------------------------------------------------------------------------
local App = {}
local DEFAULT_WINDOW = {
screenWidth = MOAIEnvironment.horizontalResolution or 640,
screenHeight = MOAIEnvironment.verticalResolution or 960,
viewWidth = 320,
viewHeight = 480,
scaleMode = "best_fit", -- "best_fit", "letterbox"
viewOffset = {0, 0},
}
---
-- Most common resolutions for mobile devices
-- Keys are resolution of longer side in pixels, values are view coordinates
-- Tried to keep view coords close to 320x480 and maintain
-- integer ratio at the same time
local mobileResolutions = {
-- apple
[480] = {480, 320}, -- 480x320
[960] = {480, 320}, -- 960x640
[1136] = {568, 320}, -- 1136x640
[1024] = {512, 384}, -- 1024x768
[2048] = {512, 384}, -- 2048x1536
-- use standard fallback for all androids
-- { [320] = {480, 360} }, -- 320x240
-- { [400] = {532, 320} }, -- 400x240
-- { [640] = {568, 320} }, -- 640x360
-- { [800] = {532, 320} }, -- 800x480
-- { [854] = {568, 320} }, -- 854x480
-- { [960] = {568, 320} }, -- 960x540
-- { [1280] = {640, 360} }, -- 1280x720
-- { [1920] = {568, 320} }, -- 1920x1080
}
---
-- Create moai window
-- @param title
-- @param windowParams table with parameters
function App:openWindow(title, windowParams)
windowParams = windowParams or DEFAULT_WINDOW
title = title or "MOAI"
for k, v in pairs(DEFAULT_WINDOW) do
if not windowParams[k] then
windowParams[k] = v
end
end
Runtime:initialize()
RenderMgr:initialize()
InputMgr:initialize()
SceneMgr:initialize()
SoundMgr:initialize()
Runtime:addEventListener("resize", self.onResize, self)
self.screenWidth = windowParams.screenWidth
self.screenHeight = windowParams.screenHeight
self:updateVieport(windowParams)
MOAISim.openWindow(title, self.screenWidth, self.screenHeight)
end
---
--
--
function App:onResize(event)
self.screenWidth = event.width
self.screenHeight = event.height
self:updateVieport(self.windowParams)
end
---
--
--
function App:updateVieport(params)
local width = params.viewWidth
local height = params.viewHeight
local wRatio = self.screenWidth / width
local hRatio = self.screenHeight / height
local view
if params.scaleMode == "best_fit" then
if self.screenWidth > self.screenHeight then
view = mobileResolutions[self.screenWidth]
self.viewWidth = view and view[1]
self.viewHeight = view and view[2]
else
view = mobileResolutions[self.screenHeight]
self.viewHeight = view and view[1]
self.viewWidth = view and view[2]
end
end
if not view or params.scaleMode == "letterbox" then
self.viewWidth = (wRatio > hRatio) and width * wRatio / hRatio or width
self.viewHeight = (hRatio > wRatio) and height * hRatio / wRatio or height
end
self.windowParams = params
self.viewport = self.viewport or MOAIViewport.new()
self.viewport:setSize(self.screenWidth, self.screenHeight)
self.viewport:setScale(self.viewWidth, self.viewHeight)
self.viewport:setOffset(params.viewOffset[1], params.viewOffset[2])
end
---
function App:getContentScale()
return self.screenWidth / self.viewWidth
end
return App
|
--------------------------------------------------------------------------------
--
--
--
--------------------------------------------------------------------------------
local App = {}
local DEFAULT_WINDOW = {
screenWidth = MOAIEnvironment.horizontalResolution or 640,
screenHeight = MOAIEnvironment.verticalResolution or 960,
viewWidth = 320,
viewHeight = 480,
scaleMode = "best_fit", -- "best_fit", "letterbox"
viewOffset = {0, 0},
}
---
-- Most common resolutions for mobile devices
-- Keys are resolution of longer side in pixels, values are view coordinates
-- Tried to keep view coords close to 320x480 and maintain
-- integer ratio at the same time
local appleResolutions = {
-- apple
[480] = {480, 320}, -- 480x320
[960] = {480, 320}, -- 960x640
[1136] = {568, 320}, -- 1136x640
[1024] = {512, 384}, -- 1024x768
[2048] = {512, 384}, -- 2048x1536
}
local androidResolutions = {
-- use standard fallback for all androids
-- { [320] = {480, 360} }, -- 320x240
-- { [400] = {532, 320} }, -- 400x240
-- { [640] = {568, 320} }, -- 640x360
-- { [800] = {532, 320} }, -- 800x480
-- { [854] = {568, 320} }, -- 854x480
-- { [960] = {568, 320} }, -- 960x540
-- { [1280] = {640, 360} }, -- 1280x720
-- { [1920] = {568, 320} }, -- 1920x1080
}
local mobileResolutions = MOAIAppIOS and appleResolutions or androidResolutions
---
-- Create moai window
-- @param title
-- @param windowParams table with parameters
function App:openWindow(title, windowParams)
windowParams = windowParams or DEFAULT_WINDOW
title = title or "MOAI"
for k, v in pairs(DEFAULT_WINDOW) do
if not windowParams[k] then
windowParams[k] = v
end
end
Runtime:initialize()
RenderMgr:initialize()
InputMgr:initialize()
SceneMgr:initialize()
SoundMgr:initialize()
Runtime:addEventListener("resize", self.onResize, self)
self.screenWidth = windowParams.screenWidth
self.screenHeight = windowParams.screenHeight
self:updateVieport(windowParams)
MOAISim.openWindow(title, self.screenWidth, self.screenHeight)
end
---
--
--
function App:onResize(event)
self.screenWidth = event.width
self.screenHeight = event.height
self:updateVieport(self.windowParams)
end
---
--
--
function App:updateVieport(params)
local width = params.viewWidth
local height = params.viewHeight
local wRatio = self.screenWidth / width
local hRatio = self.screenHeight / height
local view
if params.scaleMode == "best_fit" then
if self.screenWidth > self.screenHeight then
view = mobileResolutions[self.screenWidth]
self.viewWidth = view and view[1]
self.viewHeight = view and view[2]
else
view = mobileResolutions[self.screenHeight]
self.viewHeight = view and view[1]
self.viewWidth = view and view[2]
end
end
if not view or params.scaleMode == "letterbox" then
self.viewWidth = (wRatio > hRatio) and width * wRatio / hRatio or width
self.viewHeight = (hRatio > wRatio) and height * hRatio / wRatio or height
end
self.windowParams = params
self.viewport = self.viewport or MOAIViewport.new()
self.viewport:setSize(self.screenWidth, self.screenHeight)
self.viewport:setScale(self.viewWidth, self.viewHeight)
self.viewport:setOffset(params.viewOffset[1], params.viewOffset[2])
end
---
function App:getContentScale()
return self.screenWidth / self.viewWidth
end
return App
|
fix android resolutions
|
fix android resolutions
|
Lua
|
mit
|
Vavius/moai-framework,Vavius/moai-framework
|
f11dcce83f32b7d39acea66b692eaf90844fb5db
|
game/scripts/vscripts/heroes/hero_sara/fragment_of_logic.lua
|
game/scripts/vscripts/heroes/hero_sara/fragment_of_logic.lua
|
LinkLuaModifier("modifier_sara_fragment_of_logic", "heroes/hero_sara/fragment_of_logic.lua", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_sara_fragment_of_logic_debuff", "heroes/hero_sara/fragment_of_logic.lua", LUA_MODIFIER_MOTION_NONE)
sara_fragment_of_logic = class({
GetIntrinsicModifierName = function() return "modifier_sara_fragment_of_logic" end,
})
if IsClient() then
function sara_fragment_of_logic:GetManaCost()
return self:GetSpecialValueFor("energy_const") + self:GetCaster():GetMaxMana() * self:GetSpecialValueFor("energy_pct") * 0.01
end
end
modifier_sara_fragment_of_logic = class({
IsHidden = function() return true end,
IsPurgable = function() return false end,
})
if IsServer() then
function modifier_sara_fragment_of_logic:DeclareFunctions()
return {
MODIFIER_EVENT_ON_TAKEDAMAGE,
MODIFIER_PROPERTY_MIN_HEALTH
}
end
function modifier_sara_fragment_of_logic:OnTakeDamage(keys)
local parent = keys.unit
if parent == self:GetParent() and parent:GetHealth() <= 1 and parent.GetEnergy then
local ability = self:GetAbility()
local toWaste = ability:GetSpecialValueFor("energy_const") + parent:GetMaxEnergy() * ability:GetSpecialValueFor("energy_pct") * 0.01
if ability:IsCooldownReady() and parent:GetEnergy() >= toWaste then
if parent:HasScepter() then
ability:StartCooldown(ability:GetSpecialValueFor("cooldown_scepter"))
else
ability:AutoStartCooldown()
end
parent:AddNewModifier(parent, ability, "modifier_sara_fragment_of_logic_debuff", {duration = ability:GetSpecialValueFor("debuff_duration")})
parent:ModifyEnergy(-toWaste)
parent:SetHealth(parent:GetMaxHealth())
parent:Purge(false, true, false, true, false)
ParticleManager:CreateParticle("particles/arena/units/heroes/hero_sara/fragment_of_logic.vpcf", PATTACH_ABSORIGIN, parent)
parent:EmitSound("Hero_Chen.HandOfGodHealHero")
end
end
end
function modifier_sara_fragment_of_logic:GetMinHealth(keys)
local parent = self:GetParent()
if parent.GetEnergy then
local ability = self:GetAbility()
if ability:IsCooldownReady() and parent:GetEnergy() >= ability:GetSpecialValueFor("energy_const") + parent:GetMaxEnergy() * ability:GetSpecialValueFor("energy_pct") * 0.01 then
return 1
end
end
end
end
modifier_sara_fragment_of_logic_debuff = class({
IsPurgable = function() return false end,
IsDebuff = function() return true end,
})
|
LinkLuaModifier("modifier_sara_fragment_of_logic", "heroes/hero_sara/fragment_of_logic.lua", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_sara_fragment_of_logic_debuff", "heroes/hero_sara/fragment_of_logic.lua", LUA_MODIFIER_MOTION_NONE)
sara_fragment_of_logic = class({
GetIntrinsicModifierName = function() return "modifier_sara_fragment_of_logic" end,
})
if IsClient() then
function sara_fragment_of_logic:GetManaCost()
return self:GetSpecialValueFor("energy_const") + self:GetCaster():GetMaxMana() * self:GetSpecialValueFor("energy_pct") * 0.01
end
end
modifier_sara_fragment_of_logic = class({
IsHidden = function() return true end,
IsPurgable = function() return false end,
})
if IsServer() then
function modifier_sara_fragment_of_logic:DeclareFunctions()
return {
MODIFIER_EVENT_ON_TAKEDAMAGE,
MODIFIER_PROPERTY_MIN_HEALTH
}
end
function modifier_sara_fragment_of_logic:OnTakeDamage(keys)
local parent = keys.unit
if parent == self:GetParent() and parent:GetHealth() <= 1 and not parent:IsIllusion() and parent.GetEnergy then
local ability = self:GetAbility()
local toWaste = ability:GetSpecialValueFor("energy_const") + parent:GetMaxEnergy() * ability:GetSpecialValueFor("energy_pct") * 0.01
if ability:IsCooldownReady() and parent:GetEnergy() >= toWaste then
if parent:HasScepter() then
ability:StartCooldown(ability:GetSpecialValueFor("cooldown_scepter"))
else
ability:AutoStartCooldown()
end
parent:AddNewModifier(parent, ability, "modifier_sara_fragment_of_logic_debuff", {duration = ability:GetSpecialValueFor("debuff_duration")})
parent:ModifyEnergy(-toWaste)
parent:SetHealth(parent:GetMaxHealth())
parent:Purge(false, true, false, true, false)
ParticleManager:CreateParticle("particles/arena/units/heroes/hero_sara/fragment_of_logic.vpcf", PATTACH_ABSORIGIN, parent)
parent:EmitSound("Hero_Chen.HandOfGodHealHero")
end
end
end
function modifier_sara_fragment_of_logic:GetMinHealth(keys)
local parent = self:GetParent()
if not parent:IsIllusion() and parent.GetEnergy then
local ability = self:GetAbility()
if ability:IsCooldownReady() and parent:GetEnergy() >= ability:GetSpecialValueFor("energy_const") + parent:GetMaxEnergy() * ability:GetSpecialValueFor("energy_pct") * 0.01 then
return 1
end
end
end
end
modifier_sara_fragment_of_logic_debuff = class({
IsPurgable = function() return false end,
IsDebuff = function() return true end,
})
|
Fixed Sara's immortal illusions
|
Fixed Sara's immortal illusions
|
Lua
|
mit
|
ark120202/aabs
|
56aee3da470d00628700f8df415a8f488471d8c3
|
test_scripts/Polices/build_options/012_ATF_P_TC_HMI_sends_GetURLs_no_app_registered_HTTP.lua
|
test_scripts/Polices/build_options/012_ATF_P_TC_HMI_sends_GetURLs_no_app_registered_HTTP.lua
|
---------------------------------------------------------------------------------------------
-- Requirements summary:
-- In case HMI sends GetURLs and no apps registered SDL must return only default url
--
-- Description:
-- In case HMI sends GetURLs (<serviceType>) AND NO mobile apps registered
-- SDL must:check "endpoint" section in PolicyDataBase return only default url
--(meaning: SDL must skip others urls which relate to not registered apps)
-- 1. Used preconditions
-- SDL is built with "-DEXTENDED_POLICY: HTTP" flag
-- Application is registered. AppID is listed in PTS
-- No PTU is requested.
-- 2. Performed steps
-- Unregister application.
-- User press button on HMI to request PTU.
-- HMI->SDL: SDL.GetURLs(service=0x07)
--
-- Expected result:
-- PTU is requested. PTS is created.
-- SDL.GetURLs({urls[] = default})
---------------------------------------------------------------------------------------------
--[[ General configuration parameters ]]
config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0"
--[[ Required Shared libraries ]]
local commonSteps = require('user_modules/shared_testcases/commonSteps')
local commonFunctions = require('user_modules/shared_testcases/commonFunctions')
local testCasesForPolicyTable = require('user_modules/shared_testcases/testCasesForPolicyTable')
local testCasesForPolicyTableSnapshot = require('user_modules/shared_testcases/testCasesForPolicyTableSnapshot')
local commonTestCases = require('user_modules/shared_testcases/commonTestCases')
--[[ General Precondition before ATF start ]]
commonSteps:DeleteLogsFileAndPolicyTable()
testCasesForPolicyTable:Precondition_updatePolicy_By_overwriting_preloaded_pt("files/jsons/Policies/Policy_Table_Update/endpoints_appId.json")
--TODO: Should be removed when issue: "ATF does not stop HB timers by closing session and connection" is fixed
config.defaultProtocolVersion = 2
--[[ General Settings for configuration ]]
Test = require('connecttest')
require('cardinalities')
require('user_modules/AppTypes')
--[[ Preconditions ]]
commonFunctions:newTestCasesGroup("Preconditions")
function Test.Precondition_Wait()
commonTestCases:DelayedExp(1000)
end
function Test:Precondition_PTU_flow_SUCCESS ()
testCasesForPolicyTable:flow_PTU_SUCCEESS_HTTP(self)
end
function Test:Precondition_UnregisterApp()
self.mobileSession:SendRPC("UnregisterAppInterface", {})
EXPECT_HMINOTIFICATION("BasicCommunication.OnAppUnregistered",
{appID = self.applications[config.application1.registerAppInterfaceParams.appName], unexpectedDisconnect = false})
EXPECT_RESPONSE("UnregisterAppInterface", {success = true , resultCode = "SUCCESS"})
end
-- Request PTU
function Test:Precondition_trigger_PTU_user_request_update_from_HMI()
testCasesForPolicyTable:trigger_user_request_update_from_HMI(self)
end
--[[ Test ]]
commonFunctions:newTestCasesGroup("Test")
function Test:TestStep_PTU_GetURLs_NoAppRegistered()
local endpoints = {}
--TODO(istoimenova): Should be removed when "[GENIVI] HTTP: sdl_snapshot.json is not saved to file system" is fixed.
if ( commonSteps:file_exists( '/tmp/fs/mp/images/ivsu_cache/sdl_snapshot.json') ) then
testCasesForPolicyTableSnapshot:extract_pts()
for i = 1, #testCasesForPolicyTableSnapshot.pts_endpoints do
if (testCasesForPolicyTableSnapshot.pts_endpoints[i].service == "0x07") then
endpoints[#endpoints + 1] = {
url = testCasesForPolicyTableSnapshot.pts_endpoints[i].value,
appID = testCasesForPolicyTableSnapshot.pts_endpoints[i].appID}
end
end
else
commonFunctions:printError("sdl_snapshot is not created.")
endpoints = { {url = "http://policies.telematics.ford.com/api/policies", appID = nil} }
end
local RequestId = self.hmiConnection:SendRequest("SDL.GetURLS", { service = 7 })
EXPECT_HMIRESPONSE(RequestId,{result = {code = 0, method = "SDL.GetURLS"} } )
:Do(function(_,data)
local is_correct = {}
for i = 1, #data.result.urls do
is_correct[i] = false
for j = 1, #endpoints do
if ( data.result.urls[i].url == endpoints[j].url ) then
is_correct[i] = true
end
end
end
if(#data.result.urls ~= #endpoints ) then
self:FailTestCase("Number of urls is not as expected: "..#endpoints..". Real: "..#data.result.urls)
end
for i = 1, #is_correct do
if(is_correct[i] == false) then
self:FailTestCase("url: "..data.result.urls[i].url.." is not correct. Expected: "..endpoints[i].url)
end
end
end)
end
--[[ Postconditions ]]
commonFunctions:newTestCasesGroup("Postconditions")
testCasesForPolicyTable:Restore_preloaded_pt()
function Test.Postcondition_Stop_SDL()
StopSDL()
end
return Test
|
---------------------------------------------------------------------------------------------
-- Requirements summary:
-- In case HMI sends GetURLs and no apps registered SDL must return only default url
--
-- Description:
-- In case HMI sends GetURLs (<serviceType>) AND NO mobile apps registered
-- SDL must:check "endpoint" section in PolicyDataBase return only default url
--(meaning: SDL must skip others urls which relate to not registered apps)
-- 1. Used preconditions
-- SDL is built with "-DEXTENDED_POLICY: HTTP" flag
-- Application is registered. AppID is listed in PTS
-- No PTU is requested.
-- 2. Performed steps
-- Unregister application.
-- User press button on HMI to request PTU.
-- HMI->SDL: SDL.GetURLs(service=0x07)
--
-- Expected result:
-- PTU is requested. PTS is created.
-- SDL.GetURLs({urls[] = default})
---------------------------------------------------------------------------------------------
--[[ General configuration parameters ]]
config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0"
--[[ Required Shared libraries ]]
local commonSteps = require('user_modules/shared_testcases/commonSteps')
local commonFunctions = require('user_modules/shared_testcases/commonFunctions')
local testCasesForPolicyTable = require('user_modules/shared_testcases/testCasesForPolicyTable')
local commonTestCases = require('user_modules/shared_testcases/commonTestCases')
local mobile_session = require('mobile_session')
--[[ General Precondition before ATF start ]]
commonFunctions:SDLForceStop()
commonSteps:DeleteLogsFileAndPolicyTable()
testCasesForPolicyTable:Precondition_updatePolicy_By_overwriting_preloaded_pt("files/jsons/Policies/Policy_Table_Update/endpoints_appId.json")
--TODO: Should be removed when issue: "ATF does not stop HB timers by closing session and connection" is fixed
config.defaultProtocolVersion = 2
--[[ General Settings for configuration ]]
Test = require('connecttest')
require('cardinalities')
require('user_modules/AppTypes')
--[[ Preconditions ]]
commonFunctions:newTestCasesGroup("Preconditions")
function Test.Precondition_Wait()
commonTestCases:DelayedExp(1000)
end
function Test:Precondition_PTU_flow_SUCCESS ()
testCasesForPolicyTable:flow_PTU_SUCCEESS_HTTP(self)
end
function Test:Precondition_UnregisterApp()
self.mobileSession:SendRPC("UnregisterAppInterface", {})
EXPECT_HMINOTIFICATION("BasicCommunication.OnAppUnregistered",
{appID = self.applications[config.application1.registerAppInterfaceParams.appName], unexpectedDisconnect = false})
EXPECT_RESPONSE("UnregisterAppInterface", {success = true , resultCode = "SUCCESS"})
end
-- Request PTU
function Test:Precondition_TriggerPTU()
self.mobileSession2 = mobile_session.MobileSession(self, self.mobileConnection)
self.mobileSession2:StartService(7)
:Do(function()
local correlationId = self.mobileSession2:SendRPC("RegisterAppInterface", config.application2.registerAppInterfaceParams)
EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate", { status = "UPDATE_NEEDED" })
self.mobileSession2:ExpectResponse(correlationId, { success = true, resultCode = "SUCCESS" })
end)
end
--[[ Test ]]
commonFunctions:newTestCasesGroup("Test")
function Test:TestStep_PTU_GetURLs_NoAppRegistered()
local endpoints = { {url = "http://policies.telematics.ford.com/api/policies", appID = nil} }
local RequestId = self.hmiConnection:SendRequest("SDL.GetURLS", { service = 7 })
EXPECT_HMIRESPONSE(RequestId,{result = {code = 0, method = "SDL.GetURLS"} } )
:Do(function(_,data)
local is_correct = {}
for i = 1, #data.result.urls do
is_correct[i] = false
for j = 1, #endpoints do
if ( data.result.urls[i].url == endpoints[j].url ) then
is_correct[i] = true
end
end
end
if(#data.result.urls ~= #endpoints ) then
self:FailTestCase("Number of urls is not as expected: "..#endpoints..". Real: "..#data.result.urls)
end
for i = 1, #is_correct do
if(is_correct[i] == false) then
self:FailTestCase("url: "..data.result.urls[i].url.." is not correct. Expected: "..endpoints[i].url)
end
end
end)
end
--[[ Postconditions ]]
commonFunctions:newTestCasesGroup("Postconditions")
testCasesForPolicyTable:Restore_preloaded_pt()
function Test.Postcondition_Stop_SDL()
StopSDL()
end
return Test
|
Fix issues
|
Fix issues
|
Lua
|
bsd-3-clause
|
smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts
|
8ed9bc49f8aa96e74bbfa812999417a10f55ca9a
|
face-detector-elab/run.lua
|
face-detector-elab/run.lua
|
#!/usr/bin/env torch
------------------------------------------------------------
--
-- CNN face detector, based on convolutional network nets
--
-- original: Clement Farabet
-- E. Culurciello, A. Dundar, A. Canziani
-- Tue Mar 11 10:52:58 EDT 2014
--
------------------------------------------------------------
require 'pl'
require 'qt'
require 'qtwidget'
require 'qtuiloader'
require 'camera'
require 'image'
require 'nnx'
print '==> processing options'
opt = lapp[[
-c, --camidx (default 0) camera index: /dev/videoIDX
-n, --network (default 'model.net') path to networkimage.
-t, --threads (default 8) number of threads
--HD (default true) high resolution camera
]]
torch.setdefaulttensortype('torch.FloatTensor')
torch.setnumthreads(opt.threads)
-- blob parser in FFI (almost as fast as pure C!):
-- does not work anymore after some Torch changes.... need fix!@
function parseFFI(pin, iH, iW, threshold, blobs, scale)
--loop over pixels
for y=0, iH-1 do
for x=0, iW-1 do
if (pin[iW*y+x] > threshold) then
entry = {}
entry[1] = x
entry[2] = y
entry[3] = scale
table.insert(blobs,entry)
end
end
end
end
function parse(tin, threshold, blobs, scale)
--loop over pixels
for y=1, tin:size(1) do
for x=1, tin:size(2) do
if (tin[y][x] > threshold) then
entry = {}
entry[1] = x
entry[2] = y
entry[3] = scale
table.insert(blobs,entry)
end
end
end
end
-- load pre-trained network from disk
network1 = torch.load(opt.network) --load a network split in two: network and classifier
network = network1.modules[1] -- split network
network1.modules[2].modules[3] = nil -- remove logsoftmax
classifier1 = network1.modules[2] -- split and reconstruct classifier
network.modules[6] = nn.SpatialClassifier(classifier1)
network_fov = 32
network_sub = 4
print('Neural Network used: \n', network) -- print final network
-- setup camera
local GUI
if opt.HD then
camera = image.Camera(opt.camidx,640,360)
GUI = 'HDg.ui'
else
camera = image.Camera(opt.camidx)
GUI = 'g.ui'
end
-- process input at multiple scales
scales = {0.3, 0.24, 0.192, 0.15, 0.12, 0.1}
-- use a pyramid packer/unpacker
require 'PyramidPacker'
require 'PyramidUnPacker'
packer = nn.PyramidPacker(network, scales)
unpacker = nn.PyramidUnPacker(network)
-- setup GUI (external UI file)
if not win or not widget then
widget = qtuiloader.load(GUI)
win = qt.QtLuaPainter(widget.frame)
end
-- profiler
p = xlua.Profiler()
local neighborhood = image.gaussian1D(5)
-- Define our local normalization operator (It is an actual nn module,
-- which could be inserted into a trainable model):
local normalization = nn.SpatialContrastiveNormalization(1, neighborhood, 1):float()
-- process function
function process()
-- (1) grab frame
frame = camera:forward()
-- (2) transform it into Y space and global normalize:
frameY = image.rgb2y(frame)
-- global normalization:
local fmean = frameY:mean()
local fstd = frameY:std()
frameY:add(-fmean)
frameY:div(fstd)
-- (3) create multiscale pyramid
pyramid, coordinates = packer:forward(frameY)
-- local contrast normalization:
pyramid = normalization:forward(pyramid)
-- (4) run pre-trained network on it
multiscale = network:forward(pyramid)
-- (5) unpack pyramid
distributions = unpacker:forward(multiscale, coordinates)
-- (6) parse distributions to extract blob centroids
threshold = widget.verticalSlider.value/100-0.5
rawresults = {}
-- for i,distribution in ipairs(distributions) do
-- local pdist = torch.data(distribution[1])
-- parseFFI(pdist, distribution[1]:size(1), distribution[1]:size(2), threshold, rawresults, scales[i])
-- end
for i,distribution in ipairs(distributions) do
parse(distribution[1], threshold, rawresults, scales[i])
end
-- (7) clean up results
detections = {}
for i,res in ipairs(rawresults) do
local scale = res[3]
local x = res[1]*network_sub/scale
local y = res[2]*network_sub/scale
local w = network_fov/scale
local h = network_fov/scale
detections[i] = {x=x, y=y, w=w, h=h}
end
end
-- display function
function display()
win:gbegin()
win:showpage()
-- (1) display input image + pyramid
image.display{image=frame, win=win}
-- (2) overlay bounding boxes for each detection
for i,detect in ipairs(detections) do
win:setcolor(1,0,0)
win:rectangle(detect.x, detect.y, detect.w, detect.h)
win:stroke()
win:setfont(qt.QFont{serif=false,italic=false,size=16})
win:moveto(detect.x, detect.y-1)
win:show('face')
end
win:gend()
end
-- setup gui
timer = qt.QTimer()
timer.interval = 1
timer.singleShot = true
qt.connect(timer,
'timeout()',
function()
p:start('full loop','fps')
p:start('prediction','fps')
process()
p:lap('prediction')
p:start('display','fps')
display()
p:lap('display')
timer:start()
p:lap('full loop')
--p:printAll()
end)
widget.windowTitle = 'e-Lab Face Detector'
widget:show()
timer:start()
|
#!/usr/bin/env torch
------------------------------------------------------------
--
-- CNN face detector, based on convolutional network nets
--
-- original: Clement Farabet
-- E. Culurciello, A. Dundar, A. Canziani
-- Tue Mar 11 10:52:58 EDT 2014
--
------------------------------------------------------------
require 'pl'
require 'qt'
require 'qtwidget'
require 'qtuiloader'
require 'camera'
require 'image'
require 'nnx'
print '==> processing options'
opt = lapp[[
-c, --camidx (default 0) camera index: /dev/videoIDX
-n, --network (default 'model.net') path to networkimage.
-t, --threads (default 8) number of threads
--HD (default true) high resolution camera
]]
torch.setdefaulttensortype('torch.FloatTensor')
torch.setnumthreads(opt.threads)
-- blob parser in FFI (almost as fast as pure C!):
-- does not work anymore after some Torch changes.... need fix!@
function parseFFI(pin, iH, iW, threshold, blobs, scale)
--loop over pixels
for y=0, iH-1 do
for x=0, iW-1 do
if (pin[iW*y+x] > threshold) then
entry = {}
entry[1] = x
entry[2] = y
entry[3] = scale
table.insert(blobs,entry)
end
end
end
end
function parse(tin, threshold, blobs, scale)
--loop over pixels
for y=1, tin:size(1) do
for x=1, tin:size(2) do
if (tin[y][x] > threshold) then
entry = {}
entry[1] = x
entry[2] = y
entry[3] = scale
table.insert(blobs,entry)
end
end
end
end
-- load pre-trained network from disk
network1 = torch.load(opt.network) --load a network split in two: network and classifier
network = network1.modules[1] -- split network
network1.modules[2].modules[3] = nil -- remove logsoftmax
classifier1 = network1.modules[2] -- split and reconstruct classifier
network.modules[6] = nn.SpatialClassifier(classifier1)
network_fov = 32
network_sub = 4
print('Neural Network used: \n', network) -- print final network
-- setup camera
local GUI
if opt.HD then
camera = image.Camera(opt.camidx,640,360)
GUI = 'HDg.ui'
else
camera = image.Camera(opt.camidx)
GUI = 'g.ui'
end
-- process input at multiple scales
scales = {0.3, 0.24, 0.192, 0.15, 0.12, 0.1}
-- use a pyramid packer/unpacker
require 'PyramidPacker'
require 'PyramidUnPacker'
packer = nn.PyramidPacker(network, scales)
unpacker = nn.PyramidUnPacker(network)
-- setup GUI (external UI file)
if not win or not widget then
widget = qtuiloader.load(GUI)
win = qt.QtLuaPainter(widget.frame)
end
-- profiler
p = xlua.Profiler()
local neighborhood = image.gaussian1D(5)
-- Define our local normalization operator (It is an actual nn module,
-- which could be inserted into a trainable model):
local normalization = nn.SpatialContrastiveNormalization(1, neighborhood, 1):float()
-- process function
function process()
-- (1) grab frame
frame = camera:forward()
-- (2) transform it into Y space and global normalize:
frameY = image.rgb2y(frame)
-- global normalization:
local fmean = frameY:mean()
local fstd = frameY:std()
frameY:add(-fmean)
frameY:div(fstd)
-- (3) create multiscale pyramid
pyramid, coordinates = packer:forward(frameY)
-- local contrast normalization:
pyramid = normalization:forward(pyramid)
-- (4) run pre-trained network on it
multiscale = network:forward(pyramid)
-- (5) unpack pyramid
distributions = unpacker:forward(multiscale, coordinates)
-- (6) parse distributions to extract blob centroids
threshold = widget.verticalSlider.value/100-0.5
rawresults = {}
for i,distribution in ipairs(distributions) do
local pdist = torch.data(distribution[1]:contiguous())
parseFFI(pdist, distribution[1]:size(1), distribution[1]:size(2), threshold, rawresults, scales[i])
end
-- for i,distribution in ipairs(distributions) do
-- parse(distribution[1], threshold, rawresults, scales[i])
-- end
-- (7) clean up results
detections = {}
for i,res in ipairs(rawresults) do
local scale = res[3]
local x = res[1]*network_sub/scale
local y = res[2]*network_sub/scale
local w = network_fov/scale
local h = network_fov/scale
detections[i] = {x=x, y=y, w=w, h=h}
end
end
-- display function
function display()
win:gbegin()
win:showpage()
-- (1) display input image + pyramid
image.display{image=frame, win=win}
-- (2) overlay bounding boxes for each detection
for i,detect in ipairs(detections) do
win:setcolor(1,0,0)
win:rectangle(detect.x, detect.y, detect.w, detect.h)
win:stroke()
win:setfont(qt.QFont{serif=false,italic=false,size=16})
win:moveto(detect.x, detect.y-1)
win:show('face')
end
win:gend()
end
-- setup gui
timer = qt.QTimer()
timer.interval = 1
timer.singleShot = true
qt.connect(timer,
'timeout()',
function()
p:start('full loop','fps')
p:start('prediction','fps')
process()
p:lap('prediction')
p:start('display','fps')
display()
p:lap('display')
timer:start()
p:lap('full loop')
--p:printAll()
end)
widget.windowTitle = 'e-Lab Face Detector'
widget:show()
timer:start()
|
FFI function needs contiguous memory - fixed
|
FFI function needs contiguous memory - fixed
|
Lua
|
bsd-3-clause
|
e-lab/torch7-demos,e-lab/torch7-demos
|
52364bef5f3e1e8ff88d3134adbcc3f610ec72ee
|
init.lua
|
init.lua
|
-- We are using paths.require to appease mkl
-- Make this work with LuaJIT in Lua 5.2 compatibility mode, which
-- renames string.gfind (already deprecated in 5.1)
if not string.gfind then
string.gfind = string.gmatch
end
if not table.unpack then
table.unpack = unpack
end
require "paths"
paths.require "libtorch"
--- package stuff
function torch.packageLuaPath(name)
if not name then
local ret = string.match(torch.packageLuaPath('torch'), '(.*)/')
if not ret then --windows?
ret = string.match(torch.packageLuaPath('torch'), '(.*)\\')
end
return ret
end
for path in string.gmatch(package.path, "[^;]+") do
path = string.gsub(path, "%?", name)
local f = io.open(path)
if f then
f:close()
local ret = string.match(path, "(.*)/")
if not ret then --windows?
ret = string.match(path, "(.*)\\")
end
return ret
end
end
end
local function include(file, depth)
paths.dofile(file, 3 + (depth or 0))
end
rawset(_G, 'include', include)
function torch.include(package, file)
dofile(torch.packageLuaPath(package) .. '/' .. file)
end
function torch.class(tname, parenttname)
local function constructor(...)
local self = {}
torch.setmetatable(self, tname)
if self.__init then
self:__init(...)
end
return self
end
local function factory()
local self = {}
torch.setmetatable(self, tname)
return self
end
local mt = torch.newmetatable(tname, parenttname, constructor, nil, factory)
local mpt
if parenttname then
mpt = torch.getmetatable(parenttname)
end
return mt, mpt
end
function torch.setdefaulttensortype(typename)
assert(type(typename) == 'string', 'string expected')
if torch.getconstructortable(typename) then
torch.Tensor = torch.getconstructortable(typename)
torch.Storage = torch.getconstructortable(torch.typename(torch.Tensor(1):storage()))
else
error(string.format("<%s> is not a string describing a torch object", typename))
end
end
function torch.type(obj)
local class = torch.typename(obj)
if not class then
class = type(obj)
end
return class
end
-- Returns true if the type given by the passed-in metatable equals typeSpec.
local function exactTypeMatch(obj_mt, typeSpec)
return obj_mt.__typename == typeSpec
end
--[[ Returns true if the type given by the passed-in metatable either equals
typeSpec, or ends with ".<typeSpec>". For example, "ab.cd.ef" matches type specs
"ef", "cd.ef", and "ab.cd.ef", but not "f" or "d.ef". ]]
local function partialTypeMatch(obj_mt, typeSpec)
local typeName = obj_mt.__typename
local diffLen = #typeName - #typeSpec
if diffLen < 0 then
return false
end
if typeName:sub(diffLen+1) ~= typeSpec then
return false
end
return diffLen == 0 or typeName:sub(diffLen, diffLen) == '.'
end
--[[ See if a given object is an instance of the provided torch class. ]]
function torch.isTypeOf(obj, typeSpec)
-- typeSpec can be provided as either a string, regexp, or the constructor.
-- If the constructor is used, we look in the __typename field of the
-- metatable to find a string to compare to.
local matchFunc
if type(typeSpec) == 'table' then
typeSpec = getmetatable(typeSpec).__typename
matchFunc = exactTypeMatch
elseif type(typeSpec) == 'string' then
matchFunc = partialTypeMatch
else
error("type must be provided as [regexp] string, or factory")
end
local mt = getmetatable(obj)
while mt do
if matchFunc(mt, typeSpec) then
return true
end
mt = getmetatable(mt)
end
return false
end
torch.setdefaulttensortype('torch.DoubleTensor')
include('Tensor.lua')
include('File.lua')
include('CmdLine.lua')
include('FFI.lua')
include('Tester.lua')
include('test.lua')
function torch.totable(obj)
if torch.isTensor(obj) or torch.isStorage(obj) then
return obj:totable()
else
error("obj must be a Storage or a Tensor")
end
end
function torch.isTensor(obj)
local typename = torch.typename(obj)
if typename and typename:find('torch.*Tensor') then
return true
end
return false
end
function torch.isStorage(obj)
local typename = torch.typename(obj)
if typename and typename:find('torch.*Storage') then
return true
end
return false
end
-- alias for convenience
torch.Tensor.isTensor = torch.isTensor
return torch
|
-- We are using paths.require to appease mkl
-- Make this work with LuaJIT in Lua 5.2 compatibility mode, which
-- renames string.gfind (already deprecated in 5.1)
if not string.gfind then
string.gfind = string.gmatch
end
if not table.unpack then
table.unpack = unpack
end
require "paths"
paths.require "libtorch"
--- package stuff
function torch.packageLuaPath(name)
if not name then
local ret = string.match(torch.packageLuaPath('torch'), '(.*)/')
if not ret then --windows?
ret = string.match(torch.packageLuaPath('torch'), '(.*)\\')
end
return ret
end
for path in string.gmatch(package.path, "[^;]+") do
path = string.gsub(path, "%?", name)
local f = io.open(path)
if f then
f:close()
local ret = string.match(path, "(.*)/")
if not ret then --windows?
ret = string.match(path, "(.*)\\")
end
return ret
end
end
end
local function include(file, depth)
paths.dofile(file, 3 + (depth or 0))
end
rawset(_G, 'include', include)
function torch.include(package, file)
dofile(torch.packageLuaPath(package) .. '/' .. file)
end
function torch.class(tname, parenttname)
local function constructor(...)
local self = {}
torch.setmetatable(self, tname)
if self.__init then
self:__init(...)
end
return self
end
local function factory()
local self = {}
torch.setmetatable(self, tname)
return self
end
local mt = torch.newmetatable(tname, parenttname, constructor, nil, factory)
local mpt
if parenttname then
mpt = torch.getmetatable(parenttname)
end
return mt, mpt
end
function torch.setdefaulttensortype(typename)
assert(type(typename) == 'string', 'string expected')
if torch.getconstructortable(typename) then
torch.Tensor = torch.getconstructortable(typename)
torch.Storage = torch.getconstructortable(torch.typename(torch.Tensor(1):storage()))
else
error(string.format("<%s> is not a string describing a torch object", typename))
end
end
function torch.type(obj)
local class = torch.typename(obj)
if not class then
class = type(obj)
end
return class
end
-- Returns true if the type given by the passed-in typeName equals typeSpec.
local function exactTypeMatch(typeName, typeSpec)
return typeName == typeSpec
end
--[[ Returns true if the type given by the passed-in typeName either equals
typeSpec, or ends with ".<typeSpec>". For example, "ab.cd.ef" matches type specs
"ef", "cd.ef", and "ab.cd.ef", but not "f" or "d.ef". ]]
local function partialTypeMatch(typeName, typeSpec)
local diffLen = #typeName - #typeSpec
if diffLen < 0 then
return false
end
if typeName:sub(diffLen+1) ~= typeSpec then
return false
end
return diffLen == 0 or typeName:sub(diffLen, diffLen) == '.'
end
--[[ See if a given object is an instance of the provided torch class. ]]
function torch.isTypeOf(obj, typeSpec)
-- typeSpec can be provided as either a string, regexp, or the constructor.
-- If the constructor is used, we look in the __typename field of the
-- metatable to find a string to compare to.
local matchFunc
if type(typeSpec) == 'table' then
typeSpec = getmetatable(typeSpec).__typename
matchFunc = exactTypeMatch
elseif type(typeSpec) == 'string' then
matchFunc = partialTypeMatch
else
error("type must be provided as [regexp] string, or factory")
end
local mt = getmetatable(obj)
while mt do
if mt.__typename and matchFunc(mt.__typename, typeSpec) then
return true
end
mt = getmetatable(mt)
end
return false
end
torch.setdefaulttensortype('torch.DoubleTensor')
include('Tensor.lua')
include('File.lua')
include('CmdLine.lua')
include('FFI.lua')
include('Tester.lua')
include('test.lua')
function torch.totable(obj)
if torch.isTensor(obj) or torch.isStorage(obj) then
return obj:totable()
else
error("obj must be a Storage or a Tensor")
end
end
function torch.isTensor(obj)
local typename = torch.typename(obj)
if typename and typename:find('torch.*Tensor') then
return true
end
return false
end
function torch.isStorage(obj)
local typename = torch.typename(obj)
if typename and typename:find('torch.*Storage') then
return true
end
return false
end
-- alias for convenience
torch.Tensor.isTensor = torch.isTensor
return torch
|
Fix torch.isTypeOf(<string>, ...)
|
Fix torch.isTypeOf(<string>, ...)
Fix the following cases (they raise error now):
torch.isTypeOf("string", "nn.Module")
require 'nn';
m = nn.Module()
m.name = "module"
nn.utils.recursiveType(m, "torch.FloatTensor")
|
Lua
|
bsd-3-clause
|
eulerreich/torch7,colesbury/torch7,Atcold/torch7,xindaya/torch7,bartvm/torch7,hmandal/torch7,eulerreich/torch7,wangg12/torch7,kirangonella/torch7,chenfsjz/torch7,Atcold/torch7,ninjin/torch7,PierrotLC/torch7,clementfarabet/torch7,hmandal/torch7,waitwaitforget/torch7,ninjin/torch7,dariosena/torch7,alexbw/torch7,Moodstocks/torch7,eriche2016/torch7,diz-vara/torch7,0wu/torch7,jaak-s/torch7,dhruvparamhans/torch7,dhruvparamhans/torch7,yozw/torch7,u20024804/torch7,jibaro/torch7,wheatwaves/torch7,ujjwalkarn/torch7,wgapl/torch7,colesbury/torch7,szagoruyko/torch7,wickedfoo/torch7,jbeich/torch7,stein2013/torch7,xindaya/torch7,wangg12/torch7,pushups/torch7,nicholas-leonard/torch7,waitwaitforget/torch7,bartvm/torch7,pushups/torch7,syhw/torch7,PierrotLC/torch7,kaustubhcs/torch7,adamlerer/torch7,ilovecv/torch7,jbeich/torch7,chenfsjz/torch7,wickedfoo/torch7,ilovecv/torch7,kirangonella/torch7,clementfarabet/torch7,alexbw/torch7,LinusU/torch7,wgapl/torch7,LinusU/torch7,bnk-iitb/torch7,nicholas-leonard/torch7,adamlerer/torch7,szagoruyko/torch7,wheatwaves/torch7,syhw/torch7,0wu/torch7,bnk-iitb/torch7,jibaro/torch7,stein2013/torch7,jaak-s/torch7,kaustubhcs/torch7,dariosena/torch7,eriche2016/torch7,yozw/torch7,u20024804/torch7,ujjwalkarn/torch7,diz-vara/torch7,Moodstocks/torch7
|
b1b4201a14b2ae38df7af83658c2c4544522cfc0
|
src/nodes/platform.lua
|
src/nodes/platform.lua
|
local Timer = require 'vendor/timer'
local controls = require 'controls'
local Platform = {}
Platform.__index = Platform
function Platform.new(node, collider)
local platform = {}
setmetatable(platform, Platform)
--If the node is a polyline, we need to draw a polygon rather than rectangle
if node.polyline or node.polygon then
local polygon = node.polyline or node.polygon
local vertices = {}
for i, point in ipairs(polygon) do
table.insert(vertices, node.x + point.x)
table.insert(vertices, node.y + point.y)
end
platform.bb = collider:addPolygon(unpack(vertices))
platform.bb.polyline = polygon
else
platform.bb = collider:addRectangle(node.x, node.y, node.width, node.height)
platform.bb.polyline = nil
end
platform.drop = node.properties.drop ~= 'false'
platform.bb.node = platform
collider:setPassive(platform.bb)
return platform
end
function Platform:collide( player, dt, mtv_x, mtv_y )
self.player_touched = true
if self.dropping then
return
end
local _, wy1, _, wy2 = self.bb:bbox()
local px1, py1, px2, py2 = player.bb:bbox()
local distance = math.abs(player.velocity.y * dt) + 0.10
function updatePlayer()
player:moveBoundingBox()
player.jumping = false
player.rebounding = false
player:impactDamage()
end
if self.bb.polyline
and player.velocity.y >= 0
-- Prevent the player from being treadmilled through an object
and ( self.bb:contains(px2,py2) or self.bb:contains(px1,py2) ) then
player.velocity.y = 0
-- Use the MTV to keep players feet on the ground,
-- fudge the Y a bit to prevent falling into steep angles
player.position.y = (py1 - 4 ) + mtv_y
updatePlayer()
elseif player.velocity.y >= 0 and math.abs(wy1 - py2) <= distance then
player.velocity.y = 0
player.position.y = wy1 - player.height
updatePlayer()
end
end
function Platform:collide_end()
self.player_touched = false
self.dropping = false
end
function Platform:keyreleased( button, player )
if button == 'DOWN' and self.timer then
Timer.cancel(self.timer)
end
end
function Platform:keypressed( button, player )
if button == 'DOWN' and self.drop then
self.timer = Timer.add( 0.35, function() self.dropping = true end )
end
end
return Platform
|
local Timer = require 'vendor/timer'
local controls = require 'controls'
local Platform = {}
Platform.__index = Platform
function Platform.new(node, collider)
local platform = {}
setmetatable(platform, Platform)
--If the node is a polyline, we need to draw a polygon rather than rectangle
if node.polyline or node.polygon then
local polygon = node.polyline or node.polygon
local vertices = {}
for i, point in ipairs(polygon) do
table.insert(vertices, node.x + point.x)
table.insert(vertices, node.y + point.y)
end
platform.bb = collider:addPolygon(unpack(vertices))
platform.bb.polyline = polygon
else
platform.bb = collider:addRectangle(node.x, node.y, node.width, node.height)
platform.bb.polyline = nil
end
platform.drop = node.properties.drop ~= 'false'
platform.bb.node = platform
collider:setPassive(platform.bb)
return platform
end
function Platform:collide( player, dt, mtv_x, mtv_y )
self.player_touched = true
if self.dropping then
return
end
local _, wy1, _, wy2 = self.bb:bbox()
local px1, py1, px2, py2 = player.bb:bbox()
local distance = math.abs(player.velocity.y * dt) + 0.10
function updatePlayer()
player:moveBoundingBox()
player.jumping = false
player.rebounding = false
player:impactDamage()
end
if self.bb.polyline
and player.velocity.y >= 0
-- Prevent the player from being treadmilled through an object
and ( self.bb:contains(px2,py2) or self.bb:contains(px1,py2) ) then
player.velocity.y = 0
-- Use the MTV to keep players feet on the ground,
-- fudge the Y a bit to prevent falling into steep angles
player.position.y = (py1 - 4 ) + mtv_y
updatePlayer()
elseif player.velocity.y >= 0 and math.abs(wy1 - py2) <= distance then
player.velocity.y = 0
player.position.y = wy1 - player.height
updatePlayer()
end
end
function Platform:collide_end()
self.player_touched = false
self.dropping = false
if self.timer then
Timer.cancel(self.timer)
end
end
function Platform:keyreleased( button, player )
if button == 'DOWN' and self.timer then
Timer.cancel(self.timer)
end
end
function Platform:keypressed( button, player )
if button == 'DOWN' and self.drop then
self.timer = Timer.add( 0.35, function() self.dropping = true end )
end
end
return Platform
|
Fix #244
|
Fix #244
|
Lua
|
mit
|
hawkthorne/hawkthorne-client-lua,hawkthorne/hawkthorne-server-lua,hawkthorne/hawkthorne-client-lua,hawkthorne/hawkthorne-server-lua
|
ca49466f69aff566e4592cca1c81ced903b3fa07
|
Quadtastic/Text.lua
|
Quadtastic/Text.lua
|
local Text = {}
local unpack = unpack or table.unpack
Text.min_width = function(state, text)
return state.style.font and state.style.font:getWidth(text)
end
-- Returns a table of lines, none of which exceed the given width.
-- Returns a table with the original text if width is 0 or nil.
function Text.break_at(state, text, width)
if not width or width <= 0 then return {text} end
local lines = {}
local line = {}
local line_length = 0
local separators = {"\n", " ", "-", "/", "\\", "."}
local function complete_line(separator)
local new_line = table.concat(line, separator)
table.insert(lines, new_line)
end
local function break_up(chunk, sep_index)
local separator = separators[sep_index]
local separator_width = Text.min_width(state, separator)
for word in string.gmatch(chunk, string.format("[^%s]+", separator)) do
local wordlength = Text.min_width(state, word)
if wordlength > width then
-- Try to break at other boundaries
if sep_index == #separators then
print(string.format("Warning: %s is too long for one line", chunk))
else
break_up(word, sep_index + 1)
end
elseif line_length + wordlength > width then
complete_line(separator)
line, line_length = {word}, wordlength
else
table.insert(line, word)
line_length = line_length + wordlength + separator_width
end
end
-- Add any outstanding words
if #line > 0 then
if separator == "\n" then
for _,v in ipairs(line) do
table.insert(lines, v)
end
line, line_length = {}, 0
else
complete_line(separator)
line, line_length = {}, 0
end
end
end
break_up(text, 1)
return lines
end
Text.draw = function(state, x, y, w, h, text, options)
x = x or state.layout.next_x
y = y or state.layout.next_y
local textwidth = Text.min_width(state, text)
local textheight = 16
w = w or textwidth
h = h or textheight
if options then
-- center alignment
if options.alignment_h == ":" then
x = x + w/2 - textwidth /2
-- right alignment
elseif options.alignment_h == ">" then
x = x + w - textwidth
end
-- vertically aligned to the center
if options.alignment_v == "-" then
y = y + h/2 - textheight/2
-- aligned to the bottom
elseif options.alignment_v == "v" then
y = y + h - textheight
end
end
x = math.floor(x)
y = math.floor(y)
love.graphics.setFont(state.style.font)
-- Print Text
if options and options.font_color then
love.graphics.setColor(unpack(options.font_color))
end
love.graphics.print(text or "", x, y)
end
return Text
|
local Text = {}
local unpack = unpack or table.unpack
Text.min_width = function(state, text)
return state.style.font and state.style.font:getWidth(text)
end
-- Returns a table of lines, none of which exceed the given width.
-- Returns a table with the original text if width is 0 or nil.
function Text.break_at(state, text, width)
if not width or width <= 0 then return {text} end
local lines = {}
local line = {}
local line_length = 0
local separators = {" ", "-", "/", "\\", "."}
local function complete_line(separator)
local new_line = table.concat(line, separator)
table.insert(lines, new_line)
end
local function break_up(chunk, sep_index)
local separator = separators[sep_index]
local separator_width = Text.min_width(state, separator)
for word in string.gmatch(chunk, string.format("[^%s]+", separator)) do
local wordlength = Text.min_width(state, word)
if wordlength > width then
-- Try to break at other boundaries
if sep_index == #separators then
print(string.format("Warning: %s is too long for one line", chunk))
else
break_up(word, sep_index + 1)
end
elseif line_length + wordlength > width then
complete_line(separator)
line, line_length = {word}, wordlength
else
table.insert(line, word)
line_length = line_length + wordlength + separator_width
end
end
-- Add any outstanding words
if #line > 0 then
complete_line(separator)
line, line_length = {}, 0
end
end
for line in string.gmatch(text, "[^\n]+") do
break_up(line, 1)
end
return lines
end
Text.draw = function(state, x, y, w, h, text, options)
x = x or state.layout.next_x
y = y or state.layout.next_y
local textwidth = Text.min_width(state, text)
local textheight = 16
w = w or textwidth
h = h or textheight
if options then
-- center alignment
if options.alignment_h == ":" then
x = x + w/2 - textwidth /2
-- right alignment
elseif options.alignment_h == ">" then
x = x + w - textwidth
end
-- vertically aligned to the center
if options.alignment_v == "-" then
y = y + h/2 - textheight/2
-- aligned to the bottom
elseif options.alignment_v == "v" then
y = y + h - textheight
end
end
x = math.floor(x)
y = math.floor(y)
love.graphics.setFont(state.style.font)
-- Print Text
if options and options.font_color then
love.graphics.setColor(unpack(options.font_color))
end
love.graphics.print(text or "", x, y)
end
return Text
|
Fix multi-line text not breaking at newline
|
Fix multi-line text not breaking at newline
|
Lua
|
mit
|
25A0/Quadtastic,25A0/Quadtastic
|
cab0c3e399e8a958344f0460c4f2478c577fd079
|
kong/plugins/session/schema.lua
|
kong/plugins/session/schema.lua
|
local typedefs = require "kong.db.schema.typedefs"
local Schema = require "kong.db.schema"
local utils = require("kong.tools.utils")
local char = string.char
local rand = math.random
local encode_base64 = ngx.encode_base64
local samesite = Schema.define {
type = "string",
default = "Strict",
one_of = {
"Strict",
"Lax",
"off",
}
}
--- kong.utils.random_string with 32 bytes instead
-- @returns random string of length 44
local function random_string()
return encode_base64(utils.get_rand_bytes(32, true))
:gsub("/", char(rand(48, 57))) -- 0 - 10
:gsub("+", char(rand(65, 90))) -- A - Z
:gsub("=", char(rand(97, 122))) -- a - z
end
return {
name = "session",
fields = {
{ config = {
type = "record",
fields = {
{ consumer = typedefs.no_consumer },
{
secret = {
type = "string",
required = false,
default = random_string(),
},
},
{ cookie_name = { type = "string", default = "session" } },
{ cookie_lifetime = { type = "number", default = 3600 } },
{ cookie_renew = { type = "number", default = 600 } },
{ cookie_path = { type = "string", default = "/" } },
{ cookie_domain = { type = "string" } },
{ cookie_samesite = samesite },
{ cookie_httponly = { type = "boolean", default = true } },
{ cookie_secure = { type = "boolean", default = true } },
{ cookie_discard = { type = "number", default = 10 } },
{
storage = {
required = false,
type = "string",
one_of = {
"cookie",
"kong",
},
default = "cookie",
}
},
{
logout_methods = {
type = "array",
elements = {
type = "string",
one_of = { "GET", "POST", "DELETE" },
},
default = { "POST", "DELETE" },
}
},
{
logout_query_arg = {
required = false,
type = "string",
default = "session_logout",
}
},
{
logout_post_arg = {
required = false,
type = "string",
default = "session_logout",
},
},
},
},
},
},
}
|
local typedefs = require "kong.db.schema.typedefs"
local Schema = require "kong.db.schema"
local utils = require("kong.tools.utils")
local char = string.char
local rand = math.random
local encode_base64 = ngx.encode_base64
local samesite = Schema.define {
type = "string",
default = "Strict",
one_of = {
"Strict",
"Lax",
"off",
}
}
--- kong.utils.random_string with 32 bytes instead
-- @returns random string of length 44
local function random_string()
return encode_base64(utils.get_rand_bytes(32, true))
:gsub("/", char(rand(48, 57))) -- 0 - 10
:gsub("+", char(rand(65, 90))) -- A - Z
:gsub("=", char(rand(97, 122))) -- a - z
end
return {
name = "session",
fields = {
{ consumer = typedefs.no_consumer },
{ config = {
type = "record",
fields = {
{
secret = {
type = "string",
required = false,
default = random_string(),
},
},
{ cookie_name = { type = "string", default = "session" } },
{ cookie_lifetime = { type = "number", default = 3600 } },
{ cookie_renew = { type = "number", default = 600 } },
{ cookie_path = { type = "string", default = "/" } },
{ cookie_domain = { type = "string" } },
{ cookie_samesite = samesite },
{ cookie_httponly = { type = "boolean", default = true } },
{ cookie_secure = { type = "boolean", default = true } },
{ cookie_discard = { type = "number", default = 10 } },
{
storage = {
required = false,
type = "string",
one_of = {
"cookie",
"kong",
},
default = "cookie",
}
},
{
logout_methods = {
type = "array",
elements = {
type = "string",
one_of = { "GET", "POST", "DELETE" },
},
default = { "POST", "DELETE" },
}
},
{
logout_query_arg = {
required = false,
type = "string",
default = "session_logout",
}
},
{
logout_post_arg = {
required = false,
type = "string",
default = "session_logout",
},
},
},
},
},
},
}
|
fix(session) add no_consumer to fields
|
fix(session) add no_consumer to fields
|
Lua
|
apache-2.0
|
Kong/kong,Kong/kong,Kong/kong
|
b677817d47a8c7c96f37896dfdde6906f288feb5
|
examples/pcap/replay-pcap.lua
|
examples/pcap/replay-pcap.lua
|
--- Replay a pcap file.
local mg = require "moongen"
local device = require "device"
local memory = require "memory"
local stats = require "stats"
local log = require "log"
local pcap = require "pcap"
local limiter = require "software-ratecontrol"
function configure(parser)
parser:argument("edev", "Device to use for egress."):args(1):convert(tonumber)
parser:argument("idev", "Device to use for ingress."):args(1):convert(tonumber)
parser:argument("file", "File to replay."):args(1)
parser:option("-r --rate-multiplier", "Speed up or slow down replay, 1 = use intervals from file, default = replay as fast as possible"):default(0):convert(tonumber):target("rateMultiplier")
parser:flag("-l --loop", "Repeat pcap file.")
local args = parser:parse()
return args
end
function master(args)
local edev = device.config{port = args.edev}
local idev = device.config{port = args.idev, dropEnable = false}
device.waitForLinks()
local rateLimiter
if args.rateMultiplier > 0 then
rateLimiter = limiter:new(edev:getTxQueue(0), "custom")
end
mg.startTask("replay", edev:getTxQueue(0), args.file, args.loop, rateLimiter, args.rateMultiplier)
stats.startStatsTask{txDevices = {edev}, rxDevices = {idev}}
mg.waitForTasks()
end
function replay(queue, file, loop, rateLimiter, multiplier)
local mempool = memory:createMemPool(4096)
local bufs = mempool:bufArray()
local pcapFile = pcap:newReader(file)
local prev = 0
local linkSpeed = queue.dev:getLinkStatus().speed
while mg.running() do
local n = pcapFile:read(bufs)
if n > 0 then
if rateLimiter ~= nil then
if prev == 0 then
prev = bufs.array[0].udata64
end
for i, buf in ipairs(bufs) do
if i > n then break end
-- ts is in microseconds
local ts = buf.udata64
if prev > ts then
ts = prev
end
local delay = ts - prev
delay = tonumber(delay * 10^3) / multiplier -- nanoseconds
delay = delay / (8000 / linkSpeed) -- delay in bytes
buf:setDelay(delay)
prev = ts
end
end
else
if loop then
pcapFile:reset()
else
break
end
end
if rateLimiter then
rateLimiter:sendN(bufs, n)
else
queue:sendN(bufs, n)
end
end
end
|
--- Replay a pcap file.
local mg = require "moongen"
local device = require "device"
local memory = require "memory"
local stats = require "stats"
local log = require "log"
local pcap = require "pcap"
local limiter = require "software-ratecontrol"
function configure(parser)
parser:argument("edev", "Device to use for egress."):args(1):convert(tonumber)
parser:argument("idev", "Device to use for ingress."):args(1):convert(tonumber)
parser:argument("file", "File to replay."):args(1)
parser:option("-f --fix-rate", "Fixed net data rate in Mbit per second (ignore timestamps in pcap)"):default(0):convert(tonumber):target("fixedRate")
parser:option("-r --rate-multiplier", "Speed up or slow down replay, 1 = use intervals from file, default = replay as fast as possible"):default(0):convert(tonumber):target("rateMultiplier")
parser:flag("-l --loop", "Repeat pcap file.")
local args = parser:parse()
return args
end
function master(args)
local edev = device.config{port = args.edev}
local idev = device.config{port = args.idev, dropEnable = false}
device.waitForLinks()
local rateLimiter
if args.rateMultiplier > 0 and args.fixedRate > 0 then
print("-r and -f option cannot be set at the same time.")
return
end
if args.rateMultiplier > 0 or args.fixedRate > 0 then
rateLimiter = limiter:new(edev:getTxQueue(0), "custom")
end
mg.startTask("replay", edev:getTxQueue(0), args.file, args.loop, rateLimiter, args.rateMultiplier, args.fixedRate)
stats.startStatsTask{txDevices = {edev}, rxDevices = {idev}}
mg.waitForTasks()
end
function replay(queue, file, loop, rateLimiter, multiplier, fixedRate)
local mempool = memory:createMemPool(4096)
local bufs = mempool:bufArray()
local pcapFile = pcap:newReader(file)
local prev = 0
local linkSpeed = queue.dev:getLinkStatus().speed
while mg.running() do
local n = pcapFile:read(bufs)
if n > 0 then
if rateLimiter ~= nil then
if prev == 0 then
prev = bufs.array[0].udata64
end
for i, buf in ipairs(bufs) do
if i > n then break end
-- ts is in microseconds
local ts = buf.udata64
if prev > ts then
ts = prev
end
sz = buf:getSize()
local delay = ts - prev
delay = tonumber(delay * 10^3) / multiplier -- nanoseconds
delay = delay / (8000 / linkSpeed) -- delay in bytes
if fixedRate > 0 then
delay = (sz + 4) / (fixedRate/10000)
end
buf:setDelay(delay)
prev = ts
end
end
else
if loop then
pcapFile:reset()
else
break
end
end
if rateLimiter then
rateLimiter:sendN(bufs, n)
else
queue:sendN(bufs, n)
end
end
end
|
add fixed packet rate feature to replay-pcap
|
add fixed packet rate feature to replay-pcap
|
Lua
|
mit
|
gallenmu/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen
|
4bde88cd8146f0df3f4c9880e5265dab5702cfa4
|
lua_modules/ds18b20/ds18b20.lua
|
lua_modules/ds18b20/ds18b20.lua
|
--------------------------------------------------------------------------------
-- DS18B20 one wire module for NODEMCU
-- NODEMCU TEAM
-- LICENCE: http://opensource.org/licenses/MIT
-- Vowstar <vowstar@nodemcu.com>
--------------------------------------------------------------------------------
-- Set module name as parameter of require
local modname = ...
local M = {}
_G[modname] = M
--------------------------------------------------------------------------------
-- Local used variables
--------------------------------------------------------------------------------
-- DS18B20 dq pin
local pin = nil
-- DS18B20 default pin
local defaultPin = 9
--------------------------------------------------------------------------------
-- Local used modules
--------------------------------------------------------------------------------
-- Table module
local table = table
-- String module
local string = string
-- One wire module
local ow = ow
-- Timer module
local tmr = tmr
-- Limited to local environment
setfenv(1,M)
--------------------------------------------------------------------------------
-- Implementation
--------------------------------------------------------------------------------
C = 0
F = 1
K = 2
function setup(dq)
pin = dq
if(pin == nil) then
pin = defaultPin
end
ow.setup(pin)
end
function addrs()
setup(pin)
tbl = {}
ow.reset_search(pin)
repeat
addr = ow.search(pin)
if(addr ~= nil) then
table.insert(tbl, addr)
end
tmr.wdclr()
until (addr == nil)
ow.reset_search(pin)
return tbl
end
function readNumber(addr, unit)
result = nil
setup(pin)
flag = false
if(addr == nil) then
ow.reset_search(pin)
count = 0
repeat
count = count + 1
addr = ow.search(pin)
tmr.wdclr()
until((addr ~= nil) or (count > 100))
ow.reset_search(pin)
end
if(addr == nil) then
return result
end
crc = ow.crc8(string.sub(addr,1,7))
if (crc == addr:byte(8)) then
if ((addr:byte(1) == 0x10) or (addr:byte(1) == 0x28)) then
-- print("Device is a DS18S20 family device.")
ow.reset(pin)
ow.select(pin, addr)
ow.write(pin, 0x44, 1)
-- tmr.delay(1000000)
present = ow.reset(pin)
ow.select(pin, addr)
ow.write(pin,0xBE,1)
-- print("P="..present)
data = nil
data = string.char(ow.read(pin))
for i = 1, 8 do
data = data .. string.char(ow.read(pin))
end
-- print(data:byte(1,9))
crc = ow.crc8(string.sub(data,1,8))
-- print("CRC="..crc)
if (crc == data:byte(9)) then
if(unit == nil or unit == C) then
t = (data:byte(1) + data:byte(2) * 256) * 625
elseif(unit == F) then
t = (data:byte(1) + data:byte(2) * 256) * 1125 + 320000
elseif(unit == K) then
t = (data:byte(1) + data:byte(2) * 256) * 625 + 2731500
else
return nil
end
t1 = t / 10000
t2 = t % 10000
-- print("Temperature="..t1.."."..t2.." Centigrade")
-- result = t1.."."..t2
return t1, t2
end
tmr.wdclr()
else
-- print("Device family is not recognized.")
end
else
-- print("CRC is not valid!")
end
return result
end
function read(addr, unit)
t1, t2 = readNumber(addr, unit)
if((t1 == nil ) or (t2 ==nil)) then
return nil
else
return t1.."."..string.format("%04u", t2)
end
end
-- Return module table
return M
|
--------------------------------------------------------------------------------
-- DS18B20 one wire module for NODEMCU
-- NODEMCU TEAM
-- LICENCE: http://opensource.org/licenses/MIT
-- Vowstar <vowstar@nodemcu.com>
--------------------------------------------------------------------------------
-- Set module name as parameter of require
local modname = ...
local M = {}
_G[modname] = M
--------------------------------------------------------------------------------
-- Local used variables
--------------------------------------------------------------------------------
-- DS18B20 dq pin
local pin = nil
-- DS18B20 default pin
local defaultPin = 9
--------------------------------------------------------------------------------
-- Local used modules
--------------------------------------------------------------------------------
-- Table module
local table = table
-- String module
local string = string
-- One wire module
local ow = ow
-- Timer module
local tmr = tmr
-- Limited to local environment
setfenv(1,M)
--------------------------------------------------------------------------------
-- Implementation
--------------------------------------------------------------------------------
C = 0
F = 1
K = 2
function setup(dq)
pin = dq
if(pin == nil) then
pin = defaultPin
end
ow.setup(pin)
end
function addrs()
setup(pin)
tbl = {}
ow.reset_search(pin)
repeat
addr = ow.search(pin)
if(addr ~= nil) then
table.insert(tbl, addr)
end
tmr.wdclr()
until (addr == nil)
ow.reset_search(pin)
return tbl
end
function readNumber(addr, unit)
result = nil
setup(pin)
flag = false
if(addr == nil) then
ow.reset_search(pin)
count = 0
repeat
count = count + 1
addr = ow.search(pin)
tmr.wdclr()
until((addr ~= nil) or (count > 100))
ow.reset_search(pin)
end
if(addr == nil) then
return result
end
crc = ow.crc8(string.sub(addr,1,7))
if (crc == addr:byte(8)) then
if ((addr:byte(1) == 0x10) or (addr:byte(1) == 0x28)) then
-- print("Device is a DS18S20 family device.")
ow.reset(pin)
ow.select(pin, addr)
ow.write(pin, 0x44, 1)
-- tmr.delay(1000000)
present = ow.reset(pin)
ow.select(pin, addr)
ow.write(pin,0xBE,1)
-- print("P="..present)
data = nil
data = string.char(ow.read(pin))
for i = 1, 8 do
data = data .. string.char(ow.read(pin))
end
-- print(data:byte(1,9))
crc = ow.crc8(string.sub(data,1,8))
-- print("CRC="..crc)
if (crc == data:byte(9)) then
if(unit == nil or unit == C) then
t = (data:byte(1) + data:byte(2) * 256) * 625
elseif(unit == F) then
t = (data:byte(1) + data:byte(2) * 256) * 1125 + 320000
elseif(unit == K) then
t = (data:byte(1) + data:byte(2) * 256) * 625 + 2731500
else
return nil
end
t = t / 10000
-- print("Temperature="..t1.."."..t2.." Centigrade")
-- result = t1.."."..t2
return t
end
tmr.wdclr()
else
-- print("Device family is not recognized.")
end
else
-- print("CRC is not valid!")
end
return result
end
function read(addr, unit)
t = readNumber(addr, unit)
if (t == nil) then
return nil
else
return t
end
end
-- Return module table
return M
|
Fixed DS18B20 handling because of new floating point handling
|
Fixed DS18B20 handling because of new floating point handling
Hi,
because of the new floating point API, the old ds18b20 code returns strange values like "19.8250.8250".
This change fixes that.
Best regards,
Tobias
|
Lua
|
mit
|
natetrue/nodemcu-firmware,dan-cleinmark/nodemcu-firmware,fetchbot/nodemcu-firmware,petrkr/nodemcu-firmware,borromeotlhs/nodemcu-firmware,bhrt/nodeMCU,comitservice/nodmcu,anusornc/nodemcu-firmware,Dejvino/nodemcu-firmware,jmattsson/nodemcu-firmware,GeorgeHahn/nodemcu-firmware,shangwudong/MyNodeMcu,cal101/nodemcu-firmware,anusornc/nodemcu-firmware,funshine/nodemcu-firmware,raburton/nodemcu-firmware,oyooyo/nodemcu-firmware,dnc40085/nodemcu-firmware,digitalloggers/nodemcu-firmware,luizfeliperj/nodemcu-firmware,Alkorin/nodemcu-firmware,vsky279/nodemcu-firmware,luizfeliperj/nodemcu-firmware,benwolfe/nodemcu-firmware,ktosiu/nodemcu-firmware,FrankX0/nodemcu-firmware,borromeotlhs/nodemcu-firmware,xatanais/nodemcu-firmware,ciufciuf57/nodemcu-firmware,HEYAHONG/nodemcu-firmware,ojahan/node-mcu-firmware,AllAboutEE/nodemcu-firmware,noahchense/nodemcu-firmware,ruisebastiao/nodemcu-firmware,FelixPe/nodemcu-firmware,marcelstoer/nodemcu-firmware,funshine/nodemcu-firmware,jmattsson/nodemcu-firmware,Kisaua/nodemcu-firmware,karrots/nodemcu-firmware,dan-cleinmark/nodemcu-firmware,makefu/nodemcu-firmware,ciufciuf57/nodemcu-firmware,Kisaua/nodemcu-firmware,remspoor/nodemcu-firmware,dnc40085/nodemcu-firmware,djphoenix/nodemcu-firmware,jmattsson/nodemcu-firmware,ekapujiw2002/nodemcu-firmware,nodemcu/nodemcu-firmware,yurenyong123/nodemcu-firmware,chadouming/nodemcu-firmware,sowbug/nodemcu-firmware,GeorgeHahn/nodemcu-firmware,eku/nodemcu-firmware,SmartArduino/nodemcu-firmware,flexiti/nodemcu-firmware,shangwudong/MyNodeMcu,dscoolx6/MyESP8266,rowellx68/nodemcu-firmware-custom,romanchyla/nodemcu-firmware,petrkr/nodemcu-firmware,vowstar/nodemcu-firmware,benwolfe/nodemcu-firmware,Audumla/audiot-nodemcu-firmware,fetchbot/nodemcu-firmware,luizfeliperj/nodemcu-firmware,christakahashi/nodemcu-firmware,ekapujiw2002/nodemcu-firmware,londry/nodemcu-firmware,iotcafe/nodemcu-firmware,Audumla/audiot-nodemcu-firmware,cal101/nodemcu-firmware,rickvanbodegraven/nodemcu-firmware,danronco/nodemcu-firmware,londry/nodemcu-firmware,zhujunsan/nodemcu-firmware,devsaurus/nodemcu-firmware,Alkorin/nodemcu-firmware,ruisebastiao/nodemcu-firmware,funshine/nodemcu-firmware,iotcafe/nodemcu-firmware,weera00/nodemcu-firmware,djphoenix/nodemcu-firmware,robertfoss/nodemcu-firmware,Audumla/audiot-nodemcu-firmware,klukonin/nodemcu-firmware,weera00/nodemcu-firmware,FrankX0/nodemcu-firmware,nwf/nodemcu-firmware,Andrew-Collins/nodemcu-firmware,bogvak/nodemcu-firmware,jrahlf/nodemcu-firmware,chadouming/nodemcu-firmware,kbeckmann/nodemcu-firmware,nodemcu/nodemcu-firmware,yurenyong123/nodemcu-firmware,noahchense/nodemcu-firmware,nodemcu/nodemcu-firmware,ruisebastiao/nodemcu-firmware,sowbug/nodemcu-firmware,cal101/nodemcu-firmware,HEYAHONG/nodemcu-firmware,creationix/nodemcu-firmware,daned33/nodemcu-firmware,shangwudong/MyNodeMcu,karrots/nodemcu-firmware,comitservice/nodmcu,nwf/nodemcu-firmware,TerryE/nodemcu-firmware,karrots/nodemcu-firmware,remspoor/nodemcu-firmware,HEYAHONG/nodemcu-firmware,nodemcu/nodemcu-firmware,cs8425/nodemcu-firmware,kbeckmann/nodemcu-firmware,devsaurus/nodemcu-firmware,orlando3d/nodemcu-firmware,marktsai0316/nodemcu-firmware,vsky279/nodemcu-firmware,digitalloggers/nodemcu-firmware,oyooyo/nodemcu-firmware,filug/nodemcu-firmware,devsaurus/nodemcu-firmware,mikeller/nodemcu-firmware,rickvanbodegraven/nodemcu-firmware,jmattsson/nodemcu-firmware,vsky279/nodemcu-firmware,ciufciuf57/nodemcu-firmware,anusornc/nodemcu-firmware,zerog2k/nodemcu-firmware,fetchbot/nodemcu-firmware,romanchyla/nodemcu-firmware,remspoor/nodemcu-firmware,robertfoss/nodemcu-firmware,makefu/nodemcu-firmware,marcelstoer/nodemcu-firmware,rowellx68/nodemcu-firmware-custom,eku/nodemcu-firmware,petrkr/nodemcu-firmware,eku/nodemcu-firmware,zerog2k/nodemcu-firmware,sowbug/nodemcu-firmware,raburton/nodemcu-firmware,daned33/nodemcu-firmware,mikeller/nodemcu-firmware,zerog2k/nodemcu-firmware,klukonin/nodemcu-firmware,ktosiu/nodemcu-firmware,kbeckmann/nodemcu-firmware,londry/nodemcu-firmware,marktsai0316/nodemcu-firmware,nodemcu/nodemcu-firmware,cs8425/nodemcu-firmware,FrankX0/nodemcu-firmware,abgoyal/nodemcu-firmware,natetrue/nodemcu-firmware,TerryE/nodemcu-firmware,marcelstoer/nodemcu-firmware,karrots/nodemcu-firmware,bhrt/nodeMCU,FrankX0/nodemcu-firmware,weera00/nodemcu-firmware,bhrt/nodeMCU,karrots/nodemcu-firmware,bogvak/nodemcu-firmware,cs8425/nodemcu-firmware,natetrue/nodemcu-firmware,danronco/nodemcu-firmware,orlando3d/nodemcu-firmware,rowellx68/nodemcu-firmware-custom,remspoor/nodemcu-firmware,vsky279/nodemcu-firmware,shangwudong/MyNodeMcu,orlando3d/nodemcu-firmware,radiojam11/nodemcu-firmware,dan-cleinmark/nodemcu-firmware,flexiti/nodemcu-firmware,dscoolx6/MyESP8266,chadouming/nodemcu-firmware,funshine/nodemcu-firmware,djphoenix/nodemcu-firmware,dscoolx6/MyESP8266,abgoyal/nodemcu-firmware,Andrew-Collins/nodemcu-firmware,digitalloggers/nodemcu-firmware,raburton/nodemcu-firmware,TerryE/nodemcu-firmware,funshine/nodemcu-firmware,FrankX0/nodemcu-firmware,HEYAHONG/nodemcu-firmware,ojahan/node-mcu-firmware,dnc40085/nodemcu-firmware,petrkr/nodemcu-firmware,kbeckmann/nodemcu-firmware,kbeckmann/nodemcu-firmware,shangwudong/MyNodeMcu,iotcafe/nodemcu-firmware-lua5.3.0,remspoor/nodemcu-firmware,zhujunsan/nodemcu-firmware,oyooyo/nodemcu-firmware,danronco/nodemcu-firmware,oyooyo/nodemcu-firmware,rickvanbodegraven/nodemcu-firmware,HEYAHONG/nodemcu-firmware,Kisaua/nodemcu-firmware,bhrt/nodeMCU,TerryE/nodemcu-firmware,AllAboutEE/nodemcu-firmware,romanchyla/nodemcu-firmware,nwf/nodemcu-firmware,bhrt/nodeMCU,klukonin/nodemcu-firmware,borromeotlhs/nodemcu-firmware,Andrew-Collins/nodemcu-firmware,FelixPe/nodemcu-firmware,TerryE/nodemcu-firmware,daned33/nodemcu-firmware,xatanais/nodemcu-firmware,ktosiu/nodemcu-firmware,filug/nodemcu-firmware,FelixPe/nodemcu-firmware,djphoenix/nodemcu-firmware,yurenyong123/nodemcu-firmware,radiojam11/nodemcu-firmware,AllAboutEE/nodemcu-firmware,dnc40085/nodemcu-firmware,FelixPe/nodemcu-firmware,vowstar/nodemcu-firmware,devsaurus/nodemcu-firmware,christakahashi/nodemcu-firmware,Alkorin/nodemcu-firmware,devsaurus/nodemcu-firmware,radiojam11/nodemcu-firmware,benwolfe/nodemcu-firmware,christakahashi/nodemcu-firmware,vsky279/nodemcu-firmware,iotcafe/nodemcu-firmware-lua5.3.0,xatanais/nodemcu-firmware,marcelstoer/nodemcu-firmware,luizfeliperj/nodemcu-firmware,creationix/nodemcu-firmware,dnc40085/nodemcu-firmware,creationix/nodemcu-firmware,Alkorin/nodemcu-firmware,robertfoss/nodemcu-firmware,nwf/nodemcu-firmware,eku/nodemcu-firmware,iotcafe/nodemcu-firmware,vowstar/nodemcu-firmware,zhujunsan/nodemcu-firmware,FelixPe/nodemcu-firmware,mikeller/nodemcu-firmware,jmattsson/nodemcu-firmware,ojahan/node-mcu-firmware,nwf/nodemcu-firmware,Alkorin/nodemcu-firmware,jrahlf/nodemcu-firmware,fetchbot/nodemcu-firmware,abgoyal/nodemcu-firmware,flexiti/nodemcu-firmware,marcelstoer/nodemcu-firmware,noahchense/nodemcu-firmware,makefu/nodemcu-firmware,christakahashi/nodemcu-firmware,christakahashi/nodemcu-firmware,filug/nodemcu-firmware,chadouming/nodemcu-firmware,SmartArduino/nodemcu-firmware,SmartArduino/nodemcu-firmware,bogvak/nodemcu-firmware,marktsai0316/nodemcu-firmware,petrkr/nodemcu-firmware,Dejvino/nodemcu-firmware
|
49ccd1b6efc7b274fd9d0c7f9e009deb1524d678
|
nvim/nvim/lua/_/treesitter.lua
|
nvim/nvim/lua/_/treesitter.lua
|
local has_config, ts_configs = pcall(require, 'nvim-treesitter.configs')
local has_context, ts_context = pcall(require, 'treesitter-context')
local M = {}
local function setup_ts_config()
ts_configs.setup {
ensure_installed={
'bash',
'c',
'cmake',
'comment',
'commonlisp',
'cpp',
'css',
'dockerfile',
'fennel',
'fish',
'go',
'gomod',
'haskell',
'help',
'hjson',
'html',
'http',
'javascript',
'jsdoc',
'json',
'json5',
'llvm',
'lua',
'make',
'markdown',
'ninja',
'nix',
'org',
'python',
'regex',
'rst',
'rust',
'scss',
'toml',
'tsx',
'typescript',
'vim',
'yaml',
'norg'
},
highlight={enable=true},
indent={enable=true},
incremental_selection={
enable=true,
keymaps={
init_selection='gnn',
node_incremental='grn',
scope_incremental='grc',
node_decremental='grm'
}
},
refactor={
smart_rename={enable=true, keymaps={smart_rename='grr'}},
highlight_definitions={enable=true, clear_on_cursor_move=true},
highlight_current_scope={enable=true}
},
rainbow={enable=true, extended_mode=true},
textobjects={
select={
enable=true,
keymaps={
['af']='@function.outer',
['if']='@function.inner',
['aC']='@class.outer',
['iC']='@class.inner',
['ac']='@conditional.outer',
['ic']='@conditional.inner',
['ae']='@block.outer',
['ie']='@block.inner',
['al']='@loop.outer',
['il']='@loop.inner',
['is']='@statement.inner',
['as']='@statement.outer',
['ad']='@comment.outer',
['am']='@call.outer',
['im']='@call.inner'
}
},
move={
enable=true,
set_jumps=true, -- whether to set jumps in the jumplist
goto_next_start={[']m']='@function.outer', [']]']='@class.outer'},
goto_next_end={[']M']='@function.outer', ['][']='@class.outer'},
goto_previous_start={['[m']='@function.outer', ['[[']='@class.outer'},
goto_previous_end={['[M']='@function.outer', ['[]']='@class.outer'}
}
}
}
vim.api.nvim_command('set foldmethod=expr');
vim.api.nvim_command('set foldexpr=nvim_treesitter#foldexpr()');
end
local function setup_context()
ts_context.setup({
enable=true, -- Enable this plugin (Can be enabled/disabled later via commands)
max_lines=0, -- How many lines the window should span. Values <= 0 mean no limit.
patterns={ -- Match patterns for TS nodes. These get wrapped to match at word boundaries.
-- For all filetypes
-- Note that setting an entry here replaces all other patterns for this entry.
-- By setting the 'default' entry below, you can control which nodes you want to
-- appear in the context window.
default={
'class',
'function',
'method'
-- 'for', -- These won't appear in the context
-- 'while',
-- 'if',
-- 'switch',
-- 'case',
}
-- Example for a specific filetype.
-- If a pattern is missing, *open a PR* so everyone can benefit.
-- rust = {
-- 'impl_item',
-- },
},
exact_patterns={
-- Example for a specific filetype with Lua patterns
-- Treat patterns.rust as a Lua pattern (i.e "^impl_item$" will
-- exactly match "impl_item" only)
-- rust = true,
},
-- [!] The options below are exposed but shouldn't require your attention,
-- you can safely ignore them.
zindex=20 -- The Z-index of the context window
})
end
function M.setup()
if not has_config then return end
setup_ts_config()
if not has_context then return end
setup_context()
end
return M
|
local has_config, ts_configs = pcall(require, 'nvim-treesitter.configs')
local has_context, ts_context = pcall(require, 'treesitter-context')
local M = {}
local function setup_ts_config()
ts_configs.setup {
ensure_installed={
'bash',
'c',
'cmake',
'comment',
'commonlisp',
'cpp',
'css',
'dockerfile',
'fennel',
'fish',
'go',
'gomod',
'haskell',
'help',
'hjson',
'html',
'http',
'javascript',
'jsdoc',
'json',
'json5',
'llvm',
'lua',
'make',
'markdown',
'ninja',
'nix',
'org',
'python',
'regex',
'rst',
'rust',
'scss',
'toml',
'tsx',
'typescript',
'vim',
'yaml',
'norg'
},
highlight={enable=true},
indent={enable=true},
incremental_selection={
enable=true,
keymaps={
init_selection='gnn',
node_incremental='grn',
scope_incremental='grc',
node_decremental='grm'
}
},
refactor={
smart_rename={enable=true, keymaps={smart_rename='grr'}},
highlight_definitions={enable=true, clear_on_cursor_move=true},
highlight_current_scope={enable=false}
},
rainbow={enable=true, extended_mode=true},
textobjects={
select={
enable=true,
keymaps={
['af']='@function.outer',
['if']='@function.inner',
['aC']='@class.outer',
['iC']='@class.inner',
['ac']='@conditional.outer',
['ic']='@conditional.inner',
['ae']='@block.outer',
['ie']='@block.inner',
['al']='@loop.outer',
['il']='@loop.inner',
['is']='@statement.inner',
['as']='@statement.outer',
['ad']='@comment.outer',
['am']='@call.outer',
['im']='@call.inner'
}
},
move={
enable=true,
set_jumps=true, -- whether to set jumps in the jumplist
goto_next_start={[']m']='@function.outer', [']]']='@class.outer'},
goto_next_end={[']M']='@function.outer', ['][']='@class.outer'},
goto_previous_start={['[m']='@function.outer', ['[[']='@class.outer'},
goto_previous_end={['[M']='@function.outer', ['[]']='@class.outer'}
}
}
}
end
local function setup_context()
ts_context.setup({
enable=true, -- Enable this plugin (Can be enabled/disabled later via commands)
max_lines=0, -- How many lines the window should span. Values <= 0 mean no limit.
patterns={ -- Match patterns for TS nodes. These get wrapped to match at word boundaries.
-- For all filetypes
-- Note that setting an entry here replaces all other patterns for this entry.
-- By setting the 'default' entry below, you can control which nodes you want to
-- appear in the context window.
default={
'class',
'function',
'method'
-- 'for', -- These won't appear in the context
-- 'while',
-- 'if',
-- 'switch',
-- 'case',
}
-- Example for a specific filetype.
-- If a pattern is missing, *open a PR* so everyone can benefit.
-- rust = {
-- 'impl_item',
-- },
},
exact_patterns={
-- Example for a specific filetype with Lua patterns
-- Treat patterns.rust as a Lua pattern (i.e "^impl_item$" will
-- exactly match "impl_item" only)
-- rust = true,
},
-- [!] The options below are exposed but shouldn't require your attention,
-- you can safely ignore them.
zindex=20 -- The Z-index of the context window
})
end
function M.setup()
if not has_config then return end
setup_ts_config()
if not has_context then return end
setup_context()
end
return M
|
fix(nvim): fold and highlight_current_scope
|
fix(nvim): fold and highlight_current_scope
|
Lua
|
mit
|
skyuplam/dotfiles,skyuplam/dotfiles
|
8114c5b7f8ebaa7492f087555dd1f0476e10da63
|
asyncoperations.lua
|
asyncoperations.lua
|
local table = table
module "irc"
local meta = _META
function meta:send(fmt, ...)
local bytes, err = self.socket:send(fmt:format(...) .. "\r\n")
if bytes then
return
end
if err ~= "timeout" and err ~= "wantwrite" then
self:invoke("OnDisconnect", err, true)
self:shutdown()
error(err, errlevel)
end
end
local function clean(str)
return str:gsub("[\r\n:]", "")
end
function meta:sendChat(target, msg)
self:send("PRIVMSG %s :%s", clean(target), clean(msg))
end
function meta:sendNotice(target, msg)
self:send("NOTICE %s :%s", clean(target), clean(msg))
end
function meta:join(channel, key)
if key then
self:send("JOIN %s :%s", clean(channel), clean(key))
else
self:send("JOIN %s", clean(channel))
end
end
function meta:part(channel)
channel = clean(channel)
self:send("PART %s", channel)
if self.track_users then
self.channels[channel] = nil
end
end
function meta:trackUsers(b)
self.track_users = b
if not b then
for k,v in pairs(self.channels) do
self.channels[k] = nil
end
end
end
function meta:setMode(t)
local target = t.target or self.nick
local mode = ""
local add, rem = t.add, t.remove
assert(add or rem, "table contains neither 'add' nor 'remove'")
if add then
mode = table.concat{"+", add}
end
if rem then
mode = table.concat{mode, "-", rem}
end
self:send("MODE %s %s", clean(target), clean(mode))
end
|
local table = table
module "irc"
local meta = _META
function meta:send(fmt, ...)
local bytes, err = self.socket:send(fmt:format(...) .. "\r\n")
if bytes then
return
end
if err ~= "timeout" and err ~= "wantwrite" then
self:invoke("OnDisconnect", err, true)
self:shutdown()
error(err, errlevel)
end
end
local function clean(str)
return str:gsub("[\r\n:]", "")
end
function meta:sendChat(target, msg)
-- Split the message into segments if it includes newlines.
for line in msg:gmatch("([^\r\n]+)")
self:send("PRIVMSG %s :%s", clean(target), msg)
end
end
function meta:sendNotice(target, msg)
-- Split the message into segments if it includes newlines.
for line in msg:gmatch("([^\r\n]+)")
self:send("NOTICE %s :%s", clean(target), msg)
end
end
function meta:join(channel, key)
if key then
self:send("JOIN %s :%s", clean(channel), clean(key))
else
self:send("JOIN %s", clean(channel))
end
end
function meta:part(channel)
channel = clean(channel)
self:send("PART %s", channel)
if self.track_users then
self.channels[channel] = nil
end
end
function meta:trackUsers(b)
self.track_users = b
if not b then
for k,v in pairs(self.channels) do
self.channels[k] = nil
end
end
end
function meta:setMode(t)
local target = t.target or self.nick
local mode = ""
local add, rem = t.add, t.remove
assert(add or rem, "table contains neither 'add' nor 'remove'")
if add then
mode = table.concat{"+", add}
end
if rem then
mode = table.concat{mode, "-", rem}
end
self:send("MODE %s %s", clean(target), clean(mode))
end
|
Fixing regressions in sendChat and sendNotice.
|
Fixing regressions in sendChat and sendNotice.
Fixing: Incorrect handling of newlines in message.
Fixing: Cleaning ':' from message.
|
Lua
|
mit
|
JakobOvrum/LuaIRC,wolfy1339/LuaIRC
|
edfa13f29a5005343f6a625937ecf2ef35e57719
|
Mjolnir/setup.lua
|
Mjolnir/setup.lua
|
os.exit = core.exit
function core.runstring(s)
local fn, err = load("return " .. s)
if not fn then fn, err = load(s) end
if not fn then return tostring(err) end
local str = ""
local results = table.pack(pcall(fn))
for i = 2,results.n do
if i > 2 then str = str .. "\t" end
str = str .. tostring(results[i])
end
return str
end
function core._load(dotname)
local requirepath = 'ext.' .. dotname:gsub('%.', '_') .. '.init'
local ok, result = pcall(require, requirepath)
if not ok then
print("Something went wrong: " .. result)
return
end
local mod = result
local keys = {}
for key in string.gmatch(dotname, "%a+") do
table.insert(keys, key)
end
local t = _G[keys[1]]
table.remove(keys, 1)
local lastkey = keys[#keys]
keys[#keys] = nil
for _, k in ipairs(keys) do
local intermediate = t[k]
if intermediate == nil then
intermediate = {}
t[k] = intermediate
end
t = intermediate
end
t[lastkey] = mod
end
function _corelerrorhandler(err)
return core.errorhandler(err)
end
function core.errorhandler(err)
core._notify("Mjolnir error occurred")
print(err)
print(debug.traceback())
return err
end
function core.pcall(f, ...)
return xpcall(f, core.errorhandler, ...)
end
function core._unload(dotname)
local fn = load(dotname.." = nil")
fn() -- this is cheating, I know; oh well
core.resetters[dotname] = nil
package.loaded[dotname] = nil
end
local rawprint = print
function print(...)
rawprint(...)
local vals = table.pack(...)
for k = 1, vals.n do
vals[k] = tostring(vals[k])
end
-- using table.concat here is safe, because we just stringified all the values
local str = table.concat(vals, "\t") .. "\n"
core._logmessage(str)
end
--- core.resetters = {}
--- If extensions need to reset any state when the user's config reloads, they must add a resetter function here.
--- i.e. core.hotkey's init.lua file should run `core.resetters["core.hotkey"] = function() ... end` at some point.
core.resetters = {}
local function resetstate()
for _, fn in pairs(core.resetters) do
fn()
end
end
--- core.reload()
--- Reloads your init-file. Clears any state from extensions, i.e. disables all hotkeys, etc.
function core.reload()
local fn, err = loadfile "init.lua"
if fn then
resetstate()
core.pcall(fn)
elseif err:find "No such file or directory" then
print "-- Cannot find ~/.mjolnir/init.lua; skipping."
else
print(tostring(err))
core._notify("Syntax error in ~/.mjolnir/init.lua")
end
end
|
os.exit = core.exit
function core.runstring(s)
local fn, err = load("return " .. s)
if not fn then fn, err = load(s) end
if not fn then return tostring(err) end
local str = ""
local results = table.pack(pcall(fn))
for i = 2,results.n do
if i > 2 then str = str .. "\t" end
str = str .. tostring(results[i])
end
return str
end
function core._load(dotname)
local requirepath = 'ext.' .. dotname:gsub('%.', '_') .. '.init'
local ok, result = pcall(require, requirepath)
if not ok then
print("Something went wrong: " .. result)
return
end
local mod = result
local keys = {}
for key in string.gmatch(dotname, "%a+") do
table.insert(keys, key)
end
local t = _G[keys[1]]
table.remove(keys, 1)
local lastkey = keys[#keys]
keys[#keys] = nil
for _, k in ipairs(keys) do
local intermediate = t[k]
if intermediate == nil then
intermediate = {}
t[k] = intermediate
end
t = intermediate
end
t[lastkey] = mod
end
function _corelerrorhandler(err)
return core.errorhandler(err)
end
function core.errorhandler(err)
core._notify("Mjolnir error occurred")
print(err)
print(debug.traceback())
return err
end
function core.pcall(f, ...)
return xpcall(f, core.errorhandler, ...)
end
function core._unload(dotname)
local fn = load(dotname.." = nil")
fn() -- this is cheating, I know; oh well
core.resetters[dotname] = nil
package.loaded[dotname] = nil
end
local rawprint = print
function print(...)
rawprint(...)
local vals = table.pack(...)
for k = 1, vals.n do
vals[k] = tostring(vals[k])
end
-- using table.concat here is safe, because we just stringified all the values
local str = table.concat(vals, "\t") .. "\n"
core._logmessage(str)
end
--- core.resetters = {}
--- If extensions need to reset any state when the user's config reloads, they must add a resetter function here.
--- i.e. core.hotkey's init.lua file should run `core.resetters["core.hotkey"] = function() ... end` at some point.
core.resetters = {}
local function resetstate()
for _, fn in pairs(core.resetters) do
fn()
end
end
--- core.reload()
--- Reloads your init-file. Clears any state from extensions, i.e. disables all hotkeys, etc.
function core.reload()
local fn, err = loadfile "init.lua"
if fn then
resetstate()
if core.pcall(fn) then
print "-- Ran ~/.mjolnir/init.lua; success."
end
elseif err:find "No such file or directory" then
print "-- Cannot find ~/.mjolnir/init.lua; skipping."
else
print(tostring(err))
core._notify("Syntax error in ~/.mjolnir/init.lua")
end
end
|
Prints something when the config is successfully reloaded; fixes #430.
|
Prints something when the config is successfully reloaded; fixes #430.
|
Lua
|
mit
|
kkamdooong/hammerspoon,kkamdooong/hammerspoon,ocurr/hammerspoon,Stimim/hammerspoon,bradparks/hammerspoon,asmagill/hammerspoon,Hammerspoon/hammerspoon,hypebeast/hammerspoon,peterhajas/hammerspoon,kkamdooong/hammerspoon,asmagill/hammerspoon,knu/hammerspoon,bradparks/hammerspoon,wsmith323/hammerspoon,wsmith323/hammerspoon,zzamboni/hammerspoon,knu/hammerspoon,nkgm/hammerspoon,dopcn/hammerspoon,cmsj/hammerspoon,wvierber/hammerspoon,heptal/hammerspoon,ocurr/hammerspoon,wsmith323/hammerspoon,dopcn/hammerspoon,zzamboni/hammerspoon,Hammerspoon/hammerspoon,hypebeast/hammerspoon,dopcn/hammerspoon,wvierber/hammerspoon,latenitefilms/hammerspoon,cmsj/hammerspoon,knu/hammerspoon,hypebeast/hammerspoon,trishume/hammerspoon,Stimim/hammerspoon,Habbie/hammerspoon,ocurr/hammerspoon,kkamdooong/hammerspoon,TimVonsee/hammerspoon,bradparks/hammerspoon,ocurr/hammerspoon,CommandPost/CommandPost-App,lowne/hammerspoon,knu/hammerspoon,chrisjbray/hammerspoon,joehanchoi/hammerspoon,nkgm/hammerspoon,chrisjbray/hammerspoon,junkblocker/hammerspoon,wvierber/hammerspoon,tmandry/hammerspoon,latenitefilms/hammerspoon,knl/hammerspoon,emoses/hammerspoon,Hammerspoon/hammerspoon,Hammerspoon/hammerspoon,wvierber/hammerspoon,nkgm/hammerspoon,chrisjbray/hammerspoon,latenitefilms/hammerspoon,joehanchoi/hammerspoon,heptal/hammerspoon,knl/hammerspoon,peterhajas/hammerspoon,cmsj/hammerspoon,zzamboni/hammerspoon,lowne/hammerspoon,zzamboni/hammerspoon,Habbie/hammerspoon,peterhajas/hammerspoon,TimVonsee/hammerspoon,bradparks/hammerspoon,asmagill/hammerspoon,asmagill/hammerspoon,CommandPost/CommandPost-App,asmagill/hammerspoon,hypebeast/hammerspoon,wsmith323/hammerspoon,asmagill/hammerspoon,Hammerspoon/hammerspoon,CommandPost/CommandPost-App,tmandry/hammerspoon,Stimim/hammerspoon,bradparks/hammerspoon,CommandPost/CommandPost-App,emoses/hammerspoon,junkblocker/hammerspoon,joehanchoi/hammerspoon,CommandPost/CommandPost-App,cmsj/hammerspoon,Habbie/hammerspoon,ocurr/hammerspoon,hypebeast/hammerspoon,chrisjbray/hammerspoon,junkblocker/hammerspoon,Habbie/hammerspoon,heptal/hammerspoon,chrisjbray/hammerspoon,TimVonsee/hammerspoon,emoses/hammerspoon,heptal/hammerspoon,cmsj/hammerspoon,joehanchoi/hammerspoon,zzamboni/hammerspoon,tmandry/hammerspoon,peterhajas/hammerspoon,CommandPost/CommandPost-App,dopcn/hammerspoon,junkblocker/hammerspoon,knu/hammerspoon,wvierber/hammerspoon,knl/hammerspoon,latenitefilms/hammerspoon,latenitefilms/hammerspoon,trishume/hammerspoon,knl/hammerspoon,peterhajas/hammerspoon,TimVonsee/hammerspoon,Stimim/hammerspoon,wsmith323/hammerspoon,nkgm/hammerspoon,Habbie/hammerspoon,emoses/hammerspoon,trishume/hammerspoon,heptal/hammerspoon,lowne/hammerspoon,lowne/hammerspoon,zzamboni/hammerspoon,dopcn/hammerspoon,cmsj/hammerspoon,emoses/hammerspoon,Stimim/hammerspoon,latenitefilms/hammerspoon,joehanchoi/hammerspoon,nkgm/hammerspoon,knu/hammerspoon,kkamdooong/hammerspoon,Hammerspoon/hammerspoon,lowne/hammerspoon,chrisjbray/hammerspoon,junkblocker/hammerspoon,TimVonsee/hammerspoon,Habbie/hammerspoon,knl/hammerspoon
|
33334153f5139ab4325d29282ae54ecc6ef091bb
|
OS/DiskOS/api.lua
|
OS/DiskOS/api.lua
|
--Build DiskOS APIs--
_DiskVer = 2 --It's a global
function input()
local t = ""
local fw, fh = fontSize()
local blink = false
local blinktimer = 0
local blinktime = 0.5
local function drawblink()
local cx,cy,c = printCursor()
rect(cx*(fw+1)+1,blink and cy*(fh+2)+1 or cy*(fh+2),fw+1,blink and fh or fh+4,false,blink and 4 or c) --The blink
end
for event,a,b,c,d,e,f in pullEvent do
if event == "textinput" then
t = t .. a
print(a,false)
elseif event == "keypressed" then
if a == "backspace" then
blink = false; drawblink()
if t:len() > 0 then printBackspace() end
blink = true; drawblink()
t = t:sub(0,-2)
elseif a == "return" then
blink = false; drawblink()
return t --Return the text
elseif a == "escape" then
return false --User canceled text input.
end
elseif event == "update" then --Blink
blinktimer = blinktimer + a
if blinktimer > blinktime then
blinktimer = blinktimer - blinktime
blink = not blink
drawblink()
end
end
end
end
function SpriteSheet(img,w,h)
local ss = {img=img,w=w,h=h} --SpriteSheet
ss.cw, ss.ch, ss.quads = ss.img:width()/ss.w, ss.img:height()/ss.h, {}
for y=0, ss.h-1 do for x=0, ss.w-1 do
table.insert(ss.quads,ss.img:quad(x*ss.cw,y*ss.ch,ss.cw,ss.ch))
end end
function ss:image() return self.img end
function ss:data() return self.img:data() end
function ss:quad(id) return self.quads[id] end
function ss:rect(id) return self.quads[id]:getViewport() end
function ss:draw(id,x,y,r,sx,sy) self.img:draw(x,y,r,sx,sy,self.quads[id]) return self end
function ss:extract(id) return imagedata(self.cw,self.ch):paste(self:data(),0,0,self:rect(id)) end
return ss
end
function SpriteGroup(id,x,y,w,h,sx,sy,r,sheet)
local sx,sy = math.floor(sx or 0), math.floor(sy or 0)
if r then
if type(r) ~= "number" then return error("R must be a number, provided: "..type(r)) end
pushMatrix()
cam("translate",x,y)
cam("rotate",r)
x,y = 0,0
end
for spry = 1, h or 1 do for sprx = 1, w or 1 do
sheet:draw((id-1)+sprx+(spry*24-24),x+(sprx*sx*8-sx*8),y+(spry*sy*8-sy*8),0,sx,sy)
end end
if r then
popMatrix()
end
end
function isInRect(x,y,rect)
if x >= rect[1] and y >= rect[2] and x <= rect[1]+rect[3]-1 and y <= rect[2]+rect[4]-1 then return true end return false
end
local debugGrids = false
function whereInGrid(x,y, grid) --Grid X, Grid Y, Grid Width, Grid Height, NumOfCells in width, NumOfCells in height
local gx,gy,gw,gh,cw,ch = unpack(grid)
if isInRect(x,y,{gx,gy,gw,gh}) then
local clw, clh = math.floor(gw/cw), math.floor(gh/ch)
local x, y = x-gx, y-gy
local hx = math.floor(x/clw)+1 hx = hx <= cw and hx or hx-1
local hy = math.floor(y/clh)+1 hy = hy <= ch and hy or hy-1
if debugGrids then
for x=1,cw do for y=1,ch do
rect(gx+(x*clw-clw)-1,gy+(y*clh-clh)-1,clw,clh,true,8)
end end
rect(gx+(hx*clw-clw)-1,gy+(hy*clh-clh)-1,clw,clh,true,7)
end
return hx,hy
end
return false, false
end
--Binary functions--
function imgToBin(image)
if image:typeOf("GPU.image") then image = image:data() end --Convert the image to imagedata.
local bin = ""
local width, height = image:size()
for y=0, height-1 do
for x=0, width-1,2 do
local left = image:getPixel(x,y)
local right = x+1 < width and image:getPixel(x+1,y) or 0
right = bit.lshift(right,4)
local pixel = bit.bor(left,right)
local char = string.char(pixel)
bin = bin..char
end
end
return bin
end
function mapToBin(map)
local bin = ""
map:map(function(x,y,cid)
if cid > 255 then cid = 0 end
local cell = string.char(cid)
bin = bin..cell
return cid
end)
return bin
end
function codeToBin(code)
return math.compress(code,"lz4",9)
end
function numToBin(num,len)
local bin = ""
while true do
local byte = bit.band(num,255)
local char = string.char(byte)
bin = bin..char
num = bit.band(num, bit.bnot(255))
num = bit.rshift(num,8)
if num == 0 then break end
end
if len and bin:len() < len then bin = bin..string.rep(string.char(0), len-bin:len()) end
return bin
end
function binToNum(bin)
local num = 0
for i=bin:len(), 1, -1 do
local char = bin:sub(i,i)
local byte = string.byte(char)
num = bit.lshift(num,8)
num = bit.bor(num,byte)
end
return num
end
|
--Build DiskOS APIs--
_DiskVer = 2 --It's a global
function input()
local t = ""
local fw, fh = fontSize()
local blink = false
local blinktimer = 0
local blinktime = 0.5
local function drawblink()
local cx,cy,c = printCursor()
rect(cx*(fw+1)+1,blink and cy*(fh+2)+1 or cy*(fh+2),fw+1,blink and fh or fh+4,false,blink and 4 or c) --The blink
end
for event,a,b,c,d,e,f in pullEvent do
if event == "textinput" then
t = t .. a
print(a,false)
elseif event == "keypressed" then
if a == "backspace" then
blink = false; drawblink()
if t:len() > 0 then printBackspace() end
blink = true; drawblink()
t = t:sub(0,-2)
elseif a == "return" then
blink = false; drawblink()
return t --Return the text
elseif a == "escape" then
return false --User canceled text input.
end
elseif event == "touchpressed" then
textinput(true)
elseif event == "update" then --Blink
blinktimer = blinktimer + a
if blinktimer > blinktime then
blinktimer = blinktimer - blinktime
blink = not blink
drawblink()
end
end
end
end
function SpriteSheet(img,w,h)
local ss = {img=img,w=w,h=h} --SpriteSheet
ss.cw, ss.ch, ss.quads = ss.img:width()/ss.w, ss.img:height()/ss.h, {}
for y=0, ss.h-1 do for x=0, ss.w-1 do
table.insert(ss.quads,ss.img:quad(x*ss.cw,y*ss.ch,ss.cw,ss.ch))
end end
function ss:image() return self.img end
function ss:data() return self.img:data() end
function ss:quad(id) return self.quads[id] end
function ss:rect(id) return self.quads[id]:getViewport() end
function ss:draw(id,x,y,r,sx,sy) self.img:draw(x,y,r,sx,sy,self.quads[id]) return self end
function ss:extract(id) return imagedata(self.cw,self.ch):paste(self:data(),0,0,self:rect(id)) end
return ss
end
function SpriteGroup(id,x,y,w,h,sx,sy,r,sheet)
local sx,sy = math.floor(sx or 0), math.floor(sy or 0)
if r then
if type(r) ~= "number" then return error("R must be a number, provided: "..type(r)) end
pushMatrix()
cam("translate",x,y)
cam("rotate",r)
x,y = 0,0
end
for spry = 1, h or 1 do for sprx = 1, w or 1 do
sheet:draw((id-1)+sprx+(spry*24-24),x+(sprx*sx*8-sx*8),y+(spry*sy*8-sy*8),0,sx,sy)
end end
if r then
popMatrix()
end
end
function isInRect(x,y,rect)
if x >= rect[1] and y >= rect[2] and x <= rect[1]+rect[3]-1 and y <= rect[2]+rect[4]-1 then return true end return false
end
local debugGrids = false
function whereInGrid(x,y, grid) --Grid X, Grid Y, Grid Width, Grid Height, NumOfCells in width, NumOfCells in height
local gx,gy,gw,gh,cw,ch = unpack(grid)
if isInRect(x,y,{gx,gy,gw,gh}) then
local clw, clh = math.floor(gw/cw), math.floor(gh/ch)
local x, y = x-gx, y-gy
local hx = math.floor(x/clw)+1 hx = hx <= cw and hx or hx-1
local hy = math.floor(y/clh)+1 hy = hy <= ch and hy or hy-1
if debugGrids then
for x=1,cw do for y=1,ch do
rect(gx+(x*clw-clw)-1,gy+(y*clh-clh)-1,clw,clh,true,8)
end end
rect(gx+(hx*clw-clw)-1,gy+(hy*clh-clh)-1,clw,clh,true,7)
end
return hx,hy
end
return false, false
end
--Binary functions--
function imgToBin(image)
if image:typeOf("GPU.image") then image = image:data() end --Convert the image to imagedata.
local bin = ""
local width, height = image:size()
for y=0, height-1 do
for x=0, width-1,2 do
local left = image:getPixel(x,y)
local right = x+1 < width and image:getPixel(x+1,y) or 0
right = bit.lshift(right,4)
local pixel = bit.bor(left,right)
local char = string.char(pixel)
bin = bin..char
end
end
return bin
end
function mapToBin(map)
local bin = ""
map:map(function(x,y,cid)
if cid > 255 then cid = 0 end
local cell = string.char(cid)
bin = bin..cell
return cid
end)
return bin
end
function codeToBin(code)
return math.compress(code,"lz4",9)
end
function numToBin(num,len)
local bin = ""
while true do
local byte = bit.band(num,255)
local char = string.char(byte)
bin = bin..char
num = bit.band(num, bit.bnot(255))
num = bit.rshift(num,8)
if num == 0 then break end
end
if len and bin:len() < len then bin = bin..string.rep(string.char(0), len-bin:len()) end
return bin
end
function binToNum(bin)
local num = 0
for i=bin:len(), 1, -1 do
local char = bin:sub(i,i)
local byte = string.byte(char)
num = bit.lshift(num,8)
num = bit.bor(num,byte)
end
return num
end
|
Bugfix for android
|
Bugfix for android
|
Lua
|
mit
|
RamiLego4Game/LIKO-12
|
321ae1059b3dc4e121cca1a1f5881ac7bed827aa
|
UCDaviator/server.lua
|
UCDaviator/server.lua
|
--[[
-- Distances
LS --> LV = 4000
LS --> VM = 5000
LS --> SF = 3500
LV --> SF = 3300
LV --> VM = 1500
SF --> VM = 3000
--]]
local sml = {[511] = true, [593] = true, [513] = true} -- Beagle, Dodo, Stuntplane
local lrg = {[592] = true, [577] = true, [553] = true} -- Nevada, AT-400, Andromada
local mid = {[519] = true} -- Shamal
addEventHandler("onResourceStart", resourceRoot,
function ()
ranks = exports.UCDjobsTable:getJobRanks("Aviator")
end
)
function processFlight(flightData, vehicle)
if (client and flightData and vehicle) then
local model = vehicle.model
local playerRank = exports.UCDjobs:getPlayerJobRank(client, "Aviator") or 0
local base, bonus, distance
local start, finish
if (vehicle.vehicleType == "Plane") then
start = destinations["Plane"][airports[flightData[3]]][flightData[4]]
finish = destinations["Plane"][airports[flightData[1]]][flightData[2]]
local x1, y1, z1 = start[1], start[2], start[3]
local x2, y2, z2 = finish[1], finish[2], finish[3]
distance = getDistanceBetweenPoints3D(x1, y1, z1, x2, y2, z2)
--outputDebugString("Distance: "..distance)
if (sml[model]) then
base = math.random((distance * 1.15) - 250, (distance * 1.15) + 250)
elseif (lrg[model]) then
base = math.random((distance * 2.5) - 250, (distance * 2.5) + 250)
elseif (mid[model]) then
base = math.random((distance * 1.6) - 250, (distance * 1.75) + 400)
else
outputDebugString("Unknown type given")
return
end
else
start = destinations["Helicopter"][flightData[1]]
finish = destinations["Helicopter"][flightData[2]]
local x1, y1, z1 = start[1], start[2], start[3]
local x2, y2, z2 = finish[1], finish[2], finish[3]
distance = getDistanceBetweenPoints3D(x1, y1, z1, x2, y2, z2)
--outputDebugString("Distance: "..distance)
-- You should earn slightly more with a helicopter
base = math.random(distance * 1.5, (distance * 1.5) + 350)
end
bonus = ranks[playerRank].bonus
local newAmount = math.floor((base * (bonus / 100)) + base)
local formattedAmount = exports.UCDutil:tocomma(newAmount)
outputDebugString("Base = "..base)
outputDebugString("Bonus = "..bonus.."%")
outputDebugString("New amount = "..newAmount)
if (vehicle.vehicleType == "Plane") then
local fA = airports[flightData[1]]
local sA = airports[flightData[3]]
exports.UCDdx:new(client, "ATC: Flight from "..sA.." to "..fA.." complete ("..tostring(exports.UCDutil:mathround(distance / 1000, 2)).." km). You have been paid $"..formattedAmount..".", 255, 215, 0)
else
exports.UCDdx:new(client, "ATC: Flight complete ("..tostring(exports.UCDutil:mathround(distance / 1000, 2)).."km). You have been paid $"..formattedAmount..".", 255, 215, 0)
end
exports.UCDaccounts:SAD(client.account.name, "aviator", exports.UCDaccounts:GAD(client.account.name, "aviator") + distance)
if (client.vehicle) then
--client.vehicle.frozen = false
triggerClientEvent(client, "UCDaviator.startItinerary", client, client.vehicle, client.vehicleSeat)
end
end
end
addEvent("UCDaviator.processFlight", true)
addEventHandler("UCDaviator.processFlight", root, processFlight)
|
--[[
-- Distances
LS --> LV = 4000
LS --> VM = 5000
LS --> SF = 3500
LV --> SF = 3300
LV --> VM = 1500
SF --> VM = 3000
--]]
local sml = {[511] = true, [593] = true, [513] = true} -- Beagle, Dodo, Stuntplane
local lrg = {[592] = true, [577] = true, [553] = true} -- Nevada, AT-400, Andromada
local mid = {[519] = true} -- Shamal
addEventHandler("onResourceStart", resourceRoot,
function ()
ranks = exports.UCDjobsTable:getJobRanks("Aviator")
end
)
function processFlight(flightData, vehicle)
if (client and flightData and vehicle) then
local model = vehicle.model
local playerRank = exports.UCDjobs:getPlayerJobRank(client, "Aviator") or 0
local base, bonus, distance
local start, finish
if (vehicle.vehicleType == "Plane") then
start = destinations["Plane"][airports[flightData[3]]][flightData[4]]
finish = destinations["Plane"][airports[flightData[1]]][flightData[2]]
local x1, y1, z1 = start[1], start[2], start[3]
local x2, y2, z2 = finish[1], finish[2], finish[3]
distance = getDistanceBetweenPoints3D(x1, y1, z1, x2, y2, z2)
--outputDebugString("Distance: "..distance)
if (sml[model]) then
base = math.random((distance * 1.15) - 250, (distance * 1.15) + 250)
elseif (lrg[model]) then
base = math.random((distance * 2.5) - 250, (distance * 2.5) + 250)
elseif (mid[model]) then
base = math.random((distance * 1.6) - 250, (distance * 1.75) + 400)
else
outputDebugString("Unknown type given")
return
end
else
start = destinations["Helicopter"][flightData[1]]
finish = destinations["Helicopter"][flightData[2]]
local x1, y1, z1 = start[1], start[2], start[3]
local x2, y2, z2 = finish[1], finish[2], finish[3]
distance = getDistanceBetweenPoints3D(x1, y1, z1, x2, y2, z2)
--outputDebugString("Distance: "..distance)
-- You should earn slightly more with a helicopter
base = math.random(distance * 1.5, (distance * 1.5) + 350)
end
bonus = ranks[playerRank].bonus
local newAmount = math.floor((base * (bonus / 100)) + base)
local formattedAmount = exports.UCDutil:tocomma(newAmount)
outputDebugString("Base = "..base)
outputDebugString("Bonus = "..bonus.."%")
outputDebugString("New amount = "..newAmount)
local roundedDist = exports.UCDutil:mathround(distance / 1000, 2)
if (vehicle.vehicleType == "Plane") then
local fA = airports[flightData[1]]
local sA = airports[flightData[3]]
exports.UCDdx:new(client, "ATC: Flight from "..sA.." to "..fA.." complete ("..tostring(roundedDist).." km). You have been paid $"..formattedAmount..".", 255, 215, 0)
else
exports.UCDdx:new(client, "ATC: Flight complete ("..tostring(roundedDist).."km). You have been paid $"..formattedAmount..".", 255, 215, 0)
end
exports.UCDaccounts:SAD(client.account.name, "aviator", exports.UCDaccounts:GAD(client.account.name, "aviator") + roundedDist)
if (client.vehicle) then
--client.vehicle.frozen = false
triggerClientEvent(client, "UCDaviator.startItinerary", client, client.vehicle, client.vehicleSeat)
end
end
end
addEvent("UCDaviator.processFlight", true)
addEventHandler("UCDaviator.processFlight", root, processFlight)
|
UCDaviator
|
UCDaviator
- Fixed distance
|
Lua
|
mit
|
nokizorque/ucd,nokizorque/ucd
|
a96bcc2ed49f63db00de9acf69b54de2e354ccbe
|
localization/localization.enUS.lua
|
localization/localization.enUS.lua
|
local L = LibStub("AceLocale-3.0"):NewLocale("EPGP", "enUS", true)
if not L then return end
L["%+d EP (%s) to %s"] = true
L["%+d GP (%s) to %s"] = true
L["%d or %d"] = true
L["%s is added to the award list"] = true
L["%s is already in the award list"] = true
L["%s is dead. Award EP?"] = true
L["%s is not eligible for EP awards"] = true
L["%s is now removed from the award list"] = true
L["%s: %+d EP (%s) to %s"] = true
L["%s: %+d GP (%s) to %s"] = true
L["A member is awarded EP"] = true
L["A member is credited GP"] = true
L["Alts"] = true
L["Announce medium"] = true
L["Announce when:"] = true
L["Announce"] = true
L["Announcement of EPGP actions"] = true
L["Announces EPGP actions to the specified medium."] = true
L["Automatic boss tracking by means of a popup to mass award EP to the raid and standby when a boss is killed."] = true
L["Automatic boss tracking"] = true
L["Automatic handling of the standby list through whispers when in raid. When this is enabled, the standby list is cleared after each reward."] = true
L["Automatic loot tracking by means of a popup to assign GP to the toon that received loot. This option only has effect if you are in a raid and you are either the Raid Leader or the Master Looter."] = true
L["Automatic loot tracking"] = true
L["Award EP"] = true
L["Base GP should be a positive number"] = true
L["Boss"] = true
L["Credit GP to %s"] = true
L["Credit GP"] = true
L["Custom announce channel name"] = true
L["Decay EP and GP by %d%%?"] = true
L["Decay Percent should be a number between 0 and 100"] = true
L["Decay of EP/GP by %d%%"] = true
L["Decay"] = true
L["Decay=%s%% BaseGP=%s MinEP=%s Extras=%s%%"] = true
L["Do you want to resume recurring award (%s) %d EP/%s?"] = true
L["EP Reason"] = true
L["EP/GP are reset"] = true
L["EPGP decay"] = true
L["EPGP is an in game, relational loot distribution system"] = true
L["EPGP is using Officer Notes for data storage. Do you really want to edit the Officer Note by hand?"] = true
L["EPGP reset"] = true
L["Export"] = true
L["Extras Percent should be a number between 0 and 100"] = true
L["GP Reason"] = true
L["GP on tooltips"] = true
L["GP: %d [ItemLevel=%d]"] = true
L["GP: %d or %d [ItemLevel=%d]"] = true
L["Guild or Raid are awarded EP"] = true
L["Hint: You can open these options by typing /epgp config"] = true
L["If you want to be on the award list but you are not in the raid, you need to whisper me: 'epgp standby' or 'epgp standby <name>' where <name> is the toon that should receive awards"] = true
L["Ignoring EP change for unknown member %s"] = true
L["Ignoring GP change for unknown member %s"] = true
L["Import"] = true
L["Importing data snapshot taken at: %s"] = true
L["Invalid officer note [%s] for %s (ignored)"] = true
L["List errors"] = true
L["Lists errors during officer note parsing to the default chat frame. Examples are members with an invalid officer note."] = true
L["Loot tracking threshold"] = true
L["Loot"] = true
L["Mass EP Award"] = true
L["Min EP should be a positive number"] = true
L["Next award in "] = true
L["Other"] = true
L["Personal Action Log"] = true
L["Provide a proposed GP value of armor on tooltips. Quest items or tokens that can be traded for armor will also have a proposed GP value."] = true
L["Recurring awards resume"] = true
L["Recurring awards start"] = true
L["Recurring awards stop"] = true
L["Recurring"] = true
L["Redo"] = true
L["Reset EPGP"] = true
L["Reset all main toons' EP and GP to 0?"] = true
L["Resets EP and GP of all members of the guild. This will set all main toons' EP and GP to 0. Use with care!"] = true
L["Resume recurring award (%s) %d EP/%s"] = true
L["Sets loot tracking threshold, to disable the popup on loot below this threshold quality."] = true
L["Sets the announce medium EPGP will use to announce EPGP actions."] = true
L["Sets the custom announce channel name used to announce EPGP actions."] = true
L["Show everyone"] = true
L["Standby whispers in raid"] = true
L["Start recurring award (%s) %d EP/%s"] = true
L["Stop recurring award"] = true
L["The imported data is invalid"] = true
L["To export the current standings, copy the text below and post it to the webapp: http://epgpweb.appspot.com"] = true
L["To restore to an earlier version of the standings, copy and paste the text from the webapp: http://epgpweb.appspot.com here"] = true
L["Tooltip"] = true
L["Undo"] = true
L["Using DBM for boss kill tracking"] = true
L["Value"] = true
L["Whisper"] = true
|
local L = LibStub("AceLocale-3.0"):NewLocale("EPGP", "enUS", true)
if not L then return end
L["%+d EP (%s) to %s"] = true
L["%+d GP (%s) to %s"] = true
L["%d or %d"] = true
L["%s is added to the award list"] = true
L["%s is already in the award list"] = true
L["%s is dead. Award EP?"] = true
L["%s is not eligible for EP awards"] = true
L["%s is now removed from the award list"] = true
L["%s: %+d EP (%s) to %s"] = true
L["%s: %+d GP (%s) to %s"] = true
L["A member is awarded EP"] = true
L["A member is credited GP"] = true
L["Alts"] = true
L["Announce medium"] = true
L["Announce when:"] = true
L["Announce"] = true
L["Announcement of EPGP actions"] = true
L["Announces EPGP actions to the specified medium."] = true
L["Automatic boss tracking by means of a popup to mass award EP to the raid and standby when a boss is killed."] = true
L["Automatic boss tracking"] = true
L["Automatic handling of the standby list through whispers when in raid. When this is enabled, the standby list is cleared after each reward."] = true
L["Automatic loot tracking by means of a popup to assign GP to the toon that received loot. This option only has effect if you are in a raid and you are either the Raid Leader or the Master Looter."] = true
L["Automatic loot tracking"] = true
L["Award EP"] = true
L["Base GP should be a positive number"] = true
L["Boss"] = true
L["Credit GP to %s"] = true
L["Credit GP"] = true
L["Custom announce channel name"] = true
L["Decay EP and GP by %d%%?"] = true
L["Decay Percent should be a number between 0 and 100"] = true
L["Decay of EP/GP by %d%%"] = true
L["Decay"] = true
L["Decay=%s%% BaseGP=%s MinEP=%s Extras=%s%%"] = true
L["Do you want to resume recurring award (%s) %d EP/%s?"] = true
L["EP Reason"] = true
L["EP/GP are reset"] = true
L["EPGP decay"] = true
L["EPGP is an in game, relational loot distribution system"] = true
L["EPGP is using Officer Notes for data storage. Do you really want to edit the Officer Note by hand?"] = true
L["EPGP reset"] = true
L["Export"] = true
L["Extras Percent should be a number between 0 and 100"] = true
L["GP Reason"] = true
L["GP on tooltips"] = true
L["GP: %d [ItemLevel=%d]"] = true
L["GP: %d or %d [ItemLevel=%d]"] = true
L["Guild or Raid are awarded EP"] = true
L["Hint: You can open these options by typing /epgp config"] = true
L["If you want to be on the award list but you are not in the raid, you need to whisper me: 'epgp standby' or 'epgp standby <name>' where <name> is the toon that should receive awards"] = true
L["Ignoring EP change for unknown member %s"] = true
L["Ignoring GP change for unknown member %s"] = true
L["Import"] = true
L["Importing data snapshot taken at: %s"] = true
L["Invalid officer note [%s] for %s (ignored)"] = true
L["List errors"] = true
L["Lists errors during officer note parsing to the default chat frame. Examples are members with an invalid officer note."] = true
L["Loot tracking threshold"] = true
L["Loot"] = true
L["Mass EP Award"] = true
L["Min EP should be a positive number"] = true
L["Next award in "] = true
L["Other"] = true
L["Paste import data here"] = true
L["Personal Action Log"] = true
L["Provide a proposed GP value of armor on tooltips. Quest items or tokens that can be traded for armor will also have a proposed GP value."] = true
L["Recurring awards resume"] = true
L["Recurring awards start"] = true
L["Recurring awards stop"] = true
L["Recurring"] = true
L["Redo"] = true
L["Reset EPGP"] = true
L["Reset all main toons' EP and GP to 0?"] = true
L["Resets EP and GP of all members of the guild. This will set all main toons' EP and GP to 0. Use with care!"] = true
L["Resume recurring award (%s) %d EP/%s"] = true
L["Sets loot tracking threshold, to disable the popup on loot below this threshold quality."] = true
L["Sets the announce medium EPGP will use to announce EPGP actions."] = true
L["Sets the custom announce channel name used to announce EPGP actions."] = true
L["Show everyone"] = true
L["Standby whispers in raid"] = true
L["Start recurring award (%s) %d EP/%s"] = true
L["Stop recurring award"] = true
L["The imported data is invalid"] = true
L["To export the current standings, copy the text below and post it to the webapp: http://epgpweb.appspot.com"] = true
L["To restore to an earlier version of the standings, copy and paste the text from the webapp: http://epgpweb.appspot.com here"] = true
L["Tooltip"] = true
L["Undo"] = true
L["Using DBM for boss kill tracking"] = true
L["Value"] = true
L["Whisper"] = true
|
Add localizations for new string as part of fix of issue 356.
|
Add localizations for new string as part of fix of issue 356.
|
Lua
|
bsd-3-clause
|
sheldon/epgp,protomech/epgp-dkp-reloaded,hayword/tfatf_epgp,protomech/epgp-dkp-reloaded,ceason/epgp-tfatf,sheldon/epgp,hayword/tfatf_epgp,ceason/epgp-tfatf
|
e10bfde2327dbed9b1217cc425748505b5216583
|
mod_blocking/mod_blocking.lua
|
mod_blocking/mod_blocking.lua
|
local jid_split = require "util.jid".split;
local st = require "util.stanza";
local xmlns_blocking = "urn:xmpp:blocking";
module:add_feature("urn:xmpp:blocking");
-- Add JID to default privacy list
function add_blocked_jid(username, host, jid)
local privacy_lists = datamanager.load(username, host, "privacy") or {lists = {}};
local default_list_name = privacy_lists.default;
if not default_list_name then
default_list_name = "blocklist";
privacy_lists.default = default_list_name;
end
local default_list = privacy_lists.lists[default_list_name];
if not default_list then
default_list = { name = default_list_name, items = {} };
privacy_lists.lists[default_list_name] = default_list;
end
local items = default_list.items;
local order = items[1] and items[1].order or 0; -- Must come first
for i=1,#items do -- order must be unique
local item = items[i];
item.order = item.order + 1;
if item.type == "jid" and item.action == "deny" and item.value == jid then
return false;
end
end
table.insert(items, 1, { type = "jid"
, action = "deny"
, value = jid
, message = false
, ["presence-out"] = false
, ["presence-in"] = false
, iq = false
, order = order
});
datamanager.store(username, host, "privacy", privacy_lists);
return true;
end
-- Remove JID from default privacy list
function remove_blocked_jid(username, host, jid)
local privacy_lists = datamanager.load(username, host, "privacy") or {};
local default_list_name = privacy_lists.default;
if not default_list_name then return; end
local default_list = privacy_lists.lists[default_list_name];
if not default_list then return; end
local items = default_list.items;
local item, removed = nil, false;
for i=1,#items do -- order must be unique
item = items[i];
if item.type == "jid" and item.action == "deny" and item.value == jid then
table.remove(items, i);
removed = true;
break;
end
end
if removed then
datamanager.store(username, host, "privacy", privacy_lists);
end
return removed;
end
function remove_all_blocked_jids(username, host)
local privacy_lists = datamanager.load(username, host, "privacy") or {};
local default_list_name = privacy_lists.default;
if not default_list_name then return; end
local default_list = privacy_lists.lists[default_list_name];
if not default_list then return; end
local items = default_list.items;
local item;
for i=#items,1,-1 do -- order must be unique
item = items[i];
if item.type == "jid" and item.action == "deny" then
table.remove(items, i);
end
end
datamanager.store(username, host, "privacy", privacy_lists);
return true;
end
function get_blocked_jids(username, host)
-- Return array of blocked JIDs in default privacy list
local privacy_lists = datamanager.load(username, host, "privacy") or {};
local default_list_name = privacy_lists.default;
if not default_list_name then return {}; end
local default_list = privacy_lists.lists[default_list_name];
if not default_list then return {}; end
local items = default_list.items;
local item;
local jid_list = {};
for i=1,#items do -- order must be unique
item = items[i];
if item.type == "jid" and item.action == "deny" then
jid_list[#jid_list+1] = item.value;
end
end
return jid_list;
end
function handle_blocking_command(event)
local session, stanza = event.origin, event.stanza;
local username, host = jid_split(stanza.attr.from);
if stanza.attr.type == "set" then
if stanza.tags[1].name == "block" then
local block = stanza.tags[1];
local block_jid_list = {};
for item in block:childtags() do
block_jid_list[#block_jid_list+1] = item.attr.jid;
end
if #block_jid_list == 0 then
session.send(st.error_reply(stanza, "modify", "bad-request"));
else
for _, jid in ipairs(block_jid_list) do
add_blocked_jid(username, host, jid);
end
session.send(st.reply(stanza));
end
return true;
elseif stanza.tags[1].name == "unblock" then
remove_all_blocked_jids(username, host);
session.send(st.reply(stanza));
return true;
end
elseif stanza.attr.type == "get" and stanza.tags[1].name == "blocklist" then
local reply = st.reply(stanza):tag("blocklist", { xmlns = xmlns_blocking });
local blocked_jids = get_blocked_jids(username, host);
for _, jid in ipairs(blocked_jids) do
reply:tag("item", { jid = jid }):up();
end
session.send(reply);
return true;
end
end
module:hook("iq/self/urn:xmpp:blocking:blocklist", handle_blocking_command);
module:hook("iq/self/urn:xmpp:blocking:block", handle_blocking_command);
module:hook("iq/self/urn:xmpp:blocking:unblock", handle_blocking_command);
|
local jid_split = require "util.jid".split;
local st = require "util.stanza";
local xmlns_blocking = "urn:xmpp:blocking";
module:add_feature("urn:xmpp:blocking");
-- Add JID to default privacy list
function add_blocked_jid(username, host, jid)
local privacy_lists = datamanager.load(username, host, "privacy") or {lists = {}};
local default_list_name = privacy_lists.default;
if not default_list_name then
default_list_name = "blocklist";
privacy_lists.default = default_list_name;
end
local default_list = privacy_lists.lists[default_list_name];
if not default_list then
default_list = { name = default_list_name, items = {} };
privacy_lists.lists[default_list_name] = default_list;
end
local items = default_list.items;
local order = items[1] and items[1].order or 0; -- Must come first
for i=1,#items do -- order must be unique
local item = items[i];
item.order = item.order + 1;
if item.type == "jid" and item.action == "deny" and item.value == jid then
return false;
end
end
table.insert(items, 1, { type = "jid"
, action = "deny"
, value = jid
, message = false
, ["presence-out"] = false
, ["presence-in"] = false
, iq = false
, order = order
});
datamanager.store(username, host, "privacy", privacy_lists);
return true;
end
-- Remove JID from default privacy list
function remove_blocked_jid(username, host, jid)
local privacy_lists = datamanager.load(username, host, "privacy") or {};
local default_list_name = privacy_lists.default;
if not default_list_name then return; end
local default_list = privacy_lists.lists[default_list_name];
if not default_list then return; end
local items = default_list.items;
local item, removed = nil, false;
for i=1,#items do -- order must be unique
item = items[i];
if item.type == "jid" and item.action == "deny" and item.value == jid then
table.remove(items, i);
removed = true;
break;
end
end
if removed then
datamanager.store(username, host, "privacy", privacy_lists);
end
return removed;
end
function remove_all_blocked_jids(username, host)
local privacy_lists = datamanager.load(username, host, "privacy") or {};
local default_list_name = privacy_lists.default;
if not default_list_name then return; end
local default_list = privacy_lists.lists[default_list_name];
if not default_list then return; end
local items = default_list.items;
local item;
for i=#items,1,-1 do -- order must be unique
item = items[i];
if item.type == "jid" and item.action == "deny" then
table.remove(items, i);
end
end
datamanager.store(username, host, "privacy", privacy_lists);
return true;
end
function get_blocked_jids(username, host)
-- Return array of blocked JIDs in default privacy list
local privacy_lists = datamanager.load(username, host, "privacy") or {};
local default_list_name = privacy_lists.default;
if not default_list_name then return {}; end
local default_list = privacy_lists.lists[default_list_name];
if not default_list then return {}; end
local items = default_list.items;
local item;
local jid_list = {};
for i=1,#items do -- order must be unique
item = items[i];
if item.type == "jid" and item.action == "deny" then
jid_list[#jid_list+1] = item.value;
end
end
return jid_list;
end
local function send_push_iqs(username, host, command_type, jids)
local bare_jid = username.."@"..host;
local stanza_content = st.stanza(command_type, { xmlns = xmlns_blocking });
for _, jid in ipairs(jids) do
stanza_content:tag("item", { jid = jid }):up();
end
for resource, session in pairs(prosody.bare_sessions[bare_jid].sessions) do
local iq_push_stanza = st.iq({ type = "set", to = bare_jid.."/"..resource });
iq_push_stanza:add_child(stanza_content);
session.send(iq_push_stanza);
end
end
function handle_blocking_command(event)
local session, stanza = event.origin, event.stanza;
local username, host = jid_split(stanza.attr.from);
if stanza.attr.type == "set" then
if stanza.tags[1].name == "block" then
local block = stanza.tags[1];
local block_jid_list = {};
for item in block:childtags() do
block_jid_list[#block_jid_list+1] = item.attr.jid;
end
if #block_jid_list == 0 then
session.send(st.error_reply(stanza, "modify", "bad-request"));
else
for _, jid in ipairs(block_jid_list) do
add_blocked_jid(username, host, jid);
end
session.send(st.reply(stanza));
send_push_iqs(username, host, "block", block_jid_list);
end
return true;
elseif stanza.tags[1].name == "unblock" then
local unblock = stanza.tags[1];
local unblock_jid_list = {};
for item in unblock:childtags() do
unblock_jid_list[#unblock_jid_list+1] = item.attr.jid;
end
if #unblock_jid_list == 0 then
remove_all_blocked_jids(username, host);
else
for _, jid_to_unblock in ipairs(unblock_jid_list) do
remove_blocked_jid(username, host, jid_to_unblock);
end
end
session.send(st.reply(stanza));
send_push_iqs(username, host, "unblock", unblock_jid_list);
return true;
end
elseif stanza.attr.type == "get" and stanza.tags[1].name == "blocklist" then
local reply = st.reply(stanza):tag("blocklist", { xmlns = xmlns_blocking });
local blocked_jids = get_blocked_jids(username, host);
for _, jid in ipairs(blocked_jids) do
reply:tag("item", { jid = jid }):up();
end
session.send(reply);
return true;
end
end
module:hook("iq/self/urn:xmpp:blocking:blocklist", handle_blocking_command);
module:hook("iq/self/urn:xmpp:blocking:block", handle_blocking_command);
module:hook("iq/self/urn:xmpp:blocking:unblock", handle_blocking_command);
|
mod_blocking: Fix handling of unblocking command. Send out un-/block pushes to all resources.
|
mod_blocking: Fix handling of unblocking command. Send out un-/block pushes to all resources.
|
Lua
|
mit
|
prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2
|
72c5a569f69b472dbd343146e201d7193cbb2bf8
|
.vim/lua/pluginconfig/telescope.lua
|
.vim/lua/pluginconfig/telescope.lua
|
local actions = require('telescope.actions')
local config = require('telescope.config')
local pickers = require('telescope.pickers')
local finders = require('telescope.finders')
local make_entry = require('telescope.make_entry')
local previewers = require('telescope.previewers')
local utils = require('telescope.utils')
local conf = require('telescope.config').values
local telescope_builtin = require 'telescope.builtin'
require('telescope').setup{
defaults = {
vimgrep_arguments = {
'rg',
'--color=never',
'--no-heading',
'--with-filename',
'--line-number',
'--column',
'--smart-case'
},
prompt_position = "bottom",
prompt_prefix = ">",
selection_strategy = "reset",
sorting_strategy = "descending",
layout_strategy = "horizontal",
layout_defaults = {
-- TODO add builtin options.
},
file_sorter = require'telescope.sorters'.get_fuzzy_file,
file_ignore_patterns = {},
generic_sorter = require'telescope.sorters'.get_generic_fuzzy_sorter,
shorten_path = true,
winblend = 0,
width = 0.75,
preview_cutoff = 120,
results_height = 1,
results_width = 0.8,
border = {},
borderchars = { '─', '│', '─', '│', '╭', '╮', '╯', '╰'},
color_devicons = true,
use_less = true,
set_env = { ['COLORTERM'] = 'truecolor' }, -- default { }, currently unsupported for shells like cmd.exe / powershell.exe
file_previewer = require'telescope.previewers'.cat.new, -- For buffer previewer use `require'telescope.previewers'.vim_buffer_cat.new`
grep_previewer = require'telescope.previewers'.vimgrep.new, -- For buffer previewer use `require'telescope.previewers'.vim_buffer_vimgrep.new`
qflist_previewer = require'telescope.previewers'.qflist.new, -- For buffer previewer use `require'telescope.previewers'.vim_buffer_qflist.new`
-- Developer configurations: Not meant for general override
buffer_previewer_maker = require'telescope.previewers'.buffer_previewer_maker,
mappings = {
i = {
["<c-x>"] = false,
["<c-s>"] = actions.goto_file_selection_split,
["<Tab>"] = actions.toggle_selection,
['<C-q>'] = actions.send_selected_to_qflist,
}
}
}
}
telescope_builtin.my_mru = function(opts)
local results = vim.tbl_filter(function(val)
return 0 ~= vim.fn.filereadable(val)
end, vim.v.oldfiles)
local show_untracked = utils.get_default(opts.show_untracked, true)
local recurse_submodules = utils.get_default(opts.recurse_submodules, false)
if show_untracked and recurse_submodules then
error("Git does not suppurt both --others and --recurse-submodules")
end
local cmd = {"git", "ls-files", "--exclude-standard", "--cached", show_untracked and "--others" or nil, recurse_submodules and "--recurse-submodules" or nil}
local results2 = utils.get_os_command_output({"git", "ls-files"})
for k,v in pairs(results2) do table.insert(results, v) end
pickers.new(opts, {
prompt_title = 'MRU',
finder = finders.new_table{
results = results,
entry_maker = opts.entry_maker or make_entry.gen_from_file(opts),
},
sorter = conf.file_sorter(opts),
previewer = conf.file_previewer(opts),
}):find()
end
|
local actions = require('telescope.actions')
local config = require('telescope.config')
local pickers = require('telescope.pickers')
local finders = require('telescope.finders')
local make_entry = require('telescope.make_entry')
local previewers = require('telescope.previewers')
local utils = require('telescope.utils')
local conf = require('telescope.config').values
local telescope_builtin = require 'telescope.builtin'
local path = require('telescope.path')
require('telescope').setup{
defaults = {
vimgrep_arguments = {
'rg',
'--color=never',
'--no-heading',
'--with-filename',
'--line-number',
'--column',
'--smart-case'
},
prompt_position = "bottom",
prompt_prefix = ">",
selection_strategy = "reset",
sorting_strategy = "descending",
layout_strategy = "horizontal",
layout_defaults = {
-- TODO add builtin options.
},
file_sorter = require'telescope.sorters'.get_fuzzy_file,
file_ignore_patterns = {},
generic_sorter = require'telescope.sorters'.get_generic_fuzzy_sorter,
shorten_path = true,
winblend = 0,
width = 0.75,
preview_cutoff = 120,
results_height = 1,
results_width = 0.8,
border = {},
borderchars = { '─', '│', '─', '│', '╭', '╮', '╯', '╰'},
color_devicons = true,
use_less = true,
set_env = { ['COLORTERM'] = 'truecolor' }, -- default { }, currently unsupported for shells like cmd.exe / powershell.exe
file_previewer = require'telescope.previewers'.cat.new, -- For buffer previewer use `require'telescope.previewers'.vim_buffer_cat.new`
grep_previewer = require'telescope.previewers'.vimgrep.new, -- For buffer previewer use `require'telescope.previewers'.vim_buffer_vimgrep.new`
qflist_previewer = require'telescope.previewers'.qflist.new, -- For buffer previewer use `require'telescope.previewers'.vim_buffer_qflist.new`
-- Developer configurations: Not meant for general override
buffer_previewer_maker = require'telescope.previewers'.buffer_previewer_maker,
mappings = {
i = {
["<c-x>"] = false,
["<c-s>"] = actions.goto_file_selection_split,
["<Tab>"] = actions.toggle_selection,
['<C-q>'] = actions.send_selected_to_qflist,
}
}
},
extensions = {
media_files = {
filetypes = {"png", "webp", "jpg", "jpeg"}, -- filetypes whitelist
find_cmd = "rg" -- find command
}
}
}
function remove_duplicate_paths(tbl, cwd)
local res = {}
local hash = {}
for _,v in ipairs(tbl) do
local v1 = path.make_relative(v, cwd)
if (not hash[v1]) then
res[#res+1] = v1
hash[v1] = true
end
end
return res
end
telescope_builtin.my_mru = function(opts)
local results = vim.tbl_filter(function(val)
return 0 ~= vim.fn.filereadable(val)
end, vim.v.oldfiles)
local show_untracked = utils.get_default(opts.show_untracked, true)
local recurse_submodules = utils.get_default(opts.recurse_submodules, false)
if show_untracked and recurse_submodules then
error("Git does not suppurt both --others and --recurse-submodules")
end
local cmd = {"git", "ls-files", "--exclude-standard", "--cached", show_untracked and "--others" or nil, recurse_submodules and "--recurse-submodules" or nil}
local results2 = utils.get_os_command_output(cmd)
for k,v in pairs(results2) do table.insert(results, v) end
pickers.new(opts, {
prompt_title = 'MRU',
finder = finders.new_table{
results = remove_duplicate_paths(results, vim.loop.cwd()),
entry_maker = opts.entry_maker or make_entry.gen_from_file(opts),
},
sorter = conf.file_sorter(opts),
previewer = conf.file_previewer(opts),
}):find()
end
|
vim: Fix to store duplicated paths
|
vim: Fix to store duplicated paths
|
Lua
|
mit
|
yutakatay/dotfiles,yutakatay/dotfiles
|
4f2922745fd42ddc8e20248b171a8886cb1aaa12
|
MMOCoreORB/bin/scripts/managers/mission_manager.lua
|
MMOCoreORB/bin/scripts/managers/mission_manager.lua
|
dofile("scripts/managers/mission_npc_spawn_points.lua");
crafting_mission_items = {
"object/draft_schematic/item/quest_item/attunement_grid.iff",
"object/draft_schematic/item/quest_item/current_alternator.iff",
"object/draft_schematic/item/quest_item/feedback_controller.iff",
"object/draft_schematic/item/quest_item/output_govenor.iff",
"object/draft_schematic/item/quest_item/power_regulator.iff"
}
bh_target_zones = {
"corellia",
"dantooine",
"dathomir",
"lok",
"naboo",
"rori",
"talus",
"tatooine",
"yavin4"
}
bh_targets_at_mission_level = {
level1 = {
"bodyguard",
"bodyguard_zabrak_female"
},
level2 = {
"bodyguard",
"bodyguard_zabrak_female"
},
level3 = {
"bodyguard",
"bodyguard_zabrak_female"
}
}
enable_factional_crafting_missions = "true"
enable_factional_recon_missions = "true"
enable_factional_entertainer_missions = "true"
|
dofile("scripts/managers/mission_npc_spawn_points.lua");
crafting_mission_items = {
"object/draft_schematic/item/quest_item/attunement_grid.iff",
"object/draft_schematic/item/quest_item/current_alternator.iff",
"object/draft_schematic/item/quest_item/feedback_controller.iff",
"object/draft_schematic/item/quest_item/output_govenor.iff",
"object/draft_schematic/item/quest_item/power_regulator.iff"
}
bh_target_zones = {
"corellia",
"dantooine",
"dathomir",
"lok",
"naboo",
"rori",
"talus",
"tatooine",
"yavin4"
}
bh_targets_at_mission_level = {
level1 = {
"bodyguard",
"bodyguard_zabrak_female"
},
level2 = {
"dune_stalker_brawler",
"kai_tok_prowler"
},
level3 = {
"pirate_leader",
"sennex_guard"
}
}
enable_factional_crafting_missions = "true"
enable_factional_recon_missions = "true"
enable_factional_entertainer_missions = "true"
|
(unstable) [fixed] BH missions now gets tougher targets for each level.
|
(unstable) [fixed] BH missions now gets tougher targets for each level.
git-svn-id: e4cf3396f21da4a5d638eecf7e3b4dd52b27f938@5769 c3d1530f-68f5-4bd0-87dc-8ef779617e40
|
Lua
|
agpl-3.0
|
Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo
|
aaa0b9206c4e625133f98520d2cd25fb366b6f3e
|
.config/nvim/lua/config/toggleterm.lua
|
.config/nvim/lua/config/toggleterm.lua
|
local status_ok, p = pcall(require, "toggleterm")
if not status_ok then
return
end
p.setup({
open_mapping = [[<c-\>]],
direction = "float",
float_opts = {
border = "curved",
},
close_on_exit = true,
})
local keymap = vim.keymap.set
function _G.set_terminal_keymaps()
local opts = { buffer = 0 }
keymap("t", "<esc>", [[<C-\><C-n>]], opts)
keymap("t", "<C-h>", [[<Cmd>wincmd h<CR>]], opts)
keymap("t", "<C-j>", [[<Cmd>wincmd j<CR>]], opts)
keymap("t", "<C-k>", [[<Cmd>wincmd k<CR>]], opts)
keymap("t", "<C-l>", [[<Cmd>wincmd l<CR>]], opts)
end
-- if you only want these mappings for toggle term use term://*toggleterm#* instead
vim.api.nvim_create_autocmd({ "TermOpen" }, {
group = "_",
pattern = "term://*",
command = "lua set_terminal_keymaps()",
})
local opts = { noremap = true, silent = true }
keymap("n", ",,f", function()
vim.cmd(vim.v.count1 .. "ToggleTerm direction=float")
end, opts)
keymap("n", ",,j", function()
vim.cmd(vim.v.count1 .. "ToggleTerm direction=horizontal")
end, opts)
|
local status_ok, p = pcall(require, "toggleterm")
if not status_ok then
return
end
p.setup({
open_mapping = [[<c-\>]],
direction = "float",
float_opts = {
border = "curved",
},
close_on_exit = true,
})
local keymap = vim.keymap.set
function _G.set_terminal_keymaps()
local opts = { buffer = 0 }
keymap("t", "<esc>", [[<C-\><C-n>]], opts)
keymap("t", "<C-j>", [[<Cmd>wincmd j<CR>]], opts)
keymap("t", "<C-k>", [[<Cmd>wincmd k<CR>]], opts)
end
-- if you only want these mappings for toggle term use term://*toggleterm#* instead
vim.api.nvim_create_autocmd({ "TermOpen" }, {
group = "_",
pattern = "term://*",
command = "lua set_terminal_keymaps()",
})
local opts = { noremap = true, silent = true }
keymap("n", ",,f", function()
vim.cmd(vim.v.count1 .. "ToggleTerm direction=float")
end, opts)
keymap("n", ",,j", function()
vim.cmd(vim.v.count1 .. "ToggleTerm direction=horizontal")
end, opts)
|
[nvim] Fix ToggleTerm key bindings
|
[nvim] Fix ToggleTerm key bindings
|
Lua
|
mit
|
masa0x80/dotfiles,masa0x80/dotfiles,masa0x80/dotfiles,masa0x80/dotfiles
|
d2abcc78ca5b929adc1394a6fa897fc13d8baea6
|
busted/core.lua
|
busted/core.lua
|
local getfenv = require 'busted.compatibility'.getfenv
local setfenv = require 'busted.compatibility'.setfenv
local unpack = require 'busted.compatibility'.unpack
local pretty = require 'pl.pretty'
local throw = error
local failureMt = {
__index = {},
__tostring = function(e) return tostring(e.message) end,
__type = 'failure'
}
local failureMtNoString = {
__index = {},
__type = 'failure'
}
local pendingMt = {
__index = {},
__tostring = function(p) return p.message end,
__type = 'pending'
}
local function metatype(obj)
local otype = type(obj)
return otype == 'table' and (getmetatable(obj) or {}).__type or otype
end
local function hasToString(obj)
return type(obj) == 'string' or (getmetatable(obj) or {}).__tostring
end
return function()
local mediator = require 'mediator'()
local busted = {}
busted.version = '2.0.rc5-0'
local root = require 'busted.context'()
busted.context = root.ref()
local environment = require 'busted.environment'(busted.context)
busted.executors = {}
local executors = {}
busted.status = require 'busted.status'
function busted.getTrace(element, level, msg)
level = level or 3
local info = debug.getinfo(level, 'Sl')
while info.what == 'C' or info.short_src:match('luassert[/\\].*%.lua$') or
info.short_src:match('busted[/\\].*%.lua$') do
level = level + 1
info = debug.getinfo(level, 'Sl')
end
info.traceback = debug.traceback('', level)
info.message = msg
local file = busted.getFile(element)
return file.getTrace(file.name, info)
end
function busted.rewriteMessage(element, message, trace)
local file = busted.getFile(element)
local msg = hasToString(message) and tostring(message)
msg = msg or (message ~= nil and pretty.write(message) or 'Nil error')
msg = (file.rewriteMessage and file.rewriteMessage(file.name, msg) or msg)
local hasFileLine = msg:match('^[^\n]-:%d+: .*')
if not hasFileLine then
local trace = trace or busted.getTrace(element, 3, message)
local fileline = trace.short_src .. ':' .. trace.currentline .. ': '
msg = fileline .. msg
end
return msg
end
function busted.publish(...)
return mediator:publish(...)
end
function busted.subscribe(...)
return mediator:subscribe(...)
end
function busted.getFile(element)
local current, parent = element, busted.context.parent(element)
while parent do
if parent.file then
local file = parent.file[1]
return {
name = file.name,
getTrace = file.run.getTrace,
rewriteMessage = file.run.rewriteMessage
}
end
if parent.descriptor == 'file' then
return {
name = parent.name,
getTrace = parent.run.getTrace,
rewriteMessage = parent.run.rewriteMessage
}
end
parent = busted.context.parent(parent)
end
return parent
end
function busted.fail(msg, level)
local rawlevel = (type(level) ~= 'number' or level <= 0) and level
local level = level or 1
local _, emsg = pcall(throw, msg, rawlevel or level+2)
local e = { message = emsg }
setmetatable(e, hasToString(msg) and failureMt or failureMtNoString)
throw(e, rawlevel or level+1)
end
function busted.pending(msg)
local p = { message = msg }
setmetatable(p, pendingMt)
throw(p)
end
function busted.replaceErrorWithFail(callable)
local env = {}
local f = (getmetatable(callable) or {}).__call or callable
setmetatable(env, { __index = getfenv(f) })
env.error = busted.fail
setfenv(f, env)
end
function busted.wrapEnv(callable)
if (type(callable) == 'function' or getmetatable(callable).__call) then
-- prioritize __call if it exists, like in files
environment.wrap((getmetatable(callable) or {}).__call or callable)
end
end
function busted.safe(descriptor, run, element)
busted.context.push(element)
local trace, message
local status = 'success'
local ret = { xpcall(run, function(msg)
local errType = metatype(msg)
status = ((errType == 'pending' or errType == 'failure') and errType or 'error')
trace = busted.getTrace(element, 3, msg)
message = busted.rewriteMessage(element, msg, trace)
end) }
if not ret[1] then
busted.publish({ status, descriptor }, element, busted.context.parent(element), message, trace)
end
ret[1] = busted.status(status)
busted.context.pop()
return unpack(ret)
end
function busted.register(descriptor, executor)
executors[descriptor] = executor
local publisher = function(name, fn)
if not fn and type(name) == 'function' then
fn = name
name = nil
end
local trace
local ctx = busted.context.get()
if busted.context.parent(ctx) then
trace = busted.getTrace(ctx, 3, name)
end
local publish = function(f)
busted.publish({ 'register', descriptor }, name, f, trace)
end
if fn then publish(fn) else return publish end
end
busted.executors[descriptor] = publisher
if descriptor ~= 'file' then
environment.set(descriptor, publisher)
end
busted.subscribe({ 'register', descriptor }, function(name, fn, trace)
local ctx = busted.context.get()
local plugin = {
descriptor = descriptor,
name = name,
run = fn,
trace = trace
}
busted.context.attach(plugin)
if not ctx[descriptor] then
ctx[descriptor] = { plugin }
else
ctx[descriptor][#ctx[descriptor]+1] = plugin
end
end)
end
function busted.execute(current)
if not current then current = busted.context.get() end
for _, v in pairs(busted.context.children(current)) do
local executor = executors[v.descriptor]
if executor then
busted.safe(v.descriptor, function() executor(v) end, v)
end
end
end
return busted
end
|
local getfenv = require 'busted.compatibility'.getfenv
local setfenv = require 'busted.compatibility'.setfenv
local unpack = require 'busted.compatibility'.unpack
local path = require 'pl.path'
local pretty = require 'pl.pretty'
local throw = error
local failureMt = {
__index = {},
__tostring = function(e) return tostring(e.message) end,
__type = 'failure'
}
local failureMtNoString = {
__index = {},
__type = 'failure'
}
local pendingMt = {
__index = {},
__tostring = function(p) return p.message end,
__type = 'pending'
}
local function metatype(obj)
local otype = type(obj)
return otype == 'table' and (getmetatable(obj) or {}).__type or otype
end
local function hasToString(obj)
return type(obj) == 'string' or (getmetatable(obj) or {}).__tostring
end
return function()
local mediator = require 'mediator'()
local busted = {}
busted.version = '2.0.rc5-0'
local root = require 'busted.context'()
busted.context = root.ref()
local environment = require 'busted.environment'(busted.context)
busted.executors = {}
local executors = {}
busted.status = require 'busted.status'
function busted.getTrace(element, level, msg)
level = level or 3
local thisdir = path.dirname(debug.getinfo(1, 'Sl').source)
local info = debug.getinfo(level, 'Sl')
while info.what == 'C' or info.short_src:match('luassert[/\\].*%.lua$') or
(info.source:sub(1,1) == '@' and thisdir == path.dirname(info.source)) do
level = level + 1
info = debug.getinfo(level, 'Sl')
end
info.traceback = debug.traceback('', level)
info.message = msg
local file = busted.getFile(element)
return file.getTrace(file.name, info)
end
function busted.rewriteMessage(element, message, trace)
local file = busted.getFile(element)
local msg = hasToString(message) and tostring(message)
msg = msg or (message ~= nil and pretty.write(message) or 'Nil error')
msg = (file.rewriteMessage and file.rewriteMessage(file.name, msg) or msg)
local hasFileLine = msg:match('^[^\n]-:%d+: .*')
if not hasFileLine then
local trace = trace or busted.getTrace(element, 3, message)
local fileline = trace.short_src .. ':' .. trace.currentline .. ': '
msg = fileline .. msg
end
return msg
end
function busted.publish(...)
return mediator:publish(...)
end
function busted.subscribe(...)
return mediator:subscribe(...)
end
function busted.getFile(element)
local current, parent = element, busted.context.parent(element)
while parent do
if parent.file then
local file = parent.file[1]
return {
name = file.name,
getTrace = file.run.getTrace,
rewriteMessage = file.run.rewriteMessage
}
end
if parent.descriptor == 'file' then
return {
name = parent.name,
getTrace = parent.run.getTrace,
rewriteMessage = parent.run.rewriteMessage
}
end
parent = busted.context.parent(parent)
end
return parent
end
function busted.fail(msg, level)
local rawlevel = (type(level) ~= 'number' or level <= 0) and level
local level = level or 1
local _, emsg = pcall(throw, msg, rawlevel or level+2)
local e = { message = emsg }
setmetatable(e, hasToString(msg) and failureMt or failureMtNoString)
throw(e, rawlevel or level+1)
end
function busted.pending(msg)
local p = { message = msg }
setmetatable(p, pendingMt)
throw(p)
end
function busted.replaceErrorWithFail(callable)
local env = {}
local f = (getmetatable(callable) or {}).__call or callable
setmetatable(env, { __index = getfenv(f) })
env.error = busted.fail
setfenv(f, env)
end
function busted.wrapEnv(callable)
if (type(callable) == 'function' or getmetatable(callable).__call) then
-- prioritize __call if it exists, like in files
environment.wrap((getmetatable(callable) or {}).__call or callable)
end
end
function busted.safe(descriptor, run, element)
busted.context.push(element)
local trace, message
local status = 'success'
local ret = { xpcall(run, function(msg)
local errType = metatype(msg)
status = ((errType == 'pending' or errType == 'failure') and errType or 'error')
trace = busted.getTrace(element, 3, msg)
message = busted.rewriteMessage(element, msg, trace)
end) }
if not ret[1] then
busted.publish({ status, descriptor }, element, busted.context.parent(element), message, trace)
end
ret[1] = busted.status(status)
busted.context.pop()
return unpack(ret)
end
function busted.register(descriptor, executor)
executors[descriptor] = executor
local publisher = function(name, fn)
if not fn and type(name) == 'function' then
fn = name
name = nil
end
local trace
local ctx = busted.context.get()
if busted.context.parent(ctx) then
trace = busted.getTrace(ctx, 3, name)
end
local publish = function(f)
busted.publish({ 'register', descriptor }, name, f, trace)
end
if fn then publish(fn) else return publish end
end
busted.executors[descriptor] = publisher
if descriptor ~= 'file' then
environment.set(descriptor, publisher)
end
busted.subscribe({ 'register', descriptor }, function(name, fn, trace)
local ctx = busted.context.get()
local plugin = {
descriptor = descriptor,
name = name,
run = fn,
trace = trace
}
busted.context.attach(plugin)
if not ctx[descriptor] then
ctx[descriptor] = { plugin }
else
ctx[descriptor][#ctx[descriptor]+1] = plugin
end
end)
end
function busted.execute(current)
if not current then current = busted.context.get() end
for _, v in pairs(busted.context.children(current)) do
local executor = executors[v.descriptor]
if executor then
busted.safe(v.descriptor, function() executor(v) end, v)
end
end
end
return busted
end
|
Fix getTrace() to search based on busted dirname
|
Fix getTrace() to search based on busted dirname
|
Lua
|
mit
|
Olivine-Labs/busted,ryanplusplus/busted,nehz/busted,mpeterv/busted,sobrinho/busted,o-lim/busted,DorianGray/busted,xyliuke/busted,istr/busted,leafo/busted
|
593eecb29f50db2f02ec7a92396187bb7ef61cb2
|
deps/coro-channel.lua
|
deps/coro-channel.lua
|
exports.name = "creationix/coro-channel"
exports.version = "1.2.0"
exports.homepage = "https://github.com/luvit/lit/blob/master/deps/coro-channel.lua"
exports.description = "An adapter for wrapping uv streams as coro-streams and chaining filters."
exports.tags = {"coro", "adapter"}
exports.license = "MIT"
exports.author = { name = "Tim Caswell" }
local function wrapRead(socket)
local paused = true
local queue = {}
local waiting
local onRead
function onRead(err, chunk)
local data = err and {nil, err} or {chunk}
if waiting then
local thread = waiting
waiting = nil
assert(coroutine.resume(thread, unpack(data)))
else
queue[#queue + 1] = data
if not paused then
paused = true
assert(socket:read_stop())
end
end
end
return function ()
if #queue > 0 then
return unpack(table.remove(queue, 1))
end
if paused then
paused = false
assert(socket:read_start(onRead))
end
waiting = coroutine.running()
return coroutine.yield()
end
end
local function wrapWrite(socket)
local function wait()
local thread = coroutine.running()
return function (err)
assert(coroutine.resume(thread, err))
end
end
local function shutdown()
socket:shutdown(wait())
coroutine.yield()
if not socket:is_closing() then
socket:close()
end
end
return function (chunk)
if chunk == nil then
return shutdown()
end
assert(socket:write(chunk, wait()))
local err = coroutine.yield()
return not err, err
end
end
exports.wrapRead = wrapRead
exports.wrapWrite = wrapWrite
-- Given a raw uv_stream_t userdata, return coro-friendly read/write functions.
function exports.wrapStream(socket)
return wrapRead(socket), wrapWrite(socket)
end
function exports.chain(...)
local args = {...}
local nargs = select("#", ...)
return function (read, write)
local threads = {} -- coroutine thread for each item
local waiting = {} -- flag when waiting to pull from upstream
local boxes = {} -- storage when waiting to write to downstream
for i = 1, nargs do
threads[i] = coroutine.create(args[i])
waiting[i] = false
local r, w
if i == 1 then
r = read
else
function r()
local j = i - 1
if boxes[j] then
local data = boxes[j]
boxes[j] = nil
assert(coroutine.resume(threads[j]))
return unpack(data)
else
waiting[i] = true
return coroutine.yield()
end
end
end
if i == nargs then
w = write
else
function w(...)
local j = i + 1
if waiting[j] then
waiting[j] = false
assert(coroutine.resume(threads[j], ...))
else
boxes[i] = {...}
coroutine.yield()
end
end
end
assert(coroutine.resume(threads[i], r, w))
end
end
end
|
exports.name = "creationix/coro-channel"
exports.version = "1.2.1"
exports.homepage = "https://github.com/luvit/lit/blob/master/deps/coro-channel.lua"
exports.description = "An adapter for wrapping uv streams as coro-streams and chaining filters."
exports.tags = {"coro", "adapter"}
exports.license = "MIT"
exports.author = { name = "Tim Caswell" }
local function wrapRead(socket)
local paused = true
local queue = {}
local queueFirst = 0
local queueLast = 0
local reader = {}
local readerFirst = 0
local readerLast = 0
local function onRead(err, chunk)
local data = err and {nil, err} or {chunk}
if readerFirst < readerLast then
local thread = reader[readerFirst]
reader[readerFirst] = nil
readerFirst = readerFirst + 1
assert(coroutine.resume(thread, unpack(data)))
else
queue[queueLast] = data
queueLast = queueLast + 1
if not paused then
paused = true
assert(socket:read_stop())
end
end
end
return function ()
if queueFirst < queueLast then
local data = queue[queueFirst]
queue[queueFirst] = nil
queueFirst = queueFirst + 1
return unpack(data)
end
if paused then
paused = false
assert(socket:read_start(onRead))
end
reader[readerLast] = coroutine.running()
readerLast = readerLast + 1
return coroutine.yield()
end
end
local function wrapWrite(socket)
local function wait()
local thread = coroutine.running()
return function (err)
assert(coroutine.resume(thread, err))
end
end
local function shutdown()
socket:shutdown(wait())
coroutine.yield()
if not socket:is_closing() then
socket:close()
end
end
return function (chunk)
if chunk == nil then
return shutdown()
end
assert(socket:write(chunk, wait()))
local err = coroutine.yield()
return not err, err
end
end
exports.wrapRead = wrapRead
exports.wrapWrite = wrapWrite
-- Given a raw uv_stream_t userdata, return coro-friendly read/write functions.
function exports.wrapStream(socket)
return wrapRead(socket), wrapWrite(socket)
end
function exports.chain(...)
local args = {...}
local nargs = select("#", ...)
return function (read, write)
local threads = {} -- coroutine thread for each item
local waiting = {} -- flag when waiting to pull from upstream
local boxes = {} -- storage when waiting to write to downstream
for i = 1, nargs do
threads[i] = coroutine.create(args[i])
waiting[i] = false
local r, w
if i == 1 then
r = read
else
function r()
local j = i - 1
if boxes[j] then
local data = boxes[j]
boxes[j] = nil
assert(coroutine.resume(threads[j]))
return unpack(data)
else
waiting[i] = true
return coroutine.yield()
end
end
end
if i == nargs then
w = write
else
function w(...)
local j = i + 1
if waiting[j] then
waiting[j] = false
assert(coroutine.resume(threads[j], ...))
else
boxes[i] = {...}
coroutine.yield()
end
end
end
assert(coroutine.resume(threads[i], r, w))
end
end
end
|
Optimize and fix bug in coro-channel read queues
|
Optimize and fix bug in coro-channel read queues
|
Lua
|
apache-2.0
|
zhaozg/lit,luvit/lit,james2doyle/lit,squeek502/lit
|
cbea73ce70ea374a93478e4c4580a8a723051f00
|
quest/pasinn_539_wilderness.lua
|
quest/pasinn_539_wilderness.lua
|
--[[
Illarion Server
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License as published by the Free
Software Foundation, either version 3 of the License, or (at your option) any
later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU Affero General Public License for more
details.
You should have received a copy of the GNU Affero General Public License along
with this program. If not, see <http://www.gnu.org/licenses/>.
]]
-- INSERT INTO "quests" ("qst_id", "qst_script") VALUES (539, 'quest.pasinn_539_wilderness');
local common = require("base.common")
local M = {}
local GERMAN = Player.german
local ENGLISH = Player.english
-- Insert the quest title here, in both languages
local Title = {}
Title[GERMAN] = "Viridian Nadeln Hhle"
Title[ENGLISH] = "Viridian Needles Lair"
-- Insert an extensive description of each status here, in both languages
-- Make sure that the player knows exactly where to go and what to do
local Description = {}
Description[GERMAN] = {}
Description[ENGLISH] = {}
Description[GERMAN][1] = "Sammle fnfzehn vergiftete Mnzen in Viridian Needles Schlupfwinkel, wo der Alchemist Kaefity arbeitet."
Description[ENGLISH][1] = "Collect fifteen poisoned coins from Viridian Needles Lair where the Alchemist Kaefity is working."
Description[GERMAN][2] = "Kehre zu Pasinn zurck, er wird sicher noch eine Aufgabe fr dich haben."
Description[ENGLISH][2] = "Go back to Pasinn, he will certainly have another task for you."
Description[GERMAN][3] = "Finde den richtigen Trank aus den Kesseln in Viridian Needles Schlupfwinkel, den Pasinn haben mchte."
Description[ENGLISH][3] = "Find the proper potion that Pasinn is wanting from the Cauldrons in Viridian Needles Lair."
Description[GERMAN][4] = "Kehre zu Pasinn zurck, er wird sicher noch eine Aufgabe fr dich haben."
Description[ENGLISH][4] = "Go back to Pasinn, he will certainly have another task for you."
Description[GERMAN][5] = "Such nach Kaefitys Rezept fr den Trank, den du fr Pasinn gefunden hast. Es sollte irgendwo im Schlupfwinkel herumliegen."
Description[ENGLISH][5] = "Locate Kaefity's recipe for the potion that you found for Pasinn. It should be laying around the lair somewhere."
Description[GERMAN][6] = "Kehre zu Pasinn zurck, du hast seine Aufgabe erfllt."
Description[ENGLISH][6] = "Return to Pasinn, you have finished his task."
Description[GERMAN][7] = "Kehre zu Pasinn zurck, er wird sicher noch eine Aufgabe fr dich haben."
Description[ENGLISH][7] = "Go back to Pasinn, he will certainly have another task for you."
Description[GERMAN][8] = "Tte Kaefitys Haustier, das Sumpfmonster, fr Pasinn."
Description[ENGLISH][8] = "Kill Kaefity's pet swamp beast for Pasinn."
Description[GERMAN][9] = "Kehre zu Pasinn zurck, du hast seine Aufgabe erfllt."
Description[ENGLISH][9] = "Return to Pasinn, you have finished his task."
Description[GERMAN][10] = "Kehre zu Pasinn zurck, er wird sicher noch eine Aufgabe fr dich haben."
Description[ENGLISH][10] = "Go back to Pasinn, he will certainly have another task for you."
Description[GERMAN][11] = "Tte die Rattenalchemisten Kaefity fr Pasinn."
Description[ENGLISH][11] = "Kill Kaefity the Rat Alchemist for Pasinn."
Description[GERMAN][12] = "Kehre zu Pasinn zurck, du hast seine Aufgabe erfllt."
Description[ENGLISH][12] = "Return to Pasinn, you have finished his task."
Description[GERMAN][13] = "Du hast alle Aufgaben von Pasinn erfllt."
Description[ENGLISH][13] = "You have fulfilled all the tasks for Pasinn."
-- Insert the position of the quest start here (probably the position of an NPC or item)
local Start = {523, 205, 0}
-- For each status insert a list of positions where the quest will continue, i.e. a new status can be reached there
local QuestTarget = {}
QuestTarget[1] = {position(523, 205, 0), position(522, 205, 0)} -- Viridian Needles Lair
QuestTarget[2] = {position(523, 205, 0)}
QuestTarget[3] = {position(523, 205, 0), position(522, 205, 0)} -- Viridian Needles Lair
QuestTarget[4] = {position(840, 470, 0)}
QuestTarget[5] = {position(523, 205, 0), position(522, 205, 0)} -- Viridian Needles Lair
QuestTarget[6] = {position(840, 470, 0)}
QuestTarget[7] = {position(523, 205, 0)}
QuestTarget[8] = {position(523, 205, 0), position(522, 205, 0)} -- Viridian Needles Lair
QuestTarget[9] = {position(523, 205, 0)}
QuestTarget[10] = {position(523, 205, 0)}
QuestTarget[11] = {position(523, 205, 0), position(522, 205, 0)} -- Viridian Needles Lair
QuestTarget[12] = {position(523, 205, 0)}
QuestTarget[13] = {position(523, 205, 0)}
-- Insert the quest status which is reached at the end of the quest
local FINAL_QUEST_STATUS = 13
-- Register the monster kill parts of the quest.
monsterQuests.addQuest{
questId = 539,
location = {position = position(575, 190, -3), radius = 75},
queststatus = {from = 8, to = 9},
questTitle = {german = "Viridian Nadeln Hhle IV", english = "Viridian Needles Lair IV"},
monsterName = {german = "Sumpfmonster", english = "Swamp Monster"},
npcName = "Pasinn",
raceIds = {872} -- swamp beast
}
monsterQuests.addQuest{
questId = 539,
location = {position = position(575, 190, -3), radius = 75},
queststatus = {from = 11, to = 12},
questTitle = {german = "Viridian Nadeln Hhle V", english = "Viridian Needles Lair V"},
monsterName = {german = "Rattenalchemist", english = "Rat Alchemist"},
npcName = "Pasinn",
raceIds = {877} -- Rat Alchemist
}
function M.QuestTitle(user)
return common.GetNLS(user, Title[GERMAN], Title[ENGLISH])
end
function M.QuestDescription(user, status)
local german = Description[GERMAN][status] or ""
local english = Description[ENGLISH][status] or ""
return common.GetNLS(user, german, english)
end
function M.QuestStart()
return Start
end
function M.QuestTargets(user, status)
return QuestTarget[status]
end
function M.QuestFinalStatus()
return FINAL_QUEST_STATUS
end
return M
|
--[[
Illarion Server
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License as published by the Free
Software Foundation, either version 3 of the License, or (at your option) any
later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU Affero General Public License for more
details.
You should have received a copy of the GNU Affero General Public License along
with this program. If not, see <http://www.gnu.org/licenses/>.
]]
-- INSERT INTO "quests" ("qst_id", "qst_script") VALUES (539, 'quest.pasinn_539_wilderness');
local common = require("base.common")
local M = {}
local GERMAN = Player.german
local ENGLISH = Player.english
-- Insert the quest title here, in both languages
local Title = {}
Title[GERMAN] = "Viridian Nadeln Hhle"
Title[ENGLISH] = "Viridian Needles Lair"
-- Insert an extensive description of each status here, in both languages
-- Make sure that the player knows exactly where to go and what to do
local Description = {}
Description[GERMAN] = {}
Description[ENGLISH] = {}
Description[GERMAN][1] = "Sammle fnfzehn vergiftete Mnzen in Viridian Needles Schlupfwinkel, wo der Alchemist Kaefity arbeitet."
Description[ENGLISH][1] = "Collect fifteen poisoned coins from Viridian Needles Lair where the Alchemist Kaefity is working."
Description[GERMAN][2] = "Kehre zu Pasinn zurck, er wird sicher noch eine Aufgabe fr dich haben."
Description[ENGLISH][2] = "Go back to Pasinn, he will certainly have another task for you."
Description[GERMAN][3] = "Finde den richtigen Trank aus den Kesseln in Viridian Needles Schlupfwinkel, den Pasinn haben mchte."
Description[ENGLISH][3] = "Find the proper potion that Pasinn is wanting from the Cauldrons in Viridian Needles Lair."
Description[GERMAN][4] = "Kehre zu Pasinn zurck, er wird sicher noch eine Aufgabe fr dich haben."
Description[ENGLISH][4] = "Go back to Pasinn, he will certainly have another task for you."
Description[GERMAN][5] = "Such nach Kaefitys Rezept fr den Trank, den du fr Pasinn gefunden hast. Es sollte irgendwo im Schlupfwinkel herumliegen."
Description[ENGLISH][5] = "Locate Kaefity's recipe for the potion that you found for Pasinn. It should be laying around the lair somewhere."
Description[GERMAN][6] = "Kehre zu Pasinn zurck, du hast seine Aufgabe erfllt."
Description[ENGLISH][6] = "Return to Pasinn, you have finished his task."
Description[GERMAN][7] = "Kehre zu Pasinn zurck, er wird sicher noch eine Aufgabe fr dich haben."
Description[ENGLISH][7] = "Go back to Pasinn, he will certainly have another task for you."
Description[GERMAN][8] = "Tte Kaefitys Haustier, das Sumpfmonster, fr Pasinn."
Description[ENGLISH][8] = "Kill Kaefity's pet swamp beast for Pasinn."
Description[GERMAN][9] = "Kehre zu Pasinn zurck, du hast seine Aufgabe erfllt."
Description[ENGLISH][9] = "Return to Pasinn, you have finished his task."
Description[GERMAN][10] = "Kehre zu Pasinn zurck, er wird sicher noch eine Aufgabe fr dich haben."
Description[ENGLISH][10] = "Go back to Pasinn, he will certainly have another task for you."
Description[GERMAN][11] = "Tte die Rattenalchemisten Kaefity fr Pasinn."
Description[ENGLISH][11] = "Kill Kaefity the Rat Alchemist for Pasinn."
Description[GERMAN][12] = "Kehre zu Pasinn zurck, du hast seine Aufgabe erfllt."
Description[ENGLISH][12] = "Return to Pasinn, you have finished his task."
Description[GERMAN][13] = "Du hast alle Aufgaben von Pasinn erfllt."
Description[ENGLISH][13] = "You have fulfilled all the tasks for Pasinn."
-- Insert the position of the quest start here (probably the position of an NPC or item)
local Start = {523, 205, 0}
-- For each status insert a list of positions where the quest will continue, i.e. a new status can be reached there
local QuestTarget = {}
QuestTarget[1] = {position(523, 205, 0), position(522, 205, 0)} -- Viridian Needles Lair
QuestTarget[2] = {position(523, 205, 0)}
QuestTarget[3] = {position(523, 205, 0), position(522, 205, 0)} -- Viridian Needles Lair
QuestTarget[4] = {position(840, 470, 0)}
QuestTarget[5] = {position(523, 205, 0), position(522, 205, 0)} -- Viridian Needles Lair
QuestTarget[6] = {position(840, 470, 0)}
QuestTarget[7] = {position(523, 205, 0)}
QuestTarget[8] = {position(523, 205, 0), position(522, 205, 0)} -- Viridian Needles Lair
QuestTarget[9] = {position(523, 205, 0)}
QuestTarget[10] = {position(523, 205, 0)}
QuestTarget[11] = {position(523, 205, 0), position(522, 205, 0)} -- Viridian Needles Lair
QuestTarget[12] = {position(523, 205, 0)}
QuestTarget[13] = {position(523, 205, 0)}
-- Insert the quest status which is reached at the end of the quest
local FINAL_QUEST_STATUS = 13
-- Register the monster kill parts of the quest.
monsterQuests.addQuest{
questId = 539,
location = {position = position(575, 190, -3), radius = 75},
queststatus = {from = 8, to = 9},
questTitle = {german = Title[GERMAN], english = Title[ENGLISH]},
monsterName = {german = "Sumpfmonster", english = "Swamp Monster"},
npcName = "Pasinn",
raceIds = {872} -- swamp beast
}
monsterQuests.addQuest{
questId = 539,
location = {position = position(575, 190, -3), radius = 75},
queststatus = {from = 11, to = 12},
questTitle = {german = Title[GERMAN], english = Title[ENGLISH]},
monsterName = {german = "Rattenalchemist", english = "Rat Alchemist"},
npcName = "Pasinn",
raceIds = {877} -- Rat Alchemist
}
function M.QuestTitle(user)
return common.GetNLS(user, Title[GERMAN], Title[ENGLISH])
end
function M.QuestDescription(user, status)
local german = Description[GERMAN][status] or ""
local english = Description[ENGLISH][status] or ""
return common.GetNLS(user, german, english)
end
function M.QuestStart()
return Start
end
function M.QuestTargets(user, status)
return QuestTarget[status]
end
function M.QuestFinalStatus()
return FINAL_QUEST_STATUS
end
return M
|
fix quest log error
|
fix quest log error
|
Lua
|
agpl-3.0
|
Baylamon/Illarion-Content,KayMD/Illarion-Content,Illarion-eV/Illarion-Content,vilarion/Illarion-Content
|
ec1347e86944f47ed9cd246407c9f7fe8ac91e46
|
lua/entities/gmod_wire_expression2/core/sound.lua
|
lua/entities/gmod_wire_expression2/core/sound.lua
|
/******************************************************************************\
Built-in Sound support v1.18
\******************************************************************************/
E2Lib.RegisterExtension("sound", true)
local wire_expression2_maxsounds = CreateConVar( "wire_expression2_maxsounds", 16 )
local wire_expression2_sound_burst_max = CreateConVar( "wire_expression2_sound_burst_max", 8 )
local wire_expression2_sound_burst_rate = CreateConVar( "wire_expression2_sound_burst_rate", 0.1 )
---------------------------------------------------------------
-- Helper functions
---------------------------------------------------------------
local function isAllowed( self )
local data = self.data.sound_data
local count = data.count
if count == wire_expression2_maxsounds:GetInt() then return false end
if data.burst == 0 then return false end
data.burst = data.burst - 1
local timerid = "E2_sound_burst_count_" .. self.entity:EntIndex()
if not timer.Exists( timerid ) then
timer.Create( timerid, wire_expression2_sound_burst_rate:GetFloat(), 0, function()
if not IsValid( self.entity ) then
timer.Remove( timerid )
return
end
data.burst = data.burst + 1
if data.burst == wire_expression2_sound_burst_max:GetInt() then
timer.Remove( timerid )
end
end)
end
return true
end
local function getSound( self, index )
if isnumber( index ) then index = math.floor( index ) end
return self.data.sound_data.sounds[index]
end
local function soundStop(self, index, fade)
local sound = getSound( self, index )
if not sound then return end
fade = math.abs( fade )
if fade == 0 then
sound:Stop()
else
sound:FadeOut( fade )
end
if isnumber( index ) then index = math.floor( index ) end
self.data.sound_data.sounds[index] = nil
self.data.sound_data.count = self.data.sound_data.count - 1
end
local function soundCreate(self, entity, index, time, path, fade)
if path:match('["?]') then return end
local data = self.data.sound_data
if not isAllowed( self ) then return end
path = path:Trim()
path = path:gsub( "\\", "/" )
if isnumber( index ) then index = math.floor( index ) end
local sound = getSound( self, index )
if sound then
sound:Stop()
else
data.count = data.count + 1
end
local sound = CreateSound( entity, path )
data.sounds[index] = sound
sound:Play()
entity:CallOnRemove( "E2_stopsound", function()
if IsValid( sound ) then sound:Stop() end
end )
if time == 0 and fade == 0 then return end
time = math.abs( time )
timer.Simple( time, function()
if not IsValid( self ) or not IsValid( entity ) then return end
soundStop( self, index, fade )
end)
end
local function soundPurge( self )
local sound_data = self.data.sound_data
if sound_data.sounds then
for k,v in pairs( sound_data.sounds ) do
v:Stop()
end
end
sound_data.sounds = {}
sound_data.count = 0
end
---------------------------------------------------------------
-- Play functions
---------------------------------------------------------------
__e2setcost(25)
e2function void soundPlay( index, duration, string path )
soundCreate(self,self.entity,index,duration,path,0)
end
e2function void entity:soundPlay( index, duration, string path)
if not IsValid(this) or not isOwner(self, this) then return end
soundCreate(self,this,index,duration,path,0)
end
e2function void soundPlay( index, duration, string path, fade )
soundCreate(self,self.entity,index,duration,path,fade)
end
e2function void entity:soundPlay( index, duration, string path, fade )
if not IsValid(this) or not isOwner(self, this) then return end
soundCreate(self,this,index,duration,path,fade)
end
e2function void soundPlay( string index, duration, string path ) = e2function void soundPlay( index, duration, string path )
e2function void entity:soundPlay( string index, duration, string path ) = e2function void entity:soundPlay( index, duration, string path )
e2function void soundPlay( string index, duration, string path, fade ) = e2function void soundPlay( index, duration, string path, fade )
e2function void entity:soundPlay( string index, duration, string path, fade ) = e2function void entity:soundPlay( index, duration, string path, fade )
---------------------------------------------------------------
-- Modifier functions
---------------------------------------------------------------
__e2setcost(5)
e2function void soundStop( index )
soundStop(self, index, 0)
end
e2function void soundStop( index, fadetime )
soundStop(self, index, fadetime)
end
e2function void soundVolume( index, volume )
local sound = getSound( self, index )
if not sound then return end
sound:ChangeVolume( math.Clamp( volume, 0, 1 ), 0 )
end
e2function void soundVolume( index, volume, fadetime )
local sound = getSound( self, index )
if not sound then return end
sound:ChangeVolume( math.Clamp( volume, 0, 1 ), math.abs( fadetime ) )
end
e2function void soundPitch( index, pitch )
local sound = getSound( self, index )
if not sound then return end
sound:ChangePitch( math.Clamp( pitch, 0, 255 ), 0 )
end
e2function void soundPitch( index, pitch, fadetime )
local sound = getSound( self, index )
if not sound then return end
sound:ChangePitch( math.Clamp( pitch, 0, 255 ), math.abs( fadetime ) )
end
e2function void soundStop( string index ) = e2function void soundStop( index )
e2function void soundStop( string index, fadetime ) = e2function void soundStop( index, fadetime )
e2function void soundVolume( string index, volume ) = e2function void soundVolume( index, volume )
e2function void soundVolume( string index, volume, fadetime ) = e2function void soundVolume( index, volume, fadetime )
e2function void soundPitch( string index, pitch ) = e2function void soundPitch( index, pitch )
e2function void soundPitch( string index, pitch, fadetime ) = e2function void soundPitch( index, pitch, fadetime )
---------------------------------------------------------------
-- Other
---------------------------------------------------------------
e2function void soundPurge()
soundPurge( self )
end
e2function number soundDuration(string sound)
return SoundDuration(sound) or 0
end
---------------------------------------------------------------
registerCallback("construct", function(self)
self.data.sound_data = {}
self.data.sound_data.burst = wire_expression2_sound_burst_max:GetInt()
self.data.sound_data.sounds = {}
self.data.sound_data.count = 0
end)
registerCallback("destruct", function(self)
soundPurge( self )
end)
|
/******************************************************************************\
Built-in Sound support v1.18
\******************************************************************************/
E2Lib.RegisterExtension("sound", true)
local wire_expression2_maxsounds = CreateConVar( "wire_expression2_maxsounds", 16 )
local wire_expression2_sound_burst_max = CreateConVar( "wire_expression2_sound_burst_max", 8 )
local wire_expression2_sound_burst_rate = CreateConVar( "wire_expression2_sound_burst_rate", 0.1 )
---------------------------------------------------------------
-- Helper functions
---------------------------------------------------------------
local function isAllowed( self )
local data = self.data.sound_data
local count = data.count
if count == wire_expression2_maxsounds:GetInt() then return false end
if data.burst == 0 then return false end
data.burst = data.burst - 1
local timerid = "E2_sound_burst_count_" .. self.entity:EntIndex()
if not timer.Exists( timerid ) then
timer.Create( timerid, wire_expression2_sound_burst_rate:GetFloat(), 0, function()
if not IsValid( self.entity ) then
timer.Remove( timerid )
return
end
data.burst = data.burst + 1
if data.burst == wire_expression2_sound_burst_max:GetInt() then
timer.Remove( timerid )
end
end)
end
return true
end
local function getSound( self, index )
if isnumber( index ) then index = math.floor( index ) end
return self.data.sound_data.sounds[index]
end
local function soundStop(self, index, fade)
local sound = getSound( self, index )
if not sound then return end
fade = math.abs( fade )
if fade == 0 then
sound:Stop()
else
sound:FadeOut( fade )
end
if isnumber( index ) then index = math.floor( index ) end
self.data.sound_data.sounds[index] = nil
self.data.sound_data.count = self.data.sound_data.count - 1
timer.Remove( "E2_sound_stop_" .. self.entity:EntIndex() .. "_" .. index )
end
local function soundCreate(self, entity, index, time, path, fade)
if path:match('["?]') then return end
local data = self.data.sound_data
if not isAllowed( self ) then return end
path = path:Trim()
path = path:gsub( "\\", "/" )
if isnumber( index ) then index = math.floor( index ) end
local timerid = "E2_sound_stop_" .. self.entity:EntIndex() .. "_" .. index
local sound = getSound( self, index )
if sound then
sound:Stop()
timer.Remove( timerid )
else
data.count = data.count + 1
end
local sound = CreateSound( entity, path )
data.sounds[index] = sound
sound:Play()
entity:CallOnRemove( "E2_stopsound", function()
soundStop( self, index, 0 )
end )
if time == 0 and fade == 0 then return end
time = math.abs( time )
timer.Create( timerid, time, 1, function()
if not self or not IsValid( self.entity ) or not IsValid( entity ) then return end
soundStop( self, index, fade )
end)
end
local function soundPurge( self )
local sound_data = self.data.sound_data
if sound_data.sounds then
for k,v in pairs( sound_data.sounds ) do
v:Stop()
timer.Remove( "E2_sound_stop_" .. self.entity:EntIndex() .. "_" .. k )
end
end
sound_data.sounds = {}
sound_data.count = 0
end
---------------------------------------------------------------
-- Play functions
---------------------------------------------------------------
__e2setcost(25)
e2function void soundPlay( index, duration, string path )
soundCreate(self,self.entity,index,duration,path,0)
end
e2function void entity:soundPlay( index, duration, string path)
if not IsValid(this) or not isOwner(self, this) then return end
soundCreate(self,this,index,duration,path,0)
end
e2function void soundPlay( index, duration, string path, fade )
soundCreate(self,self.entity,index,duration,path,fade)
end
e2function void entity:soundPlay( index, duration, string path, fade )
if not IsValid(this) or not isOwner(self, this) then return end
soundCreate(self,this,index,duration,path,fade)
end
e2function void soundPlay( string index, duration, string path ) = e2function void soundPlay( index, duration, string path )
e2function void entity:soundPlay( string index, duration, string path ) = e2function void entity:soundPlay( index, duration, string path )
e2function void soundPlay( string index, duration, string path, fade ) = e2function void soundPlay( index, duration, string path, fade )
e2function void entity:soundPlay( string index, duration, string path, fade ) = e2function void entity:soundPlay( index, duration, string path, fade )
---------------------------------------------------------------
-- Modifier functions
---------------------------------------------------------------
__e2setcost(5)
e2function void soundStop( index )
soundStop(self, index, 0)
end
e2function void soundStop( index, fadetime )
soundStop(self, index, fadetime)
end
e2function void soundVolume( index, volume )
local sound = getSound( self, index )
if not sound then return end
sound:ChangeVolume( math.Clamp( volume, 0, 1 ), 0 )
end
e2function void soundVolume( index, volume, fadetime )
local sound = getSound( self, index )
if not sound then return end
sound:ChangeVolume( math.Clamp( volume, 0, 1 ), math.abs( fadetime ) )
end
e2function void soundPitch( index, pitch )
local sound = getSound( self, index )
if not sound then return end
sound:ChangePitch( math.Clamp( pitch, 0, 255 ), 0 )
end
e2function void soundPitch( index, pitch, fadetime )
local sound = getSound( self, index )
if not sound then return end
sound:ChangePitch( math.Clamp( pitch, 0, 255 ), math.abs( fadetime ) )
end
e2function void soundStop( string index ) = e2function void soundStop( index )
e2function void soundStop( string index, fadetime ) = e2function void soundStop( index, fadetime )
e2function void soundVolume( string index, volume ) = e2function void soundVolume( index, volume )
e2function void soundVolume( string index, volume, fadetime ) = e2function void soundVolume( index, volume, fadetime )
e2function void soundPitch( string index, pitch ) = e2function void soundPitch( index, pitch )
e2function void soundPitch( string index, pitch, fadetime ) = e2function void soundPitch( index, pitch, fadetime )
---------------------------------------------------------------
-- Other
---------------------------------------------------------------
e2function void soundPurge()
soundPurge( self )
end
e2function number soundDuration(string sound)
return SoundDuration(sound) or 0
end
---------------------------------------------------------------
registerCallback("construct", function(self)
self.data.sound_data = {}
self.data.sound_data.burst = wire_expression2_sound_burst_max:GetInt()
self.data.sound_data.sounds = {}
self.data.sound_data.count = 0
end)
registerCallback("destruct", function(self)
soundPurge( self )
end)
|
Fixed sounds not stopping correctly after the specified time
|
Fixed sounds not stopping correctly after the specified time
The stopping would leak over into new sounds with the same index
|
Lua
|
apache-2.0
|
sammyt291/wire,immibis/wiremod,wiremod/wire,mitterdoo/wire,thegrb93/wire,Grocel/wire,notcake/wire,Python1320/wire,mms92/wire,plinkopenguin/wiremod,rafradek/wire,NezzKryptic/Wire,garrysmodlua/wire,dvdvideo1234/wire,bigdogmat/wire,CaptainPRICE/wire
|
4b2aeceb5d11d31ca758a80cf079cb2e6aa17977
|
lua/plugins/lsp.lua
|
lua/plugins/lsp.lua
|
local nvim = require('nvim')
local plugs = require('nvim').plugs
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({})
if language ~= 'latex' or plugs['vimtex'] == nil then -- Use vimtex function instead
available_languages[#available_languages + 1] = language
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> 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 plugs = require('nvim').plugs
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) == 1 then
lsp[option].setup({})
if language ~= 'latex' or plugs['vimtex'] == nil then -- Use vimtex function instead
available_languages[#available_languages + 1] = language
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> 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(
'CursorHold',
available_languages,
"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'}
)
|
fix: small changes for lsp settings
|
fix: small changes for lsp settings
Fix executable check for language server executables
Add new CursorHold event
|
Lua
|
mit
|
Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim
|
6958bd0dafd24ae5b6cd703ffe6579e1884a52bc
|
core/length.lua
|
core/length.lua
|
local _length
_length = std.object {
length = 0,
stretch = 0,
shrink = 0,
_type = "Length",
fromLengthOrNumber = function (self, x)
if type(x) == "table" then
self.length = x.length
self.stretch = x.stretch
self.shrink = x.shrink
else
self.length = x
end
return self
end,
__tostring = function (x)
local s = tostring(x.length).."pt"
if x.stretch ~= 0 then s = s .. " plus "..x.stretch.."pt" end
if x.shrink ~= 0 then s = s .. " minus "..x.shrink.."pt" end
return s
end,
__add = function (self, other)
local result = _length {}
result:fromLengthOrNumber(self)
if type(other) == "table" then
result.length = result.length + other.length
result.stretch = result.stretch + other.stretch
result.shrink = result.shrink + other.shrink
else
result.length = result.length + other
end
return result
end,
__sub = function (self, other)
local result = _length {}
result:fromLengthOrNumber(self)
if type(other) == "table" then
result.length = result.length - other.length
result.stretch = result.stretch - other.stretch
result.shrink = result.shrink - other.shrink
else
result.length = result.length - other
end
return result
end,
__lt = function (self, other)
return (self-other).length < 0
end,
}
local length = {
new = function (spec)
return _length(spec or {})
end,
parse = function (spec)
if not spec then return _length {} end
local t = lpeg.match(SILE.parserBits.length, spec)
if not t then SU.error("Bad length definition '"..spec.."'") end
if not t.shrink then t.shrink = 0 end
if not t.stretch then t.stretch = 0 end
return _length(t)
end,
zero = _length {}
}
return length
|
local _length
_length = std.object {
length = 0,
stretch = 0,
shrink = 0,
_type = "Length",
fromLengthOrNumber = function (self, x)
if type(x) == "table" then
self.length = x.length
self.stretch = x.stretch
self.shrink = x.shrink
else
self.length = x
end
return self
end,
__tostring = function (x)
local s = tostring(x.length).."pt"
if x.stretch ~= 0 then s = s .. " plus "..x.stretch.."pt" end
if x.shrink ~= 0 then s = s .. " minus "..x.shrink.."pt" end
return s
end,
__add = function (self, other)
local result = _length {}
result:fromLengthOrNumber(self)
if type(other) == "table" then
result.length = result.length + other.length
result.stretch = result.stretch + other.stretch
result.shrink = result.shrink + other.shrink
else
result.length = result.length + other
end
return result
end,
__sub = function (self, other)
local result = _length {}
result:fromLengthOrNumber(self)
if type(other) == "table" then
result.length = result.length - other.length
result.stretch = result.stretch - other.stretch
result.shrink = result.shrink - other.shrink
else
result.length = result.length - other
end
return result
end,
-- __mul = function(self, other)
-- local result = _length {}
-- result:fromLengthOrNumber(self)
-- if type(other) == "table" then
-- SU.error("Attempt to multiply two lengths together")
-- else
-- result.length = result.length * other
-- result.stretch = result.stretch * other
-- result.shrink = result.shrink * other
-- end
-- return result
-- end,
__lt = function (self, other)
return (self-other).length < 0
end,
}
local length = {
new = function (spec)
return _length(spec or {})
end,
parse = function (spec)
if not spec then return _length {} end
local t = lpeg.match(SILE.parserBits.length, spec)
if not t then SU.error("Bad length definition '"..spec.."'") end
if not t.shrink then t.shrink = 0 end
if not t.stretch then t.stretch = 0 end
return _length(t)
end,
zero = _length {}
}
return length
|
I thought I needed this. Don’t. Keeping it for later. Commented out now because multiplying a length is currently a bug.
|
I thought I needed this. Don’t. Keeping it for later. Commented out now because multiplying a length is currently a bug.
|
Lua
|
mit
|
WAKAMAZU/sile_fe,neofob/sile,WAKAMAZU/sile_fe,alerque/sile,Nathan22Miles/sile,anthrotype/sile,shirat74/sile,neofob/sile,anthrotype/sile,alerque/sile,Nathan22Miles/sile,alerque/sile,neofob/sile,anthrotype/sile,simoncozens/sile,WAKAMAZU/sile_fe,shirat74/sile,Nathan22Miles/sile,simoncozens/sile,shirat74/sile,Nathan22Miles/sile,simoncozens/sile,WAKAMAZU/sile_fe,simoncozens/sile,Nathan22Miles/sile,alerque/sile,shirat74/sile,neofob/sile,anthrotype/sile
|
616d5a51c18cf3f0d2d7f52fc395e485aaeab91f
|
libs/term.lua
|
libs/term.lua
|
local prev, pl, luv, dir, T, stdin, exit_seq = ...
local _colors = {
[1] = "white";
[2] = "orange";
[4] = "magenta";
[8] = "lightBlue";
[16] = "yellow";
[32] = "lime";
[64] = "pink";
[128] = "gray";
[256] = "lightGray";
[512] = "cyan";
[1024] = "purple";
[2048] = "blue";
[4096] = "brown";
[8192] = "green";
[16384] = "red";
[32768] = "black";
}
local color_escapes = {
fg = {
white = T.setaf(7);
orange = T.setaf(3);
magenta = T.setaf(5);
lightBlue = T.setaf(4);
yellow = T.setaf(3);
lime = T.setaf(2);
pink = T.setaf(5);
gray = T.setaf(0);
lightGray = T.setaf(0);
cyan = T.setaf(6);
purple = T.setaf(5);
blue = T.setaf(4);
brown = T.setaf(3);
green = T.setaf(2);
red = T.setaf(1);
black = T.setaf(0);
};
bg = {
white = T.setab(7);
orange = T.setab(3);
magenta = T.setab(5);
lightBlue = T.setab(4);
yellow = T.setab(3);
lime = T.setab(2);
pink = T.setab(5);
gray = T.setab(0);
lightGray = T.setab(0);
cyan = T.setab(6);
purple = T.setab(5);
blue = T.setab(4);
brown = T.setab(3);
green = T.setab(2);
red = T.setab(1);
black = T.setab(0);
};
}
do
local fg_dir = pl.path.join(dir, '.termu', 'term-colors', 'fg')
if pl.path.isdir(fg_dir) then
for color in pl.path.dir(fg_dir) do
local path = pl.path.join(fg_dir, color)
if id ~= '.' and id ~= '..' and pl.path.isfile(path) then
local h = prev.io.open(path)
color_escapes.fg[color] = h:read '*a'
h:close()
end
end
end
local bg_dir = pl.path.join(dir, '.termu', 'term-colors', 'bg')
if pl.path.isdir(bg_dir) then
for color in pl.path.dir(bg_dir) do
local path = pl.path.join(bg_dir, color)
if id ~= '.' and id ~= '..' and pl.path.isfile(path) then
local h = prev.io.open(path)
color_escapes.bg[color] = h:read '*a'
h:close()
end
end
end
end
local hex = {
['a'] = 10;
['b'] = 11;
['c'] = 12;
['d'] = 13;
['e'] = 14;
['f'] = 15;
}
for i = 0, 9 do
hex[tostring(i)] = i
end
local cursorX, cursorY = 1, 1
local cursorBlink = true
local textColor, backColor = 0, 15
local log2 = math.log(2)
local function ccColorFor(c)
if type(c) ~= 'number' or c < 0 or c > 15 then
error('that\'s not a valid color: ' .. tostring(c))
end
return math.pow(2, c)
end
local function fromHexColor(h)
return hex[h] or error('not a hex color: ' .. tostring(h))
end
local processOutput
if pl.path.exists(pl.path.join(dir, '.termu', 'term-munging')) then
local utf8 = prev.utf8 or prev.require 'utf8'
function processOutput(out)
local res = ''
for c in out:gmatch '.' do
if c == '\0' or c == '\9' or c == '\10' or c == '\13' or c == '\32' or c == '\128' or c == '\160' then
res = res .. c
else
res = res .. utf8.char(0xE000 + c:byte())
end
end
return res
end
else
function processOutput(out)
return out
end
end
local termNat
termNat = {
clear = function()
local w, h = termNat.getSize()
for l = 0, h - 1 do
prev.io.write(T.cup(l, 0))
prev.io.write((' '):rep(w))
end
termNat.setCursorPos(cursorX, cursorY)
end;
clearLine = function()
local w, h = termNat.getSize()
prev.io.write(T.cup(cursorY - 1, 0))
prev.io.write((' '):rep(w))
termNat.setCursorPos(cursorX, cursorY)
end;
isColour = function() return true end;
isColor = function() return true end;
getSize = function()
return luv.tty_get_winsize(stdin)
-- return 52, 19
end;
getCursorPos = function() return cursorX, cursorY end;
setCursorPos = function(x, y)
if type(x) ~= 'number' or type(y) ~= 'number' then error('term.setCursorPos expects number, number, got: ' .. type(x) .. ', ' .. type(y)) end
local oldX, oldY = cursorX, cursorY
cursorX, cursorY = math.floor(x), math.floor(y)
termNat.setCursorBlink(cursorBlink)
local w, h = luv.tty_get_winsize(stdin)
if cursorY >= 1 and cursorY <= h and cursorX <= w then
prev.io.write(T.cup(cursorY - 1, math.max(0, cursorX - 1)))
end
end;
setTextColour = function(...) return termNat.setTextColor(...) end;
setTextColor = function(c)
textColor = math.log(c) / log2
prev.io.write(color_escapes.fg[_colors[c] ])
end;
getTextColour = function(...) return termNat.getTextColor(...) end;
getTextColor = function()
return ccColorFor(textColor)
end;
setBackgroundColour = function(...) return termNat.setBackgroundColor(...) end;
setBackgroundColor = function(c)
backColor = math.log(c) / log2
prev.io.write(color_escapes.bg[_colors[c] ])
end;
getBackgroundColour = function(...) return termNat.getBackgroundColor(...) end;
getBackgroundColor = function()
return ccColorFor(backColor)
end;
write = function(text)
text = tostring(text or '')
text = text:gsub('[\n\r]', '?')
local w, h = luv.tty_get_winsize(stdin)
if cursorY >= 1 and cursorY <= h and cursorX <= w then
if cursorX >= 1 then
prev.io.write(processOutput(text:sub(1, w - cursorX + 1)))
elseif cursorX > 1 - #text then
prev.io.write(processOutput(text:sub(-cursorX + 2)))
end
end
termNat.setCursorPos(cursorX + #text, cursorY)
end;
blit = function(text, textColors, backColors)
text = text:gsub('[\n\r]', '?')
if #text ~= #textColors or #text ~= #backColors then error('term.blit: text, textColors and backColors have to be the same length') end
local w, h = luv.tty_get_winsize(stdin)
if cursorY >= 1 and cursorY <= h and cursorX <= w then
local start
if cursorX >= 1 then
start = 1
elseif cursorX > 1 - #text then
start = -cursorX + 2
end
if start then
local fg, bg = textColor, backColor
for i = start, math.min(#text, w - cursorX + start) do
termNat.setTextColor(ccColorFor(fromHexColor(textColors:sub(i, i))))
termNat.setBackgroundColor(ccColorFor(fromHexColor(backColors:sub(i, i))))
prev.io.write(processOutput(text:sub(i, i)))
end
termNat.setTextColor(ccColorFor(fg))
termNat.setBackgroundColor(ccColorFor(bg))
end
end
termNat.setCursorPos(cursorX + #text, cursorY)
end;
setCursorBlink = function(blink)
cursorBlink = blink
local w, h = luv.tty_get_winsize(stdin)
if cursorBlink and cursorY >= 1 and cursorY <= h and cursorX >= 1 and cursorX <= w then
prev.io.write(T.cursor_normal())
else
prev.io.write(T.cursor_invisible())
end
end;
scroll = function(n)
n = n or 1
local w, h = luv.tty_get_winsize(stdin)
prev.io.write(n < 0 and T.cup(0, 0) or T.cup(h, w))
local txt = T[n < 0 and 'ri' or 'ind']()
prev.io.write(txt:rep(math.abs(n)))
-- if n > 0 then
-- prev.io.write(T.cup(h - n, 0))
-- prev.io.write(T.clr_eos())
-- elseif n < 0 then
-- for i = 0, n do
-- prev.io.write(T.cup(i, 0))
-- prev.io.write((' '):rep(w))
-- end
-- end
termNat.setCursorPos(cursorX, cursorY)
end
}
prev.io.write(T.smcup())
termNat.setTextColor(1)
termNat.setBackgroundColor(32768)
termNat.clear()
prev.io.flush()
exit_seq[#exit_seq + 1] = function()
prev.io.write(T.rmcup())
prev.io.flush()
end
return termNat
|
local prev, pl, luv, dir, T, stdin, exit_seq = ...
local _colors = {
[1] = "white";
[2] = "orange";
[4] = "magenta";
[8] = "lightBlue";
[16] = "yellow";
[32] = "lime";
[64] = "pink";
[128] = "gray";
[256] = "lightGray";
[512] = "cyan";
[1024] = "purple";
[2048] = "blue";
[4096] = "brown";
[8192] = "green";
[16384] = "red";
[32768] = "black";
}
local color_escapes = {
fg = {
white = T.setaf(7);
orange = T.setaf(3);
magenta = T.setaf(5);
lightBlue = T.setaf(4);
yellow = T.setaf(3);
lime = T.setaf(2);
pink = T.setaf(5);
gray = T.setaf(0);
lightGray = T.setaf(0);
cyan = T.setaf(6);
purple = T.setaf(5);
blue = T.setaf(4);
brown = T.setaf(3);
green = T.setaf(2);
red = T.setaf(1);
black = T.setaf(0);
};
bg = {
white = T.setab(7);
orange = T.setab(3);
magenta = T.setab(5);
lightBlue = T.setab(4);
yellow = T.setab(3);
lime = T.setab(2);
pink = T.setab(5);
gray = T.setab(0);
lightGray = T.setab(0);
cyan = T.setab(6);
purple = T.setab(5);
blue = T.setab(4);
brown = T.setab(3);
green = T.setab(2);
red = T.setab(1);
black = T.setab(0);
};
}
do
local fg_dir = pl.path.join(dir, '.termu', 'term-colors', 'fg')
if pl.path.isdir(fg_dir) then
for color in pl.path.dir(fg_dir) do
local path = pl.path.join(fg_dir, color)
if id ~= '.' and id ~= '..' and pl.path.isfile(path) then
local h = prev.io.open(path)
color_escapes.fg[color] = h:read '*a'
h:close()
end
end
end
local bg_dir = pl.path.join(dir, '.termu', 'term-colors', 'bg')
if pl.path.isdir(bg_dir) then
for color in pl.path.dir(bg_dir) do
local path = pl.path.join(bg_dir, color)
if id ~= '.' and id ~= '..' and pl.path.isfile(path) then
local h = prev.io.open(path)
color_escapes.bg[color] = h:read '*a'
h:close()
end
end
end
end
local hex = {
['a'] = 10;
['b'] = 11;
['c'] = 12;
['d'] = 13;
['e'] = 14;
['f'] = 15;
}
for i = 0, 9 do
hex[tostring(i)] = i
end
local cursorX, cursorY = 1, 1
local cursorBlink = true
local textColor, backColor = 0, 15
local log2 = math.log(2)
local function ccColorFor(c)
if type(c) ~= 'number' or c < 0 or c > 15 then
error('that\'s not a valid color: ' .. tostring(c))
end
return math.pow(2, c)
end
local function fromHexColor(h)
return hex[h] or error('not a hex color: ' .. tostring(h))
end
local processOutput
if pl.path.exists(pl.path.join(dir, '.termu', 'term-munging')) then
local utf8 = prev.utf8 or prev.require 'utf8'
function processOutput(out)
local res = ''
for c in out:gmatch '.' do
if c == '\0' or c == '\9' or c == '\10' or c == '\13' or c == '\32' or c == '\160' then
res = res .. c
elseif c == '\128' then
res = res .. ' '
else
res = res .. utf8.char(0xE000 + c:byte())
end
end
return res
end
else
function processOutput(out)
return out
end
end
local termNat
termNat = {
clear = function()
local w, h = termNat.getSize()
for l = 0, h - 1 do
prev.io.write(T.cup(l, 0))
prev.io.write((' '):rep(w))
end
termNat.setCursorPos(cursorX, cursorY)
end;
clearLine = function()
local w, h = termNat.getSize()
prev.io.write(T.cup(cursorY - 1, 0))
prev.io.write((' '):rep(w))
termNat.setCursorPos(cursorX, cursorY)
end;
isColour = function() return true end;
isColor = function() return true end;
getSize = function()
return luv.tty_get_winsize(stdin)
-- return 52, 19
end;
getCursorPos = function() return cursorX, cursorY end;
setCursorPos = function(x, y)
if type(x) ~= 'number' or type(y) ~= 'number' then error('term.setCursorPos expects number, number, got: ' .. type(x) .. ', ' .. type(y)) end
local oldX, oldY = cursorX, cursorY
cursorX, cursorY = math.floor(x), math.floor(y)
termNat.setCursorBlink(cursorBlink)
local w, h = luv.tty_get_winsize(stdin)
if cursorY >= 1 and cursorY <= h and cursorX <= w then
prev.io.write(T.cup(cursorY - 1, math.max(0, cursorX - 1)))
end
end;
setTextColour = function(...) return termNat.setTextColor(...) end;
setTextColor = function(c)
textColor = math.log(c) / log2
prev.io.write(color_escapes.fg[_colors[c] ])
end;
getTextColour = function(...) return termNat.getTextColor(...) end;
getTextColor = function()
return ccColorFor(textColor)
end;
setBackgroundColour = function(...) return termNat.setBackgroundColor(...) end;
setBackgroundColor = function(c)
backColor = math.log(c) / log2
prev.io.write(color_escapes.bg[_colors[c] ])
end;
getBackgroundColour = function(...) return termNat.getBackgroundColor(...) end;
getBackgroundColor = function()
return ccColorFor(backColor)
end;
write = function(text)
text = tostring(text or '')
text = text:gsub('[\n\r]', '?')
local w, h = luv.tty_get_winsize(stdin)
if cursorY >= 1 and cursorY <= h and cursorX <= w then
if cursorX >= 1 then
prev.io.write(processOutput(text:sub(1, w - cursorX + 1)))
elseif cursorX > 1 - #text then
prev.io.write(processOutput(text:sub(-cursorX + 2)))
end
end
termNat.setCursorPos(cursorX + #text, cursorY)
end;
blit = function(text, textColors, backColors)
text = text:gsub('[\n\r]', '?')
if #text ~= #textColors or #text ~= #backColors then error('term.blit: text, textColors and backColors have to be the same length') end
local w, h = luv.tty_get_winsize(stdin)
if cursorY >= 1 and cursorY <= h and cursorX <= w then
local start
if cursorX >= 1 then
start = 1
elseif cursorX > 1 - #text then
start = -cursorX + 2
end
if start then
local fg, bg = textColor, backColor
for i = start, math.min(#text, w - cursorX + start) do
termNat.setTextColor(ccColorFor(fromHexColor(textColors:sub(i, i))))
termNat.setBackgroundColor(ccColorFor(fromHexColor(backColors:sub(i, i))))
prev.io.write(processOutput(text:sub(i, i)))
end
termNat.setTextColor(ccColorFor(fg))
termNat.setBackgroundColor(ccColorFor(bg))
end
end
termNat.setCursorPos(cursorX + #text, cursorY)
end;
setCursorBlink = function(blink)
cursorBlink = blink
local w, h = luv.tty_get_winsize(stdin)
if cursorBlink and cursorY >= 1 and cursorY <= h and cursorX >= 1 and cursorX <= w then
prev.io.write(T.cursor_normal())
else
prev.io.write(T.cursor_invisible())
end
end;
scroll = function(n)
n = n or 1
local w, h = luv.tty_get_winsize(stdin)
prev.io.write(n < 0 and T.cup(0, 0) or T.cup(h, w))
local txt = T[n < 0 and 'ri' or 'ind']()
prev.io.write(txt:rep(math.abs(n)))
-- if n > 0 then
-- prev.io.write(T.cup(h - n, 0))
-- prev.io.write(T.clr_eos())
-- elseif n < 0 then
-- for i = 0, n do
-- prev.io.write(T.cup(i, 0))
-- prev.io.write((' '):rep(w))
-- end
-- end
termNat.setCursorPos(cursorX, cursorY)
end
}
prev.io.write(T.smcup())
termNat.setTextColor(1)
termNat.setBackgroundColor(32768)
termNat.clear()
prev.io.flush()
exit_seq[#exit_seq + 1] = function()
prev.io.write(T.rmcup())
prev.io.flush()
end
return termNat
|
Fix rendering of '\128'
|
Fix rendering of '\128'
|
Lua
|
mit
|
CoderPuppy/cc-emu,CoderPuppy/cc-emu,CoderPuppy/cc-emu
|
36d9fb2ca507a440c2fe988e669db9907905bfdc
|
core/ext/mime_types.lua
|
core/ext/mime_types.lua
|
-- Copyright 2007-2009 Mitchell mitchell<att>caladbolg.net. See LICENSE.
local textadept = _G.textadept
local locale = _G.locale
---
-- Handles file-specific settings.
module('textadept.mime_types', package.seeall)
-- Markdown:
-- ## Overview
--
-- Files can be recognized and associated with programming language lexers in
-- three ways:
--
-- * By file extension.
-- * By keywords in the file's shebang (`#!/path/to/exe`) line.
-- * By a pattern that matches the file's first line.
--
-- If a lexer is not associated with a file you open, first make sure the lexer
-- exists in `lexers/`. If it does not, you will need to write one. Consult the
-- [lexer][lexer] module for a tutorial.
--
-- [lexer]: ../modules/lexer.html
--
-- ## Configuration File
--
-- `core/ext/mime_types.conf` is the configuration file for mime-type detection.
--
-- #### Detection by File Extension
--
-- file_ext lexer
--
-- Note: `file_ext` should not start with a `.` (period).
--
-- #### Detection by Shebang Keywords
--
-- #shebang_word lexer
--
-- Examples of `shebang_word`'s are `lua`, `ruby`, `python`.
--
-- #### Detection by Pattern
--
-- /pattern lexer
--
-- Only the last space, the one separating the pattern from the lexer, is
-- significant. No spaces in the pattern need to be escaped.
--
-- ## Extras
--
-- This module adds an extra function to `buffer`:
--
-- * **buffer:set\_lexer** (language)<br />
-- Replacement for [`buffer:set_lexer_language()`][buffer_set_lexer_language].<br />
-- Sets a buffer._lexer field so it can be restored without querying the
-- mime-types tables. Also if the user manually sets the lexer, it should be
-- restored.<br />
-- Loads the language-specific module if it exists.
-- - lang: The string language to set.
--
-- [buffer_set_lexer_language]: buffer.html#buffer:set_lexer_language
---
-- File extensions with their associated lexers.
-- @class table
-- @name extensions
extensions = {}
---
-- Shebang words and their associated lexers.
-- @class table
-- @name shebangs
shebangs = {}
---
-- First-line patterns and their associated lexers.
-- @class table
-- @name patterns
patterns = {}
-- Load mime-types from mime_types.conf
local f = io.open(_HOME..'/core/ext/mime_types.conf', 'rb')
if f then
for line in f:lines() do
if not line:find('^%s*%%') then
if line:find('^%s*[^#/]') then -- extension definition
local ext, lexer_name = line:match('^%s*(.+)%s+(%S+)$')
if ext and lexer_name then extensions[ext] = lexer_name end
else -- shebang or pattern
local ch, text, lexer_name = line:match('^%s*([#/])(.+)%s+(%S+)$')
if ch and text and lexer_name then
(ch == '#' and shebangs or patterns)[text] = lexer_name
end
end
end
end
f:close()
end
--
-- Replacement for buffer:set_lexer_language().
-- Sets a buffer._lexer field so it can be restored without querying the
-- mime-types tables. Also if the user manually sets the lexer, it should be
-- restored.
-- Loads the language-specific module if it exists.
-- @param buffer The buffer to set the lexer language of.
-- @param lang The string language to set.
-- @usage buffer:set_lexer('language_name')
local function set_lexer(buffer, lang)
buffer._lexer = lang
buffer:set_lexer_language(lang)
if buffer.filename then
local ret, err = pcall(require, lang)
if ret then
_m[lang].set_buffer_properties()
elseif not ret and not err:find("^module '"..lang.."' not found:") then
error(err)
end
end
end
textadept.events.add_handler('buffer_new',
function() buffer.set_lexer = set_lexer end)
-- Performs actions suitable for a new buffer.
-- Sets the buffer's lexer language and loads the language module.
local function handle_new()
local lexer
if buffer.filename then
lexer = extensions[buffer.filename:match('[^/\\.]+$')]
end
if not lexer then
local line = buffer:get_line(0)
if line:find('^#!') then
for word in line:gsub('[/\\]', ' '):gmatch('%S+') do
lexer = shebangs[word]
if lexer then break end
end
end
if not lexer then
for patt, lex in pairs(patterns) do
if line:find(patt) then
lexer = lex
break
end
end
end
end
buffer:set_lexer(lexer or 'container')
end
-- Sets the buffer's lexer based on filename, shebang words, or
-- first line pattern.
local function restore_lexer()
buffer:set_lexer_language(buffer._lexer or 'container')
end
textadept.events.add_handler('file_opened', handle_new)
textadept.events.add_handler('file_saved_as', handle_new)
textadept.events.add_handler('buffer_after_switch', restore_lexer)
textadept.events.add_handler('view_new', restore_lexer)
|
-- Copyright 2007-2009 Mitchell mitchell<att>caladbolg.net. See LICENSE.
local textadept = _G.textadept
local locale = _G.locale
---
-- Handles file-specific settings.
module('textadept.mime_types', package.seeall)
-- Markdown:
-- ## Overview
--
-- Files can be recognized and associated with programming language lexers in
-- three ways:
--
-- * By file extension.
-- * By keywords in the file's shebang (`#!/path/to/exe`) line.
-- * By a pattern that matches the file's first line.
--
-- If a lexer is not associated with a file you open, first make sure the lexer
-- exists in `lexers/`. If it does not, you will need to write one. Consult the
-- [lexer][lexer] module for a tutorial.
--
-- [lexer]: ../modules/lexer.html
--
-- ## Configuration File
--
-- `core/ext/mime_types.conf` is the configuration file for mime-type detection.
--
-- #### Detection by File Extension
--
-- file_ext lexer
--
-- Note: `file_ext` should not start with a `.` (period).
--
-- #### Detection by Shebang Keywords
--
-- #shebang_word lexer
--
-- Examples of `shebang_word`'s are `lua`, `ruby`, `python`.
--
-- #### Detection by Pattern
--
-- /pattern lexer
--
-- Only the last space, the one separating the pattern from the lexer, is
-- significant. No spaces in the pattern need to be escaped.
--
-- ## Extras
--
-- This module adds an extra function to `buffer`:
--
-- * **buffer:set\_lexer** (language)<br />
-- Replacement for [`buffer:set_lexer_language()`][buffer_set_lexer_language].<br />
-- Sets a buffer._lexer field so it can be restored without querying the
-- mime-types tables. Also if the user manually sets the lexer, it should be
-- restored.<br />
-- Loads the language-specific module if it exists.
-- - lang: The string language to set.
--
-- [buffer_set_lexer_language]: buffer.html#buffer:set_lexer_language
---
-- File extensions with their associated lexers.
-- @class table
-- @name extensions
extensions = {}
---
-- Shebang words and their associated lexers.
-- @class table
-- @name shebangs
shebangs = {}
---
-- First-line patterns and their associated lexers.
-- @class table
-- @name patterns
patterns = {}
-- Load mime-types from mime_types.conf
local f = io.open(_HOME..'/core/ext/mime_types.conf', 'rb')
if f then
for line in f:lines() do
if not line:find('^%s*%%') then
if line:find('^%s*[^#/]') then -- extension definition
local ext, lexer_name = line:match('^%s*(.+)%s+(%S+)$')
if ext and lexer_name then extensions[ext] = lexer_name end
else -- shebang or pattern
local ch, text, lexer_name = line:match('^%s*([#/])(.+)%s+(%S+)$')
if ch and text and lexer_name then
(ch == '#' and shebangs or patterns)[text] = lexer_name
end
end
end
end
f:close()
end
--
-- Replacement for buffer:set_lexer_language().
-- Sets a buffer._lexer field so it can be restored without querying the
-- mime-types tables. Also if the user manually sets the lexer, it should be
-- restored.
-- Loads the language-specific module if it exists.
-- @param buffer The buffer to set the lexer language of.
-- @param lang The string language to set.
-- @usage buffer:set_lexer('language_name')
local function set_lexer(buffer, lang)
buffer._lexer = lang
buffer:set_lexer_language(lang)
local ret, err = pcall(require, lang)
if ret then
_m[lang].set_buffer_properties()
elseif not ret and not err:find("^module '"..lang.."' not found:") then
error(err)
end
end
textadept.events.add_handler('buffer_new',
function() buffer.set_lexer = set_lexer end)
buffer.set_lexer = set_lexer -- Scintilla's first buffer doesn't have this
-- Performs actions suitable for a new buffer.
-- Sets the buffer's lexer language and loads the language module.
local function handle_new()
local lexer
if buffer.filename then
lexer = extensions[buffer.filename:match('[^/\\.]+$')]
end
if not lexer then
local line = buffer:get_line(0)
if line:find('^#!') then
for word in line:gsub('[/\\]', ' '):gmatch('%S+') do
lexer = shebangs[word]
if lexer then break end
end
end
if not lexer then
for patt, lex in pairs(patterns) do
if line:find(patt) then
lexer = lex
break
end
end
end
end
buffer:set_lexer(lexer or 'container')
end
-- Sets the buffer's lexer based on filename, shebang words, or
-- first line pattern.
local function restore_lexer()
buffer:set_lexer_language(buffer._lexer or 'container')
end
textadept.events.add_handler('file_opened', handle_new)
textadept.events.add_handler('file_saved_as', handle_new)
textadept.events.add_handler('buffer_after_switch', restore_lexer)
textadept.events.add_handler('view_new', restore_lexer)
|
Fixed bugs in core/ext/mime_types.lua related to set_lexer().
|
Fixed bugs in core/ext/mime_types.lua related to set_lexer().
|
Lua
|
mit
|
rgieseke/textadept,rgieseke/textadept
|
1eb4a4f8e6061e3d7fe5b385314ca64d4852063b
|
premake5.lua
|
premake5.lua
|
solution "rtr"
configurations {"debug", "release"}
defines {"GLM_FORCE_RADIANS","GLM_SWIZZLE", "GLEW_STATIC"}
flags {"FatalWarnings"}
vectorextensions "SSE2"
includedirs {"include", "lib/**/include", "lib"}
libdirs{"lib/glew/build", "lib/log/build", "lib/glcw/build"}
configuration "windows"
defines {"WINDOWS"}
configuration "linux"
defines {"LINUX"}
configuration "debug"
defines { "DEBUG" }
flags { "Symbols" }
optimize "Off"
configuration "release"
defines { "NDEBUG" }
optimize "Full"
configuration {"gmake","windows"}
includedirs {"lib/sdl2/mingw32-x86_64/include", "lib/sdl2/mingw32-i686/include"}
libdirs {"lib/sdl2/mingw32-x86_64/lib", "lib/sdl2/mingw32-i686/lib"}
configuration {"gmake", "linux"}
project "GLEW"
kind "StaticLib"
language "C"
location "lib/glew/build"
includedirs {"lib/glew/include"}
files { "lib/glew/include/**.h", "lib/glew/src/**.c"}
configuration {"gmake", "linux"}
if _OPTIONS["cc"] == "clang" then
toolset "clang"
end
project "glcw"
kind "StaticLib"
language "C++"
location "lib/glcw/build"
includedirs {"lib/glcw/include"}
files {"lib/glcw/include/**.hpp", "lib/glcw/src/**.cpp"}
buildoptions "-std=gnu++1y"
configuration {"gmake", "windows"}
linkoptions {"-lmingw32 lib/glew/build/GLEW.lib lib/log/build/log.lib -lopengl32 -static-libgcc -static-libstdc++"}
links {"GLEW", "log"}
configuration {"gmake", "linux"}
links {"GLEW", "GL", "log"}
if _OPTIONS["cc"] == "clang" then
toolset "clang"
buildoptions "-stdlib=libc++"
links "c++"
end
project "log"
kind "StaticLib"
language "C++"
location "lib/log/build"
includedirs {"lib/log/include"}
files {"lib/log/include/**.hpp", "lib/log/src/**.cpp"}
buildoptions "-std=gnu++1y"
configuration {"gmake", "linux"}
if _OPTIONS["cc"] == "clang" then
toolset "clang"
buildoptions "-stdlib=libc++"
links "c++"
end
project "deferred_shading"
kind "WindowedApp"
language "C++"
includedirs {"include"}
files {"inlude/**.h", "include/**.hpp", "src/**.cpp"}
location "build"
buildoptions "-std=gnu++1y"
configuration {"gmake","windows"}
postbuildcommands {
"copy \"lib\\sdl2\\mingw32-x86_64\\bin\\SDL2.dll\" \"SDL2.dll\"",
}
linkoptions {"-lmingw32 lib/glew/build/GLEW.lib lib/log/build/log.lib lib/glcw/build/glcw.lib -lopengl32 -lSDL2main -lSDL2 -static-libgcc -static-libstdc++"}
links {"GLEW", "log", "glcw"}
configuration {"gmake", "linux"}
links {"GLEW", "GL", "glcw", "SDL2", "log"}
libdirs {os.findlib("SDL2")}
if _OPTIONS["cc"] == "clang" then
toolset "clang"
buildoptions "-stdlib=libc++"
links "c++"
end
|
solution "rtr"
configurations {"debug", "release"}
defines {"GLM_FORCE_RADIANS","GLM_SWIZZLE", "GLEW_STATIC"}
flags {"FatalWarnings"}
vectorextensions "SSE2"
includedirs {"include", "lib/**/include", "lib"}
libdirs{"lib/glew/build", "lib/log/build", "lib/glcw/build"}
configuration "windows"
defines {"WINDOWS"}
configuration "linux"
defines {"LINUX"}
configuration "debug"
defines { "DEBUG" }
flags { "Symbols" }
optimize "Off"
configuration "release"
defines { "NDEBUG" }
optimize "Full"
configuration {"gmake","windows"}
includedirs {"lib/sdl2/mingw32-x86_64/include", "lib/sdl2/mingw32-i686/include"}
libdirs {"lib/sdl2/mingw32-x86_64/lib", "lib/sdl2/mingw32-i686/lib"}
configuration {"gmake", "linux"}
project "GLEW"
kind "StaticLib"
language "C++"
location "lib/glew/build"
includedirs {"lib/glew/include"}
files { "lib/glew/include/**.h", "lib/glew/src/**.c"}
configuration {"gmake", "windows"}
linkoptions {"-lmingw32 -static-libgcc"}
configuration {"gmake", "linux"}
if _OPTIONS["cc"] == "clang" then
toolset "clang"
end
project "glcw"
kind "StaticLib"
language "C++"
location "lib/glcw/build"
includedirs {"lib/glcw/include"}
files {"lib/glcw/include/**.hpp", "lib/glcw/src/**.cpp"}
buildoptions "-std=gnu++1y"
configuration {"gmake", "windows"}
linkoptions {"-lmingw32 ../lib/glew/build/GLEW.lib ../lib/log/build/log.lib -lopengl32 -static-libgcc -static-libstdc++"}
links {"GLEW", "log"}
configuration {"gmake", "linux"}
links {"GLEW", "GL", "log"}
if _OPTIONS["cc"] == "clang" then
toolset "clang"
buildoptions "-stdlib=libc++"
links "c++"
end
project "log"
kind "StaticLib"
language "C++"
location "lib/log/build"
includedirs {"lib/log/include"}
files {"lib/log/include/**.hpp", "lib/log/src/**.cpp"}
buildoptions "-std=gnu++1y"
configuration {"gmake", "windows"}
linkoptions {"-lmingw32 -static-libgcc -static-libstdc++"}
configuration {"gmake", "linux"}
if _OPTIONS["cc"] == "clang" then
toolset "clang"
buildoptions "-stdlib=libc++"
links "c++"
end
project "deferred_shading"
kind "WindowedApp"
language "C++"
includedirs {"include"}
files {"inlude/**.h", "include/**.hpp", "src/**.cpp"}
location "build"
buildoptions "-std=gnu++1y"
configuration {"gmake","windows"}
postbuildcommands {
"copy ..\\lib\\sdl2\\mingw32-x86_64\\bin\\SDL2.dll SDL2.dll",
}
linkoptions {"-lmingw32 ../lib/glew/build/GLEW.lib ../lib/glcw/build/glcw.lib ../lib/log/build/log.lib -lopengl32 -lSDL2main -lSDL2 -static-libgcc -static-libstdc++"}
links {"GLEW", "log", "glcw"}
configuration {"gmake", "linux"}
links {"GLEW", "GL", "glcw", "SDL2", "log"}
libdirs {os.findlib("SDL2")}
if _OPTIONS["cc"] == "clang" then
toolset "clang"
buildoptions "-stdlib=libc++"
links "c++"
end
|
fix some stuff in premake file for windows
|
fix some stuff in premake file for windows
|
Lua
|
mit
|
Berling/deferred_shading,Berling/deferred_shading,Berling/deferred_shading
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.