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
43955b443e01013802373d482411bffeb916df6e
src/lua/tester.lua
src/lua/tester.lua
-- tester.lua -- Test switch operation by post-processing trace files. -- Copright 2012 Snabb GmbH module("tester",package.seeall) local ffi = require("ffi") local pcap = require("pcap") local C = ffi.C if #arg ~= 1 then print "Usage: tester <pcapfile>" print "" print "Test that the switching behaviour in pcapfile is correct." return end local file = io.open(arg[1], "r") local pcap_file = ffi.new("struct pcap_file") local pcap_record = ffi.new("struct pcap_record") local pcap_extra = ffi.new("struct pcap_record_extra") function main () local input, outputs = nil, {} for packet, header, extra in pcap.records(arg[1]) do if extra.flags == 0 then if input ~= nil then check(input, outputs) end input = {port = extra.port_id, packet = packet} outputs = {} else table.insert(outputs, {port = extra.port_id, packet = packet}) end -- print(#packet, header, extra, extra.port_id, extra.flags) end end local tests = 0 local failed = 0 function check (input, outputs) check_loop(input, outputs) check_drop(input, outputs) check_forward(input, outputs) check_flood(input, outputs) tests = tests + 1 end function check_loop (input, outputs) for _,output in ipairs(outputs) do if input.port == output.port then fail(input, outputs, "loop failed on port " .. input.port) end end end function check_drop (input, outputs) if #outputs == 0 then fail(input, outputs, "drop failed on packet from " .. input.port) end end local fdb = {} function check_forward (input, outputs) local src = string.sub(input.packet, 1, 6) local dst = string.sub(input.packet, 7, 12) if fdb[dst] then local found = false for _,output in ipairs(outputs) do if output.port == fdb[dst] then found = true break end end if found == false then fail(input, outputs, "forward failed, expected to " .. fdb[dst]) end end fdb[src] = input.port end local ports = {} function check_flood (input, outputs) -- Learn ports if ports[input.port] == nil then ports[input.port] = true -- Remember port ports[#ports+1] = port -- Make #ports match number of ports seen end local multicast = string.byte(input.packet, 7) < 0x80 if multicast and #outputs < #ports - 1 then fail(input, outputs, "flood failed: not sent to enough ports") end end function fail (input, outputs, reason) print(reason) failed = failed + 1 end main() if failed == 0 then print("Success! " .. tests .. " test(s) passed.") else print("Failed! " .. failed .. "/" .. tests .. " tests failed.") os.exit(1) end
-- tester.lua -- Test switch operation by post-processing trace files. -- Copright 2012 Snabb GmbH module("tester",package.seeall) local ffi = require("ffi") local pcap = require("pcap") local C = ffi.C if #arg ~= 1 then print "Usage: tester <pcapfile>" print "" print "Test that the switching behaviour in pcapfile is correct." return end local file = io.open(arg[1], "r") local pcap_file = ffi.new("struct pcap_file") local pcap_record = ffi.new("struct pcap_record") local pcap_extra = ffi.new("struct pcap_record_extra") function main () local input, outputs = nil, {} for packet, header, extra in pcap.records(arg[1]) do if extra.flags == 0 then if input ~= nil then check(input, outputs) end input = {port = extra.port_id, packet = packet} outputs = {} else table.insert(outputs, {port = extra.port_id, packet = packet}) end -- print(#packet, header, extra, extra.port_id, extra.flags) end end local tests = 0 local failed = 0 function check (input, outputs) check_loop(input, outputs) check_drop(input, outputs) check_forward(input, outputs) check_flood(input, outputs) tests = tests + 1 end function check_loop (input, outputs) for _,output in ipairs(outputs) do if input.port == output.port then fail(input, outputs, "loop failed on port " .. input.port) end end end function check_drop (input, outputs) if #outputs == 0 then fail(input, outputs, "drop failed on packet from " .. input.port) end end local fdb = {} function check_forward (input, outputs) local src = string.sub(input.packet, 1, 6) local dst = string.sub(input.packet, 7, 12) if fdb[dst] then local found = false for _,output in ipairs(outputs) do if output.port == fdb[dst] then found = true break end end if found == false then fail(input, outputs, "forward failed, expected to " .. fdb[dst]) end end fdb[src] = input.port end local ports = {} local portcount = 0 function check_flood (input, outputs) -- Learn ports if ports[input.port] == nil then ports[input.port] = true portcount = portcount + 1 end local multicast = string.byte(input.packet, 7) >= 0x80 if multicast and #outputs < portcount - 1 then fail(input, outputs, "flood failed: not sent to enough ports") end end function fail (input, outputs, reason) print(reason) failed = failed + 1 end main() if failed == 0 then print("Success! " .. tests .. " test(s) passed.") else print("Failed! " .. failed .. "/" .. tests .. " tests failed.") os.exit(1) end
tester.lua: Fixed bug in multicast flood test.
tester.lua: Fixed bug in multicast flood test.
Lua
apache-2.0
wingo/snabbswitch,snabbco/snabb,aperezdc/snabbswitch,andywingo/snabbswitch,snabbco/snabb,justincormack/snabbswitch,andywingo/snabbswitch,kellabyte/snabbswitch,eugeneia/snabb,aperezdc/snabbswitch,xdel/snabbswitch,dpino/snabbswitch,wingo/snabb,eugeneia/snabb,lukego/snabb,wingo/snabb,wingo/snabb,pavel-odintsov/snabbswitch,justincormack/snabbswitch,javierguerragiraldez/snabbswitch,wingo/snabb,eugeneia/snabbswitch,kbara/snabb,eugeneia/snabbswitch,justincormack/snabbswitch,kbara/snabb,Igalia/snabb,heryii/snabb,justincormack/snabbswitch,Igalia/snabbswitch,pirate/snabbswitch,wingo/snabb,andywingo/snabbswitch,xdel/snabbswitch,kbara/snabb,SnabbCo/snabbswitch,heryii/snabb,mixflowtech/logsensor,Igalia/snabb,heryii/snabb,fhanik/snabbswitch,eugeneia/snabbswitch,dpino/snabbswitch,wingo/snabbswitch,pavel-odintsov/snabbswitch,SnabbCo/snabbswitch,dwdm/snabbswitch,eugeneia/snabb,lukego/snabbswitch,Igalia/snabb,kellabyte/snabbswitch,eugeneia/snabb,kellabyte/snabbswitch,lukego/snabb,pavel-odintsov/snabbswitch,kbara/snabb,mixflowtech/logsensor,alexandergall/snabbswitch,Igalia/snabbswitch,hb9cwp/snabbswitch,snabbco/snabb,wingo/snabbswitch,Igalia/snabb,alexandergall/snabbswitch,Igalia/snabb,plajjan/snabbswitch,xdel/snabbswitch,lukego/snabb,dpino/snabbswitch,javierguerragiraldez/snabbswitch,lukego/snabb,heryii/snabb,plajjan/snabbswitch,snabbco/snabb,wingo/snabbswitch,dpino/snabbswitch,heryii/snabb,eugeneia/snabb,mixflowtech/logsensor,dpino/snabb,eugeneia/snabb,snabbco/snabb,alexandergall/snabbswitch,fhanik/snabbswitch,snabbnfv-goodies/snabbswitch,javierguerragiraldez/snabbswitch,hb9cwp/snabbswitch,SnabbCo/snabbswitch,snabbnfv-goodies/snabbswitch,Igalia/snabbswitch,dpino/snabb,Igalia/snabbswitch,andywingo/snabbswitch,plajjan/snabbswitch,snabbnfv-goodies/snabbswitch,dwdm/snabbswitch,dpino/snabb,lukego/snabbswitch,virtualopensystems/snabbswitch,hb9cwp/snabbswitch,snabbco/snabb,pirate/snabbswitch,dpino/snabb,hb9cwp/snabbswitch,pirate/snabbswitch,lukego/snabbswitch,SnabbCo/snabbswitch,Igalia/snabb,mixflowtech/logsensor,lukego/snabbswitch,snabbco/snabb,alexandergall/snabbswitch,alexandergall/snabbswitch,aperezdc/snabbswitch,snabbnfv-goodies/snabbswitch,virtualopensystems/snabbswitch,dpino/snabb,eugeneia/snabbswitch,alexandergall/snabbswitch,aperezdc/snabbswitch,Igalia/snabb,dpino/snabb,alexandergall/snabbswitch,kbara/snabb,plajjan/snabbswitch,eugeneia/snabb,Igalia/snabbswitch,Igalia/snabb,heryii/snabb,virtualopensystems/snabbswitch,wingo/snabb,fhanik/snabbswitch,alexandergall/snabbswitch,mixflowtech/logsensor,dwdm/snabbswitch,eugeneia/snabb,kbara/snabb,snabbco/snabb,dpino/snabb
88e72c77015e0d5e218e8e181d642e0b24dadeb5
tests/sample/shellcode-attack.lua
tests/sample/shellcode-attack.lua
require("ipv4") require("tcp") local bindshell = "\xeb\x1f\x5e\x89\x76\x08\x31\xc0\x88\x46\x07\x89\x46\x0c\xb0\x0b" .. "\x89\xf3\x8d\x4e\x08\x8d\x56\x0c\xcd\x80\x31\xdb\x89\xd8\x40\xcd" .. "\x80\xe8\xdc\xff\xff\xff/bin/sh" haka.rule { hooks = { "tcp-up" }, eval = function (self, pkt) if #pkt.payload > 0 then -- reconstruct payload payload = '' for i = 1, #pkt.payload do payload = payload .. string.format("%c", pkt.payload[i]) end -- test if shellcode is present in data if string.find(payload, bindshell) then haka.log("filter", "/bin/sh shellcode detected !!!") tcp:drop() end end end }
require("ipv4") require("tcp") local bindshell = "\xeb\x1f\x5e\x89\x76\x08\x31\xc0\x88\x46\x07\x89\x46\x0c\xb0\x0b" .. "\x89\xf3\x8d\x4e\x08\x8d\x56\x0c\xcd\x80\x31\xdb\x89\xd8\x40\xcd" .. "\x80\xe8\xdc\xff\xff\xff/bin/sh" haka.rule { hooks = { "tcp-up" }, eval = function (self, pkt) if #pkt.payload > 0 then -- reconstruct payload payload = '' for i = 1, #pkt.payload do payload = payload .. string.format("%c", pkt.payload[i]) end -- test if shellcode is present in data if string.find(payload, bindshell) then haka.log("filter", "/bin/sh shellcode detected !!!") pkt:drop() end end end }
Fix shellcode rule
Fix shellcode rule
Lua
mpl-2.0
nabilbendafi/haka,nabilbendafi/haka,haka-security/haka,LubyRuffy/haka,haka-security/haka,haka-security/haka,LubyRuffy/haka,Wingless-Archangel/haka,nabilbendafi/haka,lcheylus/haka,lcheylus/haka,Wingless-Archangel/haka,lcheylus/haka
137b1d68d842305870c4045bb2791d18142e1aef
modules/textadept/command_entry.lua
modules/textadept/command_entry.lua
-- Copyright 2007-2014 Mitchell mitchell.att.foicica.com. See LICENSE. -- Abbreviated environment and commands from Jay Gould. local M = ui.command_entry --[[ This comment is for LuaDoc. --- -- Textadept's Command Entry. -- -- ## Modes -- -- The command entry supports multiple [modes](#keys.Modes) that have their own -- sets of key bindings stored in a separate table in `_G.keys` under a mode -- prefix key. Mode names are arbitrary, but cannot conflict with lexer names or -- key sequence strings (e.g. `'lua'` or `'send'`) due to the method Textadept -- uses for looking up key bindings. An example mode is "lua_command" mode for -- executing Lua commands: -- -- local function complete_lua() ... end -- local function execute_lua() ... end -- keys['ce'] = {ui.command_entry.enter_mode, 'lua_command'} -- keys.lua_command = setmetatable({ -- ['\t'] = complete_lua, -- ['\n'] = {ui.command_entry.finish_mode, execute_lua} -- }, ui.command_entry.editing_keys) -- -- In this case, `Ctrl+E` opens the command entry and enters "lua_command" key -- mode where the `Tab` and `Enter` keys have special, defined functionality. -- (By default, Textadept pre-defines `Esc` to exit any command entry mode.) -- `Tab` shows a list of Lua completions for the entry text and `Enter` exits -- "lua_command" key mode and executes the entered code. The command entry -- handles all other editing and movement keys normally. -- @field height (number) -- The height in pixels of the command entry. module('ui.command_entry')]] --- -- A metatable with typical platform-specific key bindings for text entries. -- This metatable may be used to add basic editing keys to command entry modes. -- @usage setmetatable(keys.my_mode, ui.command_entry.editing_keys) -- @class table -- @name editing_keys M.editing_keys = {__index = { [not OSX and 'cx' or 'mx'] = {buffer.cut, M}, [not OSX and 'cc' or 'mc'] = {buffer.copy, M}, [not OSX and 'cv' or 'mv'] = {buffer.paste, M}, [not OSX and not CURSES and 'ca' or 'ma'] = {buffer.select_all, M}, [not OSX and 'cz' or 'mz'] = {buffer.undo, M}, [not OSX and 'cZ' or 'mZ'] = {buffer.redo, M}, cy = {buffer.redo, M}, -- Movement keys. [(OSX or CURSES) and 'cf' or '\0'] = {buffer.char_right, M}, [(OSX or CURSES) and 'cb' or '\0'] = {buffer.char_left, M}, [(OSX or CURSES) and 'ca' or '\0'] = {buffer.vc_home, M}, [(OSX or CURSES) and 'ce' or '\0'] = {buffer.line_end, M}, [(OSX or CURSES) and 'cd' or '\0'] = {buffer.clear, M} }} --- -- Opens the command entry in key mode *mode*. -- Key bindings will be looked up in `keys[mode]` instead of `keys`. The `Esc` -- key exits the current mode, closes the command entry, and restores normal key -- lookup. -- This function is useful for binding keys to enter a command entry mode. -- @param mode The key mode to enter into, or `nil` to exit the current mode. -- @usage keys['ce'] = {ui.command_entry.enter_mode, 'command_entry'} -- @see _G.keys.MODE -- @name enter_mode function M.enter_mode(mode) keys.MODE = mode if mode and not keys[mode]['esc'] then keys[mode]['esc'] = M.enter_mode end M:select_all() M.focus() end --- -- Exits the current key mode, closes the command entry, and calls function *f* -- (if given) with the command entry's text as an argument. -- This is useful for binding keys to exit a command entry mode and perform an -- action with the entered text. -- @param f Optional function to call. It should accept the command entry text -- as an argument. -- @usage keys['\n'] = {ui.command_entry.finish_mode, ui.print} -- @name finish_mode function M.finish_mode(f) if M:auto_c_active() then return false end -- allow Enter to autocomplete M.enter_mode(nil) if f then f(M:get_text()) end end -- Environment for abbreviated Lua commands. -- @class table -- @name env local env = setmetatable({}, { __index = function(t, k) local f = buffer[k] if f and type(f) == 'function' then f = function(...) buffer[k](buffer, ...) end elseif f == nil then f = view[k] or ui[k] or _G[k] end return f end, __newindex = function(t, k, v) for _, t2 in ipairs{buffer, view, ui} do if t2[k] ~= nil then t2[k] = v return end end rawset(t, k, v) end, }) -- Executes string *code* as Lua code that is subject to an "abbreviated" -- environment. -- In this environment, the contents of the `buffer`, `view`, and `ui` tables -- are also considered as global functions and fields. -- Prints the results of '=' expressions like in the Lua prompt. -- @param code The Lua code to execute. local function execute_lua(code) if code:find('^=') then code = 'return '..code:sub(2) end local result = assert(load(code, nil, 'bt', env))() if result ~= nil or code:find('^return ') then ui.print(result) end events.emit(events.UPDATE_UI) end args.register('-e', '--execute', 1, execute_lua, 'Execute Lua code') -- Shows a set of Lua code completions for string *code* or the entry's text. -- Completions are subject to an "abbreviated" environment where the `buffer`, -- `view`, and `ui` tables are also considered as globals. -- @param code The Lua code to complete. The default value is the entry's text. local function complete_lua(code) if not code then code = M:get_text() end local symbol, op, part = code:match('([%w_.]-)([%.:]?)([%w_]*)$') local ok, result = pcall((load('return ('..symbol..')', nil, 'bt', env))) local cmpls = {} part = '^'..part if (not ok or type(result) ~= 'table') and symbol ~= '' then return end if not ok then -- shorthand notation local pool = { buffer, view, ui, _G, _SCINTILLA.functions, _SCINTILLA.properties } for i = 1, #pool do for k in pairs(pool[i]) do if type(k) == 'string' and k:find(part) then cmpls[#cmpls + 1] = k end end end else for k in pairs(result) do if type(k) == 'string' and k:find(part) then cmpls[#cmpls + 1] = k end end if symbol == 'buffer' and op == ':' then for f in pairs(_SCINTILLA.functions) do if f:find(part) then cmpls[#cmpls + 1] = f end end elseif symbol == 'buffer' and op == '.' then for p in pairs(_SCINTILLA.properties) do if p:find(part) then cmpls[#cmpls + 1] = p end end end end table.sort(cmpls) M:auto_c_show(#part - 1, table.concat(cmpls, ' ')) end -- Define key mode for entering Lua commands. keys.lua_command = setmetatable({ ['\t'] = complete_lua, ['\n'] = {M.finish_mode, execute_lua}, }, M.editing_keys) -- Configure the command entry's default properties. events.connect(events.INITIALIZED, function() if not arg then return end -- no need to reconfigure on reset M.h_scroll_bar, M.v_scroll_bar = false, false M.margin_width_n[0], M.margin_width_n[1], M.margin_width_n[2] = 0, 0, 0 if not CURSES then M.height = M:text_height(1) end M:set_lexer('lua') end) --[[ The function below is a Lua C function. --- -- Opens the Lua command entry. -- @class function -- @name focus local focus ]]
-- Copyright 2007-2014 Mitchell mitchell.att.foicica.com. See LICENSE. -- Abbreviated environment and commands from Jay Gould. local M = ui.command_entry --[[ This comment is for LuaDoc. --- -- Textadept's Command Entry. -- -- ## Modes -- -- The command entry supports multiple [modes](#keys.Modes) that have their own -- sets of key bindings stored in a separate table in `_G.keys` under a mode -- prefix key. Mode names are arbitrary, but cannot conflict with lexer names or -- key sequence strings (e.g. `'lua'` or `'send'`) due to the method Textadept -- uses for looking up key bindings. An example mode is "lua_command" mode for -- executing Lua commands: -- -- local function complete_lua() ... end -- local function execute_lua() ... end -- keys['ce'] = {ui.command_entry.enter_mode, 'lua_command'} -- keys.lua_command = setmetatable({ -- ['\t'] = complete_lua, -- ['\n'] = {ui.command_entry.finish_mode, execute_lua} -- }, ui.command_entry.editing_keys) -- -- In this case, `Ctrl+E` opens the command entry and enters "lua_command" key -- mode where the `Tab` and `Enter` keys have special, defined functionality. -- (By default, Textadept pre-defines `Esc` to exit any command entry mode.) -- `Tab` shows a list of Lua completions for the entry text and `Enter` exits -- "lua_command" key mode and executes the entered code. The command entry -- handles all other editing and movement keys normally. -- @field height (number) -- The height in pixels of the command entry. module('ui.command_entry')]] --- -- A metatable with typical platform-specific key bindings for text entries. -- This metatable may be used to add basic editing keys to command entry modes. -- @usage setmetatable(keys.my_mode, ui.command_entry.editing_keys) -- @class table -- @name editing_keys M.editing_keys = {__index = { [not OSX and 'cx' or 'mx'] = {buffer.cut, M}, [not OSX and 'cc' or 'mc'] = {buffer.copy, M}, [not OSX and 'cv' or 'mv'] = {buffer.paste, M}, [not OSX and not CURSES and 'ca' or 'ma'] = {buffer.select_all, M}, [not OSX and 'cz' or 'mz'] = {buffer.undo, M}, [not OSX and 'cZ' or 'mZ'] = {buffer.redo, M}, cy = {buffer.redo, M}, -- Movement keys. [(OSX or CURSES) and 'cf' or '\0'] = {buffer.char_right, M}, [(OSX or CURSES) and 'cb' or '\0'] = {buffer.char_left, M}, [(OSX or CURSES) and 'ca' or '\0'] = {buffer.vc_home, M}, [(OSX or CURSES) and 'ce' or '\0'] = {buffer.line_end, M}, [(OSX or CURSES) and 'cd' or '\0'] = {buffer.clear, M} }} --- -- Opens the command entry in key mode *mode*. -- Key bindings will be looked up in `keys[mode]` instead of `keys`. The `Esc` -- key exits the current mode, closes the command entry, and restores normal key -- lookup. -- This function is useful for binding keys to enter a command entry mode. -- @param mode The key mode to enter into, or `nil` to exit the current mode. -- @usage keys['ce'] = {ui.command_entry.enter_mode, 'command_entry'} -- @see _G.keys.MODE -- @name enter_mode function M.enter_mode(mode) if M:auto_c_active() then M:auto_c_cancel() end -- may happen in curses keys.MODE = mode if mode and not keys[mode]['esc'] then keys[mode]['esc'] = M.enter_mode end M:select_all() M.focus() end --- -- Exits the current key mode, closes the command entry, and calls function *f* -- (if given) with the command entry's text as an argument. -- This is useful for binding keys to exit a command entry mode and perform an -- action with the entered text. -- @param f Optional function to call. It should accept the command entry text -- as an argument. -- @usage keys['\n'] = {ui.command_entry.finish_mode, ui.print} -- @name finish_mode function M.finish_mode(f) if M:auto_c_active() then return false end -- allow Enter to autocomplete M.enter_mode(nil) if f then f(M:get_text()) end end -- Environment for abbreviated Lua commands. -- @class table -- @name env local env = setmetatable({}, { __index = function(t, k) local f = buffer[k] if f and type(f) == 'function' then f = function(...) buffer[k](buffer, ...) end elseif f == nil then f = view[k] or ui[k] or _G[k] end return f end, __newindex = function(t, k, v) for _, t2 in ipairs{buffer, view, ui} do if t2[k] ~= nil then t2[k] = v return end end rawset(t, k, v) end, }) -- Executes string *code* as Lua code that is subject to an "abbreviated" -- environment. -- In this environment, the contents of the `buffer`, `view`, and `ui` tables -- are also considered as global functions and fields. -- Prints the results of '=' expressions like in the Lua prompt. -- @param code The Lua code to execute. local function execute_lua(code) if code:find('^=') then code = 'return '..code:sub(2) end local result = assert(load(code, nil, 'bt', env))() if result ~= nil or code:find('^return ') then ui.print(result) end events.emit(events.UPDATE_UI) end args.register('-e', '--execute', 1, execute_lua, 'Execute Lua code') -- Shows a set of Lua code completions for the entry's text, subject to an -- "abbreviated" environment where the `buffer`, `view`, and `ui` tables are -- also considered as globals. local function complete_lua() local symbol, op, part = M:get_text():match('([%w_.]-)([%.:]?)([%w_]*)$') local ok, result = pcall((load('return ('..symbol..')', nil, 'bt', env))) local cmpls = {} part = '^'..part if (not ok or type(result) ~= 'table') and symbol ~= '' then return end if not ok then -- shorthand notation local pool = { buffer, view, ui, _G, _SCINTILLA.functions, _SCINTILLA.properties } for i = 1, #pool do for k in pairs(pool[i]) do if type(k) == 'string' and k:find(part) then cmpls[#cmpls + 1] = k end end end else for k in pairs(result) do if type(k) == 'string' and k:find(part) then cmpls[#cmpls + 1] = k end end if symbol == 'buffer' and op == ':' then for f in pairs(_SCINTILLA.functions) do if f:find(part) then cmpls[#cmpls + 1] = f end end elseif symbol == 'buffer' and op == '.' then for p in pairs(_SCINTILLA.properties) do if p:find(part) then cmpls[#cmpls + 1] = p end end end end table.sort(cmpls) M:auto_c_show(#part - 1, table.concat(cmpls, ' ')) end -- Define key mode for entering Lua commands. keys.lua_command = setmetatable({ ['\t'] = complete_lua, ['\n'] = {M.finish_mode, execute_lua}, }, M.editing_keys) -- Configure the command entry's default properties. events.connect(events.INITIALIZED, function() if not arg then return end -- no need to reconfigure on reset M.h_scroll_bar, M.v_scroll_bar = false, false M.margin_width_n[0], M.margin_width_n[1], M.margin_width_n[2] = 0, 0, 0 if not CURSES then M.height = M:text_height(1) end M:set_lexer('lua') end) --[[ The function below is a Lua C function. --- -- Opens the Lua command entry. -- @class function -- @name focus local focus ]]
Fixed autocomplete bug in curses; modules/textadept/command_entry.lua
Fixed autocomplete bug in curses; modules/textadept/command_entry.lua
Lua
mit
jozadaquebatista/textadept,jozadaquebatista/textadept
00ff9e09904153f070a912c47ed1a89dfba79dcd
libs/tablesave.lua
libs/tablesave.lua
local function istr(ind) if type(ind) == 'string' then if ind:match('^[a-zA-Z_][a-zA-Z0-9_]*$') then return ind end return '["'..ind:gsub('"', '\\"')..'"]' end return '['..ind..']' end local function tdisplay(t, o, i) i = i or 0 o = o or {} local indent = o.indent or 2 local r = '' r = '{\n' for _i, _v in pairs(t) do local ty = type(_v) r = r .. (' '):rep((i + 1) * indent) .. istr(_i) .. ' = ' if ty == 'table' then r = r .. tdisplay(_v, o, i + 1) elseif ty == 'number' or ty == 'boolean' or ty == 'nil' then r = r .. tostring(_v) elseif ty == 'string' then r = r .. '"' .. _v:gsub('"', '\\"') .. '"' end r = r .. ',\n' end r = r..(' '):rep(i * indent)..'}' return r end local function tsave(t, f) local ts = tdisplay(t) local fd = io.open(f, 'w') if not fd then return nil, 'Error opening "'..f..'"' end fd:write(ts..'\n') fd:close() return true end local function tload(f) local fd = io.open(f, 'r') if not fd then return nil, 'Error opening "'..f..'"' end local ts = fd:read('*all') or '{}' fd:close() local func, syntax = load('return '..ts, 'table.load', 't', {}) if syntax then return nil, syntax end local status, t = pcall(func) if not status then return nil, t end return t end return { td = tdisplay, save = tsave, load = tload }
local function istr(ind) if type(ind) == 'string' then if ind:match('^[a-zA-Z_][a-zA-Z0-9_]*$') then return ind end return '["'..ind:gsub('"', '\\"'):gsub('\n', '\\n')..'"]' end return '['..ind..']' end local function tdisplay(t, o, i) i = i or 0 o = o or {} local indent = o.indent or 2 local r = '' r = '{\n' for _i, _v in pairs(t) do local ty = type(_v) r = r .. (' '):rep((i + 1) * indent) .. istr(_i) .. ' = ' if ty == 'table' then r = r .. tdisplay(_v, o, i + 1) elseif ty == 'number' or ty == 'boolean' or ty == 'nil' then r = r .. tostring(_v) elseif ty == 'string' then r = r .. '"' .. _v:gsub('"', '\\"'):gsub('\n', '\\n') .. '"' end r = r .. ',\n' end r = r..(' '):rep(i * indent)..'}' return r end local function tsave(t, f) local ts = tdisplay(t) local fd = io.open(f, 'w') if not fd then return nil, 'Error opening "'..f..'"' end fd:write(ts..'\n') fd:close() return true end local function tload(f) local fd = io.open(f, 'r') if not fd then return nil, 'Error opening "'..f..'"' end local ts = fd:read('*all') or '{}' fd:close() local func, syntax = load('return '..ts, 'table.load', 't', {}) if syntax then return nil, syntax end local status, t = pcall(func) if not status then return nil, t end return t end return { td = tdisplay, save = tsave, load = tload }
fixed tablesave.lua for multiline strings
fixed tablesave.lua for multiline strings
Lua
mit
LazyShpee/discord-egobot
77aa2d73e10f609d469edd9d327c6bbfd5617546
packages/verseindex.lua
packages/verseindex.lua
SILE.require("packages/url") SILE.scratch.tableofverses = {} local orig_href = SILE.Commands["href"] local writeTov = function (_) local contents = "return " .. std.string.pickle(SILE.scratch.tableofverses) local tovfile, err = io.open(SILE.masterFilename .. '.tov', "w") if not tovfile then return SU.error(err) end tovfile:write(contents) end local moveNodes = function (_) local node = SILE.scratch.info.thispage.tov if node then for i = 1, #node do node[i].pageno = SILE.formatCounter(SILE.scratch.counters.folio) SILE.scratch.tableofverses[#(SILE.scratch.tableofverses)+1] = node[i] end end end local init = function (self) self:loadPackage("infonode") self:loadPackage("leaders") local inpair = nil local repairbreak = function () end local defaultparskip = SILE.settings.get("typesetter.parfillskip") local continuepair = function (args) if not args then return end if inpair and (args.frame.id == "content") then repairbreak = function () SILE.call("break"); repairbreak = function () end end SILE.typesetter:pushState() SILE.call("tableofverses:book", { }, { inpair }) SILE.typesetter:popState() end end local pushBack = SILE.typesetter.pushBack SILE.typesetter.pushBack = function (_self) continuepair(_self) pushBack(_self) repairbreak() end local startpair = function (pair) SILE.call("makecolumns", { gutter = "4%pw" }) SILE.settings.set("typesetter.parfillskip", SILE.nodefactory.glue()) inpair = pair end local endpair = function (_) inpair = nil SILE.call("mergecolumns") SILE.settings.set("typesetter.parfillskip", defaultparskip) end SILE.registerCommand("href", function (options, content) SILE.call("markverse", options, content) return orig_href(options, content) end) SILE.registerCommand("tableofverses:book", function (_, content) SILE.call("requireSpace", { height = "4em" }) SILE.settings.set("typesetter.parfillskip", defaultparskip) SILE.call("hbox") SILE.call("skip", { height = "1ex" }) SILE.call("section", { numbering = false, skiptoc = true }, content) SILE.call("breakframevertical") startpair(content[1]) end) SILE.registerCommand("tableofverses:reference", function (options, content) if #options.pages < 1 then SU.warn("Verse in index doesn't have page marker") options.pages = { "0" } end SILE.process(content) SILE.call("noindent") SILE.call("font", { size = ".5em" }, function () SILE.call("dotfill") end) local first = true for _, pageno in pairs(options.pages) do if not first then SILE.typesetter:typeset(", ") end SILE.typesetter:typeset(pageno) first = false end SILE.call("par") end) SILE.registerCommand("markverse", function (options, content) SILE.typesetter:typeset("​") -- Protect hbox location from getting discarded SILE.call("info", { category = "tov", value = { label = options.title and { options.title } or content, osis = options.osis } }) end) SILE.registerCommand("tableofverses", function (_, _) SILE.call("chapter", { numbering = false, appendix = true }, { "Ayet Referans İndeksi" }) SILE.call("cabook:font:serif", { size = "0.95em" }) local origmethod = SILE.settings.get("linespacing.method") local origleader = SILE.settings.get("linespacing.fixed.baselinedistance") local origparskip = SILE.settings.get("document.parskip") SILE.settings.set("linespacing.method", "fixed") SILE.settings.set("linespacing.fixed.baselinedistance", SILE.length("1.1em")) SILE.settings.set("document.parskip", SILE.nodefactory.vglue({})) local refshash = {} local lastbook = nil local seq = 1 -- TODO: should this be ipairs()? for _, ref in pairs(CASILE.verses) do if not refshash[ref.osis] then refshash[ref.osis] = true if not(lastbook == ref.b) then if inpair then endpair(seq) end SILE.call("tableofverses:book", { }, { ref.b }) seq = 1 lastbook = inpair end local pages = {} local pageshash = {} local addr = ref.reformat:match(".* (.*)") local label = ref.reformat:gsub(" ", " "):gsub(" ", " ") if ref.b == "Mezmurlar" then label = label:gsub("Mezmurlar", "Mezmur") end for _, link in pairs(SILE.scratch.tableofverses) do if link.osis == ref.osis then local pageno = link.pageno if not pageshash[pageno] then pages[#pages+1] = pageno pageshash[pageno] = true end end end SILE.call("tableofverses:reference", { pages = pages, label = label }, { addr }) seq = seq + 1 end end if inpair then endpair(seq) end inpair = nil SILE.settings.set("linespacing.fixed.baselinedistance", origleader) SILE.settings.set("linespacing.method", origmethod) SILE.settings.set("document.parskip", origparskip) end) end return { exports = { writeTov = writeTov, moveTovNodes = moveNodes }, init = init }
SILE.require("packages/url") SILE.scratch.tableofverses = {} local orig_href = SILE.Commands["href"] local writeTov = function (_) local contents = "return " .. std.string.pickle(SILE.scratch.tableofverses) local tovfile, err = io.open(SILE.masterFilename .. '.tov', "w") if not tovfile then return SU.error(err) end tovfile:write(contents) end local moveNodes = function (_) local node = SILE.scratch.info.thispage.tov if node then for i = 1, #node do node[i].pageno = SILE.formatCounter(SILE.scratch.counters.folio) SILE.scratch.tableofverses[#(SILE.scratch.tableofverses)+1] = node[i] end end end local init = function (self) self:loadPackage("infonode") self:loadPackage("leaders") local inpair = nil local repairbreak = function () end local defaultparskip = SILE.settings.get("typesetter.parfillskip") local continuepair = function (args) if not args then return end if inpair and (args.frame.id == "content") then repairbreak = function () SILE.call("break"); repairbreak = function () end end SILE.typesetter:pushState() SILE.call("tableofverses:book", { }, { inpair }) SILE.typesetter:popState() end end local pushBack = SILE.typesetter.pushBack SILE.typesetter.pushBack = function (_self) continuepair(_self) pushBack(_self) repairbreak() end local startpair = function (pair) -- Temporarily disable columns pending upstream bugfix -- https://github.com/sile-typesetter/sile/issues/891 -- SILE.call("makecolumns", { gutter = "4%pw" }) SILE.settings.set("typesetter.parfillskip", SILE.nodefactory.glue()) inpair = pair end local endpair = function (_) inpair = nil SILE.call("mergecolumns") SILE.settings.set("typesetter.parfillskip", defaultparskip) end SILE.registerCommand("href", function (options, content) SILE.call("markverse", options, content) return orig_href(options, content) end) SILE.registerCommand("tableofverses:book", function (_, content) SILE.call("requireSpace", { height = "4em" }) SILE.settings.set("typesetter.parfillskip", defaultparskip) SILE.call("hbox") SILE.call("skip", { height = "1ex" }) SILE.call("section", { numbering = false, skiptoc = true }, content) SILE.call("breakframevertical") startpair(content[1]) end) SILE.registerCommand("tableofverses:reference", function (options, content) if #options.pages < 1 then SU.warn("Verse in index doesn't have page marker") options.pages = { "0" } end SILE.process(content) SILE.call("noindent") SILE.call("font", { size = ".5em" }, function () SILE.call("dotfill") end) local first = true for _, pageno in pairs(options.pages) do if not first then SILE.typesetter:typeset(", ") end SILE.typesetter:typeset(pageno) first = false end SILE.call("par") end) SILE.registerCommand("markverse", function (options, content) SILE.typesetter:typeset("​") -- Protect hbox location from getting discarded SILE.call("info", { category = "tov", value = { label = options.title and { options.title } or content, osis = options.osis } }) end) SILE.registerCommand("tableofverses", function (_, _) SILE.call("chapter", { numbering = false, appendix = true }, { "Ayet Referans İndeksi" }) SILE.call("cabook:font:serif", { size = "0.95em" }) local origmethod = SILE.settings.get("linespacing.method") local origleader = SILE.settings.get("linespacing.fixed.baselinedistance") local origparskip = SILE.settings.get("document.parskip") SILE.settings.set("linespacing.method", "fixed") SILE.settings.set("linespacing.fixed.baselinedistance", SILE.length("1.1em")) SILE.settings.set("document.parskip", SILE.nodefactory.vglue({})) local refshash = {} local lastbook = nil local seq = 1 -- TODO: should this be ipairs()? for _, ref in pairs(CASILE.verses) do if not refshash[ref.osis] then refshash[ref.osis] = true if not(lastbook == ref.b) then if inpair then endpair(seq) end SILE.call("tableofverses:book", { }, { ref.b }) seq = 1 lastbook = inpair end local pages = {} local pageshash = {} local addr = ref.reformat:match(".* (.*)") local label = ref.reformat:gsub(" ", " "):gsub(" ", " ") if ref.b == "Mezmurlar" then label = label:gsub("Mezmurlar", "Mezmur") end for _, link in pairs(SILE.scratch.tableofverses) do if link.osis == ref.osis then local pageno = link.pageno if not pageshash[pageno] then pages[#pages+1] = pageno pageshash[pageno] = true end end end SILE.call("tableofverses:reference", { pages = pages, label = label }, { addr }) seq = seq + 1 end end if inpair then endpair(seq) end inpair = nil SILE.settings.set("linespacing.fixed.baselinedistance", origleader) SILE.settings.set("linespacing.method", origmethod) SILE.settings.set("document.parskip", origparskip) end) end return { exports = { writeTov = writeTov, moveTovNodes = moveNodes }, init = init }
chore: Temporarily work around SILE bug
chore: Temporarily work around SILE bug
Lua
agpl-3.0
alerque/casile,alerque/casile,alerque/casile,alerque/casile,alerque/casile
3a0ce116cfb766c4377e2cf975773bb808fd2f32
testserver/item/grave.lua
testserver/item/grave.lua
-- Tree Script -- Envi require("base.common") require("content.grave") module("item.grave", package.seeall) -- UPDATE common SET com_script='item.grave' WHERE com_itemid IN (337, 519, 520, 521); GraveListGerman = { "PLACEHOLDER.", }; GraveListEnglish = { "PLACEHOLDER.", }; function LookAtItemIdent(User,Item) local test = "no value"; if (first==nil) then content.grave.InitGrave() first=1; end -- fetching local references local signTextDe = content.grave.signTextDe; local signTextEn = content.grave.signTextEn; local signCoo = content.grave.signCoo; local signItemId = content.grave.signItemId; local signPerception = content.grave.signPerception; found = false; UserPer = User:increaseAttrib("perception",0); tablePosition = Item.pos.x .. Item.pos.y .. Item.pos.z; if signCoo ~= nil then if (signCoo[tablePosition] ~= nil) then for i, signpos in pairs(signCoo[tablePosition]) do if (Item.pos == signpos) then if (UserPer >= signPerception[tablePosition][i]) then found = true; world:itemInform(User,Item,base.common.GetNLS(User,string.gsub(signTextDe[tablePosition][i],"currentChar",User.name),string.gsub(signTextEn[tablePosition][i],"currentChar",User.name))); test = signTextDe[tablePosition][i]; else found = true; world:itemInform(User,Item,base.common.GetNLS(User,"~Du erkennst, dass hier etwas ist, kannst es aber nicht entziffern, da du zu blind bist.~","~You recognise something, but you cannot read it, because you are too blind.~")); end end end end end --[[local outText = checkNoobiaSigns(User,Item.pos); if outText and not found then world:itemInform(User,Item,outText); found = true; end ]] if not found then world:itemInform(User,Item,world:getItemName(Item.id,User:getPlayerLanguage())); end --[[if not found then val = ((Item.pos.x + Item.pos.y + Item.pos.z) % table.getn(GraveListGerman))+1; world:itemInform( User, Item, base.common.GetNLS(User, GraveListGerman[val], GraveListEnglish[val]) ); end]]-- -- User:inform("in LookAtItem of base_wegweiser.lua"); --User:inform(test); end --[[ LookAtItemIdent identity of LookAtItem ]] LookAtItem = LookAtItemIdent;
-- Tree Script -- Envi require("base.common") require("content.grave") module("item.grave", package.seeall) -- UPDATE common SET com_script='item.grave' WHERE com_itemid IN (337, 519, 520, 521); GraveListGerman = { "PLACEHOLDER.", }; GraveListEnglish = { "PLACEHOLDER.", }; function LookAtItemIdent(User,Item) local test = "no value"; if (first==nil) then content.grave.InitGrave() first=1; end -- fetching local references local signTextDe = content.grave.signTextDe; local signTextEn = content.grave.signTextEn; local signCoo = content.grave.signCoo; local signItemId = content.grave.signItemId; local signPerception = content.grave.signPerception; found = false; UserPer = User:increaseAttrib("perception",0); tablePosition = Item.pos.x .. Item.pos.y .. Item.pos.z; if signCoo ~= nil then if (signCoo[tablePosition] ~= nil) then for i, signpos in pairs(signCoo[tablePosition]) do if (Item.pos == signpos) then if (UserPer >= signPerception[tablePosition][i]) then found = true; world:itemInform(User,Item,base.common.GetNLS(User,string.gsub(signTextDe[tablePosition][i],"currentChar",User.name),string.gsub(signTextEn[tablePosition][i],"currentChar",User.name))); test = signTextDe[tablePosition][i]; else found = true; world:itemInform(User,Item,base.common.GetNLS(User,"~Du erkennst, dass hier etwas ist, kannst es aber nicht entziffern, da du zu blind bist.~","~You recognise something, but you cannot read it, because you are too blind.~")); end end end end end --[[local outText = checkNoobiaSigns(User,Item.pos); if outText and not found then world:itemInform(User,Item,outText); found = true; end ]] if not found then world:itemInform(User,Item,base.lookat.GenerateLookAt(User, Item, base.lookat.NONE)); end --[[if not found then val = ((Item.pos.x + Item.pos.y + Item.pos.z) % table.getn(GraveListGerman))+1; world:itemInform( User, Item, base.common.GetNLS(User, GraveListGerman[val], GraveListEnglish[val]) ); end]]-- -- User:inform("in LookAtItem of base_wegweiser.lua"); --User:inform(test); end --[[ LookAtItemIdent identity of LookAtItem ]] LookAtItem = LookAtItemIdent;
fixed lookat
fixed lookat
Lua
agpl-3.0
LaFamiglia/Illarion-Content,Illarion-eV/Illarion-Content,vilarion/Illarion-Content,Baylamon/Illarion-Content,KayMD/Illarion-Content
f4be0fd1b0daa8680fd8215921a970c20dc11f32
Normalize.lua
Normalize.lua
local Normalize, parent = torch.class('nn.Normalize', 'nn.Module') function Normalize:__init(p,eps) parent.__init(self) assert(p,'p-norm not provided') assert(p > 0, p..'-norm not supported') self.p = p self.eps = eps or 1e-10 self._output = torch.Tensor() self._gradInput = torch.Tensor() end function Normalize:updateOutput(input) assert(input:dim() <= 2, 'only 1d layer supported') local input_size = input:size() if input:dim() == 1 then input = input:view(1,-1) end self._output:resizeAs(input) self.norm = self.norm or input.new() self.normp = self.normp or input.new() self.buffer = self.buffer or input.new() if self.p % 2 ~= 0 then self.buffer:abs(input):pow(self.p) else self.buffer:pow(input,self.p) end self.normp:sum(self.buffer,2):add(self.eps) self.norm:pow(self.normp,1/self.p) self._output:cdiv(input, self.norm:view(-1,1):expandAs(input)) self.output = self._output:view(input_size) return self.output end function Normalize:updateGradInput(input, gradOutput) assert(input:dim() <= 2, 'only 1d layer supported') assert(gradOutput:dim() <= 2, 'only 1d layer supported') local input_size = input:size() if input:dim() == 1 then input = input:view(1,-1) end local n = input:size(1) -- batch size local d = input:size(2) -- dimensionality of vectors -- compute diagonal term with gradOutput self._gradInput:resize(n,d,1) gradOutput = gradOutput:view(n,d,1) self._gradInput:cmul(self.normp:view(n,1,1):expand(n,d,1), gradOutput) -- compute cross term in two steps self.cross = self.cross or input.new() self.cross:resize(n,1,1) self.buffer:abs(input):pow(self.p-2):cmul(input) local b1 = self.buffer:view(n,d,1) local b2 = input:view(n,1,d) -- instead of having a huge temporary matrix (b1*b2), -- do the computations as b1*(b2*gradOutput). This avoids redundant -- computation and also a huge buffer of size n*d^2 self.cross:bmm(b2, gradOutput) self._gradInput:baddbmm(-1, b1, self.cross) -- reuse cross buffer for normalization self.cross:cmul(self.normp, self.norm) self._gradInput:cdiv(self.cross:view(n,1,1):expand(n,d,1)) self._gradInput = self._gradInput:view(n,d) self.gradInput = self._gradInput:view(input_size) return self.gradInput end function Normalize:__tostring__() local s -- different prints if the norm is integer if self.p % 1 == 0 then s = '%s(%d)' else s = '%s(%f)' end return string.format(s,torch.type(self),self.p) end
local Normalize, parent = torch.class('nn.Normalize', 'nn.Module') function Normalize:__init(p,eps) parent.__init(self) assert(p,'p-norm not provided') assert(p > 0, p..'-norm not supported') self.p = p self.eps = eps or 1e-10 end function Normalize:updateOutput(input) assert(input:dim() <= 2, 'only 1d layer supported') local is_batch = true if input:dim() == 1 then input = input:view(1,-1) is_batch = false end self.output:resizeAs(input) self.norm = self.norm or input.new() self.normp = self.normp or input.new() self.buffer = self.buffer or input.new() if self.p % 2 ~= 0 then self.buffer:abs(input):pow(self.p) else self.buffer:pow(input,self.p) end self.normp:sum(self.buffer,2):add(self.eps) self.norm:pow(self.normp,1/self.p) self.output:cdiv(input,self.norm:view(-1,1):expandAs(self.output)) if not is_batch then self.output = self.output[1] end return self.output end function Normalize:updateGradInput(input, gradOutput) assert(input:dim() <= 2, 'only 1d layer supported') assert(gradOutput:dim() <= 2, 'only 1d layer supported') local is_batch = true if input:dim() == 1 then input = input:view(1,-1) is_batch = false end local n = input:size(1) -- batch size local d = input:size(2) -- dimensionality of vectors -- compute diagonal term with gradOutput self.gradInput:resize(n,d,1) gradOutput = gradOutput:view(n,d,1) self.gradInput:cmul(self.normp:view(n,1,1):expand(n,d,1),gradOutput) -- compute cross term in two steps self.cross = self.cross or input.new() self.cross:resize(n,1,1) self.buffer:abs(input):pow(self.p-2):cmul(input) local b1 = self.buffer:view(n,d,1) local b2 = input:view(n,1,d) -- instead of having a huge temporary matrix (b1*b2), -- do the computations as b1*(b2*gradOutput). This avoids redundant -- computation and also a huge buffer of size n*d^2 self.cross:bmm(b2,gradOutput) self.gradInput:baddbmm(-1,b1, self.cross) -- reuse cross buffer for normalization self.cross:cmul(self.normp,self.norm) self.gradInput:cdiv(self.cross:view(n,1,1):expand(n,d,1)) self.gradInput = self.gradInput:view(n,d) if not is_batch then self.gradInput = self.gradInput[1] end return self.gradInput end function Normalize:__tostring__() local s -- different prints if the norm is integer if self.p % 1 == 0 then s = '%s(%d)' else s = '%s(%f)' end return string.format(s,torch.type(self),self.p) end
Revert "Fix modification of output in nn.Normalize"
Revert "Fix modification of output in nn.Normalize"
Lua
bsd-3-clause
jonathantompson/nn,jhjin/nn,apaszke/nn,xianjiec/nn,joeyhng/nn,clementfarabet/nn,nicholas-leonard/nn,Moodstocks/nn,andreaskoepf/nn,diz-vara/nn,sagarwaghmare69/nn,eulerreich/nn,caldweln/nn,eriche2016/nn,colesbury/nn,witgo/nn,rotmanmi/nn,kmul00/nn,lukasc-ch/nn,elbamos/nn,vgire/nn,mlosch/nn,PraveerSINGH/nn
ab63e24c61e614896df17e0fbb968ae9a29d5a7e
Resistance.lua
Resistance.lua
local Resistance = {}; -- Assume no exp dependence on the resistances; -- IF resistances are NOT constants, then the algorithm should be modified; the Setup function should be used -- for every case that the resistor network will be updated as the updating of the A/C matrix per spin change -- is not very straightforward. This is MUCH slower though as we will need to loop over the entire grid. -- We might want to create a new Setup function after the initial setup, as we already have the neighbours which -- need to be taken into account. Resistance.Resistances = { [-1] = 10^5;-- Semiconducting; [1] = 10^2; } Resistance.Resistances = { [-1] = 100;-- Semiconducting; [1] = 1; } -- Both; local rr= Resistance.Resistances; Resistance.Resistances[0] = 1/(1/rr[1]+1/rr[-1]); -- NOTE: Why are these parallel? -- Because in parallel the voltage is the same over both resistors - this makes sense. -- Calculate the resistance of a given network of resistors (actually a Lattice object) local Matrix = require 'Matrix' function Resistance:New() return setmetatable({A={}, C={}}, {__index=self}) end function Resistance:GetC(s1,s2) if s1 == s2 then return 1/(self.Resistances[s1]) else return 1/(self.Resistances[0]) end end -- Todo: Add an update mode wether or not we update C/A matrices -- This is to make it easier to add new methods like resistances which scale with temperature -- Or to implement something else like function Resistance:Update(Grain) -- Grain is flipped. Update neighbours. local Lattice=self.Lattice; local iSelf = Lattice.IndexFromGrain[Grain]; local A = self.A; for i,Grain2 in pairs(Grain.ResistanceNeighbours) do local iGrain = Lattice.IndexFromGrain[Grain2]; local C = self:GetC(Grain.Spin,Grain2.Spin) -- C[iSelf][iGrain] = C; -- C[iGrain][iSelf] = C; local C_OLD = -(A[iSelf][iGrain]); local Delta = C - C_OLD; A[iSelf][iGrain] = -C; A[iGrain][iSelf] = -C; A[iSelf][iSelf] = A[iSelf][iSelf] + Delta; A[iGrain][iGrain] = A[iGrain][iGrain] + Delta; end end function Resistance:Setup(Lattice) self.Lattice = Lattice; if not Lattice.IndexFromGrain then Lattice.IndexFromGrain = {}; for i,v in pairs(Lattice.Grains) do Lattice.IndexFromGrain[v] = i; end end local max_i = 0; for x=1,Lattice.x do for y=1,Lattice.y do for z=1,Lattice.z do -- NONPERIODIC local Neighbours = Lattice:GetNeighbours(x,y,z,true); local Grain1 = Lattice.Grid[x][y][z]; Grain1.ResistanceNeighbours = {}; local i1 = Grain1.Index print(i1) for _, Neighbour in pairs(Neighbours) do local Grain2 = Lattice.Grid[Neighbour[1]][Neighbour[2]][Neighbour[3]] table.insert(Grain1.ResistanceNeighbours, Grain2); local i2 = Grain2.Index local C = self:GetC(Grain1.Spin,Grain2.Spin); if not self.C[i1] then self.C[i1] = {} end; if not self.C[i2] then self.C[i2] = {} end; self.C[i1][i2] = C; self.C[i2][i1] = C; max_i = math.max(max_i, i1,i2) end end end end -- Make A local C = self.C; local A = self.A; for i = 1, max_i do for j = 1, max_i do local Cij = C[i][j]; if not A[i] then A[i] = {}; end if i ~= j then if Cij then A[i][j] = -Cij end else local sum = 0; for k = 1, max_i do sum = sum + (C[i][k] or 0) end A[i][j] = sum; print(i,j,sum) end end end end -- Per det formula function Resistance:GetResistance(Grain1_Index,Grain2_Index) local Out1 = Matrix:Det(self.A, {[Grain1_Index]=true; [Grain2_Index]=true}); local Out2 = Matrix:Det(self.A, {[Grain1_Index]=true}); return Out1/Out2; end --[[function Resistance:GetResistance(Lattice, Grain1, Grain2); -- Create a LUT if not there. if not Lattice.IndexFromGrain then Lattice.IndexFromGrain = {}; for i,v in pairs(Lattice.Grains) do Lattice.IndexFromGrain[v] = i; end end local C = Matrix:New(); for Index1, Grain in pairs(Lattice.Grains) do; local State1 = Grain.Spin; for Index2, Neighbour in pairs(Grain.Neighbours) do local State2 = Neighbour.Spin; local C if State1 == State2 then C = 1/self.Resistances[State1] else C = 1/self.Resistances[0] end if not C[Index1] then C[Index1] = {}; end C[Index1][Index2] = C; if not C[Index2] then C[Index2] = {}; end C[Index2][Index1] = C; end end end --]] return Resistance
local Resistance = {}; -- Assume no exp dependence on the resistances; -- IF resistances are NOT constants, then the algorithm should be modified; the Setup function should be used -- for every case that the resistor network will be updated as the updating of the A/C matrix per spin change -- is not very straightforward. This is MUCH slower though as we will need to loop over the entire grid. -- We might want to create a new Setup function after the initial setup, as we already have the neighbours which -- need to be taken into account. Resistance.Resistances = { [-1] = 10^5;-- Semiconducting; [1] = 10^2; } Resistance.Resistances = { [-1] = 100;-- Semiconducting; [1] = 1; } -- Both; local rr= Resistance.Resistances; Resistance.Resistances[0] = 1/(1/rr[1]+1/rr[-1]); -- NOTE: Why are these parallel? -- Because in parallel the voltage is the same over both resistors - this makes sense. -- Calculate the resistance of a given network of resistors (actually a Lattice object) local Matrix = require 'Matrix' function Resistance:New() return setmetatable({A={}, C={}}, {__index=self}) end function Resistance:GetC(s1,s2) if s1 == s2 then return 1/(self.Resistances[s1]) else return 1/(self.Resistances[0]) end end -- Todo: Add an update mode wether or not we update C/A matrices -- This is to make it easier to add new methods like resistances which scale with temperature -- Or to implement something else like function Resistance:Update(Grain) -- Grain is flipped. Update neighbours. local Lattice=self.Lattice; local iSelf = Grain.Index; local A = self.A; for i,Grain2 in pairs(Grain.ResistanceNeighbours) do local iGrain = Grain2.Index; local C = self:GetC(Grain.Spin,Grain2.Spin) -- C[iSelf][iGrain] = C; -- C[iGrain][iSelf] = C; local C_OLD = -(A[iSelf][iGrain]); local Delta = C - C_OLD; A[iSelf][iGrain] = -C; A[iGrain][iSelf] = -C; A[iSelf][iSelf] = A[iSelf][iSelf] + Delta; A[iGrain][iGrain] = A[iGrain][iGrain] + Delta; end end function Resistance:Setup(Lattice) self.Lattice = Lattice; --[[if not Lattice.IndexFromGrain then Lattice.IndexFromGrain = {}; for i,v in pairs(Lattice.Grains) do Lattice.IndexFromGrain[v] = i; end end --]] local num_resistors = 0; local max_i = 0; for x=1,Lattice.x do for y=1,Lattice.y do for z=1,Lattice.z do -- NONPERIODIC local Neighbours = Lattice:GetNeighbours(x,y,z,true); local Grain1 = Lattice.Grid[x][y][z]; Grain1.ResistanceNeighbours = {}; local i1 = Grain1.Index for _, Neighbour in pairs(Neighbours) do local Grain2 = Lattice.Grid[Neighbour[1]][Neighbour[2]][Neighbour[3]] table.insert(Grain1.ResistanceNeighbours, Grain2); local i2 = Grain2.Index local C = self:GetC(Grain1.Spin,Grain2.Spin); if not self.C[i1] then self.C[i1] = {} end; if not self.C[i2] then self.C[i2] = {} end; self.C[i1][i2] = C; self.C[i2][i1] = C; max_i = math.max(max_i, i1,i2) end num_resistors = num_resistors + #Grain1.ResistanceNeighbours; end end end -- Make A local C = self.C; local A = self.A; for i = 1, max_i do for j = 1, max_i do local Cij = C[i][j]; if not A[i] then A[i] = {}; end if i ~= j then if Cij then A[i][j] = -Cij end else local sum = 0; for k = 1, max_i do sum = sum + (C[i][k] or 0) end A[i][j] = sum; end end end num_resistors = num_resistors/2; end -- Per det formula function Resistance:GetResistance(Grain1_Index,Grain2_Index) local Out1 = Matrix:Det(self.A, {[Grain1_Index]=true; [Grain2_Index]=true}); local Out2 = Matrix:Det(self.A, {[Grain1_Index]=true}); return Out1/Out2; end --[[function Resistance:GetResistance(Lattice, Grain1, Grain2); -- Create a LUT if not there. if not Lattice.IndexFromGrain then Lattice.IndexFromGrain = {}; for i,v in pairs(Lattice.Grains) do Lattice.IndexFromGrain[v] = i; end end local C = Matrix:New(); for Index1, Grain in pairs(Lattice.Grains) do; local State1 = Grain.Spin; for Index2, Neighbour in pairs(Grain.Neighbours) do local State2 = Neighbour.Spin; local C if State1 == State2 then C = 1/self.Resistances[State1] else C = 1/self.Resistances[0] end if not C[Index1] then C[Index1] = {}; end C[Index1][Index2] = C; if not C[Index2] then C[Index2] = {}; end C[Index2][Index1] = C; end end end --]] return Resistance
fixed IndexFroGrain
fixed IndexFroGrain
Lua
mit
jochem-brouwer/VO2_Model,jochem-brouwer/VO2_Model
00f17062969b6a0e1f31224158960fe4b09cd404
Standings.lua
Standings.lua
local T = AceLibrary("Tablet-2.0") local D = AceLibrary("Dewdrop-2.0") EPGP_Standings = EPGP:NewModule("EPGP_Standings", "AceDB-2.0") function EPGP_Standings:ShowStandings() if not T:IsRegistered("EPGP_Standings") then T:Register("EPGP_Standings", "children", function() T:SetTitle("EPGP Standings"); self:OnTooltipUpdate() end, "showTitleWhenDetached", true, "showHintWhenDetached", true, "cantAttach", true, "menu", function() D:AddLine( "text", "Close window", "tooltipTitle", "Close window", "tooltipText", "Closes the standings window.", "func", function() T:Attach("EPGP_Standings") end) end ) end if T:IsAttached("EPGP_Standings") then T:Detach("EPGP_Standings") else T:Refresh("EPGP_Standings") end end function EPGP_Standings:OnTooltipUpdate() local cat = T:AddCategory( "columns", 4, "text", "Name", "textR", 1, "textG", 1, "textB", 1, "justify", "LEFT", "text2", "EP", "textR", 1, "textG", 1, "textB", 1, "justify2", "RIGHT", "text3", "GP", "textR", 1, "textG", 1, "textB", 1, "justify3", "RIGHT", "text4", "PR", "textR", 1, "textG", 1, "textB", 1, "justify4", "RIGHT" ) local t = EPGP:BuildStandingsTable() for i = 1, table.getn(t) do cat:AddLine( "text", t[i][1], "text2", t[i][2], "text3", t[i][3], "text4", t[i][4]) end end
local T = AceLibrary("Tablet-2.0") local D = AceLibrary("Dewdrop-2.0") EPGP_Standings = EPGP:NewModule("EPGP_Standings") function EPGP_Standings:ShowStandings() if not T:IsRegistered("EPGP_Standings") then T:Register("EPGP_Standings", "children", function() T:SetTitle("EPGP Standings") T:SetHint("EP: Effort Points, GP: Gear Points, PR: Priority") self:OnTooltipUpdate() end, "showTitleWhenDetached", true, "showHintWhenDetached", true, "cantAttach", true, "menu", function() D:AddLine( "text", "Close window", "tooltipTitle", "Close window", "tooltipText", "Closes the standings window.", "func", function() T:Attach("EPGP_Standings"); D:Close() end) end ) end if T:IsAttached("EPGP_Standings") then T:Detach("EPGP_Standings") else T:Refresh("EPGP_Standings") end end function EPGP_Standings:OnTooltipUpdate() local cat = T:AddCategory( "columns", 4, "text", "Name", "textR", 1, "textG", 1, "textB", 1, "justify", "LEFT", "text2", "EP", "textR", 1, "textG", 1, "textB", 1, "justify2", "RIGHT", "text3", "GP", "textR", 1, "textG", 1, "textB", 1, "justify3", "RIGHT", "text4", "PR", "textR", 1, "textG", 1, "textB", 1, "justify4", "RIGHT" ) local t = EPGP:BuildStandingsTable() for i = 1, table.getn(t) do cat:AddLine( "text", t[i][1], "text2", t[i][2], "text3", t[i][3], "text4", t[i][4]) end end
Fix closing tooltip to not leave menu behind. Add hint about EP, GP, PR.
Fix closing tooltip to not leave menu behind. Add hint about EP, GP, PR.
Lua
bsd-3-clause
protomech/epgp-dkp-reloaded,sheldon/epgp,ceason/epgp-tfatf,protomech/epgp-dkp-reloaded,hayword/tfatf_epgp,sheldon/epgp,ceason/epgp-tfatf,hayword/tfatf_epgp
9f5aa6f7500ccbad9275519fa6f6bfe960240912
scripts/bricks_auto.lua
scripts/bricks_auto.lua
dofile("ui_utils.inc"); dofile("settings.inc"); dofile("constants.inc"); dofile("screen_reader_common.inc"); dofile("common.inc"); imgThisIs = "ThisIs.png"; imgTake = "Take.png"; imgEverything = "Everything.png"; imtToMake = "toMake.png"; brickNames = { "Bricks", "Clay Bricks", "Firebricks" }; brickImages = { "makeBricks.png", "makeClayBricks.png", "makeFirebricks.png" }; typeOfBrick = 1; arrangeWindows = true; unpinWindows = true; function doit() promptParameters(); askForWindow("Make sure your chats are minimized and brick rack menus are pinned then hover ATITD window and press Shift to continue."); if(arrangeWindows) then arrangeInGrid(); end while(true) do checkBreak(); makeBricks(); lsSleep(click_delay); end end function promptParameters() scale = 1.1; local z = 0; local is_done = nil; local value = nil; -- Edit box and text display while not is_done do -- Make sure we don't lock up with no easy way to escape! checkBreak(); local y = 5; lsSetCamera(0,0,lsScreenX*scale,lsScreenY*scale); typeOfBrick = readSetting("typeOfBrick",typeOfBrick); typeOfBrick = lsDropdown("typeOfBrick", 5, y, 0, 150, typeOfBrick, brickNames); writeSetting("typeOfBrick",typeOfBrick); y = y + 32; arrangeWindows = readSetting("arrangeWindows",arrangeWindows); arrangeWindows = lsCheckBox(10, y, z, 0xFFFFFFff, "Arrange windows", arrangeWindows); writeSetting("arrangeWindows",arrangeWindows); y = y + 32; unpinWindows = readSetting("unpinWindows",unpinWindows); unpinWindows = lsCheckBox(10, y, z, 0xFFFFFFff, "Unpin windows on exit", unpinWindows); writeSetting("unpinWindows",unpinWindows); y = y + 32; lsPrintWrapped(10, y, z+10, lsScreenX - 20, 0.7, 0.7, 0xD0D0D0ff, "Stand where you can reach all brick racks with all ingredients on you."); if lsButtonText(10, (lsScreenY - 30) * scale, z, 100, 0xFFFFFFff, "OK") then is_done = 1; end if lsButtonText((lsScreenX - 100) * scale, (lsScreenY - 30) * scale, z, 100, 0xFFFFFFff, "End script") then error "Clicked End Script button"; end lsDoFrame(); lsSleep(tick_delay); end if(unpinWindows) then setCleanupCallback(cleanup); end end function makeBricks() statusScreen("Making bricks"); checkBreak(); srReadScreen(); local posList; posList = findAllImages(imgThisIs); if #posList > 0 then for i=1,#posList do safeClick(posList[i][0], posList[i][1]); lsSleep(click_delay); checkBreak(); end end posList = findAllImages(brickImages[typeOfBrick]); if #posList > 0 then for i=1,#posList do safeClick(posList[i][0], posList[i][1]); lsSleep(click_delay); checkBreak(); srReadScreen(); local s = findAllImages(imtToMake); if(#s > 0) then cleanup(); error("Out of supplies."); end end end posList = findAllImages(imgTake); if #posList > 0 then for i=1,#posList do safeClick(posList[i][0], posList[i][1]); lsSleep(click_delay); checkBreak(); end end posList = findAllImages(imgEverything); if #posList > 0 then for i=1,#posList do safeClick(posList[i][0], posList[i][1]); lsSleep(click_delay); checkBreak(); end end end function cleanup() if(unpinWindows) then closeAllWindows(); end end
dofile("ui_utils.inc"); dofile("settings.inc"); dofile("constants.inc"); dofile("screen_reader_common.inc"); dofile("common.inc"); imgTake = "Take.png"; imgEverything = "Everything.png"; imgToMake = "toMake.png"; brickNames = { "Bricks", "Clay Bricks", "Firebricks" }; brickImages = { "makeBricks.png", "makeClayBricks.png", "makeFirebricks.png" }; typeOfBrick = 1; arrangeWindows = true; unpinWindows = true; function doit() promptParameters(); askForWindow("Make sure your chats are minimized and brick rack menus are pinned then hover ATITD window and press Shift to continue."); if(arrangeWindows) then arrangeInGrid(); end while(true) do checkBreak(); makeBricks(); lsSleep(click_delay); end end function promptParameters() scale = 1.1; local z = 0; local is_done = nil; local value = nil; -- Edit box and text display while not is_done do -- Make sure we don't lock up with no easy way to escape! checkBreak(); local y = 5; lsSetCamera(0,0,lsScreenX*scale,lsScreenY*scale); typeOfBrick = readSetting("typeOfBrick",typeOfBrick); typeOfBrick = lsDropdown("typeOfBrick", 5, y, 0, 150, typeOfBrick, brickNames); writeSetting("typeOfBrick",typeOfBrick); y = y + 32; arrangeWindows = readSetting("arrangeWindows",arrangeWindows); arrangeWindows = lsCheckBox(10, y, z, 0xFFFFFFff, "Arrange windows", arrangeWindows); writeSetting("arrangeWindows",arrangeWindows); y = y + 32; unpinWindows = readSetting("unpinWindows",unpinWindows); unpinWindows = lsCheckBox(10, y, z, 0xFFFFFFff, "Unpin windows on exit", unpinWindows); writeSetting("unpinWindows",unpinWindows); y = y + 32; lsPrintWrapped(10, y, z+10, lsScreenX - 20, 0.7, 0.7, 0xD0D0D0ff, "Stand where you can reach all brick racks with all ingredients on you."); if lsButtonText(10, (lsScreenY - 30) * scale, z, 100, 0xFFFFFFff, "OK") then is_done = 1; end if lsButtonText((lsScreenX - 100) * scale, (lsScreenY - 30) * scale, z, 100, 0xFFFFFFff, "End script") then error "Clicked End Script button"; end lsDoFrame(); lsSleep(tick_delay); end if(unpinWindows) then setCleanupCallback(cleanup); end end function makeBricks() -- Click pin ups to refresh the window clickAllImages("ThisIs.png"); statusScreen("Making bricks"); srReadScreen(); local ThisIsList; ThisIsList = findAllImages("ThisIs.png"); local i; for i=1,#ThisIsList do local x = ThisIsList[i][0]; local y = ThisIsList[i][1]; local width = 100; local height = 250; local util = srFindImageInRange("utility.png", x, y, width, height, 5000); if(util) then height = util[1] - y; local p = srFindImageInRange(brickImages[typeOfBrick], x, y, width, height); if(p) then safeClick(p[0]+4,p[1]+4); lsSleep(click_delay); srReadScreen(); else local s = findAllImages(imgToMake); if(#s > 0) then cleanup(); error("Out of supplies."); else p = srFindImageInRange("Take.png", x, y, width, height, 5000); if(p) then safeClick(p[0]+4,p[1]+4); lsSleep(click_delay); srReadScreen(); p = srFindImage("Everything.png", 5000); if(p) then safeClick(p[0]+4,p[1]+4); lsSleep(click_delay); srReadScreen(); end end end end end end end function cleanup() if(unpinWindows) then closeAllWindows(); end end
bricks_auto update
bricks_auto update Fixed the script so it no longer spam clicks clay bricks if the user has Masonary skill.
Lua
mit
DashingStrike/Automato-ATITD,DashingStrike/Automato-ATITD,wzydhek/Automato-ATITD,wzydhek/Automato-ATITD
e64bdf1dc4fe46aa93076260b84dfb0763956647
classes/cabook.lua
classes/cabook.lua
local book = require("classes/book") local plain = require("classes/plain") local cabook = pl.class(book) cabook._name = "cabook" function cabook:_init (options) book._init(self, options) self:loadPackage("color") self:loadPackage("ifattop") self:loadPackage("leaders") self:loadPackage("raiselower") self:loadPackage("rebox"); self:loadPackage("rules") self:loadPackage("image") self:loadPackage("date") self:loadPackage("textcase") self:loadPackage("frametricks") self:loadPackage("inputfilter") self:loadPackage("linespacing") if self.options.verseindex then self:loadPackage("verseindex") end self:loadPackage("imprint") self:loadPackage("covers") self:registerPostinit(function (_) -- CaSILE books sometimes have sections, sometimes don't. -- Initialize some sectioning levels to work either way SILE.scratch.counters["sectioning"] = { value = { 0, 0 }, display = { "ORDINAL", "STRING" } } require("hyphenation_exceptions") SILE.settings:set("typesetter.underfulltolerance", SILE.length("6ex")) SILE.settings:set("typesetter.overfulltolerance", SILE.length("0.2ex")) SILE.call("footnote:separator", {}, function () SILE.call("rebox", { width = "6em", height = "2ex" }, function () SILE.call("hrule", { width = "5em", height = "0.2pt" }) end) SILE.call("medskip") end) SILE.call("cabook:font:serif", { size = "11.5pt" }) SILE.settings:set("linespacing.method", "fit-font") SILE.settings:set("linespacing.fit-font.extra-space", SILE.length("0.6ex plus 0.2ex minus 0.2ex")) SILE.settings:set("linebreak.hyphenPenalty", 300) SILE.scratch.insertions.classes.footnote.interInsertionSkip = SILE.length("0.7ex plus 0 minus 0") SILE.scratch.last_was_ref = false SILE.typesetter:registerPageEndHook(function () SILE.scratch.last_was_ref = false end) end) end function cabook:declareSettings () book.declareSettings(self) -- require("classes.cabook-settings")() end function cabook:declareOptions () book.declareOptions(self) local binding, crop, background, verseindex, layout self:declareOption("binding", function (_, value) if value then binding = value end return binding end) self:declareOption("crop", function (_, value) if value then crop = SU.cast("boolean", value) end return crop end) self:declareOption("background", function (_, value) if value then background = SU.cast("boolean", value) end return background end) self:declareOption("verseindex", function (_, value) if value then verseindex = SU.cast("boolean", value) end return verseindex end) -- SU.error("ga cl 2.5") self:declareOption("layout", function (_, value) if value then layout = value self:registerPostinit(function (_) require("layouts."..layout)(self) end) end return layout end) end function cabook:setOptions (options) options.binding = options.binding or "print" -- print, paperback, hardcover, coil, stapled options.crop = options.crop or true options.background = options.background or true options.verseindex = options.verseindex or false options.layout = options.layout or "a4" book.setOptions(self, options) end function cabook:registerCommands () book.registerCommands(self) -- SILE's loadPackage assumes a "packages" path, this just side steps that naming requirement self:initPackage(require("classes.commands")) self:initPackage(require("classes.inline-styles")) self:initPackage(require("classes.block-styles")) end function cabook:endPage () self:moveTocNodes() if self.moveTovNodes then self:moveTovNodes() end if not SILE.scratch.headers.skipthispage then SILE.settings:pushState() SILE.settings:reset() if self:oddPage() then SILE.call("output-right-running-head") else SILE.call("output-left-running-head") end SILE.settings:popState() end SILE.scratch.headers.skipthispage = false local ret = plain.endPage(self) if self.options.crop then self:outputCropMarks() end return ret end function cabook:finish () if self.moveTovNodes then self:writeTov() SILE.call("tableofverses") end return book.finish(self) end return cabook
local book = require("classes/book") local plain = require("classes/plain") local cabook = pl.class(book) cabook._name = "cabook" function cabook:_init (options) book._init(self, options) self:loadPackage("color") self:loadPackage("ifattop") self:loadPackage("leaders") self:loadPackage("raiselower") self:loadPackage("rebox"); self:loadPackage("rules") self:loadPackage("image") self:loadPackage("date") self:loadPackage("textcase") self:loadPackage("frametricks") self:loadPackage("inputfilter") self:loadPackage("linespacing") if self.options.verseindex then self:loadPackage("verseindex") end self:loadPackage("imprint") self:loadPackage("covers") self:registerPostinit(function (_) -- CaSILE books sometimes have sections, sometimes don't. -- Initialize some sectioning levels to work either way SILE.scratch.counters["sectioning"] = { value = { 0, 0 }, display = { "ORDINAL", "STRING" } } require("hyphenation_exceptions") SILE.settings:set("typesetter.underfulltolerance", SILE.length("6ex")) SILE.settings:set("typesetter.overfulltolerance", SILE.length("0.2ex")) table.insert(SILE.input.preambles, function () SILE.call("footnote:separator", {}, function () SILE.call("rebox", { width = "6em", height = "2ex" }, function () SILE.call("hrule", { width = "5em", height = "0.2pt" }) end) SILE.call("medskip") end) SILE.call("cabook:font:serif", { size = "11.5pt" }) end) SILE.settings:set("linespacing.method", "fit-font") SILE.settings:set("linespacing.fit-font.extra-space", SILE.length("0.6ex plus 0.2ex minus 0.2ex")) SILE.settings:set("linebreak.hyphenPenalty", 300) SILE.scratch.insertions.classes.footnote.interInsertionSkip = SILE.length("0.7ex plus 0 minus 0") SILE.scratch.last_was_ref = false SILE.typesetter:registerPageEndHook(function () SILE.scratch.last_was_ref = false end) end) end function cabook:declareSettings () book.declareSettings(self) -- require("classes.cabook-settings")() end function cabook:declareOptions () book.declareOptions(self) local binding, crop, background, verseindex, layout self:declareOption("binding", function (_, value) if value then binding = value end return binding end) self:declareOption("crop", function (_, value) if value then crop = SU.cast("boolean", value) end return crop end) self:declareOption("background", function (_, value) if value then background = SU.cast("boolean", value) end return background end) self:declareOption("verseindex", function (_, value) if value then verseindex = SU.cast("boolean", value) end return verseindex end) -- SU.error("ga cl 2.5") self:declareOption("layout", function (_, value) if value then layout = value self:registerPostinit(function (_) require("layouts."..layout)(self) end) end return layout end) end function cabook:setOptions (options) options.binding = options.binding or "print" -- print, paperback, hardcover, coil, stapled options.crop = options.crop or true options.background = options.background or true options.verseindex = options.verseindex or false options.layout = options.layout or "a4" book.setOptions(self, options) end function cabook:registerCommands () book.registerCommands(self) -- SILE's loadPackage assumes a "packages" path, this just side steps that naming requirement self:initPackage(require("classes.commands")) self:initPackage(require("classes.inline-styles")) self:initPackage(require("classes.block-styles")) end function cabook:endPage () self:moveTocNodes() if self.moveTovNodes then self:moveTovNodes() end if not SILE.scratch.headers.skipthispage then SILE.settings:pushState() SILE.settings:reset() if self:oddPage() then SILE.call("output-right-running-head") else SILE.call("output-left-running-head") end SILE.settings:popState() end SILE.scratch.headers.skipthispage = false local ret = plain.endPage(self) if self.options.crop then self:outputCropMarks() end return ret end function cabook:finish () if self.moveTovNodes then self:writeTov() SILE.call("tableofverses") end return book.finish(self) end return cabook
fix(class): Work around classes not being able to stuff content
fix(class): Work around classes not being able to stuff content
Lua
agpl-3.0
alerque/casile,alerque/casile,alerque/casile,alerque/casile,alerque/casile
687966d6ffa242d57b768963da926b0c93afd351
messages/client/messages.lua
messages/client/messages.lua
local messages = { global = { }, client = { } } local screenWidth, screenHeight = guiGetScreenSize( ) local messageWidth, messageHeight = 316, 152 function createMessage( message, messageType, messageGlobalID, hideButton, disableInput ) destroyMessage( messageType ) destroyMessage( nil, nil, messageGlobalID ) local messageID = messageGlobalID or exports.common:nextIndex( messages ) local messageRealm = messageGlobalID and "global" or "client" local messageHolder messages[ messageRealm ][ messageID ] = { messageType = messageType or "other", disableInput = disableInput } messageHolder = messages[ messageRealm ][ messageID ] local messageHeight = messageHeight - ( hideButton and 25 or 0 ) messageHolder.window = guiCreateWindow( ( screenWidth - messageWidth ) / 2, ( screenHeight - messageHeight ) / 2, messageWidth, messageHeight, "Message", false ) guiWindowSetSizable( messageHolder.window, false ) guiSetProperty( messageHolder.window, "AlwaysOnTop", "True" ) guiSetAlpha( messageHolder.window, 0.925 ) setElementData( messageHolder.window, "messages:id", messageID, false ) setElementData( messageHolder.window, "messages:type", messageHolder.messageType, false ) setElementData( messageHolder.window, "messages:realm", messageRealm, false ) setElementData( messageHolder.window, "messages:disableInput", disableInput, false ) messageHolder.message = guiCreateLabel( 17, 35, 283, 60, message, false, messageHolder.window ) guiLabelSetHorizontalAlign( messageHolder.message, "center", true ) guiLabelSetVerticalAlign( messageHolder.message, "center" ) if ( disableInput ) then guiSetInputEnabled( true ) end if ( not hideButton ) then messageHolder.button = guiCreateButton( 16, 109, 284, 25, "Continue", false, messageHolder.window ) addEventHandler( "onClientGUIClick", messageHolder.button, function( ) destroyMessage( messageHolder.messageType ) end, false ) end end addEvent( "messages:create", true ) addEventHandler( "messages:create", root, createMessage ) function destroyMessage( messageType, messageGlobalID ) if ( messageType ) then for _, messageID in ipairs( exports.common:findByValue( messages.client, messageType, true ) ) do local message = messages.client[ messageID ] if ( isElement( message.window ) ) then destroyElement( message.window ) end triggerEvent( "messages:onContinue", localPlayer, messageID, message.messageType, "client", message.disableInput ) message = nil end else if ( messageGlobalID ) then local message = messages.global[ messageGlobalID ] if ( message ) then if ( isElement( message.window ) ) then destroyElement( message.window ) end triggerEvent( "messages:onContinue", localPlayer, messageID, message.messageType, "global", message.disableInput ) messages.global[ messageGlobalID ] = nil end end end end addEvent( "messages:destroy", true ) addEventHandler( "messages:destroy", root, destroyMessage ) addEvent( "messages:onContinue", true ) addEventHandler( "messages:onContinue", root, function( id, type, realm, disableInput ) if ( type == "login" ) then triggerEvent( "accounts:enableGUI", localPlayer ) elseif ( type == "selection" ) then triggerEvent( "characters:enableGUI", localPlayer ) end end ) addEventHandler( "onClientResourceStop", root, function( resource ) if ( not getElementData( localPlayer, "account:id" ) ) then triggerEvent( "accounts:enableGUI", localPlayer ) end if ( getResourceName( resource ) == "accounts" ) then destroyMessage( "login" ) end end ) addEventHandler( "onClientResourceStart", root, function( ) triggerServerEvent( "messages:ready", localPlayer ) end )
local messages = { global = { }, client = { } } local screenWidth, screenHeight = guiGetScreenSize( ) local messageWidth, messageHeight = 316, 152 function createMessage( message, messageType, messageGlobalID, hideButton, disableInput ) destroyMessage( messageType ) destroyMessage( nil, nil, messageGlobalID ) local messageID = messageGlobalID or exports.common:nextIndex( messages ) local messageRealm = messageGlobalID and "global" or "client" local messageHolder messages[ messageRealm ][ messageID ] = { messageType = messageType or "other", disableInput = disableInput } messageHolder = messages[ messageRealm ][ messageID ] local messageHeight = messageHeight - ( hideButton and 25 or 0 ) messageHolder.window = guiCreateWindow( ( screenWidth - messageWidth ) / 2, ( screenHeight - messageHeight ) / 2, messageWidth, messageHeight, "Message", false ) guiWindowSetSizable( messageHolder.window, false ) guiSetProperty( messageHolder.window, "AlwaysOnTop", "True" ) guiSetAlpha( messageHolder.window, 0.925 ) setElementData( messageHolder.window, "messages:id", messageID, false ) setElementData( messageHolder.window, "messages:type", messageHolder.messageType, false ) setElementData( messageHolder.window, "messages:realm", messageRealm, false ) setElementData( messageHolder.window, "messages:disableInput", disableInput, false ) messageHolder.message = guiCreateLabel( 17, 35, 283, 60, message, false, messageHolder.window ) guiLabelSetHorizontalAlign( messageHolder.message, "center", true ) guiLabelSetVerticalAlign( messageHolder.message, "center" ) showCursor( true ) guiSetInputEnabled( disableInput or false ) if ( not hideButton ) then messageHolder.button = guiCreateButton( 16, 109, 284, 25, "Continue", false, messageHolder.window ) addEventHandler( "onClientGUIClick", messageHolder.button, function( ) destroyMessage( messageHolder.messageType ) end, false ) end end addEvent( "messages:create", true ) addEventHandler( "messages:create", root, createMessage ) function destroyMessage( messageType, messageGlobalID ) if ( messageType ) then for messageIndex, messageID in ipairs( exports.common:findByValue( messages.client, messageType, true ) ) do local message = messages.client[ messageID ] if ( isElement( message.window ) ) then destroyElement( message.window ) end triggerEvent( "messages:onContinue", localPlayer, messageID, message.messageType, "client", message.disableInput ) messages.client[ messageIndex ] = nil end else if ( messageGlobalID ) then local message = messages.global[ messageGlobalID ] if ( message ) then if ( isElement( message.window ) ) then destroyElement( message.window ) end triggerEvent( "messages:onContinue", localPlayer, messageID, message.messageType, "global", message.disableInput ) messages.global[ messageGlobalID ] = nil end end end if ( #messages.client == 0 ) and ( #messages.global == 0 ) then showCursor( false ) guiSetInputEnabled( false ) end end addEvent( "messages:destroy", true ) addEventHandler( "messages:destroy", root, destroyMessage ) addEvent( "messages:onContinue", true ) addEventHandler( "messages:onContinue", root, function( id, type, realm, disableInput ) if ( type == "login" ) then triggerEvent( "accounts:enableGUI", localPlayer ) elseif ( type == "selection" ) then triggerEvent( "characters:enableGUI", localPlayer ) end end ) addEventHandler( "onClientResourceStop", root, function( resource ) if ( not getElementData( localPlayer, "account:id" ) ) then triggerEvent( "accounts:enableGUI", localPlayer ) end if ( getResourceName( resource ) == "accounts" ) then destroyMessage( "login" ) destroyMessage( "selection" ) end end ) addEventHandler( "onClientResourceStart", root, function( ) triggerServerEvent( "messages:ready", localPlayer ) end )
messages: fixed cursor issues
messages: fixed cursor issues
Lua
mit
smile-tmb/lua-mta-fairplay-roleplay
cbe0a5ceb3a7cbf2125d8ef615199358ca977eab
MMOCoreORB/bin/scripts/commands/burstShot2.lua
MMOCoreORB/bin/scripts/commands/burstShot2.lua
--Copyright (C) 2007 <SWGEmu> --This File is part of Core3. --This program 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 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 Lesser General Public License for --more details. --You should have received a copy of the GNU Lesser General --Public License along with this program; if not, write to --the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA --Linking Engine3 statically or dynamically with other modules --is making a combined work based on Engine3. --Thus, the terms and conditions of the GNU Lesser General Public License --cover the whole combination. --In addition, as a special exception, the copyright holders of Engine3 --give you permission to combine Engine3 program with free software --programs or libraries that are released under the GNU LGPL and with --code included in the standard release of Core3 under the GNU LGPL --license (or modified versions of such code, with unchanged license). --You may copy and distribute such a system following the terms of the --GNU LGPL for Engine3 and the licenses of the other code concerned, --provided that you include the source code of that other code when --and as the GNU LGPL requires distribution of source code. --Note that people who make modified versions of Engine3 are not obligated --to grant this special exception for their modified versions; --it is their choice whether to do so. The GNU Lesser General Public License --gives permission to release a modified version without this exception; --this exception also makes it possible to release a modified version --which carries forward this exception. --true = 1, false = 0 BurstShot2Command = { name = "burstshot2", damageMultiplier = 4.0, speedMultiplier = 2.0, healthCostMultiplier = 2.0, actionCostMultiplier = 1.25, mindCostMultiplier = 0.5, accuracyBonus = 25, poolsToDamage = RANDOM_ATTRIBUTE, animationCRC = hashCode("fire_7_single_medium"), combatSpam = "burstblast", range = -1 } AddCommand(BurstShot2Command)
--Copyright (C) 2007 <SWGEmu> --This File is part of Core3. --This program 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 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 Lesser General Public License for --more details. --You should have received a copy of the GNU Lesser General --Public License along with this program; if not, write to --the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA --Linking Engine3 statically or dynamically with other modules --is making a combined work based on Engine3. --Thus, the terms and conditions of the GNU Lesser General Public License --cover the whole combination. --In addition, as a special exception, the copyright holders of Engine3 --give you permission to combine Engine3 program with free software --programs or libraries that are released under the GNU LGPL and with --code included in the standard release of Core3 under the GNU LGPL --license (or modified versions of such code, with unchanged license). --You may copy and distribute such a system following the terms of the --GNU LGPL for Engine3 and the licenses of the other code concerned, --provided that you include the source code of that other code when --and as the GNU LGPL requires distribution of source code. --Note that people who make modified versions of Engine3 are not obligated --to grant this special exception for their modified versions; --it is their choice whether to do so. The GNU Lesser General Public License --gives permission to release a modified version without this exception; --this exception also makes it possible to release a modified version --which carries forward this exception. --true = 1, false = 0 BurstShot2Command = { name = "burstshot2", damageMultiplier = 4.0, speedMultiplier = 2.0, healthCostMultiplier = 2.0, actionCostMultiplier = 1.25, mindCostMultiplier = 0.5, accuracyBonus = 25, coneAngle = 15, coneAction = true, poolsToDamage = RANDOM_ATTRIBUTE, animationCRC = hashCode("fire_7_single_medium"), combatSpam = "burstblast", range = -1 } AddCommand(BurstShot2Command)
[fixed] mantis 4203 carbineer burstshot2 should be cone attack
[fixed] mantis 4203 carbineer burstshot2 should be cone attack Change-Id: Id05553e78975a5b879d6a62f7398ee64b78f5f03
Lua
agpl-3.0
lasko2112/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,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo
6818333e9788463f66227e798a6698d07d775a7f
agents/monitoring/lua/lib/info.lua
agents/monitoring/lua/lib/info.lua
local Object = require('core').Object local JSON = require('json') --[[ Info ]]-- local Info = Object:extend() function Info:initialize() self._s = sigar:new() self._params = {} end function Info:serialize() return { jsonPayload = JSON.stringify(self._params) } end local NilInfo = Info:extend() --[[ CPUInfo ]]-- local CPUInfo = Info:extend() function CPUInfo:initialize() Info.initialize(self) local cpus = self._s:cpus() self._params = {} for i=1, #cpus do local info = cpus[i]:info() local data = cpus[i]:data() local bucket = 'cpu.' .. i - 1 self._params[bucket] = {} for k, v in pairs(info) do self._params[bucket][k] = v end for k, v in pairs(data) do self._params[bucket][k] = v end end end --[[ DiskInfo ]]-- local DiskInfo = Info:extend() function DiskInfo:initialize() Info.initialize(self) local disks = self._s:disks() local name, usage for i=1, #disks do name = disks[i]:name() usage = disks[i]:usage() if usage then self._params[name] = {} for key, value in pairs(usage) do self._params[name][key] = value end end end end --[[ MemoryInfo ]]-- local MemoryInfo = Info:extend() function MemoryInfo:initialize() Info.initialize(self) local meminfo = self._s:mem() for key, value in pairs(meminfo) do self._params[key] = value end end --[[ NetworkInfo ]]-- local NetworkInfo = Info:extend() function NetworkInfo:initialize() Info.initialize(self) local netifs = self._s:netifs() for i=1,#netifs do self._params.netifs[i] = {} self._params.netifs[i].info = netifs[i]:info() self._params.netifs[i].usage = netifs[i]:usage() end end --[[ Factory ]]-- function create(infoType) if infoType == 'CPU' then return CPUInfo:new() elseif infoType == 'MEMORY' then return MemoryInfo:new() elseif infoType == 'NETWORK' then return NetworkInfo:new() elseif infoType == 'DISK' then return DiskInfo:new() end return NilInfo:new() end --[[ Exports ]]-- local info = {} info.CPUInfo = CPUInfo info.DiskInfo = DiskInfo info.MemoryInfo = MemoryInfo info.NetworkInfo = NetworkInfo info.create = create return info
local Object = require('core').Object local JSON = require('json') --[[ Info ]]-- local Info = Object:extend() function Info:initialize() self._s = sigar:new() self._params = {} end function Info:serialize() return { jsonPayload = JSON.stringify(self._params) } end local NilInfo = Info:extend() --[[ CPUInfo ]]-- local CPUInfo = Info:extend() function CPUInfo:initialize() Info.initialize(self) local cpus = self._s:cpus() self._params = {} for i=1, #cpus do local info = cpus[i]:info() local data = cpus[i]:data() local bucket = 'cpu.' .. i - 1 self._params[bucket] = {} for k, v in pairs(info) do self._params[bucket][k] = v end for k, v in pairs(data) do self._params[bucket][k] = v end end end --[[ DiskInfo ]]-- local DiskInfo = Info:extend() function DiskInfo:initialize() Info.initialize(self) local disks = self._s:disks() local name, usage for i=1, #disks do name = disks[i]:name() usage = disks[i]:usage() if usage then self._params[name] = {} for key, value in pairs(usage) do self._params[name][key] = value end end end end --[[ MemoryInfo ]]-- local MemoryInfo = Info:extend() function MemoryInfo:initialize() Info.initialize(self) local meminfo = self._s:mem() for key, value in pairs(meminfo) do self._params[key] = value end end --[[ NetworkInfo ]]-- local NetworkInfo = Info:extend() function NetworkInfo:initialize() Info.initialize(self) local netifs = self._s:netifs() for i=1,#netifs do local info = netifs[i]:info() local usage = netifs[i]:usage() local name = info.name self._params[name] = {} for k, v in pairs(info) do self._params[name][k] = v end for k, v in pairs(usage) do self._params[name][k] = v end end end --[[ Factory ]]-- function create(infoType) if infoType == 'CPU' then return CPUInfo:new() elseif infoType == 'MEMORY' then return MemoryInfo:new() elseif infoType == 'NETWORK' then return NetworkInfo:new() elseif infoType == 'DISK' then return DiskInfo:new() end return NilInfo:new() end --[[ Exports ]]-- local info = {} info.CPUInfo = CPUInfo info.DiskInfo = DiskInfo info.MemoryInfo = MemoryInfo info.NetworkInfo = NetworkInfo info.create = create return info
fix network info
fix network info
Lua
apache-2.0
kans/zirgo,kans/zirgo,kans/zirgo
d8d4eaf75304462b2e911e426c2dbc8f2569c2fa
Hydra/API/screen.lua
Hydra/API/screen.lua
--- screen:frame_including_dock_and_menu() -> rect --- Returns the screen's rect in absolute coordinates, including the dock and menu. function screen:frame_including_dock_and_menu() local primary_screen = screen.allscreens()[1] local f = self:frame() f.y = primary_screen:frame().h - f.h - f.y return f end --- screen:frame_without_dock_or_menu() -> rect --- Returns the screen's rect in absolute coordinates, without the dock or menu. function screen:frame_without_dock_or_menu() local primary_screen = screen.allscreens()[1] local f = self:visibleframe() f.y = primary_screen:frame().h - f.h - f.y return f end --- screen:next() -> screen --- Returns the screen 'after' this one (I have no idea how they're ordered though); this method wraps around to the first screen. function screen:next() local screens = screen.allscreens() local i = fnutils.indexof(screens, self) + 1 if i > # screens then i = 1 end return screens[i] end --- screen:previous() -> screen --- Returns the screen 'before' this one (I have no idea how they're ordered though); this method wraps around to the last screen. function screen:previous() local screens = screen.allscreens() local i = fnutils.indexof(screens, self) - 1 if i < 1 then i = # screens end return screens[i] end local function first_screen_in_direction(screen, numrotations) if #screen.allscreens() == 1 then return nil end -- assume looking to east -- use the score distance/cos(A/2), where A is the angle by which it -- differs from the straight line in the direction you're looking -- for. (may have to manually prevent division by zero.) -- thanks mark! local otherscreens = fnutils.filter(screen.allscreens(), function(s) return s ~= screen end) local startingpoint = geometry.rectmidpoint(screen:frame_including_dock_and_menu()) local closestscreens = {} for _, s in pairs(otherscreens) do local otherpoint = geometry.rectmidpoint(s:frame_including_dock_and_menu()) otherpoint = geometry.rotateccw(otherpoint, startingpoint, numrotations) local delta = { x = otherpoint.x - startingpoint.x, y = otherpoint.y - startingpoint.y, } if delta.x > 0 then local angle = math.atan2(delta.y, delta.x) local distance = geometry.hypot(delta) local anglediff = -angle local score = distance / math.cos(anglediff / 2) table.insert(closestscreens, {s = s, score = score}) end end table.sort(closestscreens, function(a, b) return a.score < b.score end) return closestscreens[1] end --- screen:toeast() --- Get the first screen to the east of this one, ordered by proximity. function screen:toeast() return first_screen_in_direction(self, 0) end --- screen:towest() --- Get the first screen to the west of this one, ordered by proximity. function screen:towest() return first_screen_in_direction(self, 2) end --- screen:tonorth() --- Get the first screen to the north of this one, ordered by proximity. function screen:tonorth() return first_screen_in_direction(self, 1) end --- screen:tosouth() --- Get the first screen to the south of this one, ordered by proximity. function screen:tosouth() return first_screen_in_direction(self, 3) end
--- screen:frame_including_dock_and_menu() -> rect --- Returns the screen's rect in absolute coordinates, including the dock and menu. function screen:frame_including_dock_and_menu() local primary_screen = screen.allscreens()[1] local f = self:frame() f.y = primary_screen:frame().h - f.h - f.y return f end --- screen:frame_without_dock_or_menu() -> rect --- Returns the screen's rect in absolute coordinates, without the dock or menu. function screen:frame_without_dock_or_menu() local primary_screen = screen.allscreens()[1] local f = self:visibleframe() f.y = primary_screen:frame().h - f.h - f.y return f end --- screen:next() -> screen --- Returns the screen 'after' this one (I have no idea how they're ordered though); this method wraps around to the first screen. function screen:next() local screens = screen.allscreens() local i = fnutils.indexof(screens, self) + 1 if i > # screens then i = 1 end return screens[i] end --- screen:previous() -> screen --- Returns the screen 'before' this one (I have no idea how they're ordered though); this method wraps around to the last screen. function screen:previous() local screens = screen.allscreens() local i = fnutils.indexof(screens, self) - 1 if i < 1 then i = # screens end return screens[i] end local function first_screen_in_direction(screen, numrotations) if #screen.allscreens() == 1 then return nil end -- assume looking to east -- use the score distance/cos(A/2), where A is the angle by which it -- differs from the straight line in the direction you're looking -- for. (may have to manually prevent division by zero.) -- thanks mark! local otherscreens = fnutils.filter(screen.allscreens(), function(s) return s ~= screen end) local startingpoint = geometry.rectmidpoint(screen:frame_including_dock_and_menu()) local closestscreens = {} for _, s in pairs(otherscreens) do local otherpoint = geometry.rectmidpoint(s:frame_including_dock_and_menu()) otherpoint = geometry.rotateccw(otherpoint, startingpoint, numrotations) local delta = { x = otherpoint.x - startingpoint.x, y = otherpoint.y - startingpoint.y, } if delta.x > 0 then local angle = math.atan2(delta.y, delta.x) local distance = geometry.hypot(delta) local anglediff = -angle local score = distance / math.cos(anglediff / 2) table.insert(closestscreens, {s = s, score = score}) end end table.sort(closestscreens, function(a, b) return a.score < b.score end) if #closestscreens > 0 then return closestscreens[1].s else return nil end end --- screen:toeast() --- Get the first screen to the east of this one, ordered by proximity. function screen:toeast() return first_screen_in_direction(self, 0) end --- screen:towest() --- Get the first screen to the west of this one, ordered by proximity. function screen:towest() return first_screen_in_direction(self, 2) end --- screen:tonorth() --- Get the first screen to the north of this one, ordered by proximity. function screen:tonorth() return first_screen_in_direction(self, 1) end --- screen:tosouth() --- Get the first screen to the south of this one, ordered by proximity. function screen:tosouth() return first_screen_in_direction(self, 3) end
Fix screen in direction methods.
Fix screen in direction methods.
Lua
mit
zzamboni/hammerspoon,wvierber/hammerspoon,wsmith323/hammerspoon,heptal/hammerspoon,CommandPost/CommandPost-App,CommandPost/CommandPost-App,knl/hammerspoon,heptal/hammerspoon,Habbie/hammerspoon,emoses/hammerspoon,Hammerspoon/hammerspoon,dopcn/hammerspoon,junkblocker/hammerspoon,wvierber/hammerspoon,Habbie/hammerspoon,knu/hammerspoon,chrisjbray/hammerspoon,hypebeast/hammerspoon,Hammerspoon/hammerspoon,knl/hammerspoon,cmsj/hammerspoon,Habbie/hammerspoon,peterhajas/hammerspoon,peterhajas/hammerspoon,Habbie/hammerspoon,trishume/hammerspoon,asmagill/hammerspoon,cmsj/hammerspoon,chrisjbray/hammerspoon,cmsj/hammerspoon,CommandPost/CommandPost-App,knu/hammerspoon,bradparks/hammerspoon,latenitefilms/hammerspoon,chrisjbray/hammerspoon,cmsj/hammerspoon,ocurr/hammerspoon,ocurr/hammerspoon,kkamdooong/hammerspoon,asmagill/hammerspoon,peterhajas/hammerspoon,wsmith323/hammerspoon,hypebeast/hammerspoon,dopcn/hammerspoon,wvierber/hammerspoon,dopcn/hammerspoon,TimVonsee/hammerspoon,lowne/hammerspoon,heptal/hammerspoon,asmagill/hammerspoon,hypebeast/hammerspoon,lowne/hammerspoon,CommandPost/CommandPost-App,heptal/hammerspoon,nkgm/hammerspoon,dopcn/hammerspoon,tmandry/hammerspoon,Stimim/hammerspoon,tmandry/hammerspoon,Habbie/hammerspoon,knl/hammerspoon,emoses/hammerspoon,cmsj/hammerspoon,ocurr/hammerspoon,wvierber/hammerspoon,bradparks/hammerspoon,Hammerspoon/hammerspoon,Stimim/hammerspoon,wsmith323/hammerspoon,trishume/hammerspoon,latenitefilms/hammerspoon,Hammerspoon/hammerspoon,tmandry/hammerspoon,bradparks/hammerspoon,knu/hammerspoon,latenitefilms/hammerspoon,asmagill/hammerspoon,knu/hammerspoon,joehanchoi/hammerspoon,emoses/hammerspoon,junkblocker/hammerspoon,asmagill/hammerspoon,nkgm/hammerspoon,cmsj/hammerspoon,knl/hammerspoon,trishume/hammerspoon,Stimim/hammerspoon,chrisjbray/hammerspoon,zzamboni/hammerspoon,wvierber/hammerspoon,zzamboni/hammerspoon,ocurr/hammerspoon,bradparks/hammerspoon,emoses/hammerspoon,Stimim/hammerspoon,joehanchoi/hammerspoon,zzamboni/hammerspoon,junkblocker/hammerspoon,kkamdooong/hammerspoon,nkgm/hammerspoon,chrisjbray/hammerspoon,CommandPost/CommandPost-App,emoses/hammerspoon,nkgm/hammerspoon,dopcn/hammerspoon,hypebeast/hammerspoon,latenitefilms/hammerspoon,kkamdooong/hammerspoon,latenitefilms/hammerspoon,peterhajas/hammerspoon,latenitefilms/hammerspoon,Hammerspoon/hammerspoon,bradparks/hammerspoon,TimVonsee/hammerspoon,CommandPost/CommandPost-App,wsmith323/hammerspoon,knl/hammerspoon,zzamboni/hammerspoon,heptal/hammerspoon,knu/hammerspoon,wsmith323/hammerspoon,Hammerspoon/hammerspoon,junkblocker/hammerspoon,asmagill/hammerspoon,ocurr/hammerspoon,lowne/hammerspoon,TimVonsee/hammerspoon,Habbie/hammerspoon,joehanchoi/hammerspoon,chrisjbray/hammerspoon,TimVonsee/hammerspoon,TimVonsee/hammerspoon,knu/hammerspoon,kkamdooong/hammerspoon,nkgm/hammerspoon,zzamboni/hammerspoon,Stimim/hammerspoon,hypebeast/hammerspoon,junkblocker/hammerspoon,joehanchoi/hammerspoon,joehanchoi/hammerspoon,kkamdooong/hammerspoon,lowne/hammerspoon,lowne/hammerspoon,peterhajas/hammerspoon
a7d6f88a7f0ffb06d5184d275d23daba15c588f6
scripts/openal.lua
scripts/openal.lua
-- -- Copyright (c) 2012-2020 Daniele Bartolini and individual contributors. -- License: https://github.com/dbartolini/crown/blob/master/LICENSE -- function openal_project(_kind) project "openal" kind (_kind) configuration {} local AL_DIR = (CROWN_DIR .. "3rdparty/openal/") defines { "_LARGE_FILES", "_LARGEFILE_SOURCE", "AL_ALEXT_PROTOTYPES", "AL_BUILD_LIBRARY", "HAVE_C99_BOOL", "HAVE_FENV_H", "HAVE_FLOAT_H", "HAVE_LRINTF", "HAVE_MALLOC_H", "HAVE_STAT", "HAVE_STDBOOL_H", "HAVE_STDINT_H", "HAVE_STRTOF", } configuration { "not vs*" } defines { "HAVE_C99_VLA", "HAVE_DIRENT_H", "HAVE_GCC_DESTRUCTOR", "HAVE_GCC_FORMAT", "HAVE_PTHREAD_SETNAME_NP", "HAVE_PTHREAD_SETSCHEDPARAM", "HAVE_STRINGS_H", "restrict=__restrict", "SIZEOF_LONG=8", "SIZEOF_LONG_LONG=8", -- These are needed on non-Windows systems for extra features "_GNU_SOURCE=1", "_POSIX_C_SOURCE=200809L", "_XOPEN_SOURCE=700", } buildoptions { "-fPIC", "-Winline", "-fvisibility=hidden", "-fexceptions" -- :( } configuration { "linux-* or android-*" } defines { "HAVE_DLFCN_H", "HAVE_GCC_GET_CPUID", } configuration { "not android-*" } defines { "HAVE_SSE", "HAVE_SSE2", } files { AL_DIR .. "alc/mixer/mixer_sse2.cpp", AL_DIR .. "alc/mixer/mixer_sse.cpp", } configuration { "android-*" } files { AL_DIR .. "alc/backends/opensl.cpp" } links { "OpenSLES", } configuration { "linux-*" } defines { "HAVE_CPUID_H", "HAVE_POSIX_MEMALIGN", "HAVE_PTHREAD_MUTEX_TIMEDLOCK", "HAVE_PULSEAUDIO", } files { AL_DIR .. "alc/backends/pulseaudio.cpp", } configuration { "vs* or mingw-*"} defines { "_WIN32_WINNT=0x0502", "_WINDOWS", "HAVE___CONTROL87_2", "HAVE__ALIGNED_MALLOC", "HAVE__CONTROLFP", "HAVE_CPUID_INTRINSIC", "HAVE_DSOUND", "HAVE_GUIDDEF_H", "HAVE_INTRIN_H", "HAVE_IO_H", "HAVE_MMDEVAPI", "HAVE_WINDOWS_H", "HAVE_WINMM", } files { AL_DIR .. "alc/backends/mmdevapi.cpp", AL_DIR .. "alc/backends/dsound.cpp", AL_DIR .. "alc/backends/winmm.cpp", } links { "winmm", "ole32", } configuration { "vs*" } defines { "_CRT_NONSTDC_NO_DEPRECATE", "inline=__inline", "restrict=", "SIZEOF_LONG=4", "SIZEOF_LONG_LONG=8", "strcasecmp=_stricmp", "strncasecmp=_strnicmp", } buildoptions { "/wd4098", "/wd4267", "/wd4244", "/EHs", -- :( } configuration {} includedirs { AL_DIR .. "al/include", AL_DIR .. "alc", AL_DIR .. "common", AL_DIR .. "include", AL_DIR, } files { AL_DIR .. "al/*.cpp", AL_DIR .. "alc/*.cpp", AL_DIR .. "alc/backends/base.cpp", AL_DIR .. "alc/backends/loopback.cpp", AL_DIR .. "alc/backends/null.cpp", AL_DIR .. "alc/effects/*.cpp", AL_DIR .. "alc/filters/*.cpp", AL_DIR .. "alc/midi/*.cpp", AL_DIR .. "alc/mixer/mixer_c.cpp", AL_DIR .. "common/*.cpp", } configuration {} end
-- -- Copyright (c) 2012-2020 Daniele Bartolini and individual contributors. -- License: https://github.com/dbartolini/crown/blob/master/LICENSE -- function openal_project(_kind) project "openal" kind (_kind) configuration {} local AL_DIR = (CROWN_DIR .. "3rdparty/openal/") defines { "_LARGE_FILES", "_LARGEFILE_SOURCE", "AL_ALEXT_PROTOTYPES", "AL_BUILD_LIBRARY", "HAVE_C99_BOOL", "HAVE_FENV_H", "HAVE_FLOAT_H", "HAVE_LRINTF", "HAVE_MALLOC_H", "HAVE_STAT", "HAVE_STDBOOL_H", "HAVE_STDINT_H", "HAVE_STRTOF", } configuration { "not vs*" } defines { "HAVE_C99_VLA", "HAVE_DIRENT_H", "HAVE_GCC_DESTRUCTOR", "HAVE_GCC_FORMAT", "HAVE_PTHREAD_SETNAME_NP", "HAVE_PTHREAD_SETSCHEDPARAM", "HAVE_STRINGS_H", "restrict=__restrict", "SIZEOF_LONG=8", "SIZEOF_LONG_LONG=8", -- These are needed on non-Windows systems for extra features "_GNU_SOURCE=1", "_POSIX_C_SOURCE=200809L", "_XOPEN_SOURCE=700", } buildoptions { "-fPIC", "-Winline", "-fvisibility=hidden", "-fexceptions" -- :( } configuration { "linux-* or android-*" } defines { "HAVE_DLFCN_H", "HAVE_GCC_GET_CPUID", } configuration { "not android-*" } defines { "HAVE_SSE", "HAVE_SSE2", } files { AL_DIR .. "alc/mixer/mixer_sse2.cpp", AL_DIR .. "alc/mixer/mixer_sse.cpp", } configuration { "android-*" } files { AL_DIR .. "alc/backends/opensl.cpp" } links { "OpenSLES", } configuration { "linux-*" } defines { "HAVE_CPUID_H", "HAVE_POSIX_MEMALIGN", "HAVE_PTHREAD_MUTEX_TIMEDLOCK", "HAVE_PULSEAUDIO", } files { AL_DIR .. "alc/backends/pulseaudio.cpp", } configuration { "vs* or mingw-*"} defines { "_WIN32_WINNT=0x0502", "_WINDOWS", "HAVE___CONTROL87_2", "HAVE__ALIGNED_MALLOC", "HAVE__CONTROLFP", "HAVE_CPUID_INTRINSIC", "HAVE_DSOUND", "HAVE_GUIDDEF_H", "HAVE_INTRIN_H", "HAVE_IO_H", "HAVE_WASAPI", "HAVE_WINDOWS_H", "HAVE_WINMM", } files { AL_DIR .. "alc/backends/dsound.cpp", AL_DIR .. "alc/backends/wasapi.cpp", AL_DIR .. "alc/backends/winmm.cpp", } links { "winmm", "ole32", } configuration { "vs*" } defines { "_CRT_NONSTDC_NO_DEPRECATE", "restrict=", "SIZEOF_LONG=4", "SIZEOF_LONG_LONG=8", "strcasecmp=_stricmp", "strncasecmp=_strnicmp", } buildoptions { "/wd4098", "/wd4267", "/wd4244", "/EHs", -- :( } configuration {} includedirs { AL_DIR .. "al/include", AL_DIR .. "alc", AL_DIR .. "common", AL_DIR .. "include", AL_DIR, } files { AL_DIR .. "al/*.cpp", AL_DIR .. "alc/*.cpp", AL_DIR .. "alc/backends/base.cpp", AL_DIR .. "alc/backends/loopback.cpp", AL_DIR .. "alc/backends/null.cpp", AL_DIR .. "alc/effects/*.cpp", AL_DIR .. "alc/filters/*.cpp", AL_DIR .. "alc/midi/*.cpp", AL_DIR .. "alc/mixer/mixer_c.cpp", AL_DIR .. "common/*.cpp", } configuration {} end
scripts: fix windows build
scripts: fix windows build
Lua
mit
mikymod/crown,mikymod/crown,mikymod/crown,dbartolini/crown,galek/crown,taylor001/crown,taylor001/crown,dbartolini/crown,dbartolini/crown,mikymod/crown,galek/crown,taylor001/crown,galek/crown,galek/crown,taylor001/crown,dbartolini/crown
d4792ac4eb4addf40c6c9fe27f0a810a7582ea0a
PairwiseDistance.lua
PairwiseDistance.lua
local PairwiseDistance, parent = torch.class('nn.PairwiseDistance', 'nn.Module') function PairwiseDistance:__init(p) parent.__init(self) -- state self.gradInput = {torch.Tensor(), torch.Tensor()} self.output = torch.Tensor(1) self.norm=p end function PairwiseDistance:updateOutput(input) if input[1]:dim() == 1 then self.output[1]=input[1]:dist(input[2],self.norm) elseif input[1]:dim() == 2 then self.diff = self.diff or input[1].new() self.diff:resizeAs(input[1]) local diff = self.diff:zero() --local diff = torch.add(input[1], -1, input[2]) diff:add(input[1], -1, input[2]) self.output:resize(input[1]:size(1)) self.output:zero() self.output:add(diff:pow(self.norm):sum(2)) self.output:pow(1./self.norm) else error('input must be vector or matrix') end return self.output end local function mathsign(x) if x==0 then return 2*torch.random(2)-3; end if x>0 then return 1; else return -1; end end function PairwiseDistance:updateGradInput(input, gradOutput) self.gradInput[1]:resize(input[1]:size()) self.gradInput[2]:resize(input[2]:size()) self.gradInput[1]:copy(input[1]) self.gradInput[1]:add(-1, input[2]) if self.norm==1 then self.gradInput[1]:apply(mathsign) end if input[1]:dim() == 1 then self.gradInput[1]:mul(gradOutput[1]) elseif input[1]:dim() == 2 then self.grad = self.grad or gradOutput.new() self.ones = self.ones or gradOutput.new() self.grad:resizeAs(input[1]):zero() self.ones:resize(input[1]:size(2)):fill(1) self.grad:addr(gradOutput, self.ones) self.gradInput[1]:cmul(self.grad) else error('input must be vector or matrix') end self.gradInput[2]:zero():add(-1, self.gradInput[1]) return self.gradInput end
local PairwiseDistance, parent = torch.class('nn.PairwiseDistance', 'nn.Module') function PairwiseDistance:__init(p) parent.__init(self) -- state self.gradInput = {torch.Tensor(), torch.Tensor()} self.output = torch.Tensor(1) self.norm=p end function PairwiseDistance:updateOutput(input) if input[1]:dim() == 1 then self.output[1]=input[1]:dist(input[2],self.norm) elseif input[1]:dim() == 2 then self.diff = self.diff or input[1].new() self.diff:resizeAs(input[1]) local diff = self.diff:zero() --local diff = torch.add(input[1], -1, input[2]) diff:add(input[1], -1, input[2]) if math.mod(self.norm, 2) == 1 then diff:abs() end self.output:resize(input[1]:size(1)) self.output:zero() self.output:add(diff:pow(self.norm):sum(2)) self.output:pow(1./self.norm) else error('input must be vector or matrix') end return self.output end local function mathsign(x) if x==0 then return 2*torch.random(2)-3; end if x>0 then return 1; else return -1; end end function PairwiseDistance:updateGradInput(input, gradOutput) self.gradInput[1]:resize(input[1]:size()) self.gradInput[2]:resize(input[2]:size()) self.gradInput[1]:copy(input[1]) self.gradInput[1]:add(-1, input[2]) if self.norm==1 then self.gradInput[1]:apply(mathsign) end if input[1]:dim() == 1 then self.gradInput[1]:mul(gradOutput[1]) elseif input[1]:dim() == 2 then self.grad = self.grad or gradOutput.new() self.ones = self.ones or gradOutput.new() self.grad:resizeAs(input[1]):zero() self.ones:resize(input[1]:size(2)):fill(1) self.grad:addr(gradOutput, self.ones) self.gradInput[1]:cmul(self.grad) else error('input must be vector or matrix') end self.gradInput[2]:zero():add(-1, self.gradInput[1]) return self.gradInput end
Fixed PairwiseDistance for odd Lp norms
Fixed PairwiseDistance for odd Lp norms
Lua
bsd-3-clause
Moodstocks/nn,PraveerSINGH/nn,colesbury/nn,davidBelanger/nn,forty-2/nn,jhjin/nn,sagarwaghmare69/nn,karpathy/nn,caldweln/nn,douwekiela/nn,eulerreich/nn,Djabbz/nn,adamlerer/nn,jonathantompson/nn,ominux/nn,lukasc-ch/nn,hery/nn,EnjoyHacking/nn,boknilev/nn,clementfarabet/nn,LinusU/nn,fmassa/nn,rotmanmi/nn,andreaskoepf/nn,elbamos/nn,mlosch/nn,soumith/nn,zhangxiangxiao/nn,joeyhng/nn,Aysegul/nn,zchengquan/nn,sbodenstein/nn,lvdmaaten/nn,aaiijmrtt/nn,hughperkins/nn,ivendrov/nn,nicholas-leonard/nn,eriche2016/nn,PierrotLC/nn,apaszke/nn,Jeffyrao/nn,szagoruyko/nn,rickyHong/nn_lib_torch,diz-vara/nn,jzbontar/nn,witgo/nn,GregSatre/nn,abeschneider/nn,xianjiec/nn,noa/nn,bartvm/nn,kmul00/nn,mys007/nn,vgire/nn
81c31b3dea5d7c66f9712a5b8501762be266cc3d
site/api/email.lua
site/api/email.lua
--[[ Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ]]-- -- This is email.lua - a script for fetching a document (email) local JSON = require 'cjson' local elastic = require 'lib/elastic' local aaa = require 'lib/aaa' local user = require 'lib/user' local cross = require 'lib/cross' local config = require 'lib/config' local utils = require 'lib/utils' function handle(r) cross.contentType(r, "application/json") local get = r:parseargs() -- get the parameter (if any) and tidy it up local eid = (get.id or ""):gsub("\"", "") -- If it is the empty string then set it to "1" so ES doesn't barf -- N.B. ?id is treated as ?id=1 if #eid == 0 then eid = "1" end local doc = elastic.get("mbox", eid, true) -- Try searching by original source mid if not found, for backward compat if not doc or not doc.mid then doc = nil -- ensure subsequent check works if we don't find the email here either local docs = elastic.find("message-id:\"" .. r:escape(eid) .. "\"", 1, "mbox") if #docs == 1 then doc = docs[1] end -- shortened link maybe? if #docs == 0 and #eid == utils.SHORTENED_LINK_LEN then docs = elastic.find("mid:" .. r:escape(eid) .. "*", 1, "mbox") end if #docs == 1 then doc = docs[1] end end -- Did we find an email? if doc then local account = user.get(r) -- If we can access this email, ... if aaa.canAccessDoc(r, doc, account) then doc.tid = doc.request_id -- Are we in fact looking for an attachment inside this email? if get.attachment then local hash = r:escape(get.file) local fdoc = elastic.get("attachment", hash) if fdoc and fdoc.source then local out = r:base64_decode(fdoc.source:gsub("\n", "")) -- bug in mod_lua? local ct = "application/binary" local fn = "unknown" local fs = 0 for k, v in pairs(doc.attachments or {}) do if v.hash == hash then ct = v.content_type or "application/binary" fn = v.filename fs = v.size break end end cross.contentType(r, ct) r.headers_out['Content-Length'] = fs if not (ct:match("image") or ct:match("text")) then r.headers_out['Content-Disposition'] = ("attachment; filename=\"%s\";"):format(fn) end r:write(out) return cross.OK end -- Or do we just want the email itself? else local eml = utils.extractCanonEmail(doc.from or "unknown") -- Anonymize to/cc if full_headers is false -- do this before anonymizing the headers if not config.full_headers or not account then doc.to = nil doc.cc = nil end if not account then -- anonymize email address if not logged in doc = utils.anonymizeHdrs(doc, true) end -- Anonymize any email address mentioned in the email if not logged in if not account and config.antispam then doc.body = utils.anonymizeBody(doc.body) end doc.gravatar = r:md5(eml:lower()) r:puts(JSON.encode(doc)) return cross.OK end end end r:puts(JSON.encode{error = "No such e-mail or you do not have access to it."}) return cross.OK end cross.start(handle)
--[[ Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ]]-- -- This is email.lua - a script for fetching a document (email) local JSON = require 'cjson' local elastic = require 'lib/elastic' local aaa = require 'lib/aaa' local user = require 'lib/user' local cross = require 'lib/cross' local config = require 'lib/config' local utils = require 'lib/utils' local mime = require "mime" function handle(r) cross.contentType(r, "application/json") local get = r:parseargs() -- get the parameter (if any) and tidy it up local eid = (get.id or ""):gsub("\"", "") -- If it is the empty string then set it to "1" so ES doesn't barf -- N.B. ?id is treated as ?id=1 if #eid == 0 then eid = "1" end local doc = elastic.get("mbox", eid, true) -- Try searching by original source mid if not found, for backward compat if not doc or not doc.mid then doc = nil -- ensure subsequent check works if we don't find the email here either local docs = elastic.find("message-id:\"" .. r:escape(eid) .. "\"", 1, "mbox") if #docs == 1 then doc = docs[1] end -- shortened link maybe? if #docs == 0 and #eid == utils.SHORTENED_LINK_LEN then docs = elastic.find("mid:" .. r:escape(eid) .. "*", 1, "mbox") end if #docs == 1 then doc = docs[1] end end -- Did we find an email? if doc then local account = user.get(r) -- If we can access this email, ... if aaa.canAccessDoc(r, doc, account) then doc.tid = doc.request_id -- Are we in fact looking for an attachment inside this email? if get.attachment then local hash = r:escape(get.file) local fdoc = elastic.get("attachment", hash) if fdoc and fdoc.source then local out = mime.unb64(fdoc.source) local ct = "application/binary" local fn = "unknown" local fs = 0 for k, v in pairs(doc.attachments or {}) do if v.hash == hash then ct = v.content_type or "application/binary" fn = v.filename fs = v.size break end end cross.contentType(r, ct) r.headers_out['Content-Length'] = fs if not (ct:match("image") or ct:match("text")) then r.headers_out['Content-Disposition'] = ("attachment; filename=\"%s\";"):format(fn) end r:write(out) return cross.OK end -- Or do we just want the email itself? else local eml = utils.extractCanonEmail(doc.from or "unknown") -- Anonymize to/cc if full_headers is false -- do this before anonymizing the headers if not config.full_headers or not account then doc.to = nil doc.cc = nil end if not account then -- anonymize email address if not logged in doc = utils.anonymizeHdrs(doc, true) end -- Anonymize any email address mentioned in the email if not logged in if not account and config.antispam then doc.body = utils.anonymizeBody(doc.body) end doc.gravatar = r:md5(eml:lower()) r:puts(JSON.encode(doc)) return cross.OK end end end r:puts(JSON.encode{error = "No such e-mail or you do not have access to it."}) return cross.OK end cross.start(handle)
switch to socket.mime for unb64 operations
switch to socket.mime for unb64 operations This fixes #384 by changing to a less buggy b64 decoder.
Lua
apache-2.0
quenda/ponymail,jimjag/ponymail,jimjag/ponymail,Humbedooh/ponymail,jimjag/ponymail,quenda/ponymail,Humbedooh/ponymail,quenda/ponymail,jimjag/ponymail,Humbedooh/ponymail
81c91ef8a6251570daeea6cee6bef76d6c390c67
Assets/ToLua/Lua/System/Injection/LuaInjectionStation.lua
Assets/ToLua/Lua/System/Injection/LuaInjectionStation.lua
--[[MIT License Copyright (c) 2018 Jonson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.]]-- local pcall = pcall local pairs = pairs local error = error local rawget = rawget local string = string local tolua_tag = tolua_tag local getmetatable = getmetatable local CSLuaInjectStation local bridgeInfo = require "System.Injection.InjectionBridgeInfo" local function Check(csModule) local existmt = getmetatable(csModule) if rawget(existmt, tolua_tag) ~= 1 then error("Can't Inject") end return existmt end local function CacheCSLuaInjectStation() if CSLuaInjectStation == nil then CSLuaInjectStation = LuaInterface.LuaInjectionStation end end local function UpdateFunctionReference(metatable, injectInfo) local oldIndexMetamethod = metatable.__index metatable.__index = function(t, k) --Ignore Overload Function local v = rawget(injectInfo, k) if v ~= nil then return v end local status, result = pcall(oldIndexMetamethod, t, k) if status then return result else error(result) return nil end end end function InjectByModule(csModule, injectInfo) local mt = Check(csModule) local moduleName = mt[".name"] InjectByName(moduleName, injectInfo) UpdateFunctionReference(mt, injectInfo) end --Won't Update Function Reference In Lua Env function InjectByName(moduleName, injectInfo) CacheCSLuaInjectStation() local moduleBridgeInfo = rawget(bridgeInfo, moduleName) if moduleBridgeInfo == nil then error(string.format("Module %s Can't Inject", moduleName)) end for funcName, infoPipeline in pairs(injectInfo) do local injectFunction, injectFlag = infoPipeline() local injectIndex = rawget(moduleBridgeInfo, funcName) if injectIndex == nil then error(string.format("Function %s Doesn't Exist In Module %s", funcName, moduleName)) end CSLuaInjectStation.CacheInjectFunction(injectIndex, injectFlag:ToInt(), injectFunction) end end require "System.Injection.LuaInjectionBus"
--[[MIT License Copyright (c) 2018 Jonson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.]]-- local pcall = pcall local pairs = pairs local error = error local rawget = rawget local string = string local tolua_tag = tolua_tag local getmetatable = getmetatable local CSLuaInjectStation local bridgeInfo = require "System.Injection.InjectionBridgeInfo" local function Check(csModule) local existmt = getmetatable(csModule) if rawget(existmt, tolua_tag) ~= 1 then error("Can't Inject") end return existmt end local function CacheCSLuaInjectStation() if CSLuaInjectStation == nil then CSLuaInjectStation = LuaInterface.LuaInjectionStation end end local function UpdateFunctionReference(metatable, injectInfo) local oldIndexMetamethod = metatable.__index metatable.__index = function(t, k) --Ignore Overload Function local infoPipeline = rawget(injectInfo, k) if infoPipeline ~= nil then local injectFunction, injectFlag = infoPipeline() if injectFlag == LuaInterface.InjectType.Replace or injectFlag == LuaInterface.InjectType.ReplaceWithPostInvokeBase or injectFlag == LuaInterface.InjectType.ReplaceWithPreInvokeBase then return injectFunction end end local status, result = pcall(oldIndexMetamethod, t, k) if status then return result else error(result) return nil end end end function InjectByModule(csModule, injectInfo) local mt = Check(csModule) local moduleName = mt[".name"] InjectByName(moduleName, injectInfo) UpdateFunctionReference(mt, injectInfo) end --Won't Update Function Reference In Lua Env function InjectByName(moduleName, injectInfo) CacheCSLuaInjectStation() local moduleBridgeInfo = rawget(bridgeInfo, moduleName) if moduleBridgeInfo == nil then error(string.format("Module %s Can't Inject", moduleName)) end for funcName, infoPipeline in pairs(injectInfo) do local injectFunction, injectFlag = infoPipeline() local injectIndex = rawget(moduleBridgeInfo, funcName) if injectIndex == nil then error(string.format("Function %s Doesn't Exist In Module %s", funcName, moduleName)) end CSLuaInjectStation.CacheInjectFunction(injectIndex, injectFlag:ToInt(), injectFunction) end end require "System.Injection.LuaInjectionBus"
修正lua环境的函数引用更新出错的BUG
修正lua环境的函数引用更新出错的BUG
Lua
mit
topameng/tolua
7c147adbd288d3cabc68e5d970beb73b42fe0568
control.lua
control.lua
require "util" require "stdlib/log/logger" require "stdlib/gui/gui" require "src/gui" require "src/move" require "src/armor" require "src/test" LOG = Logger.new("MagneticFloor") function print(stuff) game.players[1].print(stuff) end function printBool(stuff) game.players[1].print(tostring(stuff)) end function setup() global.hoverboard = global.hoverboard or {} end function activateEquipment(index) global.hoverboard[index].inserted = true global.hoverboard[index].active = false UI.initialize(index) end function deactivateEquipment(index) if global.hoverboard[index].inserted == true then global.hoverboard[index].inserted = false UI.destroy(index) end end function createPlayerMag(i) local entity = { charge = 0, active = false, inserted = false, } global.hoverboard[i] = entity end script.on_init(setup) script.on_event(defines.events.on_player_joined_game, function(event) createPlayerMag(event.player_index) end) script.on_event(defines.events.on_tick, function(event) local n = 0 for k,v in pairs(game.players) do if global.hoverboard[k] == nil then createPlayerMag(v.index) end if global.hoverboard[k].inserted == true and global.hoverboard[k].active == true then locomotion(k) tileCheck(k) UI.updateStatus(k) end end end) script.on_event(defines.events.on_player_placed_equipment, function(event) local index = event.player_index if getArmor(index) ~= false and event.equipment.name == "hoverboard" then activateEquipment(index) end end) script.on_event(defines.events.on_player_removed_equipment, function(event) local index = event.player_index if getArmor(index) ~= false and event.equipment == "hoverboard" then deactivateEquipment(index) end end) script.on_event(defines.events.on_entity_died, function(event) if event.entity.name == "player" then global.dead = true end end) function switchMode(index) if global.hoverboard[index].active == false then global.hoverboard[index].active = true elseif global.hoverboard[index].active == true then global.hoverboard[index].active = false end UI.switchMode(global.hoverboard[index].active,index) end script.on_event(defines.events.on_gui_click,function(event) local index = event.player_index if event.element.name == "mode" then switchMode(index) end end)
require "util" require "stdlib/log/logger" require "stdlib/gui/gui" require "src/gui" require "src/move" require "src/armor" require "src/test" LOG = Logger.new("MagneticFloor") function print(stuff) game.players[1].print(stuff) end function printBool(stuff) game.players[1].print(tostring(stuff)) end function setup() global.hoverboard = global.hoverboard or {} end function activateEquipment(index) global.hoverboard[index].inserted = true global.hoverboard[index].active = false UI.initialize(index) end function deactivateEquipment(index) if global.hoverboard[index].inserted == true then global.hoverboard[index].inserted = false UI.destroy(index) end end function createPlayerMag(i) local entity = { charge = 0, active = false, inserted = false, } global.hoverboard[i] = entity end script.on_init(setup) script.on_event(defines.events.on_player_joined_game, function(event) createPlayerMag(event.player_index) end) script.on_event(defines.events.on_tick, function(event) local n = 0 for k,v in pairs(game.players) do if global.hoverboard[k] == nil then createPlayerMag(v.index) end if global.hoverboard[k].inserted == true and global.hoverboard[k].active == true then locomotion(k) tileCheck(k) UI.updateStatus(k) end end end) script.on_event(defines.events.on_player_placed_equipment, function(event) local index = event.player_index if getArmor(index) ~= false and event.equipment.name == "hoverboard" then activateEquipment(index) end end) script.on_event(defines.events.on_player_removed_equipment, function(event) local index = event.player_index if getArmor(index) ~= false and event.equipment == "hoverboard" then deactivateEquipment(index) end end) script.on_event(defines.events.on_entity_died, function(event) if event.entity.name == "player" then global.dead = true end end) function switchMode(index) if global.hoverboard[index].inserted == true then if global.hoverboard[index].active == false then global.hoverboard[index].active = true elseif global.hoverboard[index].active == true then global.hoverboard[index].active = false end UI.switchMode(global.hoverboard[index].active,index) end end script.on_event(defines.events.on_gui_click,function(event) local index = event.player_index if event.element.name == "mode" then switchMode(index) end end)
fix a crash when armor isn't equipped
fix a crash when armor isn't equipped
Lua
mit
kiba/Factorio-MagneticFloor,kiba/Factorio-MagneticFloor
ff42b5e61dba3516af89dae42b5abe930b844117
test_scripts/Polices/user_consent_of_Policies/116_ATF_Consent_timestamp.lua
test_scripts/Polices/user_consent_of_Policies/116_ATF_Consent_timestamp.lua
--------------------------------------------------------------------------------------------- -- Requirement summary: -- [Policies] SDL must add a timestamp of the consent in a specific format -- -- Description: -- Format of user consent timestamp added to Local PolicyTable. -- 1. Used preconditions: -- Start SDL and init HMI -- Close default connection -- Overwrite preloaded file to make device not consented -- Connect device -- Register app -- Consent device on HMI -- 2. Performed steps -- Check timestamp format is "<yyyy-mm-dd>T<hh:mm:ss>Z" in LPT -- -- Expected result: -- PoliciesManager must add a timestamp of user consent for the current mobile device into “time_stamp” field in the format of "<yyyy-mm-dd>T<hh:mm:ss>Z". --------------------------------------------------------------------------------------------- --[[ General configuration parameters ]] config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0" --[[ Required Shared libraries ]] local commonSteps = require('user_modules/shared_testcases/commonSteps') local commonFunctions = require('user_modules/shared_testcases/commonFunctions') local testCasesForPolicyTableSnapshot = require('user_modules/shared_testcases/testCasesForPolicyTableSnapshot') local testCasesForPolicyTable = require('user_modules/shared_testcases/testCasesForPolicyTable') --[[ General Precondition before ATF start ]] commonSteps:DeleteLogsFileAndPolicyTable() --[[ General Settings for configuration ]] Test = require('connecttest') require('cardinalities') require('user_modules/AppTypes') --[[ Preconditions ]] commonFunctions:newTestCasesGroup("Preconditions") function Test:Precondition_trigger_getting_device_consent() testCasesForPolicyTable:trigger_getting_device_consent(self, config.application1.registerAppInterfaceParams.appName, config.deviceMAC) end function Test:Precondition_PoliciesManager_changes_UP_TO_DATE() testCasesForPolicyTable:flow_SUCCEESS_EXTERNAL_PROPRIETARY(self) end --[[ Test ]] commonFunctions:newTestCasesGroup("Test") function Test:TimeStamp_in_userConsentRecords_table() local errorFlag = false local ErrorMessage = "" local TimeStamp_InUserConsentRecordsTable = testCasesForPolicyTableSnapshot:get_data_from_PTS("device_data."..config.deviceMAC..".user_consent_records.device.time_stamp") if type(TimeStamp_InUserConsentRecordsTable) ~= 'string' then self:FailTestCase("TimeStamp in user_consent_records came wrong") end if (TimeStamp_InUserConsentRecordsTable ~= nil ) then commonFunctions:userPrint(33, "TimeStamp in user_consent_records " .. tostring(TimeStamp_InUserConsentRecordsTable)) local Date, separatorFirst, Time, separatorSecond = TimeStamp_InUserConsentRecordsTable:match("([%d-]-)([T])([%d:]-)([Z])") -- Get current date local CurrentDateCommand = assert( io.popen( "date +%Y-%m-%d " , 'r')) local CurrentDate = CurrentDateCommand:read( '*l' ) if Date then if Date ~= CurrentDate then ErrorMessage = ErrorMessage .. "Date in user_consent_records is not equal to current date. Date from user_consent_records is " .. tostring(Date) .. ", current date is " .. tostring(CurrentDate) .. ". \n" errorFlag = true end else ErrorMessage = ErrorMessage .."Date in user_consent_records is wrong or absent. \n" errorFlag = true end -- Get current time if Time then local CurrentTimeCommand = assert( io.popen( "date +%H:%M" , 'r')) local TimeForPermissionConsentValue = CurrentTimeCommand:read( '*l' ) local CurrentTimeSeconds = assert( io.popen( "date +%H:%M:%S" , 'r')) local TimeToCheckSeconds = CurrentTimeSeconds:read( '*l' ) --TODO(istoimenova): Should be taken in account difference of ~2sec. In case time SDL: 12:21:59 and local time 12:22:01 will return error if( string.sub(Time,1,string.len(TimeForPermissionConsentValue)) ~= TimeForPermissionConsentValue ) then ErrorMessage = ErrorMessage .. "Time in user_consent_records is not equal to time of device consent. Time from user_consent_records is " .. tostring(Time) .. ", time to check is " .. tostring(TimeToCheckSeconds) .. " +- 1 second. \n" errorFlag = true end else ErrorMessage = ErrorMessage .."Time in user_consent_records is wrong or absent. \n" errorFlag = true end if separatorFirst then if separatorFirst ~= "T" then ErrorMessage = ErrorMessage .. "Separator 'T' between date and time in user_consent_records is not equal to 'T'. Separator from user_consent_records is " .. tostring(separatorFirst) .. ". \n" errorFlag = true end else ErrorMessage = ErrorMessage .."Separator 'T' between date and time in user_consent_records is wrong or absent. \n" errorFlag = true end if separatorSecond then if separatorSecond ~= "Z" then ErrorMessage = ErrorMessage .. "Separator 'Z' after date and time in user_consent_records is not equal to 'Z'. Separator from user_consent_records is " .. tostring(separatorSecond) .. ". \n" errorFlag = true end else ErrorMessage = ErrorMessage .."Separator 'Z' after date and time in user_consent_records is wrong or absent. \n" errorFlag = true end else ErrorMessage = ErrorMessage .. "TimeStamp is absent or empty in user_consent_records. \n" errorFlag = true end if errorFlag == true then self:FailTestCase(ErrorMessage) end end --[[ Postconditions ]] commonFunctions:newTestCasesGroup("Postconditions") function Test.Postcondition_StopSDL() StopSDL() end return Test
--------------------------------------------------------------------------------------------- -- Requirement summary: -- [Policies] SDL must add a timestamp of the consent in a specific format -- -- Description: -- Format of user consent timestamp added to Local PolicyTable. -- 1. Used preconditions: -- Start SDL and init HMI -- Close default connection -- Overwrite preloaded file to make device not consented -- Connect device -- Register app -- Consent device on HMI -- 2. Performed steps -- Check timestamp format is "<yyyy-mm-dd>T<hh:mm:ss>Z" in LPT -- -- Expected result: -- PoliciesManager must add a timestamp of user consent for the current mobile device into “time_stamp” field in the format of "<yyyy-mm-dd>T<hh:mm:ss>Z". --------------------------------------------------------------------------------------------- --[[ General configuration parameters ]] config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0" --[[ Required Shared libraries ]] local commonSteps = require('user_modules/shared_testcases/commonSteps') local commonFunctions = require('user_modules/shared_testcases/commonFunctions') local testCasesForPolicyTableSnapshot = require('user_modules/shared_testcases/testCasesForPolicyTableSnapshot') local testCasesForPolicyTable = require('user_modules/shared_testcases/testCasesForPolicyTable') --[[ Local Variables ]] local TimeToCheckSeconds = nil --[[ Local Functions ]] local function split(s, delimiter) local result = {}; for match in (s..delimiter):gmatch("(.-)"..delimiter) do table.insert(result, match); end return result; end local function clock_to_sec(c) local t = split(c, ":") return t[1] * 60 * 60 + t[2] * 60 + t[3] end --[[ General Precondition before ATF start ]] commonFunctions:SDLForceStop() commonSteps:DeleteLogsFileAndPolicyTable() --[[ General Settings for configuration ]] Test = require('connecttest') require('cardinalities') require('user_modules/AppTypes') --[[ Preconditions ]] commonFunctions:newTestCasesGroup("Preconditions") function Test:Precondition_trigger_getting_device_consent() testCasesForPolicyTable:trigger_getting_device_consent(self, config.application1.registerAppInterfaceParams.appName, config.deviceMAC) local CurrentTimeSeconds = assert( io.popen( "date +%H:%M:%S" , 'r')) TimeToCheckSeconds = CurrentTimeSeconds:read( '*l' ) end function Test:Precondition_PoliciesManager_changes_UP_TO_DATE() testCasesForPolicyTable:flow_SUCCEESS_EXTERNAL_PROPRIETARY(self) end --[[ Test ]] commonFunctions:newTestCasesGroup("Test") function Test:TimeStamp_in_userConsentRecords_table() local errorFlag = false local ErrorMessage = "" local TimeStamp_InUserConsentRecordsTable = testCasesForPolicyTableSnapshot:get_data_from_PTS("device_data."..config.deviceMAC..".user_consent_records.device.time_stamp") if type(TimeStamp_InUserConsentRecordsTable) ~= 'string' then self:FailTestCase("TimeStamp in user_consent_records came wrong") end if (TimeStamp_InUserConsentRecordsTable ~= nil ) then commonFunctions:userPrint(33, "TimeStamp in user_consent_records " .. tostring(TimeStamp_InUserConsentRecordsTable)) local Date, separatorFirst, Time, separatorSecond = TimeStamp_InUserConsentRecordsTable:match("([%d-]-)([T])([%d:]-)([Z])") -- Get current date local CurrentDateCommand = assert( io.popen( "date +%Y-%m-%d " , 'r')) local CurrentDate = CurrentDateCommand:read( '*l' ) if Date then if Date ~= CurrentDate then ErrorMessage = ErrorMessage .. "Date in user_consent_records is not equal to current date. Date from user_consent_records is " .. tostring(Date) .. ", current date is " .. tostring(CurrentDate) .. ". \n" errorFlag = true end else ErrorMessage = ErrorMessage .."Date in user_consent_records is wrong or absent. \n" errorFlag = true end -- Get current time if Time then print("Snapshot: " .. tostring(Time)) print("Current: " .. tostring(TimeToCheckSeconds)) local diff = math.abs(clock_to_sec(TimeToCheckSeconds) - clock_to_sec(Time)) print("Diff: " .. diff .. " s") if diff > 1 then ErrorMessage = ErrorMessage .. "Time in user_consent_records is not equal to time of device consent. Time from user_consent_records is " .. tostring(Time) .. ", time to check is " .. tostring(TimeToCheckSeconds) .. " +- 1 second. \n" errorFlag = true end else ErrorMessage = ErrorMessage .."Time in user_consent_records is wrong or absent. \n" errorFlag = true end if separatorFirst then if separatorFirst ~= "T" then ErrorMessage = ErrorMessage .. "Separator 'T' between date and time in user_consent_records is not equal to 'T'. Separator from user_consent_records is " .. tostring(separatorFirst) .. ". \n" errorFlag = true end else ErrorMessage = ErrorMessage .."Separator 'T' between date and time in user_consent_records is wrong or absent. \n" errorFlag = true end if separatorSecond then if separatorSecond ~= "Z" then ErrorMessage = ErrorMessage .. "Separator 'Z' after date and time in user_consent_records is not equal to 'Z'. Separator from user_consent_records is " .. tostring(separatorSecond) .. ". \n" errorFlag = true end else ErrorMessage = ErrorMessage .."Separator 'Z' after date and time in user_consent_records is wrong or absent. \n" errorFlag = true end else ErrorMessage = ErrorMessage .. "TimeStamp is absent or empty in user_consent_records. \n" errorFlag = true end if errorFlag == true then self:FailTestCase(ErrorMessage) end end --[[ Postconditions ]] commonFunctions:newTestCasesGroup("Postconditions") function Test.Postcondition_StopSDL() StopSDL() end return Test
Fix issues
Fix issues
Lua
bsd-3-clause
smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts
f2daf51d17f696bebf6db59a53e26eee579bb5a7
spec/pack_spec.lua
spec/pack_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 test_env.unload_luarocks() local extra_rocks = { "/luasec-0.6-1.rockspec", "/luassert-1.7.0-1.src.rock", "/luasocket-3.0rc1-2.src.rock", "/luasocket-3.0rc1-2.rockspec", "/say-1.2-1.src.rock", "/say-1.0-1.src.rock" } describe("LuaRocks pack tests #blackbox #b_pack", function() before_each(function() test_env.setup_specs(extra_rocks) end) it("LuaRocks pack with no flags/arguments", function() assert.is_false(run.luarocks_bool("pack")) end) it("LuaRocks pack basic", function() assert.is_true(run.luarocks_bool("pack luacov")) assert.is_true(test_env.remove_files(lfs.currentdir(), "luacov-")) end) it("LuaRocks pack invalid rockspec", function() assert.is_false(run.luarocks_bool("pack " .. testing_paths.testing_dir .. "/testfiles/invaild_validate-args-1.5.4-1.rockspec")) end) it("LuaRocks pack not installed rock", function() assert.is_false(run.luarocks_bool("pack cjson")) end) it("LuaRocks pack not installed rock from non existing manifest", function() assert.is_false(run.luarocks_bool("pack /non/exist/temp.manif")) end) it("LuaRocks pack specify which version of rock", function() assert.is_true(run.luarocks_bool("install say 1.2")) assert.is_true(run.luarocks_bool("install luassert")) assert.is_true(run.luarocks_bool("install say 1.0")) assert.is_false(run.luarocks_bool("pack say")) end) it("LuaRocks pack src", function() assert.is_true(run.luarocks_bool("install luasec " .. test_env.OPENSSL_DIRS)) assert.is_true(run.luarocks_bool("download --rockspec luasocket 3.0rc1-2")) assert.is_true(run.luarocks_bool("pack luasocket-3.0rc1-2.rockspec")) assert.is_true(test_env.remove_files(lfs.currentdir(), "luasocket-")) 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 test_env.unload_luarocks() local extra_rocks = { "/luasec-0.6-1.rockspec", "/luassert-1.7.0-1.src.rock", "/luasocket-3.0rc1-2.src.rock", "/luasocket-3.0rc1-2.rockspec", "/say-1.2-1.src.rock", "/say-1.0-1.src.rock" } describe("LuaRocks pack tests #blackbox #b_pack", function() before_each(function() test_env.setup_specs(extra_rocks) end) it("LuaRocks pack with no flags/arguments", function() assert.is_false(run.luarocks_bool("pack")) end) it("LuaRocks pack basic", function() assert.is_true(run.luarocks_bool("pack luacov")) assert.is_true(test_env.remove_files(lfs.currentdir(), "luacov-")) end) it("LuaRocks pack invalid rockspec", function() assert.is_false(run.luarocks_bool("pack " .. testing_paths.testing_dir .. "/testfiles/invaild_validate-args-1.5.4-1.rockspec")) end) it("LuaRocks pack not installed rock", function() assert.is_false(run.luarocks_bool("pack cjson")) end) it("LuaRocks pack not installed rock from non existing manifest", function() assert.is_false(run.luarocks_bool("pack /non/exist/temp.manif")) end) it("LuaRocks pack detects latest version version of rock", function() assert.is_true(run.luarocks_bool("install say 1.2")) assert.is_true(run.luarocks_bool("install luassert")) assert.is_true(run.luarocks_bool("install say 1.0")) assert.is_truthy(lfs.attributes("say-1.2-1.all.rock")) assert.is_true(test_env.remove_files(lfs.currentdir(), "say-")) end) it("LuaRocks pack src", function() assert.is_true(run.luarocks_bool("install luasec " .. test_env.OPENSSL_DIRS)) assert.is_true(run.luarocks_bool("download --rockspec luasocket 3.0rc1-2")) assert.is_true(run.luarocks_bool("pack luasocket-3.0rc1-2.rockspec")) assert.is_true(test_env.remove_files(lfs.currentdir(), "luasocket-")) end) end)
Fix test to match new behavior of `pack`.
Fix test to match new behavior of `pack`.
Lua
mit
luarocks/luarocks,xpol/luainstaller,xpol/luarocks,xpol/luainstaller,robooo/luarocks,xpol/luainstaller,xpol/luavm,robooo/luarocks,tarantool/luarocks,robooo/luarocks,xpol/luarocks,robooo/luarocks,xpol/luainstaller,keplerproject/luarocks,keplerproject/luarocks,luarocks/luarocks,xpol/luavm,xpol/luarocks,keplerproject/luarocks,xpol/luavm,xpol/luarocks,tarantool/luarocks,xpol/luavm,keplerproject/luarocks,xpol/luavm,tarantool/luarocks,luarocks/luarocks
0af71449cbc6b600e54e20400debe7478d3dee93
lib/core/test/measurement/general.lua
lib/core/test/measurement/general.lua
local U = require "togo.utility" local O = require "Quanta.Object" local Measurement = require "Quanta.Measurement" function make_test(text, item_index, value, unit, of, approximation, certain) return { text = text, item_index = item_index, value = value, unit = unit, of = U.optional(of, 0), approximation = U.optional(approximation, 0), certain = U.optional(certain, true), } end local translation_tests = { make_test("2" , 0, 2, "" ), make_test("2u" , 0, 2, "u" ), make_test("2g" , 0, 2, "g" ), make_test("2ml", 0, 2, "ml"), make_test("1/2g", 2, 2, "g", 1), make_test("1/2ml/3g", 3, 3, "g", 1), make_test("1/2ml/3g/4mg", 3, 3, "g", 1), make_test("1µg/2mg", 2, 2, "mg"), make_test("2mg/1µg", 1, 2, "mg"), make_test("?1/2", 2, 2, ""), make_test("~1/2", 2, 2, ""), make_test("~~1/~2", 2, 2, "", 0, -1, false), make_test("?1/~~2", 2, 2, "", 0, -2, false), make_test("G~1/~~~2", 2, 2, "", 0, -3, false), make_test("G~^1/?2", 2, 2, "", 0), } function do_translation_test(t) local o = O.create(t.text) U.assert(o ~= nil) local value = t.value local unit = Measurement.get_unit(t.unit) U.assert(unit) local item = t.item_index > 0 and O.child_at(o, t.item_index) or o U.assert(Measurement.get_unit(O.unit_hash(item)) == unit) local m = Measurement(o) U.assert(m.value == value) U.assert(m.qindex == unit.quantity.index) U.assert(m.magnitude == unit.magnitude) U.assert(m.of == t.of) U.assert(m.approximation == t.approximation) U.assert(m.certain == t.certain) U.assert(m == Measurement(t.value, t.unit, t.of, t.approximation, t.certain)) end function main() do local m = Measurement(1) U.assert( m.value == 1 and m.qindex == Measurement.QuantityIndex.dimensionless and m.magnitude == 0 ) m:rebase("g") U.assert( m.value == 1 and m.qindex == Measurement.QuantityIndex.mass and m.magnitude == 0 ) m:rebase("mg") U.assert(m.value == 1000 and m.magnitude == -3) m:rebase("kg") U.assert(m.value == 0.001 and m.magnitude == 3) m:rebase("g") U.assert(m.value == 1 and m.magnitude == 0) m:rebase("ml") U.assert(m.value == 1 and m.magnitude == 0) m:set(12, "µg") U.assert(m.value == 12 and m.magnitude == -6) m:rebase("g") U.assert(m.value == 0.000012 and m.magnitude == 0) end for _, t in pairs(translation_tests) do do_translation_test(t) end return 0 end return main()
local U = require "togo.utility" local O = require "Quanta.Object" local Measurement = require "Quanta.Measurement" function make_test(text, item_index, value, unit, of, approximation, certain) return { text = text, item_index = item_index, value = value, unit = unit, of = U.optional(of, 0), approximation = U.optional(approximation, 0), certain = U.optional(certain, true), } end local translation_tests = { make_test("2" , 0, 2, "" ), make_test("2u" , 0, 2, "u" ), make_test("2g" , 0, 2, "g" ), make_test("2ml", 0, 2, "ml"), make_test("1/2g", 2, 2, "g", 1), make_test("1/2ml/3g", 3, 3, "g", 1), make_test("1/2ml/3g/4mg", 3, 3, "g", 1), make_test("1µg/2mg", 2, 2, "mg"), make_test("2mg/1µg", 1, 2, "mg"), make_test("?1/2", 2, 2, ""), make_test("~1/2", 2, 2, ""), make_test("~~1/~2", 2, 2, "", 0, -1), make_test("?1/~~2", 2, 2, "", 0, -2), make_test("G~1/~~~2", 2, 2, "", 0, -3), make_test("G~^1/?2", 2, 2, "", 0, 0, false), } function do_translation_test(t) local o = O.create(t.text) U.assert(o ~= nil) local value = t.value local unit = Measurement.get_unit(t.unit) U.assert(unit) local item = t.item_index > 0 and O.child_at(o, t.item_index) or o U.assert(Measurement.get_unit(O.unit_hash(item)) == unit) local m = Measurement(o) U.assert(m.value == value) U.assert(m.qindex == unit.quantity.index) U.assert(m.magnitude == unit.magnitude) U.assert(m.of == t.of) U.assert(m.approximation == t.approximation) U.assert(m.certain == t.certain) U.assert(m == Measurement(t.value, t.unit, t.of, t.approximation, t.certain)) end function main() do local m = Measurement(1) U.assert( m.value == 1 and m.qindex == Measurement.QuantityIndex.dimensionless and m.magnitude == 0 ) m:rebase("g") U.assert( m.value == 1 and m.qindex == Measurement.QuantityIndex.mass and m.magnitude == 0 ) m:rebase("mg") U.assert(m.value == 1000 and m.magnitude == -3) m:rebase("kg") U.assert(m.value == 0.001 and m.magnitude == 3) m:rebase("g") U.assert(m.value == 1 and m.magnitude == 0) m:rebase("ml") U.assert(m.value == 1 and m.magnitude == 0) m:set(12, "µg") U.assert(m.value == 12 and m.magnitude == -6) m:rebase("g") U.assert(m.value == 0.000012 and m.magnitude == 0) end for _, t in pairs(translation_tests) do do_translation_test(t) end return 0 end return main()
lib/core/test/measurement/general.lua: fixed certainty in translation tests.
lib/core/test/measurement/general.lua: fixed certainty in translation tests.
Lua
mit
komiga/quanta,komiga/quanta,komiga/quanta
4d7744c3eb2518f1fbd50d1b57d97cc8d7c24b35
Modules/Events/Promise.lua
Modules/Events/Promise.lua
--- Promises, but without error handling as this screws with stack traces, using Roblox signals -- @classmod Promise -- See: https://promisesaplus.com/ local require = require(game:GetService("ReplicatedStorage"):WaitForChild("Nevermore")) local Maid = require("Maid") local function _isSignal(value) if typeof(value) == "RBXScriptSignal" then return true elseif type(value) == "table" and type(value.Connect) == "function" then return true end return false end local function isPromise(value) if type(value) == "table" and value.ClassName == "Promise" then return true end return false end local Promise = {} Promise.ClassName = "Promise" Promise.__index = Promise Promise.CatchErrors = false -- A+ compliance if true Promise.IsPromise = isPromise --- Construct a new promise -- @constructor Promise.new() -- @param value, default nil -- @treturn Promise function Promise.new(value) local self = setmetatable({}, Promise) self._pendingMaid = Maid.new() self:_promisify(value) return self end function Promise.resolved(...) return Promise.new():Resolve(...) end function Promise.rejected(...) return Promise.new():Reject(...) end --- Returns whether or not the promise is pending -- @treturn bool True if pending, false otherwise function Promise:IsPending() return self._pendingMaid ~= nil end function Promise:IsFulfilled() return self._fulfilled ~= nil end function Promise:IsRejected() return self._rejected ~= nil end --- Yield until the promise is complete function Promise:Wait() if self._fulfilled then return unpack(self._fulfilled) elseif self._rejected then return unpack(self._rejected) else local result local bindable = Instance.new("BindableEvent") self:Then(function(...) result = {...} bindable:Fire(true) end, function(...) result = {...} bindable:Fire(false) end) local ok = bindable.Event:Wait() bindable:Destroy() if not ok then error(tostring(result[1]), 2) end return unpack(result) end end --- -- Resolves a promise -- @return self function Promise:Resolve(...) local valueLength = select("#", ...) -- Treat tuples as an array under A+ compliance if valueLength > 1 then self:Fulfill(...) return self end local value = ... if self == value then self:Reject("TypeError: Resolved to self") return self end if isPromise(value) then value:Then(function(...) self:Fulfill(...) end, function(...) self:Reject(...) end) return self end -- Thenable like objects if type(value) == "table" and type(value.Then) == "function" then value:Then(self:_getResolveReject()) return self end self:Fulfill(value) return self end --- Fulfills the promise with the value -- @param ... Params to fulfill with -- @return self function Promise:Fulfill(...) if not self:IsPending() then return end self._fulfilled = {...} self:_endPending() return self end --- Rejects the promise with the value given -- @param ... Params to reject with -- @return self function Promise:Reject(...) if not self:IsPending() then return end self._rejected = {...} self:_endPending() return self end --- Handlers when promise is fulfilled/rejected. It takes up to two arguments, callback functions -- for the success and failure cases of the Promise -- @tparam[opt=nil] function onFulfilled Called when fulfilled with parameters -- @tparam[opt=nil] function onRejected Called when rejected with parameters -- @treturn Promise function Promise:Then(onFulfilled, onRejected) local returnPromise = Promise.new() if self._pendingMaid then self._pendingMaid:GiveTask(function() self:_executeThen(returnPromise, onFulfilled, onRejected) end) else self:_executeThen(returnPromise, onFulfilled, onRejected) end return returnPromise end function Promise:Finally(func) return self:Then(func, func) end --- Catch errors from the promise -- @treturn Promise function Promise:Catch(func) return self:Then(nil, func) end --- Rejects the current promise. -- Utility left for Maid task -- @treturn nil function Promise:Destroy() self:Reject() end --- Modifies values into promises -- @local function Promise:_promisify(value) if type(value) == "function" then self:_promisfyYieldingFunction(value) elseif _isSignal(value) then self:_promisfySignal(value) end end function Promise:_promisfySignal(signal) if not self._pendingMaid then return end self._pendingMaid:GiveTask(signal:Connect(function(...) self:Fulfill(...) end)) return end function Promise:_promisfyYieldingFunction(yieldingFunction) if not self._pendingMaid then return end local maid = Maid.new() -- Hack to spawn new thread fast local bindable = Instance.new("BindableEvent") maid:GiveTask(bindable) maid:GiveTask(bindable.Event:Connect(function() maid:DoCleaning() if self.CatchErrors then local resultList = self:_executeFunc(self, yieldingFunction, {self:_getResolveReject()}) if self:IsPending() then self:Resolve(unpack(resultList)) end else self:Resolve(yieldingFunction(self:_getResolveReject())) end end)) self._pendingMaid:GiveTask(maid) bindable:Fire() end function Promise:_getResolveReject() local called = false local function resolvePromise(...) if called then return end called = true self:Resolve(...) end local function rejectPromise(...) if called then return end called = true self:Reject(...) end return resolvePromise, rejectPromise end function Promise:_executeFunc(returnPromise, func, args) if not self.CatchErrors then return {func(unpack(args))} end local resultList local success, err = pcall(function() resultList = {func(unpack())} end) if not success then returnPromise:Reject(err) end return resultList end function Promise:_executeThen(returnPromise, onFulfilled, onRejected) local resultList if self._fulfilled then if type(onFulfilled) ~= "function" then return returnPromise:Fulfill(unpack(self._fulfilled)) end resultList = self:_executeFunc(returnPromise, onFulfilled, self._fulfilled) elseif self._rejected then if type(onRejected) ~= "function" then return returnPromise:Reject(unpack(self._rejected)) end resultList = self:_executeFunc(returnPromise, onRejected, self._rejected) else error("Internal error, cannot execute while pending") end if resultList and #resultList > 0 then returnPromise:Resolve(unpack(resultList)) end end function Promise:_endPending() local maid = self._pendingMaid self._pendingMaid = nil maid:DoCleaning() end return Promise
--- Promises, but without error handling as this screws with stack traces, using Roblox signals -- @classmod Promise -- See: https://promisesaplus.com/ local require = require(game:GetService("ReplicatedStorage"):WaitForChild("Nevermore")) local Maid = require("Maid") local function _isSignal(value) if typeof(value) == "RBXScriptSignal" then return true elseif type(value) == "table" and type(value.Connect) == "function" then return true end return false end local function isPromise(value) if type(value) == "table" and value.ClassName == "Promise" then return true end return false end local Promise = {} Promise.ClassName = "Promise" Promise.__index = Promise Promise.CatchErrors = false -- A+ compliance if true Promise.IsPromise = isPromise --- Construct a new promise -- @constructor Promise.new() -- @param value, default nil -- @treturn Promise function Promise.new(value) local self = setmetatable({}, Promise) self._pendingMaid = Maid.new() self:_promisify(value) return self end function Promise.resolved(...) return Promise.new():Resolve(...) end function Promise.rejected(...) return Promise.new():Reject(...) end --- Returns whether or not the promise is pending -- @treturn bool True if pending, false otherwise function Promise:IsPending() return self._pendingMaid ~= nil end function Promise:IsFulfilled() return self._fulfilled ~= nil end function Promise:IsRejected() return self._rejected ~= nil end --- Yield until the promise is complete function Promise:Wait() if self._fulfilled then return unpack(self._fulfilled) elseif self._rejected then return error(tostring(self._rejected[1]), 2) else local result local bindable = Instance.new("BindableEvent") self:Then(function(...) result = {...} bindable:Fire() end, function(...) result = {...} bindable:Fire() end) bindable.Event:Wait() bindable:Destroy() if self:IsRejected() then return error(tostring(result[1]), 2) end return unpack(result) end end --- -- Resolves a promise -- @return self function Promise:Resolve(...) local valueLength = select("#", ...) -- Treat tuples as an array under A+ compliance if valueLength > 1 then self:Fulfill(...) return self end local value = ... if self == value then self:Reject("TypeError: Resolved to self") return self end if isPromise(value) then value:Then(function(...) self:Fulfill(...) end, function(...) self:Reject(...) end) return self end -- Thenable like objects if type(value) == "table" and type(value.Then) == "function" then value:Then(self:_getResolveReject()) return self end self:Fulfill(value) return self end --- Fulfills the promise with the value -- @param ... Params to fulfill with -- @return self function Promise:Fulfill(...) if not self:IsPending() then return end self._fulfilled = {...} self:_endPending() return self end --- Rejects the promise with the value given -- @param ... Params to reject with -- @return self function Promise:Reject(...) if not self:IsPending() then return end self._rejected = {...} self:_endPending() return self end --- Handlers when promise is fulfilled/rejected. It takes up to two arguments, callback functions -- for the success and failure cases of the Promise -- @tparam[opt=nil] function onFulfilled Called when fulfilled with parameters -- @tparam[opt=nil] function onRejected Called when rejected with parameters -- @treturn Promise function Promise:Then(onFulfilled, onRejected) local returnPromise = Promise.new() if self._pendingMaid then self._pendingMaid:GiveTask(function() self:_executeThen(returnPromise, onFulfilled, onRejected) end) else self:_executeThen(returnPromise, onFulfilled, onRejected) end return returnPromise end function Promise:Finally(func) return self:Then(func, func) end --- Catch errors from the promise -- @treturn Promise function Promise:Catch(func) return self:Then(nil, func) end --- Rejects the current promise. -- Utility left for Maid task -- @treturn nil function Promise:Destroy() self:Reject() end --- Modifies values into promises -- @local function Promise:_promisify(value) if type(value) == "function" then self:_promisfyYieldingFunction(value) elseif _isSignal(value) then self:_promisfySignal(value) end end function Promise:_promisfySignal(signal) if not self._pendingMaid then return end self._pendingMaid:GiveTask(signal:Connect(function(...) self:Fulfill(...) end)) return end function Promise:_promisfyYieldingFunction(yieldingFunction) if not self._pendingMaid then return end local maid = Maid.new() -- Hack to spawn new thread fast local bindable = Instance.new("BindableEvent") maid:GiveTask(bindable) maid:GiveTask(bindable.Event:Connect(function() maid:DoCleaning() if self.CatchErrors then local resultList = self:_executeFunc(self, yieldingFunction, {self:_getResolveReject()}) if self:IsPending() then self:Resolve(unpack(resultList)) end else self:Resolve(yieldingFunction(self:_getResolveReject())) end end)) self._pendingMaid:GiveTask(maid) bindable:Fire() end function Promise:_getResolveReject() local called = false local function resolvePromise(...) if called then return end called = true self:Resolve(...) end local function rejectPromise(...) if called then return end called = true self:Reject(...) end return resolvePromise, rejectPromise end function Promise:_executeFunc(returnPromise, func, args) if not self.CatchErrors then return {func(unpack(args))} end local resultList local success, err = pcall(function() resultList = {func(unpack())} end) if not success then returnPromise:Reject(err) end return resultList end function Promise:_executeThen(returnPromise, onFulfilled, onRejected) local resultList if self._fulfilled then if type(onFulfilled) ~= "function" then return returnPromise:Fulfill(unpack(self._fulfilled)) end resultList = self:_executeFunc(returnPromise, onFulfilled, self._fulfilled) elseif self._rejected then if type(onRejected) ~= "function" then return returnPromise:Reject(unpack(self._rejected)) end resultList = self:_executeFunc(returnPromise, onRejected, self._rejected) else error("Internal error, cannot execute while pending") end if resultList and #resultList > 0 then returnPromise:Resolve(unpack(resultList)) end end function Promise:_endPending() local maid = self._pendingMaid self._pendingMaid = nil maid:DoCleaning() end return Promise
Fix :Wait() rejection state
Fix :Wait() rejection state
Lua
mit
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
bf51af535c554b9d4d11fe8e7d809bbf774cb9f5
Modules/Events/Promise.lua
Modules/Events/Promise.lua
--- Promises, but without error handling as this screws with stack traces, using Roblox signals -- @module Promise -- @author Quenty local ReplicatedStorage = game:GetService("ReplicatedStorage") local NevermoreEngine = require(ReplicatedStorage:WaitForChild("NevermoreEngine")) local LoadCustomLibrary = NevermoreEngine.LoadLibrary local MakeMaid = LoadCustomLibrary("Maid").MakeMaid local Signal = LoadCustomLibrary("Signal") local function IsCallable(Value) if type(Value) == "table" then local Metatable = getmetatable(Value) return Metatable and type(Metatable.__call) == "function" end return type(Value) == "function" end local Promise = {} Promise.ClassName = "Promise" Promise.__index = Promise local function IsAPromise(Value) if type(Value) == "table" and getmetatable(Value) == Promise then return true end return false end local function IsSignal(Value) if type(Value) == "table" and Value.Connect then return true end return false end function Promise.new(Value) local self = setmetatable({}, Promise) self.PendingMaid = MakeMaid() self:Promisify(Value) return self end function Promise.First(...) local Promise2 = Promise.new() local function Syncronize(Method) return function(...) Promise2[Method](Promise2, ...) end end for _, Promise in pairs({...}) do Promise:Then(Syncronize("Fulfill"), Syncronize("Reject")) end return Promise2 end function Promise.All(...) local RemainingCount = select("#", ...) local Promise2 = Promise.new() local Results = {} local AllFuilfilled = true local function Syncronize(Index, IsFullfilled) return function(Value) AllFuilfilled = AllFuilfilled and IsFullfilled Results[Index] = Value RemainingCount = RemainingCount - 1 if RemainingCount == 0 then local Method = AllFuilfilled and "Fulfill" or "Reject" Promise2[Method](Promise2, Results) end end end for Index, Item in pairs({...}) do Item:Then(Syncronize(Index, true), Syncronize(Index, false)) end return Promise2 end function Promise:IsPending() return self.PendingMaid ~= nil end --- Modifies values into promises function Promise:Promisify(Value) if IsCallable(Value) then self:_promisfyYieldingFunction(Value) elseif IsSignal(Value) then self:_promisfySignal(Signal) end end function Promise:_promisfySignal(Signal) if not self.PendingMaid then return end local Maid = MakeMaid() Maid:GiveTask(Signal:Connect(function(...) self:Fulfill(...) end)) self.PendingMaid:GiveTask(Maid) return end function Promise:_promisfyYieldingFunction(YieldingFunction) if not self.PendingMaid then return end local Maid = MakeMaid() -- Hack to spawn new thread fast local BindableEvent = Instance.new("BindableEvent") Maid:GiveTask(BindableEvent) Maid:GiveTask(BindableEvent.Event:Connect(function() Maid:DoCleaning() self:Resolve(YieldingFunction(self:_getResolveReject())) end)) self.PendingMaid:GiveTask(Maid) BindableEvent:Fire() end --- -- Resolves a promise function Promise:Resolve(Value) if self == Value then self:Reject("TypeError: Resolved to self") return end if IsAPromise(Value) then Value:Then(function(...) self:Fulfill(...) end, function(...) self:Reject(...) end) return end -- Thenable like objects if type(Value) == "table" and IsCallable(Value.Then) then Value:Then(self:_getResolveReject()) return end self:Fulfill(Value) end function Promise:Fulfill(...) if not self:IsPending() then return end self.Fulfilled = {...} self:_endPending() end function Promise:Reject(...) if not self:IsPending() then return end self.Rejected = {...} self:_endPending() end function Promise:Then(OnFulfilled, OnRejected) local ReturnPromise = Promise.new() if self.PendingMaid then self.PendingMaid:GiveTask(function() self:_executeThen(ReturnPromise, OnFulfilled, OnRejected) end) else self:_executeThen(ReturnPromise, OnFulfilled, OnRejected) end return ReturnPromise end function Promise:_getResolveReject() local Called = false local function ResolvePromise(Value) if Called then return end Called = true self:Resolve(Value) end local function RejectPromise(Reason) if Called then return end Called = true self:Reject(Reason) end return ResolvePromise, RejectPromise end function Promise:_executeThen(ReturnPromise, OnFulfilled, OnRejected) local Results if self.Fulfilled then if IsCallable(OnFulfilled) then Results = {OnFulfilled(unpack(self.Fulfilled))} else ReturnPromise:Fulfill(unpack(self.Fulfilled)) end elseif self.Rejected then if IsCallable(OnRejected) then Results = {OnRejected(unpack(self.Rejected))} else ReturnPromise:Rejected(unpack(self.Rejected)) end else error("Internal error, cannot execute while pending") end if Results and #Results > 0 then ReturnPromise:Resolve(Results[1]) end end function Promise:_endPending() local Maid = self.PendingMaid self.PendingMaid = nil Maid:DoCleaning() end function Promise:Destroy() self:Reject() end return Promise
--- Promises, but without error handling as this screws with stack traces, using Roblox signals -- @module Promise -- @author Quenty local ReplicatedStorage = game:GetService("ReplicatedStorage") local NevermoreEngine = require(ReplicatedStorage:WaitForChild("NevermoreEngine")) local LoadCustomLibrary = NevermoreEngine.LoadLibrary local MakeMaid = LoadCustomLibrary("Maid").MakeMaid local function IsCallable(Value) if type(Value) == "function" then return true elseif type(Value) == "table" then local Metatable = getmetatable(Value) return Metatable and type(Metatable.__call) == "function" end end local function IsSignal(Value) if typeof(Value) == "RBXScriptSignal" then return true elseif type(Value) == "table" and IsCallable(Value.Connect) then return true end return false end local Promise = {} Promise.ClassName = "Promise" Promise.__index = Promise local function IsAPromise(Value) if type(Value) == "table" and getmetatable(Value) == Promise then return true end return false end function Promise.new(Value) local self = setmetatable({}, Promise) self.PendingMaid = MakeMaid() self:Promisify(Value) return self end function Promise.First(...) local Promise2 = Promise.new() local function Syncronize(Method) return function(...) Promise2[Method](Promise2, ...) end end for _, Promise in pairs({...}) do Promise:Then(Syncronize("Fulfill"), Syncronize("Reject")) end return Promise2 end function Promise.All(...) local RemainingCount = select("#", ...) local Promise2 = Promise.new() local Results = {} local AllFuilfilled = true local function Syncronize(Index, IsFullfilled) return function(Value) AllFuilfilled = AllFuilfilled and IsFullfilled Results[Index] = Value RemainingCount = RemainingCount - 1 if RemainingCount == 0 then local Method = AllFuilfilled and "Fulfill" or "Reject" Promise2[Method](Promise2, Results) end end end for Index, Item in pairs({...}) do Item:Then(Syncronize(Index, true), Syncronize(Index, false)) end return Promise2 end function Promise:IsPending() return self.PendingMaid ~= nil end --- Modifies values into promises function Promise:Promisify(Value) if IsCallable(Value) then self:_promisfyYieldingFunction(Value) elseif IsSignal(Value) then self:_promisfySignal(Value) end end function Promise:_promisfySignal(Signal) if not self.PendingMaid then return end self.PendingMaid:GiveTask(Signal:Connect(function(...) self:Fulfill(...) end)) return end function Promise:_promisfyYieldingFunction(YieldingFunction) if not self.PendingMaid then return end local Maid = MakeMaid() -- Hack to spawn new thread fast local BindableEvent = Instance.new("BindableEvent") Maid:GiveTask(BindableEvent) Maid:GiveTask(BindableEvent.Event:Connect(function() Maid:DoCleaning() self:Resolve(YieldingFunction(self:_getResolveReject())) end)) self.PendingMaid:GiveTask(Maid) BindableEvent:Fire() end --- -- Resolves a promise function Promise:Resolve(Value) if self == Value then self:Reject("TypeError: Resolved to self") return end if IsAPromise(Value) then Value:Then(function(...) self:Fulfill(...) end, function(...) self:Reject(...) end) return end -- Thenable like objects if type(Value) == "table" and IsCallable(Value.Then) then Value:Then(self:_getResolveReject()) return end self:Fulfill(Value) end function Promise:Fulfill(...) if not self:IsPending() then return end self.Fulfilled = {...} self:_endPending() end function Promise:Reject(...) if not self:IsPending() then return end self.Rejected = {...} self:_endPending() end function Promise:Then(OnFulfilled, OnRejected) local ReturnPromise = Promise.new() if self.PendingMaid then self.PendingMaid:GiveTask(function() self:_executeThen(ReturnPromise, OnFulfilled, OnRejected) end) else self:_executeThen(ReturnPromise, OnFulfilled, OnRejected) end return ReturnPromise end function Promise:_getResolveReject() local Called = false local function ResolvePromise(Value) if Called then return end Called = true self:Resolve(Value) end local function RejectPromise(Reason) if Called then return end Called = true self:Reject(Reason) end return ResolvePromise, RejectPromise end function Promise:_executeThen(ReturnPromise, OnFulfilled, OnRejected) local Results if self.Fulfilled then if IsCallable(OnFulfilled) then Results = {OnFulfilled(unpack(self.Fulfilled))} else ReturnPromise:Fulfill(unpack(self.Fulfilled)) end elseif self.Rejected then if IsCallable(OnRejected) then Results = {OnRejected(unpack(self.Rejected))} else ReturnPromise:Rejected(unpack(self.Rejected)) end else error("Internal error, cannot execute while pending") end if Results and #Results > 0 then ReturnPromise:Resolve(Results[1]) end end function Promise:_endPending() local Maid = self.PendingMaid self.PendingMaid = nil Maid:DoCleaning() end function Promise:Destroy() self:Reject() end return Promise
Update promise specification and fix bugs
Update promise specification and fix bugs
Lua
mit
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
55cb139f3db006292ef8911a6b2ac3b00960fe0e
model.lua
model.lua
local schema = require("lapis.db.schema") local Model = require("lapis.db.model").Model local quizs = require('quiz.all') local model = {} model.ACTIVE = 1 model.CANCELLED = 2 model.FINISHED = 3 function model.create_schema() local types = schema.types schema.create_table("task", { {"id", types.serial}, {"quiz_id", types.foreign_key}, {"name", types.varchar}, {"text", types.varchar}, {"a1", types.varchar}, {"a2", types.varchar}, {"a3", types.varchar}, {"a4", types.varchar}, {"sequence", types.varchar}, -- e.g. "2143" {"selected", types.integer}, "PRIMARY KEY (id)" }) schema.create_table("quiz", { {"id", types.serial}, {"name", types.varchar}, {"user", types.varchar}, {"created_at", types.time}, {"updated_at", types.time}, {"tasks", types.integer}, {"answers", types.integer}, {"right_answers", types.integer}, {"state", types.integer}, {"ip", types.varchar}, {"ua", types.varchar}, "PRIMARY KEY (id)" }) end model.Task = Model:extend("task") model.Quiz = Model:extend("quiz", {timestamp=true}) local table_size = function(t) local size = 0 for _ in pairs(t) do size = size + 1 end return size end local rand_sequence = function() local ttt = {1,2,3,4} local result = '' while #ttt > 0 do local i = table.remove(ttt, math.random(1, #ttt)) result = result .. i end return result end function model.new_quiz(app) local user = app.session.user local quiz_name = app.req.params_post.name local q = quizs[quiz_name] if not q then error(app._("No such quiz found")) end local ip = app.req.headers['X-Forwarded-For'] local ua = app.req.headers['User-Agent'] local quiz = model.Quiz:create({name=quiz_name, user=user, tasks=table_size(q), answers=0, right_answers=0, state=model.ACTIVE, ip=ip, ua=ua}) for task_name, func in pairs(q) do local text, a1, a2, a3, a4 = func(app) model.Task:create({quiz_id=quiz.id, name=task_name, text=text, a1=a1, a2=a2, a3=a3, a4=a4, sequence=rand_sequence(), selected=0}) end return quiz end model.Quiz.all_tasks = function(self) return model.Task:find_all({quiz_id=self.id}) end model.Quiz.fresh_task = function(self) local all_fresh = self:all_tasks() if #all_fresh == 0 then return nil else return all_fresh[math.random(1, #all_fresh)] end end model.Task.quiz = function(self) return model.Quiz:find({id=self.id}) end model.Task.ans = function(self, i) assert(i >= 1) assert(i <= 4) return self['a' .. self.sequence:sub(i, i)] end return model
local schema = require("lapis.db.schema") local Model = require("lapis.db.model").Model local quizs = require('quiz.all') local model = {} model.ACTIVE = 1 model.CANCELLED = 2 model.FINISHED = 3 function model.create_schema() local types = schema.types schema.create_table("task", { {"id", types.serial}, {"quiz_id", types.foreign_key}, {"name", types.varchar}, {"text", types.varchar}, {"a1", types.varchar}, {"a2", types.varchar}, {"a3", types.varchar}, {"a4", types.varchar}, {"sequence", types.varchar}, -- e.g. "2143" {"selected", types.integer}, "PRIMARY KEY (id)" }) schema.create_table("quiz", { {"id", types.serial}, {"name", types.varchar}, {"user", types.varchar}, {"created_at", types.time}, {"updated_at", types.time}, {"tasks", types.integer}, {"answers", types.integer}, {"right_answers", types.integer}, {"state", types.integer}, {"ip", types.varchar}, {"ua", types.varchar}, "PRIMARY KEY (id)" }) end model.Task = Model:extend("task", { quiz = function(self) return model.Quiz:find({id=self.quiz_id}) end, ans_i = function(self, i) assert(i >= 1) assert(i <= 4) return tonumber(self.sequence:sub(i, i)) end, ans = function(self, i) return self['a' .. self:ans_i(i)] end }) model.Quiz = Model:extend("quiz", { timestamp = true, fresh_task = function(self) local all_fresh = model.Task:select( "where quiz_id = ? and selected = ? order by id", self.id, 0) if #all_fresh == 0 then return nil else return all_fresh[math.random(1, #all_fresh)] end end, all_tasks = function(self) return model.Task:select( "where quiz_id = ? order by id", self.id) end }) local table_size = function(t) local size = 0 for _ in pairs(t) do size = size + 1 end return size end local rand_sequence = function() local ttt = {1,2,3,4} local result = '' while #ttt > 0 do local i = table.remove(ttt, math.random(1, #ttt)) result = result .. i end return result end function model.new_quiz(app) local user = app.session.user local quiz_name = app.req.params_post.name local q = quizs[quiz_name] if not q then error(app:_("No such quiz found")) end local ip = app.req.headers['X-Forwarded-For'] or '0.0.0.0' local ua = app.req.headers['User-Agent'] local quiz = model.Quiz:create({name=quiz_name, user=user, tasks=table_size(q), answers=0, right_answers=0, state=model.ACTIVE, ip=ip, ua=ua}) for task_name, func in pairs(q) do local text, a1, a2, a3, a4 = func(app) model.Task:create({quiz_id=quiz.id, name=task_name, text=text, a1=a1, a2=a2, a3=a3, a4=a4, sequence=rand_sequence(), selected=0}) end return quiz end return model
model: move methods to proper place & other fixs
model: move methods to proper place & other fixs
Lua
mit
starius/kodomoquiz
2055255ea43f5d9f8fa2a5f804f83129a43b4686
model.lua
model.lua
-- NOTE: nothing is atomic for now local redis = require "redis" local bcrypt = require "bcrypt" local redismodel = require "redismodel" -- monkey-patch required to make rocks loading work local lr_fetch = require "luarocks.fetch" local lr_path = require "luarocks.path" local lr_deps = require "luarocks.deps" lr_path.configure_paths = function(rockspec) end local cfg = require("lapis.config").get() local pfx = cfg.appname local init_redis, R if ngx and cfg.use_resty_redis then -- hack to make resty-redis return nil -- instead of ngx.null, like redis-lua local null = ngx.null ngx.null = nil local redis = require "resty.redis" ngx.null = null R = redis:new() R:set_timeout(1000) init_redis = function() assert(R:connect(unpack(cfg.redis))) end else local redis = require "redis" R = redis.connect(unpack(cfg.redis)) init_redis = function() end end --- declarations local User = redismodel.new{ redis = R, prefix = pfx, name = "user", } User:add_attribute("email") User:add_index("email") User:add_attribute("fullname") User:add_attribute("password") User:add_attribute("trust_level") local Module = redismodel.new{ redis = R, prefix = pfx, name = "module", } Module:add_attribute("name") Module:add_index("name") Module:add_attribute("version") Module:add_attribute("url") Module:add_attribute("description") local Label = redismodel.new{ redis = R, prefix = pfx, name = "label", } Label:add_attribute("name") Label:add_index("name") redismodel.add_nn_assoc { master = User, slave = Module, assoc_create = "endorse", assoc_remove = "deendorse", assoc_check = "endorses", master_collection = "endorsements", slave_collection = "endorsers", } redismodel.add_nn_assoc { master = Module, slave = Label, assoc_create = "label", assoc_remove = "unlabel", assoc_check = "has_label", master_collection = "labels", slave_collection = "modules", } redismodel.add_nn_assoc { master = Module, slave = Module, assoc_create = "add_dependency", assoc_remove = "remove_dependency", assoc_check = "depends_on", master_collection = "dependencies", slave_collection = "reverse_dependencies", } --- User User.methods.check_password = function(self, pwd) assert(type(pwd) == "string") local hash = self:getattr("pwhash") if not hash then return false end return bcrypt.verify(pwd, hash) end User.methods.get_password = function(self) return nil end User.methods.set_password = function(self, pwd) assert(type(pwd) == "string") local salt = bcrypt.salt(10) local hash = assert(bcrypt.digest(pwd, salt)) self:setattr("pwhash", hash) end User.methods.get_trust_level = function(self) return tonumber(self:getattr("trust_level")) or 0 end User.methods.invalidate_token = function(self) local tk = self:getattr("pwtoken") if tk then self.model.R:del(self.model:rk("_tk_" .. tk)) self:delattr("pwtoken") end end local rand_id = function(n) local r = {} for i=1,n do r[i] = string.char(math.random(65,90)) end return table.concat(r) end User.methods.make_token = function(self) self:invalidate_token() local tk = rand_id(10) self:setattr("pwtoken", tk) local duration = 3600 * 24 * 10 -- 10 days self.model.R:setex(self.model:rk("_tk_" .. tk), duration, self.id) return tk end User.m_methods.resolve_token = function(cls, tk) assert(type(tk) == "string") local id = tonumber(cls.R:get(cls:rk("_tk_" .. tk))) if not id then return nil end local u = cls:new(id) assert(u:getattr("pwtoken") == tk) return u end local _super = User.methods.export User.methods.export = function(self) local r = _super(self) r.pwhash = self:getattr("pwhash") return r end --- Module local load_rockspec = function(rs) if type(rs) == "string" then rs = lr_fetch.load_rockspec(rs) end assert(type(rs) == "table") if type(rs.description) == "table" then rs.url = rs.url or rs.description.homepage rs.description = rs.description.summary or rs.description.detailed end return rs end local _super = Module.m_methods.create Module.m_methods.create = function(cls, t) local rs = t.rockspec and load_rockspec(t.rockspec) if rs then assert(rs.name) end t.name = t.name or (rs and rs.name) _super(cls, t) end Module.methods.update_with_rockspec = function(self, rs, fast) -- -> changed? fast = (fast ~= false) rs = load_rockspec(rs) assert(rs and rs.name and rs.version) assert(rs.name == self:get_name()) local old_version = self:get_version() if old_version then if old_version == rs.version then if fast and self:check_attributes(rs) then return false end elseif lr_deps.compare_versions(old_version, rs.version) then return false end end for k,_ in pairs(self.model.attributes) do if rs[k] then self["set_" .. k](self, rs[k]) end end local old_deps = self:dependencies() for i=1,#old_deps do self:remove_dependency(old_deps[i]) end local new_deps = rs.dependencies or {} for i=1,#new_deps do local m = Module:get_by_name(new_deps[i].name) if m then self:add_dependency(m) end end return true end Module.sort_by_nb_endorsers = { function(self) return {self:nb_endorsers(), self:get_name()} end, function(a, b) return (a[1] == b[1]) and (a[2] < b[2]) or (a[1] > b[1]) end, } --- others local init = function() init_redis() if cfg._name == "development" then if not User:resolve_email("[email protected]") then User:create{ email = "[email protected]", fullname = "John Doe", password = "tagazok", trust_level = 2, } end end end return { User = User, Module = Module, Label = Label, init = init, load_rockspec = load_rockspec, }
-- NOTE: nothing is atomic for now local redis = require "redis" local bcrypt = require "bcrypt" local redismodel = require "redismodel" -- monkey-patch required to make rocks loading work local lr_fetch = require "luarocks.fetch" local lr_path = require "luarocks.path" local lr_deps = require "luarocks.deps" lr_path.configure_paths = function(rockspec) end local cfg = require("lapis.config").get() local pfx = cfg.appname local init_redis, R if ngx and cfg.use_resty_redis then -- hack to make resty-redis return nil -- instead of ngx.null, like redis-lua local null = ngx.null ngx.null = nil local redis = require "resty.redis" ngx.null = null R = redis:new() R:set_timeout(1000) init_redis = function() assert(R:connect(unpack(cfg.redis))) end else local redis = require "redis" R = redis.connect(unpack(cfg.redis)) init_redis = function() end end --- declarations local User = redismodel.new{ redis = R, prefix = pfx, name = "user", } User:add_attribute("email") User:add_index("email") User:add_attribute("fullname") User:add_attribute("password") User:add_attribute("trust_level") local Module = redismodel.new{ redis = R, prefix = pfx, name = "module", } Module:add_attribute("name") Module:add_index("name") Module:add_attribute("version") Module:add_attribute("url") Module:add_attribute("description") local Label = redismodel.new{ redis = R, prefix = pfx, name = "label", } Label:add_attribute("name") Label:add_index("name") redismodel.add_nn_assoc { master = User, slave = Module, assoc_create = "endorse", assoc_remove = "deendorse", assoc_check = "endorses", master_collection = "endorsements", slave_collection = "endorsers", } redismodel.add_nn_assoc { master = Module, slave = Label, assoc_create = "label", assoc_remove = "unlabel", assoc_check = "has_label", master_collection = "labels", slave_collection = "modules", } redismodel.add_nn_assoc { master = Module, slave = Module, assoc_create = "add_dependency", assoc_remove = "remove_dependency", assoc_check = "depends_on", master_collection = "dependencies", slave_collection = "reverse_dependencies", } --- User User.methods.check_password = function(self, pwd) assert(type(pwd) == "string") local hash = self:getattr("pwhash") if not hash then return false end return bcrypt.verify(pwd, hash) end User.methods.get_password = function(self) return nil end User.methods.set_password = function(self, pwd) assert(type(pwd) == "string") local salt = bcrypt.salt(10) local hash = assert(bcrypt.digest(pwd, salt)) self:setattr("pwhash", hash) end User.methods.get_trust_level = function(self) return tonumber(self:getattr("trust_level")) or 0 end User.methods.invalidate_token = function(self) local tk = self:getattr("pwtoken") if tk then self.model.R:del(self.model:rk("_tk_" .. tk)) self:delattr("pwtoken") end end local rand_id = function(n) local r = {} for i=1,n do r[i] = string.char(math.random(65,90)) end return table.concat(r) end User.methods.make_token = function(self) self:invalidate_token() local tk = rand_id(10) self:setattr("pwtoken", tk) local duration = 3600 * 24 * 10 -- 10 days self.model.R:setex(self.model:rk("_tk_" .. tk), duration, self.id) return tk end User.m_methods.resolve_token = function(cls, tk) assert(type(tk) == "string") local id = tonumber(cls.R:get(cls:rk("_tk_" .. tk))) if not id then return nil end local u = cls:new(id) assert(u:getattr("pwtoken") == tk) return u end local _super = User.methods.export User.methods.export = function(self) local r = _super(self) r.pwhash = self:getattr("pwhash") return r end --- Module local load_rockspec = function(rs) if type(rs) == "string" then rs = lr_fetch.load_rockspec(rs) end assert(type(rs) == "table") if type(rs.description) == "table" then rs.url = rs.url or rs.description.homepage rs.description = rs.description.summary or rs.description.detailed end return rs end local _super = Module.m_methods.create Module.m_methods.create = function(cls, t) local rs = t.rockspec and load_rockspec(t.rockspec) if rs then assert(rs.name) end t.name = t.name or (rs and rs.name) local r = _super(cls, t) if rs then r:update_with_rockspec(rs, false) end return r end Module.methods.update_with_rockspec = function(self, rs, fast) -- -> changed? fast = (fast ~= false) rs = load_rockspec(rs) assert(rs and rs.name and rs.version) assert(rs.name == self:get_name()) local old_version = self:get_version() if old_version then if old_version == rs.version then if fast and self:check_attributes(rs) then return false end elseif lr_deps.compare_versions(old_version, rs.version) then return false end end for k,_ in pairs(self.model.attributes) do if rs[k] then self["set_" .. k](self, rs[k]) end end local old_deps = self:dependencies() for i=1,#old_deps do self:remove_dependency(old_deps[i]) end local new_deps = rs.dependencies or {} for i=1,#new_deps do local m = Module:get_by_name(new_deps[i].name) if m then self:add_dependency(m) end end return true end Module.sort_by_nb_endorsers = { function(self) return {self:nb_endorsers(), self:get_name()} end, function(a, b) return (a[1] == b[1]) and (a[2] < b[2]) or (a[1] > b[1]) end, } --- others local init = function() init_redis() if cfg._name == "development" then if not User:resolve_email("[email protected]") then User:create{ email = "[email protected]", fullname = "John Doe", password = "tagazok", trust_level = 2, } end end end return { User = User, Module = Module, Label = Label, init = init, load_rockspec = load_rockspec, }
fix new module imports
fix new module imports
Lua
mit
catwell/lua-toolbox
0cc0c31db9248acc1d5ac7961e8afd54891e7e2d
zproto.lua
zproto.lua
local engine = require "zprotoparser" local zproto = {} local protocache = {} setmetatable(protocache, {__mode = "v"}) local function create(self) local t = {} setmetatable(t, { __index = self, __gc = function(table) if t.proto then engine.free(t.proto) end end }) return t; end function zproto:load(path) local t = create(self) t.proto = engine.load(path) return t; end function zproto:parse(str) local t = create(self) t.proto = engine.parse(str) return t end local function query(self, typ) local record = protocache[typ] assert(self.proto) if not record then record = engine.query(self.proto, typ) protocache[typ] = record end return record end function zproto:encode(typ, protocol, packet) local record = query(self, typ) assert(record) assert(typ) assert(packet) return engine.encode(self.proto, record, protocol, packet) end function zproto:protocol(data, sz) return engine.protocol(data, sz) end function zproto:decode(typ, data, sz) local record = query(self, typ) return engine.decode(self.proto, record, data, sz) end return zproto
local engine = require "zprotoparser" local zproto = {} local function create(self) local t = {} setmetatable(t, { __index = self, __gc = function(table) if t.proto then engine.free(t.proto) end end }) t.protocache = {} setmetatable(t.protocache, {__mode = "v"}) return t; end function zproto:load(path) local t = create(self) t.proto = engine.load(path) return t; end function zproto:parse(str) local t = create(self) t.proto = engine.parse(str) return t end local function query(self, typ) local record = self.protocache[typ] assert(self.proto) if not record then record = engine.query(self.proto, typ) self.protocache[typ] = record end return record end function zproto:encode(typ, protocol, packet) local record = query(self, typ) assert(record) assert(typ) assert(packet) return engine.encode(self.proto, record, protocol, packet) end function zproto:protocol(data, sz) return engine.protocol(data, sz) end function zproto:decode(typ, data, sz) local record = query(self, typ) return engine.decode(self.proto, record, data, sz) end return zproto
bug fix:protocache
bug fix:protocache
Lua
mit
findstr/zproto,findstr/zproto,findstr/zproto
f7947afa9f0a64b04933fc3a20c70145662b4065
HAentry.lua
HAentry.lua
-- Da usarsi in ((Elenco Pokémon con abilità nascosta disponibile)) local m = {} local txt = require('Wikilib-strings') local multigen = require('Wikilib-multigen') local gens = require('Wikilib-gens') local ms = require('MiniSprite') local sup = require("Sup-data") local pokes = require("Poké-data") local abils = require("PokéAbil-data") -- accessoria (non esportata) per i link alle aree local function splitareas(text,gen) local regions = {[5] = "Unima", [6] = "Kalos", [7] = "Alola"} local areas = {} for w in text:gmatch("[^,]+") do if w:find("Percorso") then table.insert(areas,table.concat{"[[",w," (",regions[gen],")|",w,"]]"}) else table.insert(areas,table.concat{"[[",w,"]]"}) end end return table.concat(areas,", ") end -- per alcune formattazioni speciali local function specialtext(text) if text:find("%^") then text = text:gsub("%^(.-)%^",function(a) return sup[a] end) end if text:find("%*") then text = text:gsub("%*(.-)%*",function(a) return "<span class=\"explain tooltips\" title=\""..a.."\">*</span>" end) end return text end m.haentry = function(frame) local ndex = string.trim(frame.args.num) ndex = tonumber(ndex) or ndex local poke = pokes[ndex] local abil = abils[ndex] local final = { '|-\n|', poke.ndex, "\n|", ms.staticLua(ndex), "\n|", "[[", poke.name, "]]\n|[[", multigen.getGenValue(abil.abilityd or abil.ability1), "]]" } if frame.args.gen5ha then table.insert(final, table.concat{'<span class="explain tooltips" title="', frame.args.gen5ha, ' nella quinta generazione">*</span>'}) end if not abil.abilityd then table.insert(final, table.concat{'<span class="explain tooltips" title="Uguale all\'abilità normale">*</span>'}) end table.insert(final, "\n|") -- QUINTA GENERAZIONE if gens.getGen.ndex(poke.ndex) <= 5 then local disp5 = {} -- Dream World if frame.args.dwarea then local dwarea = "[[Dream World]]: "..splitareas(frame.args.dwarea,5) if frame.args.dwversion then dwarea = dwarea .. sup[frame.args.dwversion] end table.insert(disp5,dwarea) end -- Meandri nascosti if frame.args.hh then local hh = "[[Meandri nascosti]]: "..splitareas(frame.args.hh,5) if frame.args.hhversion then hh = hh..sup[frame.args.hhversion] end table.insert(disp5,hh) end -- scambi di Sciroccopoli if frame.args.nimbasa then local nimbasa = "[[Sciroccopoli]] ([[Scambio]] con " if frame.args.nimbasa == "M" then --giocatore maschio nimbasa = nimbasa.."[[Lilì]]" elseif frame.args.nimbasa == "F" then --giocatrice femmina nimbasa = nimbasa.."[[Dadì]]" else nimbasa = nimbasa.."[[Lilì]] o [[Dadì]]" --entrambi end table.insert(disp5,nimbasa..")") end -- RAdar if frame.args.radar then local radar = "[[RAdar Pokémon]]" if frame.args.radar ~= "true" then radar = radar..sup[frame.args.radar] end table.insert(disp5,radar) end -- altri metodi if frame.args.gen5other then table.insert(disp5,specialtext(frame.args.gen5other)) end -- caso base: non disponibile if #disp5==0 then disp5="''Non disponibile''" else disp5 = table.concat(disp5,"<br />") end table.insert(final, disp5.."\n|") end -- SESTA GENERAZIONE if gens.getGen.ndex(poke.ndex) <= 6 then local disp6 = {} -- Orde if frame.args.horde then local horde = {"[[Gruppi di Pokémon]]: ",splitareas(frame.args.horde,6)} if frame.args.hordeversion then table.insert(horde,sup[frame.args.hordeversion]) end table.insert(disp6,table.concat(horde)) end -- Safari if frame.args.safari then local safari = {"[[Safari Amici]] ("} local slist = {} for w in frame.args.safari:gmatch("[^, ]+") do -- per i pochi che si trovano in più Safari table.insert(slist,table.concat{"[[Safari Amici#Safari di tipo ", w, "|", w, "]]"}) end table.insert(safari,table.concat(slist,", ")) table.insert(safari,")") if frame.args.safariforme then -- quando solo alcune forme si trovano nel safari table.insert(safari,' <span style="font-size:smaller;">(') table.insert(safari,frame.args.safariforme) table.insert(safari,')</span>') end table.insert(disp6,table.concat(safari)) end -- altri metodi if frame.args.gen6other then table.insert(disp6,specialtext(frame.args.gen6other)) end -- caso base: necessita trasferitore (non "non disponibile": se non è nè in quinta nè in sesta non deve apparire nella lista) if table.getn(disp6)==0 then disp6="[[Pokétrasferitore]]" else disp6 = table.concat(disp6,"<br />") end table.insert(final, disp6.."\n|") end if gens.getGen.ndex(poke.ndex) <= 7 then -- SETTIMA GENERAZIONE -- I don't really know if there may be some standard method, so I'll add -- just this local disp7 = {} -- other methods if frame.args.gen7other then table.insert(disp7, specialtext(frame.args.gen7other)) end -- base case: Banca Pokémon (it's not "Not available" because it wouldn't -- have appeared in the list if it hadn't been available neither in sixth -- nor fifth gen) if table.getn(disp7)==0 then disp7="[[Banca Pokémon]]" else disp7 = table.concat(disp7,"<br />") end table.insert(final, disp7 .. "\n") end return table.concat(final) end return m
-- Da usarsi in ((Elenco Pokémon con abilità nascosta disponibile)) local m = {} local txt = require('Wikilib-strings') local multigen = require('Wikilib-multigen') local gens = require('Wikilib-gens') local ms = require('MiniSprite') local sup = require("Sup-data") local pokes = require("Poké-data") local abils = require("PokéAbil-data") -- accessoria (non esportata) per i link alle aree local function splitareas(text,gen) local regions = {[5] = "Unima", [6] = "Kalos", [7] = "Alola"} local areas = {} for w in text:gmatch("[^,]+") do if w:find("Percorso") then table.insert(areas,table.concat{"[[",w," (",regions[gen],")|",w,"]]"}) else table.insert(areas,table.concat{"[[",w,"]]"}) end end return table.concat(areas,", ") end -- per alcune formattazioni speciali local function specialtext(text) if text:find("%^") then text = text:gsub("%^(.-)%^",function(a) return sup[a] end) end if text:find("%*") then text = text:gsub("%*(.-)%*",function(a) return "<span class=\"explain tooltips\" title=\""..a.."\">*</span>" end) end return text end m.haentry = function(frame) local ndex = string.trim(frame.args.num) ndex = tonumber(ndex) or ndex local poke = pokes[ndex] local abil = abils[ndex] local final = { '|-\n|', poke.ndex, "\n|", ms.staticLua(type(ndex) == 'number' and string.tf(ndex) or ndex), "\n|", "[[", poke.name, "]]\n|[[", multigen.getGenValue(abil.abilityd or abil.ability1), "]]" } if frame.args.gen5ha then table.insert(final, table.concat{'<span class="explain tooltips" title="', frame.args.gen5ha, ' nella quinta generazione">*</span>'}) end if not abil.abilityd then table.insert(final, table.concat{'<span class="explain tooltips" title="Uguale all\'abilità normale">*</span>'}) end table.insert(final, "\n|") -- QUINTA GENERAZIONE if gens.getGen.ndex(poke.ndex) <= 5 then local disp5 = {} -- Dream World if frame.args.dwarea then local dwarea = "[[Dream World]]: "..splitareas(frame.args.dwarea,5) if frame.args.dwversion then dwarea = dwarea .. sup[frame.args.dwversion] end table.insert(disp5,dwarea) end -- Meandri nascosti if frame.args.hh then local hh = "[[Meandri nascosti]]: "..splitareas(frame.args.hh,5) if frame.args.hhversion then hh = hh..sup[frame.args.hhversion] end table.insert(disp5,hh) end -- scambi di Sciroccopoli if frame.args.nimbasa then local nimbasa = "[[Sciroccopoli]] ([[Scambio]] con " if frame.args.nimbasa == "M" then --giocatore maschio nimbasa = nimbasa.."[[Lilì]]" elseif frame.args.nimbasa == "F" then --giocatrice femmina nimbasa = nimbasa.."[[Dadì]]" else nimbasa = nimbasa.."[[Lilì]] o [[Dadì]]" --entrambi end table.insert(disp5,nimbasa..")") end -- RAdar if frame.args.radar then local radar = "[[RAdar Pokémon]]" if frame.args.radar ~= "true" then radar = radar..sup[frame.args.radar] end table.insert(disp5,radar) end -- altri metodi if frame.args.gen5other then table.insert(disp5,specialtext(frame.args.gen5other)) end -- caso base: non disponibile if #disp5==0 then disp5="''Non disponibile''" else disp5 = table.concat(disp5,"<br />") end table.insert(final, disp5.."\n|") end -- SESTA GENERAZIONE if gens.getGen.ndex(poke.ndex) <= 6 then local disp6 = {} -- Orde if frame.args.horde then local horde = {"[[Gruppi di Pokémon]]: ",splitareas(frame.args.horde,6)} if frame.args.hordeversion then table.insert(horde,sup[frame.args.hordeversion]) end table.insert(disp6,table.concat(horde)) end -- Safari if frame.args.safari then local safari = {"[[Safari Amici]] ("} local slist = {} for w in frame.args.safari:gmatch("[^, ]+") do -- per i pochi che si trovano in più Safari table.insert(slist,table.concat{"[[Safari Amici#Safari di tipo ", w, "|", w, "]]"}) end table.insert(safari,table.concat(slist,", ")) table.insert(safari,")") if frame.args.safariforme then -- quando solo alcune forme si trovano nel safari table.insert(safari,' <span style="font-size:smaller;">(') table.insert(safari,frame.args.safariforme) table.insert(safari,')</span>') end table.insert(disp6,table.concat(safari)) end -- altri metodi if frame.args.gen6other then table.insert(disp6,specialtext(frame.args.gen6other)) end -- caso base: necessita trasferitore (non "non disponibile": se non è nè in quinta nè in sesta non deve apparire nella lista) if table.getn(disp6)==0 then disp6="[[Pokétrasferitore]]" else disp6 = table.concat(disp6,"<br />") end table.insert(final, disp6.."\n|") end if gens.getGen.ndex(poke.ndex) <= 7 then -- SETTIMA GENERAZIONE -- I don't really know if there may be some standard method, so I'll add -- just this local disp7 = {} -- other methods if frame.args.gen7other then table.insert(disp7, specialtext(frame.args.gen7other)) end -- base case: Banca Pokémon (it's not "Not available" because it wouldn't -- have appeared in the list if it hadn't been available neither in sixth -- nor fifth gen) if table.getn(disp7)==0 then disp7="[[Banca Pokémon]]" else disp7 = table.concat(disp7,"<br />") end table.insert(final, disp7 .. "\n") end return table.concat(final) end return m
Fixes to HAentry
Fixes to HAentry
Lua
cc0-1.0
pokemoncentral/wiki-lua-modules
ac7c5e0268f5118b0defba7fb3a4c1ab2be5d6c1
src/program/top/top.lua
src/program/top/top.lua
-- Use of this source code is governed by the Apache 2.0 license; see COPYING. module(..., package.seeall) local ffi = require("ffi") local C = ffi.C local lib = require("core.lib") local shm = require("core.shm") local counter = require("core.counter") local S = require("syscall") local histogram = require("core.histogram") local usage = require("program.top.README_inc") local long_opts = { help = "h", list = "l" } function clearterm () io.write('\027[2J') end function run (args) local opt = {} local object = nil function opt.h (arg) print(usage) main.exit(1) end function opt.l (arg) object = arg end args = lib.dogetopt(args, opt, "hl:", long_opts) if #args > 1 then print(usage) main.exit(1) end local target_pid = select_snabb_instance(args[1]) if object then list_shm(target_pid, object) else top(target_pid) end end function select_snabb_instance (pid) local function compute_snabb_instances() -- Produces set of snabb instances, excluding this one. local pids = {} local my_pid = S.getpid() for _, name in ipairs(shm.children("/")) do -- This could fail as the name could be for example "by-name" local p = tonumber(name) if p and p ~= my_pid then table.insert(pids, name) end end return pids end local instances = compute_snabb_instances() if pid then pid = tostring(pid) -- Try to use given pid for _, instance in ipairs(instances) do if instance == pid then return pid end end print("No such Snabb instance: "..pid) elseif #instances == 1 then return instances[1] elseif #instances <= 0 then print("No Snabb instance found.") else print("Multiple Snabb instances found. Select one:") for _, instance in ipairs(instances) do print(instance) end end main.exit(1) end function list_shm (pid, object) local frame = shm.open_frame("/"..pid.."/"..object) local sorted = {} for name, _ in pairs(frame) do table.insert(sorted, name) end table.sort(sorted) for _, name in ipairs(sorted) do if name ~= 'path' and name ~= 'specs' and name ~= 'readonly' then print_row({30, 30}, {name, tostring(frame[name])}) end end shm.delete_frame(frame) end function top (instance_pid) local instance_tree = "/"..instance_pid local counters = open_counters(instance_tree) local configs = 0 local last_stats = nil while (true) do if configs < counter.read(counters.engine.configs) then -- If a (new) config is loaded we (re)open the link counters. open_link_counters(counters, instance_tree) end local new_stats = get_stats(counters) if last_stats then clearterm() print_global_metrics(new_stats, last_stats) io.write("\n") print_latency_metrics(new_stats, last_stats) print_link_metrics(new_stats, last_stats) io.flush() end last_stats = new_stats C.sleep(1) end end function open_counters (tree) local counters = {} counters.engine = shm.open_frame(tree.."/engine") counters.links = {} -- These will be populated on demand. return counters end function open_link_counters (counters, tree) -- Unmap and clear existing link counters. for _, link_frame in pairs(counters.links) do shm.delete_frame(link_frame) end counters.links = {} -- Open current link counters. for _, linkspec in ipairs(shm.children(tree.."/links")) do counters.links[linkspec] = shm.open_frame(tree.."/links/"..linkspec) end end function get_stats (counters) local new_stats = {} for _, name in ipairs({"configs", "breaths", "frees", "freebytes"}) do new_stats[name] = counter.read(counters.engine[name]) end if counters.engine.latency then new_stats.latency = counters.engine.latency:snapshot() end new_stats.links = {} for linkspec, link in pairs(counters.links) do new_stats.links[linkspec] = {} for _, name in ipairs({"rxpackets", "txpackets", "rxbytes", "txbytes", "txdrop" }) do new_stats.links[linkspec][name] = counter.read(link[name]) end end return new_stats end local global_metrics_row = {15, 15, 15} function print_global_metrics (new_stats, last_stats) local frees = tonumber(new_stats.frees - last_stats.frees) local bytes = tonumber(new_stats.freebytes - last_stats.freebytes) local breaths = tonumber(new_stats.breaths - last_stats.breaths) print_row(global_metrics_row, {"Kfrees/s", "freeGbytes/s", "breaths/s"}) print_row(global_metrics_row, {float_s(frees / 1000), float_s(bytes / (1000^3)), tostring(breaths)}) end function summarize_latency (histogram, prev) local total = histogram.total if prev then total = total - prev.total end if total == 0 then return 0, 0, 0 end local min, max, cumulative = nil, 0, 0 for count, lo, hi in histogram:iterate(prev) do if count ~= 0 then if not min then min = lo end max = hi cumulative = cumulative + (lo + hi) / 2 * tonumber(count) end end return min, cumulative / tonumber(total), max end function print_latency_metrics (new_stats, last_stats) local cur, prev = new_stats.latency, last_stats.latency if not cur then return end local min, avg, max = summarize_latency(cur, prev) print_row(global_metrics_row, {"Min breath (us)", "Average", "Maximum"}) print_row(global_metrics_row, {float_s(min*1e6), float_s(avg*1e6), float_s(max*1e6)}) print("\n") end local link_metrics_row = {31, 7, 7, 7, 7, 7} function print_link_metrics (new_stats, last_stats) print_row(link_metrics_row, {"Links (rx/tx/txdrop in Mpps)", "rx", "tx", "rxGb", "txGb", "txdrop"}) for linkspec, link in pairs(new_stats.links) do if last_stats.links[linkspec] then local rx = tonumber(new_stats.links[linkspec].rxpackets - last_stats.links[linkspec].rxpackets) local tx = tonumber(new_stats.links[linkspec].txpackets - last_stats.links[linkspec].txpackets) local rxbytes = tonumber(new_stats.links[linkspec].rxbytes - last_stats.links[linkspec].rxbytes) local txbytes = tonumber(new_stats.links[linkspec].txbytes - last_stats.links[linkspec].txbytes) local drop = tonumber(new_stats.links[linkspec].txdrop - last_stats.links[linkspec].txdrop) print_row(link_metrics_row, {linkspec, float_s(rx / 1e6), float_s(tx / 1e6), float_s(rxbytes / (1000^3)), float_s(txbytes / (1000^3)), float_s(drop / 1e6)}) end end end function pad_str (s, n) local padding = math.max(n - s:len(), 0) return ("%s%s"):format(s:sub(1, n), (" "):rep(padding)) end function print_row (spec, args) for i, s in ipairs(args) do io.write((" %s"):format(pad_str(s, spec[i]))) end io.write("\n") end function float_s (n) return ("%.2f"):format(n) end
-- Use of this source code is governed by the Apache 2.0 license; see COPYING. module(..., package.seeall) local ffi = require("ffi") local C = ffi.C local lib = require("core.lib") local shm = require("core.shm") local counter = require("core.counter") local S = require("syscall") local histogram = require("core.histogram") local usage = require("program.top.README_inc") local long_opts = { help = "h", list = "l" } function clearterm () io.write('\027[2J') end function run (args) local opt = {} local object = nil function opt.h (arg) print(usage) main.exit(1) end function opt.l (arg) object = arg end args = lib.dogetopt(args, opt, "hl:", long_opts) if #args > 1 then print(usage) main.exit(1) end local target_pid = select_snabb_instance(args[1]) if object then list_shm(target_pid, object) else top(target_pid) end end function select_snabb_instance (pid) local function compute_snabb_instances() -- Produces set of snabb instances, excluding this one. local pids = {} local my_pid = S.getpid() for _, name in ipairs(shm.children("/")) do -- This could fail as the name could be for example "by-name" local p = tonumber(name) if p and p ~= my_pid then table.insert(pids, name) end end return pids end local instances = compute_snabb_instances() if pid then pid = tostring(pid) -- Try to use given pid for _, instance in ipairs(instances) do if instance == pid then return pid end end print("No such Snabb instance: "..pid) elseif #instances == 1 then return instances[1] elseif #instances <= 0 then print("No Snabb instance found.") else print("Multiple Snabb instances found. Select one:") for _, instance in ipairs(instances) do print(instance) end end main.exit(1) end function list_shm (pid, object) local frame = shm.open_frame("/"..pid.."/"..object) local sorted = {} for name, _ in pairs(frame) do table.insert(sorted, name) end table.sort(sorted) for _, name in ipairs(sorted) do if name ~= 'path' and name ~= 'specs' and name ~= 'readonly' then print_row({30, 30}, {name, tostring(frame[name])}) end end shm.delete_frame(frame) end function top (instance_pid) local instance_tree = "/"..instance_pid local counters = open_counters(instance_tree) local configs = 0 local last_stats = nil while (true) do local current = counter.read(counters.engine.configs) if configs < current then configs = current -- If a (new) config is loaded we (re)open the link counters. open_link_counters(counters, instance_tree) end local new_stats = get_stats(counters) if last_stats then clearterm() print_global_metrics(new_stats, last_stats) io.write("\n") print_latency_metrics(new_stats, last_stats) print_link_metrics(new_stats, last_stats) io.flush() end last_stats = new_stats C.sleep(1) end end function open_counters (tree) local counters = {} counters.engine = shm.open_frame(tree.."/engine") counters.links = {} -- These will be populated on demand. return counters end function open_link_counters (counters, tree) -- Unmap and clear existing link counters. for _, link_frame in pairs(counters.links) do shm.delete_frame(link_frame) end counters.links = {} -- Open current link counters. for _, linkspec in ipairs(shm.children(tree.."/links")) do counters.links[linkspec] = shm.open_frame(tree.."/links/"..linkspec) end end function get_stats (counters) local new_stats = {} for _, name in ipairs({"configs", "breaths", "frees", "freebytes"}) do new_stats[name] = counter.read(counters.engine[name]) end if counters.engine.latency then new_stats.latency = counters.engine.latency:snapshot() end new_stats.links = {} for linkspec, link in pairs(counters.links) do new_stats.links[linkspec] = {} for _, name in ipairs({"rxpackets", "txpackets", "rxbytes", "txbytes", "txdrop" }) do new_stats.links[linkspec][name] = counter.read(link[name]) end end return new_stats end local global_metrics_row = {15, 15, 15} function print_global_metrics (new_stats, last_stats) local frees = tonumber(new_stats.frees - last_stats.frees) local bytes = tonumber(new_stats.freebytes - last_stats.freebytes) local breaths = tonumber(new_stats.breaths - last_stats.breaths) print_row(global_metrics_row, {"Kfrees/s", "freeGbytes/s", "breaths/s"}) print_row(global_metrics_row, {float_s(frees / 1000), float_s(bytes / (1000^3)), tostring(breaths)}) end function summarize_latency (histogram, prev) local total = histogram.total if prev then total = total - prev.total end if total == 0 then return 0, 0, 0 end local min, max, cumulative = nil, 0, 0 for count, lo, hi in histogram:iterate(prev) do if count ~= 0 then if not min then min = lo end max = hi cumulative = cumulative + (lo + hi) / 2 * tonumber(count) end end return min, cumulative / tonumber(total), max end function print_latency_metrics (new_stats, last_stats) local cur, prev = new_stats.latency, last_stats.latency if not cur then return end local min, avg, max = summarize_latency(cur, prev) print_row(global_metrics_row, {"Min breath (us)", "Average", "Maximum"}) print_row(global_metrics_row, {float_s(min*1e6), float_s(avg*1e6), float_s(max*1e6)}) print("\n") end local link_metrics_row = {31, 7, 7, 7, 7, 7} function print_link_metrics (new_stats, last_stats) print_row(link_metrics_row, {"Links (rx/tx/txdrop in Mpps)", "rx", "tx", "rxGb", "txGb", "txdrop"}) for linkspec, link in pairs(new_stats.links) do if last_stats.links[linkspec] then local rx = tonumber(new_stats.links[linkspec].rxpackets - last_stats.links[linkspec].rxpackets) local tx = tonumber(new_stats.links[linkspec].txpackets - last_stats.links[linkspec].txpackets) local rxbytes = tonumber(new_stats.links[linkspec].rxbytes - last_stats.links[linkspec].rxbytes) local txbytes = tonumber(new_stats.links[linkspec].txbytes - last_stats.links[linkspec].txbytes) local drop = tonumber(new_stats.links[linkspec].txdrop - last_stats.links[linkspec].txdrop) print_row(link_metrics_row, {linkspec, float_s(rx / 1e6), float_s(tx / 1e6), float_s(rxbytes / (1000^3)), float_s(txbytes / (1000^3)), float_s(drop / 1e6)}) end end end function pad_str (s, n) local padding = math.max(n - s:len(), 0) return ("%s%s"):format(s:sub(1, n), (" "):rep(padding)) end function print_row (spec, args) for i, s in ipairs(args) do io.write((" %s"):format(pad_str(s, spec[i]))) end io.write("\n") end function float_s (n) return ("%.2f"):format(n) end
top: fix bug where counters were redundantly reopened
top: fix bug where counters were redundantly reopened The formulation that was supposed to re-open counters on configuration changes actually triggered re-opening on every polling.
Lua
apache-2.0
Igalia/snabb,eugeneia/snabb,Igalia/snabbswitch,dpino/snabb,Igalia/snabb,snabbco/snabb,eugeneia/snabbswitch,Igalia/snabb,dpino/snabbswitch,alexandergall/snabbswitch,snabbco/snabb,alexandergall/snabbswitch,dpino/snabb,snabbco/snabb,eugeneia/snabb,SnabbCo/snabbswitch,eugeneia/snabbswitch,Igalia/snabbswitch,Igalia/snabb,dpino/snabbswitch,eugeneia/snabbswitch,Igalia/snabbswitch,Igalia/snabb,dpino/snabbswitch,snabbco/snabb,Igalia/snabbswitch,snabbco/snabb,alexandergall/snabbswitch,alexandergall/snabbswitch,dpino/snabbswitch,eugeneia/snabb,alexandergall/snabbswitch,dpino/snabb,eugeneia/snabb,alexandergall/snabbswitch,snabbco/snabb,eugeneia/snabb,SnabbCo/snabbswitch,Igalia/snabb,Igalia/snabb,eugeneia/snabb,alexandergall/snabbswitch,SnabbCo/snabbswitch,Igalia/snabb,snabbco/snabb,eugeneia/snabb,dpino/snabb,dpino/snabb,snabbco/snabb,dpino/snabb,alexandergall/snabbswitch,dpino/snabb,eugeneia/snabb,eugeneia/snabbswitch,Igalia/snabbswitch,SnabbCo/snabbswitch
cc6799235edbc0690159ffa24ceacf492a8281af
agents/monitoring/tests/net/init.lua
agents/monitoring/tests/net/init.lua
local table = require('table') local async = require('async') local ConnectionStream = require('monitoring/default/client/connection_stream').ConnectionStream local misc = require('monitoring/default/util/misc') local helper = require('../helper') local timer = require('timer') local fixtures = require('../fixtures') local constants = require('constants') local consts = require('../../default/util/constants') local Endpoint = require('../../default/endpoint').Endpoint local path = require('path') local exports = {} local child exports['test_reconnects'] = function(test, asserts) local options = { datacenter = 'test', stateDirectory = './tests', tls = { rejectUnauthorized = false } } local client = ConnectionStream:new('id', 'token', 'guid', options) local clientEnd = 0 local reconnect = 0 client:on('client_end', function(err) clientEnd = clientEnd + 1 end) client:on('reconnect', function(err) reconnect = reconnect + 1 end) local endpoints = {} for _, address in pairs(fixtures.TESTING_AGENT_ENDPOINTS) do -- split ip:port table.insert(endpoints, Endpoint:new(address)) end async.series({ function(callback) child = helper.start_server(callback) end, function(callback) client:on('handshake_success', misc.nCallbacks(callback, 3)) local endpoints = {} for _, address in pairs(fixtures.TESTING_AGENT_ENDPOINTS) do -- split ip:port table.insert(endpoints, Endpoint:new(address)) end client:createConnections(endpoints, function() end) end, function(callback) helper.stop_server(child) client:on('reconnect', misc.nCallbacks(callback, 3)) end, function(callback) child = helper.start_server(function() client:on('handshake_success', misc.nCallbacks(callback, 3)) end) end, }, function() helper.stop_server(child) asserts.ok(clientEnd > 0) asserts.ok(reconnect > 0) test.done() end) end exports['test_upgrades'] = function(test, asserts) local options, client, endpoints if true then test.skip("Skip upgrades test until it is reliable") return nil end -- Override the default download path consts.DEFAULT_DOWNLOAD_PATH = path.join('.', 'tmp') options = { datacenter = 'test', stateDirectory = './tests', tls = { rejectUnauthorized = false } } local endpoints = {} for _, address in pairs(fixtures.TESTING_AGENT_ENDPOINTS) do -- split ip:port table.insert(endpoints, Endpoint:new(address)) end async.series({ function(callback) child = helper.start_server(callback) end, function(callback) client = ConnectionStream:new('id', 'token', 'guid', options) client:on('handshake_success', misc.nCallbacks(callback, 3)) client:createConnections(endpoints, function() end) end, function(callback) callback = misc.nCallbacks(callback, 4) client:on('binary_upgrade.found', callback) client:on('bundle_upgrade.found', callback) client:on('bundle_upgrade.error', callback) client:on('binary_upgrade.error', callback) client:getUpgrade():forceUpgradeCheck() end }, function() helper.stop_server(child) client:done() test.done() end) end return exports
local table = require('table') local async = require('async') local ConnectionStream = require('monitoring/default/client/connection_stream').ConnectionStream local misc = require('monitoring/default/util/misc') local helper = require('../helper') local timer = require('timer') local fixtures = require('../fixtures') local constants = require('constants') local consts = require('../../default/util/constants') local Endpoint = require('../../default/endpoint').Endpoint local path = require('path') local os = require('os') local exports = {} local child exports['test_reconnects'] = function(test, asserts) if os.type() == "win32" then test.skip("Skip test_reconnects until a suitable SIGUSR1 replacement is used in runner.py") return nil end local options = { datacenter = 'test', stateDirectory = './tests', tls = { rejectUnauthorized = false } } local client = ConnectionStream:new('id', 'token', 'guid', options) local clientEnd = 0 local reconnect = 0 client:on('client_end', function(err) clientEnd = clientEnd + 1 end) client:on('reconnect', function(err) reconnect = reconnect + 1 end) local endpoints = {} for _, address in pairs(fixtures.TESTING_AGENT_ENDPOINTS) do -- split ip:port table.insert(endpoints, Endpoint:new(address)) end async.series({ function(callback) child = helper.start_server(callback) end, function(callback) client:on('handshake_success', misc.nCallbacks(callback, 3)) local endpoints = {} for _, address in pairs(fixtures.TESTING_AGENT_ENDPOINTS) do -- split ip:port table.insert(endpoints, Endpoint:new(address)) end client:createConnections(endpoints, function() end) end, function(callback) helper.stop_server(child) client:on('reconnect', misc.nCallbacks(callback, 3)) end, function(callback) child = helper.start_server(function() client:on('handshake_success', misc.nCallbacks(callback, 3)) end) end, }, function() helper.stop_server(child) asserts.ok(clientEnd > 0) asserts.ok(reconnect > 0) test.done() end) end exports['test_upgrades'] = function(test, asserts) local options, client, endpoints if true then test.skip("Skip upgrades test until it is reliable") return nil end -- Override the default download path consts.DEFAULT_DOWNLOAD_PATH = path.join('.', 'tmp') options = { datacenter = 'test', stateDirectory = './tests', tls = { rejectUnauthorized = false } } local endpoints = {} for _, address in pairs(fixtures.TESTING_AGENT_ENDPOINTS) do -- split ip:port table.insert(endpoints, Endpoint:new(address)) end async.series({ function(callback) child = helper.start_server(callback) end, function(callback) client = ConnectionStream:new('id', 'token', 'guid', options) client:on('handshake_success', misc.nCallbacks(callback, 3)) client:createConnections(endpoints, function() end) end, function(callback) callback = misc.nCallbacks(callback, 4) client:on('binary_upgrade.found', callback) client:on('bundle_upgrade.found', callback) client:on('bundle_upgrade.error', callback) client:on('binary_upgrade.error', callback) client:getUpgrade():forceUpgradeCheck() end }, function() helper.stop_server(child) client:done() test.done() end) end return exports
Change the net test, test_reconnects, to skip itself as it uses a test_server_fixture_blocking that calls a SIGUSR1. Windows can't SIGUSR1, see: http://docs.python.org/2/library/signal.html#signal.signal We'll need a Windows specific way of emulating the SIGUSR1 functionality in the Agent.
Change the net test, test_reconnects, to skip itself as it uses a test_server_fixture_blocking that calls a SIGUSR1. Windows can't SIGUSR1, see: http://docs.python.org/2/library/signal.html#signal.signal We'll need a Windows specific way of emulating the SIGUSR1 functionality in the Agent.
Lua
apache-2.0
cp16net/virgo-base,kaustavha/rackspace-monitoring-agent,cp16net/virgo-base,virgo-agent-toolkit/rackspace-monitoring-agent,AlphaStaxLLC/rackspace-monitoring-agent,cp16net/virgo-base,cp16net/virgo-base,christopherjwang/rackspace-monitoring-agent,virgo-agent-toolkit/rackspace-monitoring-agent,christopherjwang/rackspace-monitoring-agent,AlphaStaxLLC/rackspace-monitoring-agent,cp16net/virgo-base,kaustavha/rackspace-monitoring-agent
c469e737775a814a1fa5f9de40530a65ac161b2d
core/sile.lua
core/sile.lua
SILE = {} SILE.version = "0.9.0" SILE.utilities = require("core/utilities") SU = SILE.utilities SILE.inputs = {} SILE.Commands = {}; SILE.debugFlags = {} std = require("std") SILE.documentState = std.object {}; SILE.scratch = {}; SILE.length = require("core/length") require("core/parserbits") require("core/measurements") require("core/baseclass") SILE.nodefactory = require("core/nodefactory") require("core/settings") require("core/inputs-texlike") require("core/inputs-xml") require("core/inputs-common") require("core/papersizes") require("core/colorparser") require("core/pagebuilder") require("core/typesetter") require("core/hyphenator-liang") require("core/font") SILE.frameParser = require("core/frameparser") SILE.linebreak = require("core/break") require("core/frame") if pcall(function () require("justenoughharfbuzz") end) then require("core/harfbuzz-shaper") require("core/podofo-output") else require("core/pango-shaper") require("core/cairo-output") end SILE.require = function(d) -- path? return require(d) end SILE.parseArguments = function() local parser = std.optparse ("This is SILE "..SILE.version..[[ Usage: sile Banner text. Optional long description text to show when the --help option is passed. Several lines or paragraphs of long description are permitted. Options: -d, --debug=VALUE debug SILE's operation -I, --include=[FILE] accept an optional argument --version display version information, then exit --help display this help, then exit ]]) parser:on ('--', parser.finished) _G.unparsed, _G.opts = parser:parse(_G.arg) SILE.debugFlags = {} if opts.debug then for k,v in ipairs(std.string.split(opts.debug, ",")) do SILE.debugFlags[v] = 1 end end if opts.include then SILE.preamble = opts.include end end function SILE.initRepl () SILE._repl = require 'repl.console' local has_linenoise = pcall(require, 'linenoise') if has_linenoise then SILE._repl:loadplugin 'linenoise' else -- XXX check that we're not receiving input from a non-tty local has_rlwrap = os.execute('which rlwrap >/dev/null 2>/dev/null') == 0 if has_rlwrap and not os.getenv 'LUA_REPL_RLWRAP' then local command = 'LUA_REPL_RLWRAP=1 rlwrap' local index = 0 while arg[index - 1] do index = index - 1 end while arg[index] do command = string.format('%s %q', command, arg[index]) index = index + 1 end os.execute(command) return end end SILE._repl:loadplugin 'history' SILE._repl:loadplugin 'completion' SILE._repl:loadplugin 'autoreturn' SILE._repl:loadplugin 'rcfile' end function SILE.repl() if _VERSION:match("5.2") then -- No repl for you! print("luarepl does not support 5.2; sorry, REPL unavailable.") return end if not SILE._repl then SILE.initRepl() end SILE._repl:run() end function SILE.readFile(fn) SILE.currentlyProcessingFile = fn fn = SILE.resolveFile(fn) local file, err = io.open(fn) if not file then print("Could not open "..err) return end io.write("<"..fn..">") -- Sniff first few bytes local sniff = file:read("*l") or "" file:seek("set", 0) if sniff:find("<") then SILE.inputs.XML.process(fn) else SILE.inputs.TeXlike.process(fn) end end local function file_exists(name) local f=io.open(name,"r") if f~=nil then io.close(f) return true else return false end end function SILE.resolveFile(fn) if file_exists(fn) then return fn end if file_exists(fn..".sil") then return fn..".sil" end for k in SU.gtoke(os.getenv("SILE_PATH"), ";") do if k.string then local f = std.io.catfile(k.string, fn) if file_exists(f) then return f end if file_exists(f..".sil") then return f..".sil" end end end end function SILE.call(cmd,options, content) if not SILE.Commands[cmd] then SU.error("Unknown command "..cmd) end SILE.Commands[cmd](options or {}, content or {}) end return SILE
SILE = {} SILE.version = "0.9.0" SILE.utilities = require("core/utilities") SU = SILE.utilities SILE.inputs = {} SILE.Commands = {}; SILE.debugFlags = {} std = require("std") SILE.documentState = std.object {}; SILE.scratch = {}; SILE.length = require("core/length") require("core/parserbits") require("core/measurements") require("core/baseclass") SILE.nodefactory = require("core/nodefactory") require("core/settings") require("core/inputs-texlike") require("core/inputs-xml") require("core/inputs-common") require("core/papersizes") require("core/colorparser") require("core/pagebuilder") require("core/typesetter") require("core/hyphenator-liang") require("core/font") SILE.frameParser = require("core/frameparser") SILE.linebreak = require("core/break") require("core/frame") if pcall(function () require("justenoughharfbuzz") end) then require("core/harfbuzz-shaper") require("core/podofo-output") else require("core/pango-shaper") require("core/cairo-output") end SILE.require = function(d) -- path? return require(d) end SILE.parseArguments = function() local parser = std.optparse ("This is SILE "..SILE.version..[[ Usage: sile Banner text. Optional long description text to show when the --help option is passed. Several lines or paragraphs of long description are permitted. Options: -d, --debug=VALUE debug SILE's operation -I, --include=[FILE] accept an optional argument --version display version information, then exit --help display this help, then exit ]]) parser:on ('--', parser.finished) _G.unparsed, _G.opts = parser:parse(_G.arg) SILE.debugFlags = {} if opts.debug then for k,v in ipairs(std.string.split(opts.debug, ",")) do SILE.debugFlags[v] = 1 end end if opts.include then SILE.preamble = opts.include end end function SILE.initRepl () SILE._repl = require 'repl.console' local has_linenoise = pcall(require, 'linenoise') if has_linenoise then SILE._repl:loadplugin 'linenoise' else -- XXX check that we're not receiving input from a non-tty local has_rlwrap = os.execute('which rlwrap >/dev/null 2>/dev/null') == 0 if has_rlwrap and not os.getenv 'LUA_REPL_RLWRAP' then local command = 'LUA_REPL_RLWRAP=1 rlwrap' local index = 0 while arg[index - 1] do index = index - 1 end while arg[index] do command = string.format('%s %q', command, arg[index]) index = index + 1 end os.execute(command) return end end SILE._repl:loadplugin 'history' SILE._repl:loadplugin 'completion' SILE._repl:loadplugin 'autoreturn' SILE._repl:loadplugin 'rcfile' end function SILE.repl() if _VERSION:match("5.2") then setfenv = function(f, t) f = (type(f) == 'function' and f or debug.getinfo(f + 1, 'f').func) local name local up = 0 repeat up = up + 1 name = debug.getupvalue(f, up) until name == '_ENV' or name == nil if name then debug.upvaluejoin(f, up, function() return t end, 1) -- use unique upvalue, set it to f end end end if not SILE._repl then SILE.initRepl() end SILE._repl:run() end function SILE.readFile(fn) SILE.currentlyProcessingFile = fn fn = SILE.resolveFile(fn) local file, err = io.open(fn) if not file then print("Could not open "..err) return end io.write("<"..fn..">") -- Sniff first few bytes local sniff = file:read("*l") or "" file:seek("set", 0) if sniff:find("<") then SILE.inputs.XML.process(fn) else SILE.inputs.TeXlike.process(fn) end end local function file_exists(name) local f=io.open(name,"r") if f~=nil then io.close(f) return true else return false end end function SILE.resolveFile(fn) if file_exists(fn) then return fn end if file_exists(fn..".sil") then return fn..".sil" end for k in SU.gtoke(os.getenv("SILE_PATH"), ";") do if k.string then local f = std.io.catfile(k.string, fn) if file_exists(f) then return f end if file_exists(f..".sil") then return f..".sil" end end end end function SILE.call(cmd,options, content) if not SILE.Commands[cmd] then SU.error("Unknown command "..cmd) end SILE.Commands[cmd](options or {}, content or {}) end return SILE
Fix the REPL. It’s really, really useful to have a working one.
Fix the REPL. It’s really, really useful to have a working one.
Lua
mit
WAKAMAZU/sile_fe,simoncozens/sile,neofob/sile,anthrotype/sile,WAKAMAZU/sile_fe,shirat74/sile,neofob/sile,WAKAMAZU/sile_fe,Nathan22Miles/sile,simoncozens/sile,alerque/sile,neofob/sile,anthrotype/sile,shirat74/sile,anthrotype/sile,Nathan22Miles/sile,anthrotype/sile,WAKAMAZU/sile_fe,Nathan22Miles/sile,Nathan22Miles/sile,simoncozens/sile,shirat74/sile,simoncozens/sile,alerque/sile,alerque/sile,shirat74/sile,Nathan22Miles/sile,neofob/sile,alerque/sile
190da2114afc7a3d4812ed988b86ccd2dc853a93
SVUI_!Core/system/_reports/azerite.lua
SVUI_!Core/system/_reports/azerite.lua
--[[ ############################################################################## S V U I By: Failcoder ############################################################################## ########################################################## LOCALIZED LUA FUNCTIONS ########################################################## ]]-- --[[ GLOBALS ]]-- local _G = _G; local select = _G.select; local pairs = _G.pairs; local ipairs = _G.ipairs; local type = _G.type; local error = _G.error; local pcall = _G.pcall; local assert = _G.assert; local tostring = _G.tostring; local tonumber = _G.tonumber; local string = _G.string; local math = _G.math; local table = _G.table; --[[ STRING METHODS ]]-- local lower, upper = string.lower, string.upper; local find, format, len, split = string.find, string.format, string.len, string.split; local match, sub, join = string.match, string.sub, string.join; local gmatch, gsub = string.gmatch, string.gsub; --[[ MATH METHODS ]]-- local abs, ceil, floor, round = math.abs, math.ceil, math.floor, math.round; -- Basic --[[ TABLE METHODS ]]-- local twipe, tsort = table.wipe, table.sort; --[[ ########################################################## GET ADDON DATA ########################################################## ]]-- local SV = select(2, ...) local L = SV.L local Reports = SV.Reports; --[[ ########################################################## UTILITIES ########################################################## ]]-- local percColors = { "|cff0CD809", "|cffE8DA0F", "|cffFF9000", "|cffD80909" } local isEquipped = C_AzeriteItem.FindActiveAzeriteItem(); local function SetTooltipText(report) Reports:SetDataTip(report); Reports.ToolTip:AddLine(L["Heart of Azeroth"]); Reports.ToolTip:AddLine(" "); if isEquipped then local xp, totalLevelXP = C_AzeriteItem.GetAzeriteItemXPInfo(isEquipped); local currentLevel = C_AzeriteItem.GetPowerLevel(isEquipped); local xpToNextLevel = totalLevelXP - xp; local calc1 = (xp / totalLevelXP) * 100; Reports.ToolTip:AddDoubleLine(L["Current Level:"], (" %d "):format(currentLevel), 1, 1, 1); Reports.ToolTip:AddDoubleLine(L["Current Artifact Power:"], (" %s / %s (%d%%)"):format(BreakUpLargeNumbers(xp), BreakUpLargeNumbers(totalLevelXP), calc1), 1, 1, 1); Reports.ToolTip:AddDoubleLine(L["Remaining:"], (" %s "):format(BreakUpLargeNumbers(xpToNextLevel)), 1, 1, 1); else Reports.ToolTip:AddDoubleLine(L["No Heart of Azeroth"]); end end local function FormatPower(level, currXP, totalLevel, nextLevel) local calc1 = (currXP / totalLevel) * 100; local currentText = ("Level: %d (%s%d%%|r)"):format(level, percColors[calc1 >= 75 and 1 or (calc1 >= 50 and calc1 < 75) and 2 or (calc1 >= 25 and calc1 < 50) and 3 or (calc1 >= 0 and calc1 < 25) and 4], calc1); return currentText; end --[[ ########################################################## REPORT TEMPLATE ########################################################## ]]-- local REPORT_NAME = "Azerite"; local HEX_COLOR = "22FFFF"; --SV.media.color.green --SV.media.color.normal --r, g, b = 0.8, 0.8, 0.8 --local c = SV.media.color.green --r, g, b = c[1], c[2], c[3] local Report = Reports:NewReport(REPORT_NAME, { type = "data source", text = REPORT_NAME .. " Info", icon = [[Interface\Addons\SVUI_!Core\assets\icons\SVUI]] }); Report.events = {"PLAYER_ENTERING_WORLD","AZERITE_ITEM_EXPERIENCE_CHANGED"}; Report.OnEvent = function(self, event, ...) if (event == "AZERITE_ITEM_EXPERIENCE_CHANGED") then ReportBar.Populate(self); end end Report.Populate = function(self) if self.barframe:IsShown() then self.text:SetAllPoints(self); self.text:SetJustifyH("CENTER"); self.barframe:Hide(); end if isEquipped then local xp, totalLevelXP = C_AzeriteItem.GetAzeriteItemXPInfo(isEquipped); local currentLevel = C_AzeriteItem.GetPowerLevel(isEquipped); local xpToNextLevel = totalLevelXP - xp; local text = FormatPower(currentLevel, xp, totalLevelXP, xpToNextLevel); self.text:SetText(text); else self.text:SetText(L["No Heart of Azeroth"]); end end Report.OnEnter = function(self) SetTooltipText(self); Reports:ShowDataTip(); end Report.OnInit = function(self) if(not self.InnerData) then self.InnerData = {}; end Report.Populate(self); end --[[ ########################################################## BAR TYPE ########################################################## ]]-- local BAR_NAME = "Azerite Bar"; local ReportBar = Reports:NewReport(BAR_NAME, { type = "data source", text = BAR_NAME, icon = [[Interface\Addons\SVUI_!Core\assets\icons\SVUI]] }); ReportBar.events = {"PLAYER_ENTERING_WORLD","AZERITE_ITEM_EXPERIENCE_CHANGED"}; ReportBar.OnEvent = function(self, event, ...) if (event == "AZERITE_ITEM_EXPERIENCE_CHANGED") then ReportBar.Populate(self); end end ReportBar.Populate = function(self) if (not self.barframe:IsShown())then self.barframe:Show(); self.barframe.icon.texture:SetTexture(SV.media.dock.azeriteLabel); end local bar = self.barframe.bar; if isEquipped then local xp, totalLevelXP = C_AzeriteItem.GetAzeriteItemXPInfo(isEquipped); local currentLevel = C_AzeriteItem.GetPowerLevel(isEquipped); local xpToNextLevel = totalLevelXP - xp; bar:SetMinMaxValues(0, totalLevelXP); bar:SetValue(xp); bar:SetStatusBarColor(0.9, 0.64, 0.37); local toSpend = "Level "..currentLevel; self.text:SetText(toSpend); self.barframe:Show(); else bar:SetMinMaxValues(0, 1); bar:SetValue(0); self.text:SetText(L["No Heart of Azeroth"]); end end ReportBar.OnEnter = function(self) SetTooltipText(self); Reports:ShowDataTip(); end ReportBar.OnInit = function(self) if(not self.InnerData) then self.InnerData = {}; end ReportBar.Populate(self); if (not self.barframe:IsShown())then self.barframe:Show(); self.barframe.icon.texture:SetTexture(SV.media.dock.azeriteLabel); end end
--[[ ############################################################################## S V U I By: Failcoder ############################################################################## ########################################################## LOCALIZED LUA FUNCTIONS ########################################################## ]]-- --[[ GLOBALS ]]-- local _G = _G; local select = _G.select; local pairs = _G.pairs; local ipairs = _G.ipairs; local type = _G.type; local error = _G.error; local pcall = _G.pcall; local assert = _G.assert; local tostring = _G.tostring; local tonumber = _G.tonumber; local string = _G.string; local math = _G.math; local table = _G.table; --[[ STRING METHODS ]]-- local lower, upper = string.lower, string.upper; local find, format, len, split = string.find, string.format, string.len, string.split; local match, sub, join = string.match, string.sub, string.join; local gmatch, gsub = string.gmatch, string.gsub; --[[ MATH METHODS ]]-- local abs, ceil, floor, round = math.abs, math.ceil, math.floor, math.round; -- Basic --[[ TABLE METHODS ]]-- local twipe, tsort = table.wipe, table.sort; --[[ ########################################################## GET ADDON DATA ########################################################## ]]-- local SV = select(2, ...) local L = SV.L local Reports = SV.Reports; --[[ ########################################################## UTILITIES ########################################################## ]]-- local percColors = { "|cff0CD809", "|cffE8DA0F", "|cffFF9000", "|cffD80909" } local function SetTooltipText(report) Reports:SetDataTip(report); Reports.ToolTip:AddLine(L["Heart of Azeroth"]); Reports.ToolTip:AddLine(" "); local azeriteItemLocation = C_AzeriteItem.FindActiveAzeriteItem(); if (not azeriteItemLocation) then Reports.ToolTip:AddDoubleLine(L["No Heart of Azeroth"]); return; end local xp, totalLevelXP = C_AzeriteItem.GetAzeriteItemXPInfo(azeriteItemLocation); local currentLevel = C_AzeriteItem.GetPowerLevel(azeriteItemLocation); local xpToNextLevel = totalLevelXP - xp; local calc1 = (xp / totalLevelXP) * 100; Reports.ToolTip:AddDoubleLine(L["Current Level:"], (" %d "):format(currentLevel), 1, 1, 1); Reports.ToolTip:AddDoubleLine(L["Current Artifact Power:"], (" %s / %s (%d%%)"):format(BreakUpLargeNumbers(xp), BreakUpLargeNumbers(totalLevelXP), calc1), 1, 1, 1); Reports.ToolTip:AddDoubleLine(L["Remaining:"], (" %s "):format(BreakUpLargeNumbers(xpToNextLevel)), 1, 1, 1); end local function FormatPower(level, currXP, totalLevel, nextLevel) local calc1 = (currXP / totalLevel) * 100; local currentText = ("Level: %d (%s%d%%|r)"):format(level, percColors[calc1 >= 75 and 1 or (calc1 >= 50 and calc1 < 75) and 2 or (calc1 >= 25 and calc1 < 50) and 3 or (calc1 >= 0 and calc1 < 25) and 4], calc1); return currentText; end --[[ ########################################################## REPORT TEMPLATE ########################################################## ]]-- local REPORT_NAME = "Azerite"; local HEX_COLOR = "22FFFF"; --SV.media.color.green --SV.media.color.normal --r, g, b = 0.8, 0.8, 0.8 --local c = SV.media.color.green --r, g, b = c[1], c[2], c[3] local Report = Reports:NewReport(REPORT_NAME, { type = "data source", text = REPORT_NAME .. " Info", icon = [[Interface\Addons\SVUI_!Core\assets\icons\SVUI]] }); Report.events = {"PLAYER_ENTERING_WORLD"}; Report.OnEvent = function(self, event, ...) if (event == "AZERITE_ITEM_EXPERIENCE_CHANGED") then ReportBar.Populate(self); end end Report.Populate = function(self) if self.barframe:IsShown() then self.text:SetAllPoints(self); self.text:SetJustifyH("CENTER"); self.barframe:Hide(); end local azeriteItemLocation = C_AzeriteItem.FindActiveAzeriteItem(); if (not azeriteItemLocation) then Reports.ToolTip:AddDoubleLine(L["No Heart of Azeroth"]); return; end local xp, totalLevelXP = C_AzeriteItem.GetAzeriteItemXPInfo(azeriteItemLocation); local currentLevel = C_AzeriteItem.GetPowerLevel(azeriteItemLocation); local xpToNextLevel = totalLevelXP - xp; local text = FormatPower(currentLevel, xp, totalLevelXP, xpToNextLevel); self.text:SetText(text); end Report.OnEnter = function(self) SetTooltipText(self); Reports:ShowDataTip(); end Report.OnInit = function(self) if(not self.InnerData) then self.InnerData = {}; end Report.Populate(self); end --[[ ########################################################## BAR TYPE ########################################################## ]]-- local BAR_NAME = "Azerite Bar"; local ReportBar = Reports:NewReport(BAR_NAME, { type = "data source", text = BAR_NAME, icon = [[Interface\Addons\SVUI_!Core\assets\icons\SVUI]] }); ReportBar.events = {"PLAYER_ENTERING_WORLD"}; ReportBar.OnEvent = function(self, event, ...) if (event == "AZERITE_ITEM_EXPERIENCE_CHANGED") then ReportBar.Populate(self); end end ReportBar.Populate = function(self) if (not self.barframe:IsShown())then self.barframe:Show(); self.barframe.icon.texture:SetTexture(SV.media.dock.azeriteLabel); end local bar = self.barframe.bar; local azeriteItemLocation = C_AzeriteItem.FindActiveAzeriteItem(); if (not azeriteItemLocation) then bar:SetMinMaxValues(0, 1); bar:SetValue(0); self.text:SetText(L["No Heart of Azeroth"]); return; end local xp, totalLevelXP = C_AzeriteItem.GetAzeriteItemXPInfo(azeriteItemLocation); local currentLevel = C_AzeriteItem.GetPowerLevel(azeriteItemLocation); local xpToNextLevel = totalLevelXP - xp; bar:SetMinMaxValues(0, totalLevelXP); bar:SetValue(xp); bar:SetStatusBarColor(0.9, 0.64, 0.37); local toSpend = "Level "..currentLevel; self.text:SetText(toSpend); self.barframe:Show(); end ReportBar.OnEnter = function(self) SetTooltipText(self); Reports:ShowDataTip(); end ReportBar.OnInit = function(self) if(not self.InnerData) then self.InnerData = {}; end ReportBar.Populate(self); if (not self.barframe:IsShown())then self.barframe:Show(); self.barframe.icon.texture:SetTexture(SV.media.dock.azeriteLabel); end end
Azerite Reload Fix
Azerite Reload Fix
Lua
mit
FailcoderAddons/supervillain-ui
15a6e42e692e1a3b72b087d98b1b1518f1bee799
share/playlist/youtube.lua
share/playlist/youtube.lua
-- libquvi-scripts -- Copyright (C) 2012 Toni Gundogdu <[email protected]> -- -- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>. -- -- This program is free software: you can redistribute it and/or -- modify it under the terms of the GNU Affero General Public -- License as published by the Free Software Foundation, either -- version 3 of the License, or (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU Affero General Public License for more details. -- -- You should have received a copy of the GNU Affero General -- Public License along with this program. If not, see -- <http://www.gnu.org/licenses/>. -- local YouTube = {} -- Utility functions unique to this script -- Identify the playlist script. function ident(qargs) return { domains = table.concat({'youtube.com'}, ','), can_parse_url = YouTube.can_parse_url(qargs) } end -- Parse playlist properties. function parse(qargs) qargs.id = qargs.input_url:match('list=(%w+)') while #qargs.id > 16 do -- Strip playlist ID prefix (e.g. "PL") qargs.id = qargs.id:gsub("^%w", "") end if #qargs.id < 16 then error('no match: playlist ID') end local Y = require 'quvi/youtube' local P = require 'lxp.lom' local max_results = 25 local start_index = 1 qargs.media = {} local C = require 'quvi/const' local o = { [C.qfo_type] = C.qft_playlist } local r = {} -- TODO: Return playlist thumbnail URL -- TODO: Return playlist title repeat -- Get the entire playlist. local u = YouTube.config_url(qargs, start_index, max_results) local c = quvi.fetch(u, o) local x = P.parse(c) YouTube.chk_error_resp(x) r = YouTube.parse_media_urls(x) for _,u in pairs(r) do local t = { url = u } table.insert(qargs.media, t) end start_index = start_index + #r until #r == 0 return qargs end -- -- Utility functions -- function YouTube.can_parse_url(qargs) local U = require 'socket.url' local t = U.parse(qargs.input_url) if t and t.scheme and t.scheme:lower():match('^https?$') and t.host and t.host:lower():match('youtube%.com$') and t.query and t.query:lower():match('list=%w+') then return true else return false end end function YouTube.config_url(qargs, start_index, max_results) return string.format( -- Refer to http://is.gd/0msY8X 'http://gdata.youtube.com/feeds/api/playlists/%s?v=2' .. '&start-index=%s&max-results=%s&strict=true', qargs.id, start_index, max_results) end function YouTube.parse_media_urls(t) -- TODO: Return media duration_ms -- TODO: Return media title local r = {} if not t then return r end for i=1, #t do if t[i].tag == 'entry' then for j=1, #t[i] do if t[i][j].tag == 'link' then if t[i][j].attr['rel'] == 'alternate' then table.insert(r, t[i][j].attr['href']) end end end end end return r end function YouTube.chk_error_resp(t) if not t then return end local r = {} for i=1, #t do if t[i].tag == 'error' then for j=1, #t[i] do if t[i][j].tag == 'domain' then r.domain = t[i][j][1] end if t[i][j].tag == 'code' then r.code = t[i][j][1] end if t[i][j].tag == 'internalReason' then r.reason = t[i][j][1] end if t[i][j].tag == 'location' then -- Ignores 'type' attribute. r.location = t[i][j][1] end end end end if #r >0 then local m for k,v in pairs(r) do m = m .. string.format("%s=%s ", k,v) end error(m) end end -- vim: set ts=2 sw=2 tw=72 expandtab:
-- libquvi-scripts -- Copyright (C) 2012 Toni Gundogdu <[email protected]> -- -- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>. -- -- This program is free software: you can redistribute it and/or -- modify it under the terms of the GNU Affero General Public -- License as published by the Free Software Foundation, either -- version 3 of the License, or (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU Affero General Public License for more details. -- -- You should have received a copy of the GNU Affero General -- Public License along with this program. If not, see -- <http://www.gnu.org/licenses/>. -- local YouTube = {} -- Utility functions unique to this script -- Identify the playlist script. function ident(qargs) return { domains = table.concat({'youtube.com'}, ','), can_parse_url = YouTube.can_parse_url(qargs) } end -- Parse playlist properties. function parse(qargs) qargs.id = qargs.input_url:match('list=([%w_-]+)') if #qargs.id <16 then error('no match: playlist ID') end local Y = require 'quvi/youtube' local P = require 'lxp.lom' local max_results = 25 local start_index = 1 qargs.media = {} local C = require 'quvi/const' local o = { [C.qfo_type] = C.qft_playlist } local r = {} -- TODO: Return playlist thumbnail URL -- TODO: Return playlist title repeat -- Get the entire playlist. local u = YouTube.config_url(qargs, start_index, max_results) local c = quvi.fetch(u, o) local x = P.parse(c) YouTube.chk_error_resp(x) r = YouTube.parse_media_urls(x) for _,u in pairs(r) do local t = { url = u } table.insert(qargs.media, t) end start_index = start_index + #r until #r == 0 return qargs end -- -- Utility functions -- function YouTube.can_parse_url(qargs) local U = require 'socket.url' local t = U.parse(qargs.input_url) if t and t.scheme and t.scheme:lower():match('^https?$') and t.host and t.host:lower():match('youtube%.com$') and t.query and t.query:lower():match('list=[%w_-]+') then return true else return false end end function YouTube.config_url(qargs, start_index, max_results) return string.format( -- Refer to http://is.gd/0msY8X 'http://gdata.youtube.com/feeds/api/playlists/%s?v=2' .. '&start-index=%s&max-results=%s&strict=true', qargs.id, start_index, max_results) end function YouTube.parse_media_urls(t) -- TODO: Return media duration_ms -- TODO: Return media title local r = {} if not t then return r end for i=1, #t do if t[i].tag == 'entry' then for j=1, #t[i] do if t[i][j].tag == 'link' then if t[i][j].attr['rel'] == 'alternate' then table.insert(r, t[i][j].attr['href']) end end end end end return r end function YouTube.chk_error_resp(t) if not t then return end local r = {} for i=1, #t do if t[i].tag == 'error' then for j=1, #t[i] do if t[i][j].tag == 'domain' then r.domain = t[i][j][1] end if t[i][j].tag == 'code' then r.code = t[i][j][1] end if t[i][j].tag == 'internalReason' then r.reason = t[i][j][1] end if t[i][j].tag == 'location' then -- Ignores 'type' attribute. r.location = t[i][j][1] end end end end if #r >0 then local m for k,v in pairs(r) do m = m .. string.format("%s=%s ", k,v) end error(m) end end -- vim: set ts=2 sw=2 tw=72 expandtab:
FIX: playlist/youtube.lua: ID pattern
FIX: playlist/youtube.lua: ID pattern Signed-off-by: Toni Gundogdu <[email protected]>
Lua
agpl-3.0
legatvs/libquvi-scripts,legatvs/libquvi-scripts,alech/libquvi-scripts,alech/libquvi-scripts
e578c2db7c8a93fd1ac6999b9ba6f1b5c3a74406
xmake/tools/ml.lua
xmake/tools/ml.lua
--!The Make-like Build Utility based on Lua -- -- 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 ml.lua -- -- init it function init(shellname) -- save name _g.shellname = shellname or "ml.exe" -- init asflags _g.asflags = { "-nologo", "-Gd", "-MP4", "-D_MBCS", "-D_CRT_SECURE_NO_WARNINGS"} -- init flags map _g.mapflags = { -- optimize ["-O0"] = "-Od" , ["-O3"] = "-Ot" , ["-Ofast"] = "-Ox" , ["-fomit-frame-pointer"] = "-Oy" -- symbols , ["-g"] = "-Z7" , ["-fvisibility=.*"] = "" -- warnings , ["-Wall"] = "-W3" -- = "-Wall" will enable too more warnings , ["-W1"] = "-W1" , ["-W2"] = "-W2" , ["-W3"] = "-W3" , ["-Werror"] = "-WX" , ["%-Wno%-error=.*"] = "" -- vectorexts , ["-mmmx"] = "-arch:MMX" , ["-msse"] = "-arch:SSE" , ["-msse2"] = "-arch:SSE2" , ["-msse3"] = "-arch:SSE3" , ["-mssse3"] = "-arch:SSSE3" , ["-mavx"] = "-arch:AVX" , ["-mavx2"] = "-arch:AVX2" , ["-mfpu=.*"] = "" -- others , ["-ftrapv"] = "" , ["-fsanitize=address"] = "" } 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 complie command function compcmd(sourcefile, objectfile, flags) -- make it return format("%s -c %s -Fo%s %s", _g.shellname, flags, objectfile, sourcefile) end -- complie the source file function compile(sourcefile, objectfile, flags, multitasking) -- ensure the object directory os.mkdir(path.directory(objectfile)) -- compile it if multitasking then os.corun(compcmd(sourcefile, objectfile, flags)) else os.run(compcmd(sourcefile, objectfile, flags)) end end -- check the given flags function check(flags) -- make an stub source file local objectfile = os.tmpfile() .. ".obj" local sourcefile = os.tmpfile() .. ".asm" io.write(sourcefile, "end") -- check it os.run("%s -c %s -Fo%s %s", _g.shellname, ifelse(flags, flags, ""), objectfile, sourcefile) -- remove files os.rm(objectfile) os.rm(sourcefile) end
--!The Make-like Build Utility based on Lua -- -- 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 ml.lua -- -- init it function init(shellname) -- save name _g.shellname = shellname or "ml.exe" -- init asflags _g.asflags = { "-nologo", "-Gd", "-MP4", "-D_MBCS", "-D_CRT_SECURE_NO_WARNINGS"} -- init flags map _g.mapflags = { -- optimize ["-O0"] = "-Od" , ["-O3"] = "-Ot" , ["-Ofast"] = "-Ox" , ["-fomit-frame-pointer"] = "-Oy" -- symbols , ["-g"] = "-Z7" , ["-fvisibility=.*"] = "" -- warnings , ["-Wall"] = "-W3" -- = "-Wall" will enable too more warnings , ["-W1"] = "-W1" , ["-W2"] = "-W2" , ["-W3"] = "-W3" , ["-Werror"] = "-WX" , ["%-Wno%-error=.*"] = "" -- vectorexts , ["-mmmx"] = "-arch:MMX" , ["-msse"] = "-arch:SSE" , ["-msse2"] = "-arch:SSE2" , ["-msse3"] = "-arch:SSE3" , ["-mssse3"] = "-arch:SSSE3" , ["-mavx"] = "-arch:AVX" , ["-mavx2"] = "-arch:AVX2" , ["-mfpu=.*"] = "" -- others , ["-ftrapv"] = "" , ["-fsanitize=address"] = "" } end -- get the property function get(name) -- get it return _g[name] end -- make the symbol flag function symbol(level, symbolfile) -- check -FS flags if _g._FS == nil then local ok = try { function () check("-ZI -FS -Fd" .. os.tmpfile() .. ".pdb") return true end } if ok then _g._FS = true end end -- debug? generate *.pdb file local flags = "" if level == "debug" then if symbolfile then flags = "-ZI -Fd" .. symbolfile if _g._FS then flags = "-FS " .. flags end else flags = "-ZI" end end -- none return flags end -- make the warning flag function warning(level) -- the maps local maps = { none = "-w" , less = "-W1" , more = "-W3" , all = "-W3" , error = "-WX" } -- make it return maps[level] or "" end -- make the optimize flag function optimize(level) -- the maps local maps = { none = "-Od" , fast = "-O1" , faster = "-O2" , fastest = "-Ot" , smallest = "-Os" , aggressive = "-Ox" } -- make it return maps[level] or "" end -- make the vector extension flag function vectorext(extension) -- the maps local maps = { sse = "-arch:SSE" , sse2 = "-arch:SSE2" , avx = "-arch:AVX" , avx2 = "-arch:AVX2" } -- make it return maps[extension] or "" end -- make the language flag function language(stdname) return "" 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 complie command function compcmd(sourcefile, objectfile, flags) -- make it return format("%s -c %s -Fo%s %s", _g.shellname, flags, objectfile, sourcefile) end -- complie the source file function compile(sourcefile, objectfile, incdepfile, flags) -- ensure the object directory os.mkdir(path.directory(objectfile)) -- compile it os.run(compcmd(sourcefile, objectfile, flags)) end -- check the given flags function check(flags) -- make an stub source file local objectfile = os.tmpfile() .. ".obj" local sourcefile = os.tmpfile() .. ".asm" io.write(sourcefile, "end") -- check it os.run("%s -c %s -Fo%s %s", _g.shellname, ifelse(flags, flags, ""), objectfile, sourcefile) -- remove files os.rm(objectfile) os.rm(sourcefile) end
fix ml assember tool
fix ml assember tool
Lua
apache-2.0
waruqi/xmake,waruqi/xmake,waruqi/xmake,tboox/xmake,waruqi/xmake,tboox/xmake,tboox/xmake,tboox/xmake,tboox/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,tboox/xmake,tboox/xmake
71316cc3949fb057ba63f5f78e8bbf75323f361d
bin/luvit-config.lua
bin/luvit-config.lua
#!/usr/bin/env luvit --[[ Copyright 2012 The Luvit Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] local Table = require('table') local OS = require('os') local command = process.argv[1] if command == "--libs" then local flags = { "-shared", "-lm" } if OS.type() == "Darwin" then if false then -- TODO: check if 64 bit Table.insert(flags, "-pagezero_size 10000") Table.insert(flags, "-image_base 100000000") end Table.insert(flags, "-undefined dynamic_lookup") end print(Table.concat(flags, " ")) elseif command == "--cflags" then local Path = require('path') local UV = require('uv') local Fs = require('fs') -- calculate includes relative to the binary local include_dir = Path.resolve(Path.dirname(UV.execpath()), "../include/luvit") -- if not found... if not Fs.existsSync(include_dir) then -- calculate includes relative to the symlink to the binary include_dir = Path.resolve(__dirname, "../include/luvit") end local flags = { "-I" .. include_dir, "-I" .. include_dir .. "/http_parser", "-I" .. include_dir .. "/uv", "-I" .. include_dir .. "/luajit", "-D_LARGEFILE_SOURCE", "-D_FILE_OFFSET_BITS=64", "-Wall -Werror", "-fPIC" } print(Table.concat(flags, " ")) elseif command == "--version" or command == "-v" then print(process.version) else print "Usage: luvit-config [--version] [--cflags] [--libs]" -- Also note about rebase for OSX 64bit? <http://luajit.org/install.html#embed> end
#!/usr/bin/env luvit --[[ Copyright 2012 The Luvit Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] local Table = require('table') local OS = require('os') local command = process.argv[1] if command == "--libs" then local flags = { "-shared", "-lm" } if OS.type() == "Darwin" then if false then -- TODO: check if 64 bit Table.insert(flags, "-pagezero_size 10000") Table.insert(flags, "-image_base 100000000") end Table.insert(flags, "-undefined dynamic_lookup") end print(Table.concat(flags, " ")) elseif command == "--cflags" then local Path = require('path') local Fs = require('fs') -- calculate includes relative to the binary local include_dir = Path.resolve(Path.dirname(process.execPath), "../include/luvit") -- if not found... if not Fs.existsSync(include_dir) then -- calculate includes relative to the symlink to the binary include_dir = Path.resolve(__dirname, "../include/luvit") end local flags = { "-I" .. include_dir, "-I" .. include_dir .. "/http_parser", "-I" .. include_dir .. "/uv", "-I" .. include_dir .. "/luajit", "-D_LARGEFILE_SOURCE", "-D_FILE_OFFSET_BITS=64", "-Wall -Werror", "-fPIC" } print(Table.concat(flags, " ")) elseif command == "--version" or command == "-v" then print(process.version) else print "Usage: luvit-config [--version] [--cflags] [--libs]" -- Also note about rebase for OSX 64bit? <http://luajit.org/install.html#embed> end
Fix luvit-config for the recent uv->uv_native API change
Fix luvit-config for the recent uv->uv_native API change
Lua
apache-2.0
boundary/luvit,DBarney/luvit,zhaozg/luvit,kaustavha/luvit,DBarney/luvit,kaustavha/luvit,connectFree/lev,boundary/luvit,sousoux/luvit,luvit/luvit,AndrewTsao/luvit,kaustavha/luvit,GabrielNicolasAvellaneda/luvit-upstream,bsn069/luvit,sousoux/luvit,AndrewTsao/luvit,rjeli/luvit,sousoux/luvit,boundary/luvit,AndrewTsao/luvit,bsn069/luvit,sousoux/luvit,sousoux/luvit,luvit/luvit,GabrielNicolasAvellaneda/luvit-upstream,connectFree/lev,rjeli/luvit,GabrielNicolasAvellaneda/luvit-upstream,sousoux/luvit,boundary/luvit,boundary/luvit,rjeli/luvit,boundary/luvit,DBarney/luvit,rjeli/luvit,DBarney/luvit,zhaozg/luvit,GabrielNicolasAvellaneda/luvit-upstream,bsn069/luvit
92fa8584fa62e12e4df579c2d16ef9d11c1e13b5
libs/core/luasrc/model/network.lua
libs/core/luasrc/model/network.lua
--[[ LuCI - Network model Copyright 2009 Jo-Philipp Wich <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ]]-- local type, pairs, ipairs, table = type, pairs, ipairs, table local lmo = require "lmo" local nxo = require "nixio" local iwi = require "iwinfo" local ipc = require "luci.ip" local utl = require "luci.util" local uct = require "luci.model.uci.bind" module "luci.model.network" local ub = uct.bind("network") local ifs, brs function init(cursor) if cursor then cursor:unload("network") cursor:load("network") ub:init(cursor) ifs = { } brs = { } -- read interface information local n, i for n, i in ipairs(nxo.getifaddrs()) do local name = i.name:match("[^:]+") if not _M:ignore_interface(name) then ifs[name] = ifs[name] or { idx = i.ifindex or n, name = name, rawname = i.name, flags = { }, ipaddrs = { }, ip6addrs = { } } if i.family == "packet" then ifs[name].flags = i.flags ifs[name].stats = i.data ifs[name].macaddr = i.addr elseif i.family == "inet" then ifs[name].ipaddrs[#ifs[name].ipaddrs+1] = ipc.IPv4(i.addr, i.netmask) elseif i.family == "inet6" then ifs[name].ip6addrs[#ifs[name].ip6addrs+1] = ipc.IPv6(i.addr, i.netmask) end end end -- read bridge informaton local b, l for l in utl.execi("brctl show") do if not l:match("STP") then local r = utl.split(l, "%s+", nil, true) if #r == 4 then b = { name = r[1], id = r[2], stp = r[3] == "yes", ifnames = { ifs[r[4]] } } if b.ifnames[1] then b.ifnames[1].bridge = b end brs[r[1]] = b elseif b then b.ifnames[#b.ifnames+1] = ifs[r[2]] b.ifnames[#b.ifnames].bridge = b end end end end end function add_network(self, n, options) if n and #n > 0 and n:match("^[a-zA-Z0-9_]+$") and not self:get_network(n) then if ub.uci:section("network", "interface", n, options) then return network(n) end end end function get_network(self, n) if n and ub.uci:get("network", n) == "interface" then return network(n) end end function get_networks(self) local nets = { } ub.uci:foreach("network", "interface", function(s) nets[#nets+1] = network(s['.name']) end) return nets end function del_network(self, n) local r = ub.uci:delete("network", n) if r then ub.uci:foreach("network", "alias", function(s) if s.interface == n then ub.uci:delete("network", s['.name']) end end) ub.uci:foreach("network", "route", function(s) if s.interface == n then ub.uci:delete("network", s['.name']) end end) ub.uci:foreach("network", "route6", function(s) if s.interface == n then ub.uci:delete("network", s['.name']) end end) end return r end function rename_network(self, old, new) local r if new and #new > 0 and new:match("^[a-zA-Z0-9_]+$") and not self:get_network(new) then r = ub.uci:section("network", "interface", new, ub.uci:get_all("network", old)) if r then ub.uci:foreach("network", "alias", function(s) if s.interface == old then ub.uci:set("network", s['.name'], "interface", new) end end) ub.uci:foreach("network", "route", function(s) if s.interface == old then ub.uci:set("network", s['.name'], "interface", new) end end) ub.uci:foreach("network", "route6", function(s) if s.interface == old then ub.uci:set("network", s['.name'], "interface", new) end end) end end return r or false end function get_interface(self, i) return ifs[i] and interface(i) end function get_interfaces(self) local ifaces = { } local iface for iface, _ in pairs(ifs) do ifaces[#ifaces+1] = interface(iface) end return ifaces end function ignore_interface(self, x) return (x:match("^wmaster%d") or x:match("^wifi%d") or x:match("^hwsim%d") or x:match("^imq%d") or x == "lo") end network = ub:section("interface") network:property("device") network:property("ifname") network:property("proto") network:property("type") function network.name(self) return self.sid end function network.is_bridge(self) return (self:type() == "bridge") end function network.add_interface(self, ifname) if type(ifname) ~= "string" then ifname = ifname:ifname() end if ifs[ifname] then self:ifname(ub:list((self:ifname() or ''), ifname)) end end function network.del_interface(self, ifname) if type(ifname) ~= "string" then ifname = ifname:ifname() end self:ifname(ub:list((self:ifname() or ''), nil, ifname)) end function network.get_interfaces(self) local ifaces = { } local iface for _, iface in ub:list( (self:ifname() or '') .. ' ' .. (self:device() or '') ) do iface = iface:match("[^:]+") if ifs[iface] then ifaces[#ifaces+1] = interface(iface) end end return ifaces end function contains_interface(self, iface) local i local ifaces = ub:list( (self:ifname() or '') .. ' ' .. (self:device() or '') ) if type(iface) ~= "string" then iface = iface:ifname() end for _, i in ipairs(ifaces) do if i == iface then return true end end return false end interface = utl.class() function interface.__init__(self, ifname) if ifs[ifname] then self.ifname = ifname self.dev = ifs[ifname] self.br = brs[ifname] end end function interface.name(self) return self.ifname end function interface.type(self) if iwi.type(self.ifname) and iwi.type(self.ifname) ~= "dummy" then return "wifi" elseif brs[self.ifname] then return "bridge" elseif self.ifname:match("%.") then return "switch" else return "ethernet" end end function interface.ports(self) if self.br then local iface local ifaces = { } for _, iface in ipairs(self.br.ifnames) do ifaces[#ifaces+1] = interface(iface) end return ifaces end end function interface.is_up(self) return self.dev.flags and self.dev.flags.up end function interface.is_bridge(self) return (self:type() == "bridge") end function interface.get_network(self) local net for _, net in ipairs(_M:get_networks()) do if net:contains_interface(self.ifname) then return net end end end
--[[ LuCI - Network model Copyright 2009 Jo-Philipp Wich <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ]]-- local type, pairs, ipairs, table, i18n = type, pairs, ipairs, table, luci.i18n local lmo = require "lmo" local nxo = require "nixio" local iwi = require "iwinfo" local ipc = require "luci.ip" local utl = require "luci.util" local uct = require "luci.model.uci.bind" module "luci.model.network" local ub = uct.bind("network") local ifs, brs function init(cursor) if cursor then cursor:unload("network") cursor:load("network") ub:init(cursor) ifs = { } brs = { } -- read interface information local n, i for n, i in ipairs(nxo.getifaddrs()) do local name = i.name:match("[^:]+") if not _M:ignore_interface(name) then ifs[name] = ifs[name] or { idx = i.ifindex or n, name = name, rawname = i.name, flags = { }, ipaddrs = { }, ip6addrs = { } } if i.family == "packet" then ifs[name].flags = i.flags ifs[name].stats = i.data ifs[name].macaddr = i.addr elseif i.family == "inet" then ifs[name].ipaddrs[#ifs[name].ipaddrs+1] = ipc.IPv4(i.addr, i.netmask) elseif i.family == "inet6" then ifs[name].ip6addrs[#ifs[name].ip6addrs+1] = ipc.IPv6(i.addr, i.netmask) end end end -- read bridge informaton local b, l for l in utl.execi("brctl show") do if not l:match("STP") then local r = utl.split(l, "%s+", nil, true) if #r == 4 then b = { name = r[1], id = r[2], stp = r[3] == "yes", ifnames = { ifs[r[4]] } } if b.ifnames[1] then b.ifnames[1].bridge = b end brs[r[1]] = b elseif b then b.ifnames[#b.ifnames+1] = ifs[r[2]] b.ifnames[#b.ifnames].bridge = b end end end end end function add_network(self, n, options) if n and #n > 0 and n:match("^[a-zA-Z0-9_]+$") and not self:get_network(n) then if ub.uci:section("network", "interface", n, options) then return network(n) end end end function get_network(self, n) if n and ub.uci:get("network", n) == "interface" then return network(n) end end function get_networks(self) local nets = { } ub.uci:foreach("network", "interface", function(s) nets[#nets+1] = network(s['.name']) end) return nets end function del_network(self, n) local r = ub.uci:delete("network", n) if r then ub.uci:foreach("network", "alias", function(s) if s.interface == n then ub.uci:delete("network", s['.name']) end end) ub.uci:foreach("network", "route", function(s) if s.interface == n then ub.uci:delete("network", s['.name']) end end) ub.uci:foreach("network", "route6", function(s) if s.interface == n then ub.uci:delete("network", s['.name']) end end) end return r end function rename_network(self, old, new) local r if new and #new > 0 and new:match("^[a-zA-Z0-9_]+$") and not self:get_network(new) then r = ub.uci:section("network", "interface", new, ub.uci:get_all("network", old)) if r then ub.uci:foreach("network", "alias", function(s) if s.interface == old then ub.uci:set("network", s['.name'], "interface", new) end end) ub.uci:foreach("network", "route", function(s) if s.interface == old then ub.uci:set("network", s['.name'], "interface", new) end end) ub.uci:foreach("network", "route6", function(s) if s.interface == old then ub.uci:set("network", s['.name'], "interface", new) end end) end end return r or false end function get_interface(self, i) return ifs[i] and interface(i) end function get_interfaces(self) local ifaces = { } local iface for iface, _ in pairs(ifs) do ifaces[#ifaces+1] = interface(iface) end return ifaces end function ignore_interface(self, x) return (x:match("^wmaster%d") or x:match("^wifi%d") or x:match("^hwsim%d") or x:match("^imq%d") or x == "lo") end network = ub:section("interface") network:property("device") network:property("ifname") network:property("proto") network:property("type") function network.name(self) return self.sid end function network.is_bridge(self) return (self:type() == "bridge") end function network.add_interface(self, ifname) if type(ifname) ~= "string" then ifname = ifname:name() end if ifs[ifname] then self:ifname(ub:list((self:ifname() or ''), ifname)) end end function network.del_interface(self, ifname) if type(ifname) ~= "string" then ifname = ifname:name() end self:ifname(ub:list((self:ifname() or ''), nil, ifname)) end function network.get_interfaces(self) local ifaces = { } local iface for _, iface in ub:list( (self:ifname() or '') .. ' ' .. (self:device() or '') ) do iface = iface:match("[^:]+") if ifs[iface] then ifaces[#ifaces+1] = interface(iface) end end return ifaces end function network.contains_interface(self, iface) local i local ifaces = ub:list( (self:ifname() or '') .. ' ' .. (self:device() or '') ) if type(iface) ~= "string" then iface = iface:name() end for _, i in ipairs(ifaces) do if i == iface then return true end end return false end interface = utl.class() function interface.__init__(self, ifname) if ifs[ifname] then self.ifname = ifname self.dev = ifs[ifname] self.br = brs[ifname] end end function interface.name(self) return self.ifname end function interface.type(self) if iwi.type(self.ifname) and iwi.type(self.ifname) ~= "dummy" then return "wifi" elseif brs[self.ifname] then return "bridge" elseif self.ifname:match("%.") then return "switch" else return "ethernet" end end function interface.get_type_i18n(self) local x = self:type() if x == "wifi" then return i18n.translate("a_s_if_wifidev", "Wireless Adapter") elseif x == "bridge" then return i18n.translate("a_s_if_bridge", "Bridge") elseif x == "switch" then return i18n.translate("a_s_if_ethswitch", "Ethernet Switch") else return i18n.translate("a_s_if_ethdev", "Ethernet Adapter") end end function interface.ports(self) if self.br then local iface local ifaces = { } for _, iface in ipairs(self.br.ifnames) do ifaces[#ifaces+1] = interface(iface) end return ifaces end end function interface.is_up(self) return self.dev.flags and self.dev.flags.up end function interface.is_bridge(self) return (self:type() == "bridge") end function interface.get_network(self) local net for _, net in ipairs(_M:get_networks()) do if net:contains_interface(self.ifname) then return net end end end
libs/core: luci.model.network: implement contains_inteface(), fix bugs
libs/core: luci.model.network: implement contains_inteface(), fix bugs git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@5379 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
Lua
apache-2.0
fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci
a8c807873bf151fff62a5f034087c30a30160d8a
vi_mode_search.lua
vi_mode_search.lua
-- Handle the vim search emulation -- Modeled on textadept's command_entry.lua local M = {} M.search_hl_indic = _SCINTILLA.next_indic_number() local function set_colours() buffer.indic_fore[M.search_hl_indic] = 0xFF0000 buffer.indic_style[M.search_hl_indic] = _SCINTILLA.constants.INDIC_ROUNDBOX buffer.indic_alpha[M.search_hl_indic] = 100 -- Find all occurrences to highlight. buffer.indicator_current = M.search_hl_indic buffer:indicator_clear_range(0, buffer.length) end M.state = { in_search_mode = false, backwards = false, pattern = "", } local state = M.state local function do_search(backwards) if state.pattern == "" then return end ui.statusbar_text = "Search: "..state.pattern local saved_pos = buffer.current_pos buffer:search_anchor() local search_flags = _SCINTILLA.constants.FIND_REGEXP local searcher = function(...) return buffer:search_next(...) end -- Search from the end. We'll jump to the first one "after" the current pos. buffer.current_pos = 0 buffer:search_anchor() pos = searcher(search_flags, state.pattern) set_colours() if pos >= 0 then local saved_flags = buffer.search_flags buffer.search_flags = search_flags local new_pos = nil -- Need to use search_in_target to find the actual search extents. buffer.target_start = 0 buffer.target_end = buffer.length local occurences = 0 local first_pos = nil local last_pos = nil while buffer:search_in_target(state.pattern) >= 0 do local match_len = buffer.target_end - buffer.target_start last_pos = buffer.target_start if first_pos == nil then first_pos = buffer.target_start end -- Work out the current pos, ie first hit after the saved position. if backwards then if buffer.target_start < saved_pos then new_pos = buffer.target_start end else -- Forwards - take the first one after saved_pos if new_pos == nil and buffer.target_start > saved_pos then new_pos = buffer.target_start end end buffer:indicator_fill_range(buffer.target_start, match_len) if buffer.target_end == buffer.target_start then -- Zero length match - not useful, abort here. buffer.current_pos = saved_pos ui.statusbar_text = "Not found" return end -- Ensure we make some progress if buffer.target_end == buffer.target_start then buffer.target_start = buffer.target_end + 1 else buffer.target_start = buffer.target_end end buffer.target_end = buffer.length if buffer.target_start >= buffer.length then break end occurences = occurences + 1 end -- Handle wrapping search if new_pos == nil then if backwards then new_pos = last_pos else new_pos = first_pos end ui.statusbar_text = "WRAPPED SEARCH" else ui.statusbar_text = "Found " .. tostring(occurences) end -- Restore global search flags buffer.search_flags = saved_flags buffer:ensure_visible(buffer:line_from_position(new_pos)) buffer:goto_pos(new_pos) buffer.selection_start = new_pos else buffer.current_pos = saved_pos vi_mode.err("Not found") end end local function handle_search_command(command) if state.in_search_mode then state.pattern = command do_search(state.backwards) state.in_search_mode = false return false -- make sure this isn't handled again end end -- Register our key bindings for the command entry local ui_ce = ui.command_entry keys.vi_search_command = { ['\n'] = function () local exitfunc = state.exitfunc state.exitfunc = nil return ui_ce.finish_mode(function(text) if string.len(text) == 0 then text = state.pattern end exitfunc(function() state.pattern = text do_search(state.backwards) end) end) end, cv = { ['\t'] = function() return keys.vi_search_command['\t']() end, }, ['\t'] = function() -- insert the string '\t' instead of tab -- FIXME: insert at correct position ??? local text = ui.command_entry:get_text() --ui_ce.enter_mode(nil) ui.command_entry:set_text(text .. "\\t") --ui_ce.enter_mode("vi_search_command") end, ['esc'] = function() ui_ce.enter_mode(nil) -- Exit command_entry mode keys.mode = "vi_command" end, ['\b'] = function() if ui.command_entry:get_text() == "" then return keys.vi_search_command['esc']() -- exit end return false -- propagate the key end, } local function start_common(exitfunc) state.in_search_mode = true state.exitfunc = exitfunc ui.command_entry:set_text("") ui.command_entry.enter_mode('vi_search_command') end function M.start(exitfunc) state.backwards = false return start_common(exitfunc) end function M.start_rev(exitfunc) state.backwards = true return start_common(exitfunc) end function M.restart() do_search(state.backwards) end function M.restart_rev() do_search(not state.backwards) end local function search_word_common(backwards) -- Search for the word under the cursor -- TODO: quote properly, or better don't use regex' -- Uses ideas from editing.lua local pos = buffer.current_pos local s, e = buffer:word_start_position(pos, true), buffer:word_end_position(pos) local word = buffer:text_range(s, e) if word == "" then return end state.pattern = '\\b' .. word .. '\\b' state.backwards = backwards if backwards then -- Avoid hitting the current word again if the cursor isn't at the -- start. buffer.current_pos = s end do_search(backwards) end function M.search_word() search_word_common(false) end function M.search_word_rev() search_word_common(true) end return M
-- Handle the vim search emulation -- Modeled on textadept's command_entry.lua local M = {} M.search_hl_indic = _SCINTILLA.next_indic_number() local function set_colours() buffer.indic_fore[M.search_hl_indic] = 0xFF0000 buffer.indic_style[M.search_hl_indic] = _SCINTILLA.constants.INDIC_ROUNDBOX buffer.indic_alpha[M.search_hl_indic] = 100 -- Find all occurrences to highlight. buffer.indicator_current = M.search_hl_indic buffer:indicator_clear_range(0, buffer.length) end M.state = { in_search_mode = false, backwards = false, pattern = "", } local state = M.state local function do_search(backwards) if state.pattern == "" then return end ui.statusbar_text = "Search: "..state.pattern local saved_pos = buffer.current_pos buffer:search_anchor() local search_flags = _SCINTILLA.constants.FIND_REGEXP local searcher = function(...) return buffer:search_next(...) end -- Search from the end. We'll jump to the first one "after" the current pos. buffer.current_pos = 0 buffer:search_anchor() pos = searcher(search_flags, state.pattern) set_colours() if pos >= 0 then local saved_flags = buffer.search_flags buffer.search_flags = search_flags local new_pos = nil -- Need to use search_in_target to find the actual search extents. buffer.target_start = 0 buffer.target_end = buffer.length local occurences = 0 local first_pos = nil local last_pos = nil while buffer:search_in_target(state.pattern) >= 0 do local match_len = buffer.target_end - buffer.target_start last_pos = buffer.target_start if first_pos == nil then first_pos = buffer.target_start end -- Work out the current pos, ie first hit after the saved position. if backwards then if buffer.target_start < saved_pos then new_pos = buffer.target_start end else -- Forwards - take the first one after saved_pos if new_pos == nil and buffer.target_start > saved_pos then new_pos = buffer.target_start end end buffer:indicator_fill_range(buffer.target_start, match_len) if buffer.target_end == buffer.target_start then -- Zero length match - not useful, abort here. buffer.current_pos = saved_pos ui.statusbar_text = "Not found" return end -- Ensure we make some progress if buffer.target_end == buffer.target_start then buffer.target_start = buffer.target_end + 1 else buffer.target_start = buffer.target_end end buffer.target_end = buffer.length if buffer.target_start >= buffer.length then break end occurences = occurences + 1 end -- Handle wrapping search if new_pos == nil then if backwards then new_pos = last_pos else new_pos = first_pos end ui.statusbar_text = "WRAPPED SEARCH" else ui.statusbar_text = "Found " .. tostring(occurences) end -- Restore global search flags buffer.search_flags = saved_flags buffer:ensure_visible(buffer:line_from_position(new_pos)) buffer:goto_pos(new_pos) buffer.selection_start = new_pos else buffer.current_pos = saved_pos vi_mode.err("Not found") end end local function handle_search_command(command) if state.in_search_mode then state.pattern = command do_search(state.backwards) state.in_search_mode = false return false -- make sure this isn't handled again end end -- Register our key bindings for the command entry local ui_ce = ui.command_entry local function finish_search(text) local exitfunc = state.exitfunc state.exitfunc = nil if string.len(text) == 0 then text = state.pattern end exitfunc(function() state.pattern = text do_search(state.backwards) end) end keys.vi_search_command = { cv = { ['\t'] = function() return keys.vi_search_command['\t']() end, }, ['\t'] = function() -- insert the string '\t' instead of tab -- FIXME: insert at correct position ??? local text = ui.command_entry:get_text() --ui_ce.enter_mode(nil) ui.command_entry:set_text(text .. "\\t") --ui_ce.enter_mode("vi_search_command") end, ['esc'] = function() ui_ce.enter_mode(nil) -- Exit command_entry mode keys.mode = "vi_command" end, ['\b'] = function() if ui.command_entry:get_text() == "" then return keys.vi_search_command['esc']() -- exit end return false -- propagate the key end, } local function start_common(exitfunc) state.in_search_mode = true state.exitfunc = exitfunc ui.command_entry:set_text("") ui.command_entry.run(finish_search) end function M.start(exitfunc) state.backwards = false return start_common(exitfunc) end function M.start_rev(exitfunc) state.backwards = true return start_common(exitfunc) end function M.restart() do_search(state.backwards) end function M.restart_rev() do_search(not state.backwards) end local function search_word_common(backwards) -- Search for the word under the cursor -- TODO: quote properly, or better don't use regex' -- Uses ideas from editing.lua local pos = buffer.current_pos local s, e = buffer:word_start_position(pos, true), buffer:word_end_position(pos) local word = buffer:text_range(s, e) if word == "" then return end state.pattern = '\\b' .. word .. '\\b' state.backwards = backwards if backwards then -- Avoid hitting the current word again if the cursor isn't at the -- start. buffer.current_pos = s end do_search(backwards) end function M.search_word() search_word_common(false) end function M.search_word_rev() search_word_common(true) end return M
Fix the search mode to use the updated command entry.
Fix the search mode to use the updated command entry.
Lua
mit
jugglerchris/textadept-vi,jugglerchris/textadept-vi
675c659d2cfc3a6ba8c282cbef28ac470208986f
Quadtastic/Text.lua
Quadtastic/Text.lua
local Text = {} local unpack = unpack or table.unpack Text.min_width = function(state, text) return state.style.font and state.style.font:getWidth(text) end -- Returns a table of lines, none of which exceed the given width. -- Returns a table with the original text if width is 0 or nil. function Text.break_at(state, text, width) if not width or width <= 0 then return {text} end local lines = {} local line = {} local line_length = 0 local separators = {" ", "-", "/", "\\", "."} local function complete_line(separator) local new_line = table.concat(line, separator) table.insert(lines, new_line) end local function break_up(chunk, sep_index) local separator = separators[sep_index] local separator_width = Text.min_width(state, separator) for word in string.gmatch(chunk, string.format("[^%s]+", separator)) do local wordlength = Text.min_width(state, word) if wordlength > width then -- Try to break at other boundaries if sep_index == #separators then print(string.format("Warning: %s is too long for one line", chunk)) else break_up(word, sep_index + 1) end elseif line_length + wordlength > width then complete_line(separator) line, line_length = {word}, wordlength else table.insert(line, word) line_length = line_length + wordlength + separator_width end end -- Add any outstanding words if #line > 0 then complete_line(separator) line, line_length = {}, 0 end end for l in string.gmatch(text, "[^\n]+") do break_up(l, 1) end return lines end Text.draw = function(state, x, y, w, h, text, options) x = x or state.layout.next_x y = y or state.layout.next_y local textwidth = Text.min_width(state, text) local textheight = 16 w = w or textwidth h = h or textheight if options then -- center alignment if options.alignment_h == ":" then x = x + w/2 - textwidth /2 -- right alignment elseif options.alignment_h == ">" then x = x + w - textwidth end -- vertically aligned to the center if options.alignment_v == "-" then y = y + h/2 - textheight/2 -- aligned to the bottom elseif options.alignment_v == "v" then y = y + h - textheight end end x = math.floor(x) y = math.floor(y) love.graphics.setFont(state.style.font) love.graphics.setColor(state.style.font_color) -- Print Text if options and options.font_color then love.graphics.setColor(unpack(options.font_color)) end love.graphics.print(text or "", x, y) end return Text
local Text = {} local unpack = unpack or table.unpack Text.min_width = function(state, text) return state.style.font and state.style.font:getWidth(text) end -- Returns a table of lines, none of which exceed the given width. -- Returns a table with the original text if width is 0 or nil. function Text.break_at(state, text, width) if not width or width <= 0 then return {text} end local lines = {} local line = {} local line_length = 0 local separators = {" ", "-", "/", "\\", "."} local function complete_line(separator) local new_line = table.concat(line, separator) table.insert(lines, new_line) end local function break_up(chunk, sep_index) local separator = separators[sep_index] local separator_width = Text.min_width(state, separator) for word in string.gmatch(chunk, string.format("[^%s]+", separator)) do local wordlength = Text.min_width(state, word) if wordlength > width then -- Try to break at other boundaries if sep_index == #separators then print(string.format("Warning: %s is too long for one line", chunk)) else if #line > 0 then complete_line(separator) line, line_length = {}, 0 end break_up(word, sep_index + 1) end elseif line_length + wordlength > width then complete_line(separator) line, line_length = {word}, wordlength else table.insert(line, word) line_length = line_length + wordlength + separator_width end end -- Add any outstanding words if #line > 0 then complete_line(separator) line, line_length = {}, 0 end end for l in string.gmatch(text, "[^\n]+") do break_up(l, 1) end return lines end Text.draw = function(state, x, y, w, h, text, options) x = x or state.layout.next_x y = y or state.layout.next_y local textwidth = Text.min_width(state, text) local textheight = 16 w = w or textwidth h = h or textheight if options then -- center alignment if options.alignment_h == ":" then x = x + w/2 - textwidth /2 -- right alignment elseif options.alignment_h == ">" then x = x + w - textwidth end -- vertically aligned to the center if options.alignment_v == "-" then y = y + h/2 - textheight/2 -- aligned to the bottom elseif options.alignment_v == "v" then y = y + h - textheight end end x = math.floor(x) y = math.floor(y) love.graphics.setFont(state.style.font) love.graphics.setColor(state.style.font_color) -- Print Text if options and options.font_color then love.graphics.setColor(unpack(options.font_color)) end love.graphics.print(text or "", x, y) end return Text
Fix issue in line splitting that would concatenate words with wrong separator
Fix issue in line splitting that would concatenate words with wrong separator
Lua
mit
25A0/Quadtastic,25A0/Quadtastic
73a6b69bfeab7f64cddcea3f4990af6d253a9281
kong/cmd/utils/serf_signals.lua
kong/cmd/utils/serf_signals.lua
-- Enhanced implementation of previous "services.serf.lua" module, -- no change in actual logic, only decoupled from the events features -- which now live in kong.serf local pl_stringx = require "pl.stringx" local pl_utils = require "pl.utils" local pl_file = require "pl.file" local Serf = require "kong.serf" local kill = require "kong.cmd.utils.kill" local log = require "kong.cmd.utils.log" local version = require "version" local fmt = string.format local serf_bin_name = "serf" local serf_event_name = "kong" local serf_version_command = " version" -- commandline param to get version local serf_version_pattern = "^Serf v([%d%.]+)" -- pattern to grab version from output local serf_compatible = version.set("0.7.0", "0.7.0") -- compatible from-to versions local start_timeout = 5 local function check_serf_bin() local cmd = fmt("%s %s", serf_bin_name, serf_version_command) local ok, _, stdout = pl_utils.executeex(cmd) if ok and stdout then local version_match = stdout:match(serf_version_pattern) if (not version_match) or (not serf_compatible:matches(version_match)) then return nil, "incompatible Serf version. Kong requires version "..tostring(serf_compatible).. (version_match and ", got "..tostring(version_match) or "") end return true end return nil, "could not find Serf executable (is it in your $PATH?)" end local _M = {} function _M.start(kong_config, dao) -- is Serf already running in this prefix? if kill.is_running(kong_config.serf_pid) then log.verbose("Serf agent already running at %s", kong_config.serf_pid) return true else log.verbose("Serf agent not running, deleting %s", kong_config.serf_pid) pl_file.delete(kong_config.serf_pid) end -- make sure Serf is in PATH local ok, err = check_serf_bin() if not ok then return nil, err end local serf = Serf.new(kong_config, dao) local args = setmetatable({ ["-bind"] = kong_config.cluster_listen, ["-rpc-addr"] = kong_config.cluster_listen_rpc, ["-advertise"] = kong_config.cluster_advertise, ["-encrypt"] = kong_config.cluster_encrypt_key, ["-log-level"] = "err", ["-profile"] = kong_config.cluster_profile, ["-node"] = serf.node_name, ["-event-handler"] = "member-join,member-leave,member-failed," .."member-update,member-reap,user:" ..serf_event_name.."="..kong_config.serf_event }, Serf.args_mt) local cmd = string.format("nohup %s agent %s > %s 2>&1 & echo $! > %s", serf_bin_name, tostring(args), kong_config.serf_log, kong_config.serf_pid) log.debug("starting Serf agent: %s", cmd) -- start Serf agent local ok = pl_utils.execute(cmd) if not ok then return nil end log.verbose("waiting for Serf agent to be running...") -- ensure started (just an improved version of previous Serf service) local tstart = ngx.time() local texp, started = tstart + start_timeout repeat ngx.sleep(0.2) started = kill.is_running(kong_config.serf_pid) until started or ngx.time() >= texp if not started then -- time to get latest error log from serf.log local logs = pl_file.read(kong_config.serf_log) local tlogs = pl_stringx.split(logs, "\n") local err = string.gsub(tlogs[#tlogs-1], "==> ", "") err = pl_stringx.strip(err) return nil, "could not start Serf: "..err end -- cleanup current node from cluster to prevent inconsistency of data local ok, err = serf:cleanup() if not ok then return nil, err end log.verbose("auto-joining Serf cluster...") local ok, err = serf:autojoin() if not ok then return nil, err end log.verbose("adding node to Serf cluster (in datastore)...") local ok, err = serf:add_node() if not ok then return nil, err end return true end function _M.stop(kong_config, dao) log.info("leaving cluster") local serf = Serf.new(kong_config, dao) local ok, err = serf:leave() if not ok then return nil, err end log.verbose("stopping Serf agent at %s", kong_config.serf_pid) local code, res = kill.kill(kong_config.serf_pid, "-15") --SIGTERM if code == 256 then -- If no error is returned pl_file.delete(kong_config.serf_pid) end return code, res end return _M
-- Enhanced implementation of previous "services.serf.lua" module, -- no change in actual logic, only decoupled from the events features -- which now live in kong.serf local pl_stringx = require "pl.stringx" local pl_utils = require "pl.utils" local pl_file = require "pl.file" local Serf = require "kong.serf" local kill = require "kong.cmd.utils.kill" local log = require "kong.cmd.utils.log" local version = require "version" local fmt = string.format local serf_bin_name = "serf" local serf_event_name = "kong" local serf_version_command = " version" -- commandline param to get version local serf_version_pattern = "^Serf v([%d%.]+)" -- pattern to grab version from output local serf_compatible = version.set("0.7.0", "0.7.0") -- compatible from-to versions local start_timeout = 5 local function check_serf_bin() local cmd = fmt("%s %s", serf_bin_name, serf_version_command) local ok, _, stdout = pl_utils.executeex(cmd) if ok and stdout then local version_match = stdout:match(serf_version_pattern) if (not version_match) or (not serf_compatible:matches(version_match)) then return nil, "incompatible Serf version. Kong requires version "..tostring(serf_compatible).. (version_match and ", got "..tostring(version_match) or "") end return true end return nil, "could not find Serf executable (is it in your $PATH?)" end local _M = {} function _M.start(kong_config, dao) -- is Serf already running in this prefix? if kill.is_running(kong_config.serf_pid) then log.verbose("Serf agent already running at %s", kong_config.serf_pid) return true else log.verbose("Serf agent not running, deleting %s", kong_config.serf_pid) pl_file.delete(kong_config.serf_pid) end -- make sure Serf is in PATH local ok, err = check_serf_bin() if not ok then return nil, err end local serf = Serf.new(kong_config, dao) local args = setmetatable({ ["-bind"] = kong_config.cluster_listen, ["-rpc-addr"] = kong_config.cluster_listen_rpc, ["-advertise"] = kong_config.cluster_advertise, ["-encrypt"] = kong_config.cluster_encrypt_key, ["-log-level"] = "err", ["-profile"] = kong_config.cluster_profile, ["-node"] = serf.node_name, ["-event-handler"] = "member-join,member-leave,member-failed," .."member-update,member-reap,user:" ..serf_event_name.."="..kong_config.serf_event }, Serf.args_mt) local cmd = string.format("nohup %s agent %s > %s 2>&1 & echo $! > %s", serf_bin_name, tostring(args), kong_config.serf_log, kong_config.serf_pid) log.debug("starting Serf agent: %s", cmd) -- start Serf agent local ok = pl_utils.execute(cmd) if not ok then return nil end log.verbose("waiting for Serf agent to be running...") -- ensure started (just an improved version of previous Serf service) local tstart = ngx.time() local texp, started = tstart + start_timeout repeat ngx.sleep(0.2) started = kill.is_running(kong_config.serf_pid) until started or ngx.time() >= texp if not started then -- time to get latest error log from serf.log local logs = pl_file.read(kong_config.serf_log) local tlogs = pl_stringx.split(logs, "\n") local err = string.gsub(tlogs[#tlogs-1], "==> ", "") err = pl_stringx.strip(err) return nil, "could not start Serf: "..err end -- cleanup current node from cluster to prevent inconsistency of data local ok, err = serf:cleanup() if not ok then return nil, err end log.verbose("auto-joining Serf cluster...") local ok, err = serf:autojoin() if not ok then return nil, err end log.verbose("adding node to Serf cluster (in datastore)...") local ok, err = serf:add_node() if not ok then return nil, err end return true end function _M.stop(kong_config, dao) log.info("leaving cluster") local serf = Serf.new(kong_config, dao) log.verbose("invoking Serf leave") local ok, err = serf:leave() if not ok then return nil, err end log.verbose("stopping Serf agent at %s", kong_config.serf_pid) local code, res = kill.kill(kong_config.serf_pid, "-15") --SIGTERM if code == 256 then -- If no error is returned pl_file.delete(kong_config.serf_pid) end return code, res end return _M
fix(serf) more logging
fix(serf) more logging
Lua
apache-2.0
ccyphers/kong,Vermeille/kong,jebenexer/kong,icyxp/kong,shiprabehera/kong,Kong/kong,salazar/kong,beauli/kong,Kong/kong,jerizm/kong,li-wl/kong,Mashape/kong,Kong/kong,akh00/kong
e2f36deda8d6363409c7bb560d39ec0a72663307
src/tools/gcc.lua
src/tools/gcc.lua
-- -- gcc.lua -- Provides GCC-specific configuration strings. -- Copyright (c) 2002-2014 Jason Perkins and the Premake project -- premake.tools.gcc = {} local gcc = premake.tools.gcc local project = premake.project local config = premake.config -- -- Returns list of C preprocessor flags for a configuration. -- gcc.cppflags = { system = { haiku = "-MMD", wii = { "-MMD", "-MP", "-I$(LIBOGC_INC)", "$(MACHDEP)" }, _ = { "-MMD", "-MP" } } } function gcc.getcppflags(cfg) local flags = config.mapFlags(cfg, gcc.cppflags) return flags end -- -- Returns list of C compiler flags for a configuration. -- gcc.cflags = { architecture = { x32 = "-m32", x64 = "-m64", }, flags = { FatalCompileWarnings = "-Werror", NoFramePointer = "-fomit-frame-pointer", ShadowedVariables = "-Wshadow", Symbols = "-g", UndefinedIdentifiers = "-Wundef", }, floatingpoint = { Fast = "-ffast-math", Strict = "-ffloat-store", }, kind = { SharedLib = function(cfg) if cfg.system ~= premake.WINDOWS then return "-fPIC" end end, }, strictaliasing = { Off = "-fno-strict-aliasing", Level1 = { "-fstrict-aliasing", "-Wstrict-aliasing=1" }, Level2 = { "-fstrict-aliasing", "-Wstrict-aliasing=2" }, Level3 = { "-fstrict-aliasing", "-Wstrict-aliasing=3" }, }, optimize = { Off = "-O0", On = "-O2", Debug = "-Og", Full = "-O3", Size = "-Os", Speed = "-O3", }, vectorextensions = { AVX = "-mavx", SSE = "-msse", SSE2 = "-msse2", }, warnings = { Extra = "-Wall -Wextra", Off = "-w", } } function gcc.getcflags(cfg) local flags = config.mapFlags(cfg, gcc.cflags) return flags end -- -- Returns list of C++ compiler flags for a configuration. -- gcc.cxxflags = { flags = { NoExceptions = "-fno-exceptions", NoRTTI = "-fno-rtti", NoBufferSecurityCheck = "-fno-stack-protector" } } function gcc.getcxxflags(cfg) local flags = config.mapFlags(cfg, gcc.cxxflags) return flags end -- -- Decorate defines for the GCC command line. -- function gcc.getdefines(defines) local result = {} for _, define in ipairs(defines) do table.insert(result, '-D' .. define) end return result end -- -- Returns a list of forced include files, decorated for the compiler -- command line. -- -- @param cfg -- The project configuration. -- @return -- An array of force include files with the appropriate flags. -- function gcc.getforceincludes(cfg) local result = {} table.foreachi(cfg.forceincludes, function(value) local fn = project.getrelative(cfg.project, value) table.insert(result, string.format('-include %s', premake.quoted(fn))) end) return result end -- -- Decorate include file search paths for the GCC command line. -- function gcc.getincludedirs(cfg, dirs) local result = {} for _, dir in ipairs(dirs) do dir = project.getrelative(cfg.project, dir) table.insert(result, '-I' .. premake.quoted(dir)) end return result end -- -- Return a list of LDFLAGS for a specific configuration. -- gcc.ldflags = { architecture = { x32 = "-m32", x64 = "-m64", }, flags = { _Symbols = function(cfg) -- OS X has a bug, see http://lists.apple.com/archives/Darwin-dev/2006/Sep/msg00084.html return iif(cfg.system == premake.MACOSX, "-Wl,-x", "-s") end, }, kind = { SharedLib = function(cfg) local r = { iif(cfg.system == premake.MACOSX, "-dynamiclib", "-shared") } if cfg.system == "windows" and not cfg.flags.NoImportLib then table.insert(r, '-Wl,--out-implib="' .. cfg.linktarget.relpath .. '"') end return r end, WindowedApp = function(cfg) if cfg.system == premake.WINDOWS then return "-mwindows" end end, }, system = { wii = "$(MACHDEP)", } } function gcc.getldflags(cfg) local flags = config.mapFlags(cfg, gcc.ldflags) return flags end -- -- Return a list of decorated additional libraries directories. -- gcc.libraryDirectories = { architecture = { x32 = "-L/usr/lib32", x64 = "-L/usr/lib64", }, system = { wii = "-L$(LIBOGC_LIB)", } } function gcc.getLibraryDirectories(cfg) local flags = config.mapFlags(cfg, gcc.libraryDirectories) -- Scan the list of linked libraries. If any are referenced with -- paths, add those to the list of library search paths for _, dir in ipairs(config.getlinks(cfg, "system", "directory")) do table.insert(flags, '-L' .. project.getrelative(cfg.project, dir)) end return flags end -- -- Return the list of libraries to link, decorated with flags as needed. -- function gcc.getlinks(cfg, systemonly) local result = {} -- Don't use the -l form for sibling libraries, since they may have -- custom prefixes or extensions that will confuse the linker. Instead -- just list out the full relative path to the library. if not systemonly then result = config.getlinks(cfg, "siblings", "fullpath") end -- The "-l" flag is fine for system libraries local links = config.getlinks(cfg, "system", "fullpath") for _, link in ipairs(links) do if path.isframework(link) then table.insert(result, "-framework " .. path.getbasename(link)) elseif path.isobjectfile(link) then table.insert(result, link) else table.insert(result, "-l" .. path.getname(link)) end end return result end -- -- Returns makefile-specific configuration rules. -- gcc.makesettings = { system = { wii = [[ ifeq ($(strip $(DEVKITPPC)),) $(error "DEVKITPPC environment variable is not set")' endif include $(DEVKITPPC)/wii_rules']] } } function gcc.getmakesettings(cfg) local settings = config.mapFlags(cfg, gcc.makesettings) return table.concat(settings) end -- -- Retrieves the executable command name for a tool, based on the -- provided configuration and the operating environment. -- -- @param cfg -- The configuration to query. -- @param tool -- The tool to fetch, one of "cc" for the C compiler, "cxx" for -- the C++ compiler, or "ar" for the static linker. -- @return -- The executable command name for a tool, or nil if the system's -- default value should be used. -- gcc.tools = { ps3 = { cc = "ppu-lv2-g++", cxx = "ppu-lv2-g++", ar = "ppu-lv2-ar", }, } function gcc.gettoolname(cfg, tool) local names = gcc.tools[cfg.architecture] or gcc.tools[cfg.system] or {} local name = names[tool] if tool == "rc" then name = name or "windres" end return name end
-- -- gcc.lua -- Provides GCC-specific configuration strings. -- Copyright (c) 2002-2014 Jason Perkins and the Premake project -- premake.tools.gcc = {} local gcc = premake.tools.gcc local project = premake.project local config = premake.config -- -- Returns list of C preprocessor flags for a configuration. -- gcc.cppflags = { system = { haiku = "-MMD", wii = { "-MMD", "-MP", "-I$(LIBOGC_INC)", "$(MACHDEP)" }, _ = { "-MMD", "-MP" } } } function gcc.getcppflags(cfg) local flags = config.mapFlags(cfg, gcc.cppflags) return flags end -- -- Returns list of C compiler flags for a configuration. -- gcc.cflags = { architecture = { x32 = "-m32", x64 = "-m64", }, flags = { FatalCompileWarnings = "-Werror", NoFramePointer = "-fomit-frame-pointer", ShadowedVariables = "-Wshadow", Symbols = "-g", UndefinedIdentifiers = "-Wundef", }, floatingpoint = { Fast = "-ffast-math", Strict = "-ffloat-store", }, kind = { SharedLib = function(cfg) if cfg.system ~= premake.WINDOWS then return "-fPIC" end end, }, strictaliasing = { Off = "-fno-strict-aliasing", Level1 = { "-fstrict-aliasing", "-Wstrict-aliasing=1" }, Level2 = { "-fstrict-aliasing", "-Wstrict-aliasing=2" }, Level3 = { "-fstrict-aliasing", "-Wstrict-aliasing=3" }, }, optimize = { Off = "-O0", On = "-O2", Debug = "-Og", Full = "-O3", Size = "-Os", Speed = "-O3", }, vectorextensions = { AVX = "-mavx", SSE = "-msse", SSE2 = "-msse2", }, warnings = { Extra = "-Wall -Wextra", Off = "-w", } } function gcc.getcflags(cfg) local flags = config.mapFlags(cfg, gcc.cflags) return flags end -- -- Returns list of C++ compiler flags for a configuration. -- gcc.cxxflags = { flags = { NoExceptions = "-fno-exceptions", NoRTTI = "-fno-rtti", NoBufferSecurityCheck = "-fno-stack-protector" } } function gcc.getcxxflags(cfg) local flags = config.mapFlags(cfg, gcc.cxxflags) return flags end -- -- Decorate defines for the GCC command line. -- function gcc.getdefines(defines) local result = {} for _, define in ipairs(defines) do table.insert(result, '-D' .. define) end return result end -- -- Returns a list of forced include files, decorated for the compiler -- command line. -- -- @param cfg -- The project configuration. -- @return -- An array of force include files with the appropriate flags. -- function gcc.getforceincludes(cfg) local result = {} table.foreachi(cfg.forceincludes, function(value) local fn = project.getrelative(cfg.project, value) table.insert(result, string.format('-include %s', premake.quoted(fn))) end) return result end -- -- Decorate include file search paths for the GCC command line. -- function gcc.getincludedirs(cfg, dirs) local result = {} for _, dir in ipairs(dirs) do dir = project.getrelative(cfg.project, dir) table.insert(result, '-I' .. premake.quoted(dir)) end return result end -- -- Return a list of LDFLAGS for a specific configuration. -- gcc.ldflags = { architecture = { x32 = "-m32", x64 = "-m64", }, flags = { _Symbols = function(cfg) -- OS X has a bug, see http://lists.apple.com/archives/Darwin-dev/2006/Sep/msg00084.html return iif(cfg.system == premake.MACOSX, "-Wl,-x", "-s") end, }, kind = { SharedLib = function(cfg) local r = { iif(cfg.system == premake.MACOSX, "-dynamiclib", "-shared") } if cfg.system == "windows" and not cfg.flags.NoImportLib then table.insert(r, '-Wl,--out-implib="' .. cfg.linktarget.relpath .. '"') end return r end, WindowedApp = function(cfg) if cfg.system == premake.WINDOWS then return "-mwindows" end end, }, system = { wii = "$(MACHDEP)", } } function gcc.getldflags(cfg) local flags = config.mapFlags(cfg, gcc.ldflags) return flags end -- -- Return a list of decorated additional libraries directories. -- gcc.libraryDirectories = { architecture = { x32 = "-L/usr/lib32", x64 = "-L/usr/lib64", }, system = { wii = "-L$(LIBOGC_LIB)", } } function gcc.getLibraryDirectories(cfg) local flags = config.mapFlags(cfg, gcc.libraryDirectories) -- Scan the list of linked libraries. If any are referenced with -- paths, add those to the list of library search paths for _, dir in ipairs(config.getlinks(cfg, "system", "directory")) do table.insert(flags, '-L' .. project.getrelative(cfg.project, dir)) end return flags end -- -- Return the list of libraries to link, decorated with flags as needed. -- function gcc.getlinks(cfg, systemonly) local result = {} -- Don't use the -l form for sibling libraries, since they may have -- custom prefixes or extensions that will confuse the linker. Instead -- just list out the full relative path to the library. if not systemonly then result = config.getlinks(cfg, "siblings", "fullpath") end -- The "-l" flag is fine for system libraries local links = config.getlinks(cfg, "system", "fullpath") for _, link in ipairs(links) do if path.isframework(link) then table.insert(result, "-framework " .. path.getbasename(link)) elseif path.isobjectfile(link) then table.insert(result, link) else table.insert(result, "-l" .. path.getname(link)) end end return result end -- -- Returns makefile-specific configuration rules. -- gcc.makesettings = { system = { wii = [[ ifeq ($(strip $(DEVKITPPC)),) $(error "DEVKITPPC environment variable is not set")' endif include $(DEVKITPPC)/wii_rules']] } } function gcc.getmakesettings(cfg) local settings = config.mapFlags(cfg, gcc.makesettings) return table.concat(settings) end -- -- Retrieves the executable command name for a tool, based on the -- provided configuration and the operating environment. -- -- @param cfg -- The configuration to query. -- @param tool -- The tool to fetch, one of "cc" for the C compiler, "cxx" for -- the C++ compiler, or "ar" for the static linker. -- @return -- The executable command name for a tool, or nil if the system's -- default value should be used. -- gcc.tools = { ps3 = { cc = "ppu-lv2-g++", cxx = "ppu-lv2-g++", ar = "ppu-lv2-ar", }, } function gcc.gettoolname(cfg, tool) local names = gcc.tools[cfg.architecture] or gcc.tools[cfg.system] or {} local name = names[tool] if tool == "rc" then name = name or "windres" end return name end
Fix incorrect whitespace
Fix incorrect whitespace
Lua
bsd-3-clause
prapin/premake-core,dcourtois/premake-core,tvandijck/premake-core,Yhgenomics/premake-core,prapin/premake-core,lizh06/premake-core,Tiger66639/premake-core,dcourtois/premake-core,saberhawk/premake-core,sleepingwit/premake-core,resetnow/premake-core,Zefiros-Software/premake-core,prapin/premake-core,starkos/premake-core,martin-traverse/premake-core,premake/premake-core,Meoo/premake-core,felipeprov/premake-core,prapin/premake-core,noresources/premake-core,xriss/premake-core,mendsley/premake-core,premake/premake-core,CodeAnxiety/premake-core,jsfdez/premake-core,xriss/premake-core,TurkeyMan/premake-core,alarouche/premake-core,Yhgenomics/premake-core,TurkeyMan/premake-core,soundsrc/premake-core,starkos/premake-core,Zefiros-Software/premake-core,dcourtois/premake-core,grbd/premake-core,lizh06/premake-core,jsfdez/premake-core,resetnow/premake-core,resetnow/premake-core,starkos/premake-core,noresources/premake-core,akaStiX/premake-core,soundsrc/premake-core,Tiger66639/premake-core,xriss/premake-core,LORgames/premake-core,saberhawk/premake-core,saberhawk/premake-core,Meoo/premake-core,noresources/premake-core,grbd/premake-core,TurkeyMan/premake-core,premake/premake-core,starkos/premake-core,saberhawk/premake-core,grbd/premake-core,mandersan/premake-core,Blizzard/premake-core,akaStiX/premake-core,Zefiros-Software/premake-core,soundsrc/premake-core,jstewart-amd/premake-core,tritao/premake-core,grbd/premake-core,premake/premake-core,PlexChat/premake-core,martin-traverse/premake-core,mendsley/premake-core,jstewart-amd/premake-core,mendsley/premake-core,tritao/premake-core,aleksijuvani/premake-core,starkos/premake-core,Blizzard/premake-core,Blizzard/premake-core,felipeprov/premake-core,LORgames/premake-core,CodeAnxiety/premake-core,felipeprov/premake-core,lizh06/premake-core,kankaristo/premake-core,Yhgenomics/premake-core,tvandijck/premake-core,premake/premake-core,PlexChat/premake-core,alarouche/premake-core,bravnsgaard/premake-core,aleksijuvani/premake-core,starkos/premake-core,LORgames/premake-core,lizh06/premake-core,alarouche/premake-core,PlexChat/premake-core,jsfdez/premake-core,tvandijck/premake-core,tritao/premake-core,tvandijck/premake-core,LORgames/premake-core,bravnsgaard/premake-core,resetnow/premake-core,TurkeyMan/premake-core,dcourtois/premake-core,jstewart-amd/premake-core,starkos/premake-core,sleepingwit/premake-core,mandersan/premake-core,Meoo/premake-core,dcourtois/premake-core,mandersan/premake-core,Tiger66639/premake-core,felipeprov/premake-core,mandersan/premake-core,tvandijck/premake-core,mendsley/premake-core,kankaristo/premake-core,alarouche/premake-core,bravnsgaard/premake-core,PlexChat/premake-core,mandersan/premake-core,TurkeyMan/premake-core,soundsrc/premake-core,kankaristo/premake-core,xriss/premake-core,Blizzard/premake-core,sleepingwit/premake-core,bravnsgaard/premake-core,aleksijuvani/premake-core,jsfdez/premake-core,mendsley/premake-core,akaStiX/premake-core,CodeAnxiety/premake-core,soundsrc/premake-core,Blizzard/premake-core,noresources/premake-core,aleksijuvani/premake-core,tritao/premake-core,noresources/premake-core,premake/premake-core,noresources/premake-core,Blizzard/premake-core,LORgames/premake-core,akaStiX/premake-core,premake/premake-core,Yhgenomics/premake-core,xriss/premake-core,Zefiros-Software/premake-core,resetnow/premake-core,noresources/premake-core,jstewart-amd/premake-core,kankaristo/premake-core,CodeAnxiety/premake-core,Zefiros-Software/premake-core,bravnsgaard/premake-core,martin-traverse/premake-core,dcourtois/premake-core,martin-traverse/premake-core,CodeAnxiety/premake-core,Tiger66639/premake-core,sleepingwit/premake-core,jstewart-amd/premake-core,dcourtois/premake-core,sleepingwit/premake-core,Meoo/premake-core,aleksijuvani/premake-core
5a385c2d72d6f79d694da29c289757206dbf643c
premake.lua
premake.lua
-- TODO: Because there are a few remaining things ... -- 1. x86/x64 switching -- 2. clean this file up because I'm sure it could be organized better -- 3. consider maybe switching to CMake because of the ugly hack below -- -- NOTE: I am intentionally leaving out a "windows+gmake" configuration -- as trying to compile against the FBX SDK using MinGW results in -- compile errors. Some quick googling seems to indicate MinGW is -- not supported by the FBX SDK? -- If you try to use this script to build with MinGW you will end -- up with a Makefile that has god knows what in it FBX_SDK_ROOT = os.getenv("FBX_SDK_ROOT") if not FBX_SDK_ROOT then printf("ERROR: Environment variable FBX_SDK_ROOT is not set.") printf("Set it to something like: C:\\Program Files\\Autodesk\\FBX\\FBX SDK\\2013.3") os.exit() end -- avert your eyes children! if string.find(_ACTION, "xcode") then -- TODO: i'm sure we could do some string search+replace trickery to make -- this more general-purpose -- take care of the most common case where the FBX SDK is installed to the -- default location and part of the path contains a space -- god help you if you install the FBX SDK using a totally different path -- that contains a space AND you want to use Xcode -- Premake + Xcode combined fuck this up so badly making it nigh-impossible -- to do any kind of _proper_ path escaping here (I wasted an hour on this) -- (maybe I should have used CMake ....) FBX_SDK_ROOT = string.gsub(FBX_SDK_ROOT, "FBX SDK", "'FBX SDK'") end -- ok, you can look again BUILD_DIR = "build" if _ACTION == "clean" then os.rmdir(BUILD_DIR) end solution "fbx-conv" configurations { "Debug", "Release" } location (BUILD_DIR .. "/" .. _ACTION) project "fbx-conv" --- GENERAL STUFF FOR ALL PLATFORMS -------------------------------- kind "ConsoleApp" language "C++" location (BUILD_DIR .. "/" .. _ACTION) files { "./src/**.c*", "./src/**.h", } includedirs { (FBX_SDK_ROOT .. "/include"), "./libs/libpng/include", "./libs/zlib/include", } defines { "FBXSDK_NEW_API", } --- debugdir "." configuration "Debug" defines { "DEBUG", } flags { "Symbols" } configuration "Release" defines { "NDEBUG", } flags { "Optimize" } --- VISUAL STUDIO -------------------------------------------------- configuration "vs*" flags { "NoPCH", "NoMinimalRebuild" } buildoptions { "/MP" } defines { "_CRT_SECURE_NO_WARNINGS", "_CRT_NONSTDC_NO_WARNINGS" } libdirs { (FBX_SDK_ROOT .. "/lib/vs2010/x86"), "./libs/libpng/lib/windows/x86", "./libs/zlib/lib/windows/x86", } links { "libpng14", "zlib", } configuration { "vs*", "Debug" } links { "fbxsdk-2013.3-mdd", } configuration { "vs*", "Release" } links { "fbxsdk-2013.3-md", } --- LINUX ---------------------------------------------------------- configuration { "linux" } kind "ConsoleApp" buildoptions { "-Wall" } -- TODO: while using x64 will likely be fine for most people nowadays, -- we still need to make this configurable libdirs { "./libs/libpng/lib/linux/x64", "./libs/zlib/lib/linux/x64", } links { "png", "z", "pthread", "fbxsdk", "dl", } configuration { "linux", "Debug" } libdirs { (FBX_SDK_ROOT .. "/lib/gcc4/x64/debug"), } configuration { "linux", "Release" } libdirs { (FBX_SDK_ROOT .. "/lib/gcc4/x64/release"), } --- MAC ------------------------------------------------------------ configuration { "macosx" } kind "ConsoleApp" buildoptions { "-Wall" } libdirs { (FBX_SDK_ROOT .. "/lib/gcc4/ub"), "./libs/libpng/lib/macosx", "./libs/zlib/lib/macosx", } links { "png", "z", "CoreFoundation.framework", "fbxsdk", } configuration { "macosx", "Debug" } libdirs { (FBX_SDK_ROOT .. "/lib/gcc4/ub/debug"), } configuration { "macosx", "Release" } libdirs { (FBX_SDK_ROOT .. "/lib/gcc4/ub/release"), }
-- TODO: Because there are a few remaining things ... -- 1. x86/x64 switching -- 2. clean this file up because I'm sure it could be organized better -- 3. consider maybe switching to CMake because of the ugly hack below -- -- NOTE: I am intentionally leaving out a "windows+gmake" configuration -- as trying to compile against the FBX SDK using MinGW results in -- compile errors. Some quick googling seems to indicate MinGW is -- not supported by the FBX SDK? -- If you try to use this script to build with MinGW you will end -- up with a Makefile that has god knows what in it FBX_SDK_ROOT = os.getenv("FBX_SDK_ROOT") if not FBX_SDK_ROOT then printf("ERROR: Environment variable FBX_SDK_ROOT is not set.") printf("Set it to something like: C:\\Program Files\\Autodesk\\FBX\\FBX SDK\\2013.3") os.exit() end -- avert your eyes children! if string.find(_ACTION, "xcode") then -- TODO: i'm sure we could do some string search+replace trickery to make -- this more general-purpose -- take care of the most common case where the FBX SDK is installed to the -- default location and part of the path contains a space -- god help you if you install the FBX SDK using a totally different path -- that contains a space AND you want to use Xcode -- Premake + Xcode combined fuck this up so badly making it nigh-impossible -- to do any kind of _proper_ path escaping here (I wasted an hour on this) -- (maybe I should have used CMake ....) FBX_SDK_ROOT = string.gsub(FBX_SDK_ROOT, "FBX SDK", "'FBX SDK'") end -- ok, you can look again BUILD_DIR = "build" if _ACTION == "clean" then os.rmdir(BUILD_DIR) end solution "fbx-conv" configurations { "Debug", "Release" } location (BUILD_DIR .. "/" .. _ACTION) project "fbx-conv" --- GENERAL STUFF FOR ALL PLATFORMS -------------------------------- kind "ConsoleApp" language "C++" location (BUILD_DIR .. "/" .. _ACTION) files { "./src/**.c*", "./src/**.h", } includedirs { (FBX_SDK_ROOT .. "/include"), "./libs/libpng/include", "./libs/zlib/include", } defines { "FBXSDK_NEW_API", } --- debugdir "." configuration "Debug" defines { "DEBUG", } flags { "Symbols" } configuration "Release" defines { "NDEBUG", } flags { "Optimize" } --- VISUAL STUDIO -------------------------------------------------- configuration "vs*" flags { "NoPCH", "NoMinimalRebuild" } buildoptions { "/MP" } defines { "_CRT_SECURE_NO_WARNINGS", "_CRT_NONSTDC_NO_WARNINGS" } libdirs { (FBX_SDK_ROOT .. "/lib/vs2010/x86"), "./libs/libpng/lib/windows/x86", "./libs/zlib/lib/windows/x86", } links { "libpng14", "zlib", "fbxsdk-md", } configuration { "vs*", "Debug" } libdirs { (FBX_SDK_ROOT .. "/lib/vs2010/x86/debug"), } configuration { "vs*", "Release" } libdirs { (FBX_SDK_ROOT .. "/lib/vs2010/x86/release"), } --- LINUX ---------------------------------------------------------- configuration { "linux" } kind "ConsoleApp" buildoptions { "-Wall" } -- TODO: while using x64 will likely be fine for most people nowadays, -- we still need to make this configurable libdirs { "./libs/libpng/lib/linux/x64", "./libs/zlib/lib/linux/x64", } links { "png", "z", "pthread", "fbxsdk", "dl", } configuration { "linux", "Debug" } libdirs { (FBX_SDK_ROOT .. "/lib/gcc4/x64/debug"), } configuration { "linux", "Release" } libdirs { (FBX_SDK_ROOT .. "/lib/gcc4/x64/release"), } --- MAC ------------------------------------------------------------ configuration { "macosx" } kind "ConsoleApp" buildoptions { "-Wall" } libdirs { (FBX_SDK_ROOT .. "/lib/gcc4/ub"), "./libs/libpng/lib/macosx", "./libs/zlib/lib/macosx", } links { "png", "z", "CoreFoundation.framework", "fbxsdk", } configuration { "macosx", "Debug" } libdirs { (FBX_SDK_ROOT .. "/lib/gcc4/ub/debug"), } configuration { "macosx", "Release" } libdirs { (FBX_SDK_ROOT .. "/lib/gcc4/ub/release"), }
Update premake.lua
Update premake.lua Fixed windows build to use fbx sdk 2014
Lua
apache-2.0
lvlonggame/fbx-conv,xoppa/fbx-conv,arisecbf/fbx-conv,cocos2d-x/fbx-conv,lvlonggame/fbx-conv,davidedmonds/fbx-conv,iichenbf/fbx-conv,cocos2d-x/fbx-conv,xoppa/fbx-conv,reduz/fbx-conv,arisecbf/fbx-conv,reduz/fbx-conv,super626/fbx-conv,Maxwolf/Multimap.FBXConv,lvlonggame/fbx-conv,davidedmonds/fbx-conv,super626/fbx-conv,andyvand/fbx-conv,iichenbf/fbx-conv,Maxwolf/Multimap.FBXConv,cocos2d-x/fbx-conv,andyvand/fbx-conv,davidedmonds/fbx-conv,reduz/fbx-conv,iichenbf/fbx-conv,andyvand/fbx-conv,super626/fbx-conv,arisecbf/fbx-conv,xoppa/fbx-conv
21f560eabcc1b1fe810965d551b7dec6086ac2af
src/patch/ui/lib/mppatch_uiutils.lua
src/patch/ui/lib/mppatch_uiutils.lua
-- Copyright (c) 2015-2017 Lymia Alusyia <[email protected]> -- -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -- copies of the Software, and to permit persons to whom the Software is -- furnished to do so, subject to the following conditions: -- -- The above copyright notice and this permission notice shall be included in -- all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -- THE SOFTWARE. local LookUpControl = ContextPtr.LookUpControl -- cached because we override this in some of our hooks _mpPatch._mt.registerLazyVal("fullPath", function() local accum = ContextPtr:GetID() local path = ".." local seen = {} while true do local currentContext = LookUpControl(ContextPtr, path) if not currentContext then break end if seen[currentContext:GetID()] then return "{...}/"..accum end seen[currentContext:GetID()] = true accum = currentContext:GetID().."/"..accum path = path.."/.." end return accum end) function _mpPatch.loadElementFromProxy(proxyName, controlName) local proxy = ContextPtr:LoadNewContext(proxyName) Controls[controlName] = LookUpControl(proxy, controlName) end function _mpPatch.setBIsModding() function ContextPtr.LookUpControl() return { GetID = function() return "ModMultiplayerSelectScreen" end } end end -- Update function hooking function _mpPatch.hookUpdate() ContextPtr:SetUpdate(_mpPatch.event.update) end function _mpPatch.unhookUpdate() ContextPtr:ClearUpdate() end
-- Copyright (c) 2015-2017 Lymia Alusyia <[email protected]> -- -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -- copies of the Software, and to permit persons to whom the Software is -- furnished to do so, subject to the following conditions: -- -- The above copyright notice and this permission notice shall be included in -- all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -- THE SOFTWARE. local LookUpControl = ContextPtr.LookUpControl -- cached because we override this in some of our hooks _mpPatch._mt.registerLazyVal("fullPath", function() local accum = ContextPtr:GetID() local path = ".." local seen = {} while true do local currentContext = LookUpControl(ContextPtr, path) if not currentContext then break end if seen[currentContext:GetID()] then return "{...}/"..accum end seen[currentContext:GetID()] = true accum = currentContext:GetID().."/"..accum path = path.."/.." end return accum end) function _mpPatch.loadElementFromProxy(proxyName, controlName) local proxy = ContextPtr:LoadNewContext(proxyName) Controls[controlName] = LookUpControl(proxy, controlName) end function _mpPatch.setBIsModding() function ContextPtr.LookUpControl() return { GetID = function() return "ModMultiplayerSelectScreen" end } end end -- Update function hooking function _mpPatch.hookUpdate() local onUpdate = _mpPatch.event.update ContextPtr:SetUpdate(function(...) return onUpdate(...) end) end function _mpPatch.unhookUpdate() ContextPtr:ClearUpdate() end
Fix hookUpdate.
Fix hookUpdate.
Lua
mit
Lymia/MultiverseModManager,Lymia/MPPatch,Lymia/MultiverseModManager,Lymia/MPPatch,Lymia/MPPatch,Lymia/MPPatch,Lymia/CivV_Mod2DLC
04e23afe7ccc5b4e242585f5fbe6731741c5301b
Linear.lua
Linear.lua
local Linear, parent = torch.class('nn.Linear', 'nn.Module') function Linear:__init(inputSize, outputSize) parent.__init(self) self.weight = torch.Tensor(outputSize, inputSize) self.bias = torch.Tensor(outputSize) self.gradWeight = torch.Tensor(outputSize, inputSize) self.gradBias = torch.Tensor(outputSize) self:reset() end function Linear:reset(stdv) if stdv then stdv = stdv * math.sqrt(3) else stdv = 1./math.sqrt(self.weight:size(2)) end if nn.oldSeed then for i=1,self.weight:size(1) do self.weight:select(1, i):apply(function() return torch.uniform(-stdv, stdv) end) self.bias[i] = torch.uniform(-stdv, stdv) end else self.weight:uniform(-stdv, stdv) self.bias:uniform(-stdv, stdv) end end function Linear:updateOutput(input) if input:dim() == 1 then self.output:resize(self.bias:size(1)) self.output:copy(self.bias) self.output:addmv(1, self.weight, input) elseif input:dim() == 2 then local nframe = input:size(1) local nunit = self.bias:size(1) self.output:resize(nframe, nunit) if nunit == 1 then -- Special case to fix output size of 1 bug: self.output:zero():add(self.bias[1]) self.output:select(2,1):addmv(1, input, self.weight:select(1,1)) else self.output:zero():addr(1, input.new(nframe):fill(1), self.bias) self.output:addmm(1, input, self.weight:t()) end else error('input must be vector or matrix') end return self.output end function Linear:updateGradInput(input, gradOutput) if self.gradInput then local nElement = self.gradInput:nElement() self.gradInput:resizeAs(input) if self.gradInput:nElement() ~= nElement then self.gradInput:zero() end if input:dim() == 1 then self.gradInput:addmv(0, 1, self.weight:t(), gradOutput) elseif input:dim() == 2 then self.gradInput:addmm(0, 1, gradOutput, self.weight) end return self.gradInput end end function Linear:accGradParameters(input, gradOutput, scale) scale = scale or 1 if input:dim() == 1 then self.gradWeight:addr(scale, gradOutput, input) self.gradBias:add(scale, gradOutput) elseif input:dim() == 2 then local nframe = input:size(1) local nunit = self.bias:size(1) if nunit == 1 then -- Special case to fix output size of 1 bug: self.gradWeight:select(1,1):addmv(scale, input:t(), gradOutput:select(2,1)) self.gradBias:addmv(scale, gradOutput:t(), input.new(nframe):fill(1)) else self.gradWeight:addmm(scale, gradOutput:t(), input) self.gradBias:addmv(scale, gradOutput:t(), input.new(nframe):fill(1)) end end end -- we do not need to accumulate parameters when sharing Linear.sharedAccUpdateGradParameters = Linear.accUpdateGradParameters
local Linear, parent = torch.class('nn.Linear', 'nn.Module') function Linear:__init(inputSize, outputSize) parent.__init(self) self.weight = torch.Tensor(outputSize, inputSize) self.bias = torch.Tensor(outputSize) self.gradWeight = torch.Tensor(outputSize, inputSize) self.gradBias = torch.Tensor(outputSize) self:reset() end function Linear:reset(stdv) if stdv then stdv = stdv * math.sqrt(3) else stdv = 1./math.sqrt(self.weight:size(2)) end if nn.oldSeed then for i=1,self.weight:size(1) do self.weight:select(1, i):apply(function() return torch.uniform(-stdv, stdv) end) self.bias[i] = torch.uniform(-stdv, stdv) end else self.weight:uniform(-stdv, stdv) self.bias:uniform(-stdv, stdv) end end function Linear:updateOutput(input) if input:dim() == 1 then self.output:resize(self.bias:size(1)) self.output:copy(self.bias) self.output:addmv(1, self.weight, input) elseif input:dim() == 2 then local nframe = input:size(1) local nunit = self.bias:size(1) self.output:resize(nframe, nunit) if nunit == 1 then -- Special case to fix output size of 1 bug: self.output:copy(self.bias:view(1,nunit):expand(#self.output)) self.output:select(2,1):addmv(1, input, self.weight:select(1,1)) else self.output:zero():addr(1, input.new(nframe):fill(1), self.bias) self.output:addmm(1, input, self.weight:t()) end else error('input must be vector or matrix') end return self.output end function Linear:updateGradInput(input, gradOutput) if self.gradInput then local nElement = self.gradInput:nElement() self.gradInput:resizeAs(input) if self.gradInput:nElement() ~= nElement then self.gradInput:zero() end if input:dim() == 1 then self.gradInput:addmv(0, 1, self.weight:t(), gradOutput) elseif input:dim() == 2 then self.gradInput:addmm(0, 1, gradOutput, self.weight) end return self.gradInput end end function Linear:accGradParameters(input, gradOutput, scale) scale = scale or 1 if input:dim() == 1 then self.gradWeight:addr(scale, gradOutput, input) self.gradBias:add(scale, gradOutput) elseif input:dim() == 2 then local nframe = input:size(1) local nunit = self.bias:size(1) if nunit == 1 then -- Special case to fix output size of 1 bug: self.gradWeight:select(1,1):addmv(scale, input:t(), gradOutput:select(2,1)) self.gradBias:addmv(scale, gradOutput:t(), input.new(nframe):fill(1)) else self.gradWeight:addmm(scale, gradOutput:t(), input) self.gradBias:addmv(scale, gradOutput:t(), input.new(nframe):fill(1)) end end end -- we do not need to accumulate parameters when sharing Linear.sharedAccUpdateGradParameters = Linear.accUpdateGradParameters
linear blocking fix
linear blocking fix
Lua
bsd-3-clause
ominux/nn,elbamos/nn,xianjiec/nn,lukasc-ch/nn,apaszke/nn,mys007/nn,clementfarabet/nn,kmul00/nn,abeschneider/nn,GregSatre/nn,szagoruyko/nn,vgire/nn,Jeffyrao/nn,lvdmaaten/nn,jonathantompson/nn,rickyHong/nn_lib_torch,hughperkins/nn,noa/nn,ivendrov/nn,jzbontar/nn,bartvm/nn,forty-2/nn,aaiijmrtt/nn,sbodenstein/nn,diz-vara/nn,eriche2016/nn,andreaskoepf/nn,Djabbz/nn,davidBelanger/nn,joeyhng/nn,LinusU/nn,witgo/nn,nicholas-leonard/nn,zchengquan/nn,douwekiela/nn,eulerreich/nn,rotmanmi/nn,colesbury/nn,jhjin/nn,caldweln/nn,Moodstocks/nn,EnjoyHacking/nn,PraveerSINGH/nn,karpathy/nn,boknilev/nn,sagarwaghmare69/nn,fmassa/nn,adamlerer/nn,mlosch/nn,zhangxiangxiao/nn,PierrotLC/nn,hery/nn,Aysegul/nn
270bddb309c1a935c1da0761d4d2a21161fed9d9
src/program/lwaftr/query/query.lua
src/program/lwaftr/query/query.lua
module(..., package.seeall) local engine = require("core.app") local counter = require("core.counter") local lib = require("core.lib") local shm = require("core.shm") local data = require("lib.yang.data") local schema = require("lib.yang.schema") local state = require("lib.yang.state") local counters = require("program.lwaftr.counters") local lwutil = require("apps.lwaftr.lwutil") local top = require("program.top.top") local ps = require("program.ps.ps") local keys, fatal = lwutil.keys, lwutil.fatal function show_usage (code) print(require("program.lwaftr.query.README_inc")) main.exit(code) end local function sort (t) table.sort(t) return t end function parse_args (raw_args) local handlers = {} local opts = {} local name function handlers.h() show_usage(0) end function handlers.l () for _, name in ipairs(sort(keys(counters.counter_names()))) do print(name) end main.exit(0) end function handlers.n (arg) opts.name = assert(arg) end local args = lib.dogetopt(raw_args, handlers, "hln:", { help="h", ["list-all"]="l", name="n" }) if #args > 2 then show_usage(1) end return opts, unpack(args) end local function max_key_width (counters) local max_width = 0 for name, value in pairs(counters) do if value ~= 0 then if #name > max_width then max_width = #name end end end return max_width end -- Filters often contain '-', which is a special character for match. -- Escape it. local function skip_counter (name, filter) local escaped_filter = filter if escaped_filter then escaped_filter = filter:gsub("-", "%%-") end return filter and not name:match(escaped_filter) end local function print_counter (name, value, max_width) local nspaces = max_width - #name print(("%s: %s%s"):format(name, (" "):rep(nspaces), lib.comma_value(value))) end local function print_counters (pid, filter) print("lwAFTR operational counters (non-zero)") -- Open, read and print whatever counters are in that directory. local counters = counters.read_counters(pid) local max_width = max_key_width(counters) for _, name in ipairs(sort(keys(counters))) do if not skip_counter(name, filter) then local value = counters[name] if value ~= 0 then print_counter(name, value, max_width) end end end end -- Return the pid that was specified, unless it was a manager process, -- in which case, return the worker pid that actually has useful -- counters. local function pid_to_parent(pid) -- It's meaningless to get the parent of a nil 'pid'. if not pid then return pid end local pid = tonumber(pid) for _, name in ipairs(shm.children("/")) do local p = tonumber(name) if p and ps.is_worker(p) then local manager_pid = tonumber(ps.get_manager_pid(p)) -- If the precomputed by-name pid is the manager pid, set the -- pid to be the worker's pid instead to get meaningful -- counters. if manager_pid == pid then pid = p end end end return pid end function run (raw_args) local opts, arg1, arg2 = parse_args(raw_args) local pid, counter_name if not opts.name then if arg1 then pid = pid_to_parent(arg1) end counter_name = arg2 -- This may be nil else -- by-name: arguments are shifted by 1 and no pid is specified counter_name = arg1 -- Start by assuming it was run without --reconfigurable local programs = engine.enumerate_named_programs(opts.name) pid = programs[opts.name] if not pid then fatal(("Couldn't find process with name '%s'"):format(opts.name)) end -- Check if it was run with --reconfigurable If it was, find the -- children, then find the pid of their parent. Note that this -- approach will break as soon as there can be multiple workers -- which need to have their statistics aggregated, as it will only -- print the statistics for one child, not for all of them. for _, name in ipairs(shm.children("/")) do local p = tonumber(name) if p and ps.is_worker(p) then local manager_pid = tonumber(ps.get_manager_pid(p)) -- If the precomputed by-name pid is the manager pid, set -- the pid to be the worker's pid instead to get meaningful -- counters. if manager_pid == pid then pid = p end end end end if not pid then top.select_snabb_instance(pid) -- The following is not reached when there are multiple instances. fatal("Please manually specify a pid, or a name with -n name") end print_counters(pid, counter_name) end
module(..., package.seeall) local S = require("syscall") local engine = require("core.app") local counter = require("core.counter") local lib = require("core.lib") local shm = require("core.shm") local data = require("lib.yang.data") local schema = require("lib.yang.schema") local state = require("lib.yang.state") local counters = require("program.lwaftr.counters") local lwutil = require("apps.lwaftr.lwutil") local ps = require("program.ps.ps") local keys, fatal = lwutil.keys, lwutil.fatal function show_usage (code) print(require("program.lwaftr.query.README_inc")) main.exit(code) end local function sort (t) table.sort(t) return t end function parse_args (raw_args) local handlers = {} local opts = {} local name function handlers.h() show_usage(0) end function handlers.l () for _, name in ipairs(sort(keys(counters.counter_names()))) do print(name) end main.exit(0) end function handlers.n (arg) opts.name = assert(arg) end local args = lib.dogetopt(raw_args, handlers, "hln:", { help="h", ["list-all"]="l", name="n" }) if #args > 2 then show_usage(1) end return opts, unpack(args) end local function max_key_width (counters) local max_width = 0 for name, value in pairs(counters) do if value ~= 0 then if #name > max_width then max_width = #name end end end return max_width end -- Filters often contain '-', which is a special character for match. -- Escape it. local function skip_counter (name, filter) local escaped_filter = filter if escaped_filter then escaped_filter = filter:gsub("-", "%%-") end return filter and not name:match(escaped_filter) end local function print_counter (name, value, max_width) local nspaces = max_width - #name print(("%s: %s%s"):format(name, (" "):rep(nspaces), lib.comma_value(value))) end local function print_counters (pid, filter) print("lwAFTR operational counters (non-zero)") -- Open, read and print whatever counters are in that directory. local counters = counters.read_counters(pid) local max_width = max_key_width(counters) for _, name in ipairs(sort(keys(counters))) do if not skip_counter(name, filter) then local value = counters[name] if value ~= 0 then print_counter(name, value, max_width) end end end end -- Return the pid that was specified, unless it was a manager process, -- in which case, return the worker pid that actually has useful -- counters. local function pid_to_parent(pid) -- It's meaningless to get the parent of a nil 'pid'. if not pid then return pid end local pid = tonumber(pid) for _, name in ipairs(shm.children("/")) do local p = tonumber(name) if p and ps.is_worker(p) then local manager_pid = tonumber(ps.get_manager_pid(p)) -- If the precomputed by-name pid is the manager pid, set the -- pid to be the worker's pid instead to get meaningful -- counters. if manager_pid == pid then pid = p end end end return pid end local function select_snabb_instance (pid) local function compute_snabb_instances() -- Produces set of snabb instances, excluding this one. local pids = {} local my_pid = S.getpid() for _, name in ipairs(shm.children("/")) do -- This could fail as the name could be for example "by-name" local p = tonumber(name) if p and p ~= my_pid then table.insert(pids, name) end end return pids end local instances = compute_snabb_instances() if pid then pid = tostring(pid) -- Try to use given pid for _, instance in ipairs(instances) do if instance == pid then return pid end end print("No such Snabb instance: "..pid) elseif #instances == 1 then return instances[1] elseif #instances <= 0 then print("No Snabb instance found.") else print("Multiple Snabb instances found. Select one:") for _, instance in ipairs(instances) do print(instance) end end main.exit(1) end function run (raw_args) local opts, arg1, arg2 = parse_args(raw_args) local pid, counter_name if not opts.name then if arg1 then pid = pid_to_parent(arg1) end counter_name = arg2 -- This may be nil else -- by-name: arguments are shifted by 1 and no pid is specified counter_name = arg1 -- Start by assuming it was run without --reconfigurable local programs = engine.enumerate_named_programs(opts.name) pid = programs[opts.name] if not pid then fatal(("Couldn't find process with name '%s'"):format(opts.name)) end -- Check if it was run with --reconfigurable If it was, find the -- children, then find the pid of their parent. Note that this -- approach will break as soon as there can be multiple workers -- which need to have their statistics aggregated, as it will only -- print the statistics for one child, not for all of them. for _, name in ipairs(shm.children("/")) do local p = tonumber(name) if p and ps.is_worker(p) then local manager_pid = tonumber(ps.get_manager_pid(p)) -- If the precomputed by-name pid is the manager pid, set -- the pid to be the worker's pid instead to get meaningful -- counters. if manager_pid == pid then pid = p end end end end if not pid then pid = select_snabb_instance() end print_counters(pid, counter_name) end
Fix "snabb lwaftr query"
Fix "snabb lwaftr query" Once "snabbvmx lwaftr" has migrated to ptree and friends, this tool can go away and be replaced by "snabb config get-state"; until then, it's still useful.
Lua
apache-2.0
alexandergall/snabbswitch,Igalia/snabb,Igalia/snabbswitch,alexandergall/snabbswitch,snabbco/snabb,eugeneia/snabb,snabbco/snabb,Igalia/snabb,Igalia/snabb,SnabbCo/snabbswitch,snabbco/snabb,Igalia/snabb,alexandergall/snabbswitch,snabbco/snabb,eugeneia/snabb,eugeneia/snabb,alexandergall/snabbswitch,Igalia/snabb,SnabbCo/snabbswitch,Igalia/snabb,SnabbCo/snabbswitch,alexandergall/snabbswitch,eugeneia/snabb,Igalia/snabbswitch,SnabbCo/snabbswitch,snabbco/snabb,alexandergall/snabbswitch,snabbco/snabb,Igalia/snabbswitch,alexandergall/snabbswitch,eugeneia/snabb,Igalia/snabb,Igalia/snabbswitch,Igalia/snabbswitch,Igalia/snabb,snabbco/snabb,eugeneia/snabb,eugeneia/snabb,snabbco/snabb,alexandergall/snabbswitch,eugeneia/snabb
4da34dfd20314b183b9012b781b85390abe19878
modules/coro-channel.lua
modules/coro-channel.lua
exports.name = "creationix/coro-channel" exports.version = "1.0.1" -- Given a raw uv_stream_t userdara, return coro-friendly read/write functions. -- Given a raw uv_stream_t userdara, return coro-friendly read/write functions. function exports.wrapStream(socket) local paused = true local queue = {} local waiting local reading = true local writing = true local onRead local function read() if #queue > 0 then return unpack(table.remove(queue, 1)) end if paused then paused = false socket:read_start(onRead) end waiting = coroutine.running() return coroutine.yield() end function onRead(err, chunk) local data = err and {nil, err} or {chunk} if waiting then local thread = waiting waiting = nil assert(coroutine.resume(thread, unpack(data))) else queue[#queue + 1] = data if not paused then paused = true socket:read_stop() end end if not chunk then reading = false -- Close the whole socket if the writing side is also closed already. if not writing and not socket:is_closing() then socket:close() end end end local function write(chunk) if chunk == nil then -- Shutdown our side of the socket writing = false if not socket:is_closing() then socket:shutdown() -- Close if we're done reading too if not reading and not socket:is_closing() then socket:close() end end else -- TODO: add backpressure by pausing and resuming coroutine -- when write buffer is full. socket:write(chunk) end end return read, write end function exports.chain(...) local args = {...} local nargs = select("#", ...) return function (read, write) local threads = {} -- coroutine thread for each item local waiting = {} -- flag when waiting to pull from upstream local boxes = {} -- storage when waiting to write to downstream for i = 1, nargs do threads[i] = coroutine.create(args[i]) waiting[i] = false local r, w if i == 1 then r = read else function r() local j = i - 1 if boxes[j] then local data = boxes[j] boxes[j] = nil assert(coroutine.resume(threads[j])) return unpack(data) else waiting[i] = true return coroutine.yield() end end end if i == nargs then w = write else function w(...) local j = i + 1 if waiting[j] then waiting[j] = false assert(coroutine.resume(threads[j], ...)) else boxes[i] = {...} coroutine.yield() end end end assert(coroutine.resume(threads[i], r, w)) end end end
exports.name = "creationix/coro-channel" exports.version = "1.0.2" -- Given a raw uv_stream_t userdara, return coro-friendly read/write functions. -- Given a raw uv_stream_t userdara, return coro-friendly read/write functions. function exports.wrapStream(socket) local paused = true local queue = {} local waiting local reading = true local writing = true local onRead local function read() if #queue > 0 then return unpack(table.remove(queue, 1)) end if paused then paused = false assert(socket:read_start(onRead)) end waiting = coroutine.running() return coroutine.yield() end local flushing = false local flushed = false local function checkShutdown() if socket:is_closing() then return end if not flushing and not writing then flushing = true local thread = coroutine.running() socket:shutdown(function (err) flushed = true coroutine.resume(thread, not err, err) end) assert(coroutine.yield()) end if flushed and not reading then socket:close() end end function onRead(err, chunk) assert(not err, err) local data = err and {nil, err} or {chunk} if waiting then local thread = waiting waiting = nil assert(coroutine.resume(thread, unpack(data))) else queue[#queue + 1] = data if not paused then paused = true assert(socket:read_stop()) end end if not chunk then reading = false -- Close the whole socket if the writing side is also closed already. checkShutdown() end end local function write(chunk) if chunk == nil then -- Shutdown our side of the socket writing = false checkShutdown() else -- TODO: add backpressure by pausing and resuming coroutine -- when write buffer is full. assert(socket:write(chunk)) end end return read, write end function exports.chain(...) local args = {...} local nargs = select("#", ...) return function (read, write) local threads = {} -- coroutine thread for each item local waiting = {} -- flag when waiting to pull from upstream local boxes = {} -- storage when waiting to write to downstream for i = 1, nargs do threads[i] = coroutine.create(args[i]) waiting[i] = false local r, w if i == 1 then r = read else function r() local j = i - 1 if boxes[j] then local data = boxes[j] boxes[j] = nil assert(coroutine.resume(threads[j])) return unpack(data) else waiting[i] = true return coroutine.yield() end end end if i == nargs then w = write else function w(...) local j = i + 1 if waiting[j] then waiting[j] = false assert(coroutine.resume(threads[j], ...)) else boxes[i] = {...} coroutine.yield() end end end assert(coroutine.resume(threads[i], r, w)) end end end
Import channel fix from rye
Import channel fix from rye
Lua
apache-2.0
zhaozg/lit,DBarney/lit,squeek502/lit,james2doyle/lit,kaustavha/lit,lduboeuf/lit,1yvT0s/lit,luvit/lit,kidaa/lit
98126463abb81e2d9e5c858b516e4a1eb0f6669a
lib/gsmake/gsmake/repo.lua
lib/gsmake/gsmake/repo.lua
local fs = require "lemoon.fs" local class = require "lemoon.class" local filepath = require "lemoon.filepath" local sqlite3 = require "lemoon.sqlite3" local module = {} local sqlexec = function(db,sql) local id, err = db:exec(sql) if err ~= nil then throw("%s\n\t%s",sql,err) end return id end function module.ctor (gsmake,path) local obj = { GSMake = gsmake ; Path = path ; -- the global package cached repo path dbPath = filepath.join(path,"repo.db") ; -- database fullpath } module.exec(obj,function(db) sqlexec(db, [[ create table if not exists _SOURCE ( _NAME TEXT, _PATH TEXT, _SOURCE TEXT, _VERSION TEXT, _CACHED BOOLEAN ); create unique index if not exists _SOURCE_FULLNAME_INDEXER ON _SOURCE (_NAME,_VERSION); create table if not exists _SYNC ( _NAME TEXT, _PATH TEXT, _SOURCE TEXT, _VERSION TEXT, _PROTOCOL TEXT ); create unique index if not exists _SYNC_FULLNAME_INDEXER ON _SYNC (_NAME,_VERSION,_PROTOCOL); ]]) end) return obj end function module:exec (f) local db = assert(sqlite3.open(self.dbPath)) local result = { f(db) } db:close() return table.unpack(result) end function module:query_source(name,version) local SQL = string.format('SELECT * FROM _SOURCE WHERE _NAME="%s" and _VERSION="%s"',name,version) return self:exec(function(db) for _,path,_,_ in db:urows(SQL) do return path,true end return "",false end) end function module:query_sync(name,version) local SQL = string.format('SELECT * FROM _SYNC WHERE _NAME="%s" and _VERSION="%s"',name,version) return self:exec(function(db) for _,path,_,_,_ in db:urows(SQL) do return path,true end return "",false end) end function module:remove_sync(name,version) local SQL = string.format('delete FROM _SYNC WHERE _NAME="%s" and _VERSION="%s"',name,version) self:exec(function(db) sqlexec(db,SQL) end) end function module:save_sync(name,version,source,path,sync,force) if force then self:remove_sync(name,version) end local SQL = string.format('insert into _SYNC VALUES("%s","%s","%s","%s","%s")',name,path,source,version,sync) self:exec(function(db) sqlexec(db,SQL) end) end function module:remove_source(name,version) local SQL = string.format('delete FROM _SOURCE WHERE _NAME="%s" and _VERSION="%s"',name,version) self:exec(function(db) sqlexec(db,SQL) end) end function module:save_source(name,version,source,path,force) if force then self:remove_source(name,version) end local SQL = string.format('insert into _SOURCE VALUES("%s","%s","%s","%s",%d)',name,path,source,version,0) self:exec(function(db) sqlexec(db,SQL) end) end function module:save_cached_source(name,version,path) self:remove_source(name,version) local SQL = string.format('insert into _SOURCE VALUES("%s","%s","%s","%s",%d)',name,path,path,version,1) self:exec(function(db) sqlexec(db,SQL) end) end function module:remove_cached_source(name,version,path) local SQL = string.format('delete FROM _SOURCE WHERE _NAME="%s" and _VERSION="%s" and _SOURCE="%s" and _PATH="%s"',name,version,path,path) self:exec(function(db) sqlexec(db,SQL) end) end function module:query_cached_sources(callback) local SQL = 'SELECT * FROM _SOURCE WHERE _CACHED=1' return self:exec(function(db) for name,path,_,version,_ in db:urows(SQL) do callback(name,path,version) end end) end return module
local fs = require "lemoon.fs" local throw = require "lemoon.throw" local class = require "lemoon.class" local filepath = require "lemoon.filepath" local sqlite3 = require "lemoon.sqlite3" local module = {} local sqlexec = function(db,sql) local id, err = db:exec(sql) if err ~= nil then throw("%s\n\t%s",sql,err) end return id end function module.ctor (gsmake,path) local obj = { GSMake = gsmake ; Path = path ; -- the global package cached repo path dbPath = filepath.join(path,"repo.db") ; -- database fullpath } module.exec(obj,function(db) sqlexec(db, [[ create table if not exists _SOURCE ( _NAME TEXT, _PATH TEXT, _SOURCE TEXT, _VERSION TEXT, _CACHED BOOLEAN ); create unique index if not exists _SOURCE_FULLNAME_INDEXER ON _SOURCE (_NAME,_VERSION); create table if not exists _SYNC ( _NAME TEXT, _PATH TEXT, _SOURCE TEXT, _VERSION TEXT, _PROTOCOL TEXT ); create unique index if not exists _SYNC_FULLNAME_INDEXER ON _SYNC (_NAME,_VERSION,_PROTOCOL); ]]) end) return obj end function module:exec (f) local db = assert(sqlite3.open(self.dbPath)) local result = { f(db) } db:close() return table.unpack(result) end function module:query_source(name,version) local SQL = string.format('SELECT * FROM _SOURCE WHERE _NAME="%s" and _VERSION="%s"',name,version) return self:exec(function(db) for _,path,_,_ in db:urows(SQL) do return path,true end return "",false end) end function module:query_sync(name,version) local SQL = string.format('SELECT * FROM _SYNC WHERE _NAME="%s" and _VERSION="%s"',name,version) return self:exec(function(db) for _,path,_,_,_ in db:urows(SQL) do return path,true end return "",false end) end function module:remove_sync(name,version) local SQL = string.format('delete FROM _SYNC WHERE _NAME="%s" and _VERSION="%s"',name,version) self:exec(function(db) sqlexec(db,SQL) end) end function module:save_sync(name,version,source,path,sync,force) if force then self:remove_sync(name,version) end local SQL = string.format('insert into _SYNC VALUES("%s","%s","%s","%s","%s")',name,path,source,version,sync) self:exec(function(db) sqlexec(db,SQL) end) end function module:remove_source(name,version) local SQL = string.format('delete FROM _SOURCE WHERE _NAME="%s" and _VERSION="%s"',name,version) self:exec(function(db) sqlexec(db,SQL) end) end function module:save_source(name,version,source,path,force) if force then self:remove_source(name,version) end local SQL = string.format('insert into _SOURCE VALUES("%s","%s","%s","%s",%d)',name,path,source,version,0) self:exec(function(db) sqlexec(db,SQL) end) end function module:save_cached_source(name,version,path) self:remove_source(name,version) local SQL = string.format('insert into _SOURCE VALUES("%s","%s","%s","%s",%d)',name,path,path,version,1) self:exec(function(db) sqlexec(db,SQL) end) end function module:remove_cached_source(name,version,path) local SQL = string.format('delete FROM _SOURCE WHERE _NAME="%s" and _VERSION="%s" and _SOURCE="%s" and _PATH="%s"',name,version,path,path) self:exec(function(db) sqlexec(db,SQL) end) end function module:query_cached_sources(callback) local SQL = 'SELECT * FROM _SOURCE WHERE _CACHED=1' return self:exec(function(db) for name,path,_,version,_ in db:urows(SQL) do callback(name,path,version) end end) end return module
fix bug
fix bug
Lua
mit
gsmake/gsmake,gsmake/gsmake
93d1098886f08e7512afacadcd5e830c5e8a2d2b
aspects/nvim/files/.config/nvim/lua/wincent/vim/map.lua
aspects/nvim/files/.config/nvim/lua/wincent/vim/map.lua
wincent.g.map_callbacks = {} local callback_index = 0 -- TODO: For completeness, should have unmap() too, and other variants -- as they arise (nunmap() etc); but for now just going with a "dispose" -- function as return value. local map = function (mode, lhs, rhs, opts) opts = opts or {} local rhs_type = type(rhs) if rhs_type == 'function' then local key = '_' .. callback_index callback_index = callback_index + 1 wincent.g.map_callbacks[key] = rhs rhs = 'v:lua.wincent.g.map_callbacks.' .. key .. '()' elseif rhs_type ~= 'string' then error('map(): unsupported rhs type: ' .. rhs_type) end local buffer = opts.buffer opts.buffer = nil if buffer == true then vim.api.nvim_buf_set_keymap(0, mode, lhs, rhs, opts) else vim.api.nvim_set_keymap(mode, lhs, rhs, opts) end return { dispose = function() if buffer == true then vim.api.nvim_buf_del_keymap(0, mode, lhs) else vim.api.nvim_del_keymap(mode, lhs) end wincent.g.map_callbacks[key] = nil end, } end return map
wincent.g.map_callbacks = {} -- Used as tie-breaker in event that multiple registrations happen for same file -- + line. local callback_index = 0 local config_prefix = vim.env.HOME .. '/.config/nvim/' -- TODO: For completeness, should have unmap() too, and other variants -- as they arise (nunmap() etc); but for now just going with a "dispose" -- function as return value. local get_key = function (fn) local info = debug.getinfo(fn) local key = info.short_src if vim.startswith(key, config_prefix) then key = key:sub(#config_prefix + 1) end if vim.endswith(key, '.lua') then -- and sure would be weird if it _didn't_ key = key:sub(1, #key - 4) end key = key:gsub('%W', '_') key = key .. '_L' .. info.linedefined if wincent.g.map_callbacks[key] ~= nil then key = key .. '_' .. callback_index callback_index = callback_index + 1 end return key end local map = function (mode, lhs, rhs, opts) opts = opts or {} local rhs_type = type(rhs) if rhs_type == 'function' then local key = get_key(rhs) wincent.g.map_callbacks[key] = rhs rhs = 'v:lua.wincent.g.map_callbacks.' .. key .. '()' elseif rhs_type ~= 'string' then error('map(): unsupported rhs type: ' .. rhs_type) end local buffer = opts.buffer opts.buffer = nil if buffer == true then vim.api.nvim_buf_set_keymap(0, mode, lhs, rhs, opts) else vim.api.nvim_set_keymap(mode, lhs, rhs, opts) end return { dispose = function() if buffer == true then vim.api.nvim_buf_del_keymap(0, mode, lhs) else vim.api.nvim_del_keymap(mode, lhs) end wincent.g.map_callbacks[key] = nil end, } end return map
feat(nvim): improve introspectability of anonymous Lua callbacks
feat(nvim): improve introspectability of anonymous Lua callbacks Starting with mappings, but I'll apply this to the other places we use anonymous functions. Before, running `:nmap j` would print: ``` n j * v:lua.wincent.g.map_callbacks._13() ``` Now, it prints: ``` n j * v:lua.wincent.g.map_callbacks.plugin_mappings_normal_L38() ``` The callback key is produced by grabbing the path to the function via `debug.getinfo`, stripping off the prefix (eg. `~/.config/nvim`), dropping the extension, turning non-alphanumeric characters (basically that means slashes) into underscores, appending the line-number, and if necessary to resolve collisions, appending a monotonically increasing index number (this can happen if the same anonymous function is added repeatedly). Closes: https://github.com/wincent/wincent/issues/115
Lua
unlicense
wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent
775538730f8fc6204bed4492bc32839a8e290e0f
modules/admin-full/luasrc/model/cbi/admin_services/dnsmasq.lua
modules/admin-full/luasrc/model/cbi/admin_services/dnsmasq.lua
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- m = Map("dhcp", "Dnsmasq") s = m:section(TypedSection, "dnsmasq", translate("Settings")) s.anonymous = true s:option(Flag, "domainneeded") s:option(Flag, "authoritative") s:option(Flag, "boguspriv") s:option(Flag, "filterwin2k") s:option(Flag, "localise_queries") s:option(Value, "local") s:option(Value, "domain") s:option(Flag, "expandhosts") s:option(Flag, "nonegcache") s:option(Flag, "readethers") s:option(Value, "leasefile") s:option(Value, "resolvfile") s:option(Flag, "nohosts").optional = true s:option(Flag, "strictorder").optional = true s:option(Flag, "logqueries").optional = true s:option(Flag, "noresolv").optional = true s:option(Value, "dnsforwardmax").optional = true s:option(Value, "port").optional = true s:option(Value, "ednspacket_max").optional = true s:option(Value, "dhcpleasemax").optional = true s:option(Value, "addnhosts").optional = true s:option(Value, "queryport").optional = true s:option(Flag, "enable_tftp").optional = true s:option(Value, "tftp_root").optional = true s:option(Value, "dhcp_boot").optional = true return m
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- m = Map("dhcp", "Dnsmasq", translate("Dnsmasq is a combined <abbr title=\"Dynamic Host Configuration Protocol" .. "\">DHCP</abbr>-Server and <abbr title=\"Domain Name System\">DNS</abbr>-" .. "Forwarder for <abbr title=\"Network Address Translation\">NAT</abbr> " .. "firewalls")) s = m:section(TypedSection, "dnsmasq", translate("Settings")) s.anonymous = true s.addremove = false s:option(Flag, "domainneeded", translate("Domain required"), translate("Don't forward <abbr title=\"Domain Name System\">DNS</abbr>-Requests without " .. "<abbr title=\"Domain Name System\">DNS</abbr>-Name")) s:option(Flag, "authoritative", translate("Authoritative"), translate("This is the only <abbr title=\"Dynamic Host Configuration Protocol\">DHCP</" .. "abbr> in the local network")) s:option(Flag, "boguspriv", translate("Filter private"), translate("Don't forward reverse lookups for local networks")) s:option(Flag, "filterwin2k", translate("Filter useless"), translate("filter useless <abbr title=\"Domain Name System\">DNS</abbr>-queries of " .. "Windows-systems")) s:option(Flag, "localise_queries", translate("Localise queries"), translate("localises the hostname depending on its subnet")) s:option(Value, "local", translate("Local Server")) s:option(Value, "domain", translate("Local Domain")) s:option(Flag, "expandhosts", translate("Expand Hosts"), translate("adds domain names to hostentries in the resolv file")) s:option(Flag, "nonegcache", translate("don't cache unknown"), translate("prevents caching of negative <abbr title=\"Domain Name System\">DNS</abbr>-" .. "replies")) s:option(Flag, "readethers", translate("Use <code>/etc/ethers</code>"), translate("Read <code>/etc/ethers</code> to configure the <abbr title=\"Dynamic Host " .. "Configuration Protocol\">DHCP</abbr>-Server")) s:option(Value, "leasefile", translate("Leasefile"), translate("file where given <abbr title=\"Dynamic Host Configuration Protocol\">DHCP</" .. "abbr>-leases will be stored")) s:option(Value, "resolvfile", translate("Resolvfile"), translate("local <abbr title=\"Domain Name System\">DNS</abbr> file")) s:option(Flag, "nohosts", translate("Ignore <code>/etc/hosts</code>")).optional = true s:option(Flag, "strictorder", translate("Strict order"), translate("<abbr title=\"Domain Name System\">DNS</abbr>-Server will be queried in the " .. "order of the resolvfile")).optional = true s:option(Flag, "logqueries", translate("Log queries")).optional = true s:option(Flag, "noresolv", translate("Ignore resolve file")).optional = true s:option(Value, "dnsforwardmax", translate("concurrent queries")).optional = true s:option(Value, "port", translate("<abbr title=\"Domain Name System\">DNS</abbr>-Port")).optional = true s:option(Value, "ednspacket_max", translate("<abbr title=\"maximal\">max.</abbr> <abbr title=\"Extension Mechanisms for " .. "Domain Name System\">EDNS0</abbr> paket size")).optional = true s:option(Value, "dhcpleasemax", translate("<abbr title=\"maximal\">max.</abbr> <abbr title=\"Dynamic Host Configuration " .. "Protocol\">DHCP</abbr>-Leases")).optional = true s:option(Value, "addnhosts", translate("additional hostfile")).optional = true s:option(Value, "queryport", translate("query port")).optional = true s:option(Flag, "enable_tftp", translate("Enable TFTP-Server")).optional = true s:option(Value, "tftp_root", translate("TFTP-Server Root")).optional = true s:option(Value, "dhcp_boot", translate("Network Boot Image")).optional = true return m
modules/admin-full: fix dnsmasq page
modules/admin-full: fix dnsmasq page git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@5462 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
Lua
apache-2.0
fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci
b8721ab0bfe156040c881d9f1227183634c5d9d5
modules/atf/util.lua
modules/atf/util.lua
local utils = require("atf.stdlib.argument_parser") config = require('config') xmlLogger = require("logger") local module = { } local script_files = {} RequiredArgument = utils.RequiredArgument OptionalArgument = utils.OptionalArgument NoArgument = utils.NoArgument local function dump(o) if type(o) == 'table' then local s = '{ ' for k,v in pairs(o) do if type(k) ~= 'number' then k = '"'..k..'"' end s = s .. '['..k..'] = ' .. dump(v) .. ',' end return s .. '} \n' else return tostring(o) end end function print_table(t,... ) local comment = table.pack(...) if (type(t) == 'table' ) then print(dump(t).. dump(comment)) else print(tostring(t).. dump(comment)) end end function is_file_exists(name) local f = io.open(name,"r") if f ~=nil then io.close(f) return true else return false end end function module.config_file(config_file) if (is_file_exists(config_file)) then config_file = config_file:gsub('%.', " ") config_file = config_file:gsub("/", ".") config_file = config_file:gsub("[%s]lua$", "") config = require(tostring(config_file)) else print("Incorrect config file type") print("Uses default config") print("==========================") end end function module.mobile_connection(str) config.mobileHost = str end function module.mobile_connection_port(src) config.mobilePort= src end function module.hmi_connection(str) config.hmiUrl = str end function module.hmi_connection_port(src) config.hmiPort = src end function module.perflog_connection(str) config.perflogConnection=str end function module.perflog_connection_port(str) config.perflogConnectionPort=str end function module.report_path(str) config.reportPath=str end function module.report_mark(str) config.reportMark=str end function module.add_script(src) table.insert(script_files,src) end function module.storeFullSDLLogs(str) config.storeFullSDLLogs=str end function module.heartbeat(str) config.heartbeatTimeout=str end function parse_cmdl() arguments = utils.getopt(argv, opts) if (arguments) then if (arguments['config-file']) then module.config_file(arguments['config-file']) end for k,v in pairs(arguments) do if (type(k) ~= 'number') then if ( k ~= 'config-file') then k = (k):gsub ("%W", "_") module[k](v) end else if k >= 2 and v ~= "modules/launch.lua" then module.add_script(v) end end end end return script_files end function PrintUsage() utils.PrintUsage() end function declare_opt(...) utils.declare_opt(...) end function declare_long_opt(...) utils.declare_long_opt(...) end function declare_short_opt(...) utils.declare_short_opt(...) end function script_execute(script_name) xmlLogger = xmlLogger.init(tostring(script_name)) dofile(script_name) end function compareValues(a, b, name) local function iter(a, b, name, msg) if type(a) == 'table' and type(b) == 'table' then local res = true for k, v in pairs(a) do res = res and iter(v, b[k], name .. "." .. k, msg) end return res else if a == b then return true else table.insert(msg, string.format("%s: expected: %s, actual value: %s", name, a, b)) return false end end end local message = { } local res = iter(a, b, name, message) return res, table.concat(message, '\n') end
local utils = require("atf.stdlib.argument_parser") config = require('config') xmlLogger = require("logger") local module = { } local script_files = {} RequiredArgument = utils.RequiredArgument OptionalArgument = utils.OptionalArgument NoArgument = utils.NoArgument local function dump(o) if type(o) == 'table' then local s = '{ ' for k,v in pairs(o) do if type(k) ~= 'number' then k = '"'..k..'"' end s = s .. '['..k..'] = ' .. dump(v) .. ',' end return s .. '} \n' else return tostring(o) end end function print_table(t,... ) local comment = table.pack(...) if (type(t) == 'table' ) then print(dump(t).. dump(comment)) else print(tostring(t).. dump(comment)) end end function is_file_exists(name) local f = io.open(name,"r") if f ~=nil then io.close(f) return true else return false end end function module.config_file(config_file) if (is_file_exists(config_file)) then config_file = config_file:gsub('%.', " ") config_file = config_file:gsub("/", ".") config_file = config_file:gsub("[%s]lua$", "") config = require(tostring(config_file)) else print("Incorrect config file type") print("Uses default config") print("==========================") end end function module.mobile_connection(str) config.mobileHost = str end function module.mobile_connection_port(src) config.mobilePort= src end function module.hmi_connection(str) config.hmiUrl = str end function module.hmi_connection_port(src) config.hmiPort = src end function module.perflog_connection(str) config.perflogConnection=str end function module.perflog_connection_port(str) config.perflogConnectionPort=str end function module.report_path(str) config.reportPath=str end function module.report_mark(str) config.reportMark=str end function module.add_script(src) table.insert(script_files,src) end function module.storeFullSDLLogs(str) config.storeFullSDLLogs=str end function module.heartbeat(str) config.heartbeatTimeout=str end function parse_cmdl() arguments = utils.getopt(argv, opts) if (arguments) then if (arguments['config-file']) then module.config_file(arguments['config-file']) end for k,v in pairs(arguments) do if (type(k) ~= 'number') then if ( k ~= 'config-file') then k = (k):gsub ("%W", "_") module[k](v) end else if k >= 2 and v ~= "modules/launch.lua" then module.add_script(v) end end end end return script_files end function PrintUsage() utils.PrintUsage() end function declare_opt(...) utils.declare_opt(...) end function declare_long_opt(...) utils.declare_long_opt(...) end function declare_short_opt(...) utils.declare_short_opt(...) end function script_execute(script_name) xmlLogger = xmlLogger.init(tostring(script_name)) dofile(script_name) end function compareValues(a, b, name) local function iter(a, b, name, msg) if type(a) == 'table' and type(b) == 'table' then local res = true for k, v in pairs(a) do res = res and iter(v, b[k], name .. "." .. k, msg) end return res else if (type(a) ~= type(b)) then if (type(a) == 'string' and type(b) == 'number') then b = tostring(b) else table.insert(msg, string.format("type of data %s: expected %s, actual type: %s", name, type(a), type(b))) return false end end if a == b then return true else table.insert(msg, string.format("%s: expected: %s, actual value: %s", name, a, b)) return false end end end local message = { } local res = iter(a, b, name, message) return res, table.concat(message, '\n') end
Bug fix: update fix for APPLINK-13288
Bug fix: update fix for APPLINK-13288
Lua
bsd-3-clause
aderiabin/sdl_atf,aderiabin/sdl_atf,aderiabin/sdl_atf
79f2c3eb64e8d5b4475651a35fdb67e32a30b166
game/dota_addons/trap_wars/scripts/vscripts/ability_scripts/barricade_setup.lua
game/dota_addons/trap_wars/scripts/vscripts/ability_scripts/barricade_setup.lua
function OnCreated(keys) Timers:CreateTimer(1/30, function() local tilesize = GameRules.TileSize or 128 local e1p = keys.caster:GetAbsOrigin() local offset = Vector(0, 0, 60) -- offset for the fence posts -- add the gridnav blocker local blocker = SpawnEntityFromTableSynchronous("point_simple_obstruction", {origin=e1p}) keys.caster.blocker = blocker:GetEntityIndex() -- reset the entity's position after the blocker is placed (and slide it down, since the model is a bit tall) keys.caster:SetAbsOrigin(e1p - offset) -- give our fence post a random yaw keys.caster:SetForwardVector(RandomVector(1)) -- find other fence posts in the adjacent tiles and add fencing between them for _, entity in pairs(Entities:FindAllByClassnameWithin("npc_dota_creature", keys.caster:GetAbsOrigin(), tilesize+1)) do if entity.GetUnitName and entity:GetUnitName() == "npc_trapwars_barricade" and entity ~= keys.caster and entity:IsAlive() then -- new entity position local e2p = entity:GetAbsOrigin() + offset -- find the middle of the two fence posts local midpoint = e1p - (e1p-e2p)/2 -- add in the fencing between them local fencing = Entities:CreateByClassname("prop_dynamic") fencing:SetAbsOrigin(midpoint) fencing:SetModel("models/props_debris/wood_fence002.vmdl") fencing:SetModelScale(0.8) -- align the fencing local randDir = 1 if RandomInt(0, 1) > 0 then randDir = -1 end fencing:SetForwardVector(randDir*(e1p-e2p)) end end end) end function OnDestroy(keys) local tilesize = GameRules.TileSize or 128 -- remove the gridnav blocker local blocker = EntIndexToHScript(keys.caster.blocker) if blocker then blocker:RemoveSelf() end -- find and remove all of the fencing around this fence post for _, ent in pairs(Entities:FindAllByClassnameWithin("prop_dynamic", keys.caster:GetAbsOrigin(), tilesize/2+1)) do if ent:GetModelName() == "models/props_debris/wood_fence002.vmdl" then ent:Kill() end end -- hide the fence post keys.caster:AddEffects(EF_NODRAW) -- add destruction particles local part = ParticleManager:CreateParticle("particles/traps/barricade/barricade_destroyed.vpcf", PATTACH_ABSORIGIN, keys.caster) ParticleManager:SetParticleControlEnt(part, 0, keys.caster, PATTACH_ABSORIGIN, "attach_origin", keys.caster:GetAbsOrigin(), true) Timers:CreateTimer(2, function() ParticleManager:DestroyParticle(part, false) ParticleManager:ReleaseParticleIndex(part) end) end
function OnCreated(keys) Timers:CreateTimer(1/30, function() local tilesize = GameRules.TileSize or 128 --local caster_pos = keys.caster:GetAbsOrigin() local caster_pos = GameRules.GameMode:Get2DGridCenter(keys.caster:GetAbsOrigin()) local offset = Vector(0, 0, 60) -- offset for the fence posts -- add the gridnav blocker local blocker = SpawnEntityFromTableSynchronous("point_simple_obstruction", {origin=caster_pos}) keys.caster.blocker = blocker:GetEntityIndex() -- reset the entity's position after the blocker is placed (and slide it down, since the model is a bit tall) keys.caster:SetAbsOrigin(caster_pos - offset) -- give our fence post a random yaw keys.caster:SetForwardVector(RandomVector(1)) -- do a precursory removal of any diagonal fencing around this tile (very annoying that it had to come to this) local diagonal_spots = { caster_pos + Vector(tilesize/2, tilesize/2, 0), caster_pos + Vector(tilesize/2, -tilesize/2, 0), caster_pos + Vector(-tilesize/2, tilesize/2, 0), caster_pos + Vector(-tilesize/2, -tilesize/2, 0) } for _, pos in pairs(diagonal_spots) do for _, ent in pairs(Entities:FindAllByClassnameWithin("prop_dynamic", pos, tilesize/4)) do if ent:GetModelName() == "models/props_debris/wood_fence002.vmdl" then ent:Kill() end end end -- very specifically ordered list of positions to check around this entity local check_positions = { caster_pos + Vector( 0, tilesize+1, 0), caster_pos + Vector(tilesize+1, tilesize+1, 0), caster_pos + Vector(tilesize+1, 0, 0), caster_pos + Vector(tilesize+1, -tilesize-1, 0), caster_pos + Vector( 0, -tilesize-1, 0), caster_pos + Vector(-tilesize-1, -tilesize-1, 0), caster_pos + Vector(-tilesize-1, 0, 0), caster_pos + Vector(-tilesize-1, tilesize+1, 0) } -- find other barricades around this one at said positions local found_entities = {} for i, pos in pairs(check_positions) do for _, ent in pairs(Entities:FindAllByClassnameWithin("npc_dota_creature", pos, tilesize/2)) do if ent.GetUnitName and ent:GetUnitName() == "npc_trapwars_barricade" and ent:IsAlive() then found_entities[i] = ent break; end end end -- add the fencing between them (odd=horizontal\vertical, even=diagonal) for i=1, 8 do if found_entities[i] then local add_fencing = false -- if it's an odd tile (horizontal\vertical), always add if (i+1)%2 == 0 then add_fencing = true -- if it's an even tile (diagonal), add only if there isn't any even tiles next to it else if i == 1 then if not found_entities[8] and not found_entities[i+1] then add_fencing=true end elseif i == 8 then if not found_entities[i-1] and not found_entities[1] then add_fencing=true end elseif not found_entities[i-1] and not found_entities[i+1] then add_fencing=true end end if add_fencing then Timers:CreateTimer(1/15, function() -- new entity position local ent_pos = found_entities[i]:GetAbsOrigin() + offset -- add in the fencing between them local fencing = Entities:CreateByClassname("prop_dynamic") fencing:SetAbsOrigin(caster_pos - (caster_pos-ent_pos)/2) -- set the fencing model fencing:SetModel("models/props_debris/wood_fence002.vmdl") fencing:SetModelScale(0.8) -- align the fencing local rand = 1 if RandomInt(0, 1) > 0 then rand = -1 end fencing:SetForwardVector(rand*(caster_pos-ent_pos)) end) end end end end) end function OnDestroy(keys) local tilesize = GameRules.TileSize or 128 -- remove the gridnav blocker local blocker = EntIndexToHScript(keys.caster.blocker or -1) if blocker then blocker:RemoveSelf() end -- find and remove all of the fencing around this fence post for _, ent in pairs(Entities:FindAllByClassnameWithin("prop_dynamic", keys.caster:GetAbsOrigin(), math.sqrt(2*(tilesize*tilesize))/2+1)) do if ent:GetModelName() == "models/props_debris/wood_fence002.vmdl" then ent:Kill() end end -- hide the fence post keys.caster:AddEffects(EF_NODRAW) -- add destruction particles local part = ParticleManager:CreateParticle("particles/traps/barricade/barricade_destroyed.vpcf", PATTACH_ABSORIGIN, keys.caster) ParticleManager:SetParticleControlEnt(part, 0, keys.caster, PATTACH_ABSORIGIN, "attach_origin", keys.caster:GetAbsOrigin(), true) Timers:CreateTimer(2, function() ParticleManager:DestroyParticle(part, false) ParticleManager:ReleaseParticleIndex(part) end) end
Reworked barricade fencing to include diagonals, and fixed some bugs with fencing being created before the posts were in the right position.
Reworked barricade fencing to include diagonals, and fixed some bugs with fencing being created before the posts were in the right position.
Lua
mit
vyrus714/Trap-Wars
8ab8c6e837b112a3c4b4fa939aa5a7ec8e845b7a
wyx/component/property.lua
wyx/component/property.lua
local property = {} local warning = warning local depths = require 'wyx.system.renderDepths' -- check if a given property is valid local isproperty = function(prop) return property[prop] ~= nil end -- get a valid property name local getcache = {} local get = function(prop) local ret = getcache[prop] if ret == nil then if not isproperty(prop) then warning('invalid component property: %q', prop) else ret = prop getcache[prop] = ret end end return ret end -- get a property's default value local defaultcache = setmetatable({}, {__mode = 'v'}) local default = function(prop) local ret = defaultcache[prop] if ret == nil then if not isproperty(prop) then warning('invalid component property: %q', prop) else local Expression = getClass 'wyx.component.Expression' ret = property[prop].default if Expression.isExpression(ret) then ret = Expression.makeExpression(ret) end defaultcache[prop] = ret end end return ret end -- get a property's ELevel weight local weightcache = setmetatable({}, {__mode = 'v'}) local weight = function(prop) local ret = weightcache[prop] if ret == nil then if not isproperty(prop) then warning('invalid component property: %q', prop) else ret = property[prop].weight or 0 weightcache[prop] = ret end end return ret end ------------------------------------------------- -- the actual properties and sensible defaults -- ------------------------------------------------- -- combat properties property.Attack = {default = 0, weight = 0.6} property.Defense = {default = 0, weight = 1.2} property.Damage = {default = 0, weight = 0.6} property.AttackBonus = {default = 0, weight = 0.6} property.DefenseBonus = {default = 0, weight = 1.2} property.DamageBonus = {default = 0, weight = 0.6} property._DamageMin = {default = 0, weight = 0.0} property._DamageMax = {default = 0, weight = 0.0} -- health properties property.Health = {default = '=$MaxHealth', weight = 0.0} property.MaxHealth = {default = 0, weight = 1.0} property.HealthBonus = {default = 0, weight = 0.5} property.MaxHealthBonus = {default = 0, weight = 1.0} -- motion properties property.Position = {default = {1, 1}, weight = 0.0} property.CanMove = {default = true, weight = 10.0} property.IsContained = {default = false, weight = 0.0} property.IsAttached = {default = false, weight = 0.0} -- collision properties property.BlockedBy = {default = {Wall='ALL', Door='shut'}, weight = 0.0} -- graphics properties property.TileSet = {default = 'dungeon', weight = 0.0} property.TileCoords = {default = {front = {1, 1}}, weight = 0.0} property.TileSize = {default = 32, weight = 0.0} property.RenderDepth = {default = depths.game, weight = 0.0} property.Visibility = {default = 0, weight = 1.0} property.VisibilityBonus = {default = 0, weight = 1.0} -- controller properties property.CanOpenDoors = {default = false, weight = 10.0} -- time properties property.DefaultCost = {default = 0, weight = 0.0} property.AttackCost = {default = 100, weight = 0.01} property.AttackCostBonus = {default = 0, weight = -0.01} property.MoveCost = {default = 100, weight = 0.01} property.MoveCostBonus = {default = 0, weight = -0.01} property.WaitCost = {default = '!$Speed', weight = 0.0} property.WaitCostBonus = {default = 0, weight = -0.0} property.Speed = {default = 100, weight = 0.01} property.SpeedBonus = {default = 0, weight = -0.01} property.IsExhausted = {default = false, weight = 0.0} property.DoTick = {default = true, weight = 0.0} -- container properties property.MaxContainerSize = {default = 0, weight = 0.0} property.ContainedEntities = {default = {}, weight = 0.0} property.ContainedEntitiesHash = {default = {}, weight = 0.0} -- attachment properties property.AttachedEntities = {default = {}, weight = 1.0} -- the structure of valid property return setmetatable({isproperty=isproperty, default=default, weight=weight}, {__call = function(_, prop) return get(prop) end})
local property = {} local warning = warning local depths = require 'wyx.system.renderDepths' -- check if a given property is valid local isproperty = function(prop) return property[prop] ~= nil end -- get a valid property name local getcache = {} local get = function(prop) local ret = getcache[prop] if ret == nil then if not isproperty(prop) then if warning then warning('invalid component property: %q', prop) elseif Console then Console:print('invalid component property: %q', prop) else print('invalid component property: %q', prop) end else ret = prop getcache[prop] = ret end end return ret end -- get a property's default value local defaultcache = setmetatable({}, {__mode = 'v'}) local default = function(prop) local ret = defaultcache[prop] if ret == nil then if not isproperty(prop) then warning('invalid component property: %q', prop) else local Expression = getClass 'wyx.component.Expression' ret = property[prop].default if Expression.isExpression(ret) then ret = Expression.makeExpression(ret) end defaultcache[prop] = ret end end return ret end -- get a property's ELevel weight local weightcache = setmetatable({}, {__mode = 'v'}) local weight = function(prop) local ret = weightcache[prop] if ret == nil then if not isproperty(prop) then warning('invalid component property: %q', prop) else ret = property[prop].weight or 0 weightcache[prop] = ret end end return ret end ------------------------------------------------- -- the actual properties and sensible defaults -- ------------------------------------------------- -- combat properties property.Attack = {default = 0, weight = 0.6} property.Defense = {default = 0, weight = 1.2} property.Damage = {default = 0, weight = 0.6} property.AttackBonus = {default = 0, weight = 0.6} property.DefenseBonus = {default = 0, weight = 1.2} property.DamageBonus = {default = 0, weight = 0.6} property._DamageMin = {default = 0, weight = 0.0} property._DamageMax = {default = 0, weight = 0.0} -- health properties property.Health = {default = '=$MaxHealth', weight = 0.0} property.MaxHealth = {default = 0, weight = 1.0} property.HealthBonus = {default = 0, weight = 0.5} property.MaxHealthBonus = {default = 0, weight = 1.0} -- motion properties property.Position = {default = {1, 1}, weight = 0.0} property.CanMove = {default = true, weight = 10.0} property.IsContained = {default = false, weight = 0.0} property.IsAttached = {default = false, weight = 0.0} -- collision properties property.BlockedBy = {default = {Wall='ALL', Door='shut'}, weight = 0.0} -- graphics properties property.TileSet = {default = 'dungeon', weight = 0.0} property.TileCoords = {default = {front = {1, 1}}, weight = 0.0} property.TileSize = {default = 32, weight = 0.0} property.RenderDepth = {default = depths.game, weight = 0.0} property.Visibility = {default = 0, weight = 1.0} property.VisibilityBonus = {default = 0, weight = 1.0} -- controller properties property.CanOpenDoors = {default = false, weight = 10.0} -- time properties property.DefaultCost = {default = 0, weight = 0.0} property.AttackCost = {default = 100, weight = 0.01} property.AttackCostBonus = {default = 0, weight = -0.01} property.MoveCost = {default = 100, weight = 0.01} property.MoveCostBonus = {default = 0, weight = -0.01} property.WaitCost = {default = '!$Speed', weight = 0.0} property.WaitCostBonus = {default = 0, weight = -0.0} property.Speed = {default = 100, weight = 0.01} property.SpeedBonus = {default = 0, weight = -0.01} property.IsExhausted = {default = false, weight = 0.0} property.DoTick = {default = true, weight = 0.0} -- container properties property.MaxContainerSize = {default = 0, weight = 0.0} property.ContainedEntities = {default = {}, weight = 0.0} property.ContainedEntitiesHash = {default = {}, weight = 0.0} -- attachment properties property.AttachedEntities = {default = {}, weight = 1.0} -- the structure of valid property return setmetatable({isproperty=isproperty, default=default, weight=weight}, {__call = function(_, prop) return get(prop) end})
fix property warning
fix property warning
Lua
mit
scottcs/wyx
6d5c09660d96d1bf0bdeb71746c0cdca7c55bb73
src/lua/command/params.lua
src/lua/command/params.lua
------------ -- params -- params class in commands -- classmod: params -- author: AitorATuin -- license: MIT local util = require 'command.util' -- class table local Params = {} Params.__index = Params local function get_paramst_mt(paramst) local function add_index(t, field, idx) local tt = (t[field] or {}) tt[#tt+1] = idx return tt end -- argt[1] has always the command, ignore it local p = {} for i=2, #paramst do for capture in string.gmatch(paramst[i], "${([%w-_]+)}") do p[capture] = add_index(p, capture, i) end end return { __index = function(_, v) return p[v] end, __call = function(_) return p end } end Params.new = function(paramst) return setmetatable({ setmetatable(paramst, get_paramst_mt(paramst)) }, Params) end Params.add = function(self, other) local t = util.copy_table(self) for _, v in pairs(other) do t[#t+1] = v end return setmetatable(t, Params) end Params.__pow = function(this, other) if not util.eq_mt(this, other) then return nil, 'Only params can be added, second argument is not Params' end return this:add(other) end return Params
------------ -- params -- params class in commands -- classmod: params -- author: AitorATuin -- license: MIT local util = require 'command.util' -- class table local Params = {} Params.__index = Params local function get_paramst_mt(paramst) local function add_index(t, field, idx) local tt = (t[field] or {}) tt[#tt+1] = idx return tt end -- argt[1] has always the command, ignore it local p = {} for i=2, #paramst do for capture in string.gmatch(paramst[i], "${([%w-_]+)}") do p[capture] = add_index(p, capture, i) end end return { __index = function(_, v) return p[v] end, __call = function(_) return p end } end Params.new = function(paramst) return setmetatable({ setmetatable(paramst, get_paramst_mt(paramst)) }, Params) end Params.add = function(self, other) local t = util.copy_table(self) for _, v in pairs(other) do t[#t+1] = v end return setmetatable(t, Params) end Params.resolve = function(_, _) return nil end Params.__pow = function(this, values) return this:resolve(values) end Params.__add = function(this, other) if not util.eq_mt(this, other) then return nil, 'Only params can be added, second argument is not Params' end return this:add(other) end return Params
Fix __pow/__add metamethods
Fix __pow/__add metamethods
Lua
mit
AitorATuin/luacmd
eb6a9b7f18f9222d5b6bcb45d9ed125307ef747e
cv/videoio/init.lua
cv/videoio/init.lua
local cv = require 'cv._env' local ffi = require 'ffi' local C = ffi.load(cv.libPath('videoio')) --- ***************** Classes ***************** require 'cv.Classes' -- VideoCapture ffi.cdef[[ struct PtrWrapper VideoCapture_ctor_default(); struct PtrWrapper VideoCapture_ctor_device(int device); struct PtrWrapper VideoCapture_ctor_filename(const char *filename); void VideoCapture_dtor(struct PtrWrapper ptr); bool VideoCapture_open(struct PtrWrapper ptr, int device); bool VideoCapture_isOpened(struct PtrWrapper ptr); void VideoCapture_release(struct PtrWrapper ptr); bool VideoCapture_grab(struct PtrWrapper ptr); struct TensorPlusBool VideoCapture_retrieve( struct PtrWrapper ptr, struct TensorWrapper image, int flag); struct TensorPlusBool VideoCapture_read( struct PtrWrapper ptr, struct TensorWrapper image); bool VideoCapture_set(struct PtrWrapper ptr, int propId, double value); double VideoCapture_get(struct PtrWrapper ptr, int propId); ]] do local VideoCapture = torch.class('cv.VideoCapture', cv) -- v = cv.VideoCapture{} -- OR -- v = cv.VideoCapture{filename='../video.mp4'} -- OR -- v = cv.VideoCapture{device=2} function VideoCapture:__init(t) if type(t.filename or t[1]) == 'string' then self.ptr = ffi.gc(C.VideoCapture_ctor_filename(t.filename or t[1]), C.VideoCapture_dtor) elseif type(t.device or t[1]) == 'number' then self.ptr = ffi.gc(C.VideoCapture_ctor_device(t.device or t[1]), C.VideoCapture_dtor) else self.ptr = ffi.gc(C.VideoCapture_ctor_default(), C.VideoCapture_dtor) end end function VideoCapture:open(t) local argRules = { {"device", required = true} } local device = cv.argcheck(t, argRules) return C.VideoCapture_open(self.ptr, device) end function VideoCapture:isOpened() return C.VideoCapture_isOpened(self.ptr) end function VideoCapture:release() C.VideoCapture_release(self.ptr) end function VideoCapture:grab() return C.VideoCapture_grab(self.ptr) end function VideoCapture:retrieve(t) local argRules = { {"image", default = nil}, {"flag", default = 0} } local image, flag = cv.argcheck(t, argRules) result = C.VideoCapture_retrieve(self.ptr, cv.wrap_tensor(image), flag) return result.val, cv.unwrap_tensors(result.tensor) end -- result, image = cap.read{} -- OR -- im = torch.FloatTensor(640, 480, 3) -- result = cap.read{image=image} function VideoCapture:read(t) local argRules = { {"image", default = nil} } local image = cv.argcheck(t, argRules) result = C.VideoCapture_read(self.ptr, cv.wrap_tensor(image)) return result.val, cv.unwrap_tensors(result.tensor) end function VideoCapture:set(t) local argRules = { {"propId", required = true}, {"value", required = true} } local propId, value = cv.argcheck(t, argRules) return C.VideoCapture_set(self.ptr, propId, value) end function VideoCapture:get(t) local argRules = { {"propId", required = true} } local propId = cv.argcheck(t, argRules) return C.VideoCapture_get(self.ptr, propId) end end -- VideoWriter ffi.cdef[[ struct PtrWrapper VideoWriter_ctor_default(); struct PtrWrapper VideoWriter_ctor( const char *filename, int fourcc, double fps, struct SizeWrapper frameSize, bool isColor); void VideoWriter_dtor(struct PtrWrapper ptr); bool VideoWriter_open(struct PtrWrapper ptr, const char *filename, int fourcc, double fps, struct SizeWrapper frameSize, bool isColor); bool VideoWriter_isOpened(struct PtrWrapper ptr); void VideoWriter_release(struct PtrWrapper ptr); void VideoWriter_write(struct PtrWrapper ptr, struct TensorWrapper image); bool VideoWriter_set(struct PtrWrapper ptr, int propId, double value); double VideoWriter_get(struct PtrWrapper ptr, int propId); int VideoWriter_fourcc(char c1, char c2, char c3, char c4); ]] do local VideoWriter = torch.class('cv.VideoWriter', cv) function VideoWriter:__init(t) local argRules = { {"filename", required = true}, {"fourcc", required = true}, {"fps", required = true}, {"frameSize", required = true, operator = cv.Size}, {"isColor", default = nil} } local filename, fourcc, fps, frameSize, isColor = cv.argcheck(t, argRules) if t.filename then if isColor == nil then isColor = true end self.ptr = ffi.gc(C.VideoWriter_ctor( filename, fourcc, fps, frameSize, isColor), C.VideoWriter_dtor) else self.ptr = ffi.gc(C.VideoWriter_ctor_default(), C.VideoWriter_dtor) end end function VideoWriter:open(t) local argRules = { {"filename", required = true}, {"fourcc", required = true}, {"fps", required = true}, {"frameSize", required = true, operator = cv.Size}, {"isColor", default = nil} } local filename, fourcc, fps, frameSize, isColor = cv.argcheck(t, argRules) if isColor == nil then isColor = true end return C.VideoWriter_open(self.ptr, filename, fourcc, fps, frameSize, isColor) end function VideoWriter:isOpened() return C.VideoWriter_isOpened(self.ptr) end function VideoWriter:release() C.VideoWriter_release(self.ptr) end function VideoWriter:write(t) local argRules = { {"image", required = true} } local image = cv.argcheck(t, argRules) C.VideoWriter_write(self.ptr, image) end function VideoWriter:set(t) local argRules = { {"propId", required = true}, {"value", required = true} } local propId, value = cv.argcheck(t, argRules) return C.VideoWriter_set(self.ptr, propId, value) end function VideoWriter:get(t) local argRules = { {"propId", required = true} } local propId = cv.argcheck(t, argRules) return C.VideoWriter_get(self.ptr, propId) end function VideoWriter:fourcc(t) local argRules = { {"c1", required = true}, {"c2", required = true}, {"c3", required = true}, {"c4", required = true} } local c1, c2, c3, c4 = cv.argcheck(t, argRules) return C.VideoWriter_fourcc(self.ptr, c1, c2, c3, c4) end end return cv
local cv = require 'cv._env' local ffi = require 'ffi' local C = ffi.load(cv.libPath('videoio')) --- ***************** Classes ***************** require 'cv.Classes' -- VideoCapture ffi.cdef[[ struct PtrWrapper VideoCapture_ctor_default(); struct PtrWrapper VideoCapture_ctor_device(int device); struct PtrWrapper VideoCapture_ctor_filename(const char *filename); void VideoCapture_dtor(struct PtrWrapper ptr); bool VideoCapture_open(struct PtrWrapper ptr, int device); bool VideoCapture_isOpened(struct PtrWrapper ptr); void VideoCapture_release(struct PtrWrapper ptr); bool VideoCapture_grab(struct PtrWrapper ptr); struct TensorPlusBool VideoCapture_retrieve( struct PtrWrapper ptr, struct TensorWrapper image, int flag); struct TensorPlusBool VideoCapture_read( struct PtrWrapper ptr, struct TensorWrapper image); bool VideoCapture_set(struct PtrWrapper ptr, int propId, double value); double VideoCapture_get(struct PtrWrapper ptr, int propId); ]] do local VideoCapture = torch.class('cv.VideoCapture', cv) -- v = cv.VideoCapture{} -- OR -- v = cv.VideoCapture{filename='../video.mp4'} -- OR -- v = cv.VideoCapture{device=2} function VideoCapture:__init(t) if type(t.filename or t[1]) == 'string' then self.ptr = ffi.gc(C.VideoCapture_ctor_filename(t.filename or t[1]), C.VideoCapture_dtor) elseif type(t.device or t[1]) == 'number' then self.ptr = ffi.gc(C.VideoCapture_ctor_device(t.device or t[1]), C.VideoCapture_dtor) else self.ptr = ffi.gc(C.VideoCapture_ctor_default(), C.VideoCapture_dtor) end end function VideoCapture:open(t) local argRules = { {"device", required = true} } local device = cv.argcheck(t, argRules) return C.VideoCapture_open(self.ptr, device) end function VideoCapture:isOpened() return C.VideoCapture_isOpened(self.ptr) end function VideoCapture:release() C.VideoCapture_release(self.ptr) end function VideoCapture:grab() return C.VideoCapture_grab(self.ptr) end function VideoCapture:retrieve(t) local argRules = { {"image", default = nil}, {"flag", default = 0} } local image, flag = cv.argcheck(t, argRules) result = C.VideoCapture_retrieve(self.ptr, cv.wrap_tensor(image), flag) return result.val, cv.unwrap_tensors(result.tensor) end -- result, image = cap.read{} -- OR -- im = torch.FloatTensor(640, 480, 3) -- result = cap.read{image=image} function VideoCapture:read(t) local argRules = { {"image", default = nil} } local image = cv.argcheck(t, argRules) result = C.VideoCapture_read(self.ptr, cv.wrap_tensor(image)) return result.val, cv.unwrap_tensors(result.tensor) end function VideoCapture:set(t) local argRules = { {"propId", required = true}, {"value", required = true} } local propId, value = cv.argcheck(t, argRules) return C.VideoCapture_set(self.ptr, propId, value) end function VideoCapture:get(t) local argRules = { {"propId", required = true} } local propId = cv.argcheck(t, argRules) return C.VideoCapture_get(self.ptr, propId) end end -- VideoWriter ffi.cdef[[ struct PtrWrapper VideoWriter_ctor_default(); struct PtrWrapper VideoWriter_ctor( const char *filename, int fourcc, double fps, struct SizeWrapper frameSize, bool isColor); void VideoWriter_dtor(struct PtrWrapper ptr); bool VideoWriter_open(struct PtrWrapper ptr, const char *filename, int fourcc, double fps, struct SizeWrapper frameSize, bool isColor); bool VideoWriter_isOpened(struct PtrWrapper ptr); void VideoWriter_release(struct PtrWrapper ptr); void VideoWriter_write(struct PtrWrapper ptr, struct TensorWrapper image); bool VideoWriter_set(struct PtrWrapper ptr, int propId, double value); double VideoWriter_get(struct PtrWrapper ptr, int propId); int VideoWriter_fourcc(char c1, char c2, char c3, char c4); ]] do local VideoWriter = torch.class('cv.VideoWriter', cv) function VideoWriter:__init(t) local argRules = { {"filename", required = true}, {"fourcc", required = true}, {"fps", required = true}, {"frameSize", required = true, operator = cv.Size}, {"isColor", default = nil} } local filename, fourcc, fps, frameSize, isColor = cv.argcheck(t, argRules) if t.filename then if isColor == nil then isColor = true end self.ptr = ffi.gc(C.VideoWriter_ctor( filename, fourcc, fps, frameSize, isColor), C.VideoWriter_dtor) else self.ptr = ffi.gc(C.VideoWriter_ctor_default(), C.VideoWriter_dtor) end end function VideoWriter:open(t) local argRules = { {"filename", required = true}, {"fourcc", required = true}, {"fps", required = true}, {"frameSize", required = true, operator = cv.Size}, {"isColor", default = nil} } local filename, fourcc, fps, frameSize, isColor = cv.argcheck(t, argRules) if isColor == nil then isColor = true end return C.VideoWriter_open(self.ptr, filename, fourcc, fps, frameSize, isColor) end function VideoWriter:isOpened() return C.VideoWriter_isOpened(self.ptr) end function VideoWriter:release() C.VideoWriter_release(self.ptr) end function VideoWriter:write(t) local argRules = { {"image", required = true} } local image = cv.argcheck(t, argRules) C.VideoWriter_write(self.ptr, cv.wrap_tensor(image)) end function VideoWriter:set(t) local argRules = { {"propId", required = true}, {"value", required = true} } local propId, value = cv.argcheck(t, argRules) return C.VideoWriter_set(self.ptr, propId, value) end function VideoWriter:get(t) local argRules = { {"propId", required = true} } local propId = cv.argcheck(t, argRules) return C.VideoWriter_get(self.ptr, propId) end function VideoWriter:fourcc(t) local argRules = { {"c1", required = true}, {"c2", required = true}, {"c3", required = true}, {"c4", required = true} } local c1, c2, c3, c4 = cv.argcheck(t, argRules) return C.VideoWriter_fourcc(string.byte(c1), string.byte(c2), string.byte(c3), string.byte(c4)) end end return cv
fixed VideoWriter:fourcc() and added wrap_tensor() to VideoWriter:write()
fixed VideoWriter:fourcc() and added wrap_tensor() to VideoWriter:write()
Lua
mit
VisionLabs/torch-opencv
ccfc8d33cbd80807a3980304b0a0151af2318909
xmake/core/sandbox/modules/import/core/project/project.lua
xmake/core/sandbox/modules/import/core/project/project.lua
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-2020, TBOOX Open Source Group. -- -- @author ruki -- @file project.lua -- -- define module local sandbox_core_project = sandbox_core_project or {} -- load modules local table = require("base/table") local deprecated = require("base/deprecated") local utils = require("base/utils") local baseoption = require("base/option") local config = require("project/config") local option = require("project/option") local project = require("project/project") local sandbox = require("sandbox/sandbox") local raise = require("sandbox/modules/raise") local environment = require("platform/environment") local package = require("package/package") local import = require("sandbox/modules/import") -- load project function sandbox_core_project.load() -- deprecated deprecated.add("project.clear() or only remove it", "project.load()") end -- clear project function sandbox_core_project.clear() project.clear() end -- check project options function sandbox_core_project.check() -- get project options local options = {} for _, opt in pairs(project.options()) do table.insert(options, opt) end -- get sandbox instance local instance = sandbox.instance() assert(instance) -- enter the project directory local oldir, errors = os.cd(os.projectdir()) if not oldir then raise(errors) end -- enter toolchains environment environment.enter("toolchains") -- init check task local checked = {} local checktask = function (index) -- get option local opt = options[index] if opt then -- check deps of this option first for depname, dep in pairs(opt:deps()) do if not checked[depname] then dep:check() checked[depname] = true end end -- check this option if not checked[opt:name()] then opt:check() checked[opt:name()] = true end end end -- check all options local runjobs = import("private.async.runjobs", {anonymous = true}) local ok, errors = true--utils.trycall(runjobs, "check_options", instance:fork(checktask):script(), #options, 4) if not ok then raise(errors) end -- leave toolchains environment environment.leave("toolchains") -- save all options to the cache file option.save() -- leave the project directory ok, errors = os.cd(oldir) if not ok then raise(errors) end end -- get the given project rule function sandbox_core_project.rule(name) return project.rule(name) end -- get the all project rules function sandbox_core_project.rules() return project.rules() end -- get the given target function sandbox_core_project.target(name) return project.target(name) end -- get the all targets function sandbox_core_project.targets() return project.targets() end -- get the given option function sandbox_core_project.option(name) return project.option(name) end -- get the all options function sandbox_core_project.options() return project.options() end -- get the project file function sandbox_core_project.file() return project.file() end -- get the project rcfile function sandbox_core_project.rcfile() return project.rcfile() end -- get the project directory function sandbox_core_project.directory() return project.directory() end -- get the filelock of the whole project directory function sandbox_core_project.filelock() local filelock = project.filelock() if not filelock then raise("cannot create the project lock!") end return filelock end -- lock the whole project function sandbox_core_project.lock(opt) if sandbox_core_project.trylock(opt) then return true elseif baseoption.get("diagnosis") then utils.warning("the current project is being accessed by other processes, please waiting!") end local ok, errors = sandbox_core_project.filelock():lock(opt) if not ok then raise(errors) end end -- trylock the whole project function sandbox_core_project.trylock(opt) return sandbox_core_project.filelock():trylock(opt) end -- unlock the whole project function sandbox_core_project.unlock() local ok, errors = sandbox_core_project.filelock():unlock() if not ok then raise(errors) end end -- get the project mtimes function sandbox_core_project.mtimes() return project.mtimes() end -- get the project info from the given name function sandbox_core_project.get(name) return project.get(name) end -- get the project name function sandbox_core_project.name() return project.get("project") end -- get the project version, the root version of the target scope function sandbox_core_project.version() return project.get("target.version") end -- get the project modes function sandbox_core_project.modes() local modes = project.get("modes") or {} for _, target in pairs(table.wrap(project.targets())) do for _, rule in ipairs(target:orderules()) do local name = rule:name() if name:startswith("mode.") then table.insert(modes, name:sub(6)) end end end return table.unique(modes) end -- get the the given require info function sandbox_core_project.require(name) return project.require(name) end -- get the all requires function sandbox_core_project.requires() return project.requires() end -- get the all raw string requires function sandbox_core_project.requires_str() return project.requires_str() end -- return module return sandbox_core_project
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-2020, TBOOX Open Source Group. -- -- @author ruki -- @file project.lua -- -- define module local sandbox_core_project = sandbox_core_project or {} -- load modules local table = require("base/table") local deprecated = require("base/deprecated") local utils = require("base/utils") local baseoption = require("base/option") local config = require("project/config") local option = require("project/option") local project = require("project/project") local sandbox = require("sandbox/sandbox") local raise = require("sandbox/modules/raise") local environment = require("platform/environment") local package = require("package/package") local import = require("sandbox/modules/import") -- load project function sandbox_core_project.load() -- deprecated deprecated.add("project.clear() or only remove it", "project.load()") end -- clear project function sandbox_core_project.clear() project.clear() end -- check project options function sandbox_core_project.check() -- get project options local options = {} for _, opt in pairs(project.options()) do table.insert(options, opt) end -- get sandbox instance local instance = sandbox.instance() assert(instance) -- enter the project directory local oldir, errors = os.cd(os.projectdir()) if not oldir then raise(errors) end -- enter toolchains environment environment.enter("toolchains") -- init check task local checked = {} local checktask = function (index) -- get option local opt = options[index] if opt then -- check deps of this option first for depname, dep in pairs(opt:deps()) do if not checked[depname] then dep:check() checked[depname] = true end end -- check this option if not checked[opt:name()] then opt:check() checked[opt:name()] = true end end end -- check all options import("private.async.runjobs", {anonymous = true})("check_options", instance:fork(checktask):script(), #options, 4) -- leave toolchains environment environment.leave("toolchains") -- save all options to the cache file option.save() -- leave the project directory local ok, errors = os.cd(oldir) if not ok then raise(errors) end end -- get the given project rule function sandbox_core_project.rule(name) return project.rule(name) end -- get the all project rules function sandbox_core_project.rules() return project.rules() end -- get the given target function sandbox_core_project.target(name) return project.target(name) end -- get the all targets function sandbox_core_project.targets() return project.targets() end -- get the given option function sandbox_core_project.option(name) return project.option(name) end -- get the all options function sandbox_core_project.options() return project.options() end -- get the project file function sandbox_core_project.file() return project.file() end -- get the project rcfile function sandbox_core_project.rcfile() return project.rcfile() end -- get the project directory function sandbox_core_project.directory() return project.directory() end -- get the filelock of the whole project directory function sandbox_core_project.filelock() local filelock = project.filelock() if not filelock then raise("cannot create the project lock!") end return filelock end -- lock the whole project function sandbox_core_project.lock(opt) if sandbox_core_project.trylock(opt) then return true elseif baseoption.get("diagnosis") then utils.warning("the current project is being accessed by other processes, please waiting!") end local ok, errors = sandbox_core_project.filelock():lock(opt) if not ok then raise(errors) end end -- trylock the whole project function sandbox_core_project.trylock(opt) return sandbox_core_project.filelock():trylock(opt) end -- unlock the whole project function sandbox_core_project.unlock() local ok, errors = sandbox_core_project.filelock():unlock() if not ok then raise(errors) end end -- get the project mtimes function sandbox_core_project.mtimes() return project.mtimes() end -- get the project info from the given name function sandbox_core_project.get(name) return project.get(name) end -- get the project name function sandbox_core_project.name() return project.get("project") end -- get the project version, the root version of the target scope function sandbox_core_project.version() return project.get("target.version") end -- get the project modes function sandbox_core_project.modes() local modes = project.get("modes") or {} for _, target in pairs(table.wrap(project.targets())) do for _, rule in ipairs(target:orderules()) do local name = rule:name() if name:startswith("mode.") then table.insert(modes, name:sub(6)) end end end return table.unique(modes) end -- get the the given require info function sandbox_core_project.require(name) return project.require(name) end -- get the all requires function sandbox_core_project.requires() return project.requires() end -- get the all raw string requires function sandbox_core_project.requires_str() return project.requires_str() end -- return module return sandbox_core_project
fix check options
fix check options
Lua
apache-2.0
waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake
33fa5e21e7b24a60a7d1871bcaecb336de674a43
plugins/mod_time.lua
plugins/mod_time.lua
-- Prosody IM -- Copyright (C) 2008-2009 Matthew Wild -- Copyright (C) 2008-2009 Waqas Hussain -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local st = require "util.stanza"; local datetime = require "util.datetime".datetime; local legacy = require "util.datetime".legacy; -- XEP-0202: Entity Time module:add_feature("urn:xmpp:time"); module:add_iq_handler({"c2s", "s2sin"}, "urn:xmpp:time", function(session, stanza) if stanza.attr.type == "get" then session.send(st.reply(stanza):tag("time", {xmlns="urn:xmpp:time"}) :tag("tzo"):text("+00:00"):up() -- FIXME get the timezone in a platform independent fashion :tag("utc"):text(datetime())); end end); -- XEP-0090: Entity Time (deprecated) module:add_feature("jabber:iq:time"); module:add_iq_handler({"c2s", "s2sin"}, "jabber:iq:time", function(session, stanza) if stanza.attr.type == "get" then session.send(st.reply(stanza):tag("query", {xmlns="jabber:iq:time"}) :tag("utc"):text(legacy())); end end);
-- Prosody IM -- Copyright (C) 2008-2009 Matthew Wild -- Copyright (C) 2008-2009 Waqas Hussain -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local st = require "util.stanza"; local datetime = require "util.datetime".datetime; local legacy = require "util.datetime".legacy; -- XEP-0202: Entity Time module:add_feature("urn:xmpp:time"); local function time_handler(event) local origin, stanza = event.origin, event.stanza; if stanza.attr.type == "get" then origin.send(st.reply(stanza):tag("time", {xmlns="urn:xmpp:time"}) :tag("tzo"):text("+00:00"):up() -- TODO get the timezone in a platform independent fashion :tag("utc"):text(datetime())); return true; end end module:hook("iq/bare/urn:xmpp:time:time", time_handler); module:hook("iq/host/urn:xmpp:time:time", time_handler); -- XEP-0090: Entity Time (deprecated) module:add_feature("jabber:iq:time"); local function legacy_time_handler(event) local origin, stanza = event.origin, event.stanza; if stanza.attr.type == "get" then origin.send(st.reply(stanza):tag("query", {xmlns="jabber:iq:time"}) :tag("utc"):text(legacy())); return true; end end module:hook("iq/bare/jabber:iq:time:query", legacy_time_handler); module:hook("iq/host/jabber:iq:time:query", legacy_time_handler);
mod_time: Updated to use events (which also fixes a few minor issues).
mod_time: Updated to use events (which also fixes a few minor issues).
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
dde3ae9155ef1fdb7bedd33af68df7509da71e6a
Config.lua
Config.lua
local mod = EPGP:NewModule("EPGP_Config", "AceDB-2.0", "AceEvent-2.0") mod:RegisterDB("EPGP_Config_DB") mod:RegisterDefaults("profile", { data = { }, detached_data = { }, }) local T = AceLibrary("Tablet-2.0") local D = AceLibrary("Dewdrop-2.0") local C = AceLibrary("Crayon-2.0") local BC = AceLibrary("Babble-Class-2.2") function mod:OnInitialize() self.cache = EPGP:GetModule("EPGP_Cache") end function mod:OnEnable() self:RegisterEvent("EPGP_CACHE_UPDATE") if not T:IsRegistered("EPGP_Config") then T:Register("EPGP_Config", "children", function() T:SetTitle("EPGP Config") self:OnTooltipUpdate() end, "data", self.db.profile.data, "detachedData", self.db.profile.detached_data, "showTitleWhenDetached", true, "showHintWhenDetached", true, "cantAttach", true ) end if not T:IsAttached("EPGP_Config") then T:Open("EPGP_Config") end end function mod:OnDisable() T:Close("EPGP_Config") end function mod:EPGP_CACHE_UPDATE() self.alts = self:BuildAltsTable() self.outsiders = self:BuildOutsidersTable() T:Refresh("EPGP_Config") end function mod:BuildAltsTable() local t = {} for alt,main in pairs(self.cache.db.profile.alts) do if not t[main] then t[main] = {} end table.insert(t[main], alt) end return t end function mod:BuildOutsidersTable() local t = {} for outsider,dummy in pairs(self.cache.db.profile.outsiders) do t[outsider] = dummy end return t end function mod:Toggle() if T:IsAttached("EPGP_Config") then T:Detach("EPGP_Config") if (T:IsLocked("EPGP_Config")) then T:ToggleLocked("EPGP_Config") end else T:Attach("EPGP_Config") end end function mod:OnTooltipUpdate() if not self.alts then self.alts = self:BuildAltsTable() end if not self.outsiders then self.outsiders = self:BuildOutsidersTable() end local cat = T:AddCategory( "columns", 2, "text", C:Red("Main"), "child_textR", 1, "child_textG", 1, "child_textB", 1, "child_justify", "LEFT", "text2", C:Red("Alts"), "child_text2R", 1, "child_text2G", 1, "child_text2B", 1, "child_justify4", "RIGHT" ) for main,alts in pairs(self.alts) do local alts_str for _,alt in pairs(alts) do local rank, rankIndex, level, class, zone, note, officernote, online, status = self.cache:GetMemberInfo(alt) if alts_str then alts_str = alts_str.." "..C:Colorize(BC:GetHexColor(class), alt) else alts_str = C:Colorize(BC:GetHexColor(class), alt) end end local rank, rankIndex, level, class, zone, note, officernote, online, status = self.cache:GetMemberInfo(main) cat:AddLine( "text", C:Colorize(BC:GetHexColor(class), main), "text2", alts_str ) end local cat2 = T:AddCategory( "columns", 2, "text", C:Red("Outsider"), "child_textR", 1, "child_textG", 1, "child_textB", 1, "child_justify", "LEFT", "text2", C:Red("Dummy"), "child_text2R", 1, "child_text2G", 1, "child_text2B", 1, "child_justify4", "RIGHT" ) for outsider,dummy in pairs(self.outsiders) do local rank, rankIndex, level, class, zone, note, officernote, online, status = self.cache:GetMemberInfo(dummy) local color = C.COLOR_HEX_SILVER if class then color = BC:GetHexColor(class) end cat2:AddLine( "text", C:Colorize(color, outsider), "text2", C:Colorize(color, dummy) ) end local info = T:AddCategory("columns", 2) info:AddLine("text", C:Red("Min EPs"), "text2", C:Silver(self.cache.db.profile.min_eps)) info:AddLine("text", C:Red("Decay"), "text2", C:Silver(self.cache.db.profile.decay_percent.."%")) end
local mod = EPGP:NewModule("EPGP_Config", "AceDB-2.0", "AceEvent-2.0") mod:RegisterDB("EPGP_Config_DB") mod:RegisterDefaults("profile", { data = { }, detached_data = { }, }) local T = AceLibrary("Tablet-2.0") local D = AceLibrary("Dewdrop-2.0") local C = AceLibrary("Crayon-2.0") local BC = AceLibrary("Babble-Class-2.2") function mod:OnInitialize() self.cache = EPGP:GetModule("EPGP_Cache") end function mod:OnEnable() self:RegisterEvent("EPGP_CACHE_UPDATE") if not T:IsRegistered("EPGP_Config") then T:Register("EPGP_Config", "children", function() T:SetTitle("EPGP Config") self:OnTooltipUpdate() end, "data", self.db.profile.data, "detachedData", self.db.profile.detached_data, "showTitleWhenDetached", true, "showHintWhenDetached", true, "cantAttach", true ) end if not T:IsAttached("EPGP_Config") then T:Open("EPGP_Config") end end function mod:OnDisable() T:Close("EPGP_Config") end function mod:EPGP_CACHE_UPDATE() self.alts = self:BuildAltsTable() self.outsiders = self:BuildOutsidersTable() T:Refresh("EPGP_Config") end function mod:BuildAltsTable() local t = {} for alt,main in pairs(self.cache.db.profile.alts) do if not t[main] then t[main] = {} end table.insert(t[main], alt) end return t end function mod:BuildOutsidersTable() local t = {} for outsider,dummy in pairs(self.cache.db.profile.outsiders) do t[outsider] = dummy end return t end function mod:Toggle() if T:IsAttached("EPGP_Config") then T:Detach("EPGP_Config") if (T:IsLocked("EPGP_Config")) then T:ToggleLocked("EPGP_Config") end else T:Attach("EPGP_Config") end end function mod:OnTooltipUpdate() if not self.alts then self.alts = self:BuildAltsTable() end if not self.outsiders then self.outsiders = self:BuildOutsidersTable() end local cat = T:AddCategory( "columns", 2, "text", C:Red("Main"), "child_textR", 1, "child_textG", 1, "child_textB", 1, "child_justify", "LEFT", "text2", C:Red("Alts"), "child_text2R", 1, "child_text2G", 1, "child_text2B", 1, "child_justify4", "RIGHT" ) for main,alts in pairs(self.alts) do local alts_str for _,alt in pairs(alts) do local rank, rankIndex, level, class, zone, note, officernote, online, status = self.cache:GetMemberInfo(alt) if alts_str then alts_str = alts_str.." "..C:Colorize(BC:GetHexColor(class), alt) else alts_str = C:Colorize(BC:GetHexColor(class), alt) end end local rank, rankIndex, level, class, zone, note, officernote, online, status = self.cache:GetMemberInfo(main) if main and class then cat:AddLine( "text", C:Colorize(BC:GetHexColor(class), main), "text2", alts_str ) end end local cat2 = T:AddCategory( "columns", 2, "text", C:Red("Outsider"), "child_textR", 1, "child_textG", 1, "child_textB", 1, "child_justify", "LEFT", "text2", C:Red("Dummy"), "child_text2R", 1, "child_text2G", 1, "child_text2B", 1, "child_justify4", "RIGHT" ) for outsider,dummy in pairs(self.outsiders) do local rank, rankIndex, level, class, zone, note, officernote, online, status = self.cache:GetMemberInfo(dummy) local color = C.COLOR_HEX_SILVER if class then color = BC:GetHexColor(class) end cat2:AddLine( "text", C:Colorize(color, outsider), "text2", C:Colorize(color, dummy) ) end local info = T:AddCategory("columns", 2) info:AddLine("text", C:Red("Min EPs"), "text2", C:Silver(self.cache.db.profile.min_eps)) info:AddLine("text", C:Red("Decay"), "text2", C:Silver(self.cache.db.profile.decay_percent.."%")) end
Fix for issue 75. Invalid alts will now longer cause an error.
Fix for issue 75. Invalid alts will now longer cause an error.
Lua
bsd-3-clause
hayword/tfatf_epgp,protomech/epgp-dkp-reloaded,sheldon/epgp,sheldon/epgp,ceason/epgp-tfatf,hayword/tfatf_epgp,ceason/epgp-tfatf,protomech/epgp-dkp-reloaded
8c1189fb834e5335ccc6509f04e583bc9cf0323b
test_scripts/Polices/build_options/ATF_PolicyManager_changes_status_to_UPDATING_PROPRIETARY.lua
test_scripts/Polices/build_options/ATF_PolicyManager_changes_status_to_UPDATING_PROPRIETARY.lua
--------------------------------------------------------------------------------------------- -- Requirement summary: -- [PolicyTableUpdate] PoliciesManager changes status to "UPDATING" -- [HMI API] OnStatusUpdate -- -- Description: -- SDL is built with "-DEXTENDED_POLICY: PROPRIETARY" flag -- PoliciesManager must change the status to "UPDATING" and notify HMI with OnStatusUpdate("UPDATING") -- right after SnapshotPT is sent out to to mobile app via OnSystemRequest() RPC. -- -- Steps: -- 1. Register new app -- 2. Trigger PTU -- 3. SDL->HMI: Verify step of SDL.OnStatusUpdate(UPDATING) notification in PTU sequence -- -- Expected result: -- SDL.OnStatusUpdate(UPDATING) notification is send right after SDL->MOB: OnSystemRequest --------------------------------------------------------------------------------------------- --[[ General configuration parameters ]] config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0" --[[ Required Shared libraries ]] local commonFunctions = require("user_modules/shared_testcases/commonFunctions") local commonSteps = require("user_modules/shared_testcases/commonSteps") local testCasesForPolicyTable = require("user_modules/shared_testcases/testCasesForPolicyTable") --[[ Local Variables ]] local r_actual = { } --[[ Local Functions ]] local function get_id_by_val(t, v) for i = 1, #t do if (t[i] == v) then return i end end return nil end --[[ General Precondition before ATF start ]] commonFunctions:SDLForceStop() commonSteps:DeleteLogsFileAndPolicyTable() testCasesForPolicyTable.Delete_Policy_table_snapshot() --[[ General Settings for configuration ]] Test = require("connecttest") require("user_modules/AppTypes") -- [[ Notifications ]] EXPECT_HMICALL("BasicCommunication.PolicyUpdate") :Do(function() table.insert(r_actual, "BC.PolicyUpdate") end) :Times(AnyNumber()) :Pin() EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate",{ status = "UPDATING" }) :Do(function(_, d) table.insert(r_actual, "SDL.OnStatusUpdate: " .. d.params.status) end) :Times(AnyNumber()) :Pin() --[[ Test ]] commonFunctions:newTestCasesGroup("Test") function Test:TestStep_CheckMessagesSequence() local RequestId_GetUrls = self.hmiConnection:SendRequest("SDL.GetURLS", { service = 7 }) table.insert(r_actual, "SDL.GetURLS: request") EXPECT_HMIRESPONSE(RequestId_GetUrls) :Do(function() table.insert(r_actual, "SDL.GetURLS: response") EXPECT_NOTIFICATION("OnSystemRequest", { requestType = "PROPRIETARY" }) :Do(function() table.insert(r_actual, "OnSystemRequest") end) self.hmiConnection:SendNotification("BasicCommunication.OnSystemRequest", { requestType = "PROPRIETARY", fileName = "PolicyTableUpdate"}) table.insert(r_actual, "BC.OnSystemRequest") end) end function Test:ValidateResult() commonFunctions:printTable(r_actual) local onSystemRequestId = get_id_by_val(r_actual, "OnSystemRequest") local onStatusUpdate = get_id_by_val(r_actual, "SDL.OnStatusUpdate: UPDATING") print("Id of 'OnSystemRequest': " .. onSystemRequestId) print("Id of 'SDL.OnStatusUpdate: UPDATING': " .. onStatusUpdate) if onStatusUpdate < onSystemRequestId then self:FailTestCase("Unexpected 'SDL.OnStatusUpdate: UPDATING' before 'OnSystemRequest'") end end --[[ Postconditions ]] commonFunctions:newTestCasesGroup("Postconditions") function Test.Postcondition_StopSDL() StopSDL() end return Test
--------------------------------------------------------------------------------------------- -- Requirement summary: -- [PolicyTableUpdate] PoliciesManager changes status to "UPDATING" -- [HMI API] OnStatusUpdate -- -- Description: -- SDL is built with "-DEXTENDED_POLICY: PROPRIETARY" flag -- PoliciesManager must change the status to "UPDATING" and notify HMI with OnStatusUpdate("UPDATING") -- right after SnapshotPT is sent out to to mobile app via OnSystemRequest() RPC. -- -- Steps: -- 1. Register new app -- 2. Trigger PTU -- 3. SDL->HMI: Verify step of SDL.OnStatusUpdate(UPDATING) notification in PTU sequence -- -- Expected result: -- SDL.OnStatusUpdate(UPDATING) notification is send right after SDL->MOB: OnSystemRequest --------------------------------------------------------------------------------------------- --[[ General configuration parameters ]] config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0" --[[ Required Shared libraries ]] local mobile_session = require("mobile_session") local commonFunctions = require("user_modules/shared_testcases/commonFunctions") local commonSteps = require("user_modules/shared_testcases/commonSteps") --[[ Local Variables ]] local r_actual = { } local r_expected = { "SDL.OnStatusUpdate(UPDATE_NEEDED)", "BC.PolicyUpdate", "SDL.OnStatusUpdate(UPDATING)"} --[[ Local Functions ]] local function is_table_equal(t1, t2) local ty1 = type(t1) local ty2 = type(t2) if ty1 ~= ty2 then return false end if ty1 ~= 'table' and ty2 ~= 'table' then return t1 == t2 end for k1, v1 in pairs(t1) do local v2 = t2[k1] if v2 == nil or not is_table_equal(v1, v2) then return false end end for k2, v2 in pairs(t2) do local v1 = t1[k2] if v1 == nil or not is_table_equal(v1, v2) then return false end end return true end --[[ General Precondition before ATF start ]] commonFunctions:SDLForceStop() commonSteps:DeleteLogsFileAndPolicyTable() --[[ General Settings for configuration ]] Test = require("user_modules/connecttest_resumption") require("user_modules/AppTypes") --[[ Preconditions ]] commonFunctions:newTestCasesGroup("Preconditions") function Test:ConnectMobile() self:connectMobile() end function Test:StartSession() self.mobileSession1 = mobile_session.MobileSession(self, self.mobileConnection) self.mobileSession1:StartService(7) end --[[ Test ]] commonFunctions:newTestCasesGroup("Test") function Test:RAI() self.mobileSession1:SendRPC("RegisterAppInterface", config.application1.registerAppInterfaceParams) EXPECT_HMINOTIFICATION("BasicCommunication.OnAppRegistered", { application = { appName = config.application1.registerAppInterfaceParams.appName } }) :Do( function(_, d1) self.applications[config.application1.registerAppInterfaceParams.appID] = d1.params.application.appID EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate", { status = "UPDATE_NEEDED" }, { status = "UPDATING" }) :Do( function(_, d2) table.insert(r_actual, "SDL.OnStatusUpdate(" .. d2.params.status .. ")") end) :Times(2) EXPECT_HMICALL("BasicCommunication.PolicyUpdate") :Do( function() table.insert(r_actual, "BC.PolicyUpdate") end) end) end function Test:ValidateResult() if not is_table_equal(r_expected, r_actual) then local msg = table.concat({"\nExpected sequence:\n", commonFunctions:convertTableToString(r_expected, 1), "\nActual:\n", commonFunctions:convertTableToString(r_actual, 1)}) self:FailTestCase(msg) end end --[[ Postconditions ]] commonFunctions:newTestCasesGroup("Postconditions") function Test.Postcondition_StopSDL() StopSDL() end return Test
Fix after clarifications
Fix after clarifications
Lua
bsd-3-clause
smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts
72ba8a05929a692d3aeced0c7dc1379b56e723e4
action.lua
action.lua
function on_msg_receive (msg) msg.text = string.lower(msg.text) if msg.out then return end if (msg.text=='ping') then send_msg (msg.from.print_name, 'pong', ok_cb, false) elseif (msg.text=='sitealert mostra') then cmd = 'python3 /home/pi/SiteAlert-python/SiteAlert.py -se', temp send_msg(msg.from.print_name, os.capture(cmd), ok_cb, false) elseif (string.match(msg.text,'sitealert controlla')) then param = explode(msg.text) cmd = 'python3 /home/pi/SiteAlert-python/SiteAlert.py -ae '.. param[4] .. ' ' .. param[2].. ' ' .. param[6] .. ' ' .. msg.from.print_name send_msg(msg.from.print_name, os.capture(cmd), ok_cb, false) elseif (string.match(msg.text,'sitealert aggiungimi'))then param = explode(msg.text) cmd = 'python3 /home/pi/SiteAlert-python/SiteAlert.py -ame ' .. param[2] .. ' ' .. param[4] .. ' ' .. msg.from.print_name send_msg(msg.from.print_name, os.capture(cmd), ok_cb, false) elseif (string.match(msg.text,'sitealert rimuovimi'))then param = explode(msg.text) cmd = 'python3 /home/pi/SiteAlert-python/SiteAlert.py -re '.. param[2] .. ' ' .. param[3] .. ' ' .. msg.from.print_name send_msg(msg.from.print_name, os.capture(cmd), ok_cb, false) else cmd = 'Ciao '.. msg.from.print_name .. '!\nBenvenuto nel bot di @SiteAlert.\nComandi disponibili:\nsitealert controlla _link_ chiamandolo _nome_ avvisandomi _mail_\nsitealert aggiungimi _nome_ avvisandomi _mail_\nsitealert mostra\nsitealert rimuovimi _nome_ _mail_\nTest: ping' send_msg(msg.from.print_name, cmd, ok_cb, false) end end function on_our_id (id) end function on_secret_chat_created (peer) end function on_user_update (user) end function on_chat_update (user) end function on_get_difference_end () end function on_binlog_replay_end () end function os.capture(cmd) local handle = assert(io.popen(cmd, 'r')) local output = assert(handle:read('*a')) handle:close() --[[output = string.gsub( string.gsub( string.gsub(output, '^%s+', ''), '%s+$', '' ), '[\n\r]+', ' ' )]]-- return string.sub(output, 7) end function explode(str) local k = 0 array = {} for i in string.gmatch(str, "%S+") do array[k] = i k = k+1 end return array end
function on_msg_receive (msg) msg.text = msg.text:gsub("^%l", string.lower) if msg.out then return end if (msg.text=='ping') then send_msg (msg.from.print_name, 'pong', ok_cb, false) elseif (msg.text=='mostra') then cmd = 'python3 /home/pi/SiteAlert-python/SiteAlert.py -se', temp send_msg(msg.from.print_name, os.capture(cmd), ok_cb, false) elseif (string.match(msg.text,'controlla')) then param = explode(msg.text) cmd = 'python3 /home/pi/SiteAlert-python/SiteAlert.py -ae '.. param[3] .. ' ' .. param[1].. ' ' .. param[5] .. ' ' .. msg.from.print_name send_msg(msg.from.print_name, os.capture(cmd), ok_cb, false) elseif (string.match(msg.text,'aggiungimi'))then param = explode(msg.text) cmd = 'python3 /home/pi/SiteAlert-python/SiteAlert.py -ame ' .. param[1] .. ' ' .. param[3] .. ' ' .. msg.from.print_name send_msg(msg.from.print_name, os.capture(cmd), ok_cb, false) elseif (string.match(msg.text,'rimuovimi'))then param = explode(msg.text) cmd = 'python3 /home/pi/SiteAlert-python/SiteAlert.py -re '.. param[1] .. ' ' .. param[2] .. ' ' .. msg.from.print_name send_msg(msg.from.print_name, os.capture(cmd), ok_cb, false) else cmd = 'Ciao '.. msg.from.print_name .. '!\nBenvenuto nel bot di @SiteAlert.\nComandi disponibili:\ncontrolla _link_ chiamandolo _nome_ avvisandomi _mail_\naggiungimi _nome_ avvisandomi _mail_\nmostra\nrimuovimi _nome_ _mail_\nTest: ping' send_msg(msg.from.print_name, cmd, ok_cb, false) end end function on_our_id (id) end function on_secret_chat_created (peer) end function on_user_update (user) end function on_chat_update (user) end function on_get_difference_end () end function on_binlog_replay_end () end function os.capture(cmd) local handle = assert(io.popen(cmd, 'r')) local output = assert(handle:read('*a')) handle:close() --[[output = string.gsub( string.gsub( string.gsub(output, '^%s+', ''), '%s+$', '' ), '[\n\r]+', ' ' )]]-- return string.sub(output, 7) end function explode(str) local k = 0 array = {} for i in string.gmatch(str, "%S+") do array[k] = i k = k+1 end return array end
Fixed lua script
Fixed lua script
Lua
bsd-2-clause
ilteoood/SiteAlert-Python
27994745f79845a32f4f6ba7882210239d7874c2
assets/scripts/bots/workbot/WorkBot.lua
assets/scripts/bots/workbot/WorkBot.lua
-- WorkBot class 'WorkBot' (Bot) local round = require 'round' function WorkBot:__init(gameGrid, homeCoord) Bot.__init(self) LuaDebug.Log('WorkBot:__init() called!') self._gameGrid = gameGrid self._homeCoord = homeCoord self._state = Bot.WaitingForJob self._job = nil self._coord = homeCoord self._depth = 30 self._elipsis = 1 end function WorkBot:setup() local renderer = self.gameObject.renderer renderer.transform.localPosition = self:coordToPos(self._homeCoord) end function WorkBot:getCoord() local renderer = self.gameObject.renderer return self:posToCoord(renderer.transform.localPosition) end function WorkBot:getDestination() if self._state == Bot.WaitingForJob then return self._homeCoord; end if self._state == Bot.MovingToJob then if not self._job then error('ASSERT FAIL: In mining state without a job.') end return self._job:getStartLocation() end if self._state == Bot.Working then return self:getCoord() end error('ASSERT FAIL: Workbot: Invalid State.') end function WorkBot:getSpeed() return 1.0 end function WorkBot:canAcceptJobs(job) return self._state == Bot.WaitingForJob end function WorkBot:willAcceptJob(job) return class_info(job).name == 'MiningJob' end function WorkBot:acceptJob(job) LuaDebug.Log('Accepting job. State == WorkBot.States.MOVING_TO_JOB') self._job = job self._state = Bot.MovingToJob self._targetPoint = nil self._path = nil end function WorkBot:getCurrentJob() return self._job; end function WorkBot:update(deltaTime) if self._job then local t = self.gameObject.renderer.transform -- MOVING if self._state == Bot.MovingToJob or self._state == Bot.WaitingForJob then if not self._path then local coords = GetBotManager():getPath(self:getCoord(), self:getDestination(), self._job:getRadius()) self._path = {} for coord in coords do table.insert(self._path, self:coordToPos(coord)) end end if not self._targetPoint or t.localPosition:distance(self._targetPoint) < self._elipsis then self._targetPoint = table.remove(self._path, 1) end if self._targetPoint == nil then if self._state == Bot.MovingToJob then self._path = nil self._state = Bot.Working self._job:allocateWorker() -- Move to job slot relative to forward local jobSlotIndex = self._job:getWorkerCount() - 1 local jobSlotPos = self._job:getWorkerSlot(jobSlotIndex) local texDef = self._gameGrid.defaultTileset local frameWidth = texDef:getFrameWidth() local frameHeight = texDef:getFrameHeight() local dir = self:coordToPos(self._job:getStartLocation()) - t.localPosition dir:normalize() local angle = math.atan2(-dir.x, dir.y) jobSlotPos:rotate(angle) self._targetPoint = t.localPosition + Vec3f( frameWidth * (jobSlotPos.x / 2), frameHeight * (jobSlotPos.y / 2), self._depth ) end end end if self._state == Bot.Working then if self._job:isDone() then self._state = Bot.WaitingForJob end if t.localPosition:distance(self._targetPoint) < self._elipsis then self._targetPoint = nil end end if self._targetPoint ~= nil then local direction = self._targetPoint - t.localPosition direction:normalize() --cout << "targetCoord: " << targetCoord -- << " currentCoord: " << bot->getCoord() -- << " direction: " << direction << endl; local v = direction * self:getSpeed() t.localPosition = t.localPosition + Vec3f(v.x, v.y, 0); end end end function WorkBot:coordToPos(coord) local texDef = self._gameGrid.defaultTileset local frameWidth = texDef:getFrameWidth() local frameHeight = texDef:getFrameHeight() return Vec3f( (coord.x * frameWidth), (coord.y * frameHeight), self._depth ) end function WorkBot:posToCoord(pos) local texDef = self._gameGrid.defaultTileset local frameWidth = texDef:getFrameWidth() local frameHeight = texDef:getFrameHeight() return Vec2i( round(pos.x / frameWidth), round(pos.y / frameHeight) ) end function WorkBot:getState() return self._state; end
-- WorkBot class 'WorkBot' (Bot) local round = require 'round' function WorkBot:__init(gameGrid, homeCoord) Bot.__init(self) LuaDebug.Log('WorkBot:__init() called!') self._gameGrid = gameGrid self._homeCoord = homeCoord self._state = Bot.WaitingForJob self._job = nil self._coord = homeCoord self._depth = 30 self._elipsis = 1 end function WorkBot:setup() local renderer = self.gameObject.renderer renderer.transform.localPosition = self:coordToPos(self._homeCoord) end function WorkBot:getCoord() local renderer = self.gameObject.renderer return self:posToCoord(renderer.transform.localPosition) end function WorkBot:getDestination() if self._state == Bot.WaitingForJob then return self._homeCoord; end if self._state == Bot.MovingToJob then if not self._job then error('ASSERT FAIL: In mining state without a job.') end return self._job:getStartLocation() end if self._state == Bot.Working then return self:getCoord() end error('ASSERT FAIL: Workbot: Invalid State.') end function WorkBot:getSpeed() return 1.0 end function WorkBot:canAcceptJobs(job) return self._state == Bot.WaitingForJob end function WorkBot:willAcceptJob(job) return class_info(job).name == 'MiningJob' end function WorkBot:acceptJob(job) LuaDebug.Log('Accepting job. State == WorkBot.States.MOVING_TO_JOB') self._job = job self._state = Bot.MovingToJob self._targetPoint = nil self._path = nil end function WorkBot:getCurrentJob() return self._job; end function WorkBot:update(deltaTime) local t = self.gameObject.renderer.transform -- MOVING if self._state == Bot.MovingToJob or self._state == Bot.WaitingForJob then if not self._path then LuaDebug.Log('WorkBot: Finding path to ' .. tostring(self:getDestination())) local radius = 0 if self._job then radius = self._job:getRadius() end local coords = GetBotManager():getPath(self:getCoord(), self:getDestination(), radius) self._path = {} for coord in coords do table.insert(self._path, self:coordToPos(coord)) end self._targetPoint = nil end if not self._targetPoint or t.localPosition:distance(self._targetPoint) < self._elipsis then self._targetPoint = table.remove(self._path, 1) end if self._targetPoint == nil and self._state == Bot.MovingToJob then LuaDebug.Log('WorkBot: Target point reached. Switching to Working.') self._path = nil self._state = Bot.Working self._job:allocateWorker() -- Move to job slot relative to forward local jobSlotIndex = self._job:getWorkerCount() - 1 local jobSlotPos = self._job:getWorkerSlot(jobSlotIndex) local texDef = self._gameGrid.defaultTileset local frameWidth = texDef:getFrameWidth() local frameHeight = texDef:getFrameHeight() local dir = self:coordToPos(self._job:getStartLocation()) - t.localPosition dir:normalize() local angle = math.atan2(-dir.x, dir.y) jobSlotPos:rotate(angle) self._targetPoint = t.localPosition + Vec3f( frameWidth * (jobSlotPos.x / 2), frameHeight * (jobSlotPos.y / 2), self._depth ) end end if self._state == Bot.Working then if self._job:isDone() then LuaDebug.Log('WorkBot: Job is finished. Switching to WaitingForJob.') self._state = Bot.WaitingForJob self._job = nil end if t.localPosition:distance(self._targetPoint) < self._elipsis then self._targetPoint = nil end end if self._targetPoint ~= nil then local direction = self._targetPoint - t.localPosition direction:normalize() local v = direction * self:getSpeed() t.localPosition = t.localPosition + Vec3f(v.x, v.y, 0); local angle = math.atan2(direction.x, -direction.y) t.localRotation = Quatf(0,0,angle) end end function WorkBot:coordToPos(coord) local texDef = self._gameGrid.defaultTileset local frameWidth = texDef:getFrameWidth() local frameHeight = texDef:getFrameHeight() return Vec3f( (coord.x * frameWidth), (coord.y * frameHeight), self._depth ) end function WorkBot:posToCoord(pos) local texDef = self._gameGrid.defaultTileset local frameWidth = texDef:getFrameWidth() local frameHeight = texDef:getFrameHeight() return Vec2i( round(pos.x / frameWidth), round(pos.y / frameHeight) ) end function WorkBot:getState() return self._state; end
Fixed regression where bots would not return home when all jobs were finished.
Fixed regression where bots would not return home when all jobs were finished.
Lua
mit
NoxHarmonium/spacestationkeeper,NoxHarmonium/spacestationkeeper
4e94a75b4193e004f50d7e8fe2808fb8ebb2375f
Reshape.lua
Reshape.lua
local Reshape, parent = torch.class('nn.Reshape', 'nn.Module') function Reshape:__init(...) parent.__init(self) self.size = torch.LongStorage() self.batchsize = torch.LongStorage() local n = select('#', ...) if n == 1 and torch.typename(select(1, ...)) == 'torch.LongStorage' then self.size:resize(#select(1, ...)):copy(select(1, ...)) else self.size:resize(n) self.batchsize:resize(n+1) self.nelement = 1 for i=1,n do self.size[i] = select(i, ...) self.batchsize[i+1] = select(i, ...) self.nelement = self.nelement * self.size[i] end end end function Reshape:updateOutput(input) input = input:contiguous() local nelement = input:nElement() if nelement == self.nelement then self.output:set(input):resize(self.size) else self.batchsize[1] = input:size(1) self.output:set(input):resize(self.batchsize) end return self.output end function Reshape:updateGradInput(input, gradOutput) gradOutput = gradOutput:contiguous() self.gradInput:set(gradOutput):resizeAs(input) return self.gradInput end
local Reshape, parent = torch.class('nn.Reshape', 'nn.Module') function Reshape:__init(...) parent.__init(self) local arg = {...} self.size = torch.LongStorage() self.batchsize = torch.LongStorage() local n = #arg if n == 1 and torch.typename(arg[1]) == 'torch.LongStorage' then self.size:resize(#arg[1]):copy(arg[1]) else self.size:resize(n) for i=1,n do self.size[i] = arg[i] end end self.nelement = 1 self.batchsize:resize(#self.size+1) for i=1,#self.size do self.nelement = self.nelement * self.size[i] self.batchsize[i+1] = self.size[i] end end function Reshape:updateOutput(input) input = input:contiguous() local nelement = input:nElement() if nelement == self.nelement then self.output:set(input):resize(self.size) else self.batchsize[1] = input:size(1) self.output:set(input):resize(self.batchsize) end return self.output end function Reshape:updateGradInput(input, gradOutput) gradOutput = gradOutput:contiguous() self.gradInput:set(gradOutput):resizeAs(input) return self.gradInput end
bug fix + cleaner handling of variable arguments (...)
bug fix + cleaner handling of variable arguments (...)
Lua
bsd-3-clause
mys007/nn,noa/nn,ominux/nn,xianjiec/nn,abeschneider/nn,EnjoyHacking/nn,szagoruyko/nn,eriche2016/nn,Aysegul/nn,apaszke/nn,davidBelanger/nn,sagarwaghmare69/nn,bartvm/nn,joeyhng/nn,jhjin/nn,diz-vara/nn,colesbury/nn,zchengquan/nn,Jeffyrao/nn,clementfarabet/nn,PraveerSINGH/nn,LinusU/nn,fmassa/nn,ivendrov/nn,forty-2/nn,witgo/nn,adamlerer/nn,soumith/nn,rotmanmi/nn,nicholas-leonard/nn,hery/nn,zhangxiangxiao/nn,boknilev/nn,douwekiela/nn,GregSatre/nn,PierrotLC/nn,karpathy/nn,rickyHong/nn_lib_torch,Moodstocks/nn,lukasc-ch/nn,hughperkins/nn,eulerreich/nn,jzbontar/nn,elbamos/nn,aaiijmrtt/nn,kmul00/nn,sbodenstein/nn,vgire/nn,caldweln/nn,andreaskoepf/nn,Djabbz/nn,mlosch/nn,jonathantompson/nn,lvdmaaten/nn
604b4ad98a2a1ed5b31595d5bfbd0a6cab5d4748
pud/component/ControllerComponent.lua
pud/component/ControllerComponent.lua
local Class = require 'lib.hump.class' local Component = getClass 'pud.component.Component' local CommandEvent = getClass 'pud.event.CommandEvent' local ConsoleEvent = getClass 'pud.event.ConsoleEvent' local WaitCommand = getClass 'pud.command.WaitCommand' local MoveCommand = getClass 'pud.command.MoveCommand' local AttackCommand = getClass 'pud.command.AttackCommand' local OpenDoorCommand = getClass 'pud.command.OpenDoorCommand' local PickupCommand = getClass 'pud.command.PickupCommand' local DropCommand = getClass 'pud.command.DropCommand' local DoorMapType = getClass 'pud.map.DoorMapType' local message = require 'pud.component.message' local property = require 'pud.component.property' local CommandEvents = CommandEvents local vec2_equal = vec2.equal -- ControllerComponent -- local ControllerComponent = Class{name='ControllerComponent', inherits=Component, function(self, newProperties) Component._addRequiredProperties(self, {'CanOpenDoors'}) Component.construct(self, newProperties) self:_addMessages( 'COLLIDE_NONE', 'COLLIDE_BLOCKED', 'COLLIDE_ITEM', 'COLLIDE_ENEMY', 'COLLIDE_HERO') end } -- destructor function ControllerComponent:destroy() self._onGround = nil Component.destroy(self) end function ControllerComponent:_setProperty(prop, data) prop = property(prop) if nil == data then data = property.default(prop) end if prop == property('CanOpenDoors') then verify('boolean', data) end Component._setProperty(self, prop, data) end -- check for collisions at the given coordinates function ControllerComponent:_attemptMove(x, y) local pos = self._mediator:query(property('Position')) local newX, newY = pos[1] + x, pos[2] + y CollisionSystem:check(self._mediator, newX, newY) end function ControllerComponent:_wait() self:_sendCommand(WaitCommand(self._mediator)) end function ControllerComponent:_move(x, y) local canMove = self._mediator:query(property('CanMove')) if canMove then self:_sendCommand(MoveCommand(self._mediator, x, y)) else self:_wait() end end function ControllerComponent:_tryToManipulateMap(node) local wait = true if node then local mapType = node:getMapType() if mapType:isType(DoorMapType('shut')) then if self._mediator:query(property('CanOpenDoors')) then self:_sendCommand(OpenDoorCommand(self._mediator, node)) wait = false end end end if wait then self:_wait() end end function ControllerComponent:_attack(isHero, target) local etype = self._mediator:getEntityType() if isHero or 'hero' == etype then self:_sendCommand( AttackCommand(self._mediator, EntityRegistry:get(target))) else self:_wait() end end function ControllerComponent:_tryToPickup() if self._onGround then local item = EntityRegistry:get(self._onGround) local ipos = item:query(property('Position')) local mpos = self._mediator:query(property('Position')) if vec2_equal(ipos[1], ipos[2], mpos[1], mpos[2]) then self:_sendCommand(PickupCommand(self._mediator, self._onGround)) self._onGround = false end end end function ControllerComponent:_tryToDrop(id) local item = EntityRegistry:get(id) self:_sendCommand(DropCommand(self._mediator, id)) end function ControllerComponent:_sendCommand(command) CommandEvents:notify(CommandEvent(command)) end function ControllerComponent:receive(msg, ...) if msg == message('COLLIDE_NONE') then self:_move(...) elseif msg == message('COLLIDE_BLOCKED') then self:_tryToManipulateMap(...) elseif msg == message('COLLIDE_ENEMY') then self:_attack(false, ...) elseif msg == message('COLLIDE_HERO') then self:_attack(true, ...) elseif msg == message('COLLIDE_ITEM') then if self._mediator:getEntityType() == 'hero' then local id = select(1, ...) self._onGround = id if id then local item = EntityRegistry:get(id) local name = item:getName() local elevel = item:getELevel() GameEvents:push(ConsoleEvent('Item found: %s (%d)', name, elevel)) end end else Component.receive(self, msg, ...) end end -- the class return ControllerComponent
local Class = require 'lib.hump.class' local Component = getClass 'pud.component.Component' local CommandEvent = getClass 'pud.event.CommandEvent' local ConsoleEvent = getClass 'pud.event.ConsoleEvent' local WaitCommand = getClass 'pud.command.WaitCommand' local MoveCommand = getClass 'pud.command.MoveCommand' local AttackCommand = getClass 'pud.command.AttackCommand' local OpenDoorCommand = getClass 'pud.command.OpenDoorCommand' local PickupCommand = getClass 'pud.command.PickupCommand' local DropCommand = getClass 'pud.command.DropCommand' local DoorMapType = getClass 'pud.map.DoorMapType' local message = require 'pud.component.message' local property = require 'pud.component.property' local CommandEvents = CommandEvents local vec2_equal = vec2.equal -- ControllerComponent -- local ControllerComponent = Class{name='ControllerComponent', inherits=Component, function(self, newProperties) Component._addRequiredProperties(self, {'CanOpenDoors'}) Component.construct(self, newProperties) self:_addMessages( 'COLLIDE_NONE', 'COLLIDE_BLOCKED', 'COLLIDE_ITEM', 'COLLIDE_ENEMY', 'COLLIDE_HERO') end } -- destructor function ControllerComponent:destroy() Component.destroy(self) end function ControllerComponent:_setProperty(prop, data) prop = property(prop) if nil == data then data = property.default(prop) end if prop == property('CanOpenDoors') then verify('boolean', data) end Component._setProperty(self, prop, data) end -- check for collisions at the given coordinates function ControllerComponent:_attemptMove(x, y) local pos = self._mediator:query(property('Position')) local newX, newY = pos[1] + x, pos[2] + y CollisionSystem:check(self._mediator, newX, newY) end function ControllerComponent:_wait() self:_sendCommand(WaitCommand(self._mediator)) end function ControllerComponent:_move(x, y) local canMove = self._mediator:query(property('CanMove')) if canMove then self:_sendCommand(MoveCommand(self._mediator, x, y)) else self:_wait() end end function ControllerComponent:_tryToManipulateMap(node) local wait = true if node then local mapType = node:getMapType() if mapType:isType(DoorMapType('shut')) then if self._mediator:query(property('CanOpenDoors')) then self:_sendCommand(OpenDoorCommand(self._mediator, node)) wait = false end end end if wait then self:_wait() end end function ControllerComponent:_attack(isHero, target) local etype = self._mediator:getEntityType() if isHero or 'hero' == etype then self:_sendCommand( AttackCommand(self._mediator, EntityRegistry:get(target))) else self:_wait() end end function ControllerComponent:_tryToPickup() local items = EntityRegistry:getIDsByType('item') if items then local num = #items for i=1,num do local id = items[i] local item = EntityRegistry:get(id) local ipos = item:query(property('Position')) local mpos = self._mediator:query(property('Position')) if vec2_equal(ipos[1], ipos[2], mpos[1], mpos[2]) then self:_sendCommand(PickupCommand(self._mediator, id)) end end end end function ControllerComponent:_tryToDrop(id) local item = EntityRegistry:get(id) self:_sendCommand(DropCommand(self._mediator, id)) end function ControllerComponent:_sendCommand(command) CommandEvents:notify(CommandEvent(command)) end function ControllerComponent:receive(msg, ...) if msg == message('COLLIDE_NONE') then self:_move(...) elseif msg == message('COLLIDE_BLOCKED') then self:_tryToManipulateMap(...) elseif msg == message('COLLIDE_ENEMY') then self:_attack(false, ...) elseif msg == message('COLLIDE_HERO') then self:_attack(true, ...) elseif msg == message('COLLIDE_ITEM') then if self._mediator:getEntityType() == 'hero' then local id = select(1, ...) if id then local item = EntityRegistry:get(id) local name = item:getName() local elevel = item:getELevel() GameEvents:push(ConsoleEvent('Item found: %s (%d)', name, elevel)) end end else Component.receive(self, msg, ...) end end -- the class return ControllerComponent
fix pickup to check position
fix pickup to check position
Lua
mit
scottcs/wyx
a7e606b85c833379a6a970a875a712ad2edd09ac
client.lua
client.lua
-------------------------------------------------------------------------config REMOTE = false -- whether the script is being run remotely or locally DIVIDER_POS = 15 -- the divider between users and chat monitor = peripheral.wrap("left") monitor.clear() monitor.setCursorPos(1,1) --os.loadAPI("json") ------------------------------------------------------------------http requests if REMOTE then domain = "http://ftbirc.no-ip.biz:5000" else domain = "http://127.0.0.1:5000" end MESSAGES_URL = domain.."/messages" USERS_URL = domain.."/users" OPS_URL = domain.."/ops" VOICED_URL = domain.."/voiced" function decodeJsonFrom(url) local h = http.get(url) local str = h.readAll() local messages = json.decode(str) return messages end -- Fetch any range of chat messages. Either argument can be nil for no limit. function fetchMessages(first, last) local pre = {"?", "&"} local param1 = "" local param2 = "" if not first then param1 = pre[1].."start" table.remove(pre, 1) end if not last then param2 = pre[1].."end" table.remove(pre, 1) end local url = MESSAGES_URL..param1..param2 return decodeJsonFrom(url) end function fetchUsers() return decodeJsonFrom(USERS_URL) end function fetchOps() return decodeJsonFrom(OPS_URL) end function fetchVoiced() return decodeJsonFrom(VOICED_URL) end --------------------------------------------------------------------------stuff dividercolor = colors.white function drawDivider() for y=1,screenheight do screen.setTextColor(dividercolor) screen.setCursorPos(DIVIDER_POS, y) screen.write("|") end end ----------------------------------------------------------------------chat pane ChatPane = {} ChatPane.__index = ChatPane function ChatPane.create(screen) local self = {} setmetatable(self, ChatPane) self.screen = screen self.maxhistory = 50 local screenwidth, screenheight = self.screen.getSize() self.left = DIVIDER_POS + 2 self.right = screenwidth self.top = 1 self.bot = screenheight self.height = self.bot - self.top + 1 self.width = self.right - self.left + 1 -- The history is everything written to the chat diced up into -- characters and mashed together. -- It's a sequence of {["char"], ["color"]} self.history = {} return self end -- Get cursor position relative to this function ChatPane:getCursorPos() local x, y = self.screen.getCursorPos() x = x - self.left + 1 y = y - self.top + 1 return x, y end function ChatPane:setCursorPos(x, y) local setx = self.left + x - 1 local sety = self.top + y - 1 self.screen.setCursorPos(setx, sety) end -- incomplete function ChatPane:position(left, right, top, bot) self.left = left self.right = right self.top = top self.bot = bot -- update drawing end -- Write to the chat pane. Accepts \n characters. Color arg is optional. function ChatPane:write(text, color) color = color or colors.white for i=1,#text do local ch = string.sub(text, i, i) local pair = {["char"]=ch, ["color"]=color} table.insert(self.history, pair) end self:draw() end function ChatPane:newLine() local x, y = self:getCursorPos() self:setCursorPos(1, y+1) end -- Draw the text word wrapped to the screen. function ChatPane:draw() -- We only want to write the lines that fit on the screen. So the -- output is stored in a buffer and the bottom portion of it is sliced -- off and displayed. -- -- It is indexed by buffer[y[x["char" or "color"]]] local buffer = {{}} local buff_left = 1 local buff_right = self.width local buff_top = 1 local buff_x = buff_left local buff_y = buff_top for i=1,#self.history do local el = self.history[i] if el["char"] == "\n" then -- clear the rest of the line and move to next line local blank = {["char"]=" ", ["color"]=colors.white} for x=buff_x,buff_right do buffer[buff_y][x] = blank end buff_x, buff_y = buff_left, buff_y+1 buffer[buff_y] = {} else if buff_x <= buff_right then -- write next character buffer[buff_y][buff_x] = el buff_x = buff_x + 1 else -- no more space, write on the next line buff_x, buff_y = buff_left, buff_y+1 buffer[buff_y] = {} buffer[buff_y][buff_x] = el buff_x = buff_x + 1 end end end -- Make sure the last line has blank characters at the end local blank = {["char"]=" ", ["color"]=colors.white} for x=buff_x, buff_right do buffer[buff_y][x] = blank end -- Actually write the text to the screen self:setCursorPos(1,1) local startread = #buffer - self.height + 1 if startread < 1 then startread = 1 end for linenum=startread,#buffer do line = buffer[linenum] for letternum=1,#line do letter = line[letternum] ch = letter["char"] col = letter["color"] if self.screen.isColor() then self.screen.setTextColor(col) end self.screen.write(ch) end if linenum ~= #buffer then self:newLine() end end end ---------------------------------------------------------------------other shit function printToUsersPane(text) end nextmsg = 0 function updateMessages(c) messages = fetchMessages(nextmsg, nil) while not (messages[tostring(nextmsg)] == nil) do local entry = messages[tostring(nextmsg)] local nicktext, nickcol = entry["nick"]..": ", colors.gray local msgtext, msgcol = entry["message"], colors.white c:write("\n"..nicktext, nickcol) c:write(msgtext, msgcol) nextmsg = nextmsg + 1 end end function printUsers() end function printOps() end function printVoiced() end drawDivider() c = ChatPane.create(monitor) while true do updateMessages(c) os.sleep(2) end
-------------------------------------------------------------------------config REMOTE = false -- whether the script is being run remotely or locally DIVIDER_POS = 15 -- the divider between users and chat monitor = peripheral.wrap("left") monitor.clear() monitor.setCursorPos(1,1) os.loadAPI("json") ------------------------------------------------------------------http requests if REMOTE then domain = "http://ftbirc.no-ip.biz:5000" else domain = "http://127.0.0.1:5000" end MESSAGES_URL = domain.."/messages" USERS_URL = domain.."/users" OPS_URL = domain.."/ops" VOICED_URL = domain.."/voiced" function decodeJsonFrom(url) local h = http.get(url) local str = h.readAll() local messages = json.decode(str) return messages end -- Fetch any range of chat messages. Either argument can be nil for no limit. function fetchMessages(first, last) local pre = {"?", "&"} local param1 = "" local param2 = "" if not first then param1 = pre[1].."start" table.remove(pre, 1) end if not last then param2 = pre[1].."end" table.remove(pre, 1) end local url = MESSAGES_URL..param1..param2 return decodeJsonFrom(url) end function fetchUsers() return decodeJsonFrom(USERS_URL) end function fetchOps() return decodeJsonFrom(OPS_URL) end function fetchVoiced() return decodeJsonFrom(VOICED_URL) end --------------------------------------------------------------------------stuff dividercolor = colors.white function drawDivider(screen) local screenwidth, screenheight = screen.getSize() for y=1,screenheight do screen.setTextColor(dividercolor) screen.setCursorPos(DIVIDER_POS, y) screen.write("|") end end ----------------------------------------------------------------------chat pane ChatPane = {} ChatPane.__index = ChatPane function ChatPane.create(screen) local self = {} setmetatable(self, ChatPane) self.screen = screen self.maxhistory = 50 local screenwidth, screenheight = self.screen.getSize() self.left = DIVIDER_POS + 2 self.right = screenwidth self.top = 1 self.bot = screenheight self.height = self.bot - self.top + 1 self.width = self.right - self.left + 1 -- The history is everything written to the chat diced up into -- characters and mashed together. -- It's a sequence of {["char"], ["color"]} self.history = {} return self end -- Get cursor position relative to this function ChatPane:getCursorPos() local x, y = self.screen.getCursorPos() x = x - self.left + 1 y = y - self.top + 1 return x, y end function ChatPane:setCursorPos(x, y) local setx = self.left + x - 1 local sety = self.top + y - 1 self.screen.setCursorPos(setx, sety) end -- incomplete function ChatPane:position(left, right, top, bot) self.left = left self.right = right self.top = top self.bot = bot -- update drawing end -- Write to the chat pane. Accepts \n characters. Color arg is optional. function ChatPane:write(text, color) color = color or colors.white for i=1,#text do local ch = string.sub(text, i, i) local pair = {["char"]=ch, ["color"]=color} table.insert(self.history, pair) end self:draw() end function ChatPane:newLine() local x, y = self:getCursorPos() self:setCursorPos(1, y+1) end -- Draw the text word wrapped to the screen. function ChatPane:draw() -- We only want to write the lines that fit on the screen. So the -- output is stored in a buffer and the bottom portion of it is sliced -- off and displayed. -- -- It is indexed by buffer[y[x["char" or "color"]]] local buffer = {{}} local buff_left = 1 local buff_right = self.width local buff_top = 1 local buff_x = buff_left local buff_y = buff_top for i=1,#self.history do local el = self.history[i] if el["char"] == "\n" then -- clear the rest of the line and move to next line local blank = {["char"]=" ", ["color"]=colors.white} for x=buff_x,buff_right do buffer[buff_y][x] = blank end buff_x, buff_y = buff_left, buff_y+1 buffer[buff_y] = {} else if buff_x <= buff_right then -- write next character buffer[buff_y][buff_x] = el buff_x = buff_x + 1 else -- no more space, write on the next line buff_x, buff_y = buff_left, buff_y+1 buffer[buff_y] = {} buffer[buff_y][buff_x] = el buff_x = buff_x + 1 end end end -- Make sure the last line has blank characters at the end local blank = {["char"]=" ", ["color"]=colors.white} for x=buff_x, buff_right do buffer[buff_y][x] = blank end -- Actually write the text to the screen self:setCursorPos(1,1) local startread = #buffer - self.height + 1 if startread < 1 then startread = 1 end for linenum=startread,#buffer do line = buffer[linenum] for letternum=1,#line do letter = line[letternum] ch = letter["char"] col = letter["color"] if self.screen.isColor() then self.screen.setTextColor(col) end self.screen.write(ch) end if linenum ~= #buffer then self:newLine() end end end ----------------------------------------------------------------------user pane ---------------------------------------------------------------------other shit function printToUsersPane(text) end nextmsg = 0 function updateMessages(c) messages = fetchMessages(nextmsg, nil) while not (messages[tostring(nextmsg)] == nil) do local entry = messages[tostring(nextmsg)] local nicktext, nickcol = entry["nick"]..": ", colors.gray local msgtext, msgcol = entry["message"], colors.white c:write("\n"..nicktext, nickcol) c:write(msgtext, msgcol) nextmsg = nextmsg + 1 end end function printUsers() end function printOps() end function printVoiced() end drawDivider(monitor) c = ChatPane.create(monitor) while true do updateMessages(c) os.sleep(2) end
Fixed the client to work out of the box
Fixed the client to work out of the box
Lua
mit
tmerr/computercraftIRC
d4530b545bcc6066683841dcf04ee97fc889e771
MMOCoreORB/bin/scripts/mobile/tatooine/tusken_bantha.lua
MMOCoreORB/bin/scripts/mobile/tatooine/tusken_bantha.lua
tusken_bantha = Creature:new { objectName = "@mob/creature_names:tusken_bantha", socialGroup = "tusken_raider", pvpFaction = "tusken_raider", faction = "tusken_raider", level = 25, chanceHit = 0.36, damageMin = 260, damageMax = 270, baseXp = 2543, baseHAM = 6300, baseHAMmax = 7700, armor = 0, resists = {20,25,15,50,-1,-1,-1,-1,-1}, meatType = "meat_domesticated", meatAmount = 475, hideType = "hide_wooly", hideAmount = 350, boneType = "bone_mammal", boneAmount = 375, milkType = "milk_domesticated", milk = 235, tamingChance = 0, ferocity = 2, pvpBitmask = ATTACKABLE, creatureBitmask = PACK, optionsBitmask = 128, diet = CARNIVORE, templates = {"object/mobile/bantha.iff"}, lootGroups = {}, weapons = {}, conversationTemplate = "", attacks = { {"posturedownattack","postureDownChance=50"} } } CreatureTemplates:addCreatureTemplate(tusken_bantha, "tusken_bantha")
tusken_bantha = Creature:new { objectName = "@mob/creature_names:tusken_bantha", socialGroup = "tusken_raider", pvpFaction = "tusken_raider", faction = "tusken_raider", level = 25, chanceHit = 0.36, damageMin = 260, damageMax = 270, baseXp = 2543, baseHAM = 6300, baseHAMmax = 7700, armor = 0, resists = {20,25,15,50,-1,-1,-1,-1,-1}, meatType = "meat_domesticated", meatAmount = 475, hideType = "hide_wooly", hideAmount = 350, boneType = "bone_mammal", boneAmount = 375, milkType = "milk_domesticated", milk = 235, tamingChance = 0, ferocity = 2, pvpBitmask = ATTACKABLE, creatureBitmask = PACK, optionsBitmask = 128, diet = CARNIVORE, templates = {"object/mobile/bantha_saddle_hue.iff", "object/mobile/bantha_saddle.iff"}, lootGroups = {}, weapons = {}, conversationTemplate = "", attacks = { {"posturedownattack","postureDownChance=50"} } } CreatureTemplates:addCreatureTemplate(tusken_bantha, "tusken_bantha")
[fixed] Tusken Bantha to use templates with saddles.
[fixed] Tusken Bantha to use templates with saddles. Change-Id: I5eaa19c9b5e84c147d7f9eb2648dc1bf12abd3b1
Lua
agpl-3.0
Tatwi/legend-of-hondo,lasko2112/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,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo
f712ff1feadc341387840f647588b653b1fa8448
httpd.lua
httpd.lua
-- Simple NodeMCU web server (done is a not so nodeie fashion :-) -- -- Written by Scott Beasley 2015 -- Open and free to change and use. Enjoy. -- -- positron: code is based on http://letsmakerobots.com/blog/jscottb/nodemcu-esp8266-simple-httpd-web-server-example local utils = require("utils") local requestTable = {} local function setHandlerTable(tt) requestTable = tt end -- Build and return a table of the http request data local function parseHttpRequest (req) local res = {} local first = nil local key, v, strt_ndx, end_ndx local trim = utils.trim local decode = utils.decodeUrl local split = utils.split for str in string.gmatch (req, "([^\n]+)") do -- First line in the method and path if (first == nil) then first = 1 str = decode(str) parts = split(str, " ") res.method = trim( parts[1] ) assert( res.method:upper() == "GET", "Only GET Requests supported") req = trim(parts[2]) res.request = req res.httpVer = trim(parts[3]) start_ndx = string.find( req, "\?") if start_ndx ~= nil then res.path = string.sub(req, 0, start_ndx-1) qq = string.sub(req, start_ndx+1 ) parts = split(qq, "\&") res.parameters = {} for i,q in pairs(parts) do kv = split(q,"=") --print("have q "..q..", split into '"..kv[1].."' and '"..kv[2].."'") k = trim( kv[1] ) v = trim( kv[2] ) res.parameters[k] = v end else res.path=req end else -- Process remaining ":" headers res.headers = {} strt_ndx, end_ndx = string.find (str, "([^:]+)") if (end_ndx ~= nil) then v = utils.trim (string.sub (str, end_ndx + 2)) key = utils.trim (string.sub (str, strt_ndx, end_ndx)) res.headers[key] = v end end end return res end local function connect (conn, data) conn:on ("receive", function (conn, req) local queryData="" s,err = pcall( function() queryData = parseHttpRequest(req) end) local out,code if not s then out = "Bad request: "..err code = 400 else local path = queryData.path; print (queryData.method .. " '" .. path .. "'") local fn = requestTable[path] ; if fn ~= nil then out,code = fn(queryData) else code=404 out="Not Found" end end local reply = { "HTTP/1.0 "..code.." NA", "Server: PositronESP (nodeMCU)", "Content-Length: "..out:len(), "", out } conn:send( utils.join(reply, "\r\n") ) conn:close() collectgarbage() end ) end return { connect=connect, setHandlerTable=setHandlerTable }
-- Simple NodeMCU web server (done is a not so nodeie fashion :-) -- -- Written by Scott Beasley 2015 -- Open and free to change and use. Enjoy. -- -- positron: code is based on http://letsmakerobots.com/blog/jscottb/nodemcu-esp8266-simple-httpd-web-server-example local utils = require("utils") local requestTable = {} local function setHandlerTable(tt) requestTable = tt end -- Build and return a table of the http request data local function parseHttpRequest (req) local res = {} res.headers = {} local first = nil local key, v, strt_ndx, end_ndx local trim = utils.trim local decode = utils.decodeUrl local split = utils.split for str in string.gmatch (req, "([^\n]+)") do -- First line in the method and path if (first == nil) then first = 1 str = decode(str) parts = split(str, " ") res.method = trim( parts[1] ) assert( res.method:upper() == "GET", "Only GET Requests supported") req = trim(parts[2]) res.request = req res.httpVer = trim(parts[3]) start_ndx = string.find( req, "\?") if start_ndx ~= nil then res.path = string.sub(req, 0, start_ndx-1) qq = string.sub(req, start_ndx+1 ) parts = split(qq, "\&") res.parameters = {} for i,q in pairs(parts) do kv = split(q,"=") --print("have q "..q..", split into '"..kv[1].."' and '"..kv[2].."'") k = trim( kv[1] ) v = trim( kv[2] ) res.parameters[k] = v end else res.path=req end else -- Process remaining ":" headers strt_ndx, end_ndx = string.find (str, "([^:]+)") if (end_ndx ~= nil) then v = utils.trim (string.sub (str, end_ndx + 2)) key = utils.trim (string.sub (str, strt_ndx, end_ndx)) res.headers[key] = v end end end return res end local function connect (conn, data) conn:on ("receive", function (conn, req) local queryData="" s,err = pcall( function() queryData = parseHttpRequest(req) end) local out,code if not s then out = "Bad request: "..err code = 400 else local path = queryData.path; print (queryData.method .. " '" .. path .. "'") local fn = requestTable[path] ; if fn ~= nil then out,code = fn(queryData) else code=404 out="Not Found" end end local reply = { "HTTP/1.0 "..code.." NA", "Server: PositronESP (nodeMCU)", "Content-Length: "..out:len(), "", out } conn:send( utils.join(reply, "\r\n") ) conn:close() collectgarbage() end ) end return { connect=connect, setHandlerTable=setHandlerTable }
fixed bug with headers storing in httpd
fixed bug with headers storing in httpd
Lua
lgpl-2.1
positron96/esp8266-bootconfig
6a31372b25f85b043d21d54c5c16de9a01a696e5
modules/freifunk/luasrc/model/cbi/freifunk/public_status.lua
modules/freifunk/luasrc/model/cbi/freifunk/public_status.lua
require "luci.sys" require "luci.tools.webadmin" local uci = luci.model.uci.cursor_state() local ffzone = luci.tools.webadmin.firewall_find_zone("freifunk") local ffznet = ffzone and uci:get("firewall", ffzone, "network") local ffwifs = ffznet and luci.util.split(ffznet, " ") or {} -- System -- f = SimpleForm("system", "System") f.submit = false f.reset = false local system, model, memtotal, memcached, membuffers, memfree = luci.sys.sysinfo() local uptime = luci.sys.uptime() f:field(DummyValue, "_system", translate("system")).value = system f:field(DummyValue, "_cpu", translate("m_i_processor")).value = model local load1, load5, load15 = luci.sys.loadavg() f:field(DummyValue, "_la", translate("load")).value = string.format("%.2f, %.2f, %.2f", load1, load5, load15) f:field(DummyValue, "_memtotal", translate("m_i_memory")).value = string.format("%.2f MB (%.0f%% %s, %.0f%% %s, %.0f%% %s)", tonumber(memtotal) / 1024, 100 * memcached / memtotal, translate("mem_cached") or "", 100 * membuffers / memtotal, translate("mem_buffered") or "", 100 * memfree / memtotal, translate("mem_free") or "") f:field(DummyValue, "_systime", translate("m_i_systemtime")).value = os.date("%c") f:field(DummyValue, "_uptime", translate("m_i_uptime")).value = luci.tools.webadmin.date_format(tonumber(uptime)) -- Wireless -- local wireless = uci:get_all("wireless") local wifidata = luci.sys.wifi.getiwconfig() local ifaces = {} for k, v in pairs(wireless) do if v[".type"] == "wifi-iface" and luci.util.contains(ffwifs, v.device) then table.insert(ifaces, v) end end m = SimpleForm("wireless", "Freifunk WLAN") m.submit = false m.reset = false s = m:section(Table, ifaces, translate("networks")) link = s:option(DummyValue, "_link", translate("link")) function link.cfgvalue(self, section) local ifname = self.map:get(section, "ifname") return wifidata[ifname] and wifidata[ifname]["Link Quality"] or "-" end essid = s:option(DummyValue, "ssid", "ESSID") bssid = s:option(DummyValue, "_bsiid", "BSSID") function bssid.cfgvalue(self, section) local ifname = self.map:get(section, "ifname") return (wifidata[ifname] and (wifidata[ifname].Cell or wifidata[ifname]["Access Point"])) or "-" end channel = s:option(DummyValue, "channel", translate("channel")) function channel.cfgvalue(self, section) return wireless[self.map:get(section, "device")].channel end protocol = s:option(DummyValue, "_mode", translate("protocol")) function protocol.cfgvalue(self, section) local mode = wireless[self.map:get(section, "device")].mode return mode and "802." .. mode end mode = s:option(DummyValue, "mode", translate("mode")) encryption = s:option(DummyValue, "encryption", translate("iwscan_encr")) power = s:option(DummyValue, "_power", translate("power")) function power.cfgvalue(self, section) local ifname = self.map:get(section, "ifname") return wifidata[ifname] and wifidata[ifname]["Tx-Power"] or "-" end scan = s:option(Button, "_scan", translate("scan")) scan.inputstyle = "find" function scan.cfgvalue(self, section) return self.map:get(section, "ifname") or false end t2 = m:section(Table, {}, translate("iwscan"), translate("iwscan1")) function scan.write(self, section) t2.render = t2._render local ifname = self.map:get(section, "ifname") luci.util.update(t2.data, luci.sys.wifi.iwscan(ifname)) end t2._render = t2.render t2.render = function() end t2:option(DummyValue, "Quality", translate("iwscan_link")) essid = t2:option(DummyValue, "ESSID", "ESSID") function essid.cfgvalue(self, section) return luci.util.pcdata(self.map:get(section, "ESSID")) end t2:option(DummyValue, "Address", "BSSID") t2:option(DummyValue, "Mode", translate("mode")) chan = t2:option(DummyValue, "channel", translate("channel")) function chan.cfgvalue(self, section) return self.map:get(section, "Channel") or self.map:get(section, "Frequency") or "-" end t2:option(DummyValue, "Encryption key", translate("iwscan_encr")) t2:option(DummyValue, "Signal level", translate("iwscan_signal")) t2:option(DummyValue, "Noise level", translate("iwscan_noise")) -- Routes -- r = SimpleForm("routes", "Standardrouten") r.submit = false r.reset = false local routes = {} for i, route in ipairs(luci.sys.net.routes()) do if route.dest:prefix() == 0 then routes[#routes+1] = route end end v = r:section(Table, routes) net = v:option(DummyValue, "iface", translate("network")) function net.cfgvalue(self, section) return luci.tools.webadmin.iface_get_network(routes[section].device) or routes[section].device end target = v:option(DummyValue, "target", translate("target")) function target.cfgvalue(self, section) return routes[section].dest:network():string() end netmask = v:option(DummyValue, "netmask", translate("netmask")) function netmask.cfgvalue(self, section) return routes[section].dest:mask():string() end gateway = v:option(DummyValue, "gateway", translate("gateway")) function gateway.cfgvalue(self, section) return routes[section].gateway:string() end metric = v:option(DummyValue, "metric", translate("metric")) function metric.cfgvalue(self, section) return routes[section].metric end local routes6 = {} for i, route in ipairs(luci.sys.net.routes6() or {}) do if route.dest:prefix() == 0 then routes6[#routes6+1] = route end end if #routes6 > 0 then v6 = r:section(Table, routes6) net = v6:option(DummyValue, "iface", translate("network")) function net.cfgvalue(self, section) return luci.tools.webadmin.iface_get_network(routes[section].device) or routes6[section].device end target = v6:option(DummyValue, "target", translate("target")) function target.cfgvalue(self, section) return routes6[section].dest:string() end gateway = v6:option(DummyValue, "gateway6", translate("gateway6")) function gateway.cfgvalue(self, section) return routes6[section].source:string() end metric = v6:option(DummyValue, "metric", translate("metric")) function metric.cfgvalue(self, section) return string.format("%X", routes6[section].metric) end end return f, m, r
require "luci.sys" require "luci.tools.webadmin" local bit = require "bit" local uci = luci.model.uci.cursor_state() local ffzone = luci.tools.webadmin.firewall_find_zone("freifunk") local ffznet = ffzone and uci:get("firewall", ffzone, "network") local ffwifs = ffznet and luci.util.split(ffznet, " ") or {} -- System -- f = SimpleForm("system", "System") f.submit = false f.reset = false local system, model, memtotal, memcached, membuffers, memfree = luci.sys.sysinfo() local uptime = luci.sys.uptime() f:field(DummyValue, "_system", translate("system")).value = system f:field(DummyValue, "_cpu", translate("m_i_processor")).value = model local load1, load5, load15 = luci.sys.loadavg() f:field(DummyValue, "_la", translate("load")).value = string.format("%.2f, %.2f, %.2f", load1, load5, load15) f:field(DummyValue, "_memtotal", translate("m_i_memory")).value = string.format("%.2f MB (%.0f%% %s, %.0f%% %s, %.0f%% %s)", tonumber(memtotal) / 1024, 100 * memcached / memtotal, translate("mem_cached") or "", 100 * membuffers / memtotal, translate("mem_buffered") or "", 100 * memfree / memtotal, translate("mem_free") or "") f:field(DummyValue, "_systime", translate("m_i_systemtime")).value = os.date("%c") f:field(DummyValue, "_uptime", translate("m_i_uptime")).value = luci.tools.webadmin.date_format(tonumber(uptime)) -- Wireless -- local wireless = uci:get_all("wireless") local wifidata = luci.sys.wifi.getiwconfig() local ifaces = {} for k, v in pairs(wireless) do if v[".type"] == "wifi-iface" and luci.util.contains(ffwifs, v.device) then table.insert(ifaces, v) end end m = SimpleForm("wireless", "Freifunk WLAN") m.submit = false m.reset = false s = m:section(Table, ifaces, translate("networks")) link = s:option(DummyValue, "_link", translate("link")) function link.cfgvalue(self, section) local ifname = self.map:get(section, "ifname") return wifidata[ifname] and wifidata[ifname]["Link Quality"] or "-" end essid = s:option(DummyValue, "ssid", "ESSID") bssid = s:option(DummyValue, "_bsiid", "BSSID") function bssid.cfgvalue(self, section) local ifname = self.map:get(section, "ifname") return (wifidata[ifname] and (wifidata[ifname].Cell or wifidata[ifname]["Access Point"])) or "-" end channel = s:option(DummyValue, "channel", translate("channel")) function channel.cfgvalue(self, section) return wireless[self.map:get(section, "device")].channel end protocol = s:option(DummyValue, "_mode", translate("protocol")) function protocol.cfgvalue(self, section) local mode = wireless[self.map:get(section, "device")].mode return mode and "802." .. mode end mode = s:option(DummyValue, "mode", translate("mode")) encryption = s:option(DummyValue, "encryption", translate("iwscan_encr")) power = s:option(DummyValue, "_power", translate("power")) function power.cfgvalue(self, section) local ifname = self.map:get(section, "ifname") return wifidata[ifname] and wifidata[ifname]["Tx-Power"] or "-" end scan = s:option(Button, "_scan", translate("scan")) scan.inputstyle = "find" function scan.cfgvalue(self, section) return self.map:get(section, "ifname") or false end t2 = m:section(Table, {}, translate("iwscan"), translate("iwscan1")) function scan.write(self, section) t2.render = t2._render local ifname = self.map:get(section, "ifname") luci.util.update(t2.data, luci.sys.wifi.iwscan(ifname)) end t2._render = t2.render t2.render = function() end t2:option(DummyValue, "Quality", translate("iwscan_link")) essid = t2:option(DummyValue, "ESSID", "ESSID") function essid.cfgvalue(self, section) return luci.util.pcdata(self.map:get(section, "ESSID")) end t2:option(DummyValue, "Address", "BSSID") t2:option(DummyValue, "Mode", translate("mode")) chan = t2:option(DummyValue, "channel", translate("channel")) function chan.cfgvalue(self, section) return self.map:get(section, "Channel") or self.map:get(section, "Frequency") or "-" end t2:option(DummyValue, "Encryption key", translate("iwscan_encr")) t2:option(DummyValue, "Signal level", translate("iwscan_signal")) t2:option(DummyValue, "Noise level", translate("iwscan_noise")) -- Routes -- r = SimpleForm("routes", "Standardrouten") r.submit = false r.reset = false local routes = {} for i, route in ipairs(luci.sys.net.routes()) do if route.dest:prefix() == 0 then routes[#routes+1] = route end end v = r:section(Table, routes) net = v:option(DummyValue, "iface", translate("network")) function net.cfgvalue(self, section) return luci.tools.webadmin.iface_get_network(routes[section].device) or routes[section].device end target = v:option(DummyValue, "target", translate("target")) function target.cfgvalue(self, section) return routes[section].dest:network():string() end netmask = v:option(DummyValue, "netmask", translate("netmask")) function netmask.cfgvalue(self, section) return routes[section].dest:mask():string() end gateway = v:option(DummyValue, "gateway", translate("gateway")) function gateway.cfgvalue(self, section) return routes[section].gateway:string() end metric = v:option(DummyValue, "metric", translate("metric")) function metric.cfgvalue(self, section) return routes[section].metric end local routes6 = {} for i, route in ipairs(luci.sys.net.routes6() or {}) do if route.dest:prefix() == 0 then routes6[#routes6+1] = route end end if #routes6 > 0 then v6 = r:section(Table, routes6) net = v6:option(DummyValue, "iface", translate("network")) function net.cfgvalue(self, section) return luci.tools.webadmin.iface_get_network(routes[section].device) or routes6[section].device end target = v6:option(DummyValue, "target", translate("target")) function target.cfgvalue(self, section) return routes6[section].dest:string() end gateway = v6:option(DummyValue, "gateway6", translate("gateway6")) function gateway.cfgvalue(self, section) return routes6[section].source:string() end metric = v6:option(DummyValue, "metric", translate("metric")) function metric.cfgvalue(self, section) local metr = routes6[section].metric local lower = bit.band(metr, 0xffff) local higher = bit.rshift(bit.band(metr, 0xffff0000), 16) return "%04X%04X" % {higher, lower} end end return f, m, r
Fix display of v6 Routing metric on Freifunk status pages
Fix display of v6 Routing metric on Freifunk status pages git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@3891 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
Lua
apache-2.0
fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci
fbc315bbad6a126fa39106d4933d2c9baf781727
lua/entities/gmod_wire_grabber.lua
lua/entities/gmod_wire_grabber.lua
AddCSLuaFile() DEFINE_BASECLASS( "base_wire_entity" ) ENT.PrintName = "Wire Grabber" ENT.RenderGroup = RENDERGROUP_BOTH ENT.WireDebugName = "Grabber" function ENT:SetupDataTables() self:NetworkVar( "Float", 0, "BeamLength" ) end if CLIENT then return end -- No more client function ENT:Initialize() self:PhysicsInit( SOLID_VPHYSICS ) self:SetMoveType( MOVETYPE_VPHYSICS ) self:SetSolid( SOLID_VPHYSICS ) self.Inputs = Wire_CreateInputs(self, { "Grab","Strength" }) self.Outputs = Wire_CreateOutputs(self, {"Holding", "Grabbed Entity [ENTITY]"}) self.WeldStrength = 0 self.Weld = nil self.WeldEntity = nil self.ExtraProp = nil self.ExtraPropWeld = nil self:GetPhysicsObject():SetMass(10) self:Setup(100, true) self.OnlyGrabOwners = GetConVarNumber('sbox_wire_grabbers_onlyOwnersProps') > 0 end function ENT:OnRemove() if self.Weld then self:ResetGrab() end Wire_Remove(self) end function ENT:Setup(Range, Gravity) if Range then self:SetBeamLength(Range) end self.Gravity = Gravity end function ENT:ResetGrab() if IsValid(self.Weld) then self.Weld:Remove() if IsValid(self.WeldEntity) and IsValid(self.WeldEntity:GetPhysicsObject()) and self.Gravity then self.WeldEntity:GetPhysicsObject():EnableGravity(true) end end if IsValid(self.ExtraPropWeld) then self.ExtraPropWeld:Remove() end self.Weld = nil self.WeldEntity = nil self.ExtraPropWeld = nil self:SetColor(Color(255, 255, 255, self:GetColor().a)) Wire_TriggerOutput(self, "Holding", 0) Wire_TriggerOutput(self, "Grabbed Entity", self.WeldEntity) end function ENT:CanGrab(trace) -- Bail if we hit world or a player if not IsValid(trace.Entity) or trace.Entity:IsPlayer() then return false end -- If there's no physics object then we can't constraint it! if not util.IsValidPhysicsObject(trace.Entity, trace.PhysicsBone) then return false end -- We might also want to check PhysgunPickup, but this should be sufficient if self.OnlyGrabOwners and not hook.Run( "CanTool", self:GetOwner(), trace, "weld" ) then return false end return true end function ENT:TriggerInput(iname, value) if iname == "Grab" then if value ~= 0 and self.Weld == nil then local vStart = self:GetPos() local vForward = self:GetUp() local trace = util.TraceLine { start = vStart, endpos = vStart + (vForward * self:GetBeamLength()), filter = { self } } if not self:CanGrab(trace) then return end -- Weld them! local const = constraint.Weld(self, trace.Entity, 0, 0, self.WeldStrength) if const then const.Type = "" --prevents the duplicator from making this weld end local const2 --Msg("+Weld1\n") if self.ExtraProp then if self.ExtraProp:IsValid() then const2 = constraint.Weld(self.ExtraProp, trace.Entity, 0, 0, self.WeldStrength) if const2 then const2.Type = "" --prevents the duplicator from making this weld end --Msg("+Weld2\n") end end if self.Gravity then trace.Entity:GetPhysicsObject():EnableGravity(false) end self.WeldEntity = trace.Entity self.Weld = const self.ExtraPropWeld = const2 self:SetColor(Color(255, 0, 0, self:GetColor().a)) Wire_TriggerOutput(self, "Holding", 1) Wire_TriggerOutput(self, "Grabbed Entity", self.WeldEntity) elseif value == 0 then if self.Weld ~= nil or self.ExtraPropWeld ~= nil then self:ResetGrab() end end elseif iname == "Strength" then self.WeldStrength = math.max(value,0) end end --duplicator support (TAD2020) function ENT:BuildDupeInfo() local info = self.BaseClass.BuildDupeInfo(self) or {} if self.WeldEntity and self.WeldEntity:IsValid() then info.WeldEntity = self.WeldEntity:EntIndex() end if self.ExtraProp and self.ExtraProp:IsValid() then info.ExtraProp = self.ExtraProp:EntIndex() end return info end function ENT:ApplyDupeInfo(ply, ent, info, GetEntByID) self.BaseClass.ApplyDupeInfo(self, ply, ent, info, GetEntByID) self.WeldEntity = GetEntByID(info.WeldEntity) self.ExtraProp = GetEntByID(info.ExtraProp) if self.WeldEntity and self.Inputs.Grab.Value ~= 0 then if not self.Weld then self.Weld = constraint.Weld(self, trace.Entity, 0, 0, self.WeldStrength) self.Weld.Type = "" --prevents the duplicator from making this weld end if IsValid(self.ExtraProp) then self.ExtraPropWeld = constraint.Weld(self.ExtraProp, self.WeldEntity, 0, 0, self.WeldStrength) self.ExtraPropWeld.Type = "" --prevents the duplicator from making this weld end if self.Gravity then self.WeldEntity:GetPhysicsObject():EnableGravity(false) end self:SetColor(Color(255, 0, 0, self:GetColor().a)) Wire_TriggerOutput(self, "Holding", 1) Wire_TriggerOutput(self, "Grabbed Entity", self.WeldEntity) end end -- Free Fall's Owner Check Code function ENT:CheckOwner(ent) ply = self:GetPlayer() hasCPPI = istable( CPPI ) hasEPS = istable( eps ) hasPropSecure = istable( PropSecure ) hasProtector = istable( Protector ) if not hasCPPI and not hasPropProtection and not hasSPropProtection and not hasEPS and not hasPropSecure and not hasProtector then return true end local t = hook.GetTable() local fn = t.CanTool.PropProtection hasPropProtection = isfunction( fn ) if hasPropProtection then -- We're going to get the function we need now. It's local so this is a bit dirty local gi = debug.getinfo( fn ) for i=1, gi.nups do local k, v = debug.getupvalue( fn, i ) if k == "Appartient" then propProtectionFn = v end end end local fn = t.CanTool[ "SPropProtection.EntityRemoved" ] hasSPropProtection = isfunction( fn ) if hasSPropProtection then local gi = debug.getinfo( fn ) for i=1, gi.nups do local k, v = debug.getupvalue( fn, i ) if k == "SPropProtection" then SPropProtectionFn = v.PlayerCanTouch end end end local owns if hasCPPI then owns = ent:CPPICanPhysgun( ply ) elseif hasPropProtection then -- Chaussette's Prop Protection (preferred over PropSecure) owns = propProtectionFn( ply, ent ) elseif hasSPropProtection then -- Simple Prop Protection by Spacetech if ent:GetNetworkedString( "Owner" ) ~= "" then -- So it doesn't give an unowned prop owns = SPropProtectionFn( ply, ent ) else owns = false end elseif hasEPS then -- EPS owns = eps.CanPlayerTouch( ply, ent ) elseif hasPropSecure then -- PropSecure owns = PropSecure.IsPlayers( ply, ent ) elseif hasProtector then -- Protector owns = Protector.Owner( ent ) == ply:UniqueID() end return owns end duplicator.RegisterEntityClass("gmod_wire_grabber", WireLib.MakeWireEnt, "Data", "Range", "Gravity")
AddCSLuaFile() DEFINE_BASECLASS( "base_wire_entity" ) ENT.PrintName = "Wire Grabber" ENT.RenderGroup = RENDERGROUP_BOTH ENT.WireDebugName = "Grabber" function ENT:SetupDataTables() self:NetworkVar( "Float", 0, "BeamLength" ) end if CLIENT then return end -- No more client function ENT:Initialize() self:PhysicsInit( SOLID_VPHYSICS ) self:SetMoveType( MOVETYPE_VPHYSICS ) self:SetSolid( SOLID_VPHYSICS ) self.Inputs = Wire_CreateInputs(self, { "Grab","Strength" }) self.Outputs = Wire_CreateOutputs(self, {"Holding", "Grabbed Entity [ENTITY]"}) self.WeldStrength = 0 self.Weld = nil self.WeldEntity = nil self.ExtraProp = nil self.ExtraPropWeld = nil self:GetPhysicsObject():SetMass(10) self:Setup(100, true) self.OnlyGrabOwners = GetConVarNumber('sbox_wire_grabbers_onlyOwnersProps') > 0 end function ENT:OnRemove() if self.Weld then self:ResetGrab() end Wire_Remove(self) end function ENT:Setup(Range, Gravity) if Range then self:SetBeamLength(Range) end self.Gravity = Gravity end function ENT:ResetGrab() if IsValid(self.Weld) then self.Weld:Remove() if IsValid(self.WeldEntity) and IsValid(self.WeldEntity:GetPhysicsObject()) and self.Gravity then self.WeldEntity:GetPhysicsObject():EnableGravity(true) end end if IsValid(self.ExtraPropWeld) then self.ExtraPropWeld:Remove() end self.Weld = nil self.WeldEntity = nil self.ExtraPropWeld = nil self:SetColor(Color(255, 255, 255, self:GetColor().a)) Wire_TriggerOutput(self, "Holding", 0) Wire_TriggerOutput(self, "Grabbed Entity", self.WeldEntity) end function ENT:CanGrab(trace) -- Bail if we hit world or a player if not IsValid(trace.Entity) or trace.Entity:IsPlayer() then return false end -- If there's no physics object then we can't constraint it! if not util.IsValidPhysicsObject(trace.Entity, trace.PhysicsBone) then return false end -- We might also want to check PhysgunPickup, but this should be sufficient if self.OnlyGrabOwners and not hook.Run( "CanTool", self:GetOwner(), trace, "weld" ) then return false end return true end function ENT:TriggerInput(iname, value) if iname == "Grab" then if value ~= 0 and self.Weld == nil then local vStart = self:GetPos() local vForward = self:GetUp() local trace = util.TraceLine { start = vStart, endpos = vStart + (vForward * self:GetBeamLength()), filter = { self } } if not self:CanGrab(trace) then return end -- Weld them! local const = constraint.Weld(self, trace.Entity, 0, 0, self.WeldStrength) if const then const.Type = "" --prevents the duplicator from making this weld end local const2 --Msg("+Weld1\n") if self.ExtraProp then if self.ExtraProp:IsValid() then const2 = constraint.Weld(self.ExtraProp, trace.Entity, 0, 0, self.WeldStrength) if const2 then const2.Type = "" --prevents the duplicator from making this weld end --Msg("+Weld2\n") end end if self.Gravity then trace.Entity:GetPhysicsObject():EnableGravity(false) end self.WeldEntity = trace.Entity self.Weld = const self.ExtraPropWeld = const2 self:SetColor(Color(255, 0, 0, self:GetColor().a)) Wire_TriggerOutput(self, "Holding", 1) Wire_TriggerOutput(self, "Grabbed Entity", self.WeldEntity) elseif value == 0 then if self.Weld ~= nil or self.ExtraPropWeld ~= nil then self:ResetGrab() end end elseif iname == "Strength" then self.WeldStrength = math.max(value,0) end end --duplicator support (TAD2020) function ENT:BuildDupeInfo() local info = self.BaseClass.BuildDupeInfo(self) or {} if self.WeldEntity and self.WeldEntity:IsValid() then info.WeldEntity = self.WeldEntity:EntIndex() end if self.ExtraProp and self.ExtraProp:IsValid() then info.ExtraProp = self.ExtraProp:EntIndex() end return info end function ENT:ApplyDupeInfo(ply, ent, info, GetEntByID) self.BaseClass.ApplyDupeInfo(self, ply, ent, info, GetEntByID) self.WeldEntity = GetEntByID(info.WeldEntity) self.ExtraProp = GetEntByID(info.ExtraProp) if self.WeldEntity and self.Inputs.Grab.Value ~= 0 then if not self.Weld and self.trace~=nil then self.Weld = constraint.Weld(self, self.trace, 0, 0, self.WeldStrength) self.Weld.Type = "" --prevents the duplicator from making this weld end if IsValid(self.ExtraProp) then self.ExtraPropWeld = constraint.Weld(self.ExtraProp, self.WeldEntity, 0, 0, self.WeldStrength) self.ExtraPropWeld.Type = "" --prevents the duplicator from making this weld end if self.Gravity then self.WeldEntity:GetPhysicsObject():EnableGravity(false) end if self.Weld then self:SetColor(Color(255, 0, 0, self:GetColor().a)) Wire_TriggerOutput(self, "Holding", 1) Wire_TriggerOutput(self, "Grabbed Entity", self.WeldEntity) else self:ResetGrab() end end end -- Free Fall's Owner Check Code function ENT:CheckOwner(ent) ply = self:GetPlayer() hasCPPI = istable( CPPI ) hasEPS = istable( eps ) hasPropSecure = istable( PropSecure ) hasProtector = istable( Protector ) if not hasCPPI and not hasPropProtection and not hasSPropProtection and not hasEPS and not hasPropSecure and not hasProtector then return true end local t = hook.GetTable() local fn = t.CanTool.PropProtection hasPropProtection = isfunction( fn ) if hasPropProtection then -- We're going to get the function we need now. It's local so this is a bit dirty local gi = debug.getinfo( fn ) for i=1, gi.nups do local k, v = debug.getupvalue( fn, i ) if k == "Appartient" then propProtectionFn = v end end end local fn = t.CanTool[ "SPropProtection.EntityRemoved" ] hasSPropProtection = isfunction( fn ) if hasSPropProtection then local gi = debug.getinfo( fn ) for i=1, gi.nups do local k, v = debug.getupvalue( fn, i ) if k == "SPropProtection" then SPropProtectionFn = v.PlayerCanTouch end end end local owns if hasCPPI then owns = ent:CPPICanPhysgun( ply ) elseif hasPropProtection then -- Chaussette's Prop Protection (preferred over PropSecure) owns = propProtectionFn( ply, ent ) elseif hasSPropProtection then -- Simple Prop Protection by Spacetech if ent:GetNetworkedString( "Owner" ) ~= "" then -- So it doesn't give an unowned prop owns = SPropProtectionFn( ply, ent ) else owns = false end elseif hasEPS then -- EPS owns = eps.CanPlayerTouch( ply, ent ) elseif hasPropSecure then -- PropSecure owns = PropSecure.IsPlayers( ply, ent ) elseif hasProtector then -- Protector owns = Protector.Owner( ent ) == ply:UniqueID() end return owns end duplicator.RegisterEntityClass("gmod_wire_grabber", WireLib.MakeWireEnt, "Data", "Range", "Gravity")
Fixed Adv. Duping the Grabber
Fixed Adv. Duping the Grabber It assumed the entity was within reach of the tracer when it was duping. The opposite is often true. Fixes: http://errors.garrysmod.com/error/3316845705/
Lua
apache-2.0
wiremod/wire,NezzKryptic/Wire,CaptainPRICE/wire,dvdvideo1234/wire,plinkopenguin/wiremod,immibis/wiremod,notcake/wire,thegrb93/wire,rafradek/wire,Grocel/wire,garrysmodlua/wire,Python1320/wire,mms92/wire,mitterdoo/wire,sammyt291/wire,bigdogmat/wire
d5382fcc74a0f79d0e4f93bde4d2abf5b45f2e5f
util/xmppstream.lua
util/xmppstream.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 lxp = require "lxp"; local st = require "util.stanza"; local tostring = tostring; local t_insert = table.insert; local t_concat = table.concat; local default_log = require "util.logger".init("xmppstream"); local error = error; module "xmppstream" local new_parser = lxp.new; local ns_prefixes = { ["http://www.w3.org/XML/1998/namespace"] = "xml"; }; local xmlns_streams = "http://etherx.jabber.org/streams"; local ns_separator = "\1"; local ns_pattern = "^([^"..ns_separator.."]*)"..ns_separator.."?(.*)$"; _M.ns_separator = ns_separator; _M.ns_pattern = ns_pattern; function new_sax_handlers(session, stream_callbacks) local xml_handlers = {}; local log = session.log or default_log; local cb_streamopened = stream_callbacks.streamopened; local cb_streamclosed = stream_callbacks.streamclosed; local cb_error = stream_callbacks.error or function(session, e) error("XML stream error: "..tostring(e)); end; local cb_handlestanza = stream_callbacks.handlestanza; local stream_ns = stream_callbacks.stream_ns or xmlns_streams; local stream_tag = stream_ns..ns_separator..(stream_callbacks.stream_tag or "stream"); local stream_error_tag = stream_ns..ns_separator..(stream_callbacks.error_tag or "error"); local stream_default_ns = stream_callbacks.default_ns; local chardata, stanza = {}; local non_streamns_depth = 0; function xml_handlers:StartElement(tagname, attr) if stanza and #chardata > 0 then -- We have some character data in the buffer stanza:text(t_concat(chardata)); chardata = {}; end local curr_ns,name = tagname:match(ns_pattern); if name == "" then curr_ns, name = "", curr_ns; end if curr_ns ~= stream_default_ns or non_streamns_depth > 0 then attr.xmlns = curr_ns; non_streamns_depth = non_streamns_depth + 1; end -- FIXME !!!!! for i=1,#attr do local k = attr[i]; attr[i] = nil; local ns, nm = k:match(ns_pattern); if nm ~= "" then ns = ns_prefixes[ns]; if ns then attr[ns..":"..nm] = attr[k]; attr[k] = nil; end end end if not stanza then --if we are not currently inside a stanza if session.notopen then if tagname == stream_tag then non_streamns_depth = 0; if cb_streamopened then cb_streamopened(session, attr); end else -- Garbage before stream? cb_error(session, "no-stream"); end return; end if curr_ns == "jabber:client" and name ~= "iq" and name ~= "presence" and name ~= "message" then cb_error(session, "invalid-top-level-element"); end stanza = st.stanza(name, attr); else -- we are inside a stanza, so add a tag stanza:tag(name, attr); end end function xml_handlers:CharacterData(data) if stanza then t_insert(chardata, data); end end function xml_handlers:EndElement(tagname) if non_streamns_depth > 0 then non_streamns_depth = non_streamns_depth - 1; end if stanza then if #chardata > 0 then -- We have some character data in the buffer stanza:text(t_concat(chardata)); chardata = {}; end -- Complete stanza local last_add = stanza.last_add; if not last_add or #last_add == 0 then if tagname ~= stream_error_tag then cb_handlestanza(session, stanza); else cb_error(session, "stream-error", stanza); end stanza = nil; else stanza:up(); end else if tagname == stream_tag then if cb_streamclosed then cb_streamclosed(session); end else local curr_ns,name = tagname:match(ns_pattern); if name == "" then curr_ns, name = "", curr_ns; end cb_error(session, "parse-error", "unexpected-element-close", name); end stanza, chardata = nil, {}; end end local function reset() stanza, chardata = nil, {}; end local function set_session(stream, new_session) session = new_session; log = new_session.log or default_log; end return xml_handlers, { reset = reset, set_session = set_session }; end function new(session, stream_callbacks) local handlers, meta = new_sax_handlers(session, stream_callbacks); local parser = new_parser(handlers, ns_separator); local parse = parser.parse; return { reset = function () parser = new_parser(handlers, ns_separator); parse = parser.parse; meta.reset(); end, feed = function (self, data) return parse(parser, data); end, set_session = meta.set_session; }; end return _M;
-- Prosody IM -- Copyright (C) 2008-2010 Matthew Wild -- Copyright (C) 2008-2010 Waqas Hussain -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local lxp = require "lxp"; local st = require "util.stanza"; local tostring = tostring; local t_insert = table.insert; local t_concat = table.concat; local default_log = require "util.logger".init("xmppstream"); local error = error; module "xmppstream" local new_parser = lxp.new; local ns_prefixes = { ["http://www.w3.org/XML/1998/namespace"] = "xml"; }; local xmlns_streams = "http://etherx.jabber.org/streams"; local ns_separator = "\1"; local ns_pattern = "^([^"..ns_separator.."]*)"..ns_separator.."?(.*)$"; function new_sax_handlers(session, stream_callbacks) local xml_handlers = {}; local log = session.log or default_log; local cb_streamopened = stream_callbacks.streamopened; local cb_streamclosed = stream_callbacks.streamclosed; local cb_error = stream_callbacks.error or function(session, e) error("XML stream error: "..tostring(e)); end; local cb_handlestanza = stream_callbacks.handlestanza; local stream_ns = stream_callbacks.stream_ns or xmlns_streams; local stream_tag = stream_ns..ns_separator..(stream_callbacks.stream_tag or "stream"); local stream_error_tag = stream_ns..ns_separator..(stream_callbacks.error_tag or "error"); local stream_default_ns = stream_callbacks.default_ns; local chardata, stanza = {}; local non_streamns_depth = 0; function xml_handlers:StartElement(tagname, attr) if stanza and #chardata > 0 then -- We have some character data in the buffer stanza:text(t_concat(chardata)); chardata = {}; end local curr_ns,name = tagname:match(ns_pattern); if name == "" then curr_ns, name = "", curr_ns; end if curr_ns ~= stream_default_ns or non_streamns_depth > 0 then attr.xmlns = curr_ns; non_streamns_depth = non_streamns_depth + 1; end -- FIXME !!!!! for i=1,#attr do local k = attr[i]; attr[i] = nil; local ns, nm = k:match(ns_pattern); if nm ~= "" then ns = ns_prefixes[ns]; if ns then attr[ns..":"..nm] = attr[k]; attr[k] = nil; end end end if not stanza then --if we are not currently inside a stanza if session.notopen then if tagname == stream_tag then non_streamns_depth = 0; if cb_streamopened then cb_streamopened(session, attr); end else -- Garbage before stream? cb_error(session, "no-stream"); end return; end if curr_ns == "jabber:client" and name ~= "iq" and name ~= "presence" and name ~= "message" then cb_error(session, "invalid-top-level-element"); end stanza = st.stanza(name, attr); else -- we are inside a stanza, so add a tag stanza:tag(name, attr); end end function xml_handlers:CharacterData(data) if stanza then t_insert(chardata, data); end end function xml_handlers:EndElement(tagname) if non_streamns_depth > 0 then non_streamns_depth = non_streamns_depth - 1; end if stanza then if #chardata > 0 then -- We have some character data in the buffer stanza:text(t_concat(chardata)); chardata = {}; end -- Complete stanza local last_add = stanza.last_add; if not last_add or #last_add == 0 then if tagname ~= stream_error_tag then cb_handlestanza(session, stanza); else cb_error(session, "stream-error", stanza); end stanza = nil; else stanza:up(); end else if tagname == stream_tag then if cb_streamclosed then cb_streamclosed(session); end else local curr_ns,name = tagname:match(ns_pattern); if name == "" then curr_ns, name = "", curr_ns; end cb_error(session, "parse-error", "unexpected-element-close", name); end stanza, chardata = nil, {}; end end local function reset() stanza, chardata = nil, {}; end local function set_session(stream, new_session) session = new_session; log = new_session.log or default_log; end return xml_handlers, { reset = reset, set_session = set_session }; end function new(session, stream_callbacks) local handlers, meta = new_sax_handlers(session, stream_callbacks); local parser = new_parser(handlers, ns_separator); local parse = parser.parse; return { reset = function () parser = new_parser(handlers, ns_separator); parse = parser.parse; meta.reset(); end, feed = function (self, data) return parse(parser, data); end, set_session = meta.set_session; }; end return _M;
util.xmppstream: Fix logger name.
util.xmppstream: Fix logger name.
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
4125629c807419d11159312801bb049754aca21c
chooseAP.lua
chooseAP.lua
-- had to chunk up sending of webpage, to deal with low amounts of memory on ESP-8266 devices -- surely a more elegant way to do it dofile("makeChooseAPHTML.lua") local SSID = nil local pass = nil local otherSSID = nil local errMsg = nil local savedNetwork = false local resetTimer = 15 -- for resetting the module after successfully connecting to chosen network -- lookup table for wifi.sta.status() local statusTable = {} -- statusTable[0] = "neither connected nor connecting" -- statusTable[1] = "still connecting" statusTable["2"] = "wrong password" statusTable["3"] = "didn\'t find the network you specified" statusTable["4"] = "failed to connect" -- statusTable[5] = "successfully connected" wifi.sta.disconnect() wifi.setmode(wifi.STATIONAP) print('wifi status: '..wifi.sta.status()) local cfg = {} cfg.ssid = "mysticalNetwork" cfg.pwd = "mystical5000" wifi.ap.config(cfg) local srv=net.createServer(net.TCP, 300) print("connect to \'"..cfg.ssid.."\", password \""..cfg.pwd.."\", ip "..wifi.ap.getip()) cfg = nil srv:listen(80,function(conn) conn:on("receive", function(client,request) print("recieve") local errMsg = nil local _, _, delete = string.find(request, "(deleteSaved=true)") if (delete~=nil) then file.remove('networks') errMsg = "<center><h2>Saved networks deleted.<\h2><\center>" end -- check if SSID and password have been submitted local connecting = false local _, _, SSID, pass = string.find(request, "SSID=(.+)%%0D%%0A&otherSSID=&password=(.*)") print(node.heap()) if (pass~=nil and pass~="") then if (string.len(pass)<8) then local pass = nil errMsg = "<center><h2 style=\"color:red\">Whoops! Password must be at least 8 characters.<\h2><\center>" end end if (SSID==nil) then _, _, SSID, pass = string.find(request, "SSID=&otherSSID=(.+)%%0D%%0A&password=(.*)") end print(request) local buf = ""; -- if password for network is nothing, any password should work if (SSID~=nil and pass~=nil) then if (pass == "") then pass = "aaaaaaaa" end print(SSID..', '..pass) -- TO-DO: add timeout for connection attempt local connectStatus = wifi.sta.status() print(connectStatus) sendHeader(client) tmr.alarm(5,500,0,function() buf = buf.."<center><h2 style=\"color:DarkGreen\">Connecting to "..tostring(SSID) buf = buf.."!</h2><br><h2>Please hold tight, we'll be back to you shortly.</h2></center></div></html>" client:send(buf) buf = "" end) tmr.alarm(1,1000,1, function() tmr.alarm(4,1000,0,function() wifi.sta.config(tostring(SSID),tostring(pass)) wifi.sta.connect() connecting = true end) connectStatus = wifi.sta.status() print("connecting") if (connectStatus ~= 1) then if (connectStatus == 5) then print("connected!") sendHeader(client) buf = buf.."<center><h2 style=\"color:DarkGreen\">Successfully connected to "..tostring(SSID).."!" buf = buf.."</h2><br><h2>Added to network list.</h2><br><h2>Resetting module in "..resetTimer.."s...</h1></center></div></html>" client:send(buf) buf = "" file.open("networks","a+") file.writeline(tostring(SSID)) file.writeline(tostring(pass)) file.close() savedNetwork = true tmr.alarm(2,resetTimer*1000,0,function() srv:close() node.restart() end) else print("couldn't connect") sendHeader(client) buf = buf.."<center><h2 style=\"color:red\">Whoops! Could not connect to "..tostring(SSID)..". "..statusTable[tostring(connectStatus)].."</h2><br></center>" client:send(buf) buf = "" sendForm(client, errMsg) end client:send(buf) collectgarbage() tmr.stop(1) client:close() end end) end buf = "" if(not connecting) then sendHeader(client) sendForm(client, errMsg) client:send(buf) buf = "" client:close() end collectgarbage() end) end) function sendWebpage(client, pageFile) file.open(pageFile) line = file.readline() line = string.sub(line,1,string.len(line)-1) --hack to remove CR/LF while (line~=nul) do client:send(line) if (line == "<div style = \"width:80%; margin: 0 auto\">") do -- add warning about password<8 characters if needed if (errMsg~=nil) then buf = buf.."<br><br>"..errMsg client:send(buf) end end line = file.readline() end file.close() end
--TODO: make the chooseAPHTML a package, so the errmsg can be passed --add delay before trying to connect? -- had to chunk up sending of webpage, to deal with low amounts of memory on ESP-8266 devices -- surely a more elegant way to do it dofile("makeChooseAPHTML.lua") local SSID = nil local pass = nil local otherSSID = nil local errMsg = nil local savedNetwork = false local resetTimer = 15 -- for resetting the module after successfully connecting to chosen network -- lookup table for wifi.sta.status() local statusTable = {} statusTable["0"] = "neither connected nor connecting" statusTable["1"] = "still connecting" statusTable["2"] = "wrong password" statusTable["3"] = "didn\'t find the network you specified" statusTable["4"] = "failed to connect" statusTable["5"] = "successfully connected" wifi.sta.disconnect() wifi.setmode(wifi.STATIONAP) print('wifi status: '..wifi.sta.status()) local cfg = {} cfg.ssid = "mysticalNetwork" cfg.pwd = "mystical5000" wifi.ap.config(cfg) local srv=net.createServer(net.TCP, 300) print("connect to \'"..cfg.ssid.."\", password \""..cfg.pwd.."\", ip "..wifi.ap.getip()) cfg = nil srv:listen(80,function(conn) conn:on("receive", function(client,request) print("recieve") local errMsg = nil local _, _, delete = string.find(request, "(deleteSaved=true)") if (delete~=nil) then file.remove('networks') errMsg = "<center><h2>Saved networks deleted.<\h2><\center>" end -- check if SSID and password have been submitted local connecting = false local _, _, SSID, pass = string.find(request, "SSID=(.+)%%0D%%0A&otherSSID=&password=(.*)") print(node.heap()) if (pass~=nil and pass~="") then if (string.len(pass)<8) then local pass = nil errMsg = "<center><h2 style=\"color:red\">Whoops! Password must be at least 8 characters.<\h2><\center>" end end if (SSID==nil) then _, _, SSID, pass = string.find(request, "SSID=&otherSSID=(.+)%%0D%%0A&password=(.*)") end print(request) local buf = ""; -- if password for network is nothing, any password should work if (SSID~=nil and pass~=nil) then if (pass == "") then pass = "aaaaaaaa" end print(SSID..', '..pass) -- TO-DO: add timeout for connection attempt local connectStatus = wifi.sta.status() print(connectStatus) tmr.alarm(5,500,0,function() sendWebpage(client, 'header.html') buf = buf.."<center><h2 style=\"color:DarkGreen\">Connecting to "..tostring(SSID) buf = buf.."!</h2><br><h2>Please hold tight, we'll be back to you shortly.</h2></center></div></html>" client:send(buf) buf = "" wifi.sta.config(tostring(SSID),tostring(pass)) wifi.sta.connect() connecting = true end) tmr.alarm(1,1000,1, function() connectStatus = wifi.sta.status() print("connecting") print(connectStatus) if (connectStatus ~= 1) then if (connectStatus == 5) then print("connected!") sendWebpage(client, 'header.html') buf = buf.."<center><h2 style=\"color:DarkGreen\">Successfully connected to "..tostring(SSID).."!" buf = buf.."</h2><br><h2>Added to network list.</h2><br><h2>Resetting module in "..resetTimer.."s...</h1></center></div></html>" client:send(buf) buf = "" file.open("networks","a+") file.writeline(tostring(SSID)) file.writeline(tostring(pass)) file.close() savedNetwork = true tmr.alarm(2,resetTimer*1000,0,function() srv:close() node.restart() end) else print("couldn't connect") buf = buf.."<center><h2 style=\"color:red\">Whoops! Could not connect to "..tostring(SSID)..". "..statusTable[tostring(connectStatus)].."</h2><br></center>" buf = buf.."<form align=\"center\" method=\"POST\">" buf = buf.."<input type=\"hidden\" name=\"reloadNets\" value=\"true\">" buf = buf.."<input type=\"submit\" value=\"Re-scan networks\" style=\"font-size:30pt\">" buf = buf.."</form>" buf = buf.."</div>" buf = buf.."</html>" client:send(buf) buf = "" end client:send(buf) collectgarbage() tmr.stop(1) client:close() end end) end buf = "" if(not connecting) then sendWebpage(client, "chooseAP.html") client:send(buf) buf = "" client:close() end collectgarbage() end) end) function sendWebpage(client, pageFile) file.open(pageFile) line = file.readline() line = string.sub(line,1,string.len(line)-1) --hack to remove CR/LF while (line~=nul) do client:send(line) if (line == "<div style = \"width:80%; margin: 0 auto\">") then -- add warning about password<8 characters if needed if (errMsg~=nil) then buf = buf.."<br><br>"..errMsg client:send(buf) end end line = file.readline() end file.close() end
fixing sendheader function
fixing sendheader function
Lua
mit
wordsforthewise/ESP-8266_network-connect
21c3e193f88a5b99d1e83887991163e4ff127bed
src/main/resources/std/coroutine.lua
src/main/resources/std/coroutine.lua
-- Copyright (c) 2018. tangzx([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); you may not -- use this file except in compliance with the License. You may obtain a copy of -- the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -- WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -- License for the specific language governing permissions and limitations under -- the License. coroutine = {} --- --- Creates a new coroutine, with body `f`. `f` must be a Lua function. Returns --- this new coroutine, an object with type `"thread"`. ---@return thread function coroutine.create(f) end --- --- Returns true when the running coroutine can yield. --- A running coroutine is yieldable if it is not the main thread and it is not --- inside a non-yieldable C function. ---@return boolean function coroutine.isyieldable() end --- --- Starts or continues the execution of coroutine `co`. The first time you --- resume a coroutine, it starts running its body. The values `val1`, ... --- are passed as the arguments to the body function. If the coroutine has --- yielded, `resume` restarts it; the values `val1`, ... are passed as the --- results from the yield. --- --- If the coroutine runs without any errors, `resume` returns **true** plus any --- values passed to `yield` (when the coroutine yields) or any values returned --- by the body function (when the coroutine terminates). If there is any error, --- `resume` returns **false** plus the error message. ---@param co thread function coroutine.resume(co, val1, ...) end --- --- Returns the running coroutine plus a boolean, true when the running --- coroutine is the main one. ---@return thread function coroutine.running() end --- --- Returns the status of coroutine `co`, as a string: "`running`", if the --- coroutine is running (that is, it called `status`); "`suspended`", if the --- coroutine is suspended in a call to `yield`, or if it has not started running --- yet; "`normal`" if the coroutine is active but not running (that is, it has --- resumed another coroutine); and "`dead`" if the coroutine has finished its --- body function, or if it has stopped with an error. ---@param co thread ---@return string function coroutine.status(co) end --- --- Creates a new coroutine, with body `f`. `f` must be a Lua function. Returns --- a function that resumes the coroutine each time it is called. Any arguments --- passed to the function behave as the extra arguments to `resume`. Returns --- the same values returned by `resume`, except the first --- boolean. In case of error, propagates the error. function coroutine.wrap(f) end --- --- Suspends the execution of the calling coroutine. Any arguments to `yield` are --- passed as extra results to `resume`. function coroutine.yield(...) end
-- Copyright (c) 2018. tangzx([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); you may not -- use this file except in compliance with the License. You may obtain a copy of -- the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -- WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -- License for the specific language governing permissions and limitations under -- the License. coroutine = {} --- --- Creates a new coroutine, with body `f`. `f` must be a Lua function. Returns --- this new coroutine, an object with type `"thread"`. ---@param f thread ---@return thread function coroutine.create(f) end --- --- Returns true when the running coroutine can yield. --- --- A running coroutine is yieldable if it is not the main thread and it is not --- inside a non-yieldable C function. ---@return boolean function coroutine.isyieldable() end --- --- Starts or continues the execution of coroutine `co`. The first time you --- resume a coroutine, it starts running its body. The values `val1`, ... --- are passed as the arguments to the body function. If the coroutine has --- yielded, `resume` restarts it; the values `val1`, ... are passed as the --- results from the yield. --- --- If the coroutine runs without any errors, `resume` returns **true** plus any --- values passed to `yield` (when the coroutine yields) or any values returned --- by the body function (when the coroutine terminates). If there is any error, --- `resume` returns **false** plus the error message. ---@param co thread ---@param optional val1 string ---@return boolean function coroutine.resume(co, val1, ...) end --- --- Returns the running coroutine plus a boolean, true when the running --- coroutine is the main one. ---@return thread|boolean function coroutine.running() end --- --- Returns the status of coroutine `co`, as a string: "`running`", if the --- coroutine is running (that is, it called `status`); "`suspended`", if the --- coroutine is suspended in a call to `yield`, or if it has not started --- running yet; "`normal`" if the coroutine is active but not running (that --- is, it has resumed another coroutine); and "`dead`" if the coroutine has --- finished its body function, or if it has stopped with an error. ---@param co thread ---@return string function coroutine.status(co) end --- --- Creates a new coroutine, with body `f`. `f` must be a Lua function. Returns --- a function that resumes the coroutine each time it is called. Any arguments --- passed to the function behave as the extra arguments to `resume`. Returns --- the same values returned by `resume`, except the first --- boolean. In case of error, propagates the error. ---@param f fun():thread ---@return function function coroutine.wrap(f) end --- --- Suspends the execution of the calling coroutine. Any arguments to `yield` --- are passed as extra results to `resume`. function coroutine.yield(...) end
fix params, return types and doc
fix params, return types and doc Check params and return types for rightness.
Lua
apache-2.0
tangzx/IntelliJ-EmmyLua,EmmyLua/IntelliJ-EmmyLua,EmmyLua/IntelliJ-EmmyLua,tangzx/IntelliJ-EmmyLua,EmmyLua/IntelliJ-EmmyLua,EmmyLua/IntelliJ-EmmyLua,tangzx/IntelliJ-EmmyLua,tangzx/IntelliJ-EmmyLua
ed3f3e1b1385dd8a3e870186e91d2a1b3ace21c4
gm/items/id_93_medal.lua
gm/items/id_93_medal.lua
-- UPDATE common SET com_script='gm.items.id_93_medal' WHERE com_itemid=93; module("gm.items.id_93_medal", package.seeall) function UseItemWithField(User,SourceItem, TargetPos, Counter, Param) Counter=1 * string.format("%u",User.lastSpokenText); if (SourceItem.data==0) then User:inform("#w Creating monster with ID "..Counter); world:createMonster(Counter,TargetPos,20); elseif (SourceItem.data==1) then User:inform("#w Creating monster with ID "..Counter+250); world:createMonster(Counter+250,TargetPos,20); elseif (SourceItem.data==2) then User:inform("#w Creating monster with ID "..Counter+500); world:createMonster(Counter+500,TargetPos,20); elseif (SourceItem.data==3) then world:gfx(Counter,TargetPos); elseif (SourceItem.data==4) then world:makeSound(Counter,TargetPos); elseif (SourceItem.data==5) then User:setAttrib("racetyp",Counter); else User:inform("Data 0;1;2 : Monsters - Data 3 : GFX - Data 4: SFX - Data 5: Race change"); end end function UseItem(User,SourceItem,TargetItem,Counter,Param) --Counter=1 * string.format("%u",User.lastSpokenText); -- world:createMonster(Counter,position(User.pos.x+1, User.pos.y+1,User.pos.z),20); if ((SourceItem.data==8) and ( (User.id==833275147) or User.id==666) ) then UndeadEvent(User.pos); else if (gm.items.id_99_lockpicks.firsttime == nil) then User:inform("firsttime of lockpicks is set to NIL"); else User:inform("firsttime of lockpicks is set to " .. gm.items.id_99_lockpicks.firsttime); end UseItemWithField(User,SourceItem,position(User.pos.x,User.pos.y+1,User.pos.z),Counter,Param); end end
-- UPDATE common SET com_script='gm.items.id_93_medal' WHERE com_itemid=93; require("base.common") module("gm.items.id_93_medal", package.seeall) function UseItemWithField(User,SourceItem, TargetPos, Counter, Param) local a, _, number = string.find(User.lastSpokenText, "(%d+)"); Counter = 1 * number; if (SourceItem.data==0) then User:inform("#w Creating monster with ID "..Counter); world:createMonster(Counter,TargetPos,20); elseif (SourceItem.data==1) then User:inform("#w Creating monster with ID "..Counter+250); world:createMonster(Counter+250,TargetPos,20); elseif (SourceItem.data==2) then User:inform("#w Creating monster with ID "..Counter+500); world:createMonster(Counter+500,TargetPos,20); elseif (SourceItem.data==3) then world:gfx(Counter,TargetPos); elseif (SourceItem.data==4) then world:makeSound(Counter,TargetPos); elseif (SourceItem.data==5) then User:setAttrib("racetyp",Counter); else User:inform("Data 0;1;2 : Monsters - Data 3 : GFX - Data 4: SFX - Data 5: Race change"); end end function UseItem(User,SourceItem,TargetItem,Counter,Param) UseItemWithField(User,SourceItem,base.common.GetFrontPosition(User),Counter,Param); end
Fixing crash bug with medal (did not spawn any monsters)
Fixing crash bug with medal (did not spawn any monsters)
Lua
agpl-3.0
Illarion-eV/Illarion-Content,LaFamiglia/Illarion-Content,vilarion/Illarion-Content,KayMD/Illarion-Content,Baylamon/Illarion-Content
1f47a5b918c97867d71fd9371451de55c2c648b1
spec/02-kong_storage_adapter_spec.lua
spec/02-kong_storage_adapter_spec.lua
local helpers = require "spec.helpers" local utils = require "kong.tools.utils" function get_sid_from_cookie(cookie) local cookie_parts = utils.split(cookie, "; ") return utils.split(utils.split(cookie_parts[1], "|")[1], "=")[2] end for _, strategy in helpers.each_strategy() do describe("Plugin: Session (kong storage adapter) [#" .. strategy .. "]", function() local client, bp, db lazy_setup(function() bp, db = helpers.get_db_utils(strategy, { "sessions", "plugins", "routes", "services", "consumers", "keyauth_credentials", }) local route1 = bp.routes:insert { paths = {"/test1"}, hosts = {"httpbin.org"} } local route2 = bp.routes:insert { paths = {"/test2"}, hosts = {"httpbin.org"} } assert(bp.plugins:insert { name = "session", route = { id = route1.id, }, config = { storage = "kong", secret = "ultra top secret session", } }) assert(bp.plugins:insert { name = "session", route = { id = route2.id, }, config = { secret = "super secret session secret", storage = "kong", cookie_renew = 600, cookie_lifetime = 604, } }) local consumer = bp.consumers:insert { username = "coop" } bp.keyauth_credentials:insert { key = "kong", consumer = { id = consumer.id }, } local anonymous = bp.consumers:insert { username = "anon" } bp.plugins:insert { name = "key-auth", route = { id = route1.id, }, config = { anonymous = anonymous.id } } bp.plugins:insert { name = "key-auth", route = { id = route2.id, }, config = { anonymous = anonymous.id } } bp.plugins:insert { name = "request-termination", consumer = { id = anonymous.id, }, config = { status_code = 403, message = "So it goes.", } } assert(helpers.start_kong { plugins = "bundled, session", database = strategy, nginx_conf = "spec/fixtures/custom_nginx.template", }) end) lazy_teardown(function() helpers.stop_kong() end) before_each(function() client = helpers.proxy_ssl_client() end) after_each(function() if client then client:close() end end) describe("kong adapter - ", function() it("kong adapter stores consumer", function() local res, cookie local request = { method = "GET", path = "/test1/status/200", headers = { host = "httpbin.org", }, } -- make sure the anonymous consumer can't get in (request termination) res = assert(client:send(request)) assert.response(res).has.status(403) -- make a request with a valid key, grab the cookie for later request.headers.apikey = "kong" res = assert(client:send(request)) assert.response(res).has.status(200) cookie = assert.response(res).has.header("Set-Cookie") ngx.sleep(2) -- use the cookie without the key to ensure cookie still lets them in request.headers.apikey = nil request.headers.cookie = cookie res = assert(client:send(request)) assert.response(res).has.status(200) -- one more time to ensure session was not destroyed or errored out res = assert(client:send(request)) assert.response(res).has.status(200) -- make sure it's in the db local sid = get_sid_from_cookie(cookie) assert.equal(sid, db.sessions:select_by_session_id(sid).session_id) end) it("renews cookie", function() local res, cookie local request = { method = "GET", path = "/test2/status/200", headers = { host = "httpbin.org", }, } local function send_requests(request, number, step) local cookie = request.headers.cookie for i = 1, number do request.headers.cookie = cookie res = assert(client:send(request)) assert.response(res).has.status(200) cookie = res.headers['Set-Cookie'] or cookie ngx.sleep(step) end end -- make sure the anonymous consumer can't get in (request termination) res = assert(client:send(request)) assert.response(res).has.status(403) -- make a request with a valid key, grab the cookie for later request.headers.apikey = "kong" res = assert(client:send(request)) assert.response(res).has.status(200) cookie = assert.response(res).has.header("Set-Cookie") ngx.sleep(2) -- use the cookie without the key to ensure cookie still lets them in request.headers.apikey = nil request.headers.cookie = cookie res = assert(client:send(request)) assert.response(res).has.status(200) -- renewal period, make sure requests still come through and -- if set-cookie header comes through, attach it to subsequent requests send_requests(request, 5, 0.5) end) it("destroys session on logout", function() local res, cookie local request = { method = "GET", path = "/test2/status/200", headers = { host = "httpbin.org", }, } -- make sure the anonymous consumer can't get in (request termination) res = assert(client:send(request)) assert.response(res).has.status(403) -- make a request with a valid key, grab the cookie for later request.headers.apikey = "kong" res = assert(client:send(request)) assert.response(res).has.status(200) cookie = assert.response(res).has.header("Set-Cookie") ngx.sleep(2) -- use the cookie without the key to ensure cookie still lets them in request.headers.apikey = nil request.headers.cookie = cookie res = assert(client:send(request)) assert.response(res).has.status(200) -- session should be in the table initially local sid = get_sid_from_cookie(cookie) assert.equal(sid, db.sessions:select_by_session_id(sid).session_id) -- logout request res = assert(client:send({ method = "DELETE", path = "/test2/status/200?session_logout=true", headers = { cookie = cookie, host = "httpbin.org", } })) assert.response(res).has.status(200) local found, err = db.sessions:select_by_session_id(sid) -- logged out, no sessions should be in the table, without errors assert.is_nil(found) assert.is_nil(err) end) end) end) end
local helpers = require "spec.helpers" local utils = require "kong.tools.utils" local function get_sid_from_cookie(cookie) local cookie_parts = utils.split(cookie, "; ") return utils.split(utils.split(cookie_parts[1], "|")[1], "=")[2] end for _, strategy in helpers.each_strategy() do describe("Plugin: Session (kong storage adapter) [#" .. strategy .. "]", function() local client, bp, db lazy_setup(function() bp, db = helpers.get_db_utils(strategy, { "sessions", "plugins", "routes", "services", "consumers", "keyauth_credentials", }) local route1 = bp.routes:insert { paths = {"/test1"}, hosts = {"httpbin.org"} } local route2 = bp.routes:insert { paths = {"/test2"}, hosts = {"httpbin.org"} } assert(bp.plugins:insert { name = "session", route = { id = route1.id, }, config = { storage = "kong", secret = "ultra top secret session", } }) assert(bp.plugins:insert { name = "session", route = { id = route2.id, }, config = { secret = "super secret session secret", storage = "kong", cookie_renew = 600, cookie_lifetime = 604, } }) local consumer = bp.consumers:insert { username = "coop" } bp.keyauth_credentials:insert { key = "kong", consumer = { id = consumer.id }, } local anonymous = bp.consumers:insert { username = "anon" } bp.plugins:insert { name = "key-auth", route = { id = route1.id, }, config = { anonymous = anonymous.id } } bp.plugins:insert { name = "key-auth", route = { id = route2.id, }, config = { anonymous = anonymous.id } } bp.plugins:insert { name = "request-termination", consumer = { id = anonymous.id, }, config = { status_code = 403, message = "So it goes.", } } assert(helpers.start_kong { plugins = "bundled, session", database = strategy, nginx_conf = "spec/fixtures/custom_nginx.template", }) end) lazy_teardown(function() helpers.stop_kong() end) before_each(function() client = helpers.proxy_ssl_client() end) after_each(function() if client then client:close() end end) describe("kong adapter - ", function() it("kong adapter stores consumer", function() local res, cookie local request = { method = "GET", path = "/test1/status/200", headers = { host = "httpbin.org", }, } -- make sure the anonymous consumer can't get in (request termination) res = assert(client:send(request)) assert.response(res).has.status(403) -- make a request with a valid key, grab the cookie for later request.headers.apikey = "kong" res = assert(client:send(request)) assert.response(res).has.status(200) cookie = assert.response(res).has.header("Set-Cookie") ngx.sleep(2) -- use the cookie without the key to ensure cookie still lets them in request.headers.apikey = nil request.headers.cookie = cookie res = assert(client:send(request)) assert.response(res).has.status(200) -- one more time to ensure session was not destroyed or errored out res = assert(client:send(request)) assert.response(res).has.status(200) -- make sure it's in the db local sid = get_sid_from_cookie(cookie) assert.equal(sid, db.sessions:select_by_session_id(sid).session_id) end) it("renews cookie", function() local res, cookie local request = { method = "GET", path = "/test2/status/200", headers = { host = "httpbin.org", }, } local function send_requests(request, number, step) cookie = request.headers.cookie for _ = 1, number do request.headers.cookie = cookie res = assert(client:send(request)) assert.response(res).has.status(200) cookie = res.headers['Set-Cookie'] or cookie ngx.sleep(step) end end -- make sure the anonymous consumer can't get in (request termination) res = assert(client:send(request)) assert.response(res).has.status(403) -- make a request with a valid key, grab the cookie for later request.headers.apikey = "kong" res = assert(client:send(request)) assert.response(res).has.status(200) cookie = assert.response(res).has.header("Set-Cookie") ngx.sleep(2) -- use the cookie without the key to ensure cookie still lets them in request.headers.apikey = nil request.headers.cookie = cookie res = assert(client:send(request)) assert.response(res).has.status(200) -- renewal period, make sure requests still come through and -- if set-cookie header comes through, attach it to subsequent requests send_requests(request, 5, 0.5) end) it("destroys session on logout", function() local res, cookie local request = { method = "GET", path = "/test2/status/200", headers = { host = "httpbin.org", }, } -- make sure the anonymous consumer can't get in (request termination) res = assert(client:send(request)) assert.response(res).has.status(403) -- make a request with a valid key, grab the cookie for later request.headers.apikey = "kong" res = assert(client:send(request)) assert.response(res).has.status(200) cookie = assert.response(res).has.header("Set-Cookie") ngx.sleep(2) -- use the cookie without the key to ensure cookie still lets them in request.headers.apikey = nil request.headers.cookie = cookie res = assert(client:send(request)) assert.response(res).has.status(200) -- session should be in the table initially local sid = get_sid_from_cookie(cookie) assert.equal(sid, db.sessions:select_by_session_id(sid).session_id) -- logout request res = assert(client:send({ method = "DELETE", path = "/test2/status/200?session_logout=true", headers = { cookie = cookie, host = "httpbin.org", } })) assert.response(res).has.status(200) local found, err = db.sessions:select_by_session_id(sid) -- logged out, no sessions should be in the table, without errors assert.is_nil(found) assert.is_nil(err) end) end) end) end
test(lint) fix linting issues
test(lint) fix linting issues
Lua
apache-2.0
Kong/kong,Kong/kong,Kong/kong
83a1cf3761f27946f2c9dae498a95a489b91ca4a
helper.lua
helper.lua
-- Helper Module -- local setup = require "setup" local helper = {} helper.mainMenu = { h = "Help", s = "Initial Setup", n = "Search by Name of Script", c = "Search by Category", b = "Create script.db backup", q = "Exit"} helper.searchMenu ={ s = "Search by Name", b = "Main Menu", q = "Exit"} function helper.banner() banner=[[ _ _ _____ _____ _ | \ | |/ ___|| ___| | | | \| |\ `--. | |__ __ _ _ __ ___ | |__ | . ` | `--. \| __| / _` || '__| / __|| '_ \ | |\ |/\__/ /| |___ | (_| || | | (__ | | | | \_| \_/\____/ \____/ \__,_||_| \___||_| |_| ]] return banner end function helper.menu(menulist) print('\27[1m \27[36m'..helper.banner()..'\27[21m \27[0m') for key,value in pairs(menulist) do print("("..key..") "..value) end return menulist end function searchMenu() io.write('\n What do you want to do? : ') local action = io.read() if action == "q" then os.exit() elseif action == "b" then os.execute( "clear" ) helper.menu(helper.mainMenu) helper.Main() elseif action == "s" then print("Ready for Search") else os.execute() end end function helper.Main() io.write('\n What do you want to do? : ') local action = io.read() if action == "q" then os.exit() elseif action == "s" then os.execute( "clear" ) setup.install(helper.banner()) elseif action == "n" then os.execute( "clear" ) helper.menu(helper.searchMenu) searchMenu() elseif action == "b" then setup.createBackup(helper.banner()) os.execute( "clear" ) helper.menu(mainMenu) helper.Main() else os.exit() end end return helper
-- Helper Module -- local setup = require "setup" local helper = {} helper.mainMenu = {"Help (h)", "Initial Setup (i)", "Search by Name of Script (s)", "Search by Category (c)", "Create script.db backup (b)", "Exit (q)"} helper.searchMenu ={ "Search by Name (s)", "Main Menu (b)", "Exit (q)"} function helper.banner() banner=[[ _ _ _____ _____ _ | \ | |/ ___|| ___| | | | \| |\ `--. | |__ __ _ _ __ ___ | |__ | . ` | `--. \| __| / _` || '__| / __|| '_ \ | |\ |/\__/ /| |___ | (_| || | | (__ | | | | \_| \_/\____/ \____/ \__,_||_| \___||_| |_| ]] return banner 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 searchMenu() io.write('\n What do you want to do? : ') local action = io.read() if action == "q" or action == "3" then os.exit() elseif action == "b" or action == "2" then os.execute( "clear" ) helper.menu(helper.mainMenu) helper.Main() elseif action == "s" or action == "1" then print("Ready for Search") else os.execute() end end function helper.Main() io.write('\n What do you want to do? : ') local action = io.read() if action == "q" or action == "6" 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" ) helper.menu(helper.searchMenu) searchMenu() elseif action == "b" or action == "4" then setup.createBackup(helper.banner()) os.execute( "clear" ) helper.menu(mainMenu) helper.Main() else os.exit() end end return helper
Fixing Menu List
Fixing Menu List
Lua
apache-2.0
JKO/nsearch,JKO/nsearch
3af3e404b0f70b7b64c5bb3eeb77a025059d5ff1
base/lookat.lua
base/lookat.lua
-- Default look-at script module("base.lookat", package.seeall) -- init german descriptions GenericQualDe={"perfekt","exzellent","sehr gut","gut","normal","mig","schlecht","sehr schlecht","schrecklich","furchtbar"}; GenericDuraDe={}; GenericDuraDe[1]={"nagelneu" ,"neu" ,"fast neu","gebraucht","leicht abgenutzt","abgenutzt","sehr abgenutzt","alt" ,"rostig" ,"klapprig" }; GenericDuraDe[2]={"nagelneu" ,"neu" ,"fast neu","gebraucht","leicht abgenutzt","abgenutzt","sehr abgenutzt","alt" ,"morsch" ,"zerfallend"}; GenericDuraDe[3]={"nagelneu" ,"neu" ,"fast neu","gebraucht","leicht abgenutzt","abgenutzt","sehr abgenutzt","alt" ,"fadenscheinig","zerfetzt" }; GenericDuraDe[4]={"funkelnd" ,"strahlend","glnzend","gebraucht","angekratzt", "zerkratzt","matt", "alt" ,"stumpf", "brchig" }; -- init english descriptions GenericQualEn={"perfect","excellent","very good","good","normal","average","bad","very bad","awful","horrible"}; GenericDuraEn={}; GenericDuraEn[1]={"brand new","new" ,"almost new","used","slightly scraped" ,"scraped" ,"highly scraped" ,"old","rusty" ,"corroded" }; GenericDuraEn[2]={"brand new","new" ,"almost new","used","slightly scratched","scratched","highly scratched","old","rotten" ,"nearly decayed"}; GenericDuraEn[3]={"brand new","new" ,"almost new","used","slightly torn" ,"torn" ,"highly torn" ,"old","threadbare","torn" }; GenericDuraEn[4]={"sparkling","shiny" ,"glittery","used","slightly scraped","scraped" ,"highly scraped" ,"old","tarnished" ,"fragile"}; GenericDuraLm={90,80,70,60,50,40,30,15,0}; NONE = 0; METAL = 1; WOOD = 2; CLOTH = 3; JEWELERY = 4; function GenerateLookAt(user, item, material) if (user == nil) then debug("Sanity check failed, no valid character supplied."); return; end; if (item == nil) then debug("Sanity check failed, no valid item supplied."); return; end; if ((material < NONE) or (material > JEWELERY)) then debug("Sanity check failed, no valid material supplied."); end; local itemCommon = world:getItemStatsFromId(item.id); local lookAt = ItemLookAt(); local isGerman = (user:getPlayerLanguage() == Player.german); local usedName; if (isGerman) then usedName = item:getData("nameDe"); else usedName = item:getData("nameEn"); end; if (usedName == nil) then usedName = world:getItemName(item.id, user:getPlayerLanguage()); end; lookAt.name = usedName; local rarenessData = item:getData("rareness"); if (rarenessData == nil) then lookAt.rareness = ItemLookAt.commonItem; else local value = tonumber(rarenessData); if (value ~= nil) then lookAt.rareness = value; end; end; local usedDescription; if (isGerman) then usedDescription = item:getData("descriptionDe"); else usedDescription = item:getData("descriptionEn"); end; if (usedDescription ~= nil) then lookAt.description = usedDescription; end; if ((itemCommon.AgeingSpeed < 255) and (material > NONE)) then local craftedByData = item:getData("craftedBy"); if (craftedByData ~= nil) then lookAt.craftedBy = craftedByData; end; lookAt.weight = itemCommon.Weight; lookAt.worth = itemCommon.Worth; local itemDura = math.mod(item.quality, 100); local itemQual = (item.quality - itemDura) / 100; local duraIndex; for i, duraLimit in pairs(GenericDuraLm) do if (itemDura >= duraLimit) then duraIndex = i; break; end end if (isGerman) then lookAt.qualityText = GenericQualDe[itemQual]; lookAt.durabilityText = GenericDuraDe[material][duraIndex]; else lookAt.qualityText = GenericQualEn[itemData]; lookAt.durabilityText = GenericDuraEn[material][duraIndex]; end; lookAt.durabilityValue = itemDura + 1; lookAt.diamondLevel = GetGemLevel(item, "magicalDiamond"); lookAt.emeraldLevel = GetGemLevel(item, "magicalEmerald"); lookAt.rubyLevel = GetGemLevel(item, "magicalRuby"); lookAt.sapphireLevel = GetGemLevel(item, "magicalSapphire"); lookAt.amethystLevel = GetGemLevel(item, "magicalAmethyst"); lookAt.obsidianLevel = GetGemLevel(item, "magicalObsidian"); lookAt.topazLevel = GetGemLevel(item, "magicalTopaz"); lookAt.bonus = 0; end; return lookAt; end; function GetGemLevel(item, dataEntry) local dataEntry = item:getData(dataEntry); if (dataEntry == nil) then return 0; end; local value = tonumber(dataEntry); if (value == nil) then return 0; end; if ((value < 0) or (value > 10)) then return 0; else return value; end; end; function GetItemDescription(User, Item, material, Weapon, Priest) return GenerateLookAt(User, Item, material); end;
-- Default look-at script module("base.lookat", package.seeall) -- init german descriptions GenericQualDe={"perfekt","exzellent","sehr gut","gut","normal","mig","schlecht","sehr schlecht","schrecklich","furchtbar"}; GenericDuraDe={}; GenericDuraDe[1]={"nagelneu" ,"neu" ,"fast neu","gebraucht","leicht abgenutzt","abgenutzt","sehr abgenutzt","alt" ,"rostig" ,"klapprig" }; GenericDuraDe[2]={"nagelneu" ,"neu" ,"fast neu","gebraucht","leicht abgenutzt","abgenutzt","sehr abgenutzt","alt" ,"morsch" ,"zerfallend"}; GenericDuraDe[3]={"nagelneu" ,"neu" ,"fast neu","gebraucht","leicht abgenutzt","abgenutzt","sehr abgenutzt","alt" ,"fadenscheinig","zerfetzt" }; GenericDuraDe[4]={"funkelnd" ,"strahlend","glnzend","gebraucht","angekratzt", "zerkratzt","matt", "alt" ,"stumpf", "brchig" }; -- init english descriptions GenericQualEn={"perfect","excellent","very good","good","normal","average","bad","very bad","awful","horrible"}; GenericDuraEn={}; GenericDuraEn[1]={"brand new","new" ,"almost new","used","slightly scraped" ,"scraped" ,"highly scraped" ,"old","rusty" ,"corroded" }; GenericDuraEn[2]={"brand new","new" ,"almost new","used","slightly scratched","scratched","highly scratched","old","rotten" ,"nearly decayed"}; GenericDuraEn[3]={"brand new","new" ,"almost new","used","slightly torn" ,"torn" ,"highly torn" ,"old","threadbare","torn" }; GenericDuraEn[4]={"sparkling","shiny" ,"glittery","used","slightly scraped","scraped" ,"highly scraped" ,"old","tarnished" ,"fragile"}; GenericDuraLm={90,80,70,60,50,40,30,15,0}; NONE = 0; METAL = 1; WOOD = 2; CLOTH = 3; JEWELERY = 4; function GenerateLookAt(user, item, material) if (user == nil) then debug("Sanity check failed, no valid character supplied."); return; end; if (item == nil) then debug("Sanity check failed, no valid item supplied."); return; end; if ((material < NONE) or (material > JEWELERY)) then debug("Sanity check failed, no valid material supplied."); end; local itemCommon = world:getItemStatsFromId(item.id); local lookAt = ItemLookAt(); local isGerman = (user:getPlayerLanguage() == Player.german); local usedName; if (isGerman) then usedName = item:getData("nameDe"); else usedName = item:getData("nameEn"); end; if ((usedName == nil) or (usedName == "")) then usedName = world:getItemName(item.id, user:getPlayerLanguage()); end; lookAt.name = usedName; local rarenessData = item:getData("rareness"); if (rarenessData == nil) then lookAt.rareness = ItemLookAt.commonItem; else local value = tonumber(rarenessData); if (value ~= nil) then lookAt.rareness = value; end; end; local usedDescription; if (isGerman) then usedDescription = item:getData("descriptionDe"); else usedDescription = item:getData("descriptionEn"); end; if ((usedDescription == nil) or (usedDescription == "")) then lookAt.description = usedDescription; end; if ((itemCommon.AgeingSpeed < 255) and (material > NONE)) then local craftedByData = item:getData("craftedBy"); if (craftedByData ~= nil) then lookAt.craftedBy = craftedByData; end; lookAt.weight = itemCommon.Weight; lookAt.worth = itemCommon.Worth; local itemDura = math.mod(item.quality, 100); local itemQual = (item.quality - itemDura) / 100; local duraIndex; for i, duraLimit in pairs(GenericDuraLm) do if (itemDura >= duraLimit) then duraIndex = i; break; end end if (isGerman) then lookAt.qualityText = GenericQualDe[itemQual]; lookAt.durabilityText = GenericDuraDe[material][duraIndex]; else lookAt.qualityText = GenericQualEn[itemData]; lookAt.durabilityText = GenericDuraEn[material][duraIndex]; end; lookAt.durabilityValue = itemDura + 1; lookAt.diamondLevel = GetGemLevel(item, "magicalDiamond"); lookAt.emeraldLevel = GetGemLevel(item, "magicalEmerald"); lookAt.rubyLevel = GetGemLevel(item, "magicalRuby"); lookAt.sapphireLevel = GetGemLevel(item, "magicalSapphire"); lookAt.amethystLevel = GetGemLevel(item, "magicalAmethyst"); lookAt.obsidianLevel = GetGemLevel(item, "magicalObsidian"); lookAt.topazLevel = GetGemLevel(item, "magicalTopaz"); lookAt.bonus = 0; end; return lookAt; end; function GetGemLevel(item, dataEntry) local dataEntry = item:getData(dataEntry); if (dataEntry == nil) then return 0; end; local value = tonumber(dataEntry); if (value == nil) then return 0; end; if ((value < 0) or (value > 10)) then return 0; else return value; end; end; function GetItemDescription(User, Item, material, Weapon, Priest) return GenerateLookAt(User, Item, material); end;
Trying to fix a problem with showing the title of a item
Trying to fix a problem with showing the title of a item
Lua
agpl-3.0
Baylamon/Illarion-Content,LaFamiglia/Illarion-Content,KayMD/Illarion-Content,Illarion-eV/Illarion-Content,vilarion/Illarion-Content
7fac3640cdefdd3769715b38cfc5a6974c8fcb9c
loot.lua
loot.lua
local mod = EPGP:NewModule("loot", "AceEvent-3.0", "AceTimer-3.0") local L = LibStub("AceLocale-3.0"):GetLocale("EPGP") local LLN = LibStub("LibLootNotify-1.0") local ignored_items = { [20725] = true, -- Nexus Crystal [22450] = true, -- Void Crystal [34057] = true, -- Abyss Crystal [29434] = true, -- Badge of Justice [40752] = true, -- Emblem of Heroism [40753] = true, -- Emblem of Valor [45624] = true, -- Emblem of Conquest [30311] = true, -- Warp Slicer [30312] = true, -- Infinity Blade [30313] = true, -- Staff of Disintegration [30314] = true, -- Phaseshift Bulwark [30316] = true, -- Devastation [30317] = true, -- Cosmic Infuser [30318] = true, -- Netherstrand Longbow [30319] = true, -- Nether Spikes [30320] = true, -- Bundle of Nether Spikes } local in_combat = false local loot_queue = {} local timer local function IsRLorML() if UnitInRaid("player") then local loot_method, ml_party_id, ml_raid_id = GetLootMethod() if loot_method == "master" and ml_party_id == 0 then return true end if loot_method ~= "master" and IsRaidLeader() then return true end end return false end function mod:PopLootQueue() if in_combat then return end if #loot_queue == 0 then if timer then self:CancelTimer(timer, true) timer = nil end return end local player, item = unpack(loot_queue[1]) -- In theory this should never happen. if not player or not item then tremove(loot_queue, 1) return end -- User is busy with other popup. if StaticPopup_Visible("EPGP_CONFIRM_GP_CREDIT") then return end tremove(loot_queue, 1) local itemName, itemLink, itemRarity, _, _, _, _, _, _, itemTexture = GetItemInfo(item) local r, g, b = GetItemQualityColor(itemRarity) local dialog = StaticPopup_Show("EPGP_CONFIRM_GP_CREDIT", player, "", { texture = itemTexture, name = itemName, color = {r, g, b, 1}, link = itemLink }) if dialog then dialog.name = player end end local function LootReceived(event_name, player, itemLink, quantity) if IsRLorML() and CanEditOfficerNote() then local itemID = tonumber(itemLink:match("item:(%d+)") or 0) if not itemID then return end local itemRarity = select(3, GetItemInfo(itemID)) if itemRarity < mod.db.profile.threshold then return end if ignored_items[itemID] then return end tinsert(loot_queue, {player, itemLink, quantity}) if not timer then timer = mod:ScheduleRepeatingTimer("PopLootQueue", 0.1) end end end function mod:PLAYER_REGEN_DISABLED() in_combat = true end function mod:PLAYER_REGEN_ENABLED() in_combat = false end mod.dbDefaults = { profile = { enabled = true, threshold = 4, -- Epic quality items } } mod.optionsName = L["Loot"] mod.optionsDesc = L["Automatic loot tracking"] mod.optionsArgs = { help = { order = 1, type = "description", name = L["Automatic loot tracking by means of a popup to assign GP to the toon that received loot. This option only has effect if you are in a raid and you are either the Raid Leader or the Master Looter."] }, threshold = { order = 10, type = "select", name = L["Loot tracking threshold"], desc = L["Sets loot tracking threshold, to disable the popup on loot below this threshold quality."], values = { [2] = ITEM_QUALITY2_DESC, [3] = ITEM_QUALITY3_DESC, [4] = ITEM_QUALITY4_DESC, [5] = ITEM_QUALITY5_DESC, }, }, } function mod:OnEnable() self:RegisterEvent("PLAYER_REGEN_DISABLED") self:RegisterEvent("PLAYER_REGEN_ENABLED") LLN.RegisterCallback(self, "LootReceived", LootReceived) end function mod:OnDisable() LLN.UnregisterAllCallbacks(self) end
local mod = EPGP:NewModule("loot", "AceEvent-3.0", "AceTimer-3.0") local L = LibStub("AceLocale-3.0"):GetLocale("EPGP") local LLN = LibStub("LibLootNotify-1.0") local ignored_items = { [20725] = true, -- Nexus Crystal [22450] = true, -- Void Crystal [34057] = true, -- Abyss Crystal [29434] = true, -- Badge of Justice [40752] = true, -- Emblem of Heroism [40753] = true, -- Emblem of Valor [45624] = true, -- Emblem of Conquest [30311] = true, -- Warp Slicer [30312] = true, -- Infinity Blade [30313] = true, -- Staff of Disintegration [30314] = true, -- Phaseshift Bulwark [30316] = true, -- Devastation [30317] = true, -- Cosmic Infuser [30318] = true, -- Netherstrand Longbow [30319] = true, -- Nether Spikes [30320] = true, -- Bundle of Nether Spikes } local in_combat = false local loot_queue = {} local timer local function IsRLorML() if UnitInRaid("player") then local loot_method, ml_party_id, ml_raid_id = GetLootMethod() if loot_method == "master" and ml_party_id == 0 then return true end if loot_method ~= "master" and IsRaidLeader() then return true end end return false end function mod:PopLootQueue() if in_combat then return end if #loot_queue == 0 then if timer then self:CancelTimer(timer, true) timer = nil end return end local player, item = unpack(loot_queue[1]) -- In theory this should never happen. if not player or not item then tremove(loot_queue, 1) return end -- User is busy with other popup. if StaticPopup_Visible("EPGP_CONFIRM_GP_CREDIT") then return end tremove(loot_queue, 1) local itemName, itemLink, itemRarity, _, _, _, _, _, _, itemTexture = GetItemInfo(item) local r, g, b = GetItemQualityColor(itemRarity) if EPGP:GetEPGP(player) then local dialog = StaticPopup_Show("EPGP_CONFIRM_GP_CREDIT", player, "", { texture = itemTexture, name = itemName, color = {r, g, b, 1}, link = itemLink }) if dialog then dialog.name = player end end end local function LootReceived(event_name, player, itemLink, quantity) if IsRLorML() and CanEditOfficerNote() then local itemID = tonumber(itemLink:match("item:(%d+)") or 0) if not itemID then return end local itemRarity = select(3, GetItemInfo(itemID)) if itemRarity < mod.db.profile.threshold then return end if ignored_items[itemID] then return end tinsert(loot_queue, {player, itemLink, quantity}) if not timer then timer = mod:ScheduleRepeatingTimer("PopLootQueue", 0.1) end end end function mod:PLAYER_REGEN_DISABLED() in_combat = true end function mod:PLAYER_REGEN_ENABLED() in_combat = false end mod.dbDefaults = { profile = { enabled = true, threshold = 4, -- Epic quality items } } mod.optionsName = L["Loot"] mod.optionsDesc = L["Automatic loot tracking"] mod.optionsArgs = { help = { order = 1, type = "description", name = L["Automatic loot tracking by means of a popup to assign GP to the toon that received loot. This option only has effect if you are in a raid and you are either the Raid Leader or the Master Looter."] }, threshold = { order = 10, type = "select", name = L["Loot tracking threshold"], desc = L["Sets loot tracking threshold, to disable the popup on loot below this threshold quality."], values = { [2] = ITEM_QUALITY2_DESC, [3] = ITEM_QUALITY3_DESC, [4] = ITEM_QUALITY4_DESC, [5] = ITEM_QUALITY5_DESC, }, }, } function mod:OnEnable() self:RegisterEvent("PLAYER_REGEN_DISABLED") self:RegisterEvent("PLAYER_REGEN_ENABLED") LLN.RegisterCallback(self, "LootReceived", LootReceived) end function mod:OnDisable() LLN.UnregisterAllCallbacks(self) end
Validate that we actually can give the player GP before we show the GP credit dialog. This fixes issue 465.
Validate that we actually can give the player GP before we show the GP credit dialog. This fixes issue 465.
Lua
bsd-3-clause
hayword/tfatf_epgp,protomech/epgp-dkp-reloaded,sheldon/epgp,ceason/epgp-tfatf,hayword/tfatf_epgp,sheldon/epgp,protomech/epgp-dkp-reloaded,ceason/epgp-tfatf
45a5506648e4774dbc70889157649cb20cfdfaed
mod_carbons/mod_carbons.lua
mod_carbons/mod_carbons.lua
local st = require "util.stanza"; local jid_bare = require "util.jid".bare; local jid_split = require "util.jid".split; local xmlns_carbons = "urn:xmpp:carbons:1"; local xmlns_forward = "urn:xmpp:forward:0"; local host_sessions = hosts[module.host].sessions; -- TODO merge message handlers into one somehow module:hook("iq/self/"..xmlns_carbons..":enable", function(event) local origin, stanza = event.origin, event.stanza; if stanza.attr.type == "set" then module:log("debug", "%s enabled carbons", origin.full_jid); origin.want_carbons = true; origin.send(st.reply(stanza)); return true end end); module:hook("iq/self/"..xmlns_carbons..":disable", function(event) local origin, stanza = event.origin, event.stanza; if stanza.attr.type == "set" then module:log("debug", "%s disabled carbons", origin.full_jid); origin.want_carbons = nil; origin.send(st.reply(stanza)); return true end end); function c2s_message_handler(event) local origin, stanza = event.origin, event.stanza; local orig_type = stanza.attr.type; local orig_to = stanza.attr.to; if not (orig_type == nil or orig_type == "normal" or orig_type == "chat") then return end local bare_jid, user_sessions; if origin.type == "s2s" then bare_jid = jid_bare(stanza.attr.from); user_sessions = host_sessions[jid_split(orig_to)]; else bare_jid = (origin.username.."@"..origin.host) user_sessions = host_sessions[origin.username]; end if not stanza:get_child("private", xmlns_carbons) and not stanza:get_child("forwarded", xmlns_forward) then user_sessions = user_sessions and user_sessions.sessions; for resource, session in pairs(user_sessions) do local full_jid = bare_jid .. "/" .. resource; if session ~= origin and session.want_carbons then local msg = st.clone(stanza); msg.attr.xmlns = msg.attr.xmlns or "jabber:client"; local fwd = st.message{ from = bare_jid, to = full_jid, type = orig_type, } :tag("forwarded", { xmlns = xmlns_forward }) :tag("received", { xmlns = xmlns_carbons }):up() :add_child(msg); core_route_stanza(origin, fwd); end end end end function s2c_message_handler(event) local origin, stanza = event.origin, event.stanza; local orig_type = stanza.attr.type; local orig_to = stanza.attr.to; if not (orig_type == nil or orig_type == "normal" or orig_type == "chat") then return end local full_jid, bare_jid = orig_to, jid_bare(orig_to); local username, hostname, resource = jid_split(full_jid); local user_sessions = username and host_sessions[username]; if not user_sessions or hostname ~= module.host then return end local no_carbon_to = {}; if resource then no_carbon_to[resource] = true; else local top_resources = user_sessions.top_resources; for i=1,top_resources do no_carbon_to[top_resources[i]] = true; end end if not stanza:get_child("private", xmlns_carbons) and not stanza:get_child("forwarded", xmlns_forward) then user_sessions = user_sessions and user_sessions.sessions; for resource, session in pairs(user_sessions) do local full_jid = bare_jid .. "/" .. resource; if not no_carbon_to[resource] and session.want_carbons then local msg = st.clone(stanza); msg.attr.xmlns = msg.attr.xmlns or "jabber:client"; local fwd = st.message{ from = bare_jid, to = full_jid, type = orig_type, } :tag("forwarded", { xmlns = xmlns_forward }) :tag("received", { xmlns = xmlns_carbons }):up() :add_child(msg); core_route_stanza(origin, fwd); end end end end -- Stanzas sent by local clients module:hook("pre-message/bare", c2s_message_handler, 1); module:hook("pre-message/full", c2s_message_handler, 1); -- Stanszas to local clients module:hook("message/bare", s2c_message_handler, 1); -- this will suck module:hook("message/full", s2c_message_handler, 1); module:add_feature(xmlns_carbons);
local st = require "util.stanza"; local jid_bare = require "util.jid".bare; local jid_split = require "util.jid".split; local xmlns_carbons = "urn:xmpp:carbons:1"; local xmlns_forward = "urn:xmpp:forward:0"; local host_sessions = hosts[module.host].sessions; -- TODO merge message handlers into one somehow module:hook("iq/self/"..xmlns_carbons..":enable", function(event) local origin, stanza = event.origin, event.stanza; if stanza.attr.type == "set" then module:log("debug", "%s enabled carbons", origin.full_jid); origin.want_carbons = true; origin.send(st.reply(stanza)); return true end end); module:hook("iq/self/"..xmlns_carbons..":disable", function(event) local origin, stanza = event.origin, event.stanza; if stanza.attr.type == "set" then module:log("debug", "%s disabled carbons", origin.full_jid); origin.want_carbons = nil; origin.send(st.reply(stanza)); return true end end); function c2s_message_handler(event) local origin, stanza = event.origin, event.stanza; local orig_type = stanza.attr.type; local orig_to = stanza.attr.to; if not (orig_type == nil or orig_type == "normal" or orig_type == "chat") then return end local bare_jid, user_sessions; if origin.type == "s2s" then bare_jid = jid_bare(stanza.attr.from); user_sessions = host_sessions[jid_split(orig_to)]; else bare_jid = (origin.username.."@"..origin.host) user_sessions = host_sessions[origin.username]; end if not stanza:get_child("private", xmlns_carbons) and not stanza:get_child("forwarded", xmlns_forward) then user_sessions = user_sessions and user_sessions.sessions; for resource, session in pairs(user_sessions) do local full_jid = bare_jid .. "/" .. resource; if session ~= origin and session.want_carbons then local msg = st.clone(stanza); msg.attr.xmlns = msg.attr.xmlns or "jabber:client"; local fwd = st.message{ from = bare_jid, to = full_jid, type = orig_type, } :tag("forwarded", { xmlns = xmlns_forward }) :tag("sent", { xmlns = xmlns_carbons }):up() :add_child(msg); core_route_stanza(origin, fwd); end end end end function s2c_message_handler(event) local origin, stanza = event.origin, event.stanza; local orig_type = stanza.attr.type; local orig_to = stanza.attr.to; if not (orig_type == nil or orig_type == "normal" or orig_type == "chat") then return end local full_jid, bare_jid = orig_to, jid_bare(orig_to); local username, hostname, resource = jid_split(full_jid); local user_sessions = username and host_sessions[username]; if not user_sessions or hostname ~= module.host then return end local no_carbon_to = {}; if resource then no_carbon_to[resource] = true; else local top_resources = user_sessions.top_resources; for i, session in ipairs(top_resources) do no_carbon_to[session.resource] = true; module:log("debug", "not going to send to /%s", resource); end end if not stanza:get_child("private", xmlns_carbons) and not stanza:get_child("forwarded", xmlns_forward) then user_sessions = user_sessions and user_sessions.sessions; for resource, session in pairs(user_sessions) do local full_jid = bare_jid .. "/" .. resource; if not no_carbon_to[resource] and session.want_carbons then local msg = st.clone(stanza); msg.attr.xmlns = msg.attr.xmlns or "jabber:client"; local fwd = st.message{ from = bare_jid, to = full_jid, type = orig_type, } :tag("forwarded", { xmlns = xmlns_forward }) :tag("received", { xmlns = xmlns_carbons }):up() :add_child(msg); core_route_stanza(origin, fwd); end end end end -- Stanzas sent by local clients module:hook("pre-message/bare", c2s_message_handler, 1); module:hook("pre-message/full", c2s_message_handler, 1); -- Stanszas to local clients module:hook("message/bare", s2c_message_handler, 1); module:hook("message/full", s2c_message_handler, 1); module:add_feature(xmlns_carbons);
mod_carbons: Fix top_resources loop and correctly stamp sent messages (thanks xnyhps)
mod_carbons: Fix top_resources loop and correctly stamp sent messages (thanks xnyhps)
Lua
mit
prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2
adb7ec786f4789aa3f0d68e4cce49f31c968485b
src/cosy/library.lua
src/cosy/library.lua
local Configuration = require "cosy.configuration" local Digest = require "cosy.digest" local Value = require "cosy.value" local Library = {} local Client = {} local function patch (client) function client.authenticate (parameters, try_only) parameters.password = Digest ("%{username}:%{password}" % { username = parameters.username, password = parameters.password, }) client.username = parameters.username client.password = parameters.password return Client.__index (client, "authenticate") (parameters, try_only) end function client.create_user (parameters, try_only) parameters.password = Digest ("%{username}:%{password}" % { username = parameters.username, password = parameters.password, }) client.username = parameters.username client.password = parameters.password return Client.__index (client, "create_user") (parameters, try_only) end return client end if _G.js then function Client.__index (client, operation) local result = function (parameters, try_only) local identifier = #client._waiting + 1 client._ws:send (Value.expression { identifier = identifier, operation = operation, parameters = parameters or {}, try_only = try_only, }) client._waiting [identifier] = coroutine.running () local result = coroutine.yield () if result == nil then error { _ = "client:timeout", } elseif result.success then return result.response else error (result.error) end end return result end function Library.client (url) local client = setmetatable ({ _results = {}, _waiting = {}, }, Client) client._ws = _G.js.new (_G.js.global.WebSocket, url, "cosy") client._ws.onopen = function () coroutine.resume (coroutine.running (), true) end client._ws.onclose = function (_, event) coroutine.resume (coroutine.running (), nil, event.reason) end client._ws.onmessage = function (_, event) local message = Value.decode (event.data) local identifier = message.identifier if identifier then local co = client._waiting [identifier] assert (co) client._waiting[identifier] = nil coroutine.resume (co, message) else client.on_update () end end local ok, err = coroutine.yield () if not ok then error (err) end return patch (client) end function Library.connect (url) local parser = _G.js.global.document:createElement "a"; parser.href = url; local hostname = parser.hostname local port = parser.port local client = Library.client ("ws://%{hostname}:%{port}/ws" % { hostname = hostname, port = port, }) client.username = parser.username client.password = parser.password return client end else local Scheduler = require "cosy.scheduler" local Url = require "socket.url" local Websocket = require "websocket" function Client.react (client) while true do local message = client._ws:receive () if not message then return end message = Value.decode (message) local identifier = message.identifier if identifier then client._results [identifier] = message Scheduler.wakeup (client._waiting [identifier]) else client.on_update () end end end function Client.loop (client) Scheduler.addthread (Client.react, client) Scheduler.loop () end function Client.__index (client, operation) local result = function (parameters, try_only) local result = nil local coreact = Scheduler.addthread (Client.react, client) Scheduler.addthread (function () local co = coroutine.running () local identifier = #client._waiting+1 client._waiting [identifier] = co client._results [identifier] = nil client._ws:send (Value.expression { identifier = identifier, operation = operation, parameters = parameters or {}, try_only = try_only, }) Scheduler.sleep (Configuration.client.timeout._) result = client._results [identifier] client._waiting [identifier] = nil client._results [identifier] = nil Scheduler.kill (coreact) end) Scheduler.loop () if result == nil then error { _ = "client:timeout", } elseif result.success then return result.response else error (result.error) end end return result end function Library.client (url) local client = setmetatable ({ _waiting = {}, _results = {}, _react = nil, }, Client) client._ws = Websocket.client.copas { timeout = Configuration.client.timeout._, } Scheduler.addthread (function () client._ws:connect (url, "cosy") end) Scheduler.loop () return patch (client) end function Library.connect (url) local parsed = Url.parse (url) local host = parsed.host local port = parsed.port local client = Library.client ("ws://%{host}:%{port}/ws" % { host = host, port = port, }) client.username = parsed.user client.password = parsed.password return client end end return Library
local Configuration = require "cosy.configuration" local Digest = require "cosy.digest" local Value = require "cosy.value" local Scheduler = require "cosy.scheduler" local Library = {} local Client = {} local function patch (client) function client.authenticate (parameters, try_only) parameters.password = Digest ("%{username}:%{password}" % { username = parameters.username, password = parameters.password, }) client.username = parameters.username client.password = parameters.password return Client.__index (client, "authenticate") (parameters, try_only) end function client.create_user (parameters, try_only) parameters.password = Digest ("%{username}:%{password}" % { username = parameters.username, password = parameters.password, }) client.username = parameters.username client.password = parameters.password return Client.__index (client, "create_user") (parameters, try_only) end return client end function Client.__index (client, operation) return function (parameters, try_only) local result local f = function () local co = coroutine.running () local identifier = #client._waiting + 1 client._waiting [identifier] = co client._results [identifier] = nil client._ws:send (Value.expression { identifier = identifier, operation = operation, parameters = parameters or {}, try_only = try_only, }) Scheduler.sleep (Configuration.client.timeout._) result = client._results [identifier] client._waiting [identifier] = nil client._results [identifier] = nil end Scheduler.addthread (f) Scheduler.loop () if result == nil then return nil, { _ = "client:timeout", } elseif result.success then return result.response or true else return nil, result.error end end end function Library.client (t) local client = setmetatable ({ _results = {}, _waiting = {}, }, Client) client.host = t.host or false client.port = t.port or 80 client.username = t.username or false client.password = t.password or false local url = "ws://%{host}:%{port}/ws" % { host = client.host, port = client.port, } if _G.js then client._ws = _G.js.new (_G.js.global.WebSocket, url, "cosy") else local Websocket = require "websocket" client._ws = Websocket.client.ev { timeout = Configuration.client.timeout._, loop = Scheduler._loop, } end client._ws.onopen = function () Scheduler.wakeup (client._co) end client._ws.onclose = function () end client._ws.onmessage = function (_, event) local message if _G.js then message = event.data else message = event end message = Value.decode (message) local identifier = message.identifier if identifier then client._results [identifier] = message Scheduler.wakeup (client._waiting [identifier]) end end client._ws.onerror = function () end if not _G.js then client._ws:on_open (client._ws.onopen) client._ws:on_close (client._ws.onclose) client._ws:on_message (client._ws.onmessage) client._ws:on_error (client._ws.onerror) end if _G.js then client._co = coroutine.running () Scheduler.sleep (-math.huge) else Scheduler.addthread (function () client._ws:connect (url, "cosy") client._co = coroutine.running () Scheduler.sleep (-math.huge) end) Scheduler.loop () end return patch (client) end if _G.js then function Library.connect (url) local parser = _G.js.global.document:createElement "a"; parser.href = url; local hostname = parser.hostname local port = parser.port return Library.client { host = hostname, port = port, username = parser.username, password = parser.password, } end else local Url = require "socket.url" function Library.connect (url) local parsed = Url.parse (url) return Library.client { host = parsed.host, port = parsed.port, username = parsed.user, password = parsed.password, } end end return Library
Fix library for native and javascript.
Fix library for native and javascript.
Lua
mit
CosyVerif/library,CosyVerif/library,CosyVerif/library
bc5bd85bd784c1e8989a75f03d41e410c4594ba0
lua/entities/gmod_wire_egp_hud/init.lua
lua/entities/gmod_wire_egp_hud/init.lua
AddCSLuaFile("cl_init.lua") AddCSLuaFile("shared.lua") include('shared.lua') AddCSLuaFile("HUDDraw.lua") include("HUDDraw.lua") ENT.WireDebugName = "E2 Graphics Processor HUD" function ENT:Initialize() self:PhysicsInit(SOLID_VPHYSICS) self:SetMoveType(MOVETYPE_VPHYSICS) self:SetSolid(SOLID_VPHYSICS) self.RenderTable = {} self:SetUseType(SIMPLE_USE) self.Inputs = WireLib.CreateInputs( self, { "0 to 512" } ) WireLib.CreateWirelinkOutput( nil, self, {true} ) self.xScale = { 0, 512 } self.yScale = { 0, 512 } self.Scaling = false self.TopLeft = false end function ENT:TriggerInput( name, value ) if (name == "0 to 512") then self:SetNWBool( "Resolution", value != 0 ) end end function ENT:Use( ply ) umsg.Start( "EGP_HUD_Use", ply ) umsg.Entity( self ) umsg.End() end function ENT:SetEGPOwner( ply ) self.ply = ply self.plyID = ply:UniqueID() end function ENT:GetEGPOwner() if (!self.ply or !self.ply:IsValid()) then local ply = player.GetByUniqueID( self.plyID ) if (ply) then self.ply = ply end return ply else return self.ply end return false end function ENT:UpdateTransmitState() return TRANSMIT_ALWAYS end function ENT:LinkEnt( ent ) if IsValid( ent ) and ent:IsVehicle() then if self.LinkedVehicles and self.LinkedVehicles[ent] then return false end EGP:LinkHUDToVehicle( self, ent ) ent:CallOnRemove( "EGP HUD unlink on remove", function( ent ) EGP:UnlinkHUDFromVehicle( self, ent ) end) return true else return false, tostring(ent) .. " is invalid or is not a vehicle" end end function ENT:OnRemove() if self.Marks then for i=1,#self.Marks do self.Marks[i]:RemoveCallOnRemove( "EGP HUD unlink on remove" ) end end EGP:UnlinkHUDFromVehicle( self ) end function ENT:BuildDupeInfo() local info = self.BaseClass.BuildDupeInfo(self) or {} local vehicles = self.LinkedVehicles if vehicles then local _vehicles = {} for k,v in pairs( vehicles ) do _vehicles[#_vehicles+1] = k:EntIndex() end info.egp_hud_vehicles = _vehicles end return info end function ENT:ApplyDupeInfo(ply, ent, info, GetEntByID) self.BaseClass.ApplyDupeInfo(self, ply, ent, info, GetEntByID) local vehicles = info.egp_hud_vehicles for i=1,#vehicles do local vehicle = GetEntByID( vehicles[i] ) if IsValid( vehicle ) then self:LinkEnt( vehicle ) end end end
AddCSLuaFile("cl_init.lua") AddCSLuaFile("shared.lua") include('shared.lua') AddCSLuaFile("HUDDraw.lua") include("HUDDraw.lua") ENT.WireDebugName = "E2 Graphics Processor HUD" function ENT:Initialize() self:PhysicsInit(SOLID_VPHYSICS) self:SetMoveType(MOVETYPE_VPHYSICS) self:SetSolid(SOLID_VPHYSICS) self.RenderTable = {} self:SetUseType(SIMPLE_USE) self.Inputs = WireLib.CreateInputs( self, { "0 to 512" } ) WireLib.CreateWirelinkOutput( nil, self, {true} ) self.xScale = { 0, 512 } self.yScale = { 0, 512 } self.Scaling = false self.TopLeft = false end function ENT:TriggerInput( name, value ) if (name == "0 to 512") then self:SetNWBool( "Resolution", value != 0 ) end end function ENT:Use( ply ) umsg.Start( "EGP_HUD_Use", ply ) umsg.Entity( self ) umsg.End() end function ENT:SetEGPOwner( ply ) self.ply = ply self.plyID = ply:UniqueID() end function ENT:GetEGPOwner() if (!self.ply or !self.ply:IsValid()) then local ply = player.GetByUniqueID( self.plyID ) if (ply) then self.ply = ply end return ply else return self.ply end return false end function ENT:UpdateTransmitState() return TRANSMIT_ALWAYS end function ENT:LinkEnt( ent ) if IsValid( ent ) and ent:IsVehicle() then if self.LinkedVehicles and self.LinkedVehicles[ent] then return false end EGP:LinkHUDToVehicle( self, ent ) ent:CallOnRemove( "EGP HUD unlink on remove", function( ent ) EGP:UnlinkHUDFromVehicle( self, ent ) end) return true else return false, tostring(ent) .. " is invalid or is not a vehicle" end end function ENT:OnRemove() if self.Marks then for i=1,#self.Marks do self.Marks[i]:RemoveCallOnRemove( "EGP HUD unlink on remove" ) end end EGP:UnlinkHUDFromVehicle( self ) end function ENT:BuildDupeInfo() local info = self.BaseClass.BuildDupeInfo(self) or {} local vehicles = self.LinkedVehicles if vehicles then local _vehicles = {} for k,v in pairs( vehicles ) do _vehicles[#_vehicles+1] = k:EntIndex() end info.egp_hud_vehicles = _vehicles end return info end function ENT:ApplyDupeInfo(ply, ent, info, GetEntByID) self.BaseClass.ApplyDupeInfo(self, ply, ent, info, GetEntByID) local vehicles = info.egp_hud_vehicles if vehicles then for i=1,#vehicles do local vehicle = GetEntByID( vehicles[i] ) if IsValid( vehicle ) then self:LinkEnt( vehicle ) end end end end
Fixed error if duping an egp hud that wasn't linked to a vehicle
Fixed error if duping an egp hud that wasn't linked to a vehicle
Lua
apache-2.0
mms92/wire,dvdvideo1234/wire,plinkopenguin/wiremod,CaptainPRICE/wire,garrysmodlua/wire,Grocel/wire,rafradek/wire,thegrb93/wire,NezzKryptic/Wire,sammyt291/wire,Python1320/wire,wiremod/wire,bigdogmat/wire,notcake/wire,mitterdoo/wire,immibis/wiremod
ece7394025e71be9a07084a753cbd1e77b089d9b
kong/plugins/sign/handler.lua
kong/plugins/sign/handler.lua
local BasePlugin = require "kong.plugins.base_plugin" local responses = require "kong.tools.responses" local SignHandler = BasePlugin:extend() function SignHandler:new() SignHandler.super.new(self, "sign") end local function checksign(conf) if not conf.signname then ngx.log(ngx.ERR, "[sign] no conf.signname set, aborting plugin execution") return false, {status = 500, message= "Invalid plugin configuration"} end local signname = conf.signname local prefix = conf.prefix local after = conf.after local itemsplit = conf.itemsplit local pairsplit = conf.pairsplit local tbl={} local tblkey={} local args =nil local request_method = ngx.var.request_method if "GET" == request_method then args = ngx.req.get_uri_args() elseif "POST" == request_method then ngx.req.read_body() args = ngx.req.get_post_args() end local sign if type(args)=="table" then for key,value in pairs(args) do if key~=conf.signname then tbl[key]=value table.insert(tblkey,key) else sign=value end end end if not sign then return false, {status = 401, message = "No sign key found in headers" .." or querystring"} end table.sort(tblkey) local temp="" local index = 0 for _,key in pairs(tblkey) do temp=temp..key..pairsplit..tbl[key]..itemsplit index=index+1 end if index>0 then temp =string.sub(temp,1,string.len(temp)-string.len(itemsplit)) temp=prefix..temp..after local formatkey = ngx.md5(temp) if ( string.lower(formatkey) ~= string.lower(sign)) then return false, {status = 403, message = "Invalid sign credentials"} end return true end function SignHandler:access(conf) SignHandler.super.access(self) local ok, err = checksign(conf) if not ok then return responses.send(err.status, err.message) end end SignHandler.PRIORITY = 1000 return SignHandler
local BasePlugin = require "kong.plugins.base_plugin" local responses = require "kong.tools.responses" local SignHandler = BasePlugin:extend() function SignHandler:new() SignHandler.super.new(self, "sign") end local function checksign(conf) if not conf.signname then ngx.log(ngx.ERR, "[sign] no conf.signname set, aborting plugin execution") return false, {status = 500, message= "Invalid plugin configuration"} end local signname = conf.signname local prefix = conf.prefix local after = conf.after local itemsplit = conf.itemsplit local pairsplit = conf.pairsplit local tbl={} local tblkey={} local args =nil local request_method = ngx.var.request_method if "GET" == request_method then args = ngx.req.get_uri_args() elseif "POST" == request_method then ngx.req.read_body() args = ngx.req.get_post_args() end local sign if type(args)=="table" then for key,value in pairs(args) do if key~=conf.signname then tbl[key]=value table.insert(tblkey,key) else sign=value end end end if not sign then return false, {status = 401, message ={code=401,data={message= "No sign key found in headers" .." or querystring"}} } end table.sort(tblkey) local index=0 local temp="" for _,key in pairs(tblkey) do index=index+1 temp=temp..key..pairsplit..tbl[key]..itemsplit end temp =string.sub(temp,1,string.len(temp)-string.len(itemsplit)) temp=prefix..temp..after local formatkey = ngx.md5(temp) ngx.log(ngx.ERR,formatkey.."=="..sign) if ( string.lower(formatkey) ~= string.lower(sign)) then return false, {status = 403, message ={code=403,data={message="Unauthorized"}} } end return true end function SignHandler:access(conf) SignHandler.super.access(self) local ok, err = checksign(conf) if not ok then return responses.send(err.status, err.message) end end SignHandler.PRIORITY = 1000 return SignHandler
fix bug
fix bug
Lua
apache-2.0
li-wl/kong
bc303d61ab50a7060795206b0f7750c4ceaa39d3
hammerspoon/prefix.lua
hammerspoon/prefix.lua
-- Simulate tmux's key binding: prefix + hotkey local module = {} local TIMEOUT = 3 local modal = hs.hotkey.modal.new('ctrl', 'space') function modal:entered() modal.alertId = hs.alert.show("Prefix mode", TIMEOUT) hs.timer.doAfter(TIMEOUT, function() modal:exit() end) end function modal:exited() if modal.alertId then hs.alert.closeSpecific(modal.alertId) end end modal:bind('', 'escape', function() modal:exit() end) modal:bind('ctrl', 'space', function() modal:exit() end) function module.bind(mod, key, fn, autoExit) if autoExit == nil or autoExit then bindFn = function() modal:exit() fn() end else bindFn = fn end modal:bind(mod, key, bindFn) end module.bind('', 'd', hs.toggleConsole) module.bind('', 'r', hs.reload) return module
-- Tmux style hotkey binding: prefix + hotkey local module = {} local TIMEOUT = 5 local modal = hs.hotkey.modal.new('ctrl', 'space') function modal:entered() modal.alertId = hs.alert.show("Prefix Mode", 9999) modal.timer = hs.timer.doAfter(TIMEOUT, function() modal:exit() end) end function modal:exited() if modal.alertId then hs.alert.closeSpecific(modal.alertId) end module.cancelTimeout() end function module.exit() modal:exit() end function module.cancelTimeout() if modal.timer then modal.timer:stop() end end function module.bind(mod, key, fn) modal:bind(mod, key, nil, function() fn(); module.exit() end) end function module.bindMultiple(mod, key, pressedFn, releasedFn, repeatFn) modal:bind(mod, key, pressedFn, releasedFn, repeatFn) end module.bind('', 'escape', module.exit) module.bind('ctrl', 'space', module.exit) module.bind('', 'd', hs.toggleConsole) module.bind('', 'r', hs.reload) return module
[hs] misc changes on prefix mode
[hs] misc changes on prefix mode
Lua
mit
raulchen/dotfiles,raulchen/dotfiles
f5cdd1145048a0b6d90946ac8651d5286408aa91
mod_auth_external/mod_auth_external.lua
mod_auth_external/mod_auth_external.lua
-- -- Prosody IM -- Copyright (C) 2010 Waqas Hussain -- Copyright (C) 2010 Jeff Mitchell -- Copyright (C) 2013 Mikael Nordfeldth -- Copyright (C) 2013 Matthew Wild, finally came to fix it all -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local lpty = assert(require "lpty", "mod_auth_external requires lpty: https://code.google.com/p/prosody-modules/wiki/mod_auth_external#Installation"); local log = module._log; local host = module.host; local script_type = module:get_option_string("external_auth_protocol", "generic"); assert(script_type == "ejabberd" or script_type == "generic", "Config error: external_auth_protocol must be 'ejabberd' or 'generic'"); local command = module:get_option_string("external_auth_command", ""); local read_timeout = module:get_option_number("external_auth_timeout", 5); assert(not host:find(":"), "Invalid hostname"); local usermanager = require "core.usermanager"; local new_sasl = require "util.sasl".new; local pty = lpty.new({ throw_errors = false, no_local_echo = true, use_path = false }); function send_query(text) if not pty:hasproc() then local status, ret = pty:exitstatus(); if status and (status ~= "exit" or ret ~= 0) then log("warn", "Auth process exited unexpectedly with %s %d, restarting", status, ret or 0); return nil; end local ok, err = pty:startproc(command); if not ok then log("error", "Failed to start auth process '%s': %s", command, err); return nil; end log("debug", "Started auth process"); end pty:send(text); return pty:read(read_timeout); end function do_query(kind, username, password) if not username then return nil, "not-acceptable"; end local query = (password and "%s:%s:%s:%s" or "%s:%s:%s"):format(kind, username, host, password); local len = #query if len > 1000 then return nil, "policy-violation"; end if script_type == "ejabberd" then local lo = len % 256; local hi = (len - lo) / 256; query = string.char(hi, lo)..query; end if script_type == "generic" then query = query..'\n'; end local response = send_query(query); if (script_type == "ejabberd" and response == "\0\2\0\0") or (script_type == "generic" and response:gsub("\r?\n$", "") == "0") then return nil, "not-authorized"; elseif (script_type == "ejabberd" and response == "\0\2\0\1") or (script_type == "generic" and response:gsub("\r?\n$", "") == "1") then return true; else if response then log("warn", "Unable to interpret data from auth process, %s", (response:match("^error:") and response) or ("["..#response.." bytes]")); else log("warn", "Error while waiting for result from auth process: %s", response or "unknown error"); end return nil, "internal-server-error"; end end local host = module.host; local provider = {}; function provider.test_password(username, password) return do_query("auth", username, password); end function provider.set_password(username, password) return do_query("setpass", username, password); end function provider.user_exists(username) return do_query("isuser", username); end function provider.create_user(username, password) return nil, "Account creation/modification not available."; end function provider.get_sasl_handler() local testpass_authentication_profile = { plain_test = function(sasl, username, password, realm) return usermanager.test_password(username, realm, password), true; end, }; return new_sasl(host, testpass_authentication_profile); end module:provides("auth", provider);
-- -- Prosody IM -- Copyright (C) 2010 Waqas Hussain -- Copyright (C) 2010 Jeff Mitchell -- Copyright (C) 2013 Mikael Nordfeldth -- Copyright (C) 2013 Matthew Wild, finally came to fix it all -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local lpty = assert(require "lpty", "mod_auth_external requires lpty: https://code.google.com/p/prosody-modules/wiki/mod_auth_external#Installation"); local log = module._log; local host = module.host; local script_type = module:get_option_string("external_auth_protocol", "generic"); assert(script_type == "ejabberd" or script_type == "generic", "Config error: external_auth_protocol must be 'ejabberd' or 'generic'"); local command = module:get_option_string("external_auth_command", ""); local read_timeout = module:get_option_number("external_auth_timeout", 5); assert(not host:find(":"), "Invalid hostname"); local usermanager = require "core.usermanager"; local new_sasl = require "util.sasl".new; local pty = lpty.new({ throw_errors = false, no_local_echo = true, use_path = false }); function send_query(text) if not pty:hasproc() then local status, ret = pty:exitstatus(); if status and (status ~= "exit" or ret ~= 0) then log("warn", "Auth process exited unexpectedly with %s %d, restarting", status, ret or 0); return nil; end local ok, err = pty:startproc(command); if not ok then log("error", "Failed to start auth process '%s': %s", command, err); return nil; end log("debug", "Started auth process"); end pty:send(text); return pty:read(read_timeout); end function do_query(kind, username, password) if not username then return nil, "not-acceptable"; end local query = (password and "%s:%s:%s:%s" or "%s:%s:%s"):format(kind, username, host, password); local len = #query if len > 1000 then return nil, "policy-violation"; end if script_type == "ejabberd" then local lo = len % 256; local hi = (len - lo) / 256; query = string.char(hi, lo)..query; end if script_type == "generic" then query = query..'\n'; end local response, err = send_query(query); if not response then log("warn", "Error while waiting for result from auth process: %s", err or "unknown error"); elseif (script_type == "ejabberd" and response == "\0\2\0\0") or (script_type == "generic" and response:gsub("\r?\n$", "") == "0") then return nil, "not-authorized"; elseif (script_type == "ejabberd" and response == "\0\2\0\1") or (script_type == "generic" and response:gsub("\r?\n$", "") == "1") then return true; else log("warn", "Unable to interpret data from auth process, %s", (response:match("^error:") and response) or ("["..#response.." bytes]")); return nil, "internal-server-error"; end end local host = module.host; local provider = {}; function provider.test_password(username, password) return do_query("auth", username, password); end function provider.set_password(username, password) return do_query("setpass", username, password); end function provider.user_exists(username) return do_query("isuser", username); end function provider.create_user(username, password) return nil, "Account creation/modification not available."; end function provider.get_sasl_handler() local testpass_authentication_profile = { plain_test = function(sasl, username, password, realm) return usermanager.test_password(username, realm, password), true; end, }; return new_sasl(host, testpass_authentication_profile); end module:provides("auth", provider);
mod_auth_external: Fix logging of errors
mod_auth_external: Fix logging of errors
Lua
mit
prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2
347e205f3d8f7d8822cf4070e681e11056e5b7d4
DeveloperTools/data2yaml/data2yaml.lua
DeveloperTools/data2yaml/data2yaml.lua
sptbl = {} print(arg[1]) dofile(string.format("data/%s.lua", arg[1])) YAML = { name=arg[1] } function YAML.tables(self, tbl) if(tbl.params.mandatory == nil) then return end local ftbl = {} local ft = {} for k,v in pairs(tbl.params.mandatory) do if(string.match(v.type, "sp_ftbl")) then ft.name = v.name ft.comment = v.description table.insert(ftbl, ft) end end if(next(ftbl) == nil) then return end io.write("tables:\n") for k,v in pairs(ftbl) do io.write(string.format("- %s: {\n", v.name)) io.write(string.format(" audioKitName: %s,\n", v.name)) io.write(string.format(" comment: \"%s\",\n", v.comment)) io.write(" default: \n") io.write("}\n") end io.write("\n") end function YAML.parameters(self, tbl) if(tbl.params.optional == nil) then return end io.write("parameters:\n") for k,v in pairs(tbl.params.optional) do io.write(string.format("- %s: {\n", v.name)) io.write(string.format(" audioKitName: %s,\n", v.name)) io.write(string.format(" comment: \"%s\",\n", v.description)) io.write(string.format(" default: %s\n", v.default)) io.write("}\n") end io.write("\n") end function YAML.constants(self, tbl) if(tbl.params.mandatory == nil) then return end local constants = {} local c = {} for k,v in pairs(tbl.params.mandatory) do if(string.match(v.type, "sp_ftbl")) then -- ignore else c.name = v.name c.comment = v.description c.default = v.default table.insert(constants, c) end end if(next(constants) == nil) then return end io.write("constants:\n") for k,v in pairs(constants) do io.write(string.format("- %s: {\n", v.name)) io.write(string.format(" audioKitName: %s ,\n", v.name)) io.write(string.format(" comment: \"%s\",\n", v.comment)) io.write(string.format(" default: %s\n", v.default)) io.write("}\n") end io.write("\n") end function YAML.generate(self, tbl) io.write(string.format("sp_name: %s\n\n", self.name)) io.write(string.format("summary: \n\n")); io.write(string.format("shortDescription: \n\n")) io.write(string.format("description: \n\n")) self:tables(tbl) self:parameters(tbl) self:constants(tbl) end YAML:generate(sptbl[arg[1]])
sptbl = {} print(arg[1]) dofile(string.format("data/%s.lua", arg[1])) YAML = { name=arg[1] } function YAML.tables(self, tbl) if(tbl.params.mandatory == nil) then return end local ftbl = {} for k,v in pairs(tbl.params.mandatory) do if(string.match(v.type, "sp_ftbl")) then local ft = {} ft.name = v.name ft.comment = v.description table.insert(ftbl, ft) end end if(next(ftbl) == nil) then return end io.write("tables:\n") for k,v in pairs(ftbl) do io.write(string.format("- %s: {\n", v.name)) io.write(string.format(" audioKitName: %s,\n", v.name)) io.write(string.format(" comment: \"%s\",\n", v.comment)) io.write(" default: \n") io.write("}\n") end io.write("\n") end function YAML.parameters(self, tbl) if(tbl.params.optional == nil) then return end io.write("parameters:\n") for k,v in pairs(tbl.params.optional) do io.write(string.format("- %s: {\n", v.name)) io.write(string.format(" audioKitName: %s,\n", v.name)) io.write(string.format(" comment: \"%s\",\n", v.description)) io.write(string.format(" default: %s\n", v.default)) io.write("}\n") end io.write("\n") end function YAML.constants(self, tbl) if(tbl.params.mandatory == nil) then return end local constants = {} for k,v in pairs(tbl.params.mandatory) do if(string.match(v.type, "sp_ftbl")) then -- ignore else local c = {} c.name = v.name c.comment = v.description c.default = v.default table.insert(constants, c) end end if(next(constants) == nil) then return end io.write("constants:\n") for k,v in pairs(constants) do io.write(string.format("- %s: {\n", v.name)) io.write(string.format(" audioKitName: %s ,\n", v.name)) io.write(string.format(" comment: \"%s\",\n", v.comment)) io.write(string.format(" default: %s\n", v.default)) io.write("}\n") end io.write("\n") end function YAML.generate(self, tbl) io.write(string.format("sp_name: %s\n\n", self.name)) io.write(string.format("summary: \n\n")); io.write(string.format("shortDescription: \n\n")) io.write(string.format("description: \n\n")) self:tables(tbl) self:parameters(tbl) self:constants(tbl) end YAML:generate(sptbl[arg[1]])
data2yaml fixes: repeating constants do not happen now
data2yaml fixes: repeating constants do not happen now
Lua
mit
narner/AudioKit,roecrew/AudioKit,catloafsoft/AudioKit,laurentVeliscek/AudioKit,catloafsoft/AudioKit,catloafsoft/AudioKit,roecrew/AudioKit,roecrew/AudioKit,roecrew/AudioKit,dclelland/AudioKit,narner/AudioKit,dclelland/AudioKit,laurentVeliscek/AudioKit,narner/AudioKit,narner/AudioKit,laurentVeliscek/AudioKit,catloafsoft/AudioKit,dclelland/AudioKit,dclelland/AudioKit,laurentVeliscek/AudioKit
b094c72d94464deaf2272d11a78473e3d5a4608e
src/commands/addsticker.lua
src/commands/addsticker.lua
local utils = require("utils") local addsticker = { func = function(msg) local origin_title = msg.text:match("/addsticker%s*(%S.-)%s*$") local default_title = ("Sticker Pack By " .. msg.from.first_name .. (msg.from.last_name and (" " .. msg.from.last_name) or "")) local title = origin_title or default_title local info = bot.sendMessage{ chat_id = msg.chat.id, text = "Roger. Wait a moment ...", reply_to_message_id = msg.message_id } output_fn = commands.resize.func(msg, true) if not output_fn then -- already replied return end local sticker_content = utils.readFile(output_fn) -- local ret = bot.uploadStickerFile(msg.from.id, ) -- if not ret.ok then -- return bot.editMessageText{ -- chat_id = msg.chat.id, -- message_id = info.result.message_id, -- text = "Sorry, something was wrong. Please try again." -- } -- end -- local fid = ret.result.file_id -- os.remove("sticker.png") local c = 1 local url = "u" .. msg.from.id .. "_by_" .. bot.info.username local ret local try try = function() local args = { user_id = msg.from.id, name = url, title = title, emojis = "🍀" } if output_fn == "sticker.png" then args.png_sticker = sticker_content elseif output_fn == "sticker.webm" then args.webm_sticker = sticker_content end ret = bot.createNewStickerSet(args) if ret.description == "Bad Request: PEER_ID_INVALID" then return bot.editMessageText{ chat_id = msg.chat.id, message_id = info.result.message_id, text = "Please /start with me in private chat first." } elseif ret.error_code == 403 then return bot.editMessageText{ chat_id = msg.chat.id, message_id = info.result.message_id, text = "Sorry, you have blocked me." } end local pack_url = "[" .. title .. "](https://t.me/addstickers/" .. url .. ")" if ret.ok then return bot.editMessageText{ chat_id = msg.chat.id, message_id = info.result.message_id, text = "All right.\n" .. pack_url, parse_mode = "Markdown" } end local args = { user_id = msg.from.id, name = url, emojis = "🍀" } if output_fn == "sticker.png" then args.png_sticker = sticker_content elseif output_fn == "sticker.webm" then args.webm_sticker = sticker_content end ret = bot.addStickerToSet(args) if ret.ok then return bot.editMessageText{ chat_id = msg.chat.id, message_id = info.result.message_id, text = "All right.\n" .. pack_url, parse_mode = "Markdown" } elseif ret.description == "Bad Request: STICKERS_TOO_MUCH" then c = c + 1 url = "u" .. msg.from.id .. "_" .. c .. "_by_" .. bot.info.username if (not origin_title) then title = default_title .. " " .. c end return try() else return bot.editMessageText{ chat_id = msg.chat.id, message_id = info.result.message_id, text = "Failed. (`" .. ret.description .. "`)\n" .. pack_url, parse_mode = "Markdown" } end end local status, err = pcall(try) if not status then return bot.editMessageText{ chat_id = msg.chat.id, message_id = info.result.message_id, text = "Unexpected error occurred. (`" .. err .. "`)\nCC: @SJoshua", parse_mode = "Markdown" } end end, desc = "Add a sticker to your sticker pack.", form = "/addsticker [title]", help = "Reply to sticker/picture.", limit = { reply = true, } } return addsticker
local utils = require("utils") local addsticker = { func = function(msg) local info = bot.sendMessage{ chat_id = msg.chat.id, text = "Roger. Wait a moment ...", reply_to_message_id = msg.message_id } local is_static = false local is_animated = false local is_video = false local field = "" output_fn = commands.resize.func(msg, true) if output_fn == "sticker.png" then is_static = true field = "png_sticker" elseif output_fn == "sticker.tgs" then is_animated = true field = "tgs_sticker" elseif output_fn == "sticker.webm" then is_video = true field = "webm_sticker" elseif not output_fn then -- already replied return end local sticker_content = utils.readFile(output_fn) local origin_title = msg.text:match("/addsticker%s*(%S.-)%s*$") local default_title = (output_fn == "sticker.png" and "" or "Animated ") .. ("Sticker Pack By " .. msg.from.first_name .. (msg.from.last_name and (" " .. msg.from.last_name) or "")) local title = origin_title or default_title local c = 1 local url = "u" .. msg.from.id .. "_by_" .. bot.info.username local ret local try -- find a free url while c < 10 do local continue = false local ret = bot.getStickerSet(url) if not ret.ok then -- create new sticker set local args = { user_id = msg.from.id, name = url, title = title, emojis = "🍀" } args[field] = sticker_content ret = bot.createNewStickerSet(args) elseif (ret.result.is_animated and is_animated and #ret.result.stickers < 50) or (ret.result.is_video and is_video and #ret.result.stickers < 50) or (not ret.result.is_animated and not ret.result.is_video and is_static and #ret.result.stickers < 120) then local args = { user_id = msg.from.id, name = url, emojis = "🍀" } args[field] = sticker_content ret = bot.createNewStickerSet(args) else continue = true end if continue then c = c + 1 url = "u" .. msg.from.id .. "_" .. c .. "_by_" .. bot.info.username if (not origin_title) then title = default_title .. " " .. c end else if ret.description == "Bad Request: PEER_ID_INVALID" then return bot.editMessageText{ chat_id = msg.chat.id, message_id = info.result.message_id, text = "Please /start with me in private chat first." } elseif ret.error_code == 403 then return bot.editMessageText{ chat_id = msg.chat.id, message_id = info.result.message_id, text = "Sorry, you have blocked me." } end local pack_url = "[" .. title .. "](https://t.me/addstickers/" .. url .. ")" if ret.ok then return bot.editMessageText{ chat_id = msg.chat.id, message_id = info.result.message_id, text = "All right.\n" .. pack_url, parse_mode = "Markdown" } else return bot.editMessageText{ chat_id = msg.chat.id, message_id = info.result.message_id, text = "Failed. (`" .. ret.description .. "`)\n" .. pack_url, parse_mode = "Markdown" } end end end end, desc = "Add a sticker to your sticker pack.", form = "/addsticker [title]", help = "Reply to sticker/picture.", limit = { reply = true, } } return addsticker
fix(commands/addsticker): add animated/video stickers to dependent sticker sets
fix(commands/addsticker): add animated/video stickers to dependent sticker sets
Lua
apache-2.0
SJoshua/Project-Small-R
869cb0c148f8306b574b5afc3af96a88411faba6
modules/admin-full/luasrc/controller/admin/uci.lua
modules/admin-full/luasrc/controller/admin/uci.lua
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- module("luci.controller.admin.uci", package.seeall) function index() local i18n = luci.i18n.translate entry({"admin", "uci"}, nil, i18n("config")) entry({"admin", "uci", "changes"}, call("action_changes"), i18n("changes"), 40) entry({"admin", "uci", "revert"}, call("action_revert"), i18n("revert"), 30) entry({"admin", "uci", "apply"}, call("action_apply"), i18n("apply"), 20) entry({"admin", "uci", "saveapply"}, call("action_apply"), i18n("saveapply"), 10) end function convert_changes(changes) local ret = {} for r, tbl in pairs(changes) do for s, os in pairs(tbl) do for o, v in pairs(os) do local val, str if (v == "") then str = "-" val = "" else str = "" val = "="..luci.util.pcdata(v) end str = r.."."..s if o ~= ".type" then str = str.."."..o end table.insert(ret, str..val) end end end return table.concat(ret, "\n") end function action_changes() local changes = convert_changes(luci.model.uci.cursor():changes()) luci.template.render("admin_uci/changes", {changes=changes}) end function action_apply() local path = luci.dispatcher.context.path local changes = luci.model.uci.changes() local output = "" local uci = luci.model.uci.cursor() if changes then local com = {} local run = {} -- Collect files to be applied and commit changes for r, tbl in pairs(changes) do if r then if path[#path] ~= "apply" then uci:load(r) uci:commit(r) uci:unload(r) end if luci.config.uci_oncommit and luci.config.uci_oncommit[r] then run[luci.config.uci_oncommit[r]] = true end end end -- Search for post-commit commands for cmd, i in pairs(run) do output = output .. cmd .. ":" .. luci.util.exec(cmd) .. "\n" end end luci.template.render("admin_uci/apply", {changes=convert_changes(changes), output=output}) end function action_revert() local uci = luci.model.uci.cursor() local changes = uci:changes() if changes then local revert = {} -- Collect files to be reverted for r, tbl in pairs(changes) do uci:load(r) uci:revert(r) uci:unload(r) end end luci.template.render("admin_uci/revert", {changes=convert_changes(changes)}) end
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- module("luci.controller.admin.uci", package.seeall) function index() local i18n = luci.i18n.translate entry({"admin", "uci"}, nil, i18n("config")) entry({"admin", "uci", "changes"}, call("action_changes"), i18n("changes"), 40) entry({"admin", "uci", "revert"}, call("action_revert"), i18n("revert"), 30) entry({"admin", "uci", "apply"}, call("action_apply"), i18n("apply"), 20) entry({"admin", "uci", "saveapply"}, call("action_apply"), i18n("saveapply"), 10) end function convert_changes(changes) local ret = {} for r, tbl in pairs(changes) do for s, os in pairs(tbl) do for o, v in pairs(os) do local val, str if (v == "") then str = "-" val = "" else str = "" val = "="..luci.util.pcdata(v) end str = r.."."..s if o ~= ".type" then str = str.."."..o end table.insert(ret, str..val) end end end return table.concat(ret, "\n") end function action_changes() local changes = convert_changes(luci.model.uci.cursor():changes()) luci.template.render("admin_uci/changes", {changes=changes}) end function action_apply() local path = luci.dispatcher.context.path local output = "" local uci = luci.model.uci.cursor() local changes = uci:changes() if changes then local com = {} local run = {} -- Collect files to be applied and commit changes for r, tbl in pairs(changes) do if r then if path[#path] ~= "apply" then uci:load(r) uci:commit(r) uci:unload(r) end if luci.config.uci_oncommit and luci.config.uci_oncommit[r] then run[luci.config.uci_oncommit[r]] = true end end end -- Search for post-commit commands for cmd, i in pairs(run) do output = output .. cmd .. ":" .. luci.util.exec(cmd) .. "\n" end end luci.template.render("admin_uci/apply", {changes=convert_changes(changes), output=output}) end function action_revert() local uci = luci.model.uci.cursor() local changes = uci:changes() if changes then local revert = {} -- Collect files to be reverted for r, tbl in pairs(changes) do uci:load(r) uci:revert(r) uci:unload(r) end end luci.template.render("admin_uci/revert", {changes=convert_changes(changes)}) end
Fix missing UCI transition
Fix missing UCI transition
Lua
apache-2.0
8devices/luci,deepak78/luci,8devices/luci,8devices/luci,deepak78/luci,deepak78/luci,deepak78/luci,deepak78/luci,8devices/luci,deepak78/luci,deepak78/luci,8devices/luci,8devices/luci,deepak78/luci
6eb9566665f2850ae2a4218976bf85bafd707b4c
src/azk/utils/native/uuid.lua
src/azk/utils/native/uuid.lua
local ffi = require("ffi") local libuuid = ffi.os == "OSX" and ffi.C or ffi.load("uuid") local print = print local uuid = {} setfenv(1, uuid) -- TODO: Implemente windows option -- Reference: https://code.google.com/p/lua-files/source/browse/winapi/uuid.lua?r=eaea6fab8c1a9fbbf4d7644ee2b025bf0c98f49c ffi.cdef[[ typedef unsigned char uuid_t[16]; void uuid_generate(uuid_t out); void uuid_unparse(const uuid_t uu, char *out); ]] function new() local buf = ffi.new('uint8_t[16]') local uu = ffi.new('uint8_t[?]', 36) libuuid.uuid_generate(buf) libuuid.uuid_unparse(buf, uu) return ffi.string(uu, 36) end function new_clear(sub) return new():gsub("%-", ""):lower():sub(0, sub or 32) end return uuid
local ffi = require("ffi") local libuuid = ffi.os == "OSX" and ffi.C or ffi.load("uuid.so.1") local uuid = {} -- TODO: Implemente windows option -- Reference: https://code.google.com/p/lua-files/source/browse/winapi/uuid.lua?r=eaea6fab8c1a9fbbf4d7644ee2b025bf0c98f49c ffi.cdef[[ typedef unsigned char uuid_t[16]; void uuid_generate(uuid_t out); void uuid_unparse(const uuid_t uu, char *out); ]] function uuid.new() local buf = ffi.new('uint8_t[16]') local uu = ffi.new('uint8_t[?]', 36) libuuid.uuid_generate(buf) libuuid.uuid_unparse(buf, uu) return ffi.string(uu, 36) end function uuid.new_clear(sub) return uuid.new():gsub("%-", ""):lower():sub(0, sub or 32) end return uuid
Fixing ffi load uuid library.
Fixing ffi load uuid library.
Lua
apache-2.0
agendor/azk,gullitmiranda/azk,Klaudit/azk,juniorribeiro/azk,marcusgadbem/azk,nuxlli/azk,saitodisse/azk-travis-test,heitortsergent/azk,saitodisse/azk,gullitmiranda/azk,fearenales/azk,saitodisse/azk-travis-test,slobo/azk,azukiapp/azk,saitodisse/azk,slobo/azk,renanmpimentel/azk,marcusgadbem/azk,fearenales/azk,Klaudit/azk,teodor-pripoae/azk,juniorribeiro/azk,nuxlli/azk,renanmpimentel/azk,azukiapp/azk,agendor/azk,teodor-pripoae/azk,heitortsergent/azk
4edb586077e75b90a87efe52a01a67ae5c179311
lualib/redis.lua
lualib/redis.lua
local skynet = require "skynet" local socket = require "socket" local socketchannel = require "socketchannel" local table = table local string = string local assert = assert local redis = {} local command = {} local meta = { __index = command, -- DO NOT close channel in __gc } ---------- redis response local redcmd = {} redcmd[36] = function(fd, data) -- '$' local bytes = tonumber(data) if bytes < 0 then return true,nil end local firstline = fd:read(bytes+2) return true,string.sub(firstline,1,-3) end redcmd[43] = function(fd, data) -- '+' return true,data end redcmd[45] = function(fd, data) -- '-' return false,data end redcmd[58] = function(fd, data) -- ':' -- todo: return string later return true, tonumber(data) end local function read_response(fd) local result = fd:readline "\r\n" local firstchar = string.byte(result) local data = string.sub(result,2) return redcmd[firstchar](fd,data) end redcmd[42] = function(fd, data) -- '*' local n = tonumber(data) if n < 0 then return true, nil end local bulk = {} local noerr = true for i = 1,n do local ok, v = read_response(fd) if not ok then noerr = false end bulk[i] = v end return noerr, bulk end ------------------- local function redis_login(auth, db) if auth == nil and db == nil then return end return function(so) if auth then so:request("AUTH "..auth.."\r\n", read_response) end if db then so:request("SELECT "..db.."\r\n", read_response) end end end function redis.connect(db_conf) local channel = socketchannel.channel { host = db_conf.host, port = db_conf.port or 6379, auth = redis_login(db_conf.auth, db_conf.db), nodelay = true, } -- try connect first only once channel:connect(true) return setmetatable( { channel }, meta ) end function command:disconnect() self[1]:close() setmetatable(self, nil) end -- msg could be any type of value local function make_cache(f) return setmetatable({}, { __mode = "kv", __index = f, }) end local header_cache = make_cache(function(t,k) local s = "\r\n$" .. k .. "\r\n" t[k] = s return s end) local command_cache = make_cache(function(t,cmd) local s = "\r\n$"..#cmd.."\r\n"..cmd:upper() t[cmd] = s return s end) local count_cache = make_cache(function(t,k) local s = "*" .. k t[k] = s return s end) local function compose_message(cmd, msg) local t = type(msg) local lines = {} if t == "table" then lines[1] = count_cache[#msg+1] lines[2] = command_cache[cmd] local idx = 3 for _,v in ipairs(msg) do v= tostring(v) lines[idx] = header_cache[#v] lines[idx+1] = v idx = idx + 2 end lines[idx] = "\r\n" else msg = tostring(msg) lines[1] = "*2" lines[2] = command_cache[cmd] lines[3] = header_cache[#msg] lines[4] = msg lines[5] = "\r\n" end return lines end setmetatable(command, { __index = function(t,k) local cmd = string.upper(k) local f = function (self, v, ...) if type(v) == "table" then return self[1]:request(compose_message(cmd, v), read_response) else return self[1]:request(compose_message(cmd, {v, ...}), read_response) end end t[k] = f return f end}) local function read_boolean(so) local ok, result = read_response(so) return ok, result ~= 0 end function command:exists(key) local fd = self[1] return fd:request(compose_message ("EXISTS", key), read_boolean) end function command:sismember(key, value) local fd = self[1] return fd:request(compose_message ("SISMEMBER", {key, value}), read_boolean) end local function compose_table(lines, msg) local tinsert = table.insert tinsert(lines, count_cache[#msg]) for _,v in ipairs(msg) do v = tostring(v) tinsert(lines,header_cache[#v]) tinsert(lines,v) end tinsert(lines, "\r\n") return lines end function command:pipeline(ops,resp) assert(ops and #ops > 0, "pipeline is null") local fd = self[1] local cmds = {} for _, cmd in ipairs(ops) do compose_table(cmds, cmd) end if resp then return fd:request(cmds, function (fd) for i=1, #ops do local ok, out = read_response(fd) table.insert(resp, {ok = ok, out = out}) end return true, resp end) else return fd:request(cmds, function (fd) local ok, out for i=1, #ops do ok, out = read_response(fd) end -- return last response return ok,out end) end end --- watch mode local watch = {} local watchmeta = { __index = watch, __gc = function(self) self.__sock:close() end, } local function watch_login(obj, auth) return function(so) if auth then so:request("AUTH "..auth.."\r\n", read_response) end for k in pairs(obj.__psubscribe) do so:request(compose_message ("PSUBSCRIBE", k)) end for k in pairs(obj.__subscribe) do so:request(compose_message("SUBSCRIBE", k)) end end end function redis.watch(db_conf) local obj = { __subscribe = {}, __psubscribe = {}, } local channel = socketchannel.channel { host = db_conf.host, port = db_conf.port or 6379, auth = watch_login(obj, db_conf.auth), nodelay = true, } obj.__sock = channel -- try connect first only once channel:connect(true) return setmetatable( obj, watchmeta ) end function watch:disconnect() self.__sock:close() setmetatable(self, nil) end local function watch_func( name ) local NAME = string.upper(name) watch[name] = function(self, ...) local so = self.__sock for i = 1, select("#", ...) do local v = select(i, ...) so:request(compose_message(NAME, v)) end end end watch_func "subscribe" watch_func "psubscribe" watch_func "unsubscribe" watch_func "punsubscribe" function watch:message() local so = self.__sock while true do local ret = so:response(read_response) local type , channel, data , data2 = ret[1], ret[2], ret[3], ret[4] if type == "message" then return data, channel elseif type == "pmessage" then return data2, data, channel elseif type == "subscribe" then self.__subscribe[channel] = true elseif type == "psubscribe" then self.__psubscribe[channel] = true elseif type == "unsubscribe" then self.__subscribe[channel] = nil elseif type == "punsubscribe" then self.__psubscribe[channel] = nil end end end return redis
local skynet = require "skynet" local socket = require "socket" local socketchannel = require "socketchannel" local table = table local string = string local assert = assert local redis = {} local command = {} local meta = { __index = command, -- DO NOT close channel in __gc } ---------- redis response local redcmd = {} redcmd[36] = function(fd, data) -- '$' local bytes = tonumber(data) if bytes < 0 then return true,nil end local firstline = fd:read(bytes+2) return true,string.sub(firstline,1,-3) end redcmd[43] = function(fd, data) -- '+' return true,data end redcmd[45] = function(fd, data) -- '-' return false,data end redcmd[58] = function(fd, data) -- ':' -- todo: return string later return true, tonumber(data) end local function read_response(fd) local result = fd:readline "\r\n" local firstchar = string.byte(result) local data = string.sub(result,2) return redcmd[firstchar](fd,data) end redcmd[42] = function(fd, data) -- '*' local n = tonumber(data) if n < 0 then return true, nil end local bulk = {} local noerr = true for i = 1,n do local ok, v = read_response(fd) if not ok then noerr = false end bulk[i] = v end return noerr, bulk end ------------------- local compose_message local function redis_login(auth, db) if auth == nil and db == nil then return end return function(so) if auth then so:request(compose_message("AUTH", auth), read_response) end if db then so:request(compose_message("SELECT", db), read_response) end end end function redis.connect(db_conf) local channel = socketchannel.channel { host = db_conf.host, port = db_conf.port or 6379, auth = redis_login(db_conf.auth, db_conf.db), nodelay = true, } -- try connect first only once channel:connect(true) return setmetatable( { channel }, meta ) end function command:disconnect() self[1]:close() setmetatable(self, nil) end -- msg could be any type of value local function make_cache(f) return setmetatable({}, { __mode = "kv", __index = f, }) end local header_cache = make_cache(function(t,k) local s = "\r\n$" .. k .. "\r\n" t[k] = s return s end) local command_cache = make_cache(function(t,cmd) local s = "\r\n$"..#cmd.."\r\n"..cmd:upper() t[cmd] = s return s end) local count_cache = make_cache(function(t,k) local s = "*" .. k t[k] = s return s end) function compose_message(cmd, msg) local t = type(msg) local lines = {} if t == "table" then lines[1] = count_cache[#msg+1] lines[2] = command_cache[cmd] local idx = 3 for _,v in ipairs(msg) do v= tostring(v) lines[idx] = header_cache[#v] lines[idx+1] = v idx = idx + 2 end lines[idx] = "\r\n" else msg = tostring(msg) lines[1] = "*2" lines[2] = command_cache[cmd] lines[3] = header_cache[#msg] lines[4] = msg lines[5] = "\r\n" end return lines end setmetatable(command, { __index = function(t,k) local cmd = string.upper(k) local f = function (self, v, ...) if type(v) == "table" then return self[1]:request(compose_message(cmd, v), read_response) else return self[1]:request(compose_message(cmd, {v, ...}), read_response) end end t[k] = f return f end}) local function read_boolean(so) local ok, result = read_response(so) return ok, result ~= 0 end function command:exists(key) local fd = self[1] return fd:request(compose_message ("EXISTS", key), read_boolean) end function command:sismember(key, value) local fd = self[1] return fd:request(compose_message ("SISMEMBER", {key, value}), read_boolean) end local function compose_table(lines, msg) local tinsert = table.insert tinsert(lines, count_cache[#msg]) for _,v in ipairs(msg) do v = tostring(v) tinsert(lines,header_cache[#v]) tinsert(lines,v) end tinsert(lines, "\r\n") return lines end function command:pipeline(ops,resp) assert(ops and #ops > 0, "pipeline is null") local fd = self[1] local cmds = {} for _, cmd in ipairs(ops) do compose_table(cmds, cmd) end if resp then return fd:request(cmds, function (fd) for i=1, #ops do local ok, out = read_response(fd) table.insert(resp, {ok = ok, out = out}) end return true, resp end) else return fd:request(cmds, function (fd) local ok, out for i=1, #ops do ok, out = read_response(fd) end -- return last response return ok,out end) end end --- watch mode local watch = {} local watchmeta = { __index = watch, __gc = function(self) self.__sock:close() end, } local function watch_login(obj, auth) return function(so) if auth then so:request(compose_message("AUTH", auth), read_response) end for k in pairs(obj.__psubscribe) do so:request(compose_message ("PSUBSCRIBE", k)) end for k in pairs(obj.__subscribe) do so:request(compose_message("SUBSCRIBE", k)) end end end function redis.watch(db_conf) local obj = { __subscribe = {}, __psubscribe = {}, } local channel = socketchannel.channel { host = db_conf.host, port = db_conf.port or 6379, auth = watch_login(obj, db_conf.auth), nodelay = true, } obj.__sock = channel -- try connect first only once channel:connect(true) return setmetatable( obj, watchmeta ) end function watch:disconnect() self.__sock:close() setmetatable(self, nil) end local function watch_func( name ) local NAME = string.upper(name) watch[name] = function(self, ...) local so = self.__sock for i = 1, select("#", ...) do local v = select(i, ...) so:request(compose_message(NAME, v)) end end end watch_func "subscribe" watch_func "psubscribe" watch_func "unsubscribe" watch_func "punsubscribe" function watch:message() local so = self.__sock while true do local ret = so:response(read_response) local type , channel, data , data2 = ret[1], ret[2], ret[3], ret[4] if type == "message" then return data, channel elseif type == "pmessage" then return data2, data, channel elseif type == "subscribe" then self.__subscribe[channel] = true elseif type == "psubscribe" then self.__psubscribe[channel] = true elseif type == "unsubscribe" then self.__subscribe[channel] = nil elseif type == "punsubscribe" then self.__psubscribe[channel] = nil end end end return redis
修复redis auth操作没有进行compose_message的bug,该bug导致skynet连接twemproxy时,auth失败
修复redis auth操作没有进行compose_message的bug,该bug导致skynet连接twemproxy时,auth失败
Lua
mit
rainfiel/skynet,iskygame/skynet,sundream/skynet,korialuo/skynet,puXiaoyi/skynet,QuiQiJingFeng/skynet,kyle-wang/skynet,nightcj/mmo,xjdrew/skynet,chuenlungwang/skynet,pigparadise/skynet,xinjuncoding/skynet,kyle-wang/skynet,ypengju/skynet_comment,Ding8222/skynet,nightcj/mmo,firedtoad/skynet,asanosoyokaze/skynet,xcjmine/skynet,ag6ag/skynet,bigrpg/skynet,kyle-wang/skynet,QuiQiJingFeng/skynet,zhangshiqian1214/skynet,fztcjjl/skynet,JiessieDawn/skynet,rainfiel/skynet,iskygame/skynet,korialuo/skynet,codingabc/skynet,cdd990/skynet,cloudwu/skynet,xjdrew/skynet,Ding8222/skynet,bigrpg/skynet,icetoggle/skynet,cdd990/skynet,xjdrew/skynet,icetoggle/skynet,jxlczjp77/skynet,zhangshiqian1214/skynet,great90/skynet,icetoggle/skynet,puXiaoyi/skynet,codingabc/skynet,liuxuezhan/skynet,czlc/skynet,JiessieDawn/skynet,letmefly/skynet,letmefly/skynet,asanosoyokaze/skynet,cmingjian/skynet,zhouxiaoxiaoxujian/skynet,puXiaoyi/skynet,QuiQiJingFeng/skynet,wangyi0226/skynet,xcjmine/skynet,fztcjjl/skynet,asanosoyokaze/skynet,wangyi0226/skynet,firedtoad/skynet,Ding8222/skynet,zhangshiqian1214/skynet,sanikoyes/skynet,letmefly/skynet,czlc/skynet,pigparadise/skynet,zhouxiaoxiaoxujian/skynet,hongling0/skynet,wangyi0226/skynet,chuenlungwang/skynet,cloudwu/skynet,nightcj/mmo,cloudwu/skynet,xinjuncoding/skynet,hongling0/skynet,zhangshiqian1214/skynet,bigrpg/skynet,ag6ag/skynet,jxlczjp77/skynet,lawnight/skynet,cmingjian/skynet,sundream/skynet,jxlczjp77/skynet,great90/skynet,sanikoyes/skynet,rainfiel/skynet,cmingjian/skynet,bttscut/skynet,xcjmine/skynet,codingabc/skynet,ypengju/skynet_comment,xinjuncoding/skynet,firedtoad/skynet,ypengju/skynet_comment,fztcjjl/skynet,cdd990/skynet,pigparadise/skynet,zhangshiqian1214/skynet,zhouxiaoxiaoxujian/skynet,chuenlungwang/skynet,lawnight/skynet,letmefly/skynet,JiessieDawn/skynet,liuxuezhan/skynet,bttscut/skynet,sundream/skynet,liuxuezhan/skynet,korialuo/skynet,zhangshiqian1214/skynet,lawnight/skynet,czlc/skynet,sanikoyes/skynet,lawnight/skynet,bttscut/skynet,hongling0/skynet,liuxuezhan/skynet,great90/skynet,iskygame/skynet,ag6ag/skynet
1652a08b8e92048be5a0d3b9e21dd9e895a69f89
preprocess.lua
preprocess.lua
require('onmt.init') local cmd = onmt.utils.ExtendedCmdLine.new('preprocess.lua') -- First argument define the dataType: bitext/monotext - default is bitext. local dataType = cmd.getArgument(arg, '-data_type') or 'bitext' -- Options declaration local options = { { '-data_type', 'bitext', [[Type of data to preprocess. Use 'monotext' for monolingual data. This option impacts all options choices.]], { enum = {'bitext', 'monotext', 'feattext'}, depends = function(opt) return opt.data_type ~= 'feattext' or opt.idx_files end } }, { '-dry_run', false, [[If set, this will only prepare the preprocessor. Useful when using file sampling to test distribution rules.]] }, { '-save_data', '', [[Output file for the prepared data.]], { depends = function(opt) return opt.dry_run, "option `-save_data` is required" end } } } cmd:setCmdLineOptions(options, 'Preprocess') onmt.data.Preprocessor.declareOpts(cmd, dataType) onmt.utils.Logger.declareOpts(cmd) local otherOptions = { { '-seed', 3425, [[Random seed.]], { valid = onmt.utils.ExtendedCmdLine.isUInt() } } } cmd:setCmdLineOptions(otherOptions, 'Other') local opt = cmd:parse(arg) local function main() torch.manualSeed(opt.seed) _G.logger = onmt.utils.Logger.new(opt.log_file, opt.disable_logs, opt.log_level) local Preprocessor = onmt.data.Preprocessor.new(opt, dataType) if opt.dry_run then _G.logger:shutDown() return end local data = { dataType=dataType } -- keep processing options in the structure for further traceability data.opt = opt _G.logger:info('Preparing vocabulary...') data.dicts = Preprocessor:getVocabulary() _G.logger:info('Preparing training data...') data.train = Preprocessor:makeData('train', data.dicts) _G.logger:info('') _G.logger:info('Preparing validation data...') data.valid = Preprocessor:makeData('valid', data.dicts) _G.logger:info('') if dataType == 'monotext' then if opt.vocab:len() == 0 then onmt.data.Vocabulary.save('source', data.dicts.src.words, opt.save_data .. '.dict') end if opt.features_vocabs_prefix:len() == 0 then onmt.data.Vocabulary.saveFeatures('source', data.dicts.src.features, opt.save_data) end elseif dataType == 'feattext' then if opt.tgt_vocab:len() == 0 then onmt.data.Vocabulary.save('target', data.dicts.tgt.words, opt.save_data .. '.tgt.dict') end if opt.features_vocabs_prefix:len() == 0 then onmt.data.Vocabulary.saveFeatures('target', data.dicts.tgt.features, opt.save_data) end else if opt.src_vocab:len() == 0 then onmt.data.Vocabulary.save('source', data.dicts.src.words, opt.save_data .. '.src.dict') end if opt.tgt_vocab:len() == 0 then onmt.data.Vocabulary.save('target', data.dicts.tgt.words, opt.save_data .. '.tgt.dict') end if opt.features_vocabs_prefix:len() == 0 then onmt.data.Vocabulary.saveFeatures('source', data.dicts.src.features, opt.save_data..'.source') onmt.data.Vocabulary.saveFeatures('target', data.dicts.tgt.features, opt.save_data..'.target') end end _G.logger:info('Saving data to \'' .. opt.save_data .. '-train.t7\'...') torch.save(opt.save_data .. '-train.t7', data, 'binary', false) _G.logger:shutDown() end main()
require('onmt.init') local cmd = onmt.utils.ExtendedCmdLine.new('preprocess.lua') -- First argument define the dataType: bitext/monotext - default is bitext. local dataType = cmd.getArgument(arg, '-data_type') or 'bitext' -- Options declaration local options = { { '-data_type', 'bitext', [[Type of data to preprocess. Use 'monotext' for monolingual data. This option impacts all options choices.]], { enum = {'bitext', 'monotext', 'feattext'}, depends = function(opt) return opt.data_type ~= 'feattext' or opt.idx_files end } }, { '-dry_run', false, [[If set, this will only prepare the preprocessor. Useful when using file sampling to test distribution rules.]] }, { '-save_data', '', [[Output file for the prepared data.]], { depends = function(opt) return opt.dry_run or opt.save_data ~= '', "option `-save_data` is required" end } } } cmd:setCmdLineOptions(options, 'Preprocess') onmt.data.Preprocessor.declareOpts(cmd, dataType) onmt.utils.Logger.declareOpts(cmd) local otherOptions = { { '-seed', 3425, [[Random seed.]], { valid = onmt.utils.ExtendedCmdLine.isUInt() } } } cmd:setCmdLineOptions(otherOptions, 'Other') local opt = cmd:parse(arg) local function main() torch.manualSeed(opt.seed) _G.logger = onmt.utils.Logger.new(opt.log_file, opt.disable_logs, opt.log_level) local Preprocessor = onmt.data.Preprocessor.new(opt, dataType) if opt.dry_run then _G.logger:shutDown() return end local data = { dataType=dataType } -- keep processing options in the structure for further traceability data.opt = opt _G.logger:info('Preparing vocabulary...') data.dicts = Preprocessor:getVocabulary() _G.logger:info('Preparing training data...') data.train = Preprocessor:makeData('train', data.dicts) _G.logger:info('') _G.logger:info('Preparing validation data...') data.valid = Preprocessor:makeData('valid', data.dicts) _G.logger:info('') if dataType == 'monotext' then if opt.vocab:len() == 0 then onmt.data.Vocabulary.save('source', data.dicts.src.words, opt.save_data .. '.dict') end if opt.features_vocabs_prefix:len() == 0 then onmt.data.Vocabulary.saveFeatures('source', data.dicts.src.features, opt.save_data) end elseif dataType == 'feattext' then if opt.tgt_vocab:len() == 0 then onmt.data.Vocabulary.save('target', data.dicts.tgt.words, opt.save_data .. '.tgt.dict') end if opt.features_vocabs_prefix:len() == 0 then onmt.data.Vocabulary.saveFeatures('target', data.dicts.tgt.features, opt.save_data) end else if opt.src_vocab:len() == 0 then onmt.data.Vocabulary.save('source', data.dicts.src.words, opt.save_data .. '.src.dict') end if opt.tgt_vocab:len() == 0 then onmt.data.Vocabulary.save('target', data.dicts.tgt.words, opt.save_data .. '.tgt.dict') end if opt.features_vocabs_prefix:len() == 0 then onmt.data.Vocabulary.saveFeatures('source', data.dicts.src.features, opt.save_data..'.source') onmt.data.Vocabulary.saveFeatures('target', data.dicts.tgt.features, opt.save_data..'.target') end end _G.logger:info('Saving data to \'' .. opt.save_data .. '-train.t7\'...') torch.save(opt.save_data .. '-train.t7', data, 'binary', false) _G.logger:shutDown() end main()
Fix -save_vocab option dependency check
Fix -save_vocab option dependency check Fixes #364.
Lua
mit
OpenNMT/OpenNMT,jsenellart-systran/OpenNMT,jsenellart-systran/OpenNMT,jungikim/OpenNMT,jsenellart/OpenNMT,jsenellart-systran/OpenNMT,jungikim/OpenNMT,OpenNMT/OpenNMT,OpenNMT/OpenNMT,jsenellart/OpenNMT,jsenellart/OpenNMT,jungikim/OpenNMT
dba9ba793d9aaec978478e4e7b7e4585d5e4efbd
lua/job.lua
lua/job.lua
local _M = { _VERSION = "1.8.5" } local lock = require "resty.lock" local JOBS = ngx.shared.jobs local ipairs = ipairs local update_time = ngx.update_time local ngx_now = ngx.now local worker_exiting = ngx.worker.exiting local timer_at = ngx.timer.at local ngx_log = ngx.log local INFO, ERR, WARN = ngx.INFO, ngx.ERR, ngx.WARN local pcall, setmetatable = pcall, setmetatable local worker_pid = ngx.worker.pid local tinsert = table.insert local assert = assert local random = math.random local workers = ngx.worker.count() local function now() update_time() return ngx_now() end local main local function set_next_time(self) JOBS:incr(self.key .. ":next", self.interval, now()) end local function get_next_time(self) return JOBS:get(self.key .. ":next") end local function run_job(delay, self, ...) if worker_exiting() then return self:finish(...) end local ok, err = timer_at(delay, main, self, ...) if not ok then ngx_log(ERR, self.key .. " failed to add timer: ", err) self:stop() self:clean() return false end return true end main = function(premature, self, ...) if premature or not self:running() then return self:finish(...) end for _,other in ipairs(self.wait_others) do if not other:completed() then return run_job(0.1, self, ...) end end local mtx = lock:new("jobs", { timeout = 0.1, exptime = 600 }) local remains = mtx:lock(self.key .. ":mtx") if not remains then if self:running() then run_job(0.1, self, ...) end return end if self:suspended() then run_job(0.1, self, ...) mtx:unlock() return end if now() >= get_next_time(self) then local counter = JOBS:incr(self.key .. ":counter", 1, -1) local ok, err = pcall(self.callback, { counter = counter, hup = self.pid == nil }, ...) if not self.pid then self.pid = worker_pid() end if not ok then ngx_log(WARN, self.key, ": ", err) end set_next_time(self) end mtx:unlock() run_job(get_next_time(self) - now() + random(0, workers - 1) / 10, self, ...) end local job = {} -- public api function _M.new(name, callback, interval, finish) local j = { callback = callback, finish_fn = finish, interval = interval, key = name, wait_others = {}, pid = nil } return setmetatable(j, { __index = job }) end function job:run(...) if not self:completed() then ngx_log(INFO, "job ", self.key, " start") JOBS:set(self.key .. ":running", 1) set_next_time(self) return assert(run_job(0, self, ...)) end ngx_log(INFO, "job ", self.key, " already completed") return nil, "completed" end function job:suspend() if not self:suspended() then ngx_log(INFO, "job ", self.key, " suspended") JOBS:set(self.key .. ":suspended", 1) end end function job:resume() if self:suspended() then ngx_log(INFO, "job ", self.key, " resumed") JOBS:delete(self.key .. ":suspended") end end function job:stop() JOBS:delete(self.key .. ":running") JOBS:set(self.key .. ":completed", 1) ngx_log(INFO, "job ", self.key, " stopped") end function job:completed() return JOBS:get(self.key .. ":completed") == 1 end function job:running() return JOBS:get(self.key .. ":running") == 1 end function job:suspended() return JOBS:get(self.key .. ":suspended") == 1 end function job:finish(...) if self.finish_fn then self.finish_fn(...) end return true end function job:wait_for(other) tinsert(self.wait_others, other) end function job:clean() if not self:running() then JOBS:delete(self.key .. ":running") JOBS:delete(self.key .. ":completed") JOBS:delete(self.key .. ":suspended") return true end return false end return _M
local _M = { _VERSION = "1.8.5" } local lock = require "resty.lock" local JOBS = ngx.shared.jobs local ipairs = ipairs local update_time = ngx.update_time local ngx_now = ngx.now local worker_exiting = ngx.worker.exiting local timer_at = ngx.timer.at local ngx_log = ngx.log local INFO, ERR, WARN = ngx.INFO, ngx.ERR, ngx.WARN local pcall, setmetatable = pcall, setmetatable local worker_pid = ngx.worker.pid local tinsert = table.insert local assert = assert local random = math.random local workers = ngx.worker.count() local function now() update_time() return ngx_now() end local main local function set_next_time(self) JOBS:incr(self.key .. ":next", self.interval, now()) end local function get_next_time(self) return JOBS:get(self.key .. ":next") end local function run_job(delay, self, ...) if worker_exiting() then return self:finish(...) end local ok, err = timer_at(delay, main, self, ...) if not ok then ngx_log(ERR, self.key .. " failed to add timer: ", err) self:stop() self:clean() return false end return true end main = function(premature, self, ...) if premature or not self:running() then return self:finish(...) end for _,other in ipairs(self.wait_others) do if not other:completed() then return run_job(0.1, self, ...) end end local mtx = lock:new("jobs", { timeout = 0.1, exptime = 600 }) local remains = mtx:lock(self.key .. ":mtx") if not remains then if self:running() then run_job(0.1, self, ...) end return end if self:suspended() then run_job(0.1, self, ...) mtx:unlock() return end if not self:running() then mtx:unlock() return self:finish(...) end if now() >= get_next_time(self) then local counter = JOBS:incr(self.key .. ":counter", 1, -1) local ok, err = pcall(self.callback, { counter = counter, hup = self.pid == nil }, ...) if not self.pid then self.pid = worker_pid() end if not ok then ngx_log(WARN, self.key, ": ", err) end set_next_time(self) end mtx:unlock() run_job(get_next_time(self) - now() + random(0, workers - 1) / 10, self, ...) end local job = {} -- public api function _M.new(name, callback, interval, finish) local j = { callback = callback, finish_fn = finish, interval = interval, key = name, wait_others = {}, pid = nil } return setmetatable(j, { __index = job }) end function job:run(...) if not self:completed() then ngx_log(INFO, "job ", self.key, " start") JOBS:set(self.key .. ":running", 1) set_next_time(self) return assert(run_job(0, self, ...)) end ngx_log(INFO, "job ", self.key, " already completed") return nil, "completed" end function job:suspend() if not self:suspended() then ngx_log(INFO, "job ", self.key, " suspended") JOBS:set(self.key .. ":suspended", 1) end end function job:resume() if self:suspended() then ngx_log(INFO, "job ", self.key, " resumed") JOBS:delete(self.key .. ":suspended") end end function job:stop() JOBS:delete(self.key .. ":running") JOBS:set(self.key .. ":completed", 1) ngx_log(INFO, "job ", self.key, " stopped") end function job:completed() return JOBS:get(self.key .. ":completed") == 1 end function job:running() return JOBS:get(self.key .. ":running") == 1 end function job:suspended() return JOBS:get(self.key .. ":suspended") == 1 end function job:finish(...) if self.finish_fn then self.finish_fn(...) end return true end function job:wait_for(other) tinsert(self.wait_others, other) end function job:clean() if not self:running() then JOBS:delete(self.key .. ":running") JOBS:delete(self.key .. ":completed") JOBS:delete(self.key .. ":suspended") return true end return false end return _M
fix job
fix job
Lua
bsd-2-clause
ZigzagAK/nginx-resty-auto-healthcheck-config,ZigzagAK/nginx-resty-auto-healthcheck-config
85c960b845dec53dfaaf00cc42ac9a729ea4edb0
premake4.lua
premake4.lua
-- Clean Function -- newaction { trigger = "clean", description = "clean the software", execute = function () print("clean the build...") os.rmdir("./build") print("done.") end } -- A solution contains projects, and defines the available configurations solution "simhub" configurations { "Debug", "Release", "Debug_AWS" } -- pass in platform helper #defines configuration {"macosx"} defines {"build_macosx"} configuration {""} configuration {"linux"} defines {"build_linux"} configuration {""} defines {"__PLATFORM"} configuration "Debug" defines { "DEBUG" } symbols "On" configuration "Debug_AWS" defines { "DEBUG" , "_AWS_SDK" } symbols "On" links { "aws-cpp-sdk-core", "aws-cpp-sdk-polly", "aws-cpp-sdk-text-to-speech" } configuration "Release" defines { "NDEBUG" } flags { "Optimize" } links { "aws-cpp-sdk-core", "aws-cpp-sdk-polly", "aws-cpp-sdk-text-to-speech" } -- A project defines one build target project "simhub" kind "ConsoleApp" language "C++" files { "src/app/**.cpp", "src/app/**.h", "src/common/**.h", "src/common/**.cpp" } configuration {"Debug"} excludes {"src/common/aws/**"} configuration {} includedirs { "src", "src/app", "src/common", "src/libs", "src/libs/variant/include", "src/libs/variant/include/mpark", "src/libs/queue" } links { "zlog", "pthread", "config++" } targetdir ("bin") buildoptions { "--std=c++14" } configuration { "macosx", "Debug" } postbuildcommands { "dsymutil bin/simhub", "gtags" } configuration {} configuration {"linux"} links {"dl"} configuration {""} project "simhub_tests" kind "ConsoleApp" language "C++" files { "src/common/**.h", "src/common/**.cpp", "src/test/**.h", "src/test/**.cpp", "src/app/simhub.cpp", "src/libs/googletest/src/gtest-all.cc" } configuration {"Debug"} excludes {"src/common/aws/**"} configuration {} includedirs { "src/libs/googletest/include", "src/libs/googletest", "src", "src/app", "src/common", "src/libs/variant/include", "src/libs", "src/libs/variant/include/mpark", "src/libs/queue" } links { "dl", "zlog", "pthread", "config++"} targetdir ("bin") buildoptions { "--std=c++14" } project "prepare3d_plugin" kind "SharedLib" language "C++" targetname "prepare3d" targetdir ("bin/plugins") links { 'uv', 'pthread'} files { "src/libs/plugins/prepare3d/**.h", "src/libs/plugins/common/**.cpp", "src/libs/plugins/prepare3d/**.cpp" } includedirs { "src/libs/googletest/include", "src/libs/googletest", "src/common", "src/libs/plugins", "src/libs/variant/include", "src/libs", "src/libs/variant/include/mpark", "src/libs/queue" } buildoptions { "--std=c++14" } project "pokey_plugin" kind "SharedLib" language "C++" targetname "pokey" targetdir ("bin/plugins") links { "bin/plugins/Pokeys" } files { "src/libs/plugins/pokey/**.h", "src/libs/plugins/common/**.cpp", "src/libs/plugins/pokey/**.cpp" } includedirs { "src/libs/googletest/include", "src/libs/googletest", "src/common", "src/libs/plugins", "src/libs/variant/include", "src/libs", "src/libs/variant/include/mpark", "src/libs/queue" } buildoptions { "--std=c++14" }
-- Clean Function -- newaction { trigger = "clean", description = "clean the software", execute = function () print("clean the build...") os.rmdir("./obj") os.remove("./*.make") os.remove("./Makefile") print("done.") end } -- A solution contains projects, and defines the available configurations solution "simhub" configurations { "Debug", "Release", "Debug_AWS" } -- pass in platform helper #defines configuration {"macosx"} defines {"build_macosx"} configuration {""} configuration {"linux"} defines {"build_linux"} configuration {""} defines {"__PLATFORM"} configuration "Debug" defines { "DEBUG" } symbols "On" configuration "Debug_AWS" defines { "DEBUG" , "_AWS_SDK" } symbols "On" links { "aws-cpp-sdk-core", "aws-cpp-sdk-polly", "aws-cpp-sdk-text-to-speech" } configuration "Release" defines { "NDEBUG" } flags { "Optimize" } links { "aws-cpp-sdk-core", "aws-cpp-sdk-polly", "aws-cpp-sdk-text-to-speech" } -- A project defines one build target project "simhub" kind "ConsoleApp" language "C++" files { "src/app/**.cpp", "src/app/**.h", "src/common/**.h", "src/common/**.cpp" } configuration {"Debug"} excludes {"src/common/aws/**"} configuration {} includedirs { "src", "src/app", "src/common", "src/libs", "src/libs/variant/include", "src/libs/variant/include/mpark", "src/libs/queue" } links { "zlog", "pthread", "config++" } targetdir ("bin") buildoptions { "--std=c++14" } configuration { "macosx", "Debug" } postbuildcommands { "dsymutil bin/simhub", "gtags" } configuration {} configuration {"linux"} links {"dl"} configuration {""} project "simhub_tests" kind "ConsoleApp" language "C++" files { "src/common/**.h", "src/common/**.cpp", "src/test/**.h", "src/test/**.cpp", "src/app/simhub.cpp", "src/libs/googletest/src/gtest-all.cc" } configuration {"Debug"} excludes {"src/common/aws/**"} configuration {} includedirs { "src/libs/googletest/include", "src/libs/googletest", "src", "src/app", "src/common", "src/libs/variant/include", "src/libs", "src/libs/variant/include/mpark", "src/libs/queue" } links { "dl", "zlog", "pthread", "config++"} targetdir ("bin") buildoptions { "--std=c++14" } project "prepare3d_plugin" kind "SharedLib" language "C++" targetname "prepare3d" targetdir ("bin/plugins") links { 'uv', 'pthread'} files { "src/libs/plugins/prepare3d/**.h", "src/libs/plugins/common/**.cpp", "src/libs/plugins/prepare3d/**.cpp" } includedirs { "src/libs/googletest/include", "src/libs/googletest", "src/common", "src/libs/plugins", "src/libs/variant/include", "src/libs", "src/libs/variant/include/mpark", "src/libs/queue" } buildoptions { "--std=c++14" } project "pokey_plugin" kind "SharedLib" language "C++" targetname "pokey" targetdir ("bin/plugins") links { "bin/plugins/Pokeys" } files { "src/libs/plugins/pokey/**.h", "src/libs/plugins/common/**.cpp", "src/libs/plugins/pokey/**.cpp" } includedirs { "src/libs/googletest/include", "src/libs/googletest", "src/common", "src/libs/plugins", "src/libs/variant/include", "src/libs", "src/libs/variant/include/mpark", "src/libs/queue" } buildoptions { "--std=c++14" }
fixing clean
fixing clean
Lua
mit
mteichtahl/simhub,lurkerbot/simhub,lurkerbot/simhub,mteichtahl/simhub,lurkerbot/simhub,lurkerbot/simhub,mteichtahl/simhub,mteichtahl/simhub
690121932db90eb58e3397aff474bba55b52f768
premake4.lua
premake4.lua
-- -- Premake4 build script (http://industriousone.com/premake/download) -- solution 'cpp-bench' configurations {'Debug', 'Release'} language 'C++' flags {'ExtraWarnings'} targetdir 'bin' platforms {'x32','x64'} configuration 'Debug' defines { 'DEBUG' } flags { 'Symbols' } configuration 'Release' defines { 'NDEBUG' } flags { 'Symbols', 'Optimize' } project 'benchmark' location 'build' kind 'ConsoleApp' uuid '31BC2F58-F374-4984-B490-F1F08ED02DD3' files { 'src/*.h', 'src/*.cpp', 'test/*.cpp', } includedirs { 'src', } if os.get() == 'windows' then defines { 'WIN32', 'WIN32_LEAN_AND_MEAN', '_WIN32_WINNT=0x0600', '_CRT_SECURE_NO_WARNINGS', '_SCL_SECURE_NO_WARNINGS', 'NOMINMAX', } end if os.get() == 'linux' then buildoptions { '-std=c++11' } defines { '__STDC_LIMIT_MACROS', } end
-- -- Premake4 build script (http://industriousone.com/premake/download) -- solution 'cpp-bench' configurations {'Debug', 'Release'} language 'C++' flags {'ExtraWarnings'} targetdir 'bin' platforms {'x32','x64'} configuration 'Debug' defines { 'DEBUG' } flags { 'Symbols' } configuration 'Release' defines { 'NDEBUG' } flags { 'Symbols', 'Optimize' } project 'benchmark' location 'build' kind 'ConsoleApp' uuid '31BC2F58-F374-4984-B490-F1F08ED02DD3' files { 'src/*.h', 'src/*.cpp', 'test/*.h', 'test/*.cpp', } includedirs { 'src', } if os.get() == 'windows' then defines { 'WIN32', 'WIN32_LEAN_AND_MEAN', '_WIN32_WINNT=0x0600', '_CRT_SECURE_NO_WARNINGS', '_SCL_SECURE_NO_WARNINGS', 'NOMINMAX', } end if os.get() == 'linux' then buildoptions { '-std=c++11' } defines { '__STDC_LIMIT_MACROS', } links { 'rt', } end
linkage fix in linux
linkage fix in linux clock_gettime() need lib 'rt'
Lua
apache-2.0
ichenq/cpp-bench,ichenq/cpp-bench
149880b72c7b56d3936ac248ce1b802d7e1a8c87
core/portmanager.lua
core/portmanager.lua
local config = require "core.configmanager"; local certmanager = require "core.certmanager"; local server = require "net.server"; local log = require "util.logger".init("portmanager"); local multitable = require "util.multitable"; local set = require "util.set"; local table = table; local setmetatable, rawset, rawget = setmetatable, rawset, rawget; local type, tonumber, ipairs, pairs = type, tonumber, ipairs, pairs; local prosody = prosody; local fire_event = prosody.events.fire_event; module "portmanager"; --- Config local default_interfaces = { "*" }; local default_local_interfaces = { "127.0.0.1" }; if config.get("*", "use_ipv6") then table.insert(default_interfaces, "::"); table.insert(default_local_interfaces, "::1"); end --- Private state -- service_name -> { service_info, ... } local services = setmetatable({}, { __index = function (t, k) rawset(t, k, {}); return rawget(t, k); end }); -- service_name, interface (string), port (number) local active_services = multitable.new(); --- Private helpers local function error_to_friendly_message(service_name, port, err) local friendly_message = err; if err:match(" in use") then -- FIXME: Use service_name here if port == 5222 or port == 5223 or port == 5269 then friendly_message = "check that Prosody or another XMPP server is " .."not already running and using this port"; elseif port == 80 or port == 81 then friendly_message = "check that a HTTP server is not already using " .."this port"; elseif port == 5280 then friendly_message = "check that Prosody or a BOSH connection manager " .."is not already running"; else friendly_message = "this port is in use by another application"; end elseif err:match("permission") then friendly_message = "Prosody does not have sufficient privileges to use this port"; elseif err == "no ssl context" then if not config.get("*", "core", "ssl") then friendly_message = "there is no 'ssl' config under Host \"*\" which is " .."require for legacy SSL ports"; else friendly_message = "initializing SSL support failed, see previous log entries"; end end return friendly_message; end prosody.events.add_handler("item-added/net-provider", function (event) local item = event.item; register_service(item.name, item); end); prosody.events.add_handler("item-removed/net-provider", function (event) local item = event.item; unregister_service(item.name, item); end); --- Public API function activate(service_name) local service_info = services[service_name][1]; if not service_info then return nil, "Unknown service: "..service_name; end local listener = service_info.listener; local config_prefix = (service_info.config_prefix or service_name).."_"; if config_prefix == "_" then config_prefix = ""; end local bind_interfaces = config.get("*", config_prefix.."interfaces") or config.get("*", config_prefix.."interface") -- COMPAT w/pre-0.9 or (service_info.private and default_local_interfaces) or config.get("*", "interfaces") or config.get("*", "interface") -- COMPAT w/pre-0.9 or listener.default_interface -- COMPAT w/pre0.9 or default_interfaces bind_interfaces = set.new(type(bind_interfaces)~="table" and {bind_interfaces} or bind_interfaces); local bind_ports = set.new(config.get("*", config_prefix.."ports") or service_info.default_ports or {service_info.default_port or listener.default_port -- COMPAT w/pre-0.9 }); local mode, ssl = listener.default_mode or "*a"; for interface in bind_interfaces do for port in bind_ports do port = tonumber(port); if #active_services:search(nil, interface, port) > 0 then log("error", "Multiple services configured to listen on the same port ([%s]:%d): %s, %s", interface, port, active_services:search(nil, interface, port)[1][1].service.name or "<unnamed>", service_name or "<unnamed>"); else -- Create SSL context for this service/port if service_info.encryption == "ssl" then local ssl_config = config.get("*", config_prefix.."ssl"); ssl = certmanager.create_context(service_info.name.." port "..port, "server", ssl_config and (ssl_config[port] or (ssl_config.certificate and ssl_config))); end -- Start listening on interface+port local handler, err = server.addserver(interface, port, listener, mode, ssl); if not handler then log("error", "Failed to open server port %d on %s, %s", port, interface, error_to_friendly_message(service_name, port, err)); else log("debug", "Added listening service %s to [%s]:%d", service_name, interface, port); active_services:add(service_name, interface, port, { server = handler; service = service_info; }); end end end end log("info", "Activated service '%s'", service_name); return true; end function deactivate(service_name) local active = active_services:search(service_name)[1]; if not active then return; end for interface, ports in pairs(active) do for port, active_service in pairs(ports) do close(interface, port); end end log("info", "Deactivated service '%s'", service_name); end function register_service(service_name, service_info) table.insert(services[service_name], service_info); if not active_services:get(service_name) then log("debug", "No active service for %s, activating...", service_name); local ok, err = activate(service_name); if not ok then log("error", "Failed to activate service '%s': %s", service_name, err or "unknown error"); end end fire_event("service-added", { name = service_name, service = service_info }); return true; end function unregister_service(service_name, service_info) local service_info_list = services[service_name]; for i, service in ipairs(service_info_list) do if service == service_info then table.remove(service_info_list, i); end end if active_services[service_name] == service_info then deactivate(service_name); if #service_info_list > 0 then -- Other services registered with this name activate(service_name); -- Re-activate with the next available one end end fire_event("service-removed", { name = service_name, service = service_info }); end function close(interface, port) local service, server = get_service_at(interface, port); if not service then return false, "port-not-open"; end server:close(); active_services:remove(service.name, interface, port); log("debug", "Removed listening service %s from [%s]:%d", service.name, interface, port); return true; end function get_service_at(interface, port) local data = active_services:search(nil, interface, port)[1][1]; return data.service, data.server; end function get_service(service_name) return services[service_name]; end function get_active_services(...) return active_services; end function get_registered_services() return services; end return _M;
local config = require "core.configmanager"; local certmanager = require "core.certmanager"; local server = require "net.server"; local log = require "util.logger".init("portmanager"); local multitable = require "util.multitable"; local set = require "util.set"; local table = table; local setmetatable, rawset, rawget = setmetatable, rawset, rawget; local type, tonumber, ipairs, pairs = type, tonumber, ipairs, pairs; local prosody = prosody; local fire_event = prosody.events.fire_event; module "portmanager"; --- Config local default_interfaces = { "*" }; local default_local_interfaces = { "127.0.0.1" }; if config.get("*", "use_ipv6") then table.insert(default_interfaces, "::"); table.insert(default_local_interfaces, "::1"); end --- Private state -- service_name -> { service_info, ... } local services = setmetatable({}, { __index = function (t, k) rawset(t, k, {}); return rawget(t, k); end }); -- service_name, interface (string), port (number) local active_services = multitable.new(); --- Private helpers local function error_to_friendly_message(service_name, port, err) local friendly_message = err; if err:match(" in use") then -- FIXME: Use service_name here if port == 5222 or port == 5223 or port == 5269 then friendly_message = "check that Prosody or another XMPP server is " .."not already running and using this port"; elseif port == 80 or port == 81 then friendly_message = "check that a HTTP server is not already using " .."this port"; elseif port == 5280 then friendly_message = "check that Prosody or a BOSH connection manager " .."is not already running"; else friendly_message = "this port is in use by another application"; end elseif err:match("permission") then friendly_message = "Prosody does not have sufficient privileges to use this port"; elseif err == "no ssl context" then if not config.get("*", "core", "ssl") then friendly_message = "there is no 'ssl' config under Host \"*\" which is " .."require for legacy SSL ports"; else friendly_message = "initializing SSL support failed, see previous log entries"; end end return friendly_message; end prosody.events.add_handler("item-added/net-provider", function (event) local item = event.item; register_service(item.name, item); end); prosody.events.add_handler("item-removed/net-provider", function (event) local item = event.item; unregister_service(item.name, item); end); --- Public API function activate(service_name) local service_info = services[service_name][1]; if not service_info then return nil, "Unknown service: "..service_name; end local listener = service_info.listener; local config_prefix = (service_info.config_prefix or service_name).."_"; if config_prefix == "_" then config_prefix = ""; end local bind_interfaces = config.get("*", config_prefix.."interfaces") or config.get("*", config_prefix.."interface") -- COMPAT w/pre-0.9 or (service_info.private and default_local_interfaces) or config.get("*", "interfaces") or config.get("*", "interface") -- COMPAT w/pre-0.9 or listener.default_interface -- COMPAT w/pre0.9 or default_interfaces bind_interfaces = set.new(type(bind_interfaces)~="table" and {bind_interfaces} or bind_interfaces); local bind_ports = set.new(config.get("*", config_prefix.."ports") or service_info.default_ports or {service_info.default_port or listener.default_port -- COMPAT w/pre-0.9 }); local mode, ssl = listener.default_mode or "*a"; for interface in bind_interfaces do for port in bind_ports do port = tonumber(port); if #active_services:search(nil, interface, port) > 0 then log("error", "Multiple services configured to listen on the same port ([%s]:%d): %s, %s", interface, port, active_services:search(nil, interface, port)[1][1].service.name or "<unnamed>", service_name or "<unnamed>"); else -- Create SSL context for this service/port if service_info.encryption == "ssl" then local ssl_config = config.get("*", config_prefix.."ssl"); ssl = certmanager.create_context(service_info.name.." port "..port, "server", ssl_config and (ssl_config[port] or (ssl_config.certificate and ssl_config))); end -- Start listening on interface+port local handler, err = server.addserver(interface, port, listener, mode, ssl); if not handler then log("error", "Failed to open server port %d on %s, %s", port, interface, error_to_friendly_message(service_name, port, err)); else log("debug", "Added listening service %s to [%s]:%d", service_name, interface, port); active_services:add(service_name, interface, port, { server = handler; service = service_info; }); end end end end log("info", "Activated service '%s'", service_name); return true; end function deactivate(service_name, service_info) for name, interface, port, active_service in active_services:iter(service_name, nil, nil, service_info) do close(interface, port); end log("info", "Deactivated service '%s'", service_name or service_info.name); end function register_service(service_name, service_info) table.insert(services[service_name], service_info); if not active_services:get(service_name) then log("debug", "No active service for %s, activating...", service_name); local ok, err = activate(service_name); if not ok then log("error", "Failed to activate service '%s': %s", service_name, err or "unknown error"); end end fire_event("service-added", { name = service_name, service = service_info }); return true; end function unregister_service(service_name, service_info) log("debug", "Unregistering service: %s", service_name); local service_info_list = services[service_name]; for i, service in ipairs(service_info_list) do if service == service_info then table.remove(service_info_list, i); end end deactivate(nil, service_info); if #service_info_list > 0 then -- Other services registered with this name activate(service_name); -- Re-activate with the next available one end fire_event("service-removed", { name = service_name, service = service_info }); end function close(interface, port) local service, server = get_service_at(interface, port); if not service then return false, "port-not-open"; end server:close(); active_services:remove(service.name, interface, port); log("debug", "Removed listening service %s from [%s]:%d", service.name, interface, port); return true; end function get_service_at(interface, port) local data = active_services:search(nil, interface, port)[1][1]; return data.service, data.server; end function get_service(service_name) return services[service_name]; end function get_active_services(...) return active_services; end function get_registered_services() return services; end return _M;
portmanager: Fix to deactivate services when they are unregistered (metatable:iter() wins)
portmanager: Fix to deactivate services when they are unregistered (metatable:iter() wins)
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
e022ddc9f78118a98b7a90c6318e492dd452f93f
otouto/plugins/notify.lua
otouto/plugins/notify.lua
-- INFO: Stats must be activated, so that it can collect all members of a group and save his/her id to redis. -- You can deactivate it afterwards. local notify = {} function notify:init(config) notify.triggers = { "^/notify (del)$", "^/notify$" } notify.doc = [[* ]]..config.cmd_pat..[[notify* (del): Benachrichtigt dich privat, wenn du erwähnt wirst (bzw. schaltet das Feature wieder aus)]] end notify.command = 'notify [del]' -- See https://stackoverflow.com/a/32854917 function isWordFoundInString(word,input) return select(2,input:gsub('^' .. word .. '%W+','')) + select(2,input:gsub('%W+' .. word .. '$','')) + select(2,input:gsub('^' .. word .. '$','')) + select(2,input:gsub('%W+' .. word .. '%W+','')) > 0 end function notify:pre_process(msg, self) local notify_users = redis:smembers('notify:ls') -- I call this beautiful lady the "if soup" if msg.chat.type == 'chat' or msg.chat.type == 'supergroup' then if msg.text then for _,user in pairs(notify_users) do if isWordFoundInString('@'..user, string.lower(msg.text)) then local chat_id = msg.chat.id local id = redis:hget('notify:'..user, 'id') -- check, if user has sent at least one message to the group, -- so that we don't send the user some private text, when he/she is not -- in the group. if redis:sismember('chat:'..chat_id..':users', id) then -- ignore message, if user is mentioning him/herself if id == tostring(msg.from.id) then break; end local send_date = run_command('date -d @'..msg.date..' +"%d.%m.%Y um %H:%M:%S Uhr"') local send_date = string.gsub(send_date, "\n", "") local from = string.gsub(msg.from.name, "%_", " ") local chat_name = string.gsub(msg.chat.title, "%_", " ") local text = from..' am '..send_date..' in "'..chat_name..'":\n\n'..msg.text utilities.send_message(self, id, text, true) end end end end end return msg end function notify:action(msg, config, matches) if not msg.from.username then utilities.send_reply(self, msg, 'Du hast keinen Usernamen und kannst daher dieses Feature nicht nutzen. Tut mir leid!' ) return end local username = string.lower(msg.from.username) local hash = 'notify:'..username if matches[1] == "del" then if not redis:sismember('notify:ls', username) then utilities.send_reply(self, msg, 'Du wirst noch gar nicht benachrichtigt!') return end print('Setting notify in redis hash '..hash..' to false') redis:hset(hash, 'notify', false) print('Removing '..username..' from redis set notify:ls') redis:srem('notify:ls', username) utilities.send_reply(self, msg, 'Du erhälst jetzt keine Benachrichtigungen mehr, wenn du angesprochen wirst.') return else if redis:sismember('notify:ls', username) then utilities.send_reply(self, msg, 'Du wirst schon benachrichtigt!') return end print('Setting notify in redis hash '..hash..' to true') redis:hset(hash, 'notify', true) print('Setting id in redis hash '..hash..' to '..msg.from.id) redis:hset(hash, 'id', msg.from.id) print('Adding '..username..' to redis set notify:ls') redis:sadd('notify:ls', username) local res = utilities.send_message(self, msg.from.id, 'Du erhälst jetzt Benachrichtigungen, wenn du angesprochen wirst, nutze `/notify del` zum Deaktivieren.', true, nil, true) if not res then utilities.send_reply(self, msg, 'Bitte schreibe mir [privat](http://telegram.me/' .. self.info.username .. '?start=notify), um den Vorgang abzuschließen.', true) elseif msg.chat.type ~= 'private' then utilities.send_reply(self, msg, 'Du erhälst jetzt Benachrichtigungen, wenn du angesprochen wirst, nutze `/notify del` zum Deaktivieren.', true) end end end return notify
-- INFO: Stats must be activated, so that it can collect all members of a group and save his/her id to redis. -- You can deactivate it afterwards. local notify = {} function notify:init(config) notify.triggers = { "^/notify (del)$", "^/notify$" } notify.doc = [[* ]]..config.cmd_pat..[[notify* (del): Benachrichtigt dich privat, wenn du erwähnt wirst (bzw. schaltet das Feature wieder aus)]] end notify.command = 'notify [del]' -- See https://stackoverflow.com/a/32854917 function isWordFoundInString(word,input) return select(2,input:gsub('^' .. word .. '%W+','')) + select(2,input:gsub('%W+' .. word .. '$','')) + select(2,input:gsub('^' .. word .. '$','')) + select(2,input:gsub('%W+' .. word .. '%W+','')) > 0 end function notify:pre_process(msg, self) local notify_users = redis:smembers('notify:ls') -- I call this beautiful lady the "if soup" if msg.chat.type == 'chat' or msg.chat.type == 'supergroup' then if msg.text then for _,user in pairs(notify_users) do if isWordFoundInString('@'..user, string.lower(msg.text)) then local chat_id = msg.chat.id local id = redis:hget('notify:'..user, 'id') -- check, if user has sent at least one message to the group, -- so that we don't send the user some private text, when he/she is not -- in the group. if redis:sismember('chat:'..chat_id..':users', id) then -- ignore message, if user is mentioning him/herself if id ~= tostring(msg.from.id) then local send_date = run_command('date -d @'..msg.date..' +"%d.%m.%Y um %H:%M:%S Uhr"') local send_date = string.gsub(send_date, "\n", "") local from = string.gsub(msg.from.name, "%_", " ") local chat_name = string.gsub(msg.chat.title, "%_", " ") local text = from..' am '..send_date..' in "'..chat_name..'":\n\n'..msg.text utilities.send_message(self, id, text, true) end end end end end end return msg end function notify:action(msg, config, matches) if not msg.from.username then utilities.send_reply(self, msg, 'Du hast keinen Usernamen und kannst daher dieses Feature nicht nutzen. Tut mir leid!' ) return end local username = string.lower(msg.from.username) local hash = 'notify:'..username if matches[1] == "del" then if not redis:sismember('notify:ls', username) then utilities.send_reply(self, msg, 'Du wirst noch gar nicht benachrichtigt!') return end print('Setting notify in redis hash '..hash..' to false') redis:hset(hash, 'notify', false) print('Removing '..username..' from redis set notify:ls') redis:srem('notify:ls', username) utilities.send_reply(self, msg, 'Du erhälst jetzt keine Benachrichtigungen mehr, wenn du angesprochen wirst.') return else if redis:sismember('notify:ls', username) then utilities.send_reply(self, msg, 'Du wirst schon benachrichtigt!') return end print('Setting notify in redis hash '..hash..' to true') redis:hset(hash, 'notify', true) print('Setting id in redis hash '..hash..' to '..msg.from.id) redis:hset(hash, 'id', msg.from.id) print('Adding '..username..' to redis set notify:ls') redis:sadd('notify:ls', username) local res = utilities.send_message(self, msg.from.id, 'Du erhälst jetzt Benachrichtigungen, wenn du angesprochen wirst, nutze `/notify del` zum Deaktivieren.', true, nil, true) if not res then utilities.send_reply(self, msg, 'Bitte schreibe mir [privat](http://telegram.me/' .. self.info.username .. '?start=notify), um den Vorgang abzuschließen.', true) elseif msg.chat.type ~= 'private' then utilities.send_reply(self, msg, 'Du erhälst jetzt Benachrichtigungen, wenn du angesprochen wirst, nutze `/notify del` zum Deaktivieren.', true) end end end return notify
Fixe Notify
Fixe Notify
Lua
agpl-3.0
Brawl345/Brawlbot-v2
8ca5450e22e17095cadf3e87b1bd9520241457a2
rootfs/etc/nginx/lua/balancer/ewma.lua
rootfs/etc/nginx/lua/balancer/ewma.lua
-- Original Authors: Shiv Nagarajan & Scott Francis -- Accessed: March 12, 2018 -- Inspiration drawn from: -- https://github.com/twitter/finagle/blob/1bc837c4feafc0096e43c0e98516a8e1c50c4421 -- /finagle-core/src/main/scala/com/twitter/finagle/loadbalancer/PeakEwma.scala local resty_lock = require("resty.lock") local util = require("util") local split = require("util.split") local ngx = ngx local math = math local pairs = pairs local ipairs = ipairs local tostring = tostring local string = string local tonumber = tonumber local setmetatable = setmetatable local string_format = string.format local ngx_log = ngx.log local INFO = ngx.INFO local DECAY_TIME = 10 -- this value is in seconds local LOCK_KEY = ":ewma_key" local PICK_SET_SIZE = 2 local ewma_lock, ewma_lock_err = resty_lock:new("balancer_ewma_locks", {timeout = 0, exptime = 0.1}) if not ewma_lock then error(ewma_lock_err) end local _M = { name = "ewma" } local function lock(upstream) local _, err = ewma_lock:lock(upstream .. LOCK_KEY) if err then if err ~= "timeout" then ngx.log(ngx.ERR, string.format("EWMA Balancer failed to lock: %s", tostring(err))) end end return err end local function unlock() local ok, err = ewma_lock:unlock() if not ok then ngx.log(ngx.ERR, string.format("EWMA Balancer failed to unlock: %s", tostring(err))) end return err end local function decay_ewma(ewma, last_touched_at, rtt, now) local td = now - last_touched_at td = (td > 0) and td or 0 local weight = math.exp(-td/DECAY_TIME) ewma = ewma * weight + rtt * (1.0 - weight) return ewma end local function store_stats(upstream, ewma, now) local success, err, forcible = ngx.shared.balancer_ewma_last_touched_at:set(upstream, now) if not success then ngx.log(ngx.WARN, "balancer_ewma_last_touched_at:set failed " .. err) end if forcible then ngx.log(ngx.WARN, "balancer_ewma_last_touched_at:set valid items forcibly overwritten") end success, err, forcible = ngx.shared.balancer_ewma:set(upstream, ewma) if not success then ngx.log(ngx.WARN, "balancer_ewma:set failed " .. err) end if forcible then ngx.log(ngx.WARN, "balancer_ewma:set valid items forcibly overwritten") end end local function get_or_update_ewma(upstream, rtt, update) local lock_err = nil if update then lock_err = lock(upstream) end local ewma = ngx.shared.balancer_ewma:get(upstream) or 0 if lock_err ~= nil then return ewma, lock_err end local now = ngx.now() local last_touched_at = ngx.shared.balancer_ewma_last_touched_at:get(upstream) or 0 ewma = decay_ewma(ewma, last_touched_at, rtt, now) if not update then return ewma, nil end store_stats(upstream, ewma, now) unlock() return ewma, nil end local function score(upstream) -- Original implementation used names -- Endpoints don't have names, so passing in IP:Port as key instead local upstream_name = upstream.address .. ":" .. upstream.port return get_or_update_ewma(upstream_name, 0, false) end -- implementation similar to https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle -- or https://en.wikipedia.org/wiki/Random_permutation -- loop from 1 .. k -- pick a random value r from the remaining set of unpicked values (i .. n) -- swap the value at position i with the value at position r local function shuffle_peers(peers, k) for i=1, k do local rand_index = math.random(i,#peers) peers[i], peers[rand_index] = peers[rand_index], peers[i] end -- peers[1 .. k] will now contain a randomly selected k from #peers end local function pick_and_score(peers, k) shuffle_peers(peers, k) local lowest_score_index = 1 local lowest_score = score(peers[lowest_score_index]) for i = 2, k do local new_score = score(peers[i]) if new_score < lowest_score then lowest_score_index, lowest_score = i, new_score end end return peers[lowest_score_index], lowest_score end -- slow_start_ewma is something we use to avoid sending too many requests -- to the newly introduced endpoints. We currently use average ewma values -- of existing endpoints. local function calculate_slow_start_ewma(self) local total_ewma = 0 local endpoints_count = 0 for _, endpoint in pairs(self.peers) do local endpoint_string = endpoint.address .. ":" .. endpoint.port local ewma = ngx.shared.balancer_ewma:get(endpoint_string) if ewma then endpoints_count = endpoints_count + 1 total_ewma = total_ewma + ewma end end if endpoints_count == 0 then ngx.log(ngx.INFO, "no ewma value exists for the endpoints") return nil end return total_ewma / endpoints_count end function _M.balance(self) local peers = self.peers local endpoint, ewma_score = peers[1], -1 if #peers > 1 then local k = (#peers < PICK_SET_SIZE) and #peers or PICK_SET_SIZE local peer_copy = util.deepcopy(peers) endpoint, ewma_score = pick_and_score(peer_copy, k) end ngx.var.balancer_ewma_score = ewma_score -- TODO(elvinefendi) move this processing to _M.sync return endpoint.address .. ":" .. endpoint.port end function _M.after_balance(_) local response_time = tonumber(split.get_first_value(ngx.var.upstream_response_time)) or 0 local connect_time = tonumber(split.get_first_value(ngx.var.upstream_connect_time)) or 0 local rtt = connect_time + response_time local upstream = split.get_first_value(ngx.var.upstream_addr) if util.is_blank(upstream) then return end get_or_update_ewma(upstream, rtt, true) end function _M.sync(self, backend) local normalized_endpoints_added, normalized_endpoints_removed = util.diff_endpoints(self.peers, backend.endpoints) if #normalized_endpoints_added == 0 and #normalized_endpoints_removed == 0 then ngx.log(ngx.INFO, "endpoints did not change for backend " .. tostring(backend.name)) return end ngx_log(INFO, string_format("[%s] peers have changed for backend %s", self.name, backend.name)) self.traffic_shaping_policy = backend.trafficShapingPolicy self.alternative_backends = backend.alternativeBackends self.peers = backend.endpoints for _, endpoint_string in ipairs(normalized_endpoints_removed) do ngx.shared.balancer_ewma:delete(endpoint_string) ngx.shared.balancer_ewma_last_touched_at:delete(endpoint_string) end local slow_start_ewma = calculate_slow_start_ewma(self) if slow_start_ewma ~= nil then local now = ngx.now() for _, endpoint_string in ipairs(normalized_endpoints_added) do store_stats(endpoint_string, slow_start_ewma, now) end end end function _M.new(self, backend) local o = { peers = backend.endpoints, traffic_shaping_policy = backend.trafficShapingPolicy, alternative_backends = backend.alternativeBackends, } setmetatable(o, self) self.__index = self return o end return _M
-- Original Authors: Shiv Nagarajan & Scott Francis -- Accessed: March 12, 2018 -- Inspiration drawn from: -- https://github.com/twitter/finagle/blob/1bc837c4feafc0096e43c0e98516a8e1c50c4421 -- /finagle-core/src/main/scala/com/twitter/finagle/loadbalancer/PeakEwma.scala local resty_lock = require("resty.lock") local util = require("util") local split = require("util.split") local ngx = ngx local math = math local pairs = pairs local ipairs = ipairs local tostring = tostring local string = string local tonumber = tonumber local setmetatable = setmetatable local string_format = string.format local ngx_log = ngx.log local INFO = ngx.INFO local DECAY_TIME = 10 -- this value is in seconds local LOCK_KEY = ":ewma_key" local PICK_SET_SIZE = 2 local ewma_lock, ewma_lock_err = resty_lock:new("balancer_ewma_locks", {timeout = 0, exptime = 0.1}) if not ewma_lock then error(ewma_lock_err) end local _M = { name = "ewma" } local function lock(upstream) local _, err = ewma_lock:lock(upstream .. LOCK_KEY) if err then if err ~= "timeout" then ngx.log(ngx.ERR, string.format("EWMA Balancer failed to lock: %s", tostring(err))) end end return err end local function unlock() local ok, err = ewma_lock:unlock() if not ok then ngx.log(ngx.ERR, string.format("EWMA Balancer failed to unlock: %s", tostring(err))) end return err end local function decay_ewma(ewma, last_touched_at, rtt, now) local td = now - last_touched_at td = (td > 0) and td or 0 local weight = math.exp(-td/DECAY_TIME) ewma = ewma * weight + rtt * (1.0 - weight) return ewma end local function store_stats(upstream, ewma, now) local success, err, forcible = ngx.shared.balancer_ewma_last_touched_at:set(upstream, now) if not success then ngx.log(ngx.WARN, "balancer_ewma_last_touched_at:set failed " .. err) end if forcible then ngx.log(ngx.WARN, "balancer_ewma_last_touched_at:set valid items forcibly overwritten") end success, err, forcible = ngx.shared.balancer_ewma:set(upstream, ewma) if not success then ngx.log(ngx.WARN, "balancer_ewma:set failed " .. err) end if forcible then ngx.log(ngx.WARN, "balancer_ewma:set valid items forcibly overwritten") end end local function get_or_update_ewma(upstream, rtt, update) local lock_err = nil if update then lock_err = lock(upstream) end local ewma = ngx.shared.balancer_ewma:get(upstream) or 0 if lock_err ~= nil then return ewma, lock_err end local now = ngx.now() local last_touched_at = ngx.shared.balancer_ewma_last_touched_at:get(upstream) or 0 ewma = decay_ewma(ewma, last_touched_at, rtt, now) if not update then return ewma, nil end store_stats(upstream, ewma, now) unlock() return ewma, nil end local function score(upstream) -- Original implementation used names -- Endpoints don't have names, so passing in IP:Port as key instead local upstream_name = upstream.address .. ":" .. upstream.port return get_or_update_ewma(upstream_name, 0, false) end -- implementation similar to https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle -- or https://en.wikipedia.org/wiki/Random_permutation -- loop from 1 .. k -- pick a random value r from the remaining set of unpicked values (i .. n) -- swap the value at position i with the value at position r local function shuffle_peers(peers, k) for i=1, k do local rand_index = math.random(i,#peers) peers[i], peers[rand_index] = peers[rand_index], peers[i] end -- peers[1 .. k] will now contain a randomly selected k from #peers end local function pick_and_score(peers, k) shuffle_peers(peers, k) local lowest_score_index = 1 local lowest_score = score(peers[lowest_score_index]) for i = 2, k do local new_score = score(peers[i]) if new_score < lowest_score then lowest_score_index, lowest_score = i, new_score end end return peers[lowest_score_index], lowest_score end -- slow_start_ewma is something we use to avoid sending too many requests -- to the newly introduced endpoints. We currently use average ewma values -- of existing endpoints. local function calculate_slow_start_ewma(self) local total_ewma = 0 local endpoints_count = 0 for _, endpoint in pairs(self.peers) do local endpoint_string = endpoint.address .. ":" .. endpoint.port local ewma = ngx.shared.balancer_ewma:get(endpoint_string) if ewma then endpoints_count = endpoints_count + 1 total_ewma = total_ewma + ewma end end if endpoints_count == 0 then ngx.log(ngx.INFO, "no ewma value exists for the endpoints") return nil end return total_ewma / endpoints_count end function _M.balance(self) local peers = self.peers local endpoint, ewma_score = peers[1], -1 if #peers > 1 then local k = (#peers < PICK_SET_SIZE) and #peers or PICK_SET_SIZE local peer_copy = util.deepcopy(peers) endpoint, ewma_score = pick_and_score(peer_copy, k) end ngx.var.balancer_ewma_score = ewma_score -- TODO(elvinefendi) move this processing to _M.sync return endpoint.address .. ":" .. endpoint.port end function _M.after_balance(_) local response_time = tonumber(split.get_first_value(ngx.var.upstream_response_time)) or 0 local connect_time = tonumber(split.get_first_value(ngx.var.upstream_connect_time)) or 0 local rtt = connect_time + response_time local upstream = split.get_first_value(ngx.var.upstream_addr) if util.is_blank(upstream) then return end get_or_update_ewma(upstream, rtt, true) end function _M.sync(self, backend) self.traffic_shaping_policy = backend.trafficShapingPolicy self.alternative_backends = backend.alternativeBackends local normalized_endpoints_added, normalized_endpoints_removed = util.diff_endpoints(self.peers, backend.endpoints) if #normalized_endpoints_added == 0 and #normalized_endpoints_removed == 0 then ngx.log(ngx.INFO, "endpoints did not change for backend " .. tostring(backend.name)) return end ngx_log(INFO, string_format("[%s] peers have changed for backend %s", self.name, backend.name)) self.peers = backend.endpoints for _, endpoint_string in ipairs(normalized_endpoints_removed) do ngx.shared.balancer_ewma:delete(endpoint_string) ngx.shared.balancer_ewma_last_touched_at:delete(endpoint_string) end local slow_start_ewma = calculate_slow_start_ewma(self) if slow_start_ewma ~= nil then local now = ngx.now() for _, endpoint_string in ipairs(normalized_endpoints_added) do store_stats(endpoint_string, slow_start_ewma, now) end end end function _M.new(self, backend) local o = { peers = backend.endpoints, traffic_shaping_policy = backend.trafficShapingPolicy, alternative_backends = backend.alternativeBackends, } setmetatable(o, self) self.__index = self return o end return _M
bugfix: always update trafficShapingPolicy when using ewma as load-balance even if endpoints not change, otherwise update trafficShapingPolicy will not working
bugfix: always update trafficShapingPolicy when using ewma as load-balance even if endpoints not change, otherwise update trafficShapingPolicy will not working
Lua
apache-2.0
canhnt/ingress,aledbf/ingress-nginx,caicloud/ingress,kubernetes/ingress-nginx,aledbf/ingress-nginx,canhnt/ingress,caicloud/ingress,kubernetes/ingress-nginx,caicloud/ingress,caicloud/ingress,canhnt/ingress,kubernetes/ingress-nginx,aledbf/ingress-nginx,aledbf/ingress-nginx,kubernetes/ingress-nginx,kubernetes/ingress-nginx,canhnt/ingress
c506d87d2826e998f951255ce32d38f4b379f8f7
sessions.lua
sessions.lua
local check_type = require("textadept-nim.utils").check_type local errortips = require("textadept-nim.errortips") local parse_errors = errortips.parse_errors local error_handler = errortips.error_handler local get_project = require("textadept-nim.project").detect_project local consts = require("textadept-nim.constants") local nimsuggest_executable = consts.nimsuggest_exe local _M = {} -- There is placed active sessions _M.active = {} -- Filename-to-sessionname association _M.session_of = {} function _M:get_handle(filename) -- Creates new session for file if it isn't exist and returns -- handle for the session check_type("string", filename) local session_name = _M.session_of[filename] if session_name == nil or _M.active[session_name] == nil then local project = get_project(filename) session_name = project.root if _M.active[session_name] == nil then _M.active[session_name] = {name = session_name, project = project} else _M.active[session_name].project = project end _M.session_of[filename] = session_name end local session = _M.active[session_name] if session.handle == nil or session.handle:status() ~= "running" then -- create new session local current_dir = session_name:match("^(.+)[/\\][^/\\]+$") or "." local current_handler = function(code) --Hints mistakenly treated as errors if code:match("^Hint.*") then return end error_handler(_M.active[session_name], code) end if consts.VERMAGIC < 807 then session.handle = spawn(nimsuggest_executable.." --stdin --tester --debug --v2 ".. session_name, current_dir, current_handler, parse_errors, current_handler) elseif consts.VERMAGIC < 1002 then session.handle = spawn(nimsuggest_executable.." --stdin --tester --debug --v2 ".. session_name, current_dir, nil, current_handler, parse_errors, current_handler) else session.handle = os.spawn(nimsuggest_executable.." --stdin --tester --debug --v2 ".. session_name, current_dir, nil, current_handler, parse_errors, current_handler) end local ans = "" -- Skip until eof repeat ans = session.handle:read() until ans == nil or ans:sub(1,5) == "!EOF!" if session.handle == nil or session.handle:status() ~= "running" then error("Cann't start nimsuggest!") end end if session.files == nil then session.files = {} end session.files[filename] = true return session.handle end function _M:detach(filename) -- Stops nimsuggest session for filename if no other file uses it check_type("string", filename) local session_name = _M.session_of[filename] if session_name == nil then return end _M.session_of[filename] = nil local session = _M.active[session_name] if session ~= nil then session.files[filename] = nil if #session.files == 0 then if session.handle ~= nil and session.handle:status() ~= "terminated" then session.handle:write("quit\n\n") session.handle:close() end _M.active[session_name] = nil end end end function _M:request(command, filename) -- Requesting nimsuggest to do command and returns -- parsed answer as a structure local nimhandle = _M:get_handle(filename) nimhandle:write(command.."\n") local message_list = {} repeat local answer = nimhandle:read() if answer:sub(1,5) == "!EOF!" then break end table.insert(message_list, answer) until answer == nil return message_list end function _M:stop_all() -- Stops all nimsuggest sessions. -- Use at exit or reset only for file, session in pairs(_M.active) do if session.handle ~= nil and session.handle:status() ~= "terminated" then session.handle:write("quit\n\n") session.handle:close() end end _M.active = nil _M.session_of = nil end return _M
local check_type = require("textadept-nim.utils").check_type local errortips = require("textadept-nim.errortips") local parse_errors = errortips.parse_errors local error_handler = errortips.error_handler local get_project = require("textadept-nim.project").detect_project local consts = require("textadept-nim.constants") local nimsuggest_executable = consts.nimsuggest_exe local _M = {} -- There is placed active sessions _M.active = {} -- Filename-to-sessionname association _M.session_of = {} function _M:get_handle(filename) -- Creates new session for file if it isn't exist and returns -- handle for the session check_type("string", filename) local session_name = _M.session_of[filename] if session_name == nil or _M.active[session_name] == nil then local project = get_project(filename) session_name = project.root if _M.active[session_name] == nil then _M.active[session_name] = {name = session_name, project = project} else _M.active[session_name].project = project end _M.session_of[filename] = session_name end local session = _M.active[session_name] if session.handle == nil or session.handle:status() ~= "running" then -- create new session session.current_dir = session_name:match("^(.+)[/\\][^/\\]+$") or "." local current_handler = function(code) --Hints mistakenly treated as errors if code:match("^Hint.*") then return end error_handler(_M.active[session_name], code) end if consts.VERMAGIC < 807 then session.handle = spawn(nimsuggest_executable.." --stdin --tester --debug --v2 ".. session_name, session.current_dir, current_handler, parse_errors, current_handler) elseif consts.VERMAGIC < 1002 then session.handle = spawn(nimsuggest_executable.." --stdin --tester --debug --v2 ".. session_name, session.current_dir, nil, current_handler, parse_errors, current_handler) else session.handle = os.spawn(nimsuggest_executable.." --stdin --tester --debug --v2 ".. session_name, session.current_dir, nil, current_handler, parse_errors, current_handler) end local ans = "" -- Skip until eof repeat ans = session.handle:read() until ans == nil or ans:sub(1,5) == "!EOF!" if session.handle == nil or session.handle:status() ~= "running" then error("Cann't start nimsuggest!") end end if session.files == nil then session.files = {} end session.files[filename] = true return session end function _M:detach(filename) -- Stops nimsuggest session for filename if no other file uses it check_type("string", filename) local session_name = _M.session_of[filename] if session_name == nil then return end _M.session_of[filename] = nil local session = _M.active[session_name] if session ~= nil then session.files[filename] = nil if #session.files == 0 then if session.handle ~= nil and session.handle:status() ~= "terminated" then session.handle:write("quit\n\n") session.handle:close() end _M.active[session_name] = nil end end end function _M:request(command, filename) -- Requesting nimsuggest to do command and returns -- parsed answer as a structure local session = _M:get_handle(filename) local nimhandle = session.handle local i = command:find(session.current_dir, 0, 1) if i > 0 then command = command:sub(0, i-1)..command:sub(i+session.current_dir:len()+1) end nimhandle:write(command.."\n") local message_list = {} repeat local answer = nimhandle:read() if answer:sub(1,5) == "!EOF!" then break end table.insert(message_list, answer) until answer == nil return message_list end function _M:stop_all() -- Stops all nimsuggest sessions. -- Use at exit or reset only for file, session in pairs(_M.active) do if session.handle ~= nil and session.handle:status() ~= "terminated" then session.handle:write("quit\n\n") session.handle:close() end end _M.active = nil _M.session_of = nil end return _M
Fixes unknown files passing to nimsuggest (no idea why nimsuggest does not work with absolute paths)
Fixes unknown files passing to nimsuggest (no idea why nimsuggest does not work with absolute paths)
Lua
mit
xomachine/textadept-nim
e029001b10ea65f0020f40dd80aa517c78c1e3e4
src/Ship.lua
src/Ship.lua
require ("lib.lclass") class "Ship" function Ship:Ship () self.gfx = love.graphics.newImage ("gfx/schiff.png") self.r = 255 self.g = 255 self.b = 255 self.x = 200 self.y = 200 self.rot = { w = self.gfx:getWidth () / 2, h = self.gfx:getHeight () / 2, v = 0 } self.scale = 1 self.rotationSpeed = 10 self.accelerationSpeed = 33 self.acceleration = 0 self.rotation = 0 self.momentum = { x = 0, y = 0, __tostring = function(self) return "{" .. self.x .. "," .. self.y .. "}" end } self.isAccelerating = 0 self.isRotating = 0 self.reactions = { KeyboardKeyDownEvent = function(event) if event:Key() == "w" then self.isAccelerating = self.isAccelerating + 1 end if event:Key() == "s" then self.isAccelerating = self.isAccelerating - 1 end if event:Key() == "a" then self.isRotating = self.isRotating - 1 end if event:Key() == "d" then self.isRotating = self.isRotating + 1 end end, KeyboardKeyUpEvent = function(event) if event:Key() == "w" then self.isAccelerating = self.isAccelerating - 1 end if event:Key() == "s" then self.isAccelerating = self.isAccelerating + 1 end if event:Key() == "a" then self.isRotating = self.isRotating + 1 end if event:Key() == "d" then self.isRotating = self.isRotating - 1 end end } end function Ship:onUpdate (dt) self.rot.v = self.rot.v + (self.isRotating * self.rotationSpeed * dt) self.acceleration = self.acceleration + (self.isAccelerating * self.accelerationSpeed * dt) self.momentum.x = (math.cos(self.rot.v) * self.momentum.x - math.sin(self.rot.v) * self.momentum.y) * self.acceleration self.momentum.y = (math.sin(self.rot.v) * self.momentum.x + math.cos(self.rot.v) * self.momentum.y) * self.acceleration self.x = self.x + (self.momentum.x * dt) self.y = self.y + (self.momentum.y * dt) end function Ship:onRender () love.graphics.push () love.graphics.setColor (self.r, self.g, self.b, 255) love.graphics.push () love.graphics.draw ( self.gfx, self.x, self.y, self.rot.v, self.scale, self.scale, self.rot.w, self.rot.h ) love.graphics.pop () love.graphics.setColor (255, 255, 255, 255) love.graphics.pop() love.graphics.print (tostring (self.acceleration), 42, 42) love.graphics.print (tostring (self.momentum.x), 242, 42) love.graphics.print (tostring (self.momentum.y), 442, 42) end function Ship:handle (event) self.reactions[event:getClass()](event) end
require ("lib.lclass") class "Ship" function Ship:Ship () self.gfx = love.graphics.newImage ("gfx/schiff.png") self.r = 255 self.g = 255 self.b = 255 self.x = 200 self.y = 200 self.rot = { w = self.gfx:getWidth () / 2, h = self.gfx:getHeight () / 2, v = 0 } self.scale = 1 self.rotationSpeed = 10 self.accelerationSpeed = 33 self.MAX_ACCELERATION = 32 self.acceleration = 0 self.MAX_ROTATION = 2 * math.pi self.rotation = 0 self.momentum = { x = 0, y = 0 } function self.momentum:__tostring () return "{" .. self.x .. "," .. self.y .. "}" end self.isAccelerating = 0 self.isRotating = 0 self.reactions = { KeyboardKeyDownEvent = function (event) if event:Key() == "w" then self.isAccelerating = self.isAccelerating + 1 end if event:Key() == "s" then self.isAccelerating = self.isAccelerating - 1 end if event:Key() == "a" then self.isRotating = self.isRotating - 1 end if event:Key() == "d" then self.isRotating = self.isRotating + 1 end end, KeyboardKeyUpEvent = function (event) if event:Key() == "w" then self.isAccelerating = self.isAccelerating - 1 end if event:Key() == "s" then self.isAccelerating = self.isAccelerating + 1 end if event:Key() == "a" then self.isRotating = self.isRotating + 1 end if event:Key() == "d" then self.isRotating = self.isRotating - 1 end end } end function Ship:onUpdate (dt) self.rot.v = self.rot.v + (self.isRotating * self.rotationSpeed * dt) self.rot.v = self.rot.v % self.MAX_ROTATION --[[ self.acceleration = self.acceleration + (self.isAccelerating * self.accelerationSpeed * dt) self.acceleration = (math.abs (self.acceleration) < self.MAX_ACCELERATION) and self.acceleration or (self.MAX_ACCELERATION * (math.abs (self.acceleration) / self.acceleration)) ]]-- self.momentum.x = self.momentum.x + (math.sin (self.rot.v) * self.isAccelerating) self.momentum.y = self.momentum.y + (-math.cos (self.rot.v) * self.isAccelerating) self.x = self.x + (self.momentum.x * dt) self.y = self.y + (self.momentum.y * dt) end function Ship:onRender () love.graphics.push () love.graphics.setColor (self.r, self.g, self.b, 255) love.graphics.push () love.graphics.draw ( self.gfx, self.x, self.y, self.rot.v, self.scale, self.scale, self.rot.w, self.rot.h ) love.graphics.pop () love.graphics.setColor (255, 255, 255, 255) love.graphics.pop() local py = 42 local pyoff = 16 love.graphics.print ("rot.v: " .. self.rot.v, 42, py + 0 * pyoff) love.graphics.print ("acc: " .. self.acceleration, 42, py + 1 * pyoff) --love.graphics.print (tostring (self.momentum.x), 242, 42) --love.graphics.print (tostring (self.momentum.y), 442, 42) love.graphics.print ("mom: " .. self.momentum:__tostring (), 42, py + 2 * pyoff) end function Ship:handle (event) local reaction = self.reactions[event:getClass()] if reaction then reaction (event) end end
fixed movement
fixed movement changed formular calculating momentum of ship
Lua
mit
BlurryRoots/weltraumsteinekaputtmachen
66fad233d004978c958a44e33873913c7714cb00
bida2.lua
bida2.lua
-- -- bida2.lua -- -- BIDA (ver. 2) -- -- Space 0: simple birthday storage -- Tuple: { user_id (INT), date (INT) } -- Index 0: HASH { user_id } -- Index 1: TREE { date, user_id } -- local limit = 7000 function bida2_get_users_by_birthday(birthday, userid_offset) birthday = box.unpack('i', birthday) userid_offset = box.unpack('i', userid_offset) --[[ We are using user id as an offset in out tarantool request. From documentation: localhost> lua box.select_range(4, 1, 2, '1') --- - '1': {'1'} - '2': {'2'} ... That means, that select_range() function can return users with unexpected birthday => we should filter them out --]] local tuples = { box.select_range(0, 1, limit, birthday, userid_offset) } local result = {} for _, tuple in pairs(tuples) do if box.unpack('i', tuple[1]) == birthday then table.insert(result, tuple[0]) end end return unpack(result) end
-- -- bida2.lua -- -- BIDA (ver. 2) -- -- Space 0: simple birthday storage -- Tuple: { user_id (INT), date (INT) } -- Index 0: TREE { date, user_id } -- local limit = 7000 function bida2_get_users_by_birthday(birthday, userid_offset) birthday = box.unpack('i', birthday) userid_offset = box.unpack('i', userid_offset) --[[ We are using user id as an offset in out tarantool request. From documentation: localhost> lua box.select_range(4, 1, 2, '1') --- - '1': {'1'} - '2': {'2'} ... That means, that select_range() function can return users with unexpected birthday => we should filter them out --]] local tuples = { box.select_range(0, 0, limit, birthday, userid_offset) } local result = {} for _, tuple in pairs(tuples) do if box.unpack('i', tuple[1]) == birthday then table.insert(result, tuple[0]) end end return unpack(result) end
bida2: fix for a single space
bida2: fix for a single space
Lua
bsd-2-clause
BHYCHIK/tntlua,grechkin-pogrebnyakov/tntlua,mailru/tntlua
c73297ee15d7d00b087b07adc3f787e598196df5
UCDrespawn/client.lua
UCDrespawn/client.lua
------------------------------------------------------------------- --// PROJECT: Project Downtown --// RESOURCE: respawn --// DEVELOPER(S): Lewis Watson (Noki) --// DATE: 14.12.2014 --// PURPOSE: To handle client side re-spawning of players. --// FILE: \respawn\client.lua [client] ------------------------------------------------------------------- local hospitalTable = { { "All Saints Public Hospital", 1179.1, -1324.4, 14.15, 270.12222290039, 0, 70 }, { "Jefferson County Hospital", 2030.31, -1406.77, 17.2, 178.76403808594, 0, 70 }, { "Crippen Memorial Hospital", 1245.22, 334.22, 19.55, 335.55230712891, 0, 7 }, { "Fort Carson Medical Village", -319.24, 1057.76, 19.74, 343.53948974609, 0, 70 }, { "LVA Medical Centre", 1607.87, 1823, 10.82, 1.5188903808594, 0, 70 }, { "El Quebrados Health Precinct", -1514.85, 2528.23, 55.72, 358.66787719727, 0, 70 }, { "San Fierro General", -2647.62, 631.2, 14.45, 176.91278076172, 0, 70 }, { "Angel Pine Health Centre", -2199.24, -2310.78, 30.62, 319.53399658203, 0, 70 } } weaponTable = {} function getWeapons() for i=1,12 do local weapon = getPedWeapon(localPlayer, i) if weapon then local ammo = getPedTotalAmmo(localPlayer, i) weaponTable[i] = {weapon, ammo} end end return weaponTable end -- Event triggerd when the player dies addEventHandler("onClientPlayerWasted", localPlayer, function () if (source ~= localPlayer) then return false end if not (getElementHealth(localPlayer) > 0) then if (not localPlayer:isWithinColShape(exports.UCDbankrob:getBank())) then local hospitalDist = false local nearestHospital = false for i=1, #hospitalTable do local pX, pY, pZ = getElementPosition(localPlayer) local hX, hY, hZ = hospitalTable[i][2], hospitalTable[i][3], hospitalTable[i][4] local distance = getDistanceBetweenPoints3D(pX, pY, pZ, hX, hY, hZ) if not (hospitalDist) or (distance < hospitalDist) then hospitalDist = distance nearestHospital = i end end else nearestHospital = 1 end if (nearestHospital) then local ID = nearestHospital local hX, hY, hZ, rotation, hospitalName = hospitalTable[ID][2], hospitalTable[ID][3], hospitalTable[ID][4], hospitalTable[ID][5], hospitalTable[ID][1] local mX, mY, mZ, lX, lY, lZ = hospitalTable[ID][6], hospitalTable[ID][7], hospitalTable[ID][8], hospitalTable[ID][9], hospitalTable[ID][10], hospitalTable[ID][11] --setTimer(function () triggerServerEvent("respawnDeadPlayer", localPlayer, hX, hY, hZ, rotation, hospitalName, slot0, slot1, slot2, slot3, slot4, slot5, slot6, slot7, slot8, slot9, slot10, slot11, slot12, ammo2, ammo3, ammo4, ammo5, ammo6, ammo7, ammo8, ammo9) end, 4000, 1) setTimer( function () local weaponTable = getWeapons() triggerServerEvent("respawnDeadPlayer", localPlayer, hX, hY, hZ, rotation, hospitalName, weaponTable) end, 4000, 1 ) end end end )
------------------------------------------------------------------- --// PROJECT: Project Downtown --// RESOURCE: respawn --// DEVELOPER(S): Lewis Watson (Noki) --// DATE: 14.12.2014 --// PURPOSE: To handle client side re-spawning of players. --// FILE: \respawn\client.lua [client] ------------------------------------------------------------------- local hospitalTable = { { "All Saints Public Hospital", 1179.1, -1324.4, 14.15, 270.12222290039, 0, 70 }, { "Jefferson County Hospital", 2030.31, -1406.77, 17.2, 178.76403808594, 0, 70 }, { "Crippen Memorial Hospital", 1245.22, 334.22, 19.55, 335.55230712891, 0, 7 }, { "Fort Carson Medical Village", -319.24, 1057.76, 19.74, 343.53948974609, 0, 70 }, { "LVA Medical Centre", 1607.87, 1823, 10.82, 1.5188903808594, 0, 70 }, { "El Quebrados Health Precinct", -1514.85, 2528.23, 55.72, 358.66787719727, 0, 70 }, { "San Fierro General", -2647.62, 631.2, 14.45, 176.91278076172, 0, 70 }, { "Angel Pine Health Centre", -2199.24, -2310.78, 30.62, 319.53399658203, 0, 70 } } weaponTable = {} function getWeapons() for i=1,12 do local weapon = getPedWeapon(localPlayer, i) if weapon then local ammo = getPedTotalAmmo(localPlayer, i) weaponTable[i] = {weapon, ammo} end end return weaponTable end -- Event triggerd when the player dies addEventHandler("onClientPlayerWasted", localPlayer, function () if (source ~= localPlayer) then return false end if not (getElementHealth(localPlayer) > 0) then local hospitalDist = false local nearestHospital = false if (exports.UCDbankrob:getBank() and exports.UCDbankrob:getBank().type == "colshape" and localPlayer:isWithinColShape(exports.UCDbankrob:getBank())) then nearestHospital = 1 else for i=1, #hospitalTable do local pX, pY, pZ = getElementPosition(localPlayer) local hX, hY, hZ = hospitalTable[i][2], hospitalTable[i][3], hospitalTable[i][4] local distance = getDistanceBetweenPoints3D(pX, pY, pZ, hX, hY, hZ) if not (hospitalDist) or (distance < hospitalDist) then hospitalDist = distance nearestHospital = i end end end if (nearestHospital) then local ID = nearestHospital local hX, hY, hZ, rotation, hospitalName = hospitalTable[ID][2], hospitalTable[ID][3], hospitalTable[ID][4], hospitalTable[ID][5], hospitalTable[ID][1] local mX, mY, mZ, lX, lY, lZ = hospitalTable[ID][6], hospitalTable[ID][7], hospitalTable[ID][8], hospitalTable[ID][9], hospitalTable[ID][10], hospitalTable[ID][11] --setTimer(function () triggerServerEvent("respawnDeadPlayer", localPlayer, hX, hY, hZ, rotation, hospitalName, slot0, slot1, slot2, slot3, slot4, slot5, slot6, slot7, slot8, slot9, slot10, slot11, slot12, ammo2, ammo3, ammo4, ammo5, ammo6, ammo7, ammo8, ammo9) end, 4000, 1) setTimer( function () local weaponTable = getWeapons() triggerServerEvent("respawnDeadPlayer", localPlayer, hX, hY, hZ, rotation, hospitalName, weaponTable) end, 4000, 1 ) end end end )
UCDrespawn
UCDrespawn - Hopefully fixed not respawning when the bank is fucked
Lua
mit
nokizorque/ucd,nokizorque/ucd
4f7ee4c06c2defc729f175fb490f9d5a8cb018ec
util/log.lua
util/log.lua
-------------------------------------------------------------------------------- -- Copyright (c) 2015 Jason Lynch <[email protected]> -- -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -- copies of the Software, and to permit persons to whom the Software is -- furnished to do so, subject to the following conditions: -- -- The above copyright notice and this permission notice shall be included in -- all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -- THE SOFTWARE. -------------------------------------------------------------------------------- local _M = {} -------------------------------------------------------------------------------- -- Variables -------------------------------------------------------------------------------- local _file = nil local _base_frame = nil -------------------------------------------------------------------------------- -- Private Functions -------------------------------------------------------------------------------- local function _log(message) message = string.format("%s :: %6s :: %s :: %s", os.date("!%Y-%m-%d %X+0000"), emu.framecount(), _M.get_time(), message) console.log(message) if _file then _file:write(message) _file:write("\n") _file:flush() end return true end -------------------------------------------------------------------------------- -- Public Functions -------------------------------------------------------------------------------- function _M.get_time() if _base_frame then local time = (emu.framecount() - _base_frame) / 60.0988 return string.format("%s:%05.2f", os.date("!%H:%M", time), time % 60) else return string.format("%11s", "-") end end function _M.error(message) return _log(string.format("ERROR :: %s", message)) end function _M.warning(message) return _log(string.format("WARNING :: %s", message)) end function _M.log(message) return _log(message) end function _M.start() _base_frame = emu.framecount() end function _M.reset() console.clear() if _file then _file:close() _file = nil end _base_frame = nil if FULL_RUN then _file, err = io.open(string.format("logs/edge-%s-%03d-%010d-%s.log", ROUTE, ENCOUNTER_SEED, SEED, os.date("!%Y%m%d-%H%M%S")), "w") end end return _M
-------------------------------------------------------------------------------- -- Copyright (c) 2015 Jason Lynch <[email protected]> -- -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -- copies of the Software, and to permit persons to whom the Software is -- furnished to do so, subject to the following conditions: -- -- The above copyright notice and this permission notice shall be included in -- all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -- THE SOFTWARE. -------------------------------------------------------------------------------- local _M = {} -------------------------------------------------------------------------------- -- Variables -------------------------------------------------------------------------------- local _file = nil local _base_frame = nil -------------------------------------------------------------------------------- -- Private Functions -------------------------------------------------------------------------------- local function _log(message) message = string.format("%s :: %6s :: %s :: %s", os.date("!%Y-%m-%d %X+0000"), emu.framecount(), _M.get_time(), message) console.log(message) if _file then _file:write(message) _file:write("\n") _file:flush() end return true end -------------------------------------------------------------------------------- -- Public Functions -------------------------------------------------------------------------------- function _M.get_time() if _base_frame then local time = (emu.framecount() - _base_frame) / 60.0988 return string.format("%02d:%02d:%05.2f", time / 3600, (time / 60) % 60, time % 60) else return string.format("%11s", "-") end end function _M.error(message) return _log(string.format("ERROR :: %s", message)) end function _M.warning(message) return _log(string.format("WARNING :: %s", message)) end function _M.log(message) return _log(message) end function _M.start() _base_frame = emu.framecount() end function _M.reset() console.clear() if _file then _file:close() _file = nil end _base_frame = nil if FULL_RUN then _file, err = io.open(string.format("logs/edge-%s-%03d-%010d-%s.log", ROUTE, ENCOUNTER_SEED, SEED, os.date("!%Y%m%d-%H%M%S")), "w") end end return _M
Fix the time display.
Fix the time display. Signed-off-by: Jason Lynch <[email protected]>
Lua
mit
aexoden/edge
56f1aee07386ed230f1d6cfddc504a214b6e0cb9
SVUI_UnitFrames/libs/Plugins/oUF_Druidness/oUF_Druidness.lua
SVUI_UnitFrames/libs/Plugins/oUF_Druidness/oUF_Druidness.lua
if(select(2, UnitClass('player')) ~= 'DRUID') then return end --GLOBAL NAMESPACE local _G = _G; --LUA local unpack = _G.unpack; local select = _G.select; local assert = _G.assert; local error = _G.error; local print = _G.print; local pairs = _G.pairs; local next = _G.next; local tostring = _G.tostring; local type = _G.type; --STRING local string = _G.string; local format = string.format; --MATH local math = _G.math; local floor = math.floor local ceil = math.ceil --TABLE local table = _G.table; local wipe = _G.wipe; --BLIZZARD API local BEAR_FORM = _G.BEAR_FORM; local CAT_FORM = _G.CAT_FORM; local SPELL_POWER_MANA = _G.SPELL_POWER_MANA; local UnitClass = _G.UnitClass; local UnitPower = _G.UnitPower; local UnitReaction = _G.UnitReaction; local UnitPowerMax = _G.UnitPowerMax; local UnitIsPlayer = _G.UnitIsPlayer; local UnitPlayerControlled = _G.UnitPlayerControlled; local GetShapeshiftFormID = _G.GetShapeshiftFormID; local _, ns = ... local oUF = ns.oUF or oUF local ECLIPSE_BAR_SOLAR_BUFF_ID = _G.ECLIPSE_BAR_SOLAR_BUFF_ID local ECLIPSE_BAR_LUNAR_BUFF_ID = _G.ECLIPSE_BAR_LUNAR_BUFF_ID local SPELL_POWER_ECLIPSE = _G.SPELL_POWER_ECLIPSE local MOONKIN_FORM = _G.MOONKIN_FORM local ALERTED = false; local TextColors = { [1]={1,0.1,0.1}, [2]={1,0.5,0.1}, [3]={1,1,0.1}, [4]={0.5,1,0.1}, [5]={0.1,1,0.1} }; local ProxyShow = function(self) if(not self.isEnabled) then return end self:Show() end local function CatOverMana(mana, form) if mana.ManaBar:GetValue() < UnitPowerMax('player', SPELL_POWER_MANA) then mana:ProxyShow() return false else mana:Hide() return form == CAT_FORM end end local UpdateVisibility = function(self, event) local bar = self.Druidness local cat = bar.Cat local mana = bar.Mana local form = GetShapeshiftFormID() if(form) then if (form == BEAR_FORM or form == CAT_FORM) then if(CatOverMana(mana, form)) then cat:ProxyShow() else cat:Hide() end else cat:Hide() mana:Hide() end else mana:Hide() cat:Hide() end end local UpdatePower = function(self, event, unit, powerType) if(self.unit ~= unit) then return end local bar = self.Druidness if(bar.Mana and bar.Mana.ManaBar) then local mana = bar.Mana if(mana.PreUpdate) then mana:PreUpdate(unit) end local min, max = UnitPower('player', SPELL_POWER_MANA), UnitPowerMax('player', SPELL_POWER_MANA) mana.ManaBar:SetMinMaxValues(0, max) mana.ManaBar:SetValue(min) local r, g, b, t if(mana.colorPower) then t = self.colors.power["MANA"] elseif(mana.colorClass and UnitIsPlayer(unit)) or (mana.colorClassNPC and not UnitIsPlayer(unit)) or (mana.colorClassPet and UnitPlayerControlled(unit) and not UnitIsPlayer(unit)) then local _, class = UnitClass(unit) t = self.colors.class[class] elseif(mana.colorReaction and UnitReaction(unit, 'player')) then t = self.colors.reaction[UnitReaction(unit, "player")] elseif(mana.colorSmooth) then r, g, b = self.ColorGradient(min / max, unpack(mana.smoothGradient or self.colors.smooth)) end if(t) then r, g, b = t[1], t[2], t[3] end if(b) then mana.ManaBar:SetStatusBarColor(r, g, b) local bg = mana.bg if(bg) then local mu = bg.multiplier or 1 bg:SetVertexColor(r * mu, g * mu, b * mu) end end if(mana.PostUpdatePower) then mana:PostUpdatePower(unit, min, max) end end UpdateVisibility(self) end local UpdateComboPoints = function(self, event, unit) if(unit == 'pet') then return end local bar = self.Druidness; local cpoints = bar.Cat; if(bar.PreUpdate) then bar:PreUpdate() end local current = 0 if(UnitHasVehicleUI'player') then current = UnitPower("vehicle", SPELL_POWER_COMBO_POINTS); else current = UnitPower("player", SPELL_POWER_COMBO_POINTS); end if(cpoints) then local MAX_COMBO_POINTS = UnitPowerMax("player", SPELL_POWER_COMBO_POINTS); for i=1, MAX_COMBO_POINTS do if(i <= current) then cpoints[i]:Show() if(bar.PointShow) then bar.PointShow(cpoints[i]) end else if cpoints[i] then cpoints[i]:Hide() if(bar.PointHide) then bar.PointHide(cpoints[i], i) end end end end end if(bar.PostUpdateComboPoints) then return bar:PostUpdateComboPoints(current) end end local Update = function(self, ...) UpdatePower(self, ...) UpdateComboPoints(self, ...) return UpdateVisibility(self, ...) end local ForceUpdate = function(element) return Update(element.__owner, 'ForceUpdate', element.__owner.unit, 'ECLIPSE') end local function Enable(self) local bar = self.Druidness if(bar) then local mana = bar.Mana; local cpoints = bar.Cat; mana.ProxyShow = ProxyShow; cpoints.ProxyShow = ProxyShow; self:RegisterEvent('UNIT_POWER_FREQUENT', UpdatePower) self:RegisterEvent('PLAYER_TALENT_UPDATE', UpdateVisibility, true) self:RegisterEvent('UPDATE_SHAPESHIFT_FORM', UpdateVisibility, true) self:RegisterEvent('PLAYER_TARGET_CHANGED', UpdateComboPoints, true) self:RegisterEvent('UNIT_DISPLAYPOWER', UpdateComboPoints, true) self:RegisterEvent('UNIT_MAXPOWER', UpdateComboPoints, true) self:RegisterUnitEvent('UNIT_DISPLAYPOWER', "player") self:RegisterUnitEvent("UNIT_POWER_FREQUENT", "player") self:RegisterUnitEvent("UNIT_MAXPOWER", "player") UpdateVisibility(self) return true end end local function Disable(self) local bar = self.Druidness if(bar) then --local chicken = bar.Chicken local mana = bar.Mana --chicken:Hide() mana:Hide() self:RegisterEvent('UNIT_POWER_FREQUENT', UpdatePower) self:UnregisterEvent('PLAYER_TALENT_UPDATE', UpdateVisibility) self:UnregisterEvent('UPDATE_SHAPESHIFT_FORM', UpdateVisibility) self:UnregisterEvent('UNIT_COMBO_POINTS', UpdateComboPoints) self:UnregisterEvent('PLAYER_TARGET_CHANGED', UpdateComboPoints) self:UnregisterEvent('UNIT_DISPLAYPOWER', UpdateComboPoints) self:UnregisterEvent('UNIT_MAXPOWER', UpdateComboPoints) end end oUF:AddElement('BoomChicken', Update, Enable, Disable)
if(select(2, UnitClass('player')) ~= 'DRUID') then return end --GLOBAL NAMESPACE local _G = _G; --LUA local unpack = _G.unpack; local select = _G.select; local assert = _G.assert; local error = _G.error; local print = _G.print; local pairs = _G.pairs; local next = _G.next; local tostring = _G.tostring; local type = _G.type; --STRING local string = _G.string; local format = string.format; --MATH local math = _G.math; local floor = math.floor local ceil = math.ceil --TABLE local table = _G.table; local wipe = _G.wipe; --BLIZZARD API local BEAR_FORM = _G.BEAR_FORM; local CAT_FORM = _G.CAT_FORM; local SPELL_POWER_MANA = _G.SPELL_POWER_MANA; local UnitClass = _G.UnitClass; local UnitPower = _G.UnitPower; local UnitReaction = _G.UnitReaction; local UnitPowerMax = _G.UnitPowerMax; local UnitIsPlayer = _G.UnitIsPlayer; local UnitPlayerControlled = _G.UnitPlayerControlled; local GetShapeshiftFormID = _G.GetShapeshiftFormID; local _, ns = ... local oUF = ns.oUF or oUF local ECLIPSE_BAR_SOLAR_BUFF_ID = _G.ECLIPSE_BAR_SOLAR_BUFF_ID local ECLIPSE_BAR_LUNAR_BUFF_ID = _G.ECLIPSE_BAR_LUNAR_BUFF_ID local SPELL_POWER_ECLIPSE = _G.SPELL_POWER_ECLIPSE local MOONKIN_FORM = _G.MOONKIN_FORM local ALERTED = false; local TextColors = { [1]={1,0.1,0.1}, [2]={1,0.5,0.1}, [3]={1,1,0.1}, [4]={0.5,1,0.1}, [5]={0.1,1,0.1} }; local Debug if AdiDebug then Debug = AdiDebug:GetSink("oUF_Druidness") else Debug = function() end end local ProxyShow = function(self) if(not self.isEnabled) then return end self:Show() end local function CatOverMana(mana, form) if mana.ManaBar:GetValue() < UnitPowerMax('player', SPELL_POWER_MANA) then mana:ProxyShow() return false else mana:Hide() return form == CAT_FORM end end local UpdateVisibility = function(self, event) local bar = self.Druidness local cat = bar.Cat local mana = bar.Mana local form = GetShapeshiftFormID() if(form) then if (form == BEAR_FORM or form == CAT_FORM) then if(CatOverMana(mana, form)) then cat:ProxyShow() else cat:Hide() end else cat:Hide() mana:Hide() end else mana:Hide() cat:Hide() end end local UpdatePower = function(self, event, unit, powerType) if(self.unit ~= unit) then return end local bar = self.Druidness if(bar.Mana and bar.Mana.ManaBar) then local mana = bar.Mana if(mana.PreUpdate) then mana:PreUpdate(unit) end local min, max = UnitPower('player', SPELL_POWER_MANA), UnitPowerMax('player', SPELL_POWER_MANA) mana.ManaBar:SetMinMaxValues(0, max) mana.ManaBar:SetValue(min) local r, g, b, t if(mana.colorPower) then t = self.colors.power["MANA"] elseif(mana.colorClass and UnitIsPlayer(unit)) or (mana.colorClassNPC and not UnitIsPlayer(unit)) or (mana.colorClassPet and UnitPlayerControlled(unit) and not UnitIsPlayer(unit)) then local _, class = UnitClass(unit) t = self.colors.class[class] elseif(mana.colorReaction and UnitReaction(unit, 'player')) then t = self.colors.reaction[UnitReaction(unit, "player")] elseif(mana.colorSmooth) then r, g, b = self.ColorGradient(min / max, unpack(mana.smoothGradient or self.colors.smooth)) end if(t) then r, g, b = t[1], t[2], t[3] end if(b) then mana.ManaBar:SetStatusBarColor(r, g, b) local bg = mana.bg if(bg) then local mu = bg.multiplier or 1 bg:SetVertexColor(r * mu, g * mu, b * mu) end end if(mana.PostUpdatePower) then mana:PostUpdatePower(unit, min, max) end end UpdateVisibility(self) end local UpdateComboPoints = function(self, event, unit) if(unit == 'pet') then return end local bar = self.Druidness; local cpoints = bar.Cat; if(bar.PreUpdate) then bar:PreUpdate() end local current = 0 if(UnitHasVehicleUI'player') then current = UnitPower("vehicle", SPELL_POWER_COMBO_POINTS); else current = UnitPower("player", SPELL_POWER_COMBO_POINTS); end if(cpoints) then local MAX_COMBO_POINTS = UnitPowerMax("player", SPELL_POWER_COMBO_POINTS); Debug("max combo points/current: ", MAX_COMBO_POINTS,current) for i=1, MAX_COMBO_POINTS do if(i <= current) then cpoints[i]:Show() if(bar.PointShow) then bar.PointShow(cpoints[i]) end else if cpoints[i] then cpoints[i]:Hide() if(bar.PointHide) then bar.PointHide(cpoints[i], i) end end end end end if(bar.PostUpdateComboPoints) then return bar:PostUpdateComboPoints(current) end end local Update = function(self, ...) UpdatePower(self, ...) UpdateComboPoints(self, ...) return UpdateVisibility(self, ...) end local ForceUpdate = function(element) return Update(element.__owner, 'ForceUpdate', element.__owner.unit, 'ECLIPSE') end local function Enable(self) local bar = self.Druidness if(bar) then local mana = bar.Mana; local cpoints = bar.Cat; mana.ProxyShow = ProxyShow; cpoints.ProxyShow = ProxyShow; self:RegisterEvent('UNIT_POWER_FREQUENT', UpdatePower) self:RegisterEvent('PLAYER_TALENT_UPDATE', UpdateVisibility, true) self:RegisterEvent('UPDATE_SHAPESHIFT_FORM', UpdateVisibility, true) self:RegisterEvent('PLAYER_TARGET_CHANGED', UpdateComboPoints, true) self:RegisterEvent('UNIT_DISPLAYPOWER', UpdateComboPoints, true) self:RegisterEvent('UNIT_MAXPOWER', UpdateComboPoints, true) self:RegisterUnitEvent('UNIT_DISPLAYPOWER', "player") self:RegisterUnitEvent("UNIT_POWER_FREQUENT", "player") self:RegisterUnitEvent("UNIT_MAXPOWER", "player") UpdateVisibility(self) return true end end local function Disable(self) local bar = self.Druidness if(bar) then --local chicken = bar.Chicken local mana = bar.Mana --chicken:Hide() mana:Hide() self:RegisterEvent('UNIT_POWER_FREQUENT', UpdatePower) self:UnregisterEvent('PLAYER_TALENT_UPDATE', UpdateVisibility) self:UnregisterEvent('UPDATE_SHAPESHIFT_FORM', UpdateVisibility) self:UnregisterEvent('UNIT_COMBO_POINTS', UpdateComboPoints) self:UnregisterEvent('PLAYER_TARGET_CHANGED', UpdateComboPoints) self:UnregisterEvent('UNIT_DISPLAYPOWER', UpdateComboPoints) self:UnregisterEvent('UNIT_MAXPOWER', UpdateComboPoints) end end oUF:AddElement('BoomChicken', Update, Enable, Disable)
Possible fix for #84
Possible fix for #84 Fixed the offending line in oUF_Druidness - if this is the source of the problem then we're golden but it may just be masking the real issue.
Lua
mit
joev/SVUI-Temp
8780a13b75dd7191d81dc9cc90463f2da799c224
test_scripts/Polices/build_options/021_ATF_P_TC_PoliciesManager_Sets_Status_to_UP_TO_DATE_HTTP.lua
test_scripts/Polices/build_options/021_ATF_P_TC_PoliciesManager_Sets_Status_to_UP_TO_DATE_HTTP.lua
--------------------------------------------------------------------------------------------- -- Requirements summary: -- [PolicyTableUpdate] PoliciesManager changes status to “UP_TO_DATE” -- [HMI API] OnStatusUpdate -- [HMI API] OnReceivedPolicyUpdate notification -- -- Description: --PoliciesManager must change the status to “UP_TO_DATE” and notify HMI with --OnStatusUpdate("UP_TO_DATE") right after successful validation of received PTU . -- 1. Used preconditions -- SDL is built with "-DEXTENDED_POLICY: HTTP" flag -- Application is registered. -- PTU is requested. -- SDL->HMI: SDL.OnStatusUpdate(UPDATE_NEEDED) -- SDL->HMI:SDL.PolicyUpdate(file, timeout, retry[]) -- HMI -> SDL: SDL.GetURLs (<service>) -- HMI->SDL: BasicCommunication.OnSystemRequest ('url', requestType:HTTP) -- SDL->app: OnSystemRequest ('url', requestType:HTTP, fileType="JSON") -- app->SDL: SystemRequest(requestType=HTTP) -- SDL->HMI: SystemRequest(requestType=HTTP, fileName) -- HMI->SDL: SystemRequest(SUCCESS) -- 2. Performed steps -- HMI->SDL: OnReceivedPolicyUpdate(policy_file) according to data dictionary -- -- Expected result: -- SDL->HMI: OnStatusUpdate(UP_TO_DATE) --------------------------------------------------------------------------------------------- --[[ General configuration parameters ]] config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0" --[[ Required Shared libraries ]] local commonSteps = require('user_modules/shared_testcases/commonSteps') local commonFunctions = require('user_modules/shared_testcases/commonFunctions') local commonTestCases = require('user_modules/shared_testcases/commonTestCases') --[[ General Precondition before ATF start ]] commonSteps:DeleteLogsFileAndPolicyTable() --TODO: Shouold be removed when issue: "ATF does not stop HB timers by closing session and connection" is fixed config.defaultProtocolVersion = 2 --[[ General Settings for configuration ]] Test = require('connecttest') require('cardinalities') require('user_modules/AppTypes') --[[ Test ]] commonFunctions:newTestCasesGroup("Test") function Test:TestStep_PoliciesManager_changes_UP_TO_DATE() commonFunctions:check_ptu_sequence_partly(self) EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate", {}):Times(0) EXPECT_HMICALL("BasicCommunication.PolicyUpdate",{}):Times(0) commonTestCases:DelayedExp(60*1000) end --[[ Postconditions ]] commonFunctions:newTestCasesGroup("Postconditions") function Test.Postcondition_Stop_SDL() StopSDL() end return Test
--------------------------------------------------------------------------------------------- -- Requirements summary: -- [PolicyTableUpdate] PoliciesManager changes status to “UP_TO_DATE” -- [HMI API] OnStatusUpdate -- [HMI API] OnReceivedPolicyUpdate notification -- -- Description: --PoliciesManager must change the status to “UP_TO_DATE” and notify HMI with --OnStatusUpdate("UP_TO_DATE") right after successful validation of received PTU . -- 1. Used preconditions -- SDL is built with "-DEXTENDED_POLICY: HTTP" flag -- Application is registered. -- PTU is requested. -- SDL->HMI: SDL.OnStatusUpdate(UPDATE_NEEDED) -- SDL->HMI:SDL.PolicyUpdate(file, timeout, retry[]) -- HMI -> SDL: SDL.GetURLs (<service>) -- HMI->SDL: BasicCommunication.OnSystemRequest ('url', requestType:HTTP) -- SDL->app: OnSystemRequest ('url', requestType:HTTP, fileType="JSON") -- app->SDL: SystemRequest(requestType=HTTP) -- SDL->HMI: SystemRequest(requestType=HTTP, fileName) -- HMI->SDL: SystemRequest(SUCCESS) -- 2. Performed steps -- HMI->SDL: OnReceivedPolicyUpdate(policy_file) according to data dictionary -- -- Expected result: -- SDL->HMI: OnStatusUpdate(UP_TO_DATE) --------------------------------------------------------------------------------------------- --[[ General configuration parameters ]] config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0" --[[ Required Shared libraries ]] local commonSteps = require('user_modules/shared_testcases/commonSteps') local commonFunctions = require('user_modules/shared_testcases/commonFunctions') local commonTestCases = require('user_modules/shared_testcases/commonTestCases') --[[ General Precondition before ATF start ]] commonSteps:DeleteLogsFileAndPolicyTable() --TODO: Shouold be removed when issue: "ATF does not stop HB timers by closing session and connection" is fixed config.defaultProtocolVersion = 2 --[[ General Settings for configuration ]] Test = require('connecttest') require('cardinalities') require('user_modules/AppTypes') --[[ Test ]] commonFunctions:newTestCasesGroup("Test") function Test:TestStep_PoliciesManager_changes_UP_TO_DATE() commonFunctions:check_ptu_sequence_partly(self, "files/ptu.json", "PolicyTableUpdate") EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate", {}):Times(0) EXPECT_HMICALL("BasicCommunication.PolicyUpdate",{}):Times(0) commonTestCases:DelayedExp(60*1000) end --[[ Postconditions ]] commonFunctions:newTestCasesGroup("Postconditions") function Test.Postcondition_Stop_SDL() StopSDL() end return Test
Fix issues
Fix issues
Lua
bsd-3-clause
smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts