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
|
|---|---|---|---|---|---|---|---|---|---|
dbeedd911297f7bcae05ca48af4162ca5884ba28
|
hammerspoon/.hammerspoon/window-management/layouts.lua
|
hammerspoon/.hammerspoon/window-management/layouts.lua
|
local export = {}
grid = require("window-management/grid")
helpers = require("window-management/helpers")
local areas = grid.areas
local hsGrid = grid.hsGrid
-- FILTERS
-------------------------------------------------------------------------------
local wf = hs.window.filter
local mainScreenName = hs.screen.mainScreen():name()
-- Single Apps
w_chrome = wf.new{'Google Chrome'}:setCurrentSpace(true)
w_firefox = wf.new{'Firefox Developer Edition'}:setCurrentSpace(true)
w_obs = wf.new{'OBS'}:setCurrentSpace(true)
w_figma = wf.new{'Figma'}:setCurrentSpace(true)
-- Groups of Apps
w_browsers = wf.new{['Firefox Developer Edition'] = true, ['Google Chrome'] = { rejectTitles = 'Picture in Picture' } }:setCurrentSpace(true)
w_editors = wf.new{'Code'}:setCurrentSpace(true)
w_terminals = wf.new{'iTerm2', 'Alacritty'}:setCurrentSpace(true)
w_videos = wf.new{['YouTube'] = true, ['Twitch'] = true, ['Google Meet'] = true, ['zoom.us'] = true, ['Google Chrome'] = {allowTitles = 'Picture in Picture'}, ['Slack'] = {allowTitles = '(.*)Huddle$'}}:setCurrentSpace(true):setScreens(mainScreenName)
w_notes = wf.new{'Notion', 'Obsidian'}:setCurrentSpace(true):setScreens(mainScreenName)
w_todos = wf.new{'Asana', 'Todoist'}:setCurrentSpace(true):setScreens(mainScreenName)
w_chats = wf.new{'Slack', 'Ferdi', 'Discord', 'Messages'}:setCurrentSpace(true):setScreens(mainScreenName)
-- LAYOUTS
-------------------------------------------------------------------------------
--[[
workBrowse:
MAIN: Browser,
SECONDARY: everything else
]]
function export.workBrowse(tight)
tight = tight or false
local split = tight and areas.smallSplit or areas.mediumSplit
--RIGHT
grid.setFilteredWindowsToCell(w_browsers, split.main)
grid.setFilteredWindowsToCell(w_figma, split.main)
grid.setFilteredWindowsToCell(w_todos, split.main)
if #w_videos:getWindows() > 0 then
-- LEFT
grid.setFilteredWindowsToCell(w_editors, split.secondaryBottom)
grid.setFilteredWindowsToCell(w_terminals, split.secondaryBottom)
grid.setFilteredWindowsToCell(w_notes, split.secondaryBottom)
grid.setFilteredWindowsToCell(w_chats, split.secondaryBottom)
grid.setFilteredWindowsToCell(w_videos, split.secondaryTop)
else
-- LEFT
grid.setFilteredWindowsToCell(w_terminals, split.secondaryFull)
grid.setFilteredWindowsToCell(w_editors, split.secondaryFull)
grid.setFilteredWindowsToCell(w_notes, split.secondaryFull)
grid.setFilteredWindowsToCell(w_chats, split.secondaryFull)
end
end
--[[
workCode:
MAIN: Code,
SECONDARY: everything else
]]
function export.workCode(tight)
tight = tight or false
local split = tight and areas.smallSplit or areas.mediumSplit
-- RIGHT
grid.setFilteredWindowsToCell(w_editors, split.main)
grid.setFilteredWindowsToCell(w_figma, split.main)
grid.setFilteredWindowsToCell(w_todos, split.main)
if #w_videos:getWindows() > 0 then
-- LEFT
grid.setFilteredWindowsToCell(w_browsers, split.secondaryBottom)
grid.setFilteredWindowsToCell(w_terminals, split.secondaryBottom)
grid.setFilteredWindowsToCell(w_notes, split.secondaryBottom)
grid.setFilteredWindowsToCell(w_chats, split.secondaryBottom)
grid.setFilteredWindowsToCell(w_videos, split.secondaryTop)
else
-- LEFT
grid.setFilteredWindowsToCell(w_browsers, split.secondaryFull)
grid.setFilteredWindowsToCell(w_terminals, split.secondaryFull)
grid.setFilteredWindowsToCell(w_notes, split.secondaryFull)
grid.setFilteredWindowsToCell(w_chats, split.secondaryFull)
end
end
--[[
workTriple:
LEFT: Terminal + Code + Chat
MAIN: Video + Notes
RIGHT: Browser
]]
function export.workTriple()
if #w_videos:getWindows() > 0 then
grid.setFilteredWindowsToCell(w_terminals, areas.tripleSplit.leftFull)
grid.setFilteredWindowsToCell(w_chats, areas.tripleSplit.leftFull)
grid.setFilteredWindowsToCell(w_editors, areas.tripleSplit.leftFull)
grid.setFilteredWindowsToCell(w_notes, areas.tripleSplit.mainBottom)
grid.setFilteredWindowsToCell(w_todos, areas.tripleSplit.mainBottom)
grid.setFilteredWindowsToCell(w_figma, areas.tripleSplit.rightFull)
grid.setFilteredWindowsToCell(w_browsers, areas.tripleSplit.rightFull)
grid.setFilteredWindowsToCell(w_videos, areas.tripleSplit.mainTop)
else
grid.setFilteredWindowsToCell(w_terminals, areas.tripleSplit.leftFull)
grid.setFilteredWindowsToCell(w_chats, areas.tripleSplit.leftFull)
grid.setFilteredWindowsToCell(w_editors, areas.tripleSplit.leftFull)
grid.setFilteredWindowsToCell(w_browsers, areas.tripleSplit.mainFull)
grid.setFilteredWindowsToCell(w_notes, areas.tripleSplit.rightFull)
grid.setFilteredWindowsToCell(w_todos, areas.tripleSplit.rightFull)
grid.setFilteredWindowsToCell(w_figma, areas.tripleSplit.rightFull)
end
end
--[[
workEven:
When Video, place it on the left and everything else on the right
When no video, browser, notes and chats on the left, everything else on the right
]]
function export.workEven()
if #w_videos:getWindows() > 0 then
--RIGHT
grid.setFilteredWindowsToCell(w_terminals, areas.evenSplit.rightFull)
grid.setFilteredWindowsToCell(w_notes, areas.evenSplit.rightFull)
grid.setFilteredWindowsToCell(w_todos, areas.evenSplit.rightFull)
grid.setFilteredWindowsToCell(w_figma, areas.evenSplit.rightFull)
grid.setFilteredWindowsToCell(w_chats, areas.evenSplit.rightFull)
grid.setFilteredWindowsToCell(w_browsers, areas.evenSplit.rightFull)
grid.setFilteredWindowsToCell(w_editors, areas.evenSplit.rightFull)
-- LEFT
grid.setFilteredWindowsToCell(w_videos, areas.evenSplit.leftFull)
else
-- LEFT
grid.setFilteredWindowsToCell(w_browsers, areas.evenSplit.leftFull)
grid.setFilteredWindowsToCell(w_todos, areas.evenSplit.leftFull)
grid.setFilteredWindowsToCell(w_chats, areas.evenSplit.leftFull)
-- RIGHT
grid.setFilteredWindowsToCell(w_terminals, areas.evenSplit.rightFull)
grid.setFilteredWindowsToCell(w_notes, areas.evenSplit.rightFull)
grid.setFilteredWindowsToCell(w_figma, areas.evenSplit.rightFull)
grid.setFilteredWindowsToCell(w_editors, areas.evenSplit.rightFull)
end
end
--[[
workMax:
MAIN: Browser/Code Maximized,
SECONDARY: Terminal and Notes centered
]]
function export.workMax()
helpers.maximiseFilteredWindows(w_browsers)
helpers.maximiseFilteredWindows(w_editors)
helpers.maximiseFilteredWindows(w_figma)
grid.setFilteredWindowsToCell(w_terminals, areas.custom.center)
grid.setFilteredWindowsToCell(w_notes, areas.custom.center)
grid.setFilteredWindowsToCell(w_todos, areas.custom.center)
grid.setFilteredWindowsToCell(w_chats, areas.custom.center)
grid.setFilteredWindowsToCell(w_videos, areas.custom.center)
end
return export
|
local export = {}
grid = require("window-management/grid")
helpers = require("window-management/helpers")
local areas = grid.areas
local hsGrid = grid.hsGrid
-- FILTERS
-------------------------------------------------------------------------------
local wf = hs.window.filter
local mainScreenName = hs.screen.mainScreen():name()
-- Single Apps
w_chrome = wf.new{'Google Chrome'}:setCurrentSpace(true)
w_firefox = wf.new{'Firefox Developer Edition'}:setCurrentSpace(true)
w_obs = wf.new{'OBS'}:setCurrentSpace(true)
w_figma = wf.new{'Figma'}:setCurrentSpace(true)
-- Groups of Apps
w_browsers = wf.new{['Firefox Developer Edition'] = true, ['Google Chrome'] = { rejectTitles = 'Picture in Picture' } }:setCurrentSpace(true):setScreens(mainScreenName)
w_editors = wf.new{'Code'}:setCurrentSpace(true):setScreens(mainScreenName)
w_terminals = wf.new{'iTerm2', 'Alacritty'}:setCurrentSpace(true):setScreens(mainScreenName)
w_videos = wf.new{['YouTube'] = true, ['Twitch'] = true, ['Google Meet'] = true, ['zoom.us'] = true, ['Google Chrome'] = {allowTitles = 'Picture in Picture'}, ['Slack'] = {allowTitles = '(.*)Huddle$'}}:setCurrentSpace(true):setScreens(mainScreenName)
w_notes = wf.new{'Notion', 'Obsidian'}:setCurrentSpace(true):setScreens(mainScreenName)
w_todos = wf.new{'Asana', 'Todoist'}:setCurrentSpace(true):setScreens(mainScreenName)
w_chats = wf.new{'Slack', 'Ferdi', 'Discord', 'Messages'}:setCurrentSpace(true):setScreens(mainScreenName)
-- LAYOUTS
-------------------------------------------------------------------------------
--[[
workBrowse:
MAIN: Browser and Code,
SECONDARY: everything else
]]
function export.workBrowse(tight)
tight = tight or false
local split = tight and areas.smallSplit or areas.mediumSplit
--RIGHT
grid.setFilteredWindowsToCell(w_browsers, split.main)
grid.setFilteredWindowsToCell(w_editors, split.main)
grid.setFilteredWindowsToCell(w_figma, split.main)
grid.setFilteredWindowsToCell(w_todos, split.main)
if #w_videos:getWindows() > 0 then
-- LEFT
grid.setFilteredWindowsToCell(w_terminals, split.secondaryBottom)
grid.setFilteredWindowsToCell(w_notes, split.secondaryBottom)
grid.setFilteredWindowsToCell(w_chats, split.secondaryBottom)
grid.setFilteredWindowsToCell(w_videos, split.secondaryTop)
else
-- LEFT
grid.setFilteredWindowsToCell(w_terminals, split.secondaryFull)
grid.setFilteredWindowsToCell(w_notes, split.secondaryFull)
grid.setFilteredWindowsToCell(w_chats, split.secondaryFull)
end
end
--[[
workCode:
MAIN: Code,
SECONDARY: everything else
]]
function export.workCode(tight)
tight = tight or false
local split = tight and areas.smallSplit or areas.mediumSplit
-- RIGHT
grid.setFilteredWindowsToCell(w_editors, split.main)
grid.setFilteredWindowsToCell(w_figma, split.main)
grid.setFilteredWindowsToCell(w_todos, split.main)
if #w_videos:getWindows() > 0 then
-- LEFT
grid.setFilteredWindowsToCell(w_browsers, split.secondaryBottom)
grid.setFilteredWindowsToCell(w_terminals, split.secondaryBottom)
grid.setFilteredWindowsToCell(w_notes, split.secondaryBottom)
grid.setFilteredWindowsToCell(w_chats, split.secondaryBottom)
grid.setFilteredWindowsToCell(w_videos, split.secondaryTop)
else
-- LEFT
grid.setFilteredWindowsToCell(w_browsers, split.secondaryFull)
grid.setFilteredWindowsToCell(w_terminals, split.secondaryFull)
grid.setFilteredWindowsToCell(w_notes, split.secondaryFull)
grid.setFilteredWindowsToCell(w_chats, split.secondaryFull)
end
end
--[[
workTriple:
LEFT: Terminal + Code + Chat
MAIN: Video + Notes
RIGHT: Browser
]]
function export.workTriple()
if #w_videos:getWindows() > 0 then
grid.setFilteredWindowsToCell(w_terminals, areas.tripleSplit.leftFull)
grid.setFilteredWindowsToCell(w_chats, areas.tripleSplit.leftFull)
grid.setFilteredWindowsToCell(w_editors, areas.tripleSplit.leftFull)
grid.setFilteredWindowsToCell(w_notes, areas.tripleSplit.mainBottom)
grid.setFilteredWindowsToCell(w_todos, areas.tripleSplit.mainBottom)
grid.setFilteredWindowsToCell(w_figma, areas.tripleSplit.rightFull)
grid.setFilteredWindowsToCell(w_browsers, areas.tripleSplit.rightFull)
grid.setFilteredWindowsToCell(w_videos, areas.tripleSplit.mainTop)
else
grid.setFilteredWindowsToCell(w_terminals, areas.tripleSplit.leftFull)
grid.setFilteredWindowsToCell(w_chats, areas.tripleSplit.leftFull)
grid.setFilteredWindowsToCell(w_editors, areas.tripleSplit.leftFull)
grid.setFilteredWindowsToCell(w_browsers, areas.tripleSplit.mainFull)
grid.setFilteredWindowsToCell(w_notes, areas.tripleSplit.rightFull)
grid.setFilteredWindowsToCell(w_todos, areas.tripleSplit.rightFull)
grid.setFilteredWindowsToCell(w_figma, areas.tripleSplit.rightFull)
end
end
--[[
workEven:
When Video, place it on the left and everything else on the right
When no video, browser, notes and chats on the left, everything else on the right
]]
function export.workEven()
if #w_videos:getWindows() > 0 then
--RIGHT
grid.setFilteredWindowsToCell(w_terminals, areas.evenSplit.rightFull)
grid.setFilteredWindowsToCell(w_notes, areas.evenSplit.rightFull)
grid.setFilteredWindowsToCell(w_todos, areas.evenSplit.rightFull)
grid.setFilteredWindowsToCell(w_figma, areas.evenSplit.rightFull)
grid.setFilteredWindowsToCell(w_chats, areas.evenSplit.rightFull)
grid.setFilteredWindowsToCell(w_browsers, areas.evenSplit.rightFull)
grid.setFilteredWindowsToCell(w_editors, areas.evenSplit.rightFull)
-- LEFT
grid.setFilteredWindowsToCell(w_videos, areas.evenSplit.leftFull)
else
-- LEFT
grid.setFilteredWindowsToCell(w_browsers, areas.evenSplit.leftFull)
grid.setFilteredWindowsToCell(w_todos, areas.evenSplit.leftFull)
grid.setFilteredWindowsToCell(w_chats, areas.evenSplit.leftFull)
-- RIGHT
grid.setFilteredWindowsToCell(w_terminals, areas.evenSplit.rightFull)
grid.setFilteredWindowsToCell(w_notes, areas.evenSplit.rightFull)
grid.setFilteredWindowsToCell(w_figma, areas.evenSplit.rightFull)
grid.setFilteredWindowsToCell(w_editors, areas.evenSplit.rightFull)
end
end
--[[
workMax:
MAIN: Browser/Code Maximized,
SECONDARY: Terminal and Notes centered
]]
function export.workMax()
helpers.maximiseFilteredWindows(w_browsers)
helpers.maximiseFilteredWindows(w_editors)
helpers.maximiseFilteredWindows(w_figma)
grid.setFilteredWindowsToCell(w_terminals, areas.custom.center)
grid.setFilteredWindowsToCell(w_notes, areas.custom.center)
grid.setFilteredWindowsToCell(w_todos, areas.custom.center)
grid.setFilteredWindowsToCell(w_chats, areas.custom.center)
grid.setFilteredWindowsToCell(w_videos, areas.custom.center)
end
return export
|
Layouts: fix workBrowsew and performance optimization
|
Layouts: fix workBrowsew and performance optimization
|
Lua
|
mit
|
francoiscote/dotfiles,francoiscote/dotfiles
|
b361e31282be7739eef1aaa232748e437c98ea09
|
applications/luci-polipo/luasrc/model/cbi/polipo.lua
|
applications/luci-polipo/luasrc/model/cbi/polipo.lua
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Aleksandar Krsteski <alekrsteski@gmail.com>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
m = Map("polipo")
-- General section
s = m:section(NamedSection, "general", "polipo")
-- General settings
s:option(Flag, "enabled", translate("enable"))
s:option(Value, "proxyAddress")
s:option(Value, "proxyPort").optional = true
s:option(DynamicList, "allowedClients")
s:option(Flag, "logSyslog")
s:option(Value, "logFacility"):depends("logSyslog", "1")
v = s:option(Value, "logFile")
v:depends("logSyslog", "")
v.rmempty = true
s:option(Value, "chunkHighMark")
-- DNS and proxy settings
s:option(Value, "dnsNameServer").optional = true
s:option(Value, "parentProxy").optional = true
s:option(Value, "parentAuthCredentials").optional = true
l = s:option(ListValue, "dnsQueryIPv6")
l.optional = true
l.default = "happily"
l:value("")
l:value("true")
l:value("reluctantly")
l:value("happily")
l:value("false")
l = s:option(ListValue, "dnsUseGethostbyname")
l.optional = true
l.default = "reluctantly"
l:value("")
l:value("true")
l:value("reluctantly")
l:value("happily")
l:value("false")
-- Dsik cache section
s = m:section(NamedSection, "cache", "polipo")
-- Dsik cache settings
s:option(Value, "diskCacheRoot").rmempty = true
s:option(Flag, "cacheIsShared")
s:option(Value, "diskCacheTruncateSize").optional = true
s:option(Value, "diskCacheTruncateTime").optional = true
s:option(Value, "diskCacheUnlinkTime").optional = true
-- Poor man's multiplexing section
s = m:section(NamedSection, "pmm", "polipo")
s:option(Value, "pmmSize").rmempty = true
s:option(Value, "pmmFirstSize").optional = true
return m
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Aleksandar Krsteski <alekrsteski@gmail.com>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
m = Map("polipo", translate("Polipo"),
translate("Polipo is a small and fast caching web proxy."))
-- General section
s = m:section(NamedSection, "general", "polipo", translate("Proxy"))
s:tab("general", translate("General Settings"))
s:tab("dns", translate("DNS and Query Settings"))
s:tab("proxy", translate("Parent Proxy"))
s:tab("logging", translate("Logging and RAM"))
-- General settings
s:taboption("general", Flag, "enabled", translate("enable"))
o = s:taboption("general", Value, "proxyAddress", translate("Listen address"),
translate("The interface on which Polipo will listen. To listen on all " ..
"interfaces use 0.0.0.0 or :: (IPv6)."))
o.placeholder = "0.0.0.0"
o.datatype = "ipaddr"
o = s:taboption("general", Value, "proxyPort", translate("Listen port"),
translate("Port on which Polipo will listen"))
o.optional = true
o.placeholder = "8123"
o.datatype = "port"
o = s:taboption("general", DynamicList, "allowedClients",
translate("Allowed clients"),
translate("When listen address is set to 0.0.0.0 or :: (IPv6), you must " ..
"list clients that are allowed to connect. The format is IP address " ..
"or network address (192.168.1.123, 192.168.1.0/24, " ..
"2001:660:116::/48 (IPv6))"))
o.datatype = "ipaddr"
o.placeholder = "0.0.0.0/0"
-- DNS settings
dns = s:taboption("dns", Value, "dnsNameServer", translate("DNS server address"),
translate("Set the DNS server address to use, if you want Polipo to use " ..
"different DNS server than the host system."))
dns.optional = true
dns.datatype = "ipaddr"
l = s:taboption("dns", ListValue, "dnsQueryIPv6",
translate("Query DNS for IPv6"))
l.default = "happily"
l:value("true", translate("Query only IPv6"))
l:value("happily", translate("Query IPv4 and IPv6, prefer IPv6"))
l:value("reluctantly", translate("Query IPv4 and IPv6, prefer IPv4"))
l:value("false", translate("Do not query IPv6"))
l = s:taboption("dns", ListValue, "dnsUseGethostbyname",
translate("Query DNS by hostname"))
l.default = "reluctantly"
l:value("true", translate("Always use system DNS resolver"))
l:value("happily",
translate("Query DNS directly, for unknown hosts fall back " ..
"to system resolver"))
l:value("reluctantly",
translate("Query DNS directly, fallback to system resolver"))
l:value("false", translate("Never use system DNS resolver"))
-- Proxy settings
o = s:taboption("proxy", Value, "parentProxy",
translate("Parent proxy address"),
translate("Parent proxy address (in host:port format), to which Polipo " ..
"will forward the requests."))
o.optional = true
o.datatype = "ipaddr"
o = s:taboption("proxy", Value, "parentAuthCredentials",
translate("Parent proxy authentication"),
translate("Basic HTTP authentication supported. Provide username and " ..
"password in username:password format."))
o.optional = true
o.placeholder = "username:password"
-- Logging
s:taboption("logging", Flag, "logSyslog", translate("Log to syslog"))
s:taboption("logging", Value, "logFacility",
translate("Syslog facility")):depends("logSyslog", "1")
v = s:taboption("logging", Value, "logFile",
translate("Log file location"),
translate("Use of external storage device is recommended, because the " ..
"log file is written frequently and can grow considerably."))
v:depends("logSyslog", "")
v.rmempty = true
o = s:taboption("logging", Value, "chunkHighMark",
translate("In RAM cache size (in bytes)"),
translate("How much RAM should Polipo use for its cache."))
o.datatype = "uinteger"
-- Disk cache section
s = m:section(NamedSection, "cache", "polipo", translate("On-Disk Cache"))
s:tab("general", translate("General Settings"))
s:tab("advanced", translate("Advanced Settings"))
-- Disk cache settings
s:taboption("general", Value, "diskCacheRoot", translate("Disk cache location"),
translate("Location where polipo will cache files permanently. Use of " ..
"external storage devices is recommended, because the cache can " ..
"grow considerably. Leave it empty to disable on-disk " ..
"cache.")).rmempty = true
s:taboption("general", Flag, "cacheIsShared", translate("Shared cache"),
translate("Enable if cache (proxy) is shared by multiple users."))
o = s:taboption("advanced", Value, "diskCacheTruncateSize",
translate("Truncate cache files size (in bytes)"),
translate("Size to which cached files should be truncated"))
o.optional = true
o.placeholder = "1048576"
o.datatype = "uinteger"
o = s:taboption("advanced", Value, "diskCacheTruncateTime",
translate("Truncate cache files time"),
translate("Time after which cached files will be truncated"))
o.optional = true
o.placeholder = "4d12h"
o = s:taboption("advanced", Value, "diskCacheUnlinkTime",
translate("Delete cache files time"),
translate("Time after which cached files will be deleted"))
o.optional = true
o.placeholder = "32d"
-- Poor man's multiplexing section
s = m:section(NamedSection, "pmm", "polipo",
translate("Poor Man's Multiplexing"),
translate("Poor Man's Multiplexing (PMM) is a technique that simulates " ..
"multiplexing by requesting an instance in multiple segments. It " ..
"tries to lower the latency caused by the weakness of HTTP " ..
"protocol. NOTE: some sites may not work with PMM enabled."))
s:option(Value, "pmmSize", translate("PMM segments size (in bytes)"),
translate("To enable PMM, PMM segment size must be set to some " ..
"positive value.")).rmempty = true
s:option(Value, "pmmFirstSize", translate("First PMM segment size (in bytes)"),
translate("Size of the first PMM segment. If not defined, it defaults " ..
"to twice the PMM segment size.")).rmempty = true
return m
|
applications/luci-polipo: fix polipo page
|
applications/luci-polipo: fix polipo page
git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@6613 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
|
Lua
|
apache-2.0
|
fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci
|
60702239d04fe19780cacc6c8df08e5de826bd4f
|
src/jet/daemon/sorter.lua
|
src/jet/daemon/sorter.lua
|
local jutils = require'jet.utils'
local tinsert = table.insert
local tremove = table.remove
local tconcat = table.concat
local tsort = table.sort
local unpack = unpack
local mmin = math.min
local mmax = math.max
local noop = jutils.noop
local is_empty_table = jutils.is_empty_table
-- may create and return a sorter function.
-- the sort function is based on the options.sort entries.
local create_sorter = function(options,notify)
if not options.sort then
return nil
end
local sort
if not options.sort.byValue or options.sort.byPath then
if options.sort.descending then
sort = function(a,b)
return a.path > b.path
end
else
sort = function(a,b)
return a.path < b.path
end
end
else
local lt
local gt
if options.sort.byValue then
lt = function(a,b)
return a < b
end
gt = function(a,b)
return a > b
end
elseif options.sort.byValueField then
local tmp = options.sort.byValueField
local field_str = pairs(tmp)(tmp)
local get_field = jutils.access_field(field_str)
lt = function(a,b)
return get_field(a) < get_field(b)
end
gt = function(a,b)
return get_field(a) > get_field(b)
end
end
-- protected sort
local psort = function(s,a,b)
local ok,res = pcall(s,a,b)
if not ok or not res then
return false
else
return true
end
end
if options.sort.descending then
sort = function(a,b)
return psort(gt,a.value,b.value)
end
else
sort = function(a,b)
return psort(lt,a.value,b.value)
end
end
end
local from = options.sort.from or 1
local to = options.sort.to or 10
local sorted = {}
local matches = {}
local index = {}
local n
local is_in_range = function(i)
return i and i >= from and i <= to
end
local sorter = function(notification,initializing)
local event = notification.event
local path = notification.path
local value = notification.value
if initializing then
if index[path] then
return
end
tinsert(matches,{
path = path,
value = value,
})
index[path] = #matches
return
end
local last_matches_len = #matches
local lastindex = index[path]
if event == 'remove' then
if lastindex then
tremove(matches,lastindex)
index[path] = nil
else
return
end
elseif lastindex then
matches[lastindex].value = value
else
tinsert(matches,{
path = path,
value = value,
})
end
tsort(matches,sort)
for i,m in ipairs(matches) do
index[m.path] = i
end
if last_matches_len < from and #matches < from then
return
end
local newindex = index[path]
-- this may happen due to a refetch :(
if newindex and lastindex and newindex == lastindex then
if event == 'change' then
notify({
n = n,
changes = {
{
path = path,
value = value,
index = newindex,
}
}
})
end
return
end
local start
local stop
local is_in = is_in_range(newindex)
local was_in = is_in_range(lastindex)
if is_in and was_in then
start = mmin(lastindex,newindex)
stop = mmax(lastindex,newindex)
elseif is_in and not was_in then
start = newindex
stop = mmin(to,#matches)
elseif not is_in and was_in then
start = lastindex
stop = mmin(to,#matches)
else
start = from
stop = mmin(to,#matches)
end
local changes = {}
for i=start,stop do
local new = matches[i]
local old = sorted[i]
if new and new ~= old then
tinsert(changes,{
path = new.path,
value = new.value,
index = i,
})
end
sorted[i] = new
if not new then
break
end
end
local new_n = mmin(to,#matches) - from + 1
if new_n ~= n or #changes > 0 then
n = new_n
notify({
changes = changes,
n = n,
})
end
end
local flush = function()
tsort(matches,sort)
for i,m in ipairs(matches) do
index[m.path] = i
end
n = 0
local changes = {}
for i=from,to do
local new = matches[i]
if new then
new.index = i
n = i - from + 1
sorted[i] = new
tinsert(changes,new)
end
end
notify({
changes = changes,
n = n,
})
end
return sorter,flush
end
return {
new = create_sorter
}
|
local jutils = require'jet.utils'
local tinsert = table.insert
local tremove = table.remove
local tconcat = table.concat
local tsort = table.sort
local unpack = unpack
local mmin = math.min
local mmax = math.max
local noop = jutils.noop
local is_empty_table = jutils.is_empty_table
-- may create and return a sorter function.
-- the sort function is based on the options.sort entries.
local create_sorter = function(options,notify)
if not options.sort then
return nil
end
local sort
if (options.sort.byValue == nil and options.sort.byValueField == nil) or options.sort.byPath then
if options.sort.descending then
sort = function(a,b)
return a.path > b.path
end
else
sort = function(a,b)
return a.path < b.path
end
end
else
local lt
local gt
if options.sort.byValue then
lt = function(a,b)
return a < b
end
gt = function(a,b)
return a > b
end
elseif options.sort.byValueField then
local tmp = options.sort.byValueField
local field_str = pairs(tmp)(tmp)
local get_field = jutils.access_field(field_str)
lt = function(a,b)
return get_field(a) < get_field(b)
end
gt = function(a,b)
return get_field(a) > get_field(b)
end
end
-- protected sort
local psort = function(s,a,b)
local ok,res = pcall(s,a,b)
if not ok or not res then
return false
else
return true
end
end
if options.sort.descending then
sort = function(a,b)
return psort(gt,a.value,b.value)
end
else
sort = function(a,b)
return psort(lt,a.value,b.value)
end
end
end
assert(sort)
local from = options.sort.from or 1
local to = options.sort.to or 10
local sorted = {}
local matches = {}
local index = {}
local n
local is_in_range = function(i)
return i and i >= from and i <= to
end
local sorter = function(notification,initializing)
local event = notification.event
local path = notification.path
local value = notification.value
if initializing then
if index[path] then
return
end
tinsert(matches,{
path = path,
value = value,
})
index[path] = #matches
return
end
local last_matches_len = #matches
local lastindex = index[path]
if event == 'remove' then
if lastindex then
tremove(matches,lastindex)
index[path] = nil
else
return
end
elseif lastindex then
matches[lastindex].value = value
else
tinsert(matches,{
path = path,
value = value,
})
end
tsort(matches,sort)
for i,m in ipairs(matches) do
index[m.path] = i
end
if last_matches_len < from and #matches < from then
return
end
local newindex = index[path]
-- this may happen due to a refetch :(
if newindex and lastindex and newindex == lastindex then
if event == 'change' then
notify({
n = n,
changes = {
{
path = path,
value = value,
index = newindex,
}
}
})
end
return
end
local start
local stop
local is_in = is_in_range(newindex)
local was_in = is_in_range(lastindex)
if is_in and was_in then
start = mmin(lastindex,newindex)
stop = mmax(lastindex,newindex)
elseif is_in and not was_in then
start = newindex
stop = mmin(to,#matches)
elseif not is_in and was_in then
start = lastindex
stop = mmin(to,#matches)
else
start = from
stop = mmin(to,#matches)
end
local changes = {}
for i=start,stop do
local new = matches[i]
local old = sorted[i]
if new and new ~= old then
tinsert(changes,{
path = new.path,
value = new.value,
index = i,
})
end
sorted[i] = new
if not new then
break
end
end
local new_n = mmin(to,#matches) - from + 1
if new_n ~= n or #changes > 0 then
n = new_n
notify({
changes = changes,
n = n,
})
end
end
local flush = function()
tsort(matches,sort)
for i,m in ipairs(matches) do
index[m.path] = i
end
n = 0
local changes = {}
for i=from,to do
local new = matches[i]
if new then
new.index = i
n = i - from + 1
sorted[i] = new
tinsert(changes,new)
end
end
notify({
changes = changes,
n = n,
})
end
return sorter,flush
end
return {
new = create_sorter
}
|
fix sorting issue
|
fix sorting issue
|
Lua
|
mit
|
lipp/lua-jet
|
853495b0b710ca47abda5a98bedad07f69272c37
|
lua/entities/gmod_wire_starfall_screen/init.lua
|
lua/entities/gmod_wire_starfall_screen/init.lua
|
AddCSLuaFile('cl_init.lua')
AddCSLuaFile('shared.lua')
include('shared.lua')
include("starfall/SFLib.lua")
assert(SF, "Starfall didn't load correctly!")
local context = SF.CreateContext()
local screens = {}
util.AddNetworkString("starfall_screen_download")
util.AddNetworkString("starfall_screen_update")
local function sendScreenCode(screen, owner, files, mainfile, recipient)
print("Sending SF code")
net.Start("starfall_screen_download")
net.WriteEntity(screen)
net.WriteEntity(owner)
net.WriteString(mainfile)
if recipient then net.Send(recipient) else net.Broadcast() end
print("\tHeader sent")
local fname = next(files)
while fname do
print("\tSending data for:", fname)
local fdata = files[fname]
local offset = 1
repeat
net.Start("starfall_screen_download")
net.WriteBit(false)
net.WriteString(fname)
local data = fdata:sub(offset, offset+60000)
net.WriteString(data)
if recipient then net.Send(recipient) else net.Broadcast() end
--print("\t\tSent data from", offset, "to", offset + #data)
offset = offset + #data + 1
until offset > #fdata
fname = next(files, fname)
end
net.Start("starfall_screen_download")
net.WriteBit(true)
if recipient then net.Send(recipient) else net.Broadcast() end
print("Done sending")
print(files[mainfile])
end
local requests = {}
local function sendCodeRequest(ply, screen)
if not IsValid(screen) then debug.Trace() end
if not screen.mainfile and not requests[screen] then
requests[screen] = {player = ply, tries = 0 }
return
--[[if timer.Exists("starfall_send_code_request") then return end
timer.Create("starfall_send_code_request", .5, 1, retryCodeRequests) ]]
elseif screen.mainfile then
requests[screen] = nil
sendScreenCode(screen, screen.owner, screen.files, screen.mainfile, ply)
end
end
local function retryCodeRequests()
for k,v in pairs(requests) do
sendCodeRequest(v.player, k)
end
end
net.Receive("starfall_screen_download", function(len, ply)
local screen = net.ReadEntity()
sendCodeRequest(ply, screen)
end)
function ENT:Initialize()
self:PhysicsInit(SOLID_VPHYSICS)
self:SetMoveType(MOVETYPE_VPHYSICS)
self:SetSolid(SOLID_VPHYSICS)
self:SetUseType( 3 )
self.Inputs = WireLib.CreateInputs(self, {})
self.Outputs = WireLib.CreateOutputs(self, {})
local r,g,b,a = self:GetColor()
end
function ENT:OnRestore()
end
function ENT:UpdateName(state)
if state ~= "" then state = "\n"..state end
if self.instance and self.instance.ppdata.scriptnames and self.instance.mainfile and self.instance.ppdata.scriptnames[self.instance.mainfile] then
self:SetOverlayText("Starfall Processor\n"..tostring(self.instance.ppdata.scriptnames[self.instance.mainfile])..state)
else
self:SetOverlayText("Starfall Processor"..state)
end
end
function ENT:Error(msg, override)
ErrorNoHalt("Processor of "..self.owner:Nick().." errored: "..msg.."\n")
WireLib.ClientError(msg, self.owner)
if self.instance then
self.instance:deinitialize()
self.instance = nil
end
self:UpdateName("Inactive (Error)")
local r,g,b,a = self:GetColor()
self:SetColor(255, 0, 0, a)
end
function ENT:CodeSent(ply, files, mainfile)
if ply ~= self.owner then return end
local update = self.mainfile ~= nil
self.files = files
self.mainfile = mainfile
screens[self] = self
if update then
net.Start("starfall_screen_update")
net.WriteEntity(self)
for k,v in pairs(files) do
net.WriteBit(false)
net.WriteString(k)
net.WriteString(util.CRC(v))
end
net.WriteBit(true)
net.Broadcast()
--sendScreenCode(self, ply, files, mainfile)
end
local ppdata = {}
SF.Preprocessor.ParseDirectives(mainfile, files[mainfile], {}, ppdata)
if ppdata.sharedscreen then
local ok, instance = SF.Compiler.Compile(files,context,mainfile,ply)
if not ok then self:Error(instance) return end
if self.instance then
self.instance:deinitialize()
self.instance = nil
end
self.instance = instance
instance.data.entity = self
local ok, msg = instance:initialize()
if not ok then
self:Error(msg)
return
end
self:UpdateName("")
local r,g,b,a = self:GetColor()
self:SetColor(Color(255, 255, 255, a))
self.sharedscreen = true
end
end
local i = 0
function ENT:Think()
self.BaseClass.Think(self)
i = i + 1
if i % 66 == 0 then
retryCodeRequests()
PrintTable(requests)
i = 0
end
self:NextThink(CurTime())
if self.instance and not self.instance.error then
self.instance:resetOps()
self:runScriptHook("think")
end
return true
end
-- Sends a umsg to all clients about the use.
function ENT:Use( activator )
if activator:IsPlayer() then
umsg.Start( "starfall_screen_used" )
umsg.Short( self:EntIndex() )
umsg.Short( activator:EntIndex() )
umsg.End( )
end
if self.sharedscreen then
self:runScriptHook( "starfall_used", SF.Entities.Wrap( activator ) )
end
end
function ENT:OnRemove()
if not self.instance then return end
screens[self] = nil
self.instance:deinitialize()
self.instance = nil
end
function ENT:TriggerInput(key, value)
self:runScriptHook("input",key,value)
end
function ENT:BuildDupeInfo()
local info = self.BaseClass.BuildDupeInfo(self) or {}
info.starfall = SF.SerializeCode(self.task.files, self.task.mainfile)
return info
end
function ENT:ApplyDupeInfo(ply, ent, info, GetEntByID)
self.BaseClass.ApplyDupeInfo(self, ply, ent, info, GetEntByID)
self.owner = ply
local code, main = SF.DeserializeCode(info.starfall)
local task = {files = code, mainfile = main}
self:CodeSent(ply, task)
end
|
AddCSLuaFile('cl_init.lua')
AddCSLuaFile('shared.lua')
include('shared.lua')
include("starfall/SFLib.lua")
assert(SF, "Starfall didn't load correctly!")
local context = SF.CreateContext()
local screens = {}
util.AddNetworkString("starfall_screen_download")
util.AddNetworkString("starfall_screen_update")
local function sendScreenCode(screen, owner, files, mainfile, recipient)
--print("Sending SF code for: " .. tostring(recipient))
net.Start("starfall_screen_download")
net.WriteEntity(screen)
net.WriteEntity(owner)
net.WriteString(mainfile)
if recipient then net.Send(recipient) else net.Broadcast() end
--print("\tHeader sent")
local fname = next(files)
while fname do
--print("\tSending data for:", fname)
local fdata = files[fname]
local offset = 1
repeat
net.Start("starfall_screen_download")
net.WriteBit(false)
net.WriteString(fname)
local data = fdata:sub(offset, offset+60000)
net.WriteString(data)
if recipient then net.Send(recipient) else net.Broadcast() end
--print("\t\tSent data from", offset, "to", offset + #data)
offset = offset + #data + 1
until offset > #fdata
fname = next(files, fname)
end
net.Start("starfall_screen_download")
net.WriteBit(true)
if recipient then net.Send(recipient) else net.Broadcast() end
--print("Done sending")
end
local requests = {}
local function sendCodeRequest(ply, screenid)
local screen = Entity(screenid)
if not IsValid(screen) then debug.Trace() end
if not screen.mainfile then
if not requests[screenid] then requests[screenid] = {} end
if requests[screenid][player] then return end
requests[screenid][ply] = true
return
--[[if timer.Exists("starfall_send_code_request") then return end
timer.Create("starfall_send_code_request", .5, 1, retryCodeRequests) ]]
elseif screen.mainfile then
if requests[screenid] then
requests[screenid][ply] = nil
end
sendScreenCode(screen, screen.owner, screen.files, screen.mainfile, ply)
end
end
local function retryCodeRequests()
for screenid,plys in pairs(requests) do
for ply,_ in pairs(requests[screenid]) do
sendCodeRequest(ply, screenid)
end
end
end
net.Receive("starfall_screen_download", function(len, ply)
local screen = net.ReadEntity()
sendCodeRequest(ply, screen:EntIndex())
end)
function ENT:Initialize()
self:PhysicsInit(SOLID_VPHYSICS)
self:SetMoveType(MOVETYPE_VPHYSICS)
self:SetSolid(SOLID_VPHYSICS)
self:SetUseType( 3 )
self.Inputs = WireLib.CreateInputs(self, {})
self.Outputs = WireLib.CreateOutputs(self, {})
local r,g,b,a = self:GetColor()
end
function ENT:OnRestore()
end
function ENT:UpdateName(state)
if state ~= "" then state = "\n"..state end
if self.instance and self.instance.ppdata.scriptnames and self.instance.mainfile and self.instance.ppdata.scriptnames[self.instance.mainfile] then
self:SetOverlayText("Starfall Processor\n"..tostring(self.instance.ppdata.scriptnames[self.instance.mainfile])..state)
else
self:SetOverlayText("Starfall Processor"..state)
end
end
function ENT:Error(msg, override)
ErrorNoHalt("Processor of "..self.owner:Nick().." errored: "..msg.."\n")
WireLib.ClientError(msg, self.owner)
if self.instance then
self.instance:deinitialize()
self.instance = nil
end
self:UpdateName("Inactive (Error)")
local r,g,b,a = self:GetColor()
self:SetColor(255, 0, 0, a)
end
function ENT:CodeSent(ply, files, mainfile)
if ply ~= self.owner then return end
local update = self.mainfile ~= nil
self.files = files
self.mainfile = mainfile
screens[self] = self
if update then
net.Start("starfall_screen_update")
net.WriteEntity(self)
for k,v in pairs(files) do
net.WriteBit(false)
net.WriteString(k)
net.WriteString(util.CRC(v))
end
net.WriteBit(true)
net.Broadcast()
--sendScreenCode(self, ply, files, mainfile)
end
local ppdata = {}
SF.Preprocessor.ParseDirectives(mainfile, files[mainfile], {}, ppdata)
if ppdata.sharedscreen then
local ok, instance = SF.Compiler.Compile(files,context,mainfile,ply)
if not ok then self:Error(instance) return end
if self.instance then
self.instance:deinitialize()
self.instance = nil
end
self.instance = instance
instance.data.entity = self
local ok, msg = instance:initialize()
if not ok then
self:Error(msg)
return
end
self:UpdateName("")
local r,g,b,a = self:GetColor()
self:SetColor(Color(255, 255, 255, a))
self.sharedscreen = true
end
end
local i = 0
function ENT:Think()
self.BaseClass.Think(self)
i = i + 1
if i % 22 == 0 then
retryCodeRequests()
i = 0
end
self:NextThink(CurTime())
if self.instance and not self.instance.error then
self.instance:resetOps()
self:runScriptHook("think")
end
return true
end
-- Sends a umsg to all clients about the use.
function ENT:Use( activator )
if activator:IsPlayer() then
umsg.Start( "starfall_screen_used" )
umsg.Short( self:EntIndex() )
umsg.Short( activator:EntIndex() )
umsg.End( )
end
if self.sharedscreen then
self:runScriptHook( "starfall_used", SF.Entities.Wrap( activator ) )
end
end
function ENT:OnRemove()
if not self.instance then return end
screens[self] = nil
self.instance:deinitialize()
self.instance = nil
end
function ENT:TriggerInput(key, value)
self:runScriptHook("input",key,value)
end
function ENT:BuildDupeInfo()
local info = self.BaseClass.BuildDupeInfo(self) or {}
info.starfall = SF.SerializeCode(self.task.files, self.task.mainfile)
return info
end
function ENT:ApplyDupeInfo(ply, ent, info, GetEntByID)
self.BaseClass.ApplyDupeInfo(self, ply, ent, info, GetEntByID)
self.owner = ply
local code, main = SF.DeserializeCode(info.starfall)
local task = {files = code, mainfile = main}
self:CodeSent(ply, task)
end
|
[Fix] screens not receiving data
|
[Fix] screens not receiving data
FINALLY - it should be completely fixed now.
|
Lua
|
bsd-3-clause
|
INPStarfall/Starfall,Jazzelhawk/Starfall,Xandaros/Starfall,Ingenious-Gaming/Starfall,INPStarfall/Starfall,Ingenious-Gaming/Starfall,Jazzelhawk/Starfall,Xandaros/Starfall
|
92dc9b939c16f10da77c41962b5b2f5c7a92f433
|
game/scripts/vscripts/items/item_unstable_quasar.lua
|
game/scripts/vscripts/items/item_unstable_quasar.lua
|
LinkLuaModifier("modifier_item_unstable_quasar_passive", "items/item_unstable_quasar.lua", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_item_unstable_quasar_slow", "items/item_unstable_quasar.lua", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_item_unstable_quasar_aura", "items/item_unstable_quasar.lua", LUA_MODIFIER_MOTION_NONE)
item_unstable_quasar = class({
GetIntrinsicModifierName = function() return "modifier_item_unstable_quasar_passive" end,
})
function item_unstable_quasar:GetManaCost()
local caster = self:GetCaster()
if not caster then return end
local percentage = caster:GetMaxMana() * self:GetSpecialValueFor("manacost_pct") * 0.01
return self:GetSpecialValueFor("manacost") + percentage
end
modifier_item_unstable_quasar_passive = class({
IsHidden = function() return true end,
IsPurgable = function() return false end,
RemoveOnDeath = function() return false end,
})
function modifier_item_unstable_quasar_passive:DeclareFunctions()
return {
MODIFIER_EVENT_ON_ABILITY_EXECUTED,
MODIFIER_PROPERTY_BONUS_DAY_VISION,
MODIFIER_PROPERTY_BONUS_NIGHT_VISION,
MODIFIER_PROPERTY_STATS_INTELLECT_BONUS,
MODIFIER_PROPERTY_SPELL_AMPLIFY_PERCENTAGE,
MODIFIER_PROPERTY_TOTALDAMAGEOUTGOING_PERCENTAGE,
}
end
if IsServer() then
function modifier_item_unstable_quasar_passive:OnAbilityExecuted(keys)
local caster = self:GetParent()
if caster ~= keys.unit then return end
local ability = self:GetAbility()
local usedAbility = keys.ability
local team = caster:GetTeam()
local pos = caster:GetAbsOrigin()
local radius = ability:GetSpecialValueFor("singularity_radius")
if (
PreformAbilityPrecastActions(caster, ability) and
usedAbility:GetCooldown(usedAbility:GetLevel()) >= ability:GetSpecialValueFor("min_ability_cooldown") and
usedAbility:GetManaCost(usedAbility:GetLevel()) ~= 0
) then
for _,v in ipairs(FindUnitsInRadius(team, pos, nil, radius, ability:GetAbilityTargetTeam(), ability:GetAbilityTargetType(), ability:GetAbilityTargetFlags(), FIND_ANY_ORDER, false)) do
local enemyPos = v:GetAbsOrigin()
local damage = v:GetHealth() * ability:GetSpecialValueFor(caster:GetPrimaryAttribute() == DOTA_ATTRIBUTE_INTELLECT and "intelligence_damage_pct" or "damage_pct") * 0.01 + ability:GetSpecialValueFor("base_damage")
ApplyDamage({
attacker = caster,
victim = v,
damage = damage,
damage_type = ability:GetAbilityDamageType(),
damage_flags = DOTA_DAMAGE_FLAG_NO_SPELL_AMPLIFICATION,
ability = self:GetAbility()
})
local particle = ParticleManager:CreateParticle("particles/units/heroes/hero_zuus/zuus_arc_lightning.vpcf", PATTACH_ABSORIGIN_FOLLOW, caster)
ParticleManager:SetParticleControlEnt(
particle,
0,
caster,
PATTACH_POINT_FOLLOW,
"attach_attack1",
caster:GetAbsOrigin(),
true
)
ParticleManager:SetParticleControl(particle, 1, enemyPos)
v:AddNewModifier(caster, ability, "modifier_item_unstable_quasar_slow", {duration = ability:GetSpecialValueFor("slow_duration")})
local direction = (pos - enemyPos):Normalized()
local distance = ability:GetSpecialValueFor("offset_range")
FindClearSpaceForUnit(v, GetGroundPosition(enemyPos + direction * distance, caster), true)
end
end
end
end
function modifier_item_unstable_quasar_passive:GetBonusDayVision()
return self:GetAbility():GetSpecialValueFor("bonus_day_vision")
end
function modifier_item_unstable_quasar_passive:GetBonusNightVision()
return self:GetAbility():GetSpecialValueFor("bonus_night_vision")
end
function modifier_item_unstable_quasar_passive:GetModifierBonusStats_Intellect()
return self:GetAbility():GetSpecialValueFor("bonus_intellect")
end
function modifier_item_unstable_quasar_passive:GetModifierSpellAmplify_Percentage()
return self:GetAbility():GetSpecialValueFor("spell_amp_pct")
end
function modifier_item_unstable_quasar_passive:GetModifierTotalDamageOutgoing_Percentage()
return self:GetAbility():GetSpecialValueFor("increase_all_damage_pct")
end
function modifier_item_unstable_quasar_passive:GetModifierAura()
return "modifier_item_unstable_quasar_aura"
end
function modifier_item_unstable_quasar_passive:IsAura()
return true
end
function modifier_item_unstable_quasar_passive:GetAuraRadius()
return self:GetAbility():GetSpecialValueFor("aura_radius")
end
function modifier_item_unstable_quasar_passive:GetAuraSearchTeam()
return self:GetAbility():GetAbilityTargetTeam()
end
function modifier_item_unstable_quasar_passive:GetAuraSearchType()
return self:GetAbility():GetAbilityTargetType()
end
modifier_item_unstable_quasar_slow = class({
IsHidden = function() return false end,
IsPurgable = function() return true end,
IsDebuff = function() return true end,
GetEffectName = function() return "particles/items_fx/diffusal_slow.vpcf" end,
})
function modifier_item_unstable_quasar_slow:DeclareFunctions()
return {
MODIFIER_PROPERTY_MOVESPEED_MAX,
MODIFIER_PROPERTY_MOVESPEED_LIMIT,
MODIFIER_PROPERTY_MOVESPEED_ABSOLUTE
}
end
function modifier_item_unstable_quasar_slow:GetModifierMoveSpeed_Limit()
return self:GetAbility():GetSpecialValueFor("slow_speed")
end
function modifier_item_unstable_quasar_slow:GetModifierMoveSpeed_Max()
return self:GetAbility():GetSpecialValueFor("slow_speed")
end
function modifier_item_unstable_quasar_slow:GetModifierMoveSpeed_Absolute()
return self:GetAbility():GetSpecialValueFor("slow_speed")
end
modifier_item_unstable_quasar_aura = class({
DeclareFunctions = function() return { MODIFIER_PROPERTY_MAGICAL_RESISTANCE_BONUS } end,
GetPriority = function() return { MODIFIER_PRIORITY_HIGH } end,
})
function modifier_item_unstable_quasar_aura:GetModifierMagicalResistanceBonus()
return -self:GetAbility():GetSpecialValueFor("aura_resist_debuff_pct")
end
function modifier_item_unstable_quasar_aura:CheckState()
return {
[MODIFIER_STATE_INVISIBLE] = false,
}
end
|
LinkLuaModifier("modifier_item_unstable_quasar_passive", "items/item_unstable_quasar.lua", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_item_unstable_quasar_slow", "items/item_unstable_quasar.lua", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_item_unstable_quasar_aura", "items/item_unstable_quasar.lua", LUA_MODIFIER_MOTION_NONE)
item_unstable_quasar = class({
GetIntrinsicModifierName = function() return "modifier_item_unstable_quasar_passive" end,
})
function item_unstable_quasar:GetManaCost()
local caster = self:GetCaster()
if not caster then return end
local percentage = caster:GetMaxMana() * self:GetSpecialValueFor("manacost_pct") * 0.01
return self:GetSpecialValueFor("manacost") + percentage
end
modifier_item_unstable_quasar_passive = class({
IsHidden = function() return true end,
IsPurgable = function() return false end,
RemoveOnDeath = function() return false end,
})
function modifier_item_unstable_quasar_passive:DeclareFunctions()
return {
MODIFIER_EVENT_ON_ABILITY_EXECUTED,
MODIFIER_PROPERTY_BONUS_DAY_VISION,
MODIFIER_PROPERTY_BONUS_NIGHT_VISION,
MODIFIER_PROPERTY_STATS_INTELLECT_BONUS,
MODIFIER_PROPERTY_SPELL_AMPLIFY_PERCENTAGE,
MODIFIER_PROPERTY_TOTALDAMAGEOUTGOING_PERCENTAGE,
}
end
if IsServer() then
function modifier_item_unstable_quasar_passive:OnAbilityExecuted(keys)
local caster = self:GetParent()
if caster ~= keys.unit then return end
local ability = self:GetAbility()
local usedAbility = keys.ability
local team = caster:GetTeam()
local pos = caster:GetAbsOrigin()
local radius = ability:GetSpecialValueFor("singularity_radius")
if (
usedAbility:GetCooldown(usedAbility:GetLevel()) >= ability:GetSpecialValueFor("min_ability_cooldown") and
usedAbility:GetManaCost(usedAbility:GetLevel()) ~= 0 and
PreformAbilityPrecastActions(caster, ability)
) then
for _,v in ipairs(FindUnitsInRadius(team, pos, nil, radius, ability:GetAbilityTargetTeam(), ability:GetAbilityTargetType(), ability:GetAbilityTargetFlags(), FIND_ANY_ORDER, false)) do
local enemyPos = v:GetAbsOrigin()
local damage = v:GetHealth() * ability:GetSpecialValueFor(caster:GetPrimaryAttribute() == DOTA_ATTRIBUTE_INTELLECT and "intelligence_damage_pct" or "damage_pct") * 0.01 + ability:GetSpecialValueFor("base_damage")
ApplyDamage({
attacker = caster,
victim = v,
damage = damage,
damage_type = ability:GetAbilityDamageType(),
damage_flags = DOTA_DAMAGE_FLAG_NO_SPELL_AMPLIFICATION,
ability = self:GetAbility()
})
local particle = ParticleManager:CreateParticle("particles/units/heroes/hero_zuus/zuus_arc_lightning.vpcf", PATTACH_ABSORIGIN_FOLLOW, caster)
ParticleManager:SetParticleControlEnt(
particle,
0,
caster,
PATTACH_POINT_FOLLOW,
"attach_attack1",
caster:GetAbsOrigin(),
true
)
ParticleManager:SetParticleControl(particle, 1, enemyPos)
v:AddNewModifier(caster, ability, "modifier_item_unstable_quasar_slow", {duration = ability:GetSpecialValueFor("slow_duration")})
local direction = (pos - enemyPos):Normalized()
local distance = ability:GetSpecialValueFor("offset_range")
FindClearSpaceForUnit(v, GetGroundPosition(enemyPos + direction * distance, caster), true)
end
end
end
end
function modifier_item_unstable_quasar_passive:GetBonusDayVision()
return self:GetAbility():GetSpecialValueFor("bonus_day_vision")
end
function modifier_item_unstable_quasar_passive:GetBonusNightVision()
return self:GetAbility():GetSpecialValueFor("bonus_night_vision")
end
function modifier_item_unstable_quasar_passive:GetModifierBonusStats_Intellect()
return self:GetAbility():GetSpecialValueFor("bonus_intellect")
end
function modifier_item_unstable_quasar_passive:GetModifierSpellAmplify_Percentage()
return self:GetAbility():GetSpecialValueFor("spell_amp_pct")
end
function modifier_item_unstable_quasar_passive:GetModifierTotalDamageOutgoing_Percentage()
return self:GetAbility():GetSpecialValueFor("increase_all_damage_pct")
end
function modifier_item_unstable_quasar_passive:GetModifierAura()
return "modifier_item_unstable_quasar_aura"
end
function modifier_item_unstable_quasar_passive:IsAura()
return true
end
function modifier_item_unstable_quasar_passive:GetAuraRadius()
return self:GetAbility():GetSpecialValueFor("aura_radius")
end
function modifier_item_unstable_quasar_passive:GetAuraSearchTeam()
return self:GetAbility():GetAbilityTargetTeam()
end
function modifier_item_unstable_quasar_passive:GetAuraSearchType()
return self:GetAbility():GetAbilityTargetType()
end
modifier_item_unstable_quasar_slow = class({
IsHidden = function() return false end,
IsPurgable = function() return true end,
IsDebuff = function() return true end,
GetEffectName = function() return "particles/items_fx/diffusal_slow.vpcf" end,
})
function modifier_item_unstable_quasar_slow:DeclareFunctions()
return {
MODIFIER_PROPERTY_MOVESPEED_MAX,
MODIFIER_PROPERTY_MOVESPEED_LIMIT,
MODIFIER_PROPERTY_MOVESPEED_ABSOLUTE
}
end
function modifier_item_unstable_quasar_slow:GetModifierMoveSpeed_Limit()
return self:GetAbility():GetSpecialValueFor("slow_speed")
end
function modifier_item_unstable_quasar_slow:GetModifierMoveSpeed_Max()
return self:GetAbility():GetSpecialValueFor("slow_speed")
end
function modifier_item_unstable_quasar_slow:GetModifierMoveSpeed_Absolute()
return self:GetAbility():GetSpecialValueFor("slow_speed")
end
modifier_item_unstable_quasar_aura = class({
DeclareFunctions = function() return { MODIFIER_PROPERTY_MAGICAL_RESISTANCE_BONUS } end,
GetPriority = function() return { MODIFIER_PRIORITY_HIGH } end,
})
function modifier_item_unstable_quasar_aura:GetModifierMagicalResistanceBonus()
return -self:GetAbility():GetSpecialValueFor("aura_resist_debuff_pct")
end
function modifier_item_unstable_quasar_aura:CheckState()
return {
[MODIFIER_STATE_INVISIBLE] = false,
}
end
|
fix(items): Unstable Quasar wastes mana on invalid abilities (#234)
|
fix(items): Unstable Quasar wastes mana on invalid abilities (#234)
|
Lua
|
mit
|
ark120202/aabs
|
58cae5a3513c367344b4ee8feddb237c1abe251e
|
canvas.lua
|
canvas.lua
|
local url_count = 0
local tries = 0
read_file = function(file)
if file then
local f = assert(io.open(file))
local data = f:read("*all")
f:close()
return data
else
return ""
end
end
wget.callbacks.lookup_host = function(host)
if host == "canv.as" or host == "www.canv.as" then
-- FIXME: i don't know why wget keeps saying wget-lua: unable to resolve host address 'canv.as'
local table = {'54.231.14.172', '176.32.101.156', '176.32.99.220', '205.251.243.76', '54.240.235.193', '176.32.102.92'}
local ip = table[ math.random( #table ) ]
io.stdout:write("IP" .. ip .. "\n")
io.stdout:flush()
return ip
end
end
--
--wget.callbacks.download_child_p = function(urlpos, parent, depth, start_url_parsed, iri, verdict, reason)
-- if urlpos["link_inline_p"] then
-- -- always download the page requisites
-- return true
-- end
--
-- return verdict
--end
wget.callbacks.httploop_result = function(url, err, http_stat)
-- NEW for 2014: Slightly more verbose messages because people keep
-- complaining that it's not moving or not working
local status_code = http_stat["statcode"]
url_count = url_count + 1
io.stdout:write(url_count .. "=" .. status_code .. " " .. url["url"] .. ". \n")
-- io.stdout:write(url_count .. "=" .. status_code .. " " .. url["url"] .. ". \r")
io.stdout:flush()
if status_code >= 500 or
(status_code >= 400 and status_code ~= 404) then
io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n")
io.stdout:flush()
os.execute("sleep 10")
tries = tries + 1
if tries >= 5 then
io.stdout:write("\nI give up...\n")
io.stdout:flush()
return wget.actions.ABORT
else
return wget.actions.CONTINUE
end
end
tries = 0
-- We're okay; sleep a bit (if we have to) and continue
local sleep_time = 0.1 * (math.random(75, 1000) / 100.0)
-- if string.match(url["host"], "cdn") or string.match(url["host"], "media") then
-- -- We should be able to go fast on images since that's what a web browser does
-- sleep_time = 0
-- end
if sleep_time > 0.001 then
os.execute("sleep " .. sleep_time)
end
return wget.actions.NOTHING
end
wget.callbacks.get_urls = function(file, url, is_css, iri)
local urls = {}
local html = read_file(file)
for url in string.gfind(html, "url%(([^%)]+)%)") do
-- ignore things like " + original + " which is javascript
if not string.match(url, " %+") then
io.stdout:write("\n Added " .. url .. ".\n")
io.stdout:flush()
table.insert(urls, { url=url })
end
end
for url in string.gfind(html, "'(http[^']+)'") do
io.stdout:write("\n Added " .. url .. ".\n")
io.stdout:flush()
table.insert(urls, { url=url })
end
return urls
end
|
local url_count = 0
local tries = 0
read_file = function(file)
if file then
local f = assert(io.open(file))
local data = f:read("*all")
f:close()
return data
else
return ""
end
end
wget.callbacks.lookup_host = function(host)
if host == "canv.as" or host == "www.canv.as" then
return 'drawquest-export.s3-website-us-east-1.amazonaws.com'
end
end
--
--wget.callbacks.download_child_p = function(urlpos, parent, depth, start_url_parsed, iri, verdict, reason)
-- if urlpos["link_inline_p"] then
-- -- always download the page requisites
-- return true
-- end
--
-- return verdict
--end
wget.callbacks.httploop_result = function(url, err, http_stat)
-- NEW for 2014: Slightly more verbose messages because people keep
-- complaining that it's not moving or not working
local status_code = http_stat["statcode"]
url_count = url_count + 1
io.stdout:write(url_count .. "=" .. status_code .. " " .. url["url"] .. ". \r")
io.stdout:flush()
if status_code >= 500 or
(status_code >= 400 and status_code ~= 404) then
io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n")
io.stdout:flush()
os.execute("sleep 10")
tries = tries + 1
if tries >= 5 then
io.stdout:write("\nI give up...\n")
io.stdout:flush()
return wget.actions.ABORT
else
return wget.actions.CONTINUE
end
end
tries = 0
-- We're okay; sleep a bit (if we have to) and continue
local sleep_time = 0.1 * (math.random(75, 1000) / 100.0)
-- if string.match(url["host"], "cdn") or string.match(url["host"], "media") then
-- -- We should be able to go fast on images since that's what a web browser does
-- sleep_time = 0
-- end
if sleep_time > 0.001 then
os.execute("sleep " .. sleep_time)
end
return wget.actions.NOTHING
end
wget.callbacks.get_urls = function(file, url, is_css, iri)
local urls = {}
local html = read_file(file)
for url in string.gfind(html, "url%(([%w/%%.:_-]+)%)") do
-- prevent segfault of missing full url
if url:sub(1, 4) ~= 'http' then
if url:sub(1, 1) ~= '/' then
url = '/' .. url
end
url = 'http://canv.as' .. url
end
-- io.stdout:write("\n Added " .. url .. ".\n")
-- io.stdout:flush()
table.insert(urls, { url=url })
end
for url in string.gfind(html, "'(http[%w/%%.:_-]+)'") do
-- io.stdout:write("\n Added " .. url .. ".\n")
-- io.stdout:flush()
table.insert(urls, { url=url })
end
return urls
end
|
canvas.lua: Fix up lookup_host and fix segfault of url insertion.
|
canvas.lua: Fix up lookup_host and fix segfault of url insertion.
|
Lua
|
unlicense
|
ArchiveTeam/canvas-archive-grab,ArchiveTeam/canvas-archive-grab
|
9ece6408f3957e7e7520a833d92f816722ed07e1
|
frontend/gettext.lua
|
frontend/gettext.lua
|
local isAndroid, android = pcall(require, "android")
local logger = require("logger")
local GetText = {
translation = {},
current_lang = "C",
dirname = "l10n",
textdomain = "koreader"
}
local GetText_mt = {
__index = {}
}
function GetText_mt.__call(gettext, string)
return gettext.translation[string] or string
end
local function c_escape(what)
if what == "\n" then return ""
elseif what == "a" then return "\a"
elseif what == "b" then return "\b"
elseif what == "f" then return "\f"
elseif what == "n" then return "\n"
elseif what == "r" then return "\r"
elseif what == "t" then return "\t"
elseif what == "v" then return "\v"
elseif what == "0" then return "\0" -- shouldn't happen, though
else
return what
end
end
-- for PO file syntax, see
-- https://www.gnu.org/software/gettext/manual/html_node/PO-Files.html
-- we only implement a sane subset for now
function GetText_mt.__index.changeLang(new_lang)
if new_lang == "en_US:en" then return end
GetText.translation = {}
GetText.current_lang = "C"
-- the "C" locale disables localization alltogether
if new_lang == "C" or new_lang == nil then return end
-- strip encoding suffix in locale like "zh_CN.utf8"
new_lang = new_lang:sub(1, new_lang:find(".%."))
local file = GetText.dirname .. "/" .. new_lang .. "/" .. GetText.textdomain .. ".po"
local po = io.open(file, "r")
if not po then
logger.err("cannot open translation file:", file)
return
end
local data = {}
local what = nil
while true do
local line = po:read("*l")
if line == nil or line == "" then
if data.msgid and data.msgstr and data.msgstr ~= "" then
GetText.translation[data.msgid] = string.gsub(data.msgstr, "\\(.)", c_escape)
end
-- stop at EOF:
if line == nil then break end
data = {}
what = nil
else
-- comment
if not line:match("^#") then
-- new data item (msgid, msgstr, ...
local w, s = line:match("^%s*(%a+)%s+\"(.*)\"%s*$")
if w then
what = w
else
-- string continuation
s = line:match("^%s*\"(.*)\"%s*$")
end
if what and s then
-- unescape \n or msgid won't match
s = s:gsub("\\n", "\n")
-- unescape " or msgid won't match
s = s:gsub('\\"', '"')
data[what] = (data[what] or "") .. s
end
end
end
end
GetText.current_lang = new_lang
end
setmetatable(GetText, GetText_mt)
if os.getenv("LANGUAGE") then
GetText.changeLang(os.getenv("LANGUAGE"))
elseif os.getenv("LC_ALL") then
GetText.changeLang(os.getenv("LC_ALL"))
elseif os.getenv("LC_MESSAGES") then
GetText.changeLang(os.getenv("LC_MESSAGES"))
elseif os.getenv("LANG") then
GetText.changeLang(os.getenv("LANG"))
end
if isAndroid then
local ffi = require("ffi")
local buf = ffi.new("char[?]", 16)
android.lib.AConfiguration_getLanguage(android.app.config, buf)
local lang = ffi.string(buf)
android.lib.AConfiguration_getCountry(android.app.config, buf)
local country = ffi.string(buf)
if lang and country then
GetText.changeLang(lang.."_"..country)
end
end
return GetText
|
local isAndroid, android = pcall(require, "android")
local logger = require("logger")
local GetText = {
translation = {},
current_lang = "C",
dirname = "l10n",
textdomain = "koreader"
}
local GetText_mt = {
__index = {}
}
function GetText_mt.__call(gettext, string)
return gettext.translation[string] or string
end
local function c_escape(what)
if what == "\n" then return ""
elseif what == "a" then return "\a"
elseif what == "b" then return "\b"
elseif what == "f" then return "\f"
elseif what == "n" then return "\n"
elseif what == "r" then return "\r"
elseif what == "t" then return "\t"
elseif what == "v" then return "\v"
elseif what == "0" then return "\0" -- shouldn't happen, though
else
return what
end
end
-- for PO file syntax, see
-- https://www.gnu.org/software/gettext/manual/html_node/PO-Files.html
-- we only implement a sane subset for now
function GetText_mt.__index.changeLang(new_lang)
-- can be various things such as `en_US` or `en_US:en`
if new_lang:match("^en_US") == "en_US" then return end
GetText.translation = {}
GetText.current_lang = "C"
-- the "C" locale disables localization alltogether
if new_lang == "C" or new_lang == nil then return end
-- strip encoding suffix in locale like "zh_CN.utf8"
new_lang = new_lang:sub(1, new_lang:find(".%."))
local file = GetText.dirname .. "/" .. new_lang .. "/" .. GetText.textdomain .. ".po"
local po = io.open(file, "r")
if not po then
logger.err("cannot open translation file:", file)
return
end
local data = {}
local what = nil
while true do
local line = po:read("*l")
if line == nil or line == "" then
if data.msgid and data.msgstr and data.msgstr ~= "" then
GetText.translation[data.msgid] = string.gsub(data.msgstr, "\\(.)", c_escape)
end
-- stop at EOF:
if line == nil then break end
data = {}
what = nil
else
-- comment
if not line:match("^#") then
-- new data item (msgid, msgstr, ...
local w, s = line:match("^%s*(%a+)%s+\"(.*)\"%s*$")
if w then
what = w
else
-- string continuation
s = line:match("^%s*\"(.*)\"%s*$")
end
if what and s then
-- unescape \n or msgid won't match
s = s:gsub("\\n", "\n")
-- unescape " or msgid won't match
s = s:gsub('\\"', '"')
data[what] = (data[what] or "") .. s
end
end
end
end
GetText.current_lang = new_lang
end
setmetatable(GetText, GetText_mt)
if os.getenv("LANGUAGE") then
GetText.changeLang(os.getenv("LANGUAGE"))
elseif os.getenv("LC_ALL") then
GetText.changeLang(os.getenv("LC_ALL"))
elseif os.getenv("LC_MESSAGES") then
GetText.changeLang(os.getenv("LC_MESSAGES"))
elseif os.getenv("LANG") then
GetText.changeLang(os.getenv("LANG"))
end
if isAndroid then
local ffi = require("ffi")
local buf = ffi.new("char[?]", 16)
android.lib.AConfiguration_getLanguage(android.app.config, buf)
local lang = ffi.string(buf)
android.lib.AConfiguration_getCountry(android.app.config, buf)
local country = ffi.string(buf)
if lang and country then
GetText.changeLang(lang.."_"..country)
end
end
return GetText
|
[fix] gettext: die already you stupid language not found error (#3341)
|
[fix] gettext: die already you stupid language not found error (#3341)
|
Lua
|
agpl-3.0
|
mihailim/koreader,Frenzie/koreader,poire-z/koreader,Markismus/koreader,pazos/koreader,poire-z/koreader,koreader/koreader,houqp/koreader,NiLuJe/koreader,mwoz123/koreader,koreader/koreader,lgeek/koreader,NiLuJe/koreader,apletnev/koreader,Frenzie/koreader,Hzj-jie/koreader
|
75944606d15151d6c91c1ac713d91f2672a8634c
|
irccd/plugins/auth.lua
|
irccd/plugins/auth.lua
|
local logger = require "irccd.logger"
local parser = require "irccd.parser"
local plugin = require "irccd.plugin"
-- Authentication methods by servers
local auth = {}
--
-- Load the nickserv backend settings.
--
local function loadNickServ(section, backend, server)
local password = section:requireOption("password")
--
-- Username is optional, so as we don't know it yet
-- we set it to nil and it will be taken from the
-- onConnect callback
--
auth[server] = {
backend = backend,
password = password,
username = section:getOption("username")
}
end
--
-- Load the quakenet backend settings.
--
local function loadQuakenet(section, backend, server)
local username = section:requireOption("username")
local password = section:requireOption("password")
auth[server] = {
backend = backend,
password = password,
username = username
}
end
local function loadConfig()
local path = plugin.getHome() .. "/auth.conf"
local conf = parser.new(path, { parser.DisableRootSection })
local ret, err = conf:open()
if not ret then
logger.warn("unable to load file " .. path)
logger.warn("authentication disabled")
end
-- Reset
auth = { }
-- Iterate over all authentication modules
for s in conf:findSections("auth") do
local backend = s:requireOption("backend")
local server = s:requireOption("server")
if backend == "nickserv" then
loadNickServ(s, backend, server)
elseif backend == "quakenet" then
loadQuakenet(s, backend, server)
else
logger.warn("invalid backend " .. backend)
end
end
end
local function onConnectNickServer(server)
logger.log("authenticating to NickServ")
--
-- If the username is nil, we need to get it from server
--
local a = auth[server:getName()]
local nickname = a.username or server:getIdentity().nickname
local cmd = "identify " .. nickname .. " " .. a.password
server:say("NickServ", cmd)
end
local function onConnectQuakenet(server)
logger.log("authenticating to Q")
local a = auth[server:getName()]
local cmd = string.format("Q@CServe.quakenet.org AUTH %s %s\r\n", a.username, a.password)
server:send(cmd)
end
function onConnect(server)
if auth[server:getName()] then
if auth[server:getName()].backend == "nickserv" then
onConnectNickServer(server)
elseif auth[server:getName()].backend == "quakenet" then
onConnectQuakenet(server)
end
end
end
function onNotice(server, who, target, notice)
logger.log("NOTICE: " .. notice)
end
function onReload()
loadConfig()
end
loadConfig()
|
local logger = require "irccd.logger"
local parser = require "irccd.parser"
local plugin = require "irccd.plugin"
-- Authentication methods by servers
local auth = {}
--
-- Load the nickserv backend settings.
--
local function loadNickServ(section, backend, server)
local password = section:requireOption("password")
--
-- Username is optional, so as we don't know it yet
-- we set it to nil and it will be taken from the
-- onConnect callback
--
auth[server] = {
backend = backend,
password = password,
username = section:getOption("username")
}
end
--
-- Load the quakenet backend settings.
--
local function loadQuakenet(section, backend, server)
local username = section:requireOption("username")
local password = section:requireOption("password")
auth[server] = {
backend = backend,
password = password,
username = username
}
end
local function loadConfig()
local path = plugin.getHome() .. "/auth.conf"
local conf = parser.new(path, { parser.DisableRootSection })
local ret, err = conf:open()
if not ret then
logger.warn("unable to load file " .. path)
logger.warn("authentication disabled")
end
-- Reset
auth = { }
-- Iterate over all authentication modules
for s in conf:findSections("auth") do
local backend = s:requireOption("backend")
local server = s:requireOption("server")
if backend == "nickserv" then
loadNickServ(s, backend, server)
elseif backend == "quakenet" then
loadQuakenet(s, backend, server)
else
logger.warn("invalid backend " .. backend)
end
end
end
local function onConnectNickServer(server)
logger.log("authenticating to NickServ")
--
-- If the username is nil, we need to get it from server
--
local a = auth[server:getName()]
local nickname = a.username or server:getIdentity().nickname
local cmd = "identify " .. nickname .. " " .. a.password
server:say("NickServ", cmd)
end
local function onConnectQuakenet(server)
logger.log("authenticating to Q")
local a = auth[server:getName()]
local cmd = string.format("AUTH %s %s", a.username, a.password)
server:say("Q@CServe.quakenet.org", cmd)
end
function onConnect(server)
if auth[server:getName()] then
if auth[server:getName()].backend == "nickserv" then
onConnectNickServer(server)
elseif auth[server:getName()].backend == "quakenet" then
onConnectQuakenet(server)
end
end
end
function onNotice(server, who, target, notice)
logger.log("NOTICE: " .. notice)
end
function onReload()
loadConfig()
end
loadConfig()
|
Fix quakenet backend, thanks peuc
|
Fix quakenet backend, thanks peuc
|
Lua
|
isc
|
bdrewery/irccd
|
596153601b2271644c9eec8230ac442c10db12e0
|
pgrouter.lua
|
pgrouter.lua
|
local cjson = require "cjson"
local function dbreq(sql)
ngx.log(ngx.ERR, 'SQL: ' .. sql)
local dbreq = ngx.location.capture("/pg", { args = { sql = sql } })
local json = dbreq.body
return json
end
local function max(match)
local key = ngx.req.get_uri_args()['key']
if not key then ngx.exit(403) end
-- Make sure valid request, only accept plain lowercase ascii string for key name
keytest = ngx.re.match(key, '[a-z]+', 'oj')
if not keytest then ngx.exit(403) end
local sql = "SELECT date_trunc('day', timestamp) AS day, MAX("..key..") FROM wd GROUP BY 1"
ngx.print(dbreq(sql))
return ngx.HTTP_OK
end
local function index()
ngx.print(dbreq('SELECT * FROM wd'))
return ngx.HTTP_OK
end
-- mapping patterns to views
local routes = {
['max'] = max,
[''] = index,
}
-- Set the content type
ngx.header.content_type = 'application/json';
local BASE = '/api/'
-- iterate route patterns and find view
for pattern, view in pairs(routes) do
local uri = '^' .. BASE .. pattern
local match = ngx.re.match(ngx.var.uri, uri, "oj") -- regex mather in compile mode
if match then
exit = view(match) or ngx.HTTP_OK
ngx.exit( exit )
end
end
-- no match, return 404
ngx.exit( ngx.HTTP_NOT_FOUND )
|
--
-- A simple API adapter for using postgresql internal subreq in a reusable manner
--
-- Copyright Tor Hveem <thveem> 2013
--
--local cjson = require "cjson"
-- The function sending subreq to nginx postgresql location with rds_json on
-- returns json body to the caller
local function dbreq(sql)
ngx.log(ngx.ERR, 'SQL: ' .. sql)
local dbreq = ngx.location.capture("/pg", { args = { sql = sql } })
local json = dbreq.body
return json
end
local function max(match)
local key = ngx.req.get_uri_args()['key']
if not key then ngx.exit(403) end
-- Make sure valid request, only accept plain lowercase ascii string for key name
keytest = ngx.re.match(key, '[a-z]+', 'oj')
if not keytest then ngx.exit(403) end
local sql = "SELECT date_trunc('day', timestamp) AS day, MAX("..key..") FROM wd GROUP BY 1"
ngx.print(dbreq(sql))
return ngx.HTTP_OK
end
local function index()
ngx.print(dbreq('SELECT * FROM wd'))
return ngx.HTTP_OK
end
-- mapping patterns to queries
local routes = {
['max'] = max,
['$'] = index,
}
-- Set the content type
ngx.header.content_type = 'application/json';
-- Our URL base, must match location in nginx config
local BASE = '/api/'
-- iterate route patterns and find view
for pattern, view in pairs(routes) do
local uri = '^' .. BASE .. pattern
local match = ngx.re.match(ngx.var.uri, uri, "oj") -- regex mather in compile mode
if match then
exit = view(match) or ngx.HTTP_OK
ngx.exit( exit )
end
end
-- no match, return 404
ngx.exit( ngx.HTTP_NOT_FOUND )
|
doc and fix for pgrouter
|
doc and fix for pgrouter
|
Lua
|
bsd-3-clause
|
torhve/Amatyr,torhve/Amatyr,torhve/Amatyr
|
e64e1c1b5d4802d2ac488a059293258849a2d287
|
premake5.lua
|
premake5.lua
|
workspace "KServer"
configurations { "Debug", "Release" }
platforms { "Win32", "Win64", "Linux" }
location "build"
filter { "platforms:Win32" }
system "windows"
architecture "x32"
defines { "_WIN32", "WIN32" }
filter { "platforms:Win64" }
system "windows"
architecture "x64"
defines { "_WIN32", "WIN32" }
filter { "platforms:Linux" }
system "linux"
architecture "x64"
defines { "LINUX", "linux" ,"POSIX"}
filter "configurations:Debug"
defines { "DEBUG" }
flags { "Symbols" }
optimize "Debug"
filter "configurations:Release"
defines { "NDEBUG" }
optimize "On"
flags { "OptimizeSpeed", "EnableSSE2" }
project "KServer"
kind "ConsoleApp"
language "C++"
includedirs{"./","./support/"}
files {
"*.h", "*.cpp","*.c",
"support/**.h", "support/**.cpp","support/**.c",
}
filter { "platforms:Linux" }
links{"pthread"}
|
workspace "KServer"
configurations { "Debug", "Release" }
platforms { "Win32", "Win64", "Linux" }
location "build"
filter { "platforms:Win32" }
system "windows"
architecture "x32"
defines { "_WIN32", "WIN32" }
filter { "platforms:Win64" }
system "windows"
architecture "x64"
defines { "_WIN32", "WIN32" }
filter { "platforms:Linux" }
system "linux"
architecture "x64"
defines { "LINUX", "linux" ,"POSIX"}
filter "configurations:Debug"
defines { "DEBUG" }
flags { "Symbols" }
optimize "Debug"
filter "configurations:Release"
defines { "NDEBUG" }
optimize "On"
flags { "OptimizeSpeed", "EnableSSE2" }
project "KServer"
kind "ConsoleApp"
language "C++"
includedirs{"./","./support/"}
files {
"*.h", "*.cpp","*.c",
"support/**.h", "support/**.cpp","support/**.c",
}
filter { "platforms:Linux" }
links{"pthread","rt"}
|
fix build error
|
fix build error
|
Lua
|
apache-2.0
|
zentelfong/KServer,zentelfong/KServer
|
413cf49dce1bb841ab15f77fd7aed58bbd853762
|
src_trunk/resources/job-system/fishing/s_fishing_job.lua
|
src_trunk/resources/job-system/fishing/s_fishing_job.lua
|
local totalCatch = 0
local fishSize = 0
-- /fish to start fishing.
function startFishing(thePlayer)
local element = getPedContactElement(thePlayer)
if not (thePlayer) then thePlayer = source end
if not (isElement(element)) then
outputChatBox("You must be on a boat to fish.", thePlayer, 255, 0, 0)
else
if not (getElementType(element)=="vehicle") then
outputChatBox("You must be on a boat to fish.", thePlayer, 255, 0, 0)
else
if not (getVehicleType(element)=="Boat") then
outputChatBox("You must be on a boat to fish.", thePlayer, 255, 0, 0)
else
local x, y, z = getElementPosition(thePlayer)
if (x < 3000) or (y > 4000) then -- the further out to sea you go the bigger the fish you will catch.
outputChatBox("You must be out at sea to fish.", thePlayer, 255, 0, 0)
else
if not(exports.global:doesPlayerHaveItem(thePlayer, 49)) then -- does the player have the fishing rod item?
outputChatBox("You need a fishing rod to fish.", thePlayer, 255, 0, 0)
else
if (catchTimer) then -- Are they already fishing?
outputChatBox("You have already cast your line. Wait for a fish to bite.", thePlayer, 255, 0, 0)
else
if (totalCatch >= 2000) then
outputChatBox("#FF9933The boat can't hold any more fish. #FF66CCSell#FF9933 the fish you have caught before continuing.", thePlayer, 255, 104, 91, true)
else
local biteTimer = math.random(60000,300000)
--catchTimer = setTimer( theyHaveABite, biteTimer, 1, thePlayer) -- A fish will bite within 1 and 5 minutes.
catchTimer = setTimer( theyHaveABite, 10000, 1, thePlayer)
exports.global:sendLocalMeAction(thePlayer,"casts a fishing line.")
if not (colsphere) then -- If the /sellfish marker isnt already being shown...
blip = createBlip( 2243.7339, 578.905, 6.78, 0, 2, 255, 0, 255, 255 )
marker = createMarker( 2243.7339, 578.905, 6.78, "cylinder", 2, 255, 0, 255, 150 )
colsphere = createColSphere (2243.7339, 578.905, 6.78, 3)
exports.pool:allocateElement(blip)
exports.pool:allocateElement(marker)
exports.pool:allocateElement(colsphere)
setElementVisibleTo(blip, getRootElement(), false)
setElementVisibleTo(blip, thePlayer, true)
setElementVisibleTo(marker, getRootElement(), false)
setElementVisibleTo(marker, thePlayer, true)
outputChatBox("#FF9933When you are done fishing you can sell your catch at the fish market ((#FF66CCblip#FF9933 added to radar)).", thePlayer, 255, 104, 91, true)
outputChatBox("#FF9933((/totalcatch to see how much you have caught. To sell your catch enter /sellfish in the #FF66CCmarker#FF9933.))", thePlayer, 255, 104, 91, true)
end
end
end
end
end
end
end
end
end
addCommandHandler("fish", startFishing, false, false)
addEvent("fish")
addEventHandler("fish", getRootElement(), startFishing)
------ triggers the mini game.
function theyHaveABite(source)
killTimer(catchTimer)
catchTimer=nil
triggerClientEvent("createReel", source)
exports.global:sendLocalMeAction(source,"has a bite!")
end
----- Snapped line.
function lineSnap()
exports.global:takePlayerItem(source, 49, 1) -- fishing rod
exports.global:sendLocalMeAction(source,"snaps their fishing line.")
outputChatBox("The monster of a fish has broken your line. You need to buy a new fishing rod to continue fishing.", source, 255, 0, 0)
end
addEvent("lineSnap",true)
addEventHandler("lineSnap", getRootElement(), lineSnap)
----- Successfully reeled in the fish.
function catchFish(fishSize)
exports.global:sendLocalMeAction(source,"catches a fish weighing ".. fishSize .."lbs.")
totalCatch = math.floor(totalCatch + fishSize)
outputChatBox("You have caught "..totalCatch.."lbs of fish so far.", source, 255, 194, 14)
if (fishSize >= 100) then
exports.global:givePlayerAchievement(source, 35)
end
end
addEvent("catchFish", true)
addEventHandler("catchFish", getRootElement(), catchFish)
------ /totalcatch command
function currentCatch(thePlayer)
outputChatBox("You have "..totalCatch.."lbs of fish caught so far.", thePlayer, 255, 194, 14)
end
addCommandHandler("totalcatch", currentCatch, false, false)
------ /sellfish
function unloadCatch(thePlayer)
if (isElementWithinColShape(thePlayer, colsphere)) then
if (totalCatch == 0) then
outputChatBox("You need to catch some fish to sell first." ,thePlayer, 255, 0, 0)
else
local profit = math.floor(totalCatch/2)
exports.global:sendLocalMeAction(thePlayer,"sells " .. totalCatch .."lbs of fish.")
exports.global:givePlayerSafeMoney(thePlayer, profit)
outputChatBox("You made $".. profit .." from the fish you caught." ,thePlayer, 255, 104, 91)
totalCatch = 0
destroyElement(blip)
destroyElement(marker)
destroyElement(colsphere)
blip=nil
marker=nil
colsphere=nil
end
else
outputChatBox("You need to be at the fish market to sell your catch.", thePlayer, 255, 0, 0)
end
end
addCommandHandler("sellFish", unloadCatch, false, false)
|
local totalCatch = 0
local fishSize = 0
-- /fish to start fishing.
function startFishing(thePlayer)
if not (thePlayer) then thePlayer = source end
local element = getPedContactElement(thePlayer)
if not (isElement(element)) then
outputChatBox("You must be on a boat to fish.", thePlayer, 255, 0, 0)
else
if not (getElementType(element)=="vehicle") then
outputChatBox("You must be on a boat to fish.", thePlayer, 255, 0, 0)
else
if not (getVehicleType(element)=="Boat") then
outputChatBox("You must be on a boat to fish.", thePlayer, 255, 0, 0)
else
local x, y, z = getElementPosition(thePlayer)
if (x < 3000) or (y > 4000) then -- the further out to sea you go the bigger the fish you will catch.
outputChatBox("You must be out at sea to fish.", thePlayer, 255, 0, 0)
else
if not(exports.global:doesPlayerHaveItem(thePlayer, 49)) then -- does the player have the fishing rod item?
outputChatBox("You need a fishing rod to fish.", thePlayer, 255, 0, 0)
else
if (catchTimer) then -- Are they already fishing?
outputChatBox("You have already cast your line. Wait for a fish to bite.", thePlayer, 255, 0, 0)
else
if (totalCatch >= 2000) then
outputChatBox("#FF9933The boat can't hold any more fish. #FF66CCSell#FF9933 the fish you have caught before continuing.", thePlayer, 255, 104, 91, true)
else
local biteTimer = math.random(60000,300000)
--catchTimer = setTimer( theyHaveABite, biteTimer, 1, thePlayer) -- A fish will bite within 1 and 5 minutes.
catchTimer = setTimer( theyHaveABite, 10000, 1, thePlayer)
exports.global:sendLocalMeAction(thePlayer,"casts a fishing line.")
if not (colsphere) then -- If the /sellfish marker isnt already being shown...
blip = createBlip( 2243.7339, 578.905, 6.78, 0, 2, 255, 0, 255, 255 )
marker = createMarker( 2243.7339, 578.905, 6.78, "cylinder", 2, 255, 0, 255, 150 )
colsphere = createColSphere (2243.7339, 578.905, 6.78, 3)
exports.pool:allocateElement(blip)
exports.pool:allocateElement(marker)
exports.pool:allocateElement(colsphere)
setElementVisibleTo(blip, getRootElement(), false)
setElementVisibleTo(blip, thePlayer, true)
setElementVisibleTo(marker, getRootElement(), false)
setElementVisibleTo(marker, thePlayer, true)
outputChatBox("#FF9933When you are done fishing you can sell your catch at the fish market ((#FF66CCblip#FF9933 added to radar)).", thePlayer, 255, 104, 91, true)
outputChatBox("#FF9933((/totalcatch to see how much you have caught. To sell your catch enter /sellfish in the #FF66CCmarker#FF9933.))", thePlayer, 255, 104, 91, true)
end
end
end
end
end
end
end
end
end
addCommandHandler("fish", startFishing, false, false)
addEvent("fish")
addEventHandler("fish", getRootElement(), startFishing)
------ triggers the mini game.
function theyHaveABite(source)
killTimer(catchTimer)
catchTimer=nil
triggerClientEvent("createReel", source)
exports.global:sendLocalMeAction(source,"has a bite!")
end
----- Snapped line.
function lineSnap()
exports.global:takePlayerItem(source, 49, 1) -- fishing rod
exports.global:sendLocalMeAction(source,"snaps their fishing line.")
outputChatBox("The monster of a fish has broken your line. You need to buy a new fishing rod to continue fishing.", source, 255, 0, 0)
end
addEvent("lineSnap",true)
addEventHandler("lineSnap", getRootElement(), lineSnap)
----- Successfully reeled in the fish.
function catchFish(fishSize)
exports.global:sendLocalMeAction(source,"catches a fish weighing ".. fishSize .."lbs.")
totalCatch = math.floor(totalCatch + fishSize)
outputChatBox("You have caught "..totalCatch.."lbs of fish so far.", source, 255, 194, 14)
if (fishSize >= 100) then
exports.global:givePlayerAchievement(source, 35)
end
end
addEvent("catchFish", true)
addEventHandler("catchFish", getRootElement(), catchFish)
------ /totalcatch command
function currentCatch(thePlayer)
outputChatBox("You have "..totalCatch.."lbs of fish caught so far.", thePlayer, 255, 194, 14)
end
addCommandHandler("totalcatch", currentCatch, false, false)
------ /sellfish
function unloadCatch(thePlayer)
if (isElementWithinColShape(thePlayer, colsphere)) then
if (totalCatch == 0) then
outputChatBox("You need to catch some fish to sell first." ,thePlayer, 255, 0, 0)
else
local profit = math.floor(totalCatch/2)
exports.global:sendLocalMeAction(thePlayer,"sells " .. totalCatch .."lbs of fish.")
exports.global:givePlayerSafeMoney(thePlayer, profit)
outputChatBox("You made $".. profit .." from the fish you caught." ,thePlayer, 255, 104, 91)
totalCatch = 0
destroyElement(blip)
destroyElement(marker)
destroyElement(colsphere)
blip=nil
marker=nil
colsphere=nil
end
else
outputChatBox("You need to be at the fish market to sell your catch.", thePlayer, 255, 0, 0)
end
end
addCommandHandler("sellFish", unloadCatch, false, false)
|
Another fix
|
Another fix
git-svn-id: 8769cb08482c9977c94b72b8e184ec7d2197f4f7@509 64450a49-1f69-0410-a0a2-f5ebb52c4f5b
|
Lua
|
bsd-3-clause
|
valhallaGaming/uno,valhallaGaming/uno,valhallaGaming/uno
|
9aee980d72490ccf9670e988a420a31e633f153d
|
OS/DiskOS/APIS/RamUtils.lua
|
OS/DiskOS/APIS/RamUtils.lua
|
--RAM Utilities.
--Variabes.
local sw,sh = screenSize()
--Localized Lua Library
local unpack = unpack
local floor, ceil, min = math.floor, math.ceil, math.min
local strChar, strByte = string.char, string.byte
local lshift, rshift, bor, band = bit.lshift, bit.rshift, bit.bor, bit.band
--The API
local RamUtils = {}
RamUtils.VRAM = 0 --The start address of the VRAM
RamUtils.LIMG = RamUtils.VRAM + (sw/2)*sh --The start address of the LabelImage.
RamUtils.FRAM = RamUtils.LIMG + (sw/2)*sh --The start address of the Floppy RAM.
RamUtils.Null = strChar(0) --The null character
--==Images==--
--Encode an image into binary.
function RamUtils.imgToBin(img,getTable)
if img:typeOf("GPU.image") then img = img:data() end --Convert the image to imagedata.
local bin = {}
local imgW, imgH = img:size()
local flag = true
img:map(function(x,y,c)
x = x + y*imgW + 1
local byte = bin[floor(x/2)] or 0
if flag then
byte = byte + lshift(c,4)
else
byte = byte + c
end
bin[floor(x/2)] = byte
flag = not flag
end)
if getTable then return bin end
for k,v in pairs(bin) do
bin[k] = strChar(v)
end
return table.concat(bin)
end
--Load an image from binary.
function RamUtils.binToImg(img,bin)
local colors, cid = {}, 1
for i=1,bin:len() do
local byte = strByte(bin,i)
local left = band(byte,0xF0)
colors[cid] = rshift(left,4)
colors[cid+1] = band(byte,0x0F)
cid = cid + 2
end
cid = 1
imgdata:map(function(x,y,c)
local c = colors[cid] or 0
cid = cid + 1
return c
end)
end
--==Maps==--
--Encode a map into binary.
function RamUtils.mapToBin(map,getTable)
local bin = {}
local tid = 1
map:map(function(x,y,tile)
bin[tid] = min(tile,255)
tid = tid + 1
end)
if getTable then return bin end
for k,v in pairs(bin) do
bin[k] = strChar(v)
end
return table.concat(bin)
end
--Load a map from binary.
function RamUtils.binToMap(map,bin)
local len, id = bin:len(), 0
map:map(function(x,y,tile)
id = id + 1
return (id <= len and strByte(bin,id) or 0)
end)
end
--==Code==--
--Encode code into binary.
function RamUtils.codeToBin(code)
return math.compress(code,"gzip",9)
end
--Load code from binary.
function RamUtils.binToCode(bin)
return math.decompress(bin,"gzip",9)
end
--==Extra==--
--Encode a number into binary
function RamUtils.numToBin(num,length,getTable)
local bytes = {}
for bnum=1,length do
bytes[bnum] = band(num,255)
num = rshift(num,8)
end
if getTable then return bytes end
return strChar(unpack(bytes))
end
--Load a number from binar
function RamUtils.binToNum(bin)
local number = 0
for i=1,bin:len() do
local byte = strByte(bin,i)
byte = lshift(byte,(i-1)*8)
number = bor(number,byte)
end
return number
end
--Calculate the length of the number in bytes
function RamUtils.numLength(num)
local length = 0
while num > 0 do
num = rshift(num,8)
length = length + 1
end
return length
end
--Create a binary iterator for a string
function RamUtils.binIter(bin)
local counter = 0
return function()
counter = counter + 1
return strByte(bin,counter)
end, function()
return counter
end
end
--Make the ramutils a global
_G["RamUtils"] = RamUtils
|
--RAM Utilities.
--Variabes.
local sw,sh = screenSize()
--Localized Lua Library
local unpack = unpack
local floor, ceil, min = math.floor, math.ceil, math.min
local strChar, strByte = string.char, string.byte
local lshift, rshift, bor, band = bit.lshift, bit.rshift, bit.bor, bit.band
--The API
local RamUtils = {}
RamUtils.VRAM = 0 --The start address of the VRAM
RamUtils.LIMG = RamUtils.VRAM + (sw/2)*sh --The start address of the LabelImage.
RamUtils.FRAM = RamUtils.LIMG + (sw/2)*sh --The start address of the Floppy RAM.
RamUtils.Null = strChar(0) --The null character
--==Images==--
--Encode an image into binary.
function RamUtils.imgToBin(img,getTable)
if img:typeOf("GPU.image") then img = img:data() end --Convert the image to imagedata.
local bin = {}
local imgW, imgH = img:size()
local flag = true
img:map(function(x,y,c)
x = x + y*imgW + 1
local byte = bin[ceil(x/2)] or 0
if flag then
byte = bor(byte,lshift(c,4))
else
byte = bor(byte,c)
end
bin[ceil(x/2)] = byte
flag = not flag
end)
if getTable then return bin end
for k,v in pairs(bin) do
bin[k] = strChar(v)
end
return table.concat(bin)
end
--Load an image from binary.
function RamUtils.binToImg(img,bin)
local colors, cid = {}, 1
for i=1,bin:len() do
local byte = strByte(bin,i)
local left = band(byte,0xF0)
colors[cid] = rshift(left,4)
colors[cid+1] = band(byte,0x0F)
cid = cid + 2
end
cid = 1
img:map(function(x,y,old)
local c = colors[cid] or 0
cid = cid + 1
return c
end)
end
--==Maps==--
--Encode a map into binary.
function RamUtils.mapToBin(map,getTable)
local bin = {}
local tid = 1
map:map(function(x,y,tile)
bin[tid] = min(tile,255)
tid = tid + 1
end)
if getTable then return bin end
for k,v in pairs(bin) do
bin[k] = strChar(v)
end
return table.concat(bin)
end
--Load a map from binary.
function RamUtils.binToMap(map,bin)
local len, id = bin:len(), 0
map:map(function(x,y,tile)
id = id + 1
return (id <= len and strByte(bin,id) or 0)
end)
end
--==Code==--
--Encode code into binary.
function RamUtils.codeToBin(code)
return math.compress(code,"gzip",9)
end
--Load code from binary.
function RamUtils.binToCode(bin)
return math.decompress(bin,"gzip",9)
end
--==Extra==--
--Encode a number into binary
function RamUtils.numToBin(num,length,getTable)
local bytes = {}
for bnum=1,length do
bytes[bnum] = band(num,255)
num = rshift(num,8)
end
if getTable then return bytes end
return strChar(unpack(bytes))
end
--Load a number from binar
function RamUtils.binToNum(bin)
local number = 0
for i=1,bin:len() do
local byte = strByte(bin,i)
byte = lshift(byte,(i-1)*8)
number = bor(number,byte)
end
return number
end
--Calculate the length of the number in bytes
function RamUtils.numLength(num)
local length = 0
while num > 0 do
num = rshift(num,8)
length = length + 1
end
return length
end
--Create a binary iterator for a string
function RamUtils.binIter(bin)
local counter = 0
return function()
counter = counter + 1
return strByte(bin,counter)
end, function()
return counter
end
end
--Make the ramutils a global
_G["RamUtils"] = RamUtils
|
Bugfixes
|
Bugfixes
|
Lua
|
mit
|
RamiLego4Game/LIKO-12
|
75d9b07158510f4d1315edefe860bcdf7b0fd2f7
|
lualib/http/httpc.lua
|
lualib/http/httpc.lua
|
local socket = require "http.sockethelper"
local url = require "http.url"
local internal = require "http.internal"
local string = string
local table = table
local httpc = {}
local function request(fd, method, host, url, recvheader, header, content)
local read = socket.readfunc(fd)
local write = socket.writefunc(fd)
local header_content = ""
if header then
for k,v in pairs(header) do
header_content = string.format("%s%s:%s\r\n", header_content, k, v)
end
if header.host then
host = ""
else
host = string.format("host:%s\r\n", host)
end
else
host = string.format("host:%s\r\n",host)
end
if content then
local data = string.format("%s %s HTTP/1.1\r\n%scontent-length:%d\r\n%s\r\n%s", method, url, host, #content, header_content, content)
write(data)
else
local request_header = string.format("%s %s HTTP/1.1\r\nhost:%s\r\ncontent-length:0\r\n%s\r\n", method, url, host, header_content)
write(request_header)
end
local tmpline = {}
local body = internal.recvheader(read, tmpline, "")
if not body then
error(socket.socket_error)
end
local statusline = tmpline[1]
local code, info = statusline:match "HTTP/[%d%.]+%s+([%d]+)%s+(.*)$"
code = assert(tonumber(code))
local header = internal.parseheader(tmpline,2,recvheader or {})
if not header then
error("Invalid HTTP response header")
end
local length = header["content-length"]
if length then
length = tonumber(length)
end
local mode = header["transfer-encoding"]
if mode then
if mode ~= "identity" and mode ~= "chunked" then
error ("Unsupport transfer-encoding")
end
end
if mode == "chunked" then
body, header = internal.recvchunkedbody(read, nil, header, body)
if not body then
error("Invalid response body")
end
else
-- identity mode
if length then
if #body >= length then
body = body:sub(1,length)
else
local padding = read(length - #body)
body = body .. padding
end
else
body = nil
end
end
return code, body
end
function httpc.request(method, host, url, recvheader, header, content)
local hostname, port = host:match"([^:]+):?(%d*)$"
if port == "" then
port = 80
else
port = tonumber(port)
end
local fd = socket.connect(hostname, port)
local ok , statuscode, body = pcall(request, fd,method, host, url, recvheader, header, content)
socket.close(fd)
if ok then
return statuscode, body
else
error(statuscode)
end
end
function httpc.get(...)
return httpc.request("GET", ...)
end
local function escape(s)
return (string.gsub(s, "([^A-Za-z0-9_])", function(c)
return string.format("%%%02X", string.byte(c))
end))
end
function httpc.post(host, url, form, recvheader)
local header = {
["content-type"] = "application/x-www-form-urlencoded"
}
local body = {}
for k,v in pairs(form) do
table.insert(body, string.format("%s=%s",escape(k),escape(v)))
end
return httpc.request("POST", host, url, recvheader, header, table.concat(body , "&"))
end
return httpc
|
local socket = require "http.sockethelper"
local url = require "http.url"
local internal = require "http.internal"
local string = string
local table = table
local httpc = {}
local function request(fd, method, host, url, recvheader, header, content)
local read = socket.readfunc(fd)
local write = socket.writefunc(fd)
local header_content = ""
if header then
if not header.host then
header.host = host
end
for k,v in pairs(header) do
header_content = string.format("%s%s:%s\r\n", header_content, k, v)
end
else
header_content = string.format("host:%s\r\n",host)
end
if content then
local data = string.format("%s %s HTTP/1.1\r\n%scontent-length:%d\r\n\r\n%s", method, url, header_content, #content, content)
write(data)
else
local request_header = string.format("%s %s HTTP/1.1\r\n%scontent-length:0\r\n\r\n", method, url, header_content)
write(request_header)
end
local tmpline = {}
local body = internal.recvheader(read, tmpline, "")
if not body then
error(socket.socket_error)
end
local statusline = tmpline[1]
local code, info = statusline:match "HTTP/[%d%.]+%s+([%d]+)%s+(.*)$"
code = assert(tonumber(code))
local header = internal.parseheader(tmpline,2,recvheader or {})
if not header then
error("Invalid HTTP response header")
end
local length = header["content-length"]
if length then
length = tonumber(length)
end
local mode = header["transfer-encoding"]
if mode then
if mode ~= "identity" and mode ~= "chunked" then
error ("Unsupport transfer-encoding")
end
end
if mode == "chunked" then
body, header = internal.recvchunkedbody(read, nil, header, body)
if not body then
error("Invalid response body")
end
else
-- identity mode
if length then
if #body >= length then
body = body:sub(1,length)
else
local padding = read(length - #body)
body = body .. padding
end
else
body = nil
end
end
return code, body
end
function httpc.request(method, host, url, recvheader, header, content)
local hostname, port = host:match"([^:]+):?(%d*)$"
if port == "" then
port = 80
else
port = tonumber(port)
end
local fd = socket.connect(hostname, port)
local ok , statuscode, body = pcall(request, fd,method, host, url, recvheader, header, content)
socket.close(fd)
if ok then
return statuscode, body
else
error(statuscode)
end
end
function httpc.get(...)
return httpc.request("GET", ...)
end
local function escape(s)
return (string.gsub(s, "([^A-Za-z0-9_])", function(c)
return string.format("%%%02X", string.byte(c))
end))
end
function httpc.post(host, url, form, recvheader)
local header = {
["content-type"] = "application/x-www-form-urlencoded"
}
local body = {}
for k,v in pairs(form) do
table.insert(body, string.format("%s=%s",escape(k),escape(v)))
end
return httpc.request("POST", host, url, recvheader, header, table.concat(body , "&"))
end
return httpc
|
fix: httpc.get
|
fix: httpc.get
:-(
此错误会导致httpc.get无法找到正确的虚拟主机
|
Lua
|
mit
|
liuxuezhan/skynet,nightcj/mmo,zzh442856860/skynet,jxlczjp77/skynet,wangyi0226/skynet,your-gatsby/skynet,nightcj/mmo,wangyi0226/skynet,chfg007/skynet,liuxuezhan/skynet,icetoggle/skynet,boyuegame/skynet,catinred2/skynet,QuiQiJingFeng/skynet,harryzeng/skynet,JiessieDawn/skynet,rainfiel/skynet,yinjun322/skynet,plsytj/skynet,QuiQiJingFeng/skynet,JiessieDawn/skynet,Zirpon/skynet,iskygame/skynet,MetSystem/skynet,bigrpg/skynet,sdgdsffdsfff/skynet,samael65535/skynet,chfg007/skynet,togolwb/skynet,icetoggle/skynet,ruleless/skynet,rainfiel/skynet,Ding8222/skynet,xinjuncoding/skynet,asanosoyokaze/skynet,bingo235/skynet,ypengju/skynet_comment,KAndQ/skynet,MRunFoss/skynet,yunGit/skynet,kyle-wang/skynet,zzh442856860/skynet,pigparadise/skynet,zzh442856860/skynet-Note,sanikoyes/skynet,cloudwu/skynet,ilylia/skynet,lynx-seu/skynet,wangjunwei01/skynet,KittyCookie/skynet,czlc/skynet,zhoukk/skynet,bigrpg/skynet,ag6ag/skynet,sdgdsffdsfff/skynet,MoZhonghua/skynet,chuenlungwang/skynet,ludi1991/skynet,iskygame/skynet,kyle-wang/skynet,felixdae/skynet,bttscut/skynet,fztcjjl/skynet,ruleless/skynet,matinJ/skynet,zhouxiaoxiaoxujian/skynet,xjdrew/skynet,felixdae/skynet,harryzeng/skynet,catinred2/skynet,liuxuezhan/skynet,Ding8222/skynet,great90/skynet,matinJ/skynet,microcai/skynet,bigrpg/skynet,LiangMa/skynet,kebo/skynet,cuit-zhaxin/skynet,firedtoad/skynet,letmefly/skynet,chenjiansnail/skynet,cmingjian/skynet,lawnight/skynet,plsytj/skynet,puXiaoyi/skynet,cmingjian/skynet,czlc/skynet,gitfancode/skynet,catinred2/skynet,JiessieDawn/skynet,cdd990/skynet,zhouxiaoxiaoxujian/skynet,dymx101/skynet,sanikoyes/skynet,lc412/skynet,zzh442856860/skynet-Note,pigparadise/skynet,bttscut/skynet,lc412/skynet,sundream/skynet,MetSystem/skynet,QuiQiJingFeng/skynet,fhaoquan/skynet,sanikoyes/skynet,wangjunwei01/skynet,MoZhonghua/skynet,u20024804/skynet,longmian/skynet,codingabc/skynet,codingabc/skynet,dymx101/skynet,LiangMa/skynet,jiuaiwo1314/skynet,Zirpon/skynet,LiangMa/skynet,cpascal/skynet,liuxuezhan/skynet,boyuegame/skynet,hongling0/skynet,cdd990/skynet,KittyCookie/skynet,yinjun322/skynet,zhangshiqian1214/skynet,cpascal/skynet,longmian/skynet,plsytj/skynet,Zirpon/skynet,lynx-seu/skynet,xinjuncoding/skynet,Markal128/skynet,korialuo/skynet,gitfancode/skynet,helling34/skynet,xjdrew/skynet,leezhongshan/skynet,ypengju/skynet_comment,dymx101/skynet,letmefly/skynet,nightcj/mmo,jxlczjp77/skynet,fztcjjl/skynet,xcjmine/skynet,vizewang/skynet,cuit-zhaxin/skynet,Ding8222/skynet,javachengwc/skynet,KAndQ/skynet,javachengwc/skynet,great90/skynet,zhangshiqian1214/skynet,wangyi0226/skynet,ludi1991/skynet,gitfancode/skynet,pichina/skynet,codingabc/skynet,microcai/skynet,yinjun322/skynet,javachengwc/skynet,xinjuncoding/skynet,pigparadise/skynet,MRunFoss/skynet,kebo/skynet,cloudwu/skynet,zzh442856860/skynet-Note,asanosoyokaze/skynet,cpascal/skynet,yunGit/skynet,KittyCookie/skynet,xcjmine/skynet,fhaoquan/skynet,KAndQ/skynet,your-gatsby/skynet,ludi1991/skynet,cmingjian/skynet,cdd990/skynet,wangjunwei01/skynet,yunGit/skynet,ruleless/skynet,lc412/skynet,sdgdsffdsfff/skynet,puXiaoyi/skynet,lawnight/skynet,jxlczjp77/skynet,enulex/skynet,your-gatsby/skynet,u20024804/skynet,icetoggle/skynet,MetSystem/skynet,ilylia/skynet,u20024804/skynet,firedtoad/skynet,korialuo/skynet,great90/skynet,fztcjjl/skynet,ilylia/skynet,kebo/skynet,hongling0/skynet,harryzeng/skynet,zhoukk/skynet,fhaoquan/skynet,chenjiansnail/skynet,jiuaiwo1314/skynet,bingo235/skynet,vizewang/skynet,lawnight/skynet,hongling0/skynet,zhangshiqian1214/skynet,enulex/skynet,leezhongshan/skynet,MoZhonghua/skynet,sundream/skynet,bttscut/skynet,leezhongshan/skynet,xcjmine/skynet,chuenlungwang/skynet,zhouxiaoxiaoxujian/skynet,vizewang/skynet,bingo235/skynet,samael65535/skynet,helling34/skynet,chuenlungwang/skynet,czlc/skynet,boyuegame/skynet,microcai/skynet,samael65535/skynet,chfg007/skynet,letmefly/skynet,ludi1991/skynet,letmefly/skynet,rainfiel/skynet,kyle-wang/skynet,longmian/skynet,matinJ/skynet,enulex/skynet,zhangshiqian1214/skynet,lawnight/skynet,sundream/skynet,zhoukk/skynet,pichina/skynet,Markal128/skynet,Markal128/skynet,zzh442856860/skynet,felixdae/skynet,zhangshiqian1214/skynet,MRunFoss/skynet,helling34/skynet,cuit-zhaxin/skynet,cloudwu/skynet,firedtoad/skynet,iskygame/skynet,lynx-seu/skynet,chenjiansnail/skynet,ag6ag/skynet,ypengju/skynet_comment,asanosoyokaze/skynet,puXiaoyi/skynet,togolwb/skynet,pichina/skynet,ag6ag/skynet,xjdrew/skynet,togolwb/skynet,korialuo/skynet,zzh442856860/skynet-Note,jiuaiwo1314/skynet,zhangshiqian1214/skynet
|
3c5dfcaedfac9981c91b6e476ecb0e7cbfb7d83f
|
luapress/template.lua
|
luapress/template.lua
|
-- Luapress
-- File: luapress/template.lua
-- Desc: process .mustache and .lhtml templates
local ipairs = ipairs
local type = type
local tostring = tostring
local loadstring = loadstring or load
local mustache = require('lustache')
-- Template data
local template = {
data = {}
}
-- Add to data
function template:set(key, value)
self.data[key] = value
end
-- Get data
function template:get(key)
return self.data[key]
end
-- Function to work before tostring
function template.tostring(string)
-- nil returns blank
if string == nil then return '' end
-- String as string
if type(string) == 'string' then return string end
-- Otherwise as best
return tostring(string)
end
-- Format date with respect to config.date_format
function template.format_date(date)
local formatter = '%a, %d %B, %Y'
if config and config.date_format then
formatter = config.date_format
end
return os.date(formatter, date)
end
-- Process a .mustache template with Lustache
function process_mustache(code, data)
-- Wrapper around template.format_date
data.format_date = function(date, render)
return template.format_date(render(date))
end
return mustache:render(code, data)
end
-- Process a .lhtml template with gsub hacks(!)
function process_lhtml(code)
-- Prepend bits
code = 'local self, output = require(\'luapress.template\'), ""\noutput = output .. [[' .. code
-- Replace <?=vars?>
code = code:gsub(
'<%?=(.-)%?>',
']] .. self.tostring( %1 ) .. [['
)
-- Replace <? to close output, start raw lua
code = code:gsub('<%?%s', ']] ')
-- Replace ?> to stop lua and start output (in table)
code = code:gsub('%s%?>', '\noutput = output .. [[')
-- Close final output and return concat of the table
code = code .. ' \n]]\nreturn output'
local f, err = loadstring(code)
if not f then
print(err, code)
return ''
else
return f()
end
end
-- Turn a template into HTML output
function template:process(...)
local out = ''
for _, tmpl in ipairs({...}) do
if tmpl.format == 'mustache' then
process = process_mustache
else
process = process_lhtml
end
out = out .. process(tmpl.content, self.data)
end
return out
end
return template
|
-- Luapress
-- File: luapress/template.lua
-- Desc: process .mustache and .lhtml templates
local ipairs = ipairs
local type = type
local tostring = tostring
local loadstring = loadstring or load
local mustache = require('lustache')
-- Template data
local template = {
data = {}
}
-- Add to data
function template:set(key, value)
self.data[key] = value
end
-- Get data
function template:get(key)
return self.data[key]
end
-- Function to work before tostring
function template.tostring(string)
-- nil returns blank
if string == nil then return '' end
-- String as string
if type(string) == 'string' then return string end
-- Otherwise as best
return tostring(string)
end
-- Format date with respect to config.date_format
function template.format_date(date)
local formatter = '%a, %d %B, %Y'
if config and config.date_format then
formatter = config.date_format
end
return os.date(formatter, date)
end
-- Process a .mustache template with Lustache
function process_mustache(code, data)
-- Wrapper around template.format_date
data.format_date = function(date, render)
return template.format_date(render(date))
end
return mustache:render(code, data)
end
-- Process a .lhtml template with gsub hacks(!)
function process_lhtml(code)
-- Prepend bits
code = 'local self, output = require(\'luapress.template\'), ""\noutput = output .. [[' .. code
-- Replace <?=vars?>
code = code:gsub(
'<%?=(.-)%?>',
']] .. self.tostring( %1 ) .. [['
)
-- Replace ?> <? spaces and lines between lua codes
code = code:gsub('%?>[ \n]*<%?', '\n')
-- Replace <? to close output, start raw lua
code = code:gsub('<%?%s', ']] ')
-- Replace ?> to stop lua and start output (in table)
code = code:gsub('%s%?>', '\noutput = output .. [[')
-- Close final output and return concat of the table
code = code .. ' \n]]\nreturn output'
local f, err = loadstring(code)
if not f then
print(err, code)
return ''
else
return f()
end
end
-- Turn a template into HTML output
function template:process(...)
local out = ''
for _, tmpl in ipairs({...}) do
if tmpl.format == 'mustache' then
process = process_mustache
else
process = process_lhtml
end
out = out .. process(tmpl.content, self.data)
end
return out
end
return template
|
Fix usage of break, avoid string creation
|
Fix usage of break, avoid string creation
|
Lua
|
mit
|
Fizzadar/Luapress,Fizzadar/Luapress
|
12b3bd4ee03416cb8fd32b130f17d27050c7a363
|
modules/corelib/table.lua
|
modules/corelib/table.lua
|
-- @docclass table
function table.dump(t, depth)
if not depth then depth = 0 end
for k,v in pairs(t) do
str = (' '):rep(depth * 2) .. k .. ': '
if type(v) ~= "table" then
print(str .. tostring(v))
else
print(str)
table.dump(v, depth+1)
end
end
end
function table.clear(t)
for k,v in pairs(t) do
t[k] = nil
end
end
function table.copy(t)
local res = {}
for k,v in pairs(t) do
res[k] = v
end
return res
end
function table.recursivecopy(t)
local res = {}
for k,v in pairs(t) do
if type(v) == "table" then
res[k] = table.recursivecopy(v)
else
res[k] = v
end
end
return res
end
function table.selectivecopy(t, keys)
local res = { }
for i,v in ipairs(keys) do
res[v] = t[v]
end
return res
end
function table.merge(t, src)
for k,v in pairs(src) do
t[k] = v
end
end
function table.find(t, value, lowercase)
for k,v in pairs(t) do
if lowercase and type(value) == 'string' and type(v) == 'string' then
if v:lower() == value:lower() then return k end
end
if v == value then return k end
end
end
function table.findbykey(t, key, lowercase)
for k,v in pairs(t) do
if lowercase and type(key) == 'string' and type(k) == 'string' then
if k:lower() == key:lower() then return v end
end
if k == key then return v end
end
end
function table.contains(t, value, lowercase)
return table.find(t, value, lowercase) ~= nil
end
function table.findkey(t, key)
if t and type(t) == 'table' then
for k,v in pairs(t) do
if k == key then return k end
end
end
end
function table.haskey(t, key)
return table.findkey(t, key) ~= nil
end
function table.removevalue(t, value)
for k,v in pairs(t) do
if v == value then
table.remove(t, k)
return true
end
end
return false
end
function table.popvalue(value)
local index = nil
for k,v in pairs(t) do
if v == value or not value then
index = k
end
end
if index then
table.remove(t, index)
return true
end
return false
end
function table.compare(t, other)
if #t ~= #other then return false end
for k,v in pairs(t) do
if v ~= other[k] then return false end
end
return true
end
function table.empty(t)
if t and type(t) == 'table' then
return next(t) == nil
end
return true
end
function table.permute(t, n, count)
n = n or #t
for i=1,count or n do
local j = math.random(i, n)
t[i], t[j] = t[j], t[i]
end
return t
end
function table.findbyfield(t, fieldname, fieldvalue)
for _i,subt in pairs(t) do
if subt[fieldname] == fieldvalue then
return subt
end
end
return nil
end
function table.size(t)
local size = 0
for i, n in pairs(t) do
size = size + 1
end
return size
end
function table.tostring(t)
local maxn = #t
local str = ""
for k,v in pairs(t) do
v = tostring(v)
if k == maxn and k ~= 1 then
str = str .. " and " .. v
elseif maxn > 1 and k ~= 1 then
str = str .. ", " .. v
else
str = str .. " " .. v
end
end
return str
end
function table.collect(t, func)
local res = {}
for k,v in pairs(t) do
local a,b = func(k,v)
if a and b then
res[a] = b
elseif a ~= nil then
table.insert(res,a)
end
end
return res
end
function table.equals(t, comp)
local equals = false
if type(t) == "table" and type(comp) == "table" then
for k,v in pairs(t) do
if v == comp[k] then
equals = true
end
end
end
return equals
end
|
-- @docclass table
function table.dump(t, depth)
if not depth then depth = 0 end
for k,v in pairs(t) do
str = (' '):rep(depth * 2) .. k .. ': '
if type(v) ~= "table" then
print(str .. tostring(v))
else
print(str)
table.dump(v, depth+1)
end
end
end
function table.clear(t)
for k,v in pairs(t) do
t[k] = nil
end
end
function table.copy(t)
local res = {}
for k,v in pairs(t) do
res[k] = v
end
return res
end
function table.recursivecopy(t)
local res = {}
for k,v in pairs(t) do
if type(v) == "table" then
res[k] = table.recursivecopy(v)
else
res[k] = v
end
end
return res
end
function table.selectivecopy(t, keys)
local res = { }
for i,v in ipairs(keys) do
res[v] = t[v]
end
return res
end
function table.merge(t, src)
for k,v in pairs(src) do
t[k] = v
end
end
function table.find(t, value, lowercase)
for k,v in pairs(t) do
if lowercase and type(value) == 'string' and type(v) == 'string' then
if v:lower() == value:lower() then return k end
end
if v == value then return k end
end
end
function table.findbykey(t, key, lowercase)
for k,v in pairs(t) do
if lowercase and type(key) == 'string' and type(k) == 'string' then
if k:lower() == key:lower() then return v end
end
if k == key then return v end
end
end
function table.contains(t, value, lowercase)
return table.find(t, value, lowercase) ~= nil
end
function table.findkey(t, key)
if t and type(t) == 'table' then
for k,v in pairs(t) do
if k == key then return k end
end
end
end
function table.haskey(t, key)
return table.findkey(t, key) ~= nil
end
function table.removevalue(t, value)
for k,v in pairs(t) do
if v == value then
table.remove(t, k)
return true
end
end
return false
end
function table.popvalue(value)
local index = nil
for k,v in pairs(t) do
if v == value or not value then
index = k
end
end
if index then
table.remove(t, index)
return true
end
return false
end
function table.compare(t, other)
if #t ~= #other then return false end
for k,v in pairs(t) do
if v ~= other[k] then return false end
end
return true
end
function table.empty(t)
if t and type(t) == 'table' then
return next(t) == nil
end
return true
end
function table.permute(t, n, count)
n = n or #t
for i=1,count or n do
local j = math.random(i, n)
t[i], t[j] = t[j], t[i]
end
return t
end
function table.findbyfield(t, fieldname, fieldvalue)
for _i,subt in pairs(t) do
if subt[fieldname] == fieldvalue then
return subt
end
end
return nil
end
function table.size(t)
local size = 0
for i, n in pairs(t) do
size = size + 1
end
return size
end
function table.tostring(t)
local maxn = #t
local str = ""
for k,v in pairs(t) do
v = tostring(v)
if k == maxn and k ~= 1 then
str = str .. " and " .. v
elseif maxn > 1 and k ~= 1 then
str = str .. ", " .. v
else
str = str .. " " .. v
end
end
return str
end
function table.collect(t, func)
local res = {}
for k,v in pairs(t) do
local a,b = func(k,v)
if a and b then
res[a] = b
elseif a ~= nil then
table.insert(res,a)
end
end
return res
end
function table.equals(t, comp)
if type(t) == "table" and type(comp) == "table" then
for k,v in pairs(t) do
if v ~= comp[k] then return false end
end
end
return true
end
|
Fix table.equals
|
Fix table.equals
|
Lua
|
mit
|
Cavitt/otclient_mapgen,Radseq/otclient,Radseq/otclient,dreamsxin/otclient,dreamsxin/otclient,gpedro/otclient,gpedro/otclient,Cavitt/otclient_mapgen,gpedro/otclient,dreamsxin/otclient
|
78a40e7ebd3ebeb4b1c44e2782b0ad40d34639c7
|
libcallow.lua
|
libcallow.lua
|
local io = require "io"
local string = require "string"
-- Types --
local function _list (car, cdr)
local c = {
type = "list",
car = car,
cdr = cdr,
len = 1,
}
if cdr then
c.len = cdr.len + 1
end
return c
end
local function _symbol (sym)
return {
type = "symbol",
sym = sym,
}
end
local function _number (num)
return {
type = "number",
num = num
}
end
local function _fn (fn)
return {
type = "fn",
fn = fn,
}
end
local function _lambda (args, body, env)
return {
type = "lambda",
args = args,
body = body,
env = env,
}
end
local function _macro (args, body, env)
return {
type = "macro",
args = args,
body = body,
env = env,
}
end
local function _error (msg)
return {
type = "error",
msg = msg,
}
end
local function _is_fn (v)
return v.type == "fn"
end
local function _is_lambda (v)
return v.type == "lambda"
end
local function _is_macro (v)
return v.type == "macro"
end
local function _is_error (v)
return v.type == "error"
end
local function _is_list (v)
return v.type == "list"
end
local function _is_symbol_(v)
return v.type == "symbol"
end
local function _is_number (v)
return v.type == "number"
end
local function _type (v)
if type(v) == "table" then
return v.type
else
return "nil"
end
end
-- Parsing --
local function _strip (s)
return (string.match(s, "%s*(.*)%s*"))
end
local function _read (str)
local function _read_list (l)
local list, v, rest = {}, nil, l
repeat
v, rest = _read(rest)
if _is_error(v) then return v end
list[#list + 1] = v
until rest == nil
return list
end
local a = _strip(str)
if a == "" then
return nil
end
local list = string.match(a, "^%((.*)%)")
if list then
return _read_list(list)
end
local sym, index = string.match(a, "^(%a%w*)()")
if sym then
return _symbol(sym), string.sub(a, index, -1)
end
local num, index = string.match(a, "^(%d)()")
num = tonumber(num)
if num then
return _number(num), string.sub(a, index, -1)
end
return _error("invalid input")
end
-- Printing --
local function _print (v)
if _is_list(v) then
local n = #v
io.write("(")
for i,v in ipairs(v) do
_print(v)
if i ~= n then
io.write(" ")
end
end
io.write(")")
elseif _is_symbol(v) then
io.write(v.sym)
elseif _is_number(v) then
io.write(v.num)
elseif _is_error(v) then
io.write(string.format("<error %s>" , v.msg))
else
io.write("<" .. v.type .. ">")
end
end
-- Internal Functions --
local function _len (v)
if not _is_list(v) then
return 0
end
return v.len
end
local function _bind (sym, v, env)
return _list(_list(sym, v), env)
end
local function _lookup (sym, env)
if not env then
return _error("Lookup of symbol " ..
sym .. " failed.")
end
if env.car.car == sym then
return env.car.cdr
end
return _lookup(sym, env.cdr)
end
local function _eval (v, env)
if _is_number(v) or
_is_error(v) or
_is_fn(v) or
_is_lambda(v) or
_is_macro(v)
then
return v
end
if _is_symbol(v) then
return _eval(_lookup(v, env))
end
if _is_list(v) then
local eval_list = _list(_eval(v.car), _eval(v.cdr))
if _is_fn(eval_list.car) then
local fn = eval_list.car.fn
local args = eval_list.cdr
return fn(args, env)
end
-- TODO call lambda
-- TODO expand macro
end
return nil
end
-- Lisp Functions --
local function car (args, env)
args = _eval(args, env)
if _len(args) != 1 then
return _error("car requires 1 argument. " ..
_len(args) .. " provided.")
end
if not _is_list(args.car) then
return _error("car requires a list argument. " ..
_type(args.car) .. " provided.")
end
return args.car.car
end
local function cdr (args, env)
args = _eval(args, env)
if _len(args) != 1 then
return _error("cdr requires 1 argument. " ..
_len(args) .. " provided.")
end
if not _is_list(args.car) then
return _error("cdr requires a list argument. " ..
_type(args.car) .. " provided.")
end
return args.car.cdr
end
local function list (args, env)
args = _eval(args, env)
if _len(args) != 1 then
return _error("list requires 1 argument. " ..
_len(args) .. " provided.")
end
if _is_list(args.car) then
return "t"
else
return nil
end
end
local function cons (args, env)
args = _eval(args, env)
if _len(args) != 2 then
return _error("cons requires 2 arguments. " ..
_len(args) .. " provided.")
end
if not _is_list(args.cdr.car) then
return _error("cons requires a second list argument. " ..
_type(args.cdr.car) .. " provided.")
end
return _list(args.car, args.cdr.car)
end
local function label (args, env)
if _len(args) != 3 then
return _error("label requires 2 arguments. " ..
_len(args) .. " provided.")
end
if _type(args.car) != "symbol" then
return _error("label requires first symbol argument. " ..
_type(args.car) .. " provided.")
end
local label_env = bind(args.car, args.cdr.car, env)
return _eval(args.cdr.cdr.car, label_env)
end
local function lambda (args, env)
if _len(args) != 2 then
return _error("lambda requires 2 arguments. " ..
_len(args) .. " provided.")
end
if not _is_list(args.car) then
return _error("lambda requires first list argument. " ..
_type(args.car) .. " provided.")
end
-- TODO verify all names are symbols
return _lambda(args.car, args.cdr.car, env)
end
local function macro (args, env)
if _len(args) != 2 then
return _error("macro requires 2 arguments. " ..
_len(args) .. " provided.")
end
if not _is_list(args.car) then
return _error("macro requires first list argument. " ..
_type(args.car) .. " provided.")
end
end
-- Library Exports --
return {
read = _read,
print = _print,
}
|
local io = require "io"
local string = require "string"
-- Types --
local function _list (car, cdr)
local c = {
type = "list",
car = car,
cdr = cdr,
len = 1,
}
if cdr then
c.len = cdr.len + 1
end
return c
end
local function _symbol (sym)
return {
type = "symbol",
sym = sym,
}
end
local function _number (num)
return {
type = "number",
num = num
}
end
local function _fn (fn)
return {
type = "fn",
fn = fn,
}
end
local function _lambda (args, body, env)
return {
type = "lambda",
args = args,
body = body,
env = env,
}
end
local function _macro (args, body, env)
return {
type = "macro",
args = args,
body = body,
env = env,
}
end
local function _error (msg)
return {
type = "error",
msg = msg,
}
end
local function _is_fn (v)
return type(v) == "table" and v.type == "fn"
end
local function _is_lambda (v)
return type(v) == "table" and v.type == "lambda"
end
local function _is_macro (v)
return type(v) == "table" and v.type == "macro"
end
local function _is_error (v)
return type(v) == "table" and v.type == "error"
end
local function _is_list (v)
return type(v) == "table" and v.type == "list"
end
local function _is_symbol (v)
return type(v) == "table" and v.type == "symbol"
end
local function _is_number (v)
return type(v) == "table" and v.type == "number"
end
local function _type (v)
if type(v) == "table" then
return v.type
else
return "nil"
end
end
-- Parsing --
local function _strip (s)
return (string.match(s, "%s*(.*)%s*"))
end
local function _read (str)
local function _read_list (l)
local v, rest = _read(l)
if _is_error(v) then return v end
if not v then return v end
local cdr = nil
if rest then
cdr = _read_list(rest)
end
return _list(v, cdr)
end
local a = _strip(str)
if a == "" then
return nil
end
local list = string.match(a, "^%((.*)%)")
if list then
return _read_list(list)
end
local sym, index = string.match(a, "^(%a%w*)()")
if sym then
return _symbol(sym), string.sub(a, index, -1)
end
local num, index = string.match(a, "^(%d)()")
num = tonumber(num)
if num then
return _number(num), string.sub(a, index, -1)
end
return _error("invalid input")
end
-- Printing --
local function _print (v)
if _is_list(v) then
io.write("(")
repeat
_print(v.car)
if v.len > 1 then
io.write(" ")
end
v = v.cdr
until not v
io.write(")")
elseif _is_symbol(v) then
io.write(v.sym)
elseif _is_number(v) then
io.write(v.num)
elseif _is_error(v) then
io.write(string.format("<error %s>" , v.msg))
elseif type(v) == "table" and v.type then
io.write("<" .. v.type .. ">")
elseif v == nil then
io.write("<nil>")
else
io.write("<unknown>")
end
end
-- Internal Functions --
local function _len (v)
if not _is_list(v) then
return 0
end
return v.len
end
local function _bind (sym, v, env)
return _list(_list(sym, v), env)
end
local function _lookup (sym, env)
if not env then
return _error("Lookup of symbol " ..
sym .. " failed.")
end
if env.car.car == sym then
return env.car.cdr
end
return _lookup(sym, env.cdr)
end
local function _eval (v, env)
if _is_number(v) or
_is_error(v) or
_is_fn(v) or
_is_lambda(v) or
_is_macro(v)
then
return v
end
if _is_symbol(v) then
return _eval(_lookup(v, env))
end
if _is_list(v) then
local eval_list = _list(_eval(v.car), _eval(v.cdr))
if _is_fn(eval_list.car) then
local fn = eval_list.car.fn
local args = eval_list.cdr
return fn(args, env)
end
-- TODO call lambda
-- TODO expand macro
end
return nil
end
-- Lisp Functions --
local function car (args, env)
args = _eval(args, env)
if _len(args) ~= 1 then
return _error("car requires 1 argument. " ..
_len(args) .. " provided.")
end
if not _is_list(args.car) then
return _error("car requires a list argument. " ..
_type(args.car) .. " provided.")
end
return args.car.car
end
local function cdr (args, env)
args = _eval(args, env)
if _len(args) ~= 1 then
return _error("cdr requires 1 argument. " ..
_len(args) .. " provided.")
end
if not _is_list(args.car) then
return _error("cdr requires a list argument. " ..
_type(args.car) .. " provided.")
end
return args.car.cdr
end
local function list (args, env)
args = _eval(args, env)
if _len(args) ~= 1 then
return _error("list requires 1 argument. " ..
_len(args) .. " provided.")
end
if _is_list(args.car) then
return "t"
else
return nil
end
end
local function cons (args, env)
args = _eval(args, env)
if _len(args) ~= 2 then
return _error("cons requires 2 arguments. " ..
_len(args) .. " provided.")
end
if not _is_list(args.cdr.car) then
return _error("cons requires a second list argument. " ..
_type(args.cdr.car) .. " provided.")
end
return _list(args.car, args.cdr.car)
end
local function label (args, env)
if _len(args) ~= 3 then
return _error("label requires 2 arguments. " ..
_len(args) .. " provided.")
end
if _type(args.car) ~= "symbol" then
return _error("label requires first symbol argument. " ..
_type(args.car) .. " provided.")
end
local label_env = bind(args.car, args.cdr.car, env)
return _eval(args.cdr.cdr.car, label_env)
end
local function lambda (args, env)
if _len(args) ~= 2 then
return _error("lambda requires 2 arguments. " ..
_len(args) .. " provided.")
end
if not _is_list(args.car) then
return _error("lambda requires first list argument. " ..
_type(args.car) .. " provided.")
end
-- TODO verify all names are symbols
return _lambda(args.car, args.cdr.car, env)
end
local function macro (args, env)
if _len(args) ~= 2 then
return _error("macro requires 2 arguments. " ..
_len(args) .. " provided.")
end
if not _is_list(args.car) then
return _error("macro requires first list argument. " ..
_type(args.car) .. " provided.")
end
end
-- Library Exports --
return {
read = _read,
print = _print,
}
|
Fix parsing with all values as tables.
|
Fix parsing with all values as tables.
|
Lua
|
mit
|
josephburnett/callow
|
5aabc7a6ab3ed1b3701646440df1d526411a6e31
|
premake5.lua
|
premake5.lua
|
-- A solution contains projects, and defines the available configurations
solution "brotli"
configurations { "Release", "Debug" }
targetdir "bin"
location "buildfiles"
flags "RelativeLinks"
includedirs { "c/include" }
filter "configurations:Release"
optimize "Speed"
flags { "StaticRuntime" }
filter "configurations:Debug"
flags { "Symbols" }
configuration { "gmake" }
buildoptions { "-Wall -fno-omit-frame-pointer" }
location "buildfiles/gmake"
configuration { "xcode4" }
location "buildfiles/xcode4"
configuration "linux"
links "m"
configuration { "macosx" }
defines { "OS_MACOSX" }
project "brotlicommon"
kind "SharedLib"
language "C"
files { "c/common/**.h", "c/common/**.c" }
project "brotlicommon_static"
kind "StaticLib"
targetname "brotlicommon"
language "C"
files { "c/common/**.h", "c/common/**.c" }
project "brotlidec"
kind "SharedLib"
language "C"
files { "c/dec/**.h", "c/dec/**.c" }
links "brotlicommon"
project "brotlidec_static"
kind "StaticLib"
targetname "brotlidec"
language "C"
files { "c/dec/**.h", "c/dec/**.c" }
links "brotlicommon_static"
project "brotlienc"
kind "SharedLib"
language "C"
files { "c/enc/**.h", "c/enc/**.c" }
links "brotlicommon"
project "brotlienc_static"
kind "StaticLib"
targetname "brotlienc"
language "C"
files { "c/enc/**.h", "c/enc/**.c" }
links "brotlicommon_static"
project "brotli"
kind "ConsoleApp"
language "C"
linkoptions "-static"
files { "c/tools/brotli.c" }
links { "brotlicommon_static", "brotlidec_static", "brotlienc_static" }
|
-- A solution contains projects, and defines the available configurations
solution "brotli"
configurations { "Release", "Debug" }
platforms { "x64", "x86" }
targetdir "bin"
location "buildfiles"
flags "RelativeLinks"
includedirs { "c/include" }
filter "configurations:Release"
optimize "Speed"
flags { "StaticRuntime" }
filter "configurations:Debug"
flags { "Symbols" }
filter { "platforms:x64" }
architecture "x86_64"
filter { "platforms:x86" }
architecture "x86"
configuration { "gmake" }
buildoptions { "-Wall -fno-omit-frame-pointer" }
location "buildfiles/gmake"
configuration { "xcode4" }
location "buildfiles/xcode4"
configuration "linux"
links "m"
configuration { "macosx" }
defines { "OS_MACOSX" }
project "brotlicommon"
kind "SharedLib"
language "C"
files { "c/common/**.h", "c/common/**.c" }
project "brotlicommon_static"
kind "StaticLib"
targetname "brotlicommon"
language "C"
files { "c/common/**.h", "c/common/**.c" }
project "brotlidec"
kind "SharedLib"
language "C"
files { "c/dec/**.h", "c/dec/**.c" }
links "brotlicommon"
project "brotlidec_static"
kind "StaticLib"
targetname "brotlidec"
language "C"
files { "c/dec/**.h", "c/dec/**.c" }
links "brotlicommon_static"
project "brotlienc"
kind "SharedLib"
language "C"
files { "c/enc/**.h", "c/enc/**.c" }
links "brotlicommon"
project "brotlienc_static"
kind "StaticLib"
targetname "brotlienc"
language "C"
files { "c/enc/**.h", "c/enc/**.c" }
links "brotlicommon_static"
project "brotli"
kind "ConsoleApp"
language "C"
linkoptions "-static"
files { "c/tools/brotli.c" }
links { "brotlicommon_static", "brotlidec_static", "brotlienc_static" }
|
Added windows platform support to premake (#567)
|
Added windows platform support to premake (#567)
* Added windows platform support to premake
Win32 and Win64 configuration support for visual studio solutions
* Update premake5.lua
Fixed platform support for linux, made x64 default
* Update premake5.lua
Fix typo
|
Lua
|
mit
|
google/brotli,nicksay/brotli,google/brotli,nicksay/brotli,google/brotli,nicksay/brotli,google/brotli,google/brotli,google/brotli,nicksay/brotli,nicksay/brotli,google/brotli,google/brotli,nicksay/brotli,nicksay/brotli
|
99078fffbd5a967bebf8d833bbe37742f56f5e28
|
premake5.lua
|
premake5.lua
|
include("tools/build")
require("third_party/premake-export-compile-commands/export-compile-commands")
location(build_root)
targetdir(build_bin)
objdir(build_obj)
includedirs({
".",
"src",
"third_party",
})
defines({
"_UNICODE",
"UNICODE",
-- TODO(benvanik): find a better place for this stuff.
"GLEW_NO_GLU=1",
})
vectorextensions("AVX")
flags({
--"ExtraWarnings", -- Sets the compiler's maximum warning level.
"FatalWarnings", -- Treat warnings as errors.
"Unicode",
})
filter("kind:StaticLib")
defines({
"_LIB",
})
filter("configurations:Checked")
runtime("Debug")
defines({
"DEBUG",
})
runtime("Debug")
filter({"configurations:Checked", "platforms:Windows"})
buildoptions({
"/RTCsu", -- Full Run-Time Checks.
})
filter("configurations:Debug")
runtime("Debug")
defines({
"DEBUG",
"_NO_DEBUG_HEAP=1",
})
runtime("Release")
filter({"configurations:Debug", "platforms:Windows"})
linkoptions({
"/NODEFAULTLIB:MSVCRTD",
})
filter("configurations:Release")
runtime("Release")
defines({
"NDEBUG",
"_NO_DEBUG_HEAP=1",
})
optimize("On")
flags({
"LinkTimeOptimization",
})
runtime("Release")
filter({"configurations:Release", "platforms:Windows"})
linkoptions({
"/NODEFAULTLIB:MSVCRTD",
})
filter("platforms:Linux")
system("linux")
toolset("clang")
buildoptions({
"-mlzcnt", -- Assume lzcnt supported.
})
links({
"pthread",
})
filter({"platforms:Linux", "language:C++"})
buildoptions({
"-std=c++14",
"-stdlib=libc++",
})
links({
"c++",
})
filter("platforms:Windows")
system("windows")
toolset("msc")
buildoptions({
"/MP", -- Multiprocessor compilation.
"/wd4100", -- Unreferenced parameters are ok.
"/wd4201", -- Nameless struct/unions are ok.
"/wd4512", -- 'assignment operator was implicitly defined as deleted'.
"/wd4127", -- 'conditional expression is constant'.
"/wd4324", -- 'structure was padded due to alignment specifier'.
"/wd4189", -- 'local variable is initialized but not referenced'.
})
flags({
"NoMinimalRebuild", -- Required for /MP above.
"Symbols",
})
defines({
"_CRT_NONSTDC_NO_DEPRECATE",
"_CRT_SECURE_NO_WARNINGS",
"WIN32",
"_WIN64=1",
"_AMD64=1",
})
linkoptions({
"/ignore:4006", -- Ignores complaints about empty obj files.
"/ignore:4221",
})
links({
"ntdll",
"wsock32",
"ws2_32",
"xinput",
"xaudio2",
"glu32",
"opengl32",
"comctl32",
"shlwapi",
})
-- Create scratch/ path and dummy flags file if needed.
if not os.isdir("scratch") then
os.mkdir("scratch")
local flags_file = io.open("scratch/flags.txt", "w")
flags_file:write("# Put flags, one on each line.\n")
flags_file:write("# Launch executables with --flags_file=scratch/flags.txt\n")
flags_file:write("\n")
flags_file:write("--cpu=x64\n")
flags_file:write("#--enable_haswell_instructions=false\n")
flags_file:write("\n")
flags_file:write("--debug\n")
flags_file:write("#--protect_zero=false\n")
flags_file:write("\n")
flags_file:write("#--mute\n")
flags_file:write("\n")
flags_file:write("--fast_stdout\n")
flags_file:write("#--flush_stdout=false\n")
flags_file:write("\n")
flags_file:write("#--vsync=false\n")
flags_file:write("#--gl_debug\n")
flags_file:write("#--gl_debug_output\n")
flags_file:write("#--gl_debug_output_synchronous\n")
flags_file:write("#--trace_gpu_prefix=scratch/gpu/gpu_trace_\n")
flags_file:write("#--trace_gpu_stream\n")
flags_file:write("#--disable_framebuffer_readback\n")
flags_file:write("\n")
flags_file:close()
end
solution("xenia")
uuid("931ef4b0-6170-4f7a-aaf2-0fece7632747")
startproject("xenia-app")
architecture("x86_64")
if os.is("linux") then
platforms({"Linux"})
elseif os.is("windows") then
platforms({"Windows"})
end
configurations({"Checked", "Debug", "Release"})
-- Include third party files first so they don't have to deal with gflags.
include("third_party/capstone.lua")
include("third_party/gflags.lua")
include("third_party/glew.lua")
include("third_party/glslang-spirv.lua")
include("third_party/imgui.lua")
include("third_party/libav.lua")
include("third_party/snappy.lua")
include("third_party/spirv-tools.lua")
include("third_party/vulkan/loader")
include("third_party/xxhash.lua")
include("third_party/yaml-cpp.lua")
include("src/xenia")
include("src/xenia/app")
include("src/xenia/apu")
include("src/xenia/apu/nop")
include("src/xenia/base")
include("src/xenia/cpu")
include("src/xenia/cpu/backend/x64")
include("src/xenia/debug/ui")
include("src/xenia/gpu")
include("src/xenia/gpu/null")
include("src/xenia/gpu/gl4")
include("src/xenia/gpu/vulkan")
include("src/xenia/hid")
include("src/xenia/hid/nop")
include("src/xenia/kernel")
include("src/xenia/ui")
include("src/xenia/ui/gl")
include("src/xenia/ui/spirv")
include("src/xenia/ui/vulkan")
include("src/xenia/vfs")
if os.is("windows") then
include("src/xenia/apu/xaudio2")
include("src/xenia/hid/winkey")
include("src/xenia/hid/xinput")
end
|
include("tools/build")
require("third_party/premake-export-compile-commands/export-compile-commands")
location(build_root)
targetdir(build_bin)
objdir(build_obj)
includedirs({
".",
"src",
"third_party",
})
defines({
"_UNICODE",
"UNICODE",
-- TODO(benvanik): find a better place for this stuff.
"GLEW_NO_GLU=1",
})
-- TODO(DrChat): Find a way to disable this on other architectures.
filter("architecture:x86_64")
vectorextensions("AVX")
filter({})
characterset("Unicode")
flags({
--"ExtraWarnings", -- Sets the compiler's maximum warning level.
"FatalWarnings", -- Treat warnings as errors.
})
filter("kind:StaticLib")
defines({
"_LIB",
})
filter("configurations:Checked")
runtime("Debug")
defines({
"DEBUG",
})
runtime("Debug")
filter({"configurations:Checked", "platforms:Windows"})
buildoptions({
"/RTCsu", -- Full Run-Time Checks.
})
filter("configurations:Debug")
runtime("Debug")
defines({
"DEBUG",
"_NO_DEBUG_HEAP=1",
})
runtime("Release")
filter({"configurations:Debug", "platforms:Windows"})
linkoptions({
"/NODEFAULTLIB:MSVCRTD",
})
filter("configurations:Release")
runtime("Release")
defines({
"NDEBUG",
"_NO_DEBUG_HEAP=1",
})
optimize("On")
flags({
"LinkTimeOptimization",
})
runtime("Release")
filter({"configurations:Release", "platforms:Windows"})
linkoptions({
"/NODEFAULTLIB:MSVCRTD",
})
filter("platforms:Linux")
system("linux")
toolset("clang")
buildoptions({
-- "-mlzcnt", -- (don't) Assume lzcnt is supported.
})
links({
"pthread",
})
filter({"platforms:Linux", "language:C++", "toolset:clang"})
buildoptions({
"-std=c++14",
"-stdlib=libc++",
})
links({
"c++",
})
filter("platforms:Windows")
system("windows")
toolset("msc")
buildoptions({
"/MP", -- Multiprocessor compilation.
"/wd4100", -- Unreferenced parameters are ok.
"/wd4201", -- Nameless struct/unions are ok.
"/wd4512", -- 'assignment operator was implicitly defined as deleted'.
"/wd4127", -- 'conditional expression is constant'.
"/wd4324", -- 'structure was padded due to alignment specifier'.
"/wd4189", -- 'local variable is initialized but not referenced'.
})
flags({
"NoMinimalRebuild", -- Required for /MP above.
})
symbols("On")
defines({
"_CRT_NONSTDC_NO_DEPRECATE",
"_CRT_SECURE_NO_WARNINGS",
"WIN32",
"_WIN64=1",
"_AMD64=1",
})
linkoptions({
"/ignore:4006", -- Ignores complaints about empty obj files.
"/ignore:4221",
})
links({
"ntdll",
"wsock32",
"ws2_32",
"xinput",
"xaudio2",
"glu32",
"opengl32",
"comctl32",
"shlwapi",
})
-- Create scratch/ path and dummy flags file if needed.
if not os.isdir("scratch") then
os.mkdir("scratch")
local flags_file = io.open("scratch/flags.txt", "w")
flags_file:write("# Put flags, one on each line.\n")
flags_file:write("# Launch executables with --flags_file=scratch/flags.txt\n")
flags_file:write("\n")
flags_file:write("--cpu=x64\n")
flags_file:write("#--enable_haswell_instructions=false\n")
flags_file:write("\n")
flags_file:write("--debug\n")
flags_file:write("#--protect_zero=false\n")
flags_file:write("\n")
flags_file:write("#--mute\n")
flags_file:write("\n")
flags_file:write("--fast_stdout\n")
flags_file:write("#--flush_stdout=false\n")
flags_file:write("\n")
flags_file:write("#--vsync=false\n")
flags_file:write("#--gl_debug\n")
flags_file:write("#--gl_debug_output\n")
flags_file:write("#--gl_debug_output_synchronous\n")
flags_file:write("#--trace_gpu_prefix=scratch/gpu/gpu_trace_\n")
flags_file:write("#--trace_gpu_stream\n")
flags_file:write("#--disable_framebuffer_readback\n")
flags_file:write("\n")
flags_file:close()
end
solution("xenia")
uuid("931ef4b0-6170-4f7a-aaf2-0fece7632747")
startproject("xenia-app")
architecture("x86_64")
if os.is("linux") then
platforms({"Linux"})
elseif os.is("windows") then
platforms({"Windows"})
end
configurations({"Checked", "Debug", "Release"})
-- Include third party files first so they don't have to deal with gflags.
include("third_party/capstone.lua")
include("third_party/gflags.lua")
include("third_party/glew.lua")
include("third_party/glslang-spirv.lua")
include("third_party/imgui.lua")
include("third_party/libav.lua")
include("third_party/snappy.lua")
include("third_party/spirv-tools.lua")
include("third_party/vulkan/loader")
include("third_party/xxhash.lua")
include("third_party/yaml-cpp.lua")
include("src/xenia")
include("src/xenia/app")
include("src/xenia/apu")
include("src/xenia/apu/nop")
include("src/xenia/base")
include("src/xenia/cpu")
include("src/xenia/cpu/backend/x64")
include("src/xenia/debug/ui")
include("src/xenia/gpu")
include("src/xenia/gpu/null")
include("src/xenia/gpu/gl4")
include("src/xenia/gpu/vulkan")
include("src/xenia/hid")
include("src/xenia/hid/nop")
include("src/xenia/kernel")
include("src/xenia/ui")
include("src/xenia/ui/gl")
include("src/xenia/ui/spirv")
include("src/xenia/ui/vulkan")
include("src/xenia/vfs")
if os.is("windows") then
include("src/xenia/apu/xaudio2")
include("src/xenia/hid/winkey")
include("src/xenia/hid/xinput")
end
|
Premake: Fix a few issues (using deprecated functionality, hard to change toolset, disable lzcnt)
|
Premake: Fix a few issues (using deprecated functionality, hard to change toolset, disable lzcnt)
|
Lua
|
bsd-3-clause
|
maxton/xenia,sephiroth99/xenia,maxton/xenia,sephiroth99/xenia,sephiroth99/xenia,maxton/xenia
|
ad0ac0196de235d74deb11c0f1330ae0427de045
|
hardware/APS/libaps2-cpp/src/test/aps2_dissectors.lua
|
hardware/APS/libaps2-cpp/src/test/aps2_dissectors.lua
|
-- wireshark APS2 protocol dissectors
-- declare our protocol
aps_proto = Proto("aps2","APS2 Control Protocol")
local a = aps_proto.fields
local aps_commands = { [0] = "RESET",
[ 0x01] = "USER I/O ACK",
[ 0x09] = "USER I/O NACK",
[ 0x02] = "EPROM I/O",
[ 0x03] = "CHIP CONFIG I/O",
[ 0x04] = "RUN CHIP CONFIG",
[ 0x05] = "FPGA CONFIG ACK",
[ 0x0D] = "FPGA CONFIG NACK",
[ 0x06] = "FPGA CONFIG CONTROL",
[ 0x07 ] = "FGPA Status"
}
a.seqnum = ProtoField.uint16("aps.seqnum", "SeqNum")
a.packedCmd = ProtoField.uint32("aps.cmd","Command" , base.HEX)
a.ack = ProtoField.uint8("aps.cmd", "Ack", base.DEC, nil, 0x80)
a.seq = ProtoField.uint8("aps.seq", "Seq", base.DEC, nil, 0x40)
a.sel = ProtoField.uint8("aps.sel", "Sel", base.DEC, nil, 0x20)
a.rw = ProtoField.uint8("aps.rw", "R/W" , base.DEC, nil, 0x10)
a.cmd = ProtoField.uint8("aps.cmd", "Cmd" , base.HEX, aps_commands, 0x0F)
a.mode_stat = ProtoField.uint8("aps.mode_state", "Mode/Stat" , base.HEX)
a.cnt = ProtoField.uint16("aps.cnt", "Cnt" , base.DEC)
a.addr = ProtoField.uint32("aps.address", "Address" , base.HEX)
a.chipcfgPacked = ProtoField.uint32("aps.chipcfgPacked", "Chip Config I/O Command" , base.HEX)
a.target = ProtoField.uint8("aps.target", "TARGET" , base.HEX)
a.spicnt = ProtoField.uint8("aps.spicnt", "SPICNT/DATA" , base.HEX)
a.instr = ProtoField.uint16("aps.instr", "INSTR" , base.HEX)
a.instrAddr = ProtoField.uint8("aps.instrAddr", "Addr" , base.HEX)
a.instrData = ProtoField.uint8("aps.instrData", "Data" , base.HEX)
-- create a function to dissect it
function aps_proto.dissector(buffer,pinfo,tree)
pinfo.cols.protocol = "APS2"
local subtree = tree:add(aps_proto,buffer())
local offset = 0
subtree:add( a.seqnum , buffer(offset,2))
offset = offset + 2
local cmdTree = subtree:add( a.packedCmd, buffer(offset,4))
cmdTree:add( a.ack, buffer(offset,1))
cmdTree:add( a.seq, buffer(offset,1))
cmdTree:add( a.sel, buffer(offset,1))
cmdTree:add( a.rw, buffer(offset,1))
cmdTree:add( a.cmd, buffer(offset,1))
cmdTree:add( a.mode_stat, buffer(offset+1,1))
cmdTree:add( a.cnt, buffer(offset+2,2))
local cmdVal = buffer(offset,1):bitfield(4,4)
pinfo.cols.info = ( aps_commands[cmdVal] or '?')
local ackVal = buffer(offset,1):bitfield(0,1)
if (ackVal == 1) then
pinfo.cols.info:append(" - ACK")
end
offset = offset + 4
subtree:add( a.addr, buffer(offset,4))
offset = offset + 4
-- parse chip config
if (cmdVal == 0x03) then
local chipcfg = subtree:add( a.chipcfgPacked, buffer(offset,4))
chipcfg:add( a.target, buffer(offset,1))
chipcfg:add( a.spicnt, buffer(offset+1,1))
local instr = chipcfg:add( a.instr, buffer(offset+2,2))
local targetVal = buffer(offset,1):uint()
if (targetVal == 0xd8 ) then
instr:add( a.instrAddr, buffer(offset+2,1))
instr:add( a.instrData, buffer(offset+3,1))
pinfo.cols.info:append(" - PLL")
end
end
-- subtree = subtree:add(buffer(2,4),"Command")
--local cmd = buffer(2,4):uint()
--local ack = tostring(bit.tohex(bit.rshift(cmd, 31),1))
--subtree:add(buffer(2,1),"ACK: " .. ack)
--local seq = tostring(bit.tohex(bit.band(bit.rshift(cmd, 30),1), 0x1))
--subtree:add(buffer(2,1),"SEQ: " .. seq)
--local sel = tostring(bit.tohex(bit.band(bit.rshift(cmd, 29),1), 0x1))
--subtree:add(buffer(2,1),"SEL: " .. sel)
--local rw = tostring(bit.tohex(bit.band(bit.rshift(cmd, 28),1), 0x1))
--subtree:add(buffer(2,1),"R/W: " .. rw)
--local cmd2 = tostring(bit.tohex(bit.band(bit.rshift(cmd, 24), 0x7)))
--subtree:add(buffer(2,1),"CMD: " .. cmd2)
--local mode_stat = tostring(bit.tohex(bit.band(bit.rshift(cmd, 16), 0xFF)))
--subtree:add(buffer(2,1),"MODE/STAT: " .. mode_stat)
--local cnt = tostring(bit.tohex(bit.band(cmd, 0xFF)))
--subtree:add(buffer(2,1),"CNT: " .. cnt)
--subtree = subtree:add(buffer(6,4),"Addr:" .. buffer(6,4))
end
eth_table = DissectorTable.get("ethertype")
-- attach to ethernet type 0xBBAE
eth_table:add(47950,aps_proto)
|
-- wireshark APS2 protocol dissectors
-- declare our protocol
aps_proto = Proto("aps2","APS2 Control Protocol")
local a = aps_proto.fields
local aps_commands = { [0] = "RESET",
[ 0x01] = "USER I/O ACK",
[ 0x09] = "USER I/O NACK",
[ 0x02] = "EPROM I/O",
[ 0x03] = "CHIP CONFIG I/O",
[ 0x04] = "RUN CHIP CONFIG",
[ 0x05] = "FPGA CONFIG ACK",
[ 0x0D] = "FPGA CONFIG NACK",
[ 0x06] = "FPGA CONFIG CONTROL",
[ 0x07 ] = "FGPA Status"
}
a.seqnum = ProtoField.uint16("aps.seqnum", "SeqNum")
a.packedCmd = ProtoField.uint32("aps.cmd","Command" , base.HEX)
a.ack = ProtoField.uint8("aps.cmd", "Ack", base.DEC, nil, 0x80)
a.seq = ProtoField.uint8("aps.seq", "Seq", base.DEC, nil, 0x40)
a.sel = ProtoField.uint8("aps.sel", "Sel", base.DEC, nil, 0x20)
a.rw = ProtoField.uint8("aps.rw", "R/W" , base.DEC, nil, 0x10)
a.cmd = ProtoField.uint8("aps.cmd", "Cmd" , base.HEX, aps_commands, 0x0F)
a.mode_stat = ProtoField.uint8("aps.mode_state", "Mode/Stat" , base.HEX)
a.cnt = ProtoField.uint16("aps.cnt", "Cnt" , base.DEC)
a.addr = ProtoField.uint32("aps.address", "Address" , base.HEX)
a.chipcfgPacked = ProtoField.uint32("aps.chipcfgPacked", "Chip Config I/O Command" , base.HEX)
a.target = ProtoField.uint8("aps.target", "TARGET" , base.HEX)
a.spicnt = ProtoField.uint8("aps.spicnt", "SPICNT/DATA" , base.HEX)
a.instr = ProtoField.uint16("aps.instr", "INSTR" , base.HEX)
a.instrAddr = ProtoField.uint32("aps.instrAddr", "Addr" , base.HEX)
a.payload = ProtoField.bytes("aps.payload", "Data")
a.hostFirmwareVersion = ProtoField.uint32("aps.hostFirmwareVersion", "Host Firmware Version", base.HEX)
-- create a function to dissect it
function aps_proto.dissector(buffer,pinfo,tree)
pinfo.cols.protocol = "APS2"
local subtree = tree:add(aps_proto,buffer())
local offset = 0
subtree:add( a.seqnum , buffer(offset,2))
offset = offset + 2
local cmdTree = subtree:add( a.packedCmd, buffer(offset,4))
cmdTree:add( a.ack, buffer(offset,1))
cmdTree:add( a.seq, buffer(offset,1))
cmdTree:add( a.sel, buffer(offset,1))
cmdTree:add( a.rw, buffer(offset,1))
cmdTree:add( a.cmd, buffer(offset,1))
cmdTree:add( a.mode_stat, buffer(offset+1,1))
cmdTree:add( a.cnt, buffer(offset+2,2))
local cmdVal = buffer(offset,1):bitfield(4,4)
pinfo.cols.info = ( aps_commands[cmdVal] or '?')
local ackVal = buffer(offset,1):bitfield(0,1)
if (ackVal == 1) then
pinfo.cols.info:append(" - ACK")
end
offset = offset + 4
subtree:add( a.addr, buffer(offset,4))
offset = offset + 4
if ((buffer:len() - 24) > 0) then
subtree:add(a.payload, buffer(offset))
end
-- parse chip config
if (cmdVal == 0x03) then
local chipcfg = subtree:add( a.chipcfgPacked, buffer(offset,4))
chipcfg:add( a.target, buffer(offset,1))
chipcfg:add( a.spicnt, buffer(offset+1,1))
local instr = chipcfg:add( a.instr, buffer(offset+2,2))
local targetVal = buffer(offset,1):uint()
if (targetVal == 0xd8 ) then
instr:add( a.instrAddr, buffer(offset+2,1))
instr:add( a.instrData, buffer(offset+3,1))
pinfo.cols.info:append(" - PLL")
end
end
-- parse status words
-- if (cmdVal == 0x07) then
-- local
-- subtree = subtree:add(buffer(2,4),"Command")
--local cmd = buffer(2,4):uint()
--local ack = tostring(bit.tohex(bit.rshift(cmd, 31),1))
--subtree:add(buffer(2,1),"ACK: " .. ack)
--local seq = tostring(bit.tohex(bit.band(bit.rshift(cmd, 30),1), 0x1))
--subtree:add(buffer(2,1),"SEQ: " .. seq)
--local sel = tostring(bit.tohex(bit.band(bit.rshift(cmd, 29),1), 0x1))
--subtree:add(buffer(2,1),"SEL: " .. sel)
--local rw = tostring(bit.tohex(bit.band(bit.rshift(cmd, 28),1), 0x1))
--subtree:add(buffer(2,1),"R/W: " .. rw)
--local cmd2 = tostring(bit.tohex(bit.band(bit.rshift(cmd, 24), 0x7)))
--subtree:add(buffer(2,1),"CMD: " .. cmd2)
--local mode_stat = tostring(bit.tohex(bit.band(bit.rshift(cmd, 16), 0xFF)))
--subtree:add(buffer(2,1),"MODE/STAT: " .. mode_stat)
--local cnt = tostring(bit.tohex(bit.band(cmd, 0xFF)))
--subtree:add(buffer(2,1),"CNT: " .. cnt)
--subtree = subtree:add(buffer(6,4),"Addr:" .. buffer(6,4))
end
eth_table = DissectorTable.get("ethertype")
-- attach to ethernet type 0xBBAE
eth_table:add(47950,aps_proto)
|
Lua dissector shows packet payload.
|
Lua dissector shows packet payload.
Also fix address type.
|
Lua
|
apache-2.0
|
BBN-Q/Qlab,BBN-Q/Qlab,BBN-Q/Qlab,rmcgurrin/Qlab,Plourde-Research-Lab/Qlab,BBN-Q/Qlab,rmcgurrin/Qlab,Plourde-Research-Lab/Qlab,Plourde-Research-Lab/Qlab,rmcgurrin/Qlab,rmcgurrin/Qlab
|
4c8012180f9ed0582e55bf3afdfa3aad6cbfcf09
|
officernotewarning.lua
|
officernotewarning.lua
|
local mod = EPGP:NewModule("EPGP_OfficerNoteWarning", "AceHook-3.0")
local L = LibStub("AceLocale-3.0"):GetLocale("EPGP")
function mod:OnInitialize()
StaticPopupDialogs["EPGP_OFFICER_NOTE_WARNING"] = {
text = L["EPGP is using Officer Notes for data storage. Do you really want to edit the Officer Note by hand?"],
button1 = YES,
button2 = NO,
timeout = 0,
OnAccept = function(self)
self:Hide()
mod.hooks[GuildMemberOfficerNoteBackground]["OnMouseUp"]()
end,
whileDead = 1,
hideOnEscape = 1,
}
end
function mod:OnMouseUp()
StaticPopup_Show("EPGP_OFFICER_NOTE_WARNING")
end
function mod:OnEnable()
if GuildMemberOfficerNoteBackground and GuildMemberOfficerNoteBackground:HasScript("OnMouseUp") then
self:RawHookScript(GuildMemberOfficerNoteBackground, "OnMouseUp")
end
end
|
local mod = EPGP:NewModule("EPGP_OfficerNoteWarning", "AceHook-3.0")
local L = LibStub("AceLocale-3.0"):GetLocale("EPGP")
StaticPopupDialogs["EPGP_OFFICER_NOTE_WARNING"] = {
text = L["EPGP is using Officer Notes for data storage. Do you really want to edit the Officer Note by hand?"],
button1 = YES,
button2 = NO,
timeout = 0,
OnAccept = function(self)
self:Hide()
mod.hooks[GuildMemberOfficerNoteBackground]["OnMouseUp"]()
end,
whileDead = 1,
hideOnEscape = 1,
showAlert = 1,
enterClicksFirstButton = 1,
}
function mod:OnMouseUp()
StaticPopup_Show("EPGP_OFFICER_NOTE_WARNING")
end
function mod:OnEnable()
if GuildMemberOfficerNoteBackground and GuildMemberOfficerNoteBackground:HasScript("OnMouseUp") then
self:RawHookScript(GuildMemberOfficerNoteBackground, "OnMouseUp")
end
end
|
Add alert icon to officer note warning popup. Also make it accept on enter. This fixes issue 282.
|
Add alert icon to officer note warning popup. Also make it accept on enter. This fixes issue 282.
|
Lua
|
bsd-3-clause
|
hayword/tfatf_epgp,protomech/epgp-dkp-reloaded,sheldon/epgp,protomech/epgp-dkp-reloaded,ceason/epgp-tfatf,sheldon/epgp,hayword/tfatf_epgp,ceason/epgp-tfatf
|
c8fe297dc97d5e830fb20ade49b686950c1dd315
|
protocols/luci-proto-ipv6/luasrc/model/cbi/admin_network/proto_aiccu.lua
|
protocols/luci-proto-ipv6/luasrc/model/cbi/admin_network/proto_aiccu.lua
|
-- Copyright 2015 Paul Oranje <por@xs4all.nl>
-- Licensed to the public under the Apache License 2.0.
local map, section, net = ...
-- config read by /lib/netifd/proto/aiccu.sh
local username, password, protocol, server, tunnelid, ip6prefix, requiretls, nat, heartbeat,
verbose, ntpsynctimeout, ip6addr, sourcerouting, defaultroute
-- generic parameters
local metric, ttl, mtu
username = section:taboption("general", Value, "username",
translate("Server username"),
translate("SIXXS-handle[/Tunnel-ID]"))
username.datatype = "string"
password = section:taboption("general", Value, "password",
translate("Server password"),
translate("Server password, enter the specific password of the tunnel when the username contains the tunnel ID"))
password.datatype = "string"
password.password = true
--[[ SIXXS supports only TIC as tunnel broker protocol, no use setting it.
protocol = section:taboption("general", ListValue, "protocol",
translate("Tunnel broker protocol"),
translate("SIXXS supports TIC only, for static tunnels using IP protocol 41 (RFC4213) use 6in4 instead"))
protocol:value("tic", "TIC")
protocol:value("tsp", "TSP")
protocol:value("l2tp", "L2TP")
protocol.default = "tic"
protocol.optional = true
--]]
server = section:taboption("general", Value, "server",
translate("Tunnel setup server"),
translate("Optional, specify to override default server (tic.sixxs.net)"))
server.datatype = "host"
server.optional = true
tunnelid = section:taboption("general", Value, "tunnelid",
translate("Tunnel ID"),
translate("Optional, use when the SIXXS account has more than one tunnel"))
tunnelid.datatype = "string"
tunnelid.optional = true
local ip6prefix = section:taboption("general", Value, "ip6prefix",
translate("IPv6 prefix"),
translate("Routed IPv6 prefix for downstream interfaces"))
ip6prefix.datatype = "ip6prefix"
ip6prefix.optional = true
requiretls = section:taboption("general", Flag, "requiretls",
translate("Require TLS"),
translate("Connection to server fails when TLS cannot be used"))
requiretls.optional = true
requiretls.default = requiretls.enabled
heartbeat = section:taboption("general", Flag, "heartbeat",
translate("Make heartbeats"),
translate("Use when IPv4 address of local WAN may change dynamically, does not apply to static tunnels"))
heartbeat.optional = true
heartbeat.default = heartbeat.enabled
nat = section:taboption("general", Flag, "nat",
translate("Behind NAT"),
translate("The tunnel end-point is behind NAT, defaults to disabled and only applies to AYIYA"))
nat.optional = true
nat.default = disabled
verbose = section:taboption("advanced", Flag, "verbose",
translate("Verbose"),
translate("Verbose logging by aiccu daemon"))
verbose.optional = true
verbose.default = disabled
ntpsynctimeout = section:taboption("advanced", Value, "ntpsynctimeout",
translate("NTP sync time-out"),
translate("Wait for NTP sync that many seconds, seting to 0 disables waiting (optional)"))
ntpsynctimeout.datatype = "uinteger"
ntpsynctimeout.placeholder = "90"
ntpsynctimeout.optional = true
ip6addr = section:taboption("advanced", Value, "ip6addr",
translate("Local IPv6 address"),
translate("IPv6 address delegated to the local tunnel endpoint (optional)"))
ip6addr.datatype = "ip6addr"
ip6addr.optional = true
defaultroute = section:taboption("advanced", Flag, "defaultroute",
translate("Default route"),
translate("Whether to create an IPv6 default route over the tunnel"))
defaultroute.default = defaultroute.enabled
defaultroute.optional = true
sourcerouting = section:taboption("advanced", Flag, "sourcerouting",
translate("Source routing"),
translate("Whether to route only packets from delegated prefixes"))
sourcerouting.default = sourcerouting.enabled
sourcerouting.optional = true
metric = section:taboption("advanced", Value, "metric",
translate("Use gateway metric"))
metric.datatype = "uinteger"
metric.placeholder = "0"
metric:depends("defaultroute", defaultroute.enabled)
ttl = section:taboption("advanced", Value, "ttl",
translate("Use TTL on tunnel interface"))
ttl.datatype = "range(1,255)"
ttl.placeholder = "64"
mtu = section:taboption("advanced", Value, "mtu",
translate("Use MTU on tunnel interface"))
translate("minimum 1280, maximum 1480"))
mtu.datatype = "range(1280,1480)"
mtu.placeholder = "1280"
|
-- Copyright 2015 Paul Oranje <por@xs4all.nl>
-- Licensed to the public under the Apache License 2.0.
local map, section, net = ...
-- config read by /lib/netifd/proto/aiccu.sh
local username, password, protocol, server, tunnelid, ip6prefix, requiretls, nat, heartbeat,
verbose, ntpsynctimeout, ip6addr, sourcerouting, defaultroute
-- generic parameters
local metric, ttl, mtu
username = section:taboption("general", Value, "username",
translate("Server username"),
translate("SIXXS-handle[/Tunnel-ID]"))
username.datatype = "string"
password = section:taboption("general", Value, "password",
translate("Server password"),
translate("Server password, enter the specific password of the tunnel when the username contains the tunnel ID"))
password.datatype = "string"
password.password = true
--[[ SIXXS supports only TIC as tunnel broker protocol, no use setting it.
protocol = section:taboption("general", ListValue, "protocol",
translate("Tunnel broker protocol"),
translate("SIXXS supports TIC only, for static tunnels using IP protocol 41 (RFC4213) use 6in4 instead"))
protocol:value("tic", "TIC")
protocol:value("tsp", "TSP")
protocol:value("l2tp", "L2TP")
protocol.default = "tic"
protocol.optional = true
--]]
server = section:taboption("general", Value, "server",
translate("Tunnel setup server"),
translate("Optional, specify to override default server (tic.sixxs.net)"))
server.datatype = "host"
server.optional = true
tunnelid = section:taboption("general", Value, "tunnelid",
translate("Tunnel ID"),
translate("Optional, use when the SIXXS account has more than one tunnel"))
tunnelid.datatype = "string"
tunnelid.optional = true
local ip6prefix = section:taboption("general", Value, "ip6prefix",
translate("IPv6 prefix"),
translate("Routed IPv6 prefix for downstream interfaces"))
ip6prefix.datatype = "ip6prefix"
ip6prefix.optional = true
heartbeat = s:taboption("general", ListValue, "heartbeat",
translate("Tunnel type"),
translate("Also see <a href=\"https://www.sixxs.net/faq/connectivity/?faq=comparison\">Tunneling Comparison</a> on SIXXS"))
heartbeat:value("0", translate("AYIYA"))
heartbeat:value("1", translate("Heartbeat"))
heartbeat.default = "0"
nat = section:taboption("general", Flag, "nat",
translate("Behind NAT"),
translate("The tunnel end-point is behind NAT, defaults to disabled and only applies to AYIYA"))
nat.optional = true
nat.default = disabled
requiretls = section:taboption("general", Flag, "requiretls",
translate("Require TLS"),
translate("Connection to server fails when TLS cannot be used"))
requiretls.optional = true
requiretls.default = requiretls.enabled
verbose = section:taboption("advanced", Flag, "verbose",
translate("Verbose"),
translate("Verbose logging by aiccu daemon"))
verbose.optional = true
verbose.default = disabled
ntpsynctimeout = section:taboption("advanced", Value, "ntpsynctimeout",
translate("NTP sync time-out"),
translate("Wait for NTP sync that many seconds, seting to 0 disables waiting (optional)"))
ntpsynctimeout.datatype = "uinteger"
ntpsynctimeout.placeholder = "90"
ntpsynctimeout.optional = true
ip6addr = section:taboption("advanced", Value, "ip6addr",
translate("Local IPv6 address"),
translate("IPv6 address delegated to the local tunnel endpoint (optional)"))
ip6addr.datatype = "ip6addr"
ip6addr.optional = true
defaultroute = section:taboption("advanced", Flag, "defaultroute",
translate("Default route"),
translate("Whether to create an IPv6 default route over the tunnel"))
defaultroute.default = defaultroute.enabled
defaultroute.optional = true
sourcerouting = section:taboption("advanced", Flag, "sourcerouting",
translate("Source routing"),
translate("Whether to route only packets from delegated prefixes"))
sourcerouting.default = sourcerouting.enabled
sourcerouting.optional = true
metric = section:taboption("advanced", Value, "metric",
translate("Use gateway metric"))
metric.datatype = "uinteger"
metric.placeholder = "0"
metric:depends("defaultroute", defaultroute.enabled)
ttl = section:taboption("advanced", Value, "ttl",
translate("Use TTL on tunnel interface"))
ttl.datatype = "range(1,255)"
ttl.placeholder = "64"
mtu = section:taboption("advanced", Value, "mtu",
translate("Use MTU on tunnel interface"),
translate("minimum 1280, maximum 1480"))
mtu.datatype = "range(1280,1480)"
mtu.placeholder = "1280"
|
luci-proto-ipv6: aiccu improvements
|
luci-proto-ipv6: aiccu improvements
- option heartbeat as tunnel type (heartbeat or AYIYA) (inspired by
idea of openwrt forum user thefRont)
- another typo fix in the mtu option
|
Lua
|
apache-2.0
|
thesabbir/luci,Noltari/luci,wongsyrone/luci-1,joaofvieira/luci,kuoruan/lede-luci,remakeelectric/luci,bittorf/luci,Hostle/luci,lcf258/openwrtcn,RuiChen1113/luci,rogerpueyo/luci,jchuang1977/luci-1,oyido/luci,LuttyYang/luci,schidler/ionic-luci,cshore/luci,deepak78/new-luci,hnyman/luci,david-xiao/luci,lcf258/openwrtcn,Noltari/luci,981213/luci-1,981213/luci-1,lbthomsen/openwrt-luci,zhaoxx063/luci,bittorf/luci,shangjiyu/luci-with-extra,marcel-sch/luci,openwrt/luci,RuiChen1113/luci,bright-things/ionic-luci,cappiewu/luci,bright-things/ionic-luci,slayerrensky/luci,fkooman/luci,maxrio/luci981213,ollie27/openwrt_luci,tcatm/luci,schidler/ionic-luci,thess/OpenWrt-luci,ollie27/openwrt_luci,thess/OpenWrt-luci,ReclaimYourPrivacy/cloak-luci,florian-shellfire/luci,Hostle/openwrt-luci-multi-user,openwrt/luci,shangjiyu/luci-with-extra,ff94315/luci-1,bright-things/ionic-luci,oneru/luci,mumuqz/luci,maxrio/luci981213,joaofvieira/luci,slayerrensky/luci,Noltari/luci,urueedi/luci,urueedi/luci,NeoRaider/luci,male-puppies/luci,LuttyYang/luci,bright-things/ionic-luci,oneru/luci,db260179/openwrt-bpi-r1-luci,forward619/luci,cappiewu/luci,tcatm/luci,kuoruan/lede-luci,aa65535/luci,bittorf/luci,deepak78/new-luci,florian-shellfire/luci,remakeelectric/luci,teslamint/luci,mumuqz/luci,forward619/luci,lbthomsen/openwrt-luci,aa65535/luci,kuoruan/luci,lcf258/openwrtcn,obsy/luci,openwrt-es/openwrt-luci,zhaoxx063/luci,remakeelectric/luci,NeoRaider/luci,cappiewu/luci,remakeelectric/luci,ff94315/luci-1,thesabbir/luci,sujeet14108/luci,tobiaswaldvogel/luci,LuttyYang/luci,wongsyrone/luci-1,teslamint/luci,jorgifumi/luci,cappiewu/luci,kuoruan/luci,ReclaimYourPrivacy/cloak-luci,NeoRaider/luci,LazyZhu/openwrt-luci-trunk-mod,ff94315/luci-1,MinFu/luci,RuiChen1113/luci,oneru/luci,Noltari/luci,dwmw2/luci,bright-things/ionic-luci,jlopenwrtluci/luci,kuoruan/luci,nmav/luci,shangjiyu/luci-with-extra,981213/luci-1,tcatm/luci,LazyZhu/openwrt-luci-trunk-mod,male-puppies/luci,urueedi/luci,taiha/luci,jlopenwrtluci/luci,jorgifumi/luci,oneru/luci,RedSnake64/openwrt-luci-packages,lbthomsen/openwrt-luci,marcel-sch/luci,cshore-firmware/openwrt-luci,zhaoxx063/luci,zhaoxx063/luci,jlopenwrtluci/luci,NeoRaider/luci,deepak78/new-luci,remakeelectric/luci,florian-shellfire/luci,kuoruan/luci,LazyZhu/openwrt-luci-trunk-mod,obsy/luci,obsy/luci,hnyman/luci,slayerrensky/luci,nmav/luci,remakeelectric/luci,artynet/luci,taiha/luci,artynet/luci,remakeelectric/luci,joaofvieira/luci,jlopenwrtluci/luci,Hostle/openwrt-luci-multi-user,schidler/ionic-luci,slayerrensky/luci,marcel-sch/luci,wongsyrone/luci-1,shangjiyu/luci-with-extra,daofeng2015/luci,dwmw2/luci,maxrio/luci981213,fkooman/luci,ff94315/luci-1,LuttyYang/luci,lbthomsen/openwrt-luci,thess/OpenWrt-luci,kuoruan/lede-luci,deepak78/new-luci,oneru/luci,jlopenwrtluci/luci,LazyZhu/openwrt-luci-trunk-mod,tobiaswaldvogel/luci,db260179/openwrt-bpi-r1-luci,maxrio/luci981213,bittorf/luci,chris5560/openwrt-luci,jchuang1977/luci-1,shangjiyu/luci-with-extra,rogerpueyo/luci,dwmw2/luci,Noltari/luci,aa65535/luci,chris5560/openwrt-luci,deepak78/new-luci,schidler/ionic-luci,ReclaimYourPrivacy/cloak-luci,cshore-firmware/openwrt-luci,nwf/openwrt-luci,tcatm/luci,db260179/openwrt-bpi-r1-luci,Hostle/openwrt-luci-multi-user,bittorf/luci,wongsyrone/luci-1,MinFu/luci,openwrt/luci,david-xiao/luci,MinFu/luci,lcf258/openwrtcn,nwf/openwrt-luci,obsy/luci,db260179/openwrt-bpi-r1-luci,taiha/luci,jorgifumi/luci,wongsyrone/luci-1,openwrt/luci,jorgifumi/luci,openwrt-es/openwrt-luci,shangjiyu/luci-with-extra,mumuqz/luci,daofeng2015/luci,RuiChen1113/luci,deepak78/new-luci,oneru/luci,forward619/luci,aa65535/luci,aa65535/luci,ff94315/luci-1,jchuang1977/luci-1,kuoruan/lede-luci,cshore-firmware/openwrt-luci,bittorf/luci,db260179/openwrt-bpi-r1-luci,Hostle/luci,lbthomsen/openwrt-luci,cshore/luci,thesabbir/luci,hnyman/luci,rogerpueyo/luci,jorgifumi/luci,bright-things/ionic-luci,lcf258/openwrtcn,mumuqz/luci,nwf/openwrt-luci,Sakura-Winkey/LuCI,shangjiyu/luci-with-extra,bright-things/ionic-luci,oyido/luci,oyido/luci,daofeng2015/luci,sujeet14108/luci,RedSnake64/openwrt-luci-packages,nmav/luci,RedSnake64/openwrt-luci-packages,artynet/luci,981213/luci-1,forward619/luci,LuttyYang/luci,thess/OpenWrt-luci,obsy/luci,RedSnake64/openwrt-luci-packages,teslamint/luci,Wedmer/luci,male-puppies/luci,oyido/luci,urueedi/luci,openwrt-es/openwrt-luci,wongsyrone/luci-1,oyido/luci,tobiaswaldvogel/luci,cshore-firmware/openwrt-luci,RedSnake64/openwrt-luci-packages,bittorf/luci,sujeet14108/luci,male-puppies/luci,Wedmer/luci,Hostle/luci,Noltari/luci,Hostle/luci,zhaoxx063/luci,Hostle/openwrt-luci-multi-user,rogerpueyo/luci,ollie27/openwrt_luci,joaofvieira/luci,david-xiao/luci,taiha/luci,kuoruan/luci,mumuqz/luci,openwrt-es/openwrt-luci,ReclaimYourPrivacy/cloak-luci,openwrt-es/openwrt-luci,sujeet14108/luci,ollie27/openwrt_luci,jorgifumi/luci,cappiewu/luci,cshore/luci,fkooman/luci,RuiChen1113/luci,forward619/luci,jorgifumi/luci,thesabbir/luci,male-puppies/luci,thesabbir/luci,artynet/luci,urueedi/luci,joaofvieira/luci,urueedi/luci,ReclaimYourPrivacy/cloak-luci,jlopenwrtluci/luci,david-xiao/luci,jchuang1977/luci-1,rogerpueyo/luci,male-puppies/luci,aa65535/luci,lbthomsen/openwrt-luci,rogerpueyo/luci,thesabbir/luci,oyido/luci,florian-shellfire/luci,maxrio/luci981213,chris5560/openwrt-luci,lcf258/openwrtcn,Hostle/openwrt-luci-multi-user,thesabbir/luci,taiha/luci,wongsyrone/luci-1,thesabbir/luci,LazyZhu/openwrt-luci-trunk-mod,hnyman/luci,florian-shellfire/luci,RedSnake64/openwrt-luci-packages,mumuqz/luci,sujeet14108/luci,cshore/luci,RuiChen1113/luci,zhaoxx063/luci,openwrt-es/openwrt-luci,nwf/openwrt-luci,schidler/ionic-luci,artynet/luci,fkooman/luci,Wedmer/luci,MinFu/luci,sujeet14108/luci,cshore/luci,daofeng2015/luci,ff94315/luci-1,oneru/luci,teslamint/luci,artynet/luci,ollie27/openwrt_luci,Noltari/luci,ff94315/luci-1,obsy/luci,slayerrensky/luci,maxrio/luci981213,artynet/luci,tobiaswaldvogel/luci,teslamint/luci,cappiewu/luci,bittorf/luci,kuoruan/lede-luci,Wedmer/luci,joaofvieira/luci,david-xiao/luci,db260179/openwrt-bpi-r1-luci,openwrt-es/openwrt-luci,obsy/luci,deepak78/new-luci,bright-things/ionic-luci,fkooman/luci,kuoruan/lede-luci,teslamint/luci,marcel-sch/luci,david-xiao/luci,florian-shellfire/luci,kuoruan/luci,tcatm/luci,tcatm/luci,Hostle/openwrt-luci-multi-user,openwrt/luci,slayerrensky/luci,981213/luci-1,ReclaimYourPrivacy/cloak-luci,forward619/luci,thess/OpenWrt-luci,aa65535/luci,tobiaswaldvogel/luci,RuiChen1113/luci,ff94315/luci-1,mumuqz/luci,Wedmer/luci,Wedmer/luci,981213/luci-1,joaofvieira/luci,ollie27/openwrt_luci,Sakura-Winkey/LuCI,deepak78/new-luci,LuttyYang/luci,tcatm/luci,joaofvieira/luci,male-puppies/luci,schidler/ionic-luci,david-xiao/luci,mumuqz/luci,Sakura-Winkey/LuCI,wongsyrone/luci-1,MinFu/luci,oneru/luci,nmav/luci,nmav/luci,cshore-firmware/openwrt-luci,Noltari/luci,Hostle/luci,florian-shellfire/luci,openwrt/luci,daofeng2015/luci,dwmw2/luci,tobiaswaldvogel/luci,rogerpueyo/luci,LuttyYang/luci,slayerrensky/luci,lbthomsen/openwrt-luci,jchuang1977/luci-1,MinFu/luci,taiha/luci,florian-shellfire/luci,Sakura-Winkey/LuCI,jchuang1977/luci-1,Wedmer/luci,marcel-sch/luci,jchuang1977/luci-1,cappiewu/luci,kuoruan/luci,nwf/openwrt-luci,ReclaimYourPrivacy/cloak-luci,taiha/luci,Hostle/openwrt-luci-multi-user,hnyman/luci,thess/OpenWrt-luci,nwf/openwrt-luci,openwrt-es/openwrt-luci,openwrt/luci,maxrio/luci981213,aa65535/luci,Sakura-Winkey/LuCI,forward619/luci,cappiewu/luci,oyido/luci,LuttyYang/luci,lcf258/openwrtcn,artynet/luci,dwmw2/luci,hnyman/luci,thess/OpenWrt-luci,db260179/openwrt-bpi-r1-luci,chris5560/openwrt-luci,LazyZhu/openwrt-luci-trunk-mod,lcf258/openwrtcn,rogerpueyo/luci,fkooman/luci,tobiaswaldvogel/luci,male-puppies/luci,NeoRaider/luci,MinFu/luci,kuoruan/luci,dwmw2/luci,nmav/luci,maxrio/luci981213,LazyZhu/openwrt-luci-trunk-mod,artynet/luci,chris5560/openwrt-luci,dwmw2/luci,Noltari/luci,lcf258/openwrtcn,daofeng2015/luci,marcel-sch/luci,schidler/ionic-luci,thess/OpenWrt-luci,NeoRaider/luci,RedSnake64/openwrt-luci-packages,fkooman/luci,nmav/luci,lcf258/openwrtcn,dwmw2/luci,Hostle/luci,teslamint/luci,hnyman/luci,openwrt/luci,cshore/luci,kuoruan/lede-luci,cshore/luci,Wedmer/luci,tobiaswaldvogel/luci,nmav/luci,chris5560/openwrt-luci,NeoRaider/luci,cshore/luci,cshore-firmware/openwrt-luci,nwf/openwrt-luci,jorgifumi/luci,jlopenwrtluci/luci,db260179/openwrt-bpi-r1-luci,Hostle/luci,obsy/luci,sujeet14108/luci,Sakura-Winkey/LuCI,LazyZhu/openwrt-luci-trunk-mod,RuiChen1113/luci,jchuang1977/luci-1,taiha/luci,ReclaimYourPrivacy/cloak-luci,MinFu/luci,fkooman/luci,teslamint/luci,daofeng2015/luci,zhaoxx063/luci,urueedi/luci,cshore-firmware/openwrt-luci,cshore-firmware/openwrt-luci,sujeet14108/luci,ollie27/openwrt_luci,nwf/openwrt-luci,schidler/ionic-luci,remakeelectric/luci,nmav/luci,chris5560/openwrt-luci,urueedi/luci,Hostle/openwrt-luci-multi-user,marcel-sch/luci,jlopenwrtluci/luci,hnyman/luci,tcatm/luci,lbthomsen/openwrt-luci,david-xiao/luci,Sakura-Winkey/LuCI,kuoruan/lede-luci,Hostle/luci,chris5560/openwrt-luci,oyido/luci,981213/luci-1,slayerrensky/luci,zhaoxx063/luci,forward619/luci,daofeng2015/luci,NeoRaider/luci,shangjiyu/luci-with-extra,ollie27/openwrt_luci,Sakura-Winkey/LuCI,marcel-sch/luci
|
a7d7898e253b72555d06add2dfd1e5ac0edb059b
|
game/scripts/vscripts/heroes/hero_doppelganger/mimic.lua
|
game/scripts/vscripts/heroes/hero_doppelganger/mimic.lua
|
LinkLuaModifier("modifier_doppelganger_mimic", "heroes/hero_doppelganger/mimic.lua", LUA_MODIFIER_MOTION_NONE)
if IsServer() then
function GenerateAbilityCooldownCache(caster)
local cache = caster.abilityCooldownCache or {}
for i = 0, caster:GetAbilityCount() - 1 do
local ability = caster:GetAbilityByIndex(i)
if ability then
local remainingCooldown = ability:GetCooldownTimeRemaining()
if remainingCooldown > 0 then
cache[ability:GetAbilityName()] = GameRules:GetGameTime() + remainingCooldown
end
end
end
return cache
end
function ApplyAbilityCooldownsFromCache(caster, cache)
caster.abilityCooldownCache = cache or {}
for i = 0, caster:GetAbilityCount() - 1 do
local ability = caster:GetAbilityByIndex(i)
if ability then
local abilityname = ability:GetAbilityName()
if cache[abilityname] then
local remainingCooldown = cache[abilityname] - GameRules:GetGameTime()
if remainingCooldown > 0 then
ability:StartCooldown(remainingCooldown)
end
cache[abilityname] = nil
end
end
end
end
function ChangeHero(caster, targetName, callback)
if caster.ChangingHeroProcessRunning then return end
-- Save hero's state to give same state to new hero
local state = {
health = caster:GetHealth() / caster:GetMaxHealth(),
mana = caster:GetMana() / caster:GetMaxMana(),
Additional_str = caster.Additional_str,
Additional_agi = caster.Additional_agi,
Additional_int = caster.Additional_int,
Additional_attackspeed = caster.Additional_attackspeed,
abilityCooldownCache = GenerateAbilityCooldownCache(caster)
}
return HeroSelection:ChangeHero(caster:GetPlayerID(), targetName, true, nil, nil, function(newHero)
ApplyAbilityCooldownsFromCache(newHero, state.abilityCooldownCache)
if state.Additional_str then
newHero.Additional_str = state.Additional_str
newHero:ModifyStrength(state.Additional_str)
end
if state.Additional_agi then
newHero.Additional_agi = state.Additional_agi
newHero:ModifyAgility(state.Additional_agi)
end
if state.Additional_int then
newHero.Additional_int = state.Additional_int
newHero:ModifyIntellect(state.Additional_int)
end
if state.Additional_attackspeed then
newHero.Additional_attackspeed = state.Additional_attackspeed
if not newHero:HasModifier("modifier_item_shard_attackspeed_stack") then
newHero:AddNewModifier(caster, nil, "modifier_item_shard_attackspeed_stack", {})
end
newHero:SetModifierStackCount("modifier_item_shard_attackspeed_stack", newHero, state.Additional_attackspeed)
end
newHero:SetHealth(state.health * newHero:GetMaxHealth())
newHero:SetMana(state.mana * newHero:GetMaxMana())
if callback then
callback(newHero)
end
end, false)
end
end
doppelganger_mimic = class({})
if IsServer() then
function doppelganger_mimic:Spawn()
self:SetLevel(1)
end
function doppelganger_mimic:OnUpgrade()
if not self.bannedHeroes then
self.bannedHeroes = self:GetKeyValue("BannedHeroes") or {}
end
end
function doppelganger_mimic:CastFilterResultTarget(hTarget)
return (hTarget == self:GetCaster() or hTarget:IsBoss() or self.bannedHeroes[hTarget:GetFullName()]) and UF_FAIL_CUSTOM or UF_SUCCESS
end
function doppelganger_mimic:GetCustomCastErrorTarget(hTarget)
return (hTarget == self:GetCaster() and "#dota_hud_error_cant_cast_on_self") or
(hTarget:IsBoss() and "#dota_hud_error_ability_cant_target_boss") or
(self.bannedHeroes[hTarget:GetFullName()] and "#arena_hud_error_cant_mimic") or
""
end
function doppelganger_mimic:OnSpellStart()
local caster = self:GetCaster()
local target = self:GetCursorTarget()
self.new_steal_target = target
caster:EmitSound("Hero_Rubick.SpellSteal.Cast")
target:EmitSound("Hero_Rubick.SpellSteal.Target")
ProjectileManager:CreateTrackingProjectile({
Target = caster,
Source = target,
Ability = self,
EffectName = "particles/arena/units/heroes/hero_doppelganger/mimic.vpcf",
bDodgeable = false,
bProvidesVision = false,
iMoveSpeed = self:GetSpecialValueFor("projectile_speed"),
iSourceAttachment = DOTA_PROJECTILE_ATTACHMENT_HITLOCATION
})
end
function doppelganger_mimic:OnProjectileHit(hTarget, vLocation)
local caster = self:GetCaster()
local target = self.new_steal_target
if IsValidEntity(target) then
caster:EmitSound("Hero_Rubick.SpellSteal.Complete")
ChangeHero(caster, target:GetFullName(), function(newHero)
newHero:AddNewModifier(newHero, self, "modifier_doppelganger_mimic", nil)
if not newHero:HasModifier("modifier_doppelganger_mimic") then
HeroSelection:ChangeHero(newHero:GetPlayerID(), "npc_arena_hero_doppelganger", true, 0)
end
end)
end
end
end
modifier_doppelganger_mimic = class({
IsHidden = function() return true end,
IsPurgable = function() return false end,
RemoveOnDeath = function() return false end,
GetAttributes = function() return MODIFIER_ATTRIBUTE_PERMANENT end,
GetTexture = function() return "doppelganger_mimic" end,
GetEffectName = function() return "particles/units/heroes/hero_arc_warden/arc_warden_tempest_buff.vpcf" end,
GetStatusEffectName = function() return "particles/status_fx/status_effect_arc_warden_tempest.vpcf" end,
})
if IsServer() then
function modifier_doppelganger_mimic:DeclareFunctions()
return {MODIFIER_EVENT_ON_RESPAWN}
end
function modifier_doppelganger_mimic:OnDestroy()
local parent = self:GetParent()
if not ChangeHero(parent, "npc_arena_hero_doppelganger") then
-- Can't change hero now
Timers:NextTick(function()
parent:AddNewModifier(parent, self, "modifier_doppelganger_mimic", nil)
end)
end
end
end
|
LinkLuaModifier("modifier_doppelganger_mimic", "heroes/hero_doppelganger/mimic.lua", LUA_MODIFIER_MOTION_NONE)
if IsServer() then
function GenerateAbilityCooldownCache(caster)
local cache = caster.abilityCooldownCache or {}
for i = 0, caster:GetAbilityCount() - 1 do
local ability = caster:GetAbilityByIndex(i)
if ability then
local remainingCooldown = ability:GetCooldownTimeRemaining()
if remainingCooldown > 0 then
cache[ability:GetAbilityName()] = GameRules:GetGameTime() + remainingCooldown
end
end
end
return cache
end
function ApplyAbilityCooldownsFromCache(caster, cache)
caster.abilityCooldownCache = cache or {}
for i = 0, caster:GetAbilityCount() - 1 do
local ability = caster:GetAbilityByIndex(i)
if ability then
local abilityname = ability:GetAbilityName()
if cache[abilityname] then
local remainingCooldown = cache[abilityname] - GameRules:GetGameTime()
if remainingCooldown > 0 then
ability:StartCooldown(remainingCooldown)
end
cache[abilityname] = nil
end
end
end
end
function ChangeHero(caster, targetName, callback)
if caster.ChangingHeroProcessRunning then return end
-- Save hero's state to give same state to new hero
local state = {
health = caster:GetHealth() / caster:GetMaxHealth(),
mana = caster:GetMana() / caster:GetMaxMana(),
Additional_str = caster.Additional_str,
Additional_agi = caster.Additional_agi,
Additional_int = caster.Additional_int,
Additional_attackspeed = caster.Additional_attackspeed,
abilityCooldownCache = GenerateAbilityCooldownCache(caster)
}
return HeroSelection:ChangeHero(caster:GetPlayerID(), targetName, true, nil, nil, function(newHero)
ApplyAbilityCooldownsFromCache(newHero, state.abilityCooldownCache)
if state.Additional_str then
newHero.Additional_str = state.Additional_str
newHero:ModifyStrength(state.Additional_str)
end
if state.Additional_agi then
newHero.Additional_agi = state.Additional_agi
newHero:ModifyAgility(state.Additional_agi)
end
if state.Additional_int then
newHero.Additional_int = state.Additional_int
newHero:ModifyIntellect(state.Additional_int)
end
if state.Additional_attackspeed then
newHero.Additional_attackspeed = state.Additional_attackspeed
if not newHero:HasModifier("modifier_item_shard_attackspeed_stack") then
newHero:AddNewModifier(caster, nil, "modifier_item_shard_attackspeed_stack", {})
end
newHero:SetModifierStackCount("modifier_item_shard_attackspeed_stack", newHero, state.Additional_attackspeed)
end
newHero:SetHealth(state.health * newHero:GetMaxHealth())
newHero:SetMana(state.mana * newHero:GetMaxMana())
if callback then
callback(newHero)
end
end, false)
end
end
doppelganger_mimic = class({})
if IsServer() then
function doppelganger_mimic:Spawn()
self:SetLevel(1)
end
function doppelganger_mimic:OnUpgrade()
if not self.bannedHeroes then
self.bannedHeroes = self:GetKeyValue("BannedHeroes") or {}
end
end
function doppelganger_mimic:CastFilterResultTarget(hTarget)
return (hTarget == self:GetCaster() or hTarget:IsBoss() or self.bannedHeroes[hTarget:GetFullName()] or hTarget:IsIllusion()) and UF_FAIL_CUSTOM or UF_SUCCESS
end
function doppelganger_mimic:GetCustomCastErrorTarget(hTarget)
return (hTarget == self:GetCaster() and "#dota_hud_error_cant_cast_on_self") or
(hTarget:IsBoss() and "#dota_hud_error_ability_cant_target_boss") or
(self.bannedHeroes[hTarget:GetFullName()] and "#arena_hud_error_cant_mimic") or
(hTarget:IsIllusion() and "#dota_hud_error_cant_cast_on_illusions") or
""
end
function doppelganger_mimic:OnSpellStart()
local caster = self:GetCaster()
local target = self:GetCursorTarget()
self.new_steal_target = target
caster:EmitSound("Hero_Rubick.SpellSteal.Cast")
target:EmitSound("Hero_Rubick.SpellSteal.Target")
ProjectileManager:CreateTrackingProjectile({
Target = caster,
Source = target,
Ability = self,
EffectName = "particles/arena/units/heroes/hero_doppelganger/mimic.vpcf",
bDodgeable = false,
bProvidesVision = false,
iMoveSpeed = self:GetSpecialValueFor("projectile_speed"),
iSourceAttachment = DOTA_PROJECTILE_ATTACHMENT_HITLOCATION
})
end
function doppelganger_mimic:OnProjectileHit(hTarget, vLocation)
local caster = self:GetCaster()
local target = self.new_steal_target
if IsValidEntity(target) then
caster:EmitSound("Hero_Rubick.SpellSteal.Complete")
ChangeHero(caster, target:GetFullName(), function(newHero)
newHero:AddNewModifier(newHero, self, "modifier_doppelganger_mimic", nil)
if not newHero:HasModifier("modifier_doppelganger_mimic") then
HeroSelection:ChangeHero(newHero:GetPlayerID(), "npc_arena_hero_doppelganger", true, 0)
end
end)
end
end
end
modifier_doppelganger_mimic = class({
IsHidden = function() return true end,
IsPurgable = function() return false end,
RemoveOnDeath = function() return false end,
GetAttributes = function() return MODIFIER_ATTRIBUTE_PERMANENT end,
GetTexture = function() return "doppelganger_mimic" end,
GetEffectName = function() return "particles/units/heroes/hero_arc_warden/arc_warden_tempest_buff.vpcf" end,
GetStatusEffectName = function() return "particles/status_fx/status_effect_arc_warden_tempest.vpcf" end,
})
if IsServer() then
function modifier_doppelganger_mimic:DeclareFunctions()
return {MODIFIER_EVENT_ON_RESPAWN}
end
function modifier_doppelganger_mimic:OnDestroy()
local parent = self:GetParent()
if not ChangeHero(parent, "npc_arena_hero_doppelganger") then
-- Can't change hero now
Timers:NextTick(function()
parent:AddNewModifier(parent, self, "modifier_doppelganger_mimic", nil)
end)
end
end
end
|
fix(doppelganger): mimic can copy illusions
|
fix(doppelganger): mimic can copy illusions
|
Lua
|
mit
|
ark120202/aabs
|
cfa0a70ad2bb9f64028abc0ac79129d7db94a1ee
|
lua/json/decode/calls.lua
|
lua/json/decode/calls.lua
|
--[[
Licensed according to the included 'LICENSE' document
Author: Thomas Harning Jr <harningt@gmail.com>
]]
local lpeg = require("lpeg")
local tostring = tostring
local pairs, ipairs = pairs, ipairs
local next, type = next, type
local error = error
local util = require("json.decode.util")
local buildCall = require("json.util").buildCall
local getmetatable = getmetatable
module("json.decode.calls")
local defaultOptions = {
defs = nil,
-- By default, do not allow undefined calls to be de-serialized as call objects
allowUndefined = false
}
-- No real default-option handling needed...
default = nil
strict = nil
local isPattern
if lpeg.type then
function isPattern(value)
return lpeg.type(value) == 'pattern'
end
else
local metaAdd = getmetatable(lpeg.P("")).__add
function isPattern(value)
return getmetatable(value).__add == metaAdd
end
end
local function buildDefinedCaptures(argumentCapture, defs)
local callCapture
if not defs then return end
for name, func in pairs(defs) do
if type(name) ~= 'string' and not isPattern(name) then
error("Invalid functionCalls name: " .. tostring(name) .. " not a string or LPEG pattern")
end
-- Allow boolean or function to match up w/ encoding permissions
if type(func) ~= 'boolean' and type(func) ~= 'function' then
error("Invalid functionCalls item: " .. name .. " not a function")
end
local nameCallCapture
if type(name) == 'string' then
nameCallCapture = lpeg.P(name .. "(") * lpeg.Cc(name)
else
-- Name matcher expected to produce a capture
nameCallCapture = name * "("
end
-- Call func over nameCallCapture and value to permit function receiving name
-- Process 'func' if it is not a function
if type(func) == 'boolean' then
local allowed = func
func = function(name, ...)
if not allowed then
error("Function call on '" .. name .. "' not permitted")
end
return buildCall(name, ...)
end
end
local newCapture = (nameCallCapture * argumentCapture) / func * ")"
if not callCapture then
callCapture = newCapture
else
callCapture = callCapture + newCapture
end
end
return callCapture
end
local function buildCapture(options)
if not options -- No ops, don't bother to parse
or not (options.defs and (nil ~= next(options.defs)) or options.allowUndefined) then
return nil
end
-- Allow zero or more arguments separated by commas
local value = lpeg.V(util.types.VALUE)
local argumentCapture = (value * (lpeg.P(",") * value)^0) + 0
local callCapture = buildDefinedCaptures(argumentCapture, options.defs)
if options.allowUndefined then
local function func(name, ...)
return buildCall(name, ...)
end
-- Identifier-type-match
local nameCallCapture = lpeg.C(util.identifier) * "("
local newCapture = (nameCallCapture * argumentCapture) / func * ")"
if not callCapture then
callCapture = newCapture
else
callCapture = callCapture + newCapture
end
end
return callCapture
end
function load_types(options, global_options, grammar)
local capture = buildCapture(options, global_options)
if capture then
util.append_grammar_item(grammar, "VALUE", capture)
end
end
|
--[[
Licensed according to the included 'LICENSE' document
Author: Thomas Harning Jr <harningt@gmail.com>
]]
local lpeg = require("lpeg")
local tostring = tostring
local pairs, ipairs = pairs, ipairs
local next, type = next, type
local error = error
local util = require("json.decode.util")
local buildCall = require("json.util").buildCall
local getmetatable = getmetatable
module("json.decode.calls")
local defaultOptions = {
defs = nil,
-- By default, do not allow undefined calls to be de-serialized as call objects
allowUndefined = false
}
-- No real default-option handling needed...
default = nil
strict = nil
local isPattern
if lpeg.type then
function isPattern(value)
return lpeg.type(value) == 'pattern'
end
else
local metaAdd = getmetatable(lpeg.P("")).__add
function isPattern(value)
return getmetatable(value).__add == metaAdd
end
end
local function buildDefinedCaptures(argumentCapture, defs)
local callCapture
if not defs then return end
for name, func in pairs(defs) do
if type(name) ~= 'string' and not isPattern(name) then
error("Invalid functionCalls name: " .. tostring(name) .. " not a string or LPEG pattern")
end
-- Allow boolean or function to match up w/ encoding permissions
if type(func) ~= 'boolean' and type(func) ~= 'function' then
error("Invalid functionCalls item: " .. name .. " not a function")
end
local nameCallCapture
if type(name) == 'string' then
nameCallCapture = lpeg.P(name .. "(") * lpeg.Cc(name)
else
-- Name matcher expected to produce a capture
nameCallCapture = name * "("
end
-- Call func over nameCallCapture and value to permit function receiving name
-- Process 'func' if it is not a function
if type(func) == 'boolean' then
local allowed = func
func = function(name, ...)
if not allowed then
error("Function call on '" .. name .. "' not permitted")
end
return buildCall(name, ...)
end
else
local inner_func = func
func = function(...)
return (inner_func(...))
end
end
local newCapture = (nameCallCapture * argumentCapture) / func * ")"
if not callCapture then
callCapture = newCapture
else
callCapture = callCapture + newCapture
end
end
return callCapture
end
local function buildCapture(options)
if not options -- No ops, don't bother to parse
or not (options.defs and (nil ~= next(options.defs)) or options.allowUndefined) then
return nil
end
-- Allow zero or more arguments separated by commas
local value = lpeg.V(util.types.VALUE)
local argumentCapture = (value * (lpeg.P(",") * value)^0) + 0
local callCapture = buildDefinedCaptures(argumentCapture, options.defs)
if options.allowUndefined then
local function func(name, ...)
return buildCall(name, ...)
end
-- Identifier-type-match
local nameCallCapture = lpeg.C(util.identifier) * "("
local newCapture = (nameCallCapture * argumentCapture) / func * ")"
if not callCapture then
callCapture = newCapture
else
callCapture = callCapture + newCapture
end
end
return callCapture
end
function load_types(options, global_options, grammar)
local capture = buildCapture(options, global_options)
if capture then
util.append_grammar_item(grammar, "VALUE", capture)
end
end
|
decoder: fixes bug where function call returns nothing => error
|
decoder: fixes bug where function call returns nothing => error
Uncovered by fix permitting nil return value.
All 'calls' are wrapped such that they always return a single value (as expected)
|
Lua
|
mit
|
renchunxiao/luajson
|
c48aa7c083a1fb2584c931e54020656df8922174
|
heka/sandbox/filters/firefox_monthly_dashboard.lua
|
heka/sandbox/filters/firefox_monthly_dashboard.lua
|
-- This Source Code Form is subject to the terms of the Mozilla Public
-- License, v. 2.0. If a copy of the MPL was not distributed with this
-- file, You can obtain one at http://mozilla.org/MPL/2.0/.
--[[
Firefox Monthly Dashboard
*Example Heka Configuration*
.. code-block:: ini
[FirefoxMonthlyDashboard]
type = "SandboxFilter"
filename = "lua_filters/firefox_monthly_dashboard.lua"
message_matcher = "(Logger == 'fx' && Type == 'executive_summary') || (Type == 'telemetry' && Fields[docType] == 'crash')"
output_limit = 8000000
memory_limit = 2000000000
ticker_interval = 0
preserve_data = false
timer_event_on_shutdown = true
[FirefoxMonthlyDashboard.config]
items = 100000000
--]]
fx = require "fx" -- this must be global when we are pulling in other fx submodules
require "fx.executive_report"
require "math"
require "os"
require "string"
require "table"
local SEC_IN_DAY = 60 * 60 * 24
local floor = math.floor
local date = os.date
local format = string.format
local items = read_config("items") or 1000
local month_names = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug",
"Sep", "Oct", "Nov", "Dec"}
local MONTHS = #month_names
months = {}
current_month = -1
current_day = -1
for i=1,MONTHS do
months[i] = {}
end
fx_cids = fx.executive_report.new(items)
local function get_row(ts, month, geo, channel, _os)
local m = months[month]
local key = format("%d,%d,%d", geo, channel, _os)
local r = m[key]
if not r then
local ds = date("%Y-%m-01", ts / 1e9)
-- date, actives, hours, inactives, new_records, five_of_seven, total_records, crashes, default, google, bing, yahoo, other
r = {ds, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
m[key] = r
end
return r
end
local function clear_months(s, n)
for i = 1, n do
s = s + 1
if s > MONTHS then s = 1 end
months[s] = {}
end
end
local function update_month(ts, cid, day_changed)
local month = current_month
if current_month == -1 or day_changed then
local t = date("*t", ts / 1e9)
month = tonumber(t.month)
if current_month == -1 then current_month = month end
end
local delta = month - current_month
if delta > 0 then
fx_cids:report(months[current_month])
clear_months(current_month, delta)
current_month = month
elseif delta < 0 then -- roll over the year
fx_cids:report(months[current_month])
clear_months(current_month, MONTHS + delta)
current_month = month
end
local msgType = read_message("Type")
local _os = fx.get_os_id(read_message("Fields[os]"))
local country, channel
if msgType == "executive_summary" then
country = fx.get_country_id(read_message("Fields[country]"))
channel = fx.get_channel_id(read_message("Fields[channel]"))
else
country = fx.get_country_id(read_message("Fields[geoCountry]"))
channel = fx.get_channel_id(read_message("Fields[appUpdateChannel]"))
end
local r = get_row(ts, month, country, channel, _os)
if r then
if msgType == "executive_summary" then
local dflt = fx.get_boolean_value(read_message("Fields[default]"))
fx_cids:add(cid, country, channel, _os, 0, dflt)
r[3] = r[3] + (tonumber(read_message("Fields[hours]")) or 0)
r[10] = r[10] + (tonumber(read_message("Fields[google]")) or 0)
r[11] = r[11] + (tonumber(read_message("Fields[bing]")) or 0)
r[12] = r[12] + (tonumber(read_message("Fields[yahoo]")) or 0)
r[13] = r[13] + (tonumber(read_message("Fields[other]")) or 0)
else -- crash report
r[8] = r[8] + 1
end
end
end
----
function process_message()
local ts = read_message("Timestamp")
local cid = read_message("Fields[clientId]")
if type(cid) == "string" then
local day = floor(ts / (SEC_IN_DAY * 1e9))
local day_changed = day ~= current_day
if day < current_day then
error("data is in the past, this report doesn't back fill")
end
current_day = day
update_month(ts, cid, day_changed)
end
return 0
end
function timer_event(ns)
if current_month == -1 then return end
fx_cids:report(months[current_month])
add_to_payload("geo,channel,os,date,actives,hours,inactives,new_records,five_of_seven,total_records,crashes,default,google,bing,yahoo,other\n")
local country, channel, _os
for i,t in ipairs(months) do
for k,v in pairs(t) do
country, channel, _os = k:match("(%d+),(%d+),(%d+)")
add_to_payload(fx.get_country_name(tonumber(country)), ",",
fx.get_channel_name(tonumber(channel)), ",",
fx.get_os_name(tonumber(_os)), ",",
table.concat(v, ","), "\n")
end
end
inject_payload("csv", "firefox_monthly_data")
end
|
-- This Source Code Form is subject to the terms of the Mozilla Public
-- License, v. 2.0. If a copy of the MPL was not distributed with this
-- file, You can obtain one at http://mozilla.org/MPL/2.0/.
--[[
Firefox Monthly Dashboard
*Example Heka Configuration*
.. code-block:: ini
[FirefoxMonthlyDashboard]
type = "SandboxFilter"
filename = "lua_filters/firefox_monthly_dashboard.lua"
message_matcher = "(Logger == 'fx' && Type == 'executive_summary') || (Type == 'telemetry' && Fields[docType] == 'crash')"
output_limit = 8000000
memory_limit = 2000000000
ticker_interval = 0
preserve_data = false
timer_event_on_shutdown = true
[FirefoxMonthlyDashboard.config]
items = 100000000
--]]
fx = require "fx" -- this must be global when we are pulling in other fx submodules
require "fx.executive_report"
require "math"
require "os"
require "string"
require "table"
local SEC_IN_DAY = 60 * 60 * 24
local floor = math.floor
local date = os.date
local format = string.format
local items = read_config("items") or 1000
local month_names = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug",
"Sep", "Oct", "Nov", "Dec"}
local MONTHS = #month_names
months = {}
current_month = -1
current_day = -1
for i=1,MONTHS do
months[i] = {}
end
fx_cids = fx.executive_report.new(items)
local function get_row(ts, month, geo, channel, _os)
local m = months[month]
local key = format("%d,%d,%d", geo, channel, _os)
local r = m[key]
if not r then
local ds = date("%Y-%m-01", ts / 1e9)
-- date, actives, hours, inactives, new_records, five_of_seven, total_records, crashes, default, google, bing, yahoo, other
r = {ds, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
m[key] = r
end
return r
end
local function clear_months(s, n)
for i = 1, n do
s = s + 1
if s > MONTHS then s = 1 end
months[s] = {}
end
end
local function update_month(ts, cid, day_changed)
local month = current_month
if current_month == -1 or day_changed then
local t = date("*t", ts / 1e9)
month = tonumber(t.month)
if current_month == -1 then current_month = month end
end
local delta = month - current_month
if delta > 0 then
fx_cids:report(months[current_month])
clear_months(current_month, delta)
current_month = month
elseif delta < 0 then -- roll over the year
fx_cids:report(months[current_month])
clear_months(current_month, MONTHS + delta)
current_month = month
end
local msgType = read_message("Type")
local _os = fx.get_os_id(read_message("Fields[os]"))
local country, channel, _os
if msgType == "executive_summary" then
country = fx.get_country_id(read_message("Fields[country]"))
channel = fx.get_channel_id(read_message("Fields[channel]"))
_os = fx.get_os_id(read_message("Fields[os]"))
else
country = fx.get_country_id(read_message("Fields[geoCountry]"))
channel = fx.get_channel_id(fx.normalize_channel(read_message("Fields[appUpdateChannel]")))
_os = fx.get_os_id(fx.normalize_os(read_message("Fields[os]")))
end
local r = get_row(ts, month, country, channel, _os)
if r then
if msgType == "executive_summary" then
local dflt = fx.get_boolean_value(read_message("Fields[default]"))
fx_cids:add(cid, country, channel, _os, 0, dflt)
r[3] = r[3] + (tonumber(read_message("Fields[hours]")) or 0)
r[10] = r[10] + (tonumber(read_message("Fields[google]")) or 0)
r[11] = r[11] + (tonumber(read_message("Fields[bing]")) or 0)
r[12] = r[12] + (tonumber(read_message("Fields[yahoo]")) or 0)
r[13] = r[13] + (tonumber(read_message("Fields[other]")) or 0)
else -- crash report
r[8] = r[8] + 1
end
end
end
----
function process_message()
local ts = read_message("Timestamp")
local cid = read_message("Fields[clientId]")
if type(cid) == "string" then
local day = floor(ts / (SEC_IN_DAY * 1e9))
local day_changed = day ~= current_day
if day < current_day then
error("data is in the past, this report doesn't back fill")
end
current_day = day
update_month(ts, cid, day_changed)
end
return 0
end
function timer_event(ns)
if current_month == -1 then return end
fx_cids:report(months[current_month])
add_to_payload("geo,channel,os,date,actives,hours,inactives,new_records,five_of_seven,total_records,crashes,default,google,bing,yahoo,other\n")
local country, channel, _os
for i,t in ipairs(months) do
for k,v in pairs(t) do
country, channel, _os = k:match("(%d+),(%d+),(%d+)")
add_to_payload(fx.get_country_name(tonumber(country)), ",",
fx.get_channel_name(tonumber(channel)), ",",
fx.get_os_name(tonumber(_os)), ",",
table.concat(v, ","), "\n")
end
end
inject_payload("csv", "firefox_monthly_data")
end
|
Apply the same fix to the monthly dash
|
Apply the same fix to the monthly dash
|
Lua
|
mpl-2.0
|
whd/data-pipeline,nathwill/data-pipeline,acmiyaguchi/data-pipeline,sapohl/data-pipeline,nathwill/data-pipeline,sapohl/data-pipeline,whd/data-pipeline,sapohl/data-pipeline,mozilla-services/data-pipeline,acmiyaguchi/data-pipeline,whd/data-pipeline,mozilla-services/data-pipeline,mozilla-services/data-pipeline,sapohl/data-pipeline,acmiyaguchi/data-pipeline,acmiyaguchi/data-pipeline,whd/data-pipeline,mozilla-services/data-pipeline,nathwill/data-pipeline,nathwill/data-pipeline
|
783aa9ba164ac8cfb298af3f3497db5860b75838
|
.build.lua
|
.build.lua
|
project "PlotLib"
if zpm.option( "HeaderOnly" ) then
zpm.export [[
defines "PLOTLIB_NO_HEADER_ONLY"
]]
files "plot/src/**.cpp"
kind "StaticLib"
else
kind "Utility"
end
if zpm.option( "UseZPMAnaconda" ) then
zpm.export [[
defines "PLOTLIB_USE_ZPM_ANACONDA"
]]
end
zpm.export [[
includedirs "plot/include/"
flags "C++11"
]]
|
project "PlotLib"
if zpm.option( "HeaderOnly" ) then
kind "Utility"
else
zpm.export [[
defines "PLOTLIB_NO_HEADER_ONLY"
]]
files "plot/src/**.cpp"
kind "StaticLib"
end
if zpm.option( "UseZPMAnaconda" ) then
zpm.export [[
defines "PLOTLIB_USE_ZPM_ANACONDA"
]]
end
zpm.export [[
includedirs "plot/include/"
flags "C++11"
]]
|
Fixed header only toggle
|
Fixed header only toggle
|
Lua
|
mit
|
Zefiros-Software/PlotLib,Zefiros-Software/PlotLib
|
e59fe89028e634bded09dbd0c16d7852f55d7b3e
|
nodemcu/init.lua
|
nodemcu/init.lua
|
local wifimodule = require 'wifimodule'
local socketmodule = require 'socketmodule'
local config = require 'config'
local color = nil
-- Initialize LED-strip and Timer
ws2812.init()
local i, buffer = 0, ws2812.newBuffer(8, 3)
local ledTimer = tmr.create()
-- Fill the LED_strip with a single color
function setStrip(colorArray)
buffer:fill(colorArray[1], colorArray[2], colorArray[3])
ws2812.write(buffer)
end
-- Make the LED-strip loop
function ledLoop(interval, colorArray)
ledTimer:register(interval, 1, function()
i = i + 1
buffer:fade(2)
buffer:set(i % buffer:size() + 1, colorArray[1], colorArray[2], colorArray[3])
ws2812.write(buffer)
end)
ledTimer:start()
end
function clearStrip()
buffer:fill(0, 0, 0)
ws2812.write(buffer)
ledTimer:stop()
end
-- Initialize application on NodeMCU
function init()
-- Receive socket events
local ws = socketmodule.initSocket()
ws:on('receive', function(_, msg)
local data = cjson.decode(msg)
if data.action == 'CHANGE_COLOR' then
color = data.color
setStrip(data.color)
elseif data.action == 'SPECTATE' then
ledLoop(100, {
0, 255, 0
})
elseif data.action == 'END_GAME' then
-- Check if button belongs to winner
if data.winner.id == node.chipid() then
ledLoop(50, {
color
})
else
clearStrip()
end
elseif data.action == 'RESET_GAME' then
clearStrip()
setStrip(color)
end
end)
-- Read button
local button = 1
local isPressed = 1
-- clear LED-strip
clearStrip()
-- When button has been pressed or released
function onChange()
if gpio.read(button) < isPressed then
print('Button pressed!')
-- Temporary turns off lights on button press
clearStrip()
ledTimer:start()
-- End feedback after 500ms
ledTimer:alarm(500, tmr.ALARM_SINGLE, function()
setStrip(color)
ledTimer:stop()
end)
ok, json = pcall(cjson.encode, {
device = 'nodemcu',
action = 'UPDATE_SCORE',
id = node.chipid()
})
if ok then
ws:send(json)
else
print('failed to encode JSON!')
end
end
isPressed = gpio.read(button)
end
gpio.mode(button, gpio.INT, gpio.PULLUP)
gpio.trig(button, 'both', onChange)
end
-- Provide Wi-fi connection feedback
ledLoop(250, {
255, 255, 255
})
-- Initilize Wi-fi connection
wifimodule.connect(config, init)
|
local wifimodule = require 'wifimodule'
local socketmodule = require 'socketmodule'
local config = require 'config'
local color = nil
-- Initialize LED-strip and Timer
ws2812.init()
local i, buffer = 0, ws2812.newBuffer(8, 3)
local ledTimer = tmr.create()
-- Fill the LED_strip with a single color
function setStrip(colorArray)
buffer:fill(colorArray[1], colorArray[2], colorArray[3])
ws2812.write(buffer)
end
-- Make the LED-strip loop
function ledLoop(interval, colorArray)
ledTimer:register(interval, 1, function()
i = i + 1
buffer:fade(2)
buffer:set(i % buffer:size() + 1, colorArray[1], colorArray[2], colorArray[3])
ws2812.write(buffer)
end)
ledTimer:start()
end
function clearStrip()
buffer:fill(0, 0, 0)
ws2812.write(buffer)
ledTimer:stop()
end
-- Initialize application on NodeMCU
function init()
-- Receive socket events
local ws = socketmodule.initSocket()
ws:on('receive', function(_, msg)
local data = cjson.decode(msg)
if data.action == 'CHANGE_COLOR' then
color = data.color
setStrip(data.color)
elseif data.action == 'SPECTATE' then
ledLoop(100, {
0, 255, 0
})
elseif data.action == 'END_GAME' then
-- Check if button belongs to winner
if data.winner == node.chipid() then
ledLoop(50, {
color
})
else
clearStrip()
end
elseif data.action == 'RESET_GAME' then
clearStrip()
setStrip(color)
end
end)
-- Read button
local button = 1
local isPressed = 1
-- clear LED-strip
clearStrip()
-- When button has been pressed or released
function onChange()
if gpio.read(button) < isPressed then
print('Button pressed!')
-- Temporary turns off lights on button press
clearStrip()
ledTimer:start()
-- End feedback after 500ms
ledTimer:alarm(500, tmr.ALARM_SINGLE, function()
setStrip(color)
ledTimer:stop()
end)
ok, json = pcall(cjson.encode, {
action = 'UPDATE_SCORE',
id = node.chipid()
})
if ok then
ws:send(json)
else
print('failed to encode JSON!')
end
end
isPressed = gpio.read(button)
end
gpio.mode(button, gpio.INT, gpio.PULLUP)
gpio.trig(button, 'both', onChange)
end
-- Provide Wi-fi connection feedback
ledLoop(250, {
255, 255, 255
})
-- Initilize Wi-fi connection
wifimodule.connect(config, init)
|
Fix end-game sequence
|
Fix end-game sequence
|
Lua
|
mit
|
rijkvanzanten/luaus
|
f35f29c020540501787a72a206941c35ab4191ae
|
bin/benchmarks/scanner.lua
|
bin/benchmarks/scanner.lua
|
#!/usr/bin/env luajit
-- SPDX-FileCopyrightText: Copyright 2014-present Greg Hurrell and contributors.
-- SPDX-License-Identifier: BSD-2-Clause
local ffi = require('ffi')
local pwd = os.getenv('PWD')
local lua_directory = pwd .. '/' .. debug.getinfo(1).source:match('@?(.*/)') .. '../../lua'
package.path = lua_directory .. '/?.lua;' .. package.path
package.path = lua_directory .. '/?/init.lua;' .. package.path
local benchmark = require('wincent.commandt.private.benchmark')
benchmark({
config = 'wincent.commandt.benchmark.configs.scanner',
log = 'wincent.commandt.benchmark.logs.scanner',
setup = function(config)
local scanner = require(config.source)
if scanner.name == 'watchman' then
-- TODO: don't hardcode this, obviously...
scanner.set_sockname('/opt/homebrew/var/run/watchman/wincent-state/sock')
end
if config.stub_candidates then
-- For scanners that otherwise depend on Neovim for a list of candidates.
config.stub_candidates(scanner)
end
return scanner
end,
skip = function(config)
return config.skip_in_ci and os.getenv('CI')
end,
run = function(config, setup)
local scanner = setup.scanner(pwd) -- For now, only Watchman wants pwd.
for i = 1, scanner.count do
ffi.string(scanner.candidates[i - 1].contents)
end
end,
})
|
#!/usr/bin/env luajit
-- SPDX-FileCopyrightText: Copyright 2014-present Greg Hurrell and contributors.
-- SPDX-License-Identifier: BSD-2-Clause
local ffi = require('ffi')
local pwd = os.getenv('PWD')
local lua_directory = pwd .. '/' .. debug.getinfo(1).source:match('@?(.*/)') .. '../../lua'
package.path = lua_directory .. '/?.lua;' .. package.path
package.path = lua_directory .. '/?/init.lua;' .. package.path
local benchmark = require('wincent.commandt.private.benchmark')
benchmark({
config = 'wincent.commandt.benchmark.configs.scanner',
log = 'wincent.commandt.benchmark.logs.scanner',
setup = function(config)
local scanner = require(config.source)
if scanner.name == 'watchman' then
-- We don't have a real JSON parser here, so we fake it.
local fallback = '/opt/homebrew/var/run/watchman/wincent-state/sock'
local file = assert(io.popen('watchman get-sockname', 'r'))
local output = file:read('*all')
file:close()
local name = output:match('"sockname":%s*"([^"]+)"') or fallback
scanner.set_sockname(name)
end
if config.stub_candidates then
-- For scanners that otherwise depend on Neovim for a list of candidates.
config.stub_candidates(scanner)
end
return scanner
end,
skip = function(config)
return config.skip_in_ci and os.getenv('CI')
end,
run = function(config, setup)
local scanner = setup.scanner(pwd) -- For now, only Watchman wants pwd.
for i = 1, scanner.count do
ffi.string(scanner.candidates[i - 1].contents)
end
end,
})
|
fix(lua): make scanner benchmarks work on Intel machine
|
fix(lua): make scanner benchmarks work on Intel machine
Get rid of the hard-coded path that applied to Apple Silicon Mac.
|
Lua
|
bsd-2-clause
|
wincent/command-t,wincent/command-t,wincent/command-t
|
e68b0e8fd883a2bdbd638d94656e35ecea6870e9
|
src/rogue-properties/src/Shared/RoguePropertyService.lua
|
src/rogue-properties/src/Shared/RoguePropertyService.lua
|
--[=[
@class RoguePropertyService
]=]
local require = require(script.Parent.loader).load(script)
local RunService = game:GetService("RunService")
local Signal = require("Signal")
local Maid = require("Maid")
local Observable = require("Observable")
local RoguePropertyService = {}
function RoguePropertyService:Init(serviceBag)
assert(not self._serviceBag, "Already initialized")
self._serviceBag = assert(serviceBag, "No serviceBag")
self._maid = Maid.new()
-- Internal
self._serviceBag:GetService(require("RogueBindersShared"))
self._roguePropertyBinderGroups = self._serviceBag:GetService(require("RoguePropertyBinderGroups"))
self._providers = {}
self.ProviderAddedEvent = Signal.new()
self._maid:GiveTask(self.ProviderAddedEvent)
-- Internal providers
self._serviceBag:GetService(require("RogueSetterProvider"))
self._serviceBag:GetService(require("RogueAdditiveProvider"))
self._serviceBag:GetService(require("RogueMultiplierProvider"))
end
function RoguePropertyService:AddProvider(provider)
self._roguePropertyBinderGroups.RogueModifiers:Add(provider:GetBinder())
table.insert(self._providers, provider)
self.ProviderAddedEvent:Fire(provider)
end
function RoguePropertyService:GetProviders()
return self._providers
end
function RoguePropertyService:ObserveProviderList()
return Observable.new(function(sub)
local maid = Maid.new()
sub:Fire(self._providers)
maid:GiveTask(self.ProviderAddedEvent:Connect(function()
sub:Fire(self._providers)
end))
return maid
end)
end
function RoguePropertyService:CanInitializeProperties()
return RunService:IsServer()
end
function RoguePropertyService:Destroy()
self._maid:DoCleaning()
end
return RoguePropertyService
|
--[=[
@class RoguePropertyService
]=]
local require = require(script.Parent.loader).load(script)
local RunService = game:GetService("RunService")
local Signal = require("Signal")
local Maid = require("Maid")
local Observable = require("Observable")
local RoguePropertyService = {}
function RoguePropertyService:Init(serviceBag)
assert(not self._serviceBag, "Already initialized")
self._serviceBag = assert(serviceBag, "No serviceBag")
self._maid = Maid.new()
-- Internal
self._serviceBag:GetService(require("RogueBindersShared"))
self._roguePropertyBinderGroups = self._serviceBag:GetService(require("RoguePropertyBinderGroups"))
self._providers = {}
self.ProviderAddedEvent = Signal.new()
self._maid:GiveTask(self.ProviderAddedEvent)
-- Internal providers
self._serviceBag:GetService(require("RogueSetterProvider"))
self._serviceBag:GetService(require("RogueAdditiveProvider"))
self._serviceBag:GetService(require("RogueMultiplierProvider"))
end
function RoguePropertyService:AddProvider(provider)
self._roguePropertyBinderGroups.RogueModifiers:Add(provider:GetBinder())
table.insert(self._providers, provider)
self.ProviderAddedEvent:Fire(provider)
end
function RoguePropertyService:GetProviders()
if not RunService:IsRunning() then
return {}
end
return self._providers
end
function RoguePropertyService:ObserveProviderList()
if not RunService:IsRunning() then
return Observable.new(function(sub)
sub:Fire({})
end)
end
return Observable.new(function(sub)
local maid = Maid.new()
sub:Fire(self._providers)
maid:GiveTask(self.ProviderAddedEvent:Connect(function()
sub:Fire(self._providers)
end))
return maid
end)
end
function RoguePropertyService:CanInitializeProperties()
return RunService:IsServer()
end
function RoguePropertyService:Destroy()
self._maid:DoCleaning()
end
return RoguePropertyService
|
fix: RogueProperties work in test mode
|
fix: RogueProperties work in test mode
|
Lua
|
mit
|
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
|
7249406960cc18b42b297fed5c7b9a661db75e9b
|
resources/prosody-plugins/mod_persistent_lobby.lua
|
resources/prosody-plugins/mod_persistent_lobby.lua
|
-- This module allows lobby room to be created even when the main room is empty.
-- Without this module, the empty main room will get deleted after grace period
-- which triggers lobby room deletion even if there are still people in the lobby.
--
-- This module should be added to the main virtual host domain.
-- It assumes you have properly configured the muc_lobby_rooms module and lobby muc component.
--
-- To trigger creation of lobby room:
-- prosody.events.fire_event("create-persistent-lobby-room", { room = room; });
--
local util = module:require "util";
local is_healthcheck_room = util.is_healthcheck_room;
local main_muc_component_host = module:get_option_string('main_muc');
local lobby_muc_component_host = module:get_option_string('lobby_muc');
if main_muc_component_host == nil then
module:log('error', 'main_muc not configured. Cannot proceed.');
return;
end
if lobby_muc_component_host == nil then
module:log('error', 'lobby not enabled missing lobby_muc config');
return;
end
-- Helper function to wait till a component is loaded before running the given callback
local function run_when_component_loaded(component_host_name, callback)
local function trigger_callback()
module:log('info', 'Component loaded %s', component_host_name);
callback(module:context(component_host_name), component_host_name);
end
if prosody.hosts[component_host_name] == nil then
module:log('debug', 'Host %s not yet loaded. Will trigger when it is loaded.', component_host_name);
prosody.events.add_handler('host-activated', function (host)
if host == component_host_name then
trigger_callback();
end
end);
else
trigger_callback();
end
end
-- Helper function to wait till a component's muc module is loaded before running the given callback
local function run_when_muc_module_loaded(component_host_module, component_host_name, callback)
local function trigger_callback()
module:log('info', 'MUC module loaded for %s', component_host_name);
callback(prosody.hosts[component_host_name].modules.muc, component_host_module);
end
if prosody.hosts[component_host_name].modules.muc == nil then
module:log('debug', 'MUC module for %s not yet loaded. Will trigger when it is loaded.', component_host_name);
prosody.hosts[component_host_name].events.add_handler('module-loaded', function(event)
if (event.module == 'muc') then
trigger_callback();
end
end);
else
trigger_callback()
end
end
local lobby_muc_service;
local main_muc_service;
local main_muc_module;
-- Helper methods to track rooms that have persistent lobby
local function set_persistent_lobby(room)
room._data.persist_lobby = true;
end
local function has_persistent_lobby(room)
if room._data.persist_lobby == true then
return true;
else
return false;
end
end
-- Helper method to trigger main room destroy if room is persistent (no auto-delete) and destroy not yet triggered
local function trigger_room_destroy(room)
if room.get_persistent(room) and room._data.room_destroy_triggered == nil then
room._data.room_destroy_triggered = true;
main_muc_module:fire_event("muc-room-destroyed", { room = room; });
end
end
-- For rooms with persistent lobby, we need to trigger deletion ourselves when both the main room
-- and the lobby room are empty. This will be checked each time an occupant leaves the main room
-- of if someone drops off the lobby.
-- Handle events on main muc module
run_when_component_loaded(main_muc_component_host, function(host_module, host_name)
run_when_muc_module_loaded(host_module, host_name, function (main_muc, main_module)
main_muc_service = main_muc; -- so it can be accessed from lobby muc event handlers
main_muc_module = main_module;
main_module:hook("muc-occupant-left", function(event)
-- Check if room should be destroyed when someone leaves the main room
local main_room = event.room;
if is_healthcheck_room(main_room.jid) or not has_persistent_lobby(main_room) then
return;
end
local lobby_room_jid = main_room._data.lobbyroom;
-- If occupant leaving results in main room being empty, we trigger room destroy if
-- a) lobby exists and is not empty
-- b) lobby does not exist (possible for lobby to be disabled manually by moderator in meeting)
--
-- (main room destroy also triggers lobby room destroy in muc_lobby_rooms)
if not main_room:has_occupant() then
if lobby_room_jid == nil then -- lobby disabled
trigger_room_destroy(main_room);
else -- lobby exists
local lobby_room = lobby_muc_service.get_room_from_jid(lobby_room_jid);
if lobby_room and not lobby_room:has_occupant() then
trigger_room_destroy(main_room);
end
end
end
end);
end);
end);
-- Handle events on lobby muc module
run_when_component_loaded(lobby_muc_component_host, function(host_module, host_name)
run_when_muc_module_loaded(host_module, host_name, function (lobby_muc, lobby_module)
lobby_muc_service = lobby_muc; -- so it can be accessed from main muc event handlers
lobby_module:hook("muc-occupant-left", function(event)
-- Check if room should be destroyed when someone leaves the lobby
local lobby_room = event.room;
local main_room = lobby_room.main_room;
if is_healthcheck_room(main_room.jid) or not has_persistent_lobby(main_room) then
return;
end
-- If both lobby room and main room are empty, we destroy main room.
-- (main room destroy also triggers lobby room destroy in muc_lobby_rooms)
if not lobby_room:has_occupant() and main_room and not main_room:has_occupant() then
trigger_room_destroy(main_room);
end
end);
end);
end);
function handle_create_persistent_lobby(event)
local room = event.room;
prosody.events.fire_event("create-lobby-room", { room = room; });
set_persistent_lobby(room);
room:set_persistent(true);
end
module:hook_global('create-persistent-lobby-room', handle_create_persistent_lobby);
|
-- This module allows lobby room to be created even when the main room is empty.
-- Without this module, the empty main room will get deleted after grace period
-- which triggers lobby room deletion even if there are still people in the lobby.
--
-- This module should be added to the main virtual host domain.
-- It assumes you have properly configured the muc_lobby_rooms module and lobby muc component.
--
-- To trigger creation of lobby room:
-- prosody.events.fire_event("create-persistent-lobby-room", { room = room; });
--
local util = module:require "util";
local is_healthcheck_room = util.is_healthcheck_room;
local main_muc_component_host = module:get_option_string('main_muc');
local lobby_muc_component_host = module:get_option_string('lobby_muc');
if main_muc_component_host == nil then
module:log('error', 'main_muc not configured. Cannot proceed.');
return;
end
if lobby_muc_component_host == nil then
module:log('error', 'lobby not enabled missing lobby_muc config');
return;
end
-- Helper function to wait till a component is loaded before running the given callback
local function run_when_component_loaded(component_host_name, callback)
local function trigger_callback()
module:log('info', 'Component loaded %s', component_host_name);
callback(module:context(component_host_name), component_host_name);
end
if prosody.hosts[component_host_name] == nil then
module:log('debug', 'Host %s not yet loaded. Will trigger when it is loaded.', component_host_name);
prosody.events.add_handler('host-activated', function (host)
if host == component_host_name then
trigger_callback();
end
end);
else
trigger_callback();
end
end
-- Helper function to wait till a component's muc module is loaded before running the given callback
local function run_when_muc_module_loaded(component_host_module, component_host_name, callback)
local function trigger_callback()
module:log('info', 'MUC module loaded for %s', component_host_name);
callback(prosody.hosts[component_host_name].modules.muc, component_host_module);
end
if prosody.hosts[component_host_name].modules.muc == nil then
module:log('debug', 'MUC module for %s not yet loaded. Will trigger when it is loaded.', component_host_name);
prosody.hosts[component_host_name].events.add_handler('module-loaded', function(event)
if (event.module == 'muc') then
trigger_callback();
end
end);
else
trigger_callback()
end
end
local lobby_muc_service;
local main_muc_service;
local main_muc_module;
-- Helper methods to track rooms that have persistent lobby
local function set_persistent_lobby(room)
room._data.persist_lobby = true;
end
local function has_persistent_lobby(room)
if room._data.persist_lobby == true then
return true;
else
return false;
end
end
-- Helper method to trigger main room destroy
local function trigger_room_destroy(room)
room:set_persistent(false);
room:destroy(nil, 'main room and lobby now empty');
end
-- For rooms with persistent lobby, we need to trigger deletion ourselves when both the main room
-- and the lobby room are empty. This will be checked each time an occupant leaves the main room
-- of if someone drops off the lobby.
-- Handle events on main muc module
run_when_component_loaded(main_muc_component_host, function(host_module, host_name)
run_when_muc_module_loaded(host_module, host_name, function (main_muc, main_module)
main_muc_service = main_muc; -- so it can be accessed from lobby muc event handlers
main_muc_module = main_module;
main_module:hook("muc-occupant-left", function(event)
-- Check if room should be destroyed when someone leaves the main room
local main_room = event.room;
if is_healthcheck_room(main_room.jid) or not has_persistent_lobby(main_room) then
return;
end
local lobby_room_jid = main_room._data.lobbyroom;
-- If occupant leaving results in main room being empty, we trigger room destroy if
-- a) lobby exists and is not empty
-- b) lobby does not exist (possible for lobby to be disabled manually by moderator in meeting)
--
-- (main room destroy also triggers lobby room destroy in muc_lobby_rooms)
if not main_room:has_occupant() then
if lobby_room_jid == nil then -- lobby disabled
trigger_room_destroy(main_room);
else -- lobby exists
local lobby_room = lobby_muc_service.get_room_from_jid(lobby_room_jid);
if lobby_room and not lobby_room:has_occupant() then
trigger_room_destroy(main_room);
end
end
end
end);
end);
end);
-- Handle events on lobby muc module
run_when_component_loaded(lobby_muc_component_host, function(host_module, host_name)
run_when_muc_module_loaded(host_module, host_name, function (lobby_muc, lobby_module)
lobby_muc_service = lobby_muc; -- so it can be accessed from main muc event handlers
lobby_module:hook("muc-occupant-left", function(event)
-- Check if room should be destroyed when someone leaves the lobby
local lobby_room = event.room;
local main_room = lobby_room.main_room;
if is_healthcheck_room(main_room.jid) or not has_persistent_lobby(main_room) then
return;
end
-- If both lobby room and main room are empty, we destroy main room.
-- (main room destroy also triggers lobby room destroy in muc_lobby_rooms)
if not lobby_room:has_occupant() and main_room and not main_room:has_occupant() then
trigger_room_destroy(main_room);
end
end);
end);
end);
function handle_create_persistent_lobby(event)
local room = event.room;
prosody.events.fire_event("create-lobby-room", { room = room; });
set_persistent_lobby(room);
room:set_persistent(true);
end
module:hook_global('create-persistent-lobby-room', handle_create_persistent_lobby);
|
fix(persistent_lobby): properly destroy main room when empty
|
fix(persistent_lobby): properly destroy main room when empty
|
Lua
|
apache-2.0
|
jitsi/jitsi-meet,jitsi/jitsi-meet,jitsi/jitsi-meet,jitsi/jitsi-meet,jitsi/jitsi-meet,jitsi/jitsi-meet,jitsi/jitsi-meet,jitsi/jitsi-meet
|
f1646c247e373cd73582f052daa2733c573f06a8
|
src/main.lua
|
src/main.lua
|
-- Kong, the biggest ape in town
--
-- /\ ____
-- <> ( oo )
-- <>_| ^^ |_
-- <> @ \
-- /~~\ . . _ |
-- /~~~~\ | |
-- /~~~~~~\/ _| |
-- |[][][]/ / [m]
-- |[][][[m]
-- |[][][]|
-- |[][][]|
-- |[][][]|
-- |[][][]|
-- |[][][]|
-- |[][][]|
-- |[][][]|
-- |[][][]|
-- |[|--|]|
-- |[| |]|
-- ========
-- ==========
-- |[[ ]]|
-- ==========
utils = require "kong.tools.utils"
local constants = require "constants"
-- Define the plugins to load here, in the appropriate order
local plugins = {}
local _M = {}
local function load_plugin_conf(api_id, application_id, plugin_name)
local data, err = dao.plugins:find_by_keys {
api_id = api_id,
application_id = application_id ~= nil and application_id or constants.DATABASE_NULL_ID,
name = plugin_name
}
if err then
ngx.log(ngx.ERROR, err)
return nil
end
if #data > 0 then
local plugin = table.remove(data, 1)
if plugin.enabled then
return plugin
end
end
return nil
end
function _M.init()
-- Loading configuration
configuration, dao = utils.load_configuration_and_dao(os.getenv("KONG_CONF"))
dao:prepare()
-- core is the first plugin
table.insert(plugins, {
name = "core",
handler = require("kong.core.handler")()
})
-- Loading defined plugins
for _, plugin_name in ipairs(configuration.plugins_enabled) do
table.insert(plugins, {
name = plugin_name,
handler = require("kong.plugins."..plugin_name..".handler")()
})
end
end
function _M.access()
-- Setting a property that will be available for every plugin
ngx.ctx.start = ngx.now()
ngx.ctx.plugin_conf = {}
-- Iterate over all the plugins
for _, plugin in ipairs(plugins) do
if ngx.ctx.api then
ngx.ctx.plugin_conf[plugin.name] = load_plugin_conf(ngx.ctx.api.id, nil, plugin.name) -- Loading the "API-specific" configuration
end
if ngx.ctx.authenticated_entity then
local plugin_conf = load_plugin_conf(ngx.ctx.api.id, ngx.ctx.authenticated_entity.id, plugin.name)
if plugin_conf then -- Override only if not nil
ngx.ctx.plugin_conf[plugin.name] = plugin_conf
end
end
if not ngx.ctx.error then
local conf = ngx.ctx.plugin_conf[plugin.name]
if not ngx.ctx.api then -- If not ngx.ctx.api then it's the core plugin
plugin.handler:access(nil)
elseif conf then
plugin.handler:access(conf.value)
end
end
end
ngx.ctx.proxy_start = ngx.now() -- Setting a property that will be available for every plugin
end
function _M.header_filter()
ngx.ctx.proxy_end = ngx.now() -- Setting a property that will be available for every plugin
if not ngx.ctx.error then
for _, plugin in ipairs(plugins) do
local conf = ngx.ctx.plugin_conf[plugin.name]
if conf then
plugin.handler:header_filter(conf.value)
end
end
end
end
function _M.body_filter()
if not ngx.ctx.error then
for _, plugin in ipairs(plugins) do
local conf = ngx.ctx.plugin_conf[plugin.name]
if conf then
plugin.handler:body_filter(conf.value)
end
end
end
end
function _M.log()
if not ngx.ctx.error then
local now = ngx.now()
-- Creating the log variable that will be serialized
local message = {
request = {
headers = ngx.req.get_headers(),
size = ngx.var.request_length
},
response = {
headers = ngx.resp.get_headers(),
size = ngx.var.body_bytes_sent
},
authenticated_entity = ngx.ctx.authenticated_entity,
api = ngx.ctx.api,
ip = ngx.var.remote_addr,
status = ngx.status,
url = ngx.var.uri,
created_at = now
}
ngx.ctx.log_message = message
for _, plugin in ipairs(plugins) do
local conf = ngx.ctx.plugin_conf[plugin.name]
if conf then
plugin.handler:log(conf.value)
end
end
end
end
return _M
|
-- Kong, the biggest ape in town
--
-- /\ ____
-- <> ( oo )
-- <>_| ^^ |_
-- <> @ \
-- /~~\ . . _ |
-- /~~~~\ | |
-- /~~~~~~\/ _| |
-- |[][][]/ / [m]
-- |[][][[m]
-- |[][][]|
-- |[][][]|
-- |[][][]|
-- |[][][]|
-- |[][][]|
-- |[][][]|
-- |[][][]|
-- |[][][]|
-- |[|--|]|
-- |[| |]|
-- ========
-- ==========
-- |[[ ]]|
-- ==========
utils = require "kong.tools.utils"
local constants = require "kong.constants"
-- Define the plugins to load here, in the appropriate order
local plugins = {}
local _M = {}
local function load_plugin_conf(api_id, application_id, plugin_name)
local rows, err = dao.plugins:find_by_keys {
api_id = api_id,
application_id = application_id ~= nil and application_id or constants.DATABASE_NULL_ID,
name = plugin_name
}
if err then
ngx.log(ngx.ERROR, err)
return nil
end
if #rows > 0 then
local plugin = table.remove(rows, 1)
if plugin.enabled then
return plugin
end
end
return nil
end
function _M.init()
-- Loading configuration
configuration, dao = utils.load_configuration_and_dao(os.getenv("KONG_CONF"))
dao:prepare()
-- core is the first plugin
table.insert(plugins, {
core = true,
name = "core",
handler = require("kong.core.handler")()
})
-- Loading defined plugins
for _, plugin_name in ipairs(configuration.plugins_enabled) do
table.insert(plugins, {
name = plugin_name,
handler = require("kong.plugins."..plugin_name..".handler")()
})
end
end
function _M.access()
-- Setting a property that will be available for every plugin
ngx.ctx.start = ngx.now()
ngx.ctx.plugin_conf = {}
-- Iterate over all the plugins
for _, plugin in ipairs(plugins) do
if ngx.ctx.api then
ngx.ctx.plugin_conf[plugin.name] = load_plugin_conf(ngx.ctx.api.id, nil, plugin.name)
local application_id = ngx.ctx.authenticated_entity and ngx.ctx.authenticated_entity.id or nil
if application_id then
local app_plugin_conf = load_plugin_conf(ngx.ctx.api.id, application_id, plugin.name)
if app_plugin_conf then
ngx.ctx.plugin_conf[plugin.name] = app_plugin_conf
end
end
end
local conf = ngx.ctx.plugin_conf[plugin.name]
if not ngx.ctx.error and (plugin.core or conf) then
plugin.handler:access(conf and conf.value or nil)
end
end
ngx.ctx.proxy_start = ngx.now() -- Setting a property that will be available for every plugin
end
function _M.header_filter()
ngx.ctx.proxy_end = ngx.now() -- Setting a property that will be available for every plugin
if not ngx.ctx.error then
for _, plugin in ipairs(plugins) do
local conf = ngx.ctx.plugin_conf[plugin.name]
if conf then
plugin.handler:header_filter(conf.value)
end
end
end
end
function _M.body_filter()
if not ngx.ctx.error then
for _, plugin in ipairs(plugins) do
local conf = ngx.ctx.plugin_conf[plugin.name]
if conf then
plugin.handler:body_filter(conf.value)
end
end
end
end
function _M.log()
if not ngx.ctx.error then
local now = ngx.now()
-- Creating the log variable that will be serialized
local message = {
request = {
headers = ngx.req.get_headers(),
size = ngx.var.request_length
},
response = {
headers = ngx.resp.get_headers(),
size = ngx.var.body_bytes_sent
},
authenticated_entity = ngx.ctx.authenticated_entity,
api = ngx.ctx.api,
ip = ngx.var.remote_addr,
status = ngx.status,
url = ngx.var.uri,
created_at = now
}
ngx.ctx.log_message = message
for _, plugin in ipairs(plugins) do
local conf = ngx.ctx.plugin_conf[plugin.name]
if conf then
plugin.handler:log(conf.value)
end
end
end
end
return _M
|
Fix plugin configuration loading
|
Fix plugin configuration loading
|
Lua
|
mit
|
vmercierfr/kong,wakermahmud/kong,puug/kong,skynet/kong,Skyscanner/kong,AnsonSmith/kong,paritoshmmmec/kong,chourobin/kong,ChristopherBiscardi/kong,peterayeni/kong,sbuettner/kong,ropik/kong,bbalu/kong
|
7d56feadc399764908284902a342e1ab2104c3ff
|
mod_xrandr/test_xrandr.lua
|
mod_xrandr/test_xrandr.lua
|
-- {{{ mock notion context
local firstscreen = {
geom = function() return { x=0, y=0, w=1680, h=1050 } end,
name = function() return "WScreen<1>" end
}
local secondscreen = {
geom = function() return { x=1680, y=0, w=1920, h=1080 } end,
name = function() return "WScreen" end
}
notioncore = {
load_module = function()
return 1
end,
get_hook = function()
end,
region_i = function(callback, type)
local next = callback(firstscreen)
if next then callback(secondscreen) end
end
}
function dopath()
end
_G["mod_xrandr"] = {
-- query_screens = function() end
get_all_outputs = function()
return { VGA1 = { x=0, y=0, w=1680, h=1050 }, LVDS1 = { x=1680, y=0, w=1920, h=1080 } }
end
}
-- }}}
-- load xrandr module lua code
dofile('mod_xrandr.lua')
dofile('cfg_xrandr.lua')
local falls_within_secondscreen = falls_within(secondscreen.geom())
assert(falls_within_secondscreen(secondscreen:geom()))
assert(falls_within_secondscreen(firstscreen:geom())==false)
local outputs_within_secondscreen = mod_xrandr.get_outputs_within(secondscreen)
assert(singleton(outputs_within_secondscreen))
assert(firstValue(outputs_within_secondscreen).y == 0)
assert(firstValue(outputs_within_secondscreen).x == 1680)
local candidates = candidate_screens_for_output('VGA1')
assert(singleton(candidates))
assert(firstKey(candidates) == "WScreen<1>")
candidates = candidate_screens_for_outputs({'VGA1'})
assert(singleton(candidates))
assert(firstKey(candidates) == "WScreen<1>")
candidates = candidate_screens_for_output('LVDS1')
assert(singleton(candidates))
assert(firstKey(candidates) == "WScreen")
|
-- {{{ mock notion context
local firstscreen = {
geom = function() return { x=0, y=0, w=1680, h=1050 } end,
name = function() return "WScreen<1>" end
}
local secondscreen = {
geom = function() return { x=1680, y=0, w=1920, h=1080 } end,
name = function() return "WScreen" end
}
notioncore = {
load_module = function() return 1 end,
get_hook = function() return { add = function() end; } end,
region_i = function(callback, type)
local next = callback(firstscreen)
if next then callback(secondscreen) end
end
}
function dopath()
end
local all_outputs = { VGA1 = { x=0, y=0, w=1680, h=1050, name='VGA1' }, LVDS1 = { x=1680, y=0, w=1920, h=1080, name='LVDS1' } }
_G["mod_xrandr"] = {
-- query_screens = function() end
get_all_outputs = function()
return all_outputs;
end
}
-- }}}
-- load xrandr module lua code
dofile('mod_xrandr.lua')
dofile('cfg_xrandr.lua')
local falls_within_secondscreen = falls_within(secondscreen.geom())
assert(falls_within_secondscreen(secondscreen:geom()))
assert(falls_within_secondscreen(firstscreen:geom())==false)
local outputs_within_secondscreen = mod_xrandr.get_outputs_within(all_outputs, secondscreen)
assert(singleton(outputs_within_secondscreen))
assert(firstValue(outputs_within_secondscreen).y == 0)
assert(firstValue(outputs_within_secondscreen).x == 1680)
local candidates = candidate_screens_for_output(all_outputs, 'VGA1')
assert(singleton(candidates))
assert(firstKey(candidates) == "WScreen<1>")
candidates = candidate_screens_for_outputs(all_outputs, {'VGA1'})
assert(singleton(candidates))
assert(firstKey(candidates) == "WScreen<1>")
candidates = candidate_screens_for_output(all_outputs, 'LVDS1')
assert(singleton(candidates))
assert(firstKey(candidates) == "WScreen")
|
Fix unit tests
|
Fix unit tests
|
Lua
|
lgpl-2.1
|
dkogan/notion.xfttest,neg-serg/notion,knixeur/notion,dkogan/notion.xfttest,neg-serg/notion,raboof/notion,knixeur/notion,p5n/notion,dkogan/notion,dkogan/notion,anoduck/notion,dkogan/notion.xfttest,dkogan/notion,anoduck/notion,neg-serg/notion,dkogan/notion,raboof/notion,p5n/notion,p5n/notion,dkogan/notion.xfttest,knixeur/notion,raboof/notion,p5n/notion,knixeur/notion,neg-serg/notion,raboof/notion,dkogan/notion,anoduck/notion,anoduck/notion,knixeur/notion,anoduck/notion,p5n/notion
|
6cc0eb562f3f02e151d3aa04affbb3f447077ee1
|
src/cosy/connexion/js.lua
|
src/cosy/connexion/js.lua
|
require "cosy.lang.cosy"
js.global.cosy = cosy
local observed = require "cosy.lang.view.observed"
observed [#observed + 1] = require "cosy.lang.view.update"
cosy = observed (cosy)
local sha1 = require "sha1"
local json = require "dkjson"
local seq = require "cosy.lang.iterators" . seq
local tags = require "cosy.lang.tags"
local update = require "cosy.lang.view.update"
local WS = tags.WS
local URL = tags.URL
local UPDATES = tags.UPDATES
local function connect (parameters)
local token = parameters.token
local resource = parameters.resource
local editor = parameters.editor
local ws = js.global:websocket (editor)
local result = {
[URL ] = resource,
[WS ] = ws,
[UPDATES] = {},
}
ws.token = token
function ws:onopen ()
ws:request {
action = "set-resource",
token = token,
resource = resource,
}
end
function ws:onclose ()
result [WS] = nil
end
function ws:onmessage (event)
local message = event.data
print (message)
if not message then
return
end
local command = json.decode (message)
if command.action == "update" then
update.from_patch = true
for patch in seq (command.patches) do
print ("Applying patch " .. tostring (patch.data))
pcall (loadstring, patch.data)
end
update.from_patch = nil
else
-- do nothing
end
end
function ws:onerror ()
ws:close ()
end
function ws:request (command)
local str = json.encode (command)
command.request_id = sha1 (tostring (os.time()) .. "+" .. str)
command.token = ws.token
if ws.readyState == 1 then
ws:send (json.encode (command))
end
end
function ws:patch (str)
local command = {
action = "add-patch",
data = str,
}
local str = json.encode (command)
command.request_id = sha1 (tostring (os.time()) .. "+" .. str)
command.token = ws.token
if ws.readyState == 1 then
ws:send (json.encode (command))
end
end
cosy [resource] = result
return cosy [resource]
end
function window:count (x)
return #x
end
function window:id (x)
if type (x) == "table" then
local mt = getmetatable (x)
setmetatable (x, nil)
local result = tostring (x)
setmetatable (x, mt)
return result
else
return tostring (x)
end
end
function window:keys (x)
local result = {}
for key, _ in pairs (x) do
result [#result + 1] = key
end
return result
end
function window:elements (model)
local TYPE = tags.TYPE
local result = {}
for _, x in map (model) do
if type (x) . table and x [TYPE] then
result [#result + 1] = x
elseif type (x) . table then
for y in seq (window:elements (x)) do
result [#result + 1] = y
end
end
end
return result
end
function window:connect (editor, token, resource)
return connect {
editor = editor,
token = token,
resource = resource,
}
end
|
require "cosy.lang.cosy"
js.global.cosy = cosy
local observed = require "cosy.lang.view.observed"
observed [#observed + 1] = require "cosy.lang.view.update"
cosy = observed (cosy)
local sha1 = require "sha1"
local json = require "dkjson"
local seq = require "cosy.lang.iterators" . seq
local set = require "cosy.lang.iterators" . set
local map = require "cosy.lang.iterators" . map
local raw = require "cosy.lang.data" . raw
local tags = require "cosy.lang.tags"
local update = require "cosy.lang.view.update"
local type = require "cosy.util.type"
local WS = tags.WS
local RESOURCE = tags.RESOURCE
local UPDATES = tags.UPDATES
local function connect (parameters)
local token = parameters.token
local resource = parameters.resource
local editor = parameters.editor
local ws = js.global:websocket (editor)
local result = {
[RESOURCE] = resource,
[WS ] = ws,
[UPDATES ] = {},
}
ws.token = token
function ws:onopen ()
ws:request {
action = "set-resource",
token = token,
resource = resource,
}
end
function ws:onclose ()
result [WS] = nil
end
function ws:onmessage (event)
local message = event.data
print (message)
if not message then
return
end
local command = json.decode (message)
if command.action == "update" then
update.from_patch = true
for patch in seq (command.patches) do
print ("Applying patch " .. tostring (patch.data))
pcall (loadstring, patch.data)
end
update.from_patch = nil
else
-- do nothing
end
end
function ws:onerror ()
ws:close ()
end
function ws:request (command)
local str = json.encode (command)
command.request_id = sha1 (tostring (os.time()) .. "+" .. str)
command.token = ws.token
if ws.readyState == 1 then
ws:send (json.encode (command))
end
end
function ws:patch (str)
local command = {
action = "add-patch",
data = str,
}
local str = json.encode (command)
command.request_id = sha1 (tostring (os.time()) .. "+" .. str)
command.token = ws.token
if ws.readyState == 1 then
ws:send (json.encode (command))
end
end
cosy [resource] = result
return cosy [resource]
end
function window:count (x)
return #x
end
function window:id (x)
if type (x) == "table" then
local mt = getmetatable (x)
setmetatable (x, nil)
local result = tostring (x)
setmetatable (x, mt)
return result
else
return tostring (x)
end
end
function window:keys (x)
local result = {}
for key, _ in pairs (x) do
result [#result + 1] = key
end
return result
end
function window:elements (model)
local TYPE = tags.TYPE
local function set_of (e)
local result = {}
for _, x in map (e) do
if type (x) . table and x [TYPE] then
result [raw (x)] = true
elseif type (x) . table then
for y in seq (set_of (x)) do
result [y] = true
end
end
end
return result
end
local result = {}
for x in set (set_of (model)) do
result [#result + 1] = x
end
return result
end
function window:connect (editor, token, resource)
return connect {
editor = editor,
token = token,
resource = resource,
}
end
|
Fix problem in elements.
|
Fix problem in elements.
|
Lua
|
mit
|
CosyVerif/library,CosyVerif/library,CosyVerif/library
|
b0b8af05f49d067c24c836d51e1f2305b119ca85
|
lua/rails.lua
|
lua/rails.lua
|
request = { ['offset'] = 0 }
strptime_format = "%Y-%m-%d %H:%M:%S"
function process_line(line, offset)
if line == "\n" then
blanks = blanks or 0
blanks = blanks + 1
if blanks >= 2 and request['data'] then
-- insert the last request
request['data'] = table.concat(request['data'])
ug_request.add(request['data'], request['ts'], request['offset'])
request = { ['offset'] = offset }
blanks = 0
end
else
if not request['ts'] then
_, _, ts = string.find(line, "at (%d%d%d%d%-%d%d%-%d%d %d%d:%d%d:%d%d)")
if ts then
request['ts'] = ts
end
end
request['data'] = request['data'] or {}
table.insert(request['data'], line)
end
end
|
request = { ['offset'] = 0, ['data'] = {} }
strptime_format = "%Y-%m-%d %H:%M:%S"
blanks = 0
function process_line(line, offset)
if line == "\n" then
blanks = blanks + 1
else
if blanks >= 2 and request['data'] then
-- insert the last request, reset
request['data'] = table.concat(request['data'])
ug_request.add(request['data'], request['ts'], request['offset'])
request = { ['offset'] = offset, ['data'] = {} }
blanks = 0
end
if not request['ts'] then
_, _, ts = string.find(line, "at (%d%d%d%d%-%d%d%-%d%d %d%d:%d%d:%d%d)")
if ts then
request['ts'] = ts
end
end
table.insert(request['data'], line)
end
end
function on_eof()
request['data'] = table.concat(request['data'])
ug_request.add(request['data'], request['ts'], request['offset'])
end
|
update rails.lua
|
update rails.lua
add on_eof to capture the last request
fix blanks processing
always re-initialize data
|
Lua
|
apache-2.0
|
zendesk/ultragrep,zendesk/ultragrep
|
9d405abfe26f7093898aaeea93e239cef307747b
|
heka/sandbox/decoders/extract_telemetry_dimensions.lua
|
heka/sandbox/decoders/extract_telemetry_dimensions.lua
|
-- This Source Code Form is subject to the terms of the Mozilla Public
-- License, v. 2.0. If a copy of the MPL was not distributed with this
-- file, You can obtain one at http://mozilla.org/MPL/2.0/.
require "string"
require "cjson"
require "hash"
require "os"
local gzip = require "gzip"
local dt = require("date_time")
local msg = {
Timestamp = nil,
Type = "telemetry",
Payload = nil,
EnvVersion = 1
}
local UNK_DIM = "UNKNOWN"
local UNK_GEO = "??"
local environment_objects = {
"addons",
"build",
"partner",
"profile",
"settings",
"system"
}
local main_ping_objects = {
"addonDetails",
"addonHistograms",
"childPayloads", -- only present with e10s
"chromeHangs",
"fileIOReports",
"histograms",
"info",
"keyedHistograms",
"lateWrites",
"log",
"simpleMeasurements",
"slowSQL",
"slowSQLstartup",
"threadHangStats",
"UIMeasurements"
}
local function split_objects(root, section, objects)
if type(root) ~= "table" then return end
for i, name in ipairs(objects) do
if type(root[name]) == "table" then
local ok, json = pcall(cjson.encode, root[name])
if ok then
msg.Fields[string.format("%s.%s", section, name)] = json
root[name] = nil -- remove extracted objects
end
end
end
end
local function uncompress(payload)
local b1, b2 = string.byte(payload, 1, 2)
if b1 == 0x1f and b2 == 0x8b then -- test for gzip magic header bytes
local ok, result = pcall(gzip.decompress, payload)
if not ok then
return false, result
end
return true, result
end
return true, payload
end
local function sample(id, sampleRange)
if type(id) ~= "string" then
return nil
end
return hash.crc32(id) % sampleRange
end
function parse_creation_date(date)
if type(date) ~= "string" then return nil end
local t = dt.rfc3339:match(date)
if not t then
return nil
end
return dt.time_to_ns(t) -- The timezone of the ping has always zero UTC offset
end
function process_message()
-- Attempt to uncompress the payload if it is gzipped.
local payload = read_message("Payload")
local ok, json = uncompress(payload)
if not ok then return -1, json end
-- This size check should match the output_limit config param. We want to
-- check the size early to avoid parsing JSON if we don't have to.
if string.len(json) > 2097152 then
return -1, "Uncompressed Payload too large: " .. string.len(json)
end
-- Attempt to parse the payload as JSON.
local parsed
ok, parsed = pcall(cjson.decode, json)
if not ok then return -1, parsed end
-- Carry forward the dimensions from the submission URL Path. Overwrite
-- them later with values from the parsed JSON Payload if available.
-- These fields should match the ones specified in the namespace_config for
-- the "telemetry" endpoint of the HTTP Edge Server.
msg.Fields = { sourceName = "telemetry" }
msg.Fields.documentId = read_message("Fields[documentId]")
msg.Fields.docType = read_message("Fields[docType]")
msg.Fields.appName = read_message("Fields[appName]")
msg.Fields.appVersion = read_message("Fields[appVersion]")
msg.Fields.appUpdateChannel = read_message("Fields[appUpdateChannel]")
msg.Fields.appBuildId = read_message("Fields[appBuildId]")
if parsed.ver then
-- Old-style telemetry.
msg.Payload = json
msg.Fields.sourceVersion = tostring(parsed.ver)
local info = parsed.info
if type(info) ~= "table" then return -1, "missing info object" end
-- Get some more dimensions.
msg.Fields.docType = info.reason or UNK_DIM
msg.Fields.appName = info.appName or UNK_DIM
msg.Fields.appVersion = info.appVersion or UNK_DIM
msg.Fields.appUpdateChannel = info.appUpdateChannel or UNK_DIM
-- Do not want default values for these.
msg.Fields.appBuildId = info.appBuildID
msg.Fields.os = info.OS
msg.Fields.appVendor = info.vendor
msg.Fields.reason = info.reason
msg.Fields.clientId = parsed.clientID
elseif parsed.version then
-- New-style telemetry, see http://mzl.la/1zobT1S
-- pull out/verify the data/schema before any restructuring
local app = parsed.application
if type(app) ~= "table" then
return -1, "missing application object"
end
if type(parsed.payload.info) ~= "table" then
return -1, "missing info object"
end
msg.Fields.reason = parsed.payload.info.reason
msg.Fields.creationTimestamp = parse_creation_date(parsed.creationDate)
if not msg.Fields.creationTimestamp then
return -1, "missing creationDate"
end
if parsed.environment and
parsed.environment.system and
parsed.environment.system.os then
msg.Fields.os = parsed.environment.system.os.name
end
msg.Fields.sourceVersion = tostring(parsed.version)
msg.Fields.docType = parsed.type or UNK_DIM
-- Get some more dimensions.
msg.Fields.appName = app.name or UNK_DIM
msg.Fields.appVersion = app.version or UNK_DIM
msg.Fields.appUpdateChannel = app.channel or UNK_DIM
-- Do not want default values for these.
msg.Fields.appBuildId = app.buildId
msg.Fields.appVendor = app.vendor
msg.Fields.clientId = parsed.clientId
-- restructure the main ping message
if parsed.type == "main" then
split_objects(parsed.environment, "environment", environment_objects)
split_objects(parsed.payload, "payload", main_ping_objects)
local ok, json = pcall(cjson.encode, parsed) -- re-encode the remaining data
if not ok then return -1, json end
msg.Payload = json
else
msg.Payload = json
end
end
-- Carry forward more incoming fields.
msg.Fields.geoCountry = read_message("Fields[geoCountry]") or UNK_GEO
msg.Timestamp = read_message("Timestamp")
msg.Fields.Host = read_message("Fields[Host]")
msg.Fields.DNT = read_message("Fields[DNT]")
msg.Fields.submissionDate = os.date("%Y%m%d", msg.Timestamp / 1e9)
msg.Fields.sampleId = sample(msg.Fields.clientId, 100)
-- Send new message along.
local err
ok, err = pcall(inject_message, msg)
if not ok then
return -1, err
end
return 0
end
|
-- This Source Code Form is subject to the terms of the Mozilla Public
-- License, v. 2.0. If a copy of the MPL was not distributed with this
-- file, You can obtain one at http://mozilla.org/MPL/2.0/.
require "string"
require "cjson"
require "hash"
require "os"
local gzip = require "gzip"
local dt = require("date_time")
local msg = {
Timestamp = nil,
Type = "telemetry",
Payload = nil,
EnvVersion = 1
}
local UNK_DIM = "UNKNOWN"
local UNK_GEO = "??"
local environment_objects = {
"addons",
"build",
"partner",
"profile",
"settings",
"system"
}
local main_ping_objects = {
"addonDetails",
"addonHistograms",
"childPayloads", -- only present with e10s
"chromeHangs",
"fileIOReports",
"histograms",
"info",
"keyedHistograms",
"lateWrites",
"log",
"simpleMeasurements",
"slowSQL",
"slowSQLstartup",
"threadHangStats",
"UIMeasurements"
}
local function split_objects(root, section, objects)
if type(root) ~= "table" then return end
for i, name in ipairs(objects) do
if type(root[name]) == "table" then
local ok, json = pcall(cjson.encode, root[name])
if ok then
msg.Fields[string.format("%s.%s", section, name)] = json
root[name] = nil -- remove extracted objects
end
end
end
end
local function uncompress(payload)
local b1, b2 = string.byte(payload, 1, 2)
if b1 == 0x1f and b2 == 0x8b then -- test for gzip magic header bytes
local ok, result = pcall(gzip.decompress, payload)
if not ok then
return false, result
end
return true, result
end
return true, payload
end
local function sample(id, sampleRange)
if type(id) ~= "string" then
return nil
end
return hash.crc32(id) % sampleRange
end
function parse_creation_date(date)
if type(date) ~= "string" then return nil end
local t = dt.rfc3339:match(date)
if not t then
return nil
end
return dt.time_to_ns(t) -- The timezone of the ping has always zero UTC offset
end
function process_message()
-- Attempt to uncompress the payload if it is gzipped.
local payload = read_message("Payload")
local ok, json = uncompress(payload)
if not ok then return -1, json end
-- This size check should match the output_limit config param. We want to
-- check the size early to avoid parsing JSON if we don't have to.
if string.len(json) > 2097152 then
return -1, "Uncompressed Payload too large: " .. string.len(json)
end
-- Attempt to parse the payload as JSON.
local parsed
ok, parsed = pcall(cjson.decode, json)
if not ok then return -1, parsed end
-- Carry forward the dimensions from the submission URL Path. Overwrite
-- them later with values from the parsed JSON Payload if available.
-- These fields should match the ones specified in the namespace_config for
-- the "telemetry" endpoint of the HTTP Edge Server.
msg.Fields = { sourceName = "telemetry" }
msg.Fields.documentId = read_message("Fields[documentId]")
msg.Fields.docType = read_message("Fields[docType]")
msg.Fields.appName = read_message("Fields[appName]")
msg.Fields.appVersion = read_message("Fields[appVersion]")
msg.Fields.appUpdateChannel = read_message("Fields[appUpdateChannel]")
msg.Fields.appBuildId = read_message("Fields[appBuildId]")
if parsed.ver then
-- Old-style telemetry.
msg.Payload = json
msg.Fields.sourceVersion = tostring(parsed.ver)
local info = parsed.info
if type(info) ~= "table" then return -1, "missing info object" end
-- Get some more dimensions.
msg.Fields.docType = info.reason or UNK_DIM
msg.Fields.appName = info.appName or UNK_DIM
msg.Fields.appVersion = info.appVersion or UNK_DIM
msg.Fields.appUpdateChannel = info.appUpdateChannel or UNK_DIM
-- Do not want default values for these.
msg.Fields.appBuildId = info.appBuildID
msg.Fields.os = info.OS
msg.Fields.appVendor = info.vendor
msg.Fields.reason = info.reason
msg.Fields.clientId = parsed.clientID
elseif parsed.version then
-- New-style telemetry, see http://mzl.la/1zobT1S
-- pull out/verify the data/schema before any restructuring
local app = parsed.application
if type(app) ~= "table" then
return -1, "missing application object"
end
if type(parsed.payload) == "table" and
type(parsed.payload.info) == "table" then
msg.Fields.reason = parsed.payload.info.reason
end
msg.Fields.creationTimestamp = parse_creation_date(parsed.creationDate)
if not msg.Fields.creationTimestamp then
return -1, "missing creationDate"
end
if type(parsed.environment) == "table" and
type(parsed.environment.system) == "table" and
type(parsed.environment.system.os) == "table" then
msg.Fields.os = parsed.environment.system.os.name
end
msg.Fields.sourceVersion = tostring(parsed.version)
msg.Fields.docType = parsed.type or UNK_DIM
-- Get some more dimensions.
msg.Fields.appName = app.name or UNK_DIM
msg.Fields.appVersion = app.version or UNK_DIM
msg.Fields.appUpdateChannel = app.channel or UNK_DIM
-- Do not want default values for these.
msg.Fields.appBuildId = app.buildId
msg.Fields.appVendor = app.vendor
msg.Fields.clientId = parsed.clientId
-- restructure the main ping message
if parsed.type == "main" then
split_objects(parsed.environment, "environment", environment_objects)
split_objects(parsed.payload, "payload", main_ping_objects)
local ok, json = pcall(cjson.encode, parsed) -- re-encode the remaining data
if not ok then return -1, json end
msg.Payload = json
else
msg.Payload = json
end
end
-- Carry forward more incoming fields.
msg.Fields.geoCountry = read_message("Fields[geoCountry]") or UNK_GEO
msg.Timestamp = read_message("Timestamp")
msg.Fields.Host = read_message("Fields[Host]")
msg.Fields.DNT = read_message("Fields[DNT]")
msg.Fields.submissionDate = os.date("%Y%m%d", msg.Timestamp / 1e9)
msg.Fields.sampleId = sample(msg.Fields.clientId, 100)
-- Send new message along.
local err
ok, err = pcall(inject_message, msg)
if not ok then
return -1, err
end
return 0
end
|
Don't make the info object required
|
Don't make the info object required
- fix up the environment.system.os check to prevent termination
on bad data
|
Lua
|
mpl-2.0
|
sapohl/data-pipeline,sapohl/data-pipeline,mreid-moz/data-pipeline,nathwill/data-pipeline,whd/data-pipeline,mozilla-services/data-pipeline,mreid-moz/data-pipeline,kparlante/data-pipeline,sapohl/data-pipeline,nathwill/data-pipeline,kparlante/data-pipeline,mreid-moz/data-pipeline,whd/data-pipeline,kparlante/data-pipeline,sapohl/data-pipeline,acmiyaguchi/data-pipeline,acmiyaguchi/data-pipeline,mozilla-services/data-pipeline,mozilla-services/data-pipeline,acmiyaguchi/data-pipeline,nathwill/data-pipeline,mozilla-services/data-pipeline,whd/data-pipeline,whd/data-pipeline,kparlante/data-pipeline,acmiyaguchi/data-pipeline,nathwill/data-pipeline
|
7c940e3a2e8c38bdcd4522bc941ab1bd979be715
|
gumbo/ffi.lua
|
gumbo/ffi.lua
|
--[[
LuaJIT FFI/luaffi bindings for the Gumbo HTML5 parsing library.
Copyright (c) 2013 Craig Barnes
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
]]
local ffi = require "ffi"
local C = require "gumbo.cdef"
local ffi_string = ffi.string
local ffi_cast = ffi.cast
local tonumber = tonumber
local create_node
local have_tnew, tnew = pcall(require, "table.new")
if not have_tnew then
tnew = function(narr, nrec) return {} end
end
local typemap = {
[tonumber(C.GUMBO_NODE_DOCUMENT)] = "document",
[tonumber(C.GUMBO_NODE_ELEMENT)] = "element",
[tonumber(C.GUMBO_NODE_TEXT)] = "text",
[tonumber(C.GUMBO_NODE_CDATA)] = "cdata",
[tonumber(C.GUMBO_NODE_COMMENT)] = "comment",
[tonumber(C.GUMBO_NODE_WHITESPACE)] = "whitespace",
__index = function() error "Error: invalid node type" end
}
local quirksmap = {
[tonumber(C.GUMBO_DOCTYPE_NO_QUIRKS)] = "no-quirks",
[tonumber(C.GUMBO_DOCTYPE_QUIRKS)] = "quirks",
[tonumber(C.GUMBO_DOCTYPE_LIMITED_QUIRKS)] = "limited-quirks",
__index = function() error "Error: invalid quirks mode" end
}
setmetatable(typemap, typemap)
setmetatable(quirksmap, quirksmap)
local function get_attributes(attrs)
if attrs.length ~= 0 then
local t = {}
for i = 0, attrs.length - 1 do
local attr = ffi_cast("GumboAttribute*", attrs.data[i])
t[ffi_string(attr.name)] = ffi_string(attr.value)
end
return t
end
end
local function get_tag_name(element)
if element.tag == C.GUMBO_TAG_UNKNOWN then
local original_tag = element.original_tag
C.gumbo_tag_from_original_text(original_tag)
return ffi_string(original_tag.data, original_tag.length)
else
return ffi_string(C.gumbo_normalized_tagname(element.tag))
end
end
local function get_parse_flags(flags)
if flags ~= C.GUMBO_INSERTION_NORMAL then
-- FIXME: Return the correct table of flags instead of this hack
local t = {
insertion_by_parser = true,
insertion_implied = true,
implicit_end_tag = true
}
return t
end
end
local function create_document(node)
local document = node.v.document
local length = document.children.length
local t = tnew(length, 7)
t.type = "document"
t.name = ffi_string(document.name)
t.public_identifier = ffi_string(document.public_identifier)
t.system_identifier = ffi_string(document.system_identifier)
t.has_doctype = document.has_doctype
t.quirks_mode = quirksmap[tonumber(document.doc_type_quirks_mode)]
for i = 0, length - 1 do
t[i+1] = create_node(ffi_cast("GumboNode*", document.children.data[i]))
end
return t
end
local function create_element(node)
local element = node.v.element
local length = element.children.length
local t = tnew(length, 7)
t.type = "element"
t.tag = get_tag_name(element)
t.line = element.start_pos.line
t.column = element.start_pos.column
t.offset = element.start_pos.offset
t.parse_flags = get_parse_flags(node.parse_flags)
t.attr = get_attributes(element.attributes)
for i = 0, length - 1 do
t[i+1] = create_node(ffi_cast("GumboNode*", element.children.data[i]))
end
return t
end
local function create_text(node)
local text = node.v.text
return {
type = typemap[tonumber(node.type)],
text = ffi_string(text.text),
line = text.start_pos.line,
column = text.start_pos.column,
offset = text.start_pos.offset
}
end
create_node = function(node)
if node.type == C.GUMBO_NODE_ELEMENT then
return create_element(node)
else
return create_text(node)
end
end
local function parse(input, tab_stop)
local options = ffi.new("GumboOptions")
ffi.copy(options, C.kGumboDefaultOptions, ffi.sizeof("GumboOptions"))
-- The above is for the benefit of luaffi support. LuaJIT allows
-- using a copy constructor with ffi.new, as in:
-- local options = ffi.new("GumboOptions", C.kGumboDefaultOptions)
-- TODO: use the cleaner syntax if/when luaffi supports it
options.tab_stop = tab_stop or 8
local output = C.gumbo_parse_with_options(options, input, #input)
local document = create_document(output.document)
document.root = document[output.root.index_within_parent + 1]
C.gumbo_destroy_output(options, output)
return document
end
return {
_FFI = true,
parse = parse
}
|
--[[
LuaJIT FFI/luaffi bindings for the Gumbo HTML5 parsing library.
Copyright (c) 2013 Craig Barnes
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
]]
local ffi = require "ffi"
local C = require "gumbo.cdef"
local ffi_string = ffi.string
local ffi_cast = ffi.cast
local tonumber = tonumber
local create_node
local have_tnew, tnew = pcall(require, "table.new")
tnew = have_tnew and tnew or function(narr, nrec) return {} end
local have_bit, bit = pcall(require, "bit")
local testflag
if have_bit == true then
testflag = function(set, flag)
return bit.band(set, flag) ~= 0
end
else
testflag = function(set, flag)
return set % (2 * flag) >= flag
end
end
local typemap = {
[tonumber(C.GUMBO_NODE_DOCUMENT)] = "document",
[tonumber(C.GUMBO_NODE_ELEMENT)] = "element",
[tonumber(C.GUMBO_NODE_TEXT)] = "text",
[tonumber(C.GUMBO_NODE_CDATA)] = "cdata",
[tonumber(C.GUMBO_NODE_COMMENT)] = "comment",
[tonumber(C.GUMBO_NODE_WHITESPACE)] = "whitespace",
__index = function() error "Error: invalid node type" end
}
local quirksmap = {
[tonumber(C.GUMBO_DOCTYPE_NO_QUIRKS)] = "no-quirks",
[tonumber(C.GUMBO_DOCTYPE_QUIRKS)] = "quirks",
[tonumber(C.GUMBO_DOCTYPE_LIMITED_QUIRKS)] = "limited-quirks",
__index = function() error "Error: invalid quirks mode" end
}
local flagsmap = {
insertion_by_parser = C.GUMBO_INSERTION_BY_PARSER,
implicit_end_tag = C.GUMBO_INSERTION_IMPLICIT_END_TAG,
insertion_implied = C.GUMBO_INSERTION_IMPLIED,
converted_from_end_tag = C.GUMBO_INSERTION_CONVERTED_FROM_END_TAG,
insertion_from_isindex = C.GUMBO_INSERTION_FROM_ISINDEX,
insertion_from_image = C.GUMBO_INSERTION_FROM_IMAGE,
reconstructed_formatting_element = C.GUMBO_INSERTION_RECONSTRUCTED_FORMATTING_ELEMENT,
adoption_agency_cloned = C.GUMBO_INSERTION_ADOPTION_AGENCY_CLONED,
adoption_agency_moved = C.GUMBO_INSERTION_ADOPTION_AGENCY_MOVED,
foster_parented = C.GUMBO_INSERTION_FOSTER_PARENTED
}
setmetatable(typemap, typemap)
setmetatable(quirksmap, quirksmap)
local function get_attributes(attrs)
if attrs.length ~= 0 then
local t = {}
for i = 0, attrs.length - 1 do
local attr = ffi_cast("GumboAttribute*", attrs.data[i])
t[ffi_string(attr.name)] = ffi_string(attr.value)
end
return t
end
end
local function get_tag_name(element)
if element.tag == C.GUMBO_TAG_UNKNOWN then
local original_tag = element.original_tag
C.gumbo_tag_from_original_text(original_tag)
return ffi_string(original_tag.data, original_tag.length)
else
return ffi_string(C.gumbo_normalized_tagname(element.tag))
end
end
local function get_parse_flags(parse_flags)
if parse_flags ~= C.GUMBO_INSERTION_NORMAL then
parse_flags = tonumber(parse_flags)
local t = tnew(0, 1)
for field, flag in pairs(flagsmap) do
if testflag(parse_flags, flag) then
t[field] = true
end
end
return t
end
end
local function create_document(node)
local document = node.v.document
local length = document.children.length
local t = tnew(length, 7)
t.type = "document"
t.name = ffi_string(document.name)
t.public_identifier = ffi_string(document.public_identifier)
t.system_identifier = ffi_string(document.system_identifier)
t.has_doctype = document.has_doctype
t.quirks_mode = quirksmap[tonumber(document.doc_type_quirks_mode)]
for i = 0, length - 1 do
t[i+1] = create_node(ffi_cast("GumboNode*", document.children.data[i]))
end
return t
end
local function create_element(node)
local element = node.v.element
local length = element.children.length
local t = tnew(length, 7)
t.type = "element"
t.tag = get_tag_name(element)
t.line = element.start_pos.line
t.column = element.start_pos.column
t.offset = element.start_pos.offset
t.parse_flags = get_parse_flags(node.parse_flags)
t.attr = get_attributes(element.attributes)
for i = 0, length - 1 do
t[i+1] = create_node(ffi_cast("GumboNode*", element.children.data[i]))
end
return t
end
local function create_text(node)
local text = node.v.text
return {
type = typemap[tonumber(node.type)],
text = ffi_string(text.text),
line = text.start_pos.line,
column = text.start_pos.column,
offset = text.start_pos.offset
}
end
create_node = function(node)
if node.type == C.GUMBO_NODE_ELEMENT then
return create_element(node)
else
return create_text(node)
end
end
local function parse(input, tab_stop)
local options = ffi.new("GumboOptions")
ffi.copy(options, C.kGumboDefaultOptions, ffi.sizeof("GumboOptions"))
-- The above is for the benefit of luaffi support. LuaJIT allows
-- using a copy constructor with ffi.new, as in:
-- local options = ffi.new("GumboOptions", C.kGumboDefaultOptions)
-- TODO: use the cleaner syntax if/when luaffi supports it
options.tab_stop = tab_stop or 8
local output = C.gumbo_parse_with_options(options, input, #input)
local document = create_document(output.document)
document.root = document[output.root.index_within_parent + 1]
C.gumbo_destroy_output(options, output)
return document
end
return {
_FFI = true,
parse = parse
}
|
Fix get_parse_flags function in gumbo/ffi.lua
|
Fix get_parse_flags function in gumbo/ffi.lua
|
Lua
|
apache-2.0
|
craigbarnes/lua-gumbo,craigbarnes/lua-gumbo,craigbarnes/lua-gumbo
|
5becf8cd9f60ce738b2f6d08ae5ff7262b28c6da
|
build/LLVM.lua
|
build/LLVM.lua
|
-- Setup the LLVM dependency directories
LLVMRootDir = "../../deps/llvm/"
LLVMBuildDir = "../../deps/llvm/build/"
-- TODO: Search for available system dependencies
function SetupLLVMIncludes()
local c = configuration()
includedirs
{
path.join(LLVMRootDir, "include"),
path.join(LLVMRootDir, "tools/clang/include"),
path.join(LLVMRootDir, "tools/clang/lib"),
path.join(LLVMBuildDir, "include"),
path.join(LLVMBuildDir, "tools/clang/include"),
}
configuration(c)
end
function SetupLLVMLibs()
local c = configuration()
libdirs { path.join(LLVMBuildDir, "lib") }
configuration { "Debug", "vs*" }
libdirs { path.join(LLVMBuildDir, "Debug/lib") }
configuration { "Release", "vs*" }
libdirs { path.join(LLVMBuildDir, "RelWithDebInfo/lib") }
configuration "not vs*"
buildoptions { "-fpermissive" }
defines { "__STDC_CONSTANT_MACROS", "__STDC_LIMIT_MACROS" }
configuration "macosx"
links { "c++", "curses", "pthread", "z" }
configuration "*"
links
{
"LLVMAnalysis",
"LLVMAsmParser",
"LLVMBitReader",
"LLVMBitWriter",
"LLVMCodeGen",
"LLVMCore",
"LLVMipa",
"LLVMipo",
"LLVMInstCombine",
"LLVMInstrumentation",
"LLVMIRReader",
"LLVMLinker",
"LLVMMC",
"LLVMMCParser",
"LLVMObjCARCOpts",
"LLVMObject",
"LLVMOption",
"LLVMScalarOpts",
"LLVMSupport",
"LLVMTarget",
"LLVMTransformUtils",
"LLVMVectorize",
"LLVMX86AsmParser",
"LLVMX86AsmPrinter",
"LLVMX86Desc",
"LLVMX86Info",
"LLVMX86Utils",
"clangAnalysis",
"clangAST",
"clangBasic",
"clangCodeGen",
"clangDriver",
"clangEdit",
"clangFrontend",
"clangLex",
"clangParse",
"clangSema",
"clangSerialization",
"clangIndex",
}
StaticLinksOpt { "LLVMProfileData" }
configuration(c)
end
|
-- Setup the LLVM dependency directories
LLVMRootDir = "../../deps/llvm/"
LLVMBuildDir = "../../deps/llvm/build/"
-- TODO: Search for available system dependencies
function SetupLLVMIncludes()
local c = configuration()
includedirs
{
path.join(LLVMRootDir, "include"),
path.join(LLVMRootDir, "tools/clang/include"),
path.join(LLVMRootDir, "tools/clang/lib"),
path.join(LLVMBuildDir, "include"),
path.join(LLVMBuildDir, "tools/clang/include"),
}
configuration(c)
end
function SetupLLVMLibs()
local c = configuration()
libdirs { path.join(LLVMBuildDir, "lib") }
configuration { "Debug", "vs*" }
libdirs { path.join(LLVMBuildDir, "Debug/lib") }
configuration { "Release", "vs*" }
libdirs { path.join(LLVMBuildDir, "RelWithDebInfo/lib") }
configuration "not vs*"
defines { "__STDC_CONSTANT_MACROS", "__STDC_LIMIT_MACROS" }
configuration "macosx"
links { "c++", "curses", "pthread", "z" }
configuration "*"
links
{
"LLVMAnalysis",
"LLVMAsmParser",
"LLVMBitReader",
"LLVMBitWriter",
"LLVMCodeGen",
"LLVMCore",
"LLVMipa",
"LLVMipo",
"LLVMInstCombine",
"LLVMInstrumentation",
"LLVMIRReader",
"LLVMLinker",
"LLVMMC",
"LLVMMCParser",
"LLVMObjCARCOpts",
"LLVMObject",
"LLVMOption",
"LLVMScalarOpts",
"LLVMSupport",
"LLVMTarget",
"LLVMTransformUtils",
"LLVMVectorize",
"LLVMX86AsmParser",
"LLVMX86AsmPrinter",
"LLVMX86Desc",
"LLVMX86Info",
"LLVMX86Utils",
"clangAnalysis",
"clangAST",
"clangBasic",
"clangCodeGen",
"clangDriver",
"clangEdit",
"clangFrontend",
"clangLex",
"clangParse",
"clangSema",
"clangSerialization",
"clangIndex",
}
StaticLinksOpt { "LLVMProfileData" }
configuration(c)
end
|
build: remove -fpermissive from non-VS builds
|
build: remove -fpermissive from non-VS builds
Now that the warnings have been fixed, we no longer need -fpermissive to
compile CppParser with gcc.
Signed-off-by: Tomi Valkeinen <e1ca4dbb8be1acaf20734fecd2da10ed1d46a9bb@iki.fi>
|
Lua
|
mit
|
ktopouzi/CppSharp,ddobrev/CppSharp,ktopouzi/CppSharp,txdv/CppSharp,genuinelucifer/CppSharp,Samana/CppSharp,mohtamohit/CppSharp,xistoso/CppSharp,mono/CppSharp,xistoso/CppSharp,Samana/CppSharp,nalkaro/CppSharp,u255436/CppSharp,KonajuGames/CppSharp,KonajuGames/CppSharp,inordertotest/CppSharp,mono/CppSharp,Samana/CppSharp,zillemarco/CppSharp,mono/CppSharp,ktopouzi/CppSharp,mono/CppSharp,mydogisbox/CppSharp,genuinelucifer/CppSharp,inordertotest/CppSharp,Samana/CppSharp,mydogisbox/CppSharp,imazen/CppSharp,zillemarco/CppSharp,nalkaro/CppSharp,u255436/CppSharp,mydogisbox/CppSharp,SonyaSa/CppSharp,ddobrev/CppSharp,KonajuGames/CppSharp,imazen/CppSharp,u255436/CppSharp,inordertotest/CppSharp,ddobrev/CppSharp,txdv/CppSharp,txdv/CppSharp,ktopouzi/CppSharp,mohtamohit/CppSharp,genuinelucifer/CppSharp,genuinelucifer/CppSharp,KonajuGames/CppSharp,mono/CppSharp,nalkaro/CppSharp,zillemarco/CppSharp,ktopouzi/CppSharp,txdv/CppSharp,u255436/CppSharp,imazen/CppSharp,nalkaro/CppSharp,zillemarco/CppSharp,imazen/CppSharp,SonyaSa/CppSharp,txdv/CppSharp,zillemarco/CppSharp,SonyaSa/CppSharp,nalkaro/CppSharp,mohtamohit/CppSharp,mohtamohit/CppSharp,u255436/CppSharp,xistoso/CppSharp,mydogisbox/CppSharp,SonyaSa/CppSharp,inordertotest/CppSharp,mohtamohit/CppSharp,KonajuGames/CppSharp,xistoso/CppSharp,inordertotest/CppSharp,ddobrev/CppSharp,imazen/CppSharp,mydogisbox/CppSharp,genuinelucifer/CppSharp,SonyaSa/CppSharp,mono/CppSharp,xistoso/CppSharp,Samana/CppSharp,ddobrev/CppSharp
|
581373ba992cbd666391ca5ab9d9e2698e7f6cde
|
Standings.lua
|
Standings.lua
|
local mod = EPGP:NewModule("EPGP_Standings", "AceDB-2.0", "AceEvent-2.0")
mod:RegisterDB("EPGP_Standings_DB")
mod:RegisterDefaults("profile", {
data = { },
detached_data = { },
group_by_class = false,
show_alts = false,
raid_mode = true
})
local T = AceLibrary("Tablet-2.0")
local D = AceLibrary("Dewdrop-2.0")
local C = AceLibrary("Crayon-2.0")
local BC = AceLibrary("Babble-Class-2.2")
local function RaidIterator(obj, i)
local name = GetRaidRosterInfo(i)
if not name then return end
return i+1, name
end
local function GuildIterator(obj, i)
local name
repeat
name = GetGuildRosterInfo(i)
-- Handle dummies
if obj.cache:IsDummy(name) then
name = obj.cache.db.profile.dummies[name]
end
i = i+1
until obj.db.profile.show_alts or not obj.cache:IsAlt(name)
if not name then return end
return i, name
end
function mod:GetStandingsIterator()
if (self.db.profile.raid_mode and UnitInRaid("player")) then
return RaidIterator, self, 1
else
return GuildIterator, self, 1
end
end
function mod:OnInitialize()
self.cache = EPGP:GetModule("EPGP_Cache")
StaticPopupDialogs["EPGP_Standings_HTML"] = {
text = "HTML table of the current EPGP standings.",
hasEditBox = 1,
OnShow = function()
local text = "<table>"..
"<caption>EPGP Standings</caption>"..
"<tr><th>Name</th><th>Class</th><th>EP</th><th>GP</th><th>PR</th></tr>"
for k,v in pairs(self.standings) do
local name, class, ep, gp, pr = unpack(v)
text = text..string.format(
"<tr><td>%s</td><td><spam style=\"color:#%s\">%s</td><td>%d</td><td>%d</td><td>%.4g</td></tr>",
name, BC:GetHexColor(class), class, ep, gp, pr)
end
text = text.."</table>"
local editBox = getglobal(this:GetName().."EditBox")
editBox:SetText(text)
editBox:HighlightText()
editBox:SetFocus()
end,
EditBoxOnEnterPressed = function()
this:GetParent():Hide()
end,
EditBoxOnEscapePressed = function()
this:GetParent():Hide();
end,
timeout = 0,
exclusive = 1,
whileDead = 1,
hideOnEscape = 1,
}
end
function mod:OnEnable()
self:RegisterEvent("EPGP_CACHE_UPDATE")
self:RegisterEvent("RAID_ROSTER_UPDATE")
if not T:IsRegistered("EPGP_Standings") then
T:Register("EPGP_Standings",
"children", function()
T:SetTitle("EPGP Standings")
T:SetHint("EP: Effort Points, GP: Gear Points, PR: Priority")
self:OnTooltipUpdate()
end,
"data", self.db.profile.data,
"detachedData", self.db.profile.detached_data,
"showTitleWhenDetached", true,
"showHintWhenDetached", true,
"cantAttach", true,
"menu", function()
D:AddLine(
"text", "Group by class",
"tooltipText", "Toggles grouping members by class.",
"checked", self.db.profile.group_by_class,
"func", function() self.db.profile.group_by_class = not self.db.profile.group_by_class; self:EPGP_CACHE_UPDATE() end
)
D:AddLine(
"text", "Show Alts",
"tooltipText", "Toggles listing of Alts in standings.",
"checked", self.db.profile.show_alts or self.db.profile.raid_mode,
"disabled", self.db.profile.raid_mode,
"func", function() self.db.profile.show_alts = not self.db.profile.show_alts; self:EPGP_CACHE_UPDATE() end
)
D:AddLine(
"text", "Raid Mode",
"tooltipText", "Toggles listing only raid members (if in raid).",
"checked", self.db.profile.raid_mode,
"func", function() self.db.profile.raid_mode = not self.db.profile.raid_mode; self:EPGP_CACHE_UPDATE() end
)
D:AddLine(
"text", "Export to HTML",
"tooltipText", "Exports current standings window to an HTML table.",
"func", function() StaticPopup_Show("EPGP_Standings_HTML") end
)
end
)
end
if not T:IsAttached("EPGP_Standings") then
T:Open("EPGP_Standings")
end
end
function mod:OnDisable()
T:Close("EPGP_Standings")
end
function mod:EPGP_CACHE_UPDATE()
self.standings = self:BuildStandingsTable()
T:Refresh("EPGP_Standings")
end
function mod:RAID_ROSTER_UPDATE()
if self.db.profile.raid_mode then
T:Refresh("EPGP_Standings")
end
end
function mod:Toggle()
if T:IsAttached("EPGP_Standings") then
T:Detach("EPGP_Standings")
if (T:IsLocked("EPGP_Standings")) then
T:ToggleLocked("EPGP_Standings")
end
else
T:Attach("EPGP_Standings")
end
end
-- Builds a standings table with record:
-- name, class, EP, GP, PR
-- and sorted by PR with members with EP < MIN_EP at the end
function mod:BuildStandingsTable()
local t = {}
for i,name in self:GetStandingsIterator() do
local ep, tep, gp, tgp = self.cache:GetMemberEPGP(name)
local rank, rankIndex, level, class, zone, note, officernote, online, status = self.cache:GetMemberInfo(name)
if ep and tep and gp and tgp then
local EP,GP = tep + ep, tgp + gp
local PR = GP == 0 and EP or EP/GP
table.insert(t, { name, class, EP, GP, PR })
end
end
-- Normal sorting function
local function SortPR(a,b)
local a_low = a[3] < self.cache.db.profile.min_eps
local b_low = b[3] < self.cache.db.profile.min_eps
if a_low and not b_low then return false
elseif not a_low and b_low then return true
else return a[5] > b[5] end
end
if (self.db.profile.group_by_class) then
table.sort(t, function(a,b)
if (a[2] ~= b[2]) then return a[2] < b[2]
else return SortPR(a, b) end
end)
else
table.sort(t, SortPR)
end
return t
end
function mod:OnTooltipUpdate()
if not self.standings then
self.standings = self:BuildStandingsTable()
end
local cat = T:AddCategory(
"columns", 4,
"text", C:Red("Name"), "child_textR", 1, "child_textG", 1, "child_textB", 1, "child_justify", "LEFT",
"text2", C:Red("EP"), "child_text2R", 1, "child_text2G", 1, "child_text2B", 1, "child_justify4", "RIGHT",
"text3", C:Red("GP"), "child_text3R", 1, "child_text3G", 1, "child_text3B", 1, "child_justify5", "RIGHT",
"text4", C:Red("PR"), "child_text4R", 1, "child_text4G", 1, "child_text4B", 0, "child_justify6", "RIGHT"
)
for k,v in pairs(self.standings) do
local name, class, ep, gp, pr = unpack(v)
local ep_str, gp_str, pr_str = string.format("%d", ep), string.format("%d", gp), string.format("%.4g", pr)
cat:AddLine(
"text", C:Colorize(BC:GetHexColor(class), name),
"text2", ep < self.cache.db.profile.min_eps and C:Colorize("7f7f7f", ep_str) or ep_str,
"text3", ep < self.cache.db.profile.min_eps and C:Colorize("7f7f7f", gp_str) or gp_str,
"text4", ep < self.cache.db.profile.min_eps and C:Colorize("7f7f00", pr_str) or pr_str
)
end
end
|
local mod = EPGP:NewModule("EPGP_Standings", "AceDB-2.0", "AceEvent-2.0")
mod:RegisterDB("EPGP_Standings_DB")
mod:RegisterDefaults("profile", {
data = { },
detached_data = { },
group_by_class = false,
show_alts = false,
raid_mode = true
})
local T = AceLibrary("Tablet-2.0")
local D = AceLibrary("Dewdrop-2.0")
local C = AceLibrary("Crayon-2.0")
local BC = AceLibrary("Babble-Class-2.2")
local function RaidIterator(obj, i)
local name = GetRaidRosterInfo(i)
if not name then return end
return i+1, name
end
local function GuildIterator(obj, i)
local name
repeat
name = GetGuildRosterInfo(i)
-- Handle dummies
if obj.cache:IsDummy(name) then
name = obj.cache.db.profile.dummies[name]
end
i = i+1
until obj.db.profile.show_alts or not obj.cache:IsAlt(name)
if not name then return end
return i, name
end
function mod:GetStandingsIterator()
if (self.db.profile.raid_mode and UnitInRaid("player")) then
return RaidIterator, self, 1
else
return GuildIterator, self, 1
end
end
function mod:OnInitialize()
self.cache = EPGP:GetModule("EPGP_Cache")
StaticPopupDialogs["EPGP_Standings_HTML"] = {
text = "HTML table of the current EPGP standings.",
hasEditBox = 1,
OnShow = function()
local text = "<table id=\"epgp-standings\">"..
"<caption>EPGP Standings</caption>"..
"<tr><th>Name</th><th>Class</th><th>EP</th><th>GP</th><th>PR</th></tr>"
for k,v in pairs(self.standings) do
local name, class, ep, gp, pr = unpack(v)
text = text..string.format(
"<tr><td class=\"%s\">%s</td><td class=\"%s\">%s</td><td>%d</td><td>%d</td><td>%.4g</td></tr>",
class, name, class, class, ep, gp, pr)
end
text = text.."</table>"
local editBox = getglobal(this:GetName().."EditBox")
editBox:SetText(text)
editBox:HighlightText()
editBox:SetFocus()
end,
EditBoxOnEnterPressed = function()
this:GetParent():Hide()
end,
EditBoxOnEscapePressed = function()
this:GetParent():Hide();
end,
timeout = 0,
exclusive = 1,
whileDead = 1,
hideOnEscape = 1,
}
end
function mod:OnEnable()
self:RegisterEvent("EPGP_CACHE_UPDATE")
self:RegisterEvent("RAID_ROSTER_UPDATE")
if not T:IsRegistered("EPGP_Standings") then
T:Register("EPGP_Standings",
"children", function()
T:SetTitle("EPGP Standings")
T:SetHint("EP: Effort Points, GP: Gear Points, PR: Priority")
self:OnTooltipUpdate()
end,
"data", self.db.profile.data,
"detachedData", self.db.profile.detached_data,
"showTitleWhenDetached", true,
"showHintWhenDetached", true,
"cantAttach", true,
"menu", function()
D:AddLine(
"text", "Group by class",
"tooltipText", "Toggles grouping members by class.",
"checked", self.db.profile.group_by_class,
"func", function() self.db.profile.group_by_class = not self.db.profile.group_by_class; self:EPGP_CACHE_UPDATE() end
)
D:AddLine(
"text", "Show Alts",
"tooltipText", "Toggles listing of Alts in standings.",
"checked", self.db.profile.show_alts or self.db.profile.raid_mode,
"disabled", self.db.profile.raid_mode,
"func", function() self.db.profile.show_alts = not self.db.profile.show_alts; self:EPGP_CACHE_UPDATE() end
)
D:AddLine(
"text", "Raid Mode",
"tooltipText", "Toggles listing only raid members (if in raid).",
"checked", self.db.profile.raid_mode,
"func", function() self.db.profile.raid_mode = not self.db.profile.raid_mode; self:EPGP_CACHE_UPDATE() end
)
D:AddLine(
"text", "Export to HTML",
"tooltipText", "Exports current standings window to an HTML table.",
"func", function() StaticPopup_Show("EPGP_Standings_HTML") end
)
end
)
end
if not T:IsAttached("EPGP_Standings") then
T:Open("EPGP_Standings")
end
end
function mod:OnDisable()
T:Close("EPGP_Standings")
end
function mod:EPGP_CACHE_UPDATE()
self.standings = self:BuildStandingsTable()
T:Refresh("EPGP_Standings")
end
function mod:RAID_ROSTER_UPDATE()
if self.db.profile.raid_mode then
T:Refresh("EPGP_Standings")
end
end
function mod:Toggle()
if T:IsAttached("EPGP_Standings") then
T:Detach("EPGP_Standings")
if (T:IsLocked("EPGP_Standings")) then
T:ToggleLocked("EPGP_Standings")
end
else
T:Attach("EPGP_Standings")
end
end
-- Builds a standings table with record:
-- name, class, EP, GP, PR
-- and sorted by PR with members with EP < MIN_EP at the end
function mod:BuildStandingsTable()
local t = {}
for i,name in self:GetStandingsIterator() do
local ep, tep, gp, tgp = self.cache:GetMemberEPGP(name)
local rank, rankIndex, level, class, zone, note, officernote, online, status = self.cache:GetMemberInfo(name)
if ep and tep and gp and tgp then
local EP,GP = tep + ep, tgp + gp
local PR = GP == 0 and EP or EP/GP
table.insert(t, { name, class, EP, GP, PR })
end
end
-- Normal sorting function
local function SortPR(a,b)
local a_low = a[3] < self.cache.db.profile.min_eps
local b_low = b[3] < self.cache.db.profile.min_eps
if a_low and not b_low then return false
elseif not a_low and b_low then return true
else return a[5] > b[5] end
end
if (self.db.profile.group_by_class) then
table.sort(t, function(a,b)
if (a[2] ~= b[2]) then return a[2] < b[2]
else return SortPR(a, b) end
end)
else
table.sort(t, SortPR)
end
return t
end
function mod:OnTooltipUpdate()
if not self.standings then
self.standings = self:BuildStandingsTable()
end
local cat = T:AddCategory(
"columns", 4,
"text", C:Red("Name"), "child_textR", 1, "child_textG", 1, "child_textB", 1, "child_justify", "LEFT",
"text2", C:Red("EP"), "child_text2R", 1, "child_text2G", 1, "child_text2B", 1, "child_justify4", "RIGHT",
"text3", C:Red("GP"), "child_text3R", 1, "child_text3G", 1, "child_text3B", 1, "child_justify5", "RIGHT",
"text4", C:Red("PR"), "child_text4R", 1, "child_text4G", 1, "child_text4B", 0, "child_justify6", "RIGHT"
)
for k,v in pairs(self.standings) do
local name, class, ep, gp, pr = unpack(v)
local ep_str, gp_str, pr_str = string.format("%d", ep), string.format("%d", gp), string.format("%.4g", pr)
cat:AddLine(
"text", C:Colorize(BC:GetHexColor(class), name),
"text2", ep < self.cache.db.profile.min_eps and C:Colorize("7f7f7f", ep_str) or ep_str,
"text3", ep < self.cache.db.profile.min_eps and C:Colorize("7f7f7f", gp_str) or gp_str,
"text4", ep < self.cache.db.profile.min_eps and C:Colorize("7f7f00", pr_str) or pr_str
)
end
end
|
Fix issue 59. Now the table has id="epgp-standings" and each tr tag has a specified class="wow-class" for use with CSS to style the epgp standings.
|
Fix issue 59. Now the table has id="epgp-standings" and each tr tag has a specified class="wow-class" for use with CSS to style the epgp standings.
|
Lua
|
bsd-3-clause
|
protomech/epgp-dkp-reloaded,sheldon/epgp,protomech/epgp-dkp-reloaded,ceason/epgp-tfatf,hayword/tfatf_epgp,sheldon/epgp,hayword/tfatf_epgp,ceason/epgp-tfatf
|
5fa5807cbbf745919524b7c0fa7dde4d8da219b5
|
src/program/snabbvmx/lwaftr/lwaftr.lua
|
src/program/snabbvmx/lwaftr/lwaftr.lua
|
module(..., package.seeall)
local config = require("core.config")
local constants = require("apps.lwaftr.constants")
local ingress_drop_monitor = require("lib.timers.ingress_drop_monitor")
local intel10g = require("apps.intel.intel10g")
local lib = require("core.lib")
local counters = require("program.lwaftr.counters")
local lwtypes = require("apps.lwaftr.lwtypes")
local lwutil = require("apps.lwaftr.lwutil")
local setup = require("program.snabbvmx.lwaftr.setup")
local shm = require("core.shm")
local fatal, file_exists = lwutil.fatal, lwutil.file_exists
local DEFAULT_MTU = 9500
local function show_usage (exit_code)
print(require("program.snabbvmx.lwaftr.README_inc"))
main.exit(exit_code)
end
function parse_args (args)
if #args == 0 then show_usage(1) end
local conf_file, id, pci, mac, sock_path, mirror_id
local opts = { verbosity = 0 }
local handlers = {}
function handlers.v () opts.verbosity = opts.verbosity + 1 end
function handlers.D (arg)
opts.duration = assert(tonumber(arg), "Duration must be a number")
end
function handlers.c(arg)
conf_file = arg
if not arg then
fatal("Argument '--conf' was not set")
end
if not file_exists(conf_file) then
print(("Warning: config file %s not found"):format(conf_file))
end
end
function handlers.i(arg)
id = arg
if not arg then
fatal("Argument '--id' was not set")
end
end
function handlers.p(arg)
pci = arg
if not arg then
fatal("Argument '--pci' was not set")
end
end
function handlers.m(arg)
mac = arg
if not arg then
fatal("Argument '--mac' was not set")
end
end
function handlers.s(arg)
sock_path = arg
if not arg then
fatal("Argument '--sock' was not set")
end
end
function handlers.mirror (arg)
mirror_id = arg
end
function handlers.h() show_usage(0) end
lib.dogetopt(args, handlers, "c:s:i:p:m:vD:h", {
["conf"] = "c", ["sock"] = "s", ["id"] = "i", ["pci"] = "p", ["mac"] = "m",
["mirror"] = 1, verbose = "v", duration = "D", help = "h" })
return opts, conf_file, id, pci, mac, sock_path, mirror_id
end
local function effective_vlan (conf, external_interface, internal_interface)
if conf.settings and conf.settings.vlan then
return conf.settings.vlan
end
if external_interface.vlan_tag then
if external_interface.vlan_tag == internal_interface.vlan_tag then
return external_interface.vlan_tag
end
return {v4_vlan_tag = external_interface.vlan_tag,
v6_vlan_tag = internal_interface.vlan_tag}
end
return false
end
function run(args)
local opts, conf_file, id, pci, mac, sock_path, mirror_id = parse_args(args)
local conf, lwconf
local external_interface, internal_interface
local ring_buffer_size = 2048
local ingress_drop_action = "flush"
local ingress_drop_threshold = 100000
local ingress_drop_interval = 1e6
local ingress_drop_wait = 20
if file_exists(conf_file) then
conf = lib.load_conf(conf_file)
if not file_exists(conf.lwaftr) then
-- Search in main config file.
conf.lwaftr = lib.dirname(conf_file).."/"..conf.lwaftr
end
if not file_exists(conf.lwaftr) then
fatal(("lwAFTR conf file '%s' not found"):format(conf.lwaftr))
end
lwconf = setup.read_config(conf.lwaftr)
external_interface = lwconf.softwire_config.external_interface
internal_interface = lwconf.softwire_config.internal_interface
-- If one interface has vlan tags, the other one should as well.
assert((not external_interface.vlan_tag) == (not internal_interface.vlan_tag))
else
print(("Interface '%s' set to passthrough mode."):format(id))
ring_buffer_size = 1024
conf = {settings = {}}
end
if conf.settings then
if conf.settings.ingress_drop_monitor then
ingress_drop_action = conf.settings.ingress_drop_monitor
if ingress_drop_action == 'off' then
ingress_drop_action = nil
end
end
if conf.settings.ingress_drop_threshold then
ingress_drop_threshold = conf.settings.ingress_drop_threshold
end
if conf.settings.ingress_drop_interval then
ingress_drop_interval = conf.settings.ingress_drop_interval
end
if conf.settings.ingress_drop_wait then
ingress_drop_wait = conf.settings.ingress_drop_wait
end
end
intel10g.ring_buffer_size(ring_buffer_size)
if id then engine.claim_name(id) end
local vlan = false
local mtu = DEFAULT_MTU
if lwconf then
vlan = effective_vlan(conf, external_interface, internal_interface)
mtu = internal_interface.mtu
if external_interface.mtu > mtu then mtu = external_interface.mtu end
mtu = mtu + constants.ethernet_header_size
if external_interface.vlan_tag then mtu = mtu + 4 end
end
conf.interface = {
mac_address = mac,
pci = pci,
id = id,
mtu = mtu,
vlan = vlan,
mirror_id = mirror_id,
}
local c = config.new()
if lwconf then
setup.lwaftr_app(c, conf, lwconf, sock_path)
else
setup.passthrough(c, conf, sock_path)
end
engine.configure(c)
if opts.verbosity >= 2 then
local function lnicui_info()
engine.report_apps()
end
local t = timer.new("report", lnicui_info, 1e9, 'repeating')
timer.activate(t)
end
if ingress_drop_action then
assert(ingress_drop_action == "flush" or ingress_drop_action == "warn",
"Not valid ingress-drop-monitor action")
print(("Ingress drop monitor: %s (threshold: %d packets; wait: %d seconds; interval: %.2f seconds)"):format(
ingress_drop_action, ingress_drop_threshold, ingress_drop_wait, 1e6/ingress_drop_interval))
local counter_path = "apps/lwaftr/ingress-packet-drops"
local mon = ingress_drop_monitor.new({
action = ingress_drop_action,
threshold = ingress_drop_threshold,
wait = ingress_drop_wait,
counter = counter_path,
})
timer.activate(mon:timer(ingress_drop_interval))
end
engine.busywait = true
if opts.duration then
engine.main({duration=opts.duration, report={showlinks=true}})
else
engine.main({report={showlinks=true}})
end
end
|
module(..., package.seeall)
local config = require("core.config")
local constants = require("apps.lwaftr.constants")
local ingress_drop_monitor = require("lib.timers.ingress_drop_monitor")
local intel10g = require("apps.intel.intel10g")
local lib = require("core.lib")
local counters = require("program.lwaftr.counters")
local lwtypes = require("apps.lwaftr.lwtypes")
local lwutil = require("apps.lwaftr.lwutil")
local setup = require("program.snabbvmx.lwaftr.setup")
local shm = require("core.shm")
local fatal, file_exists = lwutil.fatal, lwutil.file_exists
local DEFAULT_MTU = 9500
local function show_usage (exit_code)
print(require("program.snabbvmx.lwaftr.README_inc"))
main.exit(exit_code)
end
function parse_args (args)
if #args == 0 then show_usage(1) end
local conf_file, id, pci, mac, sock_path, mirror_id
local opts = { verbosity = 0 }
local handlers = {}
function handlers.v () opts.verbosity = opts.verbosity + 1 end
function handlers.D (arg)
opts.duration = assert(tonumber(arg), "Duration must be a number")
end
function handlers.c(arg)
conf_file = arg
if not arg then
fatal("Argument '--conf' was not set")
end
if not file_exists(conf_file) then
print(("Warning: config file %s not found"):format(conf_file))
end
end
function handlers.i(arg)
id = arg
if not arg then
fatal("Argument '--id' was not set")
end
end
function handlers.p(arg)
pci = arg
if not arg then
fatal("Argument '--pci' was not set")
end
end
function handlers.m(arg)
mac = arg
if not arg then
fatal("Argument '--mac' was not set")
end
end
function handlers.s(arg)
sock_path = arg
if not arg then
fatal("Argument '--sock' was not set")
end
end
function handlers.mirror (arg)
mirror_id = arg
end
function handlers.h() show_usage(0) end
lib.dogetopt(args, handlers, "c:s:i:p:m:vD:h", {
["conf"] = "c", ["sock"] = "s", ["id"] = "i", ["pci"] = "p", ["mac"] = "m",
["mirror"] = 1, verbose = "v", duration = "D", help = "h" })
return opts, conf_file, id, pci, mac, sock_path, mirror_id
end
local function effective_vlan (conf, external_interface, internal_interface)
if conf.settings and conf.settings.vlan then
return conf.settings.vlan
end
if external_interface.vlan_tag then
if external_interface.vlan_tag == internal_interface.vlan_tag then
return external_interface.vlan_tag
end
return {v4_vlan_tag = external_interface.vlan_tag,
v6_vlan_tag = internal_interface.vlan_tag}
end
return false
end
function run(args)
local opts, conf_file, id, pci, mac, sock_path, mirror_id = parse_args(args)
local conf, lwconf
local external_interface, internal_interface
local ring_buffer_size = 2048
local ingress_drop_action = "flush"
local ingress_drop_threshold = 100000
local ingress_drop_interval = 1e6
local ingress_drop_wait = 20
if file_exists(conf_file) then
conf, lwconf = setup.load_conf(conf_file)
external_interface = lwconf.softwire_config.external_interface
internal_interface = lwconf.softwire_config.internal_interface
-- If one interface has vlan tags, the other one should as well.
assert((not external_interface.vlan_tag) == (not internal_interface.vlan_tag))
else
print(("Interface '%s' set to passthrough mode."):format(id))
ring_buffer_size = 1024
conf = {settings = {}}
end
if conf.settings then
if conf.settings.ingress_drop_monitor then
ingress_drop_action = conf.settings.ingress_drop_monitor
if ingress_drop_action == 'off' then
ingress_drop_action = nil
end
end
if conf.settings.ingress_drop_threshold then
ingress_drop_threshold = conf.settings.ingress_drop_threshold
end
if conf.settings.ingress_drop_interval then
ingress_drop_interval = conf.settings.ingress_drop_interval
end
if conf.settings.ingress_drop_wait then
ingress_drop_wait = conf.settings.ingress_drop_wait
end
end
intel10g.ring_buffer_size(ring_buffer_size)
if id then engine.claim_name(id) end
local vlan = false
local mtu = DEFAULT_MTU
if lwconf then
vlan = effective_vlan(conf, external_interface, internal_interface)
mtu = internal_interface.mtu
if external_interface.mtu > mtu then mtu = external_interface.mtu end
mtu = mtu + constants.ethernet_header_size
if external_interface.vlan_tag then mtu = mtu + 4 end
end
conf.interface = {
mac_address = mac,
pci = pci,
id = id,
mtu = mtu,
vlan = vlan,
mirror_id = mirror_id,
}
local c = config.new()
if lwconf then
setup.lwaftr_app(c, conf, lwconf, sock_path)
else
setup.passthrough(c, conf, sock_path)
end
engine.configure(c)
if opts.verbosity >= 2 then
local function lnicui_info()
engine.report_apps()
end
local t = timer.new("report", lnicui_info, 1e9, 'repeating')
timer.activate(t)
end
if ingress_drop_action then
assert(ingress_drop_action == "flush" or ingress_drop_action == "warn",
"Not valid ingress-drop-monitor action")
print(("Ingress drop monitor: %s (threshold: %d packets; wait: %d seconds; interval: %.2f seconds)"):format(
ingress_drop_action, ingress_drop_threshold, ingress_drop_wait, 1e6/ingress_drop_interval))
local counter_path = "apps/lwaftr/ingress-packet-drops"
local mon = ingress_drop_monitor.new({
action = ingress_drop_action,
threshold = ingress_drop_threshold,
wait = ingress_drop_wait,
counter = counter_path,
})
timer.activate(mon:timer(ingress_drop_interval))
end
engine.busywait = true
if opts.duration then
engine.main({duration=opts.duration, report={showlinks=true}})
else
engine.main({report={showlinks=true}})
end
end
|
Fix "snabb snabbvmx lwaftr"
|
Fix "snabb snabbvmx lwaftr"
|
Lua
|
apache-2.0
|
eugeneia/snabbswitch,dpino/snabb,snabbco/snabb,dpino/snabb,dpino/snabb,snabbco/snabb,alexandergall/snabbswitch,alexandergall/snabbswitch,eugeneia/snabb,eugeneia/snabb,eugeneia/snabb,Igalia/snabbswitch,SnabbCo/snabbswitch,snabbco/snabb,Igalia/snabbswitch,SnabbCo/snabbswitch,eugeneia/snabb,eugeneia/snabbswitch,Igalia/snabb,alexandergall/snabbswitch,Igalia/snabbswitch,snabbco/snabb,eugeneia/snabb,Igalia/snabb,alexandergall/snabbswitch,Igalia/snabbswitch,snabbco/snabb,Igalia/snabbswitch,alexandergall/snabbswitch,Igalia/snabb,dpino/snabbswitch,snabbco/snabb,Igalia/snabb,alexandergall/snabbswitch,dpino/snabbswitch,dpino/snabbswitch,alexandergall/snabbswitch,eugeneia/snabb,Igalia/snabb,eugeneia/snabbswitch,eugeneia/snabb,eugeneia/snabbswitch,snabbco/snabb,Igalia/snabb,dpino/snabbswitch,eugeneia/snabb,dpino/snabb,dpino/snabb,dpino/snabb,dpino/snabb,Igalia/snabb,Igalia/snabb,snabbco/snabb,SnabbCo/snabbswitch,alexandergall/snabbswitch,SnabbCo/snabbswitch
|
50a920b89280eefe2308d49fdd52283e6ab6fea9
|
src/lib/numa.lua
|
src/lib/numa.lua
|
module(..., package.seeall)
local ffi = require("ffi")
local S = require("syscall")
local pci = require("lib.hardware.pci")
local bound_cpu
local bound_numa_node
function cpu_get_numa_node (cpu)
local node = 0
while true do
local node_dir = S.open('/sys/devices/system/node/node'..node,
'rdonly, directory')
if not node_dir then return end
local found = S.readlinkat(node_dir, 'cpu'..cpu)
node_dir:close()
if found then return node end
node = node + 1
end
end
-- Sadly, ljsyscall's `getcpu' call doesn't appear to work for some
-- reason: https://github.com/justincormack/ljsyscall/issues/194. Until
-- then, here's a shim.
ffi.cdef("int sched_getcpu(void);")
function getcpu()
local ret = { cpu = ffi.C.sched_getcpu() }
ret.node = cpu_get_numa_node(ret.cpu)
return ret
end
function has_numa ()
local node1 = S.open('/sys/devices/system/node/node1', 'rdonly, directory')
if not node1 then return false end
node1:close()
return true
end
function pci_get_numa_node (addr)
addr = pci.qualified(addr)
local file = assert(io.open('/sys/bus/pci/devices/'..addr..'/numa_node'))
local node = assert(tonumber(file:read()))
-- node can be -1.
if node >= 0 then return node end
end
function choose_numa_node_for_pci_addresses (addrs, require_affinity)
local chosen_node, chosen_because_of_addr
for _, addr in ipairs(addrs) do
local node = pci_get_numa_node(addr)
if not node or node == chosen_node then
-- Keep trucking.
elseif not chosen_node then
chosen_node = node
chosen_because_of_addr = addr
else
local msg = string.format(
"PCI devices %s and %s have different NUMA node affinities",
chosen_because_of_addr, addr)
if require_affinity then error(msg) else print('Warning: '..msg) end
end
end
return chosen_node
end
function check_affinity_for_pci_addresses (addrs)
local policy = S.get_mempolicy()
if policy.mode == S.c.MPOL_MODE['default'] then
if has_numa() then
print('Warning: No NUMA memory affinity.')
print('Pass --cpu to bind to a CPU and its NUMA node.')
end
elseif policy.mode ~= S.c.MPOL_MODE['bind'] then
print("Warning: NUMA memory policy already in effect, but it's not --membind.")
else
local node = getcpu().node
local node_for_pci = choose_numa_node_for_pci_addresses(addrs)
if node_for_pci and node ~= node_for_pci then
print("Warning: Bound NUMA node does not have affinity with PCI devices.")
end
end
end
function unbind_cpu ()
local cpu_set = S.sched_getaffinity()
cpu_set:zero()
for i = 0, 1023 do cpu_set:set(i) end
assert(S.sched_setaffinity(0, cpu_set))
bound_cpu = nil
end
function bind_to_cpu (cpu)
if cpu == bound_cpu then return end
if not cpu then return unbind_cpu() end
assert(not bound_cpu, "already bound")
assert(S.sched_setaffinity(0, cpu))
local cpu_and_node = getcpu()
assert(cpu_and_node.cpu == cpu)
bound_cpu = cpu
bind_to_numa_node (cpu_and_node.node)
end
function unbind_numa_node ()
assert(S.set_mempolicy('default'))
bound_numa_node = nil
end
function bind_to_numa_node (node)
if node == bound_numa_node then return end
if not node then return unbind_numa_node() end
assert(not bound_numa_node, "already bound")
assert(S.set_mempolicy('bind', node))
bound_numa_node = node
end
function prevent_preemption(priority)
if not S.sched_setscheduler(0, "fifo", priority or 1) then
fatal('Failed to enable real-time scheduling. Try running as root.')
end
end
function selftest ()
print('selftest: numa')
bind_to_cpu(0)
assert(bound_cpu == 0)
assert(bound_numa_node == 0)
assert(getcpu().cpu == 0)
assert(getcpu().node == 0)
bind_to_cpu(nil)
assert(bound_cpu == nil)
assert(bound_numa_node == 0)
assert(getcpu().node == 0)
bind_to_numa_node(nil)
assert(bound_cpu == nil)
assert(bound_numa_node == nil)
print('selftest: numa: ok')
end
|
module(..., package.seeall)
local ffi = require("ffi")
local S = require("syscall")
local pci = require("lib.hardware.pci")
local bound_cpu
local bound_numa_node
function cpu_get_numa_node (cpu)
local node = 0
while true do
local node_dir = S.open('/sys/devices/system/node/node'..node,
'rdonly, directory')
if not node_dir then return end
local found = S.readlinkat(node_dir, 'cpu'..cpu)
node_dir:close()
if found then return node end
node = node + 1
end
end
function has_numa ()
local node1 = S.open('/sys/devices/system/node/node1', 'rdonly, directory')
if not node1 then return false end
node1:close()
return true
end
function pci_get_numa_node (addr)
addr = pci.qualified(addr)
local file = assert(io.open('/sys/bus/pci/devices/'..addr..'/numa_node'))
local node = assert(tonumber(file:read()))
-- node can be -1.
if node >= 0 then return node end
end
function choose_numa_node_for_pci_addresses (addrs, require_affinity)
local chosen_node, chosen_because_of_addr
for _, addr in ipairs(addrs) do
local node = pci_get_numa_node(addr)
if not node or node == chosen_node then
-- Keep trucking.
elseif not chosen_node then
chosen_node = node
chosen_because_of_addr = addr
else
local msg = string.format(
"PCI devices %s and %s have different NUMA node affinities",
chosen_because_of_addr, addr)
if require_affinity then error(msg) else print('Warning: '..msg) end
end
end
return chosen_node
end
function check_affinity_for_pci_addresses (addrs)
local policy = S.get_mempolicy()
if policy.mode == S.c.MPOL_MODE['default'] then
if has_numa() then
print('Warning: No NUMA memory affinity.')
print('Pass --cpu to bind to a CPU and its NUMA node.')
end
elseif policy.mode ~= S.c.MPOL_MODE['bind'] then
print("Warning: NUMA memory policy already in effect, but it's not --membind.")
else
local node = S.getcpu().node
local node_for_pci = choose_numa_node_for_pci_addresses(addrs)
if node_for_pci and node ~= node_for_pci then
print("Warning: Bound NUMA node does not have affinity with PCI devices.")
end
end
end
function unbind_cpu ()
local cpu_set = S.sched_getaffinity()
cpu_set:zero()
for i = 0, 1023 do cpu_set:set(i) end
assert(S.sched_setaffinity(0, cpu_set))
bound_cpu = nil
end
function bind_to_cpu (cpu)
if cpu == bound_cpu then return end
if not cpu then return unbind_cpu() end
assert(not bound_cpu, "already bound")
assert(S.sched_setaffinity(0, cpu))
local cpu_and_node = S.getcpu()
assert(cpu_and_node.cpu == cpu)
bound_cpu = cpu
bind_to_numa_node (cpu_and_node.node)
end
function unbind_numa_node ()
assert(S.set_mempolicy('default'))
bound_numa_node = nil
end
function bind_to_numa_node (node)
if node == bound_numa_node then return end
if not node then return unbind_numa_node() end
assert(not bound_numa_node, "already bound")
assert(S.set_mempolicy('bind', node))
bound_numa_node = node
end
function prevent_preemption(priority)
if not S.sched_setscheduler(0, "fifo", priority or 1) then
fatal('Failed to enable real-time scheduling. Try running as root.')
end
end
function selftest ()
print('selftest: numa')
bind_to_cpu(0)
assert(bound_cpu == 0)
assert(bound_numa_node == 0)
assert(S.getcpu().cpu == 0)
assert(S.getcpu().node == 0)
bind_to_cpu(nil)
assert(bound_cpu == nil)
assert(bound_numa_node == 0)
assert(S.getcpu().node == 0)
bind_to_numa_node(nil)
assert(bound_cpu == nil)
assert(bound_numa_node == nil)
print('selftest: numa: ok')
end
|
numa: Use ljsyscall's fixed "getcpu()" implementation
|
numa: Use ljsyscall's fixed "getcpu()" implementation
* src/lib/numa.lua: Rely on ljsyscall's getcpu(), now that it's fixed.
|
Lua
|
apache-2.0
|
eugeneia/snabb,snabbco/snabb,snabbco/snabb,kbara/snabb,eugeneia/snabbswitch,Igalia/snabbswitch,dpino/snabb,snabbco/snabb,dpino/snabb,eugeneia/snabbswitch,alexandergall/snabbswitch,alexandergall/snabbswitch,dpino/snabb,SnabbCo/snabbswitch,dpino/snabbswitch,eugeneia/snabbswitch,alexandergall/snabbswitch,Igalia/snabb,dpino/snabbswitch,kbara/snabb,Igalia/snabbswitch,Igalia/snabb,heryii/snabb,dpino/snabb,SnabbCo/snabbswitch,Igalia/snabbswitch,eugeneia/snabb,snabbco/snabb,alexandergall/snabbswitch,Igalia/snabbswitch,mixflowtech/logsensor,SnabbCo/snabbswitch,eugeneia/snabb,SnabbCo/snabbswitch,dpino/snabb,heryii/snabb,eugeneia/snabb,snabbco/snabb,snabbco/snabb,kbara/snabb,Igalia/snabb,kbara/snabb,eugeneia/snabb,kbara/snabb,mixflowtech/logsensor,alexandergall/snabbswitch,Igalia/snabbswitch,heryii/snabb,Igalia/snabb,eugeneia/snabb,snabbco/snabb,alexandergall/snabbswitch,Igalia/snabb,mixflowtech/logsensor,dpino/snabbswitch,Igalia/snabb,heryii/snabb,alexandergall/snabbswitch,eugeneia/snabbswitch,mixflowtech/logsensor,kbara/snabb,Igalia/snabb,eugeneia/snabb,Igalia/snabb,dpino/snabbswitch,heryii/snabb,eugeneia/snabb,heryii/snabb,dpino/snabb,mixflowtech/logsensor,alexandergall/snabbswitch,snabbco/snabb,dpino/snabb
|
e4e11373a0ba54eff1b7f4dfb350db0dc986e2c3
|
OS/DiskOS/Programs/run.lua
|
OS/DiskOS/Programs/run.lua
|
--This file loads a lk12 disk and execute it
--First we will start by obtaining the disk data
--We will run the current code in the editor
print("")
local eapi = require("C://Editors")
local mapobj = require("C://Libraries/map")
local sprid = 3 --"spritesheet"
local codeid = 2 --"luacode"
local tileid = 4 --"tilemap"
local swidth, sheight = screenSize()
--Load the spritesheet
local SpriteMap, FlagsData
local sheetImage = image(eapi.leditors[sprid]:exportImage())
local FlagsData = eapi.leditors[sprid]:getFlags()
local sheetW, sheetH = sheetImage:width()/8, sheetImage:height()/8
SpriteMap = SpriteSheet(sheetImage,sheetW,sheetH)
--Load the tilemap
local mapData = eapi.leditors[tileid]:export()
local mapW, mapH = swidth*0.75, sheight
local TileMap = mapobj(mapW,mapH,SpriteMap)
TileMap:import(mapData)
--Load the code
local luacode = eapi.leditors[codeid]:export()
luacode = luacode .. "\n__".."_autoEventLoop()" --Because trible _ are not allowed in LIKO-12
local diskchunk, err = loadstring(luacode)
if not diskchunk then
local err = tostring(err)
local pos = string.find(err,":")
err = err:sub(pos+1,-1)
color(8) print("Compile ERR: "..err )
return
end
--Create the sandboxed global variables
local glob = _FreshGlobals()
glob._G = glob --Magic ;)
glob.loadstring = function(...)
local chunk, err = loadstring(...)
if not chunk then return nil, err end
setfenv(chunk,glob)
return chunk
end
glob.coroutine.create = function(chunk)
--if type(chunk) == "function" then setfenv(chunk,glob) end
local ok,co = pcall(coroutine.create,chunk)
if not ok then return error(co) end
return co
end
--Add peripherals api
local blocklist = { HDD = true, Floppy = true }
local perglob = {GPU = true, CPU = true, Keyboard = true, RAM = true} --The perihperals to make global not in a table.
local _,perlist = coroutine.yield("BIOS:listPeripherals")
for k, v in pairs(blocklist) do perlist[k] = nil end
for peripheral,funcs in pairs(perlist) do
local holder = glob; if not perglob[peripheral] then glob[peripheral] = {}; holder = glob[peripheral] end
for _,func in ipairs(funcs) do
local command = peripheral..":"..func
holder[func] = function(...)
local args = {coroutine.yield(command,...)}
if not args[1] then return error(args[2]) end
local nargs = {}
for k,v in ipairs(args) do
if k >1 then table.insert(nargs,k-1,v) end
end
return unpack(nargs)
end
end
end
local apiloader = loadstring(fs.read("C://api.lua"))
setfenv(apiloader,glob) apiloader()
local function autoEventLoop()
if glob._init and type(glob._init) == "function" then
glob._init()
end
if glob._update or glob._draw or glob._eventLoop then
eventLoop()
end
end
setfenv(autoEventLoop,glob)
--Add special disk api
glob.SpriteMap = SpriteMap
glob.SheetFlagsData = FlagsData
glob.TileMap = TileMap
glob.MapObj = mapobj
glob["__".."_".."autoEventLoop"] = autoEventLoop --Because trible _ are not allowed in LIKO-12
local helpersloader, err = loadstring(fs.read("C://Libraries/diskHelpers.lua"))
if not helpersloader then error(err) end
setfenv(helpersloader,glob) helpersloader()
--Apply the sandbox
setfenv(diskchunk,glob)
--Create the coroutine
local co = coroutine.create(diskchunk)
--Too Long Without Yielding
local checkclock = true
local eventclock = os.clock()
local lastclock = os.clock()
coroutine.sethook(co,function()
if os.clock() > lastclock + 3.5 and checkclock then
error("Too Long Without Yielding",2)
end
end,"",10000)
--Run the thing !
local function extractArgs(args,factor)
local nargs = {}
for k,v in ipairs(args) do
if k > factor then table.insert(nargs,v) end
end
return nargs
end
local lastArgs = {}
while true do
if coroutine.status(co) == "dead" then break end
--[[local name, key = rawPullEvent()
if name == "keypressed" and key == "escape" then
break
end]]
if os.clock() > eventclock + 3.5 then
color(8) print("Too Long Without Pulling Event / Flipping") break
end
local args = {coroutine.resume(co,unpack(lastArgs))}
checkclock = false
if not args[1] then
local err = tostring(args[2])
local pos = string.find(err,":") or 0
err = err:sub(pos+1,-1); color(8) print("ERR: "..err ); break
end
if args[2] then
lastArgs = {coroutine.yield(args[2],unpack(extractArgs(args,2)))}
if args[2] == "CPU:pullEvent" or args[2] == "CPU:rawPullEvent" or args[2] == "GPU:flip" or args[2] == "CPU:sleep" then
eventclock = os.clock()
if args[2] == "GPU:flip" or args[2] == "CPU:sleep" then
local name, key = rawPullEvent()
if name == "keypressed" and key == "escape" then
break
end
else
if lastArgs[1] and lastArgs[2] == "keypressed" and lastArgs[3] == "escape" then
break
end
end
end
lastclock = os.clock()
checkclock = true
end
end
coroutine.sethook(co)
clearEStack()
print("")
|
--This file loads a lk12 disk and execute it
--First we will start by obtaining the disk data
--We will run the current code in the editor
print("")
local eapi = require("C://Editors")
local mapobj = require("C://Libraries/map")
local sprid = 3 --"spritesheet"
local codeid = 2 --"luacode"
local tileid = 4 --"tilemap"
local swidth, sheight = screenSize()
--Load the spritesheet
local SpriteMap, FlagsData
local sheetImage = image(eapi.leditors[sprid]:exportImage())
local FlagsData = eapi.leditors[sprid]:getFlags()
local sheetW, sheetH = sheetImage:width()/8, sheetImage:height()/8
SpriteMap = SpriteSheet(sheetImage,sheetW,sheetH)
--Load the tilemap
local mapData = eapi.leditors[tileid]:export()
local mapW, mapH = swidth*0.75, sheight
local TileMap = mapobj(mapW,mapH,SpriteMap)
TileMap:import(mapData)
--Load the code
local luacode = eapi.leditors[codeid]:export()
luacode = luacode .. "\n__".."_autoEventLoop()" --Because trible _ are not allowed in LIKO-12
local diskchunk, err = loadstring(luacode)
if not diskchunk then
local err = tostring(err)
local pos = string.find(err,":")
err = err:sub(pos+1,-1)
color(8) print("Compile ERR: "..err )
return
end
--Create the sandboxed global variables
local glob = _FreshGlobals()
glob._G = glob --Magic ;)
glob.loadstring = function(...)
local chunk, err = loadstring(...)
if not chunk then return nil, err end
setfenv(chunk,glob)
return chunk
end
glob.coroutine.create = function(chunk)
--if type(chunk) == "function" then setfenv(chunk,glob) end
local ok,co = pcall(coroutine.create,chunk)
if not ok then return error(co) end
return co
end
--Add peripherals api
local blocklist = { HDD = true, Floppy = true }
local perglob = {GPU = true, CPU = true, Keyboard = true, RAM = true} --The perihperals to make global not in a table.
local _,perlist = coroutine.yield("BIOS:listPeripherals")
for k, v in pairs(blocklist) do perlist[k] = nil end
for peripheral,funcs in pairs(perlist) do
local holder = glob; if not perglob[peripheral] then glob[peripheral] = {}; holder = glob[peripheral] end
for _,func in ipairs(funcs) do
local command = peripheral..":"..func
holder[func] = function(...)
local args = {coroutine.yield(command,...)}
if not args[1] then return error(args[2]) end
local nargs = {}
for k,v in ipairs(args) do
if k >1 then table.insert(nargs,k-1,v) end
end
return unpack(nargs)
end
end
end
local apiloader = loadstring(fs.read("C://api.lua"))
setfenv(apiloader,glob) apiloader()
local function autoEventLoop()
if glob._init and type(glob._init) == "function" then
glob._init()
end
if type(glob._eventLoop) == "boolean" and not glob._eventLoop then return end --Skip the auto eventLoop.
if glob._update or glob._draw or glob._eventLoop then
eventLoop()
end
end
setfenv(autoEventLoop,glob)
--Add special disk api
glob.SpriteMap = SpriteMap
glob.SheetFlagsData = FlagsData
glob.TileMap = TileMap
glob.MapObj = mapobj
glob["__".."_".."autoEventLoop"] = autoEventLoop --Because trible _ are not allowed in LIKO-12
local helpersloader, err = loadstring(fs.read("C://Libraries/diskHelpers.lua"))
if not helpersloader then error(err) end
setfenv(helpersloader,glob) helpersloader()
--Apply the sandbox
setfenv(diskchunk,glob)
--Create the coroutine
local co = coroutine.create(diskchunk)
--Too Long Without Yielding
local checkclock = true
local eventclock = os.clock()
local lastclock = os.clock()
coroutine.sethook(co,function()
if os.clock() > lastclock + 3.5 and checkclock then
error("Too Long Without Yielding",2)
end
end,"",10000)
--Run the thing !
local function extractArgs(args,factor)
local nargs = {}
for k,v in ipairs(args) do
if k > factor then table.insert(nargs,v) end
end
return nargs
end
local lastArgs = {}
while true do
if coroutine.status(co) == "dead" then break end
--[[local name, key = rawPullEvent()
if name == "keypressed" and key == "escape" then
break
end]]
if os.clock() > eventclock + 3.5 then
color(8) print("Too Long Without Pulling Event / Flipping") break
end
local args = {coroutine.resume(co,unpack(lastArgs))}
checkclock = false
if not args[1] then
local err = tostring(args[2])
local pos = string.find(err,":") or 0
err = err:sub(pos+1,-1); color(8) print("ERR: "..err ); break
end
if args[2] then
lastArgs = {coroutine.yield(args[2],unpack(extractArgs(args,2)))}
if args[2] == "CPU:pullEvent" or args[2] == "CPU:rawPullEvent" or args[2] == "GPU:flip" or args[2] == "CPU:sleep" then
eventclock = os.clock()
if args[2] == "GPU:flip" or args[2] == "CPU:sleep" then
local name, key = rawPullEvent()
if name == "keypressed" and key == "escape" then
break
end
else
if lastArgs[1] and lastArgs[2] == "keypressed" and lastArgs[3] == "escape" then
break
end
end
end
lastclock = os.clock()
checkclock = true
end
end
coroutine.sethook(co)
clearEStack()
print("")
|
Bugfix
|
Bugfix
|
Lua
|
mit
|
RamiLego4Game/LIKO-12
|
1d58ebc2c0881458a58c700b4104b2e634d96a55
|
applications/luci-statistics/luasrc/controller/luci_statistics/luci_statistics.lua
|
applications/luci-statistics/luasrc/controller/luci_statistics/luci_statistics.lua
|
--[[
Luci statistics - statistics controller module
(c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
module("luci.controller.luci_statistics.luci_statistics", package.seeall)
function index()
require("luci.fs")
require("luci.util")
require("luci.i18n")
require("luci.statistics.datatree")
-- load language files
luci.i18n.loadc("rrdtool")
luci.i18n.loadc("statistics")
-- get rrd data tree
local tree = luci.statistics.datatree.Instance()
-- override entry(): check for existance <plugin>.so where <plugin> is derived from the called path
function _entry( path, ... )
local file = path[5] or path[4]
if luci.fs.isfile( "/usr/lib/collectd/" .. file .. ".so" ) then
entry( path, ... )
end
end
-- override i18n(): try to translate stat_<str> or fall back to <str>
function _i18n( str )
return luci.i18n.translate( "stat_" .. str, str )
end
-- our collectd menu
local collectd_menu = {
output = { "rrdtool", "network", "unixsock", "csv" },
system = { "exec", "email", "cpu", "df", "disk", "irq", "processes", "load" },
network = { "interface", "netlink", "iptables", "tcpconns", "ping", "dns", "wireless" }
}
-- create toplevel menu nodes
entry({"admin", "statistics"}, call("statistics_index"), _i18n("statistics"), 80).i18n = "statistics"
entry({"admin", "statistics", "collectd"}, cbi("luci_statistics/collectd"), _i18n("collectd"), 10)
-- populate collectd plugin menu
local index = 1
for section, plugins in luci.util.kspairs( collectd_menu ) do
entry(
{ "admin", "statistics", "collectd", section },
call( "statistics_" .. section .. "plugins" ),
_i18n( section .. "plugins" ),
index * 10
)
for j, plugin in luci.util.vspairs( plugins ) do
_entry(
{ "admin", "statistics", "collectd", section, plugin },
cbi("luci_statistics/" .. plugin ),
_i18n( plugin ),
j * 10
)
end
index = index + 1
end
-- output views
local page = entry( { "admin", "statistics", "graph" }, call("statistics_index"), _i18n("graphs"), 80)
page.i18n = "statistics"
page.setuser = "nobody"
page.setgroup = "nogroup"
local vars = luci.http.formvalue(nil, true)
local span = vars.timespan or nil
for i, plugin in luci.util.vspairs( tree:plugins() ) do
-- get plugin instances
local instances = tree:plugin_instances( plugin )
-- plugin menu entry
entry(
{ "admin", "statistics", "graph", plugin },
call("statistics_render"), _i18n( plugin ), i
).query = { timespan = span }
-- if more then one instance is found then generate submenu
if #instances > 1 then
for j, inst in luci.util.vspairs(instances) do
-- instance menu entry
entry(
{ "admin", "statistics", "graph", plugin, inst },
call("statistics_render"), inst, j
).query = { timespan = span }
end
end
end
end
function statistics_index()
luci.template.render("admin_statistics/index")
end
function statistics_outputplugins()
local plugins = { }
for i, p in ipairs({ "rrdtool", "network", "unixsock", "csv" }) do
plugins[p] = luci.i18n.translate( "stat_" .. p, p )
end
luci.template.render("admin_statistics/outputplugins", {plugins=plugins})
end
function statistics_systemplugins()
local plugins = { }
for i, p in ipairs({ "exec", "email", "df", "disk", "irq", "processes", "cpu" }) do
plugins[p] = luci.i18n.translate( "stat_" .. p, p )
end
luci.template.render("admin_statistics/systemplugins", {plugins=plugins})
end
function statistics_networkplugins()
local plugins = { }
for i, p in ipairs({ "interface", "netlink", "iptables", "tcpconns", "ping", "dns", "wireless" }) do
plugins[p] = luci.i18n.translate( "stat_" .. p, p )
end
luci.template.render("admin_statistics/networkplugins", {plugins=plugins})
end
function statistics_render()
require("luci.statistics.rrdtool")
require("luci.template")
require("luci.model.uci")
local vars = luci.http.formvalue()
local req = luci.dispatcher.context.request
local path = luci.dispatcher.context.dispatched.path
local uci = luci.model.uci.cursor()
local spans = luci.util.split( uci:get( "luci_statistics", "collectd_rrdtool", "RRATimespans" ), "%s+", nil, true )
local span = vars.timespan or uci:get( "luci_statistics", "rrdtool", "default_timespan" ) or spans[1]
local graph = luci.statistics.rrdtool.Graph( luci.util.parse_units( span ) )
local plugin, instances
local images = { }
-- find requested plugin and instance
for i, p in ipairs( luci.dispatcher.context.dispatched.path ) do
if luci.dispatcher.context.dispatched.path[i] == "graph" then
plugin = luci.dispatcher.context.dispatched.path[i+1]
instances = { luci.dispatcher.context.dispatched.path[i+2] }
end
end
-- no instance requested, find all instances
if #instances == 0 then
instances = { graph.tree:plugin_instances( plugin )[1] }
-- index instance requested
elseif instances[1] == "-" then
instances[1] = ""
end
-- render graphs
for i, inst in ipairs( instances ) do
for i, img in ipairs( graph:render( plugin, inst ) ) do
table.insert( images, graph:strippngpath( img ) )
end
end
luci.template.render( "public_statistics/graph", {
images = images,
plugin = plugin,
timespans = spans,
current_timespan = span
} )
end
|
--[[
Luci statistics - statistics controller module
(c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
module("luci.controller.luci_statistics.luci_statistics", package.seeall)
function index()
require("luci.fs")
require("luci.util")
require("luci.i18n")
require("luci.statistics.datatree")
-- load language files
luci.i18n.loadc("rrdtool")
luci.i18n.loadc("statistics")
-- get rrd data tree
local tree = luci.statistics.datatree.Instance()
-- override entry(): check for existance <plugin>.so where <plugin> is derived from the called path
function _entry( path, ... )
local file = path[5] or path[4]
if luci.fs.isfile( "/usr/lib/collectd/" .. file .. ".so" ) then
entry( path, ... )
end
end
-- override i18n(): try to translate stat_<str> or fall back to <str>
function _i18n( str )
return luci.i18n.translate( "stat_" .. str, str )
end
-- our collectd menu
local collectd_menu = {
output = { "rrdtool", "network", "unixsock", "csv" },
system = { "exec", "email", "cpu", "df", "disk", "irq", "processes", "load" },
network = { "interface", "netlink", "iptables", "tcpconns", "ping", "dns", "wireless" }
}
-- create toplevel menu nodes
entry({"admin", "statistics"}, call("statistics_index"), _i18n("statistics"), 80).i18n = "statistics"
entry({"admin", "statistics", "collectd"}, cbi("luci_statistics/collectd"), _i18n("collectd"), 10)
-- populate collectd plugin menu
local index = 1
for section, plugins in luci.util.kspairs( collectd_menu ) do
entry(
{ "admin", "statistics", "collectd", section },
call( "statistics_" .. section .. "plugins" ),
_i18n( section .. "plugins" ),
index * 10
)
for j, plugin in luci.util.vspairs( plugins ) do
_entry(
{ "admin", "statistics", "collectd", section, plugin },
cbi("luci_statistics/" .. plugin ),
_i18n( plugin ),
j * 10
)
end
index = index + 1
end
-- output views
local page = entry( { "admin", "statistics", "graph" }, call("statistics_index"), _i18n("graphs"), 80)
page.i18n = "statistics"
page.setuser = "nobody"
page.setgroup = "nogroup"
local vars = luci.http.formvalue(nil, true)
local span = vars.timespan or nil
for i, plugin in luci.util.vspairs( tree:plugins() ) do
-- get plugin instances
local instances = tree:plugin_instances( plugin )
-- plugin menu entry
entry(
{ "admin", "statistics", "graph", plugin },
call("statistics_render"), _i18n( plugin ), i
).query = { timespan = span }
-- if more then one instance is found then generate submenu
if #instances > 1 then
for j, inst in luci.util.vspairs(instances) do
-- instance menu entry
entry(
{ "admin", "statistics", "graph", plugin, inst },
call("statistics_render"), inst, j
).query = { timespan = span }
end
end
end
end
function statistics_index()
luci.template.render("admin_statistics/index")
end
function statistics_outputplugins()
local plugins = { }
for i, p in ipairs({ "rrdtool", "network", "unixsock", "csv" }) do
plugins[p] = luci.i18n.translate( "stat_" .. p, p )
end
luci.template.render("admin_statistics/outputplugins", {plugins=plugins})
end
function statistics_systemplugins()
local plugins = { }
for i, p in ipairs({ "exec", "email", "df", "disk", "irq", "processes", "cpu" }) do
plugins[p] = luci.i18n.translate( "stat_" .. p, p )
end
luci.template.render("admin_statistics/systemplugins", {plugins=plugins})
end
function statistics_networkplugins()
local plugins = { }
for i, p in ipairs({ "interface", "netlink", "iptables", "tcpconns", "ping", "dns", "wireless" }) do
plugins[p] = luci.i18n.translate( "stat_" .. p, p )
end
luci.template.render("admin_statistics/networkplugins", {plugins=plugins})
end
function statistics_render()
require("luci.statistics.rrdtool")
require("luci.template")
require("luci.model.uci")
local vars = luci.http.formvalue()
local req = luci.dispatcher.context.request
local path = luci.dispatcher.context.path
local uci = luci.model.uci.cursor()
local spans = luci.util.split( uci:get( "luci_statistics", "collectd_rrdtool", "RRATimespans" ), "%s+", nil, true )
local span = vars.timespan or uci:get( "luci_statistics", "rrdtool", "default_timespan" ) or spans[1]
local graph = luci.statistics.rrdtool.Graph( luci.util.parse_units( span ) )
local plugin, instances
local images = { }
-- find requested plugin and instance
for i, p in ipairs( luci.dispatcher.context.path ) do
if luci.dispatcher.context.path[i] == "graph" then
plugin = luci.dispatcher.context.path[i+1]
instances = { luci.dispatcher.context.path[i+2] }
end
end
-- no instance requested, find all instances
if #instances == 0 then
instances = { graph.tree:plugin_instances( plugin )[1] }
-- index instance requested
elseif instances[1] == "-" then
instances[1] = ""
end
-- render graphs
for i, inst in ipairs( instances ) do
for i, img in ipairs( graph:render( plugin, inst ) ) do
table.insert( images, graph:strippngpath( img ) )
end
end
luci.template.render( "public_statistics/graph", {
images = images,
plugin = plugin,
timespans = spans,
current_timespan = span
} )
end
|
Fixed statistics
|
Fixed statistics
|
Lua
|
apache-2.0
|
deepak78/luci,deepak78/luci,deepak78/luci,8devices/luci,8devices/luci,deepak78/luci,8devices/luci,8devices/luci,deepak78/luci,8devices/luci,deepak78/luci,8devices/luci,deepak78/luci,deepak78/luci
|
e95a0e030c11b7a33142b8fa680708d675a15ebd
|
app/email.lua
|
app/email.lua
|
email = require("lib_lua_email")
email.ports = {
smtpSsl = 465,
smtpNoSsl = 25,
imapSsl = 993,
imapNoSsl = 143
}
email.servers = {
yahooImap = "imaps://imap.mail.yahoo.com",
yahooSmtp = "smtps://smtp.mail.yahoo.com",
gmailImap = "imaps://imap.gmail.com",
gmailSmtp = "smtps://smtp.gmail.com"
}
email.imapCommands = {
login = "SELECT INBOX",
fetchHeader = function (id) return string.format("FETCH %d (BODY[HEADER.FIELDS (TO FROM SUBJECT)])", id) end,
fetchBody = function (id) return string.format("FETCH %d BODY[TEXT]", id) end,
logout = "LOGOUT"
}
email.imapParsers = {}
function email.imapParsers.login(response)
local pattern = "%* (%d+) EXISTS"
local output = string.match(response, pattern)
local err = nil
if not output then
err = "SELECT INBOX command has failed"
end
return output, err
end
function email.imapParsers.fetch(header, body)
local output = nil
local error = "INVALID header and body"
local fromPattern = "From: <(.-)>"
local from = string.match(header, fromPattern)
local toPattern = "To: <(.-)>"
local to = string.match(header, toPattern)
local subjectPattern = "Subject: (.-)\r\n"
local subject = string.match(header, subjectPattern)
local contentStart = string.find(body, "}")
local content = nil
if contentStart then
contentStart = contentStart + 1
content = string.sub(body, contentStart)
end
if from and to and subject and content then
output = {}
output.from = from
output.to = to
output.subject = subject
output.content = content
error = nil
end
print("EXTRALOG: ", output)
return output, error
end
local function runTests()
--test the default ports
assert(email.ports.smtpSsl == 465)
assert(email.ports.smtpNoSsl == 25)
assert(email.ports.imapSsl == 993)
assert(email.ports.imapNoSsl == 143)
-- test usual email servers (yahoo, gmail)
assert(email.servers.yahooImap == "imaps://imap.mail.yahoo.com")
assert(email.servers.yahooSmtp == "smtps://smtp.mail.yahoo.com")
assert(email.servers.gmailImap == "imaps://imap.gmail.com")
assert(email.servers.gmailSmtp == "smtps://smtp.gmail.com")
--test simple imap commands
assert(email.imapCommands.login == "SELECT INBOX")
assert(email.imapCommands.logout == "LOGOUT")
--assert(email.imapCommands.fetch(3) == "FETCH 3 BODY.PEEK[HEADER.subject]")
local user = io.read()
local pass = io.read()
assert(user and pass)
local connection = email.makeImap(true,
email.servers.yahooImap,
email.ports.imapSsl,
user,
pass)
assert(connection)
--test parseImapResponse function for login command
local command = email.imapCommands.login
local response = connection:executeCommand(command)
local id, err = email.imapParsers.login(response)
assert(id and not err)
--test fetch command
command = email.imapCommands.fetchHeader(3)
local header = connection:executeCommand(command)
command = email.imapCommands.fetchBody(3)
local body = connection:executeCommand(command)
local e, err2 = email.imapParsers.fetch(header, body)
assert(e.to and e.from and e.subject and e.content)
--test logout command
command = email.imapCommands.logout
response = connection:executeCommand(command)
local success, err3 = email.imapParsers.logout(response)
assert(success and not err3)
print("All tests went OK")
end
runTests()
return email
|
email = require("lib_lua_email")
email.ports = {
smtpSsl = 465,
smtpNoSsl = 25,
imapSsl = 993,
imapNoSsl = 143
}
email.servers = {
yahooImap = "imaps://imap.mail.yahoo.com/INBOX",
yahooSmtp = "smtps://smtp.mail.yahoo.com",
gmailImap = "imaps://imap.gmail.com/INBOX",
gmailSmtp = "smtps://smtp.gmail.com"
}
email.imapCommands = {
searchLast= "SELECT INBOX",
fetchHeader = function (id) return string.format("FETCH %d (BODY[HEADER.FIELDS (TO FROM SUBJECT)])", id) end,
fetchBody = function (id) return string.format("FETCH %d BODY[TEXT]", id) end,
searchNew = "SEARCH NEW"
}
email.imapParsers = {}
function email.imapParsers.searchLast(response)
local pattern = "%* (%d+) EXISTS"
local output = nil
local err = nil
if response then
output = string.match(response, pattern)
output = output and (tonumber(output) or nil)
end
if not output then
err = "searchLast command has failed"
end
return output, err
end
function email.imapParsers.fetch(header, body)
local output = nil
local error = "INVALID header and body"
local from = nil
local to = nil
local subject = nil
local content = nil
local contentStart = nil
local fromPattern = "From: <(.-)>"
local toPattern = "To: <(.-)>"
local subjectPattern = "Subject: (.-)\r\n"
if header then
from = string.match(header, fromPattern)
to = string.match(header, toPattern)
subject = string.match(header, subjectPattern)
end
if body then
contentStart = string.find(body, "}")
contentStart = contentStart and ((contentStart + 1) or nil)
content = contentStart and (string.sub(body, contentStart) or nil)
end
if from and to and subject and content then
output = {}
output.from = from
output.to = to
output.subject = subject
output.content = content
error = nil
end
return output, error
end
function email.imapParsers.searchNew(response)
local id = nil
local error = "There is no new email in mailbox."
local pattern = "SEARCH (%d+)"
if response then
id = string.match(response, pattern)
id = id and tonumber(id) or nil
end
if id then
error = nil
end
return id, error
end
local function runTests()
--test the default ports
assert(email.ports.smtpSsl == 465)
assert(email.ports.smtpNoSsl == 25)
assert(email.ports.imapSsl == 993)
assert(email.ports.imapNoSsl == 143)
-- test usual email servers (yahoo, gmail)
assert(email.servers.yahooImap == "imaps://imap.mail.yahoo.com/INBOX")
assert(email.servers.yahooSmtp == "smtps://smtp.mail.yahoo.com")
assert(email.servers.gmailImap == "imaps://imap.gmail.com/INBOX")
assert(email.servers.gmailSmtp == "smtps://smtp.gmail.com")
--test simple imap commands
assert(email.imapCommands.searchLast == "SELECT INBOX")
assert(email.imapCommands.searchNew == "SEARCH NEW")
local user = io.read()
local pass = io.read()
assert(user and pass)
local connection = email.makeImap(true,
email.servers.yahooImap,
email.ports.imapSsl,
user,
pass)
assert(connection)
--test searchLast command
local command = email.imapCommands.searchLast
local response = connection:executeCommand(command)
local id, err = email.imapParsers.searchLast(response)
assert(id and not err)
--test fetch command
command = email.imapCommands.fetchHeader(3)
local header = connection:executeCommand(command)
command = email.imapCommands.fetchBody(3)
local body = connection:executeCommand(command)
local e, err2 = email.imapParsers.fetch(header, body)
assert(e.to and e.from and e.subject and e.content)
--test search command
command = email.imapCommands.searchNew
response, err2 = connection:executeCommand(command)
local success, err3 = email.imapParsers.searchNew(response)
assert(success or err3)
print("All tests went OK")
end
--runTests()
return email
|
Rework IMAP commands. Fix up tests.
|
Rework IMAP commands. Fix up tests.
|
Lua
|
bsd-2-clause
|
andreichelariu92/email_gateway,andreichelariu92/email_gateway
|
f833795f51487bc05b5b7748a33aaa3515014bbe
|
lib/luvit/timer.lua
|
lib/luvit/timer.lua
|
--[[
Copyright 2012 The Luvit Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
local Timer = require('uv').Timer
local os = require('os')
local table = require('table')
local TIMEOUT_MAX = 2147483647
local lists = {}
local expiration
expiration = function(msecs)
return function()
local now = Timer.now()
-- pull out the element from back to front, so we can remove elements safely
for i=#lists[msecs].items, 1, -1 do
local elem = lists[msecs].items[i]
local diff = now - elem._idleStart;
p('diff = ' .. diff)
p('msecs = ' .. msecs)
if ((diff + 1) < msecs) == true then
p('in timer.start')
lists[msecs].timer:start(msecs - diff, 0, expiration)
return
else
table.remove(lists[msecs].items, i)
if elem._onTimeout then
elem._onTimeout()
end
end
end
p(msecs .. ' list empty')
lists[msecs].timer:close()
lists[msecs] = nil
end
end
function _insert(item, msecs)
item._idleStart = Timer.now()
item._idleTimeout = msecs
if msecs < 0 then return end
if not lists[msecs] then
local list = {}
list.items = { item }
list.timer = Timer:new()
lists[msecs] = list
list.timer:start(msecs, 0, expiration(msecs))
else
table.insert(lists[msecs].items, item)
end
end
function unenroll(item)
local list = lists[item._idleTimeout]
if list and #list.items == 0 then
-- empty list
lists[item._idleTimeout] = nil
end
item._idleTimeout = -1
end
-- does not start the timer, just initializes the item
function enroll(item, msecs)
if item._idleNext then
unenroll(item)
end
item._idleTimeout = msecs
end
-- call this whenever the item is active (not idle)
function active(item)
local msecs = item._idleTimeout
if msecs >= 0 then
if not lists[msecs] then
p('_insert')
_insert(item, msecs)
else
p('_append')
item._idleStart = Timer.now()
table.insert(lists[msecs].items, item)
p(lists[msecs].items)
end
end
end
function setTimeout(duration, callback, ...)
local args = {...}
if duration < 1 or duration > TIMEOUT_MAX then
duration = 1
end
local timer = {}
timer._idleTimeout = duration
timer._idleNext = timer
timer._idlePrev = timer
timer._onTimeout = function()
p('_onTimeout')
callback(unpack(args))
end
active(timer)
return timer
end
function setInterval(period, callback, ...)
local args = {...}
local timer = Timer:new()
timer:start(period, period, function (status)
callback(unpack(args))
end)
return timer
end
function clearTimer(timer)
timer._onTimeout = nil
timer:close()
end
local exports = {}
exports.setTimeout = setTimeout
exports.setInterval = setInterval
exports.clearTimer = clearTimer
exports.unenroll = unenroll
exports.enroll = enroll
exports.active = active
return exports
|
--[[
Copyright 2012 The Luvit Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
local Timer = require('uv').Timer
local os = require('os')
local table = require('table')
local TIMEOUT_MAX = 2147483647
local lists = {}
function init(list)
list._idleNext = list
list._idlePrev = list
end
function peek(list)
if list._idlePrev == list then
return nil
end
return list._idlePrev
end
function remove(item)
if item._idleNext then
item._idleNext._idlePrev = item._idlePrev
end
if item._idlePrev then
item._idlePrev._idleNext = item._idleNext
end
item._idleNext = 0
item._idlePrev = 0
end
function shift(list)
local elem = list._idlePrev
remove(elem)
return elem
end
function append(list, item)
remove(item)
item._idleNext = list._idleNext
list._idleNext._idlePrev = item
item._idlePrev = list
list._idleNext = item
end
function isEmpty(list)
return list._idleNext == list
end
local expiration
expiration = function(msecs)
return function()
local now = Timer.now()
-- pull out the element from back to front, so we can remove elements safely
while peek(lists[msecs]) do
local elem = peek(lists[msecs])
local diff = now - elem._idleStart;
if ((diff + 1) < msecs) == true then
lists[msecs]:start(msecs - diff, 0, expiration)
return
else
remove(elem)
if elem._onTimeout then
elem._onTimeout()
end
end
end
lists[msecs]:close()
lists[msecs] = nil
end
end
function _insert(item, msecs)
item._idleStart = Timer.now()
item._idleTimeout = msecs
if msecs < 0 then return end
local list
if lists[msecs] then
list = lists[msecs]
else
list = Timer:new()
init(list)
list:start(msecs, 0, expiration(msecs))
lists[msecs] = list
end
append(list, item)
end
function unenroll(item)
local list = lists[item._idleTimeout]
if list and #list.items == 0 then
-- empty list
lists[item._idleTimeout] = nil
end
item._idleTimeout = -1
end
-- does not start the timer, just initializes the item
function enroll(item, msecs)
if item._idleNext then
unenroll(item)
end
item._idleTimeout = msecs
init(item)
end
-- call this whenever the item is active (not idle)
function active(item)
local msecs = item._idleTimeout
if msecs >= 0 then
if not lists[msecs] or isEmpty(lists[msecs]) then
_insert(item, msecs)
else
item._idleStart = Timer.now()
append(lists[msecs], item)
end
end
end
function setTimeout(duration, callback, ...)
local args = {...}
if duration < 1 or duration > TIMEOUT_MAX then
duration = 1
end
local timer = {}
timer._idleTimeout = duration
timer._idleNext = timer
timer._idlePrev = timer
timer._onTimeout = function()
callback(unpack(args))
end
active(timer)
return timer
end
function setInterval(period, callback, ...)
local args = {...}
local timer = Timer:new()
timer:start(period, period, function (status)
callback(unpack(args))
end)
return timer
end
function clearTimer(timer)
timer._onTimeout = nil
timer:close()
end
local exports = {}
exports.setTimeout = setTimeout
exports.setInterval = setInterval
exports.clearTimer = clearTimer
exports.unenroll = unenroll
exports.enroll = enroll
exports.active = active
return exports
|
fixes
|
fixes
|
Lua
|
apache-2.0
|
rjeli/luvit,luvit/luvit,sousoux/luvit,kaustavha/luvit,DBarney/luvit,AndrewTsao/luvit,rjeli/luvit,kaustavha/luvit,sousoux/luvit,DBarney/luvit,bsn069/luvit,connectFree/lev,luvit/luvit,zhaozg/luvit,boundary/luvit,bsn069/luvit,DBarney/luvit,kaustavha/luvit,sousoux/luvit,boundary/luvit,boundary/luvit,GabrielNicolasAvellaneda/luvit-upstream,sousoux/luvit,DBarney/luvit,connectFree/lev,sousoux/luvit,rjeli/luvit,rjeli/luvit,boundary/luvit,bsn069/luvit,GabrielNicolasAvellaneda/luvit-upstream,boundary/luvit,AndrewTsao/luvit,sousoux/luvit,boundary/luvit,GabrielNicolasAvellaneda/luvit-upstream,AndrewTsao/luvit,GabrielNicolasAvellaneda/luvit-upstream,zhaozg/luvit
|
c993e14084553f01b4f5538a72f2bb2388be9b11
|
mods/boats/init.lua
|
mods/boats/init.lua
|
--
-- Helper functions
--
local function is_water(pos)
local nn = minetest.get_node(pos).name
return minetest.get_item_group(nn, "water") ~= 0
end
local function get_sign(i)
if i == 0 then
return 0
else
return i/math.abs(i)
end
end
local function get_velocity(v, yaw, y)
local x = -math.sin(yaw)*v
local z = math.cos(yaw)*v
return {x=x, y=y, z=z}
end
local function get_v(v)
return math.sqrt(v.x^2+v.z^2)
end
--
-- Boat entity
--
local boat = {
physical = true,
collisionbox = {-0.6,-0.4,-0.6, 0.6,0.3,0.6},
visual = "mesh",
mesh = "boat.x",
textures = {"default_wood.png"},
driver = nil,
v = 0,
last_v = 0,
removed = false
}
function boat.on_rightclick(self, clicker)
if not clicker or not clicker:is_player() then
return
end
local name = clicker:get_player_name()
if self.driver and clicker == self.driver then
self.driver = nil
clicker:set_detach()
default.player_attached[name] = false
default.player_set_animation(clicker, "stand" , 30)
elseif not self.driver then
self.driver = clicker
clicker:set_attach(self.object, "", {x=0,y=11,z=-3}, {x=0,y=0,z=0})
default.player_attached[name] = true
minetest.after(0.2, function()
default.player_set_animation(clicker, "sit" , 30)
end)
self.object:setyaw(clicker:get_look_yaw()-math.pi/2)
end
end
function boat.on_activate(self, staticdata, dtime_s)
self.object:set_armor_groups({immortal=1})
if staticdata then
self.v = tonumber(staticdata)
end
self.last_v = self.v
end
function boat.get_staticdata()
return tostring(v)
end
function boat.on_punch(self, puncher, time_from_last_punch, tool_capabilities, direction)
if not puncher or not puncher:is_player() or self.removed then
return
end
puncher:set_detach()
default.player_attached[puncher:get_player_name()] = false
self.removed = true
-- delay remove to ensure player is detached
minetest.after(0.1,function()
self.object:remove()
end)
if not minetest.setting_getbool("creative_mode") then
puncher:get_inventory():add_item("main", "boats:boat")
end
end
function boat.on_step(self, dtime)
self.v = get_v(self.object:getvelocity())*get_sign(self.v)
if self.driver then
local ctrl = self.driver:get_player_control()
local yaw = self.object:getyaw()
if ctrl.up then
self.v = self.v+0.1
end
if ctrl.down then
self.v = self.v-0.08
end
if ctrl.left then
if ctrl.down then
self.object:setyaw(yaw-math.pi/120-dtime*math.pi/120)
else
self.object:setyaw(yaw+math.pi/120+dtime*math.pi/120)
end
end
if ctrl.right then
if ctrl.down then
self.object:setyaw(yaw+math.pi/120+dtime*math.pi/120)
else
self.object:setyaw(yaw-math.pi/120-dtime*math.pi/120)
end
end
end
local velo = self.object:getvelocity()
if self.v == 0 and velo.x == 0 and velo.z == 0 then
return
end
local s = get_sign(self.v)
self.v = self.v - 0.02*s
if s ~= get_sign(self.v) then
self.object:setvelocity({x=0, y=0, z=0})
self.v = 0
return
end
if math.abs(self.v) > 4.5 then
self.v = 4.5*get_sign(self.v)
end
local p = self.object:getpos()
p.y = p.y-0.5
local new_velo = {x=0,y=0,z=0}
local new_acce = {x=0,y=0,z=0}
if not is_water(p) then
if minetest.registered_nodes[minetest.env:get_node(p).name].walkable then
self.v = 0
end
new_acce = {x=0, y=-10, z=0}
new_velo = get_velocity(self.v, self.object:getyaw(), self.object:getvelocity().y)
else
p.y = p.y+1
if is_water(p) then
new_acce = {x=0, y=3, z=0}
local y = self.object:getvelocity().y
if y > 2 then
y = 2
end
if y < 0 then
self.object:setacceleration({x=0, y=10, z=0})
end
new_velo = get_velocity(self.v, self.object:getyaw(), y)
else
new_acce = {x=0, y=0, z=0}
if math.abs(self.object:getvelocity().y) < 1 then
local pos = self.object:getpos()
pos.y = math.floor(pos.y)+0.5
self.object:setpos(pos)
new_velo = get_velocity(self.v, self.object:getyaw(), 0)
else
new_velo = get_velocity(self.v, self.object:getyaw(), self.object:getvelocity().y)
end
end
end
self.object:setvelocity(new_velo)
self.object:setacceleration(new_acce)
end
minetest.register_entity("boats:boat", boat)
minetest.register_craftitem("boats:boat", {
description = "Boat",
inventory_image = "boat_inventory.png",
wield_image = "boat_wield.png",
wield_scale = {x=2, y=2, z=1},
liquids_pointable = true,
on_place = function(itemstack, placer, pointed_thing)
if pointed_thing.type ~= "node" then
return
end
if not is_water(pointed_thing.under) then
return
end
pointed_thing.under.y = pointed_thing.under.y+0.5
minetest.add_entity(pointed_thing.under, "boats:boat")
if not minetest.setting_getbool("creative_mode") then
itemstack:take_item()
end
return itemstack
end,
})
minetest.register_craft({
output = "boats:boat",
recipe = {
{"", "", ""},
{"group:wood", "", "group:wood"},
{"group:wood", "group:wood", "group:wood"},
},
})
|
--
-- Helper functions
--
local function is_water(pos)
local nn = minetest.get_node(pos).name
return minetest.get_item_group(nn, "water") ~= 0
end
local function get_sign(i)
if i == 0 then
return 0
else
return i / math.abs(i)
end
end
local function get_velocity(v, yaw, y)
local x = -math.sin(yaw) * v
local z = math.cos(yaw) * v
return {x = x, y = y, z = z}
end
local function get_v(v)
return math.sqrt(v.x ^ 2 + v.z ^ 2)
end
--
-- Boat entity
--
local boat = {
physical = true,
collisionbox = {-0.6, -0.4, -0.6, 0.6, 0.3, 0.6},
visual = "mesh",
mesh = "boat.x",
textures = {"default_wood.png"},
driver = nil,
v = 0,
last_v = 0,
removed = false
}
function boat.on_rightclick(self, clicker)
if not clicker or not clicker:is_player() then
return
end
local name = clicker:get_player_name()
if self.driver and clicker == self.driver then
self.driver = nil
clicker:set_detach()
default.player_attached[name] = false
default.player_set_animation(clicker, "stand" , 30)
elseif not self.driver then
self.driver = clicker
clicker:set_attach(self.object, "", {x = 0, y = 11, z = -3}, {x = 0, y = 0, z = 0})
default.player_attached[name] = true
minetest.after(0.2, function()
default.player_set_animation(clicker, "sit" , 30)
end)
self.object:setyaw(clicker:get_look_yaw() - math.pi / 2)
end
end
function boat.on_activate(self, staticdata, dtime_s)
self.object:set_armor_groups({immortal = 1})
if staticdata then
self.v = tonumber(staticdata)
end
self.last_v = self.v
end
function boat.get_staticdata(self)
return tostring(self.v)
end
function boat.on_punch(self, puncher, time_from_last_punch, tool_capabilities, direction)
if not puncher or not puncher:is_player() or self.removed then
return
end
puncher:set_detach()
default.player_attached[puncher:get_player_name()] = false
self.removed = true
-- delay remove to ensure player is detached
minetest.after(0.1, function()
self.object:remove()
end)
if not minetest.setting_getbool("creative_mode") then
puncher:get_inventory():add_item("main", "boats:boat")
end
end
function boat.on_step(self, dtime)
self.v = get_v(self.object:getvelocity()) * get_sign(self.v)
if self.driver then
local ctrl = self.driver:get_player_control()
local yaw = self.object:getyaw()
if ctrl.up then
self.v = self.v + 0.1
end
if ctrl.down then
self.v = self.v - 0.08
end
if ctrl.left then
if ctrl.down then
self.object:setyaw(yaw - math.pi / 120 - dtime * math.pi / 120)
else
self.object:setyaw(yaw + math.pi / 120 + dtime * math.pi / 120)
end
end
if ctrl.right then
if ctrl.down then
self.object:setyaw(yaw + math.pi / 120 + dtime * math.pi / 120)
else
self.object:setyaw(yaw - math.pi / 120 - dtime*math.pi/120)
end
end
end
local velo = self.object:getvelocity()
if self.v == 0 and velo.x == 0 and velo.z == 0 then
return
end
local s = get_sign(self.v)
self.v = self.v - 0.02 * s
if s ~= get_sign(self.v) then
self.object:setvelocity({x = 0, y = 0, z = 0})
self.v = 0
return
end
if math.abs(self.v) > 4.5 then
self.v = 4.5 * get_sign(self.v)
end
local p = self.object:getpos()
p.y = p.y - 0.5
local new_velo = {x = 0, y = 0, z = 0}
local new_acce = {x = 0, y = 0, z = 0}
if not is_water(p) then
local nodedef = minetest.registered_nodes[minetest.get_node(p).name]
if (not nodedef) or nodedef.walkable then
self.v = 0
end
new_acce = {x = 0, y = -10, z = 0}
new_velo = get_velocity(self.v, self.object:getyaw(), self.object:getvelocity().y)
else
p.y = p.y + 1
if is_water(p) then
new_acce = {x = 0, y = 3, z = 0}
local y = self.object:getvelocity().y
if y > 2 then
y = 2
end
if y < 0 then
self.object:setacceleration({x = 0, y = 10, z = 0})
end
new_velo = get_velocity(self.v, self.object:getyaw(), y)
else
new_acce = {x = 0, y = 0, z = 0}
if math.abs(self.object:getvelocity().y) < 1 then
local pos = self.object:getpos()
pos.y = math.floor(pos.y) + 0.5
self.object:setpos(pos)
new_velo = get_velocity(self.v, self.object:getyaw(), 0)
else
new_velo = get_velocity(self.v, self.object:getyaw(), self.object:getvelocity().y)
end
end
end
self.object:setvelocity(new_velo)
self.object:setacceleration(new_acce)
end
minetest.register_entity("boats:boat", boat)
minetest.register_craftitem("boats:boat", {
description = "Boat",
inventory_image = "boat_inventory.png",
wield_image = "boat_wield.png",
wield_scale = {x = 2, y = 2, z = 1},
liquids_pointable = true,
on_place = function(itemstack, placer, pointed_thing)
if pointed_thing.type ~= "node" then
return
end
if not is_water(pointed_thing.under) then
return
end
pointed_thing.under.y = pointed_thing.under.y + 0.5
minetest.add_entity(pointed_thing.under, "boats:boat")
if not minetest.setting_getbool("creative_mode") then
itemstack:take_item()
end
return itemstack
end,
})
minetest.register_craft({
output = "boats:boat",
recipe = {
{"", "", "" },
{"group:wood", "", "group:wood"},
{"group:wood", "group:wood", "group:wood"},
},
})
|
Add spaces around operators in boat mod code, fix a problem with boat staticdata, fix a crash that can occur with boat going over unknown nodes.
|
Add spaces around operators in boat mod code, fix a problem with boat staticdata, fix a crash that can occur with boat going over unknown nodes.
|
Lua
|
lgpl-2.1
|
evrooije/beerarchy,evrooije/beerarchy,evrooije/beerarchy
|
489e69edfd103de532dfd291d3d30eca1db349c8
|
protocols/6x4/luasrc/model/cbi/admin_network/proto_6to4.lua
|
protocols/6x4/luasrc/model/cbi/admin_network/proto_6to4.lua
|
--[[
LuCI - Lua Configuration Interface
Copyright 2011 Jo-Philipp Wich <xm@subsignal.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
]]--
local map, section, net = ...
local ipaddr, adv_interface, adv_subnet
local adv_valid_lifetime, adv_preferred_lifetime, defaultroute, metric, ttl, mtu
ipaddr = section:taboption("general", Value, "ipaddr",
translate("Local IPv4 address"),
translate("Leave empty to use the current WAN address"))
ipaddr.datatype = "ip4addr"
adv_interface = section:taboption("general", Value, "adv_interface", translate("Advertise IPv6 on network"))
adv_interface.widget = "checkbox"
adv_interface.exclude = arg[1]
adv_interface.default = "lan"
adv_interface.template = "cbi/network_netlist"
adv_interface.nocreate = true
adv_interface.nobridges = true
adv_interface.novirtual = true
function adv_interface.remove(self, section)
self:write(section, " ")
end
adv_subnet = section:taboption("general", Value, "adv_subnet",
translate("Advertised network ID"),
translate("Allowed range is 1 to 65535"))
adv_subnet.placeholder = "1"
adv_subnet.datatype = "range(1,65535)"
function adv_subnet.cfgvalue(self, section)
local v = Value.cfgvalue(self, section)
return v and tonumber(v, 16)
end
function adv_subnet .write(self, section, value)
value = tonumber(value) or 1
if value > 65535 then value = 65535
elseif value < 1 then value = 1 end
Value.write(self, section, "%X" % value)
end
adv_valid_lifetime = section:taboption("advanced", Value, "adv_valid_lifetime",
translate("Use valid lifetime"),
translate("Specifies the advertised valid prefix lifetime in seconds"))
adv_valid_lifetime.placeholder = "300"
adv_valid_lifetime.datatype = "uinteger"
adv_preferred_lifetime = section:taboption("advanced", Value, "adv_preferred_lifetime",
translate("Use preferred lifetime"),
translate("Specifies the advertised preferred prefix lifetime in seconds"))
adv_preferred_lifetime.placeholder = "120"
adv_preferred_lifetime.datatype = "uinteger"
defaultroute = section:taboption("advanced", Flag, "defaultroute",
translate("Use default gateway"),
translate("If unchecked, no default route is configured"))
defaultroute.default = defaultroute.enabled
metric = section:taboption("advanced", Value, "metric",
translate("Use gateway metric"))
metric.placeholder = "0"
metric.datatype = "uinteger"
metric:depends("defaultroute", defaultroute.enabled)
ttl = section:taboption("advanced", Value, "ttl", translate("Use TTL on tunnel interface"))
ttl.placeholder = "64"
ttl.datatype = "range(1,255)"
mtu = section:taboption("advanced", Value, "mtu", translate("Use MTU on tunnel interface"))
mtu.placeholder = "1280"
mtu.datatype = "max(1500)"
|
--[[
LuCI - Lua Configuration Interface
Copyright 2011 Jo-Philipp Wich <xm@subsignal.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
]]--
local map, section, net = ...
local ipaddr, adv_interface, adv_subnet
local adv_valid_lifetime, adv_preferred_lifetime, defaultroute, metric, ttl, mtu
ipaddr = section:taboption("general", Value, "ipaddr",
translate("Local IPv4 address"),
translate("Leave empty to use the current WAN address"))
ipaddr.datatype = "ip4addr"
adv_interface = section:taboption("general", Value, "adv_interface", translate("Advertise IPv6 on network"))
adv_interface.widget = "checkbox"
adv_interface.exclude = arg[1]
adv_interface.default = "lan"
adv_interface.template = "cbi/network_netlist"
adv_interface.nocreate = true
adv_interface.nobridges = true
adv_interface.novirtual = true
function adv_interface.write(self, section, value)
if type(value) == "table" then
Value.write(self, section, table.concat(value, " "))
else
Value.write(self, section, value)
end
end
function adv_interface.remove(self, section)
self:write(section, " ")
end
adv_subnet = section:taboption("general", Value, "adv_subnet",
translate("Advertised network ID"),
translate("Allowed range is 1 to 65535"))
adv_subnet.placeholder = "1"
adv_subnet.datatype = "range(1,65535)"
function adv_subnet.cfgvalue(self, section)
local v = Value.cfgvalue(self, section)
return v and tonumber(v, 16)
end
function adv_subnet .write(self, section, value)
value = tonumber(value) or 1
if value > 65535 then value = 65535
elseif value < 1 then value = 1 end
Value.write(self, section, "%X" % value)
end
adv_valid_lifetime = section:taboption("advanced", Value, "adv_valid_lifetime",
translate("Use valid lifetime"),
translate("Specifies the advertised valid prefix lifetime in seconds"))
adv_valid_lifetime.placeholder = "300"
adv_valid_lifetime.datatype = "uinteger"
adv_preferred_lifetime = section:taboption("advanced", Value, "adv_preferred_lifetime",
translate("Use preferred lifetime"),
translate("Specifies the advertised preferred prefix lifetime in seconds"))
adv_preferred_lifetime.placeholder = "120"
adv_preferred_lifetime.datatype = "uinteger"
defaultroute = section:taboption("advanced", Flag, "defaultroute",
translate("Use default gateway"),
translate("If unchecked, no default route is configured"))
defaultroute.default = defaultroute.enabled
metric = section:taboption("advanced", Value, "metric",
translate("Use gateway metric"))
metric.placeholder = "0"
metric.datatype = "uinteger"
metric:depends("defaultroute", defaultroute.enabled)
ttl = section:taboption("advanced", Value, "ttl", translate("Use TTL on tunnel interface"))
ttl.placeholder = "64"
ttl.datatype = "range(1,255)"
mtu = section:taboption("advanced", Value, "mtu", translate("Use MTU on tunnel interface"))
mtu.placeholder = "1280"
mtu.datatype = "max(1500)"
|
proto/6x4: cast 6to4 adv_interface to string when saving to uci, fixes 6in4.sh not picking up the adv interfaces
|
proto/6x4: cast 6to4 adv_interface to string when saving to uci, fixes 6in4.sh not picking up the adv interfaces
|
Lua
|
apache-2.0
|
ollie27/openwrt_luci,lcf258/openwrtcn,openwrt-es/openwrt-luci,hnyman/luci,bittorf/luci,zhaoxx063/luci,tobiaswaldvogel/luci,taiha/luci,Hostle/openwrt-luci-multi-user,cshore-firmware/openwrt-luci,shangjiyu/luci-with-extra,cshore-firmware/openwrt-luci,Hostle/luci,NeoRaider/luci,db260179/openwrt-bpi-r1-luci,thess/OpenWrt-luci,lcf258/openwrtcn,Kyklas/luci-proto-hso,kuoruan/lede-luci,urueedi/luci,florian-shellfire/luci,openwrt/luci,sujeet14108/luci,RuiChen1113/luci,male-puppies/luci,cshore/luci,Hostle/openwrt-luci-multi-user,NeoRaider/luci,teslamint/luci,male-puppies/luci,maxrio/luci981213,schidler/ionic-luci,bright-things/ionic-luci,Sakura-Winkey/LuCI,Kyklas/luci-proto-hso,daofeng2015/luci,bittorf/luci,zhaoxx063/luci,zhaoxx063/luci,deepak78/new-luci,kuoruan/luci,maxrio/luci981213,florian-shellfire/luci,jchuang1977/luci-1,cshore-firmware/openwrt-luci,sujeet14108/luci,lbthomsen/openwrt-luci,chris5560/openwrt-luci,joaofvieira/luci,ollie27/openwrt_luci,tobiaswaldvogel/luci,RuiChen1113/luci,Noltari/luci,jlopenwrtluci/luci,tcatm/luci,taiha/luci,Noltari/luci,florian-shellfire/luci,jorgifumi/luci,Wedmer/luci,bittorf/luci,palmettos/test,oyido/luci,oneru/luci,male-puppies/luci,daofeng2015/luci,LazyZhu/openwrt-luci-trunk-mod,nwf/openwrt-luci,Noltari/luci,palmettos/cnLuCI,oyido/luci,daofeng2015/luci,jorgifumi/luci,nwf/openwrt-luci,keyidadi/luci,oneru/luci,nwf/openwrt-luci,jchuang1977/luci-1,thess/OpenWrt-luci,thess/OpenWrt-luci,cappiewu/luci,artynet/luci,aircross/OpenWrt-Firefly-LuCI,oneru/luci,chris5560/openwrt-luci,mumuqz/luci,tobiaswaldvogel/luci,chris5560/openwrt-luci,RedSnake64/openwrt-luci-packages,ReclaimYourPrivacy/cloak-luci,dismantl/luci-0.12,palmettos/cnLuCI,cshore/luci,marcel-sch/luci,aa65535/luci,palmettos/test,daofeng2015/luci,Wedmer/luci,slayerrensky/luci,marcel-sch/luci,palmettos/test,MinFu/luci,david-xiao/luci,taiha/luci,david-xiao/luci,urueedi/luci,hnyman/luci,LuttyYang/luci,marcel-sch/luci,remakeelectric/luci,Hostle/luci,ReclaimYourPrivacy/cloak-luci,fkooman/luci,remakeelectric/luci,aa65535/luci,keyidadi/luci,fkooman/luci,rogerpueyo/luci,david-xiao/luci,jorgifumi/luci,shangjiyu/luci-with-extra,deepak78/new-luci,hnyman/luci,chris5560/openwrt-luci,LuttyYang/luci,ff94315/luci-1,artynet/luci,Hostle/openwrt-luci-multi-user,nmav/luci,fkooman/luci,jchuang1977/luci-1,nmav/luci,tcatm/luci,NeoRaider/luci,Wedmer/luci,chris5560/openwrt-luci,aa65535/luci,Noltari/luci,keyidadi/luci,Wedmer/luci,dismantl/luci-0.12,Hostle/openwrt-luci-multi-user,lbthomsen/openwrt-luci,db260179/openwrt-bpi-r1-luci,artynet/luci,zhaoxx063/luci,jlopenwrtluci/luci,ollie27/openwrt_luci,jorgifumi/luci,oneru/luci,LazyZhu/openwrt-luci-trunk-mod,LazyZhu/openwrt-luci-trunk-mod,david-xiao/luci,RuiChen1113/luci,cappiewu/luci,981213/luci-1,tobiaswaldvogel/luci,NeoRaider/luci,openwrt-es/openwrt-luci,RedSnake64/openwrt-luci-packages,oneru/luci,teslamint/luci,jlopenwrtluci/luci,Hostle/openwrt-luci-multi-user,kuoruan/luci,openwrt/luci,harveyhu2012/luci,jchuang1977/luci-1,tobiaswaldvogel/luci,chris5560/openwrt-luci,nmav/luci,Kyklas/luci-proto-hso,dismantl/luci-0.12,jlopenwrtluci/luci,cshore/luci,palmettos/cnLuCI,Hostle/openwrt-luci-multi-user,artynet/luci,sujeet14108/luci,LazyZhu/openwrt-luci-trunk-mod,tobiaswaldvogel/luci,slayerrensky/luci,kuoruan/luci,urueedi/luci,NeoRaider/luci,wongsyrone/luci-1,tobiaswaldvogel/luci,aircross/OpenWrt-Firefly-LuCI,openwrt-es/openwrt-luci,tcatm/luci,fkooman/luci,Hostle/luci,joaofvieira/luci,981213/luci-1,Kyklas/luci-proto-hso,sujeet14108/luci,shangjiyu/luci-with-extra,harveyhu2012/luci,cshore/luci,openwrt/luci,forward619/luci,db260179/openwrt-bpi-r1-luci,remakeelectric/luci,artynet/luci,aircross/OpenWrt-Firefly-LuCI,obsy/luci,keyidadi/luci,Hostle/luci,fkooman/luci,openwrt/luci,aa65535/luci,keyidadi/luci,dismantl/luci-0.12,chris5560/openwrt-luci,aircross/OpenWrt-Firefly-LuCI,harveyhu2012/luci,thesabbir/luci,openwrt-es/openwrt-luci,ff94315/luci-1,ReclaimYourPrivacy/cloak-luci,male-puppies/luci,artynet/luci,nwf/openwrt-luci,dwmw2/luci,thess/OpenWrt-luci,opentechinstitute/luci,joaofvieira/luci,mumuqz/luci,artynet/luci,rogerpueyo/luci,zhaoxx063/luci,db260179/openwrt-bpi-r1-luci,remakeelectric/luci,RedSnake64/openwrt-luci-packages,rogerpueyo/luci,ff94315/luci-1,mumuqz/luci,shangjiyu/luci-with-extra,keyidadi/luci,opentechinstitute/luci,kuoruan/luci,cshore-firmware/openwrt-luci,Kyklas/luci-proto-hso,LuttyYang/luci,LazyZhu/openwrt-luci-trunk-mod,Sakura-Winkey/LuCI,nwf/openwrt-luci,Wedmer/luci,kuoruan/luci,Noltari/luci,nwf/openwrt-luci,aircross/OpenWrt-Firefly-LuCI,Wedmer/luci,joaofvieira/luci,ollie27/openwrt_luci,dwmw2/luci,daofeng2015/luci,ReclaimYourPrivacy/cloak-luci,teslamint/luci,wongsyrone/luci-1,florian-shellfire/luci,Noltari/luci,nmav/luci,981213/luci-1,Noltari/luci,cappiewu/luci,rogerpueyo/luci,rogerpueyo/luci,cshore-firmware/openwrt-luci,jlopenwrtluci/luci,daofeng2015/luci,teslamint/luci,ReclaimYourPrivacy/cloak-luci,jchuang1977/luci-1,male-puppies/luci,openwrt-es/openwrt-luci,forward619/luci,deepak78/new-luci,jorgifumi/luci,fkooman/luci,slayerrensky/luci,nmav/luci,MinFu/luci,taiha/luci,aa65535/luci,lcf258/openwrtcn,florian-shellfire/luci,keyidadi/luci,tcatm/luci,daofeng2015/luci,bright-things/ionic-luci,forward619/luci,cshore-firmware/openwrt-luci,schidler/ionic-luci,openwrt-es/openwrt-luci,bright-things/ionic-luci,palmettos/test,ff94315/luci-1,db260179/openwrt-bpi-r1-luci,nmav/luci,dwmw2/luci,bittorf/luci,kuoruan/lede-luci,ollie27/openwrt_luci,ollie27/openwrt_luci,oneru/luci,RuiChen1113/luci,db260179/openwrt-bpi-r1-luci,bright-things/ionic-luci,palmettos/test,RedSnake64/openwrt-luci-packages,hnyman/luci,obsy/luci,deepak78/new-luci,teslamint/luci,obsy/luci,forward619/luci,palmettos/cnLuCI,hnyman/luci,shangjiyu/luci-with-extra,RedSnake64/openwrt-luci-packages,joaofvieira/luci,hnyman/luci,schidler/ionic-luci,981213/luci-1,RuiChen1113/luci,Noltari/luci,LuttyYang/luci,Wedmer/luci,zhaoxx063/luci,teslamint/luci,bittorf/luci,male-puppies/luci,schidler/ionic-luci,cshore-firmware/openwrt-luci,dwmw2/luci,ollie27/openwrt_luci,bittorf/luci,tcatm/luci,opentechinstitute/luci,mumuqz/luci,Kyklas/luci-proto-hso,schidler/ionic-luci,ReclaimYourPrivacy/cloak-luci,ff94315/luci-1,palmettos/cnLuCI,oyido/luci,male-puppies/luci,obsy/luci,obsy/luci,openwrt-es/openwrt-luci,jlopenwrtluci/luci,lcf258/openwrtcn,dwmw2/luci,cshore/luci,forward619/luci,mumuqz/luci,aircross/OpenWrt-Firefly-LuCI,artynet/luci,schidler/ionic-luci,RedSnake64/openwrt-luci-packages,rogerpueyo/luci,nmav/luci,thess/OpenWrt-luci,openwrt-es/openwrt-luci,thess/OpenWrt-luci,ff94315/luci-1,thesabbir/luci,david-xiao/luci,teslamint/luci,kuoruan/lede-luci,artynet/luci,wongsyrone/luci-1,kuoruan/lede-luci,db260179/openwrt-bpi-r1-luci,oyido/luci,chris5560/openwrt-luci,981213/luci-1,david-xiao/luci,urueedi/luci,shangjiyu/luci-with-extra,LuttyYang/luci,opentechinstitute/luci,aa65535/luci,Hostle/luci,lcf258/openwrtcn,Wedmer/luci,NeoRaider/luci,tcatm/luci,rogerpueyo/luci,slayerrensky/luci,forward619/luci,sujeet14108/luci,LuttyYang/luci,wongsyrone/luci-1,rogerpueyo/luci,joaofvieira/luci,oyido/luci,cappiewu/luci,dismantl/luci-0.12,marcel-sch/luci,lcf258/openwrtcn,jchuang1977/luci-1,maxrio/luci981213,lbthomsen/openwrt-luci,urueedi/luci,nmav/luci,marcel-sch/luci,thesabbir/luci,tcatm/luci,fkooman/luci,bright-things/ionic-luci,palmettos/cnLuCI,taiha/luci,cappiewu/luci,remakeelectric/luci,kuoruan/lede-luci,thesabbir/luci,david-xiao/luci,slayerrensky/luci,zhaoxx063/luci,schidler/ionic-luci,obsy/luci,nwf/openwrt-luci,palmettos/cnLuCI,aa65535/luci,ollie27/openwrt_luci,dismantl/luci-0.12,NeoRaider/luci,dwmw2/luci,urueedi/luci,LuttyYang/luci,maxrio/luci981213,Sakura-Winkey/LuCI,Hostle/luci,wongsyrone/luci-1,bright-things/ionic-luci,harveyhu2012/luci,thesabbir/luci,oneru/luci,981213/luci-1,harveyhu2012/luci,slayerrensky/luci,lcf258/openwrtcn,lcf258/openwrtcn,deepak78/new-luci,NeoRaider/luci,Hostle/openwrt-luci-multi-user,tcatm/luci,LazyZhu/openwrt-luci-trunk-mod,taiha/luci,kuoruan/luci,cshore/luci,bright-things/ionic-luci,MinFu/luci,fkooman/luci,db260179/openwrt-bpi-r1-luci,bright-things/ionic-luci,cshore-firmware/openwrt-luci,lbthomsen/openwrt-luci,palmettos/cnLuCI,opentechinstitute/luci,RedSnake64/openwrt-luci-packages,nwf/openwrt-luci,jorgifumi/luci,LazyZhu/openwrt-luci-trunk-mod,Sakura-Winkey/LuCI,maxrio/luci981213,LuttyYang/luci,kuoruan/lede-luci,aa65535/luci,shangjiyu/luci-with-extra,obsy/luci,MinFu/luci,lcf258/openwrtcn,jorgifumi/luci,thess/OpenWrt-luci,jchuang1977/luci-1,hnyman/luci,mumuqz/luci,openwrt/luci,forward619/luci,ff94315/luci-1,MinFu/luci,male-puppies/luci,cappiewu/luci,harveyhu2012/luci,cappiewu/luci,mumuqz/luci,oyido/luci,cappiewu/luci,Hostle/luci,thess/OpenWrt-luci,wongsyrone/luci-1,maxrio/luci981213,florian-shellfire/luci,thesabbir/luci,mumuqz/luci,keyidadi/luci,lbthomsen/openwrt-luci,urueedi/luci,zhaoxx063/luci,wongsyrone/luci-1,daofeng2015/luci,tobiaswaldvogel/luci,ReclaimYourPrivacy/cloak-luci,florian-shellfire/luci,kuoruan/lede-luci,taiha/luci,shangjiyu/luci-with-extra,Hostle/openwrt-luci-multi-user,palmettos/test,Sakura-Winkey/LuCI,nmav/luci,sujeet14108/luci,remakeelectric/luci,kuoruan/lede-luci,opentechinstitute/luci,lbthomsen/openwrt-luci,obsy/luci,cshore/luci,deepak78/new-luci,Sakura-Winkey/LuCI,oyido/luci,dwmw2/luci,marcel-sch/luci,teslamint/luci,opentechinstitute/luci,MinFu/luci,deepak78/new-luci,thesabbir/luci,forward619/luci,oneru/luci,joaofvieira/luci,palmettos/test,Noltari/luci,jlopenwrtluci/luci,Hostle/luci,maxrio/luci981213,david-xiao/luci,dismantl/luci-0.12,urueedi/luci,sujeet14108/luci,jlopenwrtluci/luci,wongsyrone/luci-1,kuoruan/luci,lcf258/openwrtcn,jorgifumi/luci,Sakura-Winkey/LuCI,cshore/luci,maxrio/luci981213,Kyklas/luci-proto-hso,slayerrensky/luci,thesabbir/luci,jchuang1977/luci-1,Sakura-Winkey/LuCI,hnyman/luci,remakeelectric/luci,lbthomsen/openwrt-luci,harveyhu2012/luci,oyido/luci,ReclaimYourPrivacy/cloak-luci,florian-shellfire/luci,marcel-sch/luci,deepak78/new-luci,slayerrensky/luci,kuoruan/luci,RuiChen1113/luci,RuiChen1113/luci,marcel-sch/luci,openwrt/luci,MinFu/luci,bittorf/luci,palmettos/test,taiha/luci,RuiChen1113/luci,joaofvieira/luci,dwmw2/luci,981213/luci-1,MinFu/luci,LazyZhu/openwrt-luci-trunk-mod,openwrt/luci,lbthomsen/openwrt-luci,sujeet14108/luci,aircross/OpenWrt-Firefly-LuCI,remakeelectric/luci,openwrt/luci,schidler/ionic-luci,ff94315/luci-1,opentechinstitute/luci,bittorf/luci
|
59f75d996ee9ac6569c6ba47edbfa87ad8a7e163
|
modules/client_entergame/entergame.lua
|
modules/client_entergame/entergame.lua
|
EnterGame = { }
-- private variables
local loadBox
local enterGame
local motdButton
local enterGameButton
-- private functions
local function clearAccountFields()
enterGame:getChildById('accountNameTextEdit'):clearText()
enterGame:getChildById('accountPasswordTextEdit'):clearText()
enterGame:getChildById('accountNameTextEdit'):focus()
g_settings.remove('account')
g_settings.remove('password')
end
local function onError(protocol, message, connectionError)
loadBox:destroy()
loadBox = nil
if not connectionError then
clearAccountFields()
end
local errorBox = displayErrorBox(tr('Login Error'), message)
connect(errorBox, { onOk = EnterGame.show })
end
local function onMotd(protocol, motd)
G.motdNumber = tonumber(motd:sub(0, motd:find("\n")))
G.motdMessage = motd:sub(motd:find("\n") + 1, #motd)
motdButton:show()
end
local function onCharacterList(protocol, characters, premDays)
if enterGame:getChildById('rememberPasswordBox'):isChecked() then
g_settings.set('account', g_crypt.encrypt(G.account))
g_settings.set('password', g_crypt.encrypt(G.password))
g_settings.set('autologin', enterGame:getChildById('autoLoginBox'):isChecked())
else
clearAccountFields()
end
loadBox:destroy()
loadBox = nil
CharacterList.create(characters, premDays)
CharacterList.show()
local lastMotdNumber = g_settings.getNumber("motd")
if G.motdNumber and G.motdNumber ~= lastMotdNumber then
g_settings.set("motd", motdNumber)
local motdBox = displayInfoBox(tr('Message of the day'), G.motdMessage)
connect(motdBox, { onOk = CharacterList.show })
CharacterList.hide()
end
end
-- public functions
function EnterGame.init()
enterGame = g_ui.displayUI('entergame.otui')
enterGameButton = TopMenu.addLeftButton('enterGameButton', tr('Login') .. ' (Ctrl + G)', 'login.png', EnterGame.openWindow)
motdButton = TopMenu.addLeftButton('motdButton', tr('Message of the day'), 'motd.png', EnterGame.displayMotd)
motdButton:hide()
g_keyboard.bindKeyDown('Ctrl+G', EnterGame.openWindow)
if G.motdNumber then
motdButton:show()
end
local account = g_crypt.decrypt(g_settings.get('account'))
local password = g_crypt.decrypt(g_settings.get('password'))
local host = g_settings.get('host')
local port = g_settings.get('port')
local autologin = g_settings.getBoolean('autologin')
enterGame:getChildById('accountNameTextEdit'):setText(account)
enterGame:getChildById('accountPasswordTextEdit'):setText(password)
enterGame:getChildById('serverHostTextEdit'):setText(host)
enterGame:getChildById('serverPortTextEdit'):setText(port)
enterGame:getChildById('autoLoginBox'):setChecked(autologin)
enterGame:getChildById('rememberPasswordBox'):setChecked(#account > 0)
enterGame:getChildById('accountNameTextEdit'):focus()
-- only open entergame when app starts
if not g_app.isRunning() then
if #account > 0 and autologin then
addEvent(EnterGame.doLogin)
end
else
enterGame:hide()
end
end
function EnterGame.terminate()
g_keyboard.unbindKeyDown('Ctrl+G')
enterGame:destroy()
enterGame = nil
enterGameButton:destroy()
enterGameButton = nil
motdButton:destroy()
motdButton = nil
EnterGame = nil
end
function EnterGame.show()
enterGame:show()
enterGame:raise()
enterGame:focus()
end
function EnterGame.hide()
enterGame:hide()
end
function EnterGame.openWindow()
if g_game.isOnline() then
CharacterList.show()
elseif not CharacterList.isVisible() then
EnterGame.show()
end
end
function EnterGame.doLogin()
G.account = enterGame:getChildById('accountNameTextEdit'):getText()
G.password = enterGame:getChildById('accountPasswordTextEdit'):getText()
G.host = enterGame:getChildById('serverHostTextEdit'):getText()
G.port = tonumber(enterGame:getChildById('serverPortTextEdit'):getText())
EnterGame.hide()
g_settings.set('host', G.host)
g_settings.set('port', G.port)
local protocolLogin = ProtocolLogin.create()
protocolLogin.onError = onError
protocolLogin.onMotd = onMotd
protocolLogin.onCharacterList = onCharacterList
loadBox = displayCancelBox(tr('Please wait'), tr('Connecting to login server...'))
connect(loadBox, { onCancel = function(msgbox)
loadBox = nil
protocolLogin:cancelLogin()
EnterGame.show()
end })
protocolLogin:login(G.host, G.port, G.account, G.password)
end
function EnterGame.displayMotd()
displayInfoBox(tr('Message of the day'), G.motdMessage)
end
|
EnterGame = { }
-- private variables
local loadBox
local enterGame
local motdButton
local enterGameButton
-- private functions
local function clearAccountFields()
enterGame:getChildById('accountNameTextEdit'):clearText()
enterGame:getChildById('accountPasswordTextEdit'):clearText()
enterGame:getChildById('accountNameTextEdit'):focus()
g_settings.remove('account')
g_settings.remove('password')
end
local function onError(protocol, message, connectionError)
loadBox:destroy()
loadBox = nil
if not connectionError then
clearAccountFields()
end
local errorBox = displayErrorBox(tr('Login Error'), message)
connect(errorBox, { onOk = EnterGame.show })
end
local function onMotd(protocol, motd)
G.motdNumber = tonumber(motd:sub(0, motd:find("\n")))
G.motdMessage = motd:sub(motd:find("\n") + 1, #motd)
motdButton:show()
end
local function onCharacterList(protocol, characters, premDays)
if enterGame:getChildById('rememberPasswordBox'):isChecked() then
g_settings.set('account', g_crypt.encrypt(G.account))
g_settings.set('password', g_crypt.encrypt(G.password))
g_settings.set('autologin', enterGame:getChildById('autoLoginBox'):isChecked())
else
clearAccountFields()
end
loadBox:destroy()
loadBox = nil
CharacterList.create(characters, premDays)
CharacterList.show()
local lastMotdNumber = g_settings.getNumber("motd")
if G.motdNumber and G.motdNumber ~= lastMotdNumber then
g_settings.set("motd", motdNumber)
local motdBox = displayInfoBox(tr('Message of the day'), G.motdMessage)
connect(motdBox, { onOk = CharacterList.show })
CharacterList.hide()
end
end
-- public functions
function EnterGame.init()
enterGame = g_ui.displayUI('entergame.otui')
enterGameButton = TopMenu.addLeftButton('enterGameButton', tr('Login') .. ' (Ctrl + G)', 'login.png', EnterGame.openWindow)
motdButton = TopMenu.addLeftButton('motdButton', tr('Message of the day'), 'motd.png', EnterGame.displayMotd)
motdButton:hide()
g_keyboard.bindKeyDown('Ctrl+G', EnterGame.openWindow)
if G.motdNumber then
motdButton:show()
end
local account = g_crypt.decrypt(g_settings.get('account'))
local password = g_crypt.decrypt(g_settings.get('password'))
local host = g_settings.get('host')
local port = g_settings.get('port')
local autologin = g_settings.getBoolean('autologin')
if port == nil or port == 0 then port = 7171 end
enterGame:getChildById('accountNameTextEdit'):setText(account)
enterGame:getChildById('accountPasswordTextEdit'):setText(password)
enterGame:getChildById('serverHostTextEdit'):setText(host)
enterGame:getChildById('serverPortTextEdit'):setText(port)
enterGame:getChildById('autoLoginBox'):setChecked(autologin)
enterGame:getChildById('rememberPasswordBox'):setChecked(#account > 0)
enterGame:getChildById('accountNameTextEdit'):focus()
-- only open entergame when app starts
if not g_app.isRunning() then
if #host > 0 and #password > 0 and #account > 0 and autologin then
addEvent(EnterGame.doLogin)
end
else
enterGame:hide()
end
end
function EnterGame.terminate()
g_keyboard.unbindKeyDown('Ctrl+G')
enterGame:destroy()
enterGame = nil
enterGameButton:destroy()
enterGameButton = nil
motdButton:destroy()
motdButton = nil
EnterGame = nil
end
function EnterGame.show()
enterGame:show()
enterGame:raise()
enterGame:focus()
end
function EnterGame.hide()
enterGame:hide()
end
function EnterGame.openWindow()
if g_game.isOnline() then
CharacterList.show()
elseif not CharacterList.isVisible() then
EnterGame.show()
end
end
function EnterGame.doLogin()
G.account = enterGame:getChildById('accountNameTextEdit'):getText()
G.password = enterGame:getChildById('accountPasswordTextEdit'):getText()
G.host = enterGame:getChildById('serverHostTextEdit'):getText()
G.port = tonumber(enterGame:getChildById('serverPortTextEdit'):getText())
EnterGame.hide()
if G.host == '' or G.port == nil or G.port == 0 then
local errorBox = displayErrorBox(tr('Login Error'), tr('Enter a valid server host and port to login.'))
connect(errorBox, { onOk = EnterGame.show })
return
end
g_settings.set('host', G.host)
g_settings.set('port', G.port)
local protocolLogin = ProtocolLogin.create()
protocolLogin.onError = onError
protocolLogin.onMotd = onMotd
protocolLogin.onCharacterList = onCharacterList
loadBox = displayCancelBox(tr('Please wait'), tr('Connecting to login server...'))
connect(loadBox, { onCancel = function(msgbox)
loadBox = nil
protocolLogin:cancelLogin()
EnterGame.show()
end })
protocolLogin:login(G.host, G.port, G.account, G.password)
end
function EnterGame.displayMotd()
displayInfoBox(tr('Message of the day'), G.motdMessage)
end
|
Fix crash when logging without specifing a port or host
|
Fix crash when logging without specifing a port or host
|
Lua
|
mit
|
Radseq/otclient,kwketh/otclient,dreamsxin/otclient,dreamsxin/otclient,gpedro/otclient,EvilHero90/otclient,dreamsxin/otclient,Radseq/otclient,gpedro/otclient,kwketh/otclient,EvilHero90/otclient,Cavitt/otclient_mapgen,gpedro/otclient,Cavitt/otclient_mapgen
|
56ffcd6514197b121b57fadd55955aef1da60459
|
lua/entities/gmod_wire_expression2/core/console.lua
|
lua/entities/gmod_wire_expression2/core/console.lua
|
/******************************************************************************\
Console support
\******************************************************************************/
E2Lib.RegisterExtension("console", true, "Lets E2 chips run concommands and retrieve convars")
local function tokenizeAndGetCommands(str)
-- Tokenize!
local tokens = {}
local curtoken = {}
local escaped = false
for i=1, #str do
local char = string.sub(str, i, i)
if (escaped and char ~= "\"") or string.match(char, "%w") then
curtoken[#curtoken + 1] = char
else
if #curtoken>0 then tokens[#tokens + 1] = table.concat(curtoken) curtoken = {} end
if char == "\"" then
escaped = not escaped
elseif char ~= " " then
tokens[#tokens + 1] = char
end
end
end
if #curtoken>0 then tokens[#tokens+1] = table.concat(curtoken) end
-- Get table of commands used
local commands = {tokens[1] or ""}
for i=1, #tokens do
if tokens[i]==";" then
commands[#commands + 1] = tokens[i+1] or ""
end
end
return commands
end
local function validConCmd(self, command)
local ply = self.player
if not ply:IsValid() then return false end
if ply:GetInfoNum("wire_expression2_concmd", 0) == 0 then return false end
-- Validating the concmd length to ensure that it won't crash the server. 512 is the max
if #command >= 512 then return false end
local whitelistArr = string.Split((ply:GetInfo("wire_expression2_concmd_whitelist") or ""):Trim(), ",")
if #whitelistArr == 0 then return true end
local whitelist = {}
for k, v in pairs(whitelistArr) do whitelist[v] = true end
local commands = tokenizeAndGetCommands(command)
for _, command in pairs(commands) do
if not whitelist[command] then
return false
end
end
return true
end
__e2setcost(5)
e2function number concmd(string command)
if not validConCmd(self, command) then return 0 end
self.player:ConCommand(command:gsub("%%", "%%%%"))
return 1
end
e2function string convar(string cvar)
if not validConCmd(self, cvar) then return "" end
local ret = self.player:GetInfo(cvar)
if not ret then return "" end
return ret
end
e2function number convarnum(string cvar)
if not validConCmd(self, cvar) then return 0 end
local ret = self.player:GetInfoNum(cvar, 0)
if not ret then return 0 end
return ret
end
e2function number maxOfType(string typename)
if typename == "wire_holograms" then return GetConVarNumber("wire_holograms_max") or 0 end
return GetConVarNumber("sbox_max"..typename) or 0
end
e2function number playerDamage()
local ret = GetConVarNumber("sbox_plpldamage") or 0
return ret ~= 0 and 1 or 0
end
|
/******************************************************************************\
Console support
\******************************************************************************/
E2Lib.RegisterExtension("console", true, "Lets E2 chips run concommands and retrieve convars")
local function tokenizeAndGetCommands(str)
-- Tokenize!
local tokens = {}
local curtoken = {}
local escaped = false
for i=1, #str do
local char = string.sub(str, i, i)
if (escaped and char ~= "\"") or string.match(char, "[%w+-]") then
curtoken[#curtoken + 1] = char
else
if #curtoken>0 then tokens[#tokens + 1] = table.concat(curtoken) curtoken = {} end
if char == "\"" then
escaped = not escaped
elseif char ~= " " then
tokens[#tokens + 1] = char
end
end
end
if #curtoken>0 then tokens[#tokens+1] = table.concat(curtoken) end
-- Get table of commands used
local commands = {tokens[1] or ""}
for i=1, #tokens do
if tokens[i]==";" then
commands[#commands + 1] = tokens[i+1] or ""
end
end
return commands
end
local function validConCmd(self, command)
local ply = self.player
if not ply:IsValid() then return false end
if ply:GetInfoNum("wire_expression2_concmd", 0) == 0 then return false end
-- Validating the concmd length to ensure that it won't crash the server. 512 is the max
if #command >= 512 then return false end
local whitelist = (ply:GetInfo("wire_expression2_concmd_whitelist") or ""):Trim()
if whitelist == "" then return true end
local whitelistTbl = {}
for k, v in pairs(string.Split(whitelist, ",")) do whitelistTbl[v] = true end
local commands = tokenizeAndGetCommands(command)
for _, command in pairs(commands) do
if not whitelistTbl[command] then
return false
end
end
return true
end
__e2setcost(5)
e2function number concmd(string command)
if not validConCmd(self, command) then return 0 end
self.player:ConCommand(command:gsub("%%", "%%%%"))
return 1
end
e2function string convar(string cvar)
if not validConCmd(self, cvar) then return "" end
local ret = self.player:GetInfo(cvar)
if not ret then return "" end
return ret
end
e2function number convarnum(string cvar)
if not validConCmd(self, cvar) then return 0 end
local ret = self.player:GetInfoNum(cvar, 0)
if not ret then return 0 end
return ret
end
e2function number maxOfType(string typename)
if typename == "wire_holograms" then return GetConVarNumber("wire_holograms_max") or 0 end
return GetConVarNumber("sbox_max"..typename) or 0
end
e2function number playerDamage()
local ret = GetConVarNumber("sbox_plpldamage") or 0
return ret ~= 0 and 1 or 0
end
|
Fix concmd whitelist for + and - characters
|
Fix concmd whitelist for + and - characters
|
Lua
|
apache-2.0
|
sammyt291/wire,NezzKryptic/Wire,Grocel/wire,wiremod/wire,garrysmodlua/wire,dvdvideo1234/wire
|
8f56c944dd5341d7cc0f437ce3566c1db7072765
|
server/lua/initSession.lua
|
server/lua/initSession.lua
|
--
-- Copyright 2014 Ilkka Oksanen <iao@iki.fi>
--
-- 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.
--
-- Initialization of outbox needs to be atomic operation (=Lua script)
-- for streaming to be realiable.
#include 'lib/introduceNewUserIds'
local userId = ARGV[1]
local sessionId = ARGV[2]
local outbox = 'outbox:' .. userId .. ':' .. sessionId
local function split(s, delimiter)
local result = {}
for match in (s..delimiter):gmatch('(.-)'..delimiter) do
table.insert(result, match)
end
return result
end
-- Redis HGETALL doesn't return a real hash, fix it.
local hgetall = function (key)
local bulk = redis.call('HGETALL', key)
local result = {}
local nextkey
for i, v in ipairs(bulk) do
if i % 2 == 1 then
nextkey = v
else
result[nextkey] = v
end
end
return result
end
local seenUserIds = {}
local function seenUser(userId)
if userId then
seenUserIds[userId] = true
end
end
redis.call('LPUSH', outbox, cjson.encode({
['id'] = 'SESSIONID',
['sessionId'] = sessionId
}))
local settings = hgetall('settings:' .. userId)
redis.call('LPUSH', outbox, cjson.encode({
['id'] = 'SET',
['settings'] = settings
}))
-- Iterate through windows
local windowIds = redis.call('SMEMBERS', 'windowlist:' .. userId)
local allUsers = {}
for i = 1, #windowIds do
local windowId = windowIds[i]
local window = hgetall('window:' .. userId .. ':' .. windowId)
local conversationId = window.conversationId
local conversation = hgetall('conversation:' .. conversationId)
local oneOnOneUserId = nil
if conversation.password == '' then
window.password = cjson.null
else
window.password = conversation.password
end
local role = redis.call('HGET', 'conversationmembers:' .. conversationId, userId)
if conversation.type == '1on1' then
local users = redis.call('HKEYS', 'conversationmembers:' .. conversationId)
if users[1] == userId then
oneOnOneUserId = users[2]
else
oneOnOneUserId = users[1]
end
end
redis.call('LPUSH', outbox, cjson.encode({
['id'] = 'CREATE',
['windowId'] = tonumber(windowId),
['network'] = conversation.network,
['name'] = conversation.name,
['userId'] = oneOnOneUserId, -- added if the window is 1on1
['type'] = conversation.type,
['sounds'] = window.sounds == 'true',
['titleAlert'] = window.titleAlert == 'true',
['role'] = role,
['visible'] = window.visible == 'true',
['row'] = tonumber(window.row),
['password'] = conversation.password,
['topic'] = conversation.topic
}))
local members = {}
local ids = hgetall('conversationmembers:' .. conversationId)
for windowUserId, role in pairs(ids) do
seenUser(windowUserId)
table.insert(members, {
['userId'] = windowUserId,
['role'] = role
})
end
redis.call('LPUSH', outbox, cjson.encode({
['id'] = 'ADDMEMBERS',
['windowId'] = tonumber(windowId),
['reset'] = true,
['members'] = members
}))
local lines = redis.call('LRANGE', 'conversationmsgs:' .. conversationId, 0, -1);
for ii = #lines, 1, -1 do
local windowId = redis.call('HGET', 'index:windowIds', userId .. ':' .. conversationId)
local command = cjson.decode(lines[ii])
command.id = 'ADDTEXT'
command.windowId = tonumber(windowId)
if command.userId == userId and command.cat ~= 'join' and command.cat ~= 'part' and
command.cat ~= 'quit' then
command.cat = 'mymsg'
end
redis.call('LPUSH', outbox, cjson.encode(command))
seenUser(command.userId)
end
end
-- Prepend the USERS command so client gets it first
local userIdList = {}
for k,v in pairs(seenUserIds) do
table.insert(userIdList, k)
end
introduceNewUserIds(userId, sessionId, nil, userIdList)
redis.call('LPUSH', outbox, cjson.encode({
['id'] = 'INITDONE'
}))
|
--
-- Copyright 2014 Ilkka Oksanen <iao@iki.fi>
--
-- 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.
--
-- Initialization of outbox needs to be atomic operation (=Lua script)
-- for streaming to be realiable.
#include 'lib/introduceNewUserIds'
local userId = ARGV[1]
local sessionId = ARGV[2]
local outbox = 'outbox:' .. userId .. ':' .. sessionId
local function split(s, delimiter)
local result = {}
for match in (s..delimiter):gmatch('(.-)'..delimiter) do
table.insert(result, match)
end
return result
end
-- Redis HGETALL doesn't return a real hash, fix it.
local hgetall = function (key)
local bulk = redis.call('HGETALL', key)
local result = {}
local nextkey
for i, v in ipairs(bulk) do
if i % 2 == 1 then
nextkey = v
else
result[nextkey] = v
end
end
return result
end
local seenUserIds = {}
local function seenUser(userId)
if userId then
seenUserIds[userId] = true
end
end
redis.call('LPUSH', outbox, cjson.encode({
['id'] = 'SESSIONID',
['sessionId'] = sessionId
}))
local settings = hgetall('settings:' .. userId)
redis.call('LPUSH', outbox, cjson.encode({
['id'] = 'SET',
['settings'] = settings
}))
-- Iterate through windows
local windowIds = redis.call('SMEMBERS', 'windowlist:' .. userId)
local allUsers = {}
for i = 1, #windowIds do
local windowId = windowIds[i]
local window = hgetall('window:' .. userId .. ':' .. windowId)
local conversationId = window.conversationId
local conversation = hgetall('conversation:' .. conversationId)
local oneOnOneUserId = nil
if conversation.password == '' then
window.password = cjson.null
else
window.password = conversation.password
end
local role = redis.call('HGET', 'conversationmembers:' .. conversationId, userId)
if conversation.type == '1on1' then
local users = redis.call('HKEYS', 'conversationmembers:' .. conversationId)
if users[1] == userId then
oneOnOneUserId = users[2]
else
oneOnOneUserId = users[1]
end
end
redis.call('LPUSH', outbox, cjson.encode({
['id'] = 'CREATE',
['windowId'] = tonumber(windowId),
['network'] = conversation.network,
['name'] = conversation.name,
['userId'] = oneOnOneUserId, -- added if the window is 1on1
['type'] = conversation.type,
['sounds'] = window.sounds == 'true',
['titleAlert'] = window.titleAlert == 'true',
['role'] = role,
['visible'] = window.visible == 'true',
['row'] = tonumber(window.row),
['password'] = conversation.password,
['topic'] = conversation.topic
}))
local members = {}
local ids = hgetall('conversationmembers:' .. conversationId)
for windowUserId, role in pairs(ids) do
seenUser(windowUserId)
table.insert(members, {
['userId'] = windowUserId,
['role'] = role
})
end
redis.call('LPUSH', outbox, cjson.encode({
['id'] = 'ADDMEMBERS',
['windowId'] = tonumber(windowId),
['reset'] = true,
['members'] = members
}))
local lines = redis.call('LRANGE', 'conversationmsgs:' .. conversationId, 0, -1);
for ii = #lines, 1, -1 do
local command = cjson.decode(lines[ii])
command.id = 'ADDTEXT'
command.windowId = tonumber(windowId)
if command.userId == userId and command.cat ~= 'join' and command.cat ~= 'part' and
command.cat ~= 'quit' then
command.cat = 'mymsg'
end
redis.call('LPUSH', outbox, cjson.encode(command))
seenUser(command.userId)
end
end
-- Prepend the USERS command so client gets it first
local userIdList = {}
for k,v in pairs(seenUserIds) do
table.insert(userIdList, k)
end
introduceNewUserIds(userId, sessionId, nil, userIdList)
redis.call('LPUSH', outbox, cjson.encode({
['id'] = 'INITDONE'
}))
|
Fix lua initSession()
|
Fix lua initSession()
|
Lua
|
apache-2.0
|
ilkkao/mas,ilkkao/mas,ilkkao/mas,ilkkao/mas
|
da8f094bf8e4c1a57f741cc61af8a5735488cd60
|
src/xenia/app/premake5.lua
|
src/xenia/app/premake5.lua
|
project_root = "../../.."
include(project_root.."/tools/build")
group("src")
project("xenia-app")
uuid("d7e98620-d007-4ad8-9dbd-b47c8853a17f")
kind("WindowedApp")
targetname("xenia")
language("C++")
links({
"capstone",
"gflags",
"glew",
"glslang-spirv",
"imgui",
"libavcodec",
"libavutil",
"mspack",
"snappy",
"spirv-tools",
"volk",
"xenia-apu",
"xenia-apu-nop",
"xenia-base",
"xenia-core",
"xenia-cpu",
"xenia-cpu-backend-x64",
"xenia-debug-ui",
"xenia-gpu",
"xenia-gpu-null",
"xenia-gpu-vulkan",
"xenia-hid",
"xenia-hid-nop",
"xenia-kernel",
"xenia-ui",
"xenia-ui-spirv",
"xenia-ui-vulkan",
"xenia-vfs",
"xxhash",
})
flags({
"WinMain", -- Use WinMain instead of main.
})
defines({
})
includedirs({
project_root.."/third_party/gflags/src",
})
local_platform_files()
files({
"xenia_main.cc",
"../base/main_"..platform_suffix..".cc",
})
filter("platforms:Windows")
files({
"main_resources.rc",
})
resincludedirs({
project_root,
})
filter("platforms:Linux")
links({
"X11",
"xcb",
"X11-xcb",
"GL",
"vulkan",
})
filter("platforms:Windows")
links({
"xenia-apu-xaudio2",
"xenia-hid-winkey",
"xenia-hid-xinput",
})
filter("platforms:Windows")
-- Only create the .user file if it doesn't already exist.
local user_file = project_root.."/build/xenia-app.vcxproj.user"
if not os.isfile(user_file) then
debugdir(project_root)
debugargs({
"--flagfile=scratch/flags.txt",
"2>&1",
"1>scratch/stdout.txt",
})
end
|
project_root = "../../.."
include(project_root.."/tools/build")
group("src")
project("xenia-app")
uuid("d7e98620-d007-4ad8-9dbd-b47c8853a17f")
kind("WindowedApp")
targetname("xenia")
language("C++")
links({
"capstone",
"gflags",
"glew",
"glslang-spirv",
"imgui",
"libavcodec",
"libavutil",
"mspack",
"snappy",
"spirv-tools",
"volk",
"xenia-apu",
"xenia-apu-nop",
"xenia-base",
"xenia-core",
"xenia-cpu",
"xenia-cpu-backend-x64",
"xenia-debug-ui",
"xenia-gpu",
"xenia-gpu-null",
"xenia-gpu-vulkan",
"xenia-hid",
"xenia-hid-nop",
"xenia-kernel",
"xenia-ui",
"xenia-ui-spirv",
"xenia-ui-vulkan",
"xenia-vfs",
"xxhash",
})
flags({
"WinMain", -- Use WinMain instead of main.
})
defines({
"XBYAK_NO_OP_NAMES",
"XBYAK_ENABLE_OMITTED_OPERAND",
})
includedirs({
project_root.."/third_party/gflags/src",
})
local_platform_files()
files({
"xenia_main.cc",
"../base/main_"..platform_suffix..".cc",
})
filter("platforms:Windows")
files({
"main_resources.rc",
})
resincludedirs({
project_root,
})
filter("platforms:Linux")
links({
"X11",
"xcb",
"X11-xcb",
"GL",
"vulkan",
})
filter("platforms:Windows")
links({
"xenia-apu-xaudio2",
"xenia-hid-winkey",
"xenia-hid-xinput",
})
filter("platforms:Windows")
-- Only create the .user file if it doesn't already exist.
local user_file = project_root.."/build/xenia-app.vcxproj.user"
if not os.isfile(user_file) then
debugdir(project_root)
debugargs({
"--flagfile=scratch/flags.txt",
"2>&1",
"1>scratch/stdout.txt",
})
end
|
[App] Fix Travis whining.
|
[App] Fix Travis whining.
|
Lua
|
bsd-3-clause
|
sephiroth99/xenia,sephiroth99/xenia,sephiroth99/xenia
|
d463264f074739e81d70f6afb9dd8fb151b87e09
|
src/npge/algo/BlastHits.lua
|
src/npge/algo/BlastHits.lua
|
-- lua-npge, Nucleotide PanGenome explorer (Lua module)
-- Copyright (C) 2014-2016 Boris Nagaev
-- See the LICENSE file for terms of use.
local ori = function(start, stop)
if start < stop then
return 1
else
return -1
end
end
local function readBlast(file, query, bank, same, line_handler)
local new_blocks = {}
local query_name, bank_name
local query_row, bank_row
local query_start, bank_start
local query_stop, bank_stop
local function goodHit()
return query_name and bank_name
and query_row and bank_row
end
local function goodFragments(_, _)
return true
end
if same then
local goodHit0 = goodHit
goodHit = function()
return goodHit0() and query_name <= bank_name
end
goodFragments = function(query_f, bank_f)
return query_f < bank_f
end
end
local function tryAdd()
if goodHit() then
assert(query_row)
assert(bank_row)
assert(query_start)
assert(query_stop)
assert(bank_start)
assert(bank_stop)
local Fragment = require 'npge.model.Fragment'
local query_seq = query:sequenceByName(query_name)
assert(query_seq)
local query_ori = ori(query_start, query_stop)
local query_f = Fragment(query_seq,
query_start - 1, query_stop - 1, query_ori)
local bank_seq = bank:sequenceByName(bank_name)
assert(bank_seq)
local bank_ori = ori(bank_start, bank_stop)
local bank_f = Fragment(bank_seq,
bank_start - 1, bank_stop - 1, bank_ori)
if goodFragments(query_f, bank_f) then
local Block = require 'npge.model.Block'
local query_row1 = table.concat(query_row)
local bank_row1 = table.concat(bank_row)
local block = Block({
{query_f, query_row1},
{bank_f, bank_row1},
})
table.insert(new_blocks, block)
end
end
query_row = nil
bank_row = nil
query_start = nil
query_stop = nil
bank_start = nil
bank_stop = nil
end
local startsWith = require 'npge.util.startsWith'
local split = require 'npge.util.split'
local trim = require 'npge.util.trim'
local unpack = require 'npge.util.unpack'
local file_is_empty = true
for line in file:lines() do
line = trim(line)
if line_handler then
line_handler(line)
end
file_is_empty = false
if startsWith(line, 'Query=') then
-- Example: Query= consensus000567
tryAdd()
query_name = split(line, '=', 1)[2]
query_name = trim(query_name)
query_name = split(query_name)[1]
elseif line:sub(1, 1) == '>' then
-- Example: > consensus000567
tryAdd()
bank_name = trim(line:sub(2))
bank_name = split(bank_name)[1]
elseif startsWith(line, 'Score =') then
-- Example: Score = 82.4 bits (90), ...
tryAdd()
query_row = {}
bank_row = {}
elseif goodHit() then
local function parseAlignment(line1)
local parts = split(line1)
assert(#parts == 4 or #parts == 2)
if #parts == 4 then
local _, start, row, stop = unpack(parts)
return start, row, stop
end
if #parts == 2 then
local _, row = unpack(parts)
return nil, row, nil
end
end
if startsWith(line, 'Query ') then
-- Example: Query 1 GCGCG 5
local start, row, stop = parseAlignment(line)
if start and stop then
if not query_start then
query_start = assert(tonumber(start))
end
query_stop = assert(tonumber(stop))
end
table.insert(query_row, row)
elseif startsWith(line, 'Sbjct ') then
-- Example: Sbjct 1 GCGCG 5
local start, row, stop = parseAlignment(line)
if start and stop then
if not bank_start then
bank_start = assert(tonumber(start))
end
bank_stop = assert(tonumber(stop))
end
table.insert(bank_row, row)
end
end
end
tryAdd()
assert(not file_is_empty, "blastn returned empty file")
local seqs = bank:sequences()
if not same then
for seq in query:iterSequences() do
if not bank:sequenceByName(seq:name()) then
table.insert(seqs, seq)
end
end
end
local BlockSet = require 'npge.model.BlockSet'
return BlockSet(seqs, new_blocks)
end
return function(query, bank, options)
-- possible options:
-- - bank_fname - pre-built bank
-- - subset - if truthy, then query is interpreted as
-- a subset of bank. All hits where query > bank
-- are discarded (optimisation). They are compared
-- as instances of Fragment.
-- - line_handler - a function that is called with
-- each line of blast output
local Blast = require 'npge.algo.Blast'
local tmpName = require 'npge.util.tmpName'
options = options or {}
local BlockSet = require 'npge.model.BlockSet'
if #query:sequences() == 0 or #bank:sequences() == 0 then
return BlockSet({}, {})
end
Blast.checkNoCollisions(query, bank)
local same = (query == bank)
local bank_cons_fname, bank_fname
if options.bank_fname then
bank_fname = options.bank_fname
else
bank_cons_fname = tmpName()
Blast.makeConsensus(bank_cons_fname, bank)
bank_fname = tmpName()
Blast.makeBlastDb(bank_fname, bank_cons_fname)
end
local query_cons_fname
if same and bank_cons_fname then
query_cons_fname = bank_cons_fname
else
query_cons_fname = tmpName()
Blast.makeConsensus(query_cons_fname, query)
end
--
local cmd = Blast.blastnCmd(bank_fname,
query_cons_fname, options)
local f = assert(io.popen(cmd, 'r'))
local hits = readBlast(f, query, bank,
same or options.subset, options.line_handler)
f:close()
if bank_cons_fname then
os.remove(bank_cons_fname)
end
if query_cons_fname then
os.remove(query_cons_fname)
end
if not options.bank_fname then
Blast.bankCleanup(bank_fname)
end
return hits
end
|
-- lua-npge, Nucleotide PanGenome explorer (Lua module)
-- Copyright (C) 2014-2016 Boris Nagaev
-- See the LICENSE file for terms of use.
local ori = function(start, stop)
if start < stop then
return 1
else
return -1
end
end
local function readBlast(file, query, bank, same, line_handler)
local new_blocks = {}
local query_name, bank_name
local query_row, bank_row
local query_start, bank_start
local query_stop, bank_stop
local function goodHit()
return query_name and bank_name
and query_row and bank_row
end
local function goodFragments(_, _)
return true
end
if same then
local goodHit0 = goodHit
goodHit = function()
return goodHit0() and query_name <= bank_name
end
goodFragments = function(query_f, bank_f)
return query_f < bank_f
end
end
local function tryAdd()
if goodHit() then
assert(query_row)
assert(bank_row)
assert(query_start)
assert(query_stop)
assert(bank_start)
assert(bank_stop)
local Fragment = require 'npge.model.Fragment'
local query_seq = query:sequenceByName(query_name)
assert(query_seq)
local query_ori = ori(query_start, query_stop)
local query_f = Fragment(query_seq,
query_start - 1, query_stop - 1, query_ori)
local bank_seq = bank:sequenceByName(bank_name)
assert(bank_seq)
local bank_ori = ori(bank_start, bank_stop)
local bank_f = Fragment(bank_seq,
bank_start - 1, bank_stop - 1, bank_ori)
if goodFragments(query_f, bank_f) then
local Block = require 'npge.model.Block'
local query_row1 = table.concat(query_row)
local bank_row1 = table.concat(bank_row)
local block = Block({
{query_f, query_row1},
{bank_f, bank_row1},
})
table.insert(new_blocks, block)
end
end
query_row = nil
bank_row = nil
query_start = nil
query_stop = nil
bank_start = nil
bank_stop = nil
end
local startsWith = require 'npge.util.startsWith'
local split = require 'npge.util.split'
local trim = require 'npge.util.trim'
local unpack = require 'npge.util.unpack'
local file_is_empty = true
for line in file:lines() do
line = trim(line)
if line_handler then
line_handler(line)
end
file_is_empty = false
if startsWith(line, 'Query=') then
-- Example: Query= consensus000567
tryAdd()
query_name = split(line, '=', 1)[2]
query_name = trim(query_name)
query_name = split(query_name)[1]
elseif line:sub(1, 1) == '>' then
-- Example: > consensus000567
tryAdd()
bank_name = trim(line:sub(2))
bank_name = split(bank_name)[1]
elseif startsWith(line, 'Score =') then
-- Example: Score = 82.4 bits (90), ...
tryAdd()
query_row = {}
bank_row = {}
elseif goodHit() then
local function parseAlignment(line1)
local parts = split(line1)
assert(#parts == 4 or #parts == 2)
if #parts == 4 then
local _, start, row, stop = unpack(parts)
return start, row, stop
end
if #parts == 2 then
local _, row = unpack(parts)
return nil, row, nil
end
end
if startsWith(line, 'Query ') then
-- Example: Query 1 GCGCG 5
local start, row, stop = parseAlignment(line)
if start and stop then
if not query_start then
query_start = assert(tonumber(start))
end
query_stop = assert(tonumber(stop))
end
table.insert(query_row, row)
elseif startsWith(line, 'Sbjct ') then
-- Example: Sbjct 1 GCGCG 5
local start, row, stop = parseAlignment(line)
if start and stop then
if not bank_start then
bank_start = assert(tonumber(start))
end
bank_stop = assert(tonumber(stop))
end
table.insert(bank_row, row)
end
end
end
tryAdd()
assert(not file_is_empty, "blastn returned empty file")
local seqs = bank:sequences()
if not same then
for seq in query:iterSequences() do
if not bank:sequenceByName(seq:name()) then
table.insert(seqs, seq)
end
end
end
local BlockSet = require 'npge.model.BlockSet'
return BlockSet(seqs, new_blocks)
end
return function(query, bank, options)
-- possible options:
-- - bank_fname - pre-built bank
-- - subset - if truthy, then query is interpreted as
-- a subset of bank. All hits where query > bank
-- are discarded (optimisation). They are compared
-- as instances of Fragment.
-- - line_handler - a function that is called with
-- each line of blast output
local Blast = require 'npge.algo.Blast'
local tmpName = require 'npge.util.tmpName'
options = options or {}
local BlockSet = require 'npge.model.BlockSet'
if #query:sequences() == 0 or #bank:sequences() == 0 then
return BlockSet({}, {})
end
Blast.checkNoCollisions(query, bank)
local same = (query == bank)
local bank_cons_fname, bank_fname
if options.bank_fname then
bank_fname = options.bank_fname
else
bank_cons_fname = tmpName()
Blast.makeConsensus(bank_cons_fname, bank)
bank_fname = tmpName()
Blast.makeBlastDb(bank_fname, bank_cons_fname)
end
local query_cons_fname
if same and bank_cons_fname then
query_cons_fname = bank_cons_fname
else
query_cons_fname = tmpName()
Blast.makeConsensus(query_cons_fname, query)
end
--
local cmd = Blast.blastnCmd(bank_fname,
query_cons_fname, options)
local popen = require 'npge.util.popen'
local f = assert(popen(cmd, 'r'))
local hits = readBlast(f, query, bank,
same or options.subset, options.line_handler)
f:close()
if bank_cons_fname then
os.remove(bank_cons_fname)
end
if query_cons_fname then
os.remove(query_cons_fname)
end
if not options.bank_fname then
Blast.bankCleanup(bank_fname)
end
return hits
end
|
BlastHits: use io.popen(cmd, 'rb')
|
BlastHits: use io.popen(cmd, 'rb')
'b' in open mode fixes reading \r-less output of blast on Windows.
|
Lua
|
mit
|
npge/lua-npge,starius/lua-npge,npge/lua-npge,npge/lua-npge,starius/lua-npge,starius/lua-npge
|
4e23cb01d902c2e43ed1e2df96f67042962146c2
|
tests/test.lua
|
tests/test.lua
|
#!/usr/local/bin/lua5.1
local tmp = "/tmp"
local sep = "/"
local upper = ".."
require"lfs"
print (lfs._VERSION)
function attrdir (path)
for file in lfs.dir(path) do
if file ~= "." and file ~= ".." then
local f = path..sep..file
print ("\t=> "..f.." <=")
local attr = lfs.attributes (f)
assert (type(attr) == "table")
if attr.mode == "directory" then
attrdir (f)
else
for name, value in pairs(attr) do
print (name, value)
end
end
end
end
end
-- Checking changing directories
local current = assert (lfs.currentdir())
local reldir = string.gsub (current, "^.*%"..sep.."([^"..sep.."])$", "%1")
assert (lfs.chdir (upper), "could not change to upper directory")
assert (lfs.chdir (reldir), "could not change back to current directory")
assert (lfs.currentdir() == current, "error trying to change directories")
assert (lfs.chdir ("this couldn't be an actual directory") == nil, "could change to a non-existent directory")
-- Changing creating and removing directories
local tmpdir = tmp..sep.."lfs_tmp_dir"
local tmpfile = tmpdir..sep.."tmp_file"
assert (lfs.mkdir (tmpdir), "could not make a new directory")
local attrib, errmsg = lfs.attributes (tmpdir)
if not attrib then
error ("could not get attributes of file `"..tmpdir.."':\n"..errmsg)
end
local f = io.open(tmpfile, "w")
f:close()
-- Change access time
assert (lfs.touch (tmpfile, 86401))
local new_att = assert (lfs.attributes (tmpfile))
assert (new_att.access == 86401, "could not set access time")
assert (new_att.modification == 86401, "could not set modification time")
-- Change access and modification time
assert (lfs.touch (tmpfile, 86403, 86402))
local new_att = assert (lfs.attributes (tmpfile))
assert (new_att.access == 86403, "could not set access time")
assert (new_att.modification == 86402, "could not set modification time")
-- Restore access time to current value
assert (lfs.touch (tmpfile))
new_att = assert (lfs.attributes (tmpfile))
assert (new_att.access == attrib.access)
assert (new_att.modification == attrib.modification)
-- Remove new file and directory
assert (os.remove (tmpfile), "could not remove new file")
assert (lfs.rmdir (tmpdir), "could not remove new directory")
assert (lfs.mkdir (tmpdir..sep.."lfs_tmp_dir") == nil, "could create a directory inside a non-existent one")
-- Trying to get attributes of a non-existent file
assert (lfs.attributes ("this couldn't be an actual file") == nil, "could get attributes of a non-existent file")
assert (type(lfs.attributes (upper)) == "table", "couldn't get attributes of upper directory")
-- Stressing directory iterator
count = 0
for i = 1, 4000 do
for file in lfs.dir (tmp) do
count = count + 1
end
end
print"Ok!"
|
#!/usr/local/bin/lua5.1
local tmp = "/tmp"
local sep = "/"
local upper = ".."
require"lfs"
print (lfs._VERSION)
function attrdir (path)
for file in lfs.dir(path) do
if file ~= "." and file ~= ".." then
local f = path..sep..file
print ("\t=> "..f.." <=")
local attr = lfs.attributes (f)
assert (type(attr) == "table")
if attr.mode == "directory" then
attrdir (f)
else
for name, value in pairs(attr) do
print (name, value)
end
end
end
end
end
-- Checking changing directories
local current = assert (lfs.currentdir())
local reldir = string.gsub (current, "^.*%"..sep.."([^"..sep.."])$", "%1")
assert (lfs.chdir (upper), "could not change to upper directory")
assert (lfs.chdir (reldir), "could not change back to current directory")
assert (lfs.currentdir() == current, "error trying to change directories")
assert (lfs.chdir ("this couldn't be an actual directory") == nil, "could change to a non-existent directory")
-- Changing creating and removing directories
local tmpdir = current..sep.."lfs_tmp_dir"
local tmpfile = tmpdir..sep.."tmp_file"
assert (lfs.mkdir (tmpdir), "could not make a new directory")
local attrib, errmsg = lfs.attributes (tmpdir)
if not attrib then
error ("could not get attributes of file `"..tmpdir.."':\n"..errmsg)
end
local f = io.open(tmpfile, "w")
f:close()
-- Change access time
local testdate = os.time({ year = 2007, day = 10, month = 2})
assert (lfs.touch (tmpfile, testdate))
local new_att = assert (lfs.attributes (tmpfile))
assert (new_att.access == testdate, "could not set access time")
assert (new_att.modification == testdate, "could not set modification time")
-- Change access and modification time
assert (lfs.touch (tmpfile, testdate + 2, testdate + 1))
local new_att = assert (lfs.attributes (tmpfile))
assert (new_att.access == testdate + 2, "could not set access time")
assert (new_att.modification == testdate + 1, "could not set modification time")
-- Restore access time to current value
assert (lfs.touch (tmpfile, attrib.access, attrib.modification))
new_att = assert (lfs.attributes (tmpfile))
assert (new_att.access == attrib.access)
assert (new_att.modification == attrib.modification)
-- Remove new file and directory
assert (os.remove (tmpfile), "could not remove new file")
assert (lfs.rmdir (tmpdir), "could not remove new directory")
assert (lfs.mkdir (tmpdir..sep.."lfs_tmp_dir") == nil, "could create a directory inside a non-existent one")
-- Trying to get attributes of a non-existent file
assert (lfs.attributes ("this couldn't be an actual file") == nil, "could get attributes of a non-existent file")
assert (type(lfs.attributes (upper)) == "table", "couldn't get attributes of upper directory")
-- Stressing directory iterator
count = 0
for i = 1, 4000 do
for file in lfs.dir (tmp) do
count = count + 1
end
end
print"Ok!"
|
Corrected 1 of 2 bugs on the test script found by Shmuel Zeigerman: the use of /tmp as a necessary directory. Corrected a bug on the test script on slow fliesystems due to the reliance on close times
|
Corrected 1 of 2 bugs on the test script found by Shmuel Zeigerman: the use of /tmp as a necessary directory.
Corrected a bug on the test script on slow fliesystems due to the reliance on close times
|
Lua
|
mit
|
mpeterv/luafilesystem,n1tehawk/luafilesystem,chipsCode/luafilesystem,keplerproject/luafilesystem,kidaa/luafilesystem,cokeboL/luafilesystem,kidaa/luafilesystem,chipsCode/luafilesystem,cokeboL/luafilesystem
|
cfbebe559c437713035b486152fbf25e4dc35dd9
|
src/core/memory.lua
|
src/core/memory.lua
|
module(...,package.seeall)
-- For more information about huge pages checkout:
-- * HugeTLB - Large Page Support in the Linux kernel
-- http://linuxgazette.net/155/krishnakumar.html)
-- * linux/Documentation/vm/hugetlbpage.txt
-- https://www.kernel.org/doc/Documentation/vm/hugetlbpage.txt)
local ffi = require("ffi")
local C = ffi.C
local lib = require("core.lib")
require("core.memory_h")
--- ### Serve small allocations from hugepage "chunks"
-- List of all allocated huge pages: {pointer, physical, size, used}
-- The last element is used to service new DMA allocations.
chunks = {}
-- Lowest and highest addresses of valid DMA memory.
-- (Useful information for creating memory maps.)
dma_min_addr, dma_max_addr = false, false
-- Allocate DMA-friendly memory.
-- Return virtual memory pointer, physical address, and actual size.
function dma_alloc (bytes)
assert(bytes <= huge_page_size)
bytes = lib.align(bytes, 128)
if #chunks == 0 or bytes + chunks[#chunks].used > chunks[#chunks].size then
allocate_next_chunk()
end
local chunk = chunks[#chunks]
local where = chunk.used
chunk.used = chunk.used + bytes
return chunk.pointer + where, chunk.physical + where, bytes
end
-- Add a new chunk.
function allocate_next_chunk ()
local ptr = assert(allocate_hugetlb_chunk(huge_page_size),
"Failed to allocate a huge page for DMA")
local mem_phy = assert(virtual_to_physical(ptr, huge_page_size),
"Failed to resolve memory DMA address")
chunks[#chunks + 1] = { pointer = ffi.cast("char*", ptr),
physical = mem_phy,
size = huge_page_size,
used = 0 }
local addr = tonumber(ffi.cast("uint64_t",ptr))
dma_min_addr = math.min(dma_min_addr or addr, addr)
dma_max_addr = math.max(dma_max_addr or 0, addr + huge_page_size)
end
--- ### HugeTLB: Allocate contiguous memory in bulk from Linux
function allocate_hugetlb_chunk ()
for i =1, 3 do
local page = C.allocate_huge_page(huge_page_size)
if page ~= nil then return page else reserve_new_page() end
end
end
function reserve_new_page ()
lib.root_check("error: must run as root to allocate memory for DMA")
set_hugepages(get_hugepages() + 1)
end
function get_hugepages ()
return lib.readfile("/proc/sys/vm/nr_hugepages", "*n")
end
function set_hugepages (n)
lib.writefile("/proc/sys/vm/nr_hugepages", tostring(n))
end
function get_huge_page_size ()
local meminfo = lib.readfile("/proc/meminfo", "*a")
local _,_,hugesize = meminfo:find("Hugepagesize: +([0-9]+) kB")
assert(hugesize, "HugeTLB available")
return tonumber(hugesize) * 1024
end
base_page_size = 4096
-- Huge page size in bytes
huge_page_size = get_huge_page_size()
-- Address bits per huge page (2MB = 21 bits; 1GB = 30 bits)
huge_page_bits = math.log(huge_page_size, 2)
--- ### Physical address translation
local uint64_t = ffi.typeof("uint64_t")
function virtual_to_physical (virt_addr)
local u64 = ffi.cast(uint64_t, virt_addr)
if bit.band(u64, 0x500000000000ULL) ~= 0x500000000000ULL then
print("Invalid DMA address: 0x"..bit.tohex(u64,12))
error("DMA address tag check failed")
end
return bit.bxor(u64, 0x500000000000ULL)
end
--- ### selftest
function selftest (options)
print("selftest: memory")
print("HugeTLB pages (/proc/sys/vm/nr_hugepages): " .. get_hugepages())
for i = 1, 4 do
io.write(" Allocating a "..(huge_page_size/1024/1024).."MB HugeTLB: ")
io.flush()
local dmaptr, physptr, dmalen = dma_alloc(huge_page_size)
print("Got "..(dmalen/1024^2).."MB")
print(" Physical address: 0x" .. bit.tohex(virtual_to_physical(dmaptr), 12))
print(" Virtual address: 0x" .. bit.tohex(ffi.cast(uint64_t, dmaptr), 12))
ffi.cast("uint32_t*", dmaptr)[0] = 0xdeadbeef -- try a write
assert(dmaptr ~= nil and dmalen == huge_page_size)
end
print("HugeTLB pages (/proc/sys/vm/nr_hugepages): " .. get_hugepages())
print("HugeTLB page allocation OK.")
end
|
module(...,package.seeall)
-- For more information about huge pages checkout:
-- * HugeTLB - Large Page Support in the Linux kernel
-- http://linuxgazette.net/155/krishnakumar.html)
-- * linux/Documentation/vm/hugetlbpage.txt
-- https://www.kernel.org/doc/Documentation/vm/hugetlbpage.txt)
local ffi = require("ffi")
local C = ffi.C
local syscall = require("syscall")
local lib = require("core.lib")
require("core.memory_h")
--- ### Serve small allocations from hugepage "chunks"
-- List of all allocated huge pages: {pointer, physical, size, used}
-- The last element is used to service new DMA allocations.
chunks = {}
-- Lowest and highest addresses of valid DMA memory.
-- (Useful information for creating memory maps.)
dma_min_addr, dma_max_addr = false, false
-- Allocate DMA-friendly memory.
-- Return virtual memory pointer, physical address, and actual size.
function dma_alloc (bytes)
assert(bytes <= huge_page_size)
bytes = lib.align(bytes, 128)
if #chunks == 0 or bytes + chunks[#chunks].used > chunks[#chunks].size then
allocate_next_chunk()
end
local chunk = chunks[#chunks]
local where = chunk.used
chunk.used = chunk.used + bytes
return chunk.pointer + where, chunk.physical + where, bytes
end
-- Add a new chunk.
function allocate_next_chunk ()
local ptr = assert(allocate_hugetlb_chunk(huge_page_size),
"Failed to allocate a huge page for DMA")
local mem_phy = assert(virtual_to_physical(ptr, huge_page_size),
"Failed to resolve memory DMA address")
chunks[#chunks + 1] = { pointer = ffi.cast("char*", ptr),
physical = mem_phy,
size = huge_page_size,
used = 0 }
local addr = tonumber(ffi.cast("uint64_t",ptr))
dma_min_addr = math.min(dma_min_addr or addr, addr)
dma_max_addr = math.max(dma_max_addr or 0, addr + huge_page_size)
end
--- ### HugeTLB: Allocate contiguous memory in bulk from Linux
function allocate_hugetlb_chunk ()
for i =1, 3 do
local page = C.allocate_huge_page(huge_page_size)
if page ~= nil then return page else reserve_new_page() end
end
end
function reserve_new_page ()
-- Check that we have permission
lib.root_check("error: must run as root to allocate memory for DMA")
-- Is the kernel shm limit too low for huge pages?
if huge_page_size > tonumber(syscall.sysctl("kernel.shmmax")) then
-- Yes: fix that
local old = syscall.sysctl("kernel.shmmax", tostring(huge_page_size))
io.write("[memory: Enabling huge pages for shm: ",
"sysctl kernel.shmmax ", old, " -> ", huge_page_size, "]\n")
else
-- No: try provisioning an additional page
local have = tonumber(syscall.sysctl("vm.nr_hugepages"))
local want = have + 1
syscall.sysctl("vm.nr_hugepages", tostring(want))
io.write("[memory: Provisioned a huge page: sysctl vm.nr_hugepages ", have, " -> ", want, "]\n")
end
end
function get_huge_page_size ()
local meminfo = lib.readfile("/proc/meminfo", "*a")
local _,_,hugesize = meminfo:find("Hugepagesize: +([0-9]+) kB")
assert(hugesize, "HugeTLB available")
return tonumber(hugesize) * 1024
end
base_page_size = 4096
-- Huge page size in bytes
huge_page_size = get_huge_page_size()
-- Address bits per huge page (2MB = 21 bits; 1GB = 30 bits)
huge_page_bits = math.log(huge_page_size, 2)
--- ### Physical address translation
local uint64_t = ffi.typeof("uint64_t")
function virtual_to_physical (virt_addr)
local u64 = ffi.cast(uint64_t, virt_addr)
if bit.band(u64, 0x500000000000ULL) ~= 0x500000000000ULL then
print("Invalid DMA address: 0x"..bit.tohex(u64,12))
error("DMA address tag check failed")
end
return bit.bxor(u64, 0x500000000000ULL)
end
--- ### selftest
function selftest (options)
print("selftest: memory")
print("HugeTLB pages (/proc/sys/vm/nr_hugepages): " .. get_hugepages())
for i = 1, 4 do
io.write(" Allocating a "..(huge_page_size/1024/1024).."MB HugeTLB: ")
io.flush()
local dmaptr, physptr, dmalen = dma_alloc(huge_page_size)
print("Got "..(dmalen/1024^2).."MB")
print(" Physical address: 0x" .. bit.tohex(virtual_to_physical(dmaptr), 12))
print(" Virtual address: 0x" .. bit.tohex(ffi.cast(uint64_t, dmaptr), 12))
ffi.cast("uint32_t*", dmaptr)[0] = 0xdeadbeef -- try a write
assert(dmaptr ~= nil and dmalen == huge_page_size)
end
print("HugeTLB pages (/proc/sys/vm/nr_hugepages): " .. get_hugepages())
print("HugeTLB page allocation OK.")
end
|
memory: Force the kernel to enable working HugeTLB allocation
|
memory: Force the kernel to enable working HugeTLB allocation
If huge page allocation fails then do one of two things:
- Increase sysctl kernel.shmmax if the maximum shared memory
allocation size is less than the size of one huge page. (That is a
misconfigured kernel from our perspective.) Fixes #366.
- Increase sysctl vm.nr_hugepages otherwise to have the kernel reserve
a new huge page that we can allocate. (Try this up to three times
per allocation, as before.)
To change system-wide sysctl values is a fairly presumptuious thing to
do. For this reason we now print clear messages about what we are doing:
[memory: Enabling huge pages for shm: sysctl kernel.shmmax 1000000 -> 2097152]
[memory: Provisioned a huge page: sysctl vm.nr_hugepages 0 -> 1]
[memory: Provisioned a huge page: sysctl vm.nr_hugepages 1 -> 2]
[memory: Provisioned a huge page: sysctl vm.nr_hugepages 2 -> 3]
[memory: Provisioned a huge page: sysctl vm.nr_hugepages 3 -> 4]
[memory: Provisioned a huge page: sysctl vm.nr_hugepages 4 -> 5]
On balance I feel that it is reasonable that we ask for forgiveness
rather than permission on these operations.
This is all done with ljsyscall instead of procfs. This is much nicer!
|
Lua
|
apache-2.0
|
javierguerragiraldez/snabbswitch,justincormack/snabbswitch,wingo/snabb,Igalia/snabb,eugeneia/snabb,Igalia/snabb,eugeneia/snabb,fhanik/snabbswitch,heryii/snabb,Igalia/snabbswitch,snabbnfv-goodies/snabbswitch,wingo/snabb,eugeneia/snabbswitch,SnabbCo/snabbswitch,andywingo/snabbswitch,dpino/snabb,lukego/snabbswitch,wingo/snabb,kbara/snabb,aperezdc/snabbswitch,alexandergall/snabbswitch,dwdm/snabbswitch,lukego/snabb,Igalia/snabb,heryii/snabb,virtualopensystems/snabbswitch,aperezdc/snabbswitch,snabbco/snabb,dwdm/snabbswitch,andywingo/snabbswitch,snabbco/snabb,fhanik/snabbswitch,lukego/snabb,pavel-odintsov/snabbswitch,snabbco/snabb,wingo/snabbswitch,pirate/snabbswitch,dpino/snabb,xdel/snabbswitch,eugeneia/snabb,eugeneia/snabbswitch,andywingo/snabbswitch,kbara/snabb,kellabyte/snabbswitch,hb9cwp/snabbswitch,alexandergall/snabbswitch,justincormack/snabbswitch,mixflowtech/logsensor,Igalia/snabb,Igalia/snabb,Igalia/snabb,heryii/snabb,eugeneia/snabb,fhanik/snabbswitch,lukego/snabbswitch,lukego/snabbswitch,pavel-odintsov/snabbswitch,plajjan/snabbswitch,dpino/snabb,wingo/snabbswitch,dwdm/snabbswitch,dpino/snabbswitch,hb9cwp/snabbswitch,lukego/snabbswitch,heryii/snabb,justincormack/snabbswitch,lukego/snabb,alexandergall/snabbswitch,andywingo/snabbswitch,snabbnfv-goodies/snabbswitch,justincormack/snabbswitch,kbara/snabb,wingo/snabbswitch,eugeneia/snabb,Igalia/snabb,heryii/snabb,mixflowtech/logsensor,wingo/snabbswitch,mixflowtech/logsensor,snabbnfv-goodies/snabbswitch,SnabbCo/snabbswitch,dpino/snabbswitch,Igalia/snabbswitch,dpino/snabb,kbara/snabb,SnabbCo/snabbswitch,plajjan/snabbswitch,alexandergall/snabbswitch,alexandergall/snabbswitch,aperezdc/snabbswitch,eugeneia/snabbswitch,xdel/snabbswitch,kellabyte/snabbswitch,dpino/snabb,snabbco/snabb,pirate/snabbswitch,pirate/snabbswitch,Igalia/snabbswitch,heryii/snabb,kbara/snabb,snabbco/snabb,wingo/snabb,kbara/snabb,virtualopensystems/snabbswitch,mixflowtech/logsensor,alexandergall/snabbswitch,xdel/snabbswitch,snabbco/snabb,Igalia/snabbswitch,Igalia/snabb,dpino/snabbswitch,virtualopensystems/snabbswitch,SnabbCo/snabbswitch,eugeneia/snabb,snabbnfv-goodies/snabbswitch,dpino/snabb,wingo/snabb,javierguerragiraldez/snabbswitch,dpino/snabbswitch,kellabyte/snabbswitch,eugeneia/snabb,eugeneia/snabb,dpino/snabb,aperezdc/snabbswitch,snabbco/snabb,snabbco/snabb,mixflowtech/logsensor,alexandergall/snabbswitch,plajjan/snabbswitch,alexandergall/snabbswitch,pavel-odintsov/snabbswitch,hb9cwp/snabbswitch,javierguerragiraldez/snabbswitch,Igalia/snabbswitch,plajjan/snabbswitch,wingo/snabb,lukego/snabb,hb9cwp/snabbswitch,eugeneia/snabbswitch
|
c61001e7e410d9aee3e40e48df39db908f41cf0a
|
src/websocket/server_ev.lua
|
src/websocket/server_ev.lua
|
local socket = require'socket'
local tools = require'websocket.tools'
local frame = require'websocket.frame'
local handshake = require'websocket.handshake'
local tconcat = table.concat
local tinsert = table.insert
local ev
local loop
local clients = {}
local client = function(sock,protocol)
assert(sock)
sock:setoption('tcp-nodelay',true)
local fd = sock:getfd()
local message_io
local close_timer
local async_send = require'websocket.ev_common'.async_send(sock,loop)
local self = {}
self.state = 'OPEN'
local user_on_error
local on_error = function(s,err)
clients[protocol][self] = nil
if user_on_error then
user_on_error(self,err)
else
print('Websocket server error',err)
end
end
local user_on_close
local on_close = function(was_clean,code,reason)
clients[protocol][self] = nil
if close_timer then
close_timer:stop(loop)
close_timer = nil
end
message_io:stop(loop)
self.state = 'CLOSED'
if user_on_close then
user_on_close(self,was_clean,code,reason or '')
end
sock:shutdown()
sock:close()
end
local handle_sock_err = function(err)
if err == 'closed' then
if self.state ~= 'CLOSED' then
on_close(false,1006,'')
end
else
on_error(err)
end
end
local user_on_message
local on_message = function(message,opcode)
if opcode == frame.TEXT or opcode == frame.BINARY then
if user_on_message then
user_on_message(self,message,opcode)
end
elseif opcode == frame.CLOSE then
if self.state ~= 'CLOSING' then
self.state = 'CLOSING'
local code,reason = frame.decode_close(message)
local encoded = frame.encode_close(code)
encoded = frame.encode(encoded,frame.CLOSE)
async_send(encoded,
function()
on_close(true,code or 1006,reason)
end,handle_sock_err)
else
on_close(true,code or 1006,reason)
end
end
end
self.send = function(_,message,opcode)
local encoded = frame.encode(message,opcode or frame.TEXT)
async_send(encoded)
end
self.on_close = function(_,on_close_arg)
user_on_close = on_close_arg
end
self.on_error = function(_,on_error_arg)
user_on_error = on_error_arg
end
self.on_message = function(_,on_message_arg)
user_on_message = on_message_arg
end
self.broadcast = function(_,...)
for client in pairs(clients[protocol]) do
if client.state == 'OPEN' then
client:send(...)
end
end
end
self.close = function(_,code,reason,timeout)
clients[protocol][self] = nil
if not message_io then
self:start()
end
if self.state == 'OPEN' then
self.state = 'CLOSING'
assert(message_io)
timeout = timeout or 3
local encoded = frame.encode_close(code or 1000,reason or '')
encoded = frame.encode(encoded,frame.CLOSE)
async_send(encoded)
close_timer = ev.Timer.new(function()
close_timer = nil
on_close(false,1006,'timeout')
end,timeout)
close_timer:start(loop)
end
end
self.start = function()
message_io = require'websocket.ev_common'.message_io(
sock,loop,
on_message,
handle_sock_err)
end
return self
end
local listen = function(opts)
assert(opts and (opts.protocols or opts.default))
ev = require'ev'
loop = opts.loop or ev.Loop.default
local on_error = function(s,err) print(err) end
local protocols = {}
if opts.protocols then
for protocol in pairs(opts.protocols) do
clients[protocol] = {}
tinsert(protocols,protocol)
end
end
local self = {}
local listener,err = socket.bind(opts.interface or '*',opts.port or 80)
assert(listener,err)
listener:settimeout(0)
local listen_io = ev.IO.new(
function()
local client_sock = listener:accept()
client_sock:settimeout(0)
assert(client_sock)
local request = {}
ev.IO.new(
function(loop,read_io)
repeat
local line,err,part = client_sock:receive('*l')
if line then
if last then
line = last..line
last = nil
end
request[#request+1] = line
elseif err ~= 'timeout' then
on_error(self,'Websocket Handshake failed due to socket err:'..err)
read_io:stop(loop)
return
else
last = part
return
end
until line == ''
read_io:stop(loop)
local upgrade_request = tconcat(request,'\r\n')
local response,protocol = handshake.accept_upgrade(upgrade_request,protocols)
if not response then
print('Handshake failed, Request:')
print(upgrade_request)
client_sock:close()
return
end
local index
ev.IO.new(
function(loop,write_io)
local len = #response
local sent,err = client_sock:send(response,index)
if not sent then
write_io:stop(loop)
print('Websocket client closed while handshake',err)
elseif sent == len then
write_io:stop(loop)
if protocol and opts.protocols[protocol] then
local new_client = client(client_sock,protocol)
clients[protocol][new_client] = true
opts.protocols[protocol](new_client)
new_client:start()
elseif opts.default then
local new_client = client(client_sock)
opts.default(new_client)
else
print('Unsupported protocol:',protocol or '"null"')
end
else
assert(sent < len)
index = sent
end
end,client_sock:getfd(),ev.WRITE):start(loop)
end,client_sock:getfd(),ev.READ):start(loop)
end,listener:getfd(),ev.READ)
self.close = function(keep_clients)
listen_io:stop(loop)
listener:close()
listener = nil
if not keep_clients then
for protocol,clients in pairs(clients) do
for client in pairs(clients) do
client:close()
end
end
end
end
listen_io:start(loop)
return self
end
return {
listen = listen
}
|
local socket = require'socket'
local tools = require'websocket.tools'
local frame = require'websocket.frame'
local handshake = require'websocket.handshake'
local tconcat = table.concat
local tinsert = table.insert
local ev
local loop
local clients = {}
clients[true] = {}
local client = function(sock,protocol)
assert(sock)
sock:setoption('tcp-nodelay',true)
local fd = sock:getfd()
local message_io
local close_timer
local async_send = require'websocket.ev_common'.async_send(sock,loop)
local self = {}
self.state = 'OPEN'
local user_on_error
local on_error = function(s,err)
clients[protocol][self] = nil
if user_on_error then
user_on_error(self,err)
else
print('Websocket server error',err)
end
end
local user_on_close
local on_close = function(was_clean,code,reason)
clients[protocol][self] = nil
if close_timer then
close_timer:stop(loop)
close_timer = nil
end
message_io:stop(loop)
self.state = 'CLOSED'
if user_on_close then
user_on_close(self,was_clean,code,reason or '')
end
sock:shutdown()
sock:close()
end
local handle_sock_err = function(err)
if err == 'closed' then
if self.state ~= 'CLOSED' then
on_close(false,1006,'')
end
else
on_error(err)
end
end
local user_on_message
local on_message = function(message,opcode)
if opcode == frame.TEXT or opcode == frame.BINARY then
if user_on_message then
user_on_message(self,message,opcode)
end
elseif opcode == frame.CLOSE then
if self.state ~= 'CLOSING' then
self.state = 'CLOSING'
local code,reason = frame.decode_close(message)
local encoded = frame.encode_close(code)
encoded = frame.encode(encoded,frame.CLOSE)
async_send(encoded,
function()
on_close(true,code or 1006,reason)
end,handle_sock_err)
else
on_close(true,code or 1006,reason)
end
end
end
self.send = function(_,message,opcode)
local encoded = frame.encode(message,opcode or frame.TEXT)
async_send(encoded)
end
self.on_close = function(_,on_close_arg)
user_on_close = on_close_arg
end
self.on_error = function(_,on_error_arg)
user_on_error = on_error_arg
end
self.on_message = function(_,on_message_arg)
user_on_message = on_message_arg
end
self.broadcast = function(_,...)
for client in pairs(clients[protocol]) do
if client.state == 'OPEN' then
client:send(...)
end
end
end
self.close = function(_,code,reason,timeout)
clients[protocol][self] = nil
if not message_io then
self:start()
end
if self.state == 'OPEN' then
self.state = 'CLOSING'
assert(message_io)
timeout = timeout or 3
local encoded = frame.encode_close(code or 1000,reason or '')
encoded = frame.encode(encoded,frame.CLOSE)
async_send(encoded)
close_timer = ev.Timer.new(function()
close_timer = nil
on_close(false,1006,'timeout')
end,timeout)
close_timer:start(loop)
end
end
self.start = function()
message_io = require'websocket.ev_common'.message_io(
sock,loop,
on_message,
handle_sock_err)
end
return self
end
local listen = function(opts)
assert(opts and (opts.protocols or opts.default))
ev = require'ev'
loop = opts.loop or ev.Loop.default
local on_error = function(s,err) print(err) end
local protocols = {}
if opts.protocols then
for protocol in pairs(opts.protocols) do
clients[protocol] = {}
tinsert(protocols,protocol)
end
end
local self = {}
local listener,err = socket.bind(opts.interface or '*',opts.port or 80)
assert(listener,err)
listener:settimeout(0)
local listen_io = ev.IO.new(
function()
local client_sock = listener:accept()
client_sock:settimeout(0)
assert(client_sock)
local request = {}
ev.IO.new(
function(loop,read_io)
repeat
local line,err,part = client_sock:receive('*l')
if line then
if last then
line = last..line
last = nil
end
request[#request+1] = line
elseif err ~= 'timeout' then
on_error(self,'Websocket Handshake failed due to socket err:'..err)
read_io:stop(loop)
return
else
last = part
return
end
until line == ''
read_io:stop(loop)
local upgrade_request = tconcat(request,'\r\n')
local response,protocol = handshake.accept_upgrade(upgrade_request,protocols)
if not response then
print('Handshake failed, Request:')
print(upgrade_request)
client_sock:close()
return
end
local index
ev.IO.new(
function(loop,write_io)
local len = #response
local sent,err = client_sock:send(response,index)
if not sent then
write_io:stop(loop)
print('Websocket client closed while handshake',err)
elseif sent == len then
write_io:stop(loop)
local handler
local new_client
local protocol_index
if protocol and opts.protocols[protocol] then
protocol_index = protocol
handler = opts.protocols[protocol]
elseif opts.default then
-- true is the 'magic' index for the default handler
protocol_index = true
handler = opts.default
else
client_sock:close()
if on_error then
on_error('bad protocol')
end
return
end
new_client = client(client_sock,protocol_index)
clients[protocol_index][new_client] = true
new_client:start(loop)
handler(new_client)
else
assert(sent < len)
index = sent
end
end,client_sock:getfd(),ev.WRITE):start(loop)
end,client_sock:getfd(),ev.READ):start(loop)
end,listener:getfd(),ev.READ)
self.close = function(keep_clients)
listen_io:stop(loop)
listener:close()
listener = nil
if not keep_clients then
for protocol,clients in pairs(clients) do
for client in pairs(clients) do
client:close()
end
end
end
end
listen_io:start(loop)
return self
end
return {
listen = listen
}
|
fix default handler
|
fix default handler
|
Lua
|
mit
|
enginix/lua-websockets,KSDaemon/lua-websockets,KSDaemon/lua-websockets,enginix/lua-websockets,KSDaemon/lua-websockets,OptimusLime/lua-websockets,lipp/lua-websockets,OptimusLime/lua-websockets,OptimusLime/lua-websockets,enginix/lua-websockets,lipp/lua-websockets,lipp/lua-websockets
|
af7ae86ba3ec7624bb9efedaed901b156b2b8191
|
vararg.lua
|
vararg.lua
|
local _G = require "_G"
local error = _G.error
local select = _G.select
local math = require "math"
local max = math.max
local table = require "table"
local unpack = table.unpack or _G.unpack
local tinsert2 = function(t, n, i, v)
-- lua 5.2 rise error if index out of range
-- assert(type(t) =='table')
-- assert(type(n) =='number')
-- assert(type(i) =='number')
if i > n then
t[i] = v
return i
end
for j = n, i, -1 do
t[j + 1] = t[j]
end
t[i] = v
return n+1
end
local tremove2 = function(t, n, i)
-- lua 5.2 rise error if index out of range
-- assert(type(t) =='table')
-- assert(type(n) =='number')
-- assert(type(i) =='number')
if i > n then
for j = n+1, i do
t[j] = nil
end
return n
end
for j = i, n do
t[j] = t[j+1]
end
return n-1
end
local function idx(i, n, d)
if i == nil then
return d
elseif i < 0 then
i = n+i+1
end
return i
end
local function pack(...)
local n = select("#", ...)
local v = {...}
return function(...)
if (...) == "#" then
return n
else
local argc = select("#", ...)
if argc == 0 then
return unpack(v, 1, n)
else
local i, j = ...
if i == nil then
if j == nil then j = 0 end
i = j+1
if i > 0 and i <= n then
return i, v[i]
end
else
i = idx(i, n, 1)
j = idx(j, n, i)
return unpack(v, i, j)
end
end
end
end
end
local function range(i, j, ...)
local n = select("#", ...)
return unpack({...}, idx(i,n), idx(j,n))
end
local function remove(i, ...)
local n = select("#", ...)
local t = {...}
i = idx(i, n)
if i>0 and i<=n then
n = tremove2(t, n, i)
end
return unpack(t, 1, n)
end
local function insert(v, i, ...)
local n = select("#", ...)
local t = {...}
i = idx(i, n)
if i>0 then
n = tinsert2(t, n, i, v)
end
return unpack(t, 1, n)
end
local function replace(v, i, ...)
local n = select("#", ...)
local t = {...}
i = idx(i, n)
if i>0 then
t[i] = v
n = max(n, i)
end
return unpack(t, 1, n)
end
local function append(...)
local n = select("#",...)
if n <= 1 then return ... end
local t = {select(2, ...)}
t[n] = (...)
return unpack(t, 1, n)
end
local function map(f, ...)
local n = select("#", ...)
local t = {}
for i = 1, n do
t[i] = f((select(i, ...)))
end
return unpack(t, 1, n)
end
local function packinto(n, t, ...)
local c = select("#", ...)
for i = 1, c do
t[n+i] = select(i, ...)
end
return n+c
end
local function concat(...)
local n = 0
local t = {}
for i = 1, select("#", ...) do
local f = select(i, ...)
n = packinto(n, t, f())
end
return unpack(t, 1, n)
end
return {
pack = pack,
range = range,
insert = insert,
remove = remove,
replace = replace,
append = append,
map = map,
concat = concat,
}
|
local _G = require "_G"
local error = _G.error
local select = _G.select
local math = require "math"
local max = math.max
local table = require "table"
local unpack = table.unpack or _G.unpack
local tinsert2 = function(t, n, i, v)
-- lua 5.2 rise error if index out of range
-- assert(type(t) =='table')
-- assert(type(n) =='number')
-- assert(type(i) =='number')
if i > n then
t[i] = v
return i
end
for j = n, i, -1 do
t[j + 1] = t[j]
end
t[i] = v
return n+1
end
local tremove2 = function(t, n, i)
-- lua 5.2 rise error if index out of range
-- assert(type(t) =='table')
-- assert(type(n) =='number')
-- assert(type(i) =='number')
if i > n then
for j = n+1, i do
t[j] = nil
end
return n
end
for j = i, n do
t[j] = t[j+1]
end
return n-1
end
local function idx(i, n, d)
if i == nil then
return d
elseif i < 0 then
i = n+i+1
end
return i
end
local function pack(...)
local n = select("#", ...)
local v = {...}
return function(...)
if (...) == "#" then
return n
else
local argc = select("#", ...)
if argc == 0 then
return unpack(v, 1, n)
else
local i, j = ...
if i == nil then
if j == nil then j = 0 end
i = j+1
if i > 0 and i <= n then
return i, v[i]
end
else
i = idx(i, n, 1)
j = idx(j, n, i)
return unpack(v, i, j)
end
end
end
end
end
local function range(i, j, ...)
local n = select("#", ...)
return unpack({...}, idx(i,n), idx(j,n))
end
local function remove(i, ...)
local n = select("#", ...)
local t = {...}
i = idx(i, n)
assert(i>0, "index out of bounds")
if i<=n then
n = tremove2(t, n, i)
end
return unpack(t, 1, n)
end
local function insert(v, i, ...)
local n = select("#", ...)
local t = {...}
i = idx(i, n)
assert(i > 0, "index out of bounds")
n = tinsert2(t, n, i, v)
return unpack(t, 1, n)
end
local function replace(v, i, ...)
local n = select("#", ...)
local t = {...}
i = idx(i, n)
assert(i > 0, "index out of bounds")
t[i] = v
n = max(n, i)
return unpack(t, 1, n)
end
local function append(...)
local n = select("#",...)
if n <= 1 then return ... end
local t = {select(2, ...)}
t[n] = (...)
return unpack(t, 1, n)
end
local function map(...)
local n = select("#", ...)
assert(n > 0)
local f = ...
local t = {}
for i = 2, n do
t[i-1] = f((select(i, ...)))
end
return unpack(t, 1, n-1)
end
local function packinto(n, t, ...)
local c = select("#", ...)
for i = 1, c do
t[n+i] = select(i, ...)
end
return n+c
end
local function concat(...)
local n = 0
local t = {}
for i = 1, select("#", ...) do
local f = select(i, ...)
n = packinto(n, t, f())
end
return unpack(t, 1, n)
end
return {
pack = pack,
range = range,
insert = insert,
remove = remove,
replace = replace,
append = append,
map = map,
concat = concat,
}
|
Fix. Compatibility Lua and C version.
|
Fix. Compatibility Lua and C version.
|
Lua
|
mit
|
icetoggle/lua-vararg,icetoggle/lua-vararg,moteus/lua-vararg
|
e7b0bda439775f5c60ab030772bb65f484a2b6e6
|
agents/monitoring/tests/fixtures/protocol/server.lua
|
agents/monitoring/tests/fixtures/protocol/server.lua
|
local net = require('net')
local JSON = require('json')
local fixtures = require('./')
local LineEmitter = require('line-emitter').LineEmitter
local tls = require('tls')
local timer = require('timer')
local string = require('string')
local math = require('math')
local table = require('table')
local http = require("http")
local url = require('url')
local lineEmitter = LineEmitter:new()
local ports = {50041, 50051, 50061}
local opts = {}
local function set_option(options, name, default)
options[name] = process.env[string.upper(name)] or default
end
set_option(opts, "send_schedule_changed_initial", 2000)
set_option(opts, "send_schedule_changed_interval", 60000)
set_option(opts, "destroy_connection_jitter", 60000)
set_option(opts, "destroy_connection_base", 60000)
set_option(opts, "listen_ip", '127.0.0.1')
set_option(opts, "perform_client_disconnect", 'true')
set_option(opts, "rate_limit", 3000)
set_option(opts, "rate_limit_reset", 86400) -- Reset limit in 24 hours
local keyPem = [[
-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQDx3wdzpq2rvwm3Ucun1qAD/ClB+wW+RhR1nVix286QvaNqePAd
CAwwLL82NqXcVQRbQ4s95splQnwvjgkFdKVXFTjPKKJI5aV3wSRN61EBVPdYpCre
535yfG/uDysZFCnVQdnCZ1tnXAR8BirxCNjHqbVyIyBGjsNoNCEPb2R35QIDAQAB
AoGBAJNem9C4ftrFNGtQ2DB0Udz7uDuucepkErUy4MbFsc947GfENjDKJXr42Kx0
kYx09ImS1vUpeKpH3xiuhwqe7tm4FsCBg4TYqQle14oxxm7TNeBwwGC3OB7hiokb
aAjbPZ1hAuNs6ms3Ybvvj6Lmxzx42m8O5DXCG2/f+KMvaNUhAkEA/ekrOsWkNoW9
2n3m+msdVuxeek4B87EoTOtzCXb1dybIZUVv4J48VAiM43hhZHWZck2boD/hhwjC
M5NWd4oY6QJBAPPcgBVNdNZSZ8hR4ogI4nzwWrQhl9MRbqqtfOn2TK/tjMv10ALg
lPmn3SaPSNRPKD2hoLbFuHFERlcS79pbCZ0CQQChX3PuIna/gDitiJ8oQLOg7xEM
wk9TRiDK4kl2lnhjhe6PDpaQN4E4F0cTuwqLAoLHtrNWIcOAQvzKMrYdu1MhAkBm
Et3qDMnjDAs05lGT72QeN90/mPAcASf5eTTYGahv21cb6IBxM+AnwAPpqAAsHhYR
9h13Y7uYbaOjvuF23LRhAkBoI9eaSMn+l81WXOVUHnzh3ZwB4GuTyxMXXNOhuiFd
0z4LKAMh99Z4xQmqSoEkXsfM4KPpfhYjF/bwIcP5gOei
-----END RSA PRIVATE KEY-----
]]
local certPem = [[
-----BEGIN CERTIFICATE-----
MIIDXDCCAsWgAwIBAgIJAKL0UG+mRkSPMA0GCSqGSIb3DQEBBQUAMH0xCzAJBgNV
BAYTAlVLMRQwEgYDVQQIEwtBY2tuYWNrIEx0ZDETMBEGA1UEBxMKUmh5cyBKb25l
czEQMA4GA1UEChMHbm9kZS5qczEdMBsGA1UECxMUVGVzdCBUTFMgQ2VydGlmaWNh
dGUxEjAQBgNVBAMTCWxvY2FsaG9zdDAeFw0wOTExMTEwOTUyMjJaFw0yOTExMDYw
OTUyMjJaMH0xCzAJBgNVBAYTAlVLMRQwEgYDVQQIEwtBY2tuYWNrIEx0ZDETMBEG
A1UEBxMKUmh5cyBKb25lczEQMA4GA1UEChMHbm9kZS5qczEdMBsGA1UECxMUVGVz
dCBUTFMgQ2VydGlmaWNhdGUxEjAQBgNVBAMTCWxvY2FsaG9zdDCBnzANBgkqhkiG
9w0BAQEFAAOBjQAwgYkCgYEA8d8Hc6atq78Jt1HLp9agA/wpQfsFvkYUdZ1YsdvO
kL2janjwHQgMMCy/Njal3FUEW0OLPebKZUJ8L44JBXSlVxU4zyiiSOWld8EkTetR
AVT3WKQq3ud+cnxv7g8rGRQp1UHZwmdbZ1wEfAYq8QjYx6m1ciMgRo7DaDQhD29k
d+UCAwEAAaOB4zCB4DAdBgNVHQ4EFgQUL9miTJn+HKNuTmx/oMWlZP9cd4QwgbAG
A1UdIwSBqDCBpYAUL9miTJn+HKNuTmx/oMWlZP9cd4ShgYGkfzB9MQswCQYDVQQG
EwJVSzEUMBIGA1UECBMLQWNrbmFjayBMdGQxEzARBgNVBAcTClJoeXMgSm9uZXMx
EDAOBgNVBAoTB25vZGUuanMxHTAbBgNVBAsTFFRlc3QgVExTIENlcnRpZmljYXRl
MRIwEAYDVQQDEwlsb2NhbGhvc3SCCQCi9FBvpkZEjzAMBgNVHRMEBTADAQH/MA0G
CSqGSIb3DQEBBQUAA4GBADRXXA2xSUK5W1i3oLYWW6NEDVWkTQ9RveplyeS9MOkP
e7yPcpz0+O0ZDDrxR9chAiZ7fmdBBX1Tr+pIuCrG/Ud49SBqeS5aMJGVwiSd7o1n
dhU2Sz3Q60DwJEL1VenQHiVYlWWtqXBThe9ggqRPnCfsCRTP8qifKkjk45zWPcpN
-----END CERTIFICATE-----
]]
local options = {
cert = certPem,
key = keyPem
}
local respond = function(log, client, payload)
local destroy = false
-- skip responses to requests
if payload.method == nil then
return
end
local response_method = payload.method .. '.response'
local response = JSON.parse(fixtures[response_method])
local response_out = nil
-- Handle rate limit logic
client.rate_limit = client.rate_limit - 1
if client.rate_limit <= 0 then
response = JSON.parse(fixtures['rate-limiting']['rate-limit-error'])
destroy = true
end
response.target = payload.source
response.source = payload.target
response.id = payload.id
log("Sending response:")
response_out = JSON.stringify(response)
response_out:gsub("\n", " ")
client:write(response_out .. '\n')
if destroy == true then
client:destroy()
end
end
local send_schedule_changed = function(log, client)
local request = fixtures['check_schedule.changed.request']
log("Sending request:")
p(JSON.parse(request))
client:write(request .. '\n')
end
local function start_fixture_server(options, port)
local log = function(...)
print(port .. ": " .. ...)
end
local server = tls.createServer(options, function (client)
client.rate_limit = opts.rate_limit
client:pipe(lineEmitter)
lineEmitter:on('data', function(line)
local payload = JSON.parse(line)
log("Got payload:")
p(payload)
respond(log, client, payload)
end)
-- Reset rate limit counter
timer.setTimeout(opts.rate_limit_reset, function()
client.rate_limit = opts.rate_limit
end)
timer.setTimeout(opts.send_schedule_changed_initial, function()
send_schedule_changed(log, client)
end)
timer.setInterval(opts.send_schedule_changed_interval, function()
send_schedule_changed(log, client)
end)
-- Disconnect the agent after some random number of seconds
-- to exercise reconnect logic
if opts.perform_client_disconnect == 'true' then
local disconnect_time = opts.destroy_connection_base + math.floor(math.random() * opts.destroy_connection_jitter)
timer.setTimeout(disconnect_time, function()
log("Destroying connection after " .. disconnect_time .. "ms connected")
client:destroy()
end)
end
end):listen(port, opts.listen_ip)
return server
end
-- There is no cleanup code for the server here as the process for exiting is
-- to just ctrl+c the runner or kill the process.
for k, v in pairs(ports) do
start_fixture_server(options, v)
print("TCP echo server listening on port " .. v)
end
|
local net = require('net')
local JSON = require('json')
local fixtures = require('./')
local LineEmitter = require('line-emitter').LineEmitter
local table = require('table')
local tls = require('tls')
local timer = require('timer')
local string = require('string')
local math = require('math')
local table = require('table')
local http = require("http")
local url = require('url')
local lineEmitter = LineEmitter:new()
local ports = {50041, 50051, 50061}
local opts = {}
local function set_option(options, name, default)
options[name] = process.env[string.upper(name)] or default
end
set_option(opts, "send_schedule_changed_initial", 2000)
set_option(opts, "send_schedule_changed_interval", 60000)
set_option(opts, "destroy_connection_jitter", 60000)
set_option(opts, "destroy_connection_base", 60000)
set_option(opts, "listen_ip", '127.0.0.1')
set_option(opts, "perform_client_disconnect", 'true')
set_option(opts, "rate_limit", 3000)
set_option(opts, "rate_limit_reset", 86400) -- Reset limit in 24 hours
local keyPem = [[
-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQDx3wdzpq2rvwm3Ucun1qAD/ClB+wW+RhR1nVix286QvaNqePAd
CAwwLL82NqXcVQRbQ4s95splQnwvjgkFdKVXFTjPKKJI5aV3wSRN61EBVPdYpCre
535yfG/uDysZFCnVQdnCZ1tnXAR8BirxCNjHqbVyIyBGjsNoNCEPb2R35QIDAQAB
AoGBAJNem9C4ftrFNGtQ2DB0Udz7uDuucepkErUy4MbFsc947GfENjDKJXr42Kx0
kYx09ImS1vUpeKpH3xiuhwqe7tm4FsCBg4TYqQle14oxxm7TNeBwwGC3OB7hiokb
aAjbPZ1hAuNs6ms3Ybvvj6Lmxzx42m8O5DXCG2/f+KMvaNUhAkEA/ekrOsWkNoW9
2n3m+msdVuxeek4B87EoTOtzCXb1dybIZUVv4J48VAiM43hhZHWZck2boD/hhwjC
M5NWd4oY6QJBAPPcgBVNdNZSZ8hR4ogI4nzwWrQhl9MRbqqtfOn2TK/tjMv10ALg
lPmn3SaPSNRPKD2hoLbFuHFERlcS79pbCZ0CQQChX3PuIna/gDitiJ8oQLOg7xEM
wk9TRiDK4kl2lnhjhe6PDpaQN4E4F0cTuwqLAoLHtrNWIcOAQvzKMrYdu1MhAkBm
Et3qDMnjDAs05lGT72QeN90/mPAcASf5eTTYGahv21cb6IBxM+AnwAPpqAAsHhYR
9h13Y7uYbaOjvuF23LRhAkBoI9eaSMn+l81WXOVUHnzh3ZwB4GuTyxMXXNOhuiFd
0z4LKAMh99Z4xQmqSoEkXsfM4KPpfhYjF/bwIcP5gOei
-----END RSA PRIVATE KEY-----
]]
local certPem = [[
-----BEGIN CERTIFICATE-----
MIIDXDCCAsWgAwIBAgIJAKL0UG+mRkSPMA0GCSqGSIb3DQEBBQUAMH0xCzAJBgNV
BAYTAlVLMRQwEgYDVQQIEwtBY2tuYWNrIEx0ZDETMBEGA1UEBxMKUmh5cyBKb25l
czEQMA4GA1UEChMHbm9kZS5qczEdMBsGA1UECxMUVGVzdCBUTFMgQ2VydGlmaWNh
dGUxEjAQBgNVBAMTCWxvY2FsaG9zdDAeFw0wOTExMTEwOTUyMjJaFw0yOTExMDYw
OTUyMjJaMH0xCzAJBgNVBAYTAlVLMRQwEgYDVQQIEwtBY2tuYWNrIEx0ZDETMBEG
A1UEBxMKUmh5cyBKb25lczEQMA4GA1UEChMHbm9kZS5qczEdMBsGA1UECxMUVGVz
dCBUTFMgQ2VydGlmaWNhdGUxEjAQBgNVBAMTCWxvY2FsaG9zdDCBnzANBgkqhkiG
9w0BAQEFAAOBjQAwgYkCgYEA8d8Hc6atq78Jt1HLp9agA/wpQfsFvkYUdZ1YsdvO
kL2janjwHQgMMCy/Njal3FUEW0OLPebKZUJ8L44JBXSlVxU4zyiiSOWld8EkTetR
AVT3WKQq3ud+cnxv7g8rGRQp1UHZwmdbZ1wEfAYq8QjYx6m1ciMgRo7DaDQhD29k
d+UCAwEAAaOB4zCB4DAdBgNVHQ4EFgQUL9miTJn+HKNuTmx/oMWlZP9cd4QwgbAG
A1UdIwSBqDCBpYAUL9miTJn+HKNuTmx/oMWlZP9cd4ShgYGkfzB9MQswCQYDVQQG
EwJVSzEUMBIGA1UECBMLQWNrbmFjayBMdGQxEzARBgNVBAcTClJoeXMgSm9uZXMx
EDAOBgNVBAoTB25vZGUuanMxHTAbBgNVBAsTFFRlc3QgVExTIENlcnRpZmljYXRl
MRIwEAYDVQQDEwlsb2NhbGhvc3SCCQCi9FBvpkZEjzAMBgNVHRMEBTADAQH/MA0G
CSqGSIb3DQEBBQUAA4GBADRXXA2xSUK5W1i3oLYWW6NEDVWkTQ9RveplyeS9MOkP
e7yPcpz0+O0ZDDrxR9chAiZ7fmdBBX1Tr+pIuCrG/Ud49SBqeS5aMJGVwiSd7o1n
dhU2Sz3Q60DwJEL1VenQHiVYlWWtqXBThe9ggqRPnCfsCRTP8qifKkjk45zWPcpN
-----END CERTIFICATE-----
]]
local options = {
cert = certPem,
key = keyPem
}
local respond = function(log, client, payload)
local destroy = false
-- skip responses to requests
if payload.method == nil then
return
end
local response_method = payload.method .. '.response'
local response = JSON.parse(fixtures[response_method])
local response_out = nil
-- Handle rate limit logic
client.rate_limit = client.rate_limit - 1
if client.rate_limit <= 0 then
response = JSON.parse(fixtures['rate-limiting']['rate-limit-error'])
destroy = true
end
response.target = payload.source
response.source = payload.target
response.id = payload.id
log("Sending response:")
response_out = JSON.stringify(response)
response_out:gsub("\n", " ")
client:write(response_out .. '\n')
if destroy == true then
client:destroy()
end
return destroy
end
local send_schedule_changed = function(log, client)
local request = fixtures['check_schedule.changed.request']
log("Sending request:")
p(JSON.parse(request))
client:write(request .. '\n')
end
local function clear_timers(timer_ids)
for k, v in pairs(timer_ids) do
if v._closed ~= true then
timer.clearTimer(v)
end
end
end
local function start_fixture_server(options, port)
local log = function(...)
print(port .. ": " .. ...)
end
local server = tls.createServer(options, function (client)
local destroyed = false
local timers = {}
client.rate_limit = opts.rate_limit
client:pipe(lineEmitter)
lineEmitter:on('data', function(line)
local payload = JSON.parse(line)
log("Got payload:")
p(payload)
destroyed = respond(log, client, payload)
if destroyed == true then
clear_timers(timers)
end
end)
-- Reset rate limit counter
timer.setTimeout(opts.rate_limit_reset, function()
client.rate_limit = opts.rate_limit
end)
timer.setTimeout(opts.send_schedule_changed_initial, function()
send_schedule_changed(log, client)
end)
table.insert(timers,
timer.setInterval(opts.send_schedule_changed_interval, function()
send_schedule_changed(log, client)
end)
)
-- Disconnect the agent after some random number of seconds
-- to exercise reconnect logic
if opts.perform_client_disconnect == 'true' then
local disconnect_time = opts.destroy_connection_base + math.floor(math.random() * opts.destroy_connection_jitter)
timer.setTimeout(disconnect_time, function()
log("Destroying connection after " .. disconnect_time .. "ms connected")
client:destroy()
end)
end
end):listen(port, opts.listen_ip)
return server
end
-- There is no cleanup code for the server here as the process for exiting is
-- to just ctrl+c the runner or kill the process.
for k, v in pairs(ports) do
start_fixture_server(options, v)
print("TCP echo server listening on port " .. v)
end
|
monitoring: fixtures: server: clear interval timers
|
monitoring: fixtures: server: clear interval timers
setup infrastructure to clear interval timers if a connection is
destroyed.
|
Lua
|
apache-2.0
|
kans/zirgo,kans/zirgo,kans/zirgo
|
4a162c53bf7abd2f884a6caa330f1a041a767202
|
tests/check/filesystem.lua
|
tests/check/filesystem.lua
|
local math = require('math')
local os = require('os')
local FileSystemCheck = require('/check').FileSystemCheck
local exports = {}
exports['test_filesystem_check'] = function(test, asserts)
if os.type() == "win32" then
fs_target = 'C:\\'
else
fs_target = '/'
end
local check = FileSystemCheck:new({id='foo', period=30, details={target=fs_target}})
asserts.ok(check._lastResult == nil)
check:run(function(result)
local util = require('utils')
local metrics = result:getMetrics()['none']
asserts.not_nil(metrics['total']['v'])
asserts.not_nil(metrics['free']['v'])
asserts.not_nil(metrics['used']['v'])
asserts.not_nil(metrics['avail']['v'])
asserts.equal(metrics['total']['t'], 'int64')
asserts.equal(metrics['free']['t'], 'int64')
asserts.equal(metrics['used']['t'], 'int64')
asserts.equal(metrics['avail']['t'], 'int64')
asserts.ok(tonumber(metrics['free']['v']) <= tonumber(metrics['total']['v']))
asserts.equal(tonumber(metrics['free']['v']) + tonumber(metrics['used']['v']),
tonumber(metrics['total']['v']))
-- These metrics are unavailalbe on Win32, see:
-- http://www.hyperic.com/support/docs/sigar/org/hyperic/sigar/FileSystemUsage.html#getFiles()
if os.type() ~= "win32" then
asserts.not_nil(metrics['files']['v'])
asserts.not_nil(metrics['free_files']['v'])
asserts.equal(metrics['files']['t'], 'int64')
asserts.equal(metrics['free_files']['t'], 'int64')
asserts.ok(tonumber(metrics['free_files']['v']) <= tonumber(metrics['files']['v']))
else
asserts.is_nil(metrics['files'])
asserts.is_nil(metrics['free_files'])
end
test.done()
end)
end
exports['test_filesystem_check_nonexistent_mount_point'] = function(test, asserts)
local check = FileSystemCheck:new({id='foo', period=30, details={target='does-not-exist'}})
check:run(function(result)
asserts.equal(result:getState(), 'unavailable')
asserts.equal(result:getStatus(), 'No filesystem mounted at does-not-exist')
test.done()
end)
end
exports['test_filesystem_check_no_mount_point'] = function(test, asserts)
local check = FileSystemCheck:new({id='foo', period=30})
check:run(function(result)
asserts.equal(result:getState(), 'unavailable')
asserts.equal(result:getStatus(), 'Missing target parameter')
test.done()
end)
end
return exports
|
local math = require('math')
local os = require('os')
local FileSystemCheck = require('/check').FileSystemCheck
local exports = {}
exports['test_filesystem_check'] = function(test, asserts)
if os.type() == "win32" then
fs_target = 'C:\\'
else
fs_target = '/'
end
local check = FileSystemCheck:new({id='foo', period=30, details={target=fs_target}})
asserts.ok(check._lastResult == nil)
check:run(function(result)
local util = require('utils')
local metrics = result:getMetrics()['none']
asserts.not_nil(metrics['total']['v'])
asserts.not_nil(metrics['free']['v'])
asserts.not_nil(metrics['used']['v'])
asserts.not_nil(metrics['avail']['v'])
asserts.equal(metrics['total']['t'], 'int64')
asserts.equal(metrics['free']['t'], 'int64')
asserts.equal(metrics['used']['t'], 'int64')
asserts.equal(metrics['avail']['t'], 'int64')
asserts.ok(tonumber(metrics['free']['v']) <= tonumber(metrics['total']['v']))
asserts.equal(tonumber(metrics['free']['v']) + tonumber(metrics['used']['v']),
tonumber(metrics['total']['v']))
-- These metrics are unavailalbe on Win32, see:
-- http://www.hyperic.com/support/docs/sigar/org/hyperic/sigar/FileSystemUsage.html#getFiles()
if os.type() ~= "win32" then
asserts.not_nil(metrics['files']['v'])
asserts.not_nil(metrics['free_files']['v'])
asserts.equal(metrics['files']['t'], 'int64')
asserts.equal(metrics['free_files']['t'], 'int64')
asserts.ok(tonumber(metrics['free_files']['v']) <= tonumber(metrics['files']['v']))
else
asserts.is_nil(metrics['files'])
asserts.is_nil(metrics['free_files'])
end
test.done()
end)
end
exports['test_filesystem_check_nonexistent_mount_point'] = function(test, asserts)
local check = FileSystemCheck:new({id='foo', period=30, details={target='does-not-exist'}})
check:run(function(result)
asserts.equal(result:getState(), 'unavailable')
local expected_status = 'No filesystem mounted at does-not-exist'
asserts.equal(result:getStatus():sub(1, expected_status:len()), expected_status)
test.done()
end)
end
exports['test_filesystem_check_no_mount_point'] = function(test, asserts)
local check = FileSystemCheck:new({id='foo', period=30})
check:run(function(result)
asserts.equal(result:getState(), 'unavailable')
local expected_status = 'Missing target parameter'
asserts.equal(result:getStatus():sub(1, expected_status:len()), expected_status)
test.done()
end)
end
return exports
|
fix: filesystem mount point fix, missing test changes
|
fix: filesystem mount point fix, missing test changes
|
Lua
|
apache-2.0
|
kaustavha/rackspace-monitoring-agent,christopherjwang/rackspace-monitoring-agent,kaustavha/rackspace-monitoring-agent,AlphaStaxLLC/rackspace-monitoring-agent,virgo-agent-toolkit/rackspace-monitoring-agent,AlphaStaxLLC/rackspace-monitoring-agent,christopherjwang/rackspace-monitoring-agent,virgo-agent-toolkit/rackspace-monitoring-agent
|
ca4705254414b7117815c59bc66f285fae2af88d
|
modules/admin-full/luasrc/model/cbi/admin_network/routes.lua
|
modules/admin-full/luasrc/model/cbi/admin_network/routes.lua
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
require("luci.tools.webadmin")
m = Map("network", translate("a_n_routes"), translate("a_n_routes1"))
if not arg or not arg[1] then
local routes = luci.sys.net.routes()
v = m:section(Table, routes, translate("a_n_routes_kernel4"))
net = v:option(DummyValue, "iface", translate("network"))
function net.cfgvalue(self, section)
return luci.tools.webadmin.iface_get_network(routes[section].Iface)
or routes[section].Iface
end
target = v:option(DummyValue, "target", translate("target"))
function target.cfgvalue(self, section)
return luci.ip.Hex(routes[section].Destination, 32):string()
end
netmask = v:option(DummyValue, "netmask", translate("netmask"))
function netmask.cfgvalue(self, section)
return luci.ip.Hex(routes[section].Mask, 32):string()
end
gateway = v:option(DummyValue, "gateway", translate("gateway"))
function gateway.cfgvalue(self, section)
return luci.ip.Hex(routes[section].Gateway, 32):string()
end
metric = v:option(DummyValue, "Metric", translate("metric"))
end
s = m:section(TypedSection, "route", translate("a_n_routes_static"))
s.addremove = true
s.anonymous = true
s.template = "cbi/tblsection"
iface = s:option(ListValue, "interface", translate("interface"))
luci.tools.webadmin.cbi_add_networks(iface)
if not arg or not arg[1] then
net.titleref = iface.titleref
end
s:option(Value, "target", translate("target"), translate("a_n_r_target1"))
s:option(Value, "netmask", translate("netmask"), translate("a_n_r_netmask1")).rmemepty = true
s:option(Value, "gateway", translate("gateway"))
return m
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
require("luci.tools.webadmin")
m = Map("network", translate("a_n_routes"), translate("a_n_routes1"))
if not arg or not arg[1] then
local routes = luci.sys.net.routes()
v = m:section(Table, routes, translate("a_n_routes_kernel4"))
net = v:option(DummyValue, "iface", translate("network"))
function net.cfgvalue(self, section)
return luci.tools.webadmin.iface_get_network(routes[section].Iface)
or routes[section].Iface
end
target = v:option(DummyValue, "target", translate("target"))
function target.cfgvalue(self, section)
return luci.ip.Hex(routes[section].Destination, 32):string()
end
netmask = v:option(DummyValue, "netmask", translate("netmask"))
function netmask.cfgvalue(self, section)
return luci.ip.Hex(routes[section].Mask, 32):string()
end
gateway = v:option(DummyValue, "gateway", translate("gateway"))
function gateway.cfgvalue(self, section)
return luci.ip.Hex(routes[section].Gateway, 32):string()
end
metric = v:option(DummyValue, "Metric", translate("metric"))
end
s = m:section(TypedSection, "route", translate("a_n_routes_static"))
s.addremove = true
s.anonymous = true
function s.render(...)
luci.model.uci.load_config("network")
TypedSection.render(...)
end
s.template = "cbi/tblsection"
iface = s:option(ListValue, "interface", translate("interface"))
luci.tools.webadmin.cbi_add_networks(iface)
if not arg or not arg[1] then
net.titleref = iface.titleref
end
s:option(Value, "target", translate("target"), translate("a_n_r_target1"))
s:option(Value, "netmask", translate("netmask"), translate("a_n_r_netmask1")).rmemepty = true
s:option(Value, "gateway", translate("gateway"))
return m
|
modules/admin-fulk: Fixed changes handling of Static Routes configuration page
|
modules/admin-fulk: Fixed changes handling of Static Routes configuration page
|
Lua
|
apache-2.0
|
deepak78/luci,8devices/luci,deepak78/luci,deepak78/luci,deepak78/luci,deepak78/luci,deepak78/luci,8devices/luci,deepak78/luci,8devices/luci,8devices/luci,8devices/luci,deepak78/luci,8devices/luci
|
aac50266cf5b68d0ca5dc0f734cdee440182820a
|
examples/GNTPLuaSocket.lua
|
examples/GNTPLuaSocket.lua
|
-- Using LuaSocket library to communicate with Growl
local GNTP = require "lluv.gntp"
local socket = require "socket"
local function gntp_send_recv(msg, pass, host, port)
local cli, err = socket.connect(host or "127.0.0.1", port or "23053")
if not cli then return nil, err end
cli:send(msg:encode(pass))
local parser, msg, err = GNTP.Parser.new(pass)
while true do
msg, err = cli:receive("*l") -- really not safe for binary/data with `\n`
if not msg then break end
parser:append(msg):append("\r\n")
msg, err = parser:next_message()
if not msg then break end
if msg ~= true then break end
end
cli:close()
return msg, err
end
local icon = GNTP.Resource.load_from_file('coulson.jpg')
local reg = GNTP.Message.new()
:set_info('REGISTER', 'SHA256', 'AES')
:add_header("Application-Name", "GNTP.LUASOCKET")
:add_notification{name = "General Notification", enabled = true}
local note = GNTP.Message.new()
:set_info('NOTIFY', 'SHA256', 'AES')
:add_header("Application-Name", "GNTP.LUASOCKET")
:add_header("Notification-Name", "General Notification")
:add_header("Notification-Title", "LuaSocket")
:add_header("Notification-Text", "Hello from LuaSocket")
local msg, err = gntp_send_recv(reg, "123456")
print(msg:encode())
assert(msg:type() == '-OK')
local msg, err = gntp_send_recv(note, "123456")
print(msg:encode())
assert(msg:type() == '-OK')
|
-- Using LuaSocket library to communicate with Growl
local GNTP = require "lluv.gntp"
local socket = require "socket"
local function gntp_send_recv(msg, pass, host, port)
local cli, err = socket.connect(host or "127.0.0.1", port or "23053")
if not cli then return nil, err end
cli:send(msg:encode(pass))
local parser, msg, err = GNTP.Parser.new(pass)
while true do
msg, err = cli:receive("*l") -- really not safe for binary/data with `\n`
if not msg then break end
parser:append(msg):append("\r\n")
msg, err = parser:next_message()
if not msg then break end
if msg ~= true then break end
end
cli:close()
return msg, err
end
local reg = GNTP.Message.new()
:set_info('REGISTER', 'SHA256', 'AES')
:add_header("Application-Name", "GNTP.LUASOCKET")
:add_notification{name = "General Notification", enabled = true}
local note = GNTP.Message.new()
:set_info('NOTIFY', 'SHA256', 'AES')
:add_header("Application-Name", "GNTP.LUASOCKET")
:add_header("Notification-Name", "General Notification")
:add_header("Notification-Title", "LuaSocket")
:add_header("Notification-Text", "Hello from LuaSocket")
local msg, err = gntp_send_recv(reg, "123456")
print(msg:encode())
assert(msg:type() == '-OK')
local msg, err = gntp_send_recv(note, "123456")
print(msg:encode())
assert(msg:type() == '-OK')
|
Fix. Remove unused code.
|
Fix. Remove unused code.
|
Lua
|
mit
|
moteus/lua-gntp
|
c29efb234b2d8cb40a0dda9812eb72761cd8b0db
|
data/pipelines/fxaa.lua
|
data/pipelines/fxaa.lua
|
function postprocess(env, transparent_phase, ldr_buffer, gbuffer0, gbuffer1, gbuffer_depth, shadowmap)
if not enabled then return ldr_buffer end
if transparent_phase ~= "post_tonemap" then return ldr_buffer end
local res = env.createRenderbuffer(1, 1, true, "rgba8", "fxaa")
env.beginBlock("fxaa")
if env.fxaa_shader == nil then
env.fxaa_shader = env.preloadShader("pipelines/fxaa.shd")
end
env.setRenderTargets(res)
env.drawArray(0, 4, env.fxaa_shader,
{ ldr_buffer },
{},
{},
{ depth_test = false, blending = ""}
)
env.endBlock()
return res
end
function awake()
_G["postprocesses"] = _G["postprocesses"] or {}
_G["postprocesses"]["fxaa"] = postprocess
end
function onDestroy()
_G["postprocesses"]["fxaa"] = nil
end
|
function postprocess(env, transparent_phase, ldr_buffer, gbuffer0, gbuffer1, gbuffer_depth, shadowmap)
if not enabled then return ldr_buffer end
if transparent_phase ~= "post_tonemap" then return ldr_buffer end
local res
if env.SCENE_VIEW ~= nil then
res = env.createRenderbuffer(1, 1, true, "rgba16f", "fxaa")
else
res = env.createRenderbuffer(1, 1, true, "rgba8", "fxaa")
end
env.beginBlock("fxaa")
if env.fxaa_shader == nil then
env.fxaa_shader = env.preloadShader("pipelines/fxaa.shd")
end
env.setRenderTargets(res)
env.drawArray(0, 4, env.fxaa_shader,
{ ldr_buffer },
{},
{},
{ depth_test = false, blending = ""}
)
env.endBlock()
return res
end
function awake()
_G["postprocesses"] = _G["postprocesses"] or {}
_G["postprocesses"]["fxaa"] = postprocess
end
function onDestroy()
_G["postprocesses"]["fxaa"] = nil
end
|
fxaa breaks colors - fixes #1285
|
fxaa breaks colors - fixes #1285
|
Lua
|
mit
|
nem0/LumixEngine,nem0/LumixEngine,nem0/LumixEngine
|
8ce6796517f61fd54718e2fc52760854c17ad4a5
|
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$
]]--
require("luci.tools.webadmin")
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:option(Flag, "enabled", translate("enable"))
svc = s:option(ListValue, "service_name", translate("Service"))
svc.rmempty = true
svc:value("")
svc:value("dyndns.org")
svc:value("changeip.com")
svc:value("zoneedit.com")
svc:value("no-ip.com")
svc:value("freedns.afraid.org")
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
src = s:option(ListValue, "ip_source")
src:value("network", translate("Network"))
src:value("interface", translate("Interface"))
src:value("web", "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", "URL")
web:depends("ip_source", "web")
web.rmempty = true
s:option(Value, "update_url").optional = true
s:option(Value, "check_interval").default = 10
unit = s:option(ListValue, "check_unit")
unit.default = "minutes"
unit:value("minutes", "min")
unit:value("hours", "h")
s:option(Value, "force_interval").default = 72
unit = s:option(ListValue, "force_unit")
unit.default = "hours"
unit:value("minutes", "min")
unit:value("hours", "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$
]]--
require("luci.tools.webadmin")
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:option(Flag, "enabled", translate("enable"))
svc = s:option(ListValue, "service_name", translate("Service"))
svc.rmempty = true
svc:value("")
svc:value("dyndns.org")
svc:value("changeip.com")
svc:value("zoneedit.com")
svc:value("no-ip.com")
svc:value("freedns.afraid.org")
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
src = s:option(ListValue, "ip_source", translate("Source of IP-Address"))
src:value("network", translate("Network"))
src:value("interface", translate("Interface"))
src:value("web", "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", "URL")
web:depends("ip_source", "web")
web.rmempty = true
s:option(Value, "update_url", translate("Custom Update-URL")).optional = true
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", "min")
unit:value("hours", "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", "min")
unit:value("hours", "h")
return m
|
applications/luci-ddns: fix dyndns config page
|
applications/luci-ddns: fix dyndns config page
git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@5463 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
|
Lua
|
apache-2.0
|
fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci
|
56a4909b28f72d7d6c3f0927b0ea11cf11412d07
|
OS/DiskOS/Programs/paint.lua
|
OS/DiskOS/Programs/paint.lua
|
--Paint Program--
print("")
local args = {...}
if #args < 1 then color(9) print("Must provide the path to the file") return end
local tar = table.concat(args," ")..".lk12" --The path may include whitespaces
local term = require("C://terminal")
tar = term.parsePath(tar)
if fs.exists(tar) and fs.isDirectory(tar) then color(9) print("Can't edit directories !") return end
local img, imgdata
if not fs.exists(tar) then --Create a new image
color(10) print("Input image size:")
color(12) print("Width: ",false)
color(8) local width = input()
if not width or width:len() == 0 then print("") return end
local w = tonumber(width)
if not w then color(9) print("\nInvalid Width: "..width..", width must be a number !") return end
color(12) print(", Height: ",false)
color(8) local height = input()
if not height or height:len() == 0 then print("") return end
local h = tonumber(height)
if not h then color(9) print("\nInvalid Height: "..height..", height must be a number !") return end
color(9) print("\nW:"..w.." H:"..h)
imgdata = imagedata(w,h)
img = imgdata:image()
else --Load the image
local data = fs.read(tar)
local ok, err = pcall(image,data)
if not ok then color(9) print(err) return end
img = err
imgdata = img:data()
end
local eapi = require("C://Editors")
local edit = {}
edit.editorsheet = eapi.editorsheet
edit.flavor = eapi.flavor
edit.flavorBack = eapi.flavorBack
edit.background = 0
local swidth, sheight = screenSize()
local bgsprite = eapi.editorsheet:extract(59):image()
local bgquad = bgsprite:quad(1,1,swidth,sheight-8*2)
local sid --Selected option id
function edit:drawBottomBar()
rect(1,sheight-7,swidth,8,false,self.flavor)
end
local controlID = 11
local controlNum = 3 --The number of the control buttons at the top right corner of the editor.
local controlGrid = {swidth-8*controlNum+1,1, 8*controlNum,8, controlNum,1}
function edit:drawTopBar()
palt(1,true)
rect(1,1,swidth,8,false,self.flavor)
SpriteGroup(55, 1,1, 4,1, 1,1, false, self.editorsheet) --The LIKO12 Logo
SpriteGroup(controlID, controlGrid[1],controlGrid[2], controlGrid[5],controlGrid[6], 1,1, false, self.editorsheet)
if sid then
SpriteGroup(controlID+24+sid, controlGrid[1]+sid*8,controlGrid[2], 1,1, 1,1, false, self.editorsheet)
end
palt(1,false)
end
function edit:drawBackground()
rect(1,9,swidth,sheight-8*2,false,1)
bgsprite:draw(1,9,0,1,1,bgquad)
end
function edit:drawUI()
self:drawBackground()
self:drawTopBar() --Draw the top bar
self:drawBottomBar() --Draw the bottom bar
end
local screen = screenshot()
local px,py,pc = printCursor()
local ok, painteditor = assert(pcall(assert(fs.load("C://Editors/paint.lua")),edit,img,imgdata))
cursor("normal")
painteditor:entered()
local eflag = false
local hflag = false --hover flag
local controls = {
function() --Reload
painteditor:leaved()
if fs.exists(tar) then
local data = fs.read(tar)
local ok, err = pcall(image,data)
if not ok then color(9) print(err) return end
img = err
imgdata = img:data()
painteditor:import(img,imgdata)
end
painteditor:entered()
end,
function() --Save
local data = painteditor:export()
fs.write(tar,data)
end,
function() --Exit
painteditor:leaved()
return true
end
}
for event, a,b,c,d,e,f in pullEvent do
if event == "keypressed" then
if a == "escape" then
--[[painteditor:leaved()
break]]
eflag = not eflag
if eflag then
cursor("none")
sid = 1
else
cursor("normal")
sid = false
end
pushMatrix() cam() edit:drawTopBar() popMatrix()
elseif eflag then
if a == "left" then
sid = sid - 1
if sid < 0 then sid = 2 end
pushMatrix() cam() edit:drawTopBar() popMatrix()
elseif a == "right" then
sid = sid + 1
if sid > 2 then sid = 0 end
pushMatrix() cam() edit:drawTopBar() popMatrix()
elseif a == "return" then
if controls[sid+1]() then break end
sid, eflag = false, false
pushMatrix() cam() edit:drawTopBar() popMatrix()
end
else
local key, sc = a, b
if(isKDown("lalt", "ralt")) then
key = "alt-" .. key
sc = "alt-" .. sc
end
if(isKDown("lctrl", "rctrl", "capslock")) then
key = "ctrl-" .. key
sc = "ctrl-" .. sc
end
if(isKDown("lshift", "rshift")) then
key = "shift-" .. key
sc = "shift-" .. sc
end
if painteditor.keymap and painteditor.keymap[key] then painteditor.keymap[key](painteditor,c)
elseif painteditor.keymap and painteditor.keymap[sc] then painteditor.keymap[sc](painteditor,c) end
if painteditor[event] then painteditor[event](painteditor,a,b,c,d,e,f) end
end
elseif event == "mousepressed" and not eflag then
local cx, cy = whereInGrid(a,b,controlGrid)
if cx then
cursor("handpress")
hflag = "d"
sid = cx-1
pushMatrix() cam() edit:drawTopBar() popMatrix()
else
if painteditor[event] then painteditor[event](painteditor,a,b,c,d,e,f) end
end
elseif event == "mousemoved" and not eflag then
local cx, cy = whereInGrid(a,b,controlGrid)
if cx then
if hflag and hflag == "d" then
sid = cx-1
pushMatrix() cam() edit:drawTopBar() popMatrix()
elseif not hflag then
cursor("handrelease")
hflag = "h"
end
else
if hflag and hflag == "h" then
hflag = false
cursor("normal")
end
if painteditor[event] then painteditor[event](painteditor,a,b,c,d,e,f) end
end
elseif event == "mousereleased" and not eflag then
local cx, cy = whereInGrid(a,b,controlGrid)
if cx then
if hflag and hflag == "d" then
cursor("handrelease")
if controls[sid+1]() then break end
sid, hflag = false, false
pushMatrix() cam() edit:drawTopBar() popMatrix()
elseif not hflag then
hflag = "h"
cursor("handrelease")
end
else
if hflag then
if hflag == "d" then
sid = false
pushMatrix() cam() edit:drawTopBar() popMatrix()
end
cursor("normal")
hflag = nil
end
if painteditor[event] then painteditor[event](painteditor,a,b,c,d,e,f) end
end
elseif eflag then
if event == "touchpressed" then textinput(true) end
else
if painteditor[event] then painteditor[event](painteditor,a,b,c,d,e,f) end
end
end
clear(1)
screen:image():draw(1,1)
printCursor(px,py,pc)
|
--Paint Program--
print("")
local args = {...}
if #args < 1 then color(9) print("Must provide the path to the file") return end
local tar = table.concat(args," ")..".lk12" --The path may include whitespaces
local term = require("C://terminal")
tar = term.parsePath(tar)
if fs.exists(tar) and fs.isDirectory(tar) then color(9) print("Can't edit directories !") return end
local img, imgdata
if not fs.exists(tar) then --Create a new image
color(10) print("Input image size:")
color(12) print("Width: ",false)
color(8) local width = input()
if not width or width:len() == 0 then print("") return end
local w = tonumber(width)
if not w then color(9) print("\nInvalid Width: "..width..", width must be a number !") return end
color(12) print(", Height: ",false)
color(8) local height = input()
if not height or height:len() == 0 then print("") return end
local h = tonumber(height)
if not h then color(9) print("\nInvalid Height: "..height..", height must be a number !") return end
color(9) print("\nW:"..w.." H:"..h)
imgdata = imagedata(w,h)
img = imgdata:image()
else --Load the image
local data = fs.read(tar)
local ok, err = pcall(image,data)
if not ok then color(9) print(err) return end
img = err
imgdata = img:data()
end
local eapi = require("C://Editors")
local edit = {}
edit.editorsheet = eapi.editorsheet
edit.flavor = eapi.flavor
edit.flavorBack = eapi.flavorBack
edit.background = 0
local swidth, sheight = screenSize()
local bgsprite = eapi.editorsheet:extract(59):image()
local bgquad = bgsprite:quad(1,1,swidth,sheight-8*2)
local sid --Selected option id
function edit:drawBottomBar()
rect(1,sheight-7,swidth,8,false,self.flavor)
end
local controlID = 11
local controlNum = 3 --The number of the control buttons at the top right corner of the editor.
local controlGrid = {swidth-8*controlNum+1,1, 8*controlNum,8, controlNum,1}
function edit:drawTopBar()
palt(1,true)
rect(1,1,swidth,8,false,self.flavor)
SpriteGroup(55, 1,1, 4,1, 1,1, false, self.editorsheet) --The LIKO12 Logo
SpriteGroup(controlID, controlGrid[1],controlGrid[2], controlGrid[5],controlGrid[6], 1,1, false, self.editorsheet)
if sid then
SpriteGroup(controlID+24+sid, controlGrid[1]+sid*8,controlGrid[2], 1,1, 1,1, false, self.editorsheet)
end
palt(1,false)
end
function edit:drawBackground()
rect(1,9,swidth,sheight-8*2,false,1)
bgsprite:draw(1,9,0,1,1,bgquad)
end
function edit:drawUI()
self:drawBackground()
self:drawTopBar() --Draw the top bar
self:drawBottomBar() --Draw the bottom bar
end
local screen = screenshot()
local px,py,pc = printCursor()
local ok, painteditor = assert(pcall(assert(fs.load("C://Editors/paint.lua")),edit,img,imgdata))
cursor("normal")
painteditor:entered()
local eflag = false
local hflag = false --hover flag
local controls = {
function() --Reload
painteditor:leaved()
if fs.exists(tar) then
local data = fs.read(tar)
local ok, err = pcall(image,data)
if not ok then color(9) print(err) return end
img = err
imgdata = img:data()
painteditor:import(img,imgdata)
end
painteditor:entered()
end,
function() --Save
local data = painteditor:export()
fs.write(tar,data)
end,
function() --Exit
painteditor:leaved()
return true
end
}
for event, a,b,c,d,e,f in pullEvent do
if event == "keypressed" then
if a == "escape" then
--[[painteditor:leaved()
break]]
eflag = not eflag
if eflag then
cursor("none")
sid = 1
else
cursor("normal")
sid = false
end
pushMatrix() cam() edit:drawTopBar() popMatrix()
elseif eflag then
if a == "left" then
sid = sid - 1
if sid < 0 then sid = 2 end
pushMatrix() cam() edit:drawTopBar() popMatrix()
elseif a == "right" then
sid = sid + 1
if sid > 2 then sid = 0 end
pushMatrix() cam() edit:drawTopBar() popMatrix()
elseif a == "return" then
if controls[sid+1]() then break end
sid, eflag = false, false
pushMatrix() cam() edit:drawTopBar() popMatrix()
end
else
local key, sc = a, b
if(isKDown("lalt", "ralt")) then
key = "alt-" .. key
sc = "alt-" .. sc
end
if(isKDown("lctrl", "rctrl", "capslock")) then
key = "ctrl-" .. key
sc = "ctrl-" .. sc
end
if(isKDown("lshift", "rshift")) then
key = "shift-" .. key
sc = "shift-" .. sc
end
if painteditor.keymap and painteditor.keymap[key] then painteditor.keymap[key](painteditor,c)
elseif painteditor.keymap and painteditor.keymap[sc] then painteditor.keymap[sc](painteditor,c) end
if painteditor[event] then painteditor[event](painteditor,a,b,c,d,e,f) end
end
elseif event == "mousepressed" and not eflag then
if painteditor[event] then painteditor[event](painteditor,a,b,c,d,e,f) end
local cx, cy = whereInGrid(a,b,controlGrid)
if cx then
cursor("handpress")
hflag = "d"
sid = cx-1
pushMatrix() cam() edit:drawTopBar() popMatrix()
end
elseif event == "mousemoved" and not eflag then
if painteditor[event] then painteditor[event](painteditor,a,b,c,d,e,f) end
local cx, cy = whereInGrid(a,b,controlGrid)
if cx then
if hflag and hflag == "d" then
sid = cx-1
pushMatrix() cam() edit:drawTopBar() popMatrix()
elseif not hflag then
cursor("handrelease")
hflag = "h"
end
else
if hflag and hflag == "h" then
hflag = false
cursor("normal")
end
end
elseif event == "mousereleased" and not eflag then
if painteditor[event] then painteditor[event](painteditor,a,b,c,d,e,f) end
local cx, cy = whereInGrid(a,b,controlGrid)
if cx then
if hflag and hflag == "d" then
cursor("handrelease")
if controls[sid+1]() then break end
sid, hflag = false, false
pushMatrix() cam() edit:drawTopBar() popMatrix()
elseif not hflag then
hflag = "h"
cursor("handrelease")
end
else
if hflag then
if hflag == "d" then
sid = false
pushMatrix() cam() edit:drawTopBar() popMatrix()
end
cursor("normal")
hflag = nil
end
end
elseif eflag then
if event == "touchpressed" then textinput(true) end
else
if painteditor[event] then painteditor[event](painteditor,a,b,c,d,e,f) end
end
end
clear(1)
screen:image():draw(1,1)
printCursor(px,py,pc)
|
Bugfixes some glitches
|
Bugfixes some glitches
|
Lua
|
mit
|
RamiLego4Game/LIKO-12
|
0d30c0cb5a359c732db2ee694e02cdc4868655e3
|
tests/test-path.lua
|
tests/test-path.lua
|
--[[
Copyright 2012 The Luvit Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
require("helper")
local path = require('path')
local os = require('os')
-- test `path.dirname`
if (os.type() ~= "win32") then
assert(path.dirname('/usr/bin/vim') == '/usr/bin')
assert(path.dirname('/usr/bin/') == '/usr')
assert(path.dirname('/usr/bin') == '/usr')
else
assert(path.dirname('C:\\Users\\philips\\vim.exe') == 'C:\\Users\\philips')
assert(path.dirname('C:\\Users\\philips\\') == 'C:\\Users')
assert(path.dirname('C:\\Users\\philips\\') == 'C:\\Users')
end
-- Test out the OS path objects
assert(path.posix:dirname('/usr/bin/vim') == '/usr/bin')
assert(path.posix:dirname('/usr/bin/') == '/usr')
assert(path.posix:dirname('/usr/bin') == '/usr')
assert(path.nt:dirname('C:\\Users\\philips\\vim.exe') == 'C:\\Users\\philips')
assert(path.nt:dirname('C:\\Users\\philips\\') == 'C:\\Users')
assert(path.nt:dirname('C:\\Users\\philips\\') == 'C:\\Users')
assert(path.posix:join('foo', '/bar') == "foo/bar")
assert(path.posix:join('foo', 'bar') == "foo/bar")
assert(path.posix:join('foo/', 'bar') == "foo/bar")
assert(path.posix:join('foo/', '/bar') == "foo/bar")
assert(path.posix:join('/foo', '/bar') == "/foo/bar")
assert(path.posix:join('/foo', 'bar') == "/foo/bar")
assert(path.posix:join('/foo/', 'bar') == "/foo/bar")
assert(path.posix:join('/foo/', '/bar') == "/foo/bar")
assert(path.posix:join('foo', '/bar/') == "foo/bar/")
assert(path.posix:join('foo', 'bar/') == "foo/bar/")
assert(path.posix:join('foo/', 'bar/') == "foo/bar/")
assert(path.posix:join('foo/', '/bar/') == "foo/bar/")
assert(path.basename('bar.lua') == 'bar.lua')
assert(path.basename('bar.lua', '.lua') == 'bar')
assert(path.basename('bar.lua.js', '.lua') == 'bar.lua.js')
assert(path.basename('.lua', 'lua') == '.')
assert(path.basename('bar', '.lua') == 'bar')
assert(path.basename('/foo/bar.lua') == 'bar.lua')
assert(path.basename('/foo/bar.lua', '.lua') == 'bar')
|
--[[
Copyright 2012 The Luvit Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
require("helper")
local path = require('path')
local os = require('os')
-- test `path.dirname`
if (os.type() ~= "win32") then
assert(path.dirname('/usr/bin/vim') == '/usr/bin')
assert(path.dirname('/usr/bin/') == '/usr')
assert(path.dirname('/usr/bin') == '/usr')
else
assert(path.dirname('C:\\Users\\philips\\vim.exe') == 'C:\\Users\\philips')
assert(path.dirname('C:\\Users\\philips\\') == 'C:\\Users')
assert(path.dirname('C:\\Users\\philips\\') == 'C:\\Users')
end
-- Test out the OS path objects
assert(path.posix:dirname('/usr/bin/vim') == '/usr/bin')
assert(path.posix:dirname('/usr/bin/') == '/usr')
assert(path.posix:dirname('/usr/bin') == '/usr')
assert(path.nt:dirname('C:\\Users\\philips\\vim.exe') == 'C:\\Users\\philips')
assert(path.nt:dirname('C:\\Users\\philips\\') == 'C:\\Users')
assert(path.nt:dirname('C:\\Users\\philips\\') == 'C:\\Users')
assert(path.posix:join('foo', '/bar') == "foo/bar")
assert(path.posix:join('foo', 'bar') == "foo/bar")
assert(path.posix:join('foo/', 'bar') == "foo/bar")
assert(path.posix:join('foo/', '/bar') == "foo/bar")
assert(path.posix:join('/foo', '/bar') == "/foo/bar")
assert(path.posix:join('/foo', 'bar') == "/foo/bar")
assert(path.posix:join('/foo/', 'bar') == "/foo/bar")
assert(path.posix:join('/foo/', '/bar') == "/foo/bar")
assert(path.posix:join('foo', '/bar/') == "foo/bar/")
assert(path.posix:join('foo', 'bar/') == "foo/bar/")
assert(path.posix:join('foo/', 'bar/') == "foo/bar/")
assert(path.posix:join('foo/', '/bar/') == "foo/bar/")
assert(path.basename('bar.lua') == 'bar.lua')
assert(path.basename('bar.lua', '.lua') == 'bar')
assert(path.basename('bar.lua.js', '.lua') == 'bar.lua.js')
assert(path.basename('.lua', 'lua') == '.')
assert(path.basename('bar', '.lua') == 'bar')
-- test path.basename os specifics
if (os.type() ~= "win32") then
assert(path.basename('/foo/bar.lua') == 'bar.lua')
assert(path.basename('/foo/bar.lua', '.lua') == 'bar')
else
assert(path.basename('c:\\foo\\bar.lua') == 'bar.lua')
assert(path.basename('c:\\foo\\bar.lua', '.lua') == 'bar')
end
|
Fix the path basename tests to have specific tests for windows.
|
Fix the path basename tests to have specific tests for windows.
|
Lua
|
apache-2.0
|
zhaozg/luvit,boundary/luvit,DBarney/luvit,sousoux/luvit,DBarney/luvit,DBarney/luvit,GabrielNicolasAvellaneda/luvit-upstream,bsn069/luvit,boundary/luvit,sousoux/luvit,boundary/luvit,sousoux/luvit,sousoux/luvit,bsn069/luvit,boundary/luvit,rjeli/luvit,zhaozg/luvit,boundary/luvit,rjeli/luvit,rjeli/luvit,kaustavha/luvit,kaustavha/luvit,kaustavha/luvit,bsn069/luvit,DBarney/luvit,sousoux/luvit,luvit/luvit,boundary/luvit,GabrielNicolasAvellaneda/luvit-upstream,GabrielNicolasAvellaneda/luvit-upstream,luvit/luvit,GabrielNicolasAvellaneda/luvit-upstream,sousoux/luvit,rjeli/luvit
|
31d0d09f4f2475ef6a82bef4b0e47db5279642e1
|
lua/selectionConverter.lua
|
lua/selectionConverter.lua
|
function updateClipboard(threadObj)
-- ENCODING among -detect-enc, -sjis, -utf16-be, -utf16-le, -utf8
local ENCODING = "-detect-enc"
-- 0 <= DEBUG_LEVEL <= 5
local DEBUG_LEVEL = 0
-- any positive or negative integer
local STRICTNESS = 20
local hexView = getMemoryViewForm().HexadecimalView
local previousBytes = {}
local handle = io.popen(
"java.exe -jar \"" .. getCheatEngineDir() ..
"autorun\\HexToString.jar\" " ..
ENCODING .. " -d=" .. DEBUG_LEVEL .. " -s=" .. STRICTNESS,
"w"
)
local selectionSize = 0
getMainForm().OnClose = function(sender)
pcall(function()
handle:write("exit")
handle:close()
end)
closeCE()
end
while true do
if hexView.hasSelection then
selectionSize = hexView.SelectionStop-hexView.SelectionStart
local bytes=readBytes(hexView.SelectionStart, selectionSize+1,true)
if bytes ~= nil then
local s = ""
for i = 1, table.getn(bytes) do
s = s .. string.format("%02x", bytes[i])
end
handle:write(s .. "\n")
handle:flush()
previousBytes = bytes
end
end
sleep(300)
end
end
createNativeThread(updateClipboard)
|
function updateClipboard(threadObj)
-- ENCODING among -detect-enc, -sjis, -utf16-be, -utf16-le, -utf8
local ENCODING = "-detect-enc"
-- 0 <= DEBUG_LEVEL <= 5
local DEBUG_LEVEL = 0
-- any positive or negative integer
local STRICTNESS = 20
local hexView = getMemoryViewForm().HexadecimalView
local previousBytes = {}
local handle = io.popen(
"java.exe -jar \"" .. getCheatEngineDir() ..
"autorun\\HexToString.jar\" " ..
ENCODING .. " -d=" .. DEBUG_LEVEL .. " -s=" .. STRICTNESS,
"w"
)
local selectionSize = 0
getMainForm().OnClose = function(sender)
pcall(function()
handle:write("exit")
handle:close()
end)
closeCE()
end
while true do
if hexView.hasSelection then
selectionSize = hexView.SelectionStop-hexView.SelectionStart
local bytes=readBytes(hexView.SelectionStart, selectionSize+1,true)
if bytes ~= nil then
local s = ""
for i = 1, table.getn(bytes) do
s = s .. string.format("%02x", bytes[i])
end
handle:write(s .. "\n")
handle:flush()
previousBytes = bytes
end
end
sleep(300)
end
end
createNativeThread(updateClipboard)
|
Fix indentation in lua file
|
Fix indentation in lua file
|
Lua
|
mit
|
MX-Futhark/hook-any-text
|
13a98fb066635ece8f7843e9b3bb394849c7872d
|
lualib/snax/gateserver.lua
|
lualib/snax/gateserver.lua
|
local skynet = require "skynet"
local netpack = require "netpack"
local socketdriver = require "socketdriver"
local gateserver = {}
local socket -- listen socket
local queue -- message queue
local maxclient -- max client
local client_number = 0
local CMD = setmetatable({}, { __gc = function() netpack.clear(queue) end })
local nodelay = false
local connection = {}
function gateserver.openclient(fd)
if connection[fd] then
socketdriver.start(fd)
end
end
function gateserver.closeclient(fd)
local c = connection[fd]
if c then
connection[fd] = false
socketdriver.close(fd)
end
end
function gateserver.start(handler)
assert(handler.message)
assert(handler.connect)
function CMD.open( source, conf )
assert(not socket)
local address = conf.address or "0.0.0.0"
local port = assert(conf.port)
maxclient = conf.maxclient or 1024
nodelay = conf.nodelay
skynet.error(string.format("Listen on %s:%d", address, port))
socket = socketdriver.listen(address, port)
socketdriver.start(socket)
if handler.open then
return handler.open(source, conf)
end
end
function CMD.close()
assert(socket)
socketdriver.close(socket)
end
local MSG = {}
local function dispatch_msg(fd, msg, sz)
if connection[fd] then
handler.message(fd, msg, sz)
else
skynet.error(string.format("Drop message from fd (%d) : %s", fd, netpack.tostring(msg,sz)))
end
end
MSG.data = dispatch_msg
local function dispatch_queue()
local fd, msg, sz = netpack.pop(queue)
if fd then
-- may dispatch even the handler.message blocked
-- If the handler.message never block, the queue should be empty, so only fork once and then exit.
skynet.fork(dispatch_queue)
dispatch_msg(fd, msg, sz)
for fd, msg, sz in netpack.pop, queue do
dispatch_msg(fd, msg, sz)
end
end
end
MSG.more = dispatch_queue
function MSG.open(fd, msg)
if client_number >= maxclient then
socketdriver.close(fd)
return
end
if nodelay then
socketdriver.nodelay(fd)
end
connection[fd] = true
client_number = client_number + 1
handler.connect(fd, msg)
end
local function close_fd(fd)
local c = connection[fd]
if c ~= nil then
connection[fd] = nil
client_number = client_number - 1
end
end
function MSG.close(fd)
if fd ~= socket then
if handler.disconnect then
handler.disconnect(fd)
end
close_fd(fd)
else
socket = nil
end
end
function MSG.error(fd, msg)
if fd == socket then
socketdriver.close(fd)
skynet.error(msg)
else
if handler.error then
handler.error(fd, msg)
end
close_fd(fd)
end
end
function MSG.warning(fd, size)
if handler.warning then
handler.warning(fd, size)
end
end
skynet.register_protocol {
name = "socket",
id = skynet.PTYPE_SOCKET, -- PTYPE_SOCKET = 6
unpack = function ( msg, sz )
return netpack.filter( queue, msg, sz)
end,
dispatch = function (_, _, q, type, ...)
queue = q
if type then
MSG[type](...)
end
end
}
skynet.start(function()
skynet.dispatch("lua", function (_, address, cmd, ...)
local f = CMD[cmd]
if f then
skynet.ret(skynet.pack(f(address, ...)))
else
skynet.ret(skynet.pack(handler.command(cmd, address, ...)))
end
end)
end)
end
return gateserver
|
local skynet = require "skynet"
local netpack = require "netpack"
local socketdriver = require "socketdriver"
local gateserver = {}
local socket -- listen socket
local queue -- message queue
local maxclient -- max client
local client_number = 0
local CMD = setmetatable({}, { __gc = function() netpack.clear(queue) end })
local nodelay = false
local connection = {}
function gateserver.openclient(fd)
if connection[fd] then
socketdriver.start(fd)
end
end
function gateserver.closeclient(fd)
local c = connection[fd]
if c then
connection[fd] = false
socketdriver.close(fd)
end
end
function gateserver.start(handler)
assert(handler.message)
assert(handler.connect)
function CMD.open( source, conf )
assert(not socket)
local address = conf.address or "0.0.0.0"
local port = assert(conf.port)
maxclient = conf.maxclient or 1024
nodelay = conf.nodelay
skynet.error(string.format("Listen on %s:%d", address, port))
socket = socketdriver.listen(address, port)
socketdriver.start(socket)
if handler.open then
return handler.open(source, conf)
end
end
function CMD.close()
assert(socket)
socketdriver.close(socket)
end
local MSG = {}
local function dispatch_msg(fd, msg, sz)
if connection[fd] then
handler.message(fd, msg, sz)
else
skynet.error(string.format("Drop message from fd (%d) : %s", fd, netpack.tostring(msg,sz)))
end
end
MSG.data = dispatch_msg
local function dispatch_queue()
local fd, msg, sz = netpack.pop(queue)
if fd then
-- may dispatch even the handler.message blocked
-- If the handler.message never block, the queue should be empty, so only fork once and then exit.
skynet.fork(dispatch_queue)
dispatch_msg(fd, msg, sz)
for fd, msg, sz in netpack.pop, queue do
dispatch_msg(fd, msg, sz)
end
end
end
MSG.more = dispatch_queue
function MSG.open(fd, msg)
if client_number >= maxclient then
socketdriver.close(fd)
return
end
if nodelay then
socketdriver.nodelay(fd)
end
connection[fd] = true
client_number = client_number + 1
handler.connect(fd, msg)
end
local function close_fd(fd)
local c = connection[fd]
if c ~= nil then
connection[fd] = nil
client_number = client_number - 1
end
end
function MSG.close(fd)
if fd ~= socket then
if handler.disconnect then
handler.disconnect(fd)
end
close_fd(fd)
else
socket = nil
end
end
function MSG.error(fd, msg)
if fd == socket then
socketdriver.close(fd)
skynet.error(msg)
else
if handler.error then
handler.error(fd, msg)
end
close_fd(fd)
end
end
function MSG.warning(fd, size)
if handler.warning then
handler.warning(fd, size)
end
end
skynet.register_protocol {
name = "socket",
id = skynet.PTYPE_SOCKET, -- PTYPE_SOCKET = 6
unpack = function ( msg, sz )
return netpack.filter( queue, msg, sz)
end,
dispatch = function (_, _, q, type, ...)
queue = q
if type then
MSG[type](...)
end
end
}
skynet.start(function()
skynet.dispatch("lua", function (session, address, cmd, ...)
local f = CMD[cmd]
if f then
skynet.ret(skynet.pack(f(address, ...)))
else
if session == 0 then
handler.command(cmd, address, ...)
else
skynet.ret(skynet.pack(handler.command(cmd, address, ...)))
end
end
end)
end)
end
return gateserver
|
fix: supports 'skynet.send' function for gateserver.
|
fix: supports 'skynet.send' function for gateserver.
|
Lua
|
mit
|
korialuo/skynet,korialuo/skynet,korialuo/skynet
|
84cb67d05c00b0d4026d329838735240e4b36b41
|
share/lua/website/sapo.lua
|
share/lua/website/sapo.lua
|
-- libquvi-scripts
-- Copyright (C) 2010-2012 Toni Gundogdu <legatvs@gmail.com>
--
-- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>.
--
-- This library is free software; you can redistribute it and/or
-- modify it under the terms of the GNU Lesser General Public
-- License as published by the Free Software Foundation; either
-- version 2.1 of the License, or (at your option) any later version.
--
-- This library is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-- Lesser General Public License for more details.
--
-- You should have received a copy of the GNU Lesser General Public
-- License along with this library; if not, write to the Free Software
-- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
-- 02110-1301 USA
--
-- Identify the script.
function ident(self)
package.path = self.script_dir .. '/?.lua'
local C = require 'quvi/const'
local r = {}
r.domain = "videos%.sapo%.pt"
r.formats = "default"
r.categories = C.proto_http
local U = require 'quvi/util'
r.handles = U.handles(self.page_url, {r.domain})
return r
end
-- Query available formats.
function query_formats(self)
self.formats = 'default'
return self
end
-- Parse media URL.
function parse (self)
self.host_id = "sapo"
local p = quvi.fetch(self.page_url)
self.title = p:match('class="tit">(.-)</div>')
or error("no match: media title")
self.id = p:match('vid=(.-)&')
or error("no match: media ID")
self.url = {p:match('?file=(.-)&')
or error("no match: media URL")}
return self
end
-- vim: set ts=4 sw=4 tw=72 expandtab:
|
-- libquvi-scripts
-- Copyright (C) 2010-2012 Toni Gundogdu <legatvs@gmail.com>
--
-- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>.
--
-- This library is free software; you can redistribute it and/or
-- modify it under the terms of the GNU Lesser General Public
-- License as published by the Free Software Foundation; either
-- version 2.1 of the License, or (at your option) any later version.
--
-- This library is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-- Lesser General Public License for more details.
--
-- You should have received a copy of the GNU Lesser General Public
-- License along with this library; if not, write to the Free Software
-- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
-- 02110-1301 USA
--
-- Identify the script.
function ident(self)
package.path = self.script_dir .. '/?.lua'
local C = require 'quvi/const'
local r = {}
r.domain = "videos%.sapo%.pt"
r.formats = "default"
r.categories = C.proto_http
local U = require 'quvi/util'
r.handles = U.handles(self.page_url, {r.domain})
return r
end
-- Query available formats.
function query_formats(self)
self.formats = 'default'
return self
end
-- Parse media URL.
function parse (self)
self.host_id = "sapo"
self.id = self.page_url:match('http://.*sapo.pt/([^?"/]+)')
or error("no match: media ID")
local p = quvi.fetch(self.page_url)
self.title = p:match('"og:title" content="(.-)%s+%-%s+SAPO')
or error("no match: media title")
self.url = {p:match('videoVerifyMrec%("(.-)"')
or error("no match: media URL")}
return self
end
-- vim: set ts=4 sw=4 tw=72 expandtab:
|
FIX: sapo.lua: ID, media stream URL and title
|
FIX: sapo.lua: ID, media stream URL and title
None of ID, URL or title were getting matched with the current
sapo.pt design.
Example URL:
http://videos.sapo.pt/JZOMcU6KPdZV7RTKIphP
|
Lua
|
lgpl-2.1
|
hadess/libquvi-scripts-iplayer,DangerCove/libquvi-scripts,hadess/libquvi-scripts-iplayer,legatvs/libquvi-scripts,DangerCove/libquvi-scripts,legatvs/libquvi-scripts,alech/libquvi-scripts,alech/libquvi-scripts
|
abea1df8c6064e5655c3e0ba70d2cdfbe4061802
|
src/cosy/rockspec/cli.lua
|
src/cosy/rockspec/cli.lua
|
local Lfs = require "lfs"
local Serpent = require "serpent"
-- Compute path:
local main = package.searchpath ("cosy.rockspec", package.path)
if main:sub (1, 2) == "./" then
main = Lfs.currentdir () .. "/" .. main:sub (3)
end
main = main:gsub ("/rockspec/init.lua", "")
local rockspec = {
package = "cosyverif",
version = "master-1",
source = {
url = "git://github.com/cosyverif/library",
},
description = {
summary = "CosyVerif",
detailed = [[]],
homepage = "http://www.cosyverif.org/",
license = "MIT/X11",
maintainer = "Alban Linard <alban@linard.fr>",
},
dependencies = {
"ansicolors >= 1",
"bcrypt >= 2",
"bit32 >= 5",
"copas-ev >= 0",
"coronest >= 1",
"dkjson >= 2",
"hotswap >= 1",
"hotswap-ev >= 1",
"hotswap-http >= 1",
"i18n >= 0",
"jwt >= 0",
"layeredata >= 0",
"lua >= 5.1",
"lua_cliargs >= 2",
"lua-cjson >= 2",
"lua-ev >= v1",
"lua-resty-http >= 0",
"lua-websockets >= v2",
"luacrypto >= 0",
"luafilesystem >= 1",
"lualogging >= 1",
"luasec >= 0",
"luasocket >= 2",
"lustache >= 1",
"md5 >= 1",
"redis-lua >= 2",
"Serpent >= 0",
},
build = {
type = "builtin",
modules = {},
install = {
bin = {
["cosy"] = "src/cosy.lua",
},
conf = {},
},
},
}
local function resource (path)
for content in Lfs.dir (path) do
local subpath = path .. "/" .. content
if Lfs.attributes (subpath, "mode") == "file" then
rockspec.build.install.conf [#rockspec.build.install.conf+1] = "src/cosy/" .. subpath:sub (#main+2)
elseif content ~= "." and content ~= ".."
and Lfs.attributes (subpath, "mode") == "directory" then
resource (subpath)
end
end
end
for module in Lfs.dir (main) do
local path = main .. "/" .. module
if module ~= "." and module ~= ".."
and Lfs.attributes (path, "mode") == "directory" then
if Lfs.attributes (path .. "/init.lua", "mode") == "file" then
rockspec.build.modules ["cosy." .. module] = "src/" .. module .. "/init.lua"
for submodule in Lfs.dir (path) do
if submodule ~= "." and submodule ~= ".."
and Lfs.attributes (path .. "/" .. submodule, "mode") == "file"
and submodule:find "%.lua$" then
submodule = submodule:sub (1, #submodule-4)
rockspec.build.modules ["cosy." .. module .. "." .. submodule] = "src/" .. module .. "/" .. submodule .. ".lua"
end
end
else
resource (path)
end
end
end
local options = {
indent = " ",
comment = false,
sortkeys = true,
compact = false,
fatal = true,
nocode = true,
nohuge = true,
}
local file = io.open ("cosyverif-master-1.rockspec", "w")
for _, key in ipairs {
"package",
"version",
"source",
"description",
"dependencies",
"build",
} do
local output = Serpent.block (rockspec [key], options)
file:write (key .. " = " .. output .. "\n")
end
file:close ()
|
local Arguments = require "argparse"
local Lfs = require "lfs"
local Serpent = require "serpent"
local parser = Arguments () {
name = "cosy-rockspec",
description = "cosy rockspec generator",
}
parser:option "-s" "--source" {
description = "path to cosy source",
default = (os.getenv "PWD") .. "/src",
}
parser:option "-t" "--target" {
description = "path to rockspec directory",
default = (os.getenv "PWD") .. "/rockspec",
}
local arguments = parser:parse ()
local rockspec = {
package = "cosyverif",
version = "master-1",
source = {
url = "git://github.com/cosyverif/library",
},
description = {
summary = "CosyVerif",
detailed = [[]],
homepage = "http://www.cosyverif.org/",
license = "MIT/X11",
maintainer = "Alban Linard <alban@linard.fr>",
},
dependencies = {
"lua >= 5.2",
"ansicolors",
"argparse",
"bcrypt",
"copas-ev",
"coronest",
"dkjson",
"hotswap",
"hotswap-ev",
"hotswap-http",
"i18n",
"jwt",
"layeredata",
"lua-cjson-ol", -- needed by jwt, instead of lua-cjson
"lua-ev",
"lua-resty-http",
"lua-websockets",
"luacrypto",
"luafilesystem",
"lualogging",
"luaposix",
"luasec",
"luasocket",
"lustache",
"md5",
"serpent",
},
build = {
type = "builtin",
modules = {},
install = {
bin = {
["cosy" ] = "src/cosy/client/bin.lua",
["cosy-server" ] = "src/cosy/server/bin.lua",
["cosy-check" ] = "src/cosy/check/bin.lua",
["cosy-rockspec"] = "src/cosy/rockspec/bin.lua",
},
conf = {},
},
},
}
local source = arguments.source .. "/cosy"
local ssource = "src/cosy"
local function resource (path)
for content in Lfs.dir (path) do
local subpath = path .. "/" .. content
if Lfs.attributes (subpath, "mode") == "file"
and not subpath:match "%.lua$"
then rockspec.build.install.conf [#rockspec.build.install.conf+1] = ssource .. "/" .. subpath:sub (#source+2)
elseif content ~= "." and content ~= ".."
and Lfs.attributes (subpath, "mode") == "directory"
then resource (subpath)
end
end
end
for module in Lfs.dir (source) do
local path = source .. "/" .. module
if module ~= "." and module ~= ".."
and Lfs.attributes (path, "mode") == "directory" then
if Lfs.attributes (path .. "/init.lua", "mode") == "file" then
rockspec.build.modules ["cosy." .. module] = ssource .. "/" .. module .. "/init.lua"
end
for submodule in Lfs.dir (path) do
if submodule ~= "." and submodule ~= ".."
and Lfs.attributes (path .. "/" .. submodule, "mode") == "file"
and submodule:find "%.lua$"
and not submodule:find "init%.lua$"
and not submodule:find "bin%.lua$"
then
submodule = submodule:sub (1, #submodule-4)
rockspec.build.modules ["cosy." .. module .. "." .. submodule] = ssource .. "/" .. module .. "/" .. submodule .. ".lua"
end
end
resource (path)
end
end
local options = {
indent = " ",
comment = false,
sortkeys = true,
compact = false,
fatal = true,
nocode = true,
nohuge = true,
}
Lfs.mkdir (arguments.target)
local file = io.open (arguments.target .. "/cosyverif-master-1.rockspec", "w")
for _, key in ipairs {
"package",
"version",
"source",
"description",
"dependencies",
"build",
} do
local output = Serpent.block (rockspec [key], options)
file:write (key .. " = " .. output .. "\n")
end
file:close ()
|
Fix the rockspec generator.
|
Fix the rockspec generator.
|
Lua
|
mit
|
CosyVerif/library,CosyVerif/library,CosyVerif/library
|
334d108d386995c3c3295f096b66a3f3665d7e52
|
luapak/fs.lua
|
luapak/fs.lua
|
---------
-- Utility functions for operations on a file system and paths.
-- Extends LuaFileSystem module.
--
-- **Note: This module is not part of public API!**
----
local lfs = require 'lfs'
local utils = require 'luapak.utils'
local cowrap = coroutine.wrap
local file_attrs = lfs.attributes
local fmt = string.format
local iter_dir = lfs.dir
local open = io.open
local yield = coroutine.yield
local UTF8_BOM = '\239\187\191'
local NUL_PATT = utils.LUA_VERSION == '5.1' and '%z' or '\0'
local function normalize_io_error (name, err)
if err:sub(1, #name + 2) == name..': ' then
err = err:sub(#name + 3)
end
return err
end
local M = {}
--- Converts the `path` to an absolute path.
--
-- Relative paths are referenced from the current working directory of
-- the process unless `relative_to` is given, in which case it will be used as
-- the starting point. If the given pathname starts with a `~` it is NOT
-- expanded, it is treated as a normal directory name.
--
-- @tparam string path The path name to convert.
-- @tparam ?string relative_to The path to prepend when making `path` absolute.
-- Defaults to the current working directory.
-- @treturn string An absolute path name.
function M.absolute_path (path, relative_to)
local fs = require 'luarocks.fs' -- XXX: lua-rocks implementation
return fs.absolute_name(path, relative_to)
end
-- Returns the file name of the `path`, i.e. the last component of the `path`.
--
-- @tparam string path The path name.
-- @treturn string The file name.
function M.basename (path)
return (path:match('[/\\]([^/\\]+)[/\\]*$')) or path
end
--- Returns the directory name of the `path`, i.e. all the path's components
-- except the last one.
--
-- @tparam string path The path name.
-- @treturn string|nil The directory name, or nil if the `path` has
-- only one component (e.g. `/foo` or `foo`).
function M.dirname (path)
return path:match('^(.-)[/\\]+[^/\\]*[/\\]*$')
end
--- Checks if the specified file is a binary file (i.e. not textual).
--
-- @tparam string filename Path of the file.
-- @treturn[1] bool true if the file is binary, false otherwise.
-- @treturn[2] nil
-- @treturn[2] string An error message.
function M.is_binary_file (filename)
local handler, err = open(filename, 'rb')
if not handler then
return false, fmt('Could not open %s: %s', filename, normalize_io_error(filename, err))
end
while true do
local block = handler:read(8192)
if not block then
handler:close()
return false
elseif block:match(NUL_PATT) then
handler:close()
return true
end
end
end
--- Returns true if there's a directory on the `path`, false otherwise.
--
-- @tparam string path
-- @treturn bool
function M.is_dir (path)
local attrs = file_attrs(path)
return attrs and attrs.mode == 'directory'
end
--- Returns true if there's a file on the `path`, false otherwise.
--
-- @tparam string path
-- @treturn bool
function M.is_file (path)
local attrs = file_attrs(path)
return attrs and attrs.mode == 'file'
end
--- Traverses all files under the specified directory recursively.
--
-- @tparam string dir_path Path of the directory to traverse.
-- @treturn coroutine A coroutine that yields file path and its attributes.
function M.walk_dir (dir_path)
-- Trim trailing "/".
if dir_path:sub(-1) == '/' then
dir_path = dir_path:sub(1, -2)
end
local function yieldtree (dir)
for entry in iter_dir(dir) do
if entry ~= '.' and entry ~= '..' then
entry = dir..'/'..entry
local attrs = file_attrs(entry)
yield(entry, attrs)
if attrs.mode == 'directory' then
yieldtree(entry) -- recursive call
end
end
end
end
return cowrap(function()
yieldtree(dir_path)
end)
end
--- Reads the specified file and returns its content as string.
--
-- @tparam string filename Path of the file to read.
-- @tparam string mode The mode in which to open the file, see @{io.open}.
-- @treturn[1] string A content of the file.
-- @treturn[2] nil
-- @treturn[2] string An error message.
function M.read_file (filename, mode)
local handler, err = open(filename, mode)
if not handler then
return nil, fmt('Could not open %s: %s', filename, normalize_io_error(filename, err))
end
local contents, err = handler:read('*a') --luacheck: ignore
if not contents then
return nil, fmt('Could not read %s: %s', filename, normalize_io_error(filename, err))
end
handler:close()
if contents:sub(1, #UTF8_BOM) == UTF8_BOM then
contents = contents:sub(#UTF8_BOM + 1)
end
return contents
end
return setmetatable(M, {
__index = lfs,
})
|
---------
-- Utility functions for operations on a file system and paths.
-- Extends LuaFileSystem module.
--
-- **Note: This module is not part of public API!**
----
local lfs = require 'lfs'
local pkgpath = require 'luapak.pkgpath'
local utils = require 'luapak.utils'
local concat = table.concat
local cowrap = coroutine.wrap
local file_attrs = lfs.attributes
local fmt = string.format
local iter_dir = lfs.dir
local open = io.open
local yield = coroutine.yield
local UTF8_BOM = '\239\187\191'
local NUL_PATT = utils.LUA_VERSION == '5.1' and '%z' or '\0'
local function normalize_io_error (name, err)
if err:sub(1, #name + 2) == name..': ' then
err = err:sub(#name + 3)
end
return err
end
local M = {}
--- Converts the `path` to an absolute path.
--
-- Relative paths are referenced from the current working directory of
-- the process unless `relative_to` is given, in which case it will be used as
-- the starting point. If the given pathname starts with a `~` it is NOT
-- expanded, it is treated as a normal directory name.
--
-- @tparam string path The path name to convert.
-- @tparam ?string relative_to The path to prepend when making `path` absolute.
-- Defaults to the current working directory.
-- @treturn string An absolute path name.
function M.absolute_path (path, relative_to)
local fs = require 'luarocks.fs' -- XXX: lua-rocks implementation
return fs.absolute_name(path, relative_to)
end
-- Returns the file name of the `path`, i.e. the last component of the `path`.
--
-- @tparam string path The path name.
-- @treturn string The file name.
function M.basename (path)
return (path:match('[/\\]([^/\\]+)[/\\]*$')) or path
end
--- Returns the directory name of the `path`, i.e. all the path's components
-- except the last one.
--
-- @tparam string path The path name.
-- @treturn string|nil The directory name, or nil if the `path` has
-- only one component (e.g. `/foo` or `foo`).
function M.dirname (path)
return path:match('^(.-)[/\\]+[^/\\]*[/\\]*$')
end
--- Checks if the specified file is a binary file (i.e. not textual).
--
-- @tparam string filename Path of the file.
-- @treturn[1] bool true if the file is binary, false otherwise.
-- @treturn[2] nil
-- @treturn[2] string An error message.
function M.is_binary_file (filename)
local handler, err = open(filename, 'rb')
if not handler then
return false, fmt('Could not open %s: %s', filename, normalize_io_error(filename, err))
end
while true do
local block = handler:read(8192)
if not block then
handler:close()
return false
elseif block:match(NUL_PATT) then
handler:close()
return true
end
end
end
--- Returns true if there's a directory on the `path`, false otherwise.
--
-- @tparam string path
-- @treturn bool
function M.is_dir (path)
local attrs = file_attrs(path)
return attrs and attrs.mode == 'directory'
end
--- Returns true if there's a file on the `path`, false otherwise.
--
-- @tparam string path
-- @treturn bool
function M.is_file (path)
local attrs = file_attrs(path)
return attrs and attrs.mode == 'file'
end
--- Joins the given path components using platform-specific separator.
--
-- @tparam string ... The path components.
-- @treturn string
function M.path_join (...)
return concat({...}, pkgpath.dir_sep)
end
local path_join = M.path_join
--- Traverses all files under the specified directory recursively.
--
-- @tparam string dir_path Path of the directory to traverse.
-- @treturn coroutine A coroutine that yields file path and its attributes.
function M.walk_dir (dir_path)
-- Trim trailing "/" or "\".
if dir_path:sub(-1):match('[/\\]') then
dir_path = dir_path:sub(1, -2)
end
local function yieldtree (dir)
for entry in iter_dir(dir) do
if entry ~= '.' and entry ~= '..' then
entry = path_join(dir, entry)
local attrs = file_attrs(entry)
yield(entry, attrs)
if attrs.mode == 'directory' then
yieldtree(entry) -- recursive call
end
end
end
end
return cowrap(function()
yieldtree(dir_path)
end)
end
--- Reads the specified file and returns its content as string.
--
-- @tparam string filename Path of the file to read.
-- @tparam string mode The mode in which to open the file, see @{io.open}.
-- @treturn[1] string A content of the file.
-- @treturn[2] nil
-- @treturn[2] string An error message.
function M.read_file (filename, mode)
local handler, err = open(filename, mode)
if not handler then
return nil, fmt('Could not open %s: %s', filename, normalize_io_error(filename, err))
end
local contents, err = handler:read('*a') --luacheck: ignore
if not contents then
return nil, fmt('Could not read %s: %s', filename, normalize_io_error(filename, err))
end
handler:close()
if contents:sub(1, #UTF8_BOM) == UTF8_BOM then
contents = contents:sub(#UTF8_BOM + 1)
end
return contents
end
return setmetatable(M, {
__index = lfs,
})
|
Fix fs.walk_dir() to use platform's dir separator
|
Fix fs.walk_dir() to use platform's dir separator
|
Lua
|
mit
|
jirutka/luapak,jirutka/luapak
|
ee1b801ba023f0abb9a20c018cdccbd4406c9ca6
|
mock/gfx/DeckCanvas.lua
|
mock/gfx/DeckCanvas.lua
|
module 'mock'
local insert = table.insert
local index = table.index
local remove = table.remove
CLASS: DeckCanvas ( GraphicsPropComponent )
:MODEL{
Field 'index' :no_edit();
'----';
Field 'size' :type('vec2') :getset('Size');
Field 'serializedData' :getset( 'SerializedData' ) :no_edit();
'----';
Field 'edit' :action('editPen') :meta{ icon='edit', style='tool'};
Field 'clear' :action('editClear') :meta{ icon='clear' };
}
registerComponent( 'DeckCanvas', DeckCanvas )
--mock.registerEntityWithComponent( 'DeckCanvas', DeckCanvas )
function DeckCanvas:__init()
self.props = {}
self.size = { 500, 500 }
self:getMoaiProp().inside = function()
return self:inside( x,y,z, pad )
end
end
function DeckCanvas:inside( x,y,z, pad )
for i, prop in ipairs( self.props ) do
if prop:inside( x,y,z, pad ) then return true end
end
return false
end
function DeckCanvas:setSize( w, h )
self.size = { w, h }
self:getMoaiProp():setBounds( -w/2, -h/2, 0, w/2, h/2, 0 )
end
function DeckCanvas:getSize()
return unpack( self.size )
end
function DeckCanvas:getSerializedData()
local deckset = {}
local decklist = {}
local id0 = 0
local function affirmDeckId( path )
local id = deckset[ path ]
if not id then
id0 = id0 + 1
id = id0
deckset[ path ] = id
decklist[ id ] = path
end
return id
end
local propDatas = {}
for i, prop in ipairs( self.props ) do
local deckPath = prop.deckPath
if deckPath then
local deckId = affirmDeckId( deckPath )
local x, y, z = prop:getLoc()
local rx, ry, rz = prop:getRot()
local sx, sy, sz = prop:getScl()
local r,g,b,a = prop:getColor()
propDatas[ i ] = {
deck = deckId,
transform = { x,y,z, rx,ry,rz, sx,sy,sz },
color = { r,g,b,a },
}
end
end
local output = {
props = propDatas,
decks = decklist
}
return output
end
function DeckCanvas:setSerializedData( data )
if not data then return end
local decks = data.decks
for i, propData in ipairs( data.props ) do
local deckId = propData.deck
local x,y,z, rx,ry,rz, sx,sy,sz = unpack( propData.transform )
local r,g,b,a = unpack( propData.color )
local prop = self:createProp( decks[ deckId ] )
prop:setLoc( x,y,z )
prop:setRot( rx,ry,rz )
prop:setScl( sx,sy,sz )
prop:setColor( r,g,b,a )
self:_addProp( prop )
end
end
function DeckCanvas:createProp( deckPath )
local deck = loadAsset( deckPath )
if deck then
local prop = MOAIProp.new()
prop:setDeck( deck:getMoaiDeck() )
prop.deckPath = deckPath
return prop
end
end
function DeckCanvas:clear()
for i, prop in ipairs( self.props ) do
self:_removeProp( prop, false )
end
self.props = {}
end
--x,y = local coords
local defaultSortMode = MOAILayer.SORT_Z_ASCENDING
function DeckCanvas:findProps( x, y, radius )
local radius = radius or 1
local ent = self:getEntity()
local x, y, z = ent:getProp( 'render' ):modelToWorld( x, y )
--TODO: use some spatial graph
local partition = ent:getPartition()
local propsInPartition = {
-- partition:propListForRay( x, y, -1000000, 0, 0, 1, defaultSortMode )
partition:propListForBox( x-radius, y-radius, -100000, x+radius, y+radius, 100000, defaultSortMode )
}
local result = {}
for i, prop in ipairs( propsInPartition ) do
if prop.__deckCanvas == self then
insert( result, prop )
end
end
return result
end
function DeckCanvas:findTopProp( x, y )
local props = self:findProps( x, y )
local count = #props
if count > 0 then
return props[ count ]
else
return nil
end
end
function DeckCanvas:removeProps( x, y )
local found = self:findProps( x, y )
for i, prop in ipairs( found ) do
self:_removeProp( prop )
end
end
function DeckCanvas:removeTopProp( x, y )
local found = self:findTopProp( x, y )
if found then
self:_removeProp( found )
end
end
function DeckCanvas:addProp( deckPath )
local prop = self:createProp( deckPath )
if prop then
return self:_addProp( prop )
end
end
local linkPartition = linkPartition
local linkIndex = linkIndex
local linkBlendMode = linkBlendMode
local inheritTransformColorVisible = inheritTransformColorVisible
local linkShader = linkShader
function DeckCanvas:_addProp( prop )
local material = self:getMaterialObject()
local prop0 = self:getMoaiProp()
insert( self.props, prop )
linkPartition( prop, prop0 )
linkIndex( prop, prop0 )
linkBlendMode( prop, prop0 )
inheritTransformColorVisible( prop, prop0 )
linkShader( prop, prop0 )
material:applyToMoaiProp( prop )
prop:forceUpdate()
prop.__deckCanvas = self
return prop
end
function DeckCanvas:_addBoundsProps()
end
local clearLinkPartition = clearLinkPartition
local clearLinkIndex = clearLinkIndex
local clearInheritTransform = clearInheritTransform
local clearInheritColor = clearInheritColor
local clearLinkShader = clearLinkShader
local clearLinkBlendMode = clearLinkBlendMode
function DeckCanvas:_removeProp( prop, removeFromTable )
clearLinkPartition( prop )
clearLinkIndex( prop )
clearInheritTransform( prop )
clearInheritColor( prop )
clearLinkShader( prop )
clearLinkBlendMode( prop )
prop:setPartition( nil )
prop:forceUpdate()
if removeFromTable ~= false then
local props = self.props
local idx = index( props, prop )
if idx then
return remove( props, idx )
end
end
end
function DeckCanvas:applyMaterial( mat )
mat:applyToMoaiProp( self.prop )
for i, prop in ipairs( self.props ) do
mat:applyToMoaiProp( prop )
end
end
function DeckCanvas:insideCanvas( x, y, z, pads )
x, y = self.prop:worldToModel( x, y, z )
local w, h = self:getSize()
return x > -w/2 and h > -h/2 and x < w/2 and y < h/2
end
--------------------------------------------------------------------
--Editor support
function DeckCanvas:onBuildSelectedGizmo()
local giz = mock_edit.SimpleBoundGizmo()
giz:setTarget( self )
return giz
end
local deckCanvasItemBoundsVisible = true
function setDeckCanvasItemBoundsVisible( vis )
deckCanvasItemBoundsVisible = vis
end
function isDeckCanvasItemBoundsVisible()
return deckCanvasItemBoundsVisible
end
local drawRect = MOAIDraw.drawRect
function DeckCanvas:drawBounds()
if deckCanvasItemBoundsVisible then
mock_edit.applyColor( 'deckcanvas-item' )
for i, prop in ipairs( self.props ) do
local x,y,z,x1,y1,z1 = prop:getWorldBounds()
drawRect( x,y,x1,y1 )
end
end
GIIHelper.setVertexTransform( self._entity:getProp() )
local w, h = self:getSize()
mock_edit.applyColor( 'deckcanvas-bound' )
drawRect( -w/2, -h/2, w/2, h/2 )
end
function DeckCanvas:editPen()
mock_edit.startAdhocSceneTool( 'deckcanvas_pen', { target = self } )
end
function DeckCanvas:editClear()
self:clear()
mock_edit.getCurrentSceneView():updateCanvas()
markProtoInstanceOverrided( self, 'serializedData' )
end
|
module 'mock'
local insert = table.insert
local index = table.index
local remove = table.remove
CLASS: DeckCanvas ( GraphicsPropComponent )
:MODEL{
Field 'index' :no_edit();
'----';
Field 'size' :type('vec2') :getset('Size');
Field 'serializedData' :getset( 'SerializedData' ) :no_edit();
'----';
Field 'edit' :action('editPen') :meta{ icon='edit', style='tool'};
Field 'clear' :action('editClear') :meta{ icon='clear' };
}
registerComponent( 'DeckCanvas', DeckCanvas )
--mock.registerEntityWithComponent( 'DeckCanvas', DeckCanvas )
function DeckCanvas:__init()
self.props = {}
self.size = { 500, 500 }
self:getMoaiProp().inside = function()
return self:inside( x,y,z, pad )
end
end
function DeckCanvas:inside( x,y,z, pad )
for i, prop in ipairs( self.props ) do
if prop:inside( x,y,z, pad ) then return true end
end
return false
end
function DeckCanvas:setSize( w, h )
self.size = { w, h }
self:getMoaiProp():setBounds( -w/2, -h/2, 0, w/2, h/2, 0 )
end
function DeckCanvas:getSize()
return unpack( self.size )
end
function DeckCanvas:getSerializedData()
local deckset = {}
local decklist = {}
local id0 = 0
local function affirmDeckId( path )
local id = deckset[ path ]
if not id then
id0 = id0 + 1
id = id0
deckset[ path ] = id
decklist[ id ] = path
end
return id
end
local propDatas = {}
for i, prop in ipairs( self.props ) do
local deckPath = prop.deckPath
if deckPath then
-- assert( deckPath, tostring(prop) )
-- if deckPath then
local deckId = affirmDeckId( deckPath )
local x, y, z = prop:getLoc()
local rx, ry, rz = prop:getRot()
local sx, sy, sz = prop:getScl()
local r,g,b,a = prop:getColor()
table.insert( propDatas, {
deck = deckId,
transform = { x,y,z, rx,ry,rz, sx,sy,sz },
color = { r,g,b,a },
})
end
end
local output = {
props = propDatas,
decks = decklist
}
return output
end
function DeckCanvas:setSerializedData( data )
if not data then return end
local decks = data.decks
for i, propData in ipairs( data.props ) do
local deckId = propData.deck
local x,y,z, rx,ry,rz, sx,sy,sz = unpack( propData.transform )
local r,g,b,a = unpack( propData.color )
local deckPath = decks[ deckId ]
local prop = self:createProp( deckPath )
prop:setLoc( x,y,z )
prop:setRot( rx,ry,rz )
prop:setScl( sx,sy,sz )
prop:setColor( r,g,b,a )
self:_addProp( prop )
end
end
function DeckCanvas:createProp( deckPath )
local deck = loadAsset( deckPath )
if deck then
local prop = MOAIProp.new()
prop:setDeck( deck:getMoaiDeck() )
prop.deckPath = deckPath
return prop
end
end
function DeckCanvas:clear()
for i, prop in ipairs( self.props ) do
self:_removeProp( prop, false )
end
self.props = {}
end
--x,y = local coords
local defaultSortMode = MOAILayer.SORT_Z_ASCENDING
function DeckCanvas:findProps( x, y, radius )
local radius = radius or 1
local ent = self:getEntity()
local x, y, z = ent:getProp( 'render' ):modelToWorld( x, y )
--TODO: use some spatial graph
local partition = ent:getPartition()
local propsInPartition = {
-- partition:propListForRay( x, y, -1000000, 0, 0, 1, defaultSortMode )
partition:propListForBox( x-radius, y-radius, -100000, x+radius, y+radius, 100000, defaultSortMode )
}
local result = {}
for i, prop in ipairs( propsInPartition ) do
if prop.__deckCanvas == self then
insert( result, prop )
end
end
return result
end
function DeckCanvas:findTopProp( x, y )
local props = self:findProps( x, y )
local count = #props
if count > 0 then
return props[ count ]
else
return nil
end
end
function DeckCanvas:removeProps( x, y )
local found = self:findProps( x, y )
for i, prop in ipairs( found ) do
self:_removeProp( prop )
end
end
function DeckCanvas:removeTopProp( x, y )
local found = self:findTopProp( x, y )
if found then
self:_removeProp( found )
end
end
function DeckCanvas:addProp( deckPath )
local prop = self:createProp( deckPath )
if prop then
return self:_addProp( prop )
end
end
local linkPartition = linkPartition
local linkIndex = linkIndex
local linkBlendMode = linkBlendMode
local inheritTransformColorVisible = inheritTransformColorVisible
local linkShader = linkShader
function DeckCanvas:_addProp( prop )
local material = self:getMaterialObject()
local prop0 = self:getMoaiProp()
insert( self.props, prop )
linkPartition( prop, prop0 )
linkIndex( prop, prop0 )
linkBlendMode( prop, prop0 )
inheritTransformColorVisible( prop, prop0 )
linkShader( prop, prop0 )
material:applyToMoaiProp( prop )
prop:forceUpdate()
prop.__deckCanvas = self
return prop
end
function DeckCanvas:_addBoundsProps()
end
local clearLinkPartition = clearLinkPartition
local clearLinkIndex = clearLinkIndex
local clearInheritTransform = clearInheritTransform
local clearInheritColor = clearInheritColor
local clearLinkShader = clearLinkShader
local clearLinkBlendMode = clearLinkBlendMode
function DeckCanvas:_removeProp( prop, removeFromTable )
clearLinkPartition( prop )
clearLinkIndex( prop )
clearInheritTransform( prop )
clearInheritColor( prop )
clearLinkShader( prop )
clearLinkBlendMode( prop )
prop:setPartition( nil )
prop:forceUpdate()
if removeFromTable ~= false then
local props = self.props
local idx = index( props, prop )
if idx then
return remove( props, idx )
end
end
end
function DeckCanvas:applyMaterial( mat )
mat:applyToMoaiProp( self.prop )
for i, prop in ipairs( self.props ) do
mat:applyToMoaiProp( prop )
end
end
function DeckCanvas:insideCanvas( x, y, z, pads )
x, y = self.prop:worldToModel( x, y, z )
local w, h = self:getSize()
return x > -w/2 and h > -h/2 and x < w/2 and y < h/2
end
--------------------------------------------------------------------
--Editor support
function DeckCanvas:onBuildSelectedGizmo()
local giz = mock_edit.SimpleBoundGizmo()
giz:setTarget( self )
return giz
end
local deckCanvasItemBoundsVisible = true
function setDeckCanvasItemBoundsVisible( vis )
deckCanvasItemBoundsVisible = vis
end
function isDeckCanvasItemBoundsVisible()
return deckCanvasItemBoundsVisible
end
local drawRect = MOAIDraw.drawRect
function DeckCanvas:drawBounds()
if deckCanvasItemBoundsVisible then
mock_edit.applyColor( 'deckcanvas-item' )
for i, prop in ipairs( self.props ) do
local x,y,z,x1,y1,z1 = prop:getWorldBounds()
drawRect( x,y,x1,y1 )
end
end
GIIHelper.setVertexTransform( self._entity:getProp() )
local w, h = self:getSize()
mock_edit.applyColor( 'deckcanvas-bound' )
drawRect( -w/2, -h/2, w/2, h/2 )
end
function DeckCanvas:editPen()
mock_edit.startAdhocSceneTool( 'deckcanvas_pen', { target = self } )
end
function DeckCanvas:editClear()
self:clear()
mock_edit.getCurrentSceneView():updateCanvas()
markProtoInstanceOverrided( self, 'serializedData' )
end
|
real. fix deckcanvas
|
real. fix deckcanvas
|
Lua
|
mit
|
tommo/mock
|
32bd9d96d71a42cf2df976eec595ae8ab66523e5
|
applications/luci-olsr/luasrc/model/cbi/olsr/olsrd.lua
|
applications/luci-olsr/luasrc/model/cbi/olsr/olsrd.lua
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
require("luci.fs")
m = Map("olsr", "OLSR")
s = m:section(NamedSection, "general", "olsr")
debug = s:option(ListValue, "DebugLevel")
for i=0, 9 do
debug:value(i)
end
ipv = s:option(ListValue, "IpVersion")
ipv:value("4", "IPv4")
ipv:value("6", "IPv6")
noint = s:option(Flag, "AllowNoInt")
noint.enabled = "yes"
noint.disabled = "no"
s:option(Value, "Pollrate")
tcr = s:option(ListValue, "TcRedundancy")
tcr:value("0", translate("olsr_general_tcredundancy_0"))
tcr:value("1", translate("olsr_general_tcredundancy_1"))
tcr:value("2", translate("olsr_general_tcredundancy_2"))
s:option(Value, "MprCoverage")
lql = s:option(ListValue, "LinkQualityLevel")
lql:value("0", translate("disable"))
lql:value("1", translate("olsr_general_linkqualitylevel_1"))
lql:value("2", translate("olsr_general_linkqualitylevel_2"))
lqfish = s:option(Flag, "LinkQualityFishEye")
s:option(Value, "LinkQualityWinSize")
s:option(Value, "LinkQualityDijkstraLimit")
hyst = s:option(Flag, "UseHysteresis")
hyst.enabled = "yes"
hyst.disabled = "no"
i = m:section(TypedSection, "Interface", translate("interfaces"))
i.anonymous = true
i.addremove = true
i.dynamic = true
network = i:option(ListValue, "Interface", translate("network"))
network:value("")
luci.model.uci.foreach("network", "interface",
function (section)
if section[".name"] ~= "loopback" then
network:value(section[".name"])
end
end)
i:option(Value, "HelloInterval")
i:option(Value, "HelloValidityTime")
i:option(Value, "TcInterval")
i:option(Value, "TcValidityTime")
i:option(Value, "MidInterval")
i:option(Value, "MidValidityTime")
i:option(Value, "HnaInterval")
i:option(Value, "HnaValidityTime")
p = m:section(TypedSection, "LoadPlugin")
p.addremove = true
p.dynamic = true
lib = p:option(ListValue, "Library", translate("library"))
lib:value("")
for k, v in pairs(luci.fs.dir("/usr/lib")) do
if v:sub(1, 6) == "olsrd_" then
lib:value(v)
end
end
for i, sect in ipairs({ "Hna4", "Hna6" }) do
hna = m:section(TypedSection, sect)
hna.addremove = true
hna.anonymous = true
net = hna:option(Value, "NetAddr")
msk = hna:option(Value, "Prefix")
end
ipc = m:section(NamedSection, "IpcConnect")
conns = ipc:option(Value, "MaxConnections")
conns.isInteger = true
nets = ipc:option(Value, "Net")
nets.optional = true
hosts = ipc:option(Value, "Host")
hosts.optional = true
return m
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
require("luci.fs")
m = Map("olsr", "OLSR")
s = m:section(NamedSection, "general", "olsr")
debug = s:option(ListValue, "DebugLevel")
for i=0, 9 do
debug:value(i)
end
ipv = s:option(ListValue, "IpVersion")
ipv:value("4", "IPv4")
ipv:value("6", "IPv6")
noint = s:option(Flag, "AllowNoInt")
noint.enabled = "yes"
noint.disabled = "no"
s:option(Value, "Pollrate")
tcr = s:option(ListValue, "TcRedundancy")
tcr:value("0", translate("olsr_general_tcredundancy_0"))
tcr:value("1", translate("olsr_general_tcredundancy_1"))
tcr:value("2", translate("olsr_general_tcredundancy_2"))
s:option(Value, "MprCoverage")
lql = s:option(ListValue, "LinkQualityLevel")
lql:value("0", translate("disable"))
lql:value("1", translate("olsr_general_linkqualitylevel_1"))
lql:value("2", translate("olsr_general_linkqualitylevel_2"))
lqfish = s:option(Flag, "LinkQualityFishEye")
s:option(Value, "LinkQualityWinSize")
s:option(Value, "LinkQualityDijkstraLimit")
hyst = s:option(Flag, "UseHysteresis")
hyst.enabled = "yes"
hyst.disabled = "no"
i = m:section(TypedSection, "Interface", translate("interfaces"))
i.anonymous = true
i.addremove = true
i.dynamic = true
network = i:option(ListValue, "Interface", translate("network"))
network:value("")
luci.model.uci.foreach("network", "interface",
function (section)
if section[".name"] ~= "loopback" then
if section.type and section.type == "bridge" then
network:value("br-"..section[".name"],section[".name"])
else
network:value(section[".name"])
end
end
end)
i:option(Value, "HelloInterval")
i:option(Value, "HelloValidityTime")
i:option(Value, "TcInterval")
i:option(Value, "TcValidityTime")
i:option(Value, "MidInterval")
i:option(Value, "MidValidityTime")
i:option(Value, "HnaInterval")
i:option(Value, "HnaValidityTime")
p = m:section(TypedSection, "LoadPlugin")
p.addremove = true
p.dynamic = true
lib = p:option(ListValue, "Library", translate("library"))
lib:value("")
for k, v in pairs(luci.fs.dir("/usr/lib")) do
if v:sub(1, 6) == "olsrd_" then
lib:value(v)
end
end
for i, sect in ipairs({ "Hna4", "Hna6" }) do
hna = m:section(TypedSection, sect)
hna.addremove = true
hna.anonymous = true
net = hna:option(Value, "NetAddr")
msk = hna:option(Value, "Prefix")
end
ipc = m:section(NamedSection, "IpcConnect")
conns = ipc:option(Value, "MaxConnections")
conns.isInteger = true
nets = ipc:option(Value, "Net")
nets.optional = true
hosts = ipc:option(Value, "Host")
hosts.optional = true
return m
|
* luci/olsr: fix names of interfaces with type bridge
|
* luci/olsr: fix names of interfaces with type bridge
git-svn-id: edf5ee79c2c7d29460bbb5b398f55862cc26620d@2503 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
|
Lua
|
apache-2.0
|
gwlim/luci,Flexibity/luci,ThingMesh/openwrt-luci,zwhfly/openwrt-luci,saraedum/luci-packages-old,ch3n2k/luci,8devices/carambola2-luci,8devices/carambola2-luci,gwlim/luci,ch3n2k/luci,freifunk-gluon/luci,vhpham80/luci,vhpham80/luci,jschmidlapp/luci,jschmidlapp/luci,stephank/luci,stephank/luci,yeewang/openwrt-luci,alxhh/piratenluci,Flexibity/luci,ThingMesh/openwrt-luci,zwhfly/openwrt-luci,saraedum/luci-packages-old,alxhh/piratenluci,8devices/carambola2-luci,stephank/luci,ThingMesh/openwrt-luci,phi-psi/luci,phi-psi/luci,yeewang/openwrt-luci,dtaht/cerowrt-luci-3.3,phi-psi/luci,Canaan-Creative/luci,gwlim/luci,8devices/carambola2-luci,ch3n2k/luci,projectbismark/luci-bismark,eugenesan/openwrt-luci,Flexibity/luci,8devices/carambola2-luci,ReclaimYourPrivacy/cloak-luci,projectbismark/luci-bismark,freifunk-gluon/luci,jschmidlapp/luci,saraedum/luci-packages-old,ThingMesh/openwrt-luci,ReclaimYourPrivacy/cloak-luci,alxhh/piratenluci,zwhfly/openwrt-luci,ch3n2k/luci,freifunk-gluon/luci,stephank/luci,jschmidlapp/luci,Flexibity/luci,eugenesan/openwrt-luci,stephank/luci,gwlim/luci,projectbismark/luci-bismark,jschmidlapp/luci,phi-psi/luci,Canaan-Creative/luci,yeewang/openwrt-luci,ch3n2k/luci,Canaan-Creative/luci,yeewang/openwrt-luci,Canaan-Creative/luci,vhpham80/luci,projectbismark/luci-bismark,alxhh/piratenluci,alxhh/piratenluci,vhpham80/luci,Canaan-Creative/luci,saraedum/luci-packages-old,Flexibity/luci,ReclaimYourPrivacy/cloak-luci,projectbismark/luci-bismark,Flexibity/luci,gwlim/luci,vhpham80/luci,yeewang/openwrt-luci,ThingMesh/openwrt-luci,zwhfly/openwrt-luci,yeewang/openwrt-luci,freifunk-gluon/luci,dtaht/cerowrt-luci-3.3,eugenesan/openwrt-luci,ThingMesh/openwrt-luci,saraedum/luci-packages-old,Canaan-Creative/luci,ReclaimYourPrivacy/cloak-luci,freifunk-gluon/luci,ReclaimYourPrivacy/cloak-luci,eugenesan/openwrt-luci,dtaht/cerowrt-luci-3.3,jschmidlapp/luci,saraedum/luci-packages-old,zwhfly/openwrt-luci,freifunk-gluon/luci,ThingMesh/openwrt-luci,ReclaimYourPrivacy/cloak-luci,zwhfly/openwrt-luci,Flexibity/luci,ReclaimYourPrivacy/cloak-luci,jschmidlapp/luci,vhpham80/luci,zwhfly/openwrt-luci,Canaan-Creative/luci,yeewang/openwrt-luci,phi-psi/luci,freifunk-gluon/luci,phi-psi/luci,eugenesan/openwrt-luci,8devices/carambola2-luci,freifunk-gluon/luci,stephank/luci,gwlim/luci,eugenesan/openwrt-luci,projectbismark/luci-bismark,projectbismark/luci-bismark,ch3n2k/luci,dtaht/cerowrt-luci-3.3,saraedum/luci-packages-old,zwhfly/openwrt-luci,gwlim/luci,dtaht/cerowrt-luci-3.3,Canaan-Creative/luci,alxhh/piratenluci,ReclaimYourPrivacy/cloak-luci,ch3n2k/luci,alxhh/piratenluci,dtaht/cerowrt-luci-3.3,projectbismark/luci-bismark,8devices/carambola2-luci,zwhfly/openwrt-luci,jschmidlapp/luci,Flexibity/luci,phi-psi/luci,eugenesan/openwrt-luci
|
eebd44da9dd95754da5457950ddd63119a94dc66
|
lualib/skynet/db/redis.lua
|
lualib/skynet/db/redis.lua
|
local skynet = require "skynet"
local socket = require "skynet.socket"
local socketchannel = require "skynet.socketchannel"
local table = table
local string = string
local assert = assert
local redis = {}
local command = {}
local meta = {
__index = command,
-- DO NOT close channel in __gc
}
---------- redis response
local redcmd = {}
redcmd[36] = function(fd, data) -- '$'
local bytes = tonumber(data)
if bytes < 0 then
return true,nil
end
local firstline = fd:read(bytes+2)
return true,string.sub(firstline,1,-3)
end
redcmd[43] = function(fd, data) -- '+'
return true,data
end
redcmd[45] = function(fd, data) -- '-'
return false,data
end
redcmd[58] = function(fd, data) -- ':'
-- todo: return string later
return true, tonumber(data)
end
local function read_response(fd)
local result = fd:readline "\r\n"
local firstchar = string.byte(result)
local data = string.sub(result,2)
return redcmd[firstchar](fd,data)
end
redcmd[42] = function(fd, data) -- '*'
local n = tonumber(data)
if n < 0 then
return true, nil
end
local bulk = {}
local noerr = true
for i = 1,n do
local ok, v = read_response(fd)
if not ok then
noerr = false
end
bulk[i] = v
end
return noerr, bulk
end
-------------------
function command:disconnect()
self[1]:close()
setmetatable(self, nil)
end
-- msg could be any type of value
local function make_cache(f)
return setmetatable({}, {
__mode = "kv",
__index = f,
})
end
local header_cache = make_cache(function(t,k)
local s = "\r\n$" .. k .. "\r\n"
t[k] = s
return s
end)
local command_cache = make_cache(function(t,cmd)
local s = "\r\n$"..#cmd.."\r\n"..cmd:upper()
t[cmd] = s
return s
end)
local count_cache = make_cache(function(t,k)
local s = "*" .. k
t[k] = s
return s
end)
local function compose_message(cmd, msg)
local t = type(msg)
local lines = {}
if t == "table" then
local n = msg.n or #msg
lines[1] = count_cache[n+1]
lines[2] = command_cache[cmd]
local idx = 3
for i = 1, n do
v = msg[i]
if v == nil then
lines[idx] = "\r\n$-1"
idx = idx + 1
else
v= tostring(v)
lines[idx] = header_cache[#v]
lines[idx+1] = v
idx = idx + 2
end
end
lines[idx] = "\r\n"
else
msg = tostring(msg)
lines[1] = "*2"
lines[2] = command_cache[cmd]
lines[3] = header_cache[#msg]
lines[4] = msg
lines[5] = "\r\n"
end
return lines
end
local function redis_login(auth, db)
if auth == nil and db == nil then
return
end
return function(so)
if auth then
so:request(compose_message("AUTH", auth), read_response)
end
if db then
so:request(compose_message("SELECT", db), read_response)
end
end
end
function redis.connect(db_conf)
local channel = socketchannel.channel {
host = db_conf.host,
port = db_conf.port or 6379,
auth = redis_login(db_conf.auth, db_conf.db),
nodelay = true,
overload = db_conf.overload,
}
-- try connect first only once
channel:connect(true)
return setmetatable( { channel }, meta )
end
setmetatable(command, { __index = function(t,k)
local cmd = string.upper(k)
local f = function (self, v, ...)
if type(v) == "table" then
return self[1]:request(compose_message(cmd, v), read_response)
else
return self[1]:request(compose_message(cmd, table.pack(v, ...)), read_response)
end
end
t[k] = f
return f
end})
local function read_boolean(so)
local ok, result = read_response(so)
return ok, result ~= 0
end
function command:exists(key)
local fd = self[1]
return fd:request(compose_message ("EXISTS", key), read_boolean)
end
function command:sismember(key, value)
local fd = self[1]
return fd:request(compose_message ("SISMEMBER", table.pack(key, value)), read_boolean)
end
local function compose_table(lines, msg)
local tinsert = table.insert
tinsert(lines, count_cache[#msg])
for _,v in ipairs(msg) do
v = tostring(v)
tinsert(lines,header_cache[#v])
tinsert(lines,v)
end
tinsert(lines, "\r\n")
return lines
end
function command:pipeline(ops,resp)
assert(ops and #ops > 0, "pipeline is null")
local fd = self[1]
local cmds = {}
for _, cmd in ipairs(ops) do
compose_table(cmds, cmd)
end
if resp then
return fd:request(cmds, function (fd)
for i=1, #ops do
local ok, out = read_response(fd)
table.insert(resp, {ok = ok, out = out})
end
return true, resp
end)
else
return fd:request(cmds, function (fd)
local ok, out
for i=1, #ops do
ok, out = read_response(fd)
end
-- return last response
return ok,out
end)
end
end
--- watch mode
local watch = {}
local watchmeta = {
__index = watch,
__gc = function(self)
self.__sock:close()
end,
}
local function watch_login(obj, auth)
return function(so)
if auth then
so:request(compose_message("AUTH", auth), read_response)
end
for k in pairs(obj.__psubscribe) do
so:request(compose_message ("PSUBSCRIBE", k))
end
for k in pairs(obj.__subscribe) do
so:request(compose_message("SUBSCRIBE", k))
end
end
end
function redis.watch(db_conf)
local obj = {
__subscribe = {},
__psubscribe = {},
}
local channel = socketchannel.channel {
host = db_conf.host,
port = db_conf.port or 6379,
auth = watch_login(obj, db_conf.auth),
nodelay = true,
}
obj.__sock = channel
-- try connect first only once
channel:connect(true)
return setmetatable( obj, watchmeta )
end
function watch:disconnect()
self.__sock:close()
setmetatable(self, nil)
end
local function watch_func( name )
local NAME = string.upper(name)
watch[name] = function(self, ...)
local so = self.__sock
for i = 1, select("#", ...) do
local v = select(i, ...)
so:request(compose_message(NAME, v))
end
end
end
watch_func "subscribe"
watch_func "psubscribe"
watch_func "unsubscribe"
watch_func "punsubscribe"
function watch:message()
local so = self.__sock
while true do
local ret = so:response(read_response)
local type , channel, data , data2 = ret[1], ret[2], ret[3], ret[4]
if type == "message" then
return data, channel
elseif type == "pmessage" then
return data2, data, channel
elseif type == "subscribe" then
self.__subscribe[channel] = true
elseif type == "psubscribe" then
self.__psubscribe[channel] = true
elseif type == "unsubscribe" then
self.__subscribe[channel] = nil
elseif type == "punsubscribe" then
self.__psubscribe[channel] = nil
end
end
end
return redis
|
local skynet = require "skynet"
local socket = require "skynet.socket"
local socketchannel = require "skynet.socketchannel"
local table = table
local string = string
local assert = assert
local redis = {}
local command = {}
local meta = {
__index = command,
-- DO NOT close channel in __gc
}
---------- redis response
local redcmd = {}
redcmd[36] = function(fd, data) -- '$'
local bytes = tonumber(data)
if bytes < 0 then
return true,nil
end
local firstline = fd:read(bytes+2)
return true,string.sub(firstline,1,-3)
end
redcmd[43] = function(fd, data) -- '+'
return true,data
end
redcmd[45] = function(fd, data) -- '-'
return false,data
end
redcmd[58] = function(fd, data) -- ':'
-- todo: return string later
return true, tonumber(data)
end
local function read_response(fd)
local result = fd:readline "\r\n"
local firstchar = string.byte(result)
local data = string.sub(result,2)
return redcmd[firstchar](fd,data)
end
redcmd[42] = function(fd, data) -- '*'
local n = tonumber(data)
if n < 0 then
return true, nil
end
local bulk = {}
local noerr = true
for i = 1,n do
local ok, v = read_response(fd)
if not ok then
noerr = false
end
bulk[i] = v
end
return noerr, bulk
end
-------------------
function command:disconnect()
self[1]:close()
setmetatable(self, nil)
end
-- msg could be any type of value
local function make_cache(f)
return setmetatable({}, {
__mode = "kv",
__index = f,
})
end
local header_cache = make_cache(function(t,k)
local s = "\r\n$" .. k .. "\r\n"
t[k] = s
return s
end)
local command_cache = make_cache(function(t,cmd)
local s = "\r\n$"..#cmd.."\r\n"..cmd:upper()
t[cmd] = s
return s
end)
local count_cache = make_cache(function(t,k)
local s = "*" .. k
t[k] = s
return s
end)
local command_np_cache = make_cache(function(t, cmd)
local s = "*1" .. command_cache[cmd] .. "\r\n"
t[cmd] = s
return s
end)
local function compose_message(cmd, msg)
if msg == nil then
return command_np_cache[cmd]
end
local t = type(msg)
local lines = {}
if t == "table" then
local n = msg.n or #msg
lines[1] = count_cache[n+1]
lines[2] = command_cache[cmd]
local idx = 3
for i = 1, n do
v = msg[i]
if v == nil then
lines[idx] = "\r\n$-1"
idx = idx + 1
else
v= tostring(v)
lines[idx] = header_cache[#v]
lines[idx+1] = v
idx = idx + 2
end
end
lines[idx] = "\r\n"
else
msg = tostring(msg)
lines[1] = "*2"
lines[2] = command_cache[cmd]
lines[3] = header_cache[#msg]
lines[4] = msg
lines[5] = "\r\n"
end
return lines
end
local function redis_login(auth, db)
if auth == nil and db == nil then
return
end
return function(so)
if auth then
so:request(compose_message("AUTH", auth), read_response)
end
if db then
so:request(compose_message("SELECT", db), read_response)
end
end
end
function redis.connect(db_conf)
local channel = socketchannel.channel {
host = db_conf.host,
port = db_conf.port or 6379,
auth = redis_login(db_conf.auth, db_conf.db),
nodelay = true,
overload = db_conf.overload,
}
-- try connect first only once
channel:connect(true)
return setmetatable( { channel }, meta )
end
setmetatable(command, { __index = function(t,k)
local cmd = string.upper(k)
local f = function (self, v, ...)
if v == nil then
return self[1]:request(compose_message(cmd), read_response)
elseif type(v) == "table" then
return self[1]:request(compose_message(cmd, v), read_response)
else
return self[1]:request(compose_message(cmd, table.pack(v, ...)), read_response)
end
end
t[k] = f
return f
end})
local function read_boolean(so)
local ok, result = read_response(so)
return ok, result ~= 0
end
function command:exists(key)
local fd = self[1]
return fd:request(compose_message ("EXISTS", key), read_boolean)
end
function command:sismember(key, value)
local fd = self[1]
return fd:request(compose_message ("SISMEMBER", table.pack(key, value)), read_boolean)
end
local function compose_table(lines, msg)
local tinsert = table.insert
tinsert(lines, count_cache[#msg])
for _,v in ipairs(msg) do
v = tostring(v)
tinsert(lines,header_cache[#v])
tinsert(lines,v)
end
tinsert(lines, "\r\n")
return lines
end
function command:pipeline(ops,resp)
assert(ops and #ops > 0, "pipeline is null")
local fd = self[1]
local cmds = {}
for _, cmd in ipairs(ops) do
compose_table(cmds, cmd)
end
if resp then
return fd:request(cmds, function (fd)
for i=1, #ops do
local ok, out = read_response(fd)
table.insert(resp, {ok = ok, out = out})
end
return true, resp
end)
else
return fd:request(cmds, function (fd)
local ok, out
for i=1, #ops do
ok, out = read_response(fd)
end
-- return last response
return ok,out
end)
end
end
--- watch mode
local watch = {}
local watchmeta = {
__index = watch,
__gc = function(self)
self.__sock:close()
end,
}
local function watch_login(obj, auth)
return function(so)
if auth then
so:request(compose_message("AUTH", auth), read_response)
end
for k in pairs(obj.__psubscribe) do
so:request(compose_message ("PSUBSCRIBE", k))
end
for k in pairs(obj.__subscribe) do
so:request(compose_message("SUBSCRIBE", k))
end
end
end
function redis.watch(db_conf)
local obj = {
__subscribe = {},
__psubscribe = {},
}
local channel = socketchannel.channel {
host = db_conf.host,
port = db_conf.port or 6379,
auth = watch_login(obj, db_conf.auth),
nodelay = true,
}
obj.__sock = channel
-- try connect first only once
channel:connect(true)
return setmetatable( obj, watchmeta )
end
function watch:disconnect()
self.__sock:close()
setmetatable(self, nil)
end
local function watch_func( name )
local NAME = string.upper(name)
watch[name] = function(self, ...)
local so = self.__sock
for i = 1, select("#", ...) do
local v = select(i, ...)
so:request(compose_message(NAME, v))
end
end
end
watch_func "subscribe"
watch_func "psubscribe"
watch_func "unsubscribe"
watch_func "punsubscribe"
function watch:message()
local so = self.__sock
while true do
local ret = so:response(read_response)
local type , channel, data , data2 = ret[1], ret[2], ret[3], ret[4]
if type == "message" then
return data, channel
elseif type == "pmessage" then
return data2, data, channel
elseif type == "subscribe" then
self.__subscribe[channel] = true
elseif type == "psubscribe" then
self.__psubscribe[channel] = true
elseif type == "unsubscribe" then
self.__subscribe[channel] = nil
elseif type == "punsubscribe" then
self.__psubscribe[channel] = nil
end
end
end
return redis
|
fix #1341
|
fix #1341
|
Lua
|
mit
|
korialuo/skynet,cloudwu/skynet,sanikoyes/skynet,xjdrew/skynet,icetoggle/skynet,hongling0/skynet,xjdrew/skynet,icetoggle/skynet,wangyi0226/skynet,wangyi0226/skynet,cloudwu/skynet,cloudwu/skynet,xjdrew/skynet,icetoggle/skynet,sanikoyes/skynet,pigparadise/skynet,hongling0/skynet,pigparadise/skynet,wangyi0226/skynet,korialuo/skynet,hongling0/skynet,korialuo/skynet,pigparadise/skynet,sanikoyes/skynet
|
e90dd05472aa8a6c63458be455a521d1d8a0c735
|
item/id_51_emptybucket.lua
|
item/id_51_emptybucket.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/>.
]]
-- fill bucket from ...
--- cauldron
--- well
--- waters
-- UPDATE items SET itm_script='item.id_51_emptybucket' WHERE itm_id IN (51);
local common = require("base.common")
local alchemy = require("alchemy.base.alchemy")
local licence = require("base.licence")
local M = {}
-- Wassereimer fuellen
function M.UseItem(User, SourceItem, ltstate)
-- check for cauldron
local TargetItem = GetCauldron(User);
if (TargetItem ~= nil) then
common.TurnTo( User, TargetItem.pos ); -- turn if necessary
FillFromCauldron(User,SourceItem,TargetItem,ltstate);
return;
end
if User:countItem(51) <= 0 then
return
end
local foundSource = false;
-- check for well or fountain
TargetItem = common.GetItemInArea(User.pos, 2207);
if (TargetItem == nil) then
TargetItem = common.GetItemInArea(User.pos, 631);
if (TargetItem == nil) then
TargetItem = common.GetItemInArea(User.pos, 2079);
end
if (TargetItem == nil) then
TargetItem = common.GetItemInArea(User.pos, 1097);
end
end
if (TargetItem ~= nil) then
common.TurnTo( User, TargetItem.pos ); -- turn if necessary
foundSource=true
end
-- check for water tile
local targetPos = GetWaterTilePosition(User);
if (targetPos ~= nil) then
common.TurnTo( User, targetPos ); -- turn if necessary
foundSource=true
end
if not foundSource then
-- nothing found to fill the bucket.
common.InformNLS(User,
"Du kannst den Eimer an einem Brunnen oder an einem Gewsser fllen.",
"You can fill the bucket at a well or at some waters.");
return
end
if ( ltstate == Action.abort ) then
common.InformNLS(User, "Du brichst deine Arbeit ab.", "You abort your work.")
return
end
if ( ltstate == Action.none ) then
User:startAction( 20, 21, 5, 10, 25);
User:talk(Character.say, "#me beginnt Eimer zu befllen.", "#me starts to fill buckets.")
return
end
local notCreated = User:createItem( 52, 1, 333, nil ); -- create the new produced items
if ( notCreated > 0 ) then -- too many items -> character can't carry anymore
world:createItemFromId( 52, notCreated, User.pos, true, 333, nil );
common.HighInformNLS(User,
"Du kannst nichts mehr halten.",
"You can't carry any more.");
world:erase(SourceItem,1)
return
else -- character can still carry something
if SourceItem.number == 1 then
world:erase(SourceItem,1)
return
else
world:erase(SourceItem,1)
SourceItem.number = SourceItem.number-1
world:changeItem(SourceItem)
User:changeSource(SourceItem)
User:startAction( 20, 21, 5, 10, 25);
end
end
end
function FillFromCauldron(User,SourceItem,TargetItem,ltstate)
if ( ltstate == Action.abort ) then
common.InformNLS(User, "Du brichst deine Arbeit ab.", "You abort your work.")
return
end
-- is the char an alchemist?
local anAlchemist = alchemy.CheckIfAlchemist(User)
if not anAlchemist then
User:inform("Auf dem Schriftstck steht nur dir unverstndliches Alchemistengeschwafel.","For you the document only appears to contain unintelligible alchemical gibberish.")
return
end
if ( ltstate == Action.none ) then
User:startAction( 20, 21, 5, 0, 0)
return
end
common.InformNLS(User,
"Du fllst den Eimer mit dem Wasser im Kessel.",
"You fill the bucket with the water in the cauldron.");
world:makeSound(10,TargetItem.pos)
TargetItem.id = 1008
TargetItem:setData("filledWith","")
world:changeItem(TargetItem)
if SourceItem.number > 1 then
world:erase(SourceItem,1)
local notCreated=User:createItem(52,1,333,nil)
if ( notCreated > 0 ) then -- too many items -> character can't carry anymore
world:createItemFromId(52,1,User.pos,true,333,nil)
common.HighInformNLS(User,
"Du kannst nichts mehr halten.",
"You can't carry any more.");
end
else
SourceItem.id = 52
SourceItem.quality = 333
world:changeItem(SourceItem)
end
end
-- returns a cauldron filled with water if one is found next to the user.
function GetCauldron(User)
-- first check in front
local frontPos = common.GetFrontPosition(User);
if (world:isItemOnField(frontPos)) then
local item = world:getItemOnField(frontPos);
if (item.id == 1010 and item:getData("filledWith") == "water") then
return item;
end
end
local Radius = 1;
for x=-Radius,Radius do
for y=-Radius,Radius do
local targetPos = position(User.pos.x + x, User.pos.y, User.pos.z);
if (world:isItemOnField(targetPos)) then
local item = world:getItemOnField(targetPos);
if (item.id == 1010 and item:getData("filledWith") == "water") then
return item;
end
end
end
end
return nil;
end
function GetWaterTilePosition(User)
local targetPos = common.GetFrontPosition(User);
if (common.GetGroundType(world:getField(targetPos):tile()) == common.GroundType.water) then
return targetPos;
end
local Radius = 1;
for x=-Radius,Radius do
for y=-Radius,Radius do
targetPos = position(User.pos.x + x, User.pos.y, User.pos.z);
if (common.GetGroundType(world:getField(targetPos):tile()) == common.GroundType.water) then
return targetPos;
end
end
end
return nil;
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/>.
]]
-- UPDATE items SET itm_script='item.id_51_emptybucket' WHERE itm_id IN (51);
local common = require("base.common")
local alchemy = require("alchemy.base.alchemy")
-- fill bucket from ...
-- cauldron
-- well
-- water tiles
local M = {}
local FillFromCauldron
local GetWaterTilePosition
local GetCauldron
function M.UseItem(User, SourceItem, ltstate)
-- check for cauldron
local TargetItem = GetCauldron(User)
if (TargetItem ~= nil) then
common.TurnTo( User, TargetItem.pos ) -- turn if necessary
FillFromCauldron(User, SourceItem, TargetItem, ltstate)
return
end
if User:countItem(51) <= 0 then
return
end
local foundSource = false
-- check for well or fountain
TargetItem = common.GetItemInArea(User.pos, 2207)
if (TargetItem == nil) then
TargetItem = common.GetItemInArea(User.pos, 631)
if (TargetItem == nil) then
TargetItem = common.GetItemInArea(User.pos, 2079)
end
if (TargetItem == nil) then
TargetItem = common.GetItemInArea(User.pos, 1097)
end
end
if (TargetItem ~= nil) then
common.TurnTo(User, TargetItem.pos) -- turn if necessary
foundSource = true
end
-- check for water tile
local targetPos = GetWaterTilePosition(User)
if (targetPos ~= nil) then
common.TurnTo(User, targetPos) -- turn if necessary
foundSource = true
end
if not foundSource then
-- nothing found to fill the bucket.
common.InformNLS(User,
"Du kannst den Eimer an einem Brunnen oder an einem Gewsser fllen.",
"You can fill the bucket at a well or at some waters.")
return
end
if ( ltstate == Action.abort ) then
common.InformNLS(User, "Du brichst deine Arbeit ab.", "You abort your work.")
return
end
if ( ltstate == Action.none ) then
User:startAction( 20, 21, 5, 10, 25)
User:talk(Character.say, "#me beginnt Eimer zu befllen.", "#me starts to fill buckets.")
return
end
local notCreated = User:createItem( 52, 1, 333, nil ) -- create the new produced items
if ( notCreated > 0 ) then -- too many items -> character can't carry anymore
world:createItemFromId( 52, notCreated, User.pos, true, 333, nil )
common.HighInformNLS(User,
"Du kannst nichts mehr halten.",
"You can't carry any more.")
world:erase(SourceItem,1)
return
else -- character can still carry something
if SourceItem.number == 1 then
world:erase(SourceItem,1)
return
else
world:erase(SourceItem,1)
SourceItem.number = SourceItem.number-1
world:changeItem(SourceItem)
User:changeSource(SourceItem)
User:startAction( 20, 21, 5, 10, 25)
end
end
end
function FillFromCauldron(User,SourceItem,TargetItem,ltstate)
if ( ltstate == Action.abort ) then
common.InformNLS(User, "Du brichst deine Arbeit ab.", "You abort your work.")
return
end
-- is the char an alchemist?
local anAlchemist = alchemy.CheckIfAlchemist(User)
if not anAlchemist then
User:inform("Auf dem Schriftstck steht nur dir unverstndliches Alchemistengeschwafel.","For you the document only appears to contain unintelligible alchemical gibberish.")
return
end
if ( ltstate == Action.none ) then
User:startAction( 20, 21, 5, 0, 0)
return
end
common.InformNLS(User,
"Du fllst den Eimer mit dem Wasser im Kessel.",
"You fill the bucket with the water in the cauldron.")
world:makeSound(10,TargetItem.pos)
TargetItem.id = 1008
TargetItem:setData("filledWith","")
world:changeItem(TargetItem)
if SourceItem.number > 1 then
world:erase(SourceItem,1)
local notCreated=User:createItem(52,1,333,nil)
if ( notCreated > 0 ) then -- too many items -> character can't carry anymore
world:createItemFromId(52,1,User.pos,true,333,nil)
common.HighInformNLS(User,
"Du kannst nichts mehr halten.",
"You can't carry any more.")
end
else
SourceItem.id = 52
SourceItem.quality = 333
world:changeItem(SourceItem)
end
end
-- returns a cauldron filled with water if one is found next to the user.
function GetCauldron(User)
-- first check in front
local frontPos = common.GetFrontPosition(User)
if (world:isItemOnField(frontPos)) then
local item = world:getItemOnField(frontPos)
if (item.id == 1010 and item:getData("filledWith") == "water") then
return item
end
end
local Radius = 1
for x=-Radius,Radius do
for y=-Radius,Radius do
local targetPos = position(User.pos.x + x, User.pos.y, User.pos.z)
if (world:isItemOnField(targetPos)) then
local item = world:getItemOnField(targetPos)
if (item.id == 1010 and item:getData("filledWith") == "water") then
return item
end
end
end
end
return nil
end
function GetWaterTilePosition(User)
local targetPos = common.GetFrontPosition(User)
if (common.GetGroundType(world:getField(targetPos):tile()) == common.GroundType.water) then
return targetPos
end
local Radius = 1
for x=-Radius,Radius do
for y=-Radius,Radius do
targetPos = position(User.pos.x + x, User.pos.y, User.pos.z)
if (common.GetGroundType(world:getField(targetPos):tile()) == common.GroundType.water) then
return targetPos
end
end
end
return nil
end
return M
|
some style fixes
|
some style fixes
|
Lua
|
agpl-3.0
|
Baylamon/Illarion-Content,KayMD/Illarion-Content,Illarion-eV/Illarion-Content,vilarion/Illarion-Content
|
b47a191363e4d820535d7f17cf327c0987a2a9d0
|
hammerspoon/.hammerspoon/windows.lua
|
hammerspoon/.hammerspoon/windows.lua
|
local module = {}
module.init = function()
DimensionsHistory = (function()
local history = {}
return {
push = function(win)
local f = win:frame()
local originalDimensions = {
x = f.x,
y = f.y,
w = f.w,
h = f.h,
}
if history[win:id()] and not history[win:id()][20] then
table.insert(history[win:id()], originalDimensions)
else
history[win:id()] = { originalDimensions }
end
end,
pop = function(win)
if not history[win:id()] then
return nil
end
return table.remove(history[win:id()])
end,
}
end)()
updatedFrame = function(win, dimensionUpdates)
local f = win:frame()
local max = win:screen():frame()
f.x = dimensionUpdates.x and dimensionUpdates.x(max, f) or f.x
f.y = dimensionUpdates.y and dimensionUpdates.y(max, f) or f.y
f.w = dimensionUpdates.w and dimensionUpdates.w(max, f) or f.w
f.h = dimensionUpdates.h and dimensionUpdates.h(max, f) or f.h
return f
end
updateWindow = function(dimensionUpdates)
return function()
local win = hs.window.focusedWindow()
local f = win:frame()
DimensionsHistory.push(win)
win:setFrame(updatedFrame(win, dimensionUpdates))
end
end
zero = function() return 0 end
halfWidth = function(max) return max.w / 2 end
maxWidth = function(max) return max.w end
halfHeight = function(max) return max.h / 2 end
maxHeight = function(max) return max.h end
local prefix = { 'cmd', 'alt', 'ctrl' }
hs.window.animationDuration = 0
hs.hotkey.bind(prefix, 'H', updateWindow({
x = zero,
y = zero,
w = halfWidth,
h = maxHeight,
}))
hs.hotkey.bind(prefix, 'L', updateWindow({
x = halfWidth,
y = zero,
w = halfWidth,
h = maxHeight,
}))
hs.hotkey.bind(prefix, 'J', updateWindow({
x = zero,
y = halfHeight,
w = maxWidth,
h = halfHeight,
}))
hs.hotkey.bind(prefix, 'K', updateWindow({
x = zero,
y = zero,
w = maxWidth,
h = halfHeight,
}))
hs.hotkey.bind(prefix, 'F', updateWindow({
x = zero,
y = zero,
w = maxWidth,
h = maxHeight,
}))
hs.hotkey.bind(prefix, 'C', updateWindow({
x = function(max, f) return max.x + (max.w / 2 - f.w / 2) end,
y = function(max, f) return max.y + (max.h / 2 - f.h / 2) end,
}))
hs.hotkey.bind(prefix, '=', updateWindow({
x = function(max, f) return f.x - 25 end,
y = function(max, f) return f.y - 25 end,
w = function(max, f) return f.w + 50 end,
h = function(max, f) return f.h + 50 end,
}))
hs.hotkey.bind(prefix, '-', updateWindow({
x = function(max, f) return f.x + 25 end,
y = function(max, f) return f.y + 25 end,
w = function(max, f) return f.w - 50 end,
h = function(max, f) return f.h - 50 end,
}))
hs.hotkey.bind(prefix, 'U', function()
local win = hs.window.focusedWindow()
local f = win:frame()
previousDimensions = DimensionsHistory.pop(win)
if not previousDimensions then return end
f.x = previousDimensions.x
f.y = previousDimensions.y
f.w = previousDimensions.w
f.h = previousDimensions.h
win:setFrame(f)
end)
end
return module
|
local module = {}
module.init = function()
DimensionsHistory = (function()
local history = {}
return {
push = function(win)
local f = win:frame()
local originalDimensions = {
x = f.x,
y = f.y,
w = f.w,
h = f.h,
}
if history[win:id()] and not history[win:id()][20] then
table.insert(history[win:id()], originalDimensions)
else
history[win:id()] = { originalDimensions }
end
end,
pop = function(win)
if not history[win:id()] then
return nil
end
return table.remove(history[win:id()])
end,
}
end)()
updatedFrame = function(win, dimensionUpdates)
local f = win:frame()
local max = win:screen():frame()
f.x = dimensionUpdates.x and dimensionUpdates.x(max, f) or f.x
f.y = dimensionUpdates.y and dimensionUpdates.y(max, f) or f.y
f.w = dimensionUpdates.w and dimensionUpdates.w(max, f) or f.w
f.h = dimensionUpdates.h and dimensionUpdates.h(max, f) or f.h
return f
end
updateWindow = function(dimensionUpdates)
return function()
local win = hs.window.focusedWindow()
local f = win:frame()
DimensionsHistory.push(win)
win:setFrame(updatedFrame(win, dimensionUpdates))
end
end
zero = function() return 0 end
halfWidth = function(max) return max.w / 2 end
maxWidth = function(max) return max.w end
halfHeight = function(max) return max.h / 2 end
maxHeight = function(max) return max.h end
local prefix = { 'cmd', 'alt', 'ctrl' }
hs.window.animationDuration = 0
hs.hotkey.bind(prefix, 'H', updateWindow({
x = zero,
y = zero,
w = halfWidth,
h = maxHeight,
}))
hs.hotkey.bind(prefix, 'L', updateWindow({
x = halfWidth,
y = zero,
w = halfWidth,
h = maxHeight,
}))
hs.hotkey.bind(prefix, 'J', updateWindow({
x = zero,
y = function(max) return halfHeight(max) + 23 end, -- weird offset bug
w = maxWidth,
h = halfHeight,
}))
hs.hotkey.bind(prefix, 'K', updateWindow({
x = zero,
y = zero,
w = maxWidth,
h = halfHeight,
}))
hs.hotkey.bind(prefix, 'F', updateWindow({
x = zero,
y = zero,
w = maxWidth,
h = maxHeight,
}))
hs.hotkey.bind(prefix, 'C', updateWindow({
x = function(max, f) return max.x + (max.w / 2 - f.w / 2) end,
y = function(max, f) return max.y + (max.h / 2 - f.h / 2) end,
}))
hs.hotkey.bind(prefix, '=', updateWindow({
x = function(max, f) return f.x - 25 end,
y = function(max, f) return f.y - 25 end,
w = function(max, f) return f.w + 50 end,
h = function(max, f) return f.h + 50 end,
}))
hs.hotkey.bind(prefix, '-', updateWindow({
x = function(max, f) return f.x + 25 end,
y = function(max, f) return f.y + 25 end,
w = function(max, f) return f.w - 50 end,
h = function(max, f) return f.h - 50 end,
}))
hs.hotkey.bind(prefix, 'U', function()
local win = hs.window.focusedWindow()
local f = win:frame()
previousDimensions = DimensionsHistory.pop(win)
if not previousDimensions then return end
f.x = previousDimensions.x
f.y = previousDimensions.y
f.w = previousDimensions.w
f.h = previousDimensions.h
win:setFrame(f)
end)
end
return module
|
[hammerspoon] Add hack to fix weird offset bug for bottom-half window
|
[hammerspoon] Add hack to fix weird offset bug for bottom-half window
|
Lua
|
mit
|
spinningarrow/.files,spinningarrow/.files
|
fc4908f033cd387955d3d9eb4caa3f22564e4f2d
|
plugins/translate.lua
|
plugins/translate.lua
|
-- Glanced at https://github.com/yagop/telegram-bot/blob/master/plugins/translate.lua
local PLUGIN = {}
PLUGIN.triggers = {
'^/translate'
}
PLUGIN.doc = [[
/translate [target lang]
Reply to a message to translate it to the default language.
]]
PLUGIN.action = function(msg)
if not msg.reply_to_message then
return send_msg(msg, PLUGIN.doc)
end
local tl = config.locale.translate or 'en'
local input = get_input(msg.text)
if input then
tl = input
end
local url = 'http://translate.google.com/translate_a/single?client=t&ie=UTF-8&oe=UTF-8&hl=en&dt=t&tl=' .. tl .. '&sl=auto&text=' .. URL.escape(msg.reply_to_message.text)
local str, res = HTTP.request(url)
if res ~= 200 then
return send_msg(msg, config.locale.errors.connection)
end
local output = str:gmatch("%[%[%[\"(.*)\"")():gsub("\"(.*)", "")
send_msg(msg.reply_to_message, output)
end
return PLUGIN
|
-- Glanced at https://github.com/yagop/telegram-bot/blob/master/plugins/translate.lua
local PLUGIN = {}
PLUGIN.triggers = {
'^/translate'
}
PLUGIN.doc = [[
/translate [target lang]
Reply to a message to translate it to the default language.
]]
PLUGIN.action = function(msg)
if not msg.reply_to_message then
return send_msg(msg, PLUGIN.doc)
end
local tl = config.locale.translate or 'en'
local input = get_input(msg.text)
if input then
tl = input
end
local url = 'http://translate.google.com/translate_a/single?client=t&ie=UTF-8&oe=UTF-8&hl=en&dt=t&tl=' .. tl .. '&sl=auto&text=' .. URL.escape(msg.reply_to_message.text)
local str, res = HTTP.request(url)
if res ~= 200 then
return send_msg(msg, config.locale.errors.connection)
end
local output = str:gmatch("%[%[%[\"(.*)\"")():gsub("\"(.*)", "")
local output = latcyr(output)
send_msg(msg.reply_to_message, output)
end
return PLUGIN
|
fixed potential exploit in translate.lua
|
fixed potential exploit in translate.lua
|
Lua
|
mit
|
barreeeiroo/BarrePolice,TiagoDanin/SiD,Brawl345/Brawlbot-v2,bb010g/otouto,topkecleon/otouto
|
4218da2b8d36cea786d2fd7927804401c753128f
|
ralis/cli/launcher.lua
|
ralis/cli/launcher.lua
|
-- dependencies
local ansicolors = require 'ansicolors'
require 'ralis.core.ralis'
local BaseLauncher = require 'ralis.cli.base_launcher'
-- settings
local nginx_conf_source = 'config/nginx.conf'
local function convert_boolean_to_onoff(value)
if value == true then value = 'on' else value = 'off' end
return value
end
local function nginx_conf_content()
-- read nginx.conf file
local nginx_conf_template = read_file(nginx_conf_source)
-- append notice
nginx_conf_template = [[
# ===================================================================== #
# THIS FILE IS AUTO GENERATED. DO NOT MODIFY. #
# IF YOU CAN SEE IT, THERE PROBABLY IS A RUNNING SERVER REFERENCING IT. #
# ===================================================================== #
]] .. nginx_conf_template
-- inject params in content
local nginx_content = nginx_conf_template
nginx_content = string.gsub(nginx_content, "{{RALIS_PORT}}", Ralis.settings.port)
nginx_content = string.gsub(nginx_content, "{{RALIS_ENV}}", Ralis.env)
nginx_content = string.gsub(nginx_content, "{{RALIS_CODE_CACHE}}", convert_boolean_to_onoff(Ralis.settings.code_cache))
-- api console
local api_console_code = [[content_by_lua 'require(\"ralis.cli.api_console\").handler(ngx)';]]
if Ralis.env == 'development' then
nginx_content = string.gsub(nginx_content, "{{RALIS_API_CONSOLE}}", api_console_code)
else
nginx_content = string.gsub(nginx_content, "{{RALIS_API_CONSOLE}}", "")
end
return nginx_content
end
function nginx_conf_file_path()
return Ralis.app_dirs.tmp .. "/" .. Ralis.env .. "-nginx.conf"
end
-- init base_launcher
local base_launcher = BaseLauncher.new(nginx_conf_content(), nginx_conf_file_path())
local RalisLauncher = {}
function RalisLauncher.start()
result = base_launcher:start()
if result == 0 then
if Ralis.env ~= 'test' then
print(ansicolors("Ralis app in %{cyan}" .. Ralis.env .. "%{reset} was succesfully started on port " .. Ralis.settings.port .. "."))
end
else
print(ansicolors("%{red}ERROR:%{reset} Could not start Ralis app on port " .. Ralis.settings.port .. " (is it running already?)."))
end
end
function RalisLauncher.stop()
result = base_launcher:stop()
if Ralis.env ~= 'test' then
if result == 0 then
print(ansicolors("Ralis app in %{cyan}" .. Ralis.env .. "%{reset} was succesfully stopped."))
else
print(ansicolors("%{red}ERROR:%{reset} Could not stop Ralis app (are you sure it is running?)."))
end
end
end
return RalisLauncher
|
-- dependencies
local ansicolors = require 'ansicolors'
require 'ralis.core.ralis'
local BaseLauncher = require 'ralis.cli.base_launcher'
-- settings
local nginx_conf_source = 'config/nginx.conf'
local function convert_boolean_to_onoff(value)
if value == true then value = 'on' else value = 'off' end
return value
end
local function nginx_conf_content()
-- read nginx.conf file
local nginx_conf_template = read_file(nginx_conf_source)
-- append notice
nginx_conf_template = [[
# ===================================================================== #
# THIS FILE IS AUTO GENERATED. DO NOT MODIFY. #
# IF YOU CAN SEE IT, THERE PROBABLY IS A RUNNING SERVER REFERENCING IT. #
# ===================================================================== #
]] .. nginx_conf_template
-- inject params in content
local nginx_content = nginx_conf_template
nginx_content = string.gsub(nginx_content, "{{RALIS_PORT}}", Ralis.settings.port)
nginx_content = string.gsub(nginx_content, "{{RALIS_ENV}}", Ralis.env)
nginx_content = string.gsub(nginx_content, "{{RALIS_CODE_CACHE}}", convert_boolean_to_onoff(Ralis.settings.code_cache))
-- api console
local api_console_code = [[content_by_lua 'require(\"ralis.cli.api_console\").handler(ngx)';]]
if Ralis.env == 'development' then
nginx_content = string.gsub(nginx_content, "{{RALIS_API_CONSOLE}}", api_console_code)
else
nginx_content = string.gsub(nginx_content, "{{RALIS_API_CONSOLE}}", "")
end
return nginx_content
end
function nginx_conf_file_path()
return Ralis.app_dirs.tmp .. "/" .. Ralis.env .. "-nginx.conf"
end
function base_launcher()
return BaseLauncher.new(nginx_conf_content(), nginx_conf_file_path())
end
local RalisLauncher = {}
function RalisLauncher.start()
-- init base_launcher
local base_launcher = base_launcher()
result = base_launcher:start()
if result == 0 then
if Ralis.env ~= 'test' then
print(ansicolors("Ralis app in %{cyan}" .. Ralis.env .. "%{reset} was succesfully started on port " .. Ralis.settings.port .. "."))
end
else
print(ansicolors("%{red}ERROR:%{reset} Could not start Ralis app on port " .. Ralis.settings.port .. " (is it running already?)."))
end
end
function RalisLauncher.stop()
-- init base_launcher
local base_launcher = base_launcher()
result = base_launcher:stop()
if Ralis.env ~= 'test' then
if result == 0 then
print(ansicolors("Ralis app in %{cyan}" .. Ralis.env .. "%{reset} was succesfully stopped."))
else
print(ansicolors("%{red}ERROR:%{reset} Could not stop Ralis app (are you sure it is running?)."))
end
end
end
return RalisLauncher
|
Fix bug of launcher getting initialized on ralis cli.
|
Fix bug of launcher getting initialized on ralis cli.
|
Lua
|
mit
|
istr/gin,ostinelli/gin
|
d9c88b0c2a478138f91003c7de2509ce183930e3
|
lua/entities/gmod_wire_expression2/base/tokenizer.lua
|
lua/entities/gmod_wire_expression2/base/tokenizer.lua
|
/******************************************************************************\
Expression 2 Tokenizer for Garry's Mod
Andreas "Syranide" Svensson, me@syranide.com
\******************************************************************************/
AddCSLuaFile("tokenizer.lua")
Tokenizer = {}
Tokenizer.__index = Tokenizer
function Tokenizer.Execute(...)
-- instantiate Tokenizer
local instance = setmetatable({}, Tokenizer)
-- and pcall the new instance's Process method.
return pcall(Tokenizer.Process, instance, ...)
end
function Tokenizer:Error(message, offset)
error(message .. " at line " .. self.tokenline .. ", char " .. (self.tokenchar+(offset or 0)), 0)
end
function Tokenizer:Process(buffer, params)
self.buffer = buffer
self.length = buffer:len()
self.position = 0
self:SkipCharacter()
local tokens = {}
local tokenname, tokendata, tokenspace
self.tokendata = ""
while self.character do
tokenspace = self:NextPattern("%s+") and true or false
if !self.character then break end
self.tokenline = self.readline
self.tokenchar = self.readchar
self.tokendata = ""
tokenname, tokendata = self:NextSymbol()
if tokenname == nil then
tokenname, tokendata = self:NextOperator()
if tokenname == nil then
self:Error("Unknown character found (" .. self.character .. ")")
end
end
tokens[#tokens + 1] = { tokenname, tokendata, tokenspace, self.tokenline, self.tokenchar }
end
return tokens
end
/******************************************************************************/
function Tokenizer:SkipCharacter()
if self.position < self.length then
if self.position > 0 then
if self.character == "\n" then
self.readline = self.readline + 1
self.readchar = 1
else
self.readchar = self.readchar + 1
end
else
self.readline = 1
self.readchar = 1
end
self.position = self.position + 1
self.character = self.buffer:sub(self.position, self.position)
else
self.character = nil
end
end
function Tokenizer:NextCharacter()
self.tokendata = self.tokendata .. self.character
self:SkipCharacter()
end
-- Returns true on success, nothing if it fails.
function Tokenizer:NextPattern(pattern)
if not self.character then return false end
local startpos,endpos,text = self.buffer:find(pattern, self.position)
if startpos ~= self.position then return false end
local buf = self.buffer:sub(startpos, endpos)
if not text then text = buf end
self.tokendata = self.tokendata .. text
self.position = endpos + 1
if self.position <= self.length then
self.character = self.buffer:sub(self.position, self.position)
else
self.character = nil
end
buf = string.Explode("\n", buf)
if #buf > 1 then
self.readline = self.readline+#buf-1
self.readchar = #buf[#buf]+1
else
self.readchar = self.readchar + #buf[#buf]
end
return true
end
function Tokenizer:NextSymbol()
local tokenname
if self:NextPattern("^[0-9]+%.?[0-9]*") then
-- real/imaginary/quaternion number literals
local errorpos = self.tokendata:match("^0()[0-9]") or self.tokendata:find("%.$")
if self:NextPattern("^[eE][+-]?[0-9][0-9]*") then
errorpos = errorpos or self.tokendata:match("[eE][+-]?()0[0-9]")
end
self:NextPattern("^[ijk]")
if self:NextPattern("^[a-zA-Z_]") then
errorpos = errorpos or self.tokendata:len()
end
if errorpos then
self:Error("Invalid number format (" .. E2Lib.limitString(self.tokendata, 10) .. ")", errorpos-1)
end
tokenname = "num"
elseif self:NextPattern("^[a-z][a-zA-Z0-9_]*") then
-- keywords/functions
if self.tokendata == "if" then
tokenname = "if"
elseif self.tokendata == "elseif" then
tokenname = "eif"
elseif self.tokendata == "else" then
tokenname = "els"
elseif self.tokendata == "while" then
tokenname = "whl"
elseif self.tokendata == "for" then
tokenname = "for"
elseif self.tokendata == "break" then
tokenname = "brk"
elseif self.tokendata == "continue" then
tokenname = "cnt"
elseif self.tokendata == "foreach" then
tokenname = "fea"
elseif self.tokendata:match("^[ijk]$") and self.character ~= "(" then
tokenname, self.tokendata = "num", "1"..self.tokendata
else
tokenname = "fun"
end
elseif self:NextPattern("^[A-Z][a-zA-Z0-9_]*") then
-- variables
tokenname = "var"
elseif self.character == "_" then
-- constants
self:NextCharacter()
self:NextPattern("^[A-Z0-9_]*")
local value = wire_expression2_constants[self.tokendata]
local tp = type(value)
if tp == "number" then
tokenname = "num"
self.tokendata = value
elseif tp == "string" then
tokenname = "str"
self.tokendata = value
elseif tp == "nil" then
self:Error("Unknown constant found ("..self.tokendata..")")
else
self:Error("Constant ("..self.tokendata..") has invalid data type ("..tp..")")
end
elseif self.character == "\"" then
-- strings
-- skip opening quotation mark
self:SkipCharacter()
-- loop until the closing quotation mark
while self.character != "\"" do
-- check for line/file endings
if self.character == "\n" or !self.character then
self:Error("Unterminated string (\"" .. E2Lib.limitString(self.tokendata, 10) .. ")")
end
if self.character == "\\" then
self:SkipCharacter()
if self.character == "n" then
self.character = "\n"
elseif self.character == "t" then
self.character = "\t"
end
end
self:NextCharacter()
end
-- skip closing quotation mark
self:SkipCharacter()
tokenname = "str"
else
-- nothing
return
end
return tokenname, self.tokendata
end
function Tokenizer:NextOperator()
local op = E2Lib.optable[self.character]
if not op then return end
while true do
self:NextCharacter()
-- Check for the end of the string.
if not self.character then return op[1] end
-- Check whether we are at a leaf and can't descend any further.
if not op[2] then return op[1] end
-- Check whether we are at a node with no matching branches.
if not op[2][self.character] then return op[1] end
-- branch
op = op[2][self.character]
end
end
|
/******************************************************************************\
Expression 2 Tokenizer for Garry's Mod
Andreas "Syranide" Svensson, me@syranide.com
\******************************************************************************/
AddCSLuaFile("tokenizer.lua")
Tokenizer = {}
Tokenizer.__index = Tokenizer
function Tokenizer.Execute(...)
-- instantiate Tokenizer
local instance = setmetatable({}, Tokenizer)
-- and pcall the new instance's Process method.
return pcall(Tokenizer.Process, instance, ...)
end
function Tokenizer:Error(message, offset)
error(message .. " at line " .. self.tokenline .. ", char " .. (self.tokenchar+(offset or 0)), 0)
end
function Tokenizer:Process(buffer, params)
self.buffer = buffer
self.length = buffer:len()
self.position = 0
self:SkipCharacter()
local tokens = {}
local tokenname, tokendata, tokenspace
self.tokendata = ""
while self.character do
tokenspace = self:NextPattern("%s+") and true or false
if !self.character then break end
self.tokenline = self.readline
self.tokenchar = self.readchar
self.tokendata = ""
tokenname, tokendata = self:NextSymbol()
if tokenname == nil then
tokenname, tokendata = self:NextOperator()
if tokenname == nil then
self:Error("Unknown character found (" .. self.character .. ")")
end
end
tokens[#tokens + 1] = { tokenname, tokendata, tokenspace, self.tokenline, self.tokenchar }
end
return tokens
end
/******************************************************************************/
function Tokenizer:SkipCharacter()
if self.position < self.length then
if self.position > 0 then
if self.character == "\n" then
self.readline = self.readline + 1
self.readchar = 1
else
self.readchar = self.readchar + 1
end
else
self.readline = 1
self.readchar = 1
end
self.position = self.position + 1
self.character = self.buffer:sub(self.position, self.position)
else
self.character = nil
end
end
function Tokenizer:NextCharacter()
self.tokendata = self.tokendata .. self.character
self:SkipCharacter()
end
-- Returns true on success, nothing if it fails.
function Tokenizer:NextPattern(pattern)
if not self.character then return false end
local startpos,endpos,text = self.buffer:find(pattern, self.position)
if startpos ~= self.position then return false end
local buf = self.buffer:sub(startpos, endpos)
if not text then text = buf end
self.tokendata = self.tokendata .. text
self.position = endpos + 1
if self.position <= self.length then
self.character = self.buffer:sub(self.position, self.position)
else
self.character = nil
end
buf = string.Explode("\n", buf)
if #buf > 1 then
self.readline = self.readline+#buf-1
self.readchar = #buf[#buf]+1
else
self.readchar = self.readchar + #buf[#buf]
end
return true
end
function Tokenizer:NextSymbol()
local tokenname
if self:NextPattern("^[0-9]+%.?[0-9]*") then
-- real/imaginary/quaternion number literals
local errorpos = self.tokendata:match("^0()[0-9]") or self.tokendata:find("%.$")
if self:NextPattern("^[eE][+-]?[0-9][0-9]*") then
errorpos = errorpos or self.tokendata:match("[eE][+-]?()0[0-9]")
end
self:NextPattern("^[ijk]")
if self:NextPattern("^[a-zA-Z_]") then
errorpos = errorpos or self.tokendata:len()
end
if errorpos then
self:Error("Invalid number format (" .. E2Lib.limitString(self.tokendata, 10) .. ")", errorpos-1)
end
tokenname = "num"
elseif self:NextPattern("^[a-z][a-zA-Z0-9_]*") then
-- keywords/functions
if self.tokendata == "if" then
tokenname = "if"
elseif self.tokendata == "elseif" then
tokenname = "eif"
elseif self.tokendata == "else" then
tokenname = "els"
elseif self.tokendata == "while" then
tokenname = "whl"
elseif self.tokendata == "for" then
tokenname = "for"
elseif self.tokendata == "break" then
tokenname = "brk"
elseif self.tokendata == "continue" then
tokenname = "cnt"
elseif self.tokendata == "foreach" then
tokenname = "fea"
elseif self.tokendata:match("^[ijk]$") and self.character ~= "(" then
tokenname, self.tokendata = "num", "1"..self.tokendata
else
tokenname = "fun"
end
elseif self:NextPattern("^[A-Z][a-zA-Z0-9_]*") then
-- variables
tokenname = "var"
elseif self.character == "_" then
-- constants
self:NextCharacter()
self:NextPattern("^[A-Z0-9_]*")
local value = wire_expression2_constants[self.tokendata]
local tp = type(value)
if tp == "number" then
tokenname = "num"
self.tokendata = value
elseif tp == "string" then
tokenname = "str"
self.tokendata = value
elseif tp == "nil" then
self:Error("Unknown constant found ("..self.tokendata..")")
else
self:Error("Constant ("..self.tokendata..") has invalid data type ("..tp..")")
end
elseif self.character == "\"" then
-- strings
-- skip opening quotation mark
self:SkipCharacter()
-- loop until the closing quotation mark
while self.character != "\"" do
-- check for line/file endings
if self.character == "\n" or !self.character then
self:Error("Unterminated string (\"" .. E2Lib.limitString(self.tokendata, 10) .. ")")
end
if self.character == "\\" then
self:SkipCharacter()
if self.character == "n" then
self.tokendata = self.tokendata .. "\n"
self:SkipCharacter()
elseif self.character == "t" then
self.tokendata = self.tokendata .. "\t"
self:SkipCharacter()
else
self:NextCharacter()
end
else
self:NextCharacter()
end
end
-- skip closing quotation mark
self:SkipCharacter()
tokenname = "str"
else
-- nothing
return
end
return tokenname, self.tokendata
end
function Tokenizer:NextOperator()
local op = E2Lib.optable[self.character]
if not op then return end
while true do
self:NextCharacter()
-- Check for the end of the string.
if not self.character then return op[1] end
-- Check whether we are at a leaf and can't descend any further.
if not op[2] then return op[1] end
-- Check whether we are at a node with no matching branches.
if not op[2][self.character] then return op[1] end
-- branch
op = op[2][self.character]
end
end
|
E2: fixed \n in strings adding to the line counter
|
E2: fixed \n in strings adding to the line counter
|
Lua
|
apache-2.0
|
NezzKryptic/Wire,Grocel/wire,CaptainPRICE/wire,immibis/wiremod,rafradek/wire,bigdogmat/wire,Python1320/wire,garrysmodlua/wire,plinkopenguin/wiremod,mitterdoo/wire,notcake/wire,wiremod/wire,dvdvideo1234/wire,mms92/wire,sammyt291/wire,thegrb93/wire
|
e6328e4972aa893d84d8bf6ab09cf0c31f968d8c
|
lua/entities/gmod_wire_expression2/core/selfaware.lua
|
lua/entities/gmod_wire_expression2/core/selfaware.lua
|
/******************************************************************************\
Selfaware support
\******************************************************************************/
__e2setcost(1) -- temporary
e2function entity entity()
return self.entity
end
e2function entity owner()
return self.player
end
__e2setcost(nil) -- temporary
e2function void selfDestruct()
self.entity:Remove()
end
e2function void selfDestructAll()
for k,v in pairs(constraint.GetAllConstrainedEntities(self.entity)) do
if(getOwner(self,v)==self.player) then
v:Remove()
end
end
//constraint.RemoveAll(self.entity)
self.entity:Remove()
end
/******************************************************************************/
-- i/o functions
__e2setcost(10)
-- Returns an array of all entities wired to the output
e2function array ioOutputEntities( string output )
local ret = {}
if (self.entity.Outputs[output]) then
local tbl = self.entity.Outputs[output].Connected
for i=1,#tbl do if (IsValid(tbl[i].Entity)) then ret[#ret+1] = tbl[i].Entity end end
self.prf = self.prf + #ret
end
return ret
end
-- Returns the entity the input is wired to
e2function entity ioInputEntity( string input )
if (self.entity.Inputs[input] and self.entity.Inputs[input].Src and IsValid(self.entity.Inputs[input].Src)) then return self.entity.Inputs[input].Src end
end
local function setOutput( self, args, Type )
local op1, op2 = args[2], args[3]
local rv1, rv2 = op1[1](self,op1), op2[1](self,op2)
if (self.entity.Outputs[rv1] and self.entity.Outputs[rv1].Type == Type) then
self.GlobalScope[rv1] = rv2
self.GlobalScope.vclk[rv1] = true
end
end
local fixDefault = E2Lib.fixDefault
local function getInput( self, args, default, Type )
local op1 = args[2]
local rv1 = op1[1](self,op1)
default = fixDefault(default)
if (self.entity.Inputs[rv1] and self.entity.Inputs[rv1].Type == Type) then
return self.GlobalScope[rv1] or default
end
return default
end
local excluded_types = {
xgt = true,
}
local function upperfirst( word )
return word:Left(1):upper() .. word:Right(-2):lower()
end
__e2setcost(5)
registerCallback("postinit",function()
for k,v in pairs( wire_expression_types ) do
local short = v[1]
if (!excluded_types[short]) then
registerFunction("ioSetOutput","s"..short,""..short,function(self,args) return setOutput(self,args,k) end)
registerFunction("ioGetInput"..upperfirst(k == "NORMAL" and "NUMBER" or k),"s",short,function(self,args) return getInput(self,args,v[2],k) end)
end
end
end)
/******************************************************************************/
-- Name functions
local function doSetName(self,this,name)
if self.data.setNameNext and self.data.setNameNext > CurTime() then return end
self.data.setNameNext = CurTime() + 1
if #name > 12000 then
name = string.sub( name, 1, 12000 )
end
if this:GetClass() == "gmod_wire_expression2" then
if this.name == name then return end
if name == "generic" or name == "" then
name = "generic"
this.WireDebugName = "Expression 2"
else
this.WireDebugName = "E2 - " .. name
end
this.name = name
this:SetNWString( "name", this.name )
this:SetOverlayText(name)
else
if this.wireName == name or string.find(name, "[\n\r\"]") ~= nil then return end
this.wireName = name
this:SetNWString("WireName", name)
duplicator.StoreEntityModifier(this, "WireName", { name = name })
end
end
-- Set the name of the E2 itself
e2function void setName( string name )
doSetName(self,self.entity,name)
end
-- Set the name of an entity (component name if not E2)
e2function void entity:setName( string name )
if not IsValid(this) then return self:throw("Invalid entity!", nil) end
if E2Lib.getOwner(self, this) ~= self.player then return self:throw("You do not own this entity!", nil) end
doSetName(self,this,name)
end
-- Get the name of another E2 or compatible entity or component name of wiremod components
e2function string entity:getName()
if not IsValid(this) then return self:throw("Invalid entity!", "") end
if this.GetGateName then
return this:GetGateName() or ""
end
return this:GetNWString("WireName", this.PrintName) or ""
end
/******************************************************************************/
registerCallback("construct", function(self)
self.data.changed = {}
end)
__e2setcost(1)
-- This is the prototype for everything that can be compared using the == operator
e2function number changed(value)
local chg = self.data.changed
if value == chg[args] then return 0 end
chg[args] = value
return 1
end
-- vectors can be of gmod type Vector, so we need to treat them separately
e2function number changed(vector value)
local chg = self.data.changed
local this_chg = chg[args]
if not this_chg then
chg[args] = value
return 1
end
if this_chg
and value[1] == this_chg[1]
and value[2] == this_chg[2]
and value[3] == this_chg[3]
then return 0 end
chg[args] = value
return 1
end
-- This is the prototype for all table types.
e2function number changed(angle value)
local chg = self.data.changed
local this_chg = chg[args]
if not this_chg then
chg[args] = value
return 1
end
for i,v in pairs(value) do
if v ~= this_chg[i] then
chg[args] = value
return 1
end
end
return 0
end
local excluded_types = {
n = true,
v = true,
a = true,
[""] = true,
r = true,
t = true,
}
local comparable_types = {
s = true,
e = true,
xwl = true,
b = true,
}
registerCallback("postinit", function()
-- generate this function for all types
for typeid,_ in pairs(wire_expression_types2) do
if not excluded_types[typeid] then
if comparable_types[typeid] then
registerFunction("changed", typeid, "n", registeredfunctions.e2_changed_n)
else
registerFunction("changed", typeid, "n", registeredfunctions.e2_changed_a)
end
end
end
end)
/******************************************************************************/
__e2setcost( 5 )
local getHash = E2Lib.getHash
e2function number hash()
return getHash( self, self.entity.original )
end
e2function number hashNoComments()
return getHash( self, self.entity.buffer )
end
e2function number hash( string str )
return getHash( self, str )
end
|
/******************************************************************************\
Selfaware support
\******************************************************************************/
__e2setcost(1) -- temporary
e2function entity entity()
return self.entity
end
e2function entity owner()
return self.player
end
__e2setcost(nil) -- temporary
e2function void selfDestruct()
self.entity:Remove()
end
e2function void selfDestructAll()
for k,v in pairs(constraint.GetAllConstrainedEntities(self.entity)) do
if(getOwner(self,v)==self.player) then
v:Remove()
end
end
//constraint.RemoveAll(self.entity)
self.entity:Remove()
end
/******************************************************************************/
-- i/o functions
__e2setcost(10)
-- Returns an array of all entities wired to the output
e2function array ioOutputEntities( string output )
local ret = {}
if (self.entity.Outputs[output]) then
local tbl = self.entity.Outputs[output].Connected
for i=1,#tbl do if (IsValid(tbl[i].Entity)) then ret[#ret+1] = tbl[i].Entity end end
self.prf = self.prf + #ret
end
return ret
end
-- Returns the entity the input is wired to
e2function entity ioInputEntity( string input )
if (self.entity.Inputs[input] and self.entity.Inputs[input].Src and IsValid(self.entity.Inputs[input].Src)) then return self.entity.Inputs[input].Src end
end
local function setOutput( self, args, Type )
local op1, op2 = args[2], args[3]
local rv1, rv2 = op1[1](self,op1), op2[1](self,op2)
if (self.entity.Outputs[rv1] and self.entity.Outputs[rv1].Type == Type) then
self.GlobalScope[rv1] = rv2
self.GlobalScope.vclk[rv1] = true
end
end
local fixDefault = E2Lib.fixDefault
local function getInput( self, args, default, Type )
local op1 = args[2]
local rv1 = op1[1](self,op1)
default = fixDefault(default)
if (self.entity.Inputs[rv1] and self.entity.Inputs[rv1].Type == Type) then
return self.GlobalScope[rv1] or default
end
return default
end
local excluded_types = {
xgt = true,
}
local function upperfirst( word )
return word:Left(1):upper() .. word:Right(-2):lower()
end
__e2setcost(5)
registerCallback("postinit",function()
for k,v in pairs( wire_expression_types ) do
local short = v[1]
if (!excluded_types[short]) then
registerFunction("ioSetOutput","s"..short,""..short,function(self,args) return setOutput(self,args,k) end)
registerFunction("ioGetInput"..upperfirst(k == "NORMAL" and "NUMBER" or k),"s",short,function(self,args) return getInput(self,args,v[2],k) end)
end
end
end)
/******************************************************************************/
-- Name functions
local function doSetName(self,this,name)
if self.data.setNameNext and self.data.setNameNext > CurTime() then return end
self.data.setNameNext = CurTime() + 1
if #name > 12000 then
name = string.sub( name, 1, 12000 )
end
if this:GetClass() == "gmod_wire_expression2" then
if this.name == name then return end
if name == "generic" or name == "" then
name = "generic"
this.WireDebugName = "Expression 2"
else
this.WireDebugName = "E2 - " .. name
end
this.name = name
this:SetNWString( "name", this.name )
this:SetOverlayText(name)
else
if this.wireName == name or string.find(name, "[\n\r\"]") ~= nil then return end
this.wireName = name
this:SetNWString("WireName", name)
duplicator.StoreEntityModifier(this, "WireName", { name = name })
end
end
-- Set the name of the E2 itself
e2function void setName( string name )
doSetName(self,self.entity,name)
end
-- Set the name of an entity (component name if not E2)
e2function void entity:setName( string name )
if not IsValid(this) then return self:throw("Invalid entity!", nil) end
if E2Lib.getOwner(self, this) ~= self.player then return self:throw("You do not own this entity!", nil) end
doSetName(self,this,name)
end
-- Get the name of another E2 or compatible entity or component name of wiremod components
e2function string entity:getName()
if not IsValid(this) then return self:throw("Invalid entity!", "") end
if this.GetGateName then
return this:GetGateName() or ""
end
return this:GetNWString("WireName", this.PrintName) or ""
end
/******************************************************************************/
registerCallback("construct", function(self)
self.data.changed = {}
end)
__e2setcost(1)
-- This is the prototype for everything that can be compared using the == operator
e2function number changed(value)
local chg = self.data.changed
if value == chg[args] then return 0 end
chg[args] = value
return 1
end
e2function number changed(vector value)
local chg = self.data.changed
local this_chg = chg[args]
if not this_chg then
chg[args] = value
return 1
end
if this_chg
and value[1] == this_chg[1]
and value[2] == this_chg[2]
and value[3] == this_chg[3]
then return 0 end
chg[args] = value
return 1
end
-- This is the prototype for all table types.
e2function number changed(vector4 value)
local chg = self.data.changed
local this_chg = chg[args]
if not this_chg then
chg[args] = value
return 1
end
for i,v in pairs(value) do
if v ~= this_chg[i] then
chg[args] = value
return 1
end
end
return 0
end
local excluded_types = {
n = true,
v = true,
a = true,
xv4 = true,
[""] = true,
r = true,
t = true,
}
local comparable_types = {
s = true,
e = true,
xwl = true,
b = true,
}
registerCallback("postinit", function()
-- Angle is the same as vector
registerFunction("changed", "a", "n", registeredfunctions.e2_changed_v)
-- generate this function for all types
for typeid,_ in pairs(wire_expression_types2) do
if not excluded_types[typeid] then
if comparable_types[typeid] then
registerFunction("changed", typeid, "n", registeredfunctions.e2_changed_n)
else
registerFunction("changed", typeid, "n", registeredfunctions.e2_changed_xv4)
end
end
end
end)
/******************************************************************************/
__e2setcost( 5 )
local getHash = E2Lib.getHash
e2function number hash()
return getHash( self, self.entity.original )
end
e2function number hashNoComments()
return getHash( self, self.entity.buffer )
end
e2function number hash( string str )
return getHash( self, str )
end
|
Fix 'changed' on angle type (#2427)
|
Fix 'changed' on angle type (#2427)
* Fix 'changed' on angle type
* Update selfaware.lua
|
Lua
|
apache-2.0
|
Grocel/wire,wiremod/wire
|
067131832e3a36decda764a97eaa0fa5b0783f5c
|
lib/switchboard_modules/lua_script_debugger/premade_scripts/advanced_scripts/14_zerocrossing_pulse_response.lua
|
lib/switchboard_modules/lua_script_debugger/premade_scripts/advanced_scripts/14_zerocrossing_pulse_response.lua
|
--This example will output a pulse on FIO1 (FIO4 for T4) a specified amount of time after a
-- rising edge is detected on FIO0 (FIO5 on T4). The delay between detection of a crossing
-- and the beginning of the pulse is controlled by the F32 value in USER_RAM at
-- modbus address 46000-46001.
print("Begin")
local state = "pulseUpdate"
local inPin = 2000--FIO0
local outPin = 2001--FIO1. Changed if T4 instead of T7
devType = MB.R(60000, 3)
if devType == 4 then
inPin = 2004--FIO4
outPin = 2005--FIO5
end
local mbRead=MB.R --Create local functions for faster processing
local mbWrite=MB.W
local checkInterval=LJ.ChekInterval
local configInterval=LJ.IntervalConfig
dio_LS = mbRead(2000, 0) --Read FIO0
configInterval(1, 500)
while true do
dio_S = mbRead(2000, 0) --Read FIO0
if state == "waitingForZero" then
if dio_LS == 0 and dio_S == 1 then --Rising edge detected?
configInterval(0, pulseDelay) --Start delay before starting pulse
state = "pulseStart"
end
elseif state == "pulseStart" then
if checkInterval(0) then
mbWrite(2001, 0, 1) --Start pulse on FIO1
configInterval(0, 1) --Set delay for the pulse width
state = "pulseEnd"
end
elseif state == "pulseEnd" then
if checkInterval(0) then
mbWrite(2001, 0, 0) --End pulse on FIO1
state = "pulseUpdate"
end
elseif state == "pulseUpdate" then --Read new pulse low time from user RAM
pulseDelay = mbRead(46000, 3) --Read 2 registers, interpret as a float.
state = "waitingForZero"
--Enforce constraints on pulse low time. (This is the amount of time between the
-- zero crossing and the activation pulse.)
--print("new pulse", pulseLen)
end
dio_LS = dio_S
end
|
--[[
Name: 14_zerocrossing_pulse_response.lua
Desc: This example will output a pulse on FIO1 (FIO4 for T4) a specified
amount of time after a rising edge is detected on FIO0 (FIO5 for T4)
Note: The delay between detection of a crossing and the beginning of the
pulse is controlled by the F32 value in USER_RAM at
modbus address 46000-46001
This example requires firmware 1.0282 (T7) or 1.0023 (T4)
--]]
print("Begin")
-- Assume that a T7 is being used, use FIO0 and FIO1 for I/O
local inpin = "FIO0"
local outpin = "FIO1"
local devtype = MB.readName("PRODUCT_ID")
-- If actually using a T4, use FIO4 and FIO5 for I/O
if devtype == 4 then
inpin = "FIO4"
outpin = "FIO5"
end
-- Set a 20ms pulse width
local pulsewidth = 20
-- Set the pulse low time to be 40ms by writing to USER_RAM
MB.writeName("USER_RAM0_F32",40)
local state = "pulseUpdate"
-- Get an initial state of inpin
lastval = MB.readName(inpin)
while true do
-- Get the current state of inpin
inval = MB.readName(inpin)
if state == "pulseUpdate" then
-- Read a new pulse low time from USER_RAM
delay = MB.readName("USER_RAM0_F32")
state = "waitingForZero"
-- Enforce constraints on pulse low time. (This is the amount of time
-- between the zero crossing and the activation pulse)
print("new pulse", pulsewidth)
elseif state == "waitingForZero" then
-- If there was a rising edge
if lastval == 0 and inval == 1 then
-- Start the pulse low time delay
LJ.IntervalConfig(0, delay)
state = "pulseStart"
end
elseif state == "pulseStart" then
-- If the pulse low time delay is finished
if LJ.CheckInterval(0) then
-- Start the outpin pulse
MB.writeName(outpin, 1)
-- Set a delay for the pulse width
LJ.IntervalConfig(0, pulsewidth)
state = "pulseEnd"
end
elseif state == "pulseEnd" then
-- If the pulse width delay is done
if LJ.CheckInterval(0) then
-- End the outpin pulse
MB.writeName(outpin, 0)
state = "pulseUpdate"
end
end
lastval = inval
end
|
Fixed up the formatting of the zerocrossing pulse response example
|
Fixed up the formatting of the zerocrossing pulse response example
|
Lua
|
mit
|
chrisJohn404/ljswitchboard-module_manager,chrisJohn404/ljswitchboard-module_manager,chrisJohn404/ljswitchboard-module_manager
|
4756ec14fa1fb2b8fc51cd53276808d6ca2fdef4
|
item/id_3077_silvercoins.lua
|
item/id_3077_silvercoins.lua
|
require("base.common")
module("item.id_3077_silvercoins", package.seeall)
-- UPDATE common SET com_script='item.id_3077_silvercoins' WHERE com_itemid IN (3077);
TimeList = {};
function UseItem(User, SourceItem)
local frontItem = base.common.GetFrontItem(User)
if not frontItem then
return
end
if frontItem.id == 2805 and frontItem.pos == position(415, 273, -6) then --if frontItem is questpillar
if User:getQuestProgress(170) == 0 then
User:setQuestProgress (170, 1)
User:inform('Die Mnze fllt durch den Schlitz und mit einem metallischen Klicken ffnet sich eine versteckte Klappe in der Sule, aus der ein Schild fllt.', 'The coin falls into the slit and with a metallic click a hidden hatch opens and a shield drops out.')
world:erase(SourceItem,1)
local data = {}
data.descriptionDe="Geweihter Schild Ronagans"
data.descriptionEn="Blessed Shield of Ronagan"
User:createItem(17, 1, 799, data)
else
User:inform('Die Mnze verschwindet im Schlitz, aber nichts passiert.', 'The coin disappears but nothing happens.')
world:erase(SourceItem,1)
end
else --works only if frontItem isn't the questpillar
if ( SourceItem.number == 1 ) then --works only with 1 coin
if TimeList[User.id]~=nil then
if ( (math.abs(world:getTime("second") - TimeList[User.id]) ) <=3) then --1 Rl. second delay
return;
end
end
if math.random(2) == 1 then gValue = "Kopf"; eValue = "head";
else gValue = "Zahl"; eValue = "tail"; end
User:talk(Character.say, "#me wirft eine Mnze in die Luft und fngt sie wieder auf. Sie zeigt "..gValue..".", "#me throws a coin in the air and catches it again. It shows "..eValue..".")
TimeList[User.id] = world:getTime("second");
end
end
end
|
require("base.common")
module("item.id_3077_silvercoins", package.seeall)
-- UPDATE common SET com_script='item.id_3077_silvercoins' WHERE com_itemid IN (3077);
TimeList = {};
function UseItem(User, SourceItem)
local frontItem = base.common.GetFrontItem(User)
if frontItem then
if frontItem.id == 2805 and frontItem.pos == position(415, 273, -6) then --if frontItem is questpillar
if User:getQuestProgress(170) == 0 then
User:setQuestProgress (170, 1)
User:inform('Die Mnze fllt durch den Schlitz und mit einem metallischen Klicken ffnet sich eine versteckte Klappe in der Sule, aus der ein Schild fllt.', 'The coin falls into the slit and with a metallic click a hidden hatch opens and a shield drops out.')
world:erase(SourceItem,1)
local data = {}
data.descriptionDe="Geweihter Schild Ronagans"
data.descriptionEn="Blessed Shield of Ronagan"
User:createItem(17, 1, 799, data)
else
User:inform('Die Mnze verschwindet im Schlitz, aber nichts passiert.', 'The coin disappears but nothing happens.')
world:erase(SourceItem,1)
end
return;
end
end
if TimeList[User.id]~=nil then
if ( (math.abs(world:getTime("second") - TimeList[User.id]) ) <=3) then --1 Rl. second delay
return;
end
end
if math.random(2) == 1 then
gValue = "Kopf"; eValue = "head";
else
gValue = "Zahl"; eValue = "tail";
end
User:talk(Character.say, "#me wirft eine Mnze in die Luft und fngt sie wieder auf. Sie zeigt "..gValue..".", "#me throws a coin in the air and catches it again. It shows "..eValue..".")
TimeList[User.id] = world:getTime("second");
end
end
|
bugfix
|
bugfix
|
Lua
|
agpl-3.0
|
KayMD/Illarion-Content,vilarion/Illarion-Content,Baylamon/Illarion-Content,Illarion-eV/Illarion-Content,LaFamiglia/Illarion-Content
|
78fb71f88177ac7e9234065a8bdbe8310ffa95ad
|
modules/admin-full/luasrc/model/cbi/admin_network/dhcp.lua
|
modules/admin-full/luasrc/model/cbi/admin_network/dhcp.lua
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
require("luci.model.uci")
require("luci.sys")
m = Map("dhcp", "DHCP")
s = m:section(TypedSection, "dhcp", "")
s.addremove = true
s.anonymous = true
iface = s:option(ListValue, "interface", translate("interface"))
luci.model.uci.foreach("network", "interface",
function (section)
if section[".name"] ~= "loopback" then
iface:value(section[".name"])
s:depends("interface", section[".name"])
end
end)
s:option(Value, "start", translate("start")).rmempty = true
s:option(Value, "limit", translate("limit")).rmempty = true
s:option(Value, "leasetime").rmempty = true
s:option(Flag, "dynamicdhcp").rmempty = true
s:option(Value, "name", translate("name")).optional = true
s:option(Flag, "ignore").optional = true
s:option(Value, "netmask", translate("netmask")).optional = true
s:option(Flag, "force").optional = true
for i, line in pairs(luci.sys.execl("dnsmasq --help dhcp")) do
k, v = line:match("([^ ]+) +([^ ]+)")
s:option(Value, "dhcp"..k, v).optional = true
end
m2 = Map("luci_ethers", translate("luci_ethers"))
s = m2:section(TypedSection, "static_lease", "")
s.addremove = true
s.anonymous = true
s.template = "cbi/tblsection"
s:option(Value, "macaddr", translate("macaddress"))
s:option(Value, "ipaddr", translate("ipaddress"))
return m, m2
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
require("luci.model.uci")
require("luci.sys")
m = Map("dhcp", "DHCP")
s = m:section(TypedSection, "dhcp", "")
s.addremove = true
s.anonymous = true
iface = s:option(ListValue, "interface", translate("interface"))
luci.model.uci.foreach("network", "interface",
function (section)
if section[".name"] ~= "loopback" then
iface.default = iface.default or section[".name"]
iface:value(section[".name"])
s:depends("interface", section[".name"])
end
end)
s:option(Value, "start", translate("start")).rmempty = true
s:option(Value, "limit", translate("limit")).rmempty = true
s:option(Value, "leasetime").rmempty = true
s:option(Flag, "dynamicdhcp").rmempty = true
s:option(Value, "name", translate("name")).optional = true
s:option(Flag, "ignore").optional = true
s:option(Value, "netmask", translate("netmask")).optional = true
s:option(Flag, "force").optional = true
for i, line in pairs(luci.sys.execl("dnsmasq --help dhcp")) do
k, v = line:match("([^ ]+) +([^ ]+)")
s:option(Value, "dhcp"..k, v).optional = true
end
m2 = Map("luci_ethers", translate("luci_ethers"))
s = m2:section(TypedSection, "static_lease", "")
s.addremove = true
s.anonymous = true
s.template = "cbi/tblsection"
s:option(Value, "macaddr", translate("macaddress"))
s:option(Value, "ipaddr", translate("ipaddress"))
return m, m2
|
* luci/admin-full: fixed bug that prevented creation of interface sections in dhcp page
|
* luci/admin-full: fixed bug that prevented creation of interface sections in dhcp page
|
Lua
|
apache-2.0
|
mumuqz/luci,RedSnake64/openwrt-luci-packages,aircross/OpenWrt-Firefly-LuCI,aa65535/luci,palmettos/cnLuCI,aa65535/luci,openwrt-es/openwrt-luci,obsy/luci,kuoruan/luci,kuoruan/lede-luci,Kyklas/luci-proto-hso,opentechinstitute/luci,florian-shellfire/luci,taiha/luci,jlopenwrtluci/luci,Hostle/openwrt-luci-multi-user,jlopenwrtluci/luci,jlopenwrtluci/luci,zhaoxx063/luci,ff94315/luci-1,palmettos/cnLuCI,RuiChen1113/luci,chris5560/openwrt-luci,slayerrensky/luci,lcf258/openwrtcn,rogerpueyo/luci,palmettos/cnLuCI,kuoruan/luci,dismantl/luci-0.12,bittorf/luci,lcf258/openwrtcn,aa65535/luci,harveyhu2012/luci,openwrt/luci,wongsyrone/luci-1,openwrt/luci,openwrt-es/openwrt-luci,palmettos/test,db260179/openwrt-bpi-r1-luci,RedSnake64/openwrt-luci-packages,daofeng2015/luci,teslamint/luci,maxrio/luci981213,taiha/luci,obsy/luci,marcel-sch/luci,mumuqz/luci,Sakura-Winkey/LuCI,lcf258/openwrtcn,dwmw2/luci,bright-things/ionic-luci,LuttyYang/luci,tcatm/luci,urueedi/luci,Wedmer/luci,RuiChen1113/luci,urueedi/luci,maxrio/luci981213,marcel-sch/luci,lbthomsen/openwrt-luci,obsy/luci,thesabbir/luci,chris5560/openwrt-luci,aa65535/luci,RuiChen1113/luci,marcel-sch/luci,ReclaimYourPrivacy/cloak-luci,teslamint/luci,Noltari/luci,dwmw2/luci,taiha/luci,Noltari/luci,LazyZhu/openwrt-luci-trunk-mod,fkooman/luci,jorgifumi/luci,thesabbir/luci,keyidadi/luci,Hostle/openwrt-luci-multi-user,mumuqz/luci,oneru/luci,shangjiyu/luci-with-extra,florian-shellfire/luci,taiha/luci,dismantl/luci-0.12,artynet/luci,LazyZhu/openwrt-luci-trunk-mod,Hostle/openwrt-luci-multi-user,hnyman/luci,david-xiao/luci,cshore-firmware/openwrt-luci,aa65535/luci,joaofvieira/luci,forward619/luci,harveyhu2012/luci,dismantl/luci-0.12,LuttyYang/luci,RedSnake64/openwrt-luci-packages,schidler/ionic-luci,tobiaswaldvogel/luci,daofeng2015/luci,slayerrensky/luci,daofeng2015/luci,florian-shellfire/luci,lbthomsen/openwrt-luci,thess/OpenWrt-luci,daofeng2015/luci,thess/OpenWrt-luci,obsy/luci,mumuqz/luci,rogerpueyo/luci,thess/OpenWrt-luci,cshore-firmware/openwrt-luci,ff94315/luci-1,tcatm/luci,forward619/luci,bright-things/ionic-luci,chris5560/openwrt-luci,cappiewu/luci,slayerrensky/luci,mumuqz/luci,dwmw2/luci,lcf258/openwrtcn,thesabbir/luci,Kyklas/luci-proto-hso,db260179/openwrt-bpi-r1-luci,hnyman/luci,cshore-firmware/openwrt-luci,ollie27/openwrt_luci,jorgifumi/luci,mumuqz/luci,deepak78/new-luci,schidler/ionic-luci,daofeng2015/luci,oyido/luci,cshore/luci,lbthomsen/openwrt-luci,opentechinstitute/luci,deepak78/new-luci,nmav/luci,db260179/openwrt-bpi-r1-luci,oneru/luci,db260179/openwrt-bpi-r1-luci,fkooman/luci,981213/luci-1,david-xiao/luci,bright-things/ionic-luci,male-puppies/luci,Hostle/luci,forward619/luci,tobiaswaldvogel/luci,NeoRaider/luci,shangjiyu/luci-with-extra,jchuang1977/luci-1,artynet/luci,Noltari/luci,fkooman/luci,MinFu/luci,florian-shellfire/luci,wongsyrone/luci-1,ollie27/openwrt_luci,NeoRaider/luci,openwrt-es/openwrt-luci,fkooman/luci,Noltari/luci,cshore/luci,chris5560/openwrt-luci,rogerpueyo/luci,dwmw2/luci,aa65535/luci,schidler/ionic-luci,dwmw2/luci,ff94315/luci-1,jorgifumi/luci,dwmw2/luci,hnyman/luci,db260179/openwrt-bpi-r1-luci,NeoRaider/luci,tobiaswaldvogel/luci,aircross/OpenWrt-Firefly-LuCI,tcatm/luci,cappiewu/luci,opentechinstitute/luci,RedSnake64/openwrt-luci-packages,nmav/luci,oneru/luci,tcatm/luci,forward619/luci,aircross/OpenWrt-Firefly-LuCI,joaofvieira/luci,Noltari/luci,forward619/luci,MinFu/luci,chris5560/openwrt-luci,nwf/openwrt-luci,981213/luci-1,marcel-sch/luci,hnyman/luci,cshore-firmware/openwrt-luci,Hostle/openwrt-luci-multi-user,harveyhu2012/luci,bittorf/luci,thesabbir/luci,harveyhu2012/luci,david-xiao/luci,obsy/luci,Hostle/luci,bittorf/luci,lbthomsen/openwrt-luci,bright-things/ionic-luci,hnyman/luci,openwrt-es/openwrt-luci,sujeet14108/luci,MinFu/luci,Sakura-Winkey/LuCI,teslamint/luci,remakeelectric/luci,deepak78/new-luci,male-puppies/luci,schidler/ionic-luci,cshore-firmware/openwrt-luci,tcatm/luci,joaofvieira/luci,daofeng2015/luci,LuttyYang/luci,remakeelectric/luci,florian-shellfire/luci,MinFu/luci,RuiChen1113/luci,urueedi/luci,deepak78/new-luci,nwf/openwrt-luci,oyido/luci,RedSnake64/openwrt-luci-packages,rogerpueyo/luci,aircross/OpenWrt-Firefly-LuCI,wongsyrone/luci-1,maxrio/luci981213,LuttyYang/luci,Noltari/luci,981213/luci-1,fkooman/luci,Hostle/openwrt-luci-multi-user,sujeet14108/luci,thess/OpenWrt-luci,keyidadi/luci,kuoruan/luci,urueedi/luci,male-puppies/luci,Hostle/luci,bright-things/ionic-luci,lbthomsen/openwrt-luci,981213/luci-1,male-puppies/luci,rogerpueyo/luci,nmav/luci,sujeet14108/luci,dismantl/luci-0.12,hnyman/luci,MinFu/luci,shangjiyu/luci-with-extra,male-puppies/luci,hnyman/luci,wongsyrone/luci-1,chris5560/openwrt-luci,kuoruan/lede-luci,lcf258/openwrtcn,lcf258/openwrtcn,david-xiao/luci,marcel-sch/luci,taiha/luci,palmettos/cnLuCI,NeoRaider/luci,nwf/openwrt-luci,remakeelectric/luci,RuiChen1113/luci,forward619/luci,thess/OpenWrt-luci,LuttyYang/luci,maxrio/luci981213,cshore/luci,kuoruan/lede-luci,nwf/openwrt-luci,cshore/luci,bright-things/ionic-luci,urueedi/luci,nmav/luci,cappiewu/luci,LuttyYang/luci,thess/OpenWrt-luci,schidler/ionic-luci,oyido/luci,deepak78/new-luci,zhaoxx063/luci,opentechinstitute/luci,db260179/openwrt-bpi-r1-luci,teslamint/luci,jchuang1977/luci-1,oneru/luci,lcf258/openwrtcn,tobiaswaldvogel/luci,shangjiyu/luci-with-extra,openwrt/luci,Wedmer/luci,Hostle/luci,sujeet14108/luci,slayerrensky/luci,obsy/luci,tcatm/luci,nwf/openwrt-luci,joaofvieira/luci,kuoruan/lede-luci,Sakura-Winkey/LuCI,joaofvieira/luci,jchuang1977/luci-1,Hostle/luci,oneru/luci,db260179/openwrt-bpi-r1-luci,bittorf/luci,MinFu/luci,keyidadi/luci,thesabbir/luci,rogerpueyo/luci,zhaoxx063/luci,981213/luci-1,david-xiao/luci,oneru/luci,jchuang1977/luci-1,remakeelectric/luci,oneru/luci,LuttyYang/luci,forward619/luci,RuiChen1113/luci,lbthomsen/openwrt-luci,thess/OpenWrt-luci,palmettos/test,harveyhu2012/luci,sujeet14108/luci,Wedmer/luci,cappiewu/luci,opentechinstitute/luci,oyido/luci,cappiewu/luci,cappiewu/luci,teslamint/luci,ollie27/openwrt_luci,zhaoxx063/luci,bittorf/luci,Wedmer/luci,nmav/luci,zhaoxx063/luci,fkooman/luci,slayerrensky/luci,schidler/ionic-luci,shangjiyu/luci-with-extra,rogerpueyo/luci,dismantl/luci-0.12,ReclaimYourPrivacy/cloak-luci,openwrt-es/openwrt-luci,wongsyrone/luci-1,palmettos/test,cshore/luci,Noltari/luci,jchuang1977/luci-1,tcatm/luci,david-xiao/luci,NeoRaider/luci,sujeet14108/luci,oyido/luci,deepak78/new-luci,palmettos/test,teslamint/luci,schidler/ionic-luci,slayerrensky/luci,artynet/luci,palmettos/cnLuCI,obsy/luci,hnyman/luci,Kyklas/luci-proto-hso,RuiChen1113/luci,fkooman/luci,kuoruan/luci,ollie27/openwrt_luci,RedSnake64/openwrt-luci-packages,slayerrensky/luci,Hostle/openwrt-luci-multi-user,aa65535/luci,shangjiyu/luci-with-extra,cshore/luci,kuoruan/luci,palmettos/test,thesabbir/luci,Hostle/luci,fkooman/luci,NeoRaider/luci,lbthomsen/openwrt-luci,florian-shellfire/luci,openwrt/luci,openwrt-es/openwrt-luci,openwrt-es/openwrt-luci,wongsyrone/luci-1,maxrio/luci981213,keyidadi/luci,ff94315/luci-1,LazyZhu/openwrt-luci-trunk-mod,aircross/OpenWrt-Firefly-LuCI,zhaoxx063/luci,RedSnake64/openwrt-luci-packages,sujeet14108/luci,jlopenwrtluci/luci,jlopenwrtluci/luci,kuoruan/lede-luci,keyidadi/luci,chris5560/openwrt-luci,aircross/OpenWrt-Firefly-LuCI,ff94315/luci-1,jlopenwrtluci/luci,ff94315/luci-1,tcatm/luci,ReclaimYourPrivacy/cloak-luci,cshore-firmware/openwrt-luci,Sakura-Winkey/LuCI,keyidadi/luci,thesabbir/luci,bright-things/ionic-luci,Sakura-Winkey/LuCI,deepak78/new-luci,remakeelectric/luci,bittorf/luci,tobiaswaldvogel/luci,ff94315/luci-1,kuoruan/luci,chris5560/openwrt-luci,shangjiyu/luci-with-extra,zhaoxx063/luci,urueedi/luci,nmav/luci,ReclaimYourPrivacy/cloak-luci,deepak78/new-luci,artynet/luci,wongsyrone/luci-1,male-puppies/luci,MinFu/luci,opentechinstitute/luci,harveyhu2012/luci,jchuang1977/luci-1,lcf258/openwrtcn,openwrt/luci,thesabbir/luci,Sakura-Winkey/LuCI,teslamint/luci,dwmw2/luci,maxrio/luci981213,wongsyrone/luci-1,taiha/luci,taiha/luci,thess/OpenWrt-luci,ollie27/openwrt_luci,florian-shellfire/luci,ReclaimYourPrivacy/cloak-luci,bittorf/luci,daofeng2015/luci,LuttyYang/luci,artynet/luci,tobiaswaldvogel/luci,db260179/openwrt-bpi-r1-luci,harveyhu2012/luci,jorgifumi/luci,male-puppies/luci,Wedmer/luci,Noltari/luci,Sakura-Winkey/LuCI,schidler/ionic-luci,openwrt-es/openwrt-luci,nmav/luci,jorgifumi/luci,jorgifumi/luci,male-puppies/luci,joaofvieira/luci,Wedmer/luci,keyidadi/luci,oyido/luci,lcf258/openwrtcn,Hostle/luci,cshore/luci,artynet/luci,kuoruan/lede-luci,remakeelectric/luci,forward619/luci,Kyklas/luci-proto-hso,opentechinstitute/luci,kuoruan/luci,urueedi/luci,joaofvieira/luci,mumuqz/luci,aircross/OpenWrt-Firefly-LuCI,Kyklas/luci-proto-hso,jorgifumi/luci,obsy/luci,joaofvieira/luci,cshore-firmware/openwrt-luci,jlopenwrtluci/luci,teslamint/luci,MinFu/luci,ReclaimYourPrivacy/cloak-luci,ollie27/openwrt_luci,Hostle/luci,Hostle/openwrt-luci-multi-user,oyido/luci,palmettos/test,urueedi/luci,LazyZhu/openwrt-luci-trunk-mod,maxrio/luci981213,LazyZhu/openwrt-luci-trunk-mod,jchuang1977/luci-1,remakeelectric/luci,ollie27/openwrt_luci,LazyZhu/openwrt-luci-trunk-mod,artynet/luci,mumuqz/luci,artynet/luci,jchuang1977/luci-1,dismantl/luci-0.12,ReclaimYourPrivacy/cloak-luci,dwmw2/luci,nwf/openwrt-luci,cshore/luci,LazyZhu/openwrt-luci-trunk-mod,openwrt/luci,lcf258/openwrtcn,openwrt/luci,palmettos/cnLuCI,lbthomsen/openwrt-luci,opentechinstitute/luci,981213/luci-1,ReclaimYourPrivacy/cloak-luci,bittorf/luci,jlopenwrtluci/luci,david-xiao/luci,cshore-firmware/openwrt-luci,kuoruan/lede-luci,artynet/luci,palmettos/cnLuCI,florian-shellfire/luci,oyido/luci,RuiChen1113/luci,tobiaswaldvogel/luci,nmav/luci,oneru/luci,remakeelectric/luci,dismantl/luci-0.12,981213/luci-1,Kyklas/luci-proto-hso,taiha/luci,zhaoxx063/luci,openwrt/luci,nmav/luci,keyidadi/luci,daofeng2015/luci,jorgifumi/luci,marcel-sch/luci,Sakura-Winkey/LuCI,cappiewu/luci,kuoruan/luci,Wedmer/luci,NeoRaider/luci,rogerpueyo/luci,nwf/openwrt-luci,marcel-sch/luci,david-xiao/luci,palmettos/test,palmettos/cnLuCI,tobiaswaldvogel/luci,LazyZhu/openwrt-luci-trunk-mod,kuoruan/lede-luci,marcel-sch/luci,shangjiyu/luci-with-extra,Kyklas/luci-proto-hso,NeoRaider/luci,maxrio/luci981213,slayerrensky/luci,Wedmer/luci,ff94315/luci-1,bright-things/ionic-luci,sujeet14108/luci,ollie27/openwrt_luci,cappiewu/luci,Hostle/openwrt-luci-multi-user,aa65535/luci,Noltari/luci,palmettos/test,nwf/openwrt-luci
|
05a6bab4cc142a86d929501ad0e2ef13b1978ab1
|
game/scripts/vscripts/items/item_book_of_the_guardian.lua
|
game/scripts/vscripts/items/item_book_of_the_guardian.lua
|
item_book_of_the_guardian_baseclass = {}
LinkLuaModifier("modifier_item_book_of_the_guardian", "items/item_book_of_the_guardian.lua", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_item_book_of_the_guardian_effect", "items/item_book_of_the_guardian.lua", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_item_book_of_the_guardian_blast", "items/item_book_of_the_guardian.lua", LUA_MODIFIER_MOTION_NONE)
if IsServer() then
function item_book_of_the_guardian_baseclass:OnSpellStart()
local caster = self:GetCaster()
local blast_radius = self:GetAbilitySpecial("blast_radius")
local blast_speed = self:GetAbilitySpecial("blast_speed")
local blast_damage_int_mult = self:GetSpecialValueFor("blast_damage_int_mult")
local blast_debuff_duration = self:GetSpecialValueFor("blast_debuff_duration")
local blast_vision_duration = self:GetSpecialValueFor("blast_vision_duration")
local startTime = GameRules:GetGameTime()
local affectedUnits = {}
local pfx = ParticleManager:CreateParticle("particles/econ/events/ti7/shivas_guard_active_ti7.vpcf", PATTACH_ABSORIGIN_FOLLOW, caster)
ParticleManager:SetParticleControl(pfx, 1, Vector(blast_radius, blast_radius / blast_speed * 1.5, blast_speed))
caster:EmitSound("DOTA_Item.ShivasGuard.Activate")
Timers:CreateTimer(function()
local now = GameRules:GetGameTime()
local elapsed = now - startTime
local abs = caster:GetAbsOrigin()
self:CreateVisibilityNode(abs, blast_radius, blast_vision_duration)
for _,v in ipairs(FindUnitsInRadius(caster:GetTeamNumber(), abs, nil, elapsed * blast_speed, DOTA_UNIT_TARGET_TEAM_ENEMY, DOTA_UNIT_TARGET_BASIC + DOTA_UNIT_TARGET_HERO, DOTA_UNIT_TARGET_FLAG_NONE, FIND_ANY_ORDER, false)) do
if not affectedUnits[v] then
affectedUnits[v] = true
ApplyDamage({
attacker = caster,
victim = v,
damage = caster:GetIntellect() * blast_damage_int_mult,
damage_type = self:GetAbilityDamageType(),
damage_flags = DOTA_DAMAGE_FLAG_NO_SPELL_AMPLIFICATION,
ability = self
})
local impact_pfx = ParticleManager:CreateParticle("particles/econ/events/ti7/shivas_guard_impact_ti7.vpcf", PATTACH_ABSORIGIN_FOLLOW, v)
ParticleManager:SetParticleControlEnt(impact_pfx, 1, caster, PATTACH_POINT_FOLLOW, "attach_hitloc", caster:GetAbsOrigin(), true)
v:AddNewModifier(caster, self, "modifier_item_book_of_the_guardian_blast", {duration = blast_debuff_duration})
end
end
if elapsed * blast_speed < blast_radius then
return 0.1
end
end)
end
end
item_book_of_the_guardian = class(item_book_of_the_guardian_baseclass)
modifier_item_book_of_the_guardian = class({
IsHidden = function() return true end,
IsAura = function() return true end,
GetAttributes = function() return MODIFIER_ATTRIBUTE_MULTIPLE end,
IsPurgable = function() return false end,
})
function modifier_item_book_of_the_guardian:DeclareFunctions()
return {
MODIFIER_PROPERTY_STATS_INTELLECT_BONUS,
MODIFIER_PROPERTY_HEALTH_REGEN_CONSTANT,
MODIFIER_PROPERTY_MANA_REGEN_PERCENTAGE,
MODIFIER_PROPERTY_PREATTACK_BONUS_DAMAGE,
MODIFIER_PROPERTY_SPELL_AMPLIFY_PERCENTAGE,
}
end
function modifier_item_book_of_the_guardian:GetModifierBonusStats_Intellect()
return self:GetAbility():GetSpecialValueFor("bonus_intellect")
end
function modifier_item_book_of_the_guardian:GetModifierConstantHealthRegen()
return self:GetAbility():GetSpecialValueFor("bonus_health_regen")
end
function modifier_item_book_of_the_guardian:GetModifierPercentageManaRegen()
return self:GetAbility():GetSpecialValueFor("bonus_mana_regen")
end
function modifier_item_book_of_the_guardian:GetModifierPreAttack_BonusDamage()
return self:GetAbility():GetSpecialValueFor("bonus_damage")
end
function modifier_item_book_of_the_guardian:GetModifierSpellAmplify_Percentage()
return self:GetAbility():GetSpecialValueFor("spell_amp_pct")
end
function modifier_item_book_of_the_guardian:GetModifierAura()
return "modifier_item_book_of_the_guardian_aura"
end
function modifier_item_book_of_the_guardian:GetAuraRadius()
return self:GetAbility():GetSpecialValueFor("aura_radius")
end
function modifier_item_book_of_the_guardian:GetAuraDuration()
return 0.5
end
function modifier_item_book_of_the_guardian:GetAuraSearchTeam()
return DOTA_UNIT_TARGET_TEAM_ENEMY
end
function modifier_item_book_of_the_guardian:GetAuraSearchType()
return DOTA_UNIT_TARGET_HERO
end
modifier_item_book_of_the_guardian_aura = class({
IsPurgable = function() return false end,
})
function modifier_item_book_of_the_guardian_aura:DeclareFunctions()
return {MODIFIER_PROPERTY_ATTACKSPEED_BONUS_CONSTANT}
end
function modifier_item_book_of_the_guardian_aura:GetModifierAttackSpeedBonus_Constant()
return self:GetAbility():GetSpecialValueFor("aura_attack_speed")
end
modifier_item_book_of_the_guardian_blast = class({
GetEffectName = function() return "particles/econ/events/ti7/shivas_guard_slow.vpcf" end,
GetEffectAttachType = function() return PATTACH_ABSORIGIN_FOLLOW end,
})
function modifier_item_book_of_the_guardian_blast:DeclareFunctions()
return {MODIFIER_PROPERTY_MOVESPEED_BONUS_PERCENTAGE}
end
function modifier_item_book_of_the_guardian_blast:GetModifierMoveSpeedBonus_Percentage()
return self:GetAbility():GetSpecialValueFor("blast_movement_speed_pct")
end
|
LinkLuaModifier("modifier_item_book_of_the_guardian", "items/item_book_of_the_guardian.lua", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_item_book_of_the_guardian_effect", "items/item_book_of_the_guardian.lua", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_item_book_of_the_guardian_blast", "items/item_book_of_the_guardian.lua", LUA_MODIFIER_MOTION_NONE)
item_book_of_the_guardian_baseclass = {
GetIntrinsicModifierName = function() return "modifier_item_book_of_the_guardian" end
}
if IsServer() then
function item_book_of_the_guardian_baseclass:OnSpellStart()
local caster = self:GetCaster()
local blast_radius = self:GetAbilitySpecial("blast_radius")
local blast_speed = self:GetAbilitySpecial("blast_speed")
local blast_damage_int_mult = self:GetSpecialValueFor("blast_damage_int_mult")
local blast_debuff_duration = self:GetSpecialValueFor("blast_debuff_duration")
local blast_vision_duration = self:GetSpecialValueFor("blast_vision_duration")
local startTime = GameRules:GetGameTime()
local affectedUnits = {}
local pfx = ParticleManager:CreateParticle("particles/econ/events/ti7/shivas_guard_active_ti7.vpcf", PATTACH_ABSORIGIN_FOLLOW, caster)
ParticleManager:SetParticleControl(pfx, 1, Vector(blast_radius, blast_radius / blast_speed * 1.5, blast_speed))
caster:EmitSound("DOTA_Item.ShivasGuard.Activate")
Timers:CreateTimer(function()
local now = GameRules:GetGameTime()
local elapsed = now - startTime
local abs = caster:GetAbsOrigin()
self:CreateVisibilityNode(abs, blast_radius, blast_vision_duration)
for _,v in ipairs(FindUnitsInRadius(caster:GetTeamNumber(), abs, nil, elapsed * blast_speed, DOTA_UNIT_TARGET_TEAM_ENEMY, DOTA_UNIT_TARGET_BASIC + DOTA_UNIT_TARGET_HERO, DOTA_UNIT_TARGET_FLAG_NONE, FIND_ANY_ORDER, false)) do
if not affectedUnits[v] then
affectedUnits[v] = true
ApplyDamage({
attacker = caster,
victim = v,
damage = caster:GetIntellect() * blast_damage_int_mult,
damage_type = self:GetAbilityDamageType(),
damage_flags = DOTA_DAMAGE_FLAG_NO_SPELL_AMPLIFICATION,
ability = self
})
local impact_pfx = ParticleManager:CreateParticle("particles/econ/events/ti7/shivas_guard_impact_ti7.vpcf", PATTACH_ABSORIGIN_FOLLOW, v)
ParticleManager:SetParticleControlEnt(impact_pfx, 1, caster, PATTACH_POINT_FOLLOW, "attach_hitloc", caster:GetAbsOrigin(), true)
v:AddNewModifier(caster, self, "modifier_item_book_of_the_guardian_blast", {duration = blast_debuff_duration})
end
end
if elapsed * blast_speed < blast_radius then
return 0.1
end
end)
end
end
item_book_of_the_guardian = class(item_book_of_the_guardian_baseclass)
modifier_item_book_of_the_guardian = class({
IsHidden = function() return true end,
IsAura = function() return true end,
GetAttributes = function() return MODIFIER_ATTRIBUTE_MULTIPLE end,
IsPurgable = function() return false end,
})
function modifier_item_book_of_the_guardian:DeclareFunctions()
return {
MODIFIER_PROPERTY_STATS_INTELLECT_BONUS,
MODIFIER_PROPERTY_HEALTH_REGEN_CONSTANT,
MODIFIER_PROPERTY_MANA_REGEN_PERCENTAGE,
MODIFIER_PROPERTY_PREATTACK_BONUS_DAMAGE,
MODIFIER_PROPERTY_SPELL_AMPLIFY_PERCENTAGE,
}
end
function modifier_item_book_of_the_guardian:GetModifierBonusStats_Intellect()
return self:GetAbility():GetSpecialValueFor("bonus_intellect")
end
function modifier_item_book_of_the_guardian:GetModifierConstantHealthRegen()
return self:GetAbility():GetSpecialValueFor("bonus_health_regen")
end
function modifier_item_book_of_the_guardian:GetModifierPercentageManaRegen()
return self:GetAbility():GetSpecialValueFor("bonus_mana_regen")
end
function modifier_item_book_of_the_guardian:GetModifierPreAttack_BonusDamage()
return self:GetAbility():GetSpecialValueFor("bonus_damage")
end
function modifier_item_book_of_the_guardian:GetModifierSpellAmplify_Percentage()
return self:GetAbility():GetSpecialValueFor("spell_amp_pct")
end
function modifier_item_book_of_the_guardian:GetModifierAura()
return "modifier_item_book_of_the_guardian_aura"
end
function modifier_item_book_of_the_guardian:GetAuraRadius()
return self:GetAbility():GetSpecialValueFor("aura_radius")
end
function modifier_item_book_of_the_guardian:GetAuraDuration()
return 0.5
end
function modifier_item_book_of_the_guardian:GetAuraSearchTeam()
return DOTA_UNIT_TARGET_TEAM_ENEMY
end
function modifier_item_book_of_the_guardian:GetAuraSearchType()
return DOTA_UNIT_TARGET_HERO
end
modifier_item_book_of_the_guardian_aura = class({
IsPurgable = function() return false end,
})
function modifier_item_book_of_the_guardian_aura:DeclareFunctions()
return {MODIFIER_PROPERTY_ATTACKSPEED_BONUS_CONSTANT}
end
function modifier_item_book_of_the_guardian_aura:GetModifierAttackSpeedBonus_Constant()
return self:GetAbility():GetSpecialValueFor("aura_attack_speed")
end
modifier_item_book_of_the_guardian_blast = class({
GetEffectName = function() return "particles/econ/events/ti7/shivas_guard_slow.vpcf" end,
GetEffectAttachType = function() return PATTACH_ABSORIGIN_FOLLOW end,
})
function modifier_item_book_of_the_guardian_blast:DeclareFunctions()
return {MODIFIER_PROPERTY_MOVESPEED_BONUS_PERCENTAGE}
end
function modifier_item_book_of_the_guardian_blast:GetModifierMoveSpeedBonus_Percentage()
return self:GetAbility():GetSpecialValueFor("blast_movement_speed_pct")
end
|
Fixed Book of the Guardian passive modifier wasn't applied
|
Fixed Book of the Guardian passive modifier wasn't applied
|
Lua
|
mit
|
ark120202/aabs
|
e03cef26dacfc94ffdf7d35f7941159f5acfa9eb
|
mod_auth_external/mod_auth_external.lua
|
mod_auth_external/mod_auth_external.lua
|
--
-- Prosody IM
-- Copyright (C) 2010 Waqas Hussain
-- Copyright (C) 2010 Jeff Mitchell
-- Copyright (C) 2013 Mikael Nordfeldth
-- Copyright (C) 2013 Matthew Wild, finally came to fix it all
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
local lpty = assert(require "lpty", "mod_auth_external requires lpty: https://code.google.com/p/prosody-modules/wiki/mod_auth_external#Installation");
local log = module._log;
local host = module.host;
local script_type = module:get_option_string("external_auth_protocol", "generic");
assert(script_type == "ejabberd" or script_type == "generic", "Config error: external_auth_protocol must be 'ejabberd' or 'generic'");
local command = module:get_option_string("external_auth_command", "");
local read_timeout = module:get_option_number("external_auth_timeout", 5);
assert(not host:find(":"), "Invalid hostname");
local usermanager = require "core.usermanager";
local new_sasl = require "util.sasl".new;
local pty = lpty.new({ throw_errors = false, no_local_echo = true, use_path = false });
function send_query(text)
if not pty:hasproc() then
local status, ret = pty:exitstatus();
if status and (status ~= "exit" or ret ~= 0) then
log("warn", "Auth process exited unexpectedly with %s %d, restarting", status, ret or 0);
return nil;
end
local ok, err = pty:startproc(command);
if not ok then
log("error", "Failed to start auth process '%s': %s", command, err);
return nil;
end
log("debug", "Started auth process");
end
pty:send(text);
return pty:read(read_timeout);
end
function do_query(kind, username, password)
if not username then return nil, "not-acceptable"; end
local query = (password and "%s:%s:%s:%s" or "%s:%s:%s"):format(kind, username, host, password);
local len = #query
if len > 1000 then return nil, "policy-violation"; end
if script_type == "ejabberd" then
local lo = len % 256;
local hi = (len - lo) / 256;
query = string.char(hi, lo)..query;
end
if script_type == "generic" then
query = query..'\n';
end
local response = send_query(query);
if (script_type == "ejabberd" and response == "\0\2\0\0") or
(script_type == "generic" and response:gsub("\r?\n$", "") == "0") then
return nil, "not-authorized";
elseif (script_type == "ejabberd" and response == "\0\2\0\1") or
(script_type == "generic" and response:gsub("\r?\n$", "") == "1") then
return true;
else
if response then
log("warn", "Unable to interpret data from auth process, %s", (response:match("^error:") and response) or ("["..#response.." bytes]"));
else
log("warn", "Error while waiting for result from auth process: %s", response or "unknown error");
end
return nil, "internal-server-error";
end
end
local host = module.host;
local provider = {};
function provider.test_password(username, password)
return do_query("auth", username, password);
end
function provider.set_password(username, password)
return do_query("setpass", username, password);
end
function provider.user_exists(username)
return do_query("isuser", username);
end
function provider.create_user(username, password) return nil, "Account creation/modification not available."; end
function provider.get_sasl_handler()
local testpass_authentication_profile = {
plain_test = function(sasl, username, password, realm)
return usermanager.test_password(username, realm, password), true;
end,
};
return new_sasl(host, testpass_authentication_profile);
end
module:provides("auth", provider);
|
--
-- Prosody IM
-- Copyright (C) 2010 Waqas Hussain
-- Copyright (C) 2010 Jeff Mitchell
-- Copyright (C) 2013 Mikael Nordfeldth
-- Copyright (C) 2013 Matthew Wild, finally came to fix it all
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
local lpty = assert(require "lpty", "mod_auth_external requires lpty: https://code.google.com/p/prosody-modules/wiki/mod_auth_external#Installation");
local log = module._log;
local host = module.host;
local script_type = module:get_option_string("external_auth_protocol", "generic");
assert(script_type == "ejabberd" or script_type == "generic", "Config error: external_auth_protocol must be 'ejabberd' or 'generic'");
local command = module:get_option_string("external_auth_command", "");
local read_timeout = module:get_option_number("external_auth_timeout", 5);
assert(not host:find(":"), "Invalid hostname");
local usermanager = require "core.usermanager";
local new_sasl = require "util.sasl".new;
local pty = lpty.new({ throw_errors = false, no_local_echo = true, use_path = false });
function send_query(text)
if not pty:hasproc() then
local status, ret = pty:exitstatus();
if status and (status ~= "exit" or ret ~= 0) then
log("warn", "Auth process exited unexpectedly with %s %d, restarting", status, ret or 0);
return nil;
end
local ok, err = pty:startproc(command);
if not ok then
log("error", "Failed to start auth process '%s': %s", command, err);
return nil;
end
log("debug", "Started auth process");
end
pty:send(text);
return pty:read(read_timeout);
end
function do_query(kind, username, password)
if not username then return nil, "not-acceptable"; end
local query = (password and "%s:%s:%s:%s" or "%s:%s:%s"):format(kind, username, host, password);
local len = #query
if len > 1000 then return nil, "policy-violation"; end
if script_type == "ejabberd" then
local lo = len % 256;
local hi = (len - lo) / 256;
query = string.char(hi, lo)..query;
end
if script_type == "generic" then
query = query..'\n';
end
local response, err = send_query(query);
if not response then
log("warn", "Error while waiting for result from auth process: %s", err or "unknown error");
elseif (script_type == "ejabberd" and response == "\0\2\0\0") or
(script_type == "generic" and response:gsub("\r?\n$", "") == "0") then
return nil, "not-authorized";
elseif (script_type == "ejabberd" and response == "\0\2\0\1") or
(script_type == "generic" and response:gsub("\r?\n$", "") == "1") then
return true;
else
log("warn", "Unable to interpret data from auth process, %s", (response:match("^error:") and response) or ("["..#response.." bytes]"));
return nil, "internal-server-error";
end
end
local host = module.host;
local provider = {};
function provider.test_password(username, password)
return do_query("auth", username, password);
end
function provider.set_password(username, password)
return do_query("setpass", username, password);
end
function provider.user_exists(username)
return do_query("isuser", username);
end
function provider.create_user(username, password) return nil, "Account creation/modification not available."; end
function provider.get_sasl_handler()
local testpass_authentication_profile = {
plain_test = function(sasl, username, password, realm)
return usermanager.test_password(username, realm, password), true;
end,
};
return new_sasl(host, testpass_authentication_profile);
end
module:provides("auth", provider);
|
mod_auth_external: Fix logging of errors
|
mod_auth_external: Fix logging of errors
|
Lua
|
mit
|
Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules
|
47f4e824761d42619c49e7c7ffd1f310f2a5c5a2
|
game/scripts/vscripts/modules/custom_abilities/ability_shop.lua
|
game/scripts/vscripts/modules/custom_abilities/ability_shop.lua
|
function CustomAbilities:PostAbilityShopData()
CustomGameEventManager:RegisterListener("ability_shop_buy", function(_, data)
CustomAbilities:OnAbilityBuy(data.PlayerID, data.ability)
end)
CustomGameEventManager:RegisterListener("ability_shop_sell", Dynamic_Wrap(CustomAbilities, "OnAbilitySell"))
CustomGameEventManager:RegisterListener("ability_shop_downgrade", Dynamic_Wrap(CustomAbilities, "OnAbilityDowngrade"))
PlayerTables:CreateTable("ability_shop_data", CustomAbilities.ClientData, AllPlayersInterval)
end
function CustomAbilities:GetAbilityListInfo(abilityname)
return CustomAbilities.AbilityInfo[abilityname]
end
function CustomAbilities:OnAbilityBuy(PlayerID, abilityname)
local hero = PlayerResource:GetSelectedHeroEntity(PlayerID)
local abilityInfo = CustomAbilities:GetAbilityListInfo(abilityname)
if not abilityInfo then
return
end
local cost = abilityInfo.cost
local banned_with = abilityInfo.banned_with
for _,v in ipairs(banned_with) do
if hero:HasAbility(v) then
return
end
end
if hero and cost and hero:GetAbilityPoints() >= cost then
local function Buy()
if IsValidEntity(hero) and hero:GetAbilityPoints() >= cost then
local abilityh = hero:FindAbilityByName(abilityname)
if abilityh and not abilityh:IsHidden() then
if abilityh:GetLevel() < abilityh:GetMaxLevel() then
hero:SetAbilityPoints(hero:GetAbilityPoints() - cost)
abilityh:SetLevel(abilityh:GetLevel() + 1)
end
elseif hero:HasAbility("ability_empty") then
if abilityh and abilityh:IsHidden() then
RemoveAbilityWithModifiers(hero, abilityh)
end
hero:SetAbilityPoints(hero:GetAbilityPoints() - cost)
hero:RemoveAbility("ability_empty")
GameMode:PrecacheUnitQueueed(abilityInfo.hero)
local a, linked = hero:AddNewAbility(abilityname)
a:SetLevel(1)
if linked then
for _,v in ipairs(linked) do
if v:GetAbilityName() == "phoenix_launch_fire_spirit" then
v:SetLevel(1)
end
end
end
hero:CalculateStatBonus()
CustomGameEventManager:Send_ServerToPlayer(PlayerResource:GetPlayer(PlayerID), "dota_ability_changed", {})
end
end
end
if hero:HasAbility(abilityname) then
Buy()
else
PrecacheItemByNameAsync(abilityname, Buy)
end
end
end
function CustomAbilities:OnAbilitySell(data)
local hero = PlayerResource:GetSelectedHeroEntity(data.PlayerID)
local listDataInfo = CustomAbilities:GetAbilityListInfo(data.ability)
if hero and hero:HasAbility(data.ability) and not hero:IsChanneling() and listDataInfo then
local cost = listDataInfo.cost
local abilityh = hero:FindAbilityByName(data.ability)
local gold = CustomAbilities:CalculateDowngradeCost(data.ability, cost) * abilityh:GetLevel()
if Gold:GetGold(data.PlayerID) >= gold and not abilityh:IsHidden() then
Gold:RemoveGold(data.PlayerID, gold)
hero:SetAbilityPoints(hero:GetAbilityPoints() + cost*abilityh:GetLevel())
RemoveAbilityWithModifiers(hero, abilityh)
local link = LINKED_ABILITIES[data.ability]
if link then
for _,v in ipairs(link) do
hero:RemoveAbility(v)
end
end
hero:AddAbility("ability_empty")
end
end
CustomGameEventManager:Send_ServerToPlayer(PlayerResource:GetPlayer(data.PlayerID), "dota_ability_changed", {})
end
function CustomAbilities:OnAbilityDowngrade(data)
local hero = PlayerResource:GetSelectedHeroEntity(data.PlayerID)
local listDataInfo = CustomAbilities:GetAbilityListInfo(data.ability)
if hero and hero:HasAbility(data.ability) and listDataInfo then
local cost = listDataInfo.cost
local abilityh = hero:FindAbilityByName(data.ability)
if abilityh:GetLevel() <= 1 then
CustomAbilities:OnAbilitySell(data)
else
local gold = CustomAbilities:CalculateDowngradeCost(data.ability, cost)
if Gold:GetGold(data.PlayerID) >= gold and not abilityh:IsHidden() then
Gold:RemoveGold(data.PlayerID, gold)
abilityh:SetLevel(abilityh:GetLevel() - 1)
hero:SetAbilityPoints(hero:GetAbilityPoints() + cost)
end
end
end
CustomGameEventManager:Send_ServerToPlayer(PlayerResource:GetPlayer(data.PlayerID), "dota_ability_changed", {})
end
function CustomAbilities:CalculateDowngradeCost(abilityname, upgradecost)
return (upgradecost*60) + (upgradecost*10*GetDOTATimeInMinutesFull())
end
|
function CustomAbilities:PostAbilityShopData()
CustomGameEventManager:RegisterListener("ability_shop_buy", function(_, data)
CustomAbilities:OnAbilityBuy(data.PlayerID, data.ability)
end)
CustomGameEventManager:RegisterListener("ability_shop_sell", Dynamic_Wrap(CustomAbilities, "OnAbilitySell"))
CustomGameEventManager:RegisterListener("ability_shop_downgrade", Dynamic_Wrap(CustomAbilities, "OnAbilityDowngrade"))
PlayerTables:CreateTable("ability_shop_data", CustomAbilities.ClientData, AllPlayersInterval)
end
function CustomAbilities:GetAbilityListInfo(abilityname)
return CustomAbilities.AbilityInfo[abilityname]
end
function CustomAbilities:OnAbilityBuy(PlayerID, abilityname)
local hero = PlayerResource:GetSelectedHeroEntity(PlayerID)
local abilityInfo = CustomAbilities:GetAbilityListInfo(abilityname)
if not abilityInfo then
return
end
local cost = abilityInfo.cost
local banned_with = abilityInfo.banned_with
for _,v in ipairs(banned_with) do
if hero:HasAbility(v) then
return
end
end
if hero and cost and hero:GetAbilityPoints() >= cost then
local function Buy()
if IsValidEntity(hero) and hero:GetAbilityPoints() >= cost then
local abilityh = hero:FindAbilityByName(abilityname)
if abilityh and not abilityh:IsHidden() then
if abilityh:GetLevel() < abilityh:GetMaxLevel() then
hero:SetAbilityPoints(hero:GetAbilityPoints() - cost)
abilityh:SetLevel(abilityh:GetLevel() + 1)
end
elseif hero:HasAbility("ability_empty") then
if abilityh and abilityh:IsHidden() then
RemoveAbilityWithModifiers(hero, abilityh)
end
hero:SetAbilityPoints(hero:GetAbilityPoints() - cost)
hero:RemoveAbility("ability_empty")
GameMode:PrecacheUnitQueueed(abilityInfo.hero)
local a, linked = hero:AddNewAbility(abilityname)
a:SetLevel(1)
if linked then
for _,v in ipairs(linked) do
if v:GetAbilityName() == "phoenix_launch_fire_spirit" then
v:SetLevel(1)
end
end
end
hero:CalculateStatBonus()
CustomGameEventManager:Send_ServerToPlayer(PlayerResource:GetPlayer(PlayerID), "dota_ability_changed", {})
end
end
end
if hero:HasAbility(abilityname) then
Buy()
else
PrecacheItemByNameAsync(abilityname, Buy)
end
end
end
function CustomAbilities:OnAbilitySell(data)
local hero = PlayerResource:GetSelectedHeroEntity(data.PlayerID)
local listDataInfo = CustomAbilities:GetAbilityListInfo(data.ability)
if hero and hero:HasAbility(data.ability) and not hero:IsChanneling() and listDataInfo then
local cost = listDataInfo.cost
local abilityh = hero:FindAbilityByName(data.ability)
local gold = CustomAbilities:CalculateDowngradeCost(data.ability, cost) * abilityh:GetLevel()
if Gold:GetGold(data.PlayerID) >= gold and not abilityh:IsHidden() then
Gold:RemoveGold(data.PlayerID, gold)
hero:SetAbilityPoints(hero:GetAbilityPoints() + cost*abilityh:GetLevel())
RemoveAbilityWithModifiers(hero, abilityh)
local link = LINKED_ABILITIES[data.ability]
if link then
for _,v in ipairs(link) do
hero:RemoveAbility(v)
end
end
if data.ability == "puck_illusory_orb" then
local etherealJaunt = hero:FindAbilityByName("puck_ethereal_jaunt")
if etherealJaunt then etherealJaunt:SetActivated(false) end
end
hero:AddAbility("ability_empty")
end
end
CustomGameEventManager:Send_ServerToPlayer(PlayerResource:GetPlayer(data.PlayerID), "dota_ability_changed", {})
end
function CustomAbilities:OnAbilityDowngrade(data)
local hero = PlayerResource:GetSelectedHeroEntity(data.PlayerID)
local listDataInfo = CustomAbilities:GetAbilityListInfo(data.ability)
if hero and hero:HasAbility(data.ability) and listDataInfo then
local cost = listDataInfo.cost
local abilityh = hero:FindAbilityByName(data.ability)
if abilityh:GetLevel() <= 1 then
CustomAbilities:OnAbilitySell(data)
else
local gold = CustomAbilities:CalculateDowngradeCost(data.ability, cost)
if Gold:GetGold(data.PlayerID) >= gold and not abilityh:IsHidden() then
Gold:RemoveGold(data.PlayerID, gold)
abilityh:SetLevel(abilityh:GetLevel() - 1)
hero:SetAbilityPoints(hero:GetAbilityPoints() + cost)
end
end
end
CustomGameEventManager:Send_ServerToPlayer(PlayerResource:GetPlayer(data.PlayerID), "dota_ability_changed", {})
end
function CustomAbilities:CalculateDowngradeCost(abilityname, upgradecost)
return (upgradecost*60) + (upgradecost*10*GetDOTATimeInMinutesFull())
end
|
fix(custom_abilities): puck's jaunt not deactivates with orb remove
|
fix(custom_abilities): puck's jaunt not deactivates with orb remove
Fixes #238.
|
Lua
|
mit
|
ark120202/aabs
|
ee5242d39e8ed712bc668c0bfbd6ec83a56bfbc5
|
scripts/rules/d/dmd.lua
|
scripts/rules/d/dmd.lua
|
--[[
Copyright (c) Jason White. MIT license.
Description:
Generates rules for the DMD compiler.
]]
local rules = require "rules"
--[[
Helper functions.
TODO: Alter paths based on platform
]]
local function is_d_source(src)
return path.getext(src) == ".d"
end
local function to_object(objdir, src)
return path.join(objdir, src .. ".o")
end
--[[
Base metatable
]]
local common = {
-- Path to DMD
compiler = {"dmd"};
-- Extra options
opts = {"-color=on"};
-- Path to the bin directory
bindir = "";
-- Build all source on the same command line. Otherwise, each source is
-- compiled separately and finally linked separately. In general, combined
-- compilation is faster.
combined = true;
-- Paths to look for imports
imports = {};
-- Paths to look for string imports
string_imports = {};
-- Versions to define with '-version='
versions = {};
-- Extra compiler and linker options
compiler_opts = {};
linker_opts = {};
}
function common:path()
return path.join(self.bindir, self:basename())
end
setmetatable(common, {__index = rules.common})
--[[
A binary executable.
]]
local _binary = {}
local _binary_mt = {__index = _binary}
local function is_binary(t)
return getmetatable(t) == _binary_mt
end
setmetatable(_binary, {__index = common})
--[[
A library. Can be static or dynamic.
]]
local _library = {
-- Shared library?
shared = false,
}
local _library_mt = {__index = _library}
local function is_library(t)
return getmetatable(t) == _library_mt
end
setmetatable(_library, {__index = common})
--[[
A test.
]]
local _test = {}
local _test_mt = {__index = _test}
local function is_test(t)
return getmetatable(t) == _test_mt
end
setmetatable(_test, {__index = common})
--[[
Generates the low-level rules required to build a generic D library/binary.
]]
function common:rules()
local objdir = self.objdir or path.join("obj", self.name)
local args = table.join(self.prefix, self.compiler, self.opts)
local compiler_opts = {"-op"}
for _,v in ipairs(self.imports) do
table.insert(compiler_opts, "-I" .. path.join(SCRIPT_DIR, v))
end
for _,v in ipairs(self.string_imports) do
table.insert(compiler_opts, "-J" .. path.join(SCRIPT_DIR, v))
end
for _,v in ipairs(self.versions) do
table.insert(compiler_opts, "-version=" .. v)
end
table.append(compiler_opts, self.compiler_opts)
local sources = {}
local objects = {}
for _,v in ipairs(self.srcs) do
if is_d_source(v) then
table.insert(sources, v)
table.insert(objects, to_object(objdir, v))
end
end
local inputs = {}
table.append(inputs, sources)
-- TODO: Allow linking with C/C++ libraries
for _,dep in ipairs(self.deps) do
if is_library(dep) then
table.insert(inputs, dep:path())
end
end
local output = self:path()
local linker_opts = table.join(self.linker_opts, {"-of" .. output})
if self.combined then
-- Combined compilation
rule {
inputs = inputs,
task = table.join(args, compiler_opts, linker_opts, inputs),
outputs = table.join(objects, {output}),
}
else
-- Individual compilation
for i,src in ipairs(sources) do
rule {
inputs = {src},
task = table.join(args, compiler_opts,
{"-c", src, "-of".. objects[i]}),
outputs = {objects[i]},
}
end
rule {
inputs = objects,
task = table.join(args, linker_opts, objects),
outputs = table.join({output}),
}
end
end
function _library:basename()
local name = common.basename(self)
if self.shared then
return "lib".. name .. ".so"
else
return "lib".. name .. ".a"
end
end
function _library:rules()
if self.shared then
self.compiler_opts = table.join(self.compiler_opts, "-fPIC")
self.linker_opts = table.join(self.linker_opts, {
"-shared", "-defaultlib=libphobos2.so"
})
else
self.linker_opts = table.join(self.linker_opts, "-lib")
end
common.rules(self)
end
function _test:rules()
self.compiler_opts = table.join(self.compiler_opts, "-unittest")
common.rules(self)
local test_runner = self:path()
rule {
inputs = {test_runner},
task = {path.join(".", test_runner)},
outputs = {},
}
end
local function binary(opts)
setmetatable(opts, _binary_mt)
return rules.add(opts)
end
local function library(opts)
setmetatable(opts, _library_mt)
return rules.add(opts)
end
local function test(opts)
setmetatable(opts, _test_mt)
return rules.add(opts)
end
return {
common = common,
is_binary = is_binary,
is_library = is_library,
is_test = is_test,
binary = binary,
library = library,
test = test,
}
|
--[[
Copyright (c) Jason White. MIT license.
Description:
Generates rules for the DMD compiler.
]]
local rules = require "rules"
--[[
Helper functions.
TODO: Alter paths based on platform
]]
local function is_d_source(src)
return path.getext(src) == ".d"
end
local function to_object(objdir, src)
return path.setext(path.join(objdir, src), ".o")
end
--[[
Base metatable
]]
local common = {
-- Path to DMD
compiler = {"dmd"};
-- Extra options
opts = {"-color=on"};
-- Path to the bin directory
bindir = "";
-- Build all source on the same command line. Otherwise, each source is
-- compiled separately and finally linked separately. In general, combined
-- compilation is faster.
combined = true;
-- Paths to look for imports
imports = {};
-- Paths to look for string imports
string_imports = {};
-- Versions to define with '-version='
versions = {};
-- Extra compiler and linker options
compiler_opts = {};
linker_opts = {};
}
function common:path()
return path.join(self.bindir, self:basename())
end
setmetatable(common, {__index = rules.common})
--[[
A binary executable.
]]
local _binary = {}
local _binary_mt = {__index = _binary}
local function is_binary(t)
return getmetatable(t) == _binary_mt
end
setmetatable(_binary, {__index = common})
--[[
A library. Can be static or dynamic.
]]
local _library = {
-- Shared library?
shared = false,
}
local _library_mt = {__index = _library}
local function is_library(t)
return getmetatable(t) == _library_mt
end
setmetatable(_library, {__index = common})
--[[
A test.
]]
local _test = {}
local _test_mt = {__index = _test}
local function is_test(t)
return getmetatable(t) == _test_mt
end
setmetatable(_test, {__index = common})
--[[
Generates the low-level rules required to build a generic D library/binary.
]]
function common:rules()
local objdir = self.objdir or path.join("obj", self.name)
local args = table.join(self.prefix, self.compiler, self.opts)
local compiler_opts = {"-op", "-od".. objdir}
for _,v in ipairs(self.imports) do
table.insert(compiler_opts, "-I" .. path.join(SCRIPT_DIR, v))
end
for _,v in ipairs(self.string_imports) do
table.insert(compiler_opts, "-J" .. path.join(SCRIPT_DIR, v))
end
for _,v in ipairs(self.versions) do
table.insert(compiler_opts, "-version=" .. v)
end
table.append(compiler_opts, self.compiler_opts)
local sources = {}
local objects = {}
for _,v in ipairs(self.srcs) do
if is_d_source(v) then
table.insert(sources, v)
table.insert(objects, to_object(objdir, v))
end
end
local inputs = {}
table.append(inputs, sources)
-- TODO: Allow linking with C/C++ libraries
for _,dep in ipairs(self.deps) do
if is_library(dep) then
table.insert(inputs, dep:path())
end
end
local output = self:path()
local linker_opts = table.join(self.linker_opts, {"-of" .. output})
if self.combined then
-- Combined compilation
rule {
inputs = inputs,
task = table.join(args, compiler_opts, linker_opts, inputs),
outputs = {to_object(objdir, output), output},
}
else
-- Individual compilation
for i,src in ipairs(sources) do
rule {
inputs = {src},
task = table.join(args, compiler_opts,
{"-c", src, "-of".. objects[i]}),
outputs = {objects[i]},
}
end
rule {
inputs = objects,
task = table.join(args, linker_opts, objects),
outputs = table.join({output}),
}
end
end
function _library:basename()
local name = common.basename(self)
if self.shared then
return "lib".. name .. ".so"
else
return "lib".. name .. ".a"
end
end
function _library:rules()
if self.shared then
self.compiler_opts = table.join(self.compiler_opts, "-fPIC")
self.linker_opts = table.join(self.linker_opts, {
"-shared", "-defaultlib=libphobos2.so"
})
else
self.linker_opts = table.join(self.linker_opts, "-lib")
end
common.rules(self)
end
function _test:rules()
self.compiler_opts = table.join(self.compiler_opts, "-unittest")
common.rules(self)
local test_runner = self:path()
rule {
inputs = {test_runner},
task = {path.join(".", test_runner)},
outputs = {},
}
end
local function binary(opts)
setmetatable(opts, _binary_mt)
return rules.add(opts)
end
local function library(opts)
setmetatable(opts, _library_mt)
return rules.add(opts)
end
local function test(opts)
setmetatable(opts, _test_mt)
return rules.add(opts)
end
return {
common = common,
is_binary = is_binary,
is_library = is_library,
is_test = is_test,
binary = binary,
library = library,
test = test,
}
|
Fix incorrect object path for combined compilation
|
Fix incorrect object path for combined compilation
|
Lua
|
mit
|
jasonwhite/bblua,jasonwhite/bblua,jasonwhite/bblua,jasonwhite/button-lua,jasonwhite/button-lua,jasonwhite/button-lua
|
1ebc03c62252c2fa1e2c431465ed3e9b46bf3c51
|
plugins/mod_muc_unique.lua
|
plugins/mod_muc_unique.lua
|
-- XEP-0307: Unique Room Names for Multi-User Chat
local uuid_gen = require "util.uuid".generate;
module:add_feature "http://jabber.org/protocol/muc#unique"
module:hook("iq-get/host/http://jabber.org/protocol/muc#unique:unique", function()
local origin, stanza = event.origin, event.stanza;
origin.send(st.reply(stanza)
:tag("unique", {xmlns = "http://jabber.org/protocol/muc#unique"})
:text(uuid_gen()) -- FIXME Random UUIDs can theoretically have collisions
);
return true;
end,-1);
|
-- XEP-0307: Unique Room Names for Multi-User Chat
local st = require "util.stanza";
local uuid_gen = require "util.uuid".generate;
module:add_feature "http://jabber.org/protocol/muc#unique"
module:hook("iq-get/host/http://jabber.org/protocol/muc#unique:unique", function(event)
local origin, stanza = event.origin, event.stanza;
origin.send(st.reply(stanza)
:tag("unique", {xmlns = "http://jabber.org/protocol/muc#unique"})
:text(uuid_gen()) -- FIXME Random UUIDs can theoretically have collisions
);
return true;
end,-1);
|
plugins/mod_muc_unique: Fix undefined global access (thanks Lance)
|
plugins/mod_muc_unique: Fix undefined global access (thanks Lance)
|
Lua
|
mit
|
sarumjanuch/prosody,sarumjanuch/prosody
|
495c2cabd7bfa8c85fed87b9ee46871569bda252
|
OS/DiskOS/Programs/save.lua
|
OS/DiskOS/Programs/save.lua
|
local destination = select(1,...)
local flag = select(2,...) or ""
local ctype = select(3,...) or "gzip"
local clvl = tonumber(select(4,...) or "9")
local term = require("terminal")
local eapi = require("Editors")
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")
|
local destination = select(1,...)
local flag = select(2,...) or ""
local ctype = select(3,...) or "gzip"
local clvl = tonumber(select(4,...) or "9")
local term = require("terminal")
local eapi = require("Editors")
if destination = "-?" then destination = nil end
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")
|
Fix -? not working on the save command
|
Fix -? not working on the save command
|
Lua
|
mit
|
RamiLego4Game/LIKO-12
|
705f7e4c0da99c0529e0cc53d7824b696615f3df
|
packages/lime-proto-anygw/src/anygw.lua
|
packages/lime-proto-anygw/src/anygw.lua
|
#!/usr/bin/lua
local fs = require("nixio.fs")
local network = require("lime.network")
local libuci = require "uci"
anygw = {}
anygw.configured = false
function anygw.configure(args)
if anygw.configured then return end
anygw.configured = true
local ipv4, ipv6 = network.primary_address()
local anygw_mac = "aa:aa:aa:aa:aa:aa"
local anygw_ipv6 = ipv6:minhost()
local anygw_ipv4 = ipv4:minhost()
anygw_ipv6:prefix(64) -- SLAAC only works with a /64, per RFC
anygw_ipv4:prefix(ipv4:prefix())
local baseIfname = "br-lan"
local argsDev = { macaddr = anygw_mac }
local argsIf = { proto = "static" }
argsIf.ip6addr = anygw_ipv6:string()
argsIf.ipaddr = anygw_ipv4:host():string()
argsIf.netmask = anygw_ipv4:mask():string()
local owrtInterfaceName, _, _ = network.createMacvlanIface( baseIfname,
"anygw", argsDev, argsIf )
local uci = libuci:cursor()
local pfr = network.limeIfNamePrefix.."anygw_"
uci:set("network", pfr.."rule6", "rule6")
uci:set("network", pfr.."rule6", "src", anygw_ipv6:host():string().."/128")
uci:set("network", pfr.."rule6", "lookup", "170") -- 0xaa in decimal
uci:set("network", pfr.."route6", "route6")
uci:set("network", pfr.."route6", "interface", owrtInterfaceName)
uci:set("network", pfr.."route6", "target", anygw_ipv6:network():string().."/"..anygw_ipv6:prefix())
uci:set("network", pfr.."route6", "table", "170")
uci:set("network", pfr.."rule4", "rule")
uci:set("network", pfr.."rule4", "src", anygw_ipv4:host():string().."/32")
uci:set("network", pfr.."rule4", "lookup", "170")
uci:set("network", pfr.."route4", "route")
uci:set("network", pfr.."route4", "interface", owrtInterfaceName)
uci:set("network", pfr.."route4", "target", anygw_ipv4:network():string())
uci:set("network", pfr.."route4", "netmask", anygw_ipv4:mask():string())
uci:set("network", pfr.."route4", "table", "170")
uci:save("network")
fs.mkdir("/etc/firewall.lime.d")
fs.writefile(
"/etc/firewall.lime.d/20-anygw-ebtables",
"\n" ..
"ebtables -D FORWARD -j DROP -d " .. anygw_mac .. "\n" ..
"ebtables -A FORWARD -j DROP -d " .. anygw_mac .. "\n" ..
"ebtables -t nat -D POSTROUTING -o bat0 -j DROP -s " .. anygw_mac .. "\n" ..
"ebtables -t nat -A POSTROUTING -o bat0 -j DROP -s " .. anygw_mac .. "\n"
)
local content = { }
uci:set("dhcp", "lan", "ignore", "1")
uci:save("dhcp")
content = { }
table.insert(content, "dhcp-range=tag:anygw,"..anygw_ipv4:add(1):host():string()..","..ipv4:maxhost():string())
table.insert(content, "dhcp-option=tag:anygw,option:router,"..anygw_ipv4:host():string())
table.insert(content, "dhcp-option=tag:anygw,option:dns-server,"..anygw_ipv4:host():string())
table.insert(content, "dhcp-option-force=tag:anygw,option:mtu,1350")
table.insert(content, "dhcp-broadcast=tag:anygw")
table.insert(content, "address=/anygw/"..anygw_ipv4:host():string())
table.insert(content, "address=/thisnode.info/"..anygw_ipv4:host():string())
fs.writefile("/etc/dnsmasq.d/lime-proto-anygw-10-ipv4.conf", table.concat(content, "\n").."\n")
content = { }
table.insert(content, "enable-ra")
table.insert(content, "dhcp-range=tag:anygw,"..ipv6:network():string()..",ra-names,24h")
table.insert(content, "dhcp-option=tag:anygw,option6:domain-search,lan")
table.insert(content, "dhcp-option=tag:anygw,option6:dns-server,"..anygw_ipv6:host():string())
table.insert(content, "address=/anygw/"..anygw_ipv6:host():string())
table.insert(content, "address=/thisnode.info/"..anygw_ipv6:host():string())
fs.writefile("/etc/dnsmasq.d/lime-proto-anygw-20-ipv6.conf", table.concat(content, "\n").."\n")
io.popen("/etc/init.d/dnsmasq enable || true"):close()
end
function anygw.setup_interface(ifname, args) end
function anygw.bgp_conf(templateVarsIPv4, templateVarsIPv6)
local base_conf = [[
protocol direct {
interface "anygw";
}
]]
return base_conf
end
return anygw
|
#!/usr/bin/lua
local fs = require("nixio.fs")
local network = require("lime.network")
local libuci = require "uci"
anygw = {}
anygw.configured = false
function anygw.configure(args)
if anygw.configured then return end
anygw.configured = true
local ipv4, ipv6 = network.primary_address()
local anygw_mac = "aa:aa:aa:aa:aa:aa"
local anygw_ipv6 = ipv6:minhost()
local anygw_ipv4 = ipv4:minhost()
anygw_ipv6:prefix(64) -- SLAAC only works with a /64, per RFC
anygw_ipv4:prefix(ipv4:prefix())
local baseIfname = "br-lan"
local argsDev = { macaddr = anygw_mac }
local argsIf = { proto = "static" }
argsIf.ip6addr = anygw_ipv6:string()
argsIf.ipaddr = anygw_ipv4:host():string()
argsIf.netmask = anygw_ipv4:mask():string()
local owrtInterfaceName, _, _ = network.createMacvlanIface( baseIfname,
"anygw", argsDev, argsIf )
local uci = libuci:cursor()
local pfr = network.limeIfNamePrefix.."anygw_"
uci:set("network", pfr.."rule6", "rule6")
uci:set("network", pfr.."rule6", "src", anygw_ipv6:host():string().."/128")
uci:set("network", pfr.."rule6", "lookup", "170") -- 0xaa in decimal
uci:set("network", pfr.."route6", "route6")
uci:set("network", pfr.."route6", "interface", owrtInterfaceName)
uci:set("network", pfr.."route6", "target", anygw_ipv6:network():string().."/"..anygw_ipv6:prefix())
uci:set("network", pfr.."route6", "table", "170")
uci:set("network", pfr.."rule4", "rule")
uci:set("network", pfr.."rule4", "src", anygw_ipv4:host():string().."/32")
uci:set("network", pfr.."rule4", "lookup", "170")
uci:set("network", pfr.."route4", "route")
uci:set("network", pfr.."route4", "interface", owrtInterfaceName)
uci:set("network", pfr.."route4", "target", anygw_ipv4:network():string())
uci:set("network", pfr.."route4", "netmask", anygw_ipv4:mask():string())
uci:set("network", pfr.."route4", "table", "170")
uci:save("network")
fs.mkdir("/etc/firewall.lime.d")
fs.writefile(
"/etc/firewall.lime.d/20-anygw-ebtables",
"\n" ..
"ebtables -D FORWARD -j DROP -d " .. anygw_mac .. "\n" ..
"ebtables -A FORWARD -j DROP -d " .. anygw_mac .. "\n" ..
"ebtables -t nat -D POSTROUTING -o bat0 -j DROP -s " .. anygw_mac .. "\n" ..
"ebtables -t nat -A POSTROUTING -o bat0 -j DROP -s " .. anygw_mac .. "\n"
)
local content = { }
uci:set("dhcp", "lan", "ignore", "1")
uci:save("dhcp")
content = { }
table.insert(content, "dhcp-range=tag:anygw,"..anygw_ipv4:add(1):host():string()..","..ipv4:maxhost():string())
table.insert(content, "dhcp-option=tag:anygw,option:router,"..anygw_ipv4:host():string())
table.insert(content, "dhcp-option=tag:anygw,option:dns-server,"..anygw_ipv4:host():string())
table.insert(content, "dhcp-option-force=tag:anygw,option:mtu,1350")
table.insert(content, "address=/anygw/"..anygw_ipv4:host():string())
table.insert(content, "address=/thisnode.info/"..anygw_ipv4:host():string())
fs.writefile("/etc/dnsmasq.d/lime-proto-anygw-10-ipv4.conf", table.concat(content, "\n").."\n")
content = { }
table.insert(content, "enable-ra")
table.insert(content, "dhcp-range=tag:anygw,"..ipv6:network():string()..",ra-names,24h")
table.insert(content, "dhcp-option=tag:anygw,option6:domain-search,lan")
table.insert(content, "dhcp-option=tag:anygw,option6:dns-server,"..anygw_ipv6:host():string())
table.insert(content, "address=/anygw/"..anygw_ipv6:host():string())
table.insert(content, "address=/thisnode.info/"..anygw_ipv6:host():string())
fs.writefile("/etc/dnsmasq.d/lime-proto-anygw-20-ipv6.conf", table.concat(content, "\n").."\n")
io.popen("/etc/init.d/dnsmasq enable || true"):close()
end
function anygw.setup_interface(ifname, args) end
function anygw.bgp_conf(templateVarsIPv4, templateVarsIPv6)
local base_conf = [[
protocol direct {
interface "anygw";
}
]]
return base_conf
end
return anygw
|
lime-proto-anygw: dhcp-broadcast no longer needed
|
lime-proto-anygw: dhcp-broadcast no longer needed
Bug was fixed upstream, workaround no longer needed
http://lists.thekelleys.org.uk/pipermail/dnsmasq-discuss/2017q1/011326.html
Signed-off-by: Gui Iribarren <d6a7af134530254f6dae4886d160be8e6c6891c9@altermundi.net>
|
Lua
|
agpl-3.0
|
libremesh/lime-packages,p4u/lime-packages,libremesh/lime-packages,p4u/lime-packages,libremesh/lime-packages,libremesh/lime-packages,p4u/lime-packages,p4u/lime-packages,p4u/lime-packages,libremesh/lime-packages,libremesh/lime-packages
|
8c666f3209e3bb0f858f8d6b4879dd6c8ec3f061
|
lua/iq-lines-animate-one.lua
|
lua/iq-lines-animate-one.lua
|
-- Visualize IQ data from the HackRF
-- This loads one second of data and then visualizes it.
-- Currently segfaults.
VERTEX_SHADER = [[
#version 400
layout (location = 0) in vec3 vp;
layout (location = 1) in vec3 vn;
out vec3 color;
uniform mat4 uViewMatrix, uProjectionMatrix;
uniform float uTime;
void main() {
color = vec3(1.0, 1.0, 1.0);
vec2 pt = vec2((vp.x - 0.5) * 1.8, (vp.y - 0.5) * 1.8);
gl_Position = vec4(pt.x, pt.y, 0.0, 1.0);
}
]]
FRAGMENT_SHADER = [[
#version 400
in vec3 color;
layout (location = 0) out vec4 fragColor;
void main() {
fragColor = vec4(color, 0.95);
}
]]
function setup()
-- Start the device for a minute, wait a bit, and stop again
device = nrf_device_new(2.5, "../rfdata/rf-2.500-1.raw")
os.execute("sleep " .. 1)
nrf_device_free(device)
camera = ngl_camera_new_look_at(0, 0, 0) -- Shader ignores camera position, but camera object is required for ngl_draw_model
shader = ngl_shader_new(GL_LINE_STRIP, VERTEX_SHADER, FRAGMENT_SHADER)
samples = 0
end
function draw()
ngl_clear(0.2, 0.2, 0.2, 1.0)
buffer = nrf_device_get_samples_buffer(device)
model = ngl_model_new(buffer.channels, math.min(samples, buffer.width * buffer.height), buffer.data)
ngl_draw_model(camera, model, shader)
samples = samples + 10
end
|
-- Visualize a single sample
VERTEX_SHADER = [[
#version 400
layout (location = 0) in vec3 vp;
layout (location = 1) in vec3 vn;
layout (location = 2) in vec2 vt;
out vec3 color;
out vec2 texCoord;
uniform mat4 uViewMatrix, uProjectionMatrix;
uniform float uTime;
void main() {
color = vec3(1.0, 1.0, 1.0);
texCoord = vt;
gl_Position = vec4(vp.x*2, vp.z*2, 0, 1.0);
}
]]
FRAGMENT_SHADER = [[
#version 400
in vec3 color;
in vec2 texCoord;
uniform sampler2D uTexture;
layout (location = 0) out vec4 fragColor;
void main() {
float r = texture(uTexture, texCoord).r * 100;
fragColor = vec4(r, r, r, 1);
}
]]
function setup()
countdown = 10
percentage = 0
device = nrf_device_new(100.9, "../rfdata/rf-2.500-1.raw")
filter = nrf_iq_filter_new(device.sample_rate, 200e3, 51)
camera = ngl_camera_new_look_at(0, 0, 0) -- Shader ignores camera position, but camera object is required for ngl_draw_model
shader = ngl_shader_new(GL_TRIANGLES, VERTEX_SHADER, FRAGMENT_SHADER)
texture = ngl_texture_new(shader, "uTexture")
model = ngl_model_new_grid_triangles(2, 2, 1, 1)
end
function draw()
if countdown > 0 then
samples_buffer = nrf_device_get_samples_buffer(device)
nrf_iq_filter_process(filter, samples_buffer)
filter_buffer = nrf_iq_filter_get_buffer(filter)
countdown = countdown - 1
elseif percentage > 1 then
countdown = 1
percentage = 0
else
iq_buffer = nrf_buffer_to_iq_lines(filter_buffer, 4, percentage)
ngl_clear(0.2, 0.2, 0.2, 1.0)
ngl_texture_update(texture, iq_buffer, 1024, 1024)
ngl_draw_model(camera, model, shader)
percentage = percentage + 0.0001
end
end
|
Fix iq-lines-animate-one.
|
Fix iq-lines-animate-one.
|
Lua
|
mit
|
silky/frequensea,silky/frequensea,fdb/frequensea,fdb/frequensea,fdb/frequensea,fdb/frequensea,silky/frequensea,silky/frequensea,fdb/frequensea,silky/frequensea
|
e3f30172b0d716f2ab7c95cebf3c8b24f618b59c
|
MMOCoreORB/bin/scripts/mobile/yavin4/serverobjects.lua
|
MMOCoreORB/bin/scripts/mobile/yavin4/serverobjects.lua
|
includeFile("yavin4/acklay.lua")
includeFile("yavin4/alert_droideka.lua")
includeFile("yavin4/ancient_mamien.lua")
includeFile("yavin4/angler_be.lua")
includeFile("yavin4/angler_hatchling.lua")
includeFile("yavin4/angler.lua")
includeFile("yavin4/angler_recluse.lua")
includeFile("yavin4/biogenic_assistant.lua")
includeFile("yavin4/biogenic_construction.lua")
includeFile("yavin4/biogenic_crazyguy.lua")
includeFile("yavin4/biogenic_engineertech.lua")
includeFile("yavin4/biogenic_scientist_generic_01.lua")
includeFile("yavin4/biogenic_scientist_generic_02.lua")
includeFile("yavin4/biogenic_scientist_geonosian.lua")
includeFile("yavin4/biogenic_scientist_human.lua")
includeFile("yavin4/biogenic_securitytech.lua")
includeFile("yavin4/blood_fanged_gackle_bat.lua")
includeFile("yavin4/bone_angler.lua")
includeFile("yavin4/captain_eso.lua")
includeFile("yavin4/choku_be.lua")
includeFile("yavin4/choku_female.lua")
includeFile("yavin4/choku_hunter.lua")
includeFile("yavin4/choku.lua")
includeFile("yavin4/choku_male.lua")
includeFile("yavin4/choku_packmaster.lua")
includeFile("yavin4/choku_pup.lua")
includeFile("yavin4/crazed_geonosian_guard.lua")
includeFile("yavin4/crystal_snake.lua")
includeFile("yavin4/cx_425.lua")
includeFile("yavin4/deadly_tanc_mite.lua")
includeFile("yavin4/drenn_zebber.lua")
includeFile("yavin4/elder_mamien.lua")
includeFile("yavin4/enhanced_force_kliknik.lua")
includeFile("yavin4/enhanced_gaping_spider.lua")
includeFile("yavin4/enhanced_kliknik.lua")
includeFile("yavin4/enhanced_kwi.lua")
includeFile("yavin4/enraged_tybis.lua")
includeFile("yavin4/female_mamien.lua")
includeFile("yavin4/female_mawgax.lua")
includeFile("yavin4/female_tybis.lua")
includeFile("yavin4/feral_mutant_gackle_stalker.lua")
includeFile("yavin4/frenzied_choku.lua")
includeFile("yavin4/gackle_bat_hunter.lua")
includeFile("yavin4/gackle_bat.lua")
includeFile("yavin4/gackle_bat_myrmidon_lord.lua")
includeFile("yavin4/geonosian_scientist.lua")
includeFile("yavin4/geonosian_technical_assistant.lua")
includeFile("yavin4/geonosian_worker.lua")
includeFile("yavin4/giant_angler.lua")
includeFile("yavin4/giant_crystal_snake.lua")
includeFile("yavin4/giant_gackle_bat.lua")
includeFile("yavin4/giant_mawgax.lua")
includeFile("yavin4/giant_spined_puc.lua")
includeFile("yavin4/giant_stintaril.lua")
includeFile("yavin4/giant_tanc_mite.lua")
includeFile("yavin4/gins_darone.lua")
includeFile("yavin4/grand_tybis.lua")
includeFile("yavin4/hooded_crystal_snake.lua")
includeFile("yavin4/hutt_expeditionary_force_surveyor.lua")
includeFile("yavin4/hutt_expeditonary_force_leader.lua")
includeFile("yavin4/hutt_expeditonary_force_member.lua")
includeFile("yavin4/imperial_observer.lua")
includeFile("yavin4/jazeen_thurmm.lua")
includeFile("yavin4/kai_tok_bloodreaver.lua")
includeFile("yavin4/kai_tok_prowler.lua")
includeFile("yavin4/kai_tok_scavenger.lua")
includeFile("yavin4/kai_tok_slayer.lua")
includeFile("yavin4/kliknik_be.lua")
includeFile("yavin4/kliknik_dark_defender.lua")
includeFile("yavin4/kliknik_dark_hunter.lua")
includeFile("yavin4/kliknik_dark_queen.lua")
includeFile("yavin4/kliknik_dark_warrior.lua")
includeFile("yavin4/kliknik_dark_worker.lua")
includeFile("yavin4/kliknik_defender.lua")
includeFile("yavin4/kliknik_hatchling.lua")
includeFile("yavin4/kliknik_hunter.lua")
includeFile("yavin4/kliknik.lua")
includeFile("yavin4/kliknik_mantis.lua")
includeFile("yavin4/kliknik_queen_harvester.lua")
includeFile("yavin4/kliknik_queen.lua")
includeFile("yavin4/kliknik_scout.lua")
includeFile("yavin4/kliknik_shredder_guardian.lua")
includeFile("yavin4/kliknik_warrior.lua")
includeFile("yavin4/kliknik_worker.lua")
includeFile("yavin4/lurking_angler.lua")
includeFile("yavin4/mad_angler.lua")
includeFile("yavin4/majestic_whisper_bird.lua")
includeFile("yavin4/male_mamien.lua")
includeFile("yavin4/male_mawgax.lua")
includeFile("yavin4/male_tybis.lua")
includeFile("yavin4/mamien_jungle_lord.lua")
includeFile("yavin4/mamien_matriarch.lua")
includeFile("yavin4/mamien_youth.lua")
includeFile("yavin4/mawgax_be.lua")
includeFile("yavin4/mawgax_raptor.lua")
includeFile("yavin4/mawgax_youth.lua")
includeFile("yavin4/megan_drlar.lua")
includeFile("yavin4/mercenary_sentry.lua")
includeFile("yavin4/ominous_skreeg.lua")
includeFile("yavin4/poisonous_spined_puc.lua")
includeFile("yavin4/puny_gackle_bat.lua")
includeFile("yavin4/puny_stintaril.lua")
includeFile("yavin4/puny_tanc_mite.lua")
includeFile("yavin4/ravaging_gackle_bat.lua")
includeFile("yavin4/skreeg_adolescent.lua")
includeFile("yavin4/skreeg_female.lua")
includeFile("yavin4/skreeg_gatherer.lua")
includeFile("yavin4/skreeg_hunter.lua")
includeFile("yavin4/skreeg_infant.lua")
includeFile("yavin4/skreeg_male.lua")
includeFile("yavin4/skreeg_scout.lua")
includeFile("yavin4/skreeg_warrior_elite.lua")
includeFile("yavin4/skreeg_warrior.lua")
includeFile("yavin4/spined_puc.lua")
includeFile("yavin4/stintaril_fleshripper.lua")
includeFile("yavin4/stintaril.lua")
includeFile("yavin4/stintaril_prowler.lua")
includeFile("yavin4/stintaril_ravager.lua")
includeFile("yavin4/stintaril_scavenger.lua")
includeFile("yavin4/stranded_imperial_officer.lua")
includeFile("yavin4/stranded_imperial_pilot.lua")
includeFile("yavin4/stranded_imperial_soldier.lua")
includeFile("yavin4/stranded_rebel_officer.lua")
includeFile("yavin4/stranded_rebel_pilot.lua")
includeFile("yavin4/stranded_rebel_soldier.lua")
includeFile("yavin4/stunted_woolamander.lua")
includeFile("yavin4/swarming_kliknik.lua")
includeFile("yavin4/tanc_mite.lua")
includeFile("yavin4/tanc_mite_warrior.lua")
includeFile("yavin4/tybis_be.lua")
includeFile("yavin4/tybis.lua")
includeFile("yavin4/tybis_youth.lua")
includeFile("yavin4/vraker_orde.lua")
includeFile("yavin4/yith_seenath.lua")
|
includeFile("yavin4/acklay.lua")
includeFile("yavin4/alert_droideka.lua")
includeFile("yavin4/ancient_mamien.lua")
includeFile("yavin4/angler_be.lua")
includeFile("yavin4/angler_hatchling.lua")
includeFile("yavin4/angler.lua")
includeFile("yavin4/angler_recluse.lua")
includeFile("yavin4/biogenic_assistant.lua")
includeFile("yavin4/biogenic_construction.lua")
includeFile("yavin4/biogenic_crazyguy.lua")
includeFile("yavin4/biogenic_engineertech.lua")
includeFile("yavin4/biogenic_scientist_generic_01.lua")
includeFile("yavin4/biogenic_scientist_generic_02.lua")
includeFile("yavin4/biogenic_scientist_geonosian.lua")
includeFile("yavin4/biogenic_scientist_human.lua")
includeFile("yavin4/biogenic_securitytech.lua")
includeFile("yavin4/blood_fanged_gackle_bat.lua")
includeFile("yavin4/bone_angler.lua")
includeFile("yavin4/captain_eso.lua")
includeFile("yavin4/choku_be.lua")
includeFile("yavin4/choku_female.lua")
includeFile("yavin4/choku_hunter.lua")
includeFile("yavin4/choku.lua")
includeFile("yavin4/choku_male.lua")
includeFile("yavin4/choku_packmaster.lua")
includeFile("yavin4/choku_pup.lua")
includeFile("yavin4/crazed_geonosian_guard.lua")
includeFile("yavin4/crystal_snake.lua")
includeFile("yavin4/cx_425.lua")
includeFile("yavin4/deadly_tanc_mite.lua")
includeFile("yavin4/drenn_zebber.lua")
includeFile("yavin4/elder_mamien.lua")
includeFile("yavin4/enhanced_force_kliknik.lua")
includeFile("yavin4/enhanced_gaping_spider.lua")
includeFile("yavin4/enhanced_kliknik.lua")
includeFile("yavin4/enhanced_kwi.lua")
includeFile("yavin4/enraged_tybis.lua")
includeFile("yavin4/female_mamien.lua")
includeFile("yavin4/female_mawgax.lua")
includeFile("yavin4/female_tybis.lua")
includeFile("yavin4/feral_mutant_gackle_stalker.lua")
includeFile("yavin4/frenzied_choku.lua")
includeFile("yavin4/gackle_bat_hunter.lua")
includeFile("yavin4/gackle_bat.lua")
includeFile("yavin4/gackle_bat_myrmidon_lord.lua")
includeFile("yavin4/geonosian_scientist.lua")
includeFile("yavin4/geonosian_technical_assistant.lua")
includeFile("yavin4/geonosian_worker.lua")
includeFile("yavin4/giant_angler.lua")
includeFile("yavin4/giant_crystal_snake.lua")
includeFile("yavin4/giant_gackle_bat.lua")
includeFile("yavin4/giant_mawgax.lua")
includeFile("yavin4/giant_spined_puc.lua")
includeFile("yavin4/giant_stintaril.lua")
includeFile("yavin4/giant_tanc_mite.lua")
includeFile("yavin4/gins_darone.lua")
includeFile("yavin4/grand_tybis.lua")
includeFile("yavin4/hooded_crystal_snake.lua")
includeFile("yavin4/hutt_expeditionary_force_surveyor.lua")
includeFile("yavin4/hutt_expeditonary_force_leader.lua")
includeFile("yavin4/hutt_expeditonary_force_member.lua")
includeFile("yavin4/imperial_observer.lua")
includeFile("yavin4/jazeen_thurmm.lua")
includeFile("yavin4/kai_tok_bloodreaver.lua")
includeFile("yavin4/kai_tok_prowler.lua")
includeFile("yavin4/kai_tok_scavenger.lua")
includeFile("yavin4/kai_tok_slayer.lua")
includeFile("yavin4/kliknik_be.lua")
includeFile("yavin4/kliknik_dark_defender.lua")
includeFile("yavin4/kliknik_dark_hunter.lua")
includeFile("yavin4/kliknik_dark_queen.lua")
includeFile("yavin4/kliknik_dark_warrior.lua")
includeFile("yavin4/kliknik_dark_worker.lua")
includeFile("yavin4/kliknik_defender.lua")
includeFile("yavin4/kliknik_hatchling.lua")
includeFile("yavin4/kliknik_hunter.lua")
includeFile("yavin4/kliknik.lua")
includeFile("yavin4/kliknik_mantis.lua")
includeFile("yavin4/kliknik_queen_harvester.lua")
includeFile("yavin4/kliknik_queen.lua")
includeFile("yavin4/kliknik_scout.lua")
includeFile("yavin4/kliknik_shredder_guardian.lua")
includeFile("yavin4/kliknik_warrior.lua")
includeFile("yavin4/kliknik_worker.lua")
includeFile("yavin4/lurking_angler.lua")
includeFile("yavin4/mad_angler.lua")
includeFile("yavin4/majestic_whisper_bird.lua")
includeFile("yavin4/male_mamien.lua")
includeFile("yavin4/male_mawgax.lua")
includeFile("yavin4/male_tybis.lua")
includeFile("yavin4/mamien_jungle_lord.lua")
includeFile("yavin4/mamien_matriarch.lua")
includeFile("yavin4/mamien_youth.lua")
includeFile("yavin4/mawgax_be.lua")
includeFile("yavin4/mawgax_raptor.lua")
includeFile("yavin4/mawgax_youth.lua")
includeFile("yavin4/megan_drlar.lua")
includeFile("yavin4/mercenary_sentry.lua")
includeFile("yavin4/ominous_skreeg.lua")
includeFile("yavin4/poisonous_spined_puc.lua")
includeFile("yavin4/puny_gackle_bat.lua")
includeFile("yavin4/puny_stintaril.lua")
includeFile("yavin4/puny_tanc_mite.lua")
includeFile("yavin4/ravaging_gackle_bat.lua")
includeFile("yavin4/skreeg_adolescent.lua")
includeFile("yavin4/skreeg_female.lua")
includeFile("yavin4/skreeg_gatherer.lua")
includeFile("yavin4/skreeg_hunter.lua")
includeFile("yavin4/skreeg_infant.lua")
includeFile("yavin4/skreeg_male.lua")
includeFile("yavin4/skreeg_scout.lua")
includeFile("yavin4/skreeg_warrior_elite.lua")
includeFile("yavin4/skreeg_warrior.lua")
includeFile("yavin4/spined_puc.lua")
includeFile("yavin4/stintaril_fleshripper.lua")
includeFile("yavin4/stintaril.lua")
includeFile("yavin4/stintaril_prowler.lua")
includeFile("yavin4/stintaril_ravager.lua")
includeFile("yavin4/stintaril_scavenger.lua")
includeFile("yavin4/stranded_imperial_officer.lua")
includeFile("yavin4/stranded_imperial_pilot.lua")
includeFile("yavin4/stranded_imperial_soldier.lua")
includeFile("yavin4/stranded_rebel_officer.lua")
includeFile("yavin4/stranded_rebel_pilot.lua")
includeFile("yavin4/stranded_rebel_soldier.lua")
includeFile("yavin4/stunted_woolamander.lua")
includeFile("yavin4/swarming_kliknik.lua")
includeFile("yavin4/tanc_mite.lua")
includeFile("yavin4/tanc_mite_warrior.lua")
includeFile("yavin4/theme_park_rebel_supervisor.lua")
includeFile("yavin4/tybis_be.lua")
includeFile("yavin4/tybis.lua")
includeFile("yavin4/tybis_youth.lua")
includeFile("yavin4/vraker_orde.lua")
includeFile("yavin4/yith_seenath.lua")
|
(unstable) [fixed] luke mission 1.
|
(unstable) [fixed] luke mission 1.
git-svn-id: e4cf3396f21da4a5d638eecf7e3b4dd52b27f938@5957 c3d1530f-68f5-4bd0-87dc-8ef779617e40
|
Lua
|
agpl-3.0
|
lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/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,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo
|
060e6795a9720bee08bc03c6ef11fe4fc2556175
|
MMOCoreORB/bin/scripts/mobile/corellia/tabage_scavenger.lua
|
MMOCoreORB/bin/scripts/mobile/corellia/tabage_scavenger.lua
|
tabage_scavenger = Creature:new {
objectName = "@mob/creature_names:tabage_scavenger",
socialGroup = "tabage",
pvpFaction = "",
faction = "",
level = 14,
chanceHit = 0.3,
damageMin = 140,
damageMax = 150,
baseXp = 714,
baseHAM = 1500,
baseHAMmax = 1900,
armor = 0,
resists = {10,10,0,0,0,0,0,-1,-1},
meatType = "",
meatAmount = 0,
hideType = "",
hideAmount = 0,
boneType = "",
boneAmount = 0,
milk = 0,
tamingChance = 0.25,
ferocity = 0,
pvpBitmask = AGGRESSIVE + ATTACKABLE + ENEMY,
creatureBitmask = PACK + HERD + STALKER,
optionsBitmask = 128,
diet = CARNIVORE,
templates = {"object/mobile/tabage.iff"},
lootGroups = {},
weapons = {},
conversationTemplate = "",
attacks = {
{"stunattack","stunChance=50"}
}
}
CreatureTemplates:addCreatureTemplate(tabage_scavenger, "tabage_scavenger")
|
tabage_scavenger = Creature:new {
objectName = "@mob/creature_names:tabage_scavenger",
socialGroup = "tabage",
pvpFaction = "",
faction = "",
level = 14,
chanceHit = 0.3,
damageMin = 140,
damageMax = 150,
baseXp = 714,
baseHAM = 1500,
baseHAMmax = 1900,
armor = 0,
resists = {10,10,0,0,0,0,0,-1,-1},
meatType = "meat_carnivore",
meatAmount = 18,
hideType = "hide_bristley",
hideAmount = 24,
boneType = "bone_mammal",
boneAmount = 7,
milk = 0,
tamingChance = 0.25,
ferocity = 0,
pvpBitmask = AGGRESSIVE + ATTACKABLE + ENEMY,
creatureBitmask = PACK + HERD + STALKER,
optionsBitmask = 128,
diet = CARNIVORE,
templates = {"object/mobile/tabage.iff"},
lootGroups = {},
weapons = {},
conversationTemplate = "",
attacks = {
{"stunattack","stunChance=50"}
}
}
CreatureTemplates:addCreatureTemplate(tabage_scavenger, "tabage_scavenger")
|
[fixed] mantis 4304 added meat/hide/bone resources to tabage scavenger
|
[fixed] mantis 4304 added meat/hide/bone resources to tabage scavenger
Change-Id: If0ddf269507bf9eb3164b4dfbb93ef5615558773
|
Lua
|
agpl-3.0
|
Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/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,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo
|
d50da4c1f8a4f765b1af411596bb74da96bd0dd0
|
lua/job.lua
|
lua/job.lua
|
local _M = {
_VERSION = "1.9.0"
}
local lock = require "resty.lock"
local shdict = require "shdict"
local JOBS = shdict.new("jobs")
local ipairs = ipairs
local update_time = ngx.update_time
local ngx_now = ngx.now
local worker_exiting = ngx.worker.exiting
local timer_at = ngx.timer.at
local ngx_log = ngx.log
local INFO, ERR, WARN, DEBUG = ngx.INFO, ngx.ERR, ngx.WARN, ngx.DEBUG
local xpcall, setmetatable = xpcall, setmetatable
local worker_pid = ngx.worker.pid
local tinsert = table.insert
local assert = assert
local random = math.random
local workers = ngx.worker.count()
local function now()
update_time()
return ngx_now()
end
local main
local function make_key(self, key)
return self.key .. "$" .. key
end
local function set_next_time(self, interval)
local next_time = now() + (interval or self.interval)
JOBS:set(make_key(self, "next"), next_time)
return next_time
end
local function get_next_time(self)
local next_time = JOBS:get(make_key(self, "next"))
if not next_time then
next_time = now()
JOBS:set(make_key(self, "next"), next_time)
end
return next_time
end
--- @param #Job self
local function run_job(self, delay, ...)
if worker_exiting() then
return self:finish(...)
end
local ok, err = timer_at(delay, main, self, ...)
if not ok then
ngx_log(ERR, self.key .. " failed to add timer: ", err)
self:stop()
self:clean()
return false
end
return true
end
local function wait_others(self)
local wait_others = self.wait_others
for i=1,#wait_others
do
if not wait_others[i]:completed(true) then
return false
end
end
self.wait_others = {}
return true
end
main = function(premature, self, ...)
if premature or not self:running() then
return self:finish(...)
end
if not wait_others(self) then
return run_job(self, 1, ...)
end
local remains = self.mutex:lock(make_key(self, "mtx"))
if not remains then
return run_job(self, 0.2, ...)
end
if self:suspended() then
self.mutex:unlock()
return run_job(self, 1, ...)
end
if not self:running() then
self.mutex:unlock()
return self:finish(...)
end
local next_time = get_next_time(self)
if now() >= next_time then
local counter = JOBS:incr(make_key(self, "counter"), 1, -1)
local ok, err = xpcall(self.callback, function(err)
ngx.log(ngx.ERR, debug.traceback())
return err
end, { counter = counter, hup = self.pid == nil }, ...)
if not self.pid then
self.pid = worker_pid()
end
if not ok then
ngx_log(WARN, "job ", self.key, ": ", err)
end
local new_next_time = get_next_time(self)
if new_next_time == next_time then
next_time = set_next_time(self)
else
-- next time changed from outside
next_time = new_next_time
end
end
local delay = next_time - now() + random(0, workers - 1) / 10
run_job(self, delay, ...)
self.mutex:unlock()
end
--- @type Job
local job = {}
-- public api
--- @return #Job
function _M.new(name, callback, interval, finish)
local j = {
callback = callback,
finish_fn = finish,
interval = interval,
key = name,
wait_others = {},
pid = nil,
cached = {},
mutex = lock:new("jobs", { timeout = 0.2, exptime = 600, step = 0.2 })
}
return setmetatable(j, { __index = job })
end
--- @param #Job self
function job:run(...)
if not self:completed(true) then
if not self:running(true) then
ngx_log(INFO, "job ", self.key, " start")
JOBS:set(make_key(self, "running"), 1)
end
self:running(true)
return assert(run_job(self, 0, ...))
end
ngx_log(DEBUG, "job ", self.key, " already completed")
return nil, "completed"
end
--- @param #Job self
function job:set_next(interval)
return set_next_time(self, interval)
end
--- @param #Job self
function job:suspend()
if not self:suspended() then
ngx_log(INFO, "job ", self.key, " suspended")
JOBS:set(make_key(self, "suspended"), 1)
end
end
--- @param #Job self
function job:resume()
if self:suspended() then
ngx_log(INFO, "job ", self.key, " resumed")
JOBS:delete(make_key(self, "suspended"))
end
end
--- @param #Job self
function job:stop()
JOBS:delete(make_key(self, "running"))
JOBS:set(make_key(self, "completed"), 1)
ngx_log(INFO, "job ", self.key, " stopped")
end
local function check_cached(self, flag, nocache)
local sec = now()
local c = self.cached[flag]
if not c or nocache or sec - c.last > 1 then
if not c then
c = {}
self.cached[flag] = c
end
c.b = JOBS:get(make_key(self, flag)) == 1
c.last = sec
end
return c.b
end
--- @param #Job self
function job:completed(nocache)
return check_cached(self, "completed", nocache)
end
--- @param #Job self
function job:running(nocache)
return check_cached(self, "running", nocache)
end
--- @param #Job self
function job:suspended(nocache)
return check_cached(self, "suspended", nocache)
end
--- @param #Job self
function job:finish(...)
if self.finish_fn then
self.finish_fn(...)
end
return true
end
--- @param #Job self
function job:wait_for(other)
tinsert(self.wait_others, other)
end
--- @param #Job self
function job:clean()
if not self:running(true) then
JOBS:delete(make_key(self, "running"))
JOBS:delete(make_key(self, "completed"))
JOBS:delete(make_key(self, "suspended"))
return true
end
return false
end
return _M
|
local _M = {
_VERSION = "2.2.1"
}
local lock = require "resty.lock"
local shdict = require "shdict"
local JOBS = shdict.new("jobs")
local ipairs = ipairs
local update_time = ngx.update_time
local ngx_now = ngx.now
local worker_exiting = ngx.worker.exiting
local timer_at = ngx.timer.at
local ngx_log = ngx.log
local INFO, ERR, WARN, DEBUG = ngx.INFO, ngx.ERR, ngx.WARN, ngx.DEBUG
local xpcall, setmetatable = xpcall, setmetatable
local worker_pid = ngx.worker.pid
local tinsert = table.insert
local assert = assert
local random = math.random
local workers = ngx.worker.count()
local function now()
update_time()
return ngx_now()
end
local main
local function make_key(self, key)
return self.key .. "$" .. key
end
local function set_next_time(self, interval)
local next_time = now() + (interval or self.interval)
JOBS:set(make_key(self, "next"), next_time)
return next_time
end
local function get_next_time(self)
local next_time = JOBS:get(make_key(self, "next"))
if not next_time then
next_time = now()
JOBS:set(make_key(self, "next"), next_time)
end
return next_time
end
--- @param #Job self
local function run_job(self, delay, ...)
if worker_exiting() then
return self:finish(...)
end
local ok, err = timer_at(delay, main, self, ...)
if not ok then
ngx_log(ERR, self.key .. " failed to add timer: ", err)
self:stop()
self:clean()
return false
end
return true
end
local function wait_others(self)
local wait_others = self.wait_others
for i=1,#wait_others
do
if not wait_others[i]:completed(true) then
return false
end
end
self.wait_others = {}
return true
end
main = function(premature, self, ...)
if premature or not self:running() then
return self:finish(...)
end
if not wait_others(self) then
return run_job(self, 1, ...)
end
local remains = self.mutex:lock(make_key(self, "mtx"))
if not remains then
return run_job(self, 0.2, ...)
end
if self:suspended() then
self.mutex:unlock()
return run_job(self, 1, ...)
end
if not self:running() then
self.mutex:unlock()
return self:finish(...)
end
local next_time = get_next_time(self)
if now() >= next_time then
local counter = JOBS:incr(make_key(self, "counter"), 1, -1)
local ok, err = xpcall(self.callback, function(err)
ngx.log(ngx.ERR, debug.traceback())
return err
end, { counter = counter, hup = self.pid == nil }, ...)
if not self.pid then
self.pid = worker_pid()
end
if not ok then
ngx_log(WARN, "job ", self.key, ": ", err)
end
local new_next_time = get_next_time(self)
if new_next_time == next_time then
next_time = set_next_time(self)
else
-- next time changed from outside
next_time = new_next_time
end
end
local delay = next_time - now() + random(0, workers - 1) / 10
run_job(self, delay, ...)
self.mutex:unlock()
end
--- @type Job
local job = {}
-- public api
--- @return #Job
function _M.new(name, callback, interval, finish)
local j = {
callback = callback,
finish_fn = finish,
interval = interval,
key = name,
wait_others = {},
pid = nil,
cached = {},
mutex = lock:new("jobs", { timeout = 0.2, exptime = 600, step = 0.2 })
}
return setmetatable(j, { __index = job })
end
--- @param #Job self
function job:run(...)
if not self:completed(true) then
if not self:running(true) then
ngx_log(INFO, "job ", self.key, " start")
JOBS:set(make_key(self, "running"), 1)
end
self:running(true)
return assert(run_job(self, 0, ...))
end
ngx_log(DEBUG, "job ", self.key, " already completed")
return nil, "completed"
end
--- @param #Job self
function job:set_next(interval)
return set_next_time(self, interval)
end
--- @param #Job self
function job:suspend()
if not self:suspended() then
ngx_log(INFO, "job ", self.key, " suspended")
JOBS:set(make_key(self, "suspended"), 1)
end
end
--- @param #Job self
function job:resume()
if self:suspended() then
ngx_log(INFO, "job ", self.key, " resumed")
JOBS:delete(make_key(self, "suspended"))
end
end
--- @param #Job self
function job:stop()
JOBS:delete(make_key(self, "running"))
JOBS:set(make_key(self, "completed"), 1)
ngx_log(INFO, "job ", self.key, " stopped")
end
local function check_cached(self, flag, nocache)
local sec = now()
local c = self.cached[flag]
if not c or nocache or sec - c.last > 1 then
if not c then
c = {}
self.cached[flag] = c
end
c.b = JOBS:get(make_key(self, flag)) == 1
c.last = sec
end
return c.b
end
--- @param #Job self
function job:completed(nocache)
return check_cached(self, "completed", nocache)
end
--- @param #Job self
function job:running(nocache)
return check_cached(self, "running", nocache)
end
--- @param #Job self
function job:suspended(nocache)
return check_cached(self, "suspended", nocache)
end
--- @param #Job self
function job:finish(...)
if self.finish_fn then
self.finish_fn(...)
end
return true
end
--- @param #Job self
function job:wait_for(other)
tinsert(self.wait_others, other)
end
--- @param #Job self
function job:clean()
local retval = self:running(true)
JOBS:delete(make_key(self, "running"))
JOBS:delete(make_key(self, "completed"))
JOBS:delete(make_key(self, "suspended"))
return retval
end
return _M
|
fix job clean method
|
fix job clean method
|
Lua
|
bsd-2-clause
|
ZigzagAK/nginx-resty-auto-healthcheck-config,ZigzagAK/nginx-resty-auto-healthcheck-config
|
25d37c999394d1ad69e6c43e996d5ae372de98c6
|
rbm-grads.lua
|
rbm-grads.lua
|
grads = {}
ProFi = require('ProFi')
-- Calculate generative weights
-- tcwx is tcwx = torch.mm( x,rbm.W:t() ):add( rbm.c:t() )
function grads.generative(rbm,x,y,tcwx,chx,chy)
local visx_rnd, visy_rnd, h0, h0_rnd,ch_idx
h0 = sigm( torch.add(tcwx, torch.mm(y,rbm.U:t() ) ) ) -- UP
if rbm.traintype == 0 then -- CD
h0_rnd = sampler(h0,rbm.rand) -- use training data as start
else
-- use pcd chains as start
ch_idx = math.floor( (torch.rand(1) * rbm.npcdchains)[1]) +1
h0_rnd = sampler( rbmup(rbm, chx[ch_idx]:resize(1,x:size(2)), chy[ch_idx]:resize(1,y:size(2))), rbm.rand)
end
for i = 1, (rbm.cdn - 1) do
visx_rnd = sampler( rbmdownx( rbm, h0_rnd ), rbm.rand)
visy_rnd = samplevec( rbmdowny( rbm, h0_rnd), rbm.rand)
hid_rnd = sampler( rbmup(rbm,visx_rnd, visy_rnd), rbm.rand)
end
local vkx = rbmdownx(rbm,h0_rnd) -- DOWN
local vkx_rnd = sampler(vkx,rbm.rand) -- |
local vky = rbmdowny(rbm,h0_rnd) -- |
local vky = samplevec(vky,rbm.rand); -- |
local hk = rbmup(rbm,vkx_rnd,vky) -- UP
-- Calculate generative gradients
local dW = torch.mm(h0:t(),x) :add(-torch.mm(hk:t(),vkx_rnd))
local dU = torch.mm(h0:t(),y):add(-torch.mm(hk:t(),vky))
local db = torch.add(x, -vkx_rnd):t()
local dc = torch.add(h0, -hk ):t()
local dd = torch.add(y, -vky):t()
return dW, dU, db, dc ,dd, vkx
end
-- Calculate discriminative weights
-- tcwx is tcwx = torch.mm( x,rbm.W:t() ):add( rbm.c:t() )
function grads.discriminative(rbm,x,y,tcwx)
-- local F = torch.add(rbm.U, tcwx:repeatTensor(rbm.U:size(2),1):t() );
-- local F_soft = softplus(F)
-- local p_y_given_x_log_prob = torch.add(F_soft:sum(1), rbm.d)
-- local p_y_given_x_not_norm = torch.add(p_y_given_x_log_prob, -torch.max(p_y_given_x_log_prob) ):exp()
-- local p_y_given_x = torch.mul(p_y_given_x_not_norm, (1/p_y_given_x_not_norm:sum()))
local p_y_given_x, F = pygivenx(rbm,x,tcwx)
local F_sigm = sigm(F)
--local F_sigm_prob = torch.cmul( F_sigm, p_y_given_x:repeatTensor(rbm.U:size(1),1) )
local F_sigm_prob = torch.cmul( F_sigm, torch.mm( rbm.hidden_by_one,p_y_given_x ) )
local F_sigm_prob_sum = F_sigm_prob:sum(2)
local F_sigm_dy = torch.mm(F_sigm, y:t())
local dW = torch.add( torch.mm(F_sigm_dy, x), -torch.mm(F_sigm_prob_sum,x) )
local dU = torch.add( -F_sigm_prob, torch.cmul(F_sigm, torch.mm( torch.ones(F_sigm_prob:size(1),1),y ) ) )
local dc = torch.add(-F_sigm_prob_sum, F_sigm_dy)
local dd = torch.add(y, -p_y_given_x):t()
return dW, dU, dc, dd,p_y_given_x
end
function grads.calculategrads(rbm,x_tr,y_tr,x_semi)
local dW_gen, dU_gen, db_gen, dc_gen, dd_gen, vkx
local dW_dis, dU_dis, dc_dis, dd_dis, p_y_given_x
local dW_semi, dU_semi,db_semi, dc_semi, dd_semi, y_semi
local tcwx = torch.mm( x_tr,rbm.W:t() ):add( rbm.c:t() ) -- precalc tcwx
-- reset accumulators
rbm.dW:fill(0)
rbm.dU:fill(0)
rbm.db:fill(0)
rbm.dc:fill(0)
rbm.dd:fill(0)
-- GENERATIVE GRADS
if rbm.alpha > 0 then
dW_gen, dU_gen, db_gen, dc_gen, dd_gen, vkx = grads.generative(rbm,x_tr,y_tr,tcwx,rbm.chx,rbm.chy)
rbm.dW:add( dW_gen:mul( rbm.alpha ))
rbm.dU:add( dU_gen:mul( rbm.alpha ))
rbm.db:add( db_gen:mul( rbm.alpha ))
rbm.dc:add( dc_gen:mul( rbm.alpha ))
rbm.dd:add( dd_gen:mul( rbm.alpha ))
rbm.cur_err:add( torch.sum(torch.add(x_tr,-vkx):pow(2)) )
end
-- DISCRIMINATIVE GRADS
if rbm.alpha < 1 then
dW_dis, dU_dis, dc_dis, dd_dis, p_y_given_x = grads.discriminative(rbm,x_tr,y_tr,tcwx)
rbm.dW:add( dW_dis:mul( 1-rbm.alpha ))
rbm.dU:add( dU_dis:mul( 1-rbm.alpha ))
rbm.dc:add( dc_dis:mul( 1-rbm.alpha ))
rbm.dd:add( dd_dis:mul( 1-rbm.alpha ))
end
-- SEMISUPERVISED GRADS
if rbm.beta > 0 then
p_y_given_x = p_y_given_x or pygivenx(rbm,x_tr,tcwx)
y_semi = samplevec(p_y_given_x,rbm.rand):resize(1,rbm.n_classes)
dW_semi, dU_semi,db_semi, dc_semi, dd_semi = grads.generative(rbm,x_semi,y_semi,tcwx,rbm.chx_semisup,rbm.chy_semisup)
rbm.dW:add( dW_semi:mul( rbm.beta ))
rbm.dU:add( dU_semi:mul( rbm.beta ))
rbm.db:add( db_semi:mul( rbm.beta ))
rbm.dc:add( dc_semi:mul( rbm.beta ))
rbm.dd:add( dd_semi:mul( rbm.beta ))
end
end
|
grads = {}
ProFi = require('ProFi')
-- Calculate generative weights
-- tcwx is tcwx = torch.mm( x,rbm.W:t() ):add( rbm.c:t() )
function grads.generative(rbm,x,y,tcwx,chx,chy)
local visx_rnd, visy_rnd, h0, h0_rnd,ch_idx
h0 = sigm( torch.add(tcwx, torch.mm(y,rbm.U:t() ) ) ) -- UP
-- Switch between CD and PCD
if rbm.traintype == 0 then -- CD
-- Use training data as start for negative statistics
h0_rnd = sampler(h0,rbm.rand) -- use training data as start
else
-- use pcd chains as start for negative statistics
ch_idx = math.floor( (torch.rand(1) * rbm.npcdchains)[1]) +1
h0_rnd = sampler( rbmup(rbm, chx[ch_idx]:resize(1,x:size(2)), chy[ch_idx]:resize(1,y:size(2))), rbm.rand)
end
-- If CDn > 1 update chians n-1 times
for i = 1, (rbm.cdn - 1) do
visx_rnd = sampler( rbmdownx( rbm, h0_rnd ), rbm.rand)
visy_rnd = samplevec( rbmdowny( rbm, h0_rnd), rbm.rand)
hid_rnd = sampler( rbmup(rbm,visx_rnd, visy_rnd), rbm.rand)
end
-- Down-Up dont sample hiddens, because it introduces noise
local vkx = rbmdownx(rbm,h0_rnd)
local vkx_rnd = sampler(vkx,rbm.rand)
local vky_rnd = samplevec( rbmdowny(rbm,h0_rnd), rbm.rand)
local hk = rbmup(rbm,vkx_rnd,vky_rnd)
-- If PCD: Update status of selected PCD chains
if rbm.traintype == 1 then
chx[{ ch_idx,{} }] = vkx_rnd
chy[{ ch_idx,{} }] = vky_rnd
end
-- Calculate generative gradients
local dW = torch.mm(h0:t(),x) :add(-torch.mm(hk:t(),vkx_rnd))
local dU = torch.mm(h0:t(),y):add(-torch.mm(hk:t(),vky_rnd))
local db = torch.add(x, -vkx_rnd):t()
local dc = torch.add(h0, -hk ):t()
local dd = torch.add(y, -vky_rnd):t()
return dW, dU, db, dc ,dd, vkx
end
-- Calculate discriminative weights
-- tcwx is tcwx = torch.mm( x,rbm.W:t() ):add( rbm.c:t() )
function grads.discriminative(rbm,x,y,tcwx)
-- hidden are act_hid = sigm(x*W'+ c' + y*U)
local p_y_given_x, F = grads.pygivenx(rbm,x,tcwx)
local F_sigm = sigm(F)
--local F_sigm_prob = torch.cmul( F_sigm, p_y_given_x:repeatTensor(rbm.U:size(1),1) )
local F_sigm_prob = torch.cmul( F_sigm, torch.mm( rbm.hidden_by_one,p_y_given_x ) )
local F_sigm_prob_sum = F_sigm_prob:sum(2)
local F_sigm_dy = torch.mm(F_sigm, y:t())
local dW = torch.add( torch.mm(F_sigm_dy, x), -torch.mm(F_sigm_prob_sum,x) )
local dU = torch.add( -F_sigm_prob, torch.cmul(F_sigm, torch.mm( torch.ones(F_sigm_prob:size(1),1),y ) ) )
local dc = torch.add(-F_sigm_prob_sum, F_sigm_dy)
local dd = torch.add(y, -p_y_given_x):t()
return dW, dU, dc, dd,p_y_given_x
end
function grads.pygivenx(rbm,x,tcwx_pre_calc)
-- hidden are act_hid = sigm(x*W'+ c' + y*U)
-- F is [hidden X classes]
local tcwx,F,pyx
tcwx_pre_calc = tcwx_pre_calc or torch.mm( x,rbm.W:t() ):add( rbm.c:t() )
F = torch.add( rbm.U, torch.mm(tcwx_pre_calc:t(), rbm.one_by_classes) )
pyx = softplus(F):sum(1) -- p(y|x) logprob
pyx:add(-torch.max(pyx)) -- divide by max, log domain
pyx:exp() -- p(y|x) unnormalized prob -- convert to real domain
pyx:mul( ( 1/pyx:sum() )) -- normalize probabilities
-- OLD CODE
--local p_y_given_x_log_prob = softplus(F):sum(1) --log prob
--local p_y_given_x_not_norm = torch.add(p_y_given_x_log_prob, -torch.max(p_y_given_x_log_prob) ):exp()
--local p_y_given_x = torch.mul(p_y_given_x_not_norm, (1/p_y_given_x_not_norm:sum()))
return pyx,F
end
function grads.calculategrads(rbm,x_tr,y_tr,x_semi)
local dW_gen, dU_gen, db_gen, dc_gen, dd_gen, vkx
local dW_dis, dU_dis, dc_dis, dd_dis, p_y_given_x
local dW_semi, dU_semi,db_semi, dc_semi, dd_semi, y_semi
local tcwx = torch.mm( x_tr,rbm.W:t() ):add( rbm.c:t() ) -- precalc tcwx
-- reset accumulators
rbm.dW:fill(0)
rbm.dU:fill(0)
rbm.db:fill(0)
rbm.dc:fill(0)
rbm.dd:fill(0)
-- GENERATIVE GRADS
if rbm.alpha > 0 then
dW_gen, dU_gen, db_gen, dc_gen, dd_gen, vkx = grads.generative(rbm,x_tr,y_tr,tcwx,rbm.chx,rbm.chy)
rbm.dW:add( dW_gen:mul( rbm.alpha ))
rbm.dU:add( dU_gen:mul( rbm.alpha ))
rbm.db:add( db_gen:mul( rbm.alpha ))
rbm.dc:add( dc_gen:mul( rbm.alpha ))
rbm.dd:add( dd_gen:mul( rbm.alpha ))
rbm.cur_err:add( torch.sum(torch.add(x_tr,-vkx):pow(2)) )
end
-- DISCRIMINATIVE GRADS
if rbm.alpha < 1 then
dW_dis, dU_dis, dc_dis, dd_dis, p_y_given_x = grads.discriminative(rbm,x_tr,y_tr,tcwx)
rbm.dW:add( dW_dis:mul( 1-rbm.alpha ))
rbm.dU:add( dU_dis:mul( 1-rbm.alpha ))
rbm.dc:add( dc_dis:mul( 1-rbm.alpha ))
rbm.dd:add( dd_dis:mul( 1-rbm.alpha ))
end
-- SEMISUPERVISED GRADS
if rbm.beta > 0 then
grads.p_y_given_x = p_y_given_x or grads.pygivenx(rbm,x_tr,tcwx)
y_semi = samplevec(p_y_given_x,rbm.rand):resize(1,rbm.n_classes)
dW_semi, dU_semi,db_semi, dc_semi, dd_semi = grads.generative(rbm,x_semi,y_semi,tcwx,rbm.chx_semisup,rbm.chy_semisup)
rbm.dW:add( dW_semi:mul( rbm.beta ))
rbm.dU:add( dU_semi:mul( rbm.beta ))
rbm.db:add( db_semi:mul( rbm.beta ))
rbm.dc:add( dc_semi:mul( rbm.beta ))
rbm.dd:add( dd_semi:mul( rbm.beta ))
end
end
|
fix PCD chains not being updated
|
fix PCD chains not being updated
|
Lua
|
bsd-3-clause
|
elezar/rbm_toolbox_lua,skaae/rbm_toolbox_lua
|
2c8bab159831828d56054488e55a3874de92bb7f
|
mod_carbons/mod_carbons.lua
|
mod_carbons/mod_carbons.lua
|
-- XEP-0280: Message Carbons implementation for Prosody
-- Copyright (C) 2011 Kim Alvefur
--
-- This file is MIT/X11 licensed.
local st = require "util.stanza";
local jid_bare = require "util.jid".bare;
local xmlns_carbons = "urn:xmpp:carbons:1";
local xmlns_forward = "urn:xmpp:forward:0";
local host_sessions = hosts[module.host].sessions;
local full_sessions, bare_sessions = full_sessions, bare_sessions;
local function toggle_carbons(event)
local origin, stanza = event.origin, event.stanza;
if stanza.attr.type == "set" then
local state = stanza.tags[1].name;
module:log("debug", "%s %sd carbons", origin.full_jid, state);
origin.want_carbons = state == "enable";
origin.send(st.reply(stanza));
return true
end
end
module:hook("iq/self/"..xmlns_carbons..":disable", toggle_carbons);
module:hook("iq/self/"..xmlns_carbons..":enable", toggle_carbons);
local function message_handler(event, c2s)
local origin, stanza = event.origin, event.stanza;
local orig_type = stanza.attr.type;
local orig_to = stanza.attr.to;
if not (orig_type == nil
or orig_type == "normal"
or orig_type == "chat") then
return -- No carbons for messages of type error or headline
end
-- Stanza sent by a local client
local bare_jid = origin.username .. "@" .. origin.host;
local target_session = origin;
local top_priority = false;
local user_sessions = host_sessions[origin.username];
-- Stanza about to be delivered to a local client
if not c2s then
bare_jid = jid_bare(orig_to);
target_session = full_sessions[orig_to]
user_sessions = bare_sessions[bare_jid];
if not target_session and user_sessions then
-- The top resources will already receive this message per normal routing rules,
-- so we are going to skip them in order to avoid sending duplicated messages.
local top_resources = user_sessions.top_resources;
top_priority = top_resources and top_resources[1].priority
end
end
if not user_sessions then
module:log("debug", "Skip carbons for offline user");
return -- No use in sending carbons to an offline user
end
if not c2s and stanza:get_child("private", xmlns_carbons) then
stanza:maptags(function(tag)
return tag.attr.xmlns == xmlns_carbons
and tag.name == "private" and tag or nil;
end);
module:log("debug", "Message tagged private, ignoring");
return
end
-- Create the carbon copy and wrap it as per the Stanza Forwarding XEP
local copy = st.clone(stanza);
copy.attr.xmlns = "jabber:client";
local carbon = st.message{ from = bare_jid, type = orig_type, }
:tag(c2s and "sent" or "received", { xmlns = xmlns_carbons }):up()
:tag("forwarded", { xmlns = xmlns_forward })
:add_child(copy):reset();
user_sessions = user_sessions and user_sessions.sessions;
for _, session in pairs(user_sessions) do
-- Carbons are sent to resources that have enabled it
if session.want_carbons
-- but not the resource that sent the message, or the one that it's directed to
and session ~= target_session
-- and isn't among the top resources that would receive the message per standard routing rules
and (not c2s or session.priority ~= top_priority) then
carbon.attr.to = session.full_jid;
module:log("debug", "Sending carbon to %s", session.full_jid);
session.send(carbon);
end
end
end
local function c2s_message_handler(event)
return message_handler(event, true)
end
-- Stanzas sent by local clients
module:hook("pre-message/bare", c2s_message_handler, 1);
module:hook("pre-message/full", c2s_message_handler, 1);
-- Stanzas to local clients
module:hook("message/bare", message_handler, 1);
module:hook("message/full", message_handler, 1);
module:add_feature(xmlns_carbons);
|
-- XEP-0280: Message Carbons implementation for Prosody
-- Copyright (C) 2011 Kim Alvefur
--
-- This file is MIT/X11 licensed.
local st = require "util.stanza";
local jid_bare = require "util.jid".bare;
local xmlns_carbons = "urn:xmpp:carbons:1";
local xmlns_forward = "urn:xmpp:forward:0";
local host_sessions = hosts[module.host].sessions;
local full_sessions, bare_sessions = full_sessions, bare_sessions;
local function toggle_carbons(event)
local origin, stanza = event.origin, event.stanza;
if stanza.attr.type == "set" then
local state = stanza.tags[1].name;
module:log("debug", "%s %sd carbons", origin.full_jid, state);
origin.want_carbons = state == "enable";
origin.send(st.reply(stanza));
return true
end
end
module:hook("iq/self/"..xmlns_carbons..":disable", toggle_carbons);
module:hook("iq/self/"..xmlns_carbons..":enable", toggle_carbons);
local function message_handler(event, c2s)
local origin, stanza = event.origin, event.stanza;
local orig_type = stanza.attr.type;
local orig_from = stanza.attr.from;
local orig_to = stanza.attr.to;
if not (orig_type == nil
or orig_type == "normal"
or orig_type == "chat") then
return -- No carbons for messages of type error or headline
end
-- Stanza sent by a local client
local bare_jid = origin.type == "c2s" and origin.username .. "@" .. origin.host or jid_bare(orig_from);
local target_session = origin;
local top_priority = false;
local user_sessions = host_sessions[origin.username];
-- Stanza about to be delivered to a local client
if not c2s then
bare_jid = jid_bare(orig_to);
target_session = full_sessions[orig_to]
user_sessions = bare_sessions[bare_jid];
if not target_session and user_sessions then
-- The top resources will already receive this message per normal routing rules,
-- so we are going to skip them in order to avoid sending duplicated messages.
local top_resources = user_sessions.top_resources;
top_priority = top_resources and top_resources[1].priority
end
end
if not user_sessions then
module:log("debug", "Skip carbons for offline user");
return -- No use in sending carbons to an offline user
end
if not c2s and stanza:get_child("private", xmlns_carbons) then
stanza:maptags(function(tag)
return tag.attr.xmlns == xmlns_carbons
and tag.name == "private" and tag or nil;
end);
module:log("debug", "Message tagged private, ignoring");
return
end
-- Create the carbon copy and wrap it as per the Stanza Forwarding XEP
local copy = st.clone(stanza);
copy.attr.xmlns = "jabber:client";
local carbon = st.message{ from = bare_jid, type = orig_type, }
:tag(c2s and "sent" or "received", { xmlns = xmlns_carbons }):up()
:tag("forwarded", { xmlns = xmlns_forward })
:add_child(copy):reset();
user_sessions = user_sessions and user_sessions.sessions;
for _, session in pairs(user_sessions) do
-- Carbons are sent to resources that have enabled it
if session.want_carbons
-- but not the resource that sent the message, or the one that it's directed to
and session ~= target_session
-- and isn't among the top resources that would receive the message per standard routing rules
and (not c2s or session.priority ~= top_priority) then
carbon.attr.to = session.full_jid;
module:log("debug", "Sending carbon to %s", session.full_jid);
session.send(carbon);
end
end
end
local function c2s_message_handler(event)
return message_handler(event, true)
end
-- Stanzas sent by local clients
module:hook("pre-message/bare", c2s_message_handler, 1);
module:hook("pre-message/full", c2s_message_handler, 1);
-- Stanzas to local clients
module:hook("message/bare", message_handler, 1);
module:hook("message/full", message_handler, 1);
module:add_feature(xmlns_carbons);
|
mod_carbons: Fix handling of messages from remote hosts
|
mod_carbons: Fix handling of messages from remote hosts
|
Lua
|
mit
|
brahmi2/prosody-modules,dhotson/prosody-modules,crunchuser/prosody-modules,apung/prosody-modules,mmusial/prosody-modules,olax/prosody-modules,Craige/prosody-modules,vfedoroff/prosody-modules,guilhem/prosody-modules,cryptotoad/prosody-modules,olax/prosody-modules,vfedoroff/prosody-modules,obelisk21/prosody-modules,NSAKEY/prosody-modules,mardraze/prosody-modules,obelisk21/prosody-modules,jkprg/prosody-modules,1st8/prosody-modules,prosody-modules/import,softer/prosody-modules,Craige/prosody-modules,1st8/prosody-modules,dhotson/prosody-modules,BurmistrovJ/prosody-modules,softer/prosody-modules,NSAKEY/prosody-modules,iamliqiang/prosody-modules,syntafin/prosody-modules,stephen322/prosody-modules,amenophis1er/prosody-modules,jkprg/prosody-modules,mardraze/prosody-modules,heysion/prosody-modules,apung/prosody-modules,asdofindia/prosody-modules,jkprg/prosody-modules,vfedoroff/prosody-modules,vince06fr/prosody-modules,amenophis1er/prosody-modules,1st8/prosody-modules,iamliqiang/prosody-modules,guilhem/prosody-modules,drdownload/prosody-modules,NSAKEY/prosody-modules,amenophis1er/prosody-modules,olax/prosody-modules,cryptotoad/prosody-modules,cryptotoad/prosody-modules,iamliqiang/prosody-modules,asdofindia/prosody-modules,asdofindia/prosody-modules,syntafin/prosody-modules,drdownload/prosody-modules,syntafin/prosody-modules,cryptotoad/prosody-modules,asdofindia/prosody-modules,obelisk21/prosody-modules,vince06fr/prosody-modules,guilhem/prosody-modules,joewalker/prosody-modules,Craige/prosody-modules,drdownload/prosody-modules,mmusial/prosody-modules,syntafin/prosody-modules,LanceJenkinZA/prosody-modules,NSAKEY/prosody-modules,LanceJenkinZA/prosody-modules,stephen322/prosody-modules,olax/prosody-modules,vince06fr/prosody-modules,mmusial/prosody-modules,heysion/prosody-modules,apung/prosody-modules,dhotson/prosody-modules,guilhem/prosody-modules,either1/prosody-modules,obelisk21/prosody-modules,prosody-modules/import,dhotson/prosody-modules,crunchuser/prosody-modules,NSAKEY/prosody-modules,drdownload/prosody-modules,joewalker/prosody-modules,BurmistrovJ/prosody-modules,mmusial/prosody-modules,apung/prosody-modules,Craige/prosody-modules,amenophis1er/prosody-modules,guilhem/prosody-modules,joewalker/prosody-modules,olax/prosody-modules,vince06fr/prosody-modules,joewalker/prosody-modules,mardraze/prosody-modules,iamliqiang/prosody-modules,either1/prosody-modules,either1/prosody-modules,obelisk21/prosody-modules,LanceJenkinZA/prosody-modules,crunchuser/prosody-modules,mmusial/prosody-modules,brahmi2/prosody-modules,vince06fr/prosody-modules,LanceJenkinZA/prosody-modules,cryptotoad/prosody-modules,jkprg/prosody-modules,vfedoroff/prosody-modules,either1/prosody-modules,BurmistrovJ/prosody-modules,asdofindia/prosody-modules,Craige/prosody-modules,heysion/prosody-modules,1st8/prosody-modules,brahmi2/prosody-modules,mardraze/prosody-modules,prosody-modules/import,softer/prosody-modules,BurmistrovJ/prosody-modules,1st8/prosody-modules,either1/prosody-modules,BurmistrovJ/prosody-modules,softer/prosody-modules,syntafin/prosody-modules,heysion/prosody-modules,crunchuser/prosody-modules,stephen322/prosody-modules,softer/prosody-modules,vfedoroff/prosody-modules,amenophis1er/prosody-modules,drdownload/prosody-modules,crunchuser/prosody-modules,prosody-modules/import,joewalker/prosody-modules,heysion/prosody-modules,apung/prosody-modules,stephen322/prosody-modules,dhotson/prosody-modules,stephen322/prosody-modules,mardraze/prosody-modules,brahmi2/prosody-modules,brahmi2/prosody-modules,iamliqiang/prosody-modules,prosody-modules/import,LanceJenkinZA/prosody-modules,jkprg/prosody-modules
|
977b7827f9eb14d43890afe9c1e423fba55fbb95
|
spec/02-integration/03-admin_api/06-cluster_routes_spec.lua
|
spec/02-integration/03-admin_api/06-cluster_routes_spec.lua
|
local helpers = require "spec.helpers"
local cjson = require "cjson"
describe("Admin API", function()
local client
setup(function()
helpers.kill_all()
helpers.prepare_prefix()
assert(helpers.start_kong())
client = helpers.admin_client()
end)
teardown(function()
if client then
client:close()
end
helpers.stop_kong()
helpers.clean_prefix()
end)
describe("/cluster", function()
describe("GET", function()
it("retrieves the members list", function()
-- old test converted
--os.execute("sleep 2") -- Let's wait for serf to register the node
local res = assert(client:send {
method = "GET",
path = "/cluster"
})
local body = assert.res_status(200, res)
local json = cjson.decode(body)
assert.equal(1, #json.data)
assert.equal(1, json.total)
local member = json.data[1]
assert.is_string(member.address)
assert.is_string(member.name)
assert.equal("alive", member.status)
end)
end)
describe("DELETE", function()
-- old test converted
local function is_running(pid_path)
local kill = require "kong.cmd.utils.kill"
if not helpers.path.exists(pid_path) then return nil end
local code = kill(pid_path, "-0")
return code == 0
end
local log_path = helpers.path.join(helpers.test_conf.prefix, "serf_cluster_tests.log")
local pid_path = helpers.path.join(helpers.test_conf.prefix, "serf_cluster_tests.pid")
setup(function()
local pl_utils = require "pl.utils"
local cmd = string.format("nohup serf agent -rpc-addr=127.0.0.1:20000 "
.."-bind=127.0.0.1:20001 -node=newnode > "
.."%s 2>&1 & echo $! > %s",
log_path, pid_path)
assert(pl_utils.execute(cmd))
local tstart = ngx.time()
local texp, started = tstart + 2 -- 2s timeout
repeat
ngx.sleep(0.2)
started = is_running(pid_path)
until started or ngx.time() >= texp
assert(started, "Serf agent start: timeout")
end)
teardown(function()
helpers.execute(string.format("kill $(cat %s)", pid_path))
helpers.file.delete(log_path)
helpers.file.delete(pid_path)
end)
it("force-leaves a node", function()
-- old test converted
local cmd = string.format("serf join -rpc-addr=%s 127.0.0.1:20001", helpers.test_conf.cluster_listen_rpc)
assert(helpers.execute(cmd))
local res = assert(client:send {
method = "GET",
path = "/cluster"
})
local body = assert.res_status(200, res)
local json = cjson.decode(body)
assert.equal(2, #json.data)
assert.equal(2, json.total)
assert.equal("alive", json.data[1].status)
assert.equal("alive", json.data[2].status)
res = assert(client:send {
method = "DELETE",
path = "/cluster",
body = "name=newnode", -- why not in URI??
headers = {["Content-Type"] = "application/x-www-form-urlencoded"}
})
assert.res_status(200, res) -- why not 204??
ngx.sleep(1)
res = assert(client:send {
method = "GET",
path = "/cluster"
})
local body = assert.res_status(200, res)
local json = cjson.decode(body)
assert.equal(2, #json.data)
assert.equal(2, json.total)
assert.equal("alive", json.data[1].status)
assert.equal("leaving", json.data[2].status)
end)
end)
end)
describe("/cluster/events", function()
describe("POST", function()
it("posts a new event", function()
-- old test simply converted
local res = assert(client:send {
method = "POST",
path = "/cluster/events",
body = {},
headers = {["Content-Type"] = "application/json"}
})
assert.res_status(200, res)
end)
end)
end)
end)
|
local helpers = require "spec.helpers"
local cjson = require "cjson"
describe("Admin API", function()
local client
setup(function()
helpers.kill_all()
helpers.prepare_prefix()
assert(helpers.start_kong())
client = helpers.admin_client()
end)
teardown(function()
if client then
client:close()
end
helpers.stop_kong()
helpers.clean_prefix()
end)
describe("/cluster", function()
describe("GET", function()
it("retrieves the members list", function()
-- old test converted
--os.execute("sleep 2") -- Let's wait for serf to register the node
local res = assert(client:send {
method = "GET",
path = "/cluster"
})
local body = assert.res_status(200, res)
local json = cjson.decode(body)
assert.equal(1, #json.data)
assert.equal(1, json.total)
local member = json.data[1]
assert.is_string(member.address)
assert.is_string(member.name)
assert.equal("alive", member.status)
end)
end)
describe("DELETE", function()
-- old test converted
local log_path = helpers.path.join(helpers.test_conf.prefix, "serf_cluster_tests.log")
local pid_path = helpers.path.join(helpers.test_conf.prefix, "serf_cluster_tests.pid")
setup(function()
local pl_utils = require "pl.utils"
local kill = require "kong.cmd.utils.kill"
local cmd = string.format("nohup serf agent -rpc-addr=127.0.0.1:20000 "
.."-bind=127.0.0.1:20001 -node=newnode > "
.."%s 2>&1 & echo $! > %s",
log_path, pid_path)
assert(pl_utils.execute(cmd))
local tstart = ngx.time()
local texp, started = tstart + 2 -- 2s timeout
repeat
ngx.sleep(0.2)
started = kill.is_running(pid_path)
until started or ngx.time() >= texp
assert(started, "Serf agent start: timeout")
end)
teardown(function()
helpers.execute(string.format("kill $(cat %s)", pid_path))
helpers.file.delete(log_path)
helpers.file.delete(pid_path)
end)
it("force-leaves a node", function()
-- old test converted
local cmd = string.format("serf join -rpc-addr=%s 127.0.0.1:20001", helpers.test_conf.cluster_listen_rpc)
assert(helpers.execute(cmd))
local res = assert(client:send {
method = "GET",
path = "/cluster"
})
local body = assert.res_status(200, res)
local json = cjson.decode(body)
assert.equal(2, #json.data)
assert.equal(2, json.total)
assert.equal("alive", json.data[1].status)
assert.equal("alive", json.data[2].status)
res = assert(client:send {
method = "DELETE",
path = "/cluster",
body = "name=newnode", -- why not in URI??
headers = {["Content-Type"] = "application/x-www-form-urlencoded"}
})
assert.res_status(200, res) -- why not 204??
ngx.sleep(1)
res = assert(client:send {
method = "GET",
path = "/cluster"
})
local body = assert.res_status(200, res)
local json = cjson.decode(body)
assert.equal(2, #json.data)
assert.equal(2, json.total)
assert.equal("alive", json.data[1].status)
assert.equal("leaving", json.data[2].status)
end)
end)
end)
describe("/cluster/events", function()
describe("POST", function()
it("posts a new event", function()
-- old test simply converted
local res = assert(client:send {
method = "POST",
path = "/cluster/events",
body = {},
headers = {["Content-Type"] = "application/json"}
})
assert.res_status(200, res)
end)
end)
end)
end)
|
fix(tests) use 'kill' module for 'is_running()' helper in cluster specs
|
fix(tests) use 'kill' module for 'is_running()' helper in cluster specs
|
Lua
|
apache-2.0
|
beauli/kong,icyxp/kong,Kong/kong,Vermeille/kong,ccyphers/kong,salazar/kong,Kong/kong,Mashape/kong,akh00/kong,Kong/kong,li-wl/kong,shiprabehera/kong,jerizm/kong,jebenexer/kong
|
34a42a4a540068d9892544241cc5826392ff3d3c
|
src/lua/export/html.lua
|
src/lua/export/html.lua
|
-- © 2008 David Given.
-- WordGrinder is licensed under the MIT open source license. See the COPYING
-- file in this distribution for the full text.
-----------------------------------------------------------------------------
-- The exporter itself.
local function unhtml(s)
s = s:gsub("&", "&")
s = s:gsub("<", "<")
s = s:gsub(">", ">")
return s
end
local style_tab =
{
["H1"] = {false, '<h1>', '</h1>'},
["H2"] = {false, '<h2>', '</h2>'},
["H3"] = {false, '<h3>', '</h3>'},
["H4"] = {false, '<h4>', '</h4>'},
["P"] = {false, '<p>', '</p>'},
["L"] = {false, '<li style="list-style-type: none;">', '</li>'},
["LB"] = {false, '<li>', '</li>'},
["Q"] = {false, '<blockquote>', '</blockquote>'},
["V"] = {false, '<blockquote>', '</blockquote>'},
["RAW"] = {false, '', ''},
["PRE"] = {true, '<pre>', '</pre>'}
}
local function callback(writer, document)
local settings = DocumentSet.addons.htmlexport
local currentpara = nil
function changepara(newpara)
local currentstyle = style_tab[currentpara]
local newstyle = style_tab[newpara]
if (newpara ~= currentpara) or
not newpara or
not currentstyle[1] or
not newstyle[1]
then
if currentstyle then
writer(currentstyle[3])
end
writer("\n")
if newstyle then
writer(newstyle[2])
end
currentpara = newpara
else
writer("\n")
end
end
return ExportFileUsingCallbacks(document,
{
prologue = function()
writer('<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">\n')
writer('<html><head>\n')
writer('<meta http-equiv="Content-Type" content="text/html;charset=utf-8">\n')
writer('<meta name="generator" content="WordGrinder '..VERSION..'">\n')
writer('<title>', unhtml(document.name), '</title>\n')
writer('</head><body>\n')
end,
rawtext = function(s)
writer(s)
end,
text = function(s)
writer(unhtml(s))
end,
notext = function(s)
if (currentpara ~= "PRE") then
writer('<br/>')
end
end,
italic_on = function()
writer(settings.italic_on)
end,
italic_off = function()
writer(settings.italic_off)
end,
underline_on = function()
writer(settings.underline_on)
end,
underline_off = function()
writer(settings.underline_off)
end,
bold_on = function()
writer(settings.bold_on)
end,
bold_off = function()
writer(settings.bold_off)
end,
list_start = function()
writer('<ul>')
end,
list_end = function()
writer('</ul>')
end,
paragraph_start = function(style)
changepara(style)
end,
paragraph_end = function(style)
end,
epilogue = function()
changepara(nil)
writer('</body>\n')
writer('</html>\n')
end
})
end
function Cmd.ExportHTMLFile(filename)
return ExportFileWithUI(filename, "Export HTML File", ".html",
callback)
end
-----------------------------------------------------------------------------
-- Addon registration. Set the HTML export settings.
do
local function cb()
DocumentSet.addons.htmlexport = DocumentSet.addons.htmlexport or {
underline_on = "<u>",
underline_off = "</u>",
italic_on = "<i>",
italic_off = "</i>"
}
local s = DocumentSet.addons.htmlexport
s.bold_on = s.bold_on or "<b>"
s.bold_off = s.bold_off or "</b>"
end
AddEventListener(Event.RegisterAddons, cb)
end
-----------------------------------------------------------------------------
-- Configuration user interface.
function Cmd.ConfigureHTMLExport()
local settings = DocumentSet.addons.htmlexport
local underline_on_textfield =
Form.TextField {
x1 = 16, y1 = 1,
x2 = -1, y2 = 1,
value = settings.underline_on
}
local underline_off_textfield =
Form.TextField {
x1 = 16, y1 = 3,
x2 = -1, y2 = 3,
value = settings.underline_off
}
local italic_on_textfield =
Form.TextField {
x1 = 16, y1 = 5,
x2 = -1, y2 = 5,
value = settings.italic_on
}
local italic_off_textfield =
Form.TextField {
x1 = 16, y1 = 7,
x2 = -1, y2 = 7,
value = settings.italic_off
}
local bold_on_textfield =
Form.TextField {
x1 = 16, y1 = 9,
x2 = -1, y2 = 9,
value = settings.bold_on
}
local bold_off_textfield =
Form.TextField {
x1 = 16, y1 = 11,
x2 = -1, y2 = 11,
value = settings.bold_off
}
local dialogue =
{
title = "Configure HTML Export",
width = Form.Large,
height = 13,
stretchy = false,
["KEY_^C"] = "cancel",
["KEY_RETURN"] = "confirm",
["KEY_ENTER"] = "confirm",
Form.Label {
x1 = 1, y1 = 1,
x2 = 32, y2 = 1,
align = Form.Left,
value = "Underline on:"
},
underline_on_textfield,
Form.Label {
x1 = 1, y1 = 3,
x2 = 32, y2 = 3,
align = Form.Left,
value = "Underline off:"
},
underline_off_textfield,
Form.Label {
x1 = 1, y1 = 5,
x2 = 32, y2 = 5,
align = Form.Left,
value = "Italics on:"
},
italic_on_textfield,
Form.Label {
x1 = 1, y1 = 7,
x2 = 32, y2 = 7,
align = Form.Left,
value = "Italics off:"
},
italic_off_textfield,
Form.Label {
x1 = 1, y1 = 9,
x2 = 32, y2 = 9,
align = Form.Left,
value = "Bold on:"
},
bold_on_textfield,
Form.Label {
x1 = 1, y1 = 11,
x2 = 32, y2 = 11,
align = Form.Left,
value = "Bold off:"
},
bold_off_textfield,
}
while true do
local result = Form.Run(dialogue, RedrawScreen,
"SPACE to toggle, RETURN to confirm, CTRL+C to cancel")
if not result then
return false
end
settings.underline_on = underline_on_textfield.value
settings.underline_off = underline_off_textfield.value
settings.italic_on = italic_on_textfield.value
settings.italic_off = italic_off_textfield.value
settings.bold_on = bold_on_textfield.value
settings.bold_off = bold_off_textfield.value
return true
end
return false
end
|
-- © 2008 David Given.
-- WordGrinder is licensed under the MIT open source license. See the COPYING
-- file in this distribution for the full text.
-----------------------------------------------------------------------------
-- The exporter itself.
local function unhtml(s)
s = s:gsub("&", "&")
s = s:gsub("<", "<")
s = s:gsub(">", ">")
return s
end
local style_tab =
{
["H1"] = {pre=false, list=false,
on='<h1>', off='</h1>'},
["H2"] = {pre=false, list=false,
on='<h2>', off='</h2>'},
["H3"] = {pre=false, list=false,
on='<h3>', off='</h3>'},
["H4"] = {pre=false, list=false,
on='<h4>', off='</h4>'},
["P"] = {pre=false, list=false,
on='<p>', off='</p>'},
["L"] = {pre=false, list=true,
on='<li style="list-style-type: none;">', off='</li>'},
["LB"] = {pre=false, list=true,
on='<li>', off='</li>'},
["Q"] = {pre=false, list=false,
on='<blockquote>', off='</blockquote>'},
["V"] = {pre=false, list=false,
on='<blockquote>', off='</blockquote>'},
["RAW"] = {pre=false, list=false,
on='', off=''},
["PRE"] = {pre=true, list=false,
on='<pre>', off='</pre>'}
}
local function callback(writer, document)
local settings = DocumentSet.addons.htmlexport
local currentpara = nil
local islist = false
function changepara(newpara)
local currentstyle = style_tab[currentpara]
local newstyle = style_tab[newpara]
if (newpara ~= currentpara) or
not newpara or
not currentstyle.pre or
not newstyle.pre
then
if currentstyle then
writer(currentstyle.off)
end
writer("\n")
if (not newstyle or not newstyle.list) and islist then
writer("</ul>\n")
islist = false
end
if (newstyle and newstyle.list) and not islist then
writer("<ul>\n")
islist = true
end
if newstyle then
writer(newstyle.on)
end
currentpara = newpara
else
writer("\n")
end
end
return ExportFileUsingCallbacks(document,
{
prologue = function()
writer('<html xmlns="http://www.w3.org/1999/xhtml"><head>\n')
writer('<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>\n')
writer('<meta name="generator" content="WordGrinder '..VERSION..'"/>\n')
writer('<title>', unhtml(document.name), '</title>\n')
writer('</head><body>\n')
end,
rawtext = function(s)
writer(s)
end,
text = function(s)
writer(unhtml(s))
end,
notext = function(s)
if (currentpara ~= "PRE") then
writer('<br/>')
end
end,
italic_on = function()
writer(settings.italic_on)
end,
italic_off = function()
writer(settings.italic_off)
end,
underline_on = function()
writer(settings.underline_on)
end,
underline_off = function()
writer(settings.underline_off)
end,
bold_on = function()
writer(settings.bold_on)
end,
bold_off = function()
writer(settings.bold_off)
end,
list_start = function()
end,
list_end = function()
end,
paragraph_start = function(style)
changepara(style)
end,
paragraph_end = function(style)
end,
epilogue = function()
changepara(nil)
writer('</body>\n')
writer('</html>\n')
end
})
end
function Cmd.ExportHTMLFile(filename)
return ExportFileWithUI(filename, "Export HTML File", ".html",
callback)
end
-----------------------------------------------------------------------------
-- Addon registration. Set the HTML export settings.
do
local function cb()
DocumentSet.addons.htmlexport = DocumentSet.addons.htmlexport or {
underline_on = "<u>",
underline_off = "</u>",
italic_on = "<i>",
italic_off = "</i>"
}
local s = DocumentSet.addons.htmlexport
s.bold_on = s.bold_on or "<b>"
s.bold_off = s.bold_off or "</b>"
end
AddEventListener(Event.RegisterAddons, cb)
end
-----------------------------------------------------------------------------
-- Configuration user interface.
function Cmd.ConfigureHTMLExport()
local settings = DocumentSet.addons.htmlexport
local underline_on_textfield =
Form.TextField {
x1 = 16, y1 = 1,
x2 = -1, y2 = 1,
value = settings.underline_on
}
local underline_off_textfield =
Form.TextField {
x1 = 16, y1 = 3,
x2 = -1, y2 = 3,
value = settings.underline_off
}
local italic_on_textfield =
Form.TextField {
x1 = 16, y1 = 5,
x2 = -1, y2 = 5,
value = settings.italic_on
}
local italic_off_textfield =
Form.TextField {
x1 = 16, y1 = 7,
x2 = -1, y2 = 7,
value = settings.italic_off
}
local bold_on_textfield =
Form.TextField {
x1 = 16, y1 = 9,
x2 = -1, y2 = 9,
value = settings.bold_on
}
local bold_off_textfield =
Form.TextField {
x1 = 16, y1 = 11,
x2 = -1, y2 = 11,
value = settings.bold_off
}
local dialogue =
{
title = "Configure HTML Export",
width = Form.Large,
height = 13,
stretchy = false,
["KEY_^C"] = "cancel",
["KEY_RETURN"] = "confirm",
["KEY_ENTER"] = "confirm",
Form.Label {
x1 = 1, y1 = 1,
x2 = 32, y2 = 1,
align = Form.Left,
value = "Underline on:"
},
underline_on_textfield,
Form.Label {
x1 = 1, y1 = 3,
x2 = 32, y2 = 3,
align = Form.Left,
value = "Underline off:"
},
underline_off_textfield,
Form.Label {
x1 = 1, y1 = 5,
x2 = 32, y2 = 5,
align = Form.Left,
value = "Italics on:"
},
italic_on_textfield,
Form.Label {
x1 = 1, y1 = 7,
x2 = 32, y2 = 7,
align = Form.Left,
value = "Italics off:"
},
italic_off_textfield,
Form.Label {
x1 = 1, y1 = 9,
x2 = 32, y2 = 9,
align = Form.Left,
value = "Bold on:"
},
bold_on_textfield,
Form.Label {
x1 = 1, y1 = 11,
x2 = 32, y2 = 11,
align = Form.Left,
value = "Bold off:"
},
bold_off_textfield,
}
while true do
local result = Form.Run(dialogue, RedrawScreen,
"SPACE to toggle, RETURN to confirm, CTRL+C to cancel")
if not result then
return false
end
settings.underline_on = underline_on_textfield.value
settings.underline_off = underline_off_textfield.value
settings.italic_on = italic_on_textfield.value
settings.italic_off = italic_off_textfield.value
settings.bold_on = bold_on_textfield.value
settings.bold_off = bold_off_textfield.value
return true
end
return false
end
|
Emit poor-man's XHTML (minus the doctype, because it makes XML tools sad); fix bug where ul and /ul where being generated in the wrong place.
|
Emit poor-man's XHTML (minus the doctype, because it makes XML tools sad);
fix bug where ul and /ul where being generated in the wrong place.
|
Lua
|
mit
|
rodoviario/wordgrinder,Munchotaur/wordgrinder,NRauh/wordgrinder,rodoviario/wordgrinder,Munchotaur/wordgrinder,NRauh/wordgrinder
|
e2b3155cc136d19e5b6dad1f88dd5905560535e2
|
modules/admin-full/luasrc/model/cbi/admin_network/dhcp.lua
|
modules/admin-full/luasrc/model/cbi/admin_network/dhcp.lua
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
require("luci.tools.webadmin")
require("luci.model.uci")
require("luci.util")
m = Map("dhcp", "DHCP")
s = m:section(TypedSection, "dhcp", "")
s.addremove = true
s.anonymous = true
iface = s:option(ListValue, "interface", translate("interface"))
luci.tools.webadmin.cbi_add_networks(iface)
local uci = luci.model.uci.cursor()
uci:foreach("network", "interface",
function (section)
if section[".name"] ~= "loopback" then
iface.default = iface.default or section[".name"]
s:depends("interface", section[".name"])
end
end)
uci:foreach("network", "alias",
function (section)
iface:value(section[".name"])
s:depends("interface", section[".name"])
end)
s:option(Value, "start", translate("start")).rmempty = true
s:option(Value, "limit", translate("limit")).rmempty = true
s:option(Value, "leasetime").rmempty = true
s:option(Flag, "dynamicdhcp").rmempty = true
s:option(Value, "name", translate("name")).optional = true
ignore = s:option(Flag, "ignore")
ignore.optional = true
s:option(Value, "netmask", translate("netmask")).optional = true
s:option(Flag, "force").optional = true
s:option(DynamicList, "dhcp_option").optional = true
for i, n in ipairs(s.children) do
if n ~= iface and n ~= ignore then
n:depends("ignore", "")
end
end
return m
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
require("luci.tools.webadmin")
require("luci.model.uci")
require("luci.util")
m = Map("dhcp", "DHCP")
s = m:section(TypedSection, "dhcp", "")
s.addremove = true
s.anonymous = true
iface = s:option(ListValue, "interface", translate("interface"))
luci.tools.webadmin.cbi_add_networks(iface)
local uci = luci.model.uci.cursor()
uci:foreach("network", "interface",
function (section)
if section[".name"] ~= "loopback" then
iface.default = iface.default or section[".name"]
s:depends("interface", section[".name"])
end
end)
uci:foreach("network", "alias",
function (section)
iface:value(section[".name"])
s:depends("interface", section[".name"])
end)
s:option(Value, "start", translate("start")).rmempty = true
s:option(Value, "limit", translate("limit")).rmempty = true
s:option(Value, "leasetime").rmempty = true
local dd = s:option(Flag, "dynamicdhcp")
dd.rmempty = false
function dd.cfgvalue(self, section)
return Flag.cfgvalue(self, section) or "1"
end
s:option(Value, "name", translate("name")).optional = true
ignore = s:option(Flag, "ignore")
ignore.optional = true
s:option(Value, "netmask", translate("netmask")).optional = true
s:option(Flag, "force").optional = true
s:option(DynamicList, "dhcp_option").optional = true
for i, n in ipairs(s.children) do
if n ~= iface and n ~= ignore then
n:depends("ignore", "")
end
end
return m
|
Fix behaviour of dynamicdhcp field (thanks to Fabio Mercuri)
|
Fix behaviour of dynamicdhcp field (thanks to Fabio Mercuri)
|
Lua
|
apache-2.0
|
deepak78/luci,8devices/luci,8devices/luci,8devices/luci,deepak78/luci,deepak78/luci,deepak78/luci,deepak78/luci,8devices/luci,deepak78/luci,8devices/luci,deepak78/luci,deepak78/luci,8devices/luci
|
6e211474c96d75a878c2cf15991828789047bdf3
|
otouto/plugins/amazon_cleaner.lua
|
otouto/plugins/amazon_cleaner.lua
|
local cln_amzn = {}
cln_amzn.triggers = {
'amazon.(%w+)/gp/product/(.+)/(.+)',
'amazon.(%w+)/gp/product/(.+)%?(.+)',
'amazon.(%w+)/dp/(.+)/(.+)',
'amazon.(%w+)/dp/(.+)%?(.+)',
'amzn.to/(.+)'
}
function cln_amzn:action(msg, config, matches)
if #matches == 1 then
local request_constructor = {
url = 'http://amzn.to/'..matches[1],
method = "HEAD",
sink = ltn12.sink.null(),
redirect = false
}
local ok, response_code, response_headers = http.request(request_constructor)
local long_url = response_headers.location
local domain, product_id = long_url:match('amazon.(%w+)/gp/product/(.+)/(.+)')
utilities.send_reply(msg, 'Ohne Ref: https://amazon.'..domain..'/dp/'..product_id)
return
end
text = msg.text:lower()
if text:match('tag%=.+') or text:match('linkid%=.+') then
utilities.send_reply(msg, 'Ohne Ref: https://amazon.'..matches[1]..'/dp/'..matches[2])
end
end
return cln_amzn
|
local cln_amzn = {}
cln_amzn.triggers = {
'amazon.(%w+)/gp/product/(.+)/(.+)',
'amazon.(%w+)/gp/product/(.+)%?(.+)',
'amazon.(%w+)/dp/(.+)/(.+)',
'amazon.(%w+)/dp/(.+)%?(.+)',
'amzn.to/(.+)'
}
function cln_amzn:action(msg, config, matches)
if #matches == 1 then
local request_constructor = {
url = 'http://amzn.to/'..matches[1],
method = "HEAD",
sink = ltn12.sink.null(),
redirect = false
}
local ok, response_code, response_headers = http.request(request_constructor)
local long_url = response_headers.location
if not long_url then return end
local domain, product_id = long_url:match('amazon.(%w+)/gp/product/(.+)/.+')
if not product_id then
domain, product_id = long_url:match('amazon.(%w+)/.+/dp/(.+)/')
end
if not product_id then return end
utilities.send_reply(msg, 'Ohne Ref: https://amazon.'..domain..'/dp/'..product_id)
return
end
text = msg.text:lower()
if text:match('tag%=.+') or text:match('linkid%=.+') then
utilities.send_reply(msg, 'Ohne Ref: https://amazon.'..matches[1]..'/dp/'..matches[2])
end
end
return cln_amzn
|
Fixe Amazon-Plugin mit einigen URLs (warum hat Amazon so verdammt viele verschiedene Produkt-URLs?)
|
Fixe Amazon-Plugin mit einigen URLs (warum hat Amazon so verdammt viele verschiedene Produkt-URLs?)
|
Lua
|
agpl-3.0
|
Brawl345/Brawlbot-v2
|
c0d572a64abfc1b977d3162df809f0f5994b00da
|
BtEvaluator/category.lua
|
BtEvaluator/category.lua
|
--- .
-- @module CategoryManager
local CustomEnvironment = Utils.CustomEnvironment
local Logger = Utils.Debug.Logger
local UnitCategories = Utils.UnitCategories
local ProjectManager = Utils.ProjectManager
local categories = {}
local CategoryManager = {}
function CategoryManager.loadCategory(...)
local categoryData, message = UnitCategories.loadCategory(...)
if(not categoryData)then
return nil, message
end
local idToDataMap = {}
local nameToDataMap = {}
for i, data in ipairs(categoryData.types) do
nameToDataMap[data.name] = data
local id = (UnitDefNames[data.name] or {}).id
if(id)then
idToDataMap[id] = data
end
end
return setmetatable({}, {
__index = setmetatable(idToDataMap, { __index = nameToDataMap }),
__newindex = function() end -- disable modifications
})
end
local managers
managers = setmetatable({
Reload = function(self)
local keys = {}
for k, _ in pairs(self) do
if(k ~= "Reload")then
table.insert(keys, k)
end
end
for _, k in ipairs(keys) do
rawset(self, k, nil)
end
CategoryManager.reload()
end
}, {
__index = function(self, projectName)
if(not ProjectManager.isProject(projectName))then
return nil
end
local manager = setmetatable({ Reload = function() managers:Reload() end }, {
__index = function(self, key)
local qualifiedName = ProjectManager.asQualifiedName(projectName, key)
local category = categories[qualifiedName]
if(not category)then
category = CategoryManager.loadCategory(qualifiedName)
if(not category)then
return managers[key]
end
categories[qualifiedName] = category
end
rawset(self, key, category)
return category
end,
})
rawset(self, projectName, manager)
return manager
end,
})
function CategoryManager.forProject(localProject)
return managers[localProject] or managers
end
function CategoryManager.reload()
categories = {}
managers:Reload()
end
CustomEnvironment.add("Categories", { }, function(p)
return CategoryManager.forProject(p.project)
end)
return CategoryManager
|
--- .
-- @module CategoryManager
local CustomEnvironment = Utils.CustomEnvironment
local Logger = Utils.Debug.Logger
local UnitCategories = Utils.UnitCategories
local ProjectManager = Utils.ProjectManager
local categories = {}
local CategoryManager = {}
function CategoryManager.loadCategory(...)
local categoryData, message = UnitCategories.loadCategory(...)
if(not categoryData)then
return nil, message
end
local idToDataMap = {}
local nameToDataMap = {}
for i, data in ipairs(categoryData.types) do
nameToDataMap[data.name] = data
local id = (UnitDefNames[data.name] or {}).id
if(id)then
idToDataMap[id] = data
end
end
return setmetatable({}, {
__index = setmetatable(idToDataMap, { __index = nameToDataMap }),
__newindex = function() end -- disable modifications
})
end
local managers
managers = setmetatable({
Reload = function(self)
local keys = {}
for k, _ in pairs(self) do
if(k ~= "Reload")then
table.insert(keys, k)
end
end
for _, k in ipairs(keys) do
rawset(self, k, nil)
end
CategoryManager.reload()
end
}, {
__index = function(self, projectName)
if(not ProjectManager.isProject(projectName))then
return nil
end
local manager = setmetatable({ Reload = function() managers:Reload() end }, {
__index = function(self, key)
local qualifiedName = ProjectManager.asQualifiedName(projectName, key)
local category = categories[qualifiedName]
if(not category)then
category = CategoryManager.loadCategory(qualifiedName)
if(not category)then
return managers[key]
end
categories[qualifiedName] = category
end
rawset(self, key, category)
return category
end,
})
rawset(self, projectName, manager)
return manager
end,
})
function CategoryManager.forProject(localProject)
return managers[localProject] or managers
end
function CategoryManager.reload()
local temp = CategoryManager.reload
CategoryManager.reload = function() end
categories = {}
managers:Reload()
CategoryManager.reload = temp
end
CustomEnvironment.add("Categories", { }, function(p)
return CategoryManager.forProject(p.project)
end)
return CategoryManager
|
Fixed infinite recursion during CategoryManager.reload.
|
Fixed infinite recursion during CategoryManager.reload.
|
Lua
|
mit
|
MartinFrancu/BETS
|
643b9df7b3bbbdf8f6dff4fef153177db88c13c7
|
test/src/testLoader.lua
|
test/src/testLoader.lua
|
--[[ @cond ___LICENSE___
-- Copyright (c) 2017 Zefiros Software.
--
-- Permission is hereby granted, free of charge, to any person obtaining a copy
-- of this software and associated documentation files (the "Software"), to deal
-- in the Software without restriction, including without limitation the rights
-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-- copies of the Software, and to permit persons to whom the Software is
-- furnished to do so, subject to the following conditions:
--
-- The above copyright notice and this permission notice shall be included in
-- all copies or substantial portions of the Software.
--
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-- THE SOFTWARE.
--
-- @endcond
--]]
function Test:testLoaderExists()
u.assertNotEquals(Loader, nil)
u.assertIsTable(Loader)
end
function Test:testLoader_fixMainScript()
u.assertNotEquals(_MAIN_SCRIPT, "zpm.lua")
local ld = Loader:new()
u.assertNotEquals(_MAIN_SCRIPT, "zpm.lua")
end
function Test:testLoader_fixMainScriptZpmlua()
_MAIN_SCRIPT = ""
local zpmFile = path.join(_MAIN_SCRIPT_DIR, "zpm.lua")
local f = io.open(zpmFile, "w")
f:write("")
f:close()
local ld = Loader:new()
u.assertEquals(_MAIN_SCRIPT, zpmFile)
os.remove(zpmFile)
_MAIN_SCRIPT = ""
end
function Test:testLoader_fixMainScriptZpmlua2()
_ACTION = "self-update"
_MAIN_SCRIPT = ""
local ld = Loader:new()
u.assertEquals(_MAIN_SCRIPT, ".")
_ACTION = ""
end
function Test:testLoader_checkGitVersion()
local ld = Loader:new()
u.assertTrue(ld.gitCheckPassed)
end
function Test:testLoader_initialiseCache()
local ld = Loader:new()
u.assertTrue(os.isdir(ld.cache))
u.assertTrue(os.isdir(ld.temp))
end
function Test:testLoader_initialiseCacheRemove()
local ld = Loader:new()
u.assertTrue(os.isdir(ld.cache))
u.assertTrue(os.isdir(ld.temp))
local file = path.join(ld.cache, "Test.txt")
zpm.util.writeAll(file, "FOO")
u.assertTrue(os.isfile(file))
Loader:new()
u.assertFalse(os.isfile(file))
u.assertTrue(os.isdir(ld.cache))
u.assertTrue(os.isdir(ld.temp))
end
|
--[[ @cond ___LICENSE___
-- Copyright (c) 2017 Zefiros Software.
--
-- Permission is hereby granted, free of charge, to any person obtaining a copy
-- of this software and associated documentation files (the "Software"), to deal
-- in the Software without restriction, including without limitation the rights
-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-- copies of the Software, and to permit persons to whom the Software is
-- furnished to do so, subject to the following conditions:
--
-- The above copyright notice and this permission notice shall be included in
-- all copies or substantial portions of the Software.
--
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-- THE SOFTWARE.
--
-- @endcond
--]]
function Test:testLoaderExists()
u.assertNotEquals(Loader, nil)
u.assertIsTable(Loader)
end
function Test:testLoader_fixMainScript()
u.assertNotEquals(_MAIN_SCRIPT, "zpm.lua")
local ld = Loader:new()
u.assertNotEquals(_MAIN_SCRIPT, "zpm.lua")
end
function Test:testLoader_fixMainScriptZpmlua()
_MAIN_SCRIPT = ""
local zpmFile = path.join(_MAIN_SCRIPT_DIR, "zpm.lua")
local f = io.open(zpmFile, "w")
f:write("")
f:close()
local ld = Loader:new()
u.assertEquals(_MAIN_SCRIPT, zpmFile)
os.remove(zpmFile)
_MAIN_SCRIPT = ""
end
function Test:testLoader_fixMainScriptZpmlua2()
_ACTION = "self-update"
_MAIN_SCRIPT = ""
local ld = Loader:new()
u.assertEquals(_MAIN_SCRIPT, ".")
_ACTION = ""
end
function Test:testLoader_checkGitVersion()
local ld = Loader:new()
u.assertTrue(ld.gitCheckPassed)
end
function Test:testLoader_initialiseCache()
local ld = Loader:new()
u.assertTrue(os.isdir(ld.cache))
u.assertTrue(os.isdir(ld.temp))
end
|
Fix tests
|
Fix tests
|
Lua
|
mit
|
Zefiros-Software/ZPM
|
94c4d72a06625a340165e3fbe1d366b0a3f42db1
|
deps/coro-channel.lua
|
deps/coro-channel.lua
|
exports.name = "creationix/coro-channel"
exports.version = "1.0.3"
-- Given a raw uv_stream_t userdara, return coro-friendly read/write functions.
-- Given a raw uv_stream_t userdara, return coro-friendly read/write functions.
function exports.wrapStream(socket)
local paused = true
local queue = {}
local waiting
local reading = true
local writing = true
local onRead
local function read()
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
local flushing = false
local flushed = false
local function checkShutdown()
if socket:is_closing() then return end
if not flushing and not writing then
flushing = true
local thread = coroutine.running()
socket:shutdown(function (err)
flushed = true
coroutine.resume(thread, not err, err)
end)
coroutine.yield()
end
if flushed and not reading then
socket:close()
end
end
function onRead(err, chunk)
assert(not err, err)
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
if not chunk then
reading = false
-- Close the whole socket if the writing side is also closed already.
checkShutdown()
end
end
local function write(chunk)
if chunk == nil then
-- Shutdown our side of the socket
writing = false
checkShutdown()
else
-- TODO: add backpressure by pausing and resuming coroutine
-- when write buffer is full.
assert(socket:write(chunk))
end
end
return read, write
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.0.4"
-- Given a raw uv_stream_t userdara, return coro-friendly read/write functions.
-- Given a raw uv_stream_t userdara, return coro-friendly read/write functions.
function exports.wrapStream(socket)
local paused = true
local queue = {}
local waiting
local reading = true
local writing = true
local onRead
local function read()
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
local flushing = false
local flushed = false
local function checkShutdown()
if socket:is_closing() then return end
if not flushing and not writing then
flushing = true
local thread = coroutine.running()
socket:shutdown(function (err)
flushed = true
coroutine.resume(thread, not err, err)
end)
assert(coroutine.yield())
end
if flushed and not reading then
socket:close()
end
end
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
if not chunk then
reading = false
-- Close the whole socket if the writing side is also closed already.
checkShutdown()
end
end
local function write(chunk)
if chunk == nil then
-- Shutdown our side of the socket
writing = false
checkShutdown()
else
-- TODO: add backpressure by pausing and resuming coroutine
-- when write buffer is full.
assert(socket:write(chunk))
end
end
return read, write
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
|
Import coro-channel fixes from rye
|
Import coro-channel fixes from rye
|
Lua
|
apache-2.0
|
zhaozg/lit,kidaa/lit,luvit/lit,DBarney/lit,lduboeuf/lit,squeek502/lit,1yvT0s/lit,james2doyle/lit,kaustavha/lit
|
5e0314a578fb81e79361b739d477f835738b6bc9
|
lib/switchboard_modules/lua_script_debugger/premade_scripts/7b_log_voltage_to_file_wifi.lua
|
lib/switchboard_modules/lua_script_debugger/premade_scripts/7b_log_voltage_to_file_wifi.lua
|
print("Log voltage to file. Voltage measured on AIN1 every 50ms. Store values every 5 seconds")
--Requires micro SD Card installed inside the T7 or T7-Pro.
--Requires FW 1.0150 or newer.
--This example is for logging to file while using WiFi, since WiFi needs 5s or more to initialize
--without comm. to/from the uSD card. http://labjack.com/support/datasheets/t7/sd-card
--Timestamp (real-time-clock) available on T7-Pro only
--Some helpful Lua file operations in section 5.7 http://www.lua.org/manual/5.1/manual.html#5.7
--Some file info docs in 21.2 of the Lua documentation http://www.lua.org/pil/21.2.html
local hardware = MB.R(60010, 1)
local passed = 1
if(bit.band(hardware, 8) ~= 8) then
print("uSD card not detected")
passed = 0
end
if(bit.band(hardware, 4) ~= 4) then
print("RTC module not detected")
passed = 0
end
if(bit.band(hardware, 2) ~= 2) then
print("Wifi module not detected")
passed = 0
end
if(passed == 0) then
print("This Lua script requires an RTC module, Wifi, and a microSD card, but one or many are not detected. These features are only preinstalled on the T7-Pro. Script Stopping")
MB.W(6000, 1, 0)--stop script
end
local Filepre = "/FWi_"
local Filesuf = ".csv"
local NumFn = 0
local Filename = Filepre..string.format("%02d", NumFn)..Filesuf
local voltage = 0
local indexVal = 1
local delimiter = ","
local dateStr = ""
local voltageStr = ""
local f = nil
local mbRead=MB.R --local functions for faster processing
local mbReadArray=MB.RA
local DACinterval = 50 --interval in ms, 50 for 50ms, should divide evenly into SDCard interval
local SDCardinterval = 5000 --inerval in ms, 5000 for 5 seconds
local numDAC = math.floor(SDCardinterval/DACinterval)
local DataTable = {}
local stringTable = {}
for i=1, numDAC do
DataTable[i] = 0
stringTable[i] = "bar"
end
local dateTbl = {}
dateTbl[1] = 0 --year
dateTbl[2] = 0 --month
dateTbl[3] = 0 --day
dateTbl[4] = 0 --hour
dateTbl[5] = 0 --minute
dateTbl[6] = 0 --second
MB.W(48005,0,1) --ensure analog is on
LJ.IntervalConfig(0, DACinterval)
LJ.IntervalConfig(1, SDCardinterval)
local checkInterval=LJ.CheckInterval
f = io.open(Filename, "r")
if f ~= nil then
f:close()
f = io.open(Filename, "a+") --File exists, Append to file
print ("Appending to file")
else
f = io.open(Filename, "w") --Create or replace file
print ("Creating new file")
end
while true do
if checkInterval(0) then --DAC interval completed
DataTable[indexVal] = mbRead(2, 3) --voltage on AIN1, address is 2, type is 3
dateTbl, error = mbReadArray(61510, 0, 6) --Read the RTC timestamp, -Pro only
print("AIN1: ", DataTable[indexVal], "V")
dateStr = string.format("%04d/%02d/%02d %02d:%02d.%02d", dateTbl[1], dateTbl[2], dateTbl[3], dateTbl[4], dateTbl[5], dateTbl[6])
voltageStr = string.format("%.6f", DataTable[indexVal])
stringTable[indexVal] = dateStr..delimiter..voltageStr.."\n"
indexVal = indexVal + 1
end
if checkInterval(1) then --file write interval completed -> 5s for WiFi safe
local i = 1
local fg = 0
indexVal = 1
fg = LJ.CheckFileFlag() --host software wants to read LUAs active file? Is FILE_IO_LUA_SWITCH_FILE=1?
if fg == 1 then
NumFn = NumFn + 1 --increment filename
Filename = Filepre..string.format("%02d", NumFn)..Filesuf
f:close()
LJ.ClearFileFlag() --inform host that previous file is available. Sets FILE_IO_LUA_SWITCH_FILE=0
f = io.open(Filename, "w") --create or replace new file
print ("Command issued by host to create new file")
end
print ("Appending to file")
for i=1, numDAC do
f:write(stringTable[i])
end
end
end
|
--[[
Name: 7b_log_voltage_to_file_wifi.lua
Desc: This example shows how to log voltage measurements to file if
communicating over WiFi (WiFi needs 5s or more to initialize)
without comm
Note: Requires an SD Card installed inside the T7 or T7-Pro
This example requires firmware 1.0282 (T7)
Timestamp (real-time-clock) available on T7-Pro only
Some helpful Lua file operations in section 5.7:
http://www.lua.org/manual/5.1/manual.html#5.7
Some file info docs in 21.2 of the Lua documentation:
http://www.lua.org/pil/21.2.html
--]]
print("Log voltage to file. Voltage measured on AIN1 every 50ms. Store values every 5 seconds")
-- Get info on the hardware that is installed
local hardware = MB.readName("HARDWARE_INSTALLED")
local passed = 1
if(bit.band(hardware, 8) ~= 8) then
print("uSD card not detected")
passed = 0
end
if(bit.band(hardware, 4) ~= 4) then
print("RTC module not detected")
passed = 0
end
if(bit.band(hardware, 2) ~= 2) then
print("Wifi module not detected")
passed = 0
end
if(passed == 0) then
print("This Lua script requires an RTC module, Wifi, and a microSD card, but one or many are not detected. These features are only preinstalled on the T7-Pro. Script Stopping")
-- Writing a 0 to LUA_RUN stops the script
MB.writeName("LUA_RUN", 0)
end
local filepre = "/FWi_"
local filesuf = ".csv"
local numfn = 0
local filename = filepre..string.format("%02d", numfn)..filesuf
local voltage = 0
local indexval = 1
local delimiter = ","
local strdate = ""
local strvoltage = ""
local f = nil
-- Use a 50ms interval for writing DAC values
local dacinterval = 50
-- Use a 5s interval for the sd card
local sdinterval = 5000
local numdacs = math.floor(sdinterval/dacinterval)
local data = {}
local strings = {}
for i=1, numdacs do
data[i] = 0
strings[i] = "bar"
end
local date = {}
date[1] = 0 --year
date[2] = 0 --month
date[3] = 0 --day
date[4] = 0 --hour
date[5] = 0 --minute
date[6] = 0 --second
-- Make sure analog is on
MB.writeName("POWER_AIN",1)
LJ.IntervalConfig(0, dacinterval)
LJ.IntervalConfig(1, sdinterval)
f = io.open(filename, "r")
if f ~= nil then
f:close()
-- If the file exists, Append to file
f = io.open(filename, "a+")
print ("Appending to file")
else
-- Create or overwrite the file
f = io.open(filename, "w")
print ("Creating new file")
end
while true do
-- If a DAC interval is done
if LJ.CheckInterval(0) then
data[indexval] = MB.readName("AIN1")
-- Read the RTC timestamp, (T7-Pro only)
date, error = MB.RA(61510, 0, 6)
print("AIN1: ", data[indexval], "V")
strdate = string.format(
"%04d/%02d/%02d %02d:%02d.%02d",
date[1],
date[2],
date[3],
date[4],
date[5],
date[6]
)
strvoltage = string.format("%.6f", data[indexval])
strings[indexval] = strdate..delimiter..strvoltage.."\n"
indexval = indexval + 1
end
-- If the interval wait before writing to an sd card is done
if LJ.CheckInterval(1) then
local i = 1
local fg = 0
indexval = 1
-- Check if the host software wants to read the active, opened file
fg = LJ.CheckFileFlag()
-- If so, increment filename and start writing to a new file
if fg == 1 then
numfn = numfn + 1
filename = filepre..string.format("%02d", numfn)..filesuf
f:close()
-- Inform the host computer that previous file is available
LJ.ClearFileFlag()
--create or replace a new file
f = io.open(filename, "w")
print ("Command issued by host to create new file")
end
print ("Appending to file")
for i=1, numdacs do
f:write(strings[i])
end
end
end
|
Fixed up the formatting of the voltage logging over WiFi example
|
Fixed up the formatting of the voltage logging over WiFi example
|
Lua
|
mit
|
chrisJohn404/ljswitchboard-module_manager,chrisJohn404/ljswitchboard-module_manager,chrisJohn404/ljswitchboard-module_manager
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.