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
|
|---|---|---|---|---|---|---|---|---|---|
2fe98d926a6f4b985efee591cc0495302b358152
|
bin/default.lua
|
bin/default.lua
|
-- default.lua
local function samples()
end
function __main__()
print('usage: ./puss <script> [options...]')
print()
local function run(script)
local cmd = string.format('%s/%s %s', puss._path, puss._self, script)
print(cmd, os.execute(cmd))
end
local samples =
{ 'samples/puss.lua'
, 'samples/const.lua'
, 'samples/glua.lua'
, 'samples/gtk.lua'
, 'samples/nuklear.lua'
, 'source_editor/main.lua'
}
while true do
print('samples test:')
for i, s in ipairs(samples) do
print( string.format(' %d - %s', i, s) )
end
print(' other - quit')
io.stdout:write('please select: ')
io.stdout:flush()
local s = samples[ math.tointeger(io.stdin:read('*l')) ]
if not s then break end
run(s)
end
end
|
-- default.lua
function __main__()
print('usage: ./puss <script> [options...]')
print()
local function run(script)
local cmd = string.format('%s/%s %s', puss._path, puss._self, script)
print(cmd, os.execute(cmd))
end
local samples =
{ 'samples/puss.lua'
, 'samples/const.lua'
, 'samples/nuklear.lua'
-- , 'samples/glua.lua'
-- , 'samples/gtk.lua'
-- , 'source_editor/main.lua'
}
while true do
print('samples test:')
for i, s in ipairs(samples) do
print( string.format(' %d - %s', i, s) )
end
print(' other - quit')
io.stdout:write('please select: ')
io.stdout:flush()
local s = samples[ math.tointeger(io.stdin:read('*l')) ]
if not s then break end
run(s)
end
end
|
fix build
|
fix build
|
Lua
|
mit
|
louisliangjun/puss,louisliangjun/puss,louisliangjun/puss,louisliangjun/puss
|
9ab17934fd4cd15b56b56babf816c2d983305496
|
hammerspoon/hammerspoon.symlink/modules/monitor-monitor.lua
|
hammerspoon/hammerspoon.symlink/modules/monitor-monitor.lua
|
local lastScreenId = -1
local usePhysicalIndicator = true
local useVirtualIndicator = true
local currentIndicator = nil
local indicatorHeight = 3 -- 0..1 = percent of menubar, >1 = pixel height
local indicatorColor = hs.drawing.color.asRGB({
red = 0,
green = 1.0,
blue = 0,
alpha = 0.3
})
-- -------------------------------------------------------= Change Handlers =--=
function handleLayoutChange()
local focusedWindow = hs.window.focusedWindow()
if not focusedWindow then return end
local screen = focusedWindow:screen()
local screenId = screen:id()
if screenId == lastScreenId then return end
lastScreenId = screenId
if usePhysicalIndicator then updatePhysicalScreenIndicator(screenId) end
if useVirtualIndicator then updateVirtualScreenIndicator(screen) end
print('Display changed to ' .. screenId)
end
-- ----------------------------------------------------= Virtual Indicators =--=
function updateVirtualScreenIndicator(screen)
clearIndicator()
local screeng = screen:fullFrame()
if indicatorHeight >= 0.0 and indicatorHeight <= 1.0 then
height = indicatorHeight*(screen:frame().y - screeng.y)
else
height = indicatorHeight
end
indicator = hs.drawing.rectangle(hs.geometry.rect(
screeng.x,
screeng.y,
screeng.w,
height
))
indicator:setFillColor(indicatorColor)
:setFill(true)
:setLevel(hs.drawing.windowLevels.overlay)
:setStroke(false)
:setBehavior(hs.drawing.windowBehaviors.canJoinAllSpaces)
:show()
currentIndicator = indicator
end
function clearIndicator()
if currentIndicator ~= nil then
currentIndicator:delete()
currentIndicator = nil
end
end
-- ---------------------------------------------------= Physical Indicators =--=
function updatePhysicalScreenIndicator(screenId)
local devicePath = getSerialOutputDevice()
if devicePath == "" then return end
local file = assert(io.open(devicePath, "w"))
file:write("set " .. screenId .. "\n")
file:flush()
file:close()
end
function getSerialOutputDevice()
local command = "ioreg -c IOSerialBSDClient -r -t " ..
"| awk 'f;/Photon/{f=1};/IOCalloutDevice/{exit}' " ..
"| sed -n 's/.*\"\\(\\/dev\\/.*\\)\".*/\\1/p'"
local handle = io.popen(command)
local result = handle:read("*a")
handle:close()
-- Strip whitespace - https://www.rosettacode.org/wiki/Strip_whitespace_from_a_string/Top_and_tail#Lua
return result:match("^%s*(.-)%s*$")
end
-- --------------------------------------------------------------= Watchers =--=
hs.screen.watcher.newWithActiveScreen(handleLayoutChange):start()
hs.spaces.watcher.new(handleLayoutChange):start()
handleLayoutChange(true) -- set the initial screen
-- Run this from the Hammerspoon console to get a listing of display IDs
function listAllScreens ()
local primaryId = hs.screen.primaryScreen():id()
for _, screen in pairs(hs.screen.allScreens()) do
local screenId = screen:id()
print(
"id: " .. screenId ..
" \"" .. screen:name() .. "\"" ..
(screenId == primaryId and " (primary)" or "")
)
end
end
|
local lastScreenId = -1
local usePhysicalIndicator = true
local useVirtualIndicator = true
local currentIndicator = nil
local indicatorHeight = 3 -- 0..1 = percent of menubar, >1 = pixel height
local indicatorColor = hs.drawing.color.asRGB({
red = 0,
green = 1.0,
blue = 0,
alpha = 0.3
})
-- -------------------------------------------------------= Change Handlers =--=
function handleLayoutChange()
local focusedWindow = hs.window.focusedWindow()
if not focusedWindow then return end
local screen = focusedWindow:screen()
local screenId = screen:id()
if screenId == lastScreenId then return end
lastScreenId = screenId
if usePhysicalIndicator then updatePhysicalScreenIndicator(screenId) end
if useVirtualIndicator then updateVirtualScreenIndicator(screen) end
print('Display changed to ' .. screenId)
end
-- ----------------------------------------------------= Virtual Indicators =--=
-- Based heavily on https://git.io/v6kZN
function updateVirtualScreenIndicator(screen)
clearIndicator()
local screeng = screen:fullFrame()
if indicatorHeight >= 0.0 and indicatorHeight <= 1.0 then
height = indicatorHeight*(screen:frame().y - screeng.y)
else
height = indicatorHeight
end
indicator = hs.drawing.rectangle(hs.geometry.rect(
screeng.x,
screeng.y,
screeng.w,
height
))
indicator:setFillColor(indicatorColor)
:setFill(true)
:setLevel(hs.drawing.windowLevels.overlay)
:setStroke(false)
:setBehavior(hs.drawing.windowBehaviors.canJoinAllSpaces)
:show()
currentIndicator = indicator
end
function clearIndicator()
if currentIndicator ~= nil then
currentIndicator:delete()
currentIndicator = nil
end
end
-- ---------------------------------------------------= Physical Indicators =--=
function updatePhysicalScreenIndicator(screenId)
local devicePath = getSerialOutputDevice()
if devicePath == "" then return end
local file = assert(io.open(devicePath, "w"))
file:write("set " .. screenId .. "\n")
file:flush()
file:close()
end
function getSerialOutputDevice()
local command = "ioreg -c IOSerialBSDClient -r -t " ..
"| awk 'f;/Photon/{f=1};/IOCalloutDevice/{exit}' " ..
"| sed -n 's/.*\"\\(\\/dev\\/.*\\)\".*/\\1/p'"
local handle = io.popen(command)
local result = handle:read("*a")
handle:close()
-- Strip whitespace - https://www.rosettacode.org/wiki/Strip_whitespace_from_a_string/Top_and_tail#Lua
return result:match("^%s*(.-)%s*$")
end
-- --------------------------------------------------------------= Watchers =--=
hs.screen.watcher.newWithActiveScreen(handleLayoutChange):start()
hs.spaces.watcher.new(handleLayoutChange):start()
handleLayoutChange(true) -- set the initial screen
-- Run this from the Hammerspoon console to get a listing of display IDs
function listAllScreens ()
local primaryId = hs.screen.primaryScreen():id()
for _, screen in pairs(hs.screen.allScreens()) do
local screenId = screen:id()
print(
"id: " .. screenId ..
" \"" .. screen:name() .. "\"" ..
(screenId == primaryId and " (primary)" or "")
)
end
end
|
fix(Hammerspoon): Add attribution for virtual indicator code
|
fix(Hammerspoon): Add attribution for virtual indicator code
|
Lua
|
mit
|
sethvoltz/dotfiles,sethvoltz/dotfiles,sethvoltz/dotfiles,sethvoltz/dotfiles
|
bbb4bd762326937eb4356e0d9969d670553f2871
|
logout-menu-widget/logout-menu.lua
|
logout-menu-widget/logout-menu.lua
|
-------------------------------------------------
-- Logout Menu Widget for Awesome Window Manager
-- More details could be found here:
-- https://github.com/streetturtle/awesome-wm-widgets/tree/master/logout-menu-widget
-- @author Pavel Makhov
-- @copyright 2020 Pavel Makhov
-------------------------------------------------
local awful = require("awful")
local wibox = require("wibox")
local gears = require("gears")
local beautiful = require("beautiful")
local HOME = os.getenv('HOME')
local ICON_DIR = HOME .. '/.config/awesome/awesome-wm-widgets/logout-menu-widget/icons/'
local logout_menu_widget = wibox.widget {
{
{
image = ICON_DIR .. 'power_w.svg',
resize = true,
widget = wibox.widget.imagebox,
},
margins = 4,
layout = wibox.container.margin
},
shape = function(cr, width, height)
gears.shape.rounded_rect(cr, width, height, 4)
end,
widget = wibox.container.background,
}
local popup = awful.popup {
ontop = true,
visible = false,
shape = function(cr, width, height)
gears.shape.rounded_rect(cr, width, height, 4)
end,
border_width = 1,
border_color = beautiful.bg_focus,
maximum_width = 400,
offset = { y = 5 },
widget = {}
}
local function worker(user_args)
local rows = { layout = wibox.layout.fixed.vertical }
local args = user_args or {}
local font = args.font or beautiful.font
local onlogout = args.onlogout or function () awesome.quit() end
local onlock = args.onlock or function() awful.spawn.with_shell("i3lock") end
local onreboot = args.onreboot or function() awful.spawn.with_shell("reboot") end
local onsuspend = args.onsuspend or function() awful.spawn.with_shell("systemctl suspend") end
local onpoweroff = args.onpoweroff or function() awful.spawn.with_shell("shutdown now") end
local menu_items = {
{ name = 'Log out', icon_name = 'log-out.svg', command = onlogout },
{ name = 'Lock', icon_name = 'lock.svg', command = onlock },
{ name = 'Reboot', icon_name = 'refresh-cw.svg', command = onreboot },
{ name = 'Suspend', icon_name = 'moon.svg', command = onsuspend },
{ name = 'Power off', icon_name = 'power.svg', command = onpoweroff },
}
for _, item in ipairs(menu_items) do
local row = wibox.widget {
{
{
{
image = ICON_DIR .. item.icon_name,
resize = false,
widget = wibox.widget.imagebox
},
{
text = item.name,
font = font,
widget = wibox.widget.textbox
},
spacing = 12,
layout = wibox.layout.fixed.horizontal
},
margins = 8,
layout = wibox.container.margin
},
bg = beautiful.bg_normal,
widget = wibox.container.background
}
row:connect_signal("mouse::enter", function(c) c:set_bg(beautiful.bg_focus) end)
row:connect_signal("mouse::leave", function(c) c:set_bg(beautiful.bg_normal) end)
local old_cursor, old_wibox
row:connect_signal("mouse::enter", function()
local wb = mouse.current_wibox
old_cursor, old_wibox = wb.cursor, wb
wb.cursor = "hand1"
end)
row:connect_signal("mouse::leave", function()
if old_wibox then
old_wibox.cursor = old_cursor
old_wibox = nil
end
end)
row:buttons(awful.util.table.join(awful.button({}, 1, function()
popup.visible = not popup.visible
item.command()
end)))
table.insert(rows, row)
end
popup:setup(rows)
logout_menu_widget:buttons(
awful.util.table.join(
awful.button({}, 1, function()
if popup.visible then
popup.visible = not popup.visible
logout_menu_widget:set_bg('#00000000')
else
popup:move_next_to(mouse.current_widget_geometry)
logout_menu_widget:set_bg(beautiful.bg_focus)
end
end)
)
)
return logout_menu_widget
end
return setmetatable(logout_menu_widget, { __call = function(_, ...) return worker(...) end })
|
-------------------------------------------------
-- Logout Menu Widget for Awesome Window Manager
-- More details could be found here:
-- https://github.com/streetturtle/awesome-wm-widgets/tree/master/logout-menu-widget
-- @author Pavel Makhov
-- @copyright 2020 Pavel Makhov
-------------------------------------------------
local awful = require("awful")
local wibox = require("wibox")
local gears = require("gears")
local beautiful = require("beautiful")
local HOME = os.getenv('HOME')
local ICON_DIR = HOME .. '/.config/awesome/awesome-wm-widgets/logout-menu-widget/icons/'
local logout_menu_widget = wibox.widget {
{
{
image = ICON_DIR .. 'power_w.svg',
resize = true,
widget = wibox.widget.imagebox,
},
margins = 4,
layout = wibox.container.margin
},
shape = function(cr, width, height)
gears.shape.rounded_rect(cr, width, height, 4)
end,
widget = wibox.container.background,
}
local popup = awful.popup {
ontop = true,
visible = false,
shape = function(cr, width, height)
gears.shape.rounded_rect(cr, width, height, 4)
end,
border_width = 1,
border_color = beautiful.bg_focus,
maximum_width = 400,
offset = { y = 5 },
widget = {}
}
local function worker(user_args)
local rows = { layout = wibox.layout.fixed.vertical }
local args = user_args or {}
local font = args.font or beautiful.font
local onlogout = args.onlogout or function () awesome.quit() end
local onlock = args.onlock or function() awful.spawn.with_shell("i3lock") end
local onreboot = args.onreboot or function() awful.spawn.with_shell("reboot") end
local onsuspend = args.onsuspend or function() awful.spawn.with_shell("systemctl suspend") end
local onpoweroff = args.onpoweroff or function() awful.spawn.with_shell("shutdown now") end
local menu_items = {
{ name = 'Log out', icon_name = 'log-out.svg', command = onlogout },
{ name = 'Lock', icon_name = 'lock.svg', command = onlock },
{ name = 'Reboot', icon_name = 'refresh-cw.svg', command = onreboot },
{ name = 'Suspend', icon_name = 'moon.svg', command = onsuspend },
{ name = 'Power off', icon_name = 'power.svg', command = onpoweroff },
}
for _, item in ipairs(menu_items) do
local row = wibox.widget {
{
{
{
image = ICON_DIR .. item.icon_name,
resize = false,
widget = wibox.widget.imagebox
},
{
text = item.name,
font = font,
widget = wibox.widget.textbox
},
spacing = 12,
layout = wibox.layout.fixed.horizontal
},
margins = 8,
layout = wibox.container.margin
},
bg = beautiful.bg_normal,
widget = wibox.container.background
}
row:connect_signal("mouse::enter", function(c) c:set_bg(beautiful.bg_focus) end)
row:connect_signal("mouse::leave", function(c) c:set_bg(beautiful.bg_normal) end)
local old_cursor, old_wibox
row:connect_signal("mouse::enter", function()
local wb = mouse.current_wibox
old_cursor, old_wibox = wb.cursor, wb
wb.cursor = "hand1"
end)
row:connect_signal("mouse::leave", function()
if old_wibox then
old_wibox.cursor = old_cursor
old_wibox = nil
end
end)
row:buttons(awful.util.table.join(awful.button({}, 1, function()
popup.visible = not popup.visible
item.command()
end)))
table.insert(rows, row)
end
popup:setup(rows)
logout_menu_widget:buttons(
awful.util.table.join(
awful.button({}, 1, function()
if popup.visible then
popup.visible = not popup.visible
logout_menu_widget:set_bg('#00000000')
else
popup:move_next_to(mouse.current_widget_geometry)
logout_menu_widget:set_bg(beautiful.bg_focus)
end
end)
)
)
return logout_menu_widget
end
return worker
|
fix: #281
|
fix: #281
|
Lua
|
mit
|
streetturtle/awesome-wm-widgets,streetturtle/awesome-wm-widgets
|
6393a0a746607130d22e5eff34ed171a0009050b
|
bindings/new_base64.lua
|
bindings/new_base64.lua
|
-- Base64-encoding
-- Sourced from http://en.wikipedia.org/wiki/Base64
--
-- Copyright (c) 2012, Daniel Lindsley
-- All rights reserved.
--
-- Modified by: Max Bruckner (FSMaxB)
-- * remove unnecessary "require"
-- * remove __ attributes
-- * rename "to_base64" -> "encode" and "from_base64" -> "decode"
-- * make it a loadable module via require
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions are met:
--
-- * Redistributions of source code must retain the above copyright notice, this
-- list of conditions and the following disclaimer.
-- * Redistributions in binary form must reproduce the above copyright notice,
-- this list of conditions and the following disclaimer in the documentation
-- and/or other materials provided with the distribution.
-- * Neither the name of the base64 nor the names of its contributors may be
-- used to endorse or promote products derived from this software without
-- specific prior written permission.
--
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
-- ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-- WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-- DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
-- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
-- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
-- SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
-- CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
-- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
local base64 = {}
local index_table = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
local function to_binary(integer)
local remaining = tonumber(integer)
local bin_bits = ''
for i = 7, 0, -1 do
local current_power = math.pow(2, i)
if remaining >= current_power then
bin_bits = bin_bits .. '1'
remaining = remaining - current_power
else
bin_bits = bin_bits .. '0'
end
end
return bin_bits
end
local function from_binary(bin_bits)
return tonumber(bin_bits, 2)
end
function base64.encode(to_encode)
local bit_pattern = ''
local encoded = ''
local trailing = ''
for i = 1, string.len(to_encode) do
bit_pattern = bit_pattern .. to_binary(string.byte(string.sub(to_encode, i, i)))
end
-- Check the number of bytes. If it's not evenly divisible by three,
-- zero-pad the ending & append on the correct number of ``=``s.
if math.mod(string.len(bit_pattern), 3) == 2 then
trailing = '=='
bit_pattern = bit_pattern .. '0000000000000000'
elseif math.mod(string.len(bit_pattern), 3) == 1 then
trailing = '='
bit_pattern = bit_pattern .. '00000000'
end
for i = 1, string.len(bit_pattern), 6 do
local byte = string.sub(bit_pattern, i, i+5)
local offset = tonumber(from_binary(byte))
encoded = encoded .. string.sub(index_table, offset+1, offset+1)
end
return string.sub(encoded, 1, -1 - string.len(trailing)) .. trailing
end
function base64.decode(to_decode)
local padded = to_decode:gsub("%s", "")
local unpadded = padded:gsub("=", "")
local bit_pattern = ''
local decoded = ''
for i = 1, string.len(unpadded) do
local char = string.sub(to_decode, i, i)
local offset, _ = string.find(index_table, char)
if offset == nil then
error("Invalid character '" .. char .. "' found.")
end
bit_pattern = bit_pattern .. string.sub(to_binary(offset-1), 3)
end
for i = 1, string.len(bit_pattern), 8 do
local byte = string.sub(bit_pattern, i, i+7)
decoded = decoded .. string.char(from_binary(byte))
end
local padding_length = padded:len()-unpadded:len()
if (padding_length == 1 or padding_length == 2) then
decoded = decoded:sub(1,-2)
end
return decoded
end
return base64
|
-- Base64-encoding
-- Sourced from http://en.wikipedia.org/wiki/Base64
--
-- Copyright (c) 2012, Daniel Lindsley
-- All rights reserved.
--
-- Modified by: Max Bruckner (FSMaxB)
-- * remove unnecessary "require"
-- * remove __ attributes
-- * rename "to_base64" -> "encode" and "from_base64" -> "decode"
-- * make it a loadable module via require
-- * fix use of the modulo operator (math.mod -> %)
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions are met:
--
-- * Redistributions of source code must retain the above copyright notice, this
-- list of conditions and the following disclaimer.
-- * Redistributions in binary form must reproduce the above copyright notice,
-- this list of conditions and the following disclaimer in the documentation
-- and/or other materials provided with the distribution.
-- * Neither the name of the base64 nor the names of its contributors may be
-- used to endorse or promote products derived from this software without
-- specific prior written permission.
--
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
-- ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-- WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-- DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
-- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
-- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
-- SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
-- CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
-- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
local base64 = {}
local index_table = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
local function to_binary(integer)
local remaining = tonumber(integer)
local bin_bits = ''
for i = 7, 0, -1 do
local current_power = math.pow(2, i)
if remaining >= current_power then
bin_bits = bin_bits .. '1'
remaining = remaining - current_power
else
bin_bits = bin_bits .. '0'
end
end
return bin_bits
end
local function from_binary(bin_bits)
return tonumber(bin_bits, 2)
end
function base64.encode(to_encode)
local bit_pattern = ''
local encoded = ''
local trailing = ''
for i = 1, string.len(to_encode) do
bit_pattern = bit_pattern .. to_binary(string.byte(string.sub(to_encode, i, i)))
end
-- Check the number of bytes. If it's not evenly divisible by three,
-- zero-pad the ending & append on the correct number of ``=``s.
if (string.len(bit_pattern) % 3) == 2 then
trailing = '=='
bit_pattern = bit_pattern .. '0000000000000000'
elseif (string.len(bit_pattern) % 3) == 1 then
trailing = '='
bit_pattern = bit_pattern .. '00000000'
end
for i = 1, string.len(bit_pattern), 6 do
local byte = string.sub(bit_pattern, i, i+5)
local offset = tonumber(from_binary(byte))
encoded = encoded .. string.sub(index_table, offset+1, offset+1)
end
return string.sub(encoded, 1, -1 - string.len(trailing)) .. trailing
end
function base64.decode(to_decode)
local padded = to_decode:gsub("%s", "")
local unpadded = padded:gsub("=", "")
local bit_pattern = ''
local decoded = ''
for i = 1, string.len(unpadded) do
local char = string.sub(to_decode, i, i)
local offset, _ = string.find(index_table, char)
if offset == nil then
error("Invalid character '" .. char .. "' found.")
end
bit_pattern = bit_pattern .. string.sub(to_binary(offset-1), 3)
end
for i = 1, string.len(bit_pattern), 8 do
local byte = string.sub(bit_pattern, i, i+7)
decoded = decoded .. string.char(from_binary(byte))
end
local padding_length = padded:len()-unpadded:len()
if (padding_length == 1 or padding_length == 2) then
decoded = decoded:sub(1,-2)
end
return decoded
end
return base64
|
base64: Fix the modulo operator
|
base64: Fix the modulo operator
|
Lua
|
lgpl-2.1
|
FSMaxB/molch,FSMaxB/molch,FSMaxB/molch
|
7e750ae50b5693d39f9118b7a0490c80185deba2
|
tests/build.lua
|
tests/build.lua
|
-- main entry
function main(argv)
-- generic?
os.exec("$(xmake) m -b")
os.exec("$(xmake) f -c")
os.exec("$(xmake)")
if os.host() ~= "windows" then
os.exec("$(xmake) install -o /tmp -a --verbose --backtrace")
os.exec("$(xmake) uninstall --installdir=/tmp --verbose --backtrace")
end
os.exec("$(xmake) p")
os.exec("$(xmake) c")
os.exec("$(xmake) f -m release")
os.exec("$(xmake) -r -a -v --backtrace")
os.exec("$(xmake) f --mode=debug --verbose --backtrace")
os.exec("$(xmake) --rebuild --all --verbose --backtrace")
os.exec("$(xmake) p --verbose --backtrace")
os.exec("$(xmake) c --verbose --backtrace")
os.exec("$(xmake) m -e buildtest")
os.exec("$(xmake) m -l")
os.exec("$(xmake) f --cc=gcc --cxx=g++")
os.exec("$(xmake) m buildtest")
if os.host() ~= "windows" then
os.exec("sudo $(xmake) install")
os.exec("sudo $(xmake) uninstall")
end
os.exec("$(xmake) f --cc=clang --cxx=clang++ --ld=clang++ --verbose --backtrace")
os.exec("$(xmake) m buildtest")
if os.host() ~= "windows" then
os.exec("sudo $(xmake) install --all -v --backtrace")
os.exec("sudo $(xmake) uninstall -v --backtrace")
end
os.exec("$(xmake) m -d buildtest")
-- test iphoneos?
if argv and argv.iphoneos then
if os.host() == "macosx" then
os.exec("$(xmake) m package -p iphoneos")
end
end
end
|
-- main entry
function main(argv)
-- generic?
os.exec("xmake m -b")
os.exec("xmake f -c")
os.exec("xmake")
if os.host() ~= "windows" then
os.exec("xmake install -o /tmp -a --verbose --backtrace")
os.exec("xmake uninstall --installdir=/tmp --verbose --backtrace")
end
os.exec("xmake p")
os.exec("xmake c")
os.exec("xmake f -m release")
os.exec("xmake -r -a -v --backtrace")
os.exec("xmake f --mode=debug --verbose --backtrace")
os.exec("xmake --rebuild --all --verbose --backtrace")
os.exec("xmake p --verbose --backtrace")
os.exec("xmake c --verbose --backtrace")
os.exec("xmake m -e buildtest")
os.exec("xmake m -l")
os.exec("xmake f --cc=gcc --cxx=g++")
os.exec("xmake m buildtest")
if os.host() ~= "windows" then
os.exec("sudo xmake install")
os.exec("sudo xmake uninstall")
end
os.exec("xmake f --cc=clang --cxx=clang++ --ld=clang++ --verbose --backtrace")
os.exec("xmake m buildtest")
if os.host() ~= "windows" then
os.exec("sudo xmake install --all -v --backtrace")
os.exec("sudo xmake uninstall -v --backtrace")
end
os.exec("xmake m -d buildtest")
-- test iphoneos?
if argv and argv.iphoneos then
if os.host() == "macosx" then
os.exec("xmake m package -p iphoneos")
end
end
end
|
Revert "use $(xmake) instead of xmake to fix cnf"
|
Revert "use $(xmake) instead of xmake to fix cnf"
This reverts commit f2e0d829b43011cce87568118a5b8b0b469ade1e.
|
Lua
|
apache-2.0
|
tboox/xmake,tboox/xmake,waruqi/xmake,waruqi/xmake,tboox/xmake,tboox/xmake,tboox/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,tboox/xmake,waruqi/xmake,tboox/xmake
|
ef9a4c5d04ea2ca5c6348b10fe5d28c7c9bdf6fe
|
modules/game_minimap/minimap.lua
|
modules/game_minimap/minimap.lua
|
DEFAULT_ZOOM = 60
MAX_FLOOR_UP = 0
MAX_FLOOR_DOWN = 15
navigating = false
minimapWidget = nil
minimapButton = nil
minimapWindow = nil
--[[
Known Issue (TODO):
If you move the minimap compass directions and
you change floor it will not update the minimap.
]]
function init()
connect(g_game, {
onGameStart = online,
onGameEnd = offline,
onForceWalk = center,
})
g_keyboard.bindKeyDown('Ctrl+M', toggle)
minimapButton = TopMenu.addRightGameToggleButton('minimapButton', tr('Minimap') .. ' (Ctrl+M)', 'minimap.png', toggle)
minimapButton:setOn(true)
minimapWindow = g_ui.loadUI('minimap.otui', modules.game_interface.getRightPanel())
minimapWidget = minimapWindow:recursiveGetChildById('minimap')
g_mouse.bindAutoPress(minimapWidget, compassClick, nil, MouseRightButton)
g_mouse.bindAutoPress(minimapWidget, compassClick, nil, MouseLeftButton)
minimapWidget:setAutoViewMode(false)
minimapWidget:setViewMode(1) -- mid view
minimapWidget:setDrawMinimapColors(true)
minimapWidget:setMultifloor(false)
minimapWidget:setKeepAspectRatio(false)
minimapWidget.onMouseRelease = onMinimapMouseRelease
minimapWidget.onMouseWheel = onMinimapMouseWheel
reset()
end
function terminate()
disconnect(g_game, {
onGameStart = online,
onGameEnd = offline,
onForceWalk = center,
})
if g_game.isOnline() then
saveMap()
end
g_keyboard.unbindKeyDown('Ctrl+M')
minimapButton:destroy()
minimapWindow:destroy()
end
function online()
reset()
loadMap()
end
function offline()
saveMap()
end
function loadMap()
local clientVersion = g_game.getClientVersion()
local minimapName = '/minimap_' .. clientVersion .. '.otcm'
g_map.clean()
g_map.loadOtcm(minimapName)
end
function saveMap()
local clientVersion = g_game.getClientVersion()
local minimapName = '/minimap_' .. clientVersion .. '.otcm'
g_map.saveOtcm(minimapName)
end
function toggle()
if minimapButton:isOn() then
minimapWindow:close()
minimapButton:setOn(false)
else
minimapWindow:open()
minimapButton:setOn(true)
end
end
function isClickInRange(position, fromPosition, toPosition)
return (position.x >= fromPosition.x and position.y >= fromPosition.y and position.x <= toPosition.x and position.y <= toPosition.y)
end
function reset()
local player = g_game.getLocalPlayer()
if not player then return end
minimapWidget:followCreature(player)
minimapWidget:setZoom(DEFAULT_ZOOM)
end
function center()
local player = g_game.getLocalPlayer()
if not player then return end
minimapWidget:followCreature(player)
end
function compassClick(self, mousePos, mouseButton, elapsed)
if elapsed < 300 then return end
navigating = true
local px = mousePos.x - self:getX()
local py = mousePos.y - self:getY()
local dx = px - self:getWidth()/2
local dy = -(py - self:getHeight()/2)
local radius = math.sqrt(dx*dx+dy*dy)
local movex = 0
local movey = 0
dx = dx/radius
dy = dy/radius
if dx > 0.5 then movex = 1 end
if dx < -0.5 then movex = -1 end
if dy > 0.5 then movey = -1 end
if dy < -0.5 then movey = 1 end
local cameraPos = minimapWidget:getCameraPosition()
local pos = {x = cameraPos.x + movex, y = cameraPos.y + movey, z = cameraPos.z}
minimapWidget:setCameraPosition(pos)
end
function onButtonClick(id)
if id == "zoomIn" then
minimapWidget:setZoom(math.max(minimapWidget:getMaxZoomIn(), minimapWidget:getZoom()-15))
elseif id == "zoomOut" then
minimapWidget:setZoom(math.min(minimapWidget:getMaxZoomOut(), minimapWidget:getZoom()+15))
elseif id == "floorUp" then
local pos = minimapWidget:getCameraPosition()
pos.z = pos.z - 1
if pos.z > MAX_FLOOR_UP then
minimapWidget:setCameraPosition(pos)
end
elseif id == "floorDown" then
local pos = minimapWidget:getCameraPosition()
pos.z = pos.z + 1
if pos.z < MAX_FLOOR_DOWN then
minimapWidget:setCameraPosition(pos)
end
end
end
function onMinimapMouseRelease(self, mousePosition, mouseButton)
if navigating then
navigating = false
return
end
local tile = self:getTile(mousePosition)
if tile and mouseButton == MouseLeftButton and self:isPressed() then
local dirs = g_map.findPath(g_game.getLocalPlayer():getPosition(), tile:getPosition(), 127)
if #dirs == 0 then
modules.game_textmessage.displayStatusMessage(tr('There is no way.'))
return true
end
g_game.autoWalk(dirs)
return true
end
return false
end
function onMinimapMouseWheel(self, mousePos, direction)
if direction == MouseWheelUp then
self:zoomIn()
else
self:zoomOut()
end
end
function onMiniWindowClose()
minimapButton:setOn(false)
end
|
DEFAULT_ZOOM = 60
MAX_FLOOR_UP = 0
MAX_FLOOR_DOWN = 15
navigating = false
minimapWidget = nil
minimapButton = nil
minimapWindow = nil
--[[
Known Issue (TODO):
If you move the minimap compass directions and
you change floor it will not update the minimap.
]]
function init()
connect(g_game, {
onGameStart = online,
onGameEnd = offline,
})
connect(LocalPlayer, { onPositionChange = center })
g_keyboard.bindKeyDown('Ctrl+M', toggle)
minimapButton = TopMenu.addRightGameToggleButton('minimapButton', tr('Minimap') .. ' (Ctrl+M)', 'minimap.png', toggle)
minimapButton:setOn(true)
minimapWindow = g_ui.loadUI('minimap.otui', modules.game_interface.getRightPanel())
minimapWidget = minimapWindow:recursiveGetChildById('minimap')
g_mouse.bindAutoPress(minimapWidget, compassClick, nil, MouseRightButton)
g_mouse.bindAutoPress(minimapWidget, compassClick, nil, MouseLeftButton)
minimapWidget:setAutoViewMode(false)
minimapWidget:setViewMode(1) -- mid view
minimapWidget:setDrawMinimapColors(true)
minimapWidget:setMultifloor(false)
minimapWidget:setKeepAspectRatio(false)
minimapWidget.onMouseRelease = onMinimapMouseRelease
minimapWidget.onMouseWheel = onMinimapMouseWheel
reset()
end
function terminate()
disconnect(g_game, {
onGameStart = online,
onGameEnd = offline,
})
disconnect(LocalPlayer, { onPositionChange = center })
if g_game.isOnline() then
saveMap()
end
g_keyboard.unbindKeyDown('Ctrl+M')
minimapButton:destroy()
minimapWindow:destroy()
end
function online()
reset()
loadMap()
end
function offline()
saveMap()
end
function loadMap()
local clientVersion = g_game.getClientVersion()
local minimapName = '/minimap_' .. clientVersion .. '.otcm'
g_map.clean()
g_map.loadOtcm(minimapName)
end
function saveMap()
local clientVersion = g_game.getClientVersion()
local minimapName = '/minimap_' .. clientVersion .. '.otcm'
g_map.saveOtcm(minimapName)
end
function toggle()
if minimapButton:isOn() then
minimapWindow:close()
minimapButton:setOn(false)
else
minimapWindow:open()
minimapButton:setOn(true)
end
end
function isClickInRange(position, fromPosition, toPosition)
return (position.x >= fromPosition.x and position.y >= fromPosition.y and position.x <= toPosition.x and position.y <= toPosition.y)
end
function reset()
local player = g_game.getLocalPlayer()
if not player then return end
minimapWidget:followCreature(player)
minimapWidget:setZoom(DEFAULT_ZOOM)
end
function center()
local player = g_game.getLocalPlayer()
if not player then return end
minimapWidget:followCreature(player)
end
function compassClick(self, mousePos, mouseButton, elapsed)
if elapsed < 300 then return end
navigating = true
local px = mousePos.x - self:getX()
local py = mousePos.y - self:getY()
local dx = px - self:getWidth()/2
local dy = -(py - self:getHeight()/2)
local radius = math.sqrt(dx*dx+dy*dy)
local movex = 0
local movey = 0
dx = dx/radius
dy = dy/radius
if dx > 0.5 then movex = 1 end
if dx < -0.5 then movex = -1 end
if dy > 0.5 then movey = -1 end
if dy < -0.5 then movey = 1 end
local cameraPos = minimapWidget:getCameraPosition()
local pos = {x = cameraPos.x + movex, y = cameraPos.y + movey, z = cameraPos.z}
minimapWidget:setCameraPosition(pos)
end
function onButtonClick(id)
if id == "zoomIn" then
minimapWidget:setZoom(math.max(minimapWidget:getMaxZoomIn(), minimapWidget:getZoom()-15))
elseif id == "zoomOut" then
minimapWidget:setZoom(math.min(minimapWidget:getMaxZoomOut(), minimapWidget:getZoom()+15))
elseif id == "floorUp" then
local pos = minimapWidget:getCameraPosition()
pos.z = pos.z - 1
if pos.z > MAX_FLOOR_UP then
minimapWidget:setCameraPosition(pos)
end
elseif id == "floorDown" then
local pos = minimapWidget:getCameraPosition()
pos.z = pos.z + 1
if pos.z < MAX_FLOOR_DOWN then
minimapWidget:setCameraPosition(pos)
end
end
end
function onMinimapMouseRelease(self, mousePosition, mouseButton)
if navigating then
navigating = false
return
end
local tile = self:getTile(mousePosition)
if tile and mouseButton == MouseLeftButton and self:isPressed() then
local dirs = g_map.findPath(g_game.getLocalPlayer():getPosition(), tile:getPosition(), 127)
if #dirs == 0 then
modules.game_textmessage.displayStatusMessage(tr('There is no way.'))
return true
end
g_game.autoWalk(dirs)
return true
end
return false
end
function onMinimapMouseWheel(self, mousePos, direction)
if direction == MouseWheelUp then
self:zoomIn()
else
self:zoomOut()
end
end
function onMiniWindowClose()
minimapButton:setOn(false)
end
|
Fix minimap desync, old issue #10
|
Fix minimap desync, old issue #10
|
Lua
|
mit
|
EvilHero90/otclient,EvilHero90/otclient,Radseq/otclient,dreamsxin/otclient,Cavitt/otclient_mapgen,dreamsxin/otclient,Radseq/otclient,dreamsxin/otclient,kwketh/otclient,kwketh/otclient,Cavitt/otclient_mapgen,gpedro/otclient,gpedro/otclient,gpedro/otclient
|
1d06181b9b134f4ad8a1ab90d493fdd800b612c6
|
commands/assets.lua
|
commands/assets.lua
|
--[[ @cond ___LICENSE___
-- Copyright (c) 2016 Koen Visscher, Paul Visscher and individual contributors.
--
-- Permission is hereby granted, free of charge, to any person obtaining a copy
-- of this software and associated documentation files (the "Software"), to deal
-- in the Software without restriction, including without limitation the rights
-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-- copies of the Software, and to permit persons to whom the Software is
-- furnished to do so, subject to the following conditions:
--
-- The above copyright notice and this permission notice shall be included in
-- all copies or substantial portions of the Software.
--
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-- THE SOFTWARE.
--
-- @endcond
--]]
zpm.assets.commands = {}
function zpm.assets.commands.extract( repo, folder, files )
if (type(files) ~= "table") then
files = {files}
end
for _, pattern in ipairs( files ) do
for _, file in ipairs( os.matchfiles( path.join( repo, pattern ) ) ) do
local target = path.join( folder, path.getrelative( repo, file ) )
local targetDir = path.getdirectory( target )
zpm.assert( path.getabsolute( targetDir ):contains( os.getcwd() ), "Executing lua outside folder is not allowed!" )
if not os.isdir( targetDir ) then
zpm.assert( os.mkdir( targetDir ), "Could not create asset directory '%s'!", targetDir )
end
os.copyfile( file, target )
zpm.assert( os.isfile(target), "Could not make file '%s'!", target )
end
end
end
function zpm.assets.commands.extractto( repo, folder, files, to )
if (type(files) ~= "table") then
files = {files}
end
for _, pattern in ipairs( files ) do
for _, file in ipairs( os.matchfiles( path.join( repo, pattern ) ) ) do
local target = path.join( os.getcwd(), to, path.getrelative( repo, file ) )
local targetDir = path.getdirectory( target )
print(target, path.getabsolute( targetDir ), ( os.getcwd() ))
zpm.assert( path.getabsolute( targetDir ):contains( os.getcwd() ), "Executing lua outside folder is not allowed!" )
if not os.isdir( targetDir ) then
zpm.assert( os.mkdir( targetDir ), "Could not create asset directory '%s'!", targetDir )
end
os.copyfile( file, target )
zpm.assert( os.isfile(target), "Could not make file '%s'!", target )
end
end
end
function zpm.assets.commands.download( repo, folder, url, to )
local targetDir = path.join( folder, to )
zpm.assert( path.getabsolute( targetDir ):contains( os.getcwd() ), "Executing lua outside assets folder is not allowed!" )
if not os.isdir( targetDir ) then
zpm.assert( os.mkdir( targetDir ), "Could not create asset directory '%s'!", targetDir )
end
zpm.util.download( url, targetDir, "*" )
end
|
--[[ @cond ___LICENSE___
-- Copyright (c) 2016 Koen Visscher, Paul Visscher and individual contributors.
--
-- Permission is hereby granted, free of charge, to any person obtaining a copy
-- of this software and associated documentation files (the "Software"), to deal
-- in the Software without restriction, including without limitation the rights
-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-- copies of the Software, and to permit persons to whom the Software is
-- furnished to do so, subject to the following conditions:
--
-- The above copyright notice and this permission notice shall be included in
-- all copies or substantial portions of the Software.
--
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-- THE SOFTWARE.
--
-- @endcond
--]]
zpm.assets.commands = {}
function zpm.assets.commands.extract( repo, folder, files )
if (type(files) ~= "table") then
files = {files}
end
for _, pattern in ipairs( files ) do
for _, file in ipairs( os.matchfiles( path.join( repo, pattern ) ) ) do
local target = path.join( folder, path.getrelative( repo, file ) )
local targetDir = path.getdirectory( target )
zpm.assert( path.getabsolute( targetDir ):contains( _MAIN_SCRIPT_DIR ), "Executing lua outside folder is not allowed!" )
if not os.isdir( targetDir ) then
zpm.assert( os.mkdir( targetDir ), "Could not create asset directory '%s'!", targetDir )
end
os.copyfile( file, target )
zpm.assert( os.isfile(target), "Could not make file '%s'!", target )
end
end
end
function zpm.assets.commands.extractto( repo, folder, files, to )
if (type(files) ~= "table") then
files = {files}
end
for _, pattern in ipairs( files ) do
for _, file in ipairs( os.matchfiles( path.join( repo, pattern ) ) ) do
local target = path.join( _MAIN_SCRIPT_DIR, to, path.getrelative( repo, file ) )
local targetDir = path.getdirectory( target )
zpm.assert( path.getabsolute( targetDir ):contains( _MAIN_SCRIPT_DIR ), "Executing lua outside folder is not allowed!" )
if not os.isdir( targetDir ) then
zpm.assert( os.mkdir( targetDir ), "Could not create asset directory '%s'!", targetDir )
end
os.copyfile( file, target )
zpm.assert( os.isfile(target), "Could not make file '%s'!", target )
end
end
end
function zpm.assets.commands.download( repo, folder, url, to )
local targetDir = path.join( folder, to )
zpm.assert( path.getabsolute( targetDir ):contains( _MAIN_SCRIPT_DIR ), "Executing lua outside assets folder is not allowed!" )
if not os.isdir( targetDir ) then
zpm.assert( os.mkdir( targetDir ), "Could not create asset directory '%s'!", targetDir )
end
zpm.util.download( url, targetDir, "*" )
end
|
Revert "Fix asset path"
|
Revert "Fix asset path"
This reverts commit 20c453e43c6abd8ebc9412389723875c90810daa.
|
Lua
|
mit
|
Zefiros-Software/ZPM
|
501598c58c1af35886a98c0465d96026352c3058
|
TemporalConvolution.lua
|
TemporalConvolution.lua
|
local TemporalConvolution, parent =
torch.class('cudnn.TemporalConvolution', 'nn.TemporalConvolution')
--use cudnn to perform temporal convolutions
--note: if padH parameter is not passed, no padding will be performed, as in parent TemporalConvolution
--however, instead of separately padding data, as is required now for nn.TemporalConvolution,
--it is recommended to pass padding parameter to this routine and use cudnn implicit padding facilities.
--limitation is that padding will be equal on both sides.
function TemporalConvolution:__init(inputFrameSize, outputFrameSize,
kH, dH, padH)
local delayedReset = self.reset
local kW = inputFrameSize
local nInputPlane = 1 -- single channel
local nOutputPlane = outputFrameSize
self.inputFrameSize = inputFrameSize
self.outputFrameSize = outputFramesize
cudnn.SpatialConvolution.__init(self, nInputPlane, nOutputPlane, kW, kH, 1, dH,0,padH)
self.weight = self.weight:view(nOutputPlane,inputFrameSize*kH)
self.gradWeight = self.gradWeight:view(outputFrameSize, inputFrameSize*kH)
--self.dW and self.kW now have different meaning than in nn.TemporalConvolution, because
--W and H are switched in temporal and spatial
end
function TemporalConvolution:createIODescriptors(input)
local sizeChanged = false
if not self.iDesc or not self.oDesc or
input:size(1) ~= self.iSize[1] or input:size(2) ~= self.iSize[2]
or input:size(3) ~= self.iSize[3] or input:size(4) ~= self.iSize[4] then
sizeChanged = true
end
cudnn.SpatialConvolution.createIODescriptors(self,input)
if sizeChanged then
self.oSize = self.output:size()
end
end
function TemporalConvolution:fastest(mode)
self = cudnn.SpatialConvolution.fastest(self,mode)
return self
end
function TemporalConvolution:resetWeightDescriptors()
cudnn.SpatialConvolution.resetWeightDescriptors(self)
end
local function inputview(input)
local _input = input
if input:dim()==2 then
_input = input:view(1,input:size(1),input:size(2))
end
return _input:view(_input:size(1),1,_input:size(2),_input:size(3))
end
function TemporalConvolution:updateOutput(input)
local _input = inputview(input)
assert(_input:size(4) == self.inputFrameSize,'invalid input frame size')
self.buffer = self.buffer or torch.CudaTensor()
self._output = self._output or torch.CudaTensor()
if self.output:storage() then self._output:set(self.output:storage()) else self._output = self.output end
if self.buffer:storage() then self.output:set(self.buffer:storage()) else self.output = self.buffer end
cudnn.SpatialConvolution.updateOutput(self,_input)
self.buffer = self.output:view(self.oSize):transpose(2,3)
self.output = self._output:resize(self.buffer:size()):copy(self.buffer)
-- self.output here is always 4D, use input dimensions to properly view output
if input:dim()==3 then
self.output=self.output:view(self.oSize[1], self.oSize[3],self.oSize[2])
else
self.output=self.output:view(self.oSize[3], self.oSize[2])
end
return self.output
end
local function transposeGradOutput(src,dst)
assert(src:dim() == 2 or src:dim() == 3, 'gradOutput has to be 2D or 3D');
local srctransposed = src:transpose(src:dim(),src:dim()-1)
dst:resize(srctransposed:size())
dst:copy(srctransposed)
if src:dim()==3 then
dst = dst:view(dst:size(1),dst:size(2),dst:size(3),1)
else
dst = dst:view(dst:size(1),dst:size(2),1)
end
return dst
end
function TemporalConvolution:updateGradInput(input, gradOutput)
if not self.gradInput then return end
local _gradOutput = transposeGradOutput(gradOutput,self.buffer)
local _input = inputview(input)
self.gradInput = cudnn.SpatialConvolution.updateGradInput(self,_input, _gradOutput)
if input:dim()==3 then
self.gradInput = self.gradInput:view(self.gradInput:size(1),self.gradInput:size(3),self.gradInput:size(4))
else
self.gradInput = self.gradInput:view(self.gradInput:size(3),self.gradInput:size(4))
end
return self.gradInput
end
function TemporalConvolution:accGradParameters(input,gradOutput,scale)
--2d (4d) view of input
local _input = inputview(input)
-- transpose gradOutput (it will likely be transposed twice, hopefully, no big deal
local _gradOutput = transposeGradOutput(gradOutput,self.buffer)
cudnn.SpatialConvolution.accGradParameters(self,_input,_gradOutput,scale)
end
function TemporalConvolution:write(f)
self.buffer = nil
self._ouptut = nil
self.oSize = nil
cudnn.SpatialConvolution.write(self,f)
end
|
local TemporalConvolution, parent =
torch.class('cudnn.TemporalConvolution', 'nn.TemporalConvolution')
--use cudnn to perform temporal convolutions
--note: if padH parameter is not passed, no padding will be performed, as in parent TemporalConvolution
--however, instead of separately padding data, as is required now for nn.TemporalConvolution,
--it is recommended to pass padding parameter to this routine and use cudnn implicit padding facilities.
--limitation is that padding will be equal on both sides.
function TemporalConvolution:__init(inputFrameSize, outputFrameSize,
kH, dH, padH)
local delayedReset = self.reset
local kW = inputFrameSize
local nInputPlane = 1 -- single channel
local nOutputPlane = outputFrameSize
self.inputFrameSize = inputFrameSize
self.outputFrameSize = outputFramesize
cudnn.SpatialConvolution.__init(self, nInputPlane, nOutputPlane, kW, kH, 1, dH,0,padH)
self.weight = self.weight:view(nOutputPlane,inputFrameSize*kH)
self.gradWeight = self.gradWeight:view(outputFrameSize, inputFrameSize*kH)
--self.dW and self.kW now have different meaning than in nn.TemporalConvolution, because
--W and H are switched in temporal and spatial
end
function TemporalConvolution:createIODescriptors(input)
local sizeChanged = false
if not self.iDesc or not self.oDesc or
input:size(1) ~= self.iSize[1] or input:size(2) ~= self.iSize[2]
or input:size(3) ~= self.iSize[3] or input:size(4) ~= self.iSize[4] then
sizeChanged = true
end
cudnn.SpatialConvolution.createIODescriptors(self,input)
if sizeChanged then
self.oSize = self.output:size()
end
end
function TemporalConvolution:fastest(mode)
self = cudnn.SpatialConvolution.fastest(self,mode)
return self
end
function TemporalConvolution:resetWeightDescriptors()
cudnn.SpatialConvolution.resetWeightDescriptors(self)
end
local function inputview(input)
local _input = input
if input:dim()==2 then
_input = input:view(1,input:size(1),input:size(2))
end
return _input:view(_input:size(1),1,_input:size(2),_input:size(3))
end
function TemporalConvolution:updateOutput(input)
local _input = inputview(input)
assert(_input:size(4) == self.inputFrameSize,'invalid input frame size')
self.buffer = self.buffer or torch.CudaTensor()
self._output = self._output or torch.CudaTensor()
if self.output:storage() then self._output:set(self.output:storage()) else self._output = self.output end
if self.buffer:storage() then self.output:set(self.buffer:storage()) else self.output = self.buffer end
cudnn.SpatialConvolution.updateOutput(self,_input)
self.buffer = self.output:view(self.oSize):transpose(2,3)
self.output = self._output:resize(self.buffer:size()):copy(self.buffer)
-- self.output here is always 4D, use input dimensions to properly view output
if input:dim()==3 then
self.output=self.output:view(self.oSize[1], self.oSize[3],self.oSize[2])
else
self.output=self.output:view(self.oSize[3], self.oSize[2])
end
return self.output
end
local function transposeGradOutput(src,dst)
assert(src:dim() == 2 or src:dim() == 3, 'gradOutput has to be 2D or 3D');
local srctransposed = src:transpose(src:dim(),src:dim()-1)
dst:resize(srctransposed:size())
dst:copy(srctransposed)
if src:dim()==3 then
dst = dst:view(dst:size(1),dst:size(2),dst:size(3),1)
else
dst = dst:view(dst:size(1),dst:size(2),1)
end
return dst
end
function TemporalConvolution:updateGradInput(input, gradOutput)
if not self.gradInput then return end
local _gradOutput = transposeGradOutput(gradOutput,self.buffer)
local _input = inputview(input)
self.gradInput = cudnn.SpatialConvolution.updateGradInput(self,_input, _gradOutput)
if input:dim()==3 then
self.gradInput = self.gradInput:view(self.gradInput:size(1),self.gradInput:size(3),self.gradInput:size(4))
else
self.gradInput = self.gradInput:view(self.gradInput:size(3),self.gradInput:size(4))
end
return self.gradInput
end
function TemporalConvolution:accGradParameters(input,gradOutput,scale)
--2d (4d) view of input
local _input = inputview(input)
-- transpose gradOutput (it will likely be transposed twice, hopefully, no big deal
local _gradOutput = transposeGradOutput(gradOutput,self.buffer)
cudnn.SpatialConvolution.accGradParameters(self,_input,_gradOutput,scale)
end
function TemporalConvolution:write(f)
self.buffer = nil
self._ouptut = nil
self.oSize = nil
cudnn.SpatialConvolution.clearDesc(self)
local var = {}
for k,v in pairs(self) do
var[k] = v
end
f:writeObject(var)
end
|
fixing TemporalConvolution serialization after cudnn.convert
|
fixing TemporalConvolution serialization after cudnn.convert
|
Lua
|
bsd-3-clause
|
phunghx/phnn.torch,phunghx/phnn.torch,phunghx/phnn.torch
|
7e7072b8aa5a0371662c15ee950acfedfba33765
|
mod_manifesto/mod_manifesto.lua
|
mod_manifesto/mod_manifesto.lua
|
-- mod_manifesto
local timer = require "util.timer";
local jid_split = require "util.jid".split;
local st = require "util.stanza";
local dm = require "util.datamanager";
local time = os.time;
local hosts = prosody.hosts;
local host = module.host;
local host_session = hosts[host];
local incoming_s2s = prosody.incoming_s2s;
local default_tpl = [[
Hello there.
This is a brief system message to let you know about some upcoming changes to the $HOST service.
Some of your contacts are on other Jabber/XMPP services that do not support encryption. As part of an initiative to increase the security of the Jabber/XMPP network, this service ($HOST) will be participating in a series of tests to discover the impact of our planned changes, and you may lose the ability to communicate with some of your contacts.
The test days well be on the following dates: January 4, February 22, March 22 and April 19. On these days we will require that all client and server connections are encrypted. Unless they enable encryption before that, you will be unable to communicate with your contacts that use these services:
$SERVICES
Your affected contacts are:
$CONTACTS
What can you do? You may tell your contacts to inform their service administrator about their lack of encryption. Your contacts may also switch to a more secure service. A list of public services can be found at https://xmpp.net/directory.php
For more information about the Jabber/XMPP security initiative that we are participating in, please read the announcement at https://stpeter.im/journal/1496.html
If you have any questions or concerns, you may contact us via $CONTACTVIA at $CONTACT
]];
local message = module:get_option_string("manifesto_contact_encryption_warning", default_tpl);
local contact = module:get_option_string("admin_contact_address", module:get_option_array("admins", {})[1]);
if not contact then
error("mod_manifesto needs you to set 'admin_contact_address' in your config file.", 0);
end
local contact_method = "Jabber/XMPP";
if select(2, contact:gsub("^mailto:", "")) > 0 then
contact_method = "email";
end
local notified;
module:hook("resource-bind", function (event)
local session = event.session;
local now = time();
local last_notify = notified[session.username] or 0;
if last_notify > ( now - 86400 * 7 ) then
return
end
timer.add_task(15, function ()
local bad_contacts, bad_hosts = {}, {};
for contact_jid, item in pairs(session.roster or {}) do
local _, contact_host = jid_split(contact_jid);
local bad = false;
local remote_host_session = host_session.s2sout[contact_host];
if remote_host_session and remote_host_session.type == "s2sout" then -- Only check remote hosts we have completed s2s connections to
if not remote_host_session.secure then
bad = true;
end
end
for session in pairs(incoming_s2s) do
if session.to_host == host and session.from_host == contact_host and session.type == "s2sin" then
if not session.secure then
bad = true;
end
end
end
if bad then
local contact_name = item.name;
if contact_name then
table.insert(bad_contacts, contact_name.." <"..contact_jid..">");
else
table.insert(bad_contacts, contact_jid);
end
if not bad_hosts[contact_host] then
bad_hosts[contact_host] = true;
table.insert(bad_hosts, contact_host);
end
end
end
if #bad_contacts > 0 then
local vars = {
HOST = host;
CONTACTS = " "..table.concat(bad_contacts, "\n ");
SERVICES = " "..table.concat(bad_hosts, "\n ");
CONTACTVIA = contact_method, CONTACT = contact;
};
session.send(st.message({ type = "headline", from = host }):tag("body"):text(message:gsub("$(%w+)", vars)));
end
notified[session.username] = now;
end);
end);
function module.load()
notified = dm.load(nil, host, module.name) or {};
end
function module.save()
dm.store(nil, host, module.name, notified);
return { notified = notified };
end
function module.restore(data)
notified = data.notified;
end
function module.unload()
dm.store(nil, host, module.name, notified);
end
function module.uninstall()
dm.store(nil, host, module.name, nil);
end
|
-- mod_manifesto
local timer = require "util.timer";
local jid_split = require "util.jid".split;
local st = require "util.stanza";
local dm = require "util.datamanager";
local time = os.time;
local hosts = prosody.hosts;
local host = module.host;
local host_session = hosts[host];
local incoming_s2s = prosody.incoming_s2s;
local default_tpl = [[
Hello there.
This is a brief system message to let you know about some upcoming changes to the $HOST service.
Some of your contacts are on other Jabber/XMPP services that do not support encryption. As part of an initiative to increase the security of the Jabber/XMPP network, this service ($HOST) will be participating in a series of tests to discover the impact of our planned changes, and you may lose the ability to communicate with some of your contacts.
The test days well be on the following dates: January 4, February 22, March 22 and April 19. On these days we will require that all client and server connections are encrypted. Unless they enable encryption before that, you will be unable to communicate with your contacts that use these services:
$SERVICES
Your affected contacts are:
$CONTACTS
What can you do? You may tell your contacts to inform their service administrator about their lack of encryption. Your contacts may also switch to a more secure service. A list of public services can be found at https://xmpp.net/directory.php
For more information about the Jabber/XMPP security initiative that we are participating in, please read the announcement at https://stpeter.im/journal/1496.html
If you have any questions or concerns, you may contact us via $CONTACTVIA at $CONTACT
]];
local message = module:get_option_string("manifesto_contact_encryption_warning", default_tpl);
local contact = module:get_option_string("admin_contact_address", module:get_option_array("admins", {})[1]);
if not contact then
error("mod_manifesto needs you to set 'admin_contact_address' in your config file.", 0);
end
local contact_method = "Jabber/XMPP";
if select(2, contact:gsub("^mailto:", "")) > 0 then
contact_method = "email";
end
local notified;
module:hook("resource-bind", function (event)
local session = event.session;
local now = time();
local last_notify = notified[session.username] or 0;
if last_notify > ( now - 86400 * 7 ) then
return
end
timer.add_task(15, function ()
if session.type ~= "c2s" then return end -- user quit already
local bad_contacts, bad_hosts = {}, {};
for contact_jid, item in pairs(session.roster or {}) do
local _, contact_host = jid_split(contact_jid);
local bad = false;
local remote_host_session = host_session.s2sout[contact_host];
if remote_host_session and remote_host_session.type == "s2sout" then -- Only check remote hosts we have completed s2s connections to
if not remote_host_session.secure then
bad = true;
end
end
for session in pairs(incoming_s2s) do
if session.to_host == host and session.from_host == contact_host and session.type == "s2sin" then
if not session.secure then
bad = true;
end
end
end
if bad then
local contact_name = item.name;
if contact_name then
table.insert(bad_contacts, contact_name.." <"..contact_jid..">");
else
table.insert(bad_contacts, contact_jid);
end
if not bad_hosts[contact_host] then
bad_hosts[contact_host] = true;
table.insert(bad_hosts, contact_host);
end
end
end
if #bad_contacts > 0 then
local vars = {
HOST = host;
CONTACTS = " "..table.concat(bad_contacts, "\n ");
SERVICES = " "..table.concat(bad_hosts, "\n ");
CONTACTVIA = contact_method, CONTACT = contact;
};
session.send(st.message({ type = "headline", from = host }):tag("body"):text(message:gsub("$(%w+)", vars)));
end
notified[session.username] = now;
end);
end);
function module.load()
notified = dm.load(nil, host, module.name) or {};
end
function module.save()
dm.store(nil, host, module.name, notified);
return { notified = notified };
end
function module.restore(data)
notified = data.notified;
end
function module.unload()
dm.store(nil, host, module.name, notified);
end
function module.uninstall()
dm.store(nil, host, module.name, nil);
end
|
mod_manifesto: Fix traceback when user disconnects before the timer (fixes #48)
|
mod_manifesto: Fix traceback when user disconnects before the timer (fixes #48)
|
Lua
|
mit
|
prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2
|
1026d63ba37b8a1074c49797ce737edb5726ed2f
|
spec/config_spec.lua
|
spec/config_spec.lua
|
local test_env = require("test/test_environment")
local lfs = require("lfs")
local run = test_env.run
local testing_paths = test_env.testing_paths
local env_variables = test_env.env_variables
local site_config
test_env.unload_luarocks()
describe("LuaRocks config tests #blackbox #b_config", function()
before_each(function()
test_env.setup_specs()
test_env.unload_luarocks() -- need to be required here, because site_config is created after first loading of specs
site_config = require("luarocks.site_config")
end)
describe("LuaRocks config - basic tests", function()
it("LuaRocks config with no flags/arguments", function()
assert.is_false(run.luarocks_bool("config"))
end)
it("LuaRocks config include dir", function()
local output = run.luarocks("config --lua-incdir")
if test_env.TEST_TARGET_OS == "windows" then
assert.are.same(output, site_config.LUA_INCDIR:gsub("\\","/"))
else
assert.are.same(output, site_config.LUA_INCDIR)
end
end)
it("LuaRocks config library dir", function()
local output = run.luarocks("config --lua-libdir")
if test_env.TEST_TARGET_OS == "windows" then
assert.are.same(output, site_config.LUA_LIBDIR:gsub("\\","/"))
else
assert.are.same(output, site_config.LUA_LIBDIR)
end
end)
it("LuaRocks config lua version", function()
local output = run.luarocks("config --lua-ver")
local lua_version = _VERSION:gsub("Lua ", "")
if test_env.LUAJIT_V then
lua_version = "5.1"
end
assert.are.same(output, lua_version)
end)
it("LuaRocks config rock trees", function()
assert.is_true(run.luarocks_bool("config --rock-trees"))
end)
it("LuaRocks config user config", function()
local user_config_path = run.luarocks("config --user-config")
assert.is.truthy(lfs.attributes(user_config_path))
end)
it("LuaRocks config missing user config", function()
assert.is_false(run.luarocks_bool("config --user-config", {LUAROCKS_CONFIG = "missing_file.lua"}))
end)
end)
describe("LuaRocks config - more complex tests #special", function()
local scdir = testing_paths.testing_lrprefix .. "/etc/luarocks"
local versioned_scname = scdir .. "/config-" .. env_variables.LUA_VERSION .. ".lua"
local scname = scdir .. "/config.lua"
local configfile
if test_env.TEST_TARGET_OS == "windows" then
configfile = versioned_scname
else
configfile = scname
end
it("LuaRocks fail system config", function()
os.rename(configfile, configfile .. ".bak")
assert.is_false(run.luarocks_bool("config --system-config"))
os.rename(configfile .. ".bak", configfile)
end)
it("LuaRocks system config", function()
lfs.mkdir(testing_paths.testing_lrprefix)
lfs.mkdir(testing_paths.testing_lrprefix .. "/etc/")
lfs.mkdir(scdir)
-- if test_env.TEST_TARGET_OS == "windows" then
-- local output = run.luarocks("config --system-config")
-- assert.are.same(output, versioned_scname)
-- else
local sysconfig = io.open(configfile, "w+")
test_env.copy(configfile, "configfile_temp")
sysconfig:write(" ")
sysconfig:close()
local output = run.luarocks("config --system-config")
assert.are.same(output, configfile)
test_env.copy("configfile_temp", configfile)
os.remove("configfile_temp")
-- end
end)
it("LuaRocks fail system config invalid", function()
lfs.mkdir(testing_paths.testing_lrprefix)
lfs.mkdir(testing_paths.testing_lrprefix .. "/etc/")
lfs.mkdir(scdir)
-- if test_env.TEST_TARGET_OS == "windows" then
sysconfig = io.open(configfile, "w+")
test_env.copy(configfile, "configfile_temp")
sysconfig:write("if if if")
sysconfig:close()
assert.is_false(run.luarocks_bool("config --system-config"))
test_env.copy("configfile_temp", configfile)
os.remove("configfile_temp")
-- else
-- sysconfig = io.open(scname, "w+")
-- sysconfig:write("if if if")
-- sysconfig:close()
-- assert.is_false(run.luarocks_bool("config --system-config"))
-- os.remove(scname)
-- end
end)
end)
end)
|
local test_env = require("test/test_environment")
local lfs = require("lfs")
local run = test_env.run
local testing_paths = test_env.testing_paths
local env_variables = test_env.env_variables
local site_config
test_env.unload_luarocks()
describe("LuaRocks config tests #blackbox #b_config", function()
before_each(function()
test_env.setup_specs()
test_env.unload_luarocks() -- need to be required here, because site_config is created after first loading of specs
site_config = require("luarocks.site_config")
end)
describe("LuaRocks config - basic tests", function()
it("LuaRocks config with no flags/arguments", function()
assert.is_false(run.luarocks_bool("config"))
end)
it("LuaRocks config include dir", function()
local output = run.luarocks("config --lua-incdir")
if test_env.TEST_TARGET_OS == "windows" then
assert.are.same(output, site_config.LUA_INCDIR:gsub("\\","/"))
else
assert.are.same(output, site_config.LUA_INCDIR)
end
end)
it("LuaRocks config library dir", function()
local output = run.luarocks("config --lua-libdir")
if test_env.TEST_TARGET_OS == "windows" then
assert.are.same(output, site_config.LUA_LIBDIR:gsub("\\","/"))
else
assert.are.same(output, site_config.LUA_LIBDIR)
end
end)
it("LuaRocks config lua version", function()
local output = run.luarocks("config --lua-ver")
local lua_version = _VERSION:gsub("Lua ", "")
if test_env.LUAJIT_V then
lua_version = "5.1"
end
assert.are.same(output, lua_version)
end)
it("LuaRocks config rock trees", function()
assert.is_true(run.luarocks_bool("config --rock-trees"))
end)
it("LuaRocks config user config", function()
local user_config_path = run.luarocks("config --user-config")
assert.is.truthy(lfs.attributes(user_config_path))
end)
it("LuaRocks config missing user config", function()
assert.is_false(run.luarocks_bool("config --user-config", {LUAROCKS_CONFIG = "missing_file.lua"}))
end)
end)
describe("LuaRocks config - more complex tests", function()
local scdir = testing_paths.testing_lrprefix .. "/etc/luarocks"
local versioned_scname = scdir .. "/config-" .. env_variables.LUA_VERSION .. ".lua"
local scname = scdir .. "/config.lua"
local configfile
if test_env.TEST_TARGET_OS == "windows" then
configfile = versioned_scname
else
configfile = scname
end
it("LuaRocks fail system config", function()
os.rename(configfile, configfile .. ".bak")
assert.is_false(run.luarocks_bool("config --system-config"))
os.rename(configfile .. ".bak", configfile)
end)
it("LuaRocks system config", function()
lfs.mkdir(testing_paths.testing_lrprefix)
lfs.mkdir(testing_paths.testing_lrprefix .. "/etc/")
lfs.mkdir(scdir)
if test_env.TEST_TARGET_OS == "windows" then
local output = run.luarocks("config --system-config")
assert.are.same(output, configfile)
else
local sysconfig = io.open(configfile, "w+")
sysconfig:write(" ")
sysconfig:close()
local output = run.luarocks("config --system-config")
assert.are.same(output, configfile)
os.remove(configfile)
end
end)
it("LuaRocks fail system config invalid", function()
lfs.mkdir(testing_paths.testing_lrprefix)
lfs.mkdir(testing_paths.testing_lrprefix .. "/etc/")
lfs.mkdir(scdir)
if test_env.TEST_TARGET_OS == "windows" then
test_env.copy(configfile, "configfile_temp")
local sysconfig = io.open(configfile, "w+")
sysconfig:write("if if if")
sysconfig:close()
assert.is_false(run.luarocks_bool("config --system-config"))
test_env.copy("configfile_temp", configfile)
else
local sysconfig = io.open(configfile, "w+")
sysconfig:write("if if if")
sysconfig:close()
assert.is_false(run.luarocks_bool("config --system-config"))
os.remove(configfile)
end
end)
end)
end)
|
Fix of config test
|
Fix of config test
|
Lua
|
mit
|
robooo/luarocks,xpol/luavm,tarantool/luarocks,xpol/luarocks,keplerproject/luarocks,xpol/luarocks,xpol/luarocks,tarantool/luarocks,xpol/luavm,keplerproject/luarocks,keplerproject/luarocks,xpol/luainstaller,robooo/luarocks,keplerproject/luarocks,tarantool/luarocks,robooo/luarocks,xpol/luainstaller,xpol/luavm,xpol/luarocks,luarocks/luarocks,xpol/luainstaller,xpol/luavm,luarocks/luarocks,robooo/luarocks,xpol/luainstaller,luarocks/luarocks,xpol/luavm
|
759c19da827d1112c03b71163caa63ddc453b7ba
|
specs/alias_spec.lua
|
specs/alias_spec.lua
|
context('Object functions specs', function()
local _ = require 'moses'
test('Not defining MOSES_ALIASES before calling Moses will not import aliases', function()
assert_nil(_.forEach)
assert_nil(_.collect)
assert_nil(_.inject)
assert_nil(_.foldl)
assert_nil(_.injectr)
assert_nil(_.foldr)
assert_nil(_.mapr)
assert_nil(_.maprr)
assert_nil(_.any)
assert_nil(_.some)
assert_nil(_.find)
assert_nil(_.filter)
assert_nil(_.discard)
assert_nil(_.every)
assert_nil(_.takeWhile)
assert_nil(_.rejectWhile)
assert_nil(_.shift)
assert_nil(_.rmRange)
assert_nil(_.head)
assert_nil(_.take)
assert_nil(_.tail)
assert_nil(_.without)
assert_nil(_.unique)
assert_nil(_.mirror)
assert_nil(_.join)
assert_nil(_.cache)
assert_nil(_.uId)
assert_nil(_.methods)
assert_nil(_.choose)
assert_nil(_.drop)
assert_nil(_.defaults)
end)
end)
context('Object functions specs', function()
package.loaded.moses = nil
_G.MOSES_ALIASES = true
local _ = require 'moses'
test('Setting MOSES_ALIASES to true before calling Moses will import aliases', function()
assert_not_nil(_.forEach)
assert_not_nil(_.collect)
assert_not_nil(_.inject)
assert_not_nil(_.foldl)
assert_not_nil(_.injectr)
assert_not_nil(_.foldr)
assert_not_nil(_.mapr)
assert_not_nil(_.maprr)
assert_not_nil(_.any)
assert_not_nil(_.some)
assert_not_nil(_.find)
assert_not_nil(_.filter)
assert_not_nil(_.discard)
assert_not_nil(_.every)
assert_not_nil(_.takeWhile)
assert_not_nil(_.rejectWhile)
assert_not_nil(_.shift)
assert_not_nil(_.rmRange)
assert_not_nil(_.head)
assert_not_nil(_.take)
assert_not_nil(_.tail)
assert_not_nil(_.without)
assert_not_nil(_.unique)
assert_not_nil(_.mirror)
assert_not_nil(_.join)
assert_not_nil(_.cache)
assert_not_nil(_.uId)
assert_not_nil(_.methods)
assert_not_nil(_.choose)
assert_not_nil(_.drop)
assert_not_nil(_.defaults)
end)
end)
|
context('Disabling aliases', function()
local _ = require 'moses'
test('Not defining MOSES_ALIASES before calling Moses will not import aliases', function()
assert_nil(_.forEach)
assert_nil(_.collect)
assert_nil(_.inject)
assert_nil(_.foldl)
assert_nil(_.injectr)
assert_nil(_.foldr)
assert_nil(_.mapr)
assert_nil(_.maprr)
assert_nil(_.any)
assert_nil(_.some)
assert_nil(_.find)
assert_nil(_.filter)
assert_nil(_.discard)
assert_nil(_.every)
assert_nil(_.takeWhile)
assert_nil(_.rejectWhile)
assert_nil(_.shift)
assert_nil(_.rmRange)
assert_nil(_.head)
assert_nil(_.take)
assert_nil(_.tail)
assert_nil(_.without)
assert_nil(_.unique)
assert_nil(_.mirror)
assert_nil(_.join)
assert_nil(_.cache)
assert_nil(_.uId)
assert_nil(_.methods)
assert_nil(_.choose)
assert_nil(_.drop)
assert_nil(_.defaults)
end)
end)
context('Enabling aliases', function()
package.loaded.moses = nil
_G.MOSES_ALIASES = true
local _ = require 'moses'
test('Setting MOSES_ALIASES to true before calling Moses will import aliases', function()
assert_not_nil(_.forEach)
assert_not_nil(_.collect)
assert_not_nil(_.inject)
assert_not_nil(_.foldl)
assert_not_nil(_.injectr)
assert_not_nil(_.foldr)
assert_not_nil(_.mapr)
assert_not_nil(_.maprr)
assert_not_nil(_.any)
assert_not_nil(_.some)
assert_not_nil(_.find)
assert_not_nil(_.filter)
assert_not_nil(_.discard)
assert_not_nil(_.every)
assert_not_nil(_.takeWhile)
assert_not_nil(_.rejectWhile)
assert_not_nil(_.shift)
assert_not_nil(_.rmRange)
assert_not_nil(_.head)
assert_not_nil(_.take)
assert_not_nil(_.tail)
assert_not_nil(_.without)
assert_not_nil(_.unique)
assert_not_nil(_.mirror)
assert_not_nil(_.join)
assert_not_nil(_.cache)
assert_not_nil(_.uId)
assert_not_nil(_.methods)
assert_not_nil(_.choose)
assert_not_nil(_.drop)
assert_not_nil(_.defaults)
end)
end)
|
Fixed aliases spec contexts names
|
Fixed aliases spec contexts names
|
Lua
|
mit
|
ignacio/Moses,AntonioModer/Moses,takaaptech/Moses
|
714bc13720056d6cc6dc0eecce98eddafe91483b
|
frontend/ui/device/screen.lua
|
frontend/ui/device/screen.lua
|
local Geom = require("ui/geometry")
local DEBUG = require("dbg")
-- Blitbuffer
-- einkfb
--[[
Codes for rotation modes:
1 for no rotation,
2 for landscape with bottom on the right side of screen, etc.
2
+--------------+
| +----------+ |
| | | |
| | Freedom! | |
| | | |
| | | |
3 | | | | 1
| | | |
| | | |
| +----------+ |
| |
| |
+--------------+
0
--]]
local Screen = {
cur_rotation_mode = 0,
native_rotation_mode = nil,
blitbuffer_rotation_mode = 0,
bb = nil,
saved_bb = nil,
fb = einkfb.open("/dev/fb0"),
-- will be set upon loading by Device class:
device = nil,
}
function Screen:init()
self.bb = self.fb.bb
self.blitbuffer_rotation_mode = self.bb:getRotation()
-- asking the framebuffer for orientation is error prone,
-- so we do this simple heuristic (for now)
if self:getWidth() > self:getHeight() then
self.native_rotation_mode = 1
else
self.native_rotation_mode = 0
end
self.cur_rotation_mode = self.native_rotation_mode
end
function Screen:refresh(refresh_type, waveform_mode, x, y, w, h)
self.fb:refresh(refresh_type, waveform_mode, x, y, w, h)
end
function Screen:getSize()
return Geom:new{w = self.bb:getWidth(), h = self.bb:getHeight()}
end
function Screen:getWidth()
return self.bb:getWidth()
end
function Screen:getHeight()
return self.bb:getHeight()
end
function Screen:getDPI()
if(self.device:getModel() == "KindlePaperWhite")
or (self.device:getModel() == "Kobo_kraken")
or (self.device:getModel() == "Kobo_phoenix") then
return 212
elseif self.device:getModel() == "Kobo_dragon" then
return 265
elseif self.device:getModel() == "Kobo_pixie" then
return 200
else
return 167
end
end
function Screen:scaleByDPI(px)
return math.floor(px * self:getDPI()/167)
end
function Screen:rescaleByDPI(px)
return math.ceil(px * 167/self:getDPI())
end
function Screen:getRotationMode()
return self.cur_rotation_mode
end
function Screen:getScreenMode()
if self:getWidth() > self:getHeight() then
return "landscape"
else
return "portrait"
end
end
function Screen:setRotationMode(mode)
self.fb.bb:rotateAbsolute(-90 * (mode - self.native_rotation_mode - self.blitbuffer_rotation_mode))
self.cur_rotation_mode = mode
end
function Screen:setScreenMode(mode)
if mode == "portrait" then
if self.cur_rotation_mode ~= 0 then
self:setRotationMode(0)
end
elseif mode == "landscape" then
if self.cur_rotation_mode == 0 or self.cur_rotation_mode == 2 then
self:setRotationMode(DLANDSCAPE_CLOCKWISE_ROTATION and 1 or 3)
elseif self.cur_rotation_mode == 1 or self.cur_rotation_mode == 3 then
self:setRotationMode((self.cur_rotation_mode + 2) % 4)
end
end
end
function Screen:saveCurrentBB()
local width, height = self:getWidth(), self:getHeight()
if not self.saved_bb then
self.saved_bb = Blitbuffer.new(width, height)
end
if self.saved_bb:getWidth() ~= width then
self.saved_bb:free()
self.saved_bb = Blitbuffer.new(width, height)
end
self.saved_bb:blitFullFrom(self.bb)
end
function Screen:restoreFromSavedBB()
self:restoreFromBB(self.saved_bb)
-- free data
self.saved_bb = nil
end
function Screen:getCurrentScreenBB()
local bb = Blitbuffer.new(self:getWidth(), self:getHeight())
bb:blitFullFrom(self.bb)
return bb
end
function Screen:restoreFromBB(bb)
if bb then
self.bb:blitFullFrom(bb)
else
DEBUG("Got nil bb in restoreFromSavedBB!")
end
end
return Screen
|
local Geom = require("ui/geometry")
local DEBUG = require("dbg")
-- Blitbuffer
-- einkfb
--[[
Codes for rotation modes:
1 for no rotation,
2 for landscape with bottom on the right side of screen, etc.
2
+--------------+
| +----------+ |
| | | |
| | Freedom! | |
| | | |
| | | |
3 | | | | 1
| | | |
| | | |
| +----------+ |
| |
| |
+--------------+
0
--]]
local Screen = {
cur_rotation_mode = 0,
native_rotation_mode = nil,
blitbuffer_rotation_mode = 0,
bb = nil,
saved_bb = nil,
fb = einkfb.open("/dev/fb0"),
-- will be set upon loading by Device class:
device = nil,
}
function Screen:init()
self.bb = self.fb.bb
self.blitbuffer_rotation_mode = self.bb:getRotation()
-- asking the framebuffer for orientation is error prone,
-- so we do this simple heuristic (for now)
if self:getWidth() > self:getHeight() then
self.native_rotation_mode = 1
else
self.native_rotation_mode = 0
end
self.cur_rotation_mode = self.native_rotation_mode
end
function Screen:refresh(refresh_type, waveform_mode, x, y, w, h)
self.fb:refresh(refresh_type, waveform_mode, x, y, w, h)
end
function Screen:getSize()
return Geom:new{w = self.bb:getWidth(), h = self.bb:getHeight()}
end
function Screen:getWidth()
return self.bb:getWidth()
end
function Screen:getHeight()
return self.bb:getHeight()
end
function Screen:getDPI()
if self.dpi ~= nil then return self.dpi end
local model = self.device:getModel()
if model == "KindlePaperWhite" or model == "KindlePaperWhite2"
or model == "Kobo_kraken" or model == "Kobo_phoenix" then
self.dpi = 212
elseif model == "Kobo_dragon" then
self.dpi = 265
elseif model == "Kobo_pixie" then
self.dpi = 200
else
self.dpi = 167
end
return self.dpi
end
function Screen:scaleByDPI(px)
return math.floor(px * self:getDPI()/167)
end
function Screen:rescaleByDPI(px)
return math.ceil(px * 167/self:getDPI())
end
function Screen:getRotationMode()
return self.cur_rotation_mode
end
function Screen:getScreenMode()
if self:getWidth() > self:getHeight() then
return "landscape"
else
return "portrait"
end
end
function Screen:setRotationMode(mode)
self.fb.bb:rotateAbsolute(-90 * (mode - self.native_rotation_mode - self.blitbuffer_rotation_mode))
self.cur_rotation_mode = mode
end
function Screen:setScreenMode(mode)
if mode == "portrait" then
if self.cur_rotation_mode ~= 0 then
self:setRotationMode(0)
end
elseif mode == "landscape" then
if self.cur_rotation_mode == 0 or self.cur_rotation_mode == 2 then
self:setRotationMode(DLANDSCAPE_CLOCKWISE_ROTATION and 1 or 3)
elseif self.cur_rotation_mode == 1 or self.cur_rotation_mode == 3 then
self:setRotationMode((self.cur_rotation_mode + 2) % 4)
end
end
end
function Screen:saveCurrentBB()
local width, height = self:getWidth(), self:getHeight()
if not self.saved_bb then
self.saved_bb = Blitbuffer.new(width, height)
end
if self.saved_bb:getWidth() ~= width then
self.saved_bb:free()
self.saved_bb = Blitbuffer.new(width, height)
end
self.saved_bb:blitFullFrom(self.bb)
end
function Screen:restoreFromSavedBB()
self:restoreFromBB(self.saved_bb)
-- free data
self.saved_bb = nil
end
function Screen:getCurrentScreenBB()
local bb = Blitbuffer.new(self:getWidth(), self:getHeight())
bb:blitFullFrom(self.bb)
return bb
end
function Screen:restoreFromBB(bb)
if bb then
self.bb:blitFullFrom(bb)
else
DEBUG("Got nil bb in restoreFromSavedBB!")
end
end
return Screen
|
fix wrong screen dpi on Kindle paperwhite 2
|
fix wrong screen dpi on Kindle paperwhite 2
|
Lua
|
agpl-3.0
|
frankyifei/koreader,poire-z/koreader,koreader/koreader,koreader/koreader,mihailim/koreader,Frenzie/koreader,chihyang/koreader,ashang/koreader,Markismus/koreader,NiLuJe/koreader,mwoz123/koreader,lgeek/koreader,robert00s/koreader,Hzj-jie/koreader,NiLuJe/koreader,houqp/koreader,apletnev/koreader,Frenzie/koreader,ashhher3/koreader,noname007/koreader,pazos/koreader,chrox/koreader,NickSavage/koreader,poire-z/koreader
|
d890e0e479b25594193b8846ea1996f9d9239421
|
src/sailor/access.lua
|
src/sailor/access.lua
|
--------------------------------------------------------------------------------
-- access.lua, v0.2.4: controls access of sailor apps
-- This file is a part of Sailor project
-- Copyright (c) 2014 Etiene Dalcol <dalcol@etiene.net>
-- License: MIT
-- http://sailorproject.org
--------------------------------------------------------------------------------
local session = require "sailor.session"
local access = {}
session.open(sailor.r)
-- Uncomment to login with "demo" / "demo"
-- Comment to login through db (user model)
--access.default = "demo"
--access.default_pass = "demo"
--access.salt = "sailorisawesome" -- set to nil to use unhashed passwords
local INVALID = "Invalid username or password."
-- Simple hashing algorithm for encrypting passworsd
function access.hash(username, password, salt)
salt = salt or access.salt
local hash = username .. password
-- Check if bcrypt is embedded
if sailor.r.htpassword then
return sailor.r:htpassword(hash, 2, 100) -- Use bcrypt on pwd
-- If not, fall back to sha1 hashing
else
if salt and sailor.r.sha1 then
for i = 1, 500 do
hash = sailor.r:sha1(salt .. hash)
end
end
end
return hash
end
function access.is_guest()
return not session.data.username
end
function access.grant(data,time)
session.setsessiontimeout (time or 604800) -- 1 week
if not data.username then return false end
access.data = data
return session.save(data)
end
function access.login(username,password)
local id
if not access.default then
local User = sailor.model("user")
local u = User:find_by_attributes{
username=username
}
if not u then
return false, INVALID
end
if u.password ~= access.hash(username, password, u.salt) then
return false, INVALID
end
id = u.id
else
if username ~= access.default or password ~= access.default_pass then
return false, INVALID
end
id = 1
end
return access.grant({username=username,id=id})
end
function access.logout()
session.destroy(sailor.r)
end
return access
|
--------------------------------------------------------------------------------
-- access.lua, v0.2.5: controls access of sailor apps
-- This file is a part of Sailor project
-- Copyright (c) 2014 Etiene Dalcol <dalcol@etiene.net>
-- License: MIT
-- http://sailorproject.org
--------------------------------------------------------------------------------
local session = require "sailor.session"
local access = {}
session.open(sailor.r)
-- Uncomment to login with "demo" / "demo"
-- Comment to login through db (user model)
--access.default = "demo"
--access.default_pass = "demo"
--access.salt = "sailorisawesome" -- set to nil to use unhashed passwords
local INVALID = "Invalid username or password."
-- Simple hashing algorithm for encrypting passworsd
function access.hash(username, password, salt)
salt = salt or access.salt
local hash = username .. password
-- Check if bcrypt is embedded
if sailor.conf.bcrypt and salt and sailor.r.htpassword then
hash = sailor.r:htpassword(salt .. hash, 2, 100) -- Use bcrypt on pwd
return hash
-- If not, fall back to sha1 hashing
else
if salt and sailor.r.sha1 then
for i = 1, 500 do
hash = sailor.r:sha1(salt .. hash)
end
end
end
return hash
end
function access.is_guest()
access.data = session.data
return not access.data.username
end
function access.grant(data,time)
session.setsessiontimeout (time or 604800) -- 1 week
if not data.username then return false end
access.data = data
return session.save(data)
end
function access.login(username,password)
local id
if not access.default then
local User = sailor.model("user")
local u = User:find_by_attributes{
username=username
}
if not u then
return false, INVALID
end
if u.password ~= access.hash(username, password, u.salt) then
return false, INVALID
end
id = u.id
else
if username ~= access.default or password ~= access.default_pass then
return false, INVALID
end
id = 1
end
return access.grant({username=username,id=id})
end
function access.logout()
session.destroy(sailor.r)
end
return access
|
Fixing missing session data
|
Fixing missing session data
|
Lua
|
mit
|
felipedaragon/sailor,sailorproject/sailor,jeary/sailor,noname007/sailor,Etiene/sailor,Etiene/sailor,ignacio/sailor,mpeterv/sailor,mpeterv/sailor,hallison/sailor,ignacio/sailor,felipedaragon/sailor
|
e3efc3223515c1c57999c9beda5278af9cd429f3
|
extension/script/frontend/debugerFactory.lua
|
extension/script/frontend/debugerFactory.lua
|
local fs = require 'bee.filesystem'
local sp = require 'bee.subprocess'
local platformOS = require 'frontend.platformOS'
local inject = require 'inject'
local useWSL = false
local useUtf8 = false
local function initialize(args)
useWSL = args.useWSL
useUtf8 = args.sourceCoding == "utf8"
end
local function towsl(s)
if not useWSL or not s:match "^%a:" then
return s
end
return s:gsub("\\", "/"):gsub("^(%a):", function(c)
return "/mnt/"..c:lower()
end)
end
local function nativepath(s)
if not useWSL and not useUtf8 and platformOS() == "Windows" then
local unicode = require 'bee.unicode'
return unicode.u2a(s)
end
return towsl(s)
end
local function create_install_script(args, pid, dbg)
local res = {}
res[#res+1] = ("local path=[[%s]];"):format(nativepath(dbg))
res[#res+1] = ("assert(loadfile(path..'/script/debugger.lua'))('%s',path,%d)"):format(
platformOS():lower(),
pid
)
return table.concat(res)
end
local function is64Exe(exe)
local f = io.open(exe:string())
if not f then
return
end
local MZ = f:read(2)
if MZ ~= 'MZ' then
f:close()
return
end
f:seek('set', 60)
local e_lfanew = ('I4'):unpack(f:read(4))
f:seek('set', e_lfanew)
local ntheader = ('z'):unpack(f:read(4) .. '\0')
if ntheader ~= 'PE' then
f:close()
return
end
f:seek('cur', 18)
local characteristics = ('I2'):unpack(f:read(2))
f:close()
return (characteristics & 0x100) == 0
end
local function getLuaRuntime(args)
if args.luaRuntime == "5.4 64bit" then
return 54, 64
elseif args.luaRuntime == "5.4 32bit" then
return 54, 32
elseif args.luaRuntime == "5.3 64bit" then
return 53, 64
elseif args.luaRuntime == "5.3 32bit" then
return 53, 32
end
return 53, 32
end
local function getLuaExe(args, dbg)
if type(args.luaexe) == "string" then
return fs.path(args.luaexe)
end
local ver, bit = getLuaRuntime(args)
local runtime = 'runtime'
if platformOS() == "Windows" then
if bit == 64 then
runtime = runtime .. "/win64"
else
runtime = runtime .. "/win32"
end
else
runtime = runtime .. "/" .. platformOS():lower()
end
if ver == 53 then
runtime = runtime .. "/lua53"
else
runtime = runtime .. "/lua54"
end
return dbg / runtime / (platformOS() == "Windows" and "lua.exe" or "lua")
end
local function installBootstrap1(option, luaexe, args)
option.cwd = (type(args.cwd) == "string") and args.cwd or luaexe:parent_path():string()
if type(args.env) == "table" then
option.env = args.env
end
end
local function installBootstrap2(c, luaexe, args, pid, dbg)
if useWSL then
c[#c+1] = "wsl"
end
c[#c+1] = towsl(luaexe:string())
c[#c+1] = "-e"
c[#c+1] = create_install_script(args, pid, dbg:string())
if type(args.arg0) == "string" then
c[#c+1] = args.arg0
elseif type(args.arg0) == "table" then
for _, v in ipairs(args.arg0) do
if type(v) == "string" then
c[#c+1] = v
end
end
end
c[#c+1] = (type(args.program) == "string") and towsl(args.program) or ".lua"
if type(args.arg) == "string" then
c[#c+1] = args.arg
elseif type(args.arg) == "table" then
for _, v in ipairs(args.arg) do
if type(v) == "string" then
c[#c+1] = v
end
end
end
end
local function create_terminal(args, dbg, pid)
initialize(args)
local luaexe = getLuaExe(args, dbg)
if not fs.exists(luaexe) then
if args.luaexe then
return nil, ("No file `%s`."):format(args.luaexe)
end
return nil, "Non-Windows need to compile lua-debug first."
end
local option = {
kind = (args.console == "integratedTerminal") and "integrated" or "external",
title = "Lua Debug",
args = {},
}
installBootstrap1(option, luaexe, args)
installBootstrap2(option.args, luaexe, args, pid, dbg)
return option
end
local function create_luaexe(args, dbg, pid)
initialize(args)
local luaexe = getLuaExe(args, dbg)
if not fs.exists(luaexe) then
if args.luaexe then
return nil, ("No file `%s`."):format(args.luaexe)
end
return nil, "Non-Windows need to compile lua-debug first."
end
local option = {
console = 'hide'
}
installBootstrap1(option, luaexe, args)
installBootstrap2(option, luaexe, args, pid, dbg)
return sp.spawn(option)
end
local function create_process(args)
initialize(args)
local application = args.runtimeExecutable
local option = {
application,
env = args.env,
console = 'new',
cwd = args.cwd or fs.path(application):parent_path(),
suspended = true,
}
local process, err
if type(args.runtimeArgs) == 'string' then
option.argsStyle = 'string'
option[2] = args.runtimeArgs
process, err = sp.spawn(option)
elseif type(args.runtimeArgs) == 'table' then
option[2] = args.runtimeArgs
process, err = sp.spawn(option)
else
process, err = sp.spawn(option)
end
if not process then
return nil, err
end
inject.injectdll(process
, (WORKDIR / "bin" / "win" / "launcher.x86.dll"):string()
, (WORKDIR / "bin" / "win" / "launcher.x64.dll"):string()
, "launch"
)
process:resume()
return process
end
return {
create_terminal = create_terminal,
create_process = create_process,
create_luaexe = create_luaexe,
}
|
local fs = require 'bee.filesystem'
local sp = require 'bee.subprocess'
local platformOS = require 'frontend.platformOS'
local inject = require 'inject'
local useWSL = false
local useUtf8 = false
local function initialize(args)
useWSL = args.useWSL
useUtf8 = args.sourceCoding == "utf8"
end
local function towsl(s)
if not useWSL or not s:match "^%a:" then
return s
end
return s:gsub("\\", "/"):gsub("^(%a):", function(c)
return "/mnt/"..c:lower()
end)
end
local function nativepath(s)
if not useWSL and not useUtf8 and platformOS() == "Windows" then
local unicode = require 'bee.unicode'
return unicode.u2a(s)
end
return towsl(s)
end
local function create_install_script(args, pid, dbg)
local res = {}
res[#res+1] = ("local path=[[%s]];"):format(nativepath(dbg))
res[#res+1] = ("assert(loadfile(path..'/script/debugger.lua'))('%s',path,%d)"):format(
platformOS():lower(),
pid
)
return table.concat(res)
end
local function is64Exe(exe)
local f = io.open(exe:string())
if not f then
return
end
local MZ = f:read(2)
if MZ ~= 'MZ' then
f:close()
return
end
f:seek('set', 60)
local e_lfanew = ('I4'):unpack(f:read(4))
f:seek('set', e_lfanew)
local ntheader = ('z'):unpack(f:read(4) .. '\0')
if ntheader ~= 'PE' then
f:close()
return
end
f:seek('cur', 18)
local characteristics = ('I2'):unpack(f:read(2))
f:close()
return (characteristics & 0x100) == 0
end
local function getLuaRuntime(args)
if args.luaRuntime == "5.4 64bit" then
return 54, 64
elseif args.luaRuntime == "5.4 32bit" then
return 54, 32
elseif args.luaRuntime == "5.3 64bit" then
return 53, 64
elseif args.luaRuntime == "5.3 32bit" then
return 53, 32
end
return 53, 32
end
local function getLuaExe(args, dbg)
if type(args.luaexe) == "string" then
return fs.path(args.luaexe)
end
local ver, bit = getLuaRuntime(args)
local runtime = 'runtime'
if platformOS() == "Windows" then
if bit == 64 then
runtime = runtime .. "/win64"
else
runtime = runtime .. "/win32"
end
else
runtime = runtime .. "/" .. platformOS():lower()
end
if ver == 53 then
runtime = runtime .. "/lua53"
else
runtime = runtime .. "/lua54"
end
return dbg / runtime / (platformOS() == "Windows" and "lua.exe" or "lua")
end
local function installBootstrap1(option, luaexe, args)
option.cwd = (type(args.cwd) == "string") and args.cwd or luaexe:parent_path():string()
if type(args.env) == "table" then
option.env = args.env
end
end
local function installBootstrap2(c, luaexe, args, pid, dbg)
c[#c+1] = towsl(luaexe:string())
c[#c+1] = "-e"
c[#c+1] = create_install_script(args, pid, dbg:string())
if type(args.arg0) == "string" then
c[#c+1] = args.arg0
elseif type(args.arg0) == "table" then
for _, v in ipairs(args.arg0) do
if type(v) == "string" then
c[#c+1] = v
end
end
end
c[#c+1] = (type(args.program) == "string") and towsl(args.program) or ".lua"
if type(args.arg) == "string" then
c[#c+1] = args.arg
elseif type(args.arg) == "table" then
for _, v in ipairs(args.arg) do
if type(v) == "string" then
c[#c+1] = v
end
end
end
end
local function create_terminal(args, dbg, pid)
initialize(args)
local luaexe = getLuaExe(args, dbg)
if not fs.exists(luaexe) then
if args.luaexe then
return nil, ("No file `%s`."):format(args.luaexe)
end
return nil, "Non-Windows need to compile lua-debug first."
end
local option = {
kind = (args.console == "integratedTerminal") and "integrated" or "external",
title = "Lua Debug",
args = {},
}
if useWSL then
option.args[1] = "wsl"
end
installBootstrap1(option, luaexe, args)
installBootstrap2(option.args, luaexe, args, pid, dbg)
return option
end
local function create_luaexe(args, dbg, pid)
initialize(args)
local luaexe = getLuaExe(args, dbg)
if not fs.exists(luaexe) then
if args.luaexe then
return nil, ("No file `%s`."):format(args.luaexe)
end
return nil, "Non-Windows need to compile lua-debug first."
end
local option = {
console = 'hide'
}
if useWSL then
local SystemRoot = (os.getenv "SystemRoot") or "C:\\WINDOWS"
option[1] = SystemRoot .. "\\sysnative\\wsl.exe"
end
installBootstrap1(option, luaexe, args)
installBootstrap2(option, luaexe, args, pid, dbg)
return sp.spawn(option)
end
local function create_process(args)
initialize(args)
local application = args.runtimeExecutable
local option = {
application,
env = args.env,
console = 'new',
cwd = args.cwd or fs.path(application):parent_path(),
suspended = true,
}
local process, err
if type(args.runtimeArgs) == 'string' then
option.argsStyle = 'string'
option[2] = args.runtimeArgs
process, err = sp.spawn(option)
elseif type(args.runtimeArgs) == 'table' then
option[2] = args.runtimeArgs
process, err = sp.spawn(option)
else
process, err = sp.spawn(option)
end
if not process then
return nil, err
end
inject.injectdll(process
, (WORKDIR / "bin" / "win" / "launcher.x86.dll"):string()
, (WORKDIR / "bin" / "win" / "launcher.x64.dll"):string()
, "launch"
)
process:resume()
return process
end
return {
create_terminal = create_terminal,
create_process = create_process,
create_luaexe = create_luaexe,
}
|
修正wsl的bug
|
修正wsl的bug
|
Lua
|
mit
|
actboy168/vscode-lua-debug,actboy168/vscode-lua-debug,actboy168/vscode-lua-debug
|
a29a1f6132c3507817158da9aed483c5f79fa9dd
|
tests/dbus.lua
|
tests/dbus.lua
|
di.load_plugin("./plugins/dbus/di_dbus.so")
local dbusl = di.spawn.run({"dbus-daemon", "--print-address", "--session", "--fork"}, false)
dbusl.on("stdout_line", function(l)
print(l)
di.env.DBUS_SESSION_BUS_ADDRESS = l
di.env.DBUS_SESSION_BUS_PID = nil
di.env.DBUS_SESSION_BUS_WINDOWID = nil
end)
dbusl.on("exit", function()
b = di.dbus.session_bus
if b.errmsg then
print(b.errmsg)
di.exit(1)
end
di.dbus.session_bus.get("org.freedesktop.DBus", "/org/freedesktop/DBus").Introspect().on("reply", function(s)
print(s)
collectgarbage()
end)
end)
|
di.load_plugin("./plugins/dbus/di_dbus.so")
di.env.DBUS_SESSION_BUS_PID = nil
di.env.DBUS_SESSION_BUS_ADDRESS = nil
local dbusl = di.spawn.run({"dbus-daemon", "--print-address=1", "--print-pid=2", "--session", "--fork"}, false)
dbusl.on("stdout_line", function(l)
print(l)
di.env.DBUS_SESSION_BUS_ADDRESS = l
end)
dbusl.on("stderr_line", function(l)
print(l)
di.env.DBUS_SESSION_BUS_PID = l
end)
dbusl.on("exit", function()
b = di.dbus.session_bus
if b.errmsg then
print(b.errmsg)
di.exit(1)
end
di.dbus.session_bus.get("org.freedesktop.DBus", "/org/freedesktop/DBus").Introspect().on("reply", function(s)
print(s)
collectgarbage()
end)
end)
|
Try to fix dbus ci test (works locally)
|
Try to fix dbus ci test (works locally)
|
Lua
|
mpl-2.0
|
yshui/deai,yshui/deai,yshui/deai
|
25b7066e555fcaac7dd0e4315ab4dc82bd73d3e3
|
applications/luci-firewall/luasrc/model/cbi/luci_fw/rrule.lua
|
applications/luci-firewall/luasrc/model/cbi/luci_fw/rrule.lua
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2010 Jo-Philipp Wich <xm@subsignal.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
local sys = require "luci.sys"
local dsp = require "luci.dispatcher"
arg[1] = arg[1] or ""
m = Map("firewall", translate("Traffic Redirection"),
translate("Traffic redirection allows you to change the " ..
"destination address of forwarded packets."))
m.redirect = dsp.build_url("admin", "network", "firewall")
if not m.uci:get(arg[1]) == "redirect" then
luci.http.redirect(m.redirect)
return
end
local has_v2 = nixio.fs.access("/lib/firewall/fw.sh")
local wan_zone = nil
m.uci:foreach("firewall", "zone",
function(s)
local n = s.network or s.name
if n then
local i
for i in n:gmatch("%S+") do
if i == "wan" then
wan_zone = s.name
return false
end
end
end
end)
s = m:section(NamedSection, arg[1], "redirect", "")
s.anonymous = true
s.addremove = false
s:tab("general", translate("General Settings"))
s:tab("advanced", translate("Advanced Settings"))
back = s:taboption("general", DummyValue, "_overview", translate("Overview"))
back.value = ""
back.titleref = luci.dispatcher.build_url("admin", "network", "firewall", "redirect")
name = s:taboption("general", Value, "_name", translate("Name"))
name.rmempty = true
name.size = 10
src = s:taboption("general", Value, "src", translate("Source zone"))
src.nocreate = true
src.default = "wan"
src.template = "cbi/firewall_zonelist"
proto = s:taboption("general", ListValue, "proto", translate("Protocol"))
proto.optional = true
proto:value("tcpudp", "TCP+UDP")
proto:value("tcp", "TCP")
proto:value("udp", "UDP")
dport = s:taboption("general", Value, "src_dport", translate("External port"),
translate("Match incoming traffic directed at the given " ..
"destination port or port range on this host"))
dport.datatype = "portrange"
dport:depends("proto", "tcp")
dport:depends("proto", "udp")
dport:depends("proto", "tcpudp")
to = s:taboption("general", Value, "dest_ip", translate("Internal IP address"),
translate("Redirect matched incoming traffic to the specified " ..
"internal host"))
to.datatype = "ip4addr"
for i, dataset in ipairs(luci.sys.net.arptable()) do
to:value(dataset["IP address"])
end
toport = s:taboption("general", Value, "dest_port", translate("Internal port (optional)"),
translate("Redirect matched incoming traffic to the given port on " ..
"the internal host"))
toport.optional = true
toport.placeholder = "0-65535"
target = s:taboption("advanced", ListValue, "target", translate("Redirection type"))
target:value("DNAT")
target:value("SNAT")
dest = s:taboption("advanced", Value, "dest", translate("Destination zone"))
dest.nocreate = true
dest.default = "lan"
dest.template = "cbi/firewall_zonelist"
src_dip = s:taboption("advanced", Value, "src_dip",
translate("Intended destination address"),
translate(
"For DNAT, match incoming traffic directed at the given destination "..
"ip address. For SNAT rewrite the source address to the given address."
))
src_dip.optional = true
src_dip.datatype = "ip4addr"
src_dip.placeholder = translate("any")
src_mac = s:taboption("advanced", Value, "src_mac", translate("Source MAC address"))
src_mac.optional = true
src_mac.datatype = "macaddr"
src_mac.placeholder = translate("any")
src_ip = s:taboption("advanced", Value, "src_ip", translate("Source IP address"))
src_ip.optional = true
src_ip.datatype = "ip4addr"
src_ip.placeholder = translate("any")
sport = s:taboption("advanced", Value, "src_port", translate("Source port"),
translate("Match incoming traffic originating from the given " ..
"source port or port range on the client host"))
sport.optional = true
sport.datatype = "portrange"
sport.placeholder = "0-65536"
sport:depends("proto", "tcp")
sport:depends("proto", "udp")
sport:depends("proto", "tcpudp")
reflection = s:taboption("advanced", Flag, "reflection", translate("Enable NAT Loopback"))
reflection.rmempty = true
reflection:depends({ target = "DNAT", src = wan_zone })
reflection.cfgvalue = function(...)
return Flag.cfgvalue(...) or "1"
end
return m
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2010 Jo-Philipp Wich <xm@subsignal.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
local sys = require "luci.sys"
local dsp = require "luci.dispatcher"
arg[1] = arg[1] or ""
m = Map("firewall", translate("Traffic Redirection"),
translate("Traffic redirection allows you to change the " ..
"destination address of forwarded packets."))
m.redirect = dsp.build_url("admin", "network", "firewall")
if not m.uci:get(arg[1]) == "redirect" then
luci.http.redirect(m.redirect)
return
end
local has_v2 = nixio.fs.access("/lib/firewall/fw.sh")
local wan_zone = nil
m.uci:foreach("firewall", "zone",
function(s)
local n = s.network or s.name
if n then
local i
for i in n:gmatch("%S+") do
if i == "wan" then
wan_zone = s.name
return false
end
end
end
end)
s = m:section(NamedSection, arg[1], "redirect", "")
s.anonymous = true
s.addremove = false
s:tab("general", translate("General Settings"))
s:tab("advanced", translate("Advanced Settings"))
back = s:taboption("general", DummyValue, "_overview", translate("Overview"))
back.value = ""
back.titleref = luci.dispatcher.build_url("admin", "network", "firewall", "redirect")
name = s:taboption("general", Value, "_name", translate("Name"))
name.rmempty = true
name.size = 10
src = s:taboption("general", Value, "src", translate("Source zone"))
src.nocreate = true
src.default = "wan"
src.template = "cbi/firewall_zonelist"
proto = s:taboption("general", Value, "proto", translate("Protocol"))
proto.optional = true
proto:value("tcpudp", "TCP+UDP")
proto:value("tcp", "TCP")
proto:value("udp", "UDP")
dport = s:taboption("general", Value, "src_dport", translate("External port"),
translate("Match incoming traffic directed at the given " ..
"destination port or port range on this host"))
dport.datatype = "portrange"
dport:depends("proto", "tcp")
dport:depends("proto", "udp")
dport:depends("proto", "tcpudp")
to = s:taboption("general", Value, "dest_ip", translate("Internal IP address"),
translate("Redirect matched incoming traffic to the specified " ..
"internal host"))
to.datatype = "ip4addr"
for i, dataset in ipairs(luci.sys.net.arptable()) do
to:value(dataset["IP address"])
end
toport = s:taboption("general", Value, "dest_port", translate("Internal port (optional)"),
translate("Redirect matched incoming traffic to the given port on " ..
"the internal host"))
toport.optional = true
toport.placeholder = "0-65535"
toport.datatype = "portrange"
toport:depends("proto", "tcp")
toport:depends("proto", "udp")
toport:depends("proto", "tcpudp")
target = s:taboption("advanced", ListValue, "target", translate("Redirection type"))
target:value("DNAT")
target:value("SNAT")
dest = s:taboption("advanced", Value, "dest", translate("Destination zone"))
dest.nocreate = true
dest.default = "lan"
dest.template = "cbi/firewall_zonelist"
src_dip = s:taboption("advanced", Value, "src_dip",
translate("Intended destination address"),
translate(
"For DNAT, match incoming traffic directed at the given destination "..
"ip address. For SNAT rewrite the source address to the given address."
))
src_dip.optional = true
src_dip.datatype = "ip4addr"
src_dip.placeholder = translate("any")
src_mac = s:taboption("advanced", Value, "src_mac", translate("Source MAC address"))
src_mac.optional = true
src_mac.datatype = "macaddr"
src_mac.placeholder = translate("any")
src_ip = s:taboption("advanced", Value, "src_ip", translate("Source IP address"))
src_ip.optional = true
src_ip.datatype = "ip4addr"
src_ip.placeholder = translate("any")
sport = s:taboption("advanced", Value, "src_port", translate("Source port"),
translate("Match incoming traffic originating from the given " ..
"source port or port range on the client host"))
sport.optional = true
sport.datatype = "portrange"
sport.placeholder = "0-65536"
sport:depends("proto", "tcp")
sport:depends("proto", "udp")
sport:depends("proto", "tcpudp")
reflection = s:taboption("advanced", Flag, "reflection", translate("Enable NAT Loopback"))
reflection.rmempty = true
reflection:depends({ target = "DNAT", src = wan_zone })
reflection.cfgvalue = function(...)
return Flag.cfgvalue(...) or "1"
end
return m
|
applications/luci-firewall: some fixes on redirection page
|
applications/luci-firewall: some fixes on redirection page
|
Lua
|
apache-2.0
|
deepak78/luci,deepak78/luci,8devices/luci,8devices/luci,8devices/luci,deepak78/luci,deepak78/luci,deepak78/luci,8devices/luci,deepak78/luci,8devices/luci,deepak78/luci,deepak78/luci,8devices/luci
|
85e486f887263b57fb6dd6ba581e30f860d087f7
|
OS/DiskOS/Editors/paint.lua
|
OS/DiskOS/Editors/paint.lua
|
local eapi, img, imgdata = ... --Check C://Programs/paint.lua
local sw, sh = screenSize()
local paint = {}
paint.pal = imagedata(16,1)
paint.pal:map(function(x,y,c) return x end)
paint.pal = paint.pal:image()
function paint:drawPalette()
self.pal:draw(1,sh-7,0,8,8)
end
function paint:drawImage()
clip(1,9,sw,sh-8*2)
img:draw(1,9)
clip()
end
function paint:entered()
eapi:drawUI()
palt(1,false)
self:drawPalette()
self:drawImage()
end
function paint:leaved()
palt(1,true)
end
function paint:import(a,b)
img, imgdata = a,b
end
function paint:export()
return imgdata:encode()
end
return paint
|
local eapi, img, imgdata = ... --Check C://Programs/paint.lua
local sw, sh = screenSize()
local paint = {}
paint.pal = imagedata(16,1)
paint.pal:map(function(x,y,c) return x end)
paint.pal = paint.pal:image()
paint.drawCursor = eapi.editorsheet:extract(8):image()
paint.fgcolor, paint.bgcolor = 8,1
paint.palGrid = {sw-16*8+1,sh-7,16*8,8,16,1}
function paint:drawPalette()
self.pal:draw(sw-16*8+1,sh-7,0,8,8)
end
function paint:drawColorCell()
palt(1,true)
pal(9,self.fgcolor)
pal(13,self.bgcolor)
eapi.editorsheet:draw(77,sw-16*8-8+1,sh-7)
pal()
palt(1,false)
end
function paint:drawImage()
clip(1,9,sw,sh-8*2)
img:draw(1,9)
clip()
end
function paint:drawBottomBar()
eapi:drawBottomBar()
self:drawPalette()
self:drawColorCell()
end
function paint:entered()
eapi:drawUI()
palt(1,false)
self:drawPalette()
self:drawColorCell()
self:drawImage()
local mx, my = getMPos()
self:mousemoved(mx,my,0,0,isMobile())
end
function paint:leaved()
palt(1,true)
end
function paint:import(a,b)
img, imgdata = a,b
end
function paint:export()
return imgdata:encode()
end
function paint:update(dt)
end
function paint:mousepressed(x,y,b,istouch)
local cx, cy = whereInGrid(x,y,self.palGrid)
if cx then
if b == 1 then
self.fgcolor = cx
elseif b == 2 then
self.bgcolor = cx
end
self:drawColorCell()
end
end
function paint:mousemoved(x,y,dx,dy,istouch)
if isInRect(x,y,{1,9,sw,sh-8*2}) then
if istouch then
cursor("draw")
else
cursor("none")
eapi:drawBackground(); self:drawImage()
eapi:drawTopBar(); self:drawBottomBar()
palt(1,true)
self.drawCursor:draw(x-3,y-3)
palt(1,false)
end
else
if cursor() == "none" then eapi:drawBackground(); self:drawImage(); eapi:drawTopBar(); self:drawBottomBar() end
if cursor() == "none" or cursor() == "draw" then cursor("normal") end
end
end
return paint
|
Moved the palette to the right Added the selected colors cell Bugfixed some glitches
|
Moved the palette to the right
Added the selected colors cell
Bugfixed some glitches
|
Lua
|
mit
|
RamiLego4Game/LIKO-12
|
50e5e847d185a7504c20bdf7ff3122a5a43d71be
|
src/cosy/fixpath/cli.lua
|
src/cosy/fixpath/cli.lua
|
local Lfs = require "lfs"
local Lustache = require "lustache"
local Colors = require 'ansicolors'
local Arguments = require "argparse"
local parser = Arguments () {
name = "cosy-fixpath",
description = "Fix PATH, CPATH, *LIBRARY_PATH in cosy binaries",
}
parser:argument "prefix" {
description = "cosy prefix directory",
}
local arguments = parser:parse ()
local string_mt = getmetatable ""
function string_mt.__mod (pattern, variables)
return Lustache:render (pattern, variables)
end
if Lfs.attributes (arguments.prefix, "mode") ~= "directory" then
print (Colors ("%{bright red blackbg}failure%{reset}"))
end
for filename in Lfs.dir (arguments.prefix .. "/bin") do
if filename:match "^cosy" then
local lines = {}
for line in io.lines (arguments.prefix .. "/bin/" .. filename) do
lines [#lines+1] = line
end
table.insert (lines, 3, [[export CPATH="{{{prefix}}}/include:${CPATH}"]] % { prefix = arguments.prefix })
table.insert (lines, 4, [[export LIBRARY_PATH="{{{prefix}}}/lib:${LIBRARY_PATH}"]] % { prefix = arguments.prefix })
table.insert (lines, 5, [[export LD_LIBRARY_PATH="{{{prefix}}}/lib:${LD_LIBRARY_PATH}"]] % { prefix = arguments.prefix })
table.insert (lines, 6, [[export DYLD_LIBRARY_PATH="{{{prefix}}}/lib:${DYLD_LIBRARY_PATH}"]] % { prefix = arguments.prefix })
table.insert (lines, 7, "")
local file = io.open (arguments.prefix .. "/bin/" .. filename, "w")
file:write (table.concat (lines, "\n") .. "\n")
file:close ()
end
end
print (Colors ("%{bright green blackbg}success%{reset}"))
|
local Lfs = require "lfs"
local Lustache = require "lustache"
local Colors = require 'ansicolors'
local Arguments = require "argparse"
local parser = Arguments () {
name = "cosy-fixpath",
description = "Fix PATH, CPATH, *LIBRARY_PATH in cosy binaries",
}
parser:argument "prefix" {
description = "cosy prefix directory",
}
parser:option "-q" "--quiet" {
description = "do not output anything",
}
local arguments = parser:parse ()
local string_mt = getmetatable ""
function string_mt.__mod (pattern, variables)
return Lustache:render (pattern, variables)
end
if Lfs.attributes (arguments.prefix, "mode") ~= "directory" then
if not arguments.quiet then
print (Colors ("%{bright red blackbg}failure%{reset}"))
end
end
for filename in Lfs.dir (arguments.prefix .. "/bin") do
if filename:match "^cosy" then
local lines = {}
for line in io.lines (arguments.prefix .. "/bin/" .. filename) do
lines [#lines+1] = line
end
table.insert (lines, 3, [[export CPATH="{{{prefix}}}/include:${CPATH}"]] % { prefix = arguments.prefix })
table.insert (lines, 4, [[export LIBRARY_PATH="{{{prefix}}}/lib:${LIBRARY_PATH}"]] % { prefix = arguments.prefix })
table.insert (lines, 5, [[export LD_LIBRARY_PATH="{{{prefix}}}/lib:${LD_LIBRARY_PATH}"]] % { prefix = arguments.prefix })
table.insert (lines, 6, [[export DYLD_LIBRARY_PATH="{{{prefix}}}/lib:${DYLD_LIBRARY_PATH}"]] % { prefix = arguments.prefix })
table.insert (lines, 7, "")
local file = io.open (arguments.prefix .. "/bin/" .. filename, "w")
file:write (table.concat (lines, "\n") .. "\n")
file:close ()
end
end
if not arguments.quiet then
print (Colors ("%{bright green blackbg}success%{reset}"))
end
|
Add --quiet option to fixpath.
|
Add --quiet option to fixpath.
|
Lua
|
mit
|
CosyVerif/library,CosyVerif/library,CosyVerif/library
|
72659bdea010b5d3e60f7e54e896c8166799f0c3
|
core/inputs-texlike.lua
|
core/inputs-texlike.lua
|
SILE.inputs.TeXlike = {}
local epnf = require("epnf")
local ID = lpeg.C( SILE.parserBits.letter * (SILE.parserBits.letter+SILE.parserBits.digit)^0 )
SILE.inputs.TeXlike.identifier = (ID + lpeg.P"-" + lpeg.P":")^1
SILE.inputs.TeXlike.parser = function (_ENV)
local _ = WS^0
local sep = S",;" * _
local eol = S"\r\n"
local quote = P'"'
local quotedString = ( quote * C((1-quote)^1) * quote )
local value = ( quotedString + (1-S",;]")^1 )
local myID = C(SILE.inputs.TeXlike.identifier + P(1)) / 1
local pair = Cg(myID * _ * "=" * _ * C(value)) * sep^-1 / function (...) local t = {...}; return t[1], t[#t] end
local list = Cf(Ct"" * pair^0, rawset)
local parameters = (
P"[" *
list *
P"]"
)^-1/function (a) return type(a)=="table" and a or {} end
local comment = (
P"%" *
P(1-eol)^0 *
eol^-1
) / ""
START "document"
document = V"texlike_stuff" * EOF"Unexpected character at end of input"
texlike_stuff = Cg(
V"environment" +
comment +
V"texlike_text" +
V"texlike_bracketed_stuff" +
V"command"
)^0
passthrough_stuff = C(Cg(
V"passthrough_text" +
V"passthrough_debracketed_stuff"
)^0)
passthrough_env_stuff = Cg(
V"passthrough_env_text"
)^0
texlike_text = C((1-S("\\{}%"))^1)
passthrough_text = C((1-S("{}"))^1)
passthrough_env_text = C((1-(P"\\end{" * (myID * Cb"tag") * P"}"))^1)
texlike_bracketed_stuff = P"{" * V"texlike_stuff" * ( P"}" + E("} expected") )
passthrough_bracketed_stuff = P"{" * V"passthrough_stuff" * ( P"}" + E("} expected") )
passthrough_debracketed_stuff = C(V"passthrough_bracketed_stuff")
command = (
( P"\\"-P"\\begin" ) *
Cg(myID, "tag") *
Cg(parameters,"attr") *
(
(Cmt(Cb"tag", function(_, _, tag) return tag == "script" end) * V"passthrough_bracketed_stuff") +
(Cmt(Cb"tag", function(_, _, tag) return tag ~= "script" end) * V"texlike_bracketed_stuff")
)^0
) - P("\\end{")
environment =
P"\\begin" *
Cg(parameters, "attr") *
P"{" *
Cg(myID, "tag") *
P"}" *
(
(Cmt(Cb"tag", function(_, _, tag) return tag == "script" end) * V"passthrough_env_stuff") +
(Cmt(Cb"tag", function(_, _, tag) return tag ~= "script" end) * V"texlike_stuff")
) *
(
P"\\end{" *
(
Cmt(myID * Cb"tag", function (_,_,thisTag,lastTag) return thisTag == lastTag end) + E"Environment mismatch"
) *
( P"}" * _ ) + E"Environment begun but never ended"
)
end
local linecache = {}
local lno, col, lastpos
local function resetCache ()
lno = 1
col = 1
lastpos = 0
linecache = { { lno = 1, pos = 1} }
end
local function getline (s, p)
start = 1
lno = 1
if p > lastpos then
lno = linecache[#linecache].lno
start = linecache[#linecache].pos + 1
col = 1
else
for j = 1,#linecache-1 do
if linecache[j+1].pos >= p then
lno = linecache[j].lno
col = p - linecache[j].pos
return lno,col
end
end
end
for i = start, p do
if string.sub( s, i, i ) == "\n" then
lno = lno + 1
col = 1
linecache[#linecache+1] = { pos = i, lno = lno }
lastpos = i
end
col = col + 1
end
return lno, col
end
local function massage_ast (tree, doc)
-- Sort out pos
if type(tree) == "string" then return tree end
if tree.pos then
tree.line, tree.col = getline(doc, tree.pos)
end
if tree.id == "document"
or tree.id == "texlike_bracketed_stuff"
or tree.id == "passthrough_bracketed_stuff"
then return massage_ast(tree[1], doc) end
if tree.id == "texlike_text"
or tree.id == "passthrough_text"
or tree.id == "passthrough_env_text"
then return tree[1] end
for key, val in ipairs(tree) do
if val.id == "texlike_stuff"
or val.id == "passthrough_stuff"
or val.id == "passthrough_env_stuff"
then
SU.splice(tree, key, key, massage_ast(val, doc))
else
tree[key] = massage_ast(val, doc)
end
end
return tree
end
function SILE.inputs.TeXlike.process (doc)
local tree = SILE.inputs.TeXlike.docToTree(doc)
local root = SILE.documentState.documentClass == nil
if root then
if tree.tag == "document" then
SILE.inputs.common.init(doc, tree)
SILE.process(tree)
elseif pcall(function () assert(loadstring(doc))() end) then
else
SU.error("Input not recognized as Lua or SILE content")
end
end
if root and not SILE.preamble then
SILE.documentState.documentClass:finish()
end
end
local _parser
function SILE.inputs.TeXlike.rebuildParser ()
_parser = epnf.define(SILE.inputs.TeXlike.parser)
end
SILE.inputs.TeXlike.rebuildParser()
function SILE.inputs.TeXlike.docToTree (doc)
local tree = epnf.parsestring(_parser, doc)
-- a document always consists of one texlike_stuff
tree = tree[1][1]
if tree.id == "texlike_text" then tree = {tree} end
if not tree then return end
resetCache()
tree = massage_ast(tree, doc)
return tree
end
SILE.inputs.TeXlike.order = 99
SILE.inputs.TeXlike.appropriate = function () return true end
|
SILE.inputs.TeXlike = {}
local epnf = require("epnf")
local ID = lpeg.C( SILE.parserBits.letter * (SILE.parserBits.letter+SILE.parserBits.digit)^0 )
SILE.inputs.TeXlike.identifier = (ID + lpeg.P"-" + lpeg.P":")^1
SILE.inputs.TeXlike.parser = function (_ENV)
local _ = WS^0
local sep = S",;" * _
local eol = S"\r\n"
local quote = P'"'
local quotedString = ( quote * C((1-quote)^1) * quote )
local value = ( quotedString + (1-S",;]")^1 )
local myID = C(SILE.inputs.TeXlike.identifier + P(1)) / 1
local pair = Cg(myID * _ * "=" * _ * C(value)) * sep^-1 / function (...) local t = {...}; return t[1], t[#t] end
local list = Cf(Ct"" * pair^0, rawset)
local parameters = (
P"[" *
list *
P"]"
)^-1/function (a) return type(a)=="table" and a or {} end
local comment = (
P"%" *
P(1-eol)^0 *
eol^-1
) / ""
START "document"
document = V"texlike_stuff" * EOF"Unexpected character at end of input"
texlike_stuff = Cg(
V"environment" +
comment +
V"texlike_text" +
V"texlike_bracketed_stuff" +
V"command"
)^0
passthrough_stuff = C(Cg(
V"passthrough_text" +
V"passthrough_debracketed_stuff"
)^0)
passthrough_env_stuff = Cg(
V"passthrough_env_text"
)^0
texlike_text = C((1-S("\\{}%"))^1)
passthrough_text = C((1-S("{}"))^1)
passthrough_env_text = C((1-(P"\\end{" * (myID * Cb"tag") * P"}"))^1)
texlike_bracketed_stuff = P"{" * V"texlike_stuff" * ( P"}" + E("} expected") )
passthrough_bracketed_stuff = P"{" * V"passthrough_stuff" * ( P"}" + E("} expected") )
passthrough_debracketed_stuff = C(V"passthrough_bracketed_stuff")
command = (
( P"\\"-P"\\begin" ) *
Cg(myID, "tag") *
Cg(parameters,"attr") *
(
(Cmt(Cb"tag", function(_, _, tag) return tag == "script" end) * V"passthrough_bracketed_stuff") +
(Cmt(Cb"tag", function(_, _, tag) return tag ~= "script" end) * V"texlike_bracketed_stuff")
)^0
) - P("\\end{")
environment =
P"\\begin" *
Cg(parameters, "attr") *
P"{" *
Cg(myID, "tag") *
P"}" *
(
(Cmt(Cb"tag", function(_, _, tag) return tag == "script" end) * V"passthrough_env_stuff") +
(Cmt(Cb"tag", function(_, _, tag) return tag ~= "script" end) * V"texlike_stuff")
) *
(
P"\\end{" *
(
Cmt(myID * Cb"tag", function (_,_,thisTag,lastTag) return thisTag == lastTag end) + E"Environment mismatch"
) *
( P"}" * _ ) + E"Environment begun but never ended"
)
end
local linecache = {}
local lno, col, lastpos
local function resetCache ()
lno = 1
col = 1
lastpos = 0
linecache = { { lno = 1, pos = 1} }
end
local function getline (s, p)
start = 1
lno = 1
if p > lastpos then
lno = linecache[#linecache].lno
start = linecache[#linecache].pos + 1
col = 1
else
for j = 1,#linecache-1 do
if linecache[j+1].pos >= p then
lno = linecache[j].lno
col = p - linecache[j].pos
return lno,col
end
end
end
for i = start, p do
if string.sub( s, i, i ) == "\n" then
lno = lno + 1
col = 1
linecache[#linecache+1] = { pos = i, lno = lno }
lastpos = i
end
col = col + 1
end
return lno, col
end
local function massage_ast (tree, doc)
-- Sort out pos
if type(tree) == "string" then return tree end
if tree.pos then
tree.line, tree.col = getline(doc, tree.pos)
end
if tree.id == "document"
or tree.id == "texlike_bracketed_stuff"
or tree.id == "passthrough_bracketed_stuff"
then return massage_ast(tree[1], doc) end
if tree.id == "texlike_text"
or tree.id == "passthrough_text"
or tree.id == "passthrough_env_text"
then return tree[1] end
for key, val in ipairs(tree) do
if val.id == "texlike_stuff"
or val.id == "passthrough_stuff"
or val.id == "passthrough_env_stuff"
then
SU.splice(tree, key, key, massage_ast(val, doc))
else
tree[key] = massage_ast(val, doc)
end
end
return tree
end
function SILE.inputs.TeXlike.process (doc)
local tree = SILE.inputs.TeXlike.docToTree(doc)
local root = SILE.documentState.documentClass == nil
if tree.tag then
if root and tree.tag == "document" then
SILE.inputs.common.init(doc, tree)
end
SILE.process(tree)
elseif pcall(function () assert(loadstring(doc))() end) then
else
SU.error("Input not recognized as Lua or SILE content")
end
if root and not SILE.preamble then
SILE.documentState.documentClass:finish()
end
end
local _parser
function SILE.inputs.TeXlike.rebuildParser ()
_parser = epnf.define(SILE.inputs.TeXlike.parser)
end
SILE.inputs.TeXlike.rebuildParser()
function SILE.inputs.TeXlike.docToTree (doc)
local tree = epnf.parsestring(_parser, doc)
-- a document always consists of one texlike_stuff
tree = tree[1][1]
if tree.id == "texlike_text" then tree = {tree} end
if not tree then return end
resetCache()
tree = massage_ast(tree, doc)
return tree
end
SILE.inputs.TeXlike.order = 99
SILE.inputs.TeXlike.appropriate = function () return true end
|
Fix case of included TeX-flavor markup
|
Fix case of included TeX-flavor markup
Closes #465. See also #505.
|
Lua
|
mit
|
alerque/sile,simoncozens/sile,simoncozens/sile,neofob/sile,simoncozens/sile,simoncozens/sile,neofob/sile,alerque/sile,alerque/sile,neofob/sile,alerque/sile,neofob/sile
|
ddfc4160a2de6f35422459d9f4950e9bb6a48e26
|
nyagos.d/suffix.lua
|
nyagos.d/suffix.lua
|
share._suffixes={}
share._setsuffix = function(suffix,cmdline)
local suffix=string.lower(suffix)
if string.sub(suffix,1,1)=='.' then
suffix = string.sub(suffix,2)
end
if not share._suffixes[suffix] then
local orgpathext = nyagos.getenv("PATHEXT")
local newext="."..suffix
if not string.find(";"..orgpathext..";",";"..newext..";",1,true) then
nyagos.setenv("PATHEXT",orgpathext..";"..newext)
end
end
local table = share._suffixes
table[suffix]=cmdline
share._suffixes = table
end
suffix = setmetatable({},{
__call = function(t,k,v) share._setsuffix(k,v) return end,
__newindex = function(t,k,v) share._setsuffix(k,v) return end,
__index = function(t,k) return share._suffixes[k] end
})
share._org_suffix_argsfilter=nyagos.argsfilter
nyagos.argsfilter = function(args)
if share._org_suffix_argsfilter then
local args_ = share._org_suffix_argsfilter(args)
if args_ then
args = args_
end
end
local path=nyagos.which(args[0])
if not path then
return
end
local m = string.match(path,"%.(%w+)$")
if not m then
return
end
local cmdline = share._suffixes[ string.lower(m) ]
if not cmdline then
return
end
local newargs={}
if type(cmdline) == 'table' then
for i=1,#cmdline do
newargs[i-1]=cmdline[i]
end
elseif type(cmdline) == 'string' then
newargs[0] = cmdline
end
newargs[#newargs+1] = path
for i=1,#args do
newargs[#newargs+1] = args[i]
end
return newargs
end
nyagos.alias.suffix = function(args)
if #args < 1 then
for key,val in pairs(share._suffixes) do
local right=val
if type(val) == "table" then
right = table.concat(val," ")
end
print(key .. "=" .. right)
end
return
end
if string.sub(args[1],1,1) == "." then
args[1] = string.sub(args[1],2)
end
if #args == 1 then
local right = share._suffixes[args[1]] or ""
if type(right) == "table" then
right = table.concat(right," ")
end
print(args[1].."=".. right)
return
end
local cmdline={}
for i=2,#args do
cmdline[#cmdline+1]=args[i]
end
share._setsuffix(args[1],cmdline)
end
suffix.pl="perl"
if nyagos.which("ipy") then
suffix.py="ipy"
elseif nyagos.which("py") then
suffix.py="py"
else
suffix.py="python"
end
suffix.rb="ruby"
suffix.lua="lua"
suffix.awk={"awk","-f"}
suffix.js={"cscript","//nologo"}
suffix.vbs={"cscript","//nologo"}
suffix.wsf={"cscript","//nologo"}
suffix.ps1={"powershell","-file"}
|
share._suffixes={}
share._setsuffix = function(suffix,cmdline)
local suffix=string.lower(suffix)
if string.sub(suffix,1,1)=='.' then
suffix = string.sub(suffix,2)
end
if not share._suffixes[suffix] then
local orgpathext = nyagos.getenv("PATHEXT")
local newext="."..suffix
if not string.find(";"..orgpathext..";",";"..newext..";",1,true) then
nyagos.setenv("PATHEXT",orgpathext..";"..newext)
end
end
local table = share._suffixes
table[suffix]=cmdline
share._suffixes = table
end
suffix = setmetatable({},{
__call = function(t,k,v) share._setsuffix(k,v) return end,
__newindex = function(t,k,v) share._setsuffix(k,v) return end,
__index = function(t,k) return share._suffixes[k] end
})
share._org_suffix_argsfilter=nyagos.argsfilter
nyagos.argsfilter = function(args)
if share._org_suffix_argsfilter then
local args_ = share._org_suffix_argsfilter(args)
if args_ then
args = args_
end
end
local path=nyagos.which(args[0])
if not path then
return
end
local m = string.match(path,"%.(%w+)$")
if not m then
return
end
local cmdline = share._suffixes[ string.lower(m) ]
if not cmdline then
return
end
local newargs={}
if type(cmdline) == 'table' then
for i=1,#cmdline do
newargs[i-1]=cmdline[i]
end
elseif type(cmdline) == 'string' then
newargs[0] = cmdline
end
newargs[#newargs+1] = path
for i=1,#args do
newargs[#newargs+1] = args[i]
end
return newargs
end
nyagos.alias.suffix = function(args)
if #args < 1 then
for key,val in pairs(share._suffixes) do
local right=val
if type(val) == "table" then
right = table.concat(val," ")
end
print(key .. "=" .. right)
end
return
end
for i=1,#args do
local left,right=string.match(args[i],"^%.?([^=]+)%=(.+)$")
if right then
local args={}
for m in string.gmatch(right,"%S+") do
args[#args+1] = m
end
share._suffixes[left] = args
else
print(args[i].."="..(share._suffixes[args[i]] or ""))
end
end
end
suffix.pl="perl"
if nyagos.which("ipy") then
suffix.py="ipy"
elseif nyagos.which("py") then
suffix.py="py"
else
suffix.py="python"
end
suffix.rb="ruby"
suffix.lua="lua"
suffix.awk={"awk","-f"}
suffix.js={"cscript","//nologo"}
suffix.vbs={"cscript","//nologo"}
suffix.wsf={"cscript","//nologo"}
suffix.ps1={"powershell","-file"}
|
Changed the syntax for suffix like `suffix EXT=COMMAND`
|
Changed the syntax for suffix like `suffix EXT=COMMAND`
|
Lua
|
bsd-3-clause
|
nocd5/nyagos,tsuyoshicho/nyagos,zetamatta/nyagos,tyochiai/nyagos
|
3522ee2c011dce20e33765f8faee641aa3cce7e4
|
OvaleIcone.lua
|
OvaleIcone.lua
|
function OvaleIcone_OnUpdate(self)
Ovale.maintenant = GetTime();
if (not Ovale.bug) then
Ovale.traced = false
end
Ovale:InitCalculerMeilleureAction()
local minAttente = Ovale:CalculerMeilleureAction(self.masterNode)
local meilleureAction = Ovale.retourAction
if (Ovale.trace) then
Ovale.trace=false
Ovale.traced = true
end
if (Ovale.bug and not Ovale.traced) then
Ovale.trace = true
end
if (Ovale.db.profile.apparence.avecCible and not UnitExists("target")) then
minAttente = nil
end
if (Ovale.db.profile.apparence.enCombat and not Ovale.enCombat) then
minAttente = nil
end
if (self.masterNode.params.nocd and
self.masterNode.params.nocd == 1 and minAttente~=nil and minAttente>1.5) then
minAttente = nil
end
if (minAttente~=nil and meilleureAction) then
if (meilleureAction~=self.actionCourante or self.ancienneAttente==nil or
(minAttente~=0 and minAttente>self.ancienneAttente+0.01)) then
self.actionCourante = meilleureAction
self.debutAction = Ovale.maintenant
end
self.ancienneAttente = minAttente
-- L'icône avec le cooldown
self.icone:Show()
self.icone:SetTexture(GetActionTexture(meilleureAction));
if (IsUsableAction(meilleureAction)) then
self.icone:SetAlpha(1.0)
else
self.icone:SetAlpha(0.25)
end
if (minAttente~=0) then
self.cd:SetCooldown(self.debutAction, minAttente+(Ovale.maintenant-self.debutAction));
end
-- Le temps restant
if (Ovale.db.profile.apparence.numeric) then
self.remains:SetText(string.format("%.1f", minAttente))
self.remains:Show()
else
self.remains:Hide()
end
-- Le raccourcis clavier
if (Ovale.db.profile.apparence.raccourcis) then
self.shortcut:Show()
self.shortcut:SetText(Ovale.shortCut[meilleureAction])
else
self.shortcut:Hide()
end
-- L'indicateur de portée
self.aPortee:Show()
if (IsActionInRange(meilleureAction,"target")==1) then
self.aPortee:SetTexture(1,1,1)
self.aPortee:Show()
elseif (IsActionInRange(meilleureAction,"target")==0) then
self.aPortee:SetTexture(1,0,0)
self.aPortee:Show()
else
self.aPortee:Hide()
end
else
self.icone:Hide()
self.aPortee:Hide()
self.shortcut:Hide()
self.remains:Hide()
end
end
function OvaleIcone_OnLoad(self)
self.icone = self:CreateTexture();
self.icone:SetDrawLayer("ARTWORK");
self.icone:SetAllPoints(self);
self.icone:Show();
self.shortcut = self:CreateFontString(nil, "OVERLAY");
self.shortcut:SetFontObject("GameFontHighlightLarge");
self.shortcut:SetPoint("BOTTOMLEFT",0,0);
self.shortcut:SetText("A");
self.shortcut:SetTextColor(1,1,1);
self.shortcut:Show();
self.remains = self:CreateFontString(nil, "OVERLAY");
self.remains:SetFontObject("GameFontHighlightLarge");
self.remains:SetAllPoints(self);
self.remains:SetTextColor(1,1,1);
self.remains:Show();
self.aPortee = self:CreateTexture();
self.aPortee:SetDrawLayer("OVERLAY")
self.aPortee:SetPoint("TOPRIGHT",self,"TOPRIGHT",-4,-4);
self.aPortee:SetHeight(self:GetHeight()/6);
self.aPortee:SetWidth(self:GetWidth()/6);
self.aPortee:SetTexture(0,0,1);
self.cd = CreateFrame("Cooldown",nil,self,nil);
self.cd:SetAllPoints(self);
end
|
function OvaleIcone_OnUpdate(self)
Ovale.maintenant = GetTime();
if (not Ovale.bug) then
Ovale.traced = false
end
Ovale:InitCalculerMeilleureAction()
local minAttente = Ovale:CalculerMeilleureAction(self.masterNode)
local meilleureAction = Ovale.retourAction
if (Ovale.trace) then
Ovale.trace=false
Ovale.traced = true
end
if (Ovale.bug and not Ovale.traced) then
Ovale.trace = true
end
if (Ovale.db.profile.apparence.avecCible and not UnitExists("target")) then
minAttente = nil
end
if (Ovale.db.profile.apparence.enCombat and not Ovale.enCombat) then
minAttente = nil
end
if (self.masterNode.params.nocd and
self.masterNode.params.nocd == 1 and minAttente~=nil and minAttente>1.5) then
minAttente = nil
end
if (minAttente~=nil and meilleureAction) then
if (meilleureAction~=self.actionCourante or self.ancienneAttente==nil or
(minAttente~=0 and minAttente>self.ancienneAttente+0.01) or
(Ovale.maintenant + minAttente < self.finAction-0.01)) then
self.actionCourante = meilleureAction
self.debutAction = Ovale.maintenant
self.finAction = minAttente + self.debutAction
if (minAttente == 0) then
self.cd:Hide()
else
self.cd:Show()
self.cd:SetCooldown(self.debutAction, self.finAction - self.debutAction);
end
end
self.ancienneAttente = minAttente
-- L'icône avec le cooldown
self.icone:Show()
self.icone:SetTexture(GetActionTexture(meilleureAction));
if (IsUsableAction(meilleureAction)) then
self.icone:SetAlpha(1.0)
else
self.icone:SetAlpha(0.25)
end
if (minAttente==0) then
self.cd:Hide()
end
-- Le temps restant
if (Ovale.db.profile.apparence.numeric) then
self.remains:SetText(string.format("%.1f", minAttente))
self.remains:Show()
else
self.remains:Hide()
end
-- Le raccourcis clavier
if (Ovale.db.profile.apparence.raccourcis) then
self.shortcut:Show()
self.shortcut:SetText(Ovale.shortCut[meilleureAction])
else
self.shortcut:Hide()
end
-- L'indicateur de portée
self.aPortee:Show()
if (IsActionInRange(meilleureAction,"target")==1) then
self.aPortee:SetTexture(1,1,1)
self.aPortee:Show()
elseif (IsActionInRange(meilleureAction,"target")==0) then
self.aPortee:SetTexture(1,0,0)
self.aPortee:Show()
else
self.aPortee:Hide()
end
else
self.icone:Hide()
self.aPortee:Hide()
self.shortcut:Hide()
self.remains:Hide()
end
end
function OvaleIcone_OnLoad(self)
self.icone = self:CreateTexture();
self.icone:SetDrawLayer("ARTWORK");
self.icone:SetAllPoints(self);
self.icone:Show();
self.shortcut = self:CreateFontString(nil, "OVERLAY");
self.shortcut:SetFontObject("GameFontHighlightLarge");
self.shortcut:SetPoint("BOTTOMLEFT",0,0);
self.shortcut:SetText("A");
self.shortcut:SetTextColor(1,1,1);
self.shortcut:Show();
self.remains = self:CreateFontString(nil, "OVERLAY");
self.remains:SetFontObject("GameFontHighlightLarge");
self.remains:SetAllPoints(self);
self.remains:SetTextColor(1,1,1);
self.remains:Show();
self.aPortee = self:CreateTexture();
self.aPortee:SetDrawLayer("OVERLAY")
self.aPortee:SetPoint("TOPRIGHT",self,"TOPRIGHT",-4,-4);
self.aPortee:SetHeight(self:GetHeight()/6);
self.aPortee:SetWidth(self:GetWidth()/6);
self.aPortee:SetTexture(0,0,1);
self.cd = CreateFrame("Cooldown",nil,self,nil);
self.cd:SetAllPoints(self);
end
|
- bug fix: hides the cooldown when a spell has no cooldown when it is first shown (e.g. a spell that is casted after a proc)
|
- bug fix: hides the cooldown when a spell has no cooldown when it is first shown (e.g. a spell that is casted after a proc)
git-svn-id: b2bb544abab4b09d60f88077ac82407cb244c9c9@30 d5049fe3-3747-40f7-a4b5-f36d6801af5f
|
Lua
|
mit
|
ultijlam/ovale,eXhausted/Ovale,ultijlam/ovale,Xeltor/ovale,ultijlam/ovale,eXhausted/Ovale,eXhausted/Ovale
|
5b0c01207078b6538cc211baa63df62ce7f4a4ee
|
modules/alarm.lua
|
modules/alarm.lua
|
local ev = require'ev'
if(not ivar2.timers) then ivar2.timers = {} end
local dateFormat = '%Y-%m-%d %X %Z'
local split = function(str, pattern)
local out = {}
str:gsub(pattern, function(match)
table.insert(out, match)
end)
return out
end
local timeMatches = {
{
'(%d+)[:.](%d%d)[:.]?(%d?%d?)', function(h, m, s)
-- Seconds will always return a match.
if(s == '') then s = 0 end
local duration = 0
local now = os.time()
local date = os.date'*t'
local ntime = date.hour * 60 * 60 + date.min * 60 + date.sec
local atime = h * 60 * 60 + m * 60 + s
-- Set the correct time of day.
date.hour = h
date.min = m
date.sec = s
-- If the alarm is right now or in the past, bump it to the next day.
if(ntime >= atime) then
date.day = date.day + 1
end
return os.time(date) - now
end
},
{'^(%d+)w$', function(w) return w * 60 * 60 * 24 * 7 end},
{'^(%d+)d$', function(d) return d * 60 * 60 * 24 end},
{'^(%d+)[ht]$', function(h) return h * 60 * 60 end},
{'^(%d+)m$', function(m) return m * 60 end},
{'^(%d+)s$', function(s) return s end},
}
local parseTime = function(input)
local duration = 0
local offset
for i=1, #input do
local found
local str = input[i]
for j=1, #timeMatches do
local pattern, func = unpack(timeMatches[j])
local a1, a2, a3 = str:match(pattern)
if(a1) then
found = true
duration = duration + func(a1, a2, a3)
end
end
if(not found) then break end
offset = i + 1
end
if(duration ~= 0) then
return duration, table.concat(input, ' ', offset)
end
end
local alarm = function(self, source, destination, message)
local duration, message = parseTime(split(message, '%S+'))
-- Couldn't figure out what the user wanted.
if(not duration) then return end
-- 60 days or more?
local nick = source.nick
if(duration >= (60 * 60 * 24 * 60) or duration == 0) then
return self:Msg('privmsg', destination, source, "%s: :'(", nick)
end
local id = 'Alarm: ' .. nick
local runningTimer = self.timers[id]
if(runningTimer) then
-- Send a notification if we are overriding an old timer.
if(runningTimer.utimestamp > os.time()) then
if(runningTimer.message) then
self:Notice(
nick,
'Previously active timer set to trigger at %s with message "%s" has been removed.',
os.date(dateFormat, runningTimer.utimestamp),
runningTimer.message
)
else
self:Notice(
nick,
'Previously active timer set to trigger at %s has been removed.',
os.date(dateFormat, runningTimer.utimestamp)
)
end
end
-- message is probably changed.
runningTimer:stop(ivar2.Loop)
end
local timer = ev.Timer.new(
function(loop, timer, revents)
if(#message == 0) then message = 'Timer finished.' end
self:Msg('privmsg', destination, source, '%s: %s', nick, message or 'Timer finished.')
end,
duration
)
if(#message > 0) then timer.message = message end
timer.utimestamp = os.time() + duration
self:Notice(nick, "I'll poke you at %s.", os.date(dateFormat, timer.utimestamp))
self.timers[id] = timer
timer:start(ivar2.Loop)
end
return {
PRIVMSG = {
['^!alarm (.*)$'] = alarm,
['^!timer (.*)$'] = alarm,
},
}
|
local ev = require'ev'
if(not ivar2.timers) then ivar2.timers = {} end
local dateFormat = '%Y-%m-%d %X %Z'
local split = function(str, pattern)
local out = {}
str:gsub(pattern, function(match)
table.insert(out, match)
end)
return out
end
local timeMatches = {
{
'(%d+)[:.](%d%d)[:.]?(%d?%d?)', function(h, m, s)
-- Seconds will always return a match.
if(s == '') then s = 0 end
local duration = 0
local now = os.time()
local date = os.date'*t'
local ntime = date.hour * 60 * 60 + date.min * 60 + date.sec
local atime = h * 60 * 60 + m * 60 + s
-- Set the correct time of day.
date.hour = h
date.min = m
date.sec = s
-- If the alarm is right now or in the past, bump it to the next day.
if(ntime >= atime) then
date.day = date.day + 1
end
return os.time(date) - now
end
},
{'^(%d+)w$', function(w) return w * 60 * 60 * 24 * 7 end},
{'^(%d+)d$', function(d) return d * 60 * 60 * 24 end},
{'^(%d+)[ht]$', function(h) return h * 60 * 60 end},
{'^(%d+)m$', function(m) return m * 60 end},
{'^(%d+)[^%p%w]*$', function(m) return m * 60 end},
{'^(%d+)s$', function(s) return s end},
}
local parseTime = function(input)
local duration = 0
local offset
for i=1, #input do
local found
local str = input[i]
for j=1, #timeMatches do
local pattern, func = unpack(timeMatches[j])
local a1, a2, a3 = str:match(pattern)
if(a1) then
found = true
duration = duration + func(a1, a2, a3)
end
end
if(not found) then break end
offset = i + 1
end
if(duration ~= 0) then
return duration, table.concat(input, ' ', offset)
end
end
local alarm = function(self, source, destination, message)
local duration, message = parseTime(split(message, '%S+'))
-- Couldn't figure out what the user wanted.
if(not duration) then return end
-- 60 days or more?
local nick = source.nick
if(duration >= (60 * 60 * 24 * 60) or duration == 0) then
return self:Msg('privmsg', destination, source, "%s: :'(", nick)
end
local id = 'Alarm: ' .. nick
local runningTimer = self.timers[id]
if(runningTimer) then
-- Send a notification if we are overriding an old timer.
if(runningTimer.utimestamp > os.time()) then
if(runningTimer.message) then
self:Notice(
nick,
'Previously active timer set to trigger at %s with message "%s" has been removed.',
os.date(dateFormat, runningTimer.utimestamp),
runningTimer.message
)
else
self:Notice(
nick,
'Previously active timer set to trigger at %s has been removed.',
os.date(dateFormat, runningTimer.utimestamp)
)
end
end
-- message is probably changed.
runningTimer:stop(ivar2.Loop)
end
local timer = ev.Timer.new(
function(loop, timer, revents)
if(#message == 0) then message = 'Timer finished.' end
self:Msg('privmsg', destination, source, '%s: %s', nick, message or 'Timer finished.')
end,
duration
)
if(#message > 0) then timer.message = message end
timer.utimestamp = os.time() + duration
self:Notice(nick, "I'll poke you at %s.", os.date(dateFormat, timer.utimestamp))
self.timers[id] = timer
timer:start(ivar2.Loop)
end
return {
PRIVMSG = {
['^!alarm (.*)$'] = alarm,
['^!timer (.*)$'] = alarm,
},
}
|
alarm: Timers with no postfix default to minutes.
|
alarm: Timers with no postfix default to minutes.
|
Lua
|
mit
|
torhve/ivar2,haste/ivar2,torhve/ivar2,torhve/ivar2
|
b490e4533c1338194cea01c454368f6fc7fd5233
|
hammerspoon/.hammerspoon/jumpcutselect.lua
|
hammerspoon/.hammerspoon/jumpcutselect.lua
|
-- Selector for jumpcut thingy
local settings = require("hs.settings")
local utils = require("utils")
local mod = {}
-- jumpcutselect
function mod.jumpcutselect()
function formatChoices(choices)
choices = utils.reverse(choices)
formattedChoices = hs.fnutils.imap(choices, function(result)
return {
["text"] = utils.trim(result),
}
end)
return formattedChoices
end
local copy = nil
local current = hs.application.frontmostApplication()
local copies = settings.get("so.meain.hs.jumpcut") or {}
local choices = formatChoices(copies)
local chooser = hs.chooser.new(function(choosen)
if copy then copy:delete() end
current:activate()
hs.eventtap.keyStrokes(choosen)
end)
chooser:choices(formatChoices(copies))
copy = hs.hotkey.bind('', 'return', function()
local id = chooser:selectedRow()
local item = choices[id]
if item then
chooser:hide()
trimmed = utils.trim(item.text)
hs.pasteboard.setContents(trimmed)
settings.set("so.meain.hs.jumpcutselect.lastselected", trimmed)
hs.alert.show(trimmed, 1)
-- hs.notify.show("Jumpcut","Text copied", trimmed)
else
hs.alert.show("Nothing to copy", 1)
end
end)
function updateChooser()
local query = chooser:query()
local filteredChoices = hs.fnutils.filter(copies, function(result)
return string.match(result, query)
end)
chooser:choices(formatChoices(filteredChoices))
end
chooser:queryChangedCallback(updateChooser)
chooser:searchSubText(false)
chooser:show()
end
function mod.registerDefaultBindings(mods, key)
mods = mods or {"cmd", "alt", "ctrl"}
key = key or "P"
hs.hotkey.bind(mods, key, mod.jumpcutselect)
end
return mod
|
-- Selector for jumpcut thingy
local settings = require("hs.settings")
local utils = require("utils")
local mod = {}
-- jumpcutselect
function mod.jumpcutselect()
function formatChoices(choices)
choices = utils.reverse(choices)
formattedChoices = hs.fnutils.imap(choices, function(result)
return {
["text"] = utils.trim(result),
}
end)
return formattedChoices
end
local copy = nil
local current = hs.application.frontmostApplication()
local copies = settings.get("so.meain.hs.jumpcut") or {}
local choices = formatChoices(copies)
local chooser = hs.chooser.new(function(choosen)
if copy then copy:delete() end
current:activate()
hs.eventtap.keyStrokes(choosen)
end)
chooser:choices(formatChoices(copies))
copy = hs.hotkey.bind('', 'return', function()
local query = chooser:query()
local filteredChoices = hs.fnutils.filter(copies, function(result)
return string.match(result, query)
end)
local id = chooser:selectedRow()
local item = formatChoices(filteredChoices)[id]
if item then
chooser:hide()
trimmed = utils.trim(item.text)
hs.pasteboard.setContents(trimmed)
settings.set("so.meain.hs.jumpcutselect.lastselected", trimmed)
hs.alert.show(trimmed, 1)
-- hs.notify.show("Jumpcut","Text copied", trimmed)
else
hs.alert.show("Nothing to copy", 1)
end
end)
function updateChooser()
local query = chooser:query()
local filteredChoices = hs.fnutils.filter(copies, function(result)
return string.match(result, query)
end)
chooser:choices(formatChoices(filteredChoices))
end
chooser:queryChangedCallback(updateChooser)
chooser:searchSubText(false)
chooser:show()
end
function mod.registerDefaultBindings(mods, key)
mods = mods or {"cmd", "alt", "ctrl"}
key = key or "P"
hs.hotkey.bind(mods, key, mod.jumpcutselect)
end
return mod
|
[hammerspoon] fix selection after filtering
|
[hammerspoon] fix selection after filtering
|
Lua
|
mit
|
meain/dotfiles,meain/dotfiles,meain/dotfiles,meain/dotfiles,meain/dotfiles,meain/dotfiles
|
13d8c957acd906fd809aa284d8ae9bfe8947569e
|
spec/algo/LoadFromLua_spec.lua
|
spec/algo/LoadFromLua_spec.lua
|
describe("algo.LoadFromLua", function()
it("loads Lua files in #sandbox", function()
local model = require 'npge.model'
local s = model.Sequence("test_name", "ATAT")
local f1 = model.Fragment(s, 0, 1, 1)
local f2 = model.Fragment(s, 3, 2, -1)
local block1 = model.Block({f2})
local block2 = model.Block({f1})
local blockset = model.BlockSet({s}, {block1, block2})
local BlockSetToLua = require 'npge.algo.BlockSetToLua'
local readIt = require 'npge.util.readIt'
local lua = readIt(BlockSetToLua(blockset))
local LoadFromLua = require 'npge.algo.LoadFromLua'
local blockset1 = LoadFromLua(lua)()
assert.equal(blockset1, blockset)
end)
it("loads sequences + blockset", function()
local model = require 'npge.model'
local s = model.Sequence("test_name", "ATAT")
if s.toRef then
local f1 = model.Fragment(s, 0, 1, 1)
local f2 = model.Fragment(s, 3, 2, -1)
local block1 = model.Block({f2})
local block2 = model.Block({f1})
local blockset = model.BlockSet({s},
{block1, block2})
local readIt = require 'npge.util.readIt'
local SequencesToLua =
require 'npge.algo.SequencesToLua'
local lua1 = readIt(SequencesToLua(blockset))
local BlockSetToLua =
require 'npge.algo.BlockSetToLua'
local lua2 = readIt(BlockSetToLua(blockset))
local LoadFromLua =
require 'npge.algo.LoadFromLua'
local enable_fromRef = true
local name2seq = LoadFromLua(lua1,
enable_fromRef)()
local blockset1 = LoadFromLua(lua2)(name2seq)
assert.equal(blockset1, blockset)
end
end)
end)
|
describe("algo.LoadFromLua", function()
it("loads Lua files in #sandbox", function()
local model = require 'npge.model'
local s = model.Sequence("test_name", "ATAT")
local f1 = model.Fragment(s, 0, 1, 1)
local f2 = model.Fragment(s, 3, 2, -1)
local block1 = model.Block({f2})
local block2 = model.Block({f1})
local blockset = model.BlockSet({s}, {block1, block2})
local BlockSetToLua = require 'npge.algo.BlockSetToLua'
local readIt = require 'npge.util.readIt'
local lua = readIt(BlockSetToLua(blockset))
local LoadFromLua = require 'npge.algo.LoadFromLua'
local blockset1 = LoadFromLua(lua)()
assert.equal(blockset1, blockset)
end)
it("loads sequences + blockset", function()
local model = require 'npge.model'
local s = model.Sequence("test_name", "ATAT")
if s.toRef then
local f1 = model.Fragment(s, 0, 1, 1)
local f2 = model.Fragment(s, 3, 2, -1)
local block1 = model.Block({f2})
local block2 = model.Block({f1})
local blockset = model.BlockSet({s},
{block1, block2})
local readIt = require 'npge.util.readIt'
local SequencesToLua =
require 'npge.algo.SequencesToLua'
local lua1 = readIt(SequencesToLua(blockset))
local BlockSetToLua =
require 'npge.algo.BlockSetToLua'
local has_sequences = true
local lua2 = readIt(BlockSetToLua(blockset,
has_sequences))
local LoadFromLua =
require 'npge.algo.LoadFromLua'
local enable_fromRef = true
local name2seq = LoadFromLua(lua1,
enable_fromRef)()
local blockset1 = LoadFromLua(lua2)(name2seq)
assert.equal(blockset1, blockset)
end
end)
end)
|
LoadFromLua: fix using preloaded sequences
|
LoadFromLua: fix using preloaded sequences
|
Lua
|
mit
|
npge/lua-npge,starius/lua-npge,starius/lua-npge,starius/lua-npge,npge/lua-npge,npge/lua-npge
|
13134c0b48ada5a0f627a4a1a10fae13b0b803b3
|
application.lua
|
application.lua
|
local sda = 6
local scl = 5
function receiver(sck, data)
print(data)
sck:close()
end
function makepromlines(prefix, name, source)
local buffer = {"# TYPE ", prefix, name, " gauge\n", prefix, name, " ", source, "\n"}
local lines = table.concat(buffer)
return lines
end
function metrics()
local t, p, h, qnh = bme280.read(altitude)
local d = bme280.dewpoint(h, t)
-- this table contains the metric names and sources.
local metricspecs = {
"temperature_celsius", t/100,
"airpressure_hectopascal", p/1000,
"airpressure_sealevel_hectopascal", qnh/1000,
"humidity_percent", h/1000,
"dewpoint_celsius", d/100,
}
local metrics = {}
for i = 1, #metricspecs, 2 do
table.insert(metrics, makepromlines("nodemcu_", metricspecs[i], metricspecs[i+1]))
end
local body = table.concat(metrics)
return body
end
function response()
local header = "HTTP/1.0 200 OK\r\nServer: NodeMCU on ESP8266\r\nContent-Type: text/plain; version=0.0.4\r\n\r\n"
local response = header .. metrics()
return response
end
i2c.setup(0, sda, scl, i2c.SLOW) -- call i2c.setup() only once
bme280.setup()
srv = net.createServer(net.TCP, 20) -- 20s timeout
if srv then
srv:listen(80, function(conn)
conn:on("receive", receiver)
conn:send(response())
conn:close()
end)
end
|
local sda = 6
local scl = 5
function makepromlines(prefix, name, source)
local buffer = {"# TYPE ", prefix, name, " gauge\n", prefix, name, " ", source, "\n"}
local lines = table.concat(buffer)
return lines
end
function metrics()
local t, p, h, qnh = bme280.read(altitude)
local d = bme280.dewpoint(h, t)
-- this table contains the metric names and sources.
local metricspecs = {
"temperature_celsius", t/100,
"airpressure_hectopascal", p/1000,
"airpressure_sealevel_hectopascal", qnh/1000,
"humidity_percent", h/1000,
"dewpoint_celsius", d/100,
}
local metrics = {}
for i = 1, #metricspecs, 2 do
table.insert(metrics, makepromlines("nodemcu_", metricspecs[i], metricspecs[i+1]))
end
local body = table.concat(metrics)
return body
end
function response()
local header = "HTTP/1.0 200 OK\r\nServer: NodeMCU on ESP8266\r\nContent-Type: text/plain; version=0.0.4\r\n\r\n"
local response = header .. metrics()
print("> " .. response)
return response
end
i2c.setup(0, sda, scl, i2c.SLOW) -- call i2c.setup() only once
-- Setup according to recommendation in 3.5.1 of datasheet:
-- - 1x oversampling
-- - sleep mode (we enable forced mode when taking measurements)
-- - IIR filter off
bme280.setup(1, 1, 1, 0, nil, 0)
srv = net.createServer(net.TCP, 20) -- 20s timeout
if srv then
srv:listen(80, function(conn)
conn:on("receive", function(conn, data)
print("< " .. data)
bme280.startreadout(0, function ()
conn:send(response())
conn:close()
end)
end)
end)
end
|
Use sleep+force mode and chain callbacks properly
|
Use sleep+force mode and chain callbacks properly
According to the datasheet[1] in section 3.5.1, the recommended
operation for weather monitoring is to use forced mode. This prevents
the sensor from becoming warm and distort the temperature results.
This also fixes the callbacks that need to be properly chained to avoid
race conditions.
1: https://ae-bst.resource.bosch.com/media/_tech/media/datasheets/BST-BME280_DS001-12.pdf
|
Lua
|
mit
|
vonneudeck/mouldy,vonneudeck/mouldy
|
a94a2577c020e1c8bb819e9392d8823f0b478b21
|
setup.lua
|
setup.lua
|
-- module for initial setup
local config = require "config"
local categoryList = config.categories
local filePath = config.filePath
local dbmodule = require "dbmodule"
local setup = {}
function setup.file_exists(file)
local f = io.open(file, "rb")
if f then f:close() end
return f ~= nil
end
-- get all lines from a file, returns an empty
-- list/table if the file does not exist
function lines_from(file)
if not setup.file_exists(file) then print "File don't exist" os.exit() end
lines = {}
for line in io.lines(file) do
lines[#lines + 1] = line
end
return lines
end
-- tests the functions above
local file = filePath
local lines = lines_from(file)
-- create a script.db backups
function createBackup()
outfile = io.open(config.fileBackup, "w")
for k,v in pairs(lines) do
outfile:write(v.."\n")
end
outfile:close()
if not setup.file_exists(config.fileBackup) then
print "the backup can not created"
else
print "backup succesfull"
end
end
function setup.install()
-- print('\27[1m \27[36m'..banner..'\27[21m \27[0m')
dbmodule.InitSetup("wc")
local t ={}
local id_script = 0
for k,v in ipairs(lines) do
v = v:gsub('%Entry { filename = "',""):gsub('", categories = { "',',"'):gsub('", } }','"'):gsub('", "','","')
for i,c in ipairs(categoryList) do
v = v:gsub('"'..c..'"',i)
end
for a in string.gmatch(v,"([^,]+)") do
table.insert(t,a)
end
for key,value in ipairs(t) do
if t[1] == value then
local val = {value}
id_script = dbmodule.InsertScript(val,"scripts")
else
dbmodule.InsertCategory(id_script,value)
end
end
t = {}
end
createBackup()
end
return setup
|
-- module for initial setup
local config = require "config"
local categoryList = config.categories
local filePath = config.filePath
local dbmodule = require "dbmodule"
local setup = {}
function setup.file_exists(file)
local f = io.open(file, "rb")
if f then f:close() end
return f ~= nil
end
-- get all lines from a file, returns an empty
-- list/table if the file does not exist
function lines_from(file)
if not setup.file_exists(file) then print "File don't exist" os.exit() end
lines = {}
for line in io.lines(file) do
lines[#lines + 1] = line
end
return lines
end
-- tests the functions above
local file = filePath
local lines = lines_from(file)
-- create a script.db backups
function createBackup()
outfile = io.open(config.fileBackup, "w")
for k,v in pairs(lines) do
outfile:write(v.."\n")
end
outfile:close()
if not setup.file_exists(config.fileBackup) then
print "the backup can not created"
else
print "backup succesfull"
end
end
function setup.install()
dbmodule.InitSetup("wc")
local t ={}
local id_script = 0
for k,v in ipairs(lines) do
v = v:gsub('%Entry { filename = "',""):gsub('", categories = { "',',"'):gsub('", } }','"'):gsub('", "','","')
for i,c in ipairs(categoryList) do
v = v:gsub('"'..c..'"',i)
end
for a in string.gmatch(v,"([^,]+)") do
table.insert(t,a)
end
for key,value in ipairs(t) do
if t[1] == value then
local val = {value}
id_script = dbmodule.InsertScript(val,"scripts")
else
dbmodule.InsertCategory(id_script,value)
end
end
t = {}
end
createBackup()
end
return setup
|
#8 fixes removed display banner
|
#8 fixes removed display banner
Signed-off-by: Jacobo Tibaquira <d8d2a0ed36dd5f2e41c721fffbe8af2e7e4fe993@gmail.com>
|
Lua
|
apache-2.0
|
JKO/nsearch,JKO/nsearch
|
7292c475b2570b5daf13995951e53847b0a7b375
|
share/luaplaylist/youtube.lua
|
share/luaplaylist/youtube.lua
|
-- $Id$
-- Helper function to get a parameter's value in a URL
function get_url_param( url, name )
return string.gsub( vlc.path, "^.*"..name.."=([^&]*).*$", "%1" )
end
-- Probe function.
function probe()
return vlc.access == "http"
and string.match( vlc.path, "youtube.com" )
and ( string.match( vlc.path, "watch%?v=" )
or string.match( vlc.path, "watch_fullscreen%?video_id=" )
or string.match( vlc.path, "p.swf" )
or string.match( vlc.path, "player2.swf" ) )
end
-- Parse function.
function parse()
if string.match( vlc.path, "watch%?v=" )
then -- This is the HTML page's URL
while true do
-- Try to find the video's title
line = vlc.readline()
if not line then break end
if string.match( line, "<meta name=\"title\"" ) then
name = string.gsub( line, "^.*content=\"([^\"]*).*$", "%1" )
end
if string.match( line, "<meta name=\"description\"" ) then
description = string.gsub( line, "^.*content=\"([^\"]*).*$", "%1" )
end
if string.match( line, "subscribe_to_user=" ) then
artist = string.gsub( line, ".*subscribe_to_user=([^&]*).*", "%1" )
end
if name and description and artist then break end
end
return { { path = string.gsub( vlc.path, "^(.*)watch%?v=([^&]*).*$", "http://%1v/%2" ); name = name; description = description; artist = artist } }
else -- This is the flash player's URL
if string.match( vlc.path, "title=" ) then
name = get_url_param( vlc.path, "title" )
end
return { { path = "http://www.youtube.com/get_video.php?video_id="..get_url_param( vlc.path, "video_id" ).."&t="..get_url_param( vlc.patch, "t" ); name = name } }
end
end
|
-- $Id$
-- Helper function to get a parameter's value in a URL
function get_url_param( url, name )
return string.gsub( vlc.path, "^.*"..name.."=([^&]*).*$", "%1" )
end
-- Probe function.
function probe()
return vlc.access == "http"
and string.match( vlc.path, "youtube.com" )
and ( string.match( vlc.path, "watch%?v=" )
or string.match( vlc.path, "watch_fullscreen%?video_id=" )
or string.match( vlc.path, "p.swf" )
or string.match( vlc.path, "player2.swf" ) )
end
-- Parse function.
function parse()
if string.match( vlc.path, "watch%?v=" )
then -- This is the HTML page's URL
while true do
-- Try to find the video's title
line = vlc.readline()
if not line then break end
if string.match( line, "<meta name=\"title\"" ) then
name = string.gsub( line, "^.*content=\"([^\"]*).*$", "%1" )
end
if string.match( line, "<meta name=\"description\"" ) then
description = string.gsub( line, "^.*content=\"([^\"]*).*$", "%1" )
end
if string.match( line, "subscribe_to_user=" ) then
artist = string.gsub( line, ".*subscribe_to_user=([^&]*).*", "%1" )
end
if string.match( line, "player2.swf" ) then
video_id = string.gsub( line, ".*BASE_YT_URL=http://youtube.com/&video_id=([^\"]*).*", "%1" )
end
if name and description and artist and video_id then break end
end
return { { path = "http://www.youtube.com/get_video.php?video_id="..video_id; name = name; description = description; artist = artist } }
else -- This is the flash player's URL
if string.match( vlc.path, "title=" ) then
name = get_url_param( vlc.path, "title" )
end
return { { path = "http://www.youtube.com/get_video.php?video_id="..get_url_param( vlc.path, "video_id" ).."&t="..get_url_param( vlc.patch, "t" ); name = name } }
end
end
|
Fixes youtube parsing
|
Fixes youtube parsing
|
Lua
|
lgpl-2.1
|
vlc-mirror/vlc-2.1,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.2,xkfz007/vlc,jomanmuk/vlc-2.2,vlc-mirror/vlc,jomanmuk/vlc-2.2,vlc-mirror/vlc,krichter722/vlc,krichter722/vlc,vlc-mirror/vlc-2.1,vlc-mirror/vlc,vlc-mirror/vlc,shyamalschandra/vlc,jomanmuk/vlc-2.2,vlc-mirror/vlc-2.1,shyamalschandra/vlc,jomanmuk/vlc-2.1,jomanmuk/vlc-2.1,shyamalschandra/vlc,xkfz007/vlc,krichter722/vlc,vlc-mirror/vlc-2.1,shyamalschandra/vlc,vlc-mirror/vlc,krichter722/vlc,krichter722/vlc,xkfz007/vlc,vlc-mirror/vlc,xkfz007/vlc,xkfz007/vlc,jomanmuk/vlc-2.2,krichter722/vlc,jomanmuk/vlc-2.1,shyamalschandra/vlc,jomanmuk/vlc-2.1,jomanmuk/vlc-2.1,jomanmuk/vlc-2.1,shyamalschandra/vlc,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.1,jomanmuk/vlc-2.2,vlc-mirror/vlc-2.1,vlc-mirror/vlc,shyamalschandra/vlc,krichter722/vlc,xkfz007/vlc,xkfz007/vlc,jomanmuk/vlc-2.2
|
9ea23cd57e3c600b98fb0c3c04c078f51facff41
|
MMOCoreORB/bin/scripts/screenplays/tasks/mat_rags.lua
|
MMOCoreORB/bin/scripts/screenplays/tasks/mat_rags.lua
|
mat_rags_missions =
{
{
missionType = "assassinate",
silentTarget = "yes",
primarySpawns =
{
{ npcTemplate = "mat_rags_desert_squill", planetName = "tatooine", npcName = "desert squill" }
},
secondarySpawns = {},
itemSpawns =
{
{ itemTemplate = "object/tangible/mission/quest_item/mat_rags_q1_needed.iff", itemName = "Squill Carcass" }
},
rewards = {}
},
{
missionType = "assassinate",
silentTarget = "yes",
primarySpawns =
{
{ npcTemplate = "mat_rags_greater_desert_womp_rat", planetName = "tatooine", npcName = "a greater desert womp rat" }
},
secondarySpawns = {},
itemSpawns =
{
{ itemTemplate = "object/tangible/mission/quest_item/mat_rags_q2_needed.iff", itemName = "Womp Rat Hide" }
},
rewards = {}
},
{
missionType = "assassinate",
silentTarget = "yes",
primarySpawns =
{
{ npcTemplate = "mat_rags_bantha_matriarch", planetName = "tatooine", npcName = "a bantha matriarch" }
},
secondarySpawns = {},
itemSpawns =
{
{ itemTemplate = "object/tangible/mission/quest_item/mat_rags_q3_needed.iff", itemName = "Bantha Horns" }
},
rewards = {}
},
{
missionType = "assassinate",
silentTarget = "yes",
primarySpawns =
{
{ npcTemplate = "mat_rags_grizzled_dewback", planetName = "tatooine", npcName = "a grizzled dewback" }
},
secondarySpawns = {},
itemSpawns =
{
{ itemTemplate = "object/tangible/mission/quest_item/mat_rags_q4_needed.iff", itemName = "Grizzled Dewback Hide" }
},
rewards =
{
{ rewardType = "loot", lootGroup = "task_reward_mat_rags" },
}
}
}
npcMapMatRags =
{
{
spawnData = { planetName = "tatooine", npcTemplate = "mat_rags", x = -2977, z = 5, y = 2458, direction = -65, cellID = 0, position = STAND },
npcNumber = 1,
stfFile = "@static_npc/tatooine/mat_rags",
hasWaypointNames = "no",
missions = mat_rags_missions
},
}
MatRags = ThemeParkLogic:new {
numberOfActs = 1,
npcMap = npcMapMatRags,
permissionMap = {},
className = "MatRags",
screenPlayState = "mat_rags_quest",
distance = 1000,
missionDescriptionStf = "",
missionCompletionMessageStf = "@theme_park/messages:static_completion_message"
}
registerScreenPlay("MatRags", true)
mat_rags_mission_giver_conv_handler = mission_giver_conv_handler:new {
themePark = MatRags
}
mat_rags_mission_target_conv_handler = mission_target_conv_handler:new {
themePark = MatRags
}
|
mat_rags_missions =
{
{
missionType = "assassinate",
silentTarget = "yes",
primarySpawns =
{
{ npcTemplate = "mat_rags_desert_squill", planetName = "tatooine", npcName = "desert squill" }
},
secondarySpawns = {},
itemSpawns =
{
{ itemTemplate = "object/tangible/mission/quest_item/mat_rags_q1_needed.iff", itemName = "Squill Carcass" }
},
rewards =
{
{ rewardType = "credits", amount = 2000 },
}
},
{
missionType = "assassinate",
silentTarget = "yes",
primarySpawns =
{
{ npcTemplate = "mat_rags_greater_desert_womp_rat", planetName = "tatooine", npcName = "a greater desert womp rat" }
},
secondarySpawns = {},
itemSpawns =
{
{ itemTemplate = "object/tangible/mission/quest_item/mat_rags_q2_needed.iff", itemName = "Womp Rat Hide" }
},
rewards =
{
{ rewardType = "credits", amount = 4000 },
}
},
{
missionType = "assassinate",
silentTarget = "yes",
primarySpawns =
{
{ npcTemplate = "mat_rags_bantha_matriarch", planetName = "tatooine", npcName = "a bantha matriarch" }
},
secondarySpawns = {},
itemSpawns =
{
{ itemTemplate = "object/tangible/mission/quest_item/mat_rags_q3_needed.iff", itemName = "Bantha Horns" }
},
rewards =
{
{ rewardType = "credits", amount = 6000 },
}
},
{
missionType = "assassinate",
silentTarget = "yes",
primarySpawns =
{
{ npcTemplate = "mat_rags_grizzled_dewback", planetName = "tatooine", npcName = "a grizzled dewback" }
},
secondarySpawns = {},
itemSpawns =
{
{ itemTemplate = "object/tangible/mission/quest_item/mat_rags_q4_needed.iff", itemName = "Grizzled Dewback Hide" }
},
rewards =
{
{ rewardType = "loot", lootGroup = "task_reward_mat_rags" },
{ rewardType = "credits", amount = 6000 },
}
}
}
npcMapMatRags =
{
{
spawnData = { planetName = "tatooine", npcTemplate = "mat_rags", x = -2977, z = 5, y = 2458, direction = -65, cellID = 0, position = STAND },
npcNumber = 1,
stfFile = "@static_npc/tatooine/mat_rags",
hasWaypointNames = "no",
missions = mat_rags_missions
},
}
MatRags = ThemeParkLogic:new {
numberOfActs = 1,
npcMap = npcMapMatRags,
permissionMap = {},
className = "MatRags",
screenPlayState = "mat_rags_quest",
distance = 1000,
missionDescriptionStf = "",
missionCompletionMessageStf = "@theme_park/messages:static_completion_message"
}
registerScreenPlay("MatRags", true)
mat_rags_mission_giver_conv_handler = mission_giver_conv_handler:new {
themePark = MatRags
}
mat_rags_mission_target_conv_handler = mission_target_conv_handler:new {
themePark = MatRags
}
|
[Fixed] Mat Rags missing rewards. Mantis #3934
|
[Fixed] Mat Rags missing rewards. Mantis #3934
Change-Id: I39b9652732887a3ebf6df0cd1ddd5dd9ffc26cfa
|
Lua
|
agpl-3.0
|
lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo
|
ad22942108da4f0fd98cf1e24ec80f5e8c7cc7e4
|
frontend/luadefaults.lua
|
frontend/luadefaults.lua
|
--[[--
Subclass of LuaSettings dedicated to handling the legacy global constants.
]]
local DataStorage = require("datastorage")
local LuaSettings = require("luasettings")
local dump = require("dump")
local ffiutil = require("ffi/util")
local util = require("util")
local isAndroid, android = pcall(require, "android")
local lfs = require("libs/libkoreader-lfs")
local logger = require("logger")
local LuaDefaults = LuaSettings:extend{
ro = nil, -- will contain the defaults.lua k/v pairs (const)
rw = nil, -- will only contain non-defaults user-modified k/v pairs
}
--- Opens a settings file.
function LuaDefaults:open(path)
local file_path = path or DataStorage:getDataDir() .. "/defaults.custom.lua"
local new = LuaDefaults:extend{
file = file_path,
}
local ok, stored
-- File being absent and returning an empty table is a use case,
-- so logger.warn() only if there was an existing file
local existing = lfs.attributes(new.file, "mode") == "file"
ok, stored = pcall(dofile, new.file)
if ok and stored then
new.rw = stored
else
if existing then logger.warn("Failed reading", new.file, "(probably corrupted).") end
-- Fallback to .old if it exists
ok, stored = pcall(dofile, new.file..".old")
if ok and stored then
if existing then logger.warn("read from backup file", new.file..".old") end
new.rw = stored
else
if existing then logger.warn("no usable backup file for", new.file, "to read from") end
new.rw = {}
end
end
-- The actual defaults file, on the other hand, is set in stone.
-- We just have to deal with some platform shenanigans...
local defaults_path = DataStorage:getDataDir() .. "/defaults.lua"
if isAndroid then
defaults_path = android.dir .. "/defaults.lua"
elseif os.getenv("APPIMAGE") then
defaults_path = "defaults.lua"
end
ok, stored = pcall(dofile, defaults_path)
if ok and stored then
new.ro = stored
else
error("Failed reading " .. defaults_path)
end
return new
end
--- Reads a setting, optionally initializing it to a default.
function LuaDefaults:readSetting(key, default)
if not default then
if self:hasBeenCustomized(key) then
return self.rw[key]
else
return self.ro[key]
end
end
if not self:hasBeenCustomized(key) then
self.rw[key] = default
return self.rw[key]
end
if self:hasBeenCustomized(key) then
return self.rw[key]
else
return self.ro[key]
end
end
--- Saves a setting.
function LuaDefaults:saveSetting(key, value)
if util.tableEquals(self.ro[key], value, true) then
-- Only keep actually custom settings in the rw table ;).
return self:delSetting(key)
else
self.rw[key] = value
end
return self
end
--- Deletes a setting.
function LuaDefaults:delSetting(key)
self.rw[key] = nil
return self
end
--- Checks if setting exists.
function LuaDefaults:has(key)
return self.ro[key] ~= nil
end
--- Checks if setting does not exist.
function LuaDefaults:hasNot(key)
return self.ro[key] == nil
end
--- Checks if setting has been customized.
function LuaDefaults:hasBeenCustomized(key)
return self.rw[key] ~= nil
end
--- Checks if setting has NOT been customized.
function LuaDefaults:hasNotBeenCustomized(key)
return self.rw[key] == nil
end
--- Checks if setting is `true` (boolean).
function LuaDefaults:isTrue(key)
if self:hasBeenCustomized(key) then
return self.rw[key] == true
else
return self.ro[key] == true
end
end
--- Checks if setting is `false` (boolean).
function LuaDefaults:isFalse(key)
if self:hasBeenCustomized(key) then
return self.rw[key] == false
else
return self.ro[key] == false
end
end
--- Low-level API for filemanagersetdefaults
function LuaDefaults:getDataTables()
return self.ro, self.rw
end
function LuaDefaults:readDefaultSetting(key)
return self.ro[key]
end
-- NOP unsupported LuaSettings APIs
function LuaDefaults:wrap() end
function LuaDefaults:child() end
function LuaDefaults:initializeExtSettings() end
function LuaDefaults:getSettingForExt() end
function LuaDefaults:saveSettingForExt() end
function LuaDefaults:addTableItem() end
function LuaDefaults:removeTableItem() end
function LuaDefaults:reset() end
--- Writes settings to disk.
function LuaDefaults:flush()
if not self.file then return end
local directory_updated = false
if lfs.attributes(self.file, "mode") == "file" then
-- As an additional safety measure (to the ffiutil.fsync* calls used below),
-- we only backup the file to .old when it has not been modified in the last 60 seconds.
-- This should ensure in the case the fsync calls are not supported
-- that the OS may have itself sync'ed that file content in the meantime.
local mtime = lfs.attributes(self.file, "modification")
if mtime < os.time() - 60 then
os.rename(self.file, self.file .. ".old")
directory_updated = true -- fsync directory content too below
end
end
local f_out = io.open(self.file, "w")
if f_out ~= nil then
f_out:write("-- we can read Lua syntax here!\nreturn ")
f_out:write(dump(self.rw, nil, true))
f_out:write("\n")
ffiutil.fsyncOpenedFile(f_out) -- force flush to the storage device
f_out:close()
end
if directory_updated then
-- Ensure the file renaming is flushed to storage device
ffiutil.fsyncDirectory(self.file)
end
return self
end
return LuaDefaults
|
--[[--
Subclass of LuaSettings dedicated to handling the legacy global constants.
]]
local DataStorage = require("datastorage")
local LuaSettings = require("luasettings")
local dump = require("dump")
local ffiutil = require("ffi/util")
local util = require("util")
local isAndroid, android = pcall(require, "android")
local lfs = require("libs/libkoreader-lfs")
local logger = require("logger")
local LuaDefaults = LuaSettings:extend{
ro = nil, -- will contain the defaults.lua k/v pairs (const)
rw = nil, -- will only contain non-defaults user-modified k/v pairs
}
--- Opens a settings file.
function LuaDefaults:open(path)
local file_path = path or DataStorage:getDataDir() .. "/defaults.custom.lua"
local new = LuaDefaults:extend{
file = file_path,
}
local ok, stored
-- File being absent and returning an empty table is a use case,
-- so logger.warn() only if there was an existing file
local existing = lfs.attributes(new.file, "mode") == "file"
ok, stored = pcall(dofile, new.file)
if ok and stored then
new.rw = stored
else
if existing then logger.warn("Failed reading", new.file, "(probably corrupted).") end
-- Fallback to .old if it exists
ok, stored = pcall(dofile, new.file..".old")
if ok and stored then
if existing then logger.warn("read from backup file", new.file..".old") end
new.rw = stored
else
if existing then logger.warn("no usable backup file for", new.file, "to read from") end
new.rw = {}
end
end
-- The actual defaults file, on the other hand, is set in stone.
-- We just have to deal with some platform shenanigans...
-- NOTE: On most platforms, $PWD should be our "install" folder, so look there first,
-- as DataDir may point elsewhere, and that elsewhere may not exist yet ;).
local defaults_path = "defaults.lua"
if isAndroid then
defaults_path = android.dir .. "/defaults.lua"
elseif not util.fileExists(defaults_path) then
-- You probably have bigger problems than this if we didn't find it in the install folder, but, oh, well ;).
defaults_path = DataStorage:getDataDir() .. "/defaults.lua"
end
ok, stored = pcall(dofile, defaults_path)
if ok and stored then
new.ro = stored
else
error("Failed reading " .. defaults_path)
end
return new
end
--- Reads a setting, optionally initializing it to a default.
function LuaDefaults:readSetting(key, default)
if not default then
if self:hasBeenCustomized(key) then
return self.rw[key]
else
return self.ro[key]
end
end
if not self:hasBeenCustomized(key) then
self.rw[key] = default
return self.rw[key]
end
if self:hasBeenCustomized(key) then
return self.rw[key]
else
return self.ro[key]
end
end
--- Saves a setting.
function LuaDefaults:saveSetting(key, value)
if util.tableEquals(self.ro[key], value, true) then
-- Only keep actually custom settings in the rw table ;).
return self:delSetting(key)
else
self.rw[key] = value
end
return self
end
--- Deletes a setting.
function LuaDefaults:delSetting(key)
self.rw[key] = nil
return self
end
--- Checks if setting exists.
function LuaDefaults:has(key)
return self.ro[key] ~= nil
end
--- Checks if setting does not exist.
function LuaDefaults:hasNot(key)
return self.ro[key] == nil
end
--- Checks if setting has been customized.
function LuaDefaults:hasBeenCustomized(key)
return self.rw[key] ~= nil
end
--- Checks if setting has NOT been customized.
function LuaDefaults:hasNotBeenCustomized(key)
return self.rw[key] == nil
end
--- Checks if setting is `true` (boolean).
function LuaDefaults:isTrue(key)
if self:hasBeenCustomized(key) then
return self.rw[key] == true
else
return self.ro[key] == true
end
end
--- Checks if setting is `false` (boolean).
function LuaDefaults:isFalse(key)
if self:hasBeenCustomized(key) then
return self.rw[key] == false
else
return self.ro[key] == false
end
end
--- Low-level API for filemanagersetdefaults
function LuaDefaults:getDataTables()
return self.ro, self.rw
end
function LuaDefaults:readDefaultSetting(key)
return self.ro[key]
end
-- NOP unsupported LuaSettings APIs
function LuaDefaults:wrap() end
function LuaDefaults:child() end
function LuaDefaults:initializeExtSettings() end
function LuaDefaults:getSettingForExt() end
function LuaDefaults:saveSettingForExt() end
function LuaDefaults:addTableItem() end
function LuaDefaults:removeTableItem() end
function LuaDefaults:reset() end
--- Writes settings to disk.
function LuaDefaults:flush()
if not self.file then return end
local directory_updated = false
if lfs.attributes(self.file, "mode") == "file" then
-- As an additional safety measure (to the ffiutil.fsync* calls used below),
-- we only backup the file to .old when it has not been modified in the last 60 seconds.
-- This should ensure in the case the fsync calls are not supported
-- that the OS may have itself sync'ed that file content in the meantime.
local mtime = lfs.attributes(self.file, "modification")
if mtime < os.time() - 60 then
os.rename(self.file, self.file .. ".old")
directory_updated = true -- fsync directory content too below
end
end
local f_out = io.open(self.file, "w")
if f_out ~= nil then
f_out:write("-- we can read Lua syntax here!\nreturn ")
f_out:write(dump(self.rw, nil, true))
f_out:write("\n")
ffiutil.fsyncOpenedFile(f_out) -- force flush to the storage device
f_out:close()
end
if directory_updated then
-- Ensure the file renaming is flushed to storage device
ffiutil.fsyncDirectory(self.file)
end
return self
end
return LuaDefaults
|
LuaDefaults: Look for defaults.lua in $PWD first
|
LuaDefaults: Look for defaults.lua in $PWD first
As DataDir may not exist yet.
Fix #9593
|
Lua
|
agpl-3.0
|
NiLuJe/koreader,koreader/koreader,Frenzie/koreader,Frenzie/koreader,NiLuJe/koreader,koreader/koreader,poire-z/koreader,poire-z/koreader
|
1c45b06a119efec243c65fd4b99a329cd0debbcd
|
kong/cmd/config.lua
|
kong/cmd/config.lua
|
local DB = require "kong.db"
local log = require "kong.cmd.utils.log"
local pl_path = require "pl.path"
local pl_file = require "pl.file"
local kong_global = require "kong.global"
local declarative = require "kong.db.declarative"
local conf_loader = require "kong.conf_loader"
local kong_yml = require "kong.templates.kong_yml"
local INIT_FILE = "kong.yml"
local accepted_formats = {
yaml = true,
json = true,
lua = true,
}
local function generate_init()
if pl_file.access_time(INIT_FILE) then
error(INIT_FILE .. " already exists in the current directory.\n" ..
"Will not overwrite it.")
end
pl_file.write(INIT_FILE, kong_yml)
end
local function execute(args)
log.disable()
-- retrieve default prefix or use given one
local default_conf = assert(conf_loader(args.conf, {
prefix = args.prefix
}))
log.enable()
assert(pl_path.exists(default_conf.prefix),
"no such prefix: " .. default_conf.prefix)
assert(pl_path.exists(default_conf.kong_env),
"Kong is not running at " .. default_conf.prefix)
-- load <PREFIX>/kong.conf containing running node's config
local conf = assert(conf_loader(default_conf.kong_env))
if args.command == "init" then
generate_init()
os.exit(0)
end
if args.command == "db-import" then
args.command = "db_import"
end
if args.command == "db_import" and conf.database == "off" then
error("'kong config db_import' only works with a database.\n" ..
"When using database=off, reload your declarative configuration\n" ..
"using the /config endpoint.")
end
package.path = conf.lua_package_path .. ";" .. package.path
local dc, err = declarative.new_config(conf)
if not dc then
error(err)
end
if args.command == "db_import" or args.command == "parse" then
local filename = args[1]
if not filename then
error("expected a declarative configuration file; see `kong config --help`")
end
local dc_table, err_or_ver = dc:parse_file(filename, accepted_formats)
if not dc_table then
error("Failed parsing:\n" .. err_or_ver)
end
if args.command == "db_import" then
log("parse successful, beginning import")
_G.kong = kong_global.new()
kong_global.init_pdk(_G.kong, conf, nil) -- nil: latest PDK
local db = assert(DB.new(conf))
assert(db:init_connector())
assert(db:connect())
assert(db.plugins:load_plugin_schemas(conf.loaded_plugins))
_G.kong.db = db
local ok, err = declarative.load_into_db(dc_table)
if not ok then
error("Failed importing:\n" .. err)
end
log("import successful")
-- send anonymous report if reporting is not disabled
if conf.anonymous_reports then
local kong_reports = require "kong.reports"
kong_reports.configure_ping(conf)
kong_reports.toggle(true)
local report = { decl_fmt_version = err_or_ver }
kong_reports.send("config-db-import", report)
end
else -- parse
log("parse successful")
end
os.exit(0)
end
error("unknown command '" .. args.command .. "'")
end
local lapp = [[
Usage: kong config COMMAND [OPTIONS]
Use declarative configuration files with Kong.
The available commands are:
init Generate an example config file to
get you started.
db_import <file> Import a declarative config file into
the Kong database.
parse <file> Parse a declarative config file (check
its syntax) but do not load it into Kong.
Options:
-c,--conf (optional string) Configuration file.
-p,--prefix (optional string) Override prefix directory.
]]
return {
lapp = lapp,
execute = execute,
sub_commands = {
init = true,
db_import = true,
parse = true,
},
}
|
local DB = require "kong.db"
local log = require "kong.cmd.utils.log"
local pl_path = require "pl.path"
local pl_file = require "pl.file"
local kong_global = require "kong.global"
local declarative = require "kong.db.declarative"
local conf_loader = require "kong.conf_loader"
local kong_yml = require "kong.templates.kong_yml"
local INIT_FILE = "kong.yml"
local accepted_formats = {
yaml = true,
json = true,
lua = true,
}
local function generate_init()
if pl_file.access_time(INIT_FILE) then
error(INIT_FILE .. " already exists in the current directory.\n" ..
"Will not overwrite it.")
end
pl_file.write(INIT_FILE, kong_yml)
end
local function execute(args)
if args.command == "init" then
generate_init()
os.exit(0)
end
log.disable()
-- retrieve default prefix or use given one
local default_conf = assert(conf_loader(args.conf, {
prefix = args.prefix
}))
log.enable()
assert(pl_path.exists(default_conf.prefix),
"no such prefix: " .. default_conf.prefix)
assert(pl_path.exists(default_conf.kong_env),
"Kong is not running at " .. default_conf.prefix)
-- load <PREFIX>/kong.conf containing running node's config
local conf = assert(conf_loader(default_conf.kong_env))
if args.command == "db-import" then
args.command = "db_import"
end
if args.command == "db_import" and conf.database == "off" then
error("'kong config db_import' only works with a database.\n" ..
"When using database=off, reload your declarative configuration\n" ..
"using the /config endpoint.")
end
package.path = conf.lua_package_path .. ";" .. package.path
local dc, err = declarative.new_config(conf)
if not dc then
error(err)
end
if args.command == "db_import" or args.command == "parse" then
local filename = args[1]
if not filename then
error("expected a declarative configuration file; see `kong config --help`")
end
local dc_table, err_or_ver = dc:parse_file(filename, accepted_formats)
if not dc_table then
error("Failed parsing:\n" .. err_or_ver)
end
if args.command == "db_import" then
log("parse successful, beginning import")
_G.kong = kong_global.new()
kong_global.init_pdk(_G.kong, conf, nil) -- nil: latest PDK
local db = assert(DB.new(conf))
assert(db:init_connector())
assert(db:connect())
assert(db.plugins:load_plugin_schemas(conf.loaded_plugins))
_G.kong.db = db
local ok, err = declarative.load_into_db(dc_table)
if not ok then
error("Failed importing:\n" .. err)
end
log("import successful")
-- send anonymous report if reporting is not disabled
if conf.anonymous_reports then
local kong_reports = require "kong.reports"
kong_reports.configure_ping(conf)
kong_reports.toggle(true)
local report = { decl_fmt_version = err_or_ver }
kong_reports.send("config-db-import", report)
end
else -- parse
log("parse successful")
end
os.exit(0)
end
error("unknown command '" .. args.command .. "'")
end
local lapp = [[
Usage: kong config COMMAND [OPTIONS]
Use declarative configuration files with Kong.
The available commands are:
init Generate an example config file to
get you started.
db_import <file> Import a declarative config file into
the Kong database.
parse <file> Parse a declarative config file (check
its syntax) but do not load it into Kong.
Options:
-c,--conf (optional string) Configuration file.
-p,--prefix (optional string) Override prefix directory.
]]
return {
lapp = lapp,
execute = execute,
sub_commands = {
init = true,
db_import = true,
parse = true,
},
}
|
fix(cmd) allow 'kong config init' to work without a prefix
|
fix(cmd) allow 'kong config init' to work without a prefix
From #4451
Signed-off-by: Thibault Charbonnier <3c2e9133e272cb489e2fea0c4328cf56b08e4226@me.com>
|
Lua
|
apache-2.0
|
Kong/kong,Mashape/kong,Kong/kong,Kong/kong
|
7ee0331351f9a80ed761ba03f0a1acd23ee72724
|
spec/helper.lua
|
spec/helper.lua
|
local check_state = require "luacheck.check_state"
local core_utils = require "luacheck.core_utils"
local stages = require "luacheck.stages"
local helper = {}
local function get_lua()
local index = -1
local res = "lua"
while arg[index] do
res = arg[index]
index = index - 1
end
return res
end
local dir_sep = package.config:sub(1, 1)
-- Return path to root directory when run from `path`.
local function antipath(path)
local _, level = path:gsub("[/\\]", "")
return (".."..dir_sep):rep(level)
end
function helper.luacov_config(prefix)
return {
statsfile = prefix.."luacov.stats.out",
modules = {
luacheck = "src/luacheck/init.lua",
["luacheck.*"] = "src",
["luacheck.*.*"] = "src"
},
exclude = {
"bin/luacheck$"
}
}
end
local luacov = package.loaded["luacov.runner"]
local lua
-- Returns command that runs `luacheck` executable from `loc_path`.
function helper.luacheck_command(loc_path)
lua = lua or get_lua()
loc_path = loc_path or "."
local prefix = antipath(loc_path)
local cmd = ("cd %s && %s"):format(loc_path, lua)
-- Extend package.path to allow loading this helper and luacheck modules.
cmd = cmd..(' -e "package.path=[[%s?.lua;%ssrc%s?.lua;%ssrc%s?%sinit.lua;]]..package.path"'):format(
prefix, prefix, dir_sep, prefix, dir_sep, dir_sep)
if luacov then
-- Launch luacov.
cmd = cmd..(' -e "require[[luacov.runner]](require[[spec.helper]].luacov_config([[%s]]))"'):format(prefix)
end
return ("%s %sbin%sluacheck.lua"):format(cmd, prefix, dir_sep)
end
function helper.get_chstate_after_stage(target_stage_name, source)
local chstate = check_state.new(source)
for index, stage_name in ipairs(stages.names) do
stages.modules[index].run(chstate)
if stage_name == target_stage_name then
return chstate
end
chstate.warnings = {}
end
error("no stage " .. target_stage_name, 0)
end
function helper.get_stage_warnings(target_stage_name, source)
local chstate = helper.get_chstate_after_stage(target_stage_name, source)
core_utils.sort_by_location(chstate.warnings)
return chstate.warnings
end
return helper
|
local helper = {}
local function get_lua()
local index = -1
local res = "lua"
while arg[index] do
res = arg[index]
index = index - 1
end
return res
end
local dir_sep = package.config:sub(1, 1)
-- Return path to root directory when run from `path`.
local function antipath(path)
local _, level = path:gsub("[/\\]", "")
return (".."..dir_sep):rep(level)
end
function helper.luacov_config(prefix)
return {
statsfile = prefix.."luacov.stats.out",
modules = {
luacheck = "src/luacheck/init.lua",
["luacheck.*"] = "src",
["luacheck.*.*"] = "src"
},
exclude = {
"bin/luacheck$"
}
}
end
local luacov = package.loaded["luacov.runner"]
local lua
-- Returns command that runs `luacheck` executable from `loc_path`.
function helper.luacheck_command(loc_path)
lua = lua or get_lua()
loc_path = loc_path or "."
local prefix = antipath(loc_path)
local cmd = ("cd %s && %s"):format(loc_path, lua)
-- Extend package.path to allow loading this helper and luacheck modules.
cmd = cmd..(' -e "package.path=[[%s?.lua;%ssrc%s?.lua;%ssrc%s?%sinit.lua;]]..package.path"'):format(
prefix, prefix, dir_sep, prefix, dir_sep, dir_sep)
if luacov then
-- Launch luacov.
cmd = cmd..(' -e "require[[luacov.runner]](require[[spec.helper]].luacov_config([[%s]]))"'):format(prefix)
end
return ("%s %sbin%sluacheck.lua"):format(cmd, prefix, dir_sep)
end
function helper.get_chstate_after_stage(target_stage_name, source)
-- Luacov isn't yet started when helper is required, defer requiring luacheck
-- modules so that their main chunks get covered.
local check_state = require "luacheck.check_state"
local stages = require "luacheck.stages"
local chstate = check_state.new(source)
for index, stage_name in ipairs(stages.names) do
stages.modules[index].run(chstate)
if stage_name == target_stage_name then
return chstate
end
chstate.warnings = {}
end
error("no stage " .. target_stage_name, 0)
end
function helper.get_stage_warnings(target_stage_name, source)
local core_utils = require "luacheck.core_utils"
local chstate = helper.get_chstate_after_stage(target_stage_name, source)
core_utils.sort_by_location(chstate.warnings)
return chstate.warnings
end
return helper
|
Fix coverage missing for main chunks of most modules
|
Fix coverage missing for main chunks of most modules
Don't require luacheck modules in main chunk of spec helper,
at that moment luacov isn't running yet.
|
Lua
|
mit
|
xpol/luacheck,xpol/luacheck,mpeterv/luacheck,xpol/luacheck,mpeterv/luacheck,mpeterv/luacheck
|
09c37d81190cfb1ab8398faeb82e6f0b1af400b6
|
plugins/mod_dialback.lua
|
plugins/mod_dialback.lua
|
-- Prosody IM v0.1
-- Copyright (C) 2008 Matthew Wild
-- Copyright (C) 2008 Waqas Hussain
--
-- This program is free software; you can redistribute it and/or
-- modify it under the terms of the GNU General Public License
-- as published by the Free Software Foundation; either version 2
-- of the License, or (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program; if not, write to the Free Software
-- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
--
local format = string.format;
local send_s2s = require "core.s2smanager".send_to_host;
local s2s_make_authenticated = require "core.s2smanager".make_authenticated;
local s2s_verify_dialback = require "core.s2smanager".verify_dialback;
local st = require "util.stanza";
local log = require "util.logger".init("mod_dialback");
local xmlns_dialback = "jabber:server:dialback";
module:add_handler({"s2sin_unauthed", "s2sin"}, "verify", xmlns_dialback,
function (origin, stanza)
-- We are being asked to verify the key, to ensure it was generated by us
log("debug", "verifying dialback key...");
local attr = stanza.attr;
-- FIXME: Grr, ejabberd breaks this one too?? it is black and white in XEP-220 example 34
--if attr.from ~= origin.to_host then error("invalid-from"); end
local type;
if s2s_verify_dialback(attr.id, attr.from, attr.to, stanza[1]) then
type = "valid"
else
type = "invalid"
log("warn", "Asked to verify a dialback key that was incorrect. An imposter is claiming to be %s?", attr.to);
end
log("debug", "verified dialback key... it is %s", type);
origin.sends2s(format("<db:verify from='%s' to='%s' id='%s' type='%s'>%s</db:verify>", attr.to, attr.from, attr.id, type, stanza[1]));
end);
module:add_handler("s2sin_unauthed", "result", xmlns_dialback,
function (origin, stanza)
-- he wants to be identified through dialback
-- We need to check the key with the Authoritative server
local attr = stanza.attr;
local attr = stanza.attr;
origin.from_host = attr.from;
origin.to_host = attr.to;
origin.dialback_key = stanza[1];
log("debug", "asking %s if key %s belongs to them", origin.from_host, origin.dialback_key);
send_s2s(origin.to_host, origin.from_host,
st.stanza("db:verify", { from = origin.to_host, to = origin.from_host, id = origin.streamid }):text(origin.dialback_key));
hosts[origin.to_host].s2sout[origin.from_host].dialback_verifying = origin;
end);
module:add_handler({ "s2sout_unauthed", "s2sout" }, "verify", xmlns_dialback,
function (origin, stanza)
if origin.dialback_verifying then
local valid;
local attr = stanza.attr;
if attr.type == "valid" then
s2s_make_authenticated(origin.dialback_verifying);
valid = "valid";
else
-- Warn the original connection that is was not verified successfully
log("warn", "dialback for "..(origin.dialback_verifying.from_host or "(unknown)").." failed");
valid = "invalid";
end
if not origin.dialback_verifying.sends2s then
log("warn", "Incoming s2s session %s was closed in the meantime, so we can't notify it of the db result", tostring(origin.dialback_verifying):match("%w+$"));
else
origin.dialback_verifying.sends2s(format("<db:result from='%s' to='%s' id='%s' type='%s'>%s</db:result>",
attr.to, attr.from, attr.id, valid, origin.dialback_verifying.dialback_key));
end
end
end);
module:add_handler({ "s2sout_unauthed", "s2sout" }, "result", xmlns_dialback,
function (origin, stanza)
if stanza.attr.type == "valid" then
s2s_make_authenticated(origin);
else
-- FIXME
error("dialback failed!");
end
end);
|
-- Prosody IM v0.1
-- Copyright (C) 2008 Matthew Wild
-- Copyright (C) 2008 Waqas Hussain
--
-- This program is free software; you can redistribute it and/or
-- modify it under the terms of the GNU General Public License
-- as published by the Free Software Foundation; either version 2
-- of the License, or (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program; if not, write to the Free Software
-- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
--
local send_s2s = require "core.s2smanager".send_to_host;
local s2s_make_authenticated = require "core.s2smanager".make_authenticated;
local s2s_verify_dialback = require "core.s2smanager".verify_dialback;
local st = require "util.stanza";
local log = require "util.logger".init("mod_dialback");
local xmlns_dialback = "jabber:server:dialback";
module:add_handler({"s2sin_unauthed", "s2sin"}, "verify", xmlns_dialback,
function (origin, stanza)
-- We are being asked to verify the key, to ensure it was generated by us
log("debug", "verifying dialback key...");
local attr = stanza.attr;
-- FIXME: Grr, ejabberd breaks this one too?? it is black and white in XEP-220 example 34
--if attr.from ~= origin.to_host then error("invalid-from"); end
local type;
if s2s_verify_dialback(attr.id, attr.from, attr.to, stanza[1]) then
type = "valid"
else
type = "invalid"
log("warn", "Asked to verify a dialback key that was incorrect. An imposter is claiming to be %s?", attr.to);
end
log("debug", "verified dialback key... it is %s", type);
origin.sends2s(st.stanza("db:verify", { from = attr.to, to = attr.from, id = attr.id, type = type }):text(stanza[1]));
end);
module:add_handler("s2sin_unauthed", "result", xmlns_dialback,
function (origin, stanza)
-- he wants to be identified through dialback
-- We need to check the key with the Authoritative server
local attr = stanza.attr;
local attr = stanza.attr;
origin.from_host = attr.from;
origin.to_host = attr.to;
origin.dialback_key = stanza[1];
log("debug", "asking %s if key %s belongs to them", origin.from_host, origin.dialback_key);
send_s2s(origin.to_host, origin.from_host,
st.stanza("db:verify", { from = origin.to_host, to = origin.from_host, id = origin.streamid }):text(origin.dialback_key));
hosts[origin.to_host].s2sout[origin.from_host].dialback_verifying = origin;
end);
module:add_handler({ "s2sout_unauthed", "s2sout" }, "verify", xmlns_dialback,
function (origin, stanza)
if origin.dialback_verifying then
local valid;
local attr = stanza.attr;
if attr.type == "valid" then
s2s_make_authenticated(origin.dialback_verifying);
valid = "valid";
else
-- Warn the original connection that is was not verified successfully
log("warn", "dialback for "..(origin.dialback_verifying.from_host or "(unknown)").." failed");
valid = "invalid";
end
if not origin.dialback_verifying.sends2s then
log("warn", "Incoming s2s session %s was closed in the meantime, so we can't notify it of the db result", tostring(origin.dialback_verifying):match("%w+$"));
else
origin.dialback_verifying.sends2s(
st.stanza("db:result", { from = attr.to, to = attr.from, id = attr.id, type = valid })
:text(origin.dialback_verifying.dialback_key));
end
end
end);
module:add_handler({ "s2sout_unauthed", "s2sout" }, "result", xmlns_dialback,
function (origin, stanza)
if stanza.attr.type == "valid" then
s2s_make_authenticated(origin);
else
-- FIXME
error("dialback failed!");
end
end);
|
Fix the last couple of places where we send strings from mod_dialback
|
Fix the last couple of places where we send strings from mod_dialback
|
Lua
|
mit
|
sarumjanuch/prosody,sarumjanuch/prosody
|
e7c6846b4f6e175cd94f60f1a74f8dbba4b7de1f
|
plugins/mod_saslauth.lua
|
plugins/mod_saslauth.lua
|
local st = require "util.stanza";
local send = require "core.sessionmanager".send_to_session;
local sm_bind_resource = require "core.sessionmanager".bind_resource;
local jid
local base64 = require "base64"
local usermanager_validate_credentials = require "core.usermanager".validate_credentials;
local t_concat, t_insert = table.concat, table.insert;
local tostring = tostring;
local jid_split = require "util.jid".split
local log = require "util.logger".init("mod_saslauth");
local xmlns_sasl ='urn:ietf:params:xml:ns:xmpp-sasl';
local xmlns_bind ='urn:ietf:params:xml:ns:xmpp-bind';
local xmlns_stanzas ='urn:ietf:params:xml:ns:xmpp-stanzas';
local new_sasl = require "util.sasl".new;
local function build_reply(status, ret, err_msg)
local reply = st.stanza(status, {xmlns = xmlns_sasl});
if status == "challenge" then
reply:text(base64.encode(ret or ""));
elseif status == "failure" then
reply:tag(ret):up();
if err_msg then reply:tag("text"):text(err_msg); end
elseif status == "success" then
reply:text(base64.encode(ret or ""));
else
error("Unknown sasl status: "..status);
end
return reply;
end
local function handle_status(session, status)
if status == "failure" then
session.sasl_handler = nil;
elseif status == "success" then
if not session.sasl_handler.username then error("SASL succeeded but we didn't get a username!"); end -- TODO move this to sessionmanager
sessionmanager.make_authenticated(session, session.sasl_handler.username);
session.sasl_handler = nil;
session:reset_stream();
end
end
local function password_callback(node, host, mechanism)
local password = (datamanager.load(node, host, "accounts") or {}).password; -- FIXME handle hashed passwords
local func = function(x) return x; end;
if password then
if mechanism == "PLAIN" then
return func, password;
elseif mechanism == "DIGEST-MD5" then
return func, require "md5".sum(node..":"..host..":"..password);
end
end
return func, nil;
end
function sasl_handler(session, stanza)
if stanza.name == "auth" then
-- FIXME ignoring duplicates because ejabberd does
session.sasl_handler = new_sasl(stanza.attr.mechanism, session.host, password_callback);
elseif not session.sasl_handler then
return; -- FIXME ignoring out of order stanzas because ejabberd does
end
local text = stanza[1];
if text then
text = base64.decode(text);
if not text then
session.sasl_handler = nil;
session.send(build_reply("failure", "incorrect-encoding"));
return;
end
end
local status, ret, err_msg = session.sasl_handler:feed(text);
handle_status(session, status);
local s = build_reply(status, ret, err_msg);
log("debug", "sasl reply: "..tostring(s));
session.send(s);
end
add_handler("c2s_unauthed", "auth", xmlns_sasl, sasl_handler);
add_handler("c2s_unauthed", "abort", xmlns_sasl, sasl_handler);
add_handler("c2s_unauthed", "response", xmlns_sasl, sasl_handler);
add_event_hook("stream-features",
function (session, features)
if not session.username then
t_insert(features, "<mechanisms xmlns='urn:ietf:params:xml:ns:xmpp-sasl'>");
-- TODO: Provide PLAIN only if TLS is active, this is a SHOULD from the introduction of RFC 4616. This behavior could be overridden via configuration but will issuing a warning or so.
t_insert(features, "<mechanism>PLAIN</mechanism>");
t_insert(features, "<mechanism>DIGEST-MD5</mechanism>");
t_insert(features, "</mechanisms>");
else
t_insert(features, "<bind xmlns='urn:ietf:params:xml:ns:xmpp-bind'><required/></bind>");
t_insert(features, "<session xmlns='urn:ietf:params:xml:ns:xmpp-session'/>");
end
--send [[<register xmlns="http://jabber.org/features/iq-register"/> ]]
end);
add_iq_handler("c2s", "urn:ietf:params:xml:ns:xmpp-bind",
function (session, stanza)
log("debug", "Client tried to bind to a resource");
local resource;
if stanza.attr.type == "set" then
local bind = stanza.tags[1];
if bind and bind.attr.xmlns == xmlns_bind then
resource = bind:child_with_name("resource");
if resource then
resource = resource[1];
end
end
end
local success, err_type, err, err_msg = sm_bind_resource(session, resource);
if not success then
session.send(st.error_reply(stanza, err_type, err, err_msg));
else
session.send(st.reply(stanza)
:tag("bind", { xmlns = xmlns_bind})
:tag("jid"):text(session.full_jid));
end
end);
add_iq_handler("c2s", "urn:ietf:params:xml:ns:xmpp-session",
function (session, stanza)
log("debug", "Client tried to bind to a resource");
send(session, st.reply(stanza));
end);
|
local st = require "util.stanza";
local sm_bind_resource = require "core.sessionmanager".bind_resource;
local jid
local base64 = require "base64"
local usermanager_validate_credentials = require "core.usermanager".validate_credentials;
local t_concat, t_insert = table.concat, table.insert;
local tostring = tostring;
local jid_split = require "util.jid".split
local log = require "util.logger".init("mod_saslauth");
local xmlns_sasl ='urn:ietf:params:xml:ns:xmpp-sasl';
local xmlns_bind ='urn:ietf:params:xml:ns:xmpp-bind';
local xmlns_stanzas ='urn:ietf:params:xml:ns:xmpp-stanzas';
local new_sasl = require "util.sasl".new;
local function build_reply(status, ret, err_msg)
local reply = st.stanza(status, {xmlns = xmlns_sasl});
if status == "challenge" then
reply:text(base64.encode(ret or ""));
elseif status == "failure" then
reply:tag(ret):up();
if err_msg then reply:tag("text"):text(err_msg); end
elseif status == "success" then
reply:text(base64.encode(ret or ""));
else
error("Unknown sasl status: "..status);
end
return reply;
end
local function handle_status(session, status)
if status == "failure" then
session.sasl_handler = nil;
elseif status == "success" then
if not session.sasl_handler.username then error("SASL succeeded but we didn't get a username!"); end -- TODO move this to sessionmanager
sessionmanager.make_authenticated(session, session.sasl_handler.username);
session.sasl_handler = nil;
session:reset_stream();
end
end
local function password_callback(node, host, mechanism)
local password = (datamanager.load(node, host, "accounts") or {}).password; -- FIXME handle hashed passwords
local func = function(x) return x; end;
if password then
if mechanism == "PLAIN" then
return func, password;
elseif mechanism == "DIGEST-MD5" then
return func, require "md5".sum(node..":"..host..":"..password);
end
end
return func, nil;
end
function sasl_handler(session, stanza)
if stanza.name == "auth" then
-- FIXME ignoring duplicates because ejabberd does
session.sasl_handler = new_sasl(stanza.attr.mechanism, session.host, password_callback);
elseif not session.sasl_handler then
return; -- FIXME ignoring out of order stanzas because ejabberd does
end
local text = stanza[1];
if text then
text = base64.decode(text);
if not text then
session.sasl_handler = nil;
session.send(build_reply("failure", "incorrect-encoding"));
return;
end
end
local status, ret, err_msg = session.sasl_handler:feed(text);
handle_status(session, status);
local s = build_reply(status, ret, err_msg);
log("debug", "sasl reply: "..tostring(s));
session.send(s);
end
add_handler("c2s_unauthed", "auth", xmlns_sasl, sasl_handler);
add_handler("c2s_unauthed", "abort", xmlns_sasl, sasl_handler);
add_handler("c2s_unauthed", "response", xmlns_sasl, sasl_handler);
add_event_hook("stream-features",
function (session, features)
if not session.username then
t_insert(features, "<mechanisms xmlns='urn:ietf:params:xml:ns:xmpp-sasl'>");
-- TODO: Provide PLAIN only if TLS is active, this is a SHOULD from the introduction of RFC 4616. This behavior could be overridden via configuration but will issuing a warning or so.
t_insert(features, "<mechanism>PLAIN</mechanism>");
t_insert(features, "<mechanism>DIGEST-MD5</mechanism>");
t_insert(features, "</mechanisms>");
else
t_insert(features, "<bind xmlns='urn:ietf:params:xml:ns:xmpp-bind'><required/></bind>");
t_insert(features, "<session xmlns='urn:ietf:params:xml:ns:xmpp-session'/>");
end
--send [[<register xmlns="http://jabber.org/features/iq-register"/> ]]
end);
add_iq_handler("c2s", "urn:ietf:params:xml:ns:xmpp-bind",
function (session, stanza)
log("debug", "Client tried to bind to a resource");
local resource;
if stanza.attr.type == "set" then
local bind = stanza.tags[1];
if bind and bind.attr.xmlns == xmlns_bind then
resource = bind:child_with_name("resource");
if resource then
resource = resource[1];
end
end
end
local success, err_type, err, err_msg = sm_bind_resource(session, resource);
if not success then
session.send(st.error_reply(stanza, err_type, err, err_msg));
else
session.send(st.reply(stanza)
:tag("bind", { xmlns = xmlns_bind})
:tag("jid"):text(session.full_jid));
end
end);
add_iq_handler("c2s", "urn:ietf:params:xml:ns:xmpp-session",
function (session, stanza)
log("debug", "Client tried to bind to a resource");
session.send(st.reply(stanza));
end);
|
Fixed mod_saslauth to use session.send for sending stanzas
|
Fixed mod_saslauth to use session.send for sending stanzas
|
Lua
|
mit
|
sarumjanuch/prosody,sarumjanuch/prosody
|
1a5c0d0ab2f6844e8e775b475225992170c1b0b7
|
applications/luci-ddns/luasrc/model/cbi/ddns/ddns.lua
|
applications/luci-ddns/luasrc/model/cbi/ddns/ddns.lua
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
local is_mini = (luci.dispatcher.context.path[1] == "mini")
m = Map("ddns", translate("Dynamic DNS"),
translate("Dynamic DNS allows that your router can be reached with " ..
"a fixed hostname while having a dynamically changing " ..
"IP address."))
s = m:section(TypedSection, "service", "")
s.addremove = true
s.anonymous = false
s:option(Flag, "enabled", translate("Enable"))
svc = s:option(ListValue, "service_name", translate("Service"))
svc.rmempty = true
local services = { }
local fd = io.open("/usr/lib/ddns/services", "r")
if fd then
local ln
repeat
ln = fd:read("*l")
local s = ln and ln:match('^%s*"([^"]+)"')
if s then services[#services+1] = s end
until not ln
fd:close()
end
local v
for _, v in luci.util.vspairs(services) do
svc:value(v)
end
svc:value("", "-- "..translate("custom").." --")
url = s:option(Value, "update_url", translate("Custom update-URL"))
url:depends("service_name", "")
url.rmempty = true
s:option(Value, "domain", translate("Hostname")).rmempty = true
s:option(Value, "username", translate("Username")).rmempty = true
pw = s:option(Value, "password", translate("Password"))
pw.rmempty = true
pw.password = true
if is_mini then
s.defaults.ip_source = "network"
s.defaults.ip_network = "wan"
else
require("luci.tools.webadmin")
src = s:option(ListValue, "ip_source",
translate("Source of IP address"))
src:value("network", translate("network"))
src:value("interface", translate("interface"))
src:value("web", translate("URL"))
iface = s:option(ListValue, "ip_network", translate("Network"))
iface:depends("ip_source", "network")
iface.rmempty = true
luci.tools.webadmin.cbi_add_networks(iface)
iface = s:option(ListValue, "ip_interface", translate("Interface"))
iface:depends("ip_source", "interface")
iface.rmempty = true
for k, v in pairs(luci.sys.net.devices()) do
iface:value(v)
end
web = s:option(Value, "ip_url", translate("URL"))
web:depends("ip_source", "web")
web.rmempty = true
end
s:option(Value, "check_interval",
translate("Check for changed IP every")).default = 10
unit = s:option(ListValue, "check_unit", translate("Check-time unit"))
unit.default = "minutes"
unit:value("minutes", translate("min"))
unit:value("hours", translate("h"))
s:option(Value, "force_interval", translate("Force update every")).default = 72
unit = s:option(ListValue, "force_unit", translate("Force-time unit"))
unit.default = "hours"
unit:value("minutes", translate("min"))
unit:value("hours", translate("h"))
return m
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
local is_mini = (luci.dispatcher.context.path[1] == "mini")
m = Map("ddns", translate("Dynamic DNS"),
translate("Dynamic DNS allows that your router can be reached with " ..
"a fixed hostname while having a dynamically changing " ..
"IP address."))
s = m:section(TypedSection, "service", "")
s.addremove = true
s.anonymous = false
s:option(Flag, "enabled", translate("Enable"))
svc = s:option(ListValue, "service_name", translate("Service"))
svc.rmempty = false
local services = { }
local fd = io.open("/usr/lib/ddns/services", "r")
if fd then
local ln
repeat
ln = fd:read("*l")
local s = ln and ln:match('^%s*"([^"]+)"')
if s then services[#services+1] = s end
until not ln
fd:close()
end
local v
for _, v in luci.util.vspairs(services) do
svc:value(v)
end
function svc.cfgvalue(...)
local v = Value.cfgvalue(...)
if not v or #v == 0 then
return "-"
else
return v
end
end
function svc.write(self, section, value)
if value == "-" then
m.uci:delete("ddns", section, self.option)
else
Value.write(self, section, value)
end
end
svc:value("-", "-- "..translate("custom").." --")
url = s:option(Value, "update_url", translate("Custom update-URL"))
url:depends("service_name", "-")
url.rmempty = true
s:option(Value, "domain", translate("Hostname")).rmempty = true
s:option(Value, "username", translate("Username")).rmempty = true
pw = s:option(Value, "password", translate("Password"))
pw.rmempty = true
pw.password = true
if is_mini then
s.defaults.ip_source = "network"
s.defaults.ip_network = "wan"
else
require("luci.tools.webadmin")
src = s:option(ListValue, "ip_source",
translate("Source of IP address"))
src:value("network", translate("network"))
src:value("interface", translate("interface"))
src:value("web", translate("URL"))
iface = s:option(ListValue, "ip_network", translate("Network"))
iface:depends("ip_source", "network")
iface.rmempty = true
luci.tools.webadmin.cbi_add_networks(iface)
iface = s:option(ListValue, "ip_interface", translate("Interface"))
iface:depends("ip_source", "interface")
iface.rmempty = true
for k, v in pairs(luci.sys.net.devices()) do
iface:value(v)
end
web = s:option(Value, "ip_url", translate("URL"))
web:depends("ip_source", "web")
web.rmempty = true
end
s:option(Value, "check_interval",
translate("Check for changed IP every")).default = 10
unit = s:option(ListValue, "check_unit", translate("Check-time unit"))
unit.default = "minutes"
unit:value("minutes", translate("min"))
unit:value("hours", translate("h"))
s:option(Value, "force_interval", translate("Force update every")).default = 72
unit = s:option(ListValue, "force_unit", translate("Force-time unit"))
unit.default = "hours"
unit:value("minutes", translate("min"))
unit:value("hours", translate("h"))
return m
|
applications/luci-ddns: fix selection of custom update_url
|
applications/luci-ddns: fix selection of custom update_url
|
Lua
|
apache-2.0
|
8devices/luci,deepak78/luci,8devices/luci,8devices/luci,deepak78/luci,deepak78/luci,deepak78/luci,8devices/luci,8devices/luci,deepak78/luci,deepak78/luci,deepak78/luci,8devices/luci,deepak78/luci
|
1b0219f8387bf70c829c69f0be57445e34cf75ce
|
apply.lua
|
apply.lua
|
include 'init.lua'
require 'nvrtc'
local ffi = require 'ffi'
local kernel_source = [[
extern "C" __global__
void kernel(float* a, int n)
{
int i = blockIdx.x * blockDim.x + threadIdx.x;
float &x = a[i];
if (i < n)
LAMBDA;
}
]]
local CUDA_NUM_THREADS = 1024
local ptx_cache = {}
local function get_blocks(N)
return math.floor((N + CUDA_NUM_THREADS - 1) / CUDA_NUM_THREADS);
end
function torch.CudaTensor:apply(lambda)
local kernel = kernel_source:gsub('LAMBDA', lambda)
local ptx = ptx_cache[lambda] or nvrtc.compileReturnPTX(kernel)
cutorch.launchPTX(ptx, {self, {'int', self:numel()}}, {CUDA_NUM_THREADS}, {get_blocks(self:numel())})
end
|
include 'init.lua'
require 'nvrtc'
local ffi = require 'ffi'
local kernel_source = [[
extern "C" __global__
void kernel(float* a, int n)
{
int i = blockIdx.x * blockDim.x + threadIdx.x;
float &x = a[i];
if (i < n)
LAMBDA;
}
]]
local CUDA_NUM_THREADS = 64
local ptx_cache = {}
local function get_blocks(N)
return math.floor((N + CUDA_NUM_THREADS - 1) / CUDA_NUM_THREADS);
end
function torch.CudaTensor:apply(lambda)
local kernel = kernel_source:gsub('LAMBDA', lambda)
local ptx
if not ptx_cache[lambda] then
ptx = nvrtc.compileReturnPTX(kernel)
ptx_cache[lambda] = ptx
else
ptx = ptx_cache[lambda]
end
cutorch.launchPTX(ptx, {self, {'int', self:numel()}}, {CUDA_NUM_THREADS}, {get_blocks(self:numel())})
end
|
fixed caching
|
fixed caching
|
Lua
|
bsd-2-clause
|
szagoruyko/cutorch-rtc
|
62b96a6a35fefbf90a5bf294bf9676c684531b59
|
spec/02-integration/05-proxy/04-dns_spec.lua
|
spec/02-integration/05-proxy/04-dns_spec.lua
|
local helpers = require "spec.helpers"
local TCP_PORT = 35000
-- @param port the port to listen on
-- @param duration the duration for which to listen and accept connections (seconds)
local function bad_tcp_server(port, duration, ...)
local threads = require "llthreads2.ex"
local thread = threads.new({
function(port, duration)
local socket = require "socket"
local expire = socket.gettime() + duration
local server = assert(socket.tcp())
local tries = 0
server:settimeout(0.1)
assert(server:setoption('reuseaddr', true))
assert(server:bind("*", port))
assert(server:listen())
while socket.gettime() < expire do
local client, err = server:accept()
socket.sleep(0.1)
if client then
client:close() -- we're behaving bad, do nothing, just close
tries = tries + 1
elseif err ~= "timeout" then
return nil, "error accepting tcp connection; " .. tostring(err)
end
end
server:close()
return tries
end
}, port, duration)
return thread:start(...)
end
describe("DNS", function()
describe("retries", function()
local retries = 3
local client
setup(function()
assert(helpers.dao.apis:insert {
name = "tests-retries",
hosts = { "retries.com" },
upstream_url = "http://127.0.0.1:" .. TCP_PORT,
retries = retries,
})
assert(helpers.start_kong())
client = helpers.proxy_client()
end)
teardown(function()
if client then client:close() end
helpers.stop_kong()
end)
it("validates the number of retries", function()
-- setup a bad server
local thread = bad_tcp_server(TCP_PORT, 1)
-- make a request to it
local r = client:send {
method = "GET",
path = "/",
headers = {
host = "retries.com"
}
}
assert.response(r).has.status(502)
-- Getting back the TCP server count of the tries
local ok, tries = thread:join()
assert.True(ok)
assert.equals(retries, tries-1 ) -- the -1 is because the initial one is not a retry.
end)
end)
describe("upstream resolve failure", function()
local client
setup(function()
assert(helpers.dao.apis:insert {
name = "tests-retries",
hosts = { "retries.com" },
upstream_url = "http://now.this.does.not/exist",
})
assert(helpers.start_kong())
client = helpers.proxy_client()
end)
teardown(function()
if client then client:close() end
helpers.stop_kong()
end)
it("fails with 503", function()
local r = client:send {
method = "GET",
path = "/",
headers = {
host = "retries.com"
}
}
assert.response(r).has.status(503)
end)
end)
end)
|
local helpers = require "spec.helpers"
local TCP_PORT = 16945
local pack = function(...) return { n = select("#", ...), ... } end
local unpack = function(t) return unpack(t, 1, t.n) end
-- @param port the port to listen on
-- @param duration the duration for which to listen and accept connections (seconds)
local function bad_tcp_server(port, duration, ...)
local threads = require "llthreads2.ex"
local thread = threads.new({
function(port, duration)
local socket = require "socket"
local expire = socket.gettime() + duration
local server = assert(socket.tcp())
local tries = 0
server:settimeout(0.1)
assert(server:setoption('reuseaddr', true))
assert(server:bind("127.0.0.1", port))
assert(server:listen())
while socket.gettime() < expire do
local client, err = server:accept()
socket.sleep(0.1)
if client then
client:close() -- we're behaving bad, do nothing, just close
tries = tries + 1
elseif err ~= "timeout" then
return nil, "error accepting tcp connection; " .. tostring(err)
end
end
server:close()
return tries
end
}, port, duration)
local result = pack(thread:start(...))
ngx.sleep(0.2) -- wait for server to start
return unpack(result)
end
describe("DNS", function()
describe("retries", function()
local retries = 3
local client
setup(function()
assert(helpers.dao.apis:insert {
name = "tests-retries",
hosts = { "retries.com" },
upstream_url = "http://127.0.0.1:" .. TCP_PORT,
retries = retries,
})
assert(helpers.start_kong())
client = helpers.proxy_client()
end)
teardown(function()
if client then client:close() end
helpers.stop_kong()
end)
it("validates the number of retries", function()
-- setup a bad server
local thread = bad_tcp_server(TCP_PORT, 1)
-- make a request to it
local r = client:send {
method = "GET",
path = "/",
headers = {
host = "retries.com"
}
}
assert.response(r).has.status(502)
-- Getting back the TCP server count of the tries
local ok, tries = thread:join()
assert.True(ok)
assert.equals(retries, tries-1 ) -- the -1 is because the initial one is not a retry.
end)
end)
describe("upstream resolve failure", function()
local client
setup(function()
assert(helpers.dao.apis:insert {
name = "tests-retries",
hosts = { "retries.com" },
upstream_url = "http://now.this.does.not/exist",
})
assert(helpers.start_kong())
client = helpers.proxy_client()
end)
teardown(function()
if client then client:close() end
helpers.stop_kong()
end)
it("fails with 503", function()
local r = client:send {
method = "GET",
path = "/",
headers = {
host = "retries.com"
}
}
assert.response(r).has.status(503)
end)
end)
end)
|
test(dns) fixes dns retries test
|
test(dns) fixes dns retries test
|
Lua
|
apache-2.0
|
Kong/kong,akh00/kong,icyxp/kong,Mashape/kong,Kong/kong,salazar/kong,jebenexer/kong,Kong/kong,shiprabehera/kong
|
af273217510ccfba59b9e0469488dafbe21c31e1
|
mods/item_drop/init.lua
|
mods/item_drop/init.lua
|
item_drop = {}
local enable_damage = minetest.setting_getbool("enable_damage")
local creative_mode = minetest.setting_getbool("creative_mode")
-- Following edits by gravgun
item_drop.drop_callbacks = {}
item_drop.pickup_callbacks = {}
-- on_drop(dropper, drop_entity, itemstack)
function item_drop.add_drop_callback(on_drop)
table.insert(item_drop.drop_callbacks, on_drop)
end
-- on_pickup(picker, itemstack)
function item_drop.add_pickup_callback(on_pickup)
table.insert(item_drop.pickup_callbacks, on_pickup)
end
-- Idea is to have a radius pickup range around the player, whatever the height
-- We need to have a radius that will at least contain 1 node distance at the player's feet
-- Using simple trigonometry, we get that we need a radius of
-- sqrt(pickup_range² + player_half_height²)
local pickup_range = 1.3
local pickup_range_squared = pickup_range*pickup_range
local player_half_height = 0.9
local scan_range = math.sqrt(player_half_height*player_half_height + pickup_range_squared)
-- Node drops are insta-pickup, everything else (player drops) are not
local delay_before_playerdrop_pickup = 1
-- Time in which the node comes to the player
local pickup_duration = 0.1
-- Little treshold so the items aren't already on the player's middle
local pickup_inv_duration = 1/pickup_duration*0.7
local function tick()
minetest.after(0.1, tick)
local tstamp = minetest.get_us_time()
for _,player in ipairs(minetest.get_connected_players()) do
if player:get_hp() > 0 or not enable_damage then
local pos = player:getpos()
pos.y = pos.y + player_half_height
local inv = player:get_inventory()
if inv then
for _,object in ipairs(minetest.get_objects_inside_radius(pos, scan_range)) do
local luaEnt = object:get_luaentity()
if luaEnt and luaEnt.name == "__builtin:item" then
local ticky = luaEnt.item_drop_min_tstamp
if ticky then
if tstamp >= ticky then
luaEnt.item_drop_min_tstamp = nil
end
elseif not luaEnt.item_drop_nopickup then
-- Point-line distance computation, heavily simplified since the wanted line,
-- being the player, is completely upright (no variation on X or Z)
local pos2 = object:getpos()
-- No sqrt, avoid useless computation
-- (just take the radius, compare it to the square of what you want)
-- Pos order doesn't really matter, we're squaring the result
-- (but don't change it, we use the cached values afterwards)
local dX = pos.x-pos2.x
local dZ = pos.z-pos2.z
local playerDistance = dX*dX+dZ*dZ
if playerDistance <= pickup_range_squared then
local itemStack = ItemStack(luaEnt.itemstring)
if inv:room_for_item("main", itemStack) then
local vec = {x=dX, y=pos.y-pos2.y, z=dZ}
vec.x = vec.x*pickup_inv_duration
vec.y = vec.y*pickup_inv_duration
vec.z = vec.z*pickup_inv_duration
object:setvelocity(vec)
luaEnt.physical_state = false
luaEnt.object:set_properties({
physical = false
})
-- Mark the object as already picking up
luaEnt.item_drop_nopickup = true
minetest.after(pickup_duration, function()
local lua = luaEnt
if object == nil or lua == nil or lua.itemstring == nil then
return
end
if inv:room_for_item("main", itemStack) then
inv:add_item("main", itemStack)
if luaEnt.itemstring ~= "" then
minetest.sound_play("item_drop_pickup", {pos = pos, gain = 0.3, max_hear_distance = 8})
end
luaEnt.itemstring = ""
object:remove()
for i, cb in ipairs(item_drop.pickup_callbacks) do
cb(player, itemstack)
end
else
object:setvelocity({x = 0,y = 0,z = 0})
luaEnt.physical_state = true
luaEnt.object:set_properties({
physical = true
})
luaEnt.item_drop_nopickup = nil
end
end)
end
end
end
end
end
end
end
end
end
local mt_handle_node_drops = minetest.handle_node_drops
function minetest.handle_node_drops(pos, drops, digger)
if digger and digger.is_fake_player then -- Pipeworks' wielders
mt_handle_node_drops(pos, drops, digger)
return
end
local inv
if creative_mode and digger and digger:is_player() then
inv = digger:get_inventory()
end
for _,item in ipairs(drops) do
local count, name
if type(item) == "string" then
count = 1
name = item
else
count = item:get_count()
name = item:get_name()
end
if not inv or not inv:contains_item("main", ItemStack(name)) then
for i=1,count do
local obj
local x = math.random(1, 5)
if math.random(1,2) == 1 then x = -x end
local z = math.random(1, 5)
if math.random(1,2) == 1 then z = -z end
obj = minetest.spawn_item(pos, name)
if obj ~= nil then
obj:setvelocity({x=1/x, y=obj:getvelocity().y, z=1/z})
end
end
end
end
end
local mt_item_drop = minetest.item_drop
function minetest.item_drop(itemstack, dropper, pos)
if dropper.is_player then
local v = dropper:get_look_dir()
local p = {x=pos.x, y=pos.y+1.2, z=pos.z}
local cs = itemstack:get_count()
if dropper:get_player_control().sneak then
cs = 1
end
local item = itemstack:take_item(cs)
local obj = core.add_item(p, item)
if obj then
v.x = v.x*2
v.y = v.y*2 + 2
v.z = v.z*2
obj:setvelocity(v)
obj:get_luaentity().item_drop_min_tstamp = minetest.get_us_time() + delay_before_playerdrop_pickup * 1000000
for i, cb in ipairs(item_drop.drop_callbacks) do
cb(dropper, obj, itemstack)
end
end
else
core.add_item(pos, itemstack)
end
return itemstack
end
if minetest.setting_getbool("log_mods") then
minetest.log("action", "[item_drop] item_drop overriden: " .. tostring(mt_item_drop) .. " " .. tostring(minetest.item_drop))
minetest.log("action", "[item_drop] loaded.")
end
tick()
|
item_drop = {}
local enable_damage = minetest.setting_getbool("enable_damage")
local creative_mode = minetest.setting_getbool("creative_mode")
local TICK_UPDATE = 0.1
local die_timeout = 20
local die_time = {}
local die_respawned = {}
minetest.register_on_joinplayer(function(player)
local player_name = player:get_player_name()
die_time[player_name] = 0
die_respawned[player_name] = false
end)
minetest.register_on_leaveplayer(function(player)
local player_name = player:get_player_name()
minetest.after(3, function()
die_time[player_name] = nil
die_respawned[player_name] = nil
end)
end)
minetest.register_on_dieplayer(function(player)
local player_name = player:get_player_name()
if not player_name then return end
die_respawned[player_name] = false
die_time[player_name] = die_timeout
end)
minetest.register_on_respawnplayer(function(player)
local player_name = player:get_player_name()
if not player_name then return end
die_respawned[player_name] = true
end)
-- Following edits by gravgun
item_drop.drop_callbacks = {}
item_drop.pickup_callbacks = {}
-- on_drop(dropper, drop_entity, itemstack)
function item_drop.add_drop_callback(on_drop)
table.insert(item_drop.drop_callbacks, on_drop)
end
-- on_pickup(picker, itemstack)
function item_drop.add_pickup_callback(on_pickup)
table.insert(item_drop.pickup_callbacks, on_pickup)
end
-- Idea is to have a radius pickup range around the player, whatever the height
-- We need to have a radius that will at least contain 1 node distance at the player's feet
-- Using simple trigonometry, we get that we need a radius of
-- sqrt(pickup_range² + player_half_height²)
local pickup_range = 1.3
local pickup_range_squared = pickup_range*pickup_range
local player_half_height = 0.9
local scan_range = math.sqrt(player_half_height*player_half_height + pickup_range_squared)
-- Node drops are insta-pickup, everything else (player drops) are not
local delay_before_playerdrop_pickup = 1
-- Time in which the node comes to the player
local pickup_duration = 0.1
-- Little treshold so the items aren't already on the player's middle
local pickup_inv_duration = 1/pickup_duration*0.7
local function tick()
local tstamp = minetest.get_us_time()
for _,player in ipairs(minetest.get_connected_players()) do
local player_name = player:get_player_name()
if die_time[player_name] < 1 then
if player:get_hp() > 0 or not enable_damage then
local pos = player:getpos()
pos.y = pos.y + player_half_height
local inv = player:get_inventory()
if inv then
for _,object in ipairs(minetest.get_objects_inside_radius(pos, scan_range)) do
local luaEnt = object:get_luaentity()
if luaEnt and luaEnt.name == "__builtin:item" then
local ticky = luaEnt.item_drop_min_tstamp
if ticky then
if tstamp >= ticky then
luaEnt.item_drop_min_tstamp = nil
end
elseif not luaEnt.item_drop_nopickup then
-- Point-line distance computation, heavily simplified since the wanted line,
-- being the player, is completely upright (no variation on X or Z)
local pos2 = object:getpos()
-- No sqrt, avoid useless computation
-- (just take the radius, compare it to the square of what you want)
-- Pos order doesn't really matter, we're squaring the result
-- (but don't change it, we use the cached values afterwards)
local dX = pos.x-pos2.x
local dZ = pos.z-pos2.z
local playerDistance = dX*dX+dZ*dZ
if playerDistance <= pickup_range_squared then
local itemStack = ItemStack(luaEnt.itemstring)
if inv:room_for_item("main", itemStack) then
local vec = {x=dX, y=pos.y-pos2.y, z=dZ}
vec.x = vec.x*pickup_inv_duration
vec.y = vec.y*pickup_inv_duration
vec.z = vec.z*pickup_inv_duration
object:setvelocity(vec)
luaEnt.physical_state = false
luaEnt.object:set_properties({
physical = false
})
-- Mark the object as already picking up
luaEnt.item_drop_nopickup = true
minetest.after(pickup_duration, function()
local lua = luaEnt
if object == nil or lua == nil or lua.itemstring == nil then
return
end
if inv:room_for_item("main", itemStack) then
inv:add_item("main", itemStack)
if luaEnt.itemstring ~= "" then
minetest.sound_play("item_drop_pickup", {pos = pos, gain = 0.3, max_hear_distance = 8})
end
luaEnt.itemstring = ""
object:remove()
for i, cb in ipairs(item_drop.pickup_callbacks) do
cb(player, itemstack)
end
else
object:setvelocity({x = 0,y = 0,z = 0})
luaEnt.physical_state = true
luaEnt.object:set_properties({
physical = true
})
luaEnt.item_drop_nopickup = nil
end
end)
end
end
end
end
end
end
end
else
if die_respawned[player_name] then
die_time[player_name] = (die_time[player_name] or die_timeout) - TICK_UPDATE
end
end
end
minetest.after(TICK_UPDATE, tick)
end
local mt_handle_node_drops = minetest.handle_node_drops
function minetest.handle_node_drops(pos, drops, digger)
if digger and digger.is_fake_player then -- Pipeworks' wielders
mt_handle_node_drops(pos, drops, digger)
return
end
local inv
if creative_mode and digger and digger:is_player() then
inv = digger:get_inventory()
end
for _,item in ipairs(drops) do
local count, name
if type(item) == "string" then
count = 1
name = item
else
count = item:get_count()
name = item:get_name()
end
if not inv or not inv:contains_item("main", ItemStack(name)) then
for i=1,count do
local obj
local x = math.random(1, 5)
if math.random(1,2) == 1 then x = -x end
local z = math.random(1, 5)
if math.random(1,2) == 1 then z = -z end
obj = minetest.spawn_item(pos, name)
if obj ~= nil then
obj:setvelocity({x=1/x, y=obj:getvelocity().y, z=1/z})
end
end
end
end
end
local mt_item_drop = minetest.item_drop
function minetest.item_drop(itemstack, dropper, pos)
if dropper.is_player then
local v = dropper:get_look_dir()
local p = {x=pos.x, y=pos.y+1.2, z=pos.z}
local cs = itemstack:get_count()
if dropper:get_player_control().sneak then
cs = 1
end
local item = itemstack:take_item(cs)
local obj = core.add_item(p, item)
if obj then
v.x = v.x*2
v.y = v.y*2 + 2
v.z = v.z*2
obj:setvelocity(v)
obj:get_luaentity().item_drop_min_tstamp = minetest.get_us_time() + delay_before_playerdrop_pickup * 1000000
for i, cb in ipairs(item_drop.drop_callbacks) do
cb(dropper, obj, itemstack)
end
end
else
core.add_item(pos, itemstack)
end
return itemstack
end
if minetest.setting_getbool("log_mods") then
minetest.log("action", "[item_drop] item_drop overriden: " .. tostring(mt_item_drop) .. " " .. tostring(minetest.item_drop))
minetest.log("action", "[item_drop] loaded.")
end
tick()
|
fix 1 part of issue https://github.com/MinetestForFun/server-minetestforfun/issues/161 player can't take items when usebug respawn
|
fix 1 part of issue https://github.com/MinetestForFun/server-minetestforfun/issues/161
player can't take items when usebug respawn
|
Lua
|
unlicense
|
Gael-de-Sailly/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,MinetestForFun/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,Ombridride/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,crabman77/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,Coethium/server-minetestforfun,MinetestForFun/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,Coethium/server-minetestforfun,MinetestForFun/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,Coethium/server-minetestforfun,sys4-fr/server-minetestforfun,MinetestForFun/server-minetestforfun
|
dc565c15a799c484ce4b049bfbbfc6f15667574a
|
retry.lua
|
retry.lua
|
-- retry(0, jid, queue, worker, now, [delay])
-- ------------------------------------------
-- This script accepts jid, queue, worker and delay for
-- retrying a job. This is similar in functionality to
-- `put`, except that this counts against the retries
-- a job has for a stage.
--
-- If the worker is not the worker with a lock on the job,
-- then it returns false. If the job is not actually running,
-- then it returns false. Otherwise, it returns the number
-- of retries remaining. If the allowed retries have been
-- exhausted, then it is automatically failed, and a negative
-- number is returned.
if #KEYS ~= 0 then
error('Retry(): Got ' .. #KEYS .. ', expected 0')
end
local jid = assert(ARGV[1] , 'Retry(): Arg "jid" missing')
local queue = assert(ARGV[2] , 'Retry(): Arg "queue" missing')
local worker = assert(ARGV[3] , 'Retry(): Arg "worker" missing')
local now = assert(tonumber(ARGV[4]) , 'Retry(): Arg "now" missing')
local delay = assert(tonumber(ARGV[5] or 0), 'Retry(): Arg "delay" not a number: ' .. tostring(ARGV[5]))
-- Let's see what the old priority, history and tags were
local oldqueue, state, retries, oldworker, priority = unpack(redis.call('hmget', 'ql:j:' .. jid, 'queue', 'state', 'retries', 'worker', 'priority'))
-- If this isn't the worker that owns
if oldworker ~= worker or (state ~= 'running') then
return false
end
-- Remove it from the locks key of the old queue
redis.call('zrem', 'ql:q:' .. oldqueue .. '-locks', jid)
local remaining = redis.call('hincrby', 'ql:j:' .. jid, 'remaining', -1)
-- Remove this job from the worker that was previously working it
redis.call('zrem', 'ql:w:' .. worker .. ':jobs', jid)
if remaining < 0 then
-- Now remove the instance from the schedule, and work queues for the queue it's in
local group = 'failed-retries-' .. queue
-- First things first, we should get the history
local history = redis.call('hget', 'ql:j:' .. jid, 'history')
-- Now, take the element of the history for which our provided worker is the worker, and update 'failed'
history = cjson.decode(history or '[]')
history[#history]['failed'] = now
redis.call('hmset', 'ql:j:' .. jid, 'state', 'failed', 'worker', '',
'expires', '', 'history', cjson.encode(history), 'failure', cjson.encode({
['group'] = group,
['message'] = 'Job exhuasted retries in queue "' .. queue .. '"',
['when'] = now,
['worker'] = worker
}))
-- Add this type of failure to the list of failures
redis.call('sadd', 'ql:failures', group)
-- And add this particular instance to the failed types
redis.call('lpush', 'ql:f:' .. group, jid)
else
-- Put it in the queue again with a delay. Like put()
if delay > 0 then
redis.call('zadd', 'ql:q:' .. queue .. '-scheduled', now + delay, jid)
else
redis.call('zadd', 'ql:q:' .. queue .. '-work', priority + (now / 10000000000), jid)
end
end
return remaining
|
-- retry(0, jid, queue, worker, now, [delay])
-- ------------------------------------------
-- This script accepts jid, queue, worker and delay for
-- retrying a job. This is similar in functionality to
-- `put`, except that this counts against the retries
-- a job has for a stage.
--
-- If the worker is not the worker with a lock on the job,
-- then it returns false. If the job is not actually running,
-- then it returns false. Otherwise, it returns the number
-- of retries remaining. If the allowed retries have been
-- exhausted, then it is automatically failed, and a negative
-- number is returned.
if #KEYS ~= 0 then
error('Retry(): Got ' .. #KEYS .. ', expected 0')
end
local jid = assert(ARGV[1] , 'Retry(): Arg "jid" missing')
local queue = assert(ARGV[2] , 'Retry(): Arg "queue" missing')
local worker = assert(ARGV[3] , 'Retry(): Arg "worker" missing')
local now = assert(tonumber(ARGV[4]) , 'Retry(): Arg "now" missing')
local delay = assert(tonumber(ARGV[5] or 0), 'Retry(): Arg "delay" not a number: ' .. tostring(ARGV[5]))
-- Let's see what the old priority, history and tags were
local oldqueue, state, retries, oldworker, priority = unpack(redis.call('hmget', 'ql:j:' .. jid, 'queue', 'state', 'retries', 'worker', 'priority'))
-- If this isn't the worker that owns
if oldworker ~= worker or (state ~= 'running') then
return false
end
-- Remove it from the locks key of the old queue
redis.call('zrem', 'ql:q:' .. oldqueue .. '-locks', jid)
local remaining = redis.call('hincrby', 'ql:j:' .. jid, 'remaining', -1)
-- Remove this job from the worker that was previously working it
redis.call('zrem', 'ql:w:' .. worker .. ':jobs', jid)
if remaining < 0 then
-- Now remove the instance from the schedule, and work queues for the queue it's in
local group = 'failed-retries-' .. queue
-- First things first, we should get the history
local history = redis.call('hget', 'ql:j:' .. jid, 'history')
-- Now, take the element of the history for which our provided worker is the worker, and update 'failed'
history = cjson.decode(history or '[]')
history[#history]['failed'] = now
redis.call('hmset', 'ql:j:' .. jid, 'state', 'failed', 'worker', '',
'expires', '', 'history', cjson.encode(history), 'failure', cjson.encode({
['group'] = group,
['message'] = 'Job exhuasted retries in queue "' .. queue .. '"',
['when'] = now,
['worker'] = worker
}))
-- Add this type of failure to the list of failures
redis.call('sadd', 'ql:failures', group)
-- And add this particular instance to the failed types
redis.call('lpush', 'ql:f:' .. group, jid)
else
-- Put it in the queue again with a delay. Like put()
if delay > 0 then
redis.call('zadd', 'ql:q:' .. queue .. '-scheduled', now + delay, jid)
redis.call('hset', 'ql:j:' .. jid, 'state', 'scheduled')
else
redis.call('zadd', 'ql:q:' .. queue .. '-work', priority + (now / 10000000000), jid)
redis.call('hset', 'ql:j:' .. jid, 'state', 'waiting')
end
end
return remaining
|
Minor bug fix
|
Minor bug fix
When jobs are retried, their state was not getting proprerly represented in the
job hash.
|
Lua
|
mit
|
backupify/qless-core,seomoz/qless-core,seomoz/qless-core
|
e5be4eb9b765b7b3aea3e3d603059e5480e1c7bb
|
xmake/tools/gcc.lua
|
xmake/tools/gcc.lua
|
--!The Automatic Cross-platform Build Tool
--
-- XMake 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.
--
-- XMake 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 XMake;
-- If not, see <a href="http://www.gnu.org/licenses/"> http://www.gnu.org/licenses/</a>
--
-- Copyright (C) 2015 - 2016, ruki All rights reserved.
--
-- @author ruki
-- @file gcc.lua
--
-- init it
function init(shellname)
-- save the shell name
_g.shellname = shellname or "gcc"
-- init mxflags
_g.mxflags = { "-fmessage-length=0"
, "-pipe"
, "-fpascal-strings"
, "\"-DIBOutlet=__attribute__((iboutlet))\""
, "\"-DIBOutletCollection(ClassName)=__attribute__((iboutletcollection(ClassName)))\""
, "\"-DIBAction=void)__attribute__((ibaction)\""}
-- init shflags
_g.shflags = { "-shared", "-fPIC" }
-- init cxflags for the kind: shared
_g.shared = {}
_g.shared.cxflags = {"-fPIC"}
-- init flags map
_g.mapflags =
{
-- warnings
["-W1"] = "-Wall"
, ["-W2"] = "-Wall"
, ["-W3"] = "-Wall"
-- strip
, ["-s"] = "-s"
, ["-S"] = "-S"
}
end
-- get the property
function get(name)
-- get it
return _g[name]
end
-- make the define flag
function define(macro)
-- make it
return "-D" .. macro:gsub("\"", "\\\"")
end
-- make the undefine flag
function undefine(macro)
-- make it
return "-U" .. macro
end
-- make the includedir flag
function includedir(dir)
-- make it
return "-I" .. dir
end
-- make the link flag
function link(lib)
-- make it
return "-l" .. lib
end
-- make the linkdir flag
function linkdir(dir)
-- make it
return "-L" .. dir
end
-- make the complie command
function compcmd(srcfile, objfile, flags)
-- make it
return format("%s -c %s -o %s %s", _g.shellname, flags, objfile, srcfile)
end
-- make the link command
function linkcmd(objfiles, targetfile, flags)
-- make it
return format("%s -o %s %s %s", _g.shellname, targetfile, objfiles, flags)
end
-- run command
function run(...)
-- run it
os.run(...)
end
-- check the given flags
function check(flags)
-- check it
os.run("%s %s -S -o %s -xc %s", _g.shellname, ifelse(flags, flags, ""), os.nuldev(), os.nuldev())
end
|
--!The Automatic Cross-platform Build Tool
--
-- XMake 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.
--
-- XMake 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 XMake;
-- If not, see <a href="http://www.gnu.org/licenses/"> http://www.gnu.org/licenses/</a>
--
-- Copyright (C) 2015 - 2016, ruki All rights reserved.
--
-- @author ruki
-- @file gcc.lua
--
-- init it
function init(shellname)
-- save the shell name
_g.shellname = shellname or "gcc"
-- init mxflags
_g.mxflags = { "-fmessage-length=0"
, "-pipe"
, "-fpascal-strings"
, "\"-DIBOutlet=__attribute__((iboutlet))\""
, "\"-DIBOutletCollection(ClassName)=__attribute__((iboutletcollection(ClassName)))\""
, "\"-DIBAction=void)__attribute__((ibaction)\""}
-- init shflags
_g.shflags = { "-shared", "-fPIC" }
-- init cxflags for the kind: shared
_g.shared = {}
_g.shared.cxflags = {"-fPIC"}
-- init flags map
_g.mapflags =
{
-- warnings
["-W1"] = "-Wall"
, ["-W2"] = "-Wall"
, ["-W3"] = "-Wall"
-- strip
, ["-s"] = "-s"
, ["-S"] = "-S"
}
end
-- get the property
function get(name)
-- get it
return _g[name]
end
-- make the define flag
function define(macro)
-- make it
return "-D" .. macro:gsub("\"", "\\\"")
end
-- make the undefine flag
function undefine(macro)
-- make it
return "-U" .. macro
end
-- make the includedir flag
function includedir(dir)
-- make it
return "-I" .. dir
end
-- make the link flag
function link(lib)
-- make it
return "-l" .. lib
end
-- make the linkdir flag
function linkdir(dir)
-- make it
return "-L" .. dir
end
-- make the complie command
function compcmd(srcfile, objfile, flags)
-- make it
return format("%s -c %s -o %s %s", _g.shellname, flags, objfile, srcfile)
end
-- make the link command
function linkcmd(objfiles, targetfile, flags)
-- make it
return format("%s -o %s %s %s", _g.shellname, targetfile, objfiles, flags)
end
-- run command
function run(...)
-- run it
os.run(...)
end
-- check the given flags
function check(flags)
-- make an stub source file
local objfile = path.join(os.tmpdir(), "xmake.gcc.o")
local srcfile = path.join(os.tmpdir(), "xmake.gcc.c")
io.write(srcfile, "int main(int argc, char** argv)\n{return 0;}")
-- check it
os.run("%s -c %s -o %s %s", _g.shellname, ifelse(flags, flags, ""), objfile, srcfile)
-- remove files
os.rm(objfile)
os.rm(srcfile)
end
|
fix checker for the gcc flags: --coverage
|
fix checker for the gcc flags: --coverage
|
Lua
|
apache-2.0
|
waruqi/xmake,tboox/xmake,tboox/xmake,tboox/xmake,tboox/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,tboox/xmake,waruqi/xmake,waruqi/xmake,tboox/xmake,waruqi/xmake,tboox/xmake
|
b2a3c17a7b1b4ea7084f6b3775f233f562c6dad4
|
plugins/likecounter.lua
|
plugins/likecounter.lua
|
local function like(likedata, chat, user)
if not likedata[chat] then
likedata[chat] = { }
end
if not likedata[chat][user] then
likedata[chat][user] = 0
end
likedata[chat][user] = tonumber(likedata[chat][user] + 1)
save_data(_config.likecounter.db, likedata)
end
local function dislike(likedata, chat, user)
if not likedata[chat] then
likedata[chat] = { }
end
if not likedata[chat][user] then
likedata[chat][user] = 0
end
likedata[chat][user] = tonumber(likedata[chat][user] -1)
save_data(_config.likecounter.db, likedata)
end
local function like_by_username(extra, success, result)
if success == 0 then
return send_large_msg(extra.receiver, lang_text('noUsernameFound'))
end
like(extra.likedata, extra.chat, result.peer_id)
end
local function like_by_reply(extra, success, result)
like(extra.likedata, result.to.peer_id, result.from.peer_id)
end
local function like_from(extra, success, result)
like(extra.likedata, result.to.peer_id, result.fwd_from.peer_id)
end
local function dislike_by_username(extra, success, result)
if success == 0 then
return send_large_msg(extra.receiver, lang_text('noUsernameFound'))
end
dislike(extra.likedata, extra.chat, result.peer_id)
end
local function dislike_by_reply(extra, success, result)
dislike(extra.likedata, result.to.peer_id, result.from.peer_id)
end
local function dislike_from(extra, success, result)
dislike(extra.likedata, result.to.peer_id, result.fwd_from.peer_id)
end
local function likes_leaderboard(users, lbtype)
local users_info = { }
-- Get user name and param
for k, user in pairs(users) do
if user then
local user_info = get_name(k)
user_info.param = tonumber(user)
table.insert(users_info, user_info)
end
end
-- Sort users by param
table.sort(users_info, function(a, b)
if a.param and b.param then
return a.param > b.param
end
end )
local text = lang_text('likesLeaderboard')
local i = 0
for k, user in pairs(users_info) do
if user.name and user.param then
i = i + 1
text = text .. i .. '. ' .. user.name .. ' => ' .. user.param .. '\n'
end
end
return text
end
local function run(msg, matches)
if msg.to.type ~= 'user' then
if matches[1]:lower() == 'createlikesdb' then
if is_sudo(msg) then
local f = io.open(_config.likecounter.db, 'w+')
f:write('{}')
f:close()
reply_msg(msg.id, lang_text('likesdbCreated'), ok_cb, false)
else
return lang_text('require_sudo')
end
return
end
local chat = tostring(msg.to.id)
local user = tostring(msg.from.id)
local likedata = load_data(_config.likecounter.db)
if not likedata[chat] then
likedata[chat] = { }
save_data(_config.likecounter.db, likedata)
end
if matches[1]:lower() == 'addlikes' and matches[2] and matches[3] and is_sudo(msg) then
likedata[chat][matches[2]] = tonumber(likedata[chat][matches[2]] + matches[3])
save_data(_config.likecounter.db, likedata)
reply_msg(msg.id, lang_text('cheating'), ok_cb, false)
return
end
if matches[1]:lower() == 'remlikes' and matches[2] and matches[3] and is_sudo(msg) then
likedata[chat][matches[2]] = tonumber(likedata[chat][matches[2]] - matches[3])
save_data(_config.likecounter.db, likedata)
reply_msg(msg.id, lang_text('cheating'), ok_cb, false)
return
end
if (matches[1]:lower() == 'likes') then
send_large_msg(get_receiver(msg), likes_leaderboard(likedata[chat]))
return
end
if msg.fwd_from then
reply_msg(msg.id, lang_text('forwardingLike'), ok_cb, false)
else
if matches[1]:lower() == 'like' then
if type(msg.reply_id) ~= "nil" then
if matches[2] then
if matches[2]:lower() == 'from' then
get_message(msg.reply_id, like_from, { likedata = likedata })
return
else
get_message(msg.reply_id, like_by_reply, { likedata = likedata })
end
else
get_message(msg.reply_id, like_by_reply, { likedata = likedata })
end
elseif string.match(matches[2], '^%d+$') then
like(likedata, chat, user)
else
resolve_username(matches[2]:gsub('@', ''), like_by_username, { chat = chat, likedata = likedata })
end
elseif matches[1]:lower() == 'dislike' then
if type(msg.reply_id) ~= "nil" then
if matches[2] then
if matches[2]:lower() == 'from' then
get_message(msg.reply_id, dislike_from, { likedata = likedata })
return
else
get_message(msg.reply_id, dislike_by_reply, { likedata = likedata })
end
else
get_message(msg.reply_id, dislike_by_reply, { likedata = likedata })
end
elseif string.match(matches[2], '^%d+$') then
dislike(likedata, chat, user)
else
resolve_username(matches[2]:gsub('@', ''), dislike_by_username, { chat = chat, likedata = likedata })
end
end
end
end
end
return {
description = "LIKECOUNTER",
patterns =
{
"^[#!/]([Ll][Ii][Kk][Ee]) (.*)$",
"^[#!/]([Ll][Ii][Kk][Ee])$",
"^[#!/]([Dd][Ii][Ss][Ll][Ii][Kk][Ee]) (.*)$",
"^[#!/]([Dd][Ii][Ss][Ll][Ii][Kk][Ee])$",
"^[#!/]([Ll][Ii][Kk][Ee][Ss])$",
"^[#!/]([Aa][Dd][Dd][Ll][Ii][Kk][Ee][Ss]) (%d+) (%d+)$",
"^[#!/]([Rr][Ee][Mm][Ll][Ii][Kk][Ee][Ss]) (%d+) (%d+)$",
},
run = run,
min_rank = 0
-- usage
-- #like <id>|<username>|<reply>|from
-- #dislike <id>|<username>|<reply>|from
-- #likes
-- SUDO
-- #createlikesdb
-- #addlikes <id> <value>
-- #remlikes <id> <value>
}
|
local function like(likedata, chat, user)
if not likedata[chat] then
likedata[chat] = { }
end
if not likedata[chat][user] then
likedata[chat][user] = 0
end
likedata[chat][user] = tonumber(likedata[chat][user] + 1)
save_data(_config.likecounter.db, likedata)
end
local function dislike(likedata, chat, user)
if not likedata[chat] then
likedata[chat] = { }
end
if not likedata[chat][user] then
likedata[chat][user] = 0
end
likedata[chat][user] = tonumber(likedata[chat][user] -1)
save_data(_config.likecounter.db, likedata)
end
local function like_by_username(extra, success, result)
if success == 0 then
return send_large_msg(extra.receiver, lang_text('noUsernameFound'))
end
like(extra.likedata, extra.chat, result.peer_id)
end
local function like_by_reply(extra, success, result)
like(extra.likedata, result.to.peer_id, result.from.peer_id)
end
local function like_from(extra, success, result)
like(extra.likedata, result.to.peer_id, result.fwd_from.peer_id)
end
local function dislike_by_username(extra, success, result)
if success == 0 then
return send_large_msg(extra.receiver, lang_text('noUsernameFound'))
end
dislike(extra.likedata, extra.chat, result.peer_id)
end
local function dislike_by_reply(extra, success, result)
dislike(extra.likedata, result.to.peer_id, result.from.peer_id)
end
local function dislike_from(extra, success, result)
dislike(extra.likedata, result.to.peer_id, result.fwd_from.peer_id)
end
local function likes_leaderboard(users, lbtype)
local users_info = { }
-- Get user name and param
for k, user in pairs(users) do
if user then
local user_info = get_name(k)
user_info.param = tonumber(user)
table.insert(users_info, user_info)
end
end
-- Sort users by param
table.sort(users_info, function(a, b)
if a.param and b.param then
return a.param > b.param
end
end )
local text = lang_text('likesLeaderboard')
local i = 0
for k, user in pairs(users_info) do
if user.name and user.param then
i = i + 1
text = text .. i .. '. ' .. user.name .. ' => ' .. user.param .. '\n'
end
end
return text
end
local function run(msg, matches)
if msg.to.type ~= 'user' then
if matches[1]:lower() == 'createlikesdb' then
if is_sudo(msg) then
local f = io.open(_config.likecounter.db, 'w+')
f:write('{}')
f:close()
reply_msg(msg.id, lang_text('likesdbCreated'), ok_cb, false)
else
return lang_text('require_sudo')
end
return
end
local chat = tostring(msg.to.id)
local user = tostring(msg.from.id)
local likedata = load_data(_config.likecounter.db)
if not likedata[chat] then
likedata[chat] = { }
save_data(_config.likecounter.db, likedata)
end
if matches[1]:lower() == 'addlikes' and matches[2] and matches[3] and is_sudo(msg) then
likedata[chat][matches[2]] = tonumber(likedata[chat][matches[2]] + matches[3])
save_data(_config.likecounter.db, likedata)
reply_msg(msg.id, lang_text('cheating'), ok_cb, false)
return
end
if matches[1]:lower() == 'remlikes' and matches[2] and matches[3] and is_sudo(msg) then
likedata[chat][matches[2]] = tonumber(likedata[chat][matches[2]] - matches[3])
save_data(_config.likecounter.db, likedata)
reply_msg(msg.id, lang_text('cheating'), ok_cb, false)
return
end
if (matches[1]:lower() == 'likes') then
send_large_msg(get_receiver(msg), likes_leaderboard(likedata[chat]))
return
end
if msg.fwd_from then
reply_msg(msg.id, lang_text('forwardingLike'), ok_cb, false)
else
if matches[1]:lower() == 'like' then
if type(msg.reply_id) ~= "nil" then
if matches[2] then
if matches[2]:lower() == 'from' then
get_message(msg.reply_id, like_from, { likedata = likedata })
return
else
get_message(msg.reply_id, like_by_reply, { likedata = likedata })
end
else
get_message(msg.reply_id, like_by_reply, { likedata = likedata })
end
elseif string.match(matches[2], '^%d+$') then
like(likedata, chat, user)
else
resolve_username(matches[2]:gsub('@', ''), like_by_username, { chat = chat, likedata = likedata })
end
elseif matches[1]:lower() == 'dislike' then
if type(msg.reply_id) ~= "nil" then
if matches[2] then
if matches[2]:lower() == 'from' then
get_message(msg.reply_id, dislike_from, { likedata = likedata })
return
else
get_message(msg.reply_id, dislike_by_reply, { likedata = likedata })
end
else
get_message(msg.reply_id, dislike_by_reply, { likedata = likedata })
end
elseif string.match(matches[2], '^%d+$') then
dislike(likedata, chat, user)
else
resolve_username(matches[2]:gsub('@', ''), dislike_by_username, { chat = chat, likedata = likedata })
end
end
end
end
end
return {
description = "LIKECOUNTER",
patterns =
{
"^[#!/]([Cc][Rr][Ee][Aa][Tt][Ee][Ll][Ii][Kk][Ee][Ss][Dd][Bb])$",
"^[#!/]([Ll][Ii][Kk][Ee]) (.*)$",
"^[#!/]([Ll][Ii][Kk][Ee])$",
"^[#!/]([Dd][Ii][Ss][Ll][Ii][Kk][Ee]) (.*)$",
"^[#!/]([Dd][Ii][Ss][Ll][Ii][Kk][Ee])$",
"^[#!/]([Ll][Ii][Kk][Ee][Ss])$",
"^[#!/]([Aa][Dd][Dd][Ll][Ii][Kk][Ee][Ss]) (%d+) (%d+)$",
"^[#!/]([Rr][Ee][Mm][Ll][Ii][Kk][Ee][Ss]) (%d+) (%d+)$",
},
run = run,
min_rank = 0
-- usage
-- #like <id>|<username>|<reply>|from
-- #dislike <id>|<username>|<reply>|from
-- #likes
-- SUDO
-- #createlikesdb
-- #addlikes <id> <value>
-- #remlikes <id> <value>
}
|
fix pattern missing
|
fix pattern missing
|
Lua
|
agpl-3.0
|
xsolinsx/AISasha
|
b1dc36ca91d912f58ca60e3f17bcb329804a151d
|
mods/MAPGEN/sea/init.lua
|
mods/MAPGEN/sea/init.lua
|
--[[
Sea
--]]
--
-- Corals
--
minetest.register_node("sea:coral_brown", {
description = "Brown Coral",
tiles = {"sea_coral_brown.png"},
groups = {cracky = 3},
drop = "sea:coral_skeleton",
sounds = default.node_sound_stone_defaults(),
})
minetest.register_node("sea:coral_orange", {
description = "Orange Coral",
tiles = {"sea_coral_orange.png"},
groups = {cracky = 3},
drop = "sea:coral_skeleton",
sounds = default.node_sound_stone_defaults(),
})
minetest.register_node("sea:coral_skeleton", {
description = "Coral Skeleton",
tiles = {"sea_coral_skeleton.png"},
groups = {cracky = 3},
sounds = default.node_sound_stone_defaults(),
})
--
-- Coral death near air
--
minetest.register_abm({
nodenames = {"sea:coral_brown", "sea:coral_orange"},
neighbors = {"air"},
interval = 17,
chance = 5,
catch_up = false,
action = function(pos, node)
minetest.set_node(pos, {name = "sea:coral_skeleton"})
end,
})
-- Coral
minetest.register_decoration({
deco_type = "schematic",
place_on = {"default:sand"},
noise_params = {
offset = -0.004,
scale = 0.1,
spread = {x = 200, y = 200, z = 200},
seed = 7013,
octaves = 3,
persist = 0.7,
},
biomes = {"great_barrier_reef"},
y_min = -12,
y_max = -2,
schematic = minetest.get_modpath("sea") .. "/schematics/corals.mts",
flags = "place_center_x, place_center_z",
rotation = "random",
})
|
--[[
Sea
--]]
--
-- Corals
--
minetest.register_node("sea:coral_brown", {
description = "Brown Coral",
tiles = {"sea_coral_brown.png"},
groups = {cracky = 3},
drop = "sea:coral_skeleton",
sounds = default.node_sound_stone_defaults(),
})
minetest.register_node("sea:coral_orange", {
description = "Orange Coral",
tiles = {"sea_coral_orange.png"},
groups = {cracky = 3},
drop = "sea:coral_skeleton",
sounds = default.node_sound_stone_defaults(),
})
minetest.register_node("sea:coral_skeleton", {
description = "Coral Skeleton",
tiles = {"sea_coral_skeleton.png"},
groups = {cracky = 3},
sounds = default.node_sound_stone_defaults(),
})
minetest.register_alias("default:coral_brown", "sea:coral_brown")
minetest.register_alias("default:coral_orange", "sea:coral_orange")
minetest.register_alias("default:coral_skeleton", "sea:coral_skeleton")
--
-- Coral death near air
--
minetest.register_abm({
nodenames = {"sea:coral_brown", "sea:coral_orange"},
neighbors = {"air"},
interval = 17,
chance = 5,
catch_up = false,
action = function(pos, node)
minetest.set_node(pos, {name = "sea:coral_skeleton"})
end,
})
-- Coral
minetest.register_decoration({
deco_type = "schematic",
place_on = {"default:sand"},
noise_params = {
offset = -0.004,
scale = 0.1,
spread = {x = 200, y = 200, z = 200},
seed = 7013,
octaves = 3,
persist = 0.7,
},
biomes = {"great_barrier_reef"},
y_min = -12,
y_max = -2,
schematic = minetest.get_modpath("sea") .. "/schematics/corals.mts",
flags = "place_center_x, place_center_z",
rotation = "random",
})
|
Register coral aliases to fix schematic
|
Register coral aliases to fix schematic
|
Lua
|
lgpl-2.1
|
vlapsley/outback,vlapsley/outback
|
1f21813cdde305170c64e1672e87ab9713626118
|
src_trunk/resources/realism-system/c_weapons_back.lua
|
src_trunk/resources/realism-system/c_weapons_back.lua
|
weapons = { }
function weaponSwitch(prevSlot, newSlot)
local weapon = getPedWeapon(source, prevSlot)
local newWeapon = getPedWeapon(source, newSlot)
if (weapons[source] == nil) then
weapons[source] = { }
end
if (weapon == 30 or weapon == 31) and (isPedInVehicle(source)==false) then
if (weapons[source][1] == nil or weapons[source][2] ~= weapon or weapons[source][3] ~= isPedDucked(source)) then -- Model never created
weapons[source][1] = createModel(source, weapon)
weapons[source][2] = weapon
weapons[source][3] = isPedDucked(source)
else
local object = weapons[source][1]
destroyElement(object)
weapons[source] = nil
end
elseif weapons[source] and weapons[source][1] and ( newWeapon == 30 or newWeapon == 31 or getPedTotalAmmo(source, 5) == 0 ) then
local object = weapons[source][1]
destroyElement(object)
weapons[source] = nil
end
end
addEventHandler("onClientPlayerWeaponSwitch", getRootElement(), weaponSwitch)
function playerEntersVehicle(player)
if (weapons[player]) then
local object = weapons[player][1]
destroyElement(object)
end
end
addEventHandler("onClientVehicleEnter", getRootElement(), playerEntersVehicle)
function playerExitsVehicle(player)
if (weapons[player]) and getPedTotalAmmo(player, 5) > 0 then
local weapon = weapons[player][2]
weapons[player][1] = createModel(player, weapon)
weapons[player][3] = isPedDucked(player)
end
end
addEventHandler("onClientVehicleExit", getRootElement(), playerExitsVehicle)
function createModel(player, weapon)
local bx, by, bz = getPedBonePosition(player, 3)
local x, y, z = getElementPosition(player)
local r = getPedRotation(player)
crouched = isPedDucked(player)
local ox, oy, oz = bx-x-0.13, by-y-0.25, bz-z+0.25
if (crouched) then
oz = -0.025
end
local objectID = 355
if (weapon==31) then
objectID = 356
elseif (weapon==30) then
objectID = 355
end
local currobject = getElementData(source, "weaponback.object")
if (isElement(currobject)) then
destroyElement(currobject)
end
local object = createObject(objectID, x, y, z)
attachElements(object, player, ox, oy, oz, 0, 60, 0)
return object
end
|
weapons = { }
function weaponSwitch(prevSlot, newSlot)
local weapon = getPedWeapon(source, prevSlot)
local newWeapon = getPedWeapon(source, newSlot)
if (weapons[source] == nil) then
weapons[source] = { }
end
if (weapon == 30 or weapon == 31) and (isPedInVehicle(source)==false) then
if (weapons[source][1] == nil or weapons[source][2] ~= weapon or weapons[source][3] ~= isPedDucked(source)) then -- Model never created
weapons[source][1] = createModel(source, weapon)
weapons[source][2] = weapon
weapons[source][3] = isPedDucked(source)
else
local object = weapons[source][1]
destroyElement(object)
weapons[source] = nil
end
elseif weapons[source] and weapons[source][1] and ( newWeapon == 30 or newWeapon == 31 or getPedTotalAmmo(source, 5) == 0 ) then
local object = weapons[source][1]
destroyElement(object)
weapons[source] = nil
end
end
addEventHandler("onClientPlayerWeaponSwitch", getRootElement(), weaponSwitch)
function playerEntersVehicle(player)
if (weapons[player]) then
local object = weapons[player][1]
if (isElement(object)) then
destroyElement(object)
end
end
end
addEventHandler("onClientVehicleEnter", getRootElement(), playerEntersVehicle)
function playerExitsVehicle(player)
if (weapons[player]) and getPedTotalAmmo(player, 5) > 0 then
local weapon = weapons[player][2]
if (weapon) then
weapons[player][1] = createModel(player, weapon)
weapons[player][3] = isPedDucked(player)
end
end
end
addEventHandler("onClientVehicleExit", getRootElement(), playerExitsVehicle)
function createModel(player, weapon)
local bx, by, bz = getPedBonePosition(player, 3)
local x, y, z = getElementPosition(player)
local r = getPedRotation(player)
crouched = isPedDucked(player)
local ox, oy, oz = bx-x-0.13, by-y-0.25, bz-z+0.25
if (crouched) then
oz = -0.025
end
local objectID = 355
if (weapon==31) then
objectID = 356
elseif (weapon==30) then
objectID = 355
end
local currobject = getElementData(source, "weaponback.object")
if (isElement(currobject)) then
destroyElement(currobject)
end
local object = createObject(objectID, x, y, z)
attachElements(object, player, ox, oy, oz, 0, 60, 0)
return object
end
|
Fixed a bug where an AK would appear on your back despite not having one
|
Fixed a bug where an AK would appear on your back despite not having one
git-svn-id: 8769cb08482c9977c94b72b8e184ec7d2197f4f7@1972 64450a49-1f69-0410-a0a2-f5ebb52c4f5b
|
Lua
|
bsd-3-clause
|
valhallaGaming/uno,valhallaGaming/uno,valhallaGaming/uno
|
6dc5fcedfdf074dbc47c8f21a42cf54d93777284
|
Lua_examples/http.lua
|
Lua_examples/http.lua
|
-- see bottom of file for useage
require( "bromsock" );
-- url: http://4o3.nl
-- method: GET or POST
-- postdatatbl: nil, unles you have POST set as method, then a key/value table containing the data
-- callback: function(table headers, string body)
function HTTPRequest(url, method, postdatatbl, callback)
if (string.StartWith(url, "http://")) then
url = string.Right(url, #url - 7)
end
local host = ""
local path = ""
local postdata = ""
local bigbooty = ""
local headers = nil
local chunkedmode = false
local chunkedmodedata = false
local pathindex = string.IndexOf("/", url)
if (pathindex > -1) then
host = string.sub(url, 1, pathindex - 1)
path = string.sub(url, pathindex)
else
host = url
end
if (#path == 0) then path = "/" end
if (postdatatbl) then
for k, v in pairs(postdatatbl) do
postdata = postdata .. k .. "=" .. v .. "&"
end
if (#postdata > 0) then
postdata = string.Left(postdata, #postdata - 1)
end
end
local pClient = BromSock();
local pPacket = BromPacket();
local function sendline(szString)
pPacket:WriteLine(szString)
pClient:Send( pPacket, true );
end
pClient:SetCallbackConnect( function( _, bConnected, szIP, iPort )
if (not bConnected) then
callback(nil, nil)
return;
end
sendline(method .. " " .. path .. " HTTP/1.1");
sendline("Host: " .. host);
if (method:lower() == "post") then
sendline("Content-Type: application/x-www-form-urlencoded");
sendline("Content-Length: " .. #postdata);
end
sendline("");
if (method:lower() == "post") then
sendline(postdata)
end
pClient:ReceiveUntil( "\r\n\r\n" );
end );
pClient:SetCallbackReceive( function( _, incommingpacket )
local szMessage = incommingpacket:ReadStringAll():Trim()
incommingpacket = nil
if (not headers) then
local headers_tmp = string.Explode("\r\n", szMessage)
headers = {}
local statusrow = headers_tmp[1]
table.remove(headers_tmp, 1)
headers["status"] = statusrow:sub(10)
for k, v in ipairs(headers_tmp) do
local tmp = string.Explode(": ", v)
headers[tmp[1]:lower()] = tmp[2]
end
if (headers["content-length"]) then
pClient:Receive(tonumber(headers["content-length"]));
elseif (headers["transfer-encoding"] and headers["transfer-encoding"] == "chunked") then
chunkedmode = true
pClient:ReceiveUntil( "\r\n" );
else
-- This is why we can't have nice fucking things.
pClient:Receive(99999);
end
elseif (chunkedmode) then
if (chunkedmodedata) then
bigbooty = bigbooty .. szMessage
chunkedmodedata = false
pClient:ReceiveUntil( "\r\n" );
else
local len = tonumber(szMessage, 16)
if (len == 0) then
callback(headers, bigbooty)
pClient:Close()
pClient = nil
pPacket = nil
return
end
chunkedmodedata = true
pClient:Receive(len + 2) -- + 2 for \r\n, stilly chunked mode
end
else
callback(headers, szMessage)
pClient:Close()
pClient = nil
pPacket = nil
end
end)
pClient:Connect(host, 80);
end
-- Why is this not in the default string.lua?
function string.IndexOf(needle, haystack)
for i = 1, #haystack do
if (haystack[i] == needle) then
return i
end
end
return -1
end
-- headers is a table containing all the headers lowercase
-- body is the source of the webpage
HTTPRequest("http://4o3.nl", "GET", nil, function(headers, body)
if (not headers) then
print("request failed")
return
end
print("yay content")
end)
|
-- see bottom of file for useage
require( "bromsock" );
-- url: http://4o3.nl
-- method: GET or POST
-- postdatatbl: nil, unles you have POST set as method, then a key/value table containing the data
-- callback: function(table headers, string body)
function HTTPRequest(url, method, postdatatbl, callback)
if (string.StartWith(url, "http://")) then
url = string.Right(url, #url - 7)
end
local host = ""
local path = ""
local postdata = ""
local bigbooty = ""
local headers = nil
local chunkedmode = false
local chunkedmodedata = false
local pathindex = string.IndexOf("/", url)
if (pathindex > -1) then
host = string.sub(url, 1, pathindex - 1)
path = string.sub(url, pathindex)
else
host = url
end
if (#path == 0) then path = "/" end
if (postdatatbl) then
for k, v in pairs(postdatatbl) do
postdata = postdata .. k .. "=" .. v .. "&"
end
if (#postdata > 0) then
postdata = string.Left(postdata, #postdata - 1)
end
end
local pClient = BromSock();
local pPacket = BromPacket();
pClient:SetCallbackConnect( function( _, bConnected, szIP, iPort )
if (not bConnected) then
callback(nil, nil)
return;
end
pPacket:WriteLine(method .. " " .. path .. " HTTP/1.1");
pPacket:WriteLine("Host: " .. host);
if (method:lower() == "post") then
pPacket:WriteLine("Content-Type: application/x-www-form-urlencoded");
pPacket:WriteLine("Content-Length: " .. #postdata);
end
pPacket:WriteLine("");
if (method:lower() == "post") then
pPacket:WriteLine(postdata)
end
pClient:Send( pPacket, true );
pClient:ReceiveUntil( "\r\n\r\n" );
end );
pClient:SetCallbackReceive( function( _, incommingpacket )
local szMessage = incommingpacket:ReadStringAll():Trim()
incommingpacket = nil
if (not headers) then
local headers_tmp = string.Explode("\r\n", szMessage)
headers = {}
local statusrow = headers_tmp[1]
table.remove(headers_tmp, 1)
headers["status"] = statusrow:sub(10)
for k, v in ipairs(headers_tmp) do
local tmp = string.Explode(": ", v)
headers[tmp[1]:lower()] = tmp[2]
end
if (headers["content-length"]) then
pClient:Receive(tonumber(headers["content-length"]));
elseif (headers["transfer-encoding"] and headers["transfer-encoding"] == "chunked") then
chunkedmode = true
pClient:ReceiveUntil( "\r\n" );
else
-- This is why we can't have nice fucking things.
pClient:Receive(99999);
end
elseif (chunkedmode) then
if (chunkedmodedata) then
bigbooty = bigbooty .. szMessage
chunkedmodedata = false
pClient:ReceiveUntil( "\r\n" );
else
local len = tonumber(szMessage, 16)
if (len == 0) then
callback(headers, bigbooty)
pClient:Close()
pClient = nil
pPacket = nil
return
end
chunkedmodedata = true
pClient:Receive(len + 2) -- + 2 for \r\n, stilly chunked mode
end
else
callback(headers, szMessage)
pClient:Close()
pClient = nil
pPacket = nil
end
end)
pClient:Connect(host, 80);
end
-- Why is this not in the default string.lua?
function string.IndexOf(needle, haystack)
for i = 1, #haystack do
if (haystack[i] == needle) then
return i
end
end
return -1
end
-- headers is a table containing all the headers lowercase
-- body is the source of the webpage
HTTPRequest("http://4o3.nl", "GET", nil, function(headers, body)
if (not headers) then
print("request failed")
return
end
print(body)
end)
|
Fixed the http example regarding sending headers
|
Fixed the http example regarding sending headers
I was sending them in multiple packets, every header. So if you were
unlucky, it would send the end of the headers before an actual header.
Yay threading.
|
Lua
|
mit
|
Bromvlieg/gm_bromsock,Bromvlieg/gm_bromsock
|
d3200df717b7e1beaef70b4bd8b99f05ff350d6a
|
MMOCoreORB/bin/scripts/loot/items/foraged_stimpack.lua
|
MMOCoreORB/bin/scripts/loot/items/foraged_stimpack.lua
|
--Automatically generated by SWGEmu Spawn Tool v0.12 loot editor.
foraged_stimpack = {
minimumLevel = 0,
maximumLevel = -1,
customObjectName = "",
directObjectTemplate = "object/tangible/medicine/stimpack_sm_s1.iff",
craftingValues = {
{"power",75,95,0},
{"charges",1,10,0},
{"skillmodmin",5,5,0},
},
customizationStringNames = {},
customizationValues = {}
}
addLootItemTemplate("foraged_stimpack", foraged_stimpack)
|
--Automatically generated by SWGEmu Spawn Tool v0.12 loot editor.
foraged_stimpack = {
minimumLevel = 0,
maximumLevel = -1,
customObjectName = "",
directObjectTemplate = "object/tangible/medicine/stimpack_sm_s1.iff",
craftingValues = {
{"power",75,95,0},
{"charges",5,10,0},
{"skillmodmin",5,5,0},
{"hitpoints",1000,1000,0},
},
customizationStringNames = {},
customizationValues = {}
}
addLootItemTemplate("foraged_stimpack", foraged_stimpack)
|
(Unstable) [Fixed] Foraged Stimpack. Mantis issue 3182
|
(Unstable) [Fixed] Foraged Stimpack. Mantis issue 3182
git-svn-id: e4cf3396f21da4a5d638eecf7e3b4dd52b27f938@5802 c3d1530f-68f5-4bd0-87dc-8ef779617e40
|
Lua
|
agpl-3.0
|
lasko2112/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,lasko2112/legend-of-hondo,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
|
7b1a0202332b8cc7b4d85e9663779f610c345d70
|
plugins/mod_announce.lua
|
plugins/mod_announce.lua
|
-- Prosody IM
-- Copyright (C) 2008-2010 Matthew Wild
-- Copyright (C) 2008-2010 Waqas Hussain
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
local st, jid, set = require "util.stanza", require "util.jid", require "util.set";
local is_admin = require "core.usermanager".is_admin;
local admins = set.new(config.get(module:get_host(), "core", "admins"));
function handle_announcement(data)
local origin, stanza = data.origin, data.stanza;
local host, resource = select(2, jid.split(stanza.attr.to));
if resource ~= "announce/online" then
return; -- Not an announcement
end
if not is_admin(stanza.attr.from) then
-- Not an admin? Not allowed!
module:log("warn", "Non-admin %s tried to send server announcement", tostring(jid.bare(stanza.attr.from)));
origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
return;
end
module:log("info", "Sending server announcement to all online users");
local host_session = hosts[host];
local message = st.clone(stanza);
message.attr.type = "headline";
message.attr.from = host;
local c = 0;
for user in pairs(host_session.sessions) do
c = c + 1;
message.attr.to = user.."@"..host;
core_post_stanza(host_session, message);
end
module:log("info", "Announcement sent to %d online users", c);
return true;
end
module:hook("message/host", handle_announcement);
|
-- Prosody IM
-- Copyright (C) 2008-2010 Matthew Wild
-- Copyright (C) 2008-2010 Waqas Hussain
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
local st, jid, set = require "util.stanza", require "util.jid", require "util.set";
local is_admin = require "core.usermanager".is_admin;
local admins = set.new(config.get(module:get_host(), "core", "admins"));
function handle_announcement(data)
local origin, stanza = data.origin, data.stanza;
local host, resource = select(2, jid.split(stanza.attr.to));
if resource ~= "announce/online" then
return; -- Not an announcement
end
if not is_admin(stanza.attr.from) then
-- Not an admin? Not allowed!
module:log("warn", "Non-admin %s tried to send server announcement", tostring(jid.bare(stanza.attr.from)));
return;
end
module:log("info", "Sending server announcement to all online users");
local host_session = hosts[host];
local message = st.clone(stanza);
message.attr.type = "headline";
message.attr.from = host;
local c = 0;
for user in pairs(host_session.sessions) do
c = c + 1;
message.attr.to = user.."@"..host;
core_post_stanza(host_session, message);
end
module:log("info", "Announcement sent to %d online users", c);
return true;
end
module:hook("message/host", handle_announcement);
|
mod_announce: Fixed an edge case where non-admins attempting to announce would get two error replies.
|
mod_announce: Fixed an edge case where non-admins attempting to announce would get two error replies.
|
Lua
|
mit
|
sarumjanuch/prosody,sarumjanuch/prosody
|
08c939b5e580117ceb250ed21720220b75575b7f
|
xmake.lua
|
xmake.lua
|
set_xmakever("2.2.5")
-- project
set_project("hikyuu")
-- version
set_version("1.1.6", {build="%Y%m%d%H%M"})
set_configvar("LOG_ACTIVE_LEVEL", 0) -- 激活的日志级别
--if is_mode("debug") then
-- set_configvar("LOG_ACTIVE_LEVEL", 0) -- 激活的日志级别
--else
-- set_configvar("LOG_ACTIVE_LEVEL", 2) -- 激活的日志级别
--end
set_configvar("USE_SPDLOG_LOGGER", 1) -- 是否使用spdlog作为日志输出
set_configvar("USE_SPDLOG_ASYNC_LOGGER", 0) -- 使用异步的spdlog
set_configvar("CHECK_ACCESS_BOUND", 1)
if is_plat("macosx") then
set_configvar("SUPPORT_SERIALIZATION", 0)
else
set_configvar("SUPPORT_SERIALIZATION", is_mode("release") and 1 or 0)
end
set_configvar("SUPPORT_TEXT_ARCHIVE", 0)
set_configvar("SUPPORT_XML_ARCHIVE", 1)
set_configvar("SUPPORT_BINARY_ARCHIVE", 1)
set_configvar("HKU_DISABLE_ASSERT", 0)
-- set warning all as error
if is_plat("windows") then
set_warnings("all", "error")
else
set_warnings("all")
end
-- set language: C99, c++ standard
set_languages("cxx17", "C99")
add_plugindirs("./xmake_plugins")
add_requires("fmt", {system=false, configs = {header_only = true, vs_runtime = "MD"}})
add_requires("spdlog", {configs = {header_only = true, fmt_external=true, vs_runtime = "MD"}})
add_requires("flatbuffers", {configs = {vs_runtime="MD"}})
add_requires("nng", {configs = {vs_runtime="MD"}})
add_defines("SPDLOG_DISABLE_DEFAULT_LOGGER") -- 禁用 spdlog 默认 logger
set_objectdir("$(buildir)/$(mode)/$(plat)/$(arch)/.objs")
set_targetdir("$(buildir)/$(mode)/$(plat)/$(arch)/lib")
add_includedirs("$(env BOOST_ROOT)")
add_linkdirs("$(env BOOST_LIB)")
-- modifed to use boost static library, except boost.python, serialization
--add_defines("BOOST_ALL_DYN_LINK")
add_defines("BOOST_SERIALIZATION_DYN_LINK")
if is_host("linux") then
if is_arch("x86_64") then
add_linkdirs("/usr/lib64")
add_linkdirs("/usr/lib/x86_64-linux-gnu")
end
end
if is_mode("debug") then
set_symbols("debug")
set_optimize("none")
end
-- is release now
if is_mode("release") then
if is_plat("windows") then
--Unix-like systems hidden symbols will cause the link dynamic libraries to failed!
set_symbols("hidden")
end
set_optimize("fastest")
set_strip("all")
end
-- for the windows platform (msvc)
if is_plat("windows") then
add_packagedirs("./hikyuu_extern_libs/pkg")
-- add some defines only for windows
add_defines("NOCRYPT", "NOGDI")
add_cxflags("-EHsc", "/Zc:__cplusplus", "/utf-8")
add_cxflags("-wd4819") --template dll export warning
add_defines("WIN32_LEAN_AND_MEAN")
if is_mode("release") then
add_cxflags("-MD")
elseif is_mode("debug") then
add_cxflags("-Gs", "-RTC1", "/bigobj")
add_cxflags("-MDd")
end
end
if not is_plat("windows") then
-- disable some compiler errors
add_cxflags("-Wno-error=deprecated-declarations", "-fno-strict-aliasing")
add_cxflags("-ftemplate-depth=1023", "-pthread")
add_shflags("-pthread")
add_ldflags("-pthread")
end
add_vectorexts("sse", "sse2", "sse3", "ssse3", "mmx", "avx")
if is_plat("windows") then
add_subdirs("./hikyuu_extern_libs/src/sqlite3")
end
add_subdirs("./hikyuu_cpp/hikyuu")
add_subdirs("./hikyuu_pywrap")
add_subdirs("./hikyuu_cpp/unit_test")
add_subdirs("./hikyuu_cpp/demo")
before_install("scripts.before_install")
on_install("scripts.on_install")
before_run("scripts.before_run")
|
set_xmakever("2.2.5")
-- project
set_project("hikyuu")
-- version
set_version("1.1.6", {build="%Y%m%d%H%M"})
set_configvar("LOG_ACTIVE_LEVEL", 0) -- 激活的日志级别
--if is_mode("debug") then
-- set_configvar("LOG_ACTIVE_LEVEL", 0) -- 激活的日志级别
--else
-- set_configvar("LOG_ACTIVE_LEVEL", 2) -- 激活的日志级别
--end
set_configvar("USE_SPDLOG_LOGGER", 1) -- 是否使用spdlog作为日志输出
set_configvar("USE_SPDLOG_ASYNC_LOGGER", 0) -- 使用异步的spdlog
set_configvar("CHECK_ACCESS_BOUND", 1)
if is_plat("macosx") then
set_configvar("SUPPORT_SERIALIZATION", 0)
else
set_configvar("SUPPORT_SERIALIZATION", is_mode("release") and 1 or 0)
end
set_configvar("SUPPORT_TEXT_ARCHIVE", 0)
set_configvar("SUPPORT_XML_ARCHIVE", 1)
set_configvar("SUPPORT_BINARY_ARCHIVE", 1)
set_configvar("HKU_DISABLE_ASSERT", 0)
-- set warning all as error
if is_plat("windows") then
set_warnings("all", "error")
else
set_warnings("all")
end
-- set language: C99, c++ standard
set_languages("cxx17", "C99")
add_plugindirs("./xmake_plugins")
add_requires("fmt", {system=false, configs = {header_only = true, vs_runtime = "MD"}})
add_requires("spdlog", {system=false, configs = {header_only = true, fmt_external=true, vs_runtime = "MD"}})
add_requires("flatbuffers", {system=false, configs = {vs_runtime="MD"}})
add_requires("nng", {system=false, configs = {vs_runtime="MD"}})
add_defines("SPDLOG_DISABLE_DEFAULT_LOGGER") -- 禁用 spdlog 默认 logger
set_objectdir("$(buildir)/$(mode)/$(plat)/$(arch)/.objs")
set_targetdir("$(buildir)/$(mode)/$(plat)/$(arch)/lib")
add_includedirs("$(env BOOST_ROOT)")
add_linkdirs("$(env BOOST_LIB)")
-- modifed to use boost static library, except boost.python, serialization
--add_defines("BOOST_ALL_DYN_LINK")
add_defines("BOOST_SERIALIZATION_DYN_LINK")
if is_host("linux") then
if is_arch("x86_64") then
add_linkdirs("/usr/lib64")
add_linkdirs("/usr/lib/x86_64-linux-gnu")
end
end
if is_mode("debug") then
set_symbols("debug")
set_optimize("none")
end
-- is release now
if is_mode("release") then
if is_plat("windows") then
--Unix-like systems hidden symbols will cause the link dynamic libraries to failed!
set_symbols("hidden")
end
set_optimize("fastest")
set_strip("all")
end
-- for the windows platform (msvc)
if is_plat("windows") then
add_packagedirs("./hikyuu_extern_libs/pkg")
-- add some defines only for windows
add_defines("NOCRYPT", "NOGDI")
add_cxflags("-EHsc", "/Zc:__cplusplus", "/utf-8")
add_cxflags("-wd4819") --template dll export warning
add_defines("WIN32_LEAN_AND_MEAN")
if is_mode("release") then
add_cxflags("-MD")
elseif is_mode("debug") then
add_cxflags("-Gs", "-RTC1", "/bigobj")
add_cxflags("-MDd")
end
end
if not is_plat("windows") then
-- disable some compiler errors
add_cxflags("-Wno-error=deprecated-declarations", "-fno-strict-aliasing")
add_cxflags("-ftemplate-depth=1023", "-pthread")
add_shflags("-pthread")
add_ldflags("-pthread")
end
add_vectorexts("sse", "sse2", "sse3", "ssse3", "mmx", "avx")
if is_plat("windows") then
add_subdirs("./hikyuu_extern_libs/src/sqlite3")
end
add_subdirs("./hikyuu_cpp/hikyuu")
add_subdirs("./hikyuu_pywrap")
add_subdirs("./hikyuu_cpp/unit_test")
add_subdirs("./hikyuu_cpp/demo")
before_install("scripts.before_install")
on_install("scripts.on_install")
before_run("scripts.before_run")
|
fixed #I2LAT3 修改xmake.lua, 强制依赖包不使用系统包
|
fixed #I2LAT3 修改xmake.lua, 强制依赖包不使用系统包
|
Lua
|
mit
|
fasiondog/hikyuu
|
a7c179c766217eeb1df209bb8b57e548a806c064
|
packages/grid.lua
|
packages/grid.lua
|
local gridSpacing -- Should be a setting
local makeUp = function ()
local toadd = gridSpacing - (SILE.typesetter.frame.state.totals.gridCursor % gridSpacing)
SILE.typesetter.frame.state.totals.gridCursor = SILE.typesetter.frame.state.totals.gridCursor + toadd
return SILE.nodefactory.newVglue({ height = SILE.length.new({ length = toadd }) })
end
local leadingFor = function(this, vbox, previous)
if not this.frame.state.totals.gridCursor then this.frame.state.totals.gridCursor = 0 end
this.frame.state.totals.gridCursor = this.frame.state.totals.gridCursor + previous.height.length + previous.depth.length
return makeUp()
end
local pushVglue = function(this, spec)
if not this.frame.state.totals.gridCursor then this.frame.state.totals.gridCursor = 0 end
this.frame.state.totals.gridCursor = this.frame.state.totals.gridCursor + spec.height.length
SILE.defaultTypesetter.pushVglue(this, spec);
SILE.defaultTypesetter.pushVglue(this, makeUp())
end
local newBoxup = function (this)
local b = SILE.defaultTypesetter.boxUpNodes(this)
if not this.frame.state.totals.gridCursor then this.frame.state.totals.gridCursor = 0 end
if #b > 1 then
this.frame.state.totals.gridCursor = this.frame.state.totals.gridCursor + b[#b].height.length + b[#b].depth.length
end
return b
end
local debugGrid = function()
local t = SILE.typesetter
if not t.frame.state.totals.gridCursor then t.frame.state.totals.gridCursor = 0 end
local g = t.frame.state.totals.gridCursor
while g < t.frame:bottom() do
SILE.outputter.rule(t.frame:left(), g, t.frame:width(), 0.1)
g = g + gridSpacing
end
end
SILE.registerCommand("grid:debug", debugGrid)
SILE.registerCommand("grid", function(options, content)
SU.required(options, "spacing", "grid package")
gridSpacing = SILE.parseComplexFrameDimension(options.spacing,"h");
SILE.typesetter:leaveHmode()
SILE.typesetter.leadingFor = leadingFor
SILE.typesetter.pushVglue = pushVglue
SILE.typesetter.boxUpNodes = newBoxup
SILE.typesetter.setVerticalGlue = function () end
SILE.typesetter.frame.state.totals.gridCursor = 0
-- add some now
SILE.defaultTypesetter.pushVglue(SILE.typesetter, makeUp())
end, "Begins typesetting on a grid spaced at <spacing> intervals.")
SILE.registerCommand("no-grid", function (options, content)
SILE.typesetter.leadingFor = SILE.defaultTypesetter.leadingFor
SILE.typesetter.pushVglue = SILE.defaultTypesetter.pushVglue
SILE.typesetter.setVerticalGlue = SILE.defaultTypesetter.setVerticalGlue
-- SILE.typesetter.state = t.state
end, "Stops grid typesetting.")
|
local gridSpacing -- Should be a setting
local makeUp = function ()
local toadd = gridSpacing - (SILE.typesetter.frame.state.totals.gridCursor % gridSpacing)
SILE.typesetter.frame.state.totals.gridCursor = SILE.typesetter.frame.state.totals.gridCursor + toadd
return SILE.nodefactory.newVglue({ height = SILE.length.new({ length = toadd }) })
end
local leadingFor = function(this, vbox, previous)
if not this.frame.state.totals.gridCursor then this.frame.state.totals.gridCursor = 0 end
this.frame.state.totals.gridCursor = this.frame.state.totals.gridCursor + previous.height.length + previous.depth.length
return makeUp()
end
local pushVglue = function(this, spec)
if not this.frame.state.totals.gridCursor then this.frame.state.totals.gridCursor = 0 end
this.frame.state.totals.gridCursor = this.frame.state.totals.gridCursor + spec.height.length
SILE.defaultTypesetter.pushVglue(this, spec);
SILE.defaultTypesetter.pushVglue(this, makeUp())
end
local newBoxup = function (this)
local b = SILE.defaultTypesetter.boxUpNodes(this)
if not this.frame.state.totals.gridCursor then this.frame.state.totals.gridCursor = 0 end
if #b > 1 then
this.frame.state.totals.gridCursor = this.frame.state.totals.gridCursor + b[#b].height.length + b[#b].depth.length
end
return b
end
local debugGrid = function()
local t = SILE.typesetter
if not t.frame.state.totals.gridCursor then t.frame.state.totals.gridCursor = 0 end
local g = t.frame:top() + t.frame.state.totals.gridCursor + SILE.toPoints("1em")
while g < t.frame:bottom() do
SILE.outputter.rule(t.frame:left(), g, t.frame:width(), 0.1)
g = g + gridSpacing
end
end
SILE.registerCommand("grid:debug", debugGrid)
SILE.registerCommand("grid", function(options, content)
SU.required(options, "spacing", "grid package")
gridSpacing = SILE.parseComplexFrameDimension(options.spacing,"h");
-- SILE.typesetter:leaveHmode()
SILE.typesetter.leadingFor = leadingFor
SILE.typesetter.pushVglue = pushVglue
SILE.typesetter.boxUpNodes = newBoxup
SILE.typesetter.setVerticalGlue = function () end
SILE.typesetter.frame.state.totals.gridCursor = 0 -- Start the grid on the first baseline
-- add some now
-- SILE.defaultTypesetter.pushVglue(SILE.typesetter, makeUp())
end, "Begins typesetting on a grid spaced at <spacing> intervals.")
SILE.registerCommand("no-grid", function (options, content)
SILE.typesetter.leadingFor = SILE.defaultTypesetter.leadingFor
SILE.typesetter.pushVglue = SILE.defaultTypesetter.pushVglue
SILE.typesetter.setVerticalGlue = SILE.defaultTypesetter.setVerticalGlue
-- SILE.typesetter.state = t.state
end, "Stops grid typesetting.")
|
Fixes(?) to grid. There is confusion about line baselines and toplines.
|
Fixes(?) to grid. There is confusion about line baselines and toplines.
|
Lua
|
mit
|
WAKAMAZU/sile_fe,shirat74/sile,WAKAMAZU/sile_fe,anthrotype/sile,shirat74/sile,neofob/sile,WAKAMAZU/sile_fe,neofob/sile,WAKAMAZU/sile_fe,simoncozens/sile,neofob/sile,neofob/sile,alerque/sile,simoncozens/sile,alerque/sile,anthrotype/sile,anthrotype/sile,simoncozens/sile,shirat74/sile,anthrotype/sile,alerque/sile,alerque/sile,shirat74/sile,simoncozens/sile
|
89ea76a90af0d4276fd39c04ce2a8e4f5b03339a
|
src_trunk/resources/job-system/fishing/c_fishing_job.lua
|
src_trunk/resources/job-system/fishing/c_fishing_job.lua
|
local count = 0
local pFish = nil
local state = 0
local fishSize = 0
local hotSpot1 = nil
local hotSpot2 = nil
local totalCatch = 0
function castLine()
local element = getPedContactElement(getLocalPlayer())
if not (isElement(element)) then
outputChatBox("You must be on a boat to fish.", 255, 0, 0)
else
if not (getElementType(element)=="vehicle") then
outputChatBox("You must be on a boat to fish.", 255, 0, 0)
else
if not (getVehicleType(element)=="Boat") then
outputChatBox("You must be on a boat to fish.", 255, 0, 0)
else
local x, y, z = getElementPosition(getLocalPlayer())
if (x < 3000) and ( y < 3000) then -- Are they out at sea.
outputChatBox("You must be out at sea to fish.", 255, 0, 0)
else
if (catchTimer) then -- Are they already fishing?
outputChatBox("You have already cast your line. Wait for a fish to bite.", 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.", 255, 104, 91, true)
else
local biteTimer = math.random(3000,300000) -- 30 seconds to 5 minutes for a bite.
catchTimer = setTimer( fishOnLine, biteTimer, 1 ) -- A fish will bite within 1 and 5 minutes.
triggerServerEvent("castOutput", getLocalPlayer())
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)
outputChatBox("#FF9933When you are done fishing you can sell your catch at the #FF66CCfish market#FF9933.", 255, 104, 91, true)
outputChatBox("#FF9933((/totalcatch to see how much you have caught. To sell your catch enter /sellfish in the #FF66CCmarker#FF9933.))", 255, 104, 91, true)
end
end
end
end
end
end
end
end
addEvent("castLine", true)
addEventHandler("castLine", getRootElement(), castLine)
function fishOnLine()
killTimer(catchTimer)
catchTimer=nil
triggerServerEvent("fishOnLine", getLocalPlayer()) -- outputs /me
-- the progress bar
count = 0
state = 0
if (pFish) then
destroyElement(pFish)
end
pFish = guiCreateProgressBar(0.425, 0.75, 0.2, 0.035, true)
outputChatBox("You got a bite! ((Tap - and = to reel in the catch.))", 0, 255, 0)
bindKey("-", "down", reelItIn)
-- create two timers
resetTimer = setTimer(resetProgress, 2750, 0)
gotAwayTimer = setTimer(gotAway, 60000, 1)
local x, y, z = getElementPosition(getLocalPlayer())
if(x>=3950) and (x<=4450) and (y>= 1220) and (y<=1750) or (x>=4250) and (x<=5000) and (y>= -103) and (y<=500) then
fishSize = math.random(100, 200)
else
local x, y, z = getElementPosition(getLocalPlayer())
if ( y > 4500) then
fishSize = math.random(75, 111)
elseif (x > 5500) then
fishSize = math.random(75, 103)
elseif (x > 4500) then
fishSize = math.random(54, 83)
elseif (x > 3500) then
fishSize = math.random(22,76)
else
fishSize = math.random(1, 56)
end
end
local lineSnap = math.random(1,10) -- Chances of line snapping 1/10. Fish over 100lbs are twice as likely to snap your line.
if (fishSize>=100)then
if (lineSnap > 9) then
outputChatBox("The monster of a fish has broken your line. You need to buy a new fishing rod to continue fishing.", 255, 0, 0)
triggerServerEvent("lineSnap",getLocalPlayer())
killTimer (resetTimer)
killTimer (gotAwayTimer)
destroyElement(pFish)
pFish = nil
unbindKey("-", "down", reelItIn)
unbindKey("=", "down", reelItIn)
fishSize = 0
end
end
end
function reelItIn()
if (state==0) then
bindKey("=", "down", reelItIn)
unbindKey("-", "down", reelItIn)
state = 1
elseif (state==1) then
bindKey("-", "down", reelItIn)
unbindKey("=", "down", reelItIn)
state = 0
end
count = count + 1
guiProgressBarSetProgress(pFish, count)
if (count>=100) then
killTimer (resetTimer)
killTimer (gotAwayTimer)
destroyElement(pFish)
pFish = nil
unbindKey("-", "down", reelItIn)
unbindKey("=", "down", reelItIn)
totalCatch = math.floor(totalCatch + fishSize)
outputChatBox("You have caught "..totalCatch.."lbs of fish so far.", 255, 194, 14)
triggerServerEvent("catchFish", getLocalPlayer(), fishSize)
end
end
function resetProgress()
if(count>=0)then
local difficulty = (fishSize/4)
guiProgressBarSetProgress(pFish, (count-difficulty))
count = count-difficulty
else
count = 0
end
end
function gotAway()
killTimer (resetTimer)
destroyElement(pFish)
pFish = nil
unbindKey("-", "down", reelItIn)
unbindKey("=", "down", reelItIn)
outputChatBox("#FF9933The fish got away.", 255, 0, 0, true)
fishSize = 0
end
-- /totalcatch command
function currentCatch()
outputChatBox("You have "..totalCatch.."lbs of fish caught so far.", 255, 194, 14)
end
addCommandHandler("totalcatch", currentCatch, false, false)
-- sellfish
function unloadCatch()
if (isElementWithinColShape(getLocalPlayer(), colsphere)) then
if (totalCatch == 0) then
outputChatBox("You need to catch some fish to sell first.", 255, 0, 0)
else
local profit = math.floor(totalCatch*0.66)
outputChatBox("You made $".. profit .." from the fish you caught.", 255, 104, 91)
triggerServerEvent("sellcatch", getLocalPlayer(), totalCatch, profit)
destroyElement(blip)
destroyElement(marker)
destroyElement(colsphere)
totalCatch = 0
end
else
outputChatBox("You need to be at the fish market to sell your catch.", 255, 0, 0)
end
end
addCommandHandler("sellFish", unloadCatch, false, false)
|
local count = 0
local pFish = nil
local state = 0
local fishSize = 0
local hotSpot1 = nil
local hotSpot2 = nil
local totalCatch = 0
local fishingBlip, fishingMarker, fishingCol = nil
function castLine()
local element = getPedContactElement(getLocalPlayer())
if not (isElement(element)) then
outputChatBox("You must be on a boat to fish.", 255, 0, 0)
else
if not (getElementType(element)=="vehicle") then
outputChatBox("You must be on a boat to fish.", 255, 0, 0)
else
if not (getVehicleType(element)=="Boat") then
outputChatBox("You must be on a boat to fish.", 255, 0, 0)
else
local x, y, z = getElementPosition(getLocalPlayer())
if (x < 3000) and ( y < 3000) then -- Are they out at sea.
outputChatBox("You must be out at sea to fish.", 255, 0, 0)
else
if (catchTimer) then -- Are they already fishing?
outputChatBox("You have already cast your line. Wait for a fish to bite.", 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.", 255, 104, 91, true)
else
--local biteTimer = math.random(3000,300000) -- 30 seconds to 5 minutes for a bite.
catchTimer = setTimer( fishOnLine, 5000, 1 ) -- A fish will bite within 1 and 5 minutes.
triggerServerEvent("castOutput", getLocalPlayer())
if not (fishingBlip) then -- If the /sellfish marker isnt already being shown...
fishingBlip = createBlip( 2243.7339, 578.905, 6.78, 0, 2, 255, 0, 255, 255 )
fishingMarker = createMarker( 2243.7339, 578.905, 6.78, "cylinder", 2, 255, 0, 255, 150 )
fishingCol = createColSphere (2243.7339, 578.905, 6.78, 3)
outputChatBox("#FF9933When you are done fishing you can sell your catch at the #FF66CCfish market#FF9933.", 255, 104, 91, true)
outputChatBox("#FF9933((/totalcatch to see how much you have caught. To sell your catch enter /sellfish in the #FF66CCmarker#FF9933.))", 255, 104, 91, true)
end
end
end
end
end
end
end
end
addEvent("castLine", true)
addEventHandler("castLine", getRootElement(), castLine)
function fishOnLine()
killTimer(catchTimer)
catchTimer=nil
local x, y, z = getElementPosition(getLocalPlayer())
if ( x < 3000) and ( y < 3000) then
outputChatBox("You should have stayed out at sea if you wanted to fish.", 255, 0, 0)
else
triggerServerEvent("fishOnLine", getLocalPlayer()) -- outputs /me
-- the progress bar
count = 0
state = 0
if (pFish) then
destroyElement(pFish)
end
pFish = guiCreateProgressBar(0.425, 0.75, 0.2, 0.035, true)
outputChatBox("You got a bite! ((Tap - and = to reel in the catch.))", 0, 255, 0)
bindKey("-", "down", reelItIn)
-- create two timers
resetTimer = setTimer(resetProgress, 2750, 0)
gotAwayTimer = setTimer(gotAway, 60000, 1)
if(x>=3950) and (x<=4450) and (y>= 1220) and (y<=1750) or (x>=4250) and (x<=5000) and (y>= -103) and (y<=500) then
fishSize = math.random(100, 200)
else
if ( y > 4500) then
fishSize = math.random(75, 111)
elseif (x > 5500) then
fishSize = math.random(75, 103)
elseif (x > 4500) then
fishSize = math.random(54, 83)
elseif (x > 3500) then
fishSize = math.random(22,76)
else
fishSize = math.random(1, 56)
end
end
local lineSnap = math.random(1,10) -- Chances of line snapping 1/10. Fish over 100lbs are twice as likely to snap your line.
if (fishSize>=100)then
if (lineSnap > 9) then
outputChatBox("The monster of a fish has broken your line. You need to buy a new fishing rod to continue fishing.", 255, 0, 0)
triggerServerEvent("lineSnap",getLocalPlayer())
killTimer (resetTimer)
killTimer (gotAwayTimer)
destroyElement(pFish)
pFish = nil
unbindKey("-", "down", reelItIn)
unbindKey("=", "down", reelItIn)
fishSize = 0
end
end
end
end
function reelItIn()
if (state==0) then
bindKey("=", "down", reelItIn)
unbindKey("-", "down", reelItIn)
state = 1
elseif (state==1) then
bindKey("-", "down", reelItIn)
unbindKey("=", "down", reelItIn)
state = 0
end
count = count + 1
guiProgressBarSetProgress(pFish, count)
if (count>=100) then
killTimer (resetTimer)
killTimer (gotAwayTimer)
destroyElement(pFish)
pFish = nil
unbindKey("-", "down", reelItIn)
unbindKey("=", "down", reelItIn)
totalCatch = math.floor(totalCatch + fishSize)
outputChatBox("You have caught "..totalCatch.."lbs of fish so far.", 255, 194, 14)
triggerServerEvent("catchFish", getLocalPlayer(), fishSize)
end
end
function resetProgress()
if(count>=0)then
local difficulty = (fishSize/4)
guiProgressBarSetProgress(pFish, (count-difficulty))
count = count-difficulty
else
count = 0
end
end
function gotAway()
killTimer (resetTimer)
destroyElement(pFish)
pFish = nil
unbindKey("-", "down", reelItIn)
unbindKey("=", "down", reelItIn)
outputChatBox("#FF9933The fish got away.", 255, 0, 0, true)
fishSize = 0
end
-- /totalcatch command
function currentCatch()
outputChatBox("You have "..totalCatch.."lbs of fish caught so far.", 255, 194, 14)
end
addCommandHandler("totalcatch", currentCatch, false, false)
-- sellfish
function unloadCatch()
if (isElementWithinColShape(getLocalPlayer(), fishingCol)) then
if (totalCatch == 0) then
outputChatBox("You need to catch some fish to sell first.", 255, 0, 0)
else
local profit = math.floor(totalCatch*0.66)
outputChatBox("You made $".. profit .." from the fish you caught.", 255, 104, 91)
triggerServerEvent("sellcatch", getLocalPlayer(), totalCatch, profit)
destroyElement(fishingBlip)
destroyElement(fishingMarker)
destroyElement(fishingCol)
fishingBlip, fishingMarker, fishingCol = nil
totalCatch = 0
end
else
outputChatBox("You need to be at the fish market to sell your catch.", 255, 0, 0)
end
end
addCommandHandler("sellFish", unloadCatch, false, false)
|
Fishing fix for catching fish when not out at sea. Possible fix for marker not appearing.
|
Fishing fix for catching fish when not out at sea. Possible fix for marker not appearing.
git-svn-id: 8769cb08482c9977c94b72b8e184ec7d2197f4f7@645 64450a49-1f69-0410-a0a2-f5ebb52c4f5b
|
Lua
|
bsd-3-clause
|
valhallaGaming/uno,valhallaGaming/uno,valhallaGaming/uno
|
046c4107b612511f6c0a13f31de5ba5a3ba28d62
|
npl_mod/nwf/utils/string_util.lua
|
npl_mod/nwf/utils/string_util.lua
|
--[[
Title: string utilities
Author: zenghui
Date: 2017/3/6
]]
local util = commonlib.gettable("nwf.util.string");
function util.split(str, delimiter)
if type(delimiter) ~= "string" or string.len(delimiter) <= 0 then
return
end
local start = 1
local t = {}
while true do
local pos = string.find (str, delimiter, start, true) -- plain find
if not pos then
break
end
table.insert (t, string.sub (str, start, pos - 1))
start = pos + string.len (delimiter)
end
table.insert (t, string.sub (str, start))
return t
end
function util.upperFirstChar(str)
local firstChar = string.sub(str, 1, 1);
local c = string.byte(firstChar);
if(c>=97 and c<=122) then
firstChar = string.upper(firstChar);
end
return firstChar .. string.sub(str, 2, #str)
end
local guid_seed = 0;
function util.new_guid()
local seed={'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
local tb = {};
guid_seed = guid_seed + 1;
math.randomseed(tostring(os.time() + guid_seed):reverse():sub(1, 6));
for i = 1, 32 do
table.insert(tb, seed[math.random(1, 16)]);
end
return table.concat(tb);
end
|
--[[
Title: string utilities
Author: zenghui
Date: 2017/3/6
]]
local util = commonlib.gettable("nwf.util.string");
function util.split(str, delimiter)
if type(delimiter) ~= "string" or string.len(delimiter) <= 0 then
return
end
local start = 1
local t = {}
while true do
local pos = string.find (str, delimiter, start, true) -- plain find
if not pos then
break
end
table.insert (t, string.sub (str, start, pos - 1))
start = pos + string.len (delimiter)
end
table.insert (t, string.sub (str, start))
return t
end
function util.upperFirstChar(str)
local firstChar = string.sub(str, 1, 1);
local c = string.byte(firstChar);
if(c>=97 and c<=122) then
firstChar = string.upper(firstChar);
end
return firstChar .. string.sub(str, 2, #str)
end
local guid_seed = 0;
local last_time = 0;
function util.new_guid()
local seed={'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
local tb = {};
local t = ParaGlobal.timeGetTime();
if (last_time ~= t) then
guid_seed = 0;
end
last_time = t;
math.randomseed(tostring(t + guid_seed):reverse():sub(1, 6));
for i = 1, 32 do
table.insert(tb, seed[math.random(1, 16)]);
end
guid_seed = guid_seed + 1;
return table.concat(tb);
end
|
fix string_util.new_guid bug 2
|
fix string_util.new_guid bug 2
|
Lua
|
mit
|
Links7094/nwf,Links7094/nwf,elvinzeng/nwf,elvinzeng/nwf
|
ead994371d3c0197c0e561422c75081edd53e7c8
|
test/config.lua
|
test/config.lua
|
local log = require 'log'
box.cfg{
listen = 33013,
wal_dir='.',
snap_dir='.',
wal_mode='none',
}
box.once('initbox', function()
local s1 = box.schema.space.create('test', {id = 513, if_not_exists = true})
local ip = s1:create_index('primary', {type = 'hash', parts = {1, 'NUM'}, if_not_exists = true})
local iname = s1:create_index('name', {type = 'tree', parts = {2, 'STR'}, if_not_exists = true})
local irtree = s1:create_index('point', {type = 'rtree', unique=false, parts = {3, 'ARRAY'}, if_not_exists = true})
local ipname = s1:create_index('id_name', {type = 'tree', parts = {1, 'NUM', 2, 'STR'}})
local s2 = box.schema.space.create('test1', {id = 514, if_not_exists = true})
local ip = s2:create_index('primary', {type = 'hash', parts = {1, 'NUM'}, if_not_exists = true})
function reseed()
local s1 = box.space.test
s1:truncate()
s1:insert{1, "hello", {1, 2}, 100}
s1:insert{2, "world", {3, 4}, 200}
local s2 = box.space.test1
s2:truncate()
s2:insert{1, "hello", {1, 2}, 100}
s2:insert{2, "world", {3, 4}, 200}
end
function func1(i)
return i+1
end
box.schema.user.grant('guest', 'read,write,execute', 'universe')
box.schema.user.create('tester', {password='testpass'})
box.schema.user.grant('tester', 'read,write,execute', 'universe')
end)
local console = require 'console'
console.listen '0.0.0.0:33015'
|
local log = require 'log'
box.cfg{
listen = 33013,
memtx_dir='.',
wal_mode='none',
}
box.once('initbox', function()
local s1 = box.schema.space.create('test', {id = 513, if_not_exists = true})
local ip = s1:create_index('primary', {type = 'hash', parts = {1, 'unsigned'}, if_not_exists = true})
local iname = s1:create_index('name', {type = 'tree', parts = {2, 'STR'}, if_not_exists = true})
local irtree = s1:create_index('point', {type = 'rtree', unique=false, parts = {3, 'ARRAY'}, if_not_exists = true})
local ipname = s1:create_index('id_name', {type = 'tree', parts = {1, 'unsigned', 2, 'STR'}})
local s2 = box.schema.space.create('test1', {id = 514, if_not_exists = true})
local ip = s2:create_index('primary', {type = 'hash', parts = {1, 'unsigned'}, if_not_exists = true})
box.schema.user.create('tester', {password='testpass'})
box.schema.user.grant('tester', 'read,write,execute', 'universe')
box.schema.func.create('reseed')
box.schema.func.create('func1')
end)
function reseed()
local s1 = box.space.test
s1:truncate()
s1:insert{1, "hello", {1, 2}, 100}
s1:insert{2, "world", {3, 4}, 200}
local s2 = box.space.test1
s2:truncate()
s2:insert{1, "hello", {1, 2}, 100}
s2:insert{2, "world", {3, 4}, 200}
end
function func1(i)
return i+1
end
box.schema.user.grant('guest', 'read,write,execute', 'universe')
local console = require 'console'
console.listen '0.0.0.0:33015'
|
fixes in test/config.lua for newer tarantool
|
fixes in test/config.lua for newer tarantool
|
Lua
|
mit
|
tarantool/tarantool-ruby
|
31ee7847496ad590da7c52995e3ffd645586f4a8
|
PokePrecSucc.lua
|
PokePrecSucc.lua
|
--[[
Navigation bar with previous and next Pokémon in dex order.
This module exports two functions.
One is the "PokePrecSucc", intended to be used within Pokémon pages, that
links the previous and next Pokémon pages.
The other is "subpage", intended to be used in Pokémon subpages to link
corresponding subpages of previous and next Pokémon.
--]]
local m = {}
local mw = require('mw')
local txt = require('Wikilib-strings') -- luacheck: no unused
local multigen = require('Wikilib-multigen')
local prevnext = require('PrevNext')
local data = require("Wikilib-data")
local pokes = require("Poké-data")
--[[
Base (internal) function to create a PokePrecSucc. Performs basic operations
such as computing previous and next Pokémon ndex, and preparing the printed
text.
Parameters:
- poke: the Pokémon name
- linksuffix: (optional) the suffix to append to links. It defaults to
nothing (ie: links base Pokémon pages). This suffix is appended as is;
it's not modified, for instance, adding a leading "/".
- list: (optional) the page to link in the middle of the prevnext.
--]]
local function basePokePrecSucc(poke, linksuffix, list)
linksuffix = linksuffix or ""
list = list or "Elenco Pokémon secondo il Pokédex Nazionale"
local pokeData = multigen.getGen(pokes[poke] or pokes[mw.text.decode(poke)])
local type1, type2 = pokeData.type1, pokeData.type2
local prev = (pokeData.ndex - 2 + data.pokeNum) % data.pokeNum + 1
local next = pokeData.ndex % data.pokeNum + 1
local prevTf, nextTf = string.tf(prev), string.tf(next)
local prevname, nextname = pokes[prev].name, pokes[next].name
return prevnext.PrevNextLua{
color = type1,
color2 = type2,
series = pokeData.name,
list = list,
prev = table.concat{"#", prevTf, ": ", prevname},
prevlink = prevname .. linksuffix,
prevspr = prevTf,
next = table.concat{"#", nextTf, ": ", nextname},
nextlink = nextname .. linksuffix,
nextspr = nextTf,
}
end
--[[
Function to create a PrecSucc of subpages.
Usage:
{{#invoke: PokePrecSucc | subpage | <Pokémon name> | <suffix> | ... }}
- 1: (optional) the name of a Pokémon. In a Pokémon subpage the suggested value
for this is "{{ROOTPAGENAME}}", that evaluates to the page name that
(often) is the Pokémon name desired. It defaults to the root page title.
- 2: (optional) if given, it is used to determine the subpage to link. It
should be the name of the subpage to link without the leading /. It
defaults to the same suffix as the page it's invoked in.
- list: (optional) the page to link from the middle text (the name of the
current Pokémon). Defaults to "Elenco Pokémon secondo il Pokédex Nazionale"
--]]
m.subpage = function(frame)
local poke = string.trim(frame.args[1]
or mw.title.getCurrentTitle().rootText):lower()
local subpageSuffix = ""
if frame.args[2] then
subpageSuffix = "/" .. string.trim(frame.args[2])
else
local title = mw.title.getCurrentTitle()
if title.isSubpage then
subpageSuffix = "/" .. mw.title.getCurrentTitle().subpageText
end
end
return basePokePrecSucc(poke, subpageSuffix, poke)
end
--[[
Function to create a PrecSucc in a Pokémon page.
Usage:
{{#invoke: PokePrecSucc | PokePrecSucc | <Pokémon name> }}
- 1: (optional) the name of a Pokémon. In a Pokémon the suggested value for
this is "{{PAGENAME}}", that evaluates to the page name that (often) is
the Pokémon name desired. If not given, it defaults to the page title.
--]]
m.PokePrecSucc = function(frame)
local poke = string.trim(frame.args[1]
or mw.title.getCurrentTitle().text):lower()
return basePokePrecSucc(poke)
end
m.pokeprecsucc, m.pokePrecSucc = m.PokePrecSucc, m.PokePrecSucc
return m
|
--[[
Navigation bar with previous and next Pokémon in dex order.
This module exports two functions.
One is the "PokePrecSucc", intended to be used within Pokémon pages, that
links the previous and next Pokémon pages.
The other is "subpage", intended to be used in Pokémon subpages to link
corresponding subpages of previous and next Pokémon.
--]]
local m = {}
local mw = require('mw')
local txt = require('Wikilib-strings') -- luacheck: no unused
local multigen = require('Wikilib-multigen')
local prevnext = require('PrevNext')
local data = require("Wikilib-data")
local pokes = require("Poké-data")
--[[
Base (internal) function to create a PokePrecSucc. Performs basic operations
such as computing previous and next Pokémon ndex, and preparing the printed
text.
Parameters:
- poke: the Pokémon name
- linksuffix: (optional) the suffix to append to links. It defaults to
nothing (ie: links base Pokémon pages). This suffix is appended as is;
it's not modified, for instance, adding a leading "/".
- list: (optional) the page to link in the middle of the prevnext.
--]]
local function basePokePrecSucc(poke, linksuffix, list)
linksuffix = linksuffix or ""
list = list or "Elenco Pokémon secondo il Pokédex Nazionale"
local pokeData = multigen.getGen(pokes[poke] or pokes[mw.text.decode(poke)])
local type1, type2 = pokeData.type1, pokeData.type2
local pred = (pokeData.ndex - 2 + data.pokeNum) % data.pokeNum + 1
local succ = pokeData.ndex % data.pokeNum + 1
local predTf, succTf = string.tf(pred), string.tf(succ)
local predname, succname = pokes[pred].name, pokes[succ].name
return prevnext.PrevNextLua{
color = type1,
color2 = type2,
series = pokeData.name,
list = list,
prev = table.concat{"#", predTf, ": ", predname},
prevlink = predname .. linksuffix,
prevspr = predTf,
next = table.concat{"#", succTf, ": ", succname},
nextlink = succname .. linksuffix,
nextspr = succTf,
}
end
--[[
Function to create a PrecSucc of subpages.
Usage:
{{#invoke: PokePrecSucc | subpage | <Pokémon name> | <suffix> | ... }}
- 1: (optional) the name of a Pokémon. In a Pokémon subpage the suggested value
for this is "{{ROOTPAGENAME}}", that evaluates to the page name that
(often) is the Pokémon name desired. It defaults to the root page title.
- 2: (optional) if given, it is used to determine the subpage to link. It
should be the name of the subpage to link without the leading /. It
defaults to the same suffix as the page it's invoked in.
- list: (optional) the page to link from the middle text (the name of the
current Pokémon). Defaults to "Elenco Pokémon secondo il Pokédex Nazionale"
--]]
m.subpage = function(frame)
local poke = string.trim(frame.args[1]
or mw.title.getCurrentTitle().rootText)
local subpageSuffix = ""
if frame.args[2] then
subpageSuffix = "/" .. string.trim(frame.args[2])
else
local title = mw.title.getCurrentTitle()
if title.isSubpage then
subpageSuffix = "/" .. mw.title.getCurrentTitle().subpageText
end
end
return basePokePrecSucc(poke:lower(), subpageSuffix, poke)
end
--[[
Function to create a PrecSucc in a Pokémon page.
Usage:
{{#invoke: PokePrecSucc | PokePrecSucc | <Pokémon name> }}
- 1: (optional) the name of a Pokémon. In a Pokémon the suggested value for
this is "{{PAGENAME}}", that evaluates to the page name that (often) is
the Pokémon name desired. If not given, it defaults to the page title.
--]]
m.PokePrecSucc = function(frame)
local poke = string.trim(frame.args[1]
or mw.title.getCurrentTitle().text):lower()
return basePokePrecSucc(poke)
end
m.pokeprecsucc, m.pokePrecSucc = m.PokePrecSucc, m.PokePrecSucc
return m
|
Fixing the fix of link of PrevNext in Pokémon subpages
|
Fixing the fix of link of PrevNext in Pokémon subpages
|
Lua
|
cc0-1.0
|
pokemoncentral/wiki-lua-modules
|
55be72df76af41c8b7dbf20f9993a2453318ddac
|
deps/coro-http.lua
|
deps/coro-http.lua
|
--[[lit-meta
name = "creationix/coro-http"
version = "2.1.0"
dependencies = {
"creationix/coro-net@2.1.0",
"luvit/http-codec@2.0.0"
}
homepage = "https://github.com/luvit/lit/blob/master/deps/coro-http.lua"
description = "An coro style http(s) client and server helper."
tags = {"coro", "http"}
license = "MIT"
author = { name = "Tim Caswell" }
]]
local httpCodec = require('http-codec')
local net = require('coro-net')
local function createServer(host, port, onConnect)
net.createServer({
host = host,
port = port,
encode = httpCodec.encoder(),
decode = httpCodec.decoder(),
}, function (read, write, socket)
for head in read do
local parts = {}
for part in read do
if #part > 0 then
parts[#parts + 1] = part
else
break
end
end
local body = table.concat(parts)
head, body = onConnect(head, body, socket)
write(head)
if body then write(body) end
write("")
if not head.keepAlive then break end
end
end)
end
local function parseUrl(url)
local protocol, host, hostname, port, path = url:match("^(https?:)//(([^/:]+):?([0-9]*))(/?.*)$")
if not protocol then error("Not a valid http url: " .. url) end
local tls = protocol == "https:"
port = port and tonumber(port) or (tls and 443 or 80)
if path == "" then path = "/" end
return {
tls = tls,
host = host,
hostname = hostname,
port = port,
path = path
}
end
local connections = {}
local function getConnection(host, port, tls)
for i = #connections, 1, -1 do
local connection = connections[i]
if connection.host == host and connection.port == port and connection.tls == tls then
table.remove(connections, i)
-- Make sure the connection is still alive before reusing it.
if not connection.socket:is_closing() then
connection.reused = true
connection.socket:ref()
return connection
end
end
end
local read, write, socket, updateDecoder, updateEncoder = assert(net.connect {
host = host,
port = port,
tls = tls,
encode = httpCodec.encoder(),
decode = httpCodec.decoder()
})
return {
socket = socket,
host = host,
port = port,
tls = tls,
read = read,
write = write,
updateEncoder = updateEncoder,
updateDecoder = updateDecoder,
reset = function ()
-- This is called after parsing the response head from a HEAD request.
-- If you forget, the codec might hang waiting for a body that doesn't exist.
updateDecoder(httpCodec.decoder())
end
}
end
local function saveConnection(connection)
if connection.socket:is_closing() then return end
connections[#connections + 1] = connection
connection.socket:unref()
end
local function request(method, url, headers, body)
local uri = parseUrl(url)
local connection = getConnection(uri.hostname, uri.port, uri.tls)
local read = connection.read
local write = connection.write
local req = {
method = method,
path = uri.path,
{"Host", uri.host}
}
local contentLength
local chunked
if headers then
for i = 1, #headers do
local key, value = unpack(headers[i])
key = key:lower()
if key == "content-length" then
contentLength = value
elseif key == "content-encoding" and value:lower() == "chunked" then
chunked = true
end
req[#req + 1] = headers[i]
end
end
if type(body) == "string" then
if not chunked and not contentLength then
req[#req + 1] = {"Content-Length", #body}
end
end
write(req)
if body then write(body) end
local res = read()
if not res then
write()
-- If we get an immediate close on a reused socket, try again with a new socket.
-- TODO: think about if this could resend requests with side effects and cause
-- them to double execute in the remote server.
if connection.reused then
return request(method, url, headers, body)
end
error("Connection closed")
end
body = {}
if req.method == "HEAD" then
connection.reset()
else
while true do
local item = read()
if not item then
res.keepAlive = false
break
end
if #item == 0 then
break
end
body[#body + 1] = item
end
end
if res.keepAlive then
saveConnection(connection)
else
write()
end
-- Follow redirects
if method == "GET" and (res.code == 302 or res.code == 307) then
for i = 1, #res do
local key, location = unpack(res[i])
if key:lower() == "location" then
return request(method, location, headers)
end
end
end
return res, table.concat(body)
end
return {
createServer = createServer,
parseUrl = parseUrl,
getConnection = getConnection,
saveConnection = saveConnection,
request = request,
}
|
--[[lit-meta
name = "creationix/coro-http"
version = "2.1.1"
dependencies = {
"creationix/coro-net@2.1.0",
"luvit/http-codec@2.0.0"
}
homepage = "https://github.com/luvit/lit/blob/master/deps/coro-http.lua"
description = "An coro style http(s) client and server helper."
tags = {"coro", "http"}
license = "MIT"
author = { name = "Tim Caswell" }
]]
local httpCodec = require('http-codec')
local net = require('coro-net')
local function createServer(host, port, onConnect)
net.createServer({
host = host,
port = port,
encode = httpCodec.encoder(),
decode = httpCodec.decoder(),
}, function (read, write, socket)
for head in read do
local parts = {}
for part in read do
if #part > 0 then
parts[#parts + 1] = part
else
break
end
end
local body = table.concat(parts)
head, body = onConnect(head, body, socket)
write(head)
if body then write(body) end
write("")
if not head.keepAlive then break end
end
end)
end
local function parseUrl(url)
local protocol, host, hostname, port, path = url:match("^(https?:)//(([^/:]+):?([0-9]*))(/?.*)$")
if not protocol then error("Not a valid http url: " .. url) end
local tls = protocol == "https:"
port = port and tonumber(port) or (tls and 443 or 80)
if path == "" then path = "/" end
return {
tls = tls,
host = host,
hostname = hostname,
port = port,
path = path
}
end
local connections = {}
local function getConnection(host, port, tls)
for i = #connections, 1, -1 do
local connection = connections[i]
if connection.host == host and connection.port == port and connection.tls == tls then
table.remove(connections, i)
-- Make sure the connection is still alive before reusing it.
if not connection.socket:is_closing() then
connection.reused = true
connection.socket:ref()
return connection
end
end
end
local read, write, socket, updateDecoder, updateEncoder = assert(net.connect {
host = host,
port = port,
tls = tls,
encode = httpCodec.encoder(),
decode = httpCodec.decoder()
})
return {
socket = socket,
host = host,
port = port,
tls = tls,
read = read,
write = write,
updateEncoder = updateEncoder,
updateDecoder = updateDecoder,
reset = function ()
-- This is called after parsing the response head from a HEAD request.
-- If you forget, the codec might hang waiting for a body that doesn't exist.
updateDecoder(httpCodec.decoder())
end
}
end
local function saveConnection(connection)
if connection.socket:is_closing() then return end
connections[#connections + 1] = connection
connection.socket:unref()
end
local function request(method, url, headers, body)
local uri = parseUrl(url)
local connection = getConnection(uri.hostname, uri.port, uri.tls)
local read = connection.read
local write = connection.write
local req = {
method = method,
path = uri.path,
{"Host", uri.host}
}
local contentLength
local chunked
if headers then
for i = 1, #headers do
local key, value = unpack(headers[i])
key = key:lower()
if key == "content-length" then
contentLength = value
elseif key == "content-encoding" and value:lower() == "chunked" then
chunked = true
end
req[#req + 1] = headers[i]
end
end
if type(body) == "string" then
if not chunked and not contentLength then
req[#req + 1] = {"Content-Length", #body}
end
end
write(req)
if body then write(body) end
local res = read()
if not res then
if not connection.socket:is_closing() then
connection.socket:close()
end
-- If we get an immediate close on a reused socket, try again with a new socket.
-- TODO: think about if this could resend requests with side effects and cause
-- them to double execute in the remote server.
if connection.reused then
return request(method, url, headers, body)
end
error("Connection closed")
end
body = {}
if req.method == "HEAD" then
connection.reset()
else
while true do
local item = read()
if not item then
res.keepAlive = false
break
end
if #item == 0 then
break
end
body[#body + 1] = item
end
end
if res.keepAlive then
saveConnection(connection)
else
write()
end
-- Follow redirects
if method == "GET" and (res.code == 302 or res.code == 307) then
for i = 1, #res do
local key, location = unpack(res[i])
if key:lower() == "location" then
return request(method, location, headers)
end
end
end
return res, table.concat(body)
end
return {
createServer = createServer,
parseUrl = parseUrl,
getConnection = getConnection,
saveConnection = saveConnection,
request = request,
}
|
Fix coro-http to not hang when reusing sockets
|
Fix coro-http to not hang when reusing sockets
|
Lua
|
apache-2.0
|
zhaozg/lit,squeek502/lit,luvit/lit,james2doyle/lit
|
092857f6e1348c89e8774787008771552622db93
|
utils/_keys/switcher.lua
|
utils/_keys/switcher.lua
|
local module = {}
local switcher = require"hs.window.switcher"
local filter = require"hs.window.filter"
local hotkey = require"hs.hotkey"
local mods = require"hs._asm.extras".mods
-- and either I'm reading window.filter wrong or its broken... well, @lowne does say it's still experimental
-- show hidden windows as well for the current space... I think...
module.switcher = switcher.new(filter.new():setCurrentSpace(true), {
selectedThumbnailSize = 288,
thumbnailSize = 96,
showTitles = false,
-- showSelectedThumbnail = false, -- wish it would just show the selected title, but this gets rid of both
textSize = 8,
textColor = { 1.0, 1.0, 1.0, 0.75 },
backgroundColor = { 0.3, 0.3, 0.3, 0.75 },
highlightColor = { 0.8, 0.5, 0.0, 0.80 },
titleBackgroundColor = { 0.0, 0.0, 0.0, 0.75 },
})
-- bind to hotkeys; WARNING: at least one modifier key is required!
hotkey.bind(mods.cAsc, 'tab', function() module.switcher:next() end)
hotkey.bind(mods.cASc, 'tab', function() module.switcher:previous() end)
return module
|
local module = {}
local switcher = require"hs.window.switcher"
local filter = require"hs.window.filter"
local hotkey = require"hs.hotkey"
local mods = require"hs._asm.extras".mods
module.switcher = switcher.new(filter.new():setCurrentSpace(true):setDefaultFilter{}, {
selectedThumbnailSize = 288,
thumbnailSize = 96,
showTitles = false,
-- showSelectedThumbnail = false, -- wish it would just show the selected title, but this gets rid of both
textSize = 7,
textColor = { 1.0, 1.0, 1.0, 0.75 },
backgroundColor = { 0.3, 0.3, 0.3, 0.75 },
highlightColor = { 0.8, 0.5, 0.0, 0.80 },
titleBackgroundColor = { 0.0, 0.0, 0.0, 0.75 },
})
-- bind to hotkeys; WARNING: at least one modifier key is required!
hotkey.bind(mods.cAsc, 'tab', function() module.switcher:next() end)
hotkey.bind(mods.cASc, 'tab', function() module.switcher:previous() end)
return module
|
updating with hidden window fix
|
updating with hidden window fix
|
Lua
|
mit
|
asmagill/hammerspoon-config,asmagill/hammerspoon-config,asmagill/hammerspoon-config
|
7aa5083d901e11e246988ef9c44022950e477e57
|
src/Display.lua
|
src/Display.lua
|
--------------------------------------------------------------------------------
-- Set of global helper functions
--
-- This file is just an example that meant to be changed for specific project.
-- It includes useful factory methods to create rigs.
--------------------------------------------------------------------------------
local Display = {}
local Label = require("core.Label")
local Group = require("core.Group")
local Layer = require("core.Layer")
local PropertyUtils = require("util.PropertyUtils")
---
-- Create MOAIProp with deck set to proper texture file
-- @param fileName Texture name or sprite frame name
-- @param width (option) image width. This will modify prop scale
-- @param height (option) image height. This will modify prop scale
--
-- @overload
-- @param table Properties
function Display.Sprite(fileName, width, height)
local properties
if type(fileName) == 'table' then
properties = fileName
fileName = properties['fileName']
width = properties['width']
height = properties['height']
properties['fileName'] = nil
properties['width'] = nil
properties['height'] = nil
end
local deck
if string.endswith(fileName, ".9.png") then
deck = ResourceMgr:getNineImageDeck(fileName)
else
deck = ResourceMgr:getImageDeck(fileName)
end
if not deck then
local atlas = ResourceMgr:getAtlasName(fileName)
assert(atlas, "Image not found: " .. fileName)
deck = ResourceMgr:getAtlasDeck(atlas)
end
local sprite = MOAIProp.new()
sprite:setDeck(deck)
sprite.deck = deck
sprite:setIndexByName(fileName)
local w, h = sprite:getDims()
local sx = width and width / w or 1
local sy = height and height / h or 1
sprite:setScl(sx, sy, 1)
if properties then
PropertyUtils.setProperties(sprite, properties, true)
end
return sprite
end
---
-- Create Text Box
-- @param str string
-- @param width
-- @param height
-- @param fontName
-- @param fontSize
-- @param color
--
-- @overload
-- @param table Properties
function Display.TextBox(str, width, height, fontName, fontSize, color)
local properties
if type(str) == 'table' then
properties = str
str = properties['text']
width = properties['width']
height = properties['height']
fontName = properties['fontName']
fontSize = properties['fontSize']
color = properties['color']
properties['text'] = nil
properties['width'] = nil
properties['height'] = nil
properties['fontName'] = nil
properties['fontSize'] = nil
properties['color'] = nil
end
local label = Label(str, width, height, fontName, fontSize)
if color then
label:setColor(unpack(color))
end
if properties then
PropertyUtils.setProperties(label, properties, true)
end
return label
end
---
-- Create Label. The only difference with text box that label cannot have pages.
-- Label will try to use smaller font size until every glyph is fitted into bounds.
-- @param str string
-- @param
function Display.Label(str, width, height, fontName, fontSize, color)
local label = Display.TextBox(str, width, height, fontName, fontSize, color)
Display.fitLabelText(label)
return label
end
---
-- Try to use smaller font size until all glyphs are visible.
--
-- @param label
-- @param decrement font size decrement. By default is 2
-- @return nil
function Display.fitLabelText(label, decrement)
decrement = decrement or 2
label:forceUpdate()
local style = label:getStyle()
local fontSize = style:getSize()
while label:more() and fontSize > 0 do
fontSize = fontSize - decrement
style:setSize(fontSize)
label:forceUpdate()
end
end
---
-- Create group
-- @param layer
-- @param width
-- @param height
--
-- @override
-- @param table Properties
function Display.Group(layer, width, height)
local properties
if layer and not layer.__class then
properties = layer
layer = properties['layer']
width = properties['width']
height = properties['height']
properties['layer'] = nil
properties['width'] = nil
properties['height'] = nil
end
local group = Group(layer, width, height)
if properties then
PropertyUtils.setProperties(group, properties, true)
end
return group
end
-- Expose other factory methods
Display.Layer = Layer
return Display
|
--------------------------------------------------------------------------------
-- Set of global helper functions
--
-- This file is just an example that meant to be changed for specific project.
-- It includes useful factory methods to create rigs.
--------------------------------------------------------------------------------
local Display = {}
local Label = require("core.Label")
local Group = require("core.Group")
local Layer = require("core.Layer")
local PropertyUtils = require("util.PropertyUtils")
---
-- Create MOAIProp with deck set to proper texture file
-- @param fileName Texture name or sprite frame name
-- @param width (option) image width. This will modify prop scale
-- @param height (option) image height. This will modify prop scale
--
-- @overload
-- @param table Properties
function Display.Sprite(fileName, width, height)
local properties
if type(fileName) == 'table' then
properties = fileName
fileName = properties['fileName']
width = properties['width']
height = properties['height']
properties['fileName'] = nil
properties['width'] = nil
properties['height'] = nil
end
local deck
if string.endswith(fileName, ".9.png") then
deck = ResourceMgr:getNineImageDeck(fileName)
else
deck = ResourceMgr:getImageDeck(fileName)
end
if not deck then
local atlas = ResourceMgr:getAtlasName(fileName)
assert(atlas, "Image not found: " .. fileName)
deck = ResourceMgr:getAtlasDeck(atlas)
end
local sprite = MOAIProp.new()
sprite:setDeck(deck)
sprite.deck = deck
sprite:setIndexByName(fileName)
local w, h = sprite:getDims()
local sx = width and width / w or 1
local sy = height and height / h or 1
sprite:setScl(sx, sy, 1)
if properties then
PropertyUtils.setProperties(sprite, properties, true)
end
return sprite
end
---
-- Create Text Box
-- @param str string
-- @param width
-- @param height
-- @param fontName
-- @param fontSize
-- @param color
--
-- @overload
-- @param table Properties
function Display.TextBox(str, width, height, fontName, fontSize, color)
local properties
if type(str) == 'table' then
properties = str
str = properties['text']
width = properties['width']
height = properties['height']
fontName = properties['fontName']
fontSize = properties['fontSize']
color = properties['color']
properties['text'] = nil
properties['width'] = nil
properties['height'] = nil
properties['fontName'] = nil
properties['fontSize'] = nil
properties['color'] = nil
end
local label = Label(str, width, height, fontName, fontSize)
if color then
label:setColor(unpack(color))
end
if properties then
PropertyUtils.setProperties(label, properties, true)
end
return label
end
---
-- Create Label. The only difference with text box that label cannot have pages.
-- Label will try to use smaller font size until every glyph is fitted into bounds.
-- @param str string
-- @param
function Display.Label(str, width, height, fontName, fontSize, color)
local label = Display.TextBox(str, width, height, fontName, fontSize, color)
Display.fitLabelText(label)
return label
end
---
-- Try to use smaller font size until all glyphs are visible.
--
-- @param label
-- @param decrement font size decrement
-- @return nil
function Display.fitLabelText(label, decrement)
decrement = decrement or label.contentScale or 2
label:forceUpdate()
local style = label:getStyle()
local fontSize = style:getSize()
while label:more() and fontSize > 0 do
fontSize = fontSize - decrement
style:setSize(fontSize)
label:forceUpdate()
end
end
---
-- Create group
-- @param layer
-- @param width
-- @param height
--
-- @override
-- @param table Properties
function Display.Group(layer, width, height)
local properties
if layer and not layer.__class then
properties = layer
layer = properties['layer']
width = properties['width']
height = properties['height']
properties['layer'] = nil
properties['width'] = nil
properties['height'] = nil
end
local group = Group(layer, width, height)
if properties then
PropertyUtils.setProperties(group, properties, true)
end
return group
end
-- Expose other factory methods
Display.Layer = Layer
return Display
|
Fix fitLabel method to take into account contentScale
|
Fix fitLabel method to take into account contentScale
|
Lua
|
mit
|
Vavius/moai-framework,Vavius/moai-framework
|
e2b223b3abec696cd5f31cee3c6df3fb8e1b7d30
|
scripts/iPhonePluginLoader.lua
|
scripts/iPhonePluginLoader.lua
|
--[[
return {
{
name = "lib name",
unique = "unique name", -- optional
factory = "factory name", -- optional
nodelete = true, -- optional
level = { 1, 2, 5, 6, etc, }, -- optional
},
}
--]]
local function create_plugin (file, list)
local fstr = "void\ndmz_create_plugins (\n" ..
" dmz::RuntimeContext *context,\n" ..
" dmz::Config &config,\n" ..
" dmz::Config &global,\n" ..
" dmz::PluginContainer &container) {\n\n" ..
" dmz::PluginInfo *info (0);\n" ..
" dmz::Config local;"
print ()
print (fstr)
for _, value in ipairs (list) do
local infoStr = ' info = new dmz::PluginInfo ("' .. value.unique .. '", '
if value.delete then infoStr = infoStr .. "PluginDeleteModeDelete, "
else infoStr = infoStr .. "PluginDeleteModeDoNotDelete, "
end
infoStr = infoStr .. "context, 0);"
if value.level then
for _, level in ipairs (value.level) do
infoStr = infoStr .. "\n info->add_level (" .. level .. ");"
end
end
local lstr = " local.set_config_context (0);\n" ..
" config.lookup_all_config_merged (" ..
'"' .. value.unique .. '", ' .. "local);"
local storeStr = " container.add_plugin (info, " ..
value.factory .. " (*info, local, global));"
print ("")
print (infoStr)
print (lstr)
print (storeStr)
end
print ("}")
end
local function create_extern (file, list)
local istr =
"#include <dmzRuntimeConfig.h>\n"..
"#include <dmzRuntimePlugin.h>\n"..
"#include <dmzRuntimePluginContainer.h>\n"..
"#include <dmzRuntimePluginInfo.h>\n"
print (istr)
print ('extern "C" {')
for _, value in ipairs (list) do
local str = "dmz::Plugin *" .. value.factory ..
" (const dmz::PluginInfo &Info, dmz::Config &local, dmz::Config &global);"
print (str)
end
print ("}")
end
local function validate_list (list)
for _, value in ipairs (list) do
if not value.name then error ("Name not defined") end
if not value.unique then value.unique = value.name end
if not value.factory then value.factory = "create_" .. value.name end
if not value.delete then value.delete = true end
end
end
if type (arg[1]) == "string" then
local list = dofile (arg[1])
if type (list) == "table" then
validate_list (list)
create_extern (nil, list)
create_plugin (nil, list)
end
end
|
--[[
return {
{
name = "lib name",
unique = "unique name", -- optional
factory = "factory name", -- optional
nodelete = true, -- optional
level = { 1, 2, 5, 6, etc, }, -- optional
},
}
--]]
local function create_plugin (file, list)
local fstr = "void\ndmz_create_plugins (\n" ..
" dmz::RuntimeContext *context,\n" ..
" dmz::Config &config,\n" ..
" dmz::Config &global,\n" ..
" dmz::PluginContainer &container) {\n\n" ..
" dmz::PluginInfo *info (0);\n" ..
" dmz::Config local;"
print ()
print (fstr)
for _, value in ipairs (list) do
local infoStr = ' info = new dmz::PluginInfo ("' .. value.unique .. '", '
if value.delete then infoStr = infoStr .. "PluginDeleteModeDelete, "
else infoStr = infoStr .. "PluginDeleteModeDoNotDelete, "
end
infoStr = infoStr .. "context, 0);"
if value.level then
for _, level in ipairs (value.level) do
infoStr = infoStr .. "\n info->add_level (" .. level .. ");"
end
end
local lstr = " local.set_config_context (0);\n" ..
" config.lookup_all_config_merged (" ..
'"' .. value.unique .. '", ' .. "local);"
local storeStr = " container.add_plugin (info, " ..
value.factory .. " (*info, local, global));"
print ("")
print (infoStr)
print (lstr)
print (storeStr)
end
print ("}")
end
local function create_extern (file, list)
local istr =
"#include <dmzRuntimeConfig.h>\n"..
"#include <dmzRuntimePlugin.h>\n"..
"#include <dmzRuntimePluginContainer.h>\n"..
"#include <dmzRuntimePluginInfo.h>\n"
print (istr)
print ('extern "C" {')
for _, value in ipairs (list) do
local str = "dmz::Plugin *" .. value.factory ..
" (const dmz::PluginInfo &Info, dmz::Config &local, dmz::Config &global);"
print (str)
end
print ("}")
end
local function validate_list (list)
for _, value in ipairs (list) do
if not value.name then error ("Name not defined") end
if not value.unique then value.unique = value.name end
if not value.factory then value.factory = "create_" .. value.name end
if not value.delete then value.delete = true end
end
end
if type (arg[1]) == "string" then
local list = dofile (arg[1])
if type (list) == "table" then
validate_list (list)
create_extern (nil, list)
create_plugin (nil, list)
end
else error ("Missing template file")
end
|
small but fix
|
small but fix
|
Lua
|
mit
|
shillcock/lmk,dmzgroup/lmk
|
d4986b45afc9fb5eb75279c1c0222c041b43a35d
|
kong/cmd/vault.lua
|
kong/cmd/vault.lua
|
local kong_global = require "kong.global"
local conf_loader = require "kong.conf_loader"
local pl_path = require "pl.path"
local log = require "kong.cmd.utils.log"
local DB = require "kong.db"
local assert = assert
local error = error
local print = print
local exit = os.exit
local fmt = string.format
local function init_db(args)
-- retrieve default prefix or use given one
log.disable()
local conf = assert(conf_loader(args.conf, {
prefix = args.prefix
}))
log.enable()
if pl_path.exists(conf.kong_env) then
-- load <PREFIX>/kong.conf containing running node's config
conf = assert(conf_loader(conf.kong_env))
end
package.path = conf.lua_package_path .. ";" .. package.path
_G.kong = kong_global.new()
kong_global.init_pdk(_G.kong, conf)
local db = assert(DB.new(conf))
assert(db:init_connector())
assert(db:connect())
assert(db.vaults:load_vault_schemas(conf.loaded_vaults))
_G.kong.db = db
end
local function get(args)
if args.command == "get" then
local reference = args[1]
if not reference then
return error("the 'get' command needs a <reference> argument \nkong vault get <reference>")
end
init_db(args)
local vault = kong.vault
if not vault.is_reference(reference) then
-- assuming short form: <name>/<resource>[/<key>]
reference = fmt("{vault://%s}", reference)
end
local opts, err = vault.parse_reference(reference)
if not opts then
return error(err)
end
local res, err = vault.get(reference)
if err then
return error(err)
end
print(res)
end
end
local function execute(args)
if args.command == "" then
exit(0)
end
if args.command == "get" then
get(args)
end
end
local lapp = [[
Usage: kong vault COMMAND [OPTIONS]
Vault utilities for Kong.
Example usage:
TEST=hello kong vault get env/test
The available commands are:
get <reference> Retrieves a value for <reference>
Options:
]]
return {
lapp = lapp,
execute = execute,
sub_commands = {
get = true,
},
}
|
local kong_global = require "kong.global"
local conf_loader = require "kong.conf_loader"
local pl_path = require "pl.path"
local log = require "kong.cmd.utils.log"
local DB = require "kong.db"
local assert = assert
local error = error
local print = print
local exit = os.exit
local fmt = string.format
local function init_db(args)
-- retrieve default prefix or use given one
log.disable()
local conf = assert(conf_loader(args.conf, {
prefix = args.prefix
}))
log.enable()
if pl_path.exists(conf.kong_env) then
-- load <PREFIX>/kong.conf containing running node's config
conf = assert(conf_loader(conf.kong_env))
end
package.path = conf.lua_package_path .. ";" .. package.path
_G.kong = kong_global.new()
kong_global.init_pdk(_G.kong, conf)
local db = assert(DB.new(conf))
assert(db:init_connector())
assert(db:connect())
assert(db.vaults:load_vault_schemas(conf.loaded_vaults))
_G.kong.db = db
end
local function get(args)
if args.command == "get" then
local reference = args[1]
if not reference then
return error("the 'get' command needs a <reference> argument \nkong vault get <reference>")
end
init_db(args)
local vault = kong.vault
if not vault.is_reference(reference) then
-- assuming short form: <name>/<resource>[/<key>]
reference = fmt("{vault://%s}", reference)
end
local opts, err = vault.parse_reference(reference)
if not opts then
return error(err)
end
local res, err = vault.get(reference)
if err then
return error(err)
end
print(res)
end
end
local function execute(args)
if args.command == "" then
exit(0)
end
if args.command == "get" then
get(args)
end
end
local lapp = [[
Usage: kong vault COMMAND [OPTIONS]
Vault utilities for Kong.
Example usage:
TEST=hello kong vault get env/test
The available commands are:
get <reference> Retrieves a value for <reference>
Options:
-c,--conf (optional string) configuration file
]]
return {
lapp = lapp,
execute = execute,
sub_commands = {
get = true,
},
}
|
fix(cli) add support for `-c`/`--conf` option to `kong vault` command
|
fix(cli) add support for `-c`/`--conf` option to `kong vault` command
### Summary
Adds support for `-c` and `--conf` options to `kong vault` commands.
|
Lua
|
apache-2.0
|
Kong/kong,Kong/kong,Kong/kong
|
c3aa96600b155d05a8a5fa928fb81215508bd17b
|
window_manager/init.lua
|
window_manager/init.lua
|
-- This variable sets how many pixels of empty space should be around the windows
MARGIN = 9
-- The number of pixels between the top of the screen and the top of the grid
TOPGAP = 50
function getWindow()
return hs.window.focusedWindow()
end
function getGrid()
local win = getWindow()
local screen = win:screen()
local max = screen:frame()
-- when using multiple monitors, some screens may start at non-zero x and y coordinates
-- in that case, the starting x and y values on the geometry to define the window need
-- to take into account the absolute x and y values of the top left corner of the screen.
-- max.x and max.y will be the distance in pixels from the top left corner of the primary
-- monitor.
local geo = hs.geometry.new(max.x, max.y + TOPGAP, max.w, max.h - TOPGAP)
local margin = hs.geometry(nil, nil, MARGIN, MARGIN)
return hs.grid.setGrid('4x4', screen, geo).setMargins(margin)
end
function getContext()
local win = getWindow()
local f = win:frame()
local screen = win:screen()
local max = screen:frame()
return win, f, screen, max, getGrid()
end
function nextScreen()
local win = getWindow()
local f = win:frame()
local screen = win:screen():next()
local max = screen:frame()
f.x = max.x
f.y = max.y
win:setFrame(f)
end
function previousScreen()
local win = getWindow()
local f = win:frame()
local screen = win:screen():previous()
local max = screen:frame()
f.x = max.x
f.y = max.y
win:setFrame(f)
end
hs.hotkey.bind({"cmd", "alt"}, "j", function() getGrid().pushWindowLeft() end)
hs.hotkey.bind({"cmd", "alt"}, "k", function() getGrid().pushWindowDown() end)
hs.hotkey.bind({"cmd", "alt"}, "l", function() getGrid().pushWindowUp() end)
hs.hotkey.bind({"cmd", "alt"}, ";", function() getGrid().pushWindowRight() end)
hs.hotkey.bind({"cmd", "alt"}, "m", function() getGrid().resizeWindowThinner() end)
hs.hotkey.bind({"cmd", "alt"}, ",", function() getGrid().resizeWindowTaller() end)
hs.hotkey.bind({"cmd", "alt"}, ".", function() getGrid().resizeWindowShorter() end)
hs.hotkey.bind({"cmd", "alt"}, "/", function() getGrid().resizeWindowWider() end)
--left half
hs.hotkey.bind({"cmd"}, "1", function()
local win, f, screen, max, grid = getContext()
grid.set(win, hs.geometry.new(0, 0, 2, 4))
end)
--right half
hs.hotkey.bind({"cmd"}, "2", function()
local win, f, screen, max, grid = getContext()
grid.set(win, hs.geometry.new(2, 0, 2, 4))
end)
--full screen
hs.hotkey.bind({"cmd"}, "3", function()
-- defaults to the focused window
getGrid().maximizeWindow()
end)
--left-quarter
hs.hotkey.bind({"cmd", "alt"}, "1", function()
local win, f, screen, max, grid = getContext()
grid.set(win, hs.geometry.new(0, 0, 1, 4))
end)
--middle-left-quarter
hs.hotkey.bind({"cmd", "alt"}, "2", function()
local win, f, screen, max, grid = getContext()
grid.set(win, hs.geometry.new(1, 0, 1, 4))
end)
--middle-right-quarter
hs.hotkey.bind({"cmd", "alt"}, "3", function()
local win, f, screen, max, grid = getContext()
grid.set(win, hs.geometry.new(2, 0, 1, 4))
end)
--right-quarter
hs.hotkey.bind({"cmd", "alt"}, "4", function()
local win, f, screen, max, grid = getContext()
grid.set(win, hs.geometry.new(3, 0, 1, 4))
end)
--top left
hs.hotkey.bind({"cmd", "alt"}, "Q", function()
local win, f, screen, max, grid = getContext()
grid.set(win, hs.geometry.new(0, 0, 2, 2))
end)
--bottom left
hs.hotkey.bind({"cmd", "alt"}, "A", function()
local win, f, screen, max, grid = getContext()
grid.set(win, hs.geometry.new(0, 2, 2, 2))
end)
--top right
hs.hotkey.bind({"cmd", "alt"}, "W", function()
local win, f, screen, max, grid = getContext()
grid.set(win, hs.geometry.new(2, 0, 2, 2))
end)
--bottom right
hs.hotkey.bind({"cmd", "alt"}, "S", function()
local win, f, screen, max, grid = getContext()
grid.set(win, hs.geometry.new(2, 2, 2, 2))
end)
--bottom
hs.hotkey.bind({"cmd", "alt"}, "B", function()
local win, f, screen, max, grid = getContext()
grid.set(win, hs.geometry.new(0, 2, 4, 2))
end)
--top
hs.hotkey.bind({"cmd", "alt"}, "T", function()
local win, f, screen, max, grid = getContext()
grid.set(win, hs.geometry.new(0, 0, 4, 2))
end)
--next screen
hs.hotkey.bind({"cmd"}, "0", function()
nextScreen()
end)
--previous screen
hs.hotkey.bind({"cmd"}, "9", function()
previousScreen()
end)
-- grid
-- bound to the hotkeys: cmd + alt + \
hs.hotkey.bind({"cmd", "alt"}, "\\", function()
local grid = getGrid()
grid.ui.highlightColor = {0.552, 0.643, 0.776, 0.4}
grid.ui.highlightStrokeColor = {0.552, 0.643, 0.776, 0.8}
grid.ui.textSize = 80
grid.show()
end)
--auto reload the configuration file on save
function reloadConfig(files)
doReload = false
for _,file in pairs(files) do
if file:sub(-4) == ".lua" then
doReload = true
end
end
if doReload then
hs.reload()
end
end
myWatcher = hs.pathwatcher.new(os.getenv("HOME") .. "/.hammerspoon/", reloadConfig):start()
hs.alert.show("Config loaded")
|
-- This variable sets how many pixels of empty space should be around the windows
MARGIN = 9
-- The number of pixels between the top of the screen and the top of the grid
TOPGAP = 50
function getActiveWindow()
return hs.window.focusedWindow()
end
function getGrid()
local win = getActiveWindow()
local screen = win:screen()
local max = screen:frame()
-- when using multiple monitors, some screens may start at non-zero x and y coordinates
-- in that case, the starting x and y values on the geometry to define the window need
-- to take into account the absolute x and y values of the top left corner of the screen.
-- max.x and max.y will be the distance in pixels from the top left corner of the primary
-- monitor.
local geo = hs.geometry.new(max.x, max.y + TOPGAP, max.w, max.h - TOPGAP)
local margin = hs.geometry(nil, nil, MARGIN, MARGIN)
return hs.grid.setGrid('4x4', screen, geo).setMargins(margin)
end
function getContext()
local win = getActiveWindow()
local f = win:frame()
local screen = win:screen()
local max = screen:frame()
return win, f, screen, max, getGrid()
end
function moveWindowOneScreenRight()
getActiveWindow():moveOneScreenEast(false, false, 0.4)
end
function moveWindowOneScreenLeft()
getActiveWindow():moveOneScreenWest(false, false, 0.4)
end
hs.hotkey.bind({"cmd", "alt"}, "j", function() getGrid().pushWindowLeft() end)
hs.hotkey.bind({"cmd", "alt"}, "k", function() getGrid().pushWindowDown() end)
hs.hotkey.bind({"cmd", "alt"}, "l", function() getGrid().pushWindowUp() end)
hs.hotkey.bind({"cmd", "alt"}, ";", function() getGrid().pushWindowRight() end)
hs.hotkey.bind({"cmd", "alt"}, "m", function() getGrid().resizeWindowThinner() end)
hs.hotkey.bind({"cmd", "alt"}, ",", function() getGrid().resizeWindowTaller() end)
hs.hotkey.bind({"cmd", "alt"}, ".", function() getGrid().resizeWindowShorter() end)
hs.hotkey.bind({"cmd", "alt"}, "/", function() getGrid().resizeWindowWider() end)
--left half
hs.hotkey.bind({"cmd"}, "1", function()
local win, f, screen, max, grid = getContext()
grid.set(win, hs.geometry.new(0, 0, 2, 4))
end)
--right half
hs.hotkey.bind({"cmd"}, "2", function()
local win, f, screen, max, grid = getContext()
grid.set(win, hs.geometry.new(2, 0, 2, 4))
end)
--full screen
hs.hotkey.bind({"cmd"}, "3", function()
-- defaults to the focused window
getGrid().maximizeWindow()
end)
--left-quarter
hs.hotkey.bind({"cmd", "alt"}, "1", function()
local win, f, screen, max, grid = getContext()
grid.set(win, hs.geometry.new(0, 0, 1, 4))
end)
--middle-left-quarter
hs.hotkey.bind({"cmd", "alt"}, "2", function()
local win, f, screen, max, grid = getContext()
grid.set(win, hs.geometry.new(1, 0, 1, 4))
end)
--middle-right-quarter
hs.hotkey.bind({"cmd", "alt"}, "3", function()
local win, f, screen, max, grid = getContext()
grid.set(win, hs.geometry.new(2, 0, 1, 4))
end)
--right-quarter
hs.hotkey.bind({"cmd", "alt"}, "4", function()
local win, f, screen, max, grid = getContext()
grid.set(win, hs.geometry.new(3, 0, 1, 4))
end)
--top left
hs.hotkey.bind({"cmd", "alt"}, "Q", function()
local win, f, screen, max, grid = getContext()
grid.set(win, hs.geometry.new(0, 0, 2, 2))
end)
--bottom left
hs.hotkey.bind({"cmd", "alt"}, "A", function()
local win, f, screen, max, grid = getContext()
grid.set(win, hs.geometry.new(0, 2, 2, 2))
end)
--top right
hs.hotkey.bind({"cmd", "alt"}, "W", function()
local win, f, screen, max, grid = getContext()
grid.set(win, hs.geometry.new(2, 0, 2, 2))
end)
--bottom right
hs.hotkey.bind({"cmd", "alt"}, "S", function()
local win, f, screen, max, grid = getContext()
grid.set(win, hs.geometry.new(2, 2, 2, 2))
end)
--bottom
hs.hotkey.bind({"cmd", "alt"}, "B", function()
local win, f, screen, max, grid = getContext()
grid.set(win, hs.geometry.new(0, 2, 4, 2))
end)
--top
hs.hotkey.bind({"cmd", "alt"}, "T", function()
local win, f, screen, max, grid = getContext()
grid.set(win, hs.geometry.new(0, 0, 4, 2))
end)
-- move window to the screen on the right
hs.hotkey.bind({"cmd"}, "0", function()
moveWindowOneScreenRight()
end)
-- move window to the screen on the left
hs.hotkey.bind({"cmd"}, "9", function()
moveWindowOneScreenLeft()
end)
-- grid
-- bound to the hotkeys: cmd + alt + \
hs.hotkey.bind({"cmd", "alt"}, "\\", function()
local grid = getGrid()
grid.ui.highlightColor = {0.552, 0.643, 0.776, 0.4}
grid.ui.highlightStrokeColor = {0.552, 0.643, 0.776, 0.8}
grid.ui.textSize = 80
grid.show()
end)
--auto reload the configuration file on save
function reloadConfig(files)
doReload = false
for _,file in pairs(files) do
if file:sub(-4) == ".lua" then
doReload = true
end
end
if doReload then
hs.reload()
end
end
myWatcher = hs.pathwatcher.new(os.getenv("HOME") .. "/.hammerspoon/", reloadConfig):start()
hs.alert.show("Config loaded")
|
fix: next/previous window command inconsistency
|
fix: next/previous window command inconsistency
The old method of getting the next and previous screen was inconsistent
about the order of the screens. Even if the screen layout remained
consistent, hammerspoon would reverse the next/previous order about
50% of the time after restarting the computer or reconnecting the
computer to external monitors. This new method is consistent and
more specific, moving screens left or right instead of next or previous.
|
Lua
|
mit
|
ConnorChristensen/ExtensionScripts,ConnorChristensen/ExtensionScripts,ConnorChristensen/ExtensionScripts
|
9f178ecc09b16d7366bc7dfae46915b7e62e6fd4
|
kong/dao/error.lua
|
kong/dao/error.lua
|
-- DAOs need more specific error objects, specifying if the error is due
-- to the schema, the database connection, a constraint violation etc, so the
-- caller can take actions based on the error type.
--
-- We will test this object and might create a KongError class too
-- if successful and needed.
--
-- Ideally, those errors could switch from having a type, to having an error
-- code.
--
-- @author thibaultcha
local error_mt = {}
error_mt.__index = error_mt
-- Returned the `message` property as a string if it is already one,
-- for format it as a string if it is a table.
-- @return the formatted `message` property
function error_mt:print_message()
if type(self.message) == "string" then
return self.message
elseif type(self.message) == "table" then
local errors = {}
for k, v in pairs(self.message) do
table.insert(errors, k..": "..v)
end
return table.concat(errors, " | ")
end
end
-- Allow a DaoError to be printed
-- @return the formatted `message` property
function error_mt:__tostring()
return self:print_message()
end
-- Allow a DaoError to be concatenated
-- @return the formatted and concatenated `message` property
function error_mt.__concat(a, b)
if getmetatable(a) == error_mt then
return a:print_message() .. b
else
return a .. b:print_message()
end
end
local mt = {
-- Constructor
-- @param err A raw error, typically returned by lua-resty-cassandra (string)
-- @param type An error type from constants, will be set as a key with 'true'
-- value on the returned error for fast comparison when dealing
-- with this error.
-- @return A DaoError with the error_mt metatable
__call = function (self, err, type)
if err == nil then
return nil
end
local t = {
[type] = true,
message = err
}
return setmetatable(t, error_mt)
end
}
return setmetatable({}, mt)
|
-- DAOs need more specific error objects, specifying if the error is due
-- to the schema, the database connection, a constraint violation etc, so the
-- caller can take actions based on the error type.
--
-- We will test this object and might create a KongError class too
-- if successful and needed.
--
-- Ideally, those errors could switch from having a type, to having an error
-- code.
--
-- @author thibaultcha
local error_mt = {}
error_mt.__index = error_mt
-- Returned the `message` property as a string if it is already one,
-- for format it as a string if it is a table.
-- @return the formatted `message` property
function error_mt:print_message()
if type(self.message) == "string" then
return self.message
elseif type(self.message) == "table" then
local errors = {}
for k, v in pairs(self.message) do
table.insert(errors, k..": "..v)
end
return table.concat(errors, " | ")
end
end
-- Allow a DaoError to be printed
-- @return the formatted `message` property
function error_mt:__tostring()
return self:print_message()
end
-- Allow a DaoError to be concatenated
-- @return the formatted and concatenated `message` property
function error_mt.__concat(a, b)
if getmetatable(a) == error_mt then
return a:print_message() .. b
else
return a .. b:print_message()
end
end
local mt = {
-- Constructor
-- @param err A raw error, typically returned by lua-resty-cassandra (string)
-- @param err_type An error type from constants, will be set as a key with 'true'
-- value on the returned error for fast comparison when dealing
-- with this error.
-- @return A DaoError with the error_mt metatable
__call = function (self, err, err_type)
if err == nil then
return nil
end
local t = {
[err_type] = true,
message = tostring(err)
}
return setmetatable(t, error_mt)
end
}
return setmetatable({}, mt)
|
fix: comply to resty-cassandra's new errors
|
fix: comply to resty-cassandra's new errors
|
Lua
|
apache-2.0
|
peterayeni/kong,puug/kong,vmercierfr/kong,bbalu/kong,Skyscanner/kong,skynet/kong,ropik/kong,chourobin/kong,ChristopherBiscardi/kong,sbuettner/kong,AnsonSmith/kong,wakermahmud/kong,paritoshmmmec/kong
|
5b01af319790fc80a461b79a93a364c1c0ac470c
|
OS/DiskOS/Programs/rm.lua
|
OS/DiskOS/Programs/rm.lua
|
--Remove/delete a specific file
local args = {...} --Get the arguments passed to this program
if #args < 1 or args[1] == "-?" then
printUsage(
"rm <files/directory>","Deletes the file/directory"
)
return
end
local tar = table.concat(args," ") --The path may include whitespaces
local term = require("C://terminal")
local function index(path,notfirst)
color(9)
if fs.isFile(path) then print("Deleted "..path) fs.remove(path) return end
local items = fs.directoryItems(path)
for k, item in ipairs(items) do
if fs.isDirectory(path..item) then
print("Entering directory "..path..item.."/") pullEvent()
index(path..item.."/",true)
else
print("Deleted "..path..item) pullEvent()
fs.remove(path..item)
end
end
fs.remove(path)
if not notfirst then color(11) print("Deleted File/s successfully") end
return true
end
local tarExists; tar, tarExists = term.resolve(tar)
if not tarExists then color(8) print("Path doesn't exists") return end
index(tar)
|
--Remove/delete a specific file
local args = {...} --Get the arguments passed to this program
if #args < 1 or args[1] == "-?" then
printUsage(
"rm <files/directory>","Deletes the file/directory"
)
return
end
local tar = table.concat(args," ") --The path may include whitespaces
local term = require("C://terminal")
local function index(path,notfirst)
color(9)
if fs.isFile(path) then print("Deleted "..path) fs.remove(path) return end
local items = fs.directoryItems(path)
for k, item in ipairs(items) do
if fs.isDirectory(path..item) then
print("Entering directory "..path..item.."/") pullEvent()
index(path..item.."/",true)
else
print("Deleted "..path..item) pullEvent()
fs.remove(path..item)
end
end
fs.remove(path)
if not notfirst then color(11) print("Deleted File/s successfully") end
return true
end
tar = term.resolve(tar)
if not fs.exists(tar) then color(8) print("Path doesn't exists") return end
index(tar)
|
Bugfix
|
Bugfix
|
Lua
|
mit
|
RamiLego4Game/LIKO-12
|
f8495287fe917cd47aee2d9a19a025c4af02eed0
|
Peripherals/FDD/init.lua
|
Peripherals/FDD/init.lua
|
local perpath = select(1,...) --The path to the FDD folder
local bit = require("bit")
local band, bor, lshift, rshift = bit.band, bit.bor, bit.lshift, bit.rshift
return function(config)
local GPUKit = config.GPUKit or error("The FDD peripheral requires the GPUKit")
local RAM = config.RAM or error("The FDD peripheral requires the RAM peripheral")
local FIMG --The floppy disk image
local DiskSize = config.DiskSize or 64*1024 --The floppy disk size
local FRAMAddress = config.FRAMAddress or 0 --The floppy ram start address
--The color palette
local ColorSet = {}
for i=0,15 do
local r,g,b,a = unpack(GPUKit._ColorSet[i])
r,g,b,a = band(r,252), band(g,252), band(b,252), 252
ColorSet[i] = {r,g,b,a}
ColorSet[r*10^9 + g*10^6 + b*10^3 + a] = i
end
--The label image
local LabelImage = GPUKit.LabelImage
local LabelX, LabelY, LabelW, LabelH = 32,120, GPUKit._LIKO_W, GPUKit._LIKO_H
--DiskCleanupMapper
local function _CleanUpDisk(x,y,r,g,b,a)
return band(r,252), band(g,252), band(b,252), band(a,252)
end
--DiskWriteMapper
local WritePos = 0
local function _WriteDisk(x,y,r,g,b,a)
local byte = select(2,RAM.peek(FRAMAddress+WritePos))
r = bor(r, rshift( band(byte,192) ,6) )
g = bor(g, rshift( band(byte,48 ) ,4) )
b = bor(b, rshift( band(byte,12 ) ,2) )
a = bor(a, band(byte,3 ) )
WritePos = (WritePos + 1) % (DiskSize)
return r, g, b, a
end
--DiskReadMapper
local ReadPos = 0
local function _ReadDisk(x,y,r,g,b,a)
r = lshift(r,6)
g = lshift(g,4)
b = lshift(b,2)
local byte = bor(r,g,b,a)
RAM.poke(FRAMAddress+ReadPos,byte)
ReadPos = (ReadPos + 1) % (DiskSize)
return r, g, b, a
end
--LabelDrawMapper
local function _DrawLabel(x,y,r,g,b,a)
FIMG:setPixel(LabelX+x,LabelY+y,unpack(ColorSet[r]))
return r,g,b,a
end
--LabelScanMapper
local function _ScanLabel(x,y,r,g,b,a)
local r,g,b,a = band(r,252), band(g,252), band(b,252), band(a,252)
local code = r*10^9 + g*10^6 + b*10^3 + a
local id = ColorSet[code] or 0
LabelImage:setPixel(x,y,id,0,0,255)
end
--The API starts here--
local fapi = {}
--Create a new floppy disk and mount it
--tname -> template name, without the .png extension
function fapi.newDisk(tname)
local tname = tname or "Disk"
if type(tname) ~= "string" then return false, "Disk template name must be a string or a nil, provided: "..type(tname) end
if not love.filesystem.exists(perpath..tname..".png") then return false, "Disk template '"..tname.."' doesn't exist !" end
FIMG = love.image.newImageData(perpath..tname..".png")
return true --Done Successfully
end
function fapi.exportDisk()
--Clean up any already existing data on the disk.
FIMG:mapPixel(_CleanUpDisk)
--Write the label image
LabelImage:mapPixel(_DrawLabel)
--Write new data
FIMG:mapPixel(_WriteDisk)
return true, FIMG:encode("png"):getString()
end
function fapi.importDisk(data)
if type(data) ~= "string" then return false,"Data must be a string, provided: "..type(data) end
--Scan the label image
for y=LabelY,LabelY+LabelH-1 do
for x=LabelX,LabelX+LabelW-1 do
_ScanLabel(x-LabelX,y-LabelH,FIMG:getPixel(x,y))
end
end
--Read the data
FIMG:mapPixel(_ReadDisk)
return true --Done successfully
end
--Initialize with the default disk
fapi.newDisk()
return fapi
end
|
local perpath = select(1,...) --The path to the FDD folder
local bit = require("bit")
local band, bor, lshift, rshift = bit.band, bit.bor, bit.lshift, bit.rshift
local function exe(ok,err,...)
if ok then
return err,...
else
return error(err or "NULL")
end
end
return function(config)
local GPUKit = config.GPUKit or error("The FDD peripheral requires the GPUKit")
local RAM = config.RAM or error("The FDD peripheral requires the RAM peripheral")
local FIMG --The floppy disk image
local DiskSize = config.DiskSize or 64*1024 --The floppy disk size
local FRAMAddress = config.FRAMAddress or 0 --The floppy ram start address
--The color palette
local ColorSet = {}
for i=0,15 do
local r,g,b,a = unpack(GPUKit._ColorSet[i])
r,g,b,a = band(r,252), band(g,252), band(b,252), 252
ColorSet[i] = {r,g,b,a}
ColorSet[r*10^9 + g*10^6 + b*10^3 + a] = i
end
--The label image
local LabelImage = GPUKit.LabelImage
local LabelX, LabelY, LabelW, LabelH = 32,120, GPUKit._LIKO_W, GPUKit._LIKO_H
--DiskCleanupMapper
local function _CleanUpDisk(x,y,r,g,b,a)
return band(r,252), band(g,252), band(b,252), band(a,252)
end
--DiskWriteMapper
local WritePos = 0
local function _WriteDisk(x,y,r,g,b,a)
local byte = exe(RAM.peek(FRAMAddress+WritePos))
r = bor(r, band( rshift(byte ,6), 3) )
g = bor(g, band( rshift(byte ,4), 3) )
b = bor(b, band( rshift(byte ,2), 3) )
a = bor(a, band(byte,3))
WritePos = (WritePos + 1) % (DiskSize)
return r, g, b, a
end
--DiskReadMapper
local ReadPos = 0
local function _ReadDisk(x,y,r,g,b,a)
local r2 = lshift( band(r, 3), 6)
local g2 = lshift( band(g, 3), 4)
local b2 = lshift( band(b, 3), 2)
local a2 = band(a, 3)
local byte = bor(r2,g2,b2,a2)
RAM.poke(FRAMAddress+ReadPos,byte)
ReadPos = (ReadPos + 1) % (DiskSize)
return r, g, b, a
end
--LabelDrawMapper
local function _DrawLabel(x,y,r,g,b,a)
FIMG:setPixel(LabelX+x,LabelY+y,unpack(ColorSet[r]))
return r,g,b,a
end
--LabelScanMapper
local function _ScanLabel(x,y,r,g,b,a)
local r,g,b,a = band(r,252), band(g,252), band(b,252), band(a,252)
local code = r*10^9 + g*10^6 + b*10^3 + a
local id = ColorSet[code] or 0
LabelImage:setPixel(x,y,id,0,0,255)
end
--The API starts here--
local fapi = {}
--Create a new floppy disk and mount it
--tname -> template name, without the .png extension
function fapi.newDisk(tname)
local tname = tname or "Disk"
if type(tname) ~= "string" then return false, "Disk template name must be a string or a nil, provided: "..type(tname) end
if not love.filesystem.exists(perpath..tname..".png") then return false, "Disk template '"..tname.."' doesn't exist !" end
FIMG = love.image.newImageData(perpath..tname..".png")
return true --Done Successfully
end
function fapi.exportDisk()
--Clean up any already existing data on the disk.
FIMG:mapPixel(_CleanUpDisk)
--Write the label image
LabelImage:mapPixel(_DrawLabel)
--Write new data
FIMG:mapPixel(_WriteDisk)
return true, FIMG:encode("png"):getString()
end
function fapi.importDisk(data)
if type(data) ~= "string" then return false,"Data must be a string, provided: "..type(data) end
FIMG = love.image.newImageData(love.filesystem.newFileData(data,"image.png"))
--Scan the label image
for y=LabelY,LabelY+LabelH-1 do
for x=LabelX,LabelX+LabelW-1 do
_ScanLabel(x-LabelX,y-LabelY,FIMG:getPixel(x,y))
end
end
--Read the data
FIMG:mapPixel(_ReadDisk)
return true --Done successfully
end
--Initialize with the default disk
fapi.newDisk()
return fapi
end
|
Got it to work after a lot of fixes
|
Got it to work after a lot of fixes
|
Lua
|
mit
|
RamiLego4Game/LIKO-12
|
166f7b6174251c684df3f30f6a3e4920c637d561
|
util/pubsub.lua
|
util/pubsub.lua
|
module("pubsub", package.seeall);
local service = {};
local service_mt = { __index = service };
local default_config = {
broadcaster = function () end;
get_affiliation = function () end;
capabilities = {};
};
function new(config)
config = config or {};
return setmetatable({
config = setmetatable(config, { __index = default_config });
affiliations = {};
nodes = {};
}, service_mt);
end
function service:jids_equal(jid1, jid2)
local normalize = self.config.normalize_jid;
return normalize(jid1) == normalize(jid2);
end
function service:may(node, actor, action)
if actor == true then return true; end
local node_obj = self.nodes[node];
local node_aff = node_obj and node_obj.affiliations[actor];
local service_aff = self.affiliations[actor]
or self.config.get_affiliation(actor, node, action)
or "none";
local node_capabilities = node_obj and node_obj.capabilities;
local service_capabilities = self.config.capabilities;
-- Check if node allows/forbids it
if node_capabilities then
local caps = node_capabilities[node_aff or service_aff];
if caps then
local can = caps[action];
if can ~= nil then
return can;
end
end
end
-- Check service-wide capabilities instead
local caps = service_capabilities[node_aff or service_aff];
if caps then
local can = caps[action];
if can ~= nil then
return can;
end
end
return false;
end
function service:set_affiliation(node, actor, jid, affiliation)
-- Access checking
if not self:may(node, actor, "set_affiliation") then
return false, "forbidden";
end
--
local node_obj = self.nodes[node];
if not node_obj then
return false, "item-not-found";
end
node_obj.affiliations[jid] = affiliation;
local _, jid_sub = self:get_subscription(node, nil, jid);
if not jid_sub and not self:may(node, jid, "be_unsubscribed") then
local ok, err = self:add_subscription(node, nil, jid);
if not ok then
return ok, err;
end
elseif jid_sub and not self:may(node, jid, "be_subscribed") then
local ok, err = self:add_subscription(node, nil, jid);
if not ok then
return ok, err;
end
end
return true;
end
function service:add_subscription(node, actor, jid, options)
-- Access checking
local cap;
if jid == actor or self:jids_equal(actor, jid) then
cap = "subscribe";
else
cap = "subscribe_other";
end
if not self:may(node, actor, cap) then
return false, "forbidden";
end
if not self:may(node, jid, "be_subscribed") then
return false, "forbidden";
end
--
local node_obj = self.nodes[node];
if not node_obj then
if not self.config.autocreate_on_subscribe then
return false, "item-not-found";
else
local ok, err = self:create(node, actor);
if not ok then
return ok, err;
end
end
end
node_obj.subscribers[jid] = options or true;
return true;
end
function service:remove_subscription(node, actor, jid)
-- Access checking
local cap;
if jid == actor or self:jids_equal(actor, jid) then
cap = "unsubscribe";
else
cap = "unsubscribe_other";
end
if not self:may(node, actor, cap) then
return false, "forbidden";
end
if not self:may(node, jid, "be_unsubscribed") then
return false, "forbidden";
end
--
local node_obj = self.nodes[node];
if not node_obj then
return false, "item-not-found";
end
if not node_obj.subscribers[jid] then
return false, "not-subscribed";
end
node_obj.subscribers[jid] = nil;
return true;
end
function service:get_subscription(node, actor, jid)
-- Access checking
local cap;
if jid == actor or self:jids_equal(actor, jid) then
cap = "get_subscription";
else
cap = "get_subscription_other";
end
if not self:may(node, actor, cap) then
return false, "forbidden";
end
--
local node_obj = self.nodes[node];
if node_obj then
return true, node_obj.subscribers[jid];
end
end
function service:create(node, actor)
-- Access checking
if not self:may(node, actor, "create") then
return false, "forbidden";
end
--
if self.nodes[node] then
return false, "conflict";
end
self.nodes[node] = {
name = node;
subscribers = {};
config = {};
data = {};
affiliations = {};
};
local ok, err = self:set_affiliation(node, true, actor, "owner");
if not ok then
self.nodes[node] = nil;
end
return ok, err;
end
function service:publish(node, actor, id, item)
-- Access checking
if not self:may(node, actor, "publish") then
return false, "forbidden";
end
--
local node_obj = self.nodes[node];
if not node_obj then
if not self.config.autocreate_on_publish then
return false, "item-not-found";
end
local ok, err = self:create(node, actor);
if not ok then
return ok, err;
end
node_obj = self.nodes[node];
end
node_obj.data[id] = item;
self.config.broadcaster(node, node_obj.subscribers, item);
return true;
end
function service:retract(node, actor, id, retract)
-- Access checking
if not self:may(node, actor, "retract") then
return false, "forbidden";
end
--
local node_obj = self.nodes[node];
if (not node_obj) or (not node_obj.data[id]) then
return false, "item-not-found";
end
node_obj.data[id] = nil;
if retract then
self.config.broadcaster(node, node_obj.subscribers, retract);
end
return true
end
function service:get_items(node, actor, id)
-- Access checking
if not self:may(node, actor, "get_items") then
return false, "forbidden";
end
--
local node_obj = self.nodes[node];
if not node_obj then
return false, "item-not-found";
end
if id then -- Restrict results to a single specific item
return true, { [id] = node_obj.data[id] };
else
return true, node_obj.data;
end
end
function service:get_nodes(actor)
-- Access checking
if not self:may(nil, actor, "get_nodes") then
return false, "forbidden";
end
--
return true, self.nodes;
end
-- Access models only affect 'none' affiliation caps, service/default access level...
function service:set_node_capabilities(node, actor, capabilities)
-- Access checking
if not self:may(node, actor, "configure") then
return false, "forbidden";
end
--
local node_obj = self.nodes[node];
if not node_obj then
return false, "item-not-found";
end
node_obj.capabilities = capabilities;
return true;
end
return _M;
|
module("pubsub", package.seeall);
local service = {};
local service_mt = { __index = service };
local default_config = {
broadcaster = function () end;
get_affiliation = function () end;
capabilities = {};
};
function new(config)
config = config or {};
return setmetatable({
config = setmetatable(config, { __index = default_config });
affiliations = {};
nodes = {};
}, service_mt);
end
function service:jids_equal(jid1, jid2)
local normalize = self.config.normalize_jid;
return normalize(jid1) == normalize(jid2);
end
function service:may(node, actor, action)
if actor == true then return true; end
local node_obj = self.nodes[node];
local node_aff = node_obj and node_obj.affiliations[actor];
local service_aff = self.affiliations[actor]
or self.config.get_affiliation(actor, node, action)
or "none";
local node_capabilities = node_obj and node_obj.capabilities;
local service_capabilities = self.config.capabilities;
-- Check if node allows/forbids it
if node_capabilities then
local caps = node_capabilities[node_aff or service_aff];
if caps then
local can = caps[action];
if can ~= nil then
return can;
end
end
end
-- Check service-wide capabilities instead
local caps = service_capabilities[node_aff or service_aff];
if caps then
local can = caps[action];
if can ~= nil then
return can;
end
end
return false;
end
function service:set_affiliation(node, actor, jid, affiliation)
-- Access checking
if not self:may(node, actor, "set_affiliation") then
return false, "forbidden";
end
--
local node_obj = self.nodes[node];
if not node_obj then
return false, "item-not-found";
end
node_obj.affiliations[jid] = affiliation;
local _, jid_sub = self:get_subscription(node, nil, jid);
if not jid_sub and not self:may(node, jid, "be_unsubscribed") then
local ok, err = self:add_subscription(node, nil, jid);
if not ok then
return ok, err;
end
elseif jid_sub and not self:may(node, jid, "be_subscribed") then
local ok, err = self:add_subscription(node, nil, jid);
if not ok then
return ok, err;
end
end
return true;
end
function service:add_subscription(node, actor, jid, options)
-- Access checking
local cap;
if jid == actor or self:jids_equal(actor, jid) then
cap = "subscribe";
else
cap = "subscribe_other";
end
if not self:may(node, actor, cap) then
return false, "forbidden";
end
if not self:may(node, jid, "be_subscribed") then
return false, "forbidden";
end
--
local node_obj = self.nodes[node];
if not node_obj then
if not self.config.autocreate_on_subscribe then
return false, "item-not-found";
else
local ok, err = self:create(node, actor);
if not ok then
return ok, err;
end
node_obj = self.nodes[node];
end
end
node_obj.subscribers[jid] = options or true;
return true;
end
function service:remove_subscription(node, actor, jid)
-- Access checking
local cap;
if jid == actor or self:jids_equal(actor, jid) then
cap = "unsubscribe";
else
cap = "unsubscribe_other";
end
if not self:may(node, actor, cap) then
return false, "forbidden";
end
if not self:may(node, jid, "be_unsubscribed") then
return false, "forbidden";
end
--
local node_obj = self.nodes[node];
if not node_obj then
return false, "item-not-found";
end
if not node_obj.subscribers[jid] then
return false, "not-subscribed";
end
node_obj.subscribers[jid] = nil;
return true;
end
function service:get_subscription(node, actor, jid)
-- Access checking
local cap;
if jid == actor or self:jids_equal(actor, jid) then
cap = "get_subscription";
else
cap = "get_subscription_other";
end
if not self:may(node, actor, cap) then
return false, "forbidden";
end
--
local node_obj = self.nodes[node];
if node_obj then
return true, node_obj.subscribers[jid];
end
end
function service:create(node, actor)
-- Access checking
if not self:may(node, actor, "create") then
return false, "forbidden";
end
--
if self.nodes[node] then
return false, "conflict";
end
self.nodes[node] = {
name = node;
subscribers = {};
config = {};
data = {};
affiliations = {};
};
local ok, err = self:set_affiliation(node, true, actor, "owner");
if not ok then
self.nodes[node] = nil;
end
return ok, err;
end
function service:publish(node, actor, id, item)
-- Access checking
if not self:may(node, actor, "publish") then
return false, "forbidden";
end
--
local node_obj = self.nodes[node];
if not node_obj then
if not self.config.autocreate_on_publish then
return false, "item-not-found";
end
local ok, err = self:create(node, actor);
if not ok then
return ok, err;
end
node_obj = self.nodes[node];
end
node_obj.data[id] = item;
self.config.broadcaster(node, node_obj.subscribers, item);
return true;
end
function service:retract(node, actor, id, retract)
-- Access checking
if not self:may(node, actor, "retract") then
return false, "forbidden";
end
--
local node_obj = self.nodes[node];
if (not node_obj) or (not node_obj.data[id]) then
return false, "item-not-found";
end
node_obj.data[id] = nil;
if retract then
self.config.broadcaster(node, node_obj.subscribers, retract);
end
return true
end
function service:get_items(node, actor, id)
-- Access checking
if not self:may(node, actor, "get_items") then
return false, "forbidden";
end
--
local node_obj = self.nodes[node];
if not node_obj then
return false, "item-not-found";
end
if id then -- Restrict results to a single specific item
return true, { [id] = node_obj.data[id] };
else
return true, node_obj.data;
end
end
function service:get_nodes(actor)
-- Access checking
if not self:may(nil, actor, "get_nodes") then
return false, "forbidden";
end
--
return true, self.nodes;
end
-- Access models only affect 'none' affiliation caps, service/default access level...
function service:set_node_capabilities(node, actor, capabilities)
-- Access checking
if not self:may(node, actor, "configure") then
return false, "forbidden";
end
--
local node_obj = self.nodes[node];
if not node_obj then
return false, "item-not-found";
end
node_obj.capabilities = capabilities;
return true;
end
return _M;
|
util.pubsub: Fix traceback when using autocreate-on-subscribe
|
util.pubsub: Fix traceback when using autocreate-on-subscribe
|
Lua
|
mit
|
sarumjanuch/prosody,sarumjanuch/prosody
|
158341f0d4e3db4eef3d9d97a6637f6eae54a70d
|
tests/stft.lua
|
tests/stft.lua
|
require 'audio'
local signal = require 'signal'
require 'gfx.js'
torch.setdefaulttensortype('torch.FloatTensor')
inp = audio.samplevoice():float()
print(#(inp[1]))
stft = signal.stft(inp[1], 1024, 512, 'hamming')
stft = signal.stft(inp[1], 1024, 512)
stft = signal.stft(inp[1], 1024, 512, 'bartlett')
a=os.clock()
stft = signal.stft(inp[1], 1024, 512, 'hann')
print('Time taken for stft from signal package: ' .. os.clock()-a)
a=os.clock()
stft2 = audio.stft(inp, 1024, 'hann', 512)
print('Time taken for stft from audio package: ' .. os.clock()-a)
print(#stft)
-- display magnitude
gfx.image(stft[{{1,100},{1,100},1}])
gfx.image(stft2[{{1,100},{stft2:size(2)-100,stft2:size(2)},1}])
spect = signal.spectrogram(inp[1], 1024, 512)
gfx.image(spect)
|
require 'audio'
require 'image'
local signal = require 'signal'
torch.setdefaulttensortype('torch.FloatTensor')
inp = audio.samplevoice():float():squeeze()
print(#(inp))
stft = signal.stft(inp, 1024, 512, 'hamming')
stft = signal.stft(inp, 1024, 512)
stft = signal.stft(inp, 1024, 512, 'bartlett')
a=os.clock()
stft = signal.stft(inp, 1024, 512, 'hann')
print('Time taken for stft from signal package: ' .. os.clock()-a)
a=os.clock()
stft2 = audio.stft(inp, 1024, 'hann', 512)
print('Time taken for stft from audio package: ' .. os.clock()-a)
print(#stft)
-- display magnitude
image.display(stft[{{1,100},{1,100},1}])
image.display(stft2[{{1,100},{stft2:size(2)-100,stft2:size(2)},1}])
spect = signal.spectrogram(inp, 1024, 512)
image.display(spect)
|
fixes for test
|
fixes for test
|
Lua
|
bsd-3-clause
|
soumith/torch-signal
|
01ab9f469bfacf4d047750bf0e5769238a27876f
|
LogisticsWagons/wagons/requesterwagon.lua
|
LogisticsWagons/wagons/requesterwagon.lua
|
-- passive logistics wagon
local class = require 'middleclass'
RequesterWagon = class('RequesterWagon',ProxyWagon)
function RequesterWagon:initialize(parent,data)
debugLog("RequesterWagon:initialize")
ProxyWagon.initialize(self, parent, data)
self.wagonType = "RequesterWagon"
if(data ~= nil) then
debugLog("Need to check the requester slots")
else
self.requestSlots = {}
end
end
function RequesterWagon:updateWagon(tick)
ProxyWagon.updateWagon(self,tick)
self:updateRequestSlots()
end
function RequesterWagon:updateDataSerialisation()
ProxyWagon.updateDataSerialisation(self)
self.data.requestSlots = self.requestSlots
end
function RequesterWagon:createProxyType()
local proxyType = "lw-logistic-chest-requester-trans"
self:createProxy(proxyType)
end
function RequesterWagon:createProxy(proxyType)
ProxyWagon.createProxy(self,proxyType,true)
self:setRequestSlots()
end
function RequesterWagon:updateRequestSlots()
if self.proxy ~= nil then
local i = 0
local slots = {}
while i < 10 do
i = i + 1
slots[i] = self.proxy.getrequestslot(i)
if slots[i] == nil then
slots[i] = {}
end
end
self.requestSlots = slots
end
end
function RequesterWagon:setRequestSlots()
if self.proxy ~= nil and self.requestSlots ~= {} then
local i = 0
local slots = self.requestSlots
while i < 10 do
i = i + 1
if slots[i] == nil or next(slots[i]) == nil then
self.proxy.clearrequestslot(i)
else
debugLog("Setting request slot to: " .. serpent.dump(slots[i]))
self.proxy.setrequestslot(slots[i],i)
end
end
self.requestSlots = slots
end
end
|
-- passive logistics wagon
local class = require 'middleclass'
RequesterWagon = class('RequesterWagon',ProxyWagon)
function RequesterWagon:initialize(parent,data)
debugLog("RequesterWagon:initialize")
ProxyWagon.initialize(self, parent, data)
self.wagonType = "RequesterWagon"
if(data ~= nil) then
self.requestSlots = data.requestSlots
else
self.requestSlots = {}
end
end
function RequesterWagon:updateWagon(tick)
ProxyWagon.updateWagon(self,tick)
self:updateRequestSlots()
end
function RequesterWagon:updateDataSerialisation()
ProxyWagon.updateDataSerialisation(self)
self.data.requestSlots = self.requestSlots
end
function RequesterWagon:createProxyType()
local proxyType = "lw-logistic-chest-requester-trans"
self:createProxy(proxyType)
end
function RequesterWagon:createProxy(proxyType)
ProxyWagon.createProxy(self,proxyType,true)
self:setRequestSlots()
end
function RequesterWagon:updateRequestSlots()
if self.proxy ~= nil then
local i = 0
local slots = {}
while i < 10 do
i = i + 1
slots[i] = self.proxy.getrequestslot(i)
if slots[i] == nil then
slots[i] = {}
end
end
self.requestSlots = slots
end
end
function RequesterWagon:setRequestSlots()
if self.proxy ~= nil and self.requestSlots ~= nil and self.requestSlots ~= {} then
local i = 0
local slots = self.requestSlots
while i < 10 do
i = i + 1
if slots[i] == nil or next(slots[i]) == nil then
self.proxy.clearrequestslot(i)
else
debugLog("Setting request slot to: " .. serpent.dump(slots[i]))
self.proxy.setrequestslot(slots[i],i)
end
end
self.requestSlots = slots
end
end
|
Fixes bug with saving the requester state
|
Fixes bug with saving the requester state
|
Lua
|
mit
|
gnzzz/Factorio-Logistics-Wagons
|
b18d6cb9c63209ce9923221a17984fa6aef84800
|
mod_manifesto/mod_manifesto.lua
|
mod_manifesto/mod_manifesto.lua
|
-- mod_manifesto
local timer = require "util.timer";
local jid_split = require "util.jid".split;
local st = require "util.stanza";
local dm = require "util.datamanager";
local time = os.time;
local hosts = prosody.hosts;
local host = module.host;
local host_session = hosts[host];
local incoming_s2s = prosody.incoming_s2s;
local default_tpl = [[
Hello there.
This is a brief system message to let you know about some upcoming changes to the $HOST service.
Some of your contacts are on other Jabber/XMPP services that do not support encryption. As part of an initiative to increase the security of the Jabber/XMPP network, this service ($HOST) will be participating in a series of tests to discover the impact of our planned changes, and you may lose the ability to communicate with some of your contacts.
The test days well be on the following dates: January 4, February 22, March 22 and April 19. On these days we will require that all client and server connections are encrypted. Unless they enable encryption before that, you will be unable to communicate with your contacts that use these services:
$SERVICES
Your affected contacts are:
$CONTACTS
What can you do? You may tell your contacts to inform their service administrator about their lack of encryption. Your contacts may also switch to a more secure service. A list of public services can be found at https://xmpp.net/directory.php
For more information about the Jabber/XMPP security initiative that we are participating in, please read the announcement at https://stpeter.im/journal/1496.html
If you have any questions or concerns, you may contact us via $CONTACTVIA at $CONTACT
]];
local message = module:get_option_string("manifesto_contact_encryption_warning", default_tpl);
local contact = module:get_option_string("admin_contact_address", module:get_option_array("admins", {})[1]);
if not contact then
error("mod_manifesto needs you to set 'admin_contact_address' in your config file.", 0);
end
local contact_method = "Jabber/XMPP";
if select(2, contact:gsub("^mailto:", "")) > 0 then
contact_method = "email";
end
local notified;
module:hook("resource-bind", function (event)
local session = event.session;
local now = time();
local last_notify = notified[session.username] or 0;
if last_notify > ( now - 86400 * 7 ) then
return
end
timer.add_task(15, function ()
local bad_contacts, bad_hosts = {}, {};
for contact_jid, item in pairs(session.roster or {}) do
local _, contact_host = jid_split(contact_jid);
local bad = false;
local remote_host_session = host_session.s2sout[contact_host];
if remote_host_session and remote_host_session.type == "s2sout" then -- Only check remote hosts we have completed s2s connections to
if not remote_host_session.secure then
bad = true;
end
end
for session in pairs(incoming_s2s) do
if session.to_host == host and session.from_host == contact_host and session.type == "s2sin" then
if not session.secure then
bad = true;
end
end
end
if bad then
local contact_name = item.name;
if contact_name then
table.insert(bad_contacts, contact_name.." <"..contact_jid..">");
else
table.insert(bad_contacts, contact_jid);
end
if not bad_hosts[contact_host] then
bad_hosts[contact_host] = true;
table.insert(bad_hosts, contact_host);
end
end
end
if #bad_contacts > 0 then
local vars = {
HOST = host;
CONTACTS = " "..table.concat(bad_contacts, "\n ");
SERVICES = " "..table.concat(bad_hosts, "\n ");
CONTACTVIA = contact_method, CONTACT = contact;
};
session.send(st.message({ type = "headline", from = host }):tag("body"):text(message:gsub("$(%w+)", vars)));
end
notified[session.username] = now;
end);
end);
function module.load()
notified = dm.load(nil, host, module.name) or {};
end
function module.save()
dm.store(nil, host, module.name, notified);
return { notified = notified };
end
function module.restore(data)
notified = data.notified;
end
function module.unload()
dm.store(nil, host, module.name, notified);
end
function module.uninstall()
dm.store(nil, host, module.name, nil);
end
|
-- mod_manifesto
local timer = require "util.timer";
local jid_split = require "util.jid".split;
local st = require "util.stanza";
local dm = require "util.datamanager";
local time = os.time;
local hosts = prosody.hosts;
local host = module.host;
local host_session = hosts[host];
local incoming_s2s = prosody.incoming_s2s;
local default_tpl = [[
Hello there.
This is a brief system message to let you know about some upcoming changes to the $HOST service.
Some of your contacts are on other Jabber/XMPP services that do not support encryption. As part of an initiative to increase the security of the Jabber/XMPP network, this service ($HOST) will be participating in a series of tests to discover the impact of our planned changes, and you may lose the ability to communicate with some of your contacts.
The test days well be on the following dates: January 4, February 22, March 22 and April 19. On these days we will require that all client and server connections are encrypted. Unless they enable encryption before that, you will be unable to communicate with your contacts that use these services:
$SERVICES
Your affected contacts are:
$CONTACTS
What can you do? You may tell your contacts to inform their service administrator about their lack of encryption. Your contacts may also switch to a more secure service. A list of public services can be found at https://xmpp.net/directory.php
For more information about the Jabber/XMPP security initiative that we are participating in, please read the announcement at https://stpeter.im/journal/1496.html
If you have any questions or concerns, you may contact us via $CONTACTVIA at $CONTACT
]];
local message = module:get_option_string("manifesto_contact_encryption_warning", default_tpl);
local contact = module:get_option_string("admin_contact_address", module:get_option_array("admins", {})[1]);
if not contact then
error("mod_manifesto needs you to set 'admin_contact_address' in your config file.", 0);
end
local contact_method = "Jabber/XMPP";
if select(2, contact:gsub("^mailto:", "")) > 0 then
contact_method = "email";
end
local notified;
module:hook("resource-bind", function (event)
local session = event.session;
local now = time();
local last_notify = notified[session.username] or 0;
if last_notify > ( now - 86400 * 7 ) then
return
end
timer.add_task(15, function ()
if session.type ~= "c2s" then return end -- user quit already
local bad_contacts, bad_hosts = {}, {};
for contact_jid, item in pairs(session.roster or {}) do
local _, contact_host = jid_split(contact_jid);
local bad = false;
local remote_host_session = host_session.s2sout[contact_host];
if remote_host_session and remote_host_session.type == "s2sout" then -- Only check remote hosts we have completed s2s connections to
if not remote_host_session.secure then
bad = true;
end
end
for session in pairs(incoming_s2s) do
if session.to_host == host and session.from_host == contact_host and session.type == "s2sin" then
if not session.secure then
bad = true;
end
end
end
if bad then
local contact_name = item.name;
if contact_name then
table.insert(bad_contacts, contact_name.." <"..contact_jid..">");
else
table.insert(bad_contacts, contact_jid);
end
if not bad_hosts[contact_host] then
bad_hosts[contact_host] = true;
table.insert(bad_hosts, contact_host);
end
end
end
if #bad_contacts > 0 then
local vars = {
HOST = host;
CONTACTS = " "..table.concat(bad_contacts, "\n ");
SERVICES = " "..table.concat(bad_hosts, "\n ");
CONTACTVIA = contact_method, CONTACT = contact;
};
session.send(st.message({ type = "headline", from = host }):tag("body"):text(message:gsub("$(%w+)", vars)));
end
notified[session.username] = now;
end);
end);
function module.load()
notified = dm.load(nil, host, module.name) or {};
end
function module.save()
dm.store(nil, host, module.name, notified);
return { notified = notified };
end
function module.restore(data)
notified = data.notified;
end
function module.unload()
dm.store(nil, host, module.name, notified);
end
function module.uninstall()
dm.store(nil, host, module.name, nil);
end
|
mod_manifesto: Fix traceback when user disconnects before the timer (fixes #48)
|
mod_manifesto: Fix traceback when user disconnects before the timer (fixes #48)
|
Lua
|
mit
|
Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules
|
945ea854ea2a37f53550e4beabab799210221d31
|
src/cosy/lang/data.lua
|
src/cosy/lang/data.lua
|
-- Basic data manipulation
-- =======================
--
-- Data in CosyVerif mainly represents formalisms and models, with two
-- requirements:
--
-- * use a memory efficient representation, as big models are sometimes
-- encountered;
-- * provide a user friendly manipulation, as users are allowed to edit
-- models in a text editor instead of the graphical user interface.
--
-- In order to fulfill these two requirements, we split the data
-- representation from its manipulation: __raw data__ is stored as Lua
-- tables, and __views__ are provided on demand upon them for manipulation.
--
-- Data is also split in several notions:
--
-- * _components_ are the top level elements that store data;
-- * _data_ are the building blocks of components; each data belongs to only
-- one component;
-- * _tags_ are special keys used in components and data, used to identify
-- internal or tool specific data.
-- Implementation details
-- ----------------------
--
-- This module makes use of both the standard `type` function, and the
-- extensible one provided in `cosy.util.type`.
--
-- __Trick:__ the standard `type` function is saved and renamed `luatype`.
--
local luatype = type
local type = require "cosy.util.type"
local tags = require "cosy.lang.tags"
-- Three tags are used within this module: `RAW`, `OWNER` and `VIEW`.
-- Two of them (`RAW` and `VIEW`) are required by the view mechanism.
-- The third one (`OWNER`) is required by the component mechanism.
--
local RAW = tags.RAW
local VIEW = tags.VIEW
local OWNER = tags.OWNER
-- Access to raw data
-- ------------------
--
-- The `raw` function returns the raw data behind any data (already a raw
-- one or a view). It can be used as in the example code below, that
-- retrieves in `r` the raw data from data `x`:
--
-- local r = raw (x)
--
-- This function is usable on all Lua values. When its parameter is a
-- component or data, wrapped within a view, the raw component or data is
-- returned. Otherwise, the parameter is returned unchanged.
-- `raw` should thus be preferred to direct access using the `RAW` tag
-- when the parameter can be any Lua value, even not a table.
--
local function raw (x)
if luatype (x) == "table" then
return x [RAW] or x
else
return x
end
end
-- Access to owner
-- ---------------
--
-- The `owner` function returns the owner of any data. It can be used as
-- in the example code below, that retrieves in `o` the owner of data `x`:
--
-- local o = owner (x)
--
-- This function is usable on all Lua values. When its parameter is a
-- component or data, its owner is returned. Otherwise, `nil` is returned.
-- `owner` should thus be preferred to direct access using the `OWNER` tag
-- when the parameter can be any Lua value, even not a table.
--
local function owner (x)
if luatype (x) == "table" then
return x [OWNER]
else
return nil
end
end
-- Iteration over a component
-- --------------------------
--
-- A component is a rooted graph of data. The `walk` function allows to
-- iterate over the data reachable within and from a component. It behaves
-- as a Lua iterator, where each step returns a data. It can be used in a
-- `for` loop as in the example below:
--
-- for data in walk (c, { ... }) do
-- ...
-- end
--
-- __WARNING:__ Contrary to `pairs` and `ipairs`, the iteration returns only
-- one value (the data) instead of a key and a value.
--
-- `walk` takes two arguments:
--
-- * `data` is the component to iterate over, that is mandatory;
-- * `args` is an optional table containing iteration parameters.
--
-- The iteration parameters are:
--
-- * `visit_once`: when set, each data is only returned once in the
-- iteration, even if it can be accessed through two paths in the
-- component;
-- * `in_component`: when set, only data within the components are returned,
-- while all reachable data, even in other components, are returned
-- otherwise.
--
local function walk (data, args)
local config = {
visit_once = true,
in_component = true,
}
if args and luatype (args) == "table" then
if args.visit_once == false then
config.visit_once = false
end
if args.in_component == false then
config.in_component = false
end
end
local function iterate (data, view, visited)
coroutine.yield (view (data))
if not visited [data] then
visited [data] = true
for k, v in pairs (data) do
if not type (k).tag and type (v).table
and not (config.visit_once and visited [v])
and not (config.in_component and owner (v) ~= owner (data)) then
iterate (v, view, visited)
end
end
visited [data] = config.visit_once or nil
end
end
assert (type (data).component)
local view = data [VIEW] or function (x) return x end
local data = raw (data)
return coroutine.wrap (function () iterate (data, view, {}) end)
end
-- Extensible `type` function
-- --------------------------
--
-- We extend the `type` function with the different notions found in
-- CosyVerif:
--
-- * `"tag"` is the type returned for all tags;
-- * `"data"` is the type returned for all data except components and tags;
-- * `"component"` is the type returned for all components (that is for the
-- data at the root of a component);
-- * `"table"` is still returned for every table that does not meet one of
-- the above constraints.
-- A tag is a data, the owner of which is `tags`.
type.tag = function (data)
return owner (data) == tags
end
-- A component is a data, the owner of which is itself.
type.component = function (data)
return owner (data) == raw (data)
end
-- A data is any data with an owner, that is both not a tag and not a
-- component.
type.data = function (data)
local o = owner (data)
return o
and o ~= raw (data)
and o ~= tags
end
-- Every other table is considered as a raw table.
-- Module
-- ------
--
-- This module exports three functions:
--
-- * `raw` and `owner` that allow to access respectively the raw data behind
-- and the owner of any data;
-- * `walk` that allows to iterate over the data of a component.
--
return {
raw = raw,
owner = owner,
walk = walk,
}
|
-- Basic data manipulation
-- =======================
--
-- Data in CosyVerif mainly represents formalisms and models, with two
-- requirements:
--
-- * use a memory efficient representation, as big models are sometimes
-- encountered;
-- * provide a user friendly manipulation, as users are allowed to edit
-- models in a text editor instead of the graphical user interface.
--
-- In order to fulfill these two requirements, we split the data
-- representation from its manipulation: __raw data__ is stored as Lua
-- tables, and __views__ are provided on demand upon them for manipulation.
--
-- Data is also split in several notions:
--
-- * _components_ are the top level elements that store data;
-- * _data_ are the building blocks of components; each data belongs to only
-- one component;
-- * _tags_ are special keys used in components and data, used to identify
-- internal or tool specific data.
-- Implementation details
-- ----------------------
--
-- This module makes use of both the standard `type` function, and the
-- extensible one provided in `cosy.util.type`.
--
-- __Trick:__ the standard `type` function is saved and renamed `luatype`.
--
local luatype = type
local type = require "cosy.util.type"
local tags = require "cosy.lang.tags"
-- Three tags are used within this module: `RAW`, `OWNER` and `VIEW`.
-- Two of them (`RAW` and `VIEW`) are required by the view mechanism.
-- The third one (`OWNER`) is required by the component mechanism.
--
local RAW = tags.RAW
local VIEW = tags.VIEW
local OWNER = tags.OWNER
-- Access to raw data
-- ------------------
--
-- The `raw` function returns the raw data behind any data (already a raw
-- one or a view). It can be used as in the example code below, that
-- retrieves in `r` the raw data from data `x`:
--
-- local r = raw (x)
--
-- This function is usable on all Lua values. When its parameter is a
-- component or data, wrapped within a view, the raw component or data is
-- returned. Otherwise, the parameter is returned unchanged.
-- `raw` should thus be preferred to direct access using the `RAW` tag
-- when the parameter can be any Lua value, even not a table.
--
local function raw (x)
if luatype (x) == "table" then
return x [RAW] or x
else
return x
end
end
-- Access to owner
-- ---------------
--
-- The `owner` function returns the owner of any data. It can be used as
-- in the example code below, that retrieves in `o` the owner of data `x`:
--
-- local o = owner (x)
--
-- This function is usable on all Lua values. When its parameter is a
-- component or data, its owner is returned. Otherwise, `nil` is returned.
-- `owner` should thus be preferred to direct access using the `OWNER` tag
-- when the parameter can be any Lua value, even not a table.
--
local function owner (x)
if luatype (x) == "table" then
return x [OWNER]
else
return nil
end
end
-- Iteration over a component
-- --------------------------
--
-- A component is a rooted graph of data. The `walk` function allows to
-- iterate over the data reachable within and from a component. It behaves
-- as a Lua iterator, where each step returns a data. It can be used in a
-- `for` loop as in the example below:
--
-- for data in walk (c, { ... }) do
-- ...
-- end
--
-- __WARNING:__ Contrary to `pairs` and `ipairs`, the iteration returns only
-- one value (the data) instead of a key and a value.
--
-- `walk` takes two arguments:
--
-- * `data` is the component to iterate over, that is mandatory;
-- * `args` is an optional table containing iteration parameters.
--
-- The iteration parameters are:
--
-- * `visit_once`: when set, each data is only returned once in the
-- iteration, even if it can be accessed through two paths in the
-- component;
-- * `in_component`: when set, only data within the components are returned,
-- while all reachable data, even in other components, are returned
-- otherwise.
--
local function walk (data, args)
local config = {
visit_once = true,
in_component = true,
}
if args and luatype (args) == "table" then
if args.visit_once == false then
config.visit_once = false
end
if args.in_component == false then
config.in_component = false
end
end
local function iterate (data, view, visited)
local data_view = data
for _, f in ipairs (view) do
data_view = f (data_view)
end
coroutine.yield (data_view)
if not visited [data] then
visited [data] = true
for k, v in pairs (data) do
if not type (k).tag and type (v).table
and not (config.visit_once and visited [v])
and not (config.in_component and owner (v) ~= owner (data)) then
iterate (v, view, visited)
end
end
visited [data] = config.visit_once or nil
end
end
assert (type (data).component)
local view = data [VIEW] or {}
local data = raw (data)
return coroutine.wrap (function () iterate (data, view, {}) end)
end
-- Extensible `type` function
-- --------------------------
--
-- We extend the `type` function with the different notions found in
-- CosyVerif:
--
-- * `"tag"` is the type returned for all tags;
-- * `"data"` is the type returned for all data except components and tags;
-- * `"component"` is the type returned for all components (that is for the
-- data at the root of a component);
-- * `"table"` is still returned for every table that does not meet one of
-- the above constraints.
-- A tag is a data, the owner of which is `tags`.
type.tag = function (data)
return owner (data) == tags
end
-- A component is a data, the owner of which is itself.
type.component = function (data)
return owner (data) == raw (data)
end
-- A data is any data with an owner, that is both not a tag and not a
-- component.
type.data = function (data)
local o = owner (data)
return o
and o ~= raw (data)
and o ~= tags
end
-- Every other table is considered as a raw table.
-- Module
-- ------
--
-- This module exports three functions:
--
-- * `raw` and `owner` that allow to access respectively the raw data behind
-- and the owner of any data;
-- * `walk` that allows to iterate over the data of a component.
--
return {
raw = raw,
owner = owner,
walk = walk,
}
|
Fix view reconstruction.
|
Fix view reconstruction.
|
Lua
|
mit
|
CosyVerif/library,CosyVerif/library,CosyVerif/library
|
fd8b5945a984f13d189142f4086def68dc35d727
|
lua/json/decode/state.lua
|
lua/json/decode/state.lua
|
--[[
Licensed according to the included 'LICENSE' document
Author: Thomas Harning Jr <harningt@gmail.com>
]]
local setmetatable = setmetatable
local jsonutil = require("json.util")
local assert = assert
local type = type
local next = next
local unpack = unpack
module("json.decode.state")
local state_ops = {}
local state_mt = {
__index = state_ops
}
function state_ops.pop(self)
self.previous_set = true
self.previous = self.active
local i = self.i
-- Load in this array into the active item
self.active = self.stack[i]
self.active_state = self.state_stack[i]
self.active_key = self.key_stack[i]
self.stack[i] = nil
self.state_stack[i] = nil
self.key_stack[i] = nil
self.i = i - 1
end
function state_ops.push(self)
local i = self.i + 1
self.i = i
self.stack[i] = self.active
self.state_stack[i] = self.active_state
self.key_stack[i] = self.active_key
end
function state_ops.put_object_value(self, trailing)
local object_options = self.options.object
if trailing and object_options.trailingComma then
if not self.active_key then
return
end
end
assert(self.active_key, "Missing key value")
object_options.setObjectKey(self.active, self.active_key, self:grab_value())
self.active_key = nil
end
function state_ops.put_array_value(self, trailing)
-- Safety check
if trailing and not self.previous_set and self.options.array.trailingComma then
return
end
local new_index = self.active_state + 1
self.active_state = new_index
self.active[new_index] = self:grab_value()
end
function state_ops.put_value(self, trailing)
if self.active_state == 'object' then
self:put_object_value(trailing)
else
self:put_array_value(trailing)
end
end
function state_ops.new_array(self)
local new_array = {}
if jsonutil.InitArray then
new_array = jsonutil.InitArray(new_array) or new_array
end
self.active = new_array
self.active_state = 0
self.active_key = nil
self:unset_value()
end
function state_ops.end_array(self)
if self.previous_set or self.active_state ~= 0 then
-- Not an empty array
self:put_value(true)
end
if self.active_state ~= #self.active then
-- Store the length in
self.active.n = self.active_state
end
end
function state_ops.new_object(self)
local new_object = {}
self.active = new_object
self.active_state = 'object'
self.active_key = nil
self:unset_value()
end
function state_ops.end_object(self)
if self.previous_set or next(self.active) then
-- Not an empty object
self:put_value(true)
end
end
function state_ops.new_call(self, name, func)
-- TODO setup properly
local new_call = {}
new_call.name = name
new_call.func = func
self.active = new_call
self.active_state = 0
self.active_key = nil
self:unset_value()
end
function state_ops.end_call(self)
if self.previous_set or self.active_state ~= 0 then
-- Not an empty array
self:put_value(true)
end
if self.active_state ~= #self.active then
-- Store the length in
self.active.n = self.active_state
end
local func = self.active.func
if func == true then
func = jsonutil.buildCall
end
self.active = func(self.active.name, unpack(self.active, 1, self.active.n or #self.active))
end
function state_ops.unset_value(self)
self.previous_set = false
self.previous = nil
end
function state_ops.grab_value(self)
assert(self.previous_set, "Previous value not set")
self.previous_set = false
return self.previous
end
function state_ops.set_value(self, value)
assert(not self.previous_set, "Value set when one already in slot")
self.previous_set = true
self.previous = value
end
function state_ops.set_key(self)
assert(self.active_state == 'object', "Cannot set key on array")
local value = self:grab_value()
local value_type = type(value)
if self.options.object.number then
assert(value_type == 'string' or value_type == 'number', "As configured, a key must be a number or string")
else
assert(value_type == 'string', "As configured, a key must be a string")
end
self.active_key = value
end
function create(options)
local ret = {
options = options,
stack = {},
state_stack = {},
key_stack = {},
i = 0,
active = nil,
active_key = nil,
previous = nil,
active_state = nil
}
return setmetatable(ret, state_mt)
end
|
--[[
Licensed according to the included 'LICENSE' document
Author: Thomas Harning Jr <harningt@gmail.com>
]]
local setmetatable = setmetatable
local jsonutil = require("json.util")
local assert = assert
local type = type
local next = next
local unpack = unpack
_ENV = nil
local state_ops = {}
local state_mt = {
__index = state_ops
}
function state_ops.pop(self)
self.previous_set = true
self.previous = self.active
local i = self.i
-- Load in this array into the active item
self.active = self.stack[i]
self.active_state = self.state_stack[i]
self.active_key = self.key_stack[i]
self.stack[i] = nil
self.state_stack[i] = nil
self.key_stack[i] = nil
self.i = i - 1
end
function state_ops.push(self)
local i = self.i + 1
self.i = i
self.stack[i] = self.active
self.state_stack[i] = self.active_state
self.key_stack[i] = self.active_key
end
function state_ops.put_object_value(self, trailing)
local object_options = self.options.object
if trailing and object_options.trailingComma then
if not self.active_key then
return
end
end
assert(self.active_key, "Missing key value")
object_options.setObjectKey(self.active, self.active_key, self:grab_value())
self.active_key = nil
end
function state_ops.put_array_value(self, trailing)
-- Safety check
if trailing and not self.previous_set and self.options.array.trailingComma then
return
end
local new_index = self.active_state + 1
self.active_state = new_index
self.active[new_index] = self:grab_value()
end
function state_ops.put_value(self, trailing)
if self.active_state == 'object' then
self:put_object_value(trailing)
else
self:put_array_value(trailing)
end
end
function state_ops.new_array(self)
local new_array = {}
if jsonutil.InitArray then
new_array = jsonutil.InitArray(new_array) or new_array
end
self.active = new_array
self.active_state = 0
self.active_key = nil
self:unset_value()
end
function state_ops.end_array(self)
if self.previous_set or self.active_state ~= 0 then
-- Not an empty array
self:put_value(true)
end
if self.active_state ~= #self.active then
-- Store the length in
self.active.n = self.active_state
end
end
function state_ops.new_object(self)
local new_object = {}
self.active = new_object
self.active_state = 'object'
self.active_key = nil
self:unset_value()
end
function state_ops.end_object(self)
if self.previous_set or next(self.active) then
-- Not an empty object
self:put_value(true)
end
end
function state_ops.new_call(self, name, func)
-- TODO setup properly
local new_call = {}
new_call.name = name
new_call.func = func
self.active = new_call
self.active_state = 0
self.active_key = nil
self:unset_value()
end
function state_ops.end_call(self)
if self.previous_set or self.active_state ~= 0 then
-- Not an empty array
self:put_value(true)
end
if self.active_state ~= #self.active then
-- Store the length in
self.active.n = self.active_state
end
local func = self.active.func
if func == true then
func = jsonutil.buildCall
end
self.active = func(self.active.name, unpack(self.active, 1, self.active.n or #self.active))
end
function state_ops.unset_value(self)
self.previous_set = false
self.previous = nil
end
function state_ops.grab_value(self)
assert(self.previous_set, "Previous value not set")
self.previous_set = false
return self.previous
end
function state_ops.set_value(self, value)
assert(not self.previous_set, "Value set when one already in slot")
self.previous_set = true
self.previous = value
end
function state_ops.set_key(self)
assert(self.active_state == 'object', "Cannot set key on array")
local value = self:grab_value()
local value_type = type(value)
if self.options.object.number then
assert(value_type == 'string' or value_type == 'number', "As configured, a key must be a number or string")
else
assert(value_type == 'string', "As configured, a key must be a string")
end
self.active_key = value
end
local function create(options)
local ret = {
options = options,
stack = {},
state_stack = {},
key_stack = {},
i = 0,
active = nil,
active_key = nil,
previous = nil,
active_state = nil
}
return setmetatable(ret, state_mt)
end
local state = {
create = create
}
return state
|
decoder: fixes 5.2-strict mode state object
|
decoder: fixes 5.2-strict mode state object
|
Lua
|
mit
|
renchunxiao/luajson
|
51cb9f4a2f75c6431a2857e1c5c800d05007060e
|
example/gatedNegationRanking.lua
|
example/gatedNegationRanking.lua
|
local cutorch = require "cutorch"
local cunn = require "cunn"
local nn = require "nn"
local nngraph = require "nngraph"
local optim = require "optim"
-- set gated network hyperparameters
local opt = {}
opt.embedSize = 300
opt.gateSize = 300
opt.hiddenSize = 600
opt.jackknifeSize = 10
opt.numEpochs = 1
opt.batchSize = 8
opt.useGPU = true -- use CUDA_VISIBLE_DEVICES to set the GPU you want to use
opt.predFile = "predict.out"
-- define gated network graph
---- declare inputs
print("Constructing input layers")
local word_vector = nn.Identity()()
local gate_vector = nn.Identity()()
local targ_vector = nn.Identity()()
local sample_vector = nn.Identity()()
---- define hidden layer
print("Constructing hidden state")
local h = nn.Sigmoid()(nn.Bilinear(opt.embedSize, opt.gateSize, opt.hiddenSize)({word_vector, gate_vector}))
---- define output layer
print("Constructing output")
local output = nn.Bilinear(opt.hiddenSize, opt.gateSize, opt.embedSize)({h, gate_vector})
---- Construct model
print("Constructing module")
local ged = nn.gModule({word_vector, gate_vector}, {output})
-- define loss function
print("Defining loss function")
local out_vec = nn.Identity()()
local targ_vec = nn.Identity()()
local sample_vec = nn.Identity()()
local rank = nn.Identity()()
local cos1 = nn.CosineDistance()({out_vec, targ_vec})
local cos2 = nn.CosineDistance()({out_vec, sample_vec})
local parInput = nn.ParallelTable()
:add(nn.Identity())
:add(nn.Identity())
local loss = nn.MarginRankingCriterion()({parInput({cos1, cos2}), rank})
local loss_module = nn.gModule({out_vec, targ_vec, sample_vec, rank}, {loss})
-- GPU mode
if opt.useGPU then
ged:cuda()
loss_module:cuda()
end
-- read training and test data
print("Reading training data")
traindata = torch.Tensor(19578, 4*opt.embedSize)
io.input('data.top10nns.raw.ranking.train')
linecount = 0
for line in io.lines() do
linecount = linecount + 1
valcount = 0
for num in string.gmatch(line, "%S+") do
valcount = valcount + 1
if valcount > 1 then
traindata[linecount][valcount - 1] = tonumber(num)
end
end
end
print("Reading test data")
testdata = torch.Tensor(225, 4*opt.embedSize)
testwords = {}
io.input('data.top10nns.raw.ranking.test')
linecount = 0
for line in io.lines() do
linecount = linecount + 1
valcount = 0
for num in string.gmatch(line, "%S+") do
valcount = valcount + 1
if valcount == 1 then
testwords[linecount] = num
else
testdata[linecount][valcount - 1] = tonumber(num)
end
end
end
-- train model
local x, gradParameters = ged:getParameters()
for epoch = 1, opt.numEpochs do
print("Training epoch", epoch)
shuffle = torch.randperm(traindata:size()[1])
current_loss = 0
for t = 1, traindata:size()[1], opt.batchSize do
print("example number: ", t)
local inputs = {}
local gates = {}
local targets = {}
local samples = {}
for j = t, math.min(t + opt.batchSize - 1, traindata:size()[1]) do
local input = traindata[shuffle[j]]:narrow(1, 1, opt.embedSize):resize(1, opt.embedSize)
local gate = traindata[shuffle[j]]:narrow(1, opt.embedSize + 1, opt.embedSize):resize(1, opt.embedSize)
local target = traindata[shuffle[j]]:narrow(1, 2*opt.embedSize + 1, opt.embedSize):resize(1, opt.embedSize)
local sample = traindata[shuffle[j]]:narrow(1, 3*opt.embedSize + 1, opt.embedSize):resize(1,opt.embedSize)
if opt.useGPU then
input = input:cuda()
gate = gate:cuda()
target = target:cuda()
sample = sample:cuda()
end
table.insert(inputs, input:clone())
table.insert(gates, gate:clone())
table.insert(targets, target:clone())
table.insert(samples, sample:clone())
end
local feval = function(w) -- w = weight vector. returns loss, dloss_dw
gradParameters:zero()
inputs = torch.cat(inputs, 1)
gates = torch.cat(gates, 1)
targets = torch.cat(targets, 1)
samples = torch.cat(samples, 1)
ranks = torch.ones(inputs:size(1)):cuda()
local result = ged:forward({inputs, gates})
local f = loss_module:forward({result, targets, samples, ranks})
local gradErr = loss_module:backward({result, targets, samples, ranks},
torch.ones(1):cuda())
local gradOut, gradTarg, gradSample, gradRank = unpack(gradErr)
ged:backward({inputs[k], gates[k]}, gradOut)
-- normalize gradients and f(X)
gradParameters:div(inputs:size(1))
return f, gradParameters
end -- local feval
_, fs = optim.adadelta(feval, x, {rho = 0.9})
current_loss = current_loss + fs[1]
end -- for t = 1, traindata:size()[1], opt.batchSize
current_loss = current_loss / traindata:size()[1]
print("... Current loss", current_loss)
end -- for epoch = 1, opt.numEpochs
-- predict
print "Predicting"
-- module with the first half of the network
for t = 1, testdata:size()[1] do
local input_word = testwords[t]
local input = traindata[shuffle[j]]:narrow(1, 1, opt.embedSize):resize(1, opt.embedSize)
local gate = traindata[shuffle[j]]:narrow(1, opt.embedSize + 1, opt.embedSize):resize(1, opt.embedSize)
if opt.useGPU then
input = input:cuda()
gate = gate:cuda()
end
local output = ged:forward({input, gate})
opt.predfile:write(input_word .. "\t[")
for k = 1, output:size()[2] do
opt.predfile:write(output[t][k] .. ", ")
end
opt.predfile:write("]\n")
end
print("Saving model")
torch.save("model.net", ged)
|
local cutorch = require "cutorch"
local cunn = require "cunn"
local nn = require "nn"
local nngraph = require "nngraph"
local optim = require "optim"
-- set gated network hyperparameters
local opt = {}
opt.embedSize = 300
opt.gateSize = 300
opt.hiddenSize = 600
opt.jackknifeSize = 10
opt.numEpochs = 1
opt.batchSize = 100
opt.useGPU = true -- use CUDA_VISIBLE_DEVICES to set the GPU you want to use
opt.predFile = "predict.out"
-- define gated network graph
---- declare inputs
print("Constructing input layers")
local word_vector = nn.Identity()()
local gate_vector = nn.Identity()()
local targ_vector = nn.Identity()()
local sample_vector = nn.Identity()()
---- define hidden layer
print("Constructing hidden state")
local h = nn.Sigmoid()(nn.Bilinear(opt.embedSize, opt.gateSize, opt.hiddenSize)({word_vector, gate_vector}))
---- define output layer
print("Constructing output")
local output = nn.Bilinear(opt.hiddenSize, opt.gateSize, opt.embedSize)({h, gate_vector})
---- Construct model
print("Constructing module")
local ged = nn.gModule({word_vector, gate_vector}, {output})
-- define loss function
print("Defining loss function")
local out_vec = nn.Identity()()
local targ_vec = nn.Identity()()
local sample_vec = nn.Identity()()
local rank = nn.Identity()()
local cos1 = nn.CosineDistance()({out_vec, targ_vec})
local cos2 = nn.CosineDistance()({out_vec, sample_vec})
local parInput = nn.ParallelTable()
:add(nn.Identity())
:add(nn.Identity())
local loss = nn.MarginRankingCriterion()({parInput({cos1, cos2}), rank})
local loss_module = nn.gModule({out_vec, targ_vec, sample_vec, rank}, {loss})
-- GPU mode
if opt.useGPU then
ged:cuda()
loss_module:cuda()
end
-- read training and test data
print("Reading training data")
traindata = torch.Tensor(19578, 4*opt.embedSize)
io.input('data.top10nns.raw.ranking.train')
linecount = 0
for line in io.lines() do
linecount = linecount + 1
valcount = 0
for num in string.gmatch(line, "%S+") do
valcount = valcount + 1
if valcount > 1 then
traindata[linecount][valcount - 1] = tonumber(num)
end
end
end
print("Reading test data")
testdata = torch.Tensor(225, 4*opt.embedSize)
testwords = {}
io.input('data.top10nns.raw.ranking.test')
linecount = 0
for line in io.lines() do
linecount = linecount + 1
valcount = 0
for num in string.gmatch(line, "%S+") do
valcount = valcount + 1
if valcount == 1 then
testwords[linecount] = num
else
testdata[linecount][valcount - 1] = tonumber(num)
end
end
end
-- train model
local x, gradParameters = ged:getParameters()
for epoch = 1, opt.numEpochs do
print("Training epoch", epoch)
shuffle = torch.randperm(traindata:size()[1])
current_loss = 0
for t = 1, traindata:size()[1], opt.batchSize do
print("example number: ", t)
local inputs = {}
local gates = {}
local targets = {}
local samples = {}
for j = t, math.min(t + opt.batchSize - 1, traindata:size()[1]) do
local input = traindata[shuffle[j]]:narrow(1, 1, opt.embedSize):resize(1, opt.embedSize)
local gate = traindata[shuffle[j]]:narrow(1, opt.embedSize + 1, opt.embedSize):resize(1, opt.embedSize)
local target = traindata[shuffle[j]]:narrow(1, 2*opt.embedSize + 1, opt.embedSize):resize(1, opt.embedSize)
local sample = traindata[shuffle[j]]:narrow(1, 3*opt.embedSize + 1, opt.embedSize):resize(1,opt.embedSize)
if opt.useGPU then
input = input:cuda()
gate = gate:cuda()
target = target:cuda()
sample = sample:cuda()
end
table.insert(inputs, input:clone())
table.insert(gates, gate:clone())
table.insert(targets, target:clone())
table.insert(samples, sample:clone())
end
local feval = function(w) -- w = weight vector. returns loss, dloss_dw
gradParameters:zero()
inputs = torch.cat(inputs, 1)
gates = torch.cat(gates, 1)
targets = torch.cat(targets, 1)
samples = torch.cat(samples, 1)
ranks = torch.ones(inputs:size(1)):cuda()
local result = ged:forward({inputs, gates})
local f = loss_module:forward({result, targets, samples, ranks})
local gradErr = loss_module:backward({result, targets, samples, ranks},
torch.ones(1):cuda())
local gradOut, gradTarg, gradSample, gradRank = unpack(gradErr)
ged:backward({inputs, gates}, gradOut)
-- normalize gradients and f(X)
gradParameters:div(inputs:size(1))
return f, gradParameters
end -- local feval
_, fs = optim.adadelta(feval, x, {rho = 0.9})
current_loss = current_loss + fs[1]
end -- for t = 1, traindata:size()[1], opt.batchSize
current_loss = current_loss / traindata:size()[1]
print("... Current loss", current_loss)
end -- for epoch = 1, opt.numEpochs
-- predict
print "Predicting"
predFileStream = io.open(opt.predFile, "w")
-- module with the first half of the network
local shuffle = torch.randperm(testdata:size(1))
for t = 1, testdata:size(1) do
local input_word = testwords[t]
local input = testdata[shuffle[t]]:narrow(1, 1, opt.embedSize):resize(1, opt.embedSize)
local gate = testdata[shuffle[t]]:narrow(1, opt.embedSize + 1, opt.embedSize):resize(1, opt.embedSize)
if opt.useGPU then
input = input:cuda()
gate = gate:cuda()
end
local output = ged:forward({input, gate})
predFileStream:write(input_word .. "\t[")
for k = 1, output:size()[2] do
predFileStream:write(output[t][k] .. ", ")
end
predFileStream:write("]\n")
end
print("Saving model")
torch.save("model.net", ged)
|
Fix io issues in training and prediction.
|
Fix io issues in training and prediction.
|
Lua
|
mit
|
douwekiela/nncg-negation
|
ab85eafaa6a2d04fbc95c6ea410d0fe804721390
|
Wikilib-evos.lua
|
Wikilib-evos.lua
|
--[[
Library for Evo/data module use.
--]]
local ev = {}
local tab = require('Wikilib-tables') -- luacheck: no unused
local forms = require('Wikilib-forms')
local multigen = require('Wikilib-multigen')
local evodata = require("Evo-data")
local pokes = require("Poké-data")
--[[
Given a Pokémon's table from Evo/data and an identifier of a Pokémon, check
whether the table belongs to that Pokémon or not.
The identifier can be either an ndex (possibly with an abbr) or a name.
This function is based on the assumption that a Pokémon's name won't ever be
the same as an ndex with abbr; if that is ever falsified by TPCi this function
have to be rewritten.
--]]
ev.ownTable = function(pkmn, evotab)
-- if type(pkmn) == 'number' then
-- return pkmn == evotab.ndex
-- if evotab.name == pkmn then
-- return true
-- else
-- return evotab.ndex == pkmn
-- end
return pkmn == evotab.name or pkmn == evotab.ndex
end
--[[
Given a Pokémon's table from Evo/data module, applies a fold on the tree rooted
at that table.
The function takes the accumulator as the first argument, then the value.
The visit is postfix (highest level before) and branches are visited in the
module's order.
--]]
ev.foldEvoTree = function(evotab, acc, func)
acc = func(acc, evotab)
if evotab.evos then
acc = table.fold(evotab.evos, acc, function(acc1, v)
return ev.foldEvoTree(v, acc1, func)
end, ipairs) -- Uses ipairs to keep the module's order
end
return acc
end
--[[
Given a Pokémon name or ndex, returns the evotable of that Pokémon, not of its
whole evolutionary line, that is the subtree rooted at the Pokémon's node.
--]]
ev.preciseEvotable = function(name)
return ev.foldEvoTree(evodata[name], nil, function(acc, v)
if acc then
return acc
elseif ev.ownTable(name, v) then
return v
else
return nil
end
end)
end
--[[
Given a Pokémon name or ndex (possibly with abbr), returns the evo tree pruned
of branches that aren't in the subtree nor in the path to root of that Pokémon.
I.e: the exact tree that Evobox should print.
Example: given Eevee, this functions returns Eevee and all its evolutions, but
given Vaporeon it returns only Eevee with evolution Vaporeon, pruning away all
other evolutions.
The parameter should be the ndex as found in the evo-data module (that is, three
digits possibly followed by the abbr, in first uppercase).
--]]
ev.prunedEvotree = function(name)
-- Support function. Needed because it's recursive. Local to access ndex and
-- simplify pass to map.
local function recPruneEvoTree(evotab)
if ev.ownTable(name, evotab) then
return evotab
end
if not evotab.evos then
return nil
end
local result = {}
result.evos = table.mapToNum(evotab.evos, recPruneEvoTree, ipairs)
if #result.evos == 0 then
return nil
end
for k, v in pairs(evotab) do
if k ~= "evos" then
result[k] = v
end
end
return result
end
return recPruneEvoTree(evodata[name])
end
--[[
Given two Pokémon names or ndexes returns true iff they are in the same
evolutionary line. The two arguments must be able to index Poké/data.
--]]
ev.sameEvoLine = function(name1, name2)
return evodata[name1] == evodata[name2]
end
--[[
Given a Pokémon's ndex, returns the list of all Pokémon in which it can evolve.
The list is of ndexes.
If a Pokémon without ndex should be inserted in this list, it doesn't appear.
--]]
ev.evoList = function(name)
return ev.foldEvoTree(ev.preciseEvotable(name), {}, function(acc, v)
table.insert(acc, v.ndex)
return acc
end)
end
--[[
Given a Pokémon name or ndex return the list of names of Pokémon that can
evolve into it. The list is sorted in reverse evolution order.
--]]
ev.preevoList = function(name)
local function explore(evotab)
if ev.ownTable(name, evotab) then
return {}
end
if not evotab.evos then
return nil
end
for _, v in pairs(evotab.evos) do
local acc = explore(v)
if acc then
table.insert(acc, evotab.name)
return acc
end
end
return nil
end
return explore(evodata[name])
end
--[[
Given a Pokémon name od ndex, returns the list of types of its evolutions that
it doesn't have.
The optional argument gen specifies in which gen this should be computed,
defaults to the latest.
--]]
ev.evoTypesList = function(name, gen)
local thisdata = pokes[name] or pokes[forms.getnameabbr(name)]
return table.filter(table.unique(table.flatMap(ev.foldEvoTree(ev.preciseEvotable(name), {}, function(acc, v)
table.insert(acc, v.ndex)
return acc
end), function(ndex)
local pokedata = pokes[ndex] or pokes[forms.getnameabbr(name)]
return multigen.getGen({ pokedata.type1, pokedata.type2 }, gen)
end)), function(type)
return not (type == thisdata.type1 or type == thisdata.type2)
end)
end
--[[
Given a Pokémon name od ndex, returns the list of types of its alternative
forms (only those in which it can change) that it doesn't have.
The optional argument gen specifies in which gen this should be computed,
defaults to the latest.
--]]
ev.formTypesList = function(name, gen)
local formstab = evodata.forms[name]
if not formstab then
return {}
end
local thisdata = pokes[name] or pokes[forms.getnameabbr(name)]
return table.filter(table.unique(table.flatMap(formstab, function(tt)
return table.flatMap(tt, function(formtab)
local pokedata = pokes[forms.uselessToEmpty(formtab.name)]
return multigen.getGen({ pokedata.type1, pokedata.type2 }, gen)
end)
end)), function(type)
return not (type == thisdata.type1 or type == thisdata.type2)
end)
end
--[[
Given a Pokémon name or ndex return true iff that Pokémon can't evolve further.
--]]
ev.isFullyEvolved = function(name)
return ev.preciseEvotable(name).evos == nil
-- return table.empty(ev.preciseEvotable(name).evos)
end
--[[
Given a Pokémon name or ndex return the name of the Pokémon that can evolve
into it. If no such Pokémon exists, return nil.
--]]
ev.directPreevo = function(name)
return ev.foldEvoTree(evodata[name], nil, function(acc, v)
if acc then
return acc
elseif v.evos and table.any(v.evos, function(a)
return ev.ownTable(name, a)
end) then
return v.name
else
return nil
end
end)
end
return ev
|
--[[
Library for Evo/data module use.
--]]
local ev = {}
local tab = require('Wikilib-tables') -- luacheck: no unused
local forms = require('Wikilib-forms')
local multigen = require('Wikilib-multigen')
local evodata = require("Evo-data")
local pokes = require("Poké-data")
--[[
Given a Pokémon's table from Evo/data and an identifier of a Pokémon, check
whether the table belongs to that Pokémon or not.
The identifier can be either an ndex (possibly with an abbr) or a name.
This function is based on the assumption that a Pokémon's name won't ever be
the same as an ndex with abbr; if that is ever falsified by TPCi this function
have to be rewritten.
--]]
ev.ownTable = function(pkmn, evotab)
-- if type(pkmn) == 'number' then
-- return pkmn == evotab.ndex
-- if evotab.name == pkmn then
-- return true
-- else
-- return evotab.ndex == pkmn
-- end
return pkmn == evotab.name or pkmn == evotab.ndex
end
--[[
Given a Pokémon's table from Evo/data module, applies a fold on the tree rooted
at that table.
The function takes the accumulator as the first argument, then the value.
The visit is postfix (highest level before) and branches are visited in the
module's order.
--]]
ev.foldEvoTree = function(evotab, acc, func)
acc = func(acc, evotab)
if evotab.evos then
acc = table.fold(evotab.evos, acc, function(acc1, v)
return ev.foldEvoTree(v, acc1, func)
end, ipairs) -- Uses ipairs to keep the module's order
end
return acc
end
--[[
Given a Pokémon name or ndex, returns the evotable of that Pokémon, not of its
whole evolutionary line, that is the subtree rooted at the Pokémon's node.
--]]
ev.preciseEvotable = function(name)
return ev.foldEvoTree(evodata[name], nil, function(acc, v)
if acc then
return acc
elseif ev.ownTable(name, v) then
return v
else
return nil
end
end)
end
--[[
Given a Pokémon name or ndex (possibly with abbr), returns the evo tree pruned
of branches that aren't in the subtree nor in the path to root of that Pokémon.
I.e: the exact tree that Evobox should print.
Example: given Eevee, this functions returns Eevee and all its evolutions, but
given Vaporeon it returns only Eevee with evolution Vaporeon, pruning away all
other evolutions.
The parameter should be the ndex as found in the evo-data module (that is, three
digits possibly followed by the abbr, in first uppercase).
--]]
ev.prunedEvotree = function(name)
-- Support function. Needed because it's recursive. Local to access ndex and
-- simplify pass to map.
local function recPruneEvoTree(evotab)
if ev.ownTable(name, evotab) then
return evotab
end
if not evotab.evos then
return nil
end
local result = {}
result.evos = table.mapToNum(evotab.evos, recPruneEvoTree, ipairs)
if #result.evos == 0 then
return nil
end
for k, v in pairs(evotab) do
if k ~= "evos" then
result[k] = v
end
end
return result
end
return recPruneEvoTree(evodata[name])
end
--[[
Given two Pokémon names or ndexes returns true iff they are in the same
evolutionary line. The two arguments must be able to index Poké/data.
--]]
ev.sameEvoLine = function(name1, name2)
return evodata[name1] == evodata[name2]
end
--[[
Given a Pokémon's ndex, returns the list of all Pokémon in which it can evolve.
The list is of ndexes.
If a Pokémon without ndex should be inserted in this list, it doesn't appear.
--]]
ev.evoList = function(name)
return ev.foldEvoTree(ev.preciseEvotable(name), {}, function(acc, v)
table.insert(acc, v.ndex)
return acc
end)
end
--[[
Given a Pokémon name or ndex return the list of names of Pokémon that can
evolve into it. The list is sorted in reverse evolution order.
--]]
ev.preevoList = function(name)
local function explore(evotab)
if ev.ownTable(name, evotab) then
return {}
end
if not evotab.evos then
return nil
end
for _, v in pairs(evotab.evos) do
local acc = explore(v)
if acc then
table.insert(acc, evotab.name)
return acc
end
end
return nil
end
return explore(evodata[name])
end
--[[
Given a Pokémon name od ndex, returns the list of types of its evolutions that
it doesn't have.
The optional argument gen specifies in which gen this should be computed,
defaults to the latest.
--]]
ev.evoTypesList = function(name, gen)
local thisdata = pokes[name] or pokes[forms.getnameabbr(name)]
return table.filter(table.unique(table.flatMap(ev.foldEvoTree(ev.preciseEvotable(name), {}, function(acc, v)
table.insert(acc, v.ndex)
return acc
end), function(ndex)
local pokedata = pokes[ndex] or pokes[forms.getnameabbr(name)]
return multigen.getGen({ pokedata.type1, pokedata.type2 }, gen)
end)), function(type)
return not (type == thisdata.type1 or type == thisdata.type2)
end)
end
--[[
Given a Pokémon name od ndex, returns the list of types of its alternative
forms (only those in which it can change) that it doesn't have.
The optional argument gen specifies in which gen this should be computed,
defaults to the latest.
--]]
ev.formTypesList = function(name, gen)
local formstab = evodata.forms[name]
if not formstab then
return {}
end
local thisdata = pokes[name] or pokes[forms.getnameabbr(name)]
return table.filter(table.unique(table.flatMap(formstab, function(tt)
return table.flatMap(tt, function(formtab)
local pokedata = pokes[forms.uselessToEmpty(formtab.name)]
return multigen.getGen({ pokedata.type1, pokedata.type2 }, gen)
end)
end)), function(type)
return not (type == thisdata.type1 or type == thisdata.type2)
end)
end
--[[
Given a Pokémon name or ndex return true iff that Pokémon can't evolve further.
--]]
ev.isFullyEvolved = function(name)
-- BREEDONLY means that a Pokémon breeds from the evos table, but doesn't
-- evolve into it, hence it's fully evolved (cfr. Phione).
local precEvotable = ev.preciseEvotable(name)
local BREEDONLY = evodata.conditions.BREEDONLY
if precEvotable.conditions and precEvotable.conditions[BREEDONLY] then
return true
end
return precEvotable.evos == nil
end
--[[
Given a Pokémon name or ndex return the name of the Pokémon that can evolve
into it. If no such Pokémon exists, return nil.
--]]
ev.directPreevo = function(name)
return ev.foldEvoTree(evodata[name], nil, function(acc, v)
if acc then
return acc
elseif v.evos and table.any(v.evos, function(a)
return ev.ownTable(name, a)
end) then
return v.name
else
return nil
end
end)
end
return ev
|
Fixed bug that didn't consider Phione fully evolved
|
Fixed bug that didn't consider Phione fully evolved
|
Lua
|
cc0-1.0
|
pokemoncentral/wiki-lua-modules
|
aafb9f54fa328ac66cf37e07087b22645979a65b
|
generator/signalslot.lua
|
generator/signalslot.lua
|
module('signalslot', package.seeall)
local print_slot_h = fprint(assert(io.open(module_name.._src..module_name..'_slot.hpp', 'w')))
local print_slot_c = fprint(assert(io.open(module_name.._src..module_name..'_slot.cpp', 'w')))
local signals = {}
local slots = {}
function copy_signals(functions)
for f in pairs(functions) do
if f.xarg.signal=='1' then
signals[f] = 1
end
end
end
function slots_for_signals(types)
for sig in pairs(signals) do
local args, comma = '(', ''
for i, a in ipairs(sig.arguments) do
args = args .. comma .. a.xarg.type_name .. ' arg'..i
comma = ', '
end
args = args .. ')'
local pushlines, stack = make_pushlines(sig.arguments, types)
if not slots['void __slot '..args] and pushlines then
slots['void __slot '..args] = 'void LqtSlotAcceptor::__slot '..args..[[ {
//int oldtop = lua_gettop(L);
//lua_getfield(L, -1, "__slot]]..string.gsub(args, ' arg.', '')..[[");
//if (lua_isnil(L, -1)) {
//lua_pop(L, 1);
//lua_getfield(L, -1, "__slot");
//}
//if (!lua_isfunction(L, -1)) {
//lua_settop(L, oldtop);
//return;
//}
lua_pushvalue(L, -2);
]] .. pushlines .. [[
if (lqtL_pcall(L, ]]..stack..[[+1, 0, 0)) {
//lua_error(L);
qDebug() << lua_tostring(L, -1);
lua_pop(L, 1);
}
//lua_settop(L, oldtop);
}
]]
end
end
end
function print_slots(s)
print_slot_h'class LqtSlotAcceptor : public QObject {'
print_slot_h' Q_OBJECT'
print_slot_h' lua_State *L;'
print_slot_h' public:'
print_slot_h(' LqtSlotAcceptor(lua_State *l, QObject *p=NULL) : QObject(p), L(l) { setObjectName("'..module_name..'"); lqtL_register(L, this); }')
print_slot_h' virtual ~LqtSlotAcceptor() { lqtL_unregister(L, this); }'
print_slot_h' public slots:'
for p, b in pairs(s) do
print_slot_h(' '..p..';')
end
print_slot_h'};\n'
print_slot_h('\nextern LqtSlotAcceptor *lqtSlotAcceptor_'..module_name..';')
for p, b in pairs(s) do
print_slot_c(b)
end
print_slot_c('\nLqtSlotAcceptor *lqtSlotAcceptor_'..module_name..';')
end
-------------------------------------------------------------------------------
function process(functions, typesystem)
copy_signals(functions)
slots_for_signals(signals, typesystem)
end
function output()
print_slot_h('#ifndef LQT_SLOT_'..module_name)
print_slot_h('#define LQT_SLOT_'..module_name)
print_slot_h(output_includes)
print_slot_c('#include "'..module_name..'_slot.hpp'..'"\n\n')
print_slots(slots)
print_slot_h('#endif')
end
|
module('signalslot', package.seeall)
local print_slot_h = fprint(assert(io.open(module_name.._src..module_name..'_slot.hpp', 'w')))
local print_slot_c = fprint(assert(io.open(module_name.._src..module_name..'_slot.cpp', 'w')))
local signals = {}
local slots = {}
function copy_signals(functions)
for f in pairs(functions) do
if f.xarg.signal=='1' then
signals[f] = true
end
end
end
function slots_for_signals(types)
for sig in pairs(signals) do
local args, comma = '(', ''
for i, a in ipairs(sig.arguments) do
args = args .. comma .. a.xarg.type_name .. ' arg'..i
comma = ', '
end
args = args .. ')'
local pushlines, stack = make_pushlines(sig.arguments, types)
if pushlines then
if not slots['void __slot '..args] then
slots['void __slot '..args] = 'void LqtSlotAcceptor::__slot '..args..[[ {
//int oldtop = lua_gettop(L);
//lua_getfield(L, -1, "__slot]]..string.gsub(args, ' arg.', '')..[[");
//if (lua_isnil(L, -1)) {
//lua_pop(L, 1);
//lua_getfield(L, -1, "__slot");
//}
//if (!lua_isfunction(L, -1)) {
//lua_settop(L, oldtop);
//return;
//}
lua_pushvalue(L, -2);
]] .. pushlines .. [[
if (lqtL_pcall(L, ]]..stack..[[+1, 0, 0)) {
//lua_error(L);
qDebug() << lua_tostring(L, -1);
lua_pop(L, 1);
}
//lua_settop(L, oldtop);
}
]]
end
else
ignore(sig.xarg.fullname, 'slot', stack)
end
end
end
function print_slots(s)
print_slot_h'class LqtSlotAcceptor : public QObject {'
print_slot_h' Q_OBJECT'
print_slot_h' lua_State *L;'
print_slot_h' public:'
print_slot_h(' LqtSlotAcceptor(lua_State *l, QObject *p=NULL) : QObject(p), L(l) { setObjectName("'..module_name..'"); lqtL_register(L, this); }')
print_slot_h' virtual ~LqtSlotAcceptor() { lqtL_unregister(L, this); }'
print_slot_h' public slots:'
for p, b in pairs(s) do
print_slot_h(' '..p..';')
print_slot_c(b)
end
print_slot_h'};\n'
print_slot_h('\nextern LqtSlotAcceptor *lqtSlotAcceptor_'..module_name..';')
print_slot_c('\nLqtSlotAcceptor *lqtSlotAcceptor_'..module_name..';')
end
-------------------------------------------------------------------------------
function process(functions, typesystem)
copy_signals(functions)
slots_for_signals(typesystem)
end
function output()
print_slot_h('#ifndef LQT_SLOT_'..module_name)
print_slot_h('#define LQT_SLOT_'..module_name)
print_slot_h(output_includes)
print_slot_c('#include "'..module_name..'_slot.hpp'..'"\n\n')
print_slots(slots)
print_slot_h('#endif')
end
|
fix generation of slots
|
fix generation of slots
|
Lua
|
mit
|
mkottman/lqt,mkottman/lqt
|
1fd7e41053816611551eb90d909eec09f39a71e9
|
src/cooldown/src/Shared/CooldownBase.lua
|
src/cooldown/src/Shared/CooldownBase.lua
|
--- Base object for a cooldown. Provides calculation utilties.
-- @classmod CooldownBase
-- @author Quenty
local require = require(script.Parent.loader).load(script)
local BaseObject = require("BaseObject")
local TimeSyncService = require("TimeSyncService")
local CooldownBase = setmetatable({}, BaseObject)
CooldownBase.ClassName = "CooldownBase"
CooldownBase.__index = CooldownBase
function CooldownBase.new(obj, serviceBag)
local self = setmetatable(BaseObject.new(obj), CooldownBase)
self._serviceBag = assert(serviceBag, "No serviceBag")
self._timeSyncService = self._serviceBag:GetService(TimeSyncService)
return self
end
function CooldownBase:GetTimePassed()
local startTime = self:GetStartTime()
if not startTime then
return nil
end
return self._timeSyncService:GetSyncedClock():GetTime() - startTime
end
function CooldownBase:GetTimeRemaining()
local endTime = self:GetEndTime()
if not endTime then
return nil
end
return endTime - self._timeSyncService:GetSyncedClock():GetTime()
end
function CooldownBase:GetEndTime()
local startTime = self:GetStartTime()
if not startTime then
return nil
end
return startTime + self:GetLength()
end
function CooldownBase:GetStartTime()
error("Not implemented")
end
function CooldownBase:GetLength()
return self._obj.Value
end
return CooldownBase
|
--- Base object for a cooldown. Provides calculation utilties.
-- @classmod CooldownBase
-- @author Quenty
local require = require(script.Parent.loader).load(script)
local BaseObject = require("BaseObject")
local TimeSyncService = require("TimeSyncService")
local CooldownBase = setmetatable({}, BaseObject)
CooldownBase.ClassName = "CooldownBase"
CooldownBase.__index = CooldownBase
function CooldownBase.new(obj, serviceBag)
local self = setmetatable(BaseObject.new(obj), CooldownBase)
self._serviceBag = assert(serviceBag, "No serviceBag")
self._timeSyncService = self._serviceBag:GetService(TimeSyncService)
self._maid:GivePromise(self._timeSyncService:PromiseSyncedClock())
:Then(function(syncedClock)
self._syncedClock = syncedClock
end)
return self
end
function CooldownBase:GetTimePassed()
local startTime = self:GetStartTime()
if not startTime then
return nil
end
if not self._syncedClock then
return nil
end
return self._syncedClock:GetTime() - startTime
end
function CooldownBase:GetTimeRemaining()
local endTime = self:GetEndTime()
if not endTime then
return nil
end
if not self._syncedClock then
return nil
end
return endTime - self._syncedClock:GetTime()
end
function CooldownBase:GetEndTime()
local startTime = self:GetStartTime()
if not startTime then
return nil
end
return startTime + self:GetLength()
end
function CooldownBase:GetStartTime()
error("Not implemented")
end
function CooldownBase:GetLength()
return self._obj.Value
end
return CooldownBase
|
fix: Cooldown can handle a synced clock not being synced
|
fix: Cooldown can handle a synced clock not being synced
|
Lua
|
mit
|
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
|
c2eae94ab43bf53fed439afffc44a643b3334a1b
|
demos/transitions/Kim.lua
|
demos/transitions/Kim.lua
|
-- Transitions Demo: Kim
--
-- Copyright (c) 2010-16 Bifrost Entertainment AS and Tommy Nguyen
-- Distributed under the MIT License.
-- (See accompanying file LICENSE or copy at http://opensource.org/licenses/MIT)
local Math = require("Math")
local Transition = require("Transition")
Kim = {}
Kim.__index = Kim
function Kim.new(sprite)
local self = {}
setmetatable(self, Kim)
self.origin = {0, 0}
self.sprite = sprite
-- Used to alternate between move and rotate.
self.alternate = false
-- Cache rainbow namespace.
local rainbow = rainbow
-- Move sprite to the centre of the screen.
local screen = rainbow.platform.screen
self.moving = Transition.move(self.sprite, screen.width * 0.5, screen.height * 0.5, 400)
-- Make sprite transparent while rotating, and opaque while moving.
self.sprite:set_color(0xff, 0xff, 0xff, 0x00)
self.alpha = Transition.fadeto(self.sprite, 0xff, 400)
-- Subscribe this class to input events.
rainbow.input.subscribe(self)
return self
end
function Kim:key_down(key, modifiers)
local distance = 64
local moved = false
if key == 97 then -- Left
self.origin[1] = self.origin[1] - distance
moved = true
elseif key == 100 then -- Right
self.origin[1] = self.origin[1] + distance
moved = true
elseif key == 115 then -- Down
self.origin[2] = self.origin[2] - distance
moved = true
elseif key == 119 then -- Up
self.origin[2] = self.origin[2] + distance
moved = true
end
if moved then
local screen = rainbow.platform.screen
rainbow.renderer.set_projection(
self.origin[1],
self.origin[2] + screen.height,
self.origin[1] + screen.width,
self.origin[2])
end
end
function Kim:key_up()
end
function Kim:pointer_began(pointers)
-- Cancel the previous transitions.
self.alpha:cancel()
self.moving:cancel()
if self.alternate then
-- Rotate 360 degrees in 1 second. Linear effect.
local angle = self.sprite:get_angle() + Math.radians(360)
self.moving = Transition.rotate(self.sprite, angle, 1000)
self.alpha = Transition.fadeto(self.sprite, 0x40, 1000)
self.alternate = false
else
-- Move to point in 0.5 seconds. Squared ease-in effect.
for h,p in pairs(pointers) do
local x, y = self.sprite:get_position()
self.moving = Transition.move(self.node, p.x - x, p.y - y, 500, Transition.Functions.easeinout_cubic)
self.alpha = Transition.fadeto(self.sprite, 0xff, 500)
self.alternate = true
break
end
end
end
-- We don't care about these events.
function Kim:pointer_canceled() end
function Kim:pointer_ended() end
function Kim:pointer_moved() end
|
-- Transitions Demo: Kim
--
-- Copyright (c) 2010-16 Bifrost Entertainment AS and Tommy Nguyen
-- Distributed under the MIT License.
-- (See accompanying file LICENSE or copy at http://opensource.org/licenses/MIT)
local Math = require("Math")
local Transition = require("Transition")
Kim = {}
Kim.__index = Kim
function Kim.new(sprite)
local self = {}
setmetatable(self, Kim)
self.origin = {0, 0}
self.sprite = sprite
-- Used to alternate between move and rotate.
self.alternate = false
-- Cache rainbow namespace.
local rainbow = rainbow
-- Move sprite to the centre of the screen.
local screen = rainbow.platform.screen
self.moving = Transition.move(self.sprite, screen.width * 0.5, screen.height * 0.5, 400)
-- Make sprite transparent while rotating, and opaque while moving.
self.sprite:set_color(0xff, 0xff, 0xff, 0x00)
self.alpha = Transition.fadeto(self.sprite, 0xff, 400)
-- Subscribe this class to input events.
rainbow.input.subscribe(self)
return self
end
function Kim:key_down(key, modifiers)
local distance = 64
local moved = false
if key == 1 then -- Left / A
self.origin[1] = self.origin[1] - distance
moved = true
elseif key == 4 then -- Right / D
self.origin[1] = self.origin[1] + distance
moved = true
elseif key == 19 then -- Down / S
self.origin[2] = self.origin[2] - distance
moved = true
elseif key == 23 then -- Up / W
self.origin[2] = self.origin[2] + distance
moved = true
end
if moved then
local screen = rainbow.platform.screen
rainbow.renderer.set_projection(
self.origin[1],
self.origin[2],
self.origin[1] + screen.width,
self.origin[2] + screen.height)
end
end
function Kim:key_up()
end
function Kim:pointer_began(pointers)
-- Cancel the previous transitions.
self.alpha:cancel()
self.moving:cancel()
if self.alternate then
-- Rotate 360 degrees in 1 second. Linear effect.
local angle = self.sprite:get_angle() + Math.radians(360)
self.moving = Transition.rotate(self.sprite, angle, 1000)
self.alpha = Transition.fadeto(self.sprite, 0x40, 1000)
self.alternate = false
else
-- Move to point in 0.5 seconds. Squared ease-in effect.
for h,p in pairs(pointers) do
local x, y = self.sprite:get_position()
self.moving = Transition.move(self.node, p.x - x, p.y - y, 500, Transition.Functions.easeinout_cubic)
self.alpha = Transition.fadeto(self.sprite, 0xff, 500)
self.alternate = true
break
end
end
end
-- We don't care about these events.
function Kim:pointer_canceled() end
function Kim:pointer_ended() end
function Kim:pointer_moved() end
|
Fixed 'transitions' demo's camera and input handling.
|
Fixed 'transitions' demo's camera and input handling.
|
Lua
|
mit
|
tn0502/rainbow,tn0502/rainbow,tn0502/rainbow,tn0502/rainbow,tn0502/rainbow,tn0502/rainbow
|
a431f7765fec650d5b8b00f6041c490f563d9c54
|
lua/entities/gmod_wire_expression2/core/strfunc.lua
|
lua/entities/gmod_wire_expression2/core/strfunc.lua
|
local function nicename( word )
local ret = word:lower()
if ret == "normal" then return "number" end
return ret
end
local function checkFuncName( self, funcname )
if self.funcs[funcname] then
return self.funcs[funcname], self.funcs_ret[funcname]
elseif wire_expression2_funcs[funcname] then
return wire_expression2_funcs[funcname][3], wire_expression2_funcs[funcname][2]
end
end
registerCallback("construct", function(self) self.strfunc_cache = {} end)
local insert = table.insert
local concat = table.concat
local function findFunc( self, funcname, typeids, typeids_str )
local func, func_return_type
self.prf = self.prf + 1
local str = funcname .. "(" .. typeids_str .. ")"
for i=1,#self.strfunc_cache do
local t = self.strfunc_cache[i]
if t[1] == str then
return t[2], t[3]
end
end
self.prf = self.prf + 2
if #typeids > 0 then
if not func then
func, func_return_type = checkFuncName( self, str )
end
if not func then
func, func_return_type = checkFuncName( self, funcname .. "(" .. typeids[1] .. ":" .. concat(typeids,"",2) .. ")" )
end
if not func then
for i=#typeids,1,-1 do
func, func_return_type = checkFuncName( self, funcname .. "(" .. concat(typeids,"",1,i) .. "...)" )
if func then break end
end
if not func then
func, func_return_type = checkFuncName( self, funcname .. "(...)" )
end
end
if not func then
for i=#typeids,2,-1 do
func, func_return_type = checkFuncName( self, funcname .. "(" .. typeids[1] .. ":" .. concat(typeids,"",2,i) .. "...)" )
if func then break end
end
if not func then
func, func_return_type = checkFuncName( self, funcname .. "(" .. typeids[1] .. ":...)" )
end
end
else
func, func_return_type = checkFuncName( self, funcname .. "()" )
end
if func then
local t = { str, func, func_return_type }
insert( self.strfunc_cache, 1, t )
if #self.strfunc_cache == 21 then self.strfunc_cache[21] = nil end
end
return func, func_return_type
end
__e2setcost(6)
registerOperator( "sfun", "", "", function(self, args)
local op1, funcargs, typeids, typeids_str, returntype = args[2], args[3], args[4], args[5], args[6]
local funcname = op1[1](self,op1)
local func, func_return_type = findFunc( self, funcname, typeids, typeids_str )
if not func then error( "No function with the specified arguments exists", 0 ) end
if returntype ~= "" and func_return_type ~= returntype then
error( "Mismatching return types. Got " .. nicename(wire_expression_types2[returntype][1]) .. ", expected " .. nicename(wire_expression_types2[func_return_type][1] ), 0 )
end
if returntype ~= "" then
return func( self, funcargs )
else
func( self, funcargs )
end
end)
|
local function nicename( word )
local ret = word:lower()
if ret == "normal" then return "number" end
return ret
end
local function checkFuncName( self, funcname )
if self.funcs[funcname] then
return self.funcs[funcname], self.funcs_ret[funcname]
elseif wire_expression2_funcs[funcname] then
return wire_expression2_funcs[funcname][3], wire_expression2_funcs[funcname][2]
end
end
registerCallback("construct", function(self) self.strfunc_cache = {} end)
local insert = table.insert
local concat = table.concat
local function findFunc( self, funcname, typeids, typeids_str )
local func, func_return_type, vararg
self.prf = self.prf + 40
local str = funcname .. "(" .. typeids_str .. ")"
for i=1,#self.strfunc_cache do
local t = self.strfunc_cache[i]
if t[1] == str then
return t[2], t[3]
end
end
self.prf = self.prf + 40
if #typeids > 0 then
if not func then
func, func_return_type = checkFuncName( self, str )
end
if not func then
func, func_return_type = checkFuncName( self, funcname .. "(" .. typeids[1] .. ":" .. concat(typeids,"",2) .. ")" )
end
if not func then
for i=#typeids,1,-1 do
func, func_return_type = checkFuncName( self, funcname .. "(" .. concat(typeids,"",1,i) .. "...)" )
if func then vararg = true break end
end
if not func then
func, func_return_type = checkFuncName( self, funcname .. "(...)" )
if func then vararg = true end
end
end
if not func then
for i=#typeids,2,-1 do
func, func_return_type = checkFuncName( self, funcname .. "(" .. typeids[1] .. ":" .. concat(typeids,"",2,i) .. "...)" )
if func then vararg = true break end
end
if not func then
func, func_return_type = checkFuncName( self, funcname .. "(" .. typeids[1] .. ":...)" )
if func then vararg = true end
end
end
else
func, func_return_type = checkFuncName( self, funcname .. "()" )
end
if func then
local t = { str, func, func_return_type }
insert( self.strfunc_cache, 1, t )
if #self.strfunc_cache == 21 then self.strfunc_cache[21] = nil end
end
return func, func_return_type, vararg
end
__e2setcost(20)
registerOperator( "sfun", "", "", function(self, args)
local op1, funcargs, typeids, typeids_str, returntype = args[2], args[3], args[4], args[5], args[6]
local funcname = op1[1](self,op1)
local func, func_return_type, vararg = findFunc( self, funcname, typeids, typeids_str )
if not func then error( "No function with the specified arguments exists", 0 ) end
if returntype ~= "" and func_return_type ~= returntype then
error( "Mismatching return types. Got " .. nicename(wire_expression_types2[returntype][1]) .. ", expected " .. nicename(wire_expression_types2[func_return_type][1] ), 0 )
end
self.prf = self.prf + 40
if vararg then
funcargs[1] = function(self,arg) return arg[1] end
funcargs[#funcargs+1] = typeids
funcargs.TraceName = "FUN"
end
if returntype ~= "" then
return func( self, funcargs )
else
func( self, funcargs )
end
end)
|
Made calling functions by strings more expensive
|
Made calling functions by strings more expensive
Made calling functions by strings more expensive to match normal function calls.
Also fixed calling functions with varargs (...)
|
Lua
|
apache-2.0
|
mms92/wire,wiremod/wire,sammyt291/wire,immibis/wiremod,notcake/wire,mitterdoo/wire,Grocel/wire,dvdvideo1234/wire,garrysmodlua/wire,plinkopenguin/wiremod,bigdogmat/wire,CaptainPRICE/wire,NezzKryptic/Wire,thegrb93/wire,Python1320/wire,rafradek/wire
|
26c45850a83e6956129429550e13bb582e405740
|
Module.lua
|
Module.lua
|
local Module = torch.class('nn.Module')
function Module:__init()
self.gradInput = torch.Tensor()
self.output = torch.Tensor()
end
function Module:parameters()
if self.weight and self.bias then
return {self.weight, self.bias}, {self.gradWeight, self.gradBias}
elseif self.weight then
return {self.weight}, {self.gradWeight}
elseif self.bias then
return {self.bias}, {self.gradBias}
else
return
end
end
function Module:updateOutput(input)
return self.output
end
function Module:forward(input)
return self:updateOutput(input)
end
function Module:backward(input, gradOutput)
self:updateGradInput(input, gradOutput)
self:accGradParameters(input, gradOutput)
return self.gradInput
end
function Module:backwardUpdate(input, gradOutput, lr)
self:updateGradInput(input, gradOutput)
self:accUpdateGradParameters(input, gradOutput, lr)
return self.gradInput
end
function Module:updateGradInput(input, gradOutput)
return self.gradInput
end
function Module:accGradParameters(input, gradOutput, scale)
end
function Module:accUpdateGradParameters(input, gradOutput, lr)
local gradWeight = self.gradWeight
local gradBias = self.gradBias
self.gradWeight = self.weight
self.gradBias = self.bias
self:accGradParameters(input, gradOutput, -lr)
self.gradWeight = gradWeight
self.gradBias = gradBias
end
function Module:sharedAccUpdateGradParameters(input, gradOutput, lr)
if self:parameters() then
self:zeroGradParameters()
self:accGradParameters(input, gradOutput, 1)
self:updateParameters(lr)
end
end
function Module:zeroGradParameters()
local _,gradParams = self:parameters()
if gradParams then
for i=1,#gradParams do
gradParams[i]:zero()
end
end
end
function Module:updateParameters(learningRate)
local params, gradParams = self:parameters()
if params then
for i=1,#params do
params[i]:add(-learningRate, gradParams[i])
end
end
end
function Module:share(mlp, ...)
local arg = {...}
for i,v in ipairs(arg) do
if self[v] ~= nil then
self[v]:set(mlp[v])
self.accUpdateGradParameters = self.sharedAccUpdateGradParameters
mlp.accUpdateGradParameters = mlp.sharedAccUpdateGradParameters
end
end
return self
end
function Module:clone(...)
local f = torch.MemoryFile("rw"):binary()
f:writeObject(self)
f:seek(1)
local clone = f:readObject()
f:close()
if select('#',...) > 0 then
clone:share(self,...)
end
return clone
end
function Module:type(type)
-- find all tensors and convert them
for key,param in pairs(self) do
if torch.typename(param) and torch.typename(param):find('torch%..+Tensor') then
self[key] = param:type(type)
end
end
-- find submodules in classic containers 'modules'
if self.modules then
for _,module in ipairs(self.modules) do
module:type(type)
end
end
return self
end
function Module:float()
return self:type('torch.FloatTensor')
end
function Module:double()
return self:type('torch.DoubleTensor')
end
function Module:cuda()
return self:type('torch.CudaTensor')
end
function Module:reset()
end
function Module:getParameters()
-- get parameters
local parameters,gradParameters = self:parameters()
local function storageInSet(set, storage) --this is waste of time (need correct hash)
for key, val in pairs(set) do
if key == storage then
return val
end
end
end
-- this function flattens arbitrary lists of parameters,
-- even complex shared ones
local function flatten(parameters)
local storages = {}
local nParameters = 0
for k = 1,#parameters do
if not storageInSet(storages, parameters[k]:storage()) then
storages[parameters[k]:storage()] = nParameters
nParameters = nParameters + parameters[k]:storage():size()
end
end
local flatParameters = torch.Tensor(nParameters):fill(1)
local flatStorage = flatParameters:storage()
for k = 1,#parameters do
local storageOffset = storageInSet(storages, parameters[k]:storage())
parameters[k]:set(flatStorage,
storageOffset + parameters[k]:storageOffset(),
parameters[k]:size(),
parameters[k]:stride())
parameters[k]:zero()
end
local cumSumOfHoles = flatParameters:cumsum(1)
local nUsedParameters = nParameters - cumSumOfHoles[#cumSumOfHoles]
local flatUsedParameters = torch.Tensor(nUsedParameters)
local flatUsedStorage = flatUsedParameters:storage()
for k = 1,#parameters do
local offset = cumSumOfHoles[parameters[k]:storageOffset()]
parameters[k]:set(flatUsedStorage,
parameters[k]:storageOffset() - offset,
parameters[k]:size(),
parameters[k]:stride())
end
for k, v in pairs(storages) do
flatParameters[{{v+1,v+k:size()}}]:copy(torch.Tensor():set(k))
end
for k = 1,flatUsedParameters:nElement() do
flatUsedParameters[k] = flatParameters[k+cumSumOfHoles[k] ]
end
return flatUsedParameters
end
-- flatten parameters and gradients
local flatParameters = flatten(parameters)
local flatGradParameters = flatten(gradParameters)
-- return new flat vector that contains all discrete parameters
return flatParameters, flatGradParameters
end
function Module:__call__(input, gradOutput)
self:forward(input)
if gradOutput then
self:backward(input, gradOutput)
return self.output, self.gradInput
else
return self.output
end
end
|
local Module = torch.class('nn.Module')
function Module:__init()
self.gradInput = torch.Tensor()
self.output = torch.Tensor()
end
function Module:parameters()
if self.weight and self.bias then
return {self.weight, self.bias}, {self.gradWeight, self.gradBias}
elseif self.weight then
return {self.weight}, {self.gradWeight}
elseif self.bias then
return {self.bias}, {self.gradBias}
else
return
end
end
function Module:updateOutput(input)
return self.output
end
function Module:forward(input)
return self:updateOutput(input)
end
function Module:backward(input, gradOutput)
self:updateGradInput(input, gradOutput)
self:accGradParameters(input, gradOutput)
return self.gradInput
end
function Module:backwardUpdate(input, gradOutput, lr)
self:updateGradInput(input, gradOutput)
self:accUpdateGradParameters(input, gradOutput, lr)
return self.gradInput
end
function Module:updateGradInput(input, gradOutput)
return self.gradInput
end
function Module:accGradParameters(input, gradOutput, scale)
end
function Module:accUpdateGradParameters(input, gradOutput, lr)
local gradWeight = self.gradWeight
local gradBias = self.gradBias
self.gradWeight = self.weight
self.gradBias = self.bias
self:accGradParameters(input, gradOutput, -lr)
self.gradWeight = gradWeight
self.gradBias = gradBias
end
function Module:sharedAccUpdateGradParameters(input, gradOutput, lr)
if self:parameters() then
self:zeroGradParameters()
self:accGradParameters(input, gradOutput, 1)
self:updateParameters(lr)
end
end
function Module:zeroGradParameters()
local _,gradParams = self:parameters()
if gradParams then
for i=1,#gradParams do
gradParams[i]:zero()
end
end
end
function Module:updateParameters(learningRate)
local params, gradParams = self:parameters()
if params then
for i=1,#params do
params[i]:add(-learningRate, gradParams[i])
end
end
end
function Module:share(mlp, ...)
local arg = {...}
for i,v in ipairs(arg) do
if self[v] ~= nil then
self[v]:set(mlp[v])
self.accUpdateGradParameters = self.sharedAccUpdateGradParameters
mlp.accUpdateGradParameters = mlp.sharedAccUpdateGradParameters
end
end
return self
end
function Module:clone(...)
local f = torch.MemoryFile("rw"):binary()
f:writeObject(self)
f:seek(1)
local clone = f:readObject()
f:close()
if select('#',...) > 0 then
clone:share(self,...)
end
return clone
end
function Module:type(type)
-- find all tensors and convert them
for key,param in pairs(self) do
if torch.typename(param) and torch.typename(param):find('torch%..+Tensor') then
self[key] = param:type(type)
end
end
-- find submodules in classic containers 'modules'
if self.modules then
for _,module in ipairs(self.modules) do
module:type(type)
end
end
return self
end
function Module:float()
return self:type('torch.FloatTensor')
end
function Module:double()
return self:type('torch.DoubleTensor')
end
function Module:cuda()
return self:type('torch.CudaTensor')
end
function Module:reset()
end
function Module:getParameters()
-- get parameters
local parameters,gradParameters = self:parameters()
local function storageInSet(set, storage) --this is waste of time (need correct hash)
for key, val in pairs(set) do
if key == storage then
return val
end
end
end
-- this function flattens arbitrary lists of parameters,
-- even complex shared ones
local function flatten(parameters)
local Tensor = parameters[1].new
local storages = {}
local nParameters = 0
for k = 1,#parameters do
if not storageInSet(storages, parameters[k]:storage()) then
storages[parameters[k]:storage()] = nParameters
nParameters = nParameters + parameters[k]:storage():size()
end
end
local flatParameters = Tensor(nParameters):fill(1)
local flatStorage = flatParameters:storage()
for k = 1,#parameters do
local storageOffset = storageInSet(storages, parameters[k]:storage())
parameters[k]:set(flatStorage,
storageOffset + parameters[k]:storageOffset(),
parameters[k]:size(),
parameters[k]:stride())
parameters[k]:zero()
end
local cumSumOfHoles = flatParameters:float():cumsum(1)
local nUsedParameters = nParameters - cumSumOfHoles[#cumSumOfHoles]
local flatUsedParameters = Tensor(nUsedParameters)
local flatUsedStorage = flatUsedParameters:storage()
for k = 1,#parameters do
local offset = cumSumOfHoles[parameters[k]:storageOffset()]
parameters[k]:set(flatUsedStorage,
parameters[k]:storageOffset() - offset,
parameters[k]:size(),
parameters[k]:stride())
end
for k, v in pairs(storages) do
flatParameters[{{v+1,v+k:size()}}]:copy(Tensor():set(k))
end
for k = 1,flatUsedParameters:nElement() do
flatUsedParameters[k] = flatParameters[k+cumSumOfHoles[k] ]
end
return flatUsedParameters
end
-- flatten parameters and gradients
local flatParameters = flatten(parameters)
local flatGradParameters = flatten(gradParameters)
-- return new flat vector that contains all discrete parameters
return flatParameters, flatGradParameters
end
function Module:__call__(input, gradOutput)
self:forward(input)
if gradOutput then
self:backward(input, gradOutput)
return self.output, self.gradInput
else
return self.output
end
end
|
Fixed getParameters() for CUDA. When did that break?
|
Fixed getParameters() for CUDA. When did that break?
|
Lua
|
bsd-3-clause
|
eriche2016/nn,aaiijmrtt/nn,sagarwaghmare69/nn,mlosch/nn,forty-2/nn,zhangxiangxiao/nn,ominux/nn,karpathy/nn,adamlerer/nn,diz-vara/nn,apaszke/nn,lukasc-ch/nn,PierrotLC/nn,rickyHong/nn_lib_torch,hery/nn,nicholas-leonard/nn,colesbury/nn,davidBelanger/nn,caldweln/nn,GregSatre/nn,xianjiec/nn,ivendrov/nn,clementfarabet/nn,vgire/nn,douwekiela/nn,rotmanmi/nn,szagoruyko/nn,EnjoyHacking/nn,jzbontar/nn,mys007/nn,PraveerSINGH/nn,andreaskoepf/nn,bartvm/nn,Aysegul/nn,LinusU/nn,sbodenstein/nn,abeschneider/nn,hughperkins/nn,fmassa/nn,lvdmaaten/nn,joeyhng/nn,soumith/nn,jonathantompson/nn,zchengquan/nn,jhjin/nn,Moodstocks/nn,kmul00/nn,boknilev/nn,witgo/nn,eulerreich/nn,noa/nn,elbamos/nn,Jeffyrao/nn,Djabbz/nn
|
5305902f1be0754f58f23d78e7aaab4b8e97f9e6
|
plugins/time.lua
|
plugins/time.lua
|
local command = 'time <$location*>'
local doc = [[*Utilize os seguite comandos citados abaixo:*
*________________________*
`/horas [`*local*`]` - Para o bot informar que horas são em sua cidade ou local mencionado.]]
local action = function(msg)
local input = msg.text:input()
if not input then
if msg.reply_to_message and msg.reply_to_message.text then
input = msg.reply_to_message.text
else
sendMessage(msg.chat.id, [[
*Utilize os seguite comandos citados abaixo:*
*________________________*
`/horas [`*local*`]` - Para o bot informar que horas são em sua cidade ou local mencionado.
]], true, msg.message_id, true)
return
end
end
local coords = get_coords(input)
if type(coords) == 'string' then
api.sendReply(msg, coords)
return
end
local url = 'https://maps.googleapis.com/maps/api/timezone/json?location=' .. coords.lat ..','.. coords.lon .. '×tamp='..os.time()
local jstr, res = HTTPS.request(url)
if res ~= 200 then
sendReply(msg, config.errors.connection)
return
end
local jdat = JSON.decode(jstr)
local timestamp = os.time(os.date("!*t"))
local localTime = timestamp + jdat.rawOffset + jdat.dstOffset
sendReply(msg, os.date('Pelo meu relogio em '..input..' agora são: %H:%M:%S %p', localTime))
end
return {
action = action,
doc = doc,
command = command,
triggers = {
'^/time[@'..bot.username..']*',
'^/data[@'..bot.username..']*',
'^/hora[@'..bot.username..']*'
}
}
|
local command = 'time <$location*>'
local doc = [[```
/time <$location*>
$doc_time*.
```]]
local triggers = {
'^/time[@'..bot.username..']*',
'^/hora[@'..bot.username..']*',
'^/date[@'..bot.username..']*',
'^/data[@'..bot.username..']*'
}
local action = function(msg)
local input = msg.text:input()
if not input then
if msg.reply_to_message and msg.reply_to_message.text then
input = msg.reply_to_message.text
else
sendMessage(msg.chat.id, sendLang(doc, lang), true, msg.message_id, true)
return
end
end
local coords = get_coords(input)
if type(coords) == 'string' then
sendReply(msg, coords)
return
end
local url = 'https://maps.googleapis.com/maps/api/timezone/json?location=' .. coords.lat ..','.. coords.lon .. '×tamp='..os.time(os.date('!*t'))
local jstr, res = HTTPS.request(url)
if res ~= 200 then
sendReply(msg, config.errors.connection)
return
end
local jdat = JSON.decode(jstr)
local timestamp = os.time(os.date('!*t')) + jdat.rawOffset + jdat.dstOffset + config.time_offset
local utcoff = (jdat.rawOffset + jdat.dstOffset) / 3600
if utcoff == math.abs(utcoff) then
utcoff = '+' .. utcoff
end
local message = os.date('%I:%M %p\n', timestamp) .. os.date('%A, %B %d, %Y\n', timestamp) .. jdat.timeZoneName .. ' (UTC' .. utcoff .. ')'
sendReply(msg, message)
end
return {
action = action,
triggers = triggers,
doc = doc,
command = command
}
|
FIX e Update Time
|
FIX e Update Time
|
Lua
|
agpl-3.0
|
TiagoDanin/SiD
|
ea506f853a4cf03d9fd28cd615b523d441298c07
|
src_trunk/resources/realism-system/s_alarm.lua
|
src_trunk/resources/realism-system/s_alarm.lua
|
function pickLock(thePlayer)
if(isVehicleLocked(source))then
CarAlarm(source, thePlayer)
end
end
addEventHandler("onVehicleStartEnter", getRootElement(), pickLock)
function CarAlarm(theVehicle, thePlayer)
if ( getVehicleOverrideLights ( theVehicle ) ~= 2 ) then -- if the current state isn't 'force on'
setVehicleOverrideLights ( theVehicle, 2 ) -- force the lights on
else
setVehicleOverrideLights ( theVehicle, 1 ) -- otherwise, force the lights off
end
local carX, carY, carZ = getElementPosition( theVehicle )
local alarmSphere = createColSphere( carX, carY, carZ, 200 )
exports.pool:allocateElement(alarmSphere) -- Create the colSphere for chat output to local players
local targetPlayers = getElementsWithinColShape( alarmSphere, "player" )
for i, key in ipairs( targetPlayers ) do
playSoundFrontEnd(key, 2)
end
destroyElement (alarmSphere)
end
|
function pickLock(thePlayer)
if(isVehicleLocked(source))then
--CarAlarm(source, thePlayer)
setTimer(CarAlarm, 1000, 20, source, thePlayer)
end
end
addEventHandler("onVehicleStartEnter", getRootElement(), pickLock)
function CarAlarm(theVehicle, thePlayer)
if ( getVehicleOverrideLights ( theVehicle ) ~= 2 ) then -- if the current state isn't 'force on'
setVehicleOverrideLights ( theVehicle, 2 ) -- force the lights on
else
setVehicleOverrideLights ( theVehicle, 1 ) -- otherwise, force the lights off
end
local carX, carY, carZ = getElementPosition( theVehicle )
local alarmSphere = createColSphere( carX, carY, carZ, 200 )
exports.pool:allocateElement(alarmSphere) -- Create the colSphere for chat output to local players
local targetPlayers = getElementsWithinColShape( alarmSphere, "player" )
for i, key in ipairs( targetPlayers ) do
playSoundFrontEnd(key, 2)
end
destroyElement (alarmSphere)
end
|
Fix for car alarms v2
|
Fix for car alarms v2
git-svn-id: 8769cb08482c9977c94b72b8e184ec7d2197f4f7@506 64450a49-1f69-0410-a0a2-f5ebb52c4f5b
|
Lua
|
bsd-3-clause
|
valhallaGaming/uno,valhallaGaming/uno,valhallaGaming/uno
|
de10433ddf99127e5ef25a73c0b4500072764057
|
mod_listusers/mod_listusers.lua
|
mod_listusers/mod_listusers.lua
|
function module.command(args)
local action = table.remove(args, 1);
if not action then -- Default, list registered users
local data_path = CFG_DATADIR or "data";
if not pcall(require, "luarocks.loader") then
pcall(require, "luarocks.require");
end
local lfs = require "lfs";
function decode(s)
return s:gsub("%%([a-fA-F0-9][a-fA-F0-9])", function (c)
return string.char(tonumber("0x"..c));
end);
end
for host in lfs.dir(data_path) do
local accounts = data_path.."/"..host.."/accounts";
if lfs.attributes(accounts, "mode") == "directory" then
for user in lfs.dir(accounts) do
if user:sub(1,1) ~= "." then
print(decode(user:gsub("%.dat$", "")).."@"..decode(host));
end
end
end
end
elseif action == "--connected" then -- List connected users
local socket = require "socket";
local default_local_interfaces = { };
if socket.tcp6 and config.get("*", "use_ipv6") ~= false then
table.insert(default_local_interfaces, "::1");
end
if config.get("*", "use_ipv4") ~= false then
table.insert(default_local_interfaces, "127.0.0.1");
end
local console_interfaces = config.get("*", "console_interfaces")
or config.get("*", "local_interfaces")
or default_local_interfaces
console_interfaces = type(console_interfaces)~="table"
and {console_interfaces} or console_interfaces;
local console_ports = config.get("*", "console_ports") or 5582
console_ports = type(console_ports) ~= "table" and { console_ports } or console_ports;
local st, conn = pcall(assert,socket.connect(console_interfaces[1], console_ports[1]));
if (not st) then print("Error"..(conn and ": "..conn or "")); return 1; end
conn:send("c2s:show()\n");
conn:settimeout(1); -- Only hit in case of failure
repeat local line = conn:receive()
if not line then break; end
local jid = line:match("^| (.+)$");
if jid then
jid = jid:gsub(" %- (%w+%(%d+%))$", "\t%1");
print(jid);
elseif line:match("^| OK:") then
return 0;
end
until false;
end
return 0;
end
|
function module.command(args)
local action = table.remove(args, 1);
if not action then -- Default, list registered users
local data_path = CFG_DATADIR or "data";
if not pcall(require, "luarocks.loader") then
pcall(require, "luarocks.require");
end
local lfs = require "lfs";
function decode(s)
return s:gsub("%%([a-fA-F0-9][a-fA-F0-9])", function (c)
return string.char(tonumber("0x"..c));
end);
end
for host in lfs.dir(data_path) do
local accounts = data_path.."/"..host.."/accounts";
if lfs.attributes(accounts, "mode") == "directory" then
for user in lfs.dir(accounts) do
if user:sub(1,1) ~= "." then
print(decode(user:gsub("%.dat$", "")).."@"..decode(host));
end
end
end
end
elseif action == "--connected" then -- List connected users
local socket = require "socket";
local default_local_interfaces = { };
if socket.tcp6 and config.get("*", "use_ipv6") ~= false then
table.insert(default_local_interfaces, "::1");
end
if config.get("*", "use_ipv4") ~= false then
table.insert(default_local_interfaces, "127.0.0.1");
end
local console_interfaces = config.get("*", "console_interfaces")
or config.get("*", "local_interfaces")
or default_local_interfaces
console_interfaces = type(console_interfaces)~="table"
and {console_interfaces} or console_interfaces;
local console_ports = config.get("*", "console_ports") or 5582
console_ports = type(console_ports) ~= "table" and { console_ports } or console_ports;
local st, conn = pcall(assert,socket.connect(console_interfaces[1], console_ports[1]));
if (not st) then print("Error"..(conn and ": "..conn or "")); return 1; end
local banner = config.get("*", "console_banner");
if (
(not banner) or
(
(type(banner) == "string") and
(banner:match("^| (.+)$"))
)
) then
repeat
local rec_banner = conn:receive()
until
rec_banner == "" or
rec_banner == nil; -- skip banner
end
conn:send("c2s:show()\n");
conn:settimeout(1); -- Only hit in case of failure
repeat local line = conn:receive()
if not line then break; end
local jid = line:match("^| (.+)$");
if jid then
jid = jid:gsub(" %- (%w+%(%d+%))$", "\t%1");
print(jid);
elseif line:match("^| OK:") then
return 0;
end
until false;
end
return 0;
end
|
mod_listusers: fixed banner skipping cycle
|
mod_listusers: fixed banner skipping cycle
|
Lua
|
mit
|
cryptotoad/prosody-modules,jkprg/prosody-modules,BurmistrovJ/prosody-modules,vfedoroff/prosody-modules,vince06fr/prosody-modules,jkprg/prosody-modules,mmusial/prosody-modules,syntafin/prosody-modules,softer/prosody-modules,brahmi2/prosody-modules,stephen322/prosody-modules,joewalker/prosody-modules,Craige/prosody-modules,obelisk21/prosody-modules,vince06fr/prosody-modules,olax/prosody-modules,crunchuser/prosody-modules,cryptotoad/prosody-modules,syntafin/prosody-modules,asdofindia/prosody-modules,guilhem/prosody-modules,jkprg/prosody-modules,obelisk21/prosody-modules,mmusial/prosody-modules,Craige/prosody-modules,prosody-modules/import,NSAKEY/prosody-modules,LanceJenkinZA/prosody-modules,guilhem/prosody-modules,dhotson/prosody-modules,1st8/prosody-modules,1st8/prosody-modules,LanceJenkinZA/prosody-modules,vfedoroff/prosody-modules,vince06fr/prosody-modules,stephen322/prosody-modules,heysion/prosody-modules,crunchuser/prosody-modules,brahmi2/prosody-modules,prosody-modules/import,1st8/prosody-modules,1st8/prosody-modules,softer/prosody-modules,softer/prosody-modules,syntafin/prosody-modules,obelisk21/prosody-modules,mardraze/prosody-modules,vince06fr/prosody-modules,vince06fr/prosody-modules,amenophis1er/prosody-modules,prosody-modules/import,crunchuser/prosody-modules,guilhem/prosody-modules,LanceJenkinZA/prosody-modules,olax/prosody-modules,apung/prosody-modules,BurmistrovJ/prosody-modules,drdownload/prosody-modules,amenophis1er/prosody-modules,Craige/prosody-modules,vfedoroff/prosody-modules,asdofindia/prosody-modules,dhotson/prosody-modules,olax/prosody-modules,LanceJenkinZA/prosody-modules,Craige/prosody-modules,syntafin/prosody-modules,softer/prosody-modules,iamliqiang/prosody-modules,mardraze/prosody-modules,joewalker/prosody-modules,either1/prosody-modules,apung/prosody-modules,mmusial/prosody-modules,brahmi2/prosody-modules,cryptotoad/prosody-modules,stephen322/prosody-modules,mardraze/prosody-modules,drdownload/prosody-modules,LanceJenkinZA/prosody-modules,syntafin/prosody-modules,asdofindia/prosody-modules,mmusial/prosody-modules,obelisk21/prosody-modules,dhotson/prosody-modules,BurmistrovJ/prosody-modules,prosody-modules/import,BurmistrovJ/prosody-modules,either1/prosody-modules,amenophis1er/prosody-modules,jkprg/prosody-modules,amenophis1er/prosody-modules,either1/prosody-modules,NSAKEY/prosody-modules,dhotson/prosody-modules,mardraze/prosody-modules,NSAKEY/prosody-modules,olax/prosody-modules,asdofindia/prosody-modules,1st8/prosody-modules,mmusial/prosody-modules,heysion/prosody-modules,iamliqiang/prosody-modules,iamliqiang/prosody-modules,olax/prosody-modules,cryptotoad/prosody-modules,joewalker/prosody-modules,cryptotoad/prosody-modules,heysion/prosody-modules,heysion/prosody-modules,Craige/prosody-modules,softer/prosody-modules,asdofindia/prosody-modules,drdownload/prosody-modules,stephen322/prosody-modules,joewalker/prosody-modules,either1/prosody-modules,NSAKEY/prosody-modules,stephen322/prosody-modules,guilhem/prosody-modules,NSAKEY/prosody-modules,guilhem/prosody-modules,BurmistrovJ/prosody-modules,iamliqiang/prosody-modules,apung/prosody-modules,mardraze/prosody-modules,prosody-modules/import,vfedoroff/prosody-modules,apung/prosody-modules,brahmi2/prosody-modules,heysion/prosody-modules,obelisk21/prosody-modules,dhotson/prosody-modules,joewalker/prosody-modules,crunchuser/prosody-modules,drdownload/prosody-modules,either1/prosody-modules,crunchuser/prosody-modules,apung/prosody-modules,jkprg/prosody-modules,iamliqiang/prosody-modules,brahmi2/prosody-modules,vfedoroff/prosody-modules,amenophis1er/prosody-modules,drdownload/prosody-modules
|
05cc92a5bbbf31c2a123e8742d423536c852d673
|
mod_seclabels/mod_seclabels.lua
|
mod_seclabels/mod_seclabels.lua
|
local st = require "util.stanza";
local xmlns_label = "urn:xmpp:sec-label:0";
local xmlns_label_catalog = "urn:xmpp:sec-label:catalog:2";
local xmlns_label_catalog_old = "urn:xmpp:sec-label:catalog:0"; -- COMPAT
module:add_feature(xmlns_label);
module:add_feature(xmlns_label_catalog);
module:add_feature(xmlns_label_catalog_old);
module:hook("account-disco-info", function(event) -- COMPAT
local stanza = event.stanza;
stanza:tag('feature', {var=xmlns_label}):up();
stanza:tag('feature', {var=xmlns_label_catalog}):up();
end);
local default_labels = {
Classified = {
SECRET = { color = "black", bgcolor = "aqua", label = "THISISSECRET" };
PUBLIC = { label = "THISISPUBLIC" };
};
};
local catalog_name, catalog_desc, labels;
function get_conf()
catalog_name = module:get_option_string("security_catalog_name", "Default");
catalog_desc = module:get_option_string("security_catalog_desc", "My labels");
labels = module:get_option("security_labels", default_labels);
end
module:hook("config-reloaded",get_conf);
get_conf();
function handle_catalog_request(request)
local catalog_request = request.stanza.tags[1];
local reply = st.reply(request.stanza)
:tag("catalog", {
xmlns = catalog_request.attr.xmlns,
to = catalog_request.attr.to,
name = catalog_name,
desc = catalog_desc
});
local function add_labels(catalog, labels, selector)
for name, value in pairs(labels) do
if value.label then
if catalog_request.attr.xmlns == xmlns_label_catalog then
catalog:tag("item", {
selector = selector..name,
default = value.default and "true" or nil,
}):tag("securitylabel", { xmlns = xmlns_label })
else -- COMPAT
catalog:tag("securitylabel", {
xmlns = xmlns_label,
selector = selector..name,
default = value.default and "true" or nil,
})
end
if value.name or value.color or value.bgcolor then
catalog:tag("displaymarking", {
fgcolor = value.color,
bgcolor = value.bgcolor,
}):text(value.name or name):up();
end
if type(value.label) == "string" then
catalog:tag("label"):text(value.label):up();
elseif type(value.label) == "table" then
catalog:tag("label"):add_child(value.label):up();
end
catalog:up();
if catalog_request.attr.xmlns == xmlns_label_catalog then
catalog:up();
end
else
add_labels(catalog, value, (selector or "")..name.."|");
end
end
end
add_labels(reply, labels, "");
request.origin.send(reply);
return true;
end
module:hook("iq/host/"..xmlns_label_catalog..":catalog", handle_catalog_request);
module:hook("iq/self/"..xmlns_label_catalog..":catalog", handle_catalog_request); -- COMPAT
module:hook("iq/self/"..xmlns_label_catalog_old..":catalog", handle_catalog_request); -- COMPAT
|
local st = require "util.stanza";
local xmlns_label = "urn:xmpp:sec-label:0";
local xmlns_label_catalog = "urn:xmpp:sec-label:catalog:2";
local xmlns_label_catalog_old = "urn:xmpp:sec-label:catalog:0"; -- COMPAT
module:add_feature(xmlns_label);
module:add_feature(xmlns_label_catalog);
module:add_feature(xmlns_label_catalog_old);
module:hook("account-disco-info", function(event) -- COMPAT
local stanza = event.stanza;
stanza:tag('feature', {var=xmlns_label}):up();
stanza:tag('feature', {var=xmlns_label_catalog}):up();
end);
local default_labels = {
Classified = {
SECRET = { color = "black", bgcolor = "aqua", label = "THISISSECRET" };
PUBLIC = { label = "THISISPUBLIC" };
};
};
local catalog_name, catalog_desc, labels;
local function get_conf()
catalog_name = module:get_option_string("security_catalog_name", "Default");
catalog_desc = module:get_option_string("security_catalog_desc", "My labels");
labels = module:get_option("security_labels", default_labels);
end
module:hook_global("config-reloaded",get_conf);
get_conf();
function handle_catalog_request(request)
local catalog_request = request.stanza.tags[1];
local reply = st.reply(request.stanza)
:tag("catalog", {
xmlns = catalog_request.attr.xmlns,
to = catalog_request.attr.to,
name = catalog_name,
desc = catalog_desc
});
local function add_labels(catalog, labels, selector)
for name, value in pairs(labels) do
if value.label then
if catalog_request.attr.xmlns == xmlns_label_catalog then
catalog:tag("item", {
selector = selector..name,
default = value.default and "true" or nil,
}):tag("securitylabel", { xmlns = xmlns_label })
else -- COMPAT
catalog:tag("securitylabel", {
xmlns = xmlns_label,
selector = selector..name,
default = value.default and "true" or nil,
})
end
if value.name or value.color or value.bgcolor then
catalog:tag("displaymarking", {
fgcolor = value.color,
bgcolor = value.bgcolor,
}):text(value.name or name):up();
end
if type(value.label) == "string" then
catalog:tag("label"):text(value.label):up();
elseif type(value.label) == "table" then
catalog:tag("label"):add_child(value.label):up();
end
catalog:up();
if catalog_request.attr.xmlns == xmlns_label_catalog then
catalog:up();
end
else
add_labels(catalog, value, (selector or "")..name.."|");
end
end
end
-- TODO query remote servers
--[[ FIXME later
labels = module:fire_event("sec-label-catalog", {
to = catalog_request.attr.to,
request = request; -- or just origin?
labels = labels;
}) or labels;
--]]
add_labels(reply, labels, "");
request.origin.send(reply);
return true;
end
module:hook("iq/host/"..xmlns_label_catalog..":catalog", handle_catalog_request);
module:hook("iq/self/"..xmlns_label_catalog..":catalog", handle_catalog_request); -- COMPAT
module:hook("iq/self/"..xmlns_label_catalog_old..":catalog", handle_catalog_request); -- COMPAT
|
mod_seclabels: Fix config reloading
|
mod_seclabels: Fix config reloading
|
Lua
|
mit
|
crunchuser/prosody-modules,crunchuser/prosody-modules,amenophis1er/prosody-modules,guilhem/prosody-modules,LanceJenkinZA/prosody-modules,mmusial/prosody-modules,softer/prosody-modules,either1/prosody-modules,NSAKEY/prosody-modules,amenophis1er/prosody-modules,mmusial/prosody-modules,joewalker/prosody-modules,mardraze/prosody-modules,brahmi2/prosody-modules,Craige/prosody-modules,guilhem/prosody-modules,drdownload/prosody-modules,asdofindia/prosody-modules,drdownload/prosody-modules,cryptotoad/prosody-modules,apung/prosody-modules,guilhem/prosody-modules,prosody-modules/import,syntafin/prosody-modules,crunchuser/prosody-modules,obelisk21/prosody-modules,brahmi2/prosody-modules,BurmistrovJ/prosody-modules,joewalker/prosody-modules,stephen322/prosody-modules,vfedoroff/prosody-modules,prosody-modules/import,Craige/prosody-modules,BurmistrovJ/prosody-modules,syntafin/prosody-modules,vince06fr/prosody-modules,mardraze/prosody-modules,obelisk21/prosody-modules,amenophis1er/prosody-modules,asdofindia/prosody-modules,softer/prosody-modules,asdofindia/prosody-modules,mardraze/prosody-modules,BurmistrovJ/prosody-modules,cryptotoad/prosody-modules,mardraze/prosody-modules,stephen322/prosody-modules,guilhem/prosody-modules,softer/prosody-modules,Craige/prosody-modules,dhotson/prosody-modules,1st8/prosody-modules,NSAKEY/prosody-modules,1st8/prosody-modules,iamliqiang/prosody-modules,vince06fr/prosody-modules,stephen322/prosody-modules,jkprg/prosody-modules,drdownload/prosody-modules,cryptotoad/prosody-modules,jkprg/prosody-modules,prosody-modules/import,prosody-modules/import,mmusial/prosody-modules,jkprg/prosody-modules,asdofindia/prosody-modules,olax/prosody-modules,dhotson/prosody-modules,amenophis1er/prosody-modules,vince06fr/prosody-modules,vince06fr/prosody-modules,brahmi2/prosody-modules,stephen322/prosody-modules,dhotson/prosody-modules,brahmi2/prosody-modules,olax/prosody-modules,joewalker/prosody-modules,1st8/prosody-modules,iamliqiang/prosody-modules,jkprg/prosody-modules,drdownload/prosody-modules,1st8/prosody-modules,apung/prosody-modules,vfedoroff/prosody-modules,stephen322/prosody-modules,mmusial/prosody-modules,BurmistrovJ/prosody-modules,crunchuser/prosody-modules,apung/prosody-modules,drdownload/prosody-modules,LanceJenkinZA/prosody-modules,syntafin/prosody-modules,LanceJenkinZA/prosody-modules,asdofindia/prosody-modules,olax/prosody-modules,joewalker/prosody-modules,NSAKEY/prosody-modules,mmusial/prosody-modules,apung/prosody-modules,vfedoroff/prosody-modules,prosody-modules/import,heysion/prosody-modules,iamliqiang/prosody-modules,vince06fr/prosody-modules,jkprg/prosody-modules,obelisk21/prosody-modules,guilhem/prosody-modules,syntafin/prosody-modules,softer/prosody-modules,heysion/prosody-modules,heysion/prosody-modules,cryptotoad/prosody-modules,olax/prosody-modules,syntafin/prosody-modules,heysion/prosody-modules,amenophis1er/prosody-modules,iamliqiang/prosody-modules,vfedoroff/prosody-modules,Craige/prosody-modules,vfedoroff/prosody-modules,1st8/prosody-modules,LanceJenkinZA/prosody-modules,either1/prosody-modules,either1/prosody-modules,apung/prosody-modules,NSAKEY/prosody-modules,NSAKEY/prosody-modules,BurmistrovJ/prosody-modules,crunchuser/prosody-modules,Craige/prosody-modules,softer/prosody-modules,dhotson/prosody-modules,LanceJenkinZA/prosody-modules,heysion/prosody-modules,iamliqiang/prosody-modules,either1/prosody-modules,either1/prosody-modules,cryptotoad/prosody-modules,brahmi2/prosody-modules,olax/prosody-modules,joewalker/prosody-modules,obelisk21/prosody-modules,obelisk21/prosody-modules,dhotson/prosody-modules,mardraze/prosody-modules
|
061c867738c8db13604f19f3ee15644ff88814f3
|
src/patch/ui/hooks/modsmenu_enablempmenu.lua
|
src/patch/ui/hooks/modsmenu_enablempmenu.lua
|
if _mpPatch and _mpPatch.loaded then
_mpPatch.loadElementFromProxy("mppatch_multiplayerproxy", "ModMultiplayerSelectScreen")
Controls.MultiPlayerButton:RegisterCallback(Mouse.eLClick, function()
UIManager:QueuePopup(Controls.ModMultiplayerSelectScreen, PopupPriority.ModMultiplayerSelectScreen)
end)
Controls.MultiPlayerButton:SetHide(false)
local function getModMessage(name, title)
local mods = {}
for _, v in ipairs(Modding.GetActivatedMods()) do
if Modding.GetModProperty(v.ID, v.Version, name) ~= "1" then
table.insert(mods, "[ICON_BULLET]".._mpPatch.getModName(v.ID, v.Version))
end
end
if #mods == 0 then
return nil
else
return Locale.Lookup(title).."[NEWLINE]"..table.concat(mods, "[NEWLINE]")
end
end
local function setTooltip(control, name, title)
control:SetToolTipString(getModMessage(name, title))
end
local function showMessage(name, title)
local result = getModMessage(name, title)
if result then
Events.FrontEndPopup.CallImmediate(Locale.Lookup("TXT_KEY_MPPATCH_WARNING_PREFIX")..result)
end
end
local OnSinglePlayerClickOld = OnSinglePlayerClick
function OnSinglePlayerClick(...)
showMessage("SupportsSinglePlayer", "TXT_KEY_MPPATCH_NO_SINGLEPLAYER_SUPPORT")
return OnSinglePlayerClickOld(...)
end
Controls.SinglePlayerButton:RegisterCallback(Mouse.eLClick, OnSinglePlayerClick)
local OnMultiPlayerClickOld = OnMultiPlayerClick
function OnMultiPlayerClick(...)
showMessage("SupportsMultiplayer" , "TXT_KEY_MPPATCH_NO_MULTIPLAYER_SUPPORT" )
return OnMultiPlayerClickOld(...)
end
Controls.MultiPlayerButton:RegisterCallback(Mouse.eLClick, OnMultiPlayerClick)
local function onShowHideHook()
setTooltip(Controls.SinglePlayerButton, "SupportsSinglePlayer", "TXT_KEY_MPPATCH_NO_SINGLEPLAYER_SUPPORT")
setTooltip(Controls.MultiPlayerButton , "SupportsMultiplayer" , "TXT_KEY_MPPATCH_NO_MULTIPLAYER_SUPPORT" )
end
Modding = _mpPatch.hookTable(Modding, {
AllEnabledModsContainPropertyValue = function(...)
local name = ...
if name == "SupportsSinglePlayer" then
onShowHideHook()
return true
elseif name == "SupportsMultiplayer" then
return true
end
return Modding._super.AllEnabledModsContainPropertyValue(...)
end
})
end
|
if _mpPatch and _mpPatch.loaded then
_mpPatch.loadElementFromProxy("mppatch_multiplayerproxy", "ModMultiplayerSelectScreen")
local function getModMessage(name, title)
local mods = {}
for _, v in ipairs(Modding.GetActivatedMods()) do
if Modding.GetModProperty(v.ID, v.Version, name) ~= "1" then
table.insert(mods, "[ICON_BULLET]".._mpPatch.getModName(v.ID, v.Version))
end
end
if #mods == 0 then
return nil
else
return Locale.Lookup(title).."[NEWLINE]"..table.concat(mods, "[NEWLINE]")
end
end
local function setTooltip(control, name, title)
control:SetToolTipString(getModMessage(name, title))
end
local function showMessage(name, title)
local result = getModMessage(name, title)
if result then
Events.FrontEndPopup.CallImmediate(Locale.Lookup("TXT_KEY_MPPATCH_WARNING_PREFIX")..result)
end
end
local OnSinglePlayerClickOld = OnSinglePlayerClick
function OnSinglePlayerClick(...)
showMessage("SupportsSinglePlayer", "TXT_KEY_MPPATCH_NO_SINGLEPLAYER_SUPPORT")
return OnSinglePlayerClickOld(...)
end
Controls.SinglePlayerButton:RegisterCallback(Mouse.eLClick, OnSinglePlayerClick)
function OnMultiPlayerClick(...)
showMessage("SupportsMultiplayer" , "TXT_KEY_MPPATCH_NO_MULTIPLAYER_SUPPORT" )
UIManager:QueuePopup(Controls.ModMultiplayerSelectScreen, PopupPriority.ModMultiplayerSelectScreen)
end
Controls.MultiPlayerButton:RegisterCallback(Mouse.eLClick, OnMultiPlayerClick)
Controls.MultiPlayerButton:SetHide(false)
local function onShowHideHook()
setTooltip(Controls.SinglePlayerButton, "SupportsSinglePlayer", "TXT_KEY_MPPATCH_NO_SINGLEPLAYER_SUPPORT")
setTooltip(Controls.MultiPlayerButton , "SupportsMultiplayer" , "TXT_KEY_MPPATCH_NO_MULTIPLAYER_SUPPORT" )
end
Modding = _mpPatch.hookTable(Modding, {
AllEnabledModsContainPropertyValue = function(...)
local name = ...
if name == "SupportsSinglePlayer" then
onShowHideHook()
return true
elseif name == "SupportsMultiplayer" then
return true
end
return Modding._super.AllEnabledModsContainPropertyValue(...)
end
})
end
|
Fix regression in modsmenu.
|
Fix regression in modsmenu.
|
Lua
|
mit
|
Lymia/MPPatch,Lymia/MultiverseModManager,Lymia/MPPatch,Lymia/MultiverseModManager,Lymia/CivV_Mod2DLC,Lymia/MPPatch,Lymia/MPPatch
|
a6c5eba1e685294df1e18c9f3b4e5ef38d136a5b
|
src_trunk/resources/global/admin_globals.lua
|
src_trunk/resources/global/admin_globals.lua
|
function getAdmins()
local players = exports.pool:getPoolElementsByType("player")
local admins = { }
local count = 1
for key, value in ipairs(players) do
local adminLevel = getElementData(value, "adminlevel")
if (adminLevel>0) then
admins[count] = value
count = count + 1
end
end
return admins
end
function isPlayerAdmin(thePlayer)
local adminLevel = tonumber(getElementData(thePlayer, "adminlevel"))
if(adminLevel==0) then
return false
elseif(adminLevel>=1) then
return true
end
end
function isPlayerFullAdmin(thePlayer)
local adminLevel = tonumber(getElementData(thePlayer, "adminlevel"))
if(adminLevel==0) then
return false
elseif(adminLevel>=2) then
return true
end
end
function isPlayerSuperAdmin(thePlayer)
local adminLevel = tonumber(getElementData(thePlayer, "adminlevel"))
if(adminLevel==0) then
return false
elseif(adminLevel>=3) then
return true
end
end
function isPlayerHeadAdmin(thePlayer)
local adminLevel = tonumber(getElementData(thePlayer, "adminlevel"))
if(adminLevel==0) then
return false
elseif(adminLevel>=5) then
return true
end
end
function isPlayerLeadAdmin(thePlayer)
local adminLevel = tonumber(getElementData(thePlayer, "adminlevel"))
if(adminLevel==0) then
return false
elseif(adminLevel>=4) then
return true
end
end
function getPlayerAdminLevel(thePlayer)
local adminLevel = tonumber(getElementData(thePlayer, "adminlevel"))
return adminLevel
end
local titles = { "Trial Admin", "Admin", "Super Admin", "Lead Admin", "Head Admin", "Owner" }
function getPlayerAdminTitle(thePlayer)
local adminLevel = tonumber(getElementData(thePlayer, "adminlevel")) or 0
local text = titles[adminLevel] or "Player"
local hiddenAdmin = getElementData(thePlayer, "hiddenadmin") or 0
if (hiddenAdmin==1) then
text = text .. " (Hidden)"
end
return text
end
local scripterAccounts = {
Daniels = true,
Chamberlain = true,
mabako = true,
Cazomino09 = true,
Serizzim = true,
Flobu = true,
ryden = true,
['Mr.Hankey'] = true
}
function isPlayerScripter(thePlayer)
if getElementType(thePlayer) == "console" or isPlayerHeadAdmin(thePlayer) or scripterAccounts[getElementData(thePlayer, "gameaccountusername")] then
return true
else
return false
end
end
|
function getAdmins()
local players = exports.pool:getPoolElementsByType("player")
local admins = { }
local count = 1
for key, value in ipairs(players) do
local adminLevel = getElementData(value, "adminlevel")
if (adminLevel>0) then
admins[count] = value
count = count + 1
end
end
return admins
end
function isPlayerAdmin(thePlayer)
local adminLevel = tonumber(getElementData(thePlayer, "adminlevel"))
if(adminLevel==0) or not (adminLevel) then
return false
elseif(adminLevel>=1) then
return true
end
end
function isPlayerFullAdmin(thePlayer)
local adminLevel = tonumber(getElementData(thePlayer, "adminlevel"))
if(adminLevel==0) or not (adminLevel) then
return false
elseif(adminLevel>=2) then
return true
end
end
function isPlayerSuperAdmin(thePlayer)
local adminLevel = tonumber(getElementData(thePlayer, "adminlevel"))
if(adminLevel==0) or not (adminLevel) then
return false
elseif(adminLevel>=3) then
return true
end
end
function isPlayerHeadAdmin(thePlayer)
local adminLevel = tonumber(getElementData(thePlayer, "adminlevel"))
if(adminLevel==0) or not (adminLevel) then
return false
elseif(adminLevel>=5) then
return true
end
end
function isPlayerLeadAdmin(thePlayer)
local adminLevel = tonumber(getElementData(thePlayer, "adminlevel"))
if(adminLevel==0) or not (adminLevel) then
return false
elseif(adminLevel>=4) then
return true
end
end
function getPlayerAdminLevel(thePlayer)
local adminLevel = tonumber(getElementData(thePlayer, "adminlevel"))
return adminLevel
end
local titles = { "Trial Admin", "Admin", "Super Admin", "Lead Admin", "Head Admin", "Owner" }
function getPlayerAdminTitle(thePlayer)
local adminLevel = tonumber(getElementData(thePlayer, "adminlevel")) or 0
local text = titles[adminLevel] or "Player"
local hiddenAdmin = getElementData(thePlayer, "hiddenadmin") or 0
if (hiddenAdmin==1) then
text = text .. " (Hidden)"
end
return text
end
local scripterAccounts = {
Daniels = true,
Chamberlain = true,
mabako = true,
Cazomino09 = true,
Serizzim = true,
Flobu = true,
ryden = true,
['Mr.Hankey'] = true
}
function isPlayerScripter(thePlayer)
if getElementType(thePlayer) == "console" or isPlayerHeadAdmin(thePlayer) or scripterAccounts[getElementData(thePlayer, "gameaccountusername")] then
return true
else
return false
end
end
|
Error fix for isPlayerXAdmin
|
Error fix for isPlayerXAdmin
git-svn-id: 8769cb08482c9977c94b72b8e184ec7d2197f4f7@1663 64450a49-1f69-0410-a0a2-f5ebb52c4f5b
|
Lua
|
bsd-3-clause
|
valhallaGaming/uno,valhallaGaming/uno,valhallaGaming/uno
|
7f254a34d8849b5f28711dccb2891569aa60c382
|
cli.lua
|
cli.lua
|
eso_addon_MailLooter = eso_addon_MailLooter or {}
local ADDON = eso_addon_MailLooter
local function CommandHandler(text)
if text == "" then
d( ADDON.NAME .. " version " .. ADDON.VERSION )
d( "Commands:" )
d( "debug on|off - turns debug messages on and off" )
d( "reset - reset if it got stuck" )
return
elseif text == "debug off" then
ADDON.SetSetting_debug(false)
elseif text == "debug on" then
ADDON.SetSetting_debug(true)
elseif text == "reset" then
ADDON.Core.Reset()
end
end
-- Slash Commands --
SLASH_COMMANDS["/maillooter"] = CommandHandler
|
eso_addon_MailLooter = eso_addon_MailLooter or {}
local ADDON = eso_addon_MailLooter
local function CommandHandler(text)
if text == "" then
d( ADDON.NAME .. " version " .. ADDON.VERSION )
d( "Commands:" )
d( "debug [on/off] - Turns debug messages on and off" )
d( "reset - Reset the maillooter in case it is stuck." )
return
elseif text == "debug off" then
ADDON.SetSetting_debug(false)
elseif text == "debug on" then
ADDON.SetSetting_debug(true)
elseif text == "reset" then
ADDON.Core.Reset()
end
end
-- Slash Commands --
SLASH_COMMANDS["/maillooter"] = CommandHandler
|
Fixed help formatting.
|
Fixed help formatting.
|
Lua
|
mit
|
nilsbrummond/ESO-MailLooter
|
24ce25cede25ebf14588b55065869ccc64124176
|
helper.lua
|
helper.lua
|
-- Helper Module
--
local setup = require "setup"
local dbmodule = require "dbmodule"
local config = require "config"
scriptdb = config.scriptdb
local helper = {}
helper.mainMenu = {"Help (h)", "Initial Setup (i)", "Search Script (s)", "Exit (q)"}
function helper.banner()
banner=[[
================================================
_ _ _____ _____ _
| \ | |/ ___|| ___| | |
| \| |\ `--. | |__ __ _ _ __ ___ | |__
| . ` | `--. \| __| / _` || '__| / __|| '_ \
| |\ |/\__/ /| |___ | (_| || | | (__ | | | |
\_| \_/\____/ \____/ \__,_||_| \___||_| |_|
================================================
Version 0.1 | @jjtibaquira
================================================
]]
return banner
end
function getScriptDesc( nse )
io.write('\nDo yo want more info about any script, choose the script using id [1-'..#nse..'] or quit (0)')
local option = io.read()
key = tonumber(option)
if nse[key] then
print("\n")
local file = config.scriptsPath..nse[key]
local lines = lines_from(file)
for k,v in pairs(lines) do
local i = string.find(v, "license")
if not i then
print('\27[96m'..v..'\27[0m')
else
getScriptDesc(nse)
end
end
elseif option == "0" then
os.execute("clear")
print('\27[1m \27[36m'..helper.banner()..'\27[21m \27[0m')
helper.searchConsole()
else
os.execute("clear")
helper.menu(helper.mainMenu)
helper.Main()
end
end
function resultList(nse)
if #nse > 0 then
print('\27[1m \27[36m'..helper.banner()..'\27[21m \27[0m')
print("\nTotal Scripts Found "..#nse.."\n")
for k,v in ipairs(nse) do
print('\27[92m'..k.." "..v..'\27[0m')
end
getScriptDesc(nse)
else
print('\27[1m \27[36m'..helper.banner()..'\27[21m \27[0m')
print("\nNot Results Found\n")
io.write("Do you want search again? [y/n]: ")
local action = io.read()
if action == 'y' then
os.execute("clear")
print('\27[1m \27[36m'..helper.banner()..'\27[21m \27[0m')
helper.searchConsole()
else
os.execute("clear")
helper.menu(helper.mainMenu)
helper.Main()
end
end
end
function resultListaCat(scripts,catName)
if #scripts > 0 then
print('\27[1m \27[36m'..helper.banner()..'\27[21m \27[0m')
print("\nTotal Scripts Found "..#scripts.." into "..catName.." Category\n")
for k,v in ipairs(scripts) do
print('\27[92m'..k.." "..v..'\27[0m')
end
getScriptDesc(scripts)
else
print("Not Results Found\n")
print("=== These are the enabled Categories ===\n")
dbmodule.findAll("categories")
end
end
function helper.menu(menulist)
print('\27[1m \27[36m'..helper.banner()..'\27[21m \27[0m')
for key,value in ipairs(menulist) do
print(key.." "..value)
end
return menulist
end
function helper.searchConsole()
io.write('nsearch> ')
local command = io.read()
if command == "help" then
os.execute("clear")
print('\27[1m \27[36m'..helper.banner()..'\27[21m \27[0m')
print("name : search by script's name ")
print("category : search by category")
print("exit : close the console")
print("back : returns to the main menu")
print("\n Usage:")
print("\n name:http")
print("\n category:exploit \n")
helper.searchConsole()
elseif string.find(command,"name:") then
string = command:gsub("name:","")
os.execute("clear")
resultList(dbmodule.findScript(string))
elseif string.find(command,"exit") then
os.exit()
elseif string.find(command,"back") then
os.execute("clear")
helper.menu(helper.mainMenu)
helper.Main()
elseif string.find(command,"category:") then
string = command:gsub("category:","")
os.execute("clear")
resultListaCat(dbmodule.SearchByCat(string),string)
elseif (string.find(command,"name:") and string.find(command,"category:")) then
print(command)
os.execute("clear")
helper.searchConsole()
else
helper.searchConsole()
end
end
function helper.Main()
io.write('\n What do you want to do? : ')
local action = io.read()
if action == "q" or action == "4" then
os.exit()
elseif action == "i" or action == "2" then
os.execute( "clear" )
setup.install(helper.banner())
elseif action == "s" or action == "3" then
os.execute( "clear" )
print('\27[1m \27[36m'..helper.banner()..'\27[21m \27[0m')
helper.searchConsole()
else
os.execute("clear")
helper.menu(helper.mainMenu)
helper.Main()
end
end
return helper
|
-- Helper Module
--
local setup = require "setup"
local dbmodule = require "dbmodule"
local config = require "config"
scriptdb = config.scriptdb
local helper = {}
helper.mainMenu = {"Help (h)", "Initial Setup (i)", "Search Script (s)", "Exit (q)"}
function helper.banner()
banner=[[
================================================
_ _ _____ _____ _
| \ | |/ ___|| ___| | |
| \| |\ `--. | |__ __ _ _ __ ___ | |__
| . ` | `--. \| __| / _` || '__| / __|| '_ \
| |\ |/\__/ /| |___ | (_| || | | (__ | | | |
\_| \_/\____/ \____/ \__,_||_| \___||_| |_|
================================================
Version 0.1 | @jjtibaquira
================================================
]]
return banner
end
function getScriptDesc( nse )
io.write('\nDo yo want more info about any script, choose the script using id [1-'..#nse..'] or quit (0)')
local option = io.read()
key = tonumber(option)
if nse[key] then
print("\n")
local file = config.scriptsPath..nse[key]
local lines = lines_from(file)
for k,v in pairs(lines) do
local i = string.find(v, "license")
if not i then
print('\27[96m'..v..'\27[0m')
else
getScriptDesc(nse)
end
end
elseif option == "0" then
os.execute("clear")
print('\27[1m \27[36m'..helper.banner()..'\27[21m \27[0m')
helper.searchConsole()
else
os.execute("clear")
helper.menu(helper.mainMenu)
helper.Main()
end
end
function resultList(nse)
if #nse > 0 then
print('\27[1m \27[36m'..helper.banner()..'\27[21m \27[0m')
print("\nTotal Scripts Found "..#nse.."\n")
for k,v in ipairs(nse) do
print('\27[92m'..k.." "..v..'\27[0m')
end
getScriptDesc(nse)
else
print('\27[1m \27[36m'..helper.banner()..'\27[21m \27[0m')
print("\nNot Results Found\n")
io.write("Do you want search again? [y/n]: ")
local action = io.read()
if action == 'y' then
os.execute("clear")
print('\27[1m \27[36m'..helper.banner()..'\27[21m \27[0m')
helper.searchConsole()
else
os.execute("clear")
helper.menu(helper.mainMenu)
helper.Main()
end
end
end
function resultListaCat(scripts,catName)
if #scripts > 0 then
print('\27[1m \27[36m'..helper.banner()..'\27[21m \27[0m')
print("\nTotal Scripts Found "..#scripts.." into "..catName.." Category\n")
for k,v in ipairs(scripts) do
print('\27[92m'..k.." "..v..'\27[0m')
end
getScriptDesc(scripts)
else
print("Not Results Found\n")
print("=== These are the enabled Categories ===\n")
dbmodule.findAll("categories")
end
end
function helper.menu(menulist)
print('\27[1m \27[36m'..helper.banner()..'\27[21m \27[0m')
for key,value in ipairs(menulist) do
print(key.." "..value)
end
return menulist
end
function helper.searchConsole()
io.write('nsearch> ')
local command = io.read()
if command == "help" then
os.execute("clear")
print('\27[1m \27[36m'..helper.banner()..'\27[21m \27[0m')
print("name : search by script's name ")
print("category : search by category")
print("exit : close the console")
print("back : returns to the main menu")
print("\n Usage:")
print("\n name:http")
print("\n category:exploit \n")
helper.searchConsole()
elseif (string.find(command,"name:") and string.find(command,"category:")) then
print(command)
os.execute("clear")
helper.searchConsole()
elseif string.find(command,"name:") then
string = command:gsub("name:","")
os.execute("clear")
resultList(dbmodule.findScript(string))
elseif string.find(command,"exit") then
os.exit()
elseif string.find(command,"back") then
os.execute("clear")
helper.menu(helper.mainMenu)
helper.Main()
elseif string.find(command,"category:") then
string = command:gsub("category:","")
os.execute("clear")
resultListaCat(dbmodule.SearchByCat(string),string)
else
helper.searchConsole()
end
end
function helper.Main()
io.write('\n What do you want to do? : ')
local action = io.read()
if action == "q" or action == "4" then
os.exit()
elseif action == "i" or action == "2" then
os.execute( "clear" )
setup.install(helper.banner())
elseif action == "s" or action == "3" then
os.execute( "clear" )
print('\27[1m \27[36m'..helper.banner()..'\27[21m \27[0m')
helper.searchConsole()
else
os.execute("clear")
helper.menu(helper.mainMenu)
helper.Main()
end
end
return helper
|
#1 fixing syntax for if
|
#1 fixing syntax for if
Signed-off-by: Jacobo Tibaquira <d8d2a0ed36dd5f2e41c721fffbe8af2e7e4fe993@gmail.com>
|
Lua
|
apache-2.0
|
JKO/nsearch,JKO/nsearch
|
b401588263d3e3e7ae1a5f82abfc83b5b281fd74
|
deps/websocket-codec.lua
|
deps/websocket-codec.lua
|
exports.name = "creationix/websocket-codec"
exports.version = "1.0.7"
exports.homepage = "https://github.com/luvit/lit/blob/master/deps/websocket-codec.lua"
exports.description = "A codec implementing websocket framing and helpers for handshakeing"
exports.tags = {"http", "websocket", "codec"}
exports.license = "MIT"
exports.author = { name = "Tim Caswell" }
local digest = require('openssl').digest.digest
local base64 = require('openssl').base64
local random = require('openssl').random
local band = bit.band
local bor = bit.bor
local bxor = bit.bxor
local rshift = bit.rshift
local lshift = bit.lshift
local char = string.char
local byte = string.byte
local sub = string.sub
local gmatch = string.gmatch
local lower = string.lower
local gsub = string.gsub
local concat = table.concat
local function applyMask(data, mask)
local bytes = {
[0] = byte(mask, 1),
[1] = byte(mask, 2),
[2] = byte(mask, 3),
[3] = byte(mask, 4)
}
local out = {}
for i = 1, #data do
out[i] = char(
bxor(byte(data, i), bytes[(i - 1) % 4])
)
end
return concat(out)
end
function exports.decode(chunk)
if #chunk < 2 then return end
local second = byte(chunk, 2)
local len = band(second, 0x7f)
local offset
if len == 126 then
if #chunk < 4 then return end
len = bor(
lshift(byte(chunk, 3), 8),
byte(chunk, 4))
offset = 4
elseif len == 127 then
if #chunk < 10 then return end
len = bor(
lshift(byte(chunk, 3), 56),
lshift(byte(chunk, 4), 48),
lshift(byte(chunk, 5), 40),
lshift(byte(chunk, 6), 32),
lshift(byte(chunk, 7), 24),
lshift(byte(chunk, 8), 16),
lshift(byte(chunk, 9), 8),
byte(chunk, 10))
offset = 10
else
offset = 2
end
local mask = band(second, 0x80) > 0
if mask then
offset = offset + 4
end
if #chunk < offset + len then return end
local first = byte(chunk, 1)
local payload = sub(chunk, offset + 1, offset + len)
assert(#payload == len, "Length mismatch")
if mask then
payload = applyMask(payload, sub(chunk, offset - 3, offset))
end
local extra = sub(chunk, offset + len + 1)
return {
fin = band(first, 0x80) > 0,
rsv1 = band(first, 0x40) > 0,
rsv2 = band(first, 0x20) > 0,
rsv3 = band(first, 0x10) > 0,
opcode = band(first, 0xf),
mask = mask,
len = len,
payload = payload
}, extra
end
function exports.encode(item)
if type(item) == "string" then
item = {
opcode = 2,
payload = item
}
end
local payload = item.payload
assert(type(payload) == "string", "payload must be string")
local len = #payload
local fin = item.fin
if fin == nil then fin = true end
local rsv1 = item.rsv1
local rsv2 = item.rsv2
local rsv3 = item.rsv3
local opcode = item.opcode or 2
local mask = item.mask
local chars = {
char(bor(
fin and 0x80 or 0,
rsv1 and 0x40 or 0,
rsv2 and 0x20 or 0,
rsv3 and 0x10 or 0,
opcode
)),
char(bor(
mask and 0x80 or 0,
len < 126 and len or (len < 0x10000) and 126 or 127
))
}
if len >= 0x10000 then
chars[3] = char(band(rshift(len, 56), 0xff))
chars[4] = char(band(rshift(len, 48), 0xff))
chars[5] = char(band(rshift(len, 40), 0xff))
chars[6] = char(band(rshift(len, 32), 0xff))
chars[7] = char(band(rshift(len, 24), 0xff))
chars[8] = char(band(rshift(len, 16), 0xff))
chars[9] = char(band(rshift(len, 8), 0xff))
chars[10] = char(band(len, 0xff))
elseif len >= 126 then
chars[3] = char(band(rshift(len, 8), 0xff))
chars[4] = char(band(len, 0xff))
end
if mask then
local key = random(4)
return concat(chars) .. key .. applyMask(payload, key)
end
return concat(chars) .. payload
end
local websocketGuid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
function exports.acceptKey(key)
return gsub(base64(digest("sha1", key .. websocketGuid, true)), "\n", "")
end
local acceptKey = exports.acceptKey
-- Make a client handshake connection
function exports.handshake(options, request)
local key = gsub(base64(random(20)), "\n", "")
local host = options.host
local path = options.path or "/"
local protocol = options.protocol
local req = {
method = "GET",
path = path,
{"Connection", "Upgrade"},
{"Upgrade", "websocket"},
{"Sec-WebSocket-Version", "13"},
{"Sec-WebSocket-Key", key},
}
for i = 1, #options do
req[#req + 1] = options[i]
end
if host then
req[#req + 1] = {"Host", host}
end
if protocol then
req[#req + 1] = {"Sec-WebSocket-Protocol", protocol}
end
local res = request(req)
if not res then
return nil, "Missing response from server"
end
-- Parse the headers for quick reading
if res.code ~= 101 then
return nil, "response must be code 101"
end
local headers = {}
for i = 1, #res do
local name, value = unpack(res[i])
headers[lower(name)] = value
end
if not headers.connection or lower(headers.connection) ~= "upgrade" then
return nil, "Invalid or missing connection upgrade header in response"
end
if headers["sec-websocket-accept"] ~= acceptKey(key) then
return nil, "challenge key missing or mismatched"
end
if protocol and headers["sec-websocket-protocol"] ~= protocol then
return nil, "protocol missing or mistmatched"
end
return true
end
function exports.handleHandshake(head, protocol)
-- WebSocket connections must be GET requests
if not head.method == "GET" then return end
-- Parse the headers for quick reading
local headers = {}
for i = 1, #head do
local name, value = unpack(head[i])
headers[lower(name)] = value
end
-- Must have 'Upgrade: websocket' and 'Connection: Upgrade' headers
if not (headers.connection and headers.upgrade and
headers.connection:lower():find("upgrade", 1, true) and
headers.upgrade:lower():find("websocket", 1, true)) then return end
-- Make sure it's a new client speaking v13 of the protocol
if tonumber(headers["sec-websocket-version"]) < 13 then
return nil, "only websocket protocol v13 supported"
end
local key = headers["sec-websocket-key"]
if not key then
return nil, "websocket security key missing"
end
-- If the server wants a specified protocol, check for it.
if protocol then
local foundProtocol = false
local list = headers["sec-websocket-protocol"]
if list then
for item in gmatch(list, "[^, ]+") do
if item == protocol then
foundProtocol = true
break
end
end
end
if not foundProtocol then
return nil, "specified protocol missing in request"
end
end
local accept = acceptKey(key)
local res = {
code = 101,
{"Upgrade", "websocket"},
{"Connection", "Upgrade"},
{"Sec-WebSocket-Accept", accept},
}
if protocol then
res[#res + 1] = {"Sec-WebSocket-Protocol", protocol}
end
return res
end
|
exports.name = "creationix/websocket-codec"
exports.version = "1.0.7"
exports.homepage = "https://github.com/luvit/lit/blob/master/deps/websocket-codec.lua"
exports.description = "A codec implementing websocket framing and helpers for handshakeing"
exports.tags = {"http", "websocket", "codec"}
exports.license = "MIT"
exports.author = { name = "Tim Caswell" }
local digest = require('openssl').digest.digest
local base64 = require('openssl').base64
local random = require('openssl').random
local band = bit.band
local bor = bit.bor
local bxor = bit.bxor
local rshift = bit.rshift
local lshift = bit.lshift
local char = string.char
local byte = string.byte
local sub = string.sub
local gmatch = string.gmatch
local lower = string.lower
local gsub = string.gsub
local concat = table.concat
local function applyMask(data, mask)
local bytes = {
[0] = byte(mask, 1),
[1] = byte(mask, 2),
[2] = byte(mask, 3),
[3] = byte(mask, 4)
}
local out = {}
for i = 1, #data do
out[i] = char(
bxor(byte(data, i), bytes[(i - 1) % 4])
)
end
return concat(out)
end
function exports.decode(chunk)
if #chunk < 2 then return end
local second = byte(chunk, 2)
local len = band(second, 0x7f)
local offset
if len == 126 then
if #chunk < 4 then return end
len = bor(
lshift(byte(chunk, 3), 8),
byte(chunk, 4))
offset = 4
elseif len == 127 then
if #chunk < 10 then return end
len = bor(
lshift(byte(chunk, 3), 24),
lshift(byte(chunk, 4), 16),
lshift(byte(chunk, 5), 8),
byte(chunk, 6)
) * 0x100000000 + bor(
lshift(byte(chunk, 7), 24),
lshift(byte(chunk, 8), 16),
lshift(byte(chunk, 9), 8),
byte(chunk, 10)
)
offset = 10
else
offset = 2
end
local mask = band(second, 0x80) > 0
if mask then
offset = offset + 4
end
if #chunk < offset + len then return end
local first = byte(chunk, 1)
local payload = sub(chunk, offset + 1, offset + len)
assert(#payload == len, "Length mismatch")
if mask then
payload = applyMask(payload, sub(chunk, offset - 3, offset))
end
local extra = sub(chunk, offset + len + 1)
return {
fin = band(first, 0x80) > 0,
rsv1 = band(first, 0x40) > 0,
rsv2 = band(first, 0x20) > 0,
rsv3 = band(first, 0x10) > 0,
opcode = band(first, 0xf),
mask = mask,
len = len,
payload = payload
}, extra
end
function exports.encode(item)
if type(item) == "string" then
item = {
opcode = 2,
payload = item
}
end
local payload = item.payload
assert(type(payload) == "string", "payload must be string")
local len = #payload
local fin = item.fin
if fin == nil then fin = true end
local rsv1 = item.rsv1
local rsv2 = item.rsv2
local rsv3 = item.rsv3
local opcode = item.opcode or 2
local mask = item.mask
local chars = {
char(bor(
fin and 0x80 or 0,
rsv1 and 0x40 or 0,
rsv2 and 0x20 or 0,
rsv3 and 0x10 or 0,
opcode
)),
char(bor(
mask and 0x80 or 0,
len < 126 and len or (len < 0x10000) and 126 or 127
))
}
if len >= 0x10000 then
local high = len / 0x100000000
chars[3] = char(band(rshift(high, 24), 0xff))
chars[4] = char(band(rshift(high, 16), 0xff))
chars[5] = char(band(rshift(high, 8), 0xff))
chars[6] = char(band(high, 0xff))
chars[7] = char(band(rshift(len, 24), 0xff))
chars[8] = char(band(rshift(len, 16), 0xff))
chars[9] = char(band(rshift(len, 8), 0xff))
chars[10] = char(band(len, 0xff))
elseif len >= 126 then
chars[3] = char(band(rshift(len, 8), 0xff))
chars[4] = char(band(len, 0xff))
end
if mask then
local key = random(4)
return concat(chars) .. key .. applyMask(payload, key)
end
return concat(chars) .. payload
end
local websocketGuid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
function exports.acceptKey(key)
return gsub(base64(digest("sha1", key .. websocketGuid, true)), "\n", "")
end
local acceptKey = exports.acceptKey
-- Make a client handshake connection
function exports.handshake(options, request)
local key = gsub(base64(random(20)), "\n", "")
local host = options.host
local path = options.path or "/"
local protocol = options.protocol
local req = {
method = "GET",
path = path,
{"Connection", "Upgrade"},
{"Upgrade", "websocket"},
{"Sec-WebSocket-Version", "13"},
{"Sec-WebSocket-Key", key},
}
for i = 1, #options do
req[#req + 1] = options[i]
end
if host then
req[#req + 1] = {"Host", host}
end
if protocol then
req[#req + 1] = {"Sec-WebSocket-Protocol", protocol}
end
local res = request(req)
if not res then
return nil, "Missing response from server"
end
-- Parse the headers for quick reading
if res.code ~= 101 then
return nil, "response must be code 101"
end
local headers = {}
for i = 1, #res do
local name, value = unpack(res[i])
headers[lower(name)] = value
end
if not headers.connection or lower(headers.connection) ~= "upgrade" then
return nil, "Invalid or missing connection upgrade header in response"
end
if headers["sec-websocket-accept"] ~= acceptKey(key) then
return nil, "challenge key missing or mismatched"
end
if protocol and headers["sec-websocket-protocol"] ~= protocol then
return nil, "protocol missing or mistmatched"
end
return true
end
function exports.handleHandshake(head, protocol)
-- WebSocket connections must be GET requests
if not head.method == "GET" then return end
-- Parse the headers for quick reading
local headers = {}
for i = 1, #head do
local name, value = unpack(head[i])
headers[lower(name)] = value
end
-- Must have 'Upgrade: websocket' and 'Connection: Upgrade' headers
if not (headers.connection and headers.upgrade and
headers.connection:lower():find("upgrade", 1, true) and
headers.upgrade:lower():find("websocket", 1, true)) then return end
-- Make sure it's a new client speaking v13 of the protocol
if tonumber(headers["sec-websocket-version"]) < 13 then
return nil, "only websocket protocol v13 supported"
end
local key = headers["sec-websocket-key"]
if not key then
return nil, "websocket security key missing"
end
-- If the server wants a specified protocol, check for it.
if protocol then
local foundProtocol = false
local list = headers["sec-websocket-protocol"]
if list then
for item in gmatch(list, "[^, ]+") do
if item == protocol then
foundProtocol = true
break
end
end
end
if not foundProtocol then
return nil, "specified protocol missing in request"
end
end
local accept = acceptKey(key)
local res = {
code = 101,
{"Upgrade", "websocket"},
{"Connection", "Upgrade"},
{"Sec-WebSocket-Accept", accept},
}
if protocol then
res[#res + 1] = {"Sec-WebSocket-Protocol", protocol}
end
return res
end
|
Fix length encoding for large websocket frames
|
Fix length encoding for large websocket frames
|
Lua
|
apache-2.0
|
luvit/lit,squeek502/lit,james2doyle/lit,zhaozg/lit
|
e76f60b047db2433469ce127054d8be43a06015c
|
game/scripts/vscripts/heroes/hero_faceless_void/time_lock.lua
|
game/scripts/vscripts/heroes/hero_faceless_void/time_lock.lua
|
function TimeLock(keys)
local caster = keys.caster
local target = keys.target
local ability = keys.ability
local skills = {}
local bonus_cooldown = ability:GetLevelSpecialValueFor("bonus_cooldown", ability:GetLevel() - 1)
if not caster:IsIllusion() then
if target:IsRealHero() or target:IsBoss() then
for i = 0, target:GetAbilityCount() - 1 do
local skill = target:GetAbilityByIndex(i)
if skill and not skill:IsHidden() then
table.insert(skills, skill)
end
end
local delayed = skills[RandomInt(1, #skills)]
if delayed then
local cd = delayed:GetCooldownTimeRemaining()
if cd > 0 then
delayed:StartCooldown(cd + bonus_cooldown)
else
delayed:StartCooldown(bonus_cooldown)
end
end
ability:ApplyDataDrivenModifier(caster, target, "modifier_time_lock_stun_arena", { duration = ability:GetLevelSpecialValueFor("duration", ability:GetLevel() - 1) })
else
ability:ApplyDataDrivenModifier(caster, target, "modifier_time_lock_stun_arena", { duration = ability:GetLevelSpecialValueFor("duration_creep", ability:GetLevel() - 1) })
end
end
end
|
function TimeLock(keys)
local caster = keys.caster
local target = keys.target
local ability = keys.ability
local skills = {}
local bonus_cooldown = ability:GetLevelSpecialValueFor("bonus_cooldown", ability:GetLevel() - 1)
if not caster:IsIllusion() then
if target:IsRealHero() or target:IsBoss() then
for i = 0, target:GetAbilityCount() - 1 do
local skill = target:GetAbilityByIndex(i)
if skill and not skill:IsHidden() then
table.insert(skills, skill)
end
end
local delayed = skills[RandomInt(1, #skills)]
if delayed then
local cd = delayed:GetCooldownTimeRemaining()
if cd > 0 then
delayed:StartCooldown(cd + bonus_cooldown)
else
delayed:StartCooldown(bonus_cooldown)
end
end
ability:ApplyDataDrivenModifier(caster, target, keys.modifier, { duration = ability:GetLevelSpecialValueFor("duration", ability:GetLevel() - 1) })
else
ability:ApplyDataDrivenModifier(caster, target, keys.modifier, { duration = ability:GetLevelSpecialValueFor("duration_creep", ability:GetLevel() - 1) })
end
end
end
|
Fixed Faceless Void - Time Lock not applied modifier
|
Fixed Faceless Void - Time Lock not applied modifier
|
Lua
|
mit
|
ark120202/aabs
|
c5bb6ef2ae0e7554306776fbf4746ba086051cd1
|
init.lua
|
init.lua
|
--
-- init.lua
--
-- This is the initialization file of SSOwat. It is called once at the Nginx
-- server's start.
-- Consequently, all the variables declared (along with libraries and
-- translations) in this file will be *persistent* from one HTTP request to
-- another.
--
-- Remove prepending '@' & trailing 'init.lua'
script_path = string.sub(debug.getinfo(1).source, 2, -9)
-- Include local libs in package.path
package.path = package.path .. ";"..script_path.."?.lua"
-- Load libraries
local json = require "json"
local lualdap = require "lualdap"
local math = require "math"
local hige = require "hige"
local lfs = require "lfs"
local socket = require "socket"
local config = require "config"
-- Persistent shared table
flashs = {}
i18n = {}
-- Efficient function to get a random string
function random_string()
math.randomseed( tonumber(tostring(socket.gettime()*10000):reverse()) )
str = tostring(math.random()):sub(3)
socket.sleep(1e-400)
return str
end
-- Load translations in the "i18n" above table
local locale_dir = script_path.."portal/locales/"
for file in lfs.dir(locale_dir) do
if string.sub(file, -4) == "json" then
local lang = string.sub(file, 1, 2)
local locale_file = io.open(locale_dir..file, "r")
i18n[lang] = json.decode(locale_file:read("*all"))
end
end
-- Path of the configuration
conf_path = "/etc/ssowat/conf.json"
-- You should see that in your Nginx error logs by default
ngx.log(ngx.INFO, "SSOwat ready")
|
--
-- init.lua
--
-- This is the initialization file of SSOwat. It is called once at the Nginx
-- server's start.
-- Consequently, all the variables declared (along with libraries and
-- translations) in this file will be *persistent* from one HTTP request to
-- another.
--
-- Remove prepending '@' & trailing 'init.lua'
script_path = string.sub(debug.getinfo(1).source, 2, -9)
-- Include local libs in package.path
package.path = package.path .. ";"..script_path.."?.lua"
-- Load libraries
local json = require "json"
local lualdap = require "lualdap"
local math = require "math"
local hige = require "hige"
local lfs = require "lfs"
local socket = require "socket"
local config = require "config"
-- Persistent shared table
flashs = {}
i18n = {}
-- convert a string to a hex
function tohex(str)
return (str:gsub('.', function (c)
return string.format('%02X', string.byte(c))
end))
end
-- Efficient function to get a random string
function random_string()
local random_bytes = io.open("/dev/urandom"):read(64);
return tohex(random_bytes);
end
-- Load translations in the "i18n" above table
local locale_dir = script_path.."portal/locales/"
for file in lfs.dir(locale_dir) do
if string.sub(file, -4) == "json" then
local lang = string.sub(file, 1, 2)
local locale_file = io.open(locale_dir..file, "r")
i18n[lang] = json.decode(locale_file:read("*all"))
end
end
-- Path of the configuration
conf_path = "/etc/ssowat/conf.json"
-- You should see that in your Nginx error logs by default
ngx.log(ngx.INFO, "SSOwat ready")
|
[fix] uses a cryptographically secure source of randomness
|
[fix] uses a cryptographically secure source of randomness
|
Lua
|
agpl-3.0
|
Kloadut/SSOwat,YunoHost/SSOwat,Kloadut/SSOwat,YunoHost/SSOwat
|
c7f75e4f895312b3774c369371216b55ffb773c9
|
init.lua
|
init.lua
|
-- Copyright 2015 Boundary, Inc.
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
local framework = require('framework')
local url = require('url')
local table = require('table')
local json = require('json')
local Plugin = framework.Plugin
local WebRequestDataSource = framework.WebRequestDataSource
local pack = framework.util.pack
local params = framework.params
params.pollInterval = notEmpty(params.pollInterval, 1000)
local options = url.parse(params.stats_url)
options.wait_for_end = false
local ds = WebRequestDataSource:new(options)
local plugin = Plugin:new(params, ds)
function plugin:onParseValues(data)
local parsed = json.parse(data)
local result = {}
result['ELASTIC_SEARCH_STATUS'] = parsed.status
result['ELASTIC_SEARCH_NODE_COUNT'] = parsed.nodes.count.total
result['ELASTIC_SEARCH_INDEX_COUNT'] = parsed.indices.count
result['ELASTIC_SEARCH_DOCUMENT_COUNT'] = parsed.indices.docs.count
result['ELASTIC_SEARCH_STORE_SIZE'] = parsed.indices.store.size_in_bytes
result['ELASTIC_SEARCH_SEGMENT_COUNT'] = parsed.indices.segments.count
result['ELASTIC_SEARCH_TOTAL_SHARDS'] = parsed.indices.shards.total or 0.0
result['ELASTIC_SEARCH_PRIMARY_SHARDS'] = parsed.indices.shards.primaries or 0.0
result['ELASTIC_SEARCH_FIELDDATA_MEMORY_SIZE'] = parsed.indices.fielddata.memory_size_in_bytes
result['ELASTIC_SEARCH_FIELDDATA_EVICTIONS'] = parsed.indices.fielddata.evictions
result['ELASTIC_SEARCH_FILTER_CACHE_MEMORY_SIZE'] = parsed.indices.filter_cache.memory_size_in_bytes
result['ELASTIC_SEARCH_FILTER_CACHE_EVICTIONS'] = parsed.indices.filter_cache.evictions
result['ELASTIC_SEARCH_ID_CACHE_MEMORY_SIZE'] = parsed.indices.id_cache.memory_size_in_bytes
result['ELASTIC_SEARCH_COMPLETION_SIZE'] = parsed.indices.completion.size_in_bytes
return result
end
plugin:run()
|
-- Copyright 2015 Boundary, Inc.
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
local framework = require('framework')
local url = require('url')
local table = require('table')
local json = require('json')
local Plugin = framework.Plugin
local WebRequestDataSource = framework.WebRequestDataSource
local pack = framework.util.pack
local notEmpty = framework.string.notEmpty
local params = framework.params
params.pollInterval = notEmpty(params.pollInterval, 1000)
local options = url.parse(params.stats_url)
options.wait_for_end = false
local ds = WebRequestDataSource:new(options)
local plugin = Plugin:new(params, ds)
function plugin:onParseValues(data)
local parsed = json.parse(data)
local result = {}
result['ELASTIC_SEARCH_STATUS'] = parsed.status
result['ELASTIC_SEARCH_NODE_COUNT'] = parsed.nodes.count.total
result['ELASTIC_SEARCH_INDEX_COUNT'] = parsed.indices.count
result['ELASTIC_SEARCH_DOCUMENT_COUNT'] = parsed.indices.docs.count
result['ELASTIC_SEARCH_STORE_SIZE'] = parsed.indices.store.size_in_bytes
result['ELASTIC_SEARCH_SEGMENT_COUNT'] = parsed.indices.segments.count
result['ELASTIC_SEARCH_TOTAL_SHARDS'] = parsed.indices.shards.total or 0.0
result['ELASTIC_SEARCH_PRIMARY_SHARDS'] = parsed.indices.shards.primaries or 0.0
result['ELASTIC_SEARCH_FIELDDATA_MEMORY_SIZE'] = parsed.indices.fielddata.memory_size_in_bytes
result['ELASTIC_SEARCH_FIELDDATA_EVICTIONS'] = parsed.indices.fielddata.evictions
result['ELASTIC_SEARCH_FILTER_CACHE_MEMORY_SIZE'] = parsed.indices.filter_cache.memory_size_in_bytes
result['ELASTIC_SEARCH_FILTER_CACHE_EVICTIONS'] = parsed.indices.filter_cache.evictions
result['ELASTIC_SEARCH_ID_CACHE_MEMORY_SIZE'] = parsed.indices.id_cache.memory_size_in_bytes
result['ELASTIC_SEARCH_COMPLETION_SIZE'] = parsed.indices.completion.size_in_bytes
return result
end
plugin:run()
|
Bug fix call to notEmpty
|
Bug fix call to notEmpty
Signed-off-by: GabrielNicolasAvellaneda <83a8591a9a34d9745961eaad83d1d871cc3e5445@gmail.com>
|
Lua
|
apache-2.0
|
jdgwartney/boundary-plugin-elasticsearch
|
d4bf0a4cfe5be047a758ee5ab1989b6e759fe7c7
|
loss/treenll.lua
|
loss/treenll.lua
|
------------------------------------------------------------------------
--[[ TreeNLL ]]--
-- Loss subclass
-- Negative Log Likelihood for SoftmaxTrees.
-- Used for maximizing the likelihood of SoftmaxTree Model outputs.
-- SoftmaxTree outputs a column tensor representing the likelihood
-- of each target in the batch. Thus SoftmaxTree requires the targets.
-- So this Loss only computes the negative log of those outputs, as
-- well as its corresponding gradients.
------------------------------------------------------------------------
local TreeNLL, parent = torch.class("dp.TreeNLL", "dp.Loss")
TreeNLL.isTreeNLL = true
function TreeNLL:__init(config)
self._module = nn.Sequential()
self._module:add(nn.Log())
self._module:add(nn.Mean()) --not in cunn
config = config or {}
parent.__init(self, config)
self._output_grad = torch.Tensor{-1}
end
function TreeNLL:_forward(carry)
local input = self:inputAct()
self.loss = -self._module:forward(input)[1]
return carry
end
function TreeNLL:_backward(carry)
local input = self:inputAct()
local input_grad = self._module:backward(input, self._output_grad)
self:inputGrad(input_grad)
return carry
end
function TreeNLL:_type(type)
if type == 'torch.FloatTensor' or type == 'torch.DoubleTensor' then
self._input_type = type
elseif type == 'torch.IntTensor' or type == 'torch.LongTensor' then
-- this actually doesn't change anything:
self._output_type = type
end
end
|
------------------------------------------------------------------------
--[[ TreeNLL ]]--
-- Loss subclass
-- Negative Log Likelihood for SoftmaxTrees.
-- Used for maximizing the likelihood of SoftmaxTree Model outputs.
-- SoftmaxTree outputs a column tensor representing the log likelihood
-- of each target in the batch. Thus SoftmaxTree requires the targets.
-- So this Loss only computes the negative of those outputs, as
-- well as its corresponding gradients.
------------------------------------------------------------------------
local TreeNLL, parent = torch.class("dp.TreeNLL", "dp.Loss")
TreeNLL.isTreeNLL = true
function TreeNLL:__init(config)
self._module = nn.Sequential()
self._module:add(nn.Mean()) --not in cunn
config = config or {}
parent.__init(self, config)
self._output_grad = torch.Tensor{-1}
end
function TreeNLL:_forward(carry)
local input = self:inputAct()
self.loss = -self._module:forward(input)[1]
return carry
end
function TreeNLL:_backward(carry)
local input = self:inputAct()
local input_grad = self._module:backward(input, self._output_grad)
self:inputGrad(input_grad)
return carry
end
function TreeNLL:_type(type)
if type == 'torch.FloatTensor' or type == 'torch.DoubleTensor' then
self._input_type = type
elseif type == 'torch.IntTensor' or type == 'torch.LongTensor' then
-- this actually doesn't change anything:
self._output_type = type
end
end
|
fixed dp.Dictionary for cuda
|
fixed dp.Dictionary for cuda
|
Lua
|
bsd-3-clause
|
jnhwkim/dp,kracwarlock/dp,sagarwaghmare69/dp,fiskio/dp,rickyHong/dptorchLib,eulerreich/dp,nicholas-leonard/dp
|
94add70445bd2a692ecde2e5dd5ebdec592edd30
|
src/cosy/webclient/main.lua
|
src/cosy/webclient/main.lua
|
local location = js.global.location
loader = require (location.origin .. "/lua/cosy.loader")
local function screen (authentication)
local result,err = client.server.filter({
authentication = authentication,
iterator = "return function (yield, store)\
for k in pairs (store.user) do\
yield (store.user [k].username)\
end\
end"
})
local iframe = js.global.document:getElementById("map").contentWindow
for key,value in pairs(result) do
local result, err = client.user.information {
user = value
}
if result.position.latitude and result.position.longitude then
iframe.cluster (nil,result.position.latitude,result.position.longitude)
end
end
iframe.groupcluster ()
end
local function main()
local lib = require "cosy.library"
client = lib.connect (js.global.location.origin)
local storage = js.global.sessionStorage
local token = storage:getItem("cosytoken")
local user = storage:getItem("cosyuser")
local connected = false
local result, err = client.user.is_authentified {
authentication = token
}
if result and user == result.username and token ~= js.null then
connected = true
end
js.global.document:getElementById("content-wrapper").innerHTML = loader.loadhttp ( "/html/main.html")
js.global.document:getElementById("logo").onclick = function()
js.global.document:getElementById("content-wrapper").innerHTML = loader.loadhttp ( "/html/main.html")
screen (token)
return false
end
if connected then
screen (token)
js.global.document:getElementById("navbar-login").innerHTML = loader.loadhttp ( "/html/logoutnavbar.html")
js.global.document:getElementById("user-in").innerHTML = user
local result, err = client.user.update {
authentication = token
}
if result.name then
js.global.document:getElementById("user-name").innerHTML = result.name
end
if result.lastseen then
js.global.document:getElementById("user-last").innerHTML = os.date('%d/%m/%Y %H:%M:%S', result.lastseen)
end
if result.avatar then
js.global.document:getElementById("user-image-s").src = 'data:image/png;base64,'..result.avatar
js.global.document:getElementById("user-image-b").src = 'data:image/png;base64,'..result.avatar
else
js.global.document:getElementById("user-image-s").src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAAAAAA6fptVAAAACklEQVQYV2P4DwABAQEAWk1v8QAAAABJRU5ErkJggg=="
js.global.document:getElementById("user-image-b").src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAAAAAA6fptVAAAACklEQVQYV2P4DwABAQEAWk1v8QAAAABJRU5ErkJggg=="
end
js.global.document:getElementById("logout-button").onclick = function()
storage:removeItem("cosytoken")
storage:removeItem("cosyuser")
js.global.location.href = "/"
return false
end
js.global.document:getElementById("profile-button").onclick = function()
require ("cosy.webclient.profile")
return false
end
else
local auth = require ("cosy.webclient.auth")
js.global.document:getElementById("navbar-login").innerHTML = loader.loadhttp ( "/html/loginnavbar.html")
js.global.document:getElementById("login-button").onclick = function()
coroutine.wrap(auth.login) ()
return false
end
js.global.document:getElementById("signup-button").onclick = function()
coroutine.wrap(auth.register) ()
return false
end
end
end
local co = coroutine.create (main)
coroutine.resume (co)
|
local location = js.global.location
loader = require (location.origin .. "/lua/cosy.loader")
client = {}
local function screen ()
local value = require "cosy.value"
local result,err = client.server.filter({
iterator = "return function (yield, store)\
for k in pairs (store.user) do\
yield {lat = store.user [k].position.latitude , lng = store.user [k].position.longitude}\
end\
end"
})
local iframe = js.global.document:getElementById("map").contentWindow
for key,value in pairs(result) do
if value.lat and value.lng then
iframe.cluster (nil,value.lat,value.lng)
end
end
iframe.groupcluster ()
end
local function main()
local lib = require "cosy.library"
client = lib.connect (js.global.location.origin)
local storage = js.global.sessionStorage
local token = storage:getItem("cosytoken")
local user = storage:getItem("cosyuser")
local connected = false
local result, err = client.user.is_authentified {
authentication = token
}
if result and user == result.username and token ~= js.null then
connected = true
end
js.global.document:getElementById("content-wrapper").innerHTML = loader.loadhttp ( "/html/main.html")
if connected then
js.global.document:getElementById("navbar-login").innerHTML = loader.loadhttp ( "/html/logoutnavbar.html")
js.global.document:getElementById("user-in").innerHTML = user
local result, err = client.user.update {
authentication = token
}
if result.name then
js.global.document:getElementById("user-name").innerHTML = result.name
end
if result.lastseen then
js.global.document:getElementById("user-last").innerHTML = os.date('%d/%m/%Y %H:%M:%S', result.lastseen)
end
if result.avatar then
js.global.document:getElementById("user-image-s").src = 'data:image/png;base64,'..result.avatar
js.global.document:getElementById("user-image-b").src = 'data:image/png;base64,'..result.avatar
else
js.global.document:getElementById("user-image-s").src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAAAAAA6fptVAAAACklEQVQYV2P4DwABAQEAWk1v8QAAAABJRU5ErkJggg=="
js.global.document:getElementById("user-image-b").src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAAAAAA6fptVAAAACklEQVQYV2P4DwABAQEAWk1v8QAAAABJRU5ErkJggg=="
end
js.global.document:getElementById("logout-button").onclick = function()
storage:removeItem("cosytoken")
storage:removeItem("cosyuser")
js.global.location.href = "/"
return false
end
js.global.document:getElementById("profile-button").onclick = function()
require ("cosy.webclient.profile")
return false
end
else
local auth = require ("cosy.webclient.auth")
js.global.document:getElementById("navbar-login").innerHTML = loader.loadhttp ( "/html/loginnavbar.html")
js.global.document:getElementById("login-button").onclick = function()
coroutine.wrap(auth.login) ()
return false
end
js.global.document:getElementById("signup-button").onclick = function()
coroutine.wrap(auth.register) ()
return false
end
end
local map = js.global.document:getElementById("map")
if map.contentWindow.cluster == nil then
map.onload = function ()
local co = coroutine.create (screen)
coroutine.resume (co)
end
else
screen()
end
end
local co = coroutine.create (main)
coroutine.resume (co)
|
enhance map, use iterator with position after the fix
|
enhance map, use iterator with position after the fix
|
Lua
|
mit
|
CosyVerif/library,CosyVerif/library,CosyVerif/library
|
c9658bda61e18cdf89336ff9d0b718079ecb406d
|
HOME/.hammerspoon/init.lua
|
HOME/.hammerspoon/init.lua
|
hs.alert.show("Hammerspoon config loaded")
hyper = {"cmd", "alt", "ctrl", "shift"}
-- bind reload at start in case of error later in config
hs.hotkey.bind(hyper, "R", hs.reload)
hs.hotkey.bind(hyper, "Y", hs.toggleConsole)
hs.ipc.cliInstall()
hs.ipc.cliSaveHistory(true)
function inspect(value)
hs.alert.show(hs.inspect(value))
end
fennel = require("fennel")
table.insert(package.loaders or package.searchers, fennel.searcher)
fennel.dofile("init.fnl") -- exports into global namespace
|
hs.alert.show("Hammerspoon config loaded")
hyper = {"cmd", "alt", "ctrl", "shift"}
-- bind reload at start in case of error later in config
hs.hotkey.bind(hyper, "R", hs.reload)
hs.hotkey.bind(hyper, "Y", hs.toggleConsole)
function inspect(value)
hs.alert.show(hs.inspect(value))
end
-- install cli
arch = io.popen('uname -p', 'r'):read('*l')
path = arch == 'arm' and '/opt/homebrew' or nil
hs.ipc.cliInstall(path)
hs.ipc.cliSaveHistory(true)
fennel = require("fennel")
table.insert(package.loaders or package.searchers, fennel.searcher)
fennel.dofile("init.fnl") -- exports into global namespace
|
Hammerspoon: fix cli install on M1
|
Hammerspoon: fix cli install on M1
|
Lua
|
mit
|
kbd/setup,kbd/setup,kbd/setup,kbd/setup,kbd/setup
|
6ee33420a98b12fcd65b047bf56a3a98408bdd70
|
convert.lua
|
convert.lua
|
-- modules that can be converted to nn seamlessly
local layer_list = {
'SpatialConvolution',
'SpatialCrossMapLRN',
'SpatialFullConvolution',
'SpatialMaxPooling',
'SpatialAveragePooling',
'ReLU',
'Tanh',
'Sigmoid',
'SoftMax',
'LogSoftMax',
'VolumetricConvolution',
'VolumetricMaxPooling',
'VolumetricAveragePooling',
}
-- similar to nn.Module.apply
-- goes over a net and recursively replaces modules
-- using callback function
local function replace(self, callback)
local out = callback(self)
if self.modules then
for i, module in ipairs(self.modules) do
self.modules[i] = replace(module, callback)
end
end
return out
end
-- goes over a given net and converts all layers to dst backend
-- for example: net = cudnn.convert(net, cudnn)
function cudnn.convert(net, dst)
return replace(net, function(x)
local y = 0
local src = dst == nn and cudnn or nn
local src_prefix = src == nn and 'nn.' or 'cudnn.'
local dst_prefix = dst == nn and 'nn.' or 'cudnn.'
local function convert(v)
local y = {}
torch.setmetatable(y, dst_prefix..v)
if v == 'ReLU' then y = dst.ReLU() end -- because parameters
for k,u in pairs(x) do y[k] = u end
if src == cudnn and x.clearDesc then x.clearDesc(y) end
if src == cudnn and v == 'SpatialAveragePooling' then y.divide = true end
return y
end
local t = torch.typename(x)
if t == 'nn.SpatialConvolutionMM' then
y = convert('SpatialConvolution')
elseif t == 'inn.SpatialCrossResponseNormalization' then
y = convert('SpatialCrossMapLRN')
else
for i,v in ipairs(layer_list) do
if torch.typename(x) == src_prefix..v then
y = convert(v)
end
end
end
return y == 0 and x or y
end)
end
|
-- modules that can be converted to nn seamlessly
local layer_list = {
'SpatialConvolution',
'SpatialCrossMapLRN',
'SpatialFullConvolution',
'SpatialMaxPooling',
'SpatialAveragePooling',
'ReLU',
'Tanh',
'Sigmoid',
'SoftMax',
'LogSoftMax',
'VolumetricConvolution',
'VolumetricMaxPooling',
'VolumetricAveragePooling',
}
-- similar to nn.Module.apply
-- goes over a net and recursively replaces modules
-- using callback function
local function replace(self, callback)
local out = callback(self)
if self.modules then
for i, module in ipairs(self.modules) do
self.modules[i] = replace(module, callback)
end
end
return out
end
-- goes over a given net and converts all layers to dst backend
-- for example: net = cudnn.convert(net, cudnn)
function cudnn.convert(net, dst)
return replace(net, function(x)
local y = 0
local src = dst == nn and cudnn or nn
local src_prefix = src == nn and 'nn.' or 'cudnn.'
local dst_prefix = dst == nn and 'nn.' or 'cudnn.'
local function convert(v)
local y = {}
torch.setmetatable(y, dst_prefix..v)
if v == 'ReLU' then y = dst.ReLU() end -- because parameters
for k,u in pairs(x) do y[k] = u end
if src == cudnn and x.clearDesc then x.clearDesc(y) end
if src == cudnn and v == 'SpatialAveragePooling' then
y.divide = true
y.count_include_pad = v.mode == 'CUDNN_POOLING_AVERAGE_COUNT_INCLUDE_PADDING'
end
return y
end
local t = torch.typename(x)
if t == 'nn.SpatialConvolutionMM' then
y = convert('SpatialConvolution')
elseif t == 'inn.SpatialCrossResponseNormalization' then
y = convert('SpatialCrossMapLRN')
else
for i,v in ipairs(layer_list) do
if torch.typename(x) == src_prefix..v then
y = convert(v)
end
end
end
return y == 0 and x or y
end)
end
|
Fixed cudnn -> nn avg-pooling conversion
|
Fixed cudnn -> nn avg-pooling conversion
cudnn.convert now properly initializes nn.SpatialAveragePooling.count_include_pad
|
Lua
|
bsd-3-clause
|
phunghx/phnn.torch,phunghx/phnn.torch,phunghx/phnn.torch
|
6d6aa7be2b61838c2abd5d9309f88da198788371
|
src_trunk/resources/social-system/c_player_rightclick.lua
|
src_trunk/resources/social-system/c_player_rightclick.lua
|
wRightClick = nil
bAddAsFriend, bFrisk, bRestrain, bCloseMenu = nil
sent = false
ax, ay = nil
player = nil
function clickPlayer(button, state, absX, absY, wx, wy, wz, element)
if (element) and (button="right") then
if (getElementType(element)=="player") and (sent==false) and (element~=getLocalPlayer()) then
if (wRightClick) then
hidePlayerMenu()
end
showCursor(true)
ax = absX
ay = absY
player = element
sent = true
triggerServerEvent("sendPlayerInfo", getLocalPlayer(), element)
elseif not (element) then
hidePlayerMenu()
end
end
end
addEventHandler("onClientClick", getRootElement(), clickPlayer, false)
function showPlayerMenu(targetPlayer, friends, description)
wRightClick = guiCreateWindow(ax, ay, 150, 200, string.gsub(getPlayerName(targetPlayer), "_", " "), false)
local targetid = tonumber(getElementData(targetPlayer, "gameaccountid"))
local found = false
for key, value in ipairs(friends) do
if (friends[key]==targetid) then
found = true
end
end
if (found==false) then
bAddAsFriend = guiCreateButton(0.05, 0.13, 0.87, 0.1, "Add as friend", true, wRightClick)
addEventHandler("onClientGUIClick", bAddAsFriend, caddFriend, false)
else
bAddAsFriend = guiCreateButton(0.05, 0.13, 0.87, 0.1, "Remove friend", true, wRightClick)
addEventHandler("onClientGUIClick", bAddAsFriend, cremoveFriend, false)
end
bAddAsFriend = guiCreateButton(0.05, 0.45, 0.87, 0.1, "Close Menu", true, wRightClick)
addEventHandler("onClientGUIClick", bAddAsFriend, hidePlayerMenu, false)
sent = false
-- FRISK
--bFrisk = guiCreateButton(0.05, 0.25, 0.87, 0.1, "Frisk", true, wRightClick)
--addEventHandler("onClientGUIClick", bFrisk, cfriskPlayer, false)
end
addEvent("displayPlayerMenu", true)
addEventHandler("displayPlayerMenu", getRootElement(), showPlayerMenu)
--------------------
-- FRISKING --
--------------------
wFriskItems, bFriskTakeItem, bFriskClose, gFriskItems, FriskColName = nil
function cfriskPlayer(button, state, x, y)
if not (wFriskItems) then
local width, height = 300, 200
local scrWidth, scrHeight = guiGetScreenSize()
wFriskItems = guiCreateWindow(x, y, width, height, "Frisk: " .. getPlayerName(player), false)
guiWindowSetSizable(wFriskItems, false)
gFriskItems = guiCreateGridList(0.05, 0.1, 0.9, 0.7, true, wFriskItems)
FriskColName = guiGridListAddColumn(gFriskItems, "Name", 0.9)
local items = getElementData(player, "items")
for i = 1, 10 do
local itemID = tonumber(gettok(items, i, string.byte(',')))
if (itemID~=nil) then
local itemName = exports.global:cgetItemName(itemID)
outputChatBox(tostring(itemName))
local row = guiGridListAddRow(gFriskItems)
guiGridListSetItemText(gFriskItems, row, FriskColName, tostring(itemName), false, false)
end
end
bFriskTakeItem = guiCreateButton(0.05, 0.85, 0.45, 0.1, "Take Item", true, wFriskItems)
bFriskClose = guiCreateButton(0.5, 0.85, 0.45, 0.1, "Close", true, wFriskItems)
addEventHandler("onClientGUIClick", bFrisk, hidePlayerMenu, false)
else
guiBringToFront(wFriskItems, true)
end
end
--------------------
-- END FRISKING --
--------------------
function caddFriend()
triggerServerEvent("addFriend", getLocalPlayer(), player)
hidePlayerMenu()
end
function cremoveFriend()
local id = tonumber(getElementData(player, "gameaccountid"))
local username = getPlayerName(player)
triggerServerEvent("removeFriend", getLocalPlayer(), id, username, true)
hidePlayerMenu()
end
function hidePlayerMenu()
destroyElement(bAddAsFriend)
bAddAsFriend = nil
destroyElement(wRightClick)
wRightClick = nil
ax = nil
ay = nil
player = nil
showCursor(false)
end
|
wRightClick = nil
bAddAsFriend, bFrisk, bRestrain, bCloseMenu = nil
sent = false
ax, ay = nil
player = nil
gotClick = false
function clickPlayer(button, state, absX, absY, wx, wy, wz, element)
if (element) and (getElementType(element)=="player") and (button=="right") and (state=="down") and (sent==false) and (element==getLocalPlayer()) then
if (wRightClick) then
hidePlayerMenu()
end
showCursor(true)
ax = absX
ay = absY
player = element
sent = true
triggerServerEvent("sendPlayerInfo", getLocalPlayer(), element)
elseif not (element) then
hidePlayerMenu()
end
end
addEventHandler("onClientClick", getRootElement(), clickPlayer, false)
function showPlayerMenu(targetPlayer, friends, description)
wRightClick = guiCreateWindow(ax, ay, 150, 200, string.gsub(getPlayerName(targetPlayer), "_", " "), false)
local targetid = tonumber(getElementData(targetPlayer, "gameaccountid"))
local found = false
for key, value in ipairs(friends) do
if (friends[key]==targetid) then
found = true
end
end
if (found==false) then
bAddAsFriend = guiCreateButton(0.05, 0.13, 0.87, 0.1, "Add as friend", true, wRightClick)
addEventHandler("onClientGUIClick", bAddAsFriend, caddFriend, false)
else
bAddAsFriend = guiCreateButton(0.05, 0.13, 0.87, 0.1, "Remove friend", true, wRightClick)
addEventHandler("onClientGUIClick", bAddAsFriend, cremoveFriend, false)
end
bCloseMenu = guiCreateButton(0.05, 0.45, 0.87, 0.1, "Close Menu", true, wRightClick)
addEventHandler("onClientGUIClick", bCloseMenu, hidePlayerMenu, false)
sent = false
-- FRISK
--bFrisk = guiCreateButton(0.05, 0.25, 0.87, 0.1, "Frisk", true, wRightClick)
--addEventHandler("onClientGUIClick", bFrisk, cfriskPlayer, false)
end
addEvent("displayPlayerMenu", true)
addEventHandler("displayPlayerMenu", getRootElement(), showPlayerMenu)
--------------------
-- FRISKING --
--------------------
wFriskItems, bFriskTakeItem, bFriskClose, gFriskItems, FriskColName = nil
function cfriskPlayer(button, state, x, y)
if not (wFriskItems) then
local width, height = 300, 200
local scrWidth, scrHeight = guiGetScreenSize()
wFriskItems = guiCreateWindow(x, y, width, height, "Frisk: " .. getPlayerName(player), false)
guiWindowSetSizable(wFriskItems, false)
gFriskItems = guiCreateGridList(0.05, 0.1, 0.9, 0.7, true, wFriskItems)
FriskColName = guiGridListAddColumn(gFriskItems, "Name", 0.9)
local items = getElementData(player, "items")
for i = 1, 10 do
local itemID = tonumber(gettok(items, i, string.byte(',')))
if (itemID~=nil) then
local itemName = exports.global:cgetItemName(itemID)
outputChatBox(tostring(itemName))
local row = guiGridListAddRow(gFriskItems)
guiGridListSetItemText(gFriskItems, row, FriskColName, tostring(itemName), false, false)
end
end
bFriskTakeItem = guiCreateButton(0.05, 0.85, 0.45, 0.1, "Take Item", true, wFriskItems)
bFriskClose = guiCreateButton(0.5, 0.85, 0.45, 0.1, "Close", true, wFriskItems)
addEventHandler("onClientGUIClick", bFrisk, hidePlayerMenu, false)
else
guiBringToFront(wFriskItems, true)
end
end
--------------------
-- END FRISKING --
--------------------
function caddFriend()
triggerServerEvent("addFriend", getLocalPlayer(), player)
hidePlayerMenu()
end
function cremoveFriend()
local id = tonumber(getElementData(player, "gameaccountid"))
local username = getPlayerName(player)
triggerServerEvent("removeFriend", getLocalPlayer(), id, username, true)
hidePlayerMenu()
end
function hidePlayerMenu()
destroyElement(bAddAsFriend)
bAddAsFriend = nil
destroyElement(wRightClick)
wRightClick = nil
ax = nil
ay = nil
player = nil
showCursor(false)
end
|
Crash fix for social system
|
Crash fix for social system
git-svn-id: 8769cb08482c9977c94b72b8e184ec7d2197f4f7@249 64450a49-1f69-0410-a0a2-f5ebb52c4f5b
|
Lua
|
bsd-3-clause
|
valhallaGaming/uno,valhallaGaming/uno,valhallaGaming/uno
|
d3a8fd2d166e57b937a2bc6bd2bbda8d372598fa
|
logapi.lua
|
logapi.lua
|
local fs = require( "filesystem" )
local term = require( "term" )
--Container
local logContainerMeta = { }
logContainerMeta.__index = logContainerMeta
function logContainer( inPath ) -- Creates a log container ( sort of a massive list for entries ).
slc = {
path = inPath
entries = { }
}
setmetatable( slc, logContainerMeta )
if ( fs.exists( inPath ) ) then
slc:loadFrom( inPath )
end
return slc
end
function logContainerMeta:addEntry( newEntry ) -- Adds an entry "object" to the specified container.
table.insert( self.entries, newEntry )
io.output( io.open( self.path, "wa" ) )
io.write( newEntry.serialize, "\n" )
io.flush( )
io.close( )
end
-- Looks through container and returns a new table of entries that are matching the filter.
function logContainerMeta:findEntriesByPriority( filterPriority )
retTable = { }
for k, v in ipairs( self.entries ) do
if ( v.priority == tostring( filterPriority ) ) then
table.insert( retTable, v )
end
end
return retTable
end
-- Looks through container and returns a new table of entries that are matching the filter.
-- Note that the filter can be either dd/mm/yy, hh/mm/ss, or dd/mm/yy hh/mm/ss.
function logContainerMeta:findEntriesByDateTime( filtertd )
retTable = { }
for k, v in ipairs( self.entries ) do
if (
v.timedatestamp == filtertd or
string.sub( v.timedatestamp, 1, 8 ) == filtertd or
string.sub( v.timedatestamp, 10, 18 ) == filtertd
) then
table.insert( retTable, v )
end
end
return retTable
end
function logContainerMeta:loadFrom( path ) -- Loads an entry list from the specified path
io.input( path )
for line in io.lines( ) do
self:addEntry( entryUnserialize( line ) )
end
end
function logContainerMeta:save( path ) -- Saves the entry list to the specified path
io.output( path )
for k, v in ipairs( self.entries ) do
io.write( v:serialize( ), "\n" )
end
io.flush( )
io.close( )
end
function logContainerMeta:exportCSV( path )
io.output( path )
io.write( "Date/Time,Log Info,Priority\n" )
for k, v in ipairs( self.entries ) do
io.write( v:serializeCSV( ), "\n" )
end
io.flush( )
io.close( )
end
--Entry
local entryMeta = { }
entryMeta.__index = entryMeta
function entry( intds, inInfo, inPriority ) -- Create new entry "object", intds can be either nil ( get current time ) or you can specify a time, make sure it's in the correct format
e = {
timedatestamp = "",
info = tostring( inInfo ),
priority = tostring( inPriority )
}
if ( intds == nil ) then
e.timedatestamp = tostring( os.date( ) )
else
e.timedatestamp = tostring( intds )
end
setmetatable( e, entryMeta )
return e
end
function entryUnserialize( entrystring ) -- Takes a string and creates an entry from it
part = 0
tds = ""
inf = ""
pri = ""
for i = 1, #entrystring do
cchar = string.sub( entrystring, i, i )
if ( cchar == "|" ) then
part = part + 1
else
if ( cchar ~= "\t" ) then
if ( part == 1 ) then
tds = tds .. cchar
elseif ( part == 2 ) then
inf = inf .. cchar
elseif ( part == 3 ) then
pri = pri .. cchar
end
end
end
end
return entry( tds, inf, pri )
end
function entryMeta:serialize( ) -- Serializes entry for transmission or storage
return "|" .. self.timedatestamp .. "|" .. self.info .. "|" .. self.priority .. "|"
end
function entryMeta:serializeCSV( ) -- Serializes entry for transmission or storage
return "\"" .. self.timedatestamp .. "\",\"" .. self.info .. "\",\"" .. self.priority .. "\""
end
|
local fs = require( "filesystem" )
local term = require( "term" )
--Container
local logContainerMeta = { }
logContainerMeta.__index = logContainerMeta
function logContainer( inPath ) -- Creates a log container ( sort of a massive list for entries ).
slc = {
path = inPath
entries = { }
}
setmetatable( slc, logContainerMeta )
if ( fs.exists( inPath ) ) then
slc:loadFrom( inPath )
end
return slc
end
function logContainerMeta:addEntry( newEntry ) -- Adds an entry "object" to the specified container.
table.insert( self.entries, newEntry )
file = io.open( self.path, "wa" )
io.output( file )
io.write( newEntry.serialize, "\n" )
io.flush( file )
io.close( file )
end
-- Looks through container and returns a new table of entries that are matching the filter.
function logContainerMeta:findEntriesByPriority( filterPriority )
retTable = { }
for k, v in ipairs( self.entries ) do
if ( v.priority == tostring( filterPriority ) ) then
table.insert( retTable, v )
end
end
return retTable
end
-- Looks through container and returns a new table of entries that are matching the filter.
-- Note that the filter can be either dd/mm/yy, hh/mm/ss, or dd/mm/yy hh/mm/ss.
function logContainerMeta:findEntriesByDateTime( filtertd )
retTable = { }
for k, v in ipairs( self.entries ) do
if (
v.timedatestamp == filtertd or
string.sub( v.timedatestamp, 1, 8 ) == filtertd or
string.sub( v.timedatestamp, 10, 18 ) == filtertd
) then
table.insert( retTable, v )
end
end
return retTable
end
function logContainerMeta:loadFrom( path ) -- Loads an entry list from the specified path
io.input( path )
for line in io.lines( ) do
self:addEntry( entryUnserialize( line ) )
end
end
function logContainerMeta:save( path ) -- Saves the entry list to the specified path
io.output( path )
for k, v in ipairs( self.entries ) do
io.write( v:serialize( ), "\n" )
end
io.flush( )
io.close( )
end
function logContainerMeta:exportCSV( path )
io.output( path )
io.write( "Date/Time,Log Info,Priority\n" )
for k, v in ipairs( self.entries ) do
io.write( v:serializeCSV( ), "\n" )
end
io.flush( )
io.close( )
end
--Entry
local entryMeta = { }
entryMeta.__index = entryMeta
function entry( intds, inInfo, inPriority ) -- Create new entry "object", intds can be either nil ( get current time ) or you can specify a time, make sure it's in the correct format
e = {
timedatestamp = "",
info = tostring( inInfo ),
priority = tostring( inPriority )
}
if ( intds == nil ) then
e.timedatestamp = tostring( os.date( ) )
else
e.timedatestamp = tostring( intds )
end
setmetatable( e, entryMeta )
return e
end
function entryUnserialize( entrystring ) -- Takes a string and creates an entry from it
part = 0
tds = ""
inf = ""
pri = ""
for i = 1, #entrystring do
cchar = string.sub( entrystring, i, i )
if ( cchar == "|" ) then
part = part + 1
else
if ( cchar ~= "\t" ) then
if ( part == 1 ) then
tds = tds .. cchar
elseif ( part == 2 ) then
inf = inf .. cchar
elseif ( part == 3 ) then
pri = pri .. cchar
end
end
end
end
return entry( tds, inf, pri )
end
function entryMeta:serialize( ) -- Serializes entry for transmission or storage
return "|" .. self.timedatestamp .. "|" .. self.info .. "|" .. self.priority .. "|"
end
function entryMeta:serializeCSV( ) -- Serializes entry for transmission or storage
return "\"" .. self.timedatestamp .. "\",\"" .. self.info .. "\",\"" .. self.priority .. "\""
end
|
Another IO Fix
|
Another IO Fix
|
Lua
|
mit
|
sirdabalot/OCLOGAPI
|
b65d0926588ece10a064e67a98442a4bd64c05f0
|
epgp_options.lua
|
epgp_options.lua
|
local L = LibStub("AceLocale-3.0"):GetLocale("EPGP")
local GP = LibStub("LibGearPoints-1.0")
local Debug = LibStub("LibDebug-1.0")
function EPGP:SetupOptions()
local options = {
name = "EPGP",
type = "group",
childGroups = "tab",
handler = self,
args = {
help = {
order = 1,
type = "description",
name = L["EPGP is an in game, relational loot distribution system"],
},
hint = {
order = 2,
type = "description",
name = L["Hint: You can open these options by typing /epgp config"],
},
list_errors = {
order = 1000,
type = "execute",
name = L["List errors"],
desc = L["Lists errors during officer note parsing to the default chat frame. Examples are members with an invalid officer note."],
func = function()
outputFunc = function(s) DEFAULT_CHAT_FRAME:AddMessage(s) end
EPGP:ReportErrors(outputFunc)
end,
},
reset = {
order = 1001,
type = "execute",
name = L["Reset EPGP"],
desc = L["Resets EP and GP of all members of the guild. This will set all main toons' EP and GP to 0. Use with care!"],
func = function() StaticPopup_Show("EPGP_RESET_EPGP") end,
},
},
}
local registry = LibStub("AceConfigRegistry-3.0")
registry:RegisterOptionsTable("EPGP Options", options)
local dialog = LibStub("AceConfigDialog-3.0")
dialog:AddToBlizOptions("EPGP Options", "EPGP")
-- Setup options for each module that defines them.
for name, m in self:IterateModules() do
if m.optionsArgs then
-- Set all options under this module as disabled when the module
-- is disabled.
for n, o in pairs(m.optionsArgs) do
if o.disabled then
local old_disabled = o.disabled
o.disabled = function(i)
return old_disabled(i) or m:IsDisabled()
end
else
o.disabled = "IsDisabled"
end
end
-- Add the enable/disable option.
m.optionsArgs.enabled = {
order = 0,
type = "toggle",
width = "full",
name = ENABLE,
get = "IsEnabled",
set = "SetEnabled",
}
end
if m.optionsName then
registry:RegisterOptionsTable("EPGP " .. name, {
handler = m,
order = 100,
type = "group",
name = m.optionsName,
desc = m.optionsDesc,
args = m.optionsArgs,
get = "GetDBVar",
set = "SetDBVar",
})
dialog:AddToBlizOptions("EPGP " .. name, m.optionsName, "EPGP")
end
end
EPGP:RegisterChatCommand("epgp", "ProcessCommand")
end
function EPGP:ProcessCommand(str)
local command, nextpos = self:GetArgs(str, 1)
if command == "config" then
InterfaceOptionsFrame_OpenToCategory("EPGP")
elseif command == "debug" then
Debug:Toggle()
elseif command == "massep" then
local reason, amount = self:GetArgs(str, 2, nextpos)
amount = tonumber(amount)
if self:CanIncEPBy(reason, amount) then
self:IncMassEPBy(reason, amount)
end
elseif command == "ep" then
local member, reason, amount = self:GetArgs(str, 3, nextpos)
amount = tonumber(amount)
if self:CanIncEPBy(reason, amount) then
self:IncEPBy(member, reason, amount)
end
elseif command == "gp" then
local member, itemlink, amount = self:GetArgs(str, 3, nextpos)
self:Print(member, itemlink, amount)
if amount then
amount = tonumber(amount)
else
local gp1, gp2 = GP:GetValue(itemlink)
self:Print(gp1, gp2)
-- Only automatically fill amount if we have a single GP value.
if gp1 and not gp2 then
amount = gp1
end
end
if self:CanIncGPBy(itemlink, amount) then
self:IncGPBy(member, itemlink, amount)
end
elseif command == "decay" then
if EPGP:CanDecayEPGP() then
StaticPopup_Show("EPGP_DECAY_EPGP", EPGP:GetDecayPercent())
end
elseif command == "help" then
local help = {
self.version,
" config - "..L["Open the configuration options"],
" debug - "..L["Open the debug window"],
" massep <reason> <amount> - "..L["Mass EP Award"],
" ep <name> <reason> <amount> - "..L["Award EP"],
" gp <name> <itemlink> [<amount>] - "..L["Credit GP"],
" decay - "..L["Decay of EP/GP by %d%%"]:format(EPGP:GetDecayPercent()),
}
EPGP:Print(table.concat(help, "\n"))
else
if EPGPFrame and IsInGuild() then
if EPGPFrame:IsShown() then
HideUIPanel(EPGPFrame)
else
ShowUIPanel(EPGPFrame)
end
end
end
end
|
local L = LibStub("AceLocale-3.0"):GetLocale("EPGP")
local GP = LibStub("LibGearPoints-1.0")
local Debug = LibStub("LibDebug-1.0")
function EPGP:SetupOptions()
local options = {
name = "EPGP",
type = "group",
childGroups = "tab",
handler = self,
args = {
help = {
order = 1,
type = "description",
name = L["EPGP is an in game, relational loot distribution system"],
},
hint = {
order = 2,
type = "description",
name = L["Hint: You can open these options by typing /epgp config"],
},
list_errors = {
order = 1000,
type = "execute",
name = L["List errors"],
desc = L["Lists errors during officer note parsing to the default chat frame. Examples are members with an invalid officer note."],
func = function()
outputFunc = function(s) DEFAULT_CHAT_FRAME:AddMessage(s) end
EPGP:ReportErrors(outputFunc)
end,
},
reset = {
order = 1001,
type = "execute",
name = L["Reset EPGP"],
desc = L["Resets EP and GP of all members of the guild. This will set all main toons' EP and GP to 0. Use with care!"],
func = function() StaticPopup_Show("EPGP_RESET_EPGP") end,
},
},
}
local registry = LibStub("AceConfigRegistry-3.0")
registry:RegisterOptionsTable("EPGP Options", options)
local dialog = LibStub("AceConfigDialog-3.0")
dialog:AddToBlizOptions("EPGP Options", "EPGP")
-- Setup options for each module that defines them.
for name, m in self:IterateModules() do
if m.optionsArgs then
-- Set all options under this module as disabled when the module
-- is disabled.
for n, o in pairs(m.optionsArgs) do
if o.disabled then
local old_disabled = o.disabled
o.disabled = function(i)
return old_disabled(i) or m:IsDisabled()
end
else
o.disabled = "IsDisabled"
end
end
-- Add the enable/disable option.
m.optionsArgs.enabled = {
order = 0,
type = "toggle",
width = "full",
name = ENABLE,
get = "IsEnabled",
set = "SetEnabled",
}
end
if m.optionsName then
registry:RegisterOptionsTable("EPGP " .. name, {
handler = m,
order = 100,
type = "group",
name = m.optionsName,
desc = m.optionsDesc,
args = m.optionsArgs,
get = "GetDBVar",
set = "SetDBVar",
})
dialog:AddToBlizOptions("EPGP " .. name, m.optionsName, "EPGP")
end
end
EPGP:RegisterChatCommand("epgp", "ProcessCommand")
end
function EPGP:ProcessCommand(str)
str = str:gsub("%%t", UnitName("target") or "notarget")
local command, nextpos = self:GetArgs(str, 1)
if command == "config" then
InterfaceOptionsFrame_OpenToCategory("EPGP")
elseif command == "debug" then
Debug:Toggle()
elseif command == "massep" then
local reason, amount = self:GetArgs(str, 2, nextpos)
amount = tonumber(amount)
if self:CanIncEPBy(reason, amount) then
self:IncMassEPBy(reason, amount)
end
elseif command == "ep" then
local member, reason, amount = self:GetArgs(str, 3, nextpos)
amount = tonumber(amount)
if self:CanIncEPBy(reason, amount) then
self:IncEPBy(member, reason, amount)
end
elseif command == "gp" then
local member, itemlink, amount = self:GetArgs(str, 3, nextpos)
self:Print(member, itemlink, amount)
if amount then
amount = tonumber(amount)
else
local gp1, gp2 = GP:GetValue(itemlink)
self:Print(gp1, gp2)
-- Only automatically fill amount if we have a single GP value.
if gp1 and not gp2 then
amount = gp1
end
end
if self:CanIncGPBy(itemlink, amount) then
self:IncGPBy(member, itemlink, amount)
end
elseif command == "decay" then
if EPGP:CanDecayEPGP() then
StaticPopup_Show("EPGP_DECAY_EPGP", EPGP:GetDecayPercent())
end
elseif command == "help" then
local help = {
self.version,
" config - "..L["Open the configuration options"],
" debug - "..L["Open the debug window"],
" massep <reason> <amount> - "..L["Mass EP Award"],
" ep <name> <reason> <amount> - "..L["Award EP"],
" gp <name> <itemlink> [<amount>] - "..L["Credit GP"],
" decay - "..L["Decay of EP/GP by %d%%"]:format(EPGP:GetDecayPercent()),
}
EPGP:Print(table.concat(help, "\n"))
else
if EPGPFrame and IsInGuild() then
if EPGPFrame:IsShown() then
HideUIPanel(EPGPFrame)
else
ShowUIPanel(EPGPFrame)
end
end
end
end
|
Add support for %t in epgp commands.
|
Add support for %t in epgp commands.
Fixes issue 543.
|
Lua
|
bsd-3-clause
|
sheldon/epgp,ceason/epgp-tfatf,protomech/epgp-dkp-reloaded,ceason/epgp-tfatf,protomech/epgp-dkp-reloaded,hayword/tfatf_epgp,sheldon/epgp,hayword/tfatf_epgp
|
55c11d7a377ab4f77868ebc70630b91868df5979
|
SpatialFractionalMaxPooling.lua
|
SpatialFractionalMaxPooling.lua
|
local SpatialFractionalMaxPooling, parent =
torch.class('nn.SpatialFractionalMaxPooling', 'nn.Module')
-- Usage:
-- nn.SpatialFractionalMaxPooling(poolSizeW, poolSizeH, outW, outH)
-- the output should be the exact size (outH x outW)
-- nn.SpatialFractionalMaxPooling(poolSizeW, poolSizeH, ratioW, ratioH)
-- the output should be the size (floor(inH x ratioH) x floor(inW x ratioW))
-- ratios are numbers between (0, 1) exclusive
function SpatialFractionalMaxPooling:__init(poolSizeW, poolSizeH, arg1, arg2)
parent.__init(self)
assert(poolSizeW >= 2)
assert(poolSizeH >= 2)
-- Pool size (how wide the pooling for each output unit is)
self.poolSizeW = poolSizeW
self.poolSizeH = poolSizeH
-- Random samples are drawn for all
-- batch * plane * (height, width; i.e., 2) points. This determines
-- the 2d "pseudorandom" overlapping pooling regions for each
-- (batch element x input plane). A new set of random samples is
-- drawn every updateOutput call, unless we disable it via
-- :fixPoolingRegions().
self.randomSamples = nil
-- Flag to disable re-generation of random samples for producing
-- a new pooling. For testing purposes
self.newRandomPool = false
if arg1 >= 1 and arg2 >= 1 then
-- Desired output size: the input tensor will determine the reduction
-- ratio
self.outW = arg1
self.outH = arg2
else
-- Reduction ratio specified per each input
-- This is the reduction ratio that we use
self.ratioW = arg1
self.ratioH = arg2
-- The reduction ratio must be between 0 and 1
assert(self.ratioW > 0 and self.ratioW < 1)
assert(self.ratioH > 0 and self.ratioH < 1)
end
end
function SpatialFractionalMaxPooling:getBufferSize_(input)
local batchSize = 0
local planeSize = 0
if input:nDimension() == 3 then
batchSize = 1
planeSize = input:size(1)
elseif input:nDimension() == 4 then
batchSize = input:size(1)
planeSize = input:size(2)
else
error('input must be dim 3 or 4')
end
return torch.LongStorage({batchSize, planeSize, 2})
end
function SpatialFractionalMaxPooling:initSampleBuffer_(input)
local sampleBufferSize = self:getBufferSize_(input)
if self.randomSamples == nil then
self.randomSamples = input.new():resize(sampleBufferSize):uniform()
elseif (self.randomSamples:size(1) ~= sampleBufferSize[1] or
self.randomSamples:size(2) ~= sampleBufferSize[2]) then
self.randomSamples:resize(sampleBufferSize):uniform()
else
if not self.newRandomPool then
-- Create new pooling windows, since this is a subsequent call
self.randomSamples:uniform()
end
end
end
function SpatialFractionalMaxPooling:getOutputSizes_(input)
local outW = self.outW
local outH = self.outH
if self.ratioW ~= nil and self.ratioH ~= nil then
if input:nDimension() == 4 then
outW = math.floor(input:size(4) * self.ratioW)
outH = math.floor(input:size(3) * self.ratioH)
elseif input:nDimension() == 3 then
outW = math.floor(input:size(3) * self.ratioW)
outH = math.floor(input:size(2) * self.ratioH)
else
error('input must be dim 3 or 4')
end
-- Neither can be smaller than 1
assert(outW > 0, 'reduction ratio or input width too small')
assert(outH > 0, 'reduction ratio or input height too small')
else
assert(outW ~= nil and outH ~= nil)
end
return outW, outH
end
-- Call this to turn off regeneration of random pooling regions each
-- updateOutput call.
function SpatialFractionalMaxPooling:fixPoolingRegions(val)
if val == nil then
val = true
end
self.newRandomPool = val
return self
end
function SpatialFractionalMaxPooling:updateOutput(input)
self.indices = self.indices or input.new()
self:initSampleBuffer_(input)
local outW, outH = self:getOutputSizes_(input)
input.nn.SpatialFractionalMaxPooling_updateOutput(
self.output, input,
outW, outH, self.poolSizeW, self.poolSizeH,
self.indices, self.randomSamples)
return self.output
end
function SpatialFractionalMaxPooling:updateGradInput(input, gradOutput)
assert(self.randomSamples ~= nil,
'must call updateOutput/forward first')
local outW, outH = self:getOutputSizes_(input)
input.nn.SpatialFractionalMaxPooling_updateGradInput(
self.gradInput, input, gradOutput,
outW, outH, self.poolSizeW, self.poolSizeH,
self.indices)
return self.gradInput
end
-- backward compat
function SpatialFractionalMaxPooling:empty()
self:clearState()
end
function SpatialFractionalMaxPooling:clearState()
nn.utils.clear(self, 'indices', 'randomSamples')
return parent.clearState(self)
end
function SpatialFractionalMaxPooling:__tostring__()
return string.format('%s(%d,%d,%d,%d)', torch.type(self),
self.outW and self.outW or self.ratioW,
self.outH and self.outH or self.ratioH,
self.poolSizeW, self.poolSizeH)
end
|
local SpatialFractionalMaxPooling, parent =
torch.class('nn.SpatialFractionalMaxPooling', 'nn.Module')
-- Usage:
-- nn.SpatialFractionalMaxPooling(poolSizeW, poolSizeH, outW, outH)
-- the output should be the exact size (outH x outW)
-- nn.SpatialFractionalMaxPooling(poolSizeW, poolSizeH, ratioW, ratioH)
-- the output should be the size (floor(inH x ratioH) x floor(inW x ratioW))
-- ratios are numbers between (0, 1) exclusive
function SpatialFractionalMaxPooling:__init(poolSizeW, poolSizeH, arg1, arg2)
parent.__init(self)
assert(poolSizeW >= 2)
assert(poolSizeH >= 2)
-- Pool size (how wide the pooling for each output unit is)
self.poolSizeW = poolSizeW
self.poolSizeH = poolSizeH
-- Random samples are drawn for all
-- batch * plane * (height, width; i.e., 2) points. This determines
-- the 2d "pseudorandom" overlapping pooling regions for each
-- (batch element x input plane). A new set of random samples is
-- drawn every updateOutput call, unless we disable it via
-- :fixPoolingRegions().
self.randomSamples = nil
-- Flag to disable re-generation of random samples for producing
-- a new pooling. For testing purposes
self.newRandomPool = false
if arg1 >= 1 and arg2 >= 1 then
-- Desired output size: the input tensor will determine the reduction
-- ratio
self.outW = arg1
self.outH = arg2
else
-- Reduction ratio specified per each input
-- This is the reduction ratio that we use
self.ratioW = arg1
self.ratioH = arg2
-- The reduction ratio must be between 0 and 1
assert(self.ratioW > 0 and self.ratioW < 1)
assert(self.ratioH > 0 and self.ratioH < 1)
end
end
function SpatialFractionalMaxPooling:getBufferSize_(input)
local batchSize = 0
local planeSize = 0
if input:nDimension() == 3 then
batchSize = 1
planeSize = input:size(1)
elseif input:nDimension() == 4 then
batchSize = input:size(1)
planeSize = input:size(2)
else
error('input must be dim 3 or 4')
end
return torch.LongStorage({batchSize, planeSize, 2})
end
function SpatialFractionalMaxPooling:initSampleBuffer_(input)
local sampleBufferSize = self:getBufferSize_(input)
if self.randomSamples == nil then
self.randomSamples = input.new():resize(sampleBufferSize):uniform()
elseif (self.randomSamples:size(1) ~= sampleBufferSize[1] or
self.randomSamples:size(2) ~= sampleBufferSize[2]) then
self.randomSamples:resize(sampleBufferSize):uniform()
else
if not self.newRandomPool then
-- Create new pooling windows, since this is a subsequent call
self.randomSamples:uniform()
end
end
end
function SpatialFractionalMaxPooling:getOutputSizes_(input)
local outW = self.outW
local outH = self.outH
if self.ratioW ~= nil and self.ratioH ~= nil then
if input:nDimension() == 4 then
outW = math.floor(input:size(4) * self.ratioW)
outH = math.floor(input:size(3) * self.ratioH)
elseif input:nDimension() == 3 then
outW = math.floor(input:size(3) * self.ratioW)
outH = math.floor(input:size(2) * self.ratioH)
else
error('input must be dim 3 or 4')
end
-- Neither can be smaller than 1
assert(outW > 0, 'reduction ratio or input width too small')
assert(outH > 0, 'reduction ratio or input height too small')
else
assert(outW ~= nil and outH ~= nil)
end
return outW, outH
end
-- Call this to turn off regeneration of random pooling regions each
-- updateOutput call.
function SpatialFractionalMaxPooling:fixPoolingRegions(val)
if val == nil then
val = true
end
self.newRandomPool = val
return self
end
function SpatialFractionalMaxPooling:updateOutput(input)
self.indices = self.indices or input.new()
self:initSampleBuffer_(input)
local outW, outH = self:getOutputSizes_(input)
input.nn.SpatialFractionalMaxPooling_updateOutput(
self.output, input,
outW, outH, self.poolSizeW, self.poolSizeH,
self.indices, self.randomSamples)
return self.output
end
function SpatialFractionalMaxPooling:updateGradInput(input, gradOutput)
assert(self.randomSamples ~= nil,
'must call updateOutput/forward first')
local outW, outH = self:getOutputSizes_(input)
input.nn.SpatialFractionalMaxPooling_updateGradInput(
self.gradInput, input, gradOutput,
outW, outH, self.poolSizeW, self.poolSizeH,
self.indices)
return self.gradInput
end
-- backward compat
function SpatialFractionalMaxPooling:empty()
self:clearState()
end
function SpatialFractionalMaxPooling:clearState()
self.indices = nil
self.randomSamples = nil
return parent.clearState(self)
end
function SpatialFractionalMaxPooling:__tostring__()
return string.format('%s(%d,%d,%d,%d)', torch.type(self),
self.outW and self.outW or self.ratioW,
self.outH and self.outH or self.ratioH,
self.poolSizeW, self.poolSizeH)
end
|
Fix problem with nn.SpatialFractionalMaxPooling:clearState()
|
Fix problem with nn.SpatialFractionalMaxPooling:clearState()
:initSampleBuffer_() was producing an error when called (from :updateOutput()) after calling :clearState(). The randomSamples field was an empty tensor in that case.
Now :clearState() sets indices and randomSamples to nil, so the module is in the same state as after construction.
|
Lua
|
bsd-3-clause
|
sagarwaghmare69/nn,diz-vara/nn,kmul00/nn,andreaskoepf/nn,apaszke/nn,colesbury/nn,nicholas-leonard/nn,joeyhng/nn,caldweln/nn,elbamos/nn,jonathantompson/nn,PraveerSINGH/nn,xianjiec/nn,jhjin/nn,eriche2016/nn
|
531d9932a46e20fd46a895c004bc949c6eb55185
|
core/storagemanager.lua
|
core/storagemanager.lua
|
local error, type = error, type;
local setmetatable = setmetatable;
local config = require "core.configmanager";
local datamanager = require "util.datamanager";
local modulemanager = require "core.modulemanager";
local multitable = require "util.multitable";
local hosts = hosts;
local log = require "util.logger".init("storagemanager");
local olddm = {}; -- maintain old datamanager, for backwards compatibility
for k,v in pairs(datamanager) do olddm[k] = v; end
local prosody = prosody;
module("storagemanager")
local default_driver_mt = { name = "internal" };
default_driver_mt.__index = default_driver_mt;
function default_driver_mt:open(store)
return setmetatable({ host = self.host, store = store }, default_driver_mt);
end
function default_driver_mt:get(user) return olddm.load(user, self.host, self.store); end
function default_driver_mt:set(user, data) return olddm.store(user, self.host, self.store, data); end
local stores_available = multitable.new();
function initialize_host(host)
local host_session = hosts[host];
host_session.events.add_handler("item-added/data-driver", function (event)
local item = event.item;
stores_available:set(host, item.name, item);
end);
host_session.events.add_handler("item-removed/data-driver", function (event)
local item = event.item;
stores_available:set(host, item.name, nil);
end);
end
prosody.events.add_handler("host-activated", initialize_host, 101);
local function load_driver(host, driver_name)
if not driver_name then
return;
end
local driver = stores_available:get(host, driver_name);
if driver then return driver; end
if driver_name ~= "internal" then
local ok, err = modulemanager.load(host, "storage_"..driver_name);
if not ok then
log("error", "Failed to load storage driver plugin %s: %s", driver_name, err);
end
return stores_available:get(host, driver_name);
else
return setmetatable({host = host}, default_driver_mt);
end
end
function open(host, store, typ)
local storage = config.get(host, "core", "storage");
local driver_name;
local option_type = type(storage);
if option_type == "string" then
driver_name = storage;
elseif option_type == "table" then
driver_name = storage[store];
end
local driver = load_driver(host, driver_name);
if not driver then
driver_name = config.get(host, "core", "default_storage");
driver = load_driver(host, driver_name);
if not driver then
if driver_name or (type(storage) == "string"
or type(storage) == "table" and storage[store]) then
log("warn", "Falling back to default driver for %s storage on %s", store, host);
end
driver_name = "internal";
driver = load_driver(host, driver_name);
end
end
local ret, err = driver:open(store, typ);
if not ret then
if err == "unsupported-store" then
log("debug", "Storage driver %s does not support store %s (%s), falling back to internal driver",
driver_name, store, typ);
ret = setmetatable({ host = host, store = store }, default_driver_mt); -- default to default driver
err = nil;
end
end
return ret, err;
end
function datamanager.load(username, host, datastore)
return open(host, datastore):get(username);
end
function datamanager.store(username, host, datastore, data)
return open(host, datastore):set(username, data);
end
return _M;
|
local error = error;
local setmetatable = setmetatable;
local config = require "core.configmanager";
local datamanager = require "util.datamanager";
local modulemanager = require "core.modulemanager";
local hosts = hosts;
local log = require "util.logger".init("storagemanager");
local olddm = {}; -- maintain old datamanager, for backwards compatibility
for k,v in pairs(datamanager) do olddm[k] = v; end
module("storagemanager")
local default_driver_mt = { name = "internal" };
default_driver_mt.__index = default_driver_mt;
function default_driver_mt:open(store)
return setmetatable({ host = self.host, store = store }, default_driver_mt);
end
function default_driver_mt:get(user) return olddm.load(user, self.host, self.store); end
function default_driver_mt:set(user, data) return olddm.store(user, self.host, self.store, data); end
local stores_available = multitable.new();
function initialize_host(host)
host_session.events.add_handler("item-added/data-driver", function (event)
local item = event.item;
stores_available:set(host, item.name, item);
end);
host_session.events.add_handler("item-removed/data-driver", function (event)
local item = event.item;
stores_available:set(host, item.name, nil);
end);
end
local function load_driver(host, driver_name)
if not driver_name then
return;
end
local driver = stores_available:get(host, driver_name);
if not driver then
if driver_name ~= "internal" then
modulemanager.load(host, "storage_"..driver_name);
else
return setmetatable({host = host}, default_driver_mt);
end
end
end
function open(host, store, typ)
local storage = config.get(host, "core", "storage");
local driver_name;
local option_type = type(storage);
if option_type == "string" then
driver_name = storage;
elseif option_type == "table" then
driver_name = storage[store];
end
local driver = load_driver(host, driver_name);
if not driver then
driver_name = config.get(host, "core", "default_storage");
driver = load_driver(host, driver_name);
if not driver then
driver_name = "internal";
log("warn", "Falling back to default driver for %s storage on %s", store, host);
driver = load_driver(host, driver_name);
end
end
local ret, err = driver:open(store, typ);
if not ret then
if err == "unsupported-store" then
log("debug", "Storage driver %s does not support store %s (%s), falling back to internal driver",
driver_name, store, typ);
ret = setmetatable({ host = host, store = store }, default_driver_mt); -- default to default driver
err = nil;
end
end
return ret, err;
end
function datamanager.load(username, host, datastore)
return open(host, datastore):get(username);
end
function datamanager.store(username, host, datastore, data)
return open(host, datastore):set(username, data);
end
return _M;
|
storagemanager: Fix syntax error
|
storagemanager: Fix syntax error
|
Lua
|
mit
|
sarumjanuch/prosody,sarumjanuch/prosody
|
ad521bf4802894dbb21c21c3ad34792f0976d9d0
|
nyagos.lua
|
nyagos.lua
|
print "Nihongo Yet Another GOing Shell"
print "Copyright (c) 2014 HAYAMA_Kaoru and NYAOS.ORG"
-- This is system-lua files which will be updated.
-- When you want to customize, please edit ~\.nyagos
-- Please do not edit this.
local function split(equation)
local pos=string.find(equation,"=",1,true)
if pos then
local left=string.sub(equation,1,pos-1)
local right=string.sub(equation,pos+1)
return left,right,pos
else
return nil,nil,nil
end
end
function set(equation)
local left,right,pos = split(equation)
if pos and string.sub(left,-1) == "+" then
left = string.sub(left,1,-2)
local original=os.getenv(left)
if string.find(right,original) then
right = right .. ";" .. original
else
right = original
end
end
if right then
right = string.gsub(right,"%%(%w+)%%",function(w)
return os.getenv(w)
end)
nyagos.setenv(left,right)
end
end
function alias(equation)
local left,right,pos = split(equation)
if right then
nyagos.alias(left,right)
end
end
function exists(path)
local fd=io.open(path)
if fd then
fd:close()
return true
else
return false
end
end
exec = nyagos.exec
alias 'assoc=%COMSPEC% /c assoc $*'
alias 'attrib=%COMSPEC% /c attrib $*'
alias 'copy=%COMSPEC% /c copy $*'
alias 'del=%COMSPEC% /c del $*'
alias 'dir=%COMSPEC% /c dir $*'
alias 'for=%COMSPEC% /c for $*'
alias 'md=%COMSPEC% /c md $*'
alias 'mkdir=%COMSPEC% /c mkdir $*'
alias 'mklink=%COMSPEC% /c mklink $*'
alias 'move=%COMSPEC% /c move $*'
alias 'open=%COMSPEC% /c for %I in ($*) do @start "%I"'
alias 'rd=%COMSPEC% /c rd $*'
alias 'ren=%COMSPEC% /c ren $*'
alias 'rename=%COMSPEC% /c rename $*'
alias 'rmdir=%COMSPEC% /c rmdir $*'
alias 'start=%COMSPEC% /c start $*'
alias 'type=%COMSPEC% /c type $*'
alias 'ls=ls -oF $*'
local home = os.getenv("HOME") or os.getenv("USERPROFILE")
if home then
exec "cd"
local rcfname = '.nyagos'
if exists(rcfname) then
local chank,err=loadfile(rcfname)
if chank then
chank()
elseif err then
print(err)
end
end
end
|
print "Nihongo Yet Another GOing Shell"
print "Copyright (c) 2014 HAYAMA_Kaoru and NYAOS.ORG"
-- This is system-lua files which will be updated.
-- When you want to customize, please edit ~\.nyagos
-- Please do not edit this.
local function split(equation)
local pos=string.find(equation,"=",1,true)
if pos then
local left=string.sub(equation,1,pos-1)
local right=string.sub(equation,pos+1)
return left,right,pos
else
return nil,nil,nil
end
end
function set(equation)
local left,right,pos = split(equation)
if pos and string.sub(left,-1) == "+" then
left = string.sub(left,1,-2)
local original=os.getenv(left)
if string.find(right,original) then
right = original
else
right = right .. ";" .. original
end
end
if right then
right = string.gsub(right,"%%(%w+)%%",function(w)
return os.getenv(w)
end)
nyagos.setenv(left,right)
end
end
function alias(equation)
local left,right,pos = split(equation)
if right then
nyagos.alias(left,right)
end
end
function exists(path)
local fd=io.open(path)
if fd then
fd:close()
return true
else
return false
end
end
exec = nyagos.exec
alias 'assoc=%COMSPEC% /c assoc $*'
alias 'attrib=%COMSPEC% /c attrib $*'
alias 'copy=%COMSPEC% /c copy $*'
alias 'del=%COMSPEC% /c del $*'
alias 'dir=%COMSPEC% /c dir $*'
alias 'for=%COMSPEC% /c for $*'
alias 'md=%COMSPEC% /c md $*'
alias 'mkdir=%COMSPEC% /c mkdir $*'
alias 'mklink=%COMSPEC% /c mklink $*'
alias 'move=%COMSPEC% /c move $*'
alias 'open=%COMSPEC% /c for %I in ($*) do @start "%I"'
alias 'rd=%COMSPEC% /c rd $*'
alias 'ren=%COMSPEC% /c ren $*'
alias 'rename=%COMSPEC% /c rename $*'
alias 'rmdir=%COMSPEC% /c rmdir $*'
alias 'start=%COMSPEC% /c start $*'
alias 'type=%COMSPEC% /c type $*'
alias 'ls=ls -oF $*'
local home = os.getenv("HOME") or os.getenv("USERPROFILE")
if home then
exec "cd"
local rcfname = '.nyagos'
if exists(rcfname) then
local chank,err=loadfile(rcfname)
if chank then
chank()
elseif err then
print(err)
end
end
end
|
Fix: set "PATH+=..." が機能していなかった
|
Fix: set "PATH+=..." が機能していなかった
|
Lua
|
bsd-3-clause
|
tsuyoshicho/nyagos,hattya/nyagos,kissthink/nyagos,kissthink/nyagos,zetamatta/nyagos,nocd5/nyagos,kissthink/nyagos,tyochiai/nyagos,hattya/nyagos,hattya/nyagos
|
cb2291dc20f37cd771059c8557e3ece6e513b747
|
runtime/chooseOutputs.lua
|
runtime/chooseOutputs.lua
|
local A = 174;
local B = 175;
local LEFT = 170;
local RIGHT = 171;
local AIR = 0
local TILE = 1
local GOOMBA = 2
nodes = {};
connections = {};
connectionsLitMap = {};
require('NEAT/util/generateNeurons')
require('NEAT/models/Node')
require('NEAT/models/connection')
require('NEAT/config')
--Solve the node recursively
function solveNode(node)
for k, conn in pairs(node.connections) do
--Recursively solve the node
if (conn.to.litTile and conn.litTile) then return end;
if (conn.to.litGoomba and conn.litGoomba) then return end;
--Only try to light the node if it's not lit already
if (conn.type == 1 and node.litTile) then
conn.to.litTile = true;
connectionsLitMap[conn.id].lit = true;
end;
if (conn.type == 2 and node.litGoomba) then
conn.to.litGoomba = true;
connectionsLitMap[conn.id].lit = true;
end;
return solveNode(conn.to);
end
end
--Select which buttons to press based off the synapses
function chooseOutputs(synapses, tiles)
local neurons = generateNeurons(synapses);
--Create a Node for every Neuron and add it to the nodes
for k, neur in pairs(neurons) do
local node = Node:new();
node.ID = neur.label;
node.type = neur.type;
nodes[node.ID] = node;
end;
--Iterate through all the synapses in the species
for k, syn in pairs(synapses) do
local connection = Connection:new();
connection.id = syn.historicalMarking;
connection.to = nodes[syn.to];
connection.from = nodes[syn.from];
connection.weight = syn.weight;
--Object specifically to pass to the server to show the status of the synapse
local connectionLit = {};
connectionLit.type = syn.type;
connectionLit.lit = false;
connectionLit.historicalMarking = syn.historicalMarking;
--Add it to the litMap
connectionsLitMap[syn.historicalMarking] = connectionLit;
table.insert(nodes[syn.from].connections, connection);
table.insert(connections, connection);
end;
--Check the power of the first layer of Nodes
for idx=1,168 do
--Ensure we have a node associated with that tile
if (nodes[idx]) then
local node = nodes[idx];
--Find the coordinates of the tile
local y = math.floor(idx / 13) - 6;
local x = (idx % 13);
if x == 0 then x = 13 end;
--Find the value at the tile
local tileVal = tiles[y][x];
--Node is lit of tileVal == node.type
--Light the respective connections
litGoomba = tileVal == 2;
litTile = tileVal == 1;
node.litGoomba = litGoomba;
node.litTile = litTile;
for k,conn in pairs(node.connections) do
if (conn.type == 1 and litTile) then conn.litTile = true end;
if (conn.type == 2 and litGoomba) then conn.litGoomba = true end;
end
--Solve the node
solveNode(node);
end;
end
local nodeA = nodes[A];
local nodeB = nodes[B];
local nodeRight = nodes[RIGHT];
local nodeLeft = nodes[LEFT];
local outputs = {};
outputs.a = nodeA.litTile or nodeA.litGoomba;
outputs.b = nodeB.litTile or nodeB.litGoomba;
outputs.right = nodeRight.litTile or nodeRight.litGoomba;
if MODDED_ALGORITHM then
outputs.left = false
else
outputs.left = nodeLeft.litTile or nodeLeft.litGoomba;
end
return outputs;
-- print(pretty(nodes));
--Check if we've created a Node from the IDs yet
end
|
local A = 174;
local B = 175;
local LEFT = 170;
local RIGHT = 171;
local AIR = 0
local TILE = 1
local GOOMBA = 2
connectionsLitMap = {};
require('NEAT/util/generateNeurons')
require('NEAT/models/Node')
require('NEAT/models/connection')
require('NEAT/config')
--Solve the node recursively
function solveNode(node)
for k, conn in pairs(node.connections) do
--Recursively solve the node
if (conn.to.litTile and conn.litTile) then return end;
if (conn.to.litGoomba and conn.litGoomba) then return end;
--Only try to light the node if it's not lit already
if (conn.type == 1 and node.litTile) then
conn.to.litTile = true;
connectionsLitMap[conn.id].lit = true;
end;
if (conn.type == 2 and node.litGoomba) then
conn.to.litGoomba = true;
connectionsLitMap[conn.id].lit = true;
end;
return solveNode(conn.to);
end
end
--Select which buttons to press based off the synapses
function chooseOutputs(synapses, tiles)
local nodes = {};
local connections = {};
local neurons = generateNeurons(synapses);
--Create a Node for every Neuron and add it to the nodes
for k, neur in pairs(neurons) do
local node = Node:new();
node.ID = neur.label;
node.type = neur.type;
nodes[node.ID] = node;
end;
--Iterate through all the synapses in the species
for k, syn in pairs(synapses) do
local connection = Connection:new();
connection.id = syn.historicalMarking;
connection.to = nodes[syn.to];
connection.from = nodes[syn.from];
connection.weight = syn.weight;
--Object specifically to pass to the server to show the status of the synapse
local connectionLit = {};
connectionLit.type = syn.type;
connectionLit.lit = false;
connectionLit.historicalMarking = syn.historicalMarking;
--Add it to the litMap
connectionsLitMap[syn.historicalMarking] = connectionLit;
table.insert(nodes[syn.from].connections, connection);
table.insert(connections, connection);
end;
--Check the power of the first layer of Nodes
for idx=1,168 do
--Ensure we have a node associated with that tile
if (nodes[idx]) then
local node = nodes[idx];
--Find the coordinates of the tile
local y = math.floor(idx / 13) - 6;
local x = (idx % 13);
if x == 0 then x = 13 end;
--Find the value at the tile
local tileVal = tiles[y][x];
--Node is lit of tileVal == node.type
--Light the respective connections
litGoomba = tileVal == 2;
litTile = tileVal == 1;
node.litGoomba = litGoomba;
node.litTile = litTile;
for k,conn in pairs(node.connections) do
if (conn.type == 1 and litTile) then conn.litTile = true end;
if (conn.type == 2 and litGoomba) then conn.litGoomba = true end;
end
--Solve the node
solveNode(node);
end;
end
local nodeA = nodes[A];
local nodeB = nodes[B];
local nodeRight = nodes[RIGHT];
local nodeLeft = nodes[LEFT];
local outputs = {};
outputs.a = nodeA.litTile or nodeA.litGoomba;
outputs.b = nodeB.litTile or nodeB.litGoomba;
outputs.right = nodeRight.litTile or nodeRight.litGoomba;
if MODDED_ALGORITHM then
outputs.left = false
else
outputs.left = nodeLeft.litTile or nodeLeft.litGoomba;
end
return outputs;
-- print(pretty(nodes));
--Check if we've created a Node from the IDs yet
end
|
Fixed memory leak
|
Fixed memory leak
|
Lua
|
mit
|
joenot443/crAIg,joenot443/crAIg,joenot443/crAIg
|
ab4d70bf69949b5695f2467f547e1514791c60ab
|
tools/premake/app_template.lua
|
tools/premake/app_template.lua
|
function add_pmtech_links()
configuration "Debug"
links { "pen_d", "put_d" }
configuration "Release"
links { "pen", "put" }
configuration {}
end
local function add_osx_links()
links
{
"Cocoa.framework",
"OpenGL.framework",
"GameController.framework",
"iconv",
"fmod"
}
add_pmtech_links()
end
local function add_linux_links()
links
{
"pthread",
"GLEW",
"GLU",
"GL",
"X11",
"fmod"
}
add_pmtech_links()
end
local function add_win32_links()
links
{
"d3d11.lib",
"dxguid.lib",
"winmm.lib",
"comctl32.lib",
"fmod64_vc.lib",
"Shlwapi.lib"
}
add_pmtech_links()
end
local function add_ios_links()
links
{
"OpenGLES.framework",
"Foundation.framework",
"UIKit.framework",
"GLKit.framework",
"QuartzCore.framework",
}
end
local function add_ios_files(project_name, root_directory)
files
{
(pmtech_dir .. "/template/ios/**.*"),
"bin/ios/data"
}
excludes
{
("**.DS_Store")
}
xcodebuildresources
{
"bin/ios/data"
}
end
local function setup_android()
files
{
pmtech_dir .. "/template/android/manifest/**.*",
pmtech_dir .. "/template/android/activity/**.*"
}
androidabis
{
"armeabi-v7a", "x86"
}
end
local function setup_platform(project_name, root_directory)
if platform_dir == "win32" then
systemversion(windows_sdk_version())
disablewarnings { "4800", "4305", "4018", "4244", "4267", "4996" }
add_win32_links()
elseif platform_dir == "osx" then
add_osx_links()
elseif platform_dir == "ios" then
add_ios_links()
add_ios_files(project_name, root_directory)
elseif platform_dir == "linux" then
add_linux_links()
elseif platform_dir == "android" then
setup_android()
end
end
local function setup_bullet()
bullet_lib = "bullet_monolithic"
bullet_lib_debug = "bullet_monolithic_d"
bullet_lib_dir = "osx"
if platform_dir == "linux" then
bullet_lib_dir = "linux"
end
if _ACTION == "vs2017" or _ACTION == "vs2015" then
bullet_lib_dir = _ACTION
bullet_lib = (bullet_lib .. "_x64")
bullet_lib_debug = (bullet_lib_debug .. "_x64")
end
libdirs
{
(pmtech_dir .. "third_party/bullet/lib/" .. bullet_lib_dir)
}
configuration "Debug"
links { bullet_lib_debug }
configuration "Release"
links { bullet_lib }
configuration {}
end
local function setup_fmod()
libdirs
{
(pmtech_dir .. "third_party/fmod/lib/" .. platform_dir)
}
end
function setup_modules()
setup_bullet()
setup_fmod()
end
function create_app(project_name, source_directory, root_directory)
project ( project_name )
kind "WindowedApp"
language "C++"
dependson { "pen", "put" }
includedirs
{
pmtech_dir .. "pen/include",
pmtech_dir .. "pen/include/common",
pmtech_dir .. "pen/include/" .. platform_dir,
pmtech_dir .. "pen/include/" .. renderer_dir,
pmtech_dir .. "put/include/",
pmtech_dir .. "third_party/",
"include/",
}
files
{
(root_directory .. "code/" .. source_directory .. "/**.cpp"),
(root_directory .. "code/" .. source_directory .. "/**.c"),
(root_directory .. "code/" .. source_directory .. "/**.h"),
(root_directory .. "code/" .. source_directory .. "/**.m"),
(root_directory .. "code/" .. source_directory .. "/**.mm")
}
libdirs
{
pmtech_dir .. "pen/lib/" .. platform_dir,
pmtech_dir .. "put/lib/" .. platform_dir,
}
setup_env()
setup_platform(project_name, root_directory)
setup_modules()
location (root_directory .. "/build/" .. platform_dir)
targetdir (root_directory .. "/bin/" .. platform_dir)
debugdir (root_directory .. "/bin/" .. platform_dir)
configuration "Debug"
defines { "DEBUG" }
flags { "WinMain" }
symbols "On"
targetname (project_name .. "_d")
architecture "x64"
configuration "Release"
defines { "NDEBUG" }
flags { "WinMain", "OptimizeSpeed" }
targetname (project_name)
architecture "x64"
end
function create_app_example( project_name, root_directory )
create_app( project_name, project_name, root_directory )
end
|
function add_pmtech_links()
configuration "Debug"
links { "put_d", "pen_d" }
configuration "Release"
links { "put", "pen" }
configuration {}
end
local function add_osx_links()
links
{
"Cocoa.framework",
"OpenGL.framework",
"GameController.framework",
"iconv",
"fmod"
}
add_pmtech_links()
end
local function add_linux_links()
add_pmtech_links()
links
{
"pthread",
"GLEW",
"GLU",
"GL",
"X11",
"fmod"
}
end
local function add_win32_links()
links
{
"d3d11.lib",
"dxguid.lib",
"winmm.lib",
"comctl32.lib",
"fmod64_vc.lib",
"Shlwapi.lib"
}
add_pmtech_links()
end
local function add_ios_links()
links
{
"OpenGLES.framework",
"Foundation.framework",
"UIKit.framework",
"GLKit.framework",
"QuartzCore.framework",
}
end
local function add_ios_files(project_name, root_directory)
files
{
(pmtech_dir .. "/template/ios/**.*"),
"bin/ios/data"
}
excludes
{
("**.DS_Store")
}
xcodebuildresources
{
"bin/ios/data"
}
end
local function setup_android()
files
{
pmtech_dir .. "/template/android/manifest/**.*",
pmtech_dir .. "/template/android/activity/**.*"
}
androidabis
{
"armeabi-v7a", "x86"
}
end
local function setup_platform(project_name, root_directory)
if platform_dir == "win32" then
systemversion(windows_sdk_version())
disablewarnings { "4800", "4305", "4018", "4244", "4267", "4996" }
add_win32_links()
elseif platform_dir == "osx" then
add_osx_links()
elseif platform_dir == "ios" then
add_ios_links()
add_ios_files(project_name, root_directory)
elseif platform_dir == "linux" then
add_linux_links()
elseif platform_dir == "android" then
setup_android()
end
end
local function setup_bullet()
bullet_lib = "bullet_monolithic"
bullet_lib_debug = "bullet_monolithic_d"
bullet_lib_dir = "osx"
if platform_dir == "linux" then
bullet_lib_dir = "linux"
end
if _ACTION == "vs2017" or _ACTION == "vs2015" then
bullet_lib_dir = _ACTION
bullet_lib = (bullet_lib .. "_x64")
bullet_lib_debug = (bullet_lib_debug .. "_x64")
end
libdirs
{
(pmtech_dir .. "third_party/bullet/lib/" .. bullet_lib_dir)
}
configuration "Debug"
links { bullet_lib_debug }
configuration "Release"
links { bullet_lib }
configuration {}
end
local function setup_fmod()
libdirs
{
(pmtech_dir .. "third_party/fmod/lib/" .. platform_dir)
}
end
function setup_modules()
setup_bullet()
setup_fmod()
end
function create_app(project_name, source_directory, root_directory)
project ( project_name )
kind "WindowedApp"
language "C++"
dependson { "pen", "put" }
includedirs
{
pmtech_dir .. "pen/include",
pmtech_dir .. "pen/include/common",
pmtech_dir .. "pen/include/" .. platform_dir,
pmtech_dir .. "pen/include/" .. renderer_dir,
pmtech_dir .. "put/include/",
pmtech_dir .. "third_party/",
"include/",
}
files
{
(root_directory .. "code/" .. source_directory .. "/**.cpp"),
(root_directory .. "code/" .. source_directory .. "/**.c"),
(root_directory .. "code/" .. source_directory .. "/**.h"),
(root_directory .. "code/" .. source_directory .. "/**.m"),
(root_directory .. "code/" .. source_directory .. "/**.mm")
}
libdirs
{
pmtech_dir .. "pen/lib/" .. platform_dir,
pmtech_dir .. "put/lib/" .. platform_dir,
}
setup_env()
setup_platform(project_name, root_directory)
setup_modules()
location (root_directory .. "/build/" .. platform_dir)
targetdir (root_directory .. "/bin/" .. platform_dir)
debugdir (root_directory .. "/bin/" .. platform_dir)
configuration "Debug"
defines { "DEBUG" }
flags { "WinMain" }
symbols "On"
targetname (project_name .. "_d")
architecture "x64"
configuration "Release"
defines { "NDEBUG" }
flags { "WinMain", "OptimizeSpeed" }
targetname (project_name)
architecture "x64"
end
function create_app_example( project_name, root_directory )
create_app( project_name, project_name, root_directory )
end
|
fix link order for linux
|
fix link order for linux
|
Lua
|
mit
|
polymonster/pmtech,polymonster/pmtech,polymonster/pmtech,polymonster/pmtech,polymonster/pmtech,polymonster/pmtech
|
ec61a3655f73009275fa451a3ae737853dfc9edb
|
watchlog/watchlogfilejavalog.lua
|
watchlog/watchlogfilejavalog.lua
|
local multilineW = require 'watchlog.watchlogfilemultiline'
local util = require 'util.util'
local tableutil = require 'util.tableutil'
local json = require 'rapidjson'
local watchlogfilejavalog = {
---- CONSTANTS ----
---- Core Data ----
---- Temp Data ----
}
setmetatable(watchlogfilejavalog , multilineW)
watchlogfilejavalog.__index = watchlogfilejavalog
function watchlogfilejavalog:new(task, customParserConfig, tunningConfig, first)
local self = {}
self = multilineW:new(task, customParserConfig, tunningConfig, first)
setmetatable(self , watchlogfilejavalog)
return self
end
function watchlogfilejavalog:handleEventPlus(kafkaClient , topic , msgTable)
if self.multiLineNum == 1 then
self:handleEvent(kafkaClient , topic , msgTable[1])
else
local handled = self:parseData(msgTable[1])
local tmp_content = {}
if handled then
local exceptionName , exceptionMsg = msgTable[2]:match('%s?([^%s]-tion):(.*)') --('(.-Exception):(.*)')
if exceptionName and exceptionMsg then
tmp_content['exceptionName'] = exceptionName
tmp_content['exceptionMsg'] = exceptionMsg
if self.multiLineNum > 2 then
tmp_content['stack'] = table.concat(msgTable , '\n' , 2)
end
else
tmp_content['messageDetail'] = table.concat(msgTable , '\n' , 2)
end
tableutil.simpleCopy(self.EVENT_CONTAINER , tmp_content)
kafkaClient.safeSendMsg(topic , self.tempKafkaKey , json.encode(tmp_content) , 10)
else
print(table.concat(msgTable , '\n'))
end
end
end
return watchlogfilejavalog
|
local multilineW = require 'watchlog.watchlogfilemultiline'
local util = require 'util.util'
local tableutil = require 'util.tableutil'
local json = require 'rapidjson'
local watchlogfilejavalog = {
---- CONSTANTS ----
---- Core Data ----
---- Temp Data ----
}
setmetatable(watchlogfilejavalog , multilineW)
watchlogfilejavalog.__index = watchlogfilejavalog
function watchlogfilejavalog:new(task, customParserConfig, tunningConfig, first)
local self = {}
self = multilineW:new(task, customParserConfig, tunningConfig, first)
setmetatable(self , watchlogfilejavalog)
return self
end
function watchlogfilejavalog:handleEventPlus(kafkaClient , topic , msgTable)
if self.multiLineNum == 1 then
self:handleEvent(kafkaClient , topic , msgTable[1])
else
self.count = self.count + self.multiLineNum
local handled = self:parseData(msgTable[1])
local tmp_content = {}
if handled then
local exceptionName , exceptionMsg = msgTable[2]:match('%s?([^%s]-tion):(.*)') --('(.-Exception):(.*)')
if exceptionName and exceptionMsg then
tmp_content['exceptionName'] = exceptionName
tmp_content['exceptionMsg'] = exceptionMsg
if self.multiLineNum > 2 then
tmp_content['stack'] = table.concat(msgTable , '\n' , 2)
end
else
tmp_content['messageDetail'] = table.concat(msgTable , '\n' , 2)
end
tableutil.simpleCopy(self.EVENT_CONTAINER , tmp_content)
kafkaClient.safeSendMsg(topic , self.tempKafkaKey , json.encode(tmp_content) , 10)
else
print(table.concat(msgTable , '\n'))
end
end
end
return watchlogfilejavalog
|
fix javalog的统计错误
|
fix javalog的统计错误
|
Lua
|
apache-2.0
|
peiliping/logwatch
|
948c1fe6023a37e72ab2db1d5b1ad7f4436add3e
|
applications/luci-app-opkg/luasrc/controller/opkg.lua
|
applications/luci-app-opkg/luasrc/controller/opkg.lua
|
-- Copyright 2018 Jo-Philipp Wich <jo@mein.io>
-- Licensed to the public under the Apache License 2.0.
module("luci.controller.opkg", package.seeall)
function index()
entry({"admin", "system", "opkg"}, template("opkg"), _("Software"), 30)
entry({"admin", "system", "opkg", "list"}, call("action_list")).leaf = true
entry({"admin", "system", "opkg", "exec"}, post("action_exec")).leaf = true
entry({"admin", "system", "opkg", "statvfs"}, call("action_statvfs")).leaf = true
entry({"admin", "system", "opkg", "config"}, post_on({ data = true }, "action_config")).leaf = true
end
function action_list(mode)
local cmd
if mode == "installed" then
cmd = { "/bin/cat", "/usr/lib/opkg/status" }
else
cmd = { "/bin/sh", "-c", [[find /tmp/opkg-lists/ -type f '!' -name '*.sig' | xargs -r gzip -cd]] }
end
luci.http.prepare_content("text/plain; charset=utf-8")
luci.sys.process.exec(cmd, luci.http.write)
end
function action_exec(command, package)
local sys = require "luci.sys"
local cmd = { "/bin/opkg", "--force-removal-of-dependent-packages" }
local pkg = luci.http.formvalue("package")
if luci.http.formvalue("autoremove") == "true" then
cmd[#cmd + 1] = "--autoremove"
end
if luci.http.formvalue("overwrite") == "true" then
cmd[#cmd + 1] = "--force-overwrite"
end
cmd[#cmd + 1] = command
if pkg then
cmd[#cmd + 1] = pkg
end
luci.http.prepare_content("application/json")
luci.http.write_json(sys.process.exec(cmd, true, true))
end
function action_statvfs()
local fs = require "nixio.fs"
luci.http.prepare_content("application/json")
luci.http.write_json(fs.statvfs("/") or {})
end
function action_config()
local fs = require "nixio.fs"
local js = require "luci.jsonc"
local data = luci.http.formvalue("data")
if data then
data = js.parse(data)
if not data then
luci.http.status(400, "Bad Request")
return
end
local file, content
for file, content in pairs(data) do
if type(content) ~= "string" or
(file ~= "opkg.conf" and not file:match("^opkg/[^/]+%.conf$"))
then
luci.http.status(400, "Bad Request")
return
end
local path = "/etc/%s" % file
if not fs.access(path, "w") then
luci.http.status(403, "Permission denied")
return
end
fs.writefile(path, content:gsub("\r\n", "\n"))
end
luci.http.status(204, "Saved")
else
local rv = { ["opkg.conf"] = fs.readfile("/etc/opkg.conf") }
local entries = fs.dir("/etc/opkg")
if entries then
local entry
for entry in entries do
if entry:match("%.conf$") then
rv["opkg/%s" % entry] = fs.readfile("/etc/opkg/%s" % entry)
end
end
end
luci.http.prepare_content("application/json")
luci.http.write_json(rv)
end
end
|
-- Copyright 2018 Jo-Philipp Wich <jo@mein.io>
-- Licensed to the public under the Apache License 2.0.
module("luci.controller.opkg", package.seeall)
function index()
entry({"admin", "system", "opkg"}, template("opkg"), _("Software"), 30)
entry({"admin", "system", "opkg", "list"}, call("action_list")).leaf = true
entry({"admin", "system", "opkg", "exec"}, post("action_exec")).leaf = true
entry({"admin", "system", "opkg", "statvfs"}, call("action_statvfs")).leaf = true
entry({"admin", "system", "opkg", "config"}, post_on({ data = true }, "action_config")).leaf = true
end
function action_list(mode)
local util = require "luci.util"
local cmd
if mode == "installed" then
cmd = { "/bin/cat", "/usr/lib/opkg/status" }
else
local lists_dir = nil
local fd = io.popen([[sed -rne 's#^lists_dir \S+ (\S+)#\1#p' /etc/opkg.conf /etc/opkg/*.conf 2>/dev/null]], "r")
if fd then
lists_dir = fd:read("*l")
fd:close()
end
if not lists_dir or #lists_dir == "" then
lists_dir = "/tmp/opkg-lists"
end
cmd = { "/bin/sh", "-c", [[find %s -type f '!' -name '*.sig' | xargs -r gzip -cd]] % util.shellquote(lists_dir) }
end
luci.http.prepare_content("text/plain; charset=utf-8")
luci.sys.process.exec(cmd, luci.http.write)
end
function action_exec(command, package)
local sys = require "luci.sys"
local cmd = { "/bin/opkg", "--force-removal-of-dependent-packages" }
local pkg = luci.http.formvalue("package")
if luci.http.formvalue("autoremove") == "true" then
cmd[#cmd + 1] = "--autoremove"
end
if luci.http.formvalue("overwrite") == "true" then
cmd[#cmd + 1] = "--force-overwrite"
end
cmd[#cmd + 1] = command
if pkg then
cmd[#cmd + 1] = pkg
end
luci.http.prepare_content("application/json")
luci.http.write_json(sys.process.exec(cmd, true, true))
end
function action_statvfs()
local fs = require "nixio.fs"
luci.http.prepare_content("application/json")
luci.http.write_json(fs.statvfs("/") or {})
end
function action_config()
local fs = require "nixio.fs"
local js = require "luci.jsonc"
local data = luci.http.formvalue("data")
if data then
data = js.parse(data)
if not data then
luci.http.status(400, "Bad Request")
return
end
local file, content
for file, content in pairs(data) do
if type(content) ~= "string" or
(file ~= "opkg.conf" and not file:match("^opkg/[^/]+%.conf$"))
then
luci.http.status(400, "Bad Request")
return
end
local path = "/etc/%s" % file
if not fs.access(path, "w") then
luci.http.status(403, "Permission denied")
return
end
fs.writefile(path, content:gsub("\r\n", "\n"))
end
luci.http.status(204, "Saved")
else
local rv = { ["opkg.conf"] = fs.readfile("/etc/opkg.conf") }
local entries = fs.dir("/etc/opkg")
if entries then
local entry
for entry in entries do
if entry:match("%.conf$") then
rv["opkg/%s" % entry] = fs.readfile("/etc/opkg/%s" % entry)
end
end
end
luci.http.prepare_content("application/json")
luci.http.write_json(rv)
end
end
|
luci-app-opkg: support nonstandard list locations
|
luci-app-opkg: support nonstandard list locations
Fixes: #3287
Signed-off-by: Jo-Philipp Wich <bd73d35759d75cc215150d1bbc94f1b1078bee01@mein.io>
|
Lua
|
apache-2.0
|
hnyman/luci,openwrt/luci,openwrt/luci,lbthomsen/openwrt-luci,rogerpueyo/luci,hnyman/luci,lbthomsen/openwrt-luci,nmav/luci,rogerpueyo/luci,openwrt/luci,hnyman/luci,rogerpueyo/luci,tobiaswaldvogel/luci,nmav/luci,rogerpueyo/luci,openwrt/luci,lbthomsen/openwrt-luci,nmav/luci,hnyman/luci,lbthomsen/openwrt-luci,hnyman/luci,lbthomsen/openwrt-luci,hnyman/luci,tobiaswaldvogel/luci,nmav/luci,openwrt/luci,hnyman/luci,tobiaswaldvogel/luci,lbthomsen/openwrt-luci,openwrt/luci,lbthomsen/openwrt-luci,openwrt/luci,tobiaswaldvogel/luci,rogerpueyo/luci,hnyman/luci,nmav/luci,rogerpueyo/luci,nmav/luci,nmav/luci,tobiaswaldvogel/luci,tobiaswaldvogel/luci,rogerpueyo/luci,rogerpueyo/luci,tobiaswaldvogel/luci,tobiaswaldvogel/luci,lbthomsen/openwrt-luci,nmav/luci,openwrt/luci,nmav/luci
|
64cab0d12833209d5a02c4a8aa9c6b4f452acdbc
|
share/lua/website/ard.lua
|
share/lua/website/ard.lua
|
-- libquvi-scripts
-- Copyright (C) 2013 Thomas Weißschuh
--
-- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>.
--
-- This library is free software; you can redistribute it and/or
-- modify it under the terms of the GNU Lesser General Public
-- License as published by the Free Software Foundation; either
-- version 2.1 of the License, or (at your option) any later version.
--
-- This library is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-- Lesser General Public License for more details.
--
-- You should have received a copy of the GNU Lesser General Public
-- License along with this library; if not, write to the Free Software
-- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
-- 02110-1301 USA
local Ard = {}
function ident(self)
local C = require 'quvi/const'
local U = require 'quvi/util'
local B = require 'quvi/bit'
local r = {}
r.domain = 'www%.ardmediathek%.de'
r.formats = 'default|best'
r.categories = B.bit_or(C.proto_http, C.proto_rtmp)
r.handles = U.handles(self.page_url, {r.domain},
nil, {"documentId=%d+$"})
return r
end
function query_formats(self)
local config = Ard.get_config(self)
local formats = Ard.iter_formats(config)
local t = {}
for _,v in pairs(formats) do
table.insert(t, Ard.to_s(v))
end
table.sort(t)
self.formats = table.concat(t, "|")
return self
end
function parse(self)
local config = Ard.get_config(self)
local Util = require 'quvi/util'
self.host_id = 'ard'
self.title = config:match(
'<meta property="og:title" content="([^"]*)'
):gsub(
'%s*%- %w-$', '' -- remove name of station
):gsub(
'%s*%(FSK.*', '' -- remove FSK nonsense
)
or error('no match: media title')
self.thumbnail_url = config:match(
'<meta property="og:image" content="([^"]*)'
) or ''
local formats = Ard.iter_formats(config)
local format = Util.choose_format(self,
formats,
Ard.choose_best,
Ard.choose_default,
Ard.to_s)
or error('unable to choose format')
if not format.url then error('no match: media url') end
self.url = { format.url }
return self
end
function Ard.test_availability(page)
-- some videos are only scrapable at certain times
local fsk_pattern =
'Der Clip ist deshalb nur von (%d%d?) bis (%d%d?) Uhr verfügbar'
local from, to = page:match(fsk_pattern)
if from and to then
error('video only available from ' ..from.. ':00 to '
..to.. ':00 CET')
end
end
function Ard.get_config(self)
local c = quvi.fetch(self.page_url)
self.id = self.page_url:match('documentId=(%d*)')
or error('no match: media id')
if c:match('<title>ARD Mediathek %- Fehlerseite</title>') then
error('invalid URL, maybe the media is no longer available')
end
return c
end
function Ard.choose_best(t)
return t[#t] -- return the last from the array
end
function Ard.choose_default(t)
return t[1] -- return the first from the array
end
function Ard.to_s(t)
return string.format("%s_%s_i%02d%s%s",
(t.quality) and t.quality or 'sd',
t.container, t.stream_id,
(t.encoding) and '_'..t.encoding or '',
(t.height) and '_'..t.height or '')
end
function Ard.quality_from(suffix)
local q = suffix:match('%.web(%w)%.') or suffix:match('%.(%w)%.')
or suffix:match('[=%.]Web%-(%w)') -- .webs. or Web-S or .s
if q then
q = q:lower()
local t = {s='ld', m='md', l='sd', xl='hd'}
for k,v in pairs(t) do
if q == k then return v end
end
end
return q
end
function Ard.height_from(suffix)
local h = suffix:match('_%d+x(%d+)[_%.]')
if h then return h..'p' end
end
function Ard.container_from(suffix)
return suffix:match('^(...):') or suffix:match('%.(...)$') or 'mp4'
end
function Ard.iter_formats(page)
local r = {}
local s = 'mediaCollection%.addMediaStream'
.. '%(0, (%d+), "(.-)", "(.-)", "%w+"%);'
Ard.test_availability(page)
for s_id, prefix, suffix in page:gmatch(s) do
local u = prefix .. suffix
u = u:match('^(.-)?') or u -- remove querystring
local t = {
container = Ard.container_from(suffix),
encoding = suffix:match('%.(h264)%.'),
quality = Ard.quality_from(suffix),
height = Ard.height_from(suffix),
stream_id = s_id, -- internally (by service) used stream ID
url = u
}
table.insert(r,t)
end
if #r == 0 then error('no media urls found') end
return r
end
-- vim: set ts=4 sw=4 sts=4 tw=72 expandtab:
|
-- libquvi-scripts
-- Copyright (C) 2013 Thomas Weißschuh
--
-- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>.
--
-- This library is free software; you can redistribute it and/or
-- modify it under the terms of the GNU Lesser General Public
-- License as published by the Free Software Foundation; either
-- version 2.1 of the License, or (at your option) any later version.
--
-- This library is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-- Lesser General Public License for more details.
--
-- You should have received a copy of the GNU Lesser General Public
-- License along with this library; if not, write to the Free Software
-- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
-- 02110-1301 USA
local Ard = {}
function ident(self)
package.path = self.script_dir .. '/?.lua'
local C = require 'quvi/const'
local U = require 'quvi/util'
local B = require 'quvi/bit'
local r = {}
r.domain = 'www%.ardmediathek%.de'
r.formats = 'default|best'
r.categories = B.bit_or(C.proto_http, C.proto_rtmp)
r.handles = U.handles(self.page_url, {r.domain},
nil, {"documentId=%d+$"})
return r
end
function query_formats(self)
local config = Ard.get_config(self)
local formats = Ard.iter_formats(config)
local t = {}
for _,v in pairs(formats) do
table.insert(t, Ard.to_s(v))
end
table.sort(t)
self.formats = table.concat(t, "|")
return self
end
function parse(self)
local config = Ard.get_config(self)
local Util = require 'quvi/util'
self.host_id = 'ard'
self.title = config:match(
'<meta property="og:title" content="([^"]*)'
):gsub(
'%s*%- %w-$', '' -- remove name of station
):gsub(
'%s*%(FSK.*', '' -- remove FSK nonsense
)
or error('no match: media title')
self.thumbnail_url = config:match(
'<meta property="og:image" content="([^"]*)'
) or ''
local formats = Ard.iter_formats(config)
local format = Util.choose_format(self,
formats,
Ard.choose_best,
Ard.choose_default,
Ard.to_s)
or error('unable to choose format')
if not format.url then error('no match: media url') end
self.url = { format.url }
return self
end
function Ard.test_availability(page)
-- some videos are only scrapable at certain times
local fsk_pattern =
'Der Clip ist deshalb nur von (%d%d?) bis (%d%d?) Uhr verfügbar'
local from, to = page:match(fsk_pattern)
if from and to then
error('video only available from ' ..from.. ':00 to '
..to.. ':00 CET')
end
end
function Ard.get_config(self)
local c = quvi.fetch(self.page_url)
self.id = self.page_url:match('documentId=(%d*)')
or error('no match: media id')
if c:match('<title>ARD Mediathek %- Fehlerseite</title>') then
error('invalid URL, maybe the media is no longer available')
end
return c
end
function Ard.choose_best(t)
return t[#t] -- return the last from the array
end
function Ard.choose_default(t)
return t[1] -- return the first from the array
end
function Ard.to_s(t)
return string.format("%s_%s_i%02d%s%s",
(t.quality) and t.quality or 'sd',
t.container, t.stream_id,
(t.encoding) and '_'..t.encoding or '',
(t.height) and '_'..t.height or '')
end
function Ard.quality_from(suffix)
local q = suffix:match('%.web(%w)%.') or suffix:match('%.(%w)%.')
or suffix:match('[=%.]Web%-(%w)') -- .webs. or Web-S or .s
if q then
q = q:lower()
local t = {s='ld', m='md', l='sd', xl='hd'}
for k,v in pairs(t) do
if q == k then return v end
end
end
return q
end
function Ard.height_from(suffix)
local h = suffix:match('_%d+x(%d+)[_%.]')
if h then return h..'p' end
end
function Ard.container_from(suffix)
return suffix:match('^(...):') or suffix:match('%.(...)$') or 'mp4'
end
function Ard.iter_formats(page)
local r = {}
local s = 'mediaCollection%.addMediaStream'
.. '%(0, (%d+), "(.-)", "(.-)", "%w+"%);'
Ard.test_availability(page)
for s_id, prefix, suffix in page:gmatch(s) do
local u = prefix .. suffix
u = u:match('^(.-)?') or u -- remove querystring
local t = {
container = Ard.container_from(suffix),
encoding = suffix:match('%.(h264)%.'),
quality = Ard.quality_from(suffix),
height = Ard.height_from(suffix),
stream_id = s_id, -- internally (by service) used stream ID
url = u
}
table.insert(r,t)
end
if #r == 0 then error('no media urls found') end
return r
end
-- vim: set ts=4 sw=4 sts=4 tw=72 expandtab:
|
FIX: ard.lua: Assign self.script_dir to package.path
|
FIX: ard.lua: Assign self.script_dir to package.path
Assign the value of the self.script_dir to the package.path so that
the 'quvi/*' modules can be found.
Reported-by: Fabian Homborg <82fdcde710576c960b66532fc81d0508995ec635@gmail.com>
Signed-off-by: Toni Gundogdu <eac2284b3c43676907b96f08de9d3d52d5df0361@gmail.com>
|
Lua
|
agpl-3.0
|
alech/libquvi-scripts,legatvs/libquvi-scripts,alech/libquvi-scripts,legatvs/libquvi-scripts
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.