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
bcca0549d5a0517d589008b80539241caf332943
examples/table_align_fix.lua
examples/table_align_fix.lua
-- Pandoc uses the obsolete "align" attribute on th and td elements. -- This example replaces all such occurrences with the CSS text-align property. local gumbo = require "gumbo" local document = assert(gumbo.parseFile(arg[1] or io.stdin)) local function fixAlignAttr(elements) for i = 1, elements.length do local element = elements[i] local align = element:getAttribute("align") if align then if align ~= "left" then -- left is the default for ltr languages local css = "text-align:" .. align local style = element:getAttribute("style") if style then css = style .. "; " .. css end element:setAttribute("style", css) end element:removeAttribute("align") end end end fixAlignAttr(document:getElementsByTagName("td")) fixAlignAttr(document:getElementsByTagName("th")) document:serialize(io.stdout)
-- Pandoc uses the obsolete "align" attribute on th and td elements. -- This example replaces all such occurrences with the CSS text-align property. local gumbo = require "gumbo" local document = assert(gumbo.parseFile(arg[1] or io.stdin)) local function fixAlignAttr(elements) for i, element in ipairs(elements) do local align = element:getAttribute("align") if align then if align ~= "left" then -- left is the default for ltr languages local css = "text-align:" .. align local style = element:getAttribute("style") if style then css = style .. "; " .. css end element:setAttribute("style", css) end element:removeAttribute("align") end end end fixAlignAttr(document:getElementsByTagName("td")) fixAlignAttr(document:getElementsByTagName("th")) document:serialize(io.stdout)
Use ipairs instead of numeric for loop in examples/table_align_fix.lua
Use ipairs instead of numeric for loop in examples/table_align_fix.lua
Lua
apache-2.0
craigbarnes/lua-gumbo,craigbarnes/lua-gumbo,craigbarnes/lua-gumbo
2b5c0796a7a07dfcfeb2099cbd8da6ee80f89a5c
init.lua
init.lua
-- Copyright 2007 Mitchell Foral mitchell<att>caladbolg.net. See LICENSE. require 'ext/pm' require 'ext/find' require 'ext/mime_types' require 'ext/keys' local mpath = _HOME..'modules/?.lua;'.._HOME..'/modules/?/init.lua' package.path = package.path..';'..mpath -- modules to load on startup require 'textadept' -- end modules require 'ext/key_commands' -- process command line arguments local textadept = textadept if #arg == 0 then textadept.io.load_session() else local base_dir = arg[0]:match('^.+/') or '' for _, filename in ipairs(arg) do textadept.io.open(base_dir..filename) end textadept.pm.entry_text = 'buffers' textadept.pm.activate() end
-- Copyright 2007 Mitchell Foral mitchell<att>caladbolg.net. See LICENSE. require 'ext/pm' require 'ext/find' require 'ext/mime_types' require 'ext/keys' local mpath = _HOME..'modules/?.lua;'.._HOME..'/modules/?/init.lua' package.path = package.path..';'..mpath -- modules to load on startup require 'textadept' -- end modules require 'ext/key_commands' -- process command line arguments local textadept = textadept if #arg == 0 then textadept.io.load_session() else local base_dir = arg[0]:match('^.+/') or '' local filepath for _, filename in ipairs(arg) do if not filename:match('^~?/') then textadept.io.open(base_dir..filename) else textadept.io.open(filename) end end textadept.pm.entry_text = 'buffers' textadept.pm.activate() end
Fixed command line parameters bug; init.lua When files are passed by the command line, they are assumed to be relative to Textadept's path. Instead, check if the file has a leading '~/' or '/' indicating an absolute path. If so, do not treat it that way. Otherwise treat it as relative.
Fixed command line parameters bug; init.lua When files are passed by the command line, they are assumed to be relative to Textadept's path. Instead, check if the file has a leading '~/' or '/' indicating an absolute path. If so, do not treat it that way. Otherwise treat it as relative.
Lua
mit
jozadaquebatista/textadept,jozadaquebatista/textadept
b8085a01cd82d3f02d693851fbfebba9b9a5e8df
main.lua
main.lua
--[[ Copyright 2014-2015 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 bundle = require("luvi").bundle loadstring(bundle.readfile("luvit-loader.lua"), "bundle:luvit-loader.lua")() -- Upvalues local uv = require("uv") local version = require("./package").version local log = require("log").log require("snapshot") -- Global setup _G.p = require("pretty-print").prettyPrint -- Settings local EXIT_SUCCESS = 0 local EXIT_FAILURE = -1 local aliases = { ["-v"] = "version", ["-h"] = "help" } local commandLine = {} function commandLine.run() coroutine.wrap(function() self.processUserInput() end)() uv.run() end function commandLine.processUserInput() local command = self.processArguments() local success, errorMessage = xpcall(function() self.executeCommand(command) end, debug.traceback) if not success then self.reportFailure(errorMessage) return end self.reportSuccess() end function commandLine.processArguments() local command = args[1] or "help" if command:sub(1, 2) == "--" then command = command:sub(3) end command = aliases[command] or command return command end function commandLine.executeCommand(command) self.outputVersionInfo() if command == "version" then -- Since the version is always printed, there's nothing left to do self.exitWithCode(EXIT_SUCCESS) end if self.isValidCommand(command) then log("command", table.concat(args, " "), "highlight") self.executeCommandHandler(command) else log("invalid command", command, "failure") self.executeCommandHandler("help") self.reportFailure("Invalid Command: " .. command) end end function commandLine.reportSuccess() log("done", "success", "success") print() self.exitWithCode(EXIT_SUCCESS) end function commandLine.reportFailure(errorMessage) log("fail", errorMessage, "failure") print() self.exitWithCode(EXIT_FAILURE) end function commandLine.outputVersionInfo() log("lit version", version) log("luvi version", require("luvi").version) end function commandLine.exitWithCode(exitCode) uv.walk(function(handle) if handle then local function close() if not handle:is_closing() then handle:close() end end if handle.shutdown then handle:shutdown(close) else close() end end end) uv.run() os.exit(exitCode) end function commandLine.isValidCommand(command) local commandHandler = "./commands/" .. command .. ".lua" return bundle.stat(commandHandler:sub(3)) -- A command is valid if a script handler for it exists end function commandLine.executeCommandHandler(command) local commandHandler = "./commands/" .. command .. ".lua" require(commandHandler)() end commandLine.run()
--[[ Copyright 2014-2015 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 bundle = require("luvi").bundle loadstring(bundle.readfile("luvit-loader.lua"), "bundle:luvit-loader.lua")() -- Upvalues local uv = require("uv") local version = require("./package").version local log = require("log").log require("snapshot") -- Global setup _G.p = require("pretty-print").prettyPrint -- Settings local EXIT_SUCCESS = 0 local EXIT_FAILURE = -1 local aliases = { ["-v"] = "version", ["-h"] = "help" } local commandLine = {} function commandLine.run() coroutine.wrap(function() commandLine.processUserInput() end)() uv.run() end function commandLine.processUserInput() local command = commandLine.processArguments() local success, errorMessage = xpcall(function() commandLine.executeCommand(command) end, debug.traceback) if not success then commandLine.reportFailure(errorMessage) return end commandLine.reportSuccess() end function commandLine.processArguments() local command = args[1] or "help" if command:sub(1, 2) == "--" then command = command:sub(3) end command = aliases[command] or command return command end function commandLine.executeCommand(command) commandLine.outputVersionInfo() if command == "version" then -- Since the version is always printed, there's nothing left to do commandLine.exitWithCode(EXIT_SUCCESS) end if commandLine.isValidCommand(command) then log("command", table.concat(args, " "), "highlight") commandLine.executeCommandHandler(command) else log("invalid command", command, "failure") commandLine.executeCommandHandler("help") commandLine.reportFailure("Invalid Command: " .. command) end end function commandLine.reportSuccess() log("done", "success", "success") print() commandLine.exitWithCode(EXIT_SUCCESS) end function commandLine.reportFailure(errorMessage) log("fail", errorMessage, "failure") print() commandLine.exitWithCode(EXIT_FAILURE) end function commandLine.outputVersionInfo() log("lit version", version) log("luvi version", require("luvi").version) end function commandLine.exitWithCode(exitCode) uv.walk(function(handle) if handle then local function close() if not handle:is_closing() then handle:close() end end if handle.shutdown then handle:shutdown(close) else close() end end end) uv.run() os.exit(exitCode) end function commandLine.isValidCommand(command) local commandHandler = "./commands/" .. command .. ".lua" return bundle.stat(commandHandler:sub(3)) -- A command is valid if a script handler for it exists end function commandLine.executeCommandHandler(command) local commandHandler = "./commands/" .. command .. ".lua" require(commandHandler)() end commandLine.run()
Fix invalid references to self
Fix invalid references to self
Lua
apache-2.0
zhaozg/lit,luvit/lit
2fd077d8d6fafddc0ccc7a61d29d9dc70c7fa7f6
examples/compress.lua
examples/compress.lua
--[[ compress.lua This example shows how a the compress module can be used to create zip files and write them to a compatible ostream. Files and directories can be added via istreams and filesystem paths. --]] -- the ostream local fostream = assert(require("poco.fileostream")) local compress = assert(require("poco.zip.compress")) local path = assert(require("poco.path")) -- write the zip file to the output stream in the temp directory. local output_zip_path = path(path.temp()) output_zip_path:setFileName("compress_example.zip") local zfs = assert(fostream(output_zip_path:toString())) -- create compress instance with the fileostream. --- compress stores a reference to the fileostream to prevent GC, --- so a reference does not need to be maintained by the caller. --- additionally, the default true parameter for seekable must be false for --- non-seekable istreams such as pipeistream, socketistream, etc. local c = assert(compress(zfs)) -- print the list of file extensions that will get stored in the zipfile -- via the STORE method rather than DEFLATE. print("\nFile extensions using STORE method: ") for k,v in pairs(c:getStoreExtensions()) do print(k,v) end -- store a comment for the zip file and print it out. c:setZipComment("example comment") print("\nZip file comment:", c:getZipComment()) -- assume current working directory is the directory containing the examples. local examples_path = assert(path(path.current())) -- add all files and directories under the 'examples' directory to the zip file. io.write(string.format("\nAdding recursive directory: %s\nto: %s\n", examples_path:toString(), output_zip_path:toString())) assert(c:addRecursive(examples_path, "examples")) -- add README.md to readme/README.md via the addFile function. examples_path:popDirectory() examples_path:setFileName("README.md") io.write(string.format("\nAdding File: %s\nto: %s\n", examples_path:toString(), output_zip_path:toString())) -- assert(c:addFile(examples_path, "readme/README.md")) --[[ alternatively one could add a file via an poco istream via the addIStream function. -- note that this source could be a memoryistream, pipeistream, socketistream, etc. local fistream = assert(require("poco.fileistream")) local fis = assert(fistream(examples_path:toString())) --]] -- finalize the zip file. c:close()
--[[ compress.lua This example shows how a the compress module can be used to create zip files and write them to a compatible ostream. Files and directories can be added via istreams and filesystem paths. --]] -- the ostream could be other types, such as pipeostream, teeostream, memoryostream, etc. local fostream = assert(require("poco.fileostream")) local compress = assert(require("poco.zip.compress")) local path = assert(require("poco.path")) -- write the zip file to the output stream in the temp directory. local output_zip_path = path(path.temp()) output_zip_path:setFileName("compress_example.zip") local zfs = assert(fostream(output_zip_path:toString())) -- create compress instance with the fileostream. --- compress stores a reference to the fileostream to prevent GC, --- so a reference does not need to be maintained by the caller. --- additionally, the default true parameter for seekable must be false for --- non-seekable istreams such as pipeistream, socketistream, etc. local c = assert(compress(zfs)) -- print the list of file extensions that will get stored in the zipfile -- via the STORE method rather than DEFLATE. print("\nFile extensions using STORE method: ") for k,v in pairs(c:getStoreExtensions()) do print(k,v) end -- store a comment for the zip file and print it out. c:setZipComment("example comment") print("\nZip file comment:", c:getZipComment()) -- assume current working directory is the directory containing the examples. local examples_path = assert(path(path.current())) -- add all files and directories under the 'examples' directory to the zip file. io.write(string.format("\nAdding recursive directory: %s\nto: %s\n", examples_path:toString(), output_zip_path:toString())) assert(c:addRecursive(examples_path, "examples")) -- add README.md to readme/README.md via the addFile function. examples_path:popDirectory() examples_path:setFileName("README.md") io.write(string.format("\nAdding File: %s\nto: %s\n", examples_path:toString(), output_zip_path:toString())) assert(c:addFile(examples_path, "readme/README.md")) --[[ alternatively one could add a file via an poco istream via the addIStream function. -- note that this source could be a memoryistream, pipeistream, socketistream, etc. local fistream = assert(require("poco.fileistream")) local fis = assert(fistream(examples_path:toString())) --]] -- finalize the zip file. c:close()
uncomment addFile() example, fix ostream comment
uncomment addFile() example, fix ostream comment
Lua
bsd-3-clause
ma-bo/lua-poco,ma-bo/lua-poco
00304b3c634280db1a63bffa285ce946b06eb243
examples/scorched.lua
examples/scorched.lua
-- Basic Scorched Earth clone NUM_PLAYERS = 3 function setup() setup_terrain() setup_players() end function setup_terrain() terrain = {} local periods = {} local amplitudes = {} local nwaves = 10 for i = 1, nwaves do periods[i] = math.random()*0.1 + 0.01 amplitudes[i] = math.random() * 50 end for i = 0, WIDTH-1 do local h = 200 for j = 1, nwaves do h = h + math.sin(i*periods[j])*amplitudes[j] end terrain[i] = h end end function setup_players() players = {} for i = 1, NUM_PLAYERS do local player = {} player.x = math.random(10, WIDTH-10) player.y = terrain[player.x] player.r = 255 player.g = 0 player.b = 0 for x = player.x - 8, player.x + 8 do if terrain[x] >= player.y then terrain[x] = player.y-1 end end players[i] = player end end function draw() draw_terrain() draw_players() end function draw_terrain() background(30, 30, 200) fill(20, 150, 20, 1.0) for i = 0, WIDTH-1 do line(i, 0, i, terrain[i]) end end function draw_players() for i, player in ipairs(players) do fill(player.r, player.g, player.b, 1) rect(player.x-6, player.y, 12, 8) end end
-- Basic Scorched Earth clone NUM_PLAYERS = 3 function setup() setup_terrain() setup_players() end function setup_terrain() terrain = {} local periods = {} local amplitudes = {} local nwaves = 10 for i = 1, nwaves do periods[i] = math.random()*0.1 + 0.01 amplitudes[i] = math.random() * 50 end for i = 0, WIDTH-1 do local h = 200 for j = 1, nwaves do h = h + math.sin(i*periods[j])*amplitudes[j] end terrain[i] = h end end function setup_players() players = {} for i = 1, NUM_PLAYERS do local player = {} player.x = math.random(10, WIDTH-10) player.y = terrain[player.x] player.r = 255 player.g = 0 player.b = 0 for x = player.x - 8, player.x + 8 do if terrain[x] >= player.y then terrain[x] = player.y-1 end end players[i] = player end end function draw() draw_terrain() draw_players() end function draw_terrain() background(30, 30, 200) fill(20, 150, 20, 1.0) for i = 0, WIDTH-1 do line(i, 0, i, terrain[i]) end end function draw_players() for i, player in ipairs(players) do fill(player.r, player.g, player.b, 1) rect(player.x-6, player.y, 12, 8) end end
scorched: fix indentation
scorched: fix indentation
Lua
bsd-2-clause
antirez/load81,seclorum/load81,saisai/load81,antirez/load81,seclorum/load81,saisai/load81,antirez/load81,seclorum/load81,seclorum/load81,antirez/load81,saisai/load81,seclorum/load81,antirez/load81,saisai/load81,saisai/load81
64b052bbd8b46779269b8a4a1f10e51a67e0ee7e
modules/luci-mod-admin-full/luasrc/model/cbi/admin_system/fstab.lua
modules/luci-mod-admin-full/luasrc/model/cbi/admin_system/fstab.lua
-- Copyright 2008 Steven Barth <steven@midlink.org> -- Licensed to the public under the Apache License 2.0. require("luci.tools.webadmin") local fs = require "nixio.fs" local util = require "nixio.util" local tp = require "luci.template.parser" local block = io.popen("block info", "r") local ln, dev, devices = nil, nil, {} repeat ln = block:read("*l") dev = ln and ln:match("^/dev/(.-):") if dev then local e, s, key, val = { } for key, val in ln:gmatch([[(%w+)="(.-)"]]) do e[key:lower()] = val devices[val] = e end s = tonumber((fs.readfile("/sys/class/block/%s/size" % dev))) e.dev = "/dev/%s" % dev e.size = s and math.floor(s / 2048) devices[e.dev] = e end until not ln block:close() m = Map("fstab", translate("Mount Points")) local mounts = luci.sys.mounts() v = m:section(Table, mounts, translate("Mounted file systems")) fs = v:option(DummyValue, "fs", translate("Filesystem")) mp = v:option(DummyValue, "mountpoint", translate("Mount Point")) avail = v:option(DummyValue, "avail", translate("Available")) function avail.cfgvalue(self, section) return luci.tools.webadmin.byte_format( ( tonumber(mounts[section].available) or 0 ) * 1024 ) .. " / " .. luci.tools.webadmin.byte_format( ( tonumber(mounts[section].blocks) or 0 ) * 1024 ) end used = v:option(DummyValue, "used", translate("Used")) function used.cfgvalue(self, section) return ( mounts[section].percent or "0%" ) .. " (" .. luci.tools.webadmin.byte_format( ( tonumber(mounts[section].used) or 0 ) * 1024 ) .. ")" end mount = m:section(TypedSection, "mount", translate("Mount Points"), translate("Mount Points define at which point a memory device will be attached to the filesystem")) mount.anonymous = true mount.addremove = true mount.template = "cbi/tblsection" mount.extedit = luci.dispatcher.build_url("admin/system/fstab/mount/%s") mount.create = function(...) local sid = TypedSection.create(...) if sid then luci.http.redirect(mount.extedit % sid) return end end mount:option(Flag, "enabled", translate("Enabled")).rmempty = false dev = mount:option(DummyValue, "device", translate("Device")) dev.rawhtml = true dev.cfgvalue = function(self, section) local v, e v = m.uci:get("fstab", section, "uuid") e = v and devices[v:lower()] if v and e and e.size then return "UUID: %s (%s, %d MB)" %{ tp.pcdata(v), e.dev, e.size } elseif v and e then return "UUID: %s (%s)" %{ tp.pcdata(v), e.dev } elseif v then return "UUID: %s (<em>%s</em>)" %{ tp.pcdata(v), translate("not present") } end v = m.uci:get("fstab", section, "label") e = v and devices[v] if v and e and e.size then return "Label: %s (%s, %d MB)" %{ tp.pcdata(v), e.dev, e.size } elseif v and e then return "Label: %s (%s)" %{ tp.pcdata(v), e.dev } elseif v then return "Label: %s (<em>%s</em>)" %{ tp.pcdata(v), translate("not present") } end v = Value.cfgvalue(self, section) or "?" e = v and devices[v] if v and e and e.size then return "%s (%d MB)" %{ tp.pcdata(v), e.size } elseif v and e then return tp.pcdata(v) elseif v then return "%s (<em>%s</em>)" %{ tp.pcdata(v), translate("not present") } end end mp = mount:option(DummyValue, "target", translate("Mount Point")) mp.cfgvalue = function(self, section) if m.uci:get("fstab", section, "is_rootfs") == "1" then return "/overlay" else return Value.cfgvalue(self, section) or "?" end end fs = mount:option(DummyValue, "fstype", translate("Filesystem")) fs.cfgvalue = function(self, section) local v, e v = m.uci:get("fstab", section, "uuid") v = v and v:lower() or m.uci:get("fstab", section, "label") v = v or m.uci:get("fstab", section, "device") e = v and devices[v] return e and e.type or m.uci:get("fstab", section, "fstype") or "?" end op = mount:option(DummyValue, "options", translate("Options")) op.cfgvalue = function(self, section) return Value.cfgvalue(self, section) or "defaults" end rf = mount:option(DummyValue, "is_rootfs", translate("Root")) rf.cfgvalue = function(self, section) local target = m.uci:get("fstab", section, "target") if target == "/" then return translate("yes") elseif target == "/overlay" then return translate("overlay") else return translate("no") end end ck = mount:option(DummyValue, "enabled_fsck", translate("Check")) ck.cfgvalue = function(self, section) return Value.cfgvalue(self, section) == "1" and translate("yes") or translate("no") end swap = m:section(TypedSection, "swap", "SWAP", translate("If your physical memory is insufficient unused data can be temporarily swapped to a swap-device resulting in a higher amount of usable <abbr title=\"Random Access Memory\">RAM</abbr>. Be aware that swapping data is a very slow process as the swap-device cannot be accessed with the high datarates of the <abbr title=\"Random Access Memory\">RAM</abbr>.")) swap.anonymous = true swap.addremove = true swap.template = "cbi/tblsection" swap.extedit = luci.dispatcher.build_url("admin/system/fstab/swap/%s") swap.create = function(...) local sid = TypedSection.create(...) if sid then luci.http.redirect(swap.extedit % sid) return end end swap:option(Flag, "enabled", translate("Enabled")).rmempty = false dev = swap:option(DummyValue, "device", translate("Device")) dev.cfgvalue = function(self, section) local v v = m.uci:get("fstab", section, "uuid") if v then return "UUID: %s" % v end v = m.uci:get("fstab", section, "label") if v then return "Label: %s" % v end v = Value.cfgvalue(self, section) or "?" return size[v] and "%s (%s MB)" % {v, size[v]} or v end return m
-- Copyright 2008 Steven Barth <steven@midlink.org> -- Licensed to the public under the Apache License 2.0. require("luci.tools.webadmin") local fs = require "nixio.fs" local util = require "nixio.util" local tp = require "luci.template.parser" local block = io.popen("block info", "r") local ln, dev, devices = nil, nil, {} repeat ln = block:read("*l") dev = ln and ln:match("^/dev/(.-):") if dev then local e, s, key, val = { } for key, val in ln:gmatch([[(%w+)="(.-)"]]) do e[key:lower()] = val devices[val] = e end s = tonumber((fs.readfile("/sys/class/block/%s/size" % dev))) e.dev = "/dev/%s" % dev e.size = s and math.floor(s / 2048) devices[e.dev] = e end until not ln block:close() m = Map("fstab", translate("Mount Points")) local mounts = luci.sys.mounts() v = m:section(Table, mounts, translate("Mounted file systems")) fs = v:option(DummyValue, "fs", translate("Filesystem")) mp = v:option(DummyValue, "mountpoint", translate("Mount Point")) avail = v:option(DummyValue, "avail", translate("Available")) function avail.cfgvalue(self, section) return luci.tools.webadmin.byte_format( ( tonumber(mounts[section].available) or 0 ) * 1024 ) .. " / " .. luci.tools.webadmin.byte_format( ( tonumber(mounts[section].blocks) or 0 ) * 1024 ) end used = v:option(DummyValue, "used", translate("Used")) function used.cfgvalue(self, section) return ( mounts[section].percent or "0%" ) .. " (" .. luci.tools.webadmin.byte_format( ( tonumber(mounts[section].used) or 0 ) * 1024 ) .. ")" end mount = m:section(TypedSection, "mount", translate("Mount Points"), translate("Mount Points define at which point a memory device will be attached to the filesystem")) mount.anonymous = true mount.addremove = true mount.template = "cbi/tblsection" mount.extedit = luci.dispatcher.build_url("admin/system/fstab/mount/%s") mount.create = function(...) local sid = TypedSection.create(...) if sid then luci.http.redirect(mount.extedit % sid) return end end mount:option(Flag, "enabled", translate("Enabled")).rmempty = false dev = mount:option(DummyValue, "device", translate("Device")) dev.rawhtml = true dev.cfgvalue = function(self, section) local v, e v = m.uci:get("fstab", section, "uuid") e = v and devices[v:lower()] if v and e and e.size then return "UUID: %s (%s, %d MB)" %{ tp.pcdata(v), e.dev, e.size } elseif v and e then return "UUID: %s (%s)" %{ tp.pcdata(v), e.dev } elseif v then return "UUID: %s (<em>%s</em>)" %{ tp.pcdata(v), translate("not present") } end v = m.uci:get("fstab", section, "label") e = v and devices[v] if v and e and e.size then return "Label: %s (%s, %d MB)" %{ tp.pcdata(v), e.dev, e.size } elseif v and e then return "Label: %s (%s)" %{ tp.pcdata(v), e.dev } elseif v then return "Label: %s (<em>%s</em>)" %{ tp.pcdata(v), translate("not present") } end v = Value.cfgvalue(self, section) or "?" e = v and devices[v] if v and e and e.size then return "%s (%d MB)" %{ tp.pcdata(v), e.size } elseif v and e then return tp.pcdata(v) elseif v then return "%s (<em>%s</em>)" %{ tp.pcdata(v), translate("not present") } end end mp = mount:option(DummyValue, "target", translate("Mount Point")) mp.cfgvalue = function(self, section) if m.uci:get("fstab", section, "is_rootfs") == "1" then return "/overlay" else return Value.cfgvalue(self, section) or "?" end end fs = mount:option(DummyValue, "fstype", translate("Filesystem")) fs.cfgvalue = function(self, section) local v, e v = m.uci:get("fstab", section, "uuid") v = v and v:lower() or m.uci:get("fstab", section, "label") v = v or m.uci:get("fstab", section, "device") e = v and devices[v] return e and e.type or m.uci:get("fstab", section, "fstype") or "?" end op = mount:option(DummyValue, "options", translate("Options")) op.cfgvalue = function(self, section) return Value.cfgvalue(self, section) or "defaults" end rf = mount:option(DummyValue, "is_rootfs", translate("Root")) rf.cfgvalue = function(self, section) local target = m.uci:get("fstab", section, "target") if target == "/" then return translate("yes") elseif target == "/overlay" then return translate("overlay") else return translate("no") end end ck = mount:option(DummyValue, "enabled_fsck", translate("Check")) ck.cfgvalue = function(self, section) return Value.cfgvalue(self, section) == "1" and translate("yes") or translate("no") end swap = m:section(TypedSection, "swap", "SWAP", translate("If your physical memory is insufficient unused data can be temporarily swapped to a swap-device resulting in a higher amount of usable <abbr title=\"Random Access Memory\">RAM</abbr>. Be aware that swapping data is a very slow process as the swap-device cannot be accessed with the high datarates of the <abbr title=\"Random Access Memory\">RAM</abbr>.")) swap.anonymous = true swap.addremove = true swap.template = "cbi/tblsection" swap.extedit = luci.dispatcher.build_url("admin/system/fstab/swap/%s") swap.create = function(...) local sid = TypedSection.create(...) if sid then luci.http.redirect(swap.extedit % sid) return end end swap:option(Flag, "enabled", translate("Enabled")).rmempty = false dev = swap:option(DummyValue, "device", translate("Device")) dev.cfgvalue = function(self, section) local v v = m.uci:get("fstab", section, "uuid") if v then return "UUID: %s" % v end v = m.uci:get("fstab", section, "label") if v then return "Label: %s" % v end v = Value.cfgvalue(self, section) or "?" e = v and devices[v] if v and e and e.size then return "%s (%s MB)" % {v, e.size} else return v end end return m
luci-mod-admin-full: mount points SWAP fix
luci-mod-admin-full: mount points SWAP fix SWAP section was showing an error. Fixed it to display the devices/size properly.
Lua
apache-2.0
deepak78/new-luci,taiha/luci,cshore-firmware/openwrt-luci,artynet/luci,ff94315/luci-1,hnyman/luci,shangjiyu/luci-with-extra,db260179/openwrt-bpi-r1-luci,schidler/ionic-luci,MinFu/luci,NeoRaider/luci,remakeelectric/luci,mumuqz/luci,NeoRaider/luci,urueedi/luci,oneru/luci,LazyZhu/openwrt-luci-trunk-mod,kuoruan/luci,db260179/openwrt-bpi-r1-luci,openwrt-es/openwrt-luci,kuoruan/luci,RuiChen1113/luci,nmav/luci,thess/OpenWrt-luci,jchuang1977/luci-1,daofeng2015/luci,cshore/luci,hnyman/luci,marcel-sch/luci,urueedi/luci,forward619/luci,deepak78/new-luci,david-xiao/luci,oyido/luci,Wedmer/luci,cshore-firmware/openwrt-luci,981213/luci-1,wongsyrone/luci-1,mumuqz/luci,Sakura-Winkey/LuCI,zhaoxx063/luci,Noltari/luci,kuoruan/luci,thesabbir/luci,oyido/luci,openwrt/luci,cappiewu/luci,hnyman/luci,thesabbir/luci,bright-things/ionic-luci,daofeng2015/luci,taiha/luci,kuoruan/lede-luci,lbthomsen/openwrt-luci,Noltari/luci,chris5560/openwrt-luci,kuoruan/lede-luci,LuttyYang/luci,oneru/luci,male-puppies/luci,schidler/ionic-luci,maxrio/luci981213,dwmw2/luci,florian-shellfire/luci,fkooman/luci,Sakura-Winkey/LuCI,ff94315/luci-1,cappiewu/luci,jorgifumi/luci,schidler/ionic-luci,981213/luci-1,tobiaswaldvogel/luci,Noltari/luci,remakeelectric/luci,joaofvieira/luci,maxrio/luci981213,tobiaswaldvogel/luci,dwmw2/luci,joaofvieira/luci,dwmw2/luci,jchuang1977/luci-1,rogerpueyo/luci,kuoruan/lede-luci,remakeelectric/luci,thesabbir/luci,lbthomsen/openwrt-luci,forward619/luci,Sakura-Winkey/LuCI,Sakura-Winkey/LuCI,jorgifumi/luci,daofeng2015/luci,sujeet14108/luci,tobiaswaldvogel/luci,teslamint/luci,openwrt-es/openwrt-luci,maxrio/luci981213,florian-shellfire/luci,tcatm/luci,cshore/luci,jlopenwrtluci/luci,db260179/openwrt-bpi-r1-luci,cshore/luci,nmav/luci,bright-things/ionic-luci,schidler/ionic-luci,rogerpueyo/luci,ff94315/luci-1,jlopenwrtluci/luci,openwrt-es/openwrt-luci,dwmw2/luci,ollie27/openwrt_luci,ff94315/luci-1,tcatm/luci,nmav/luci,jlopenwrtluci/luci,ollie27/openwrt_luci,oyido/luci,kuoruan/luci,shangjiyu/luci-with-extra,forward619/luci,Wedmer/luci,jlopenwrtluci/luci,Wedmer/luci,LuttyYang/luci,jchuang1977/luci-1,florian-shellfire/luci,NeoRaider/luci,nwf/openwrt-luci,nwf/openwrt-luci,LazyZhu/openwrt-luci-trunk-mod,joaofvieira/luci,mumuqz/luci,ff94315/luci-1,schidler/ionic-luci,chris5560/openwrt-luci,bright-things/ionic-luci,urueedi/luci,kuoruan/luci,chris5560/openwrt-luci,maxrio/luci981213,aa65535/luci,bright-things/ionic-luci,rogerpueyo/luci,fkooman/luci,rogerpueyo/luci,ollie27/openwrt_luci,dwmw2/luci,fkooman/luci,ollie27/openwrt_luci,nwf/openwrt-luci,teslamint/luci,schidler/ionic-luci,NeoRaider/luci,remakeelectric/luci,lcf258/openwrtcn,chris5560/openwrt-luci,cappiewu/luci,ollie27/openwrt_luci,florian-shellfire/luci,bittorf/luci,taiha/luci,cshore/luci,remakeelectric/luci,forward619/luci,obsy/luci,artynet/luci,mumuqz/luci,Noltari/luci,openwrt-es/openwrt-luci,981213/luci-1,MinFu/luci,marcel-sch/luci,zhaoxx063/luci,teslamint/luci,daofeng2015/luci,thesabbir/luci,joaofvieira/luci,nwf/openwrt-luci,nwf/openwrt-luci,artynet/luci,fkooman/luci,wongsyrone/luci-1,artynet/luci,bittorf/luci,nmav/luci,jlopenwrtluci/luci,remakeelectric/luci,openwrt/luci,deepak78/new-luci,oyido/luci,jorgifumi/luci,daofeng2015/luci,lcf258/openwrtcn,artynet/luci,hnyman/luci,rogerpueyo/luci,zhaoxx063/luci,db260179/openwrt-bpi-r1-luci,male-puppies/luci,shangjiyu/luci-with-extra,lbthomsen/openwrt-luci,sujeet14108/luci,openwrt-es/openwrt-luci,jlopenwrtluci/luci,david-xiao/luci,Wedmer/luci,thesabbir/luci,rogerpueyo/luci,cappiewu/luci,lbthomsen/openwrt-luci,sujeet14108/luci,obsy/luci,obsy/luci,aa65535/luci,david-xiao/luci,forward619/luci,nwf/openwrt-luci,florian-shellfire/luci,tobiaswaldvogel/luci,oyido/luci,Hostle/luci,db260179/openwrt-bpi-r1-luci,openwrt-es/openwrt-luci,lcf258/openwrtcn,forward619/luci,kuoruan/lede-luci,deepak78/new-luci,shangjiyu/luci-with-extra,thess/OpenWrt-luci,LuttyYang/luci,kuoruan/luci,981213/luci-1,MinFu/luci,Hostle/luci,lcf258/openwrtcn,LuttyYang/luci,Noltari/luci,RuiChen1113/luci,981213/luci-1,mumuqz/luci,bittorf/luci,bittorf/luci,nwf/openwrt-luci,shangjiyu/luci-with-extra,cshore/luci,deepak78/new-luci,openwrt/luci,mumuqz/luci,joaofvieira/luci,Noltari/luci,cshore/luci,mumuqz/luci,tcatm/luci,jlopenwrtluci/luci,lcf258/openwrtcn,rogerpueyo/luci,wongsyrone/luci-1,daofeng2015/luci,obsy/luci,fkooman/luci,florian-shellfire/luci,bittorf/luci,marcel-sch/luci,Sakura-Winkey/LuCI,david-xiao/luci,Hostle/luci,bittorf/luci,oneru/luci,shangjiyu/luci-with-extra,artynet/luci,teslamint/luci,chris5560/openwrt-luci,kuoruan/luci,MinFu/luci,bright-things/ionic-luci,Hostle/luci,zhaoxx063/luci,kuoruan/lede-luci,MinFu/luci,marcel-sch/luci,lbthomsen/openwrt-luci,oneru/luci,lcf258/openwrtcn,teslamint/luci,oyido/luci,dwmw2/luci,obsy/luci,ff94315/luci-1,LazyZhu/openwrt-luci-trunk-mod,kuoruan/lede-luci,marcel-sch/luci,male-puppies/luci,cappiewu/luci,joaofvieira/luci,lcf258/openwrtcn,zhaoxx063/luci,david-xiao/luci,RuiChen1113/luci,openwrt/luci,RuiChen1113/luci,tcatm/luci,joaofvieira/luci,tobiaswaldvogel/luci,Hostle/luci,nmav/luci,ff94315/luci-1,teslamint/luci,openwrt-es/openwrt-luci,cappiewu/luci,MinFu/luci,jorgifumi/luci,LuttyYang/luci,urueedi/luci,lbthomsen/openwrt-luci,Hostle/luci,rogerpueyo/luci,nmav/luci,sujeet14108/luci,remakeelectric/luci,jchuang1977/luci-1,Sakura-Winkey/LuCI,zhaoxx063/luci,cshore-firmware/openwrt-luci,urueedi/luci,openwrt/luci,florian-shellfire/luci,RuiChen1113/luci,kuoruan/lede-luci,marcel-sch/luci,zhaoxx063/luci,forward619/luci,LazyZhu/openwrt-luci-trunk-mod,NeoRaider/luci,jchuang1977/luci-1,maxrio/luci981213,obsy/luci,cshore/luci,jchuang1977/luci-1,aa65535/luci,Wedmer/luci,urueedi/luci,sujeet14108/luci,david-xiao/luci,MinFu/luci,obsy/luci,openwrt/luci,lcf258/openwrtcn,david-xiao/luci,sujeet14108/luci,wongsyrone/luci-1,sujeet14108/luci,chris5560/openwrt-luci,thess/OpenWrt-luci,openwrt-es/openwrt-luci,kuoruan/luci,wongsyrone/luci-1,forward619/luci,jorgifumi/luci,shangjiyu/luci-with-extra,aa65535/luci,hnyman/luci,mumuqz/luci,shangjiyu/luci-with-extra,fkooman/luci,jchuang1977/luci-1,jorgifumi/luci,nmav/luci,taiha/luci,male-puppies/luci,maxrio/luci981213,thess/OpenWrt-luci,kuoruan/lede-luci,oneru/luci,hnyman/luci,aa65535/luci,joaofvieira/luci,fkooman/luci,male-puppies/luci,openwrt/luci,aa65535/luci,aa65535/luci,ollie27/openwrt_luci,bright-things/ionic-luci,Wedmer/luci,artynet/luci,urueedi/luci,tcatm/luci,RuiChen1113/luci,db260179/openwrt-bpi-r1-luci,bittorf/luci,LuttyYang/luci,NeoRaider/luci,daofeng2015/luci,maxrio/luci981213,remakeelectric/luci,zhaoxx063/luci,male-puppies/luci,nwf/openwrt-luci,nmav/luci,marcel-sch/luci,oneru/luci,db260179/openwrt-bpi-r1-luci,lcf258/openwrtcn,jlopenwrtluci/luci,LazyZhu/openwrt-luci-trunk-mod,wongsyrone/luci-1,cshore-firmware/openwrt-luci,cshore/luci,ff94315/luci-1,daofeng2015/luci,taiha/luci,schidler/ionic-luci,NeoRaider/luci,LazyZhu/openwrt-luci-trunk-mod,dwmw2/luci,Noltari/luci,thesabbir/luci,Hostle/luci,MinFu/luci,male-puppies/luci,ollie27/openwrt_luci,RuiChen1113/luci,artynet/luci,deepak78/new-luci,deepak78/new-luci,bright-things/ionic-luci,teslamint/luci,hnyman/luci,lbthomsen/openwrt-luci,NeoRaider/luci,oneru/luci,LuttyYang/luci,nmav/luci,dwmw2/luci,obsy/luci,oyido/luci,wongsyrone/luci-1,bright-things/ionic-luci,tobiaswaldvogel/luci,tcatm/luci,thess/OpenWrt-luci,Sakura-Winkey/LuCI,981213/luci-1,thess/OpenWrt-luci,Wedmer/luci,chris5560/openwrt-luci,cshore-firmware/openwrt-luci,marcel-sch/luci,thess/OpenWrt-luci,LuttyYang/luci,thesabbir/luci,bittorf/luci,tobiaswaldvogel/luci,Noltari/luci,tobiaswaldvogel/luci,taiha/luci,oyido/luci,ollie27/openwrt_luci,male-puppies/luci,teslamint/luci,thess/OpenWrt-luci,artynet/luci,oneru/luci,jorgifumi/luci,wongsyrone/luci-1,schidler/ionic-luci,aa65535/luci,deepak78/new-luci,cshore-firmware/openwrt-luci,thesabbir/luci,LazyZhu/openwrt-luci-trunk-mod,Wedmer/luci,hnyman/luci,LazyZhu/openwrt-luci-trunk-mod,RuiChen1113/luci,db260179/openwrt-bpi-r1-luci,tcatm/luci,jorgifumi/luci,taiha/luci,cappiewu/luci,david-xiao/luci,florian-shellfire/luci,sujeet14108/luci,cappiewu/luci,cshore-firmware/openwrt-luci,Hostle/luci,urueedi/luci,lbthomsen/openwrt-luci,fkooman/luci,jchuang1977/luci-1,tcatm/luci,taiha/luci,lcf258/openwrtcn,Sakura-Winkey/LuCI,maxrio/luci981213,Noltari/luci,openwrt/luci,chris5560/openwrt-luci,981213/luci-1,cshore-firmware/openwrt-luci
89e089e61f79397be4590c95cb616cff1fc9441f
icesl-gallery/gear.lua
icesl-gallery/gear.lua
--[[ The MIT License (MIT) Copyright (c) 2019 Loïc Fejoz 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. ]] -- emit the inside of the involute of the circle of radius r for the first two quadrants local r = 15 local n = 16 local h = 3 gear = implicit_distance_field(v(-6*r,-2*r,0), v(2*r,4*r,h), [[ const float PI = 3.1415926535897932384626433832795; uniform float r = 5; uniform float n = 16; float involute_solid(vec3 p) { float num = p.y + sqrt(p.x * p.x + p.y * p.y - r * r); float denom = r + p.x; float theta = 2 * atan(num, denom); vec2 c = vec2(r * cos(theta), r * sin(theta)); float s = r * theta; float sp = length(p.xy - c); return sp - s; } float distance(vec3 p) { float l = length(p.xy) - r; float alpha1 = mod(atan(p.y, p.x), 2 * PI / n); float rho = length(p.xy); vec3 p1 = vec3(rho * cos(alpha1), rho * sin(alpha1), p.z); float alpha2 = mod(atan(p.y, -p.x), 2 * PI / n); vec3 p2 = vec3(rho * cos(alpha2), rho * sin(alpha2), p.z); return min(l, max(involute_solid(p1), involute_solid(p2))); } ]]) set_uniform_scalar(gear, 'r', r) set_uniform_scalar(gear, 'n', n) emit(gear,2) emit(cylinder(r,h),1)
--[[ The MIT License (MIT) Copyright (c) 2019 Loïc Fejoz 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. ]] function gear_solid(params) local number_of_teeth = params.number_of_teeth or 15 local circular_pitch = params.circular_pitch or -1 local diametral_pitch = params.diametral_pitch or -1 local pressure_angle = params.pressure_angle or 28 local clearance = params.clearance or 0.2 local gear_thickness = params.gear_thickness or 12 local rim_thickness = params.rim_thickness or 15 local rim_width = params.rim_width or 5 local hub_thickness = params.hub_thickness or 17 local hub_diameter = params.hub_diameter or 15 local bore_diameter = params.bore_diameter or 5 local circles = params.circles or 3 local backlash = params.backlash or 0 local twist = params.twist or 0 local involute_facets = params.involute_facets or 0 local flat = params.flat or false if ( circular_pitch < 0 and diametral_pitch < 0 ) then print("!! gear module needs either a diametral_pitch or circular_pitch !!"); return Void end -- Convert diametrial pitch to our native circular pitch if circular_pitch < 0 then circular_pitch = 180/diametral_pitch end print("Circular pitch:" .. circular_pitch) -- Pitch diameter: Diameter of pitch circle. pitch_diameter = number_of_teeth * circular_pitch / 180; pitch_radius = pitch_diameter/2; print("Teeth:" .. number_of_teeth) print("Pitch radius:" .. pitch_radius); -- Base Circle base_radius = pitch_radius*cos(pressure_angle); print("Base radius:" .. base_radius) -- Diametrial pitch: Number of teeth per unit length. pitch_diametrial = number_of_teeth / pitch_diameter; print("Pitch diametrial:" .. pitch_diametrial) -- Addendum: Radial distance from pitch circle to outside circle. addendum = 1/pitch_diametrial; print("Addendum:" .. addendum) --Outer Circle outer_radius = pitch_radius+addendum; print("Outer radius:" .. outer_radius) -- Dedendum: Radial distance from pitch circle to root diameter dedendum = addendum + clearance; print("Dedendum:" .. dedendum) -- Root diameter: Diameter of bottom of tooth spaces. root_radius = pitch_radius-dedendum; print("Root radius:" .. root_radius) backlash_angle = backlash / pitch_radius * 180 / math.pi; print("Backlash angle:"..backlash_angle) half_thick_angle = (360 / number_of_teeth - backlash_angle) / 4; print("half_thick_angle:" .. half_thick_angle) -- Variables controlling the rim. rim_radius = root_radius - rim_width; print("Rim radius:"..rim_radius) -- Variables controlling the circular holes in the gear. circle_orbit_diameter=hub_diameter/2+rim_radius; circle_orbit_curcumference=math.pi*circle_orbit_diameter; local gear = implicit_distance_field( v(-2*root_radius,-2*root_radius,0), v(2*root_radius,2*root_radius, rim_thickness*0.8), [[ const float PI = 3.1415926535897932384626433832795; uniform float r = 5; uniform float z = 16; uniform float r_outside = 20; uniform float r_root = 15; uniform float delta_involute = 0.5; float involute_solid(vec3 p) { float num = p.y + sqrt(p.x * p.x + p.y * p.y - r * r); float denom = r + p.x; float theta = 2 * atan(num, denom); vec2 c = vec2(r * cos(theta), r * sin(theta)); float s = r * theta; float sp = length(p.xy - c); return sp - s + delta_involute; } float distance(vec3 p) { float l_outside = length(p.xy) - r_outside; float l_root = length(p.xy) - r_root; float alpha1 = mod(atan(p.y, p.x), 2 * PI / z); float rho = length(p.xy); vec3 p1 = vec3(rho * cos(alpha1), rho * sin(alpha1), p.z); float alpha2 = mod(atan(p.y, -p.x), 2 * PI / z); vec3 p2 = vec3(rho * cos(alpha2), rho * sin(alpha2), p.z); return max(l_outside, min(l_root, max(involute_solid(p1), involute_solid(p2)))); } ]]) set_uniform_scalar(gear, 'r', base_radius) set_uniform_scalar(gear, 'r_outside',outer_radius) set_uniform_scalar(gear, 'r_root',root_radius) set_uniform_scalar(gear, 'z', number_of_teeth) --set_uniform_scalar(gear, 'delta_involute', ???) return gear end local params = {number_of_teeth=20,circular_pitch=300,flat=true} local b_solid = gear_solid(params) emit(b_solid,2) dofile("C:\\Users\\lfejoz\\AppData\\Roaming\\IceSL\\icesl-models\\libs\\gear.lua") local b = rotate(0,0, 180 / params.number_of_teeth) * gear(params) emit(b,3)
fix(gallery): Update and compare gear
fix(gallery): Update and compare gear Move it into its own function. Compare with gear provided by IceSL. Still on-going work.
Lua
mit
loic-fejoz/loic-fejoz-fabmoments,loic-fejoz/loic-fejoz-fabmoments,loic-fejoz/loic-fejoz-fabmoments
9c6a3bab1335c17b394a5509d61ae31cffd2bdac
modules/textadept/session.lua
modules/textadept/session.lua
-- Copyright 2007-2009 Mitchell mitchell<att>caladbolg.net. See LICENSE. local textadept = _G.textadept local locale = _G.locale --- -- Session support for the textadept module. module('_m.textadept.session', package.seeall) -- Markdown: -- ## Settings -- -- * `DEFAULT_SESSION`: The path to the default session file. -- settings DEFAULT_SESSION = _USERHOME..'/session' -- end settings --- -- Loads a Textadept session file. -- Textadept restores split views, opened buffers, cursor information, and -- project manager details. -- @param filename The absolute path to the session file to load. Defaults to -- DEFAULT_SESSION if not specified. -- @param only_pm Flag indicating whether or not to load only the Project -- Manager session settings. Defaults to false. -- @return true if the session file was opened and read; false otherwise. -- @usage _m.textadept.session.load(filename) function load(filename, only_pm) local f = io.open(filename or DEFAULT_SESSION, 'rb') if not only_pm and not f then if not textadept.io.close_all() then return false end end local current_view, splits = 1, { [0] = {} } for line in f:lines() do if not only_pm then if line:find('^buffer:') then local anchor, current_pos, first_visible_line, filename = line:match('^buffer: (%d+) (%d+) (%d+) (.+)$') if not filename:find('^%[.+%]$') then textadept.io.open(filename or '') else textadept.new_buffer() buffer._type = filename end -- Restore saved buffer selection and view. local anchor = tonumber(anchor) or 0 local current_pos = tonumber(current_pos) or 0 local first_visible_line = tonumber(first_visible_line) or 0 local buffer = buffer buffer._anchor, buffer._current_pos = anchor, current_pos buffer._first_visible_line = first_visible_line buffer:line_scroll(0, buffer:visible_from_doc_line(first_visible_line)) buffer:set_sel(anchor, current_pos) elseif line:find('^%s*split%d:') then local level, num, type, size = line:match('^(%s*)split(%d): (%S+) (%d+)') local view = splits[#level] and splits[#level][tonumber(num)] or view splits[#level + 1] = { view:split(type == 'true') } splits[#level + 1][1].size = tonumber(size) -- could be 1 or 2 elseif line:find('^%s*view%d:') then local level, num, buf_idx = line:match('^(%s*)view(%d): (%d+)$') local view = splits[#level][tonumber(num)] or view buf_idx = tonumber(buf_idx) if buf_idx > #textadept.buffers then buf_idx = #textadept.buffers end view:goto_buffer(buf_idx) elseif line:find('^current_view:') then local view_idx = line:match('^current_view: (%d+)') current_view = tonumber(view_idx) or 1 end end if line:find('^size:') then local width, height = line:match('^size: (%d+) (%d+)$') if width and height then textadept.size = { width, height } end elseif line:find('^pm:') then local width, cursor, text = line:match('^pm: (%d+) ([%d:]+) (.*)$') textadept.pm.width = width or 0 textadept.pm.entry_text = text or '' textadept.pm.activate() if cursor then textadept.pm.cursor = cursor end end end f:close() textadept.views[current_view]:focus() textadept.session_file = filename or DEFAULT_SESSION return true end --- -- Saves a Textadept session to a file. -- Saves split views, opened buffers, cursor information, and project manager -- details. -- @param filename The absolute path to the session file to save. Defaults to -- either the current session file or DEFAULT_SESSION if not specified. -- @usage _m.textadept.session.save(filename) function save(filename) local session = {} local buffer_line = "buffer: %d %d %d %s" -- anchor, cursor, line, filename local split_line = "%ssplit%d: %s %d" -- level, number, type, size local view_line = "%sview%d: %d" -- level, number, doc index -- Write out opened buffers. for _, buffer in ipairs(textadept.buffers) do local filename = buffer.filename or buffer._type if filename then local current = buffer.doc_pointer == textadept.focused_doc_pointer local anchor = current and 'anchor' or '_anchor' local current_pos = current and 'current_pos' or '_current_pos' local first_visible_line = current and 'first_visible_line' or '_first_visible_line' session[#session + 1] = buffer_line:format(buffer[anchor] or 0, buffer[current_pos] or 0, buffer[first_visible_line] or 0, filename) end end -- Write out split views. local function write_split(split, level, number) local c1, c2 = split[1], split[2] local vertical, size = tostring(split.vertical), split.size local spaces = (' '):rep(level) session[#session + 1] = split_line:format(spaces, number, vertical, size) spaces = (' '):rep(level + 1) if type(c1) == 'table' then write_split(c1, level + 1, 1) else session[#session + 1] = view_line:format(spaces, 1, c1) end if type(c2) == 'table' then write_split(c2, level + 1, 2) else session[#session + 1] = view_line:format(spaces, 2, c2) end end local splits = textadept.get_split_table() if type(splits) == 'table' then write_split(splits, 0, 0) else session[#session + 1] = view_line:format('', 1, splits) end -- Write out the current focused view. local current_view = view for index, view in ipairs(textadept.views) do if view == current_view then current_view = index break end end session[#session + 1] = ("current_view: %d"):format(current_view) -- Write out other things. local size = textadept.size session[#session + 1] = ("size: %d %d"):format(size[1], size[2]) local pm = textadept.pm session[#session + 1] = ("pm: %d %s %s"):format(pm.width, pm.cursor or '0', pm.entry_text) -- Write the session. local f = io.open(filename or textadept.session_file or DEFAULT_SESSION, 'wb') if f then f:write(table.concat(session, '\n')) f:close() end end textadept.events.add_handler('quit', save, 1)
-- Copyright 2007-2009 Mitchell mitchell<att>caladbolg.net. See LICENSE. local textadept = _G.textadept local locale = _G.locale --- -- Session support for the textadept module. module('_m.textadept.session', package.seeall) -- Markdown: -- ## Settings -- -- * `DEFAULT_SESSION`: The path to the default session file. -- settings DEFAULT_SESSION = _USERHOME..'/session' -- end settings --- -- Loads a Textadept session file. -- Textadept restores split views, opened buffers, cursor information, and -- project manager details. -- @param filename The absolute path to the session file to load. Defaults to -- DEFAULT_SESSION if not specified. -- @param only_pm Flag indicating whether or not to load only the Project -- Manager session settings. Defaults to false. -- @return true if the session file was opened and read; false otherwise. -- @usage _m.textadept.session.load(filename) function load(filename, only_pm) local f = io.open(filename or DEFAULT_SESSION, 'rb') if not only_pm and not f then if not textadept.io.close_all() then return false end end if not f then return false end local current_view, splits = 1, { [0] = {} } for line in f:lines() do if not only_pm then if line:find('^buffer:') then local anchor, current_pos, first_visible_line, filename = line:match('^buffer: (%d+) (%d+) (%d+) (.+)$') if not filename:find('^%[.+%]$') then textadept.io.open(filename or '') else textadept.new_buffer() buffer._type = filename end -- Restore saved buffer selection and view. local anchor = tonumber(anchor) or 0 local current_pos = tonumber(current_pos) or 0 local first_visible_line = tonumber(first_visible_line) or 0 local buffer = buffer buffer._anchor, buffer._current_pos = anchor, current_pos buffer._first_visible_line = first_visible_line buffer:line_scroll(0, buffer:visible_from_doc_line(first_visible_line)) buffer:set_sel(anchor, current_pos) elseif line:find('^%s*split%d:') then local level, num, type, size = line:match('^(%s*)split(%d): (%S+) (%d+)') local view = splits[#level] and splits[#level][tonumber(num)] or view splits[#level + 1] = { view:split(type == 'true') } splits[#level + 1][1].size = tonumber(size) -- could be 1 or 2 elseif line:find('^%s*view%d:') then local level, num, buf_idx = line:match('^(%s*)view(%d): (%d+)$') local view = splits[#level][tonumber(num)] or view buf_idx = tonumber(buf_idx) if buf_idx > #textadept.buffers then buf_idx = #textadept.buffers end view:goto_buffer(buf_idx) elseif line:find('^current_view:') then local view_idx = line:match('^current_view: (%d+)') current_view = tonumber(view_idx) or 1 end end if line:find('^size:') then local width, height = line:match('^size: (%d+) (%d+)$') if width and height then textadept.size = { width, height } end elseif line:find('^pm:') then local width, cursor, text = line:match('^pm: (%d+) ([%d:]+) (.*)$') textadept.pm.width = width or 0 textadept.pm.entry_text = text or '' textadept.pm.activate() if cursor then textadept.pm.cursor = cursor end end end f:close() textadept.views[current_view]:focus() textadept.session_file = filename or DEFAULT_SESSION return true end --- -- Saves a Textadept session to a file. -- Saves split views, opened buffers, cursor information, and project manager -- details. -- @param filename The absolute path to the session file to save. Defaults to -- either the current session file or DEFAULT_SESSION if not specified. -- @usage _m.textadept.session.save(filename) function save(filename) local session = {} local buffer_line = "buffer: %d %d %d %s" -- anchor, cursor, line, filename local split_line = "%ssplit%d: %s %d" -- level, number, type, size local view_line = "%sview%d: %d" -- level, number, doc index -- Write out opened buffers. for _, buffer in ipairs(textadept.buffers) do local filename = buffer.filename or buffer._type if filename then local current = buffer.doc_pointer == textadept.focused_doc_pointer local anchor = current and 'anchor' or '_anchor' local current_pos = current and 'current_pos' or '_current_pos' local first_visible_line = current and 'first_visible_line' or '_first_visible_line' session[#session + 1] = buffer_line:format(buffer[anchor] or 0, buffer[current_pos] or 0, buffer[first_visible_line] or 0, filename) end end -- Write out split views. local function write_split(split, level, number) local c1, c2 = split[1], split[2] local vertical, size = tostring(split.vertical), split.size local spaces = (' '):rep(level) session[#session + 1] = split_line:format(spaces, number, vertical, size) spaces = (' '):rep(level + 1) if type(c1) == 'table' then write_split(c1, level + 1, 1) else session[#session + 1] = view_line:format(spaces, 1, c1) end if type(c2) == 'table' then write_split(c2, level + 1, 2) else session[#session + 1] = view_line:format(spaces, 2, c2) end end local splits = textadept.get_split_table() if type(splits) == 'table' then write_split(splits, 0, 0) else session[#session + 1] = view_line:format('', 1, splits) end -- Write out the current focused view. local current_view = view for index, view in ipairs(textadept.views) do if view == current_view then current_view = index break end end session[#session + 1] = ("current_view: %d"):format(current_view) -- Write out other things. local size = textadept.size session[#session + 1] = ("size: %d %d"):format(size[1], size[2]) local pm = textadept.pm session[#session + 1] = ("pm: %d %s %s"):format(pm.width, pm.cursor or '0', pm.entry_text) -- Write the session. local f = io.open(filename or textadept.session_file or DEFAULT_SESSION, 'wb') if f then f:write(table.concat(session, '\n')) f:close() end end textadept.events.add_handler('quit', save, 1)
Fix error message for session file not found; modules/textadept/session.lua
Fix error message for session file not found; modules/textadept/session.lua
Lua
mit
rgieseke/textadept,rgieseke/textadept
dfd19bbe0a990232288fa3426a350e79dab48a89
.build.lua
.build.lua
project "CoreLib" files "core/src/**.cpp" kind "StaticLib" zpm.export(function() includedirs "core/include/" flags "C++14" pic "On" defines { "PROGRAM_NAME="..zpm.setting( "PROGRAM_NAME" ), "PROGRAM_COMPANY="..zpm.setting( "PROGRAM_COMPANY" ), "PROGRAM_COPYRIGHT="..zpm.setting( "PROGRAM_COPYRIGHT" ) } filter "system:not macosx" linkgroups "On" filter "system:linux" links { "pthread", "dl" } filter {} end) zpm.uses { "Zefiros-Software/DocoptCpp", "Zefiros-Software/SerLib", "Zefiros-Software/MathLib", "Zefiros-Software/Boost", "Zefiros-Software/Fmt", "Zefiros-Software/libsimdpp" }
project "CoreLib" files "core/src/**.cpp" kind "StaticLib" zpm.export(function() includedirs "core/include/" flags "C++14" pic "On" defines { "PROGRAM_NAME=\""..zpm.setting( "PROGRAM_NAME" ) .. "\"", "PROGRAM_COMPANY=\""..zpm.setting( "PROGRAM_COMPANY" ) .. "\"", "PROGRAM_COPYRIGHT=\""..zpm.setting( "PROGRAM_COPYRIGHT" ) .. "\"" } filter "system:not macosx" linkgroups "On" filter "system:linux" links { "pthread", "dl" } filter {} end) zpm.uses { "Zefiros-Software/DocoptCpp", "Zefiros-Software/SerLib", "Zefiros-Software/MathLib", "Zefiros-Software/Boost", "Zefiros-Software/Fmt", "Zefiros-Software/libsimdpp" }
Syntax fix
Syntax fix
Lua
mit
Zefiros-Software/CoreLib,Zefiros-Software/CoreLib
0b1157d2aefed208643efda66dadb93ccff93899
docker/test_auth.lua
docker/test_auth.lua
local M = {} local auth_cookie_name = "kbase_session" local json = require("json") local locklib = require("resty.lock") local httplib = require("resty.http") local httpclient = httplib:new() local token_cache = nil -- tokens live for up to 5 minutes local max_token_lifespan = 5 * 60 -- local auth_url = 'http://127.0.0.1:65001/users/' local auth_url = 'https://kbase.us/services/authorization/Sessions/Login' local initialize local get_user_from_cache local validate_and_cache_token local get_user local parse_cookie local url_decode local test_auth local initialized = nil M.lock_name = "lock_map" initialize = function(self, conf) if conf then for k, v in pairs(conf) do ngx.log(ngx.INFO, string.format("Auth.init conf(%s) = %s", k, tostring(v))) end else conf = {} end if not initialized then initialized = os.time() M.max_token_lifespan = conf.max_token_lifespan or max_token_lifespan token_cache = conf.token_cache or ngx.shared.token_cache ngx.log(ngx.INFO, string.format("Initializing Auth module: token lifespan = %d seconds", M.max_token_lifespan)) else ngx.log(ngx.INFO, string.format("Auth module already initialized at %d, skipping", initialized)) end end -- If the given token is stored in the cache, and hasn't expired, this -- returns that user id. -- If it has expired, or the token doesn't exist, returns nil get_user_from_cache = function(self, token) if token then -- TODO: hash that token return token_cache:get(token) else return nil end end -- Validates the token by looking it up in the Auth service. -- If valid, adds it to the token cache and returns the user id. -- If not, returns nil -- This uses the resty.lock to lock up that particular key while -- trying to validate. validate_and_cache_token = function(self, token) local token_lock = locklib:new(M.lock_name) elapsed, err = token_lock:lock(token) local user_id = nil d = {token=token, fields='user_id'} local user_request = { url = auth_url, method = "POST", body = d } ngx.log(ngx.ERR, "Sending validation request: "..json.encode(user_request)) local ok, code, headers, status, body = httpclient:request(user_request) if code >= 200 and code < 300 then local profile = json.decode(body) ngx.log(ngx.ERR, "Something? "..body) if profile.user_id then user_id = profile.user_id token_cache:set(token_cache, token, user_id, M.max_token_lifespan) else --error - missing user id from token lookup ngx.log(ngx.ERR, "Error: auth token lookup doesn't return a user id") end else ngx.log(ngx.ERR, "Error during token validation: "..status.." "..body) end token_lock:unlock() return user_id end get_user = function(self, token) if token then ngx.log(ngx.ERR, "Looking up a token") user = get_user_from_cache(token) if user then ngx.log(ngx.ERR, "Found user! "..user) return user else ngx.log(ngx.ERR, "Didn't find user, validating token...") user = validate_and_cache_token(token) return user end end end parse_cookie = function(cookie) local token_dict = {} local cookie = string.gsub(cookie, ";$", "") cookie = url_decode(cookie) for k, v in string.gmatch(cookie, "([%w_]+)=([^|]+);?") do token_dict[k] = v end if token_dict['token'] then token_dict['token'] = string.gsub(token_dict['token'], "PIPESIGN", "|") token_dict['token'] = string.gsub(token_dict['token'], "EQUALSSIGN", "=") -- ngx.log( ngx.DEBUG, string.format("token[token] = %s",token['token'])) return token_dict['token'] end return nil end -- -- simple URL decode function url_decode = function(str) str = string.gsub (str, "+", " ") str = string.gsub (str, "%%(%x%x)", function(h) return string.char(tonumber(h,16)) end) str = string.gsub (str, "\r\n", "\n") return str end test_auth = function(self) local headers = ngx.req.get_headers() local cheader = ngx.unescape_uri(headers['Cookie']) local token_dict = {} local token = nil if cheader then local session = string.match(cheader, auth_cookie_name.."=([%S]+);?") if session then token = parse_cookie(session) end end user = get_user(self, token) local table = { {"token: ", token}, {"user_id: ", user} } ngx.say(table) end M.initialize = initialize M.get_user = get_user M.test_auth = test_auth return M
local M = {} local auth_cookie_name = "kbase_session" local json = require("json") local locklib = require("resty.lock") local httplib = require("resty.http") local httpclient = httplib:new() local token_cache = nil -- tokens live for up to 5 minutes local max_token_lifespan = 5 * 60 local auth_url = 'http://127.0.0.1:65001' -- local auth_url = 'https://kbase.us/services/authorization/Sessions/Login' local initialize local get_user_from_cache local validate_and_cache_token local get_user local parse_cookie local url_decode local test_auth local initialized = nil M.lock_name = "lock_map" initialize = function(self, conf) if conf then for k, v in pairs(conf) do ngx.log(ngx.INFO, string.format("Auth.init conf(%s) = %s", k, tostring(v))) end else conf = {} end if not initialized then initialized = os.time() M.max_token_lifespan = conf.max_token_lifespan or max_token_lifespan token_cache = conf.token_cache or ngx.shared.token_cache ngx.log(ngx.INFO, string.format("Initializing Auth module: token lifespan = %d seconds", M.max_token_lifespan)) else ngx.log(ngx.INFO, string.format("Auth module already initialized at %d, skipping", initialized)) end end -- If the given token is stored in the cache, and hasn't expired, this -- returns that user id. -- If it has expired, or the token doesn't exist, returns nil get_user_from_cache = function(token) if token then -- TODO: hash that token return token_cache:get(token) else return nil end end -- Validates the token by looking it up in the Auth service. -- If valid, adds it to the token cache and returns the user id. -- If not, returns nil -- This uses the resty.lock to lock up that particular key while -- trying to validate. validate_and_cache_token = function(token) if not token then return nil end local token_lock = locklib:new(M.lock_name) elapsed, err = token_lock:lock(token) local user_id = nil d = {token=token, fields='user_id'} local user_request = { url = auth_url, method = "POST", body = d } ngx.log(ngx.ERR, "Sending validation request: "..json.encode(user_request)) local ok,code,headers,status,body = httpclient:request(user_request) if code >= 200 and code < 300 then local profile = json.decode(body) ngx.log(ngx.ERR, "Something? "..body) if profile.user_id then user_id = profile.user_id token_cache:set(token_cache, token, user_id, M.max_token_lifespan) else --error - missing user id from token lookup ngx.log(ngx.ERR, "Error: auth token lookup doesn't return a user id") end else ngx.log(ngx.ERR, "Error during token validation: "..status.." "..body) end token_lock:unlock() return user_id end get_user = function(self, token) if token then ngx.log(ngx.ERR, "Looking up a token") user = get_user_from_cache(token) if user then ngx.log(ngx.ERR, "Found user! "..user) return user else ngx.log(ngx.ERR, "Didn't find user, validating token...") user = validate_and_cache_token(token) return user end end end parse_cookie = function(cookie) local token_dict = {} local cookie = string.gsub(cookie, ";$", "") cookie = url_decode(cookie) for k, v in string.gmatch(cookie, "([%w_]+)=([^|]+);?") do token_dict[k] = v end if token_dict['token'] then token_dict['token'] = string.gsub(token_dict['token'], "PIPESIGN", "|") token_dict['token'] = string.gsub(token_dict['token'], "EQUALSSIGN", "=") -- ngx.log( ngx.DEBUG, string.format("token[token] = %s",token['token'])) return token_dict['token'] end return nil end -- -- simple URL decode function url_decode = function(str) str = string.gsub (str, "+", " ") str = string.gsub (str, "%%(%x%x)", function(h) return string.char(tonumber(h,16)) end) str = string.gsub (str, "\r\n", "\n") return str end test_auth = function(self) local headers = ngx.req.get_headers() local cheader = ngx.unescape_uri(headers['Cookie']) local token_dict = {} local token = nil if cheader then local session = string.match(cheader, auth_cookie_name.."=([%S]+);?") if session then token = parse_cookie(session) end end user = get_user(self, token) local table = { {"token: ", token}, {"user_id: ", user} } ngx.say(table) end M.initialize = initialize M.get_user = get_user M.test_auth = test_auth return M
Fix a few method signatures
Fix a few method signatures
Lua
mit
pranjan77/narrative,pranjan77/narrative,pranjan77/narrative,kbase/narrative,kbase/narrative,kbase/narrative,briehl/narrative,briehl/narrative,briehl/narrative,jmchandonia/narrative,pranjan77/narrative,briehl/narrative,kbase/narrative,pranjan77/narrative,jmchandonia/narrative,jmchandonia/narrative,kbase/narrative,jmchandonia/narrative,pranjan77/narrative,jmchandonia/narrative,kbase/narrative,briehl/narrative,jmchandonia/narrative,briehl/narrative,briehl/narrative,jmchandonia/narrative,pranjan77/narrative
55d1d90e3e65cec98ab26e8c7144675b02478241
api-gateway-config/scripts/lua/lib/filemgmt.lua
api-gateway-config/scripts/lua/lib/filemgmt.lua
-- Copyright (c) 2016 IBM. All rights reserved. -- -- 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. --- @module -- -- @author Alex Song (songs) local utils = require "lib/utils" local cjson = require "cjson" local request = require "lib/request" local _M = {} --- Create/overwrite Nginx Conf file for given resource -- @param baseConfDir the base directory for storing conf files for managed resources -- @param tenant the namespace for the resource -- @param gatewayPath the gateway path of the resource -- @param resourceObj object containing different operations/policies for the resource -- @return fileLocation location of created/updated conf file function _M.createResourceConf(baseConfDir, tenant, gatewayPath, resourceObj) resourceObj = utils.serializeTable(cjson.decode(resourceObj)) local decoded = cjson.decode(resourceObj) local prefix = utils.concatStrings({"\tinclude /etc/api-gateway/conf.d/commons/common-headers.conf;\n", "\tset $upstream https://172.17.0.1;\n", "\tset $tenant ", tenant, ";\n", "\tset $gatewayPath ", utils.concatStrings({"\"", ngx.unescape_uri(gatewayPath), "\""}), ";\n\n"}) if decoded.apiId ~= nil then prefix = utils.concatStrings({prefix, "\tset $apiId ", decoded.apiId, ";\n"}) end -- Set resource headers and mapping by calling routing.processCall() local outgoingResource = utils.concatStrings({"\taccess_by_lua_block {\n", "\t\tlocal routing = require \"routing\"\n", "\t\trouting.processCall(", resourceObj, ")\n", "\t}\n\n", "\tproxy_pass $upstream;\n"}) -- Add to endpoint conf file os.execute(utils.concatStrings({"mkdir -p ", baseConfDir, tenant})) local fileLocation = utils.concatStrings({baseConfDir, tenant, "/", gatewayPath, ".conf"}) local file, err = io.open(fileLocation, "w") if not file then request.err(500, utils.concatStrings({"Error adding to endpoint conf file: ", err})) end local updatedPath = ngx.unescape_uri(gatewayPath):gsub("%{(%w*)%}", utils.convertTemplatedPathParam) local location = utils.concatStrings({"location ~ ^/api/", tenant, "/", updatedPath, " {\n", prefix, outgoingResource, "}\n"}) file:write(location) file:close() -- reload nginx to refresh conf files os.execute("/usr/local/sbin/nginx -s reload") return fileLocation end --- Delete Ngx conf file for given resource -- @param baseConfDir the base directory for storing conf files for managed resources -- @param tenant the namespace for the resource -- @param gatewayPath the gateway path of the resource -- @return fileLocation location of deleted conf file function _M.deleteResourceConf(baseConfDir, tenant, gatewayPath) local fileLocation = utils.concatStrings({baseConfDir, tenant, "/", gatewayPath, ".conf"}) os.execute(utils.concatStrings({"rm -f ", fileLocation})) -- reload nginx to refresh conf files os.execute("/usr/local/sbin/nginx -s reload") return fileLocation end return _M
-- Copyright (c) 2016 IBM. All rights reserved. -- -- 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. --- @module -- -- @author Alex Song (songs) local utils = require "lib/utils" local cjson = require "cjson" local request = require "lib/request" local _M = {} --- Create/overwrite Nginx Conf file for given resource -- @param baseConfDir the base directory for storing conf files for managed resources -- @param tenant the namespace for the resource -- @param gatewayPath the gateway path of the resource -- @param resourceObj object containing different operations/policies for the resource -- @return fileLocation location of created/updated conf file function _M.createResourceConf(baseConfDir, tenant, gatewayPath, resourceObj) local decoded = cjson.decode(resourceObj) resourceObj = utils.serializeTable(decoded) local prefix = utils.concatStrings({"\tinclude /etc/api-gateway/conf.d/commons/common-headers.conf;\n", "\tset $upstream https://172.17.0.1;\n", "\tset $tenant ", tenant, ";\n", "\tset $gatewayPath ", utils.concatStrings({"\"", ngx.unescape_uri(gatewayPath), "\""}), ";\n\n"}) if decoded.apiId ~= nil then prefix = utils.concatStrings({prefix, "\tset $apiId ", decoded.apiId, ";\n"}) end -- Set resource headers and mapping by calling routing.processCall() local outgoingResource = utils.concatStrings({"\taccess_by_lua_block {\n", "\t\tlocal routing = require \"routing\"\n", "\t\trouting.processCall(", resourceObj, ")\n", "\t}\n\n", "\tproxy_pass $upstream;\n"}) -- Add to endpoint conf file os.execute(utils.concatStrings({"mkdir -p ", baseConfDir, tenant})) local fileLocation = utils.concatStrings({baseConfDir, tenant, "/", gatewayPath, ".conf"}) local file, err = io.open(fileLocation, "w") if not file then request.err(500, utils.concatStrings({"Error adding to endpoint conf file: ", err})) end local updatedPath = ngx.unescape_uri(gatewayPath):gsub("%{(%w*)%}", utils.convertTemplatedPathParam) local location = utils.concatStrings({"location ~ ^/api/", tenant, "/", updatedPath, " {\n", prefix, outgoingResource, "}\n"}) file:write(location) file:close() -- reload nginx to refresh conf files os.execute("/usr/local/sbin/nginx -s reload") return fileLocation end --- Delete Ngx conf file for given resource -- @param baseConfDir the base directory for storing conf files for managed resources -- @param tenant the namespace for the resource -- @param gatewayPath the gateway path of the resource -- @return fileLocation location of deleted conf file function _M.deleteResourceConf(baseConfDir, tenant, gatewayPath) local fileLocation = utils.concatStrings({baseConfDir, tenant, "/", gatewayPath, ".conf"}) os.execute(utils.concatStrings({"rm -f ", fileLocation})) -- reload nginx to refresh conf files os.execute("/usr/local/sbin/nginx -s reload") return fileLocation end return _M
Fix merge issue
Fix merge issue
Lua
apache-2.0
openwhisk/openwhisk-apigateway,alexsong93/openwhisk-apigateway,openwhisk/apigateway,taylorking/apigateway,openwhisk/apigateway,taylorking/apigateway,openwhisk/apigateway,alexsong93/openwhisk-apigateway,LukeFarrell/incubator-openwhisk-apigateway,alexsong93/openwhisk-apigateway,LukeFarrell/incubator-openwhisk-apigateway,LukeFarrell/incubator-openwhisk-apigateway,openwhisk/openwhisk-apigateway,taylorking/apigateway,openwhisk/openwhisk-apigateway
0b8267de1a1ff1301d9be51792b881d44cedece2
tests/cairo.lua
tests/cairo.lua
--[[-------------------------------------------------------------------------- LGI testsuite, cairo overrides test group. Copyright (c) 2012 Pavel Holejsovsky Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php --]]-------------------------------------------------------------------------- local io = require 'io' local os = require 'os' local lgi = require 'lgi' local check = testsuite.check local checkv = testsuite.checkv local cairo = testsuite.group.new('cairo') function cairo.matrix() local cairo = lgi.cairo local matrix = cairo.Matrix() checkv(matrix.xx, 0, 'number') checkv(matrix.yx, 0, 'number') checkv(matrix.xy, 0, 'number') checkv(matrix.yy, 0, 'number') checkv(matrix.x0, 0, 'number') checkv(matrix.y0, 0, 'number') matrix = cairo.Matrix { xx = 1, yx =1.5, xy = 2, yy = 2.5, x0 = 3, y0 = 3.5 } checkv(matrix.xx, 1, 'number') checkv(matrix.yx, 1.5, 'number') checkv(matrix.xy, 2, 'number') checkv(matrix.yy, 2.5, 'number') checkv(matrix.x0, 3, 'number') checkv(matrix.y0, 3.5, 'number') end function cairo.matrix_getset() local cairo = lgi.cairo local surface = cairo.ImageSurface('ARGB32', 100, 100) local cr = cairo.Context(surface) local m = cairo.Matrix { xx = 1, yx =1.5, xy = 2, yy = 2.5, x0 = 3, y0 = 3.5 } cr.matrix = m local m2 = cr.matrix check(m.xx == m2.xx) check(m.yx == m2.yx) check(m.xy == m2.xy) check(m.yy == m2.yy) check(m.x0 == m2.x0) check(m.y0 == m2.y0) end function cairo.dash() local cairo = lgi.cairo local surface = cairo.ImageSurface('ARGB32', 100, 100) local cr = cairo.Context(surface) local dash, offset = cr:get_dash() check(type(dash) == 'table') check(next(dash) == nil) cr:set_dash({ 1, 2, math.pi }, 2.22) dash, offset = cr:get_dash() check(#dash == 3) check(dash[1] == 1) check(dash[2] == 2) check(dash[3] == math.pi) check(offset == 2.22) cr:set_dash(nil, 0) dash, offset = cr:get_dash() check(type(dash) == 'table') check(next(dash) == nil) end function cairo.path() local cairo = lgi.cairo local surface = cairo.ImageSurface('ARGB32', 100, 100) local cr = cairo.Context(surface) cr:move_to(10, 11) cr:curve_to(1, 2, 3, 4, 5, 6) cr:close_path() cr:line_to(21, 22) local i = 1 for t, pts in cr:copy_path():pairs() do if i == 1 then checkv(t, 'MOVE_TO', 'string') check(type(pts) == 'table' and #pts == 1) checkv(pts[1].x, 10, 'number') checkv(pts[1].y, 11, 'number') elseif i == 2 then checkv(t, 'MOVE_TO', 'string') check(type(pts) == 'table' and #pts == 3) checkv(pts[1].x, 1, 'number') checkv(pts[1].y, 2, 'number') checkv(pts[2].x, 3, 'number') checkv(pts[2].y, 4, 'number') checkv(pts[3].x, 5, 'number') checkv(pts[3].y, 6, 'number') elseif i == 3 then checkv(t, 'MOVE_TO', 'string') check(type(pts) == 'table' and #pts == 0) elseif i == 4 then checkv(t, 'LINE_TO', 'string') check(type(pts) == 'table' and #pts == 1) checkv(pts[1].x, 21, 'number') checkv(pts[1].y, 22, 'number') else check(false) end i = i + 1 end check(i == 4) end function cairo.surface_type() local cairo = lgi.cairo local surface = cairo.ImageSurface('ARGB32', 100, 100) local cr = cairo.Context(surface) check(cairo.ImageSurface:is_type_of(surface)) check(cairo.Surface:is_type_of(surface)) check(not cairo.RecordingSurface:is_type_of(surface)) local s2 = cr.target check(cairo.ImageSurface:is_type_of(s2)) check(cairo.Surface:is_type_of(s2)) check(not cairo.RecordingSurface:is_type_of(s2)) end function cairo.context_transform() local cairo = lgi.cairo local surface = cairo.ImageSurface('ARGB32', 100, 100) local cr = cairo.Context(surface) function compare(a, b) check(math.abs(a-b) < 0.1) end cr:rotate(-math.pi / 2) cr:translate(100, 200) local x, y = cr:user_to_device(10, 20) compare(x, 220) compare(y, -110) local x, y = cr:device_to_user(220, -110) compare(x, 10) compare(y, 20) local x, y = cr:user_to_device_distance(10, 20) compare(x, 20) compare(y, -10) local x, y = cr:device_to_user_distance(20, -10) compare(x, 10) compare(y, 20) end
--[[-------------------------------------------------------------------------- LGI testsuite, cairo overrides test group. Copyright (c) 2012 Pavel Holejsovsky Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php --]]-------------------------------------------------------------------------- local io = require 'io' local os = require 'os' local lgi = require 'lgi' local check = testsuite.check local checkv = testsuite.checkv local cairo = testsuite.group.new('cairo') function cairo.matrix() local cairo = lgi.cairo local matrix = cairo.Matrix() checkv(matrix.xx, 0, 'number') checkv(matrix.yx, 0, 'number') checkv(matrix.xy, 0, 'number') checkv(matrix.yy, 0, 'number') checkv(matrix.x0, 0, 'number') checkv(matrix.y0, 0, 'number') matrix = cairo.Matrix { xx = 1, yx =1.5, xy = 2, yy = 2.5, x0 = 3, y0 = 3.5 } checkv(matrix.xx, 1, 'number') checkv(matrix.yx, 1.5, 'number') checkv(matrix.xy, 2, 'number') checkv(matrix.yy, 2.5, 'number') checkv(matrix.x0, 3, 'number') checkv(matrix.y0, 3.5, 'number') end function cairo.matrix_getset() local cairo = lgi.cairo local surface = cairo.ImageSurface('ARGB32', 100, 100) local cr = cairo.Context(surface) local m = cairo.Matrix { xx = 1, yx =1.5, xy = 2, yy = 2.5, x0 = 3, y0 = 3.5 } cr.matrix = m local m2 = cr.matrix check(m.xx == m2.xx) check(m.yx == m2.yx) check(m.xy == m2.xy) check(m.yy == m2.yy) check(m.x0 == m2.x0) check(m.y0 == m2.y0) end function cairo.dash() local cairo = lgi.cairo local surface = cairo.ImageSurface('ARGB32', 100, 100) local cr = cairo.Context(surface) local dash, offset = cr:get_dash() check(type(dash) == 'table') check(next(dash) == nil) cr:set_dash({ 1, 2, math.pi }, 2.22) dash, offset = cr:get_dash() check(#dash == 3) check(dash[1] == 1) check(dash[2] == 2) check(dash[3] == math.pi) check(offset == 2.22) cr:set_dash(nil, 0) dash, offset = cr:get_dash() check(type(dash) == 'table') check(next(dash) == nil) end function cairo.path() local cairo = lgi.cairo local surface = cairo.ImageSurface('ARGB32', 100, 100) local cr = cairo.Context(surface) cr:move_to(10, 11) cr:curve_to(1, 2, 3, 4, 5, 6) cr:close_path() cr:line_to(21, 22) local i = 1 for t, pts in cr:copy_path():pairs() do if i == 1 then checkv(t, 'MOVE_TO', 'string') check(type(pts) == 'table' and #pts == 1) checkv(pts[1].x, 10, 'number') checkv(pts[1].y, 11, 'number') elseif i == 2 then checkv(t, 'CURVE_TO', 'string') check(type(pts) == 'table' and #pts == 3) checkv(pts[1].x, 1, 'number') checkv(pts[1].y, 2, 'number') checkv(pts[2].x, 3, 'number') checkv(pts[2].y, 4, 'number') checkv(pts[3].x, 5, 'number') checkv(pts[3].y, 6, 'number') elseif i == 3 then checkv(t, 'CLOSE_PATH', 'string') check(type(pts) == 'table' and #pts == 0) elseif i == 4 then checkv(t, 'MOVE_TO', 'string') check(type(pts) == 'table' and #pts == 1) checkv(pts[1].x, 10, 'number') checkv(pts[1].y, 11, 'number') elseif i == 5 then checkv(t, 'LINE_TO', 'string') check(type(pts) == 'table' and #pts == 1) checkv(pts[1].x, 21, 'number') checkv(pts[1].y, 22, 'number') else check(false) end i = i + 1 end check(i == 6) end function cairo.surface_type() local cairo = lgi.cairo local surface = cairo.ImageSurface('ARGB32', 100, 100) local cr = cairo.Context(surface) check(cairo.ImageSurface:is_type_of(surface)) check(cairo.Surface:is_type_of(surface)) check(not cairo.RecordingSurface:is_type_of(surface)) local s2 = cr.target check(cairo.ImageSurface:is_type_of(s2)) check(cairo.Surface:is_type_of(s2)) check(not cairo.RecordingSurface:is_type_of(s2)) end function cairo.context_transform() local cairo = lgi.cairo local surface = cairo.ImageSurface('ARGB32', 100, 100) local cr = cairo.Context(surface) function compare(a, b) check(math.abs(a-b) < 0.1) end cr:rotate(-math.pi / 2) cr:translate(100, 200) local x, y = cr:user_to_device(10, 20) compare(x, 220) compare(y, -110) local x, y = cr:device_to_user(220, -110) compare(x, 10) compare(y, 20) local x, y = cr:user_to_device_distance(10, 20) compare(x, 20) compare(y, -10) local x, y = cr:device_to_user_distance(20, -10) compare(x, 10) compare(y, 20) end
Fix hopelessly broken cairo path enumeration test
Fix hopelessly broken cairo path enumeration test One of the bugs in the test unfortunately hid others, after finding and fixing initial bug (by Uli), the rest appeared and were fixed by this commit.
Lua
mit
zevv/lgi,pavouk/lgi,psychon/lgi
ed2f1a8ca0a2c463569844807732f05cfefd5463
deployment_scripts/puppet/modules/lma_collector/files/plugins/filters/logs_counter.lua
deployment_scripts/puppet/modules/lma_collector/files/plugins/filters/logs_counter.lua
-- Copyright 2016 Mirantis, Inc. -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. require 'string' local utils = require 'lma_utils' local hostname = read_config('hostname') or error('hostname must be specified') local interval = (read_config('interval') or error('interval must be specified!')) + 0 local discovered_services = {} local logs_counters = {} local current_service = 1 local enter_at local interval_in_ns = interval * 1e9 local msg = { Type = "metric", Timestamp = nil, Severity = 6, } function process_message () local severity = read_message("Fields[severity_label]") local logger = read_message("Logger") local service = string.match(logger, "^openstack%.(%a+)$") if service == nil then return -1, "Cannot match any services from " .. logger end if not logs_counters[service] then -- a new service has been discovered discovered_services[#discovered_services + 1] = service logs_counters[service] = {} logs_counters[service]['last_timer_event'] = 0 for _, label in pairs(utils.severity_to_label_map) do logs_counters[service][label] = 0 end end logs_counters[service][severity] = logs_counters[service][severity] + 1 return 0 end function timer_event(ns) -- We can only send a maximum of ten events per call. -- So we send all metrics about one service and we will proceed with -- the following services at the next ticker event. if #discovered_services == 0 then return 0 end -- Initialize enter_at during the first call to timer_event if not enter_at then enter_at = ns end -- To be able to send a metric we need to check if we are within the -- interval specified in the configuration and if we haven't already sent -- all metrics. if ns - enter_at < interval_in_ns and current_service <= #discovered_services then local service_name = discovered_services[current_service] local last_timer_event = logs_counters[service_name]['last_timer_event'] local delta_sec = (ns - last_timer_event) / 1e9 for level, val in pairs(logs_counters[service_name]) do -- We don't send the first value if last_timer_event ~= 0 and delta_sec ~= 0 then msg.Timestamp = ns msg.Fields = { name = 'log_messages', type = utils.metric_type['DERIVE'], value = val / delta_sec, service = service_name, level = string.lower(level), hostname = hostname, tag_fields = {'service', 'level'}, } utils.inject_tags(msg) ok, err = utils.safe_inject_message(msg) if ok ~= 0 then return -1, err end end -- reset the counter logs_counters[service_name][level] = 0 end logs_counters[service_name]['last_timer_event'] = ns current_service = current_service + 1 end if ns - enter_at >= interval_in_ns then enter_at = ns current_service = 1 end return 0 end
-- Copyright 2016 Mirantis, Inc. -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. require 'string' local utils = require 'lma_utils' local hostname = read_config('hostname') or error('hostname must be specified') local interval = (read_config('interval') or error('interval must be specified!')) + 0 local discovered_services = {} local logs_counters = {} local last_timer_events = {} local current_service = 1 local enter_at local interval_in_ns = interval * 1e9 local msg = { Type = "metric", Timestamp = nil, Severity = 6, } function process_message () local severity = read_message("Fields[severity_label]") local logger = read_message("Logger") local service = string.match(logger, "^openstack%.(%a+)$") if service == nil then return -1, "Cannot match any services from " .. logger end if not logs_counters[service] then -- a new service has been discovered discovered_services[#discovered_services + 1] = service logs_counters[service] = {} last_timer_events[service] = 0 for _, label in pairs(utils.severity_to_label_map) do logs_counters[service][label] = 0 end end logs_counters[service][severity] = logs_counters[service][severity] + 1 return 0 end function timer_event(ns) -- We can only send a maximum of ten events per call. -- So we send all metrics about one service and we will proceed with -- the following services at the next ticker event. if #discovered_services == 0 then return 0 end -- Initialize enter_at during the first call to timer_event if not enter_at then enter_at = ns end -- To be able to send a metric we need to check if we are within the -- interval specified in the configuration and if we haven't already sent -- all metrics. if ns - enter_at < interval_in_ns and current_service <= #discovered_services then local service_name = discovered_services[current_service] local last_timer_event = last_timer_events[service_name] local delta_sec = (ns - last_timer_event) / 1e9 for level, val in pairs(logs_counters[service_name]) do -- We don't send the first value if last_timer_event ~= 0 and delta_sec ~= 0 then msg.Timestamp = ns msg.Fields = { name = 'log_messages', type = utils.metric_type['DERIVE'], value = val / delta_sec, service = service_name, level = string.lower(level), hostname = hostname, tag_fields = {'service', 'level'}, } utils.inject_tags(msg) ok, err = utils.safe_inject_message(msg) if ok ~= 0 then return -1, err end end -- reset the counter logs_counters[service_name][level] = 0 end last_timer_events[service_name] = ns current_service = current_service + 1 end if ns - enter_at >= interval_in_ns then enter_at = ns current_service = 1 end return 0 end
Fix the log counter filter
Fix the log counter filter This change makes sure that the filter doesn't send a metric with the 'last_timer_event' tag. Change-Id: Iad3f03dfbc151710d5704aa803e3fb379b7f04bf
Lua
apache-2.0
stackforge/fuel-plugin-lma-collector,stackforge/fuel-plugin-lma-collector,stackforge/fuel-plugin-lma-collector,stackforge/fuel-plugin-lma-collector,stackforge/fuel-plugin-lma-collector
e1739b84f64156a2101419e8d92c82fdacdf566e
Roster.lua
Roster.lua
------------------------------------------------------------------------------- -- Roster handling code ------------------------------------------------------------------------------- function EPGP:GetRoster() if (not self.roster) then self.roster = { } end return self.roster end function EPGP:GetAlts() if (not self.alts) then self.alts = { } end return self.alts end function EPGP:SetRoster(r) assert(r and type(r) == "table", "Roster is not a table!") self.roster = r end -- Reads roster from server function EPGP:PullRoster() -- Figure out alts local alts = GetGuildInfoText() or "" local alts_table = self:GetAlts() for from, to in string.gfind(alts, "(%a+):(%a+)\n") do self:Debug("Adding %s as an alt for %s", to, from) alts_table[to] = from end -- Update roster for i = 1, GetNumGuildMembers(true) do local name, _, _, _, class, _, note, officernote, _, _ = GetGuildRosterInfo(i) local roster = self:GetRoster() if (name) then roster[name] = { class, self:PointString2Table(note), self:PointString2Table(officernote) } end end end -- Writes roster to server function EPGP:PushRoster() for i = 1, GetNumGuildMembers(true) do local name, _, _, _, _, _, _, _, _, _ = GetGuildRosterInfo(i) local roster = self:GetRoster() if (name and roster[name]) then local _, ep, gp = unpack(roster[name]) local note = self:PointTable2String(ep) local officernote = self:PointTable2String(gp) GuildRosterSetPublicNote(i, note) GuildRosterSetOfficerNote(i, officernote) end end -- Cause the roster to be pulled from server GuildRoster() end ------------------------------------------------------------------------------- -- EP/GP manipulation -- -- We use public/officers notes to keep track of EP/GP. Each note has storage -- for a string of max length of 31. So with two bytes for each score, we can -- have up to 15 numbers in it, which gives a max raid window of 15. -- -- NOTE: Each number is in hex which means that we can have max 256 GP/EP for -- each raid. This needs to be improved to raise the limit. -- -- EPs are stored in the public note. The first byte is the EPs gathered for -- the current raid. The second is the EPs gathered in the previous raid (of -- the guild not the membeer). Ditto for the rest. -- -- GPs are stored in the officers note, in a similar manner as the EPs. -- -- Bonus EPs are added to the last/current raid. function EPGP:PointString2Table(s) if (string.len(s) == 0) then local EMPTY_POINTS = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } return EMPTY_POINTS end local t = { } for i = 1, string.len(s), 2 do local val = self:Decode(string.sub(s, i, i+1)) table.insert(t, val) end return t end function EPGP:PointTable2String(t) local s = "" for k, v in pairs(t) do local ss = string.format("%02s", self:Encode(v)) assert(string.len(ss) == 2) s = s .. ss end return s end function EPGP:GetEPGP(name) assert(name and type(name) == "string") local roster = self:GetRoster() assert(roster[name], "Cannot find member record to update!") local _, ep, gp = unpack(roster[name]) assert(ep and gp, "Member record corrupted!") return ep, gp end function EPGP:SetEPGP(name, ep, gp) assert(name and type(name) == "string") assert(ep and type(ep) == "table") assert(gp and type(gp) == "table") local roster = self:GetRoster() assert(roster[name], "Cannot find member record to update!") local class, _, _ = unpack(roster[name]) roster[name] = { class, ep, gp } end -- Sets all EP/GP to 0 function EPGP:ResetEPGP() for i = 1, GetNumGuildMembers(true) do GuildRosterSetPublicNote(i, "") GuildRosterSetOfficerNote(i, "") end GuildRoster() self:Report("All EP/GP are reset.") end function EPGP:NewRaid() local roster = self:GetRoster() for n, t in pairs(roster) do local name, _, ep, gp = n, unpack(t) table.remove(ep) table.insert(ep, 1, 0) table.remove(gp) table.insert(gp, 1, 0) self:SetEPGP(name, ep, gp) end self:PushRoster() self:Report("Created new raid.") end function EPGP:ResolveMember(member) local alts = self:GetAlts() while (alts[member]) do member = alts[member] end return member end function EPGP:AddEP2Member(member, points) member = self:ResolveMember(member) local ep, gp = self:GetEPGP(member) ep[1] = ep[1] + tonumber(points) self:SetEPGP(member, ep, gp) self:PushRoster() self:Report("Added " .. tostring(points) .. " EPs to " .. member .. ".") end function EPGP:AddEP2Raid(points) local raid = { } for i = 1, GetNumRaidMembers() do local name, _, _, _, _, _, zone, _, _ = GetRaidRosterInfo(i) if (zone == self.current_zone) then self:AddEP2Member(name, points) end end self:PushRoster() end function EPGP:AddGP2Member(member, points) member = self:ResolveMember(member) local ep, gp = self:GetEPGP(member) gp[1] = gp[1] + tonumber(points) self:SetEPGP(member, ep, gp) self:PushRoster() self:Report("Added " .. tostring(points) .. " GPs to " .. member .. ".") end
------------------------------------------------------------------------------- -- Roster handling code ------------------------------------------------------------------------------- function EPGP:GetRoster() if (not self.roster) then self.roster = { } end return self.roster end function EPGP:GetAlts() if (not self.alts) then self.alts = { } end return self.alts end function EPGP:SetRoster(r) assert(r and type(r) == "table", "Roster is not a table!") self.roster = r end -- Reads roster from server function EPGP:PullRoster() -- Figure out alts local alts = GetGuildInfoText() or "" local alts_table = self:GetAlts() for from, to in string.gfind(alts, "(%a+):(%a+)\n") do self:Debug("Adding %s as an alt for %s", to, from) alts_table[to] = from end -- Update roster for i = 1, GetNumGuildMembers(true) do local name, _, _, _, class, _, note, officernote, _, _ = GetGuildRosterInfo(i) local roster = self:GetRoster() if (name) then roster[name] = { class, self:PointString2Table(note), self:PointString2Table(officernote) } end end end -- Writes roster to server function EPGP:PushRoster() for i = 1, GetNumGuildMembers(true) do local name, _, _, _, _, _, _, _, _, _ = GetGuildRosterInfo(i) local roster = self:GetRoster() if (name and roster[name]) then local _, ep, gp = unpack(roster[name]) local note = self:PointTable2String(ep) local officernote = self:PointTable2String(gp) GuildRosterSetPublicNote(i, note) GuildRosterSetOfficerNote(i, officernote) end end end ------------------------------------------------------------------------------- -- EP/GP manipulation -- -- We use public/officers notes to keep track of EP/GP. Each note has storage -- for a string of max length of 31. So with two bytes for each score, we can -- have up to 15 numbers in it, which gives a max raid window of 15. -- -- NOTE: Each number is in hex which means that we can have max 256 GP/EP for -- each raid. This needs to be improved to raise the limit. -- -- EPs are stored in the public note. The first byte is the EPs gathered for -- the current raid. The second is the EPs gathered in the previous raid (of -- the guild not the membeer). Ditto for the rest. -- -- GPs are stored in the officers note, in a similar manner as the EPs. -- -- Bonus EPs are added to the last/current raid. function EPGP:PointString2Table(s) if (string.len(s) == 0) then local EMPTY_POINTS = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } return EMPTY_POINTS end local t = { } for i = 1, string.len(s), 2 do local val = self:Decode(string.sub(s, i, i+1)) table.insert(t, val) end return t end function EPGP:PointTable2String(t) local s = "" for k, v in pairs(t) do local ss = string.format("%02s", self:Encode(v)) assert(string.len(ss) == 2) s = s .. ss end return s end function EPGP:GetEPGP(name) assert(name and type(name) == "string") local roster = self:GetRoster() assert(roster[name], "Cannot find member record to update!") local _, ep, gp = unpack(roster[name]) assert(ep and gp, "Member record corrupted!") return ep, gp end function EPGP:SetEPGP(name, ep, gp) assert(name and type(name) == "string") assert(ep and type(ep) == "table") assert(gp and type(gp) == "table") local roster = self:GetRoster() assert(roster[name], "Cannot find member record to update!") local class, _, _ = unpack(roster[name]) roster[name] = { class, ep, gp } end -- Sets all EP/GP to 0 function EPGP:ResetEPGP() for i = 1, GetNumGuildMembers(true) do GuildRosterSetPublicNote(i, "") GuildRosterSetOfficerNote(i, "") end GuildRoster() self:Report("All EP/GP are reset.") end function EPGP:NewRaid() local roster = self:GetRoster() for n, t in pairs(roster) do local name, _, ep, gp = n, unpack(t) table.remove(ep) table.insert(ep, 1, 0) table.remove(gp) table.insert(gp, 1, 0) self:SetEPGP(name, ep, gp) end self:PushRoster() self:Report("Created new raid.") end function EPGP:ResolveMember(member) local alts = self:GetAlts() while (alts[member]) do member = alts[member] end return member end function EPGP:AddEP2Member(member, points) member = self:ResolveMember(member) local ep, gp = self:GetEPGP(member) ep[1] = ep[1] + tonumber(points) self:SetEPGP(member, ep, gp) self:PushRoster() self:Report("Added " .. tostring(points) .. " EPs to " .. member .. ".") end function EPGP:AddEP2Raid(points) local raid = { } for i = 1, GetNumRaidMembers() do local name, _, _, _, _, _, zone, _, _ = GetRaidRosterInfo(i) if (zone == self.current_zone) then self:AddEP2Member(name, points) end end self:PushRoster() end function EPGP:AddGP2Member(member, points) member = self:ResolveMember(member) local ep, gp = self:GetEPGP(member) gp[1] = gp[1] + tonumber(points) self:SetEPGP(member, ep, gp) self:PushRoster() self:Report("Added " .. tostring(points) .. " GPs to " .. member .. ".") end
Revert broken "fix"
Revert broken "fix"
Lua
bsd-3-clause
protomech/epgp-dkp-reloaded,hayword/tfatf_epgp,ceason/epgp-tfatf,hayword/tfatf_epgp,sheldon/epgp,sheldon/epgp,ceason/epgp-tfatf,protomech/epgp-dkp-reloaded
89eb3c88241af293e0123e0f86d3992c2fb3b607
plugins/plugins.lua
plugins/plugins.lua
do -- #Begin plugins.lua by @BeyondTeam -- Returns the key (index) in the config.enabled_plugins table local function plugin_enabled( name ) for k,v in pairs(_config.enabled_plugins) do if name == v then return k end end -- If not found return false end -- Returns true if file exists in plugins folder local function plugin_exists( name ) for k,v in pairs(plugins_names()) do if name..'.lua' == v then return true end end return false end local function list_all_plugins(only_enabled, msg) local tmp = '\n\n@BeyondTeam' local text = '' local nsum = 0 for k, v in pairs( plugins_names( )) do -- ✔ enabled, ❌ disabled local status = '|✖️|>' nsum = nsum+1 nact = 0 -- Check if is enabled for k2, v2 in pairs(_config.enabled_plugins) do if v == v2..'.lua' then status = '|✔|>' end nact = nact+1 end if not only_enabled or status == '|✔|>'then -- get the name v = string.match (v, "(.*)%.lua") text = text..nsum..'.'..status..' '..v..' \n' end end text = '<code>'..text..'</code>\n\n'..nsum..' <b>📂plugins installed</b>\n\n'..nact..' <i>✔️plugins enabled</i>\n\n'..nsum-nact..' <i>❌plugins disabled</i>'..tmp tdcli.sendMessage(msg.to.id, msg.id_, 1, text, 1, 'html') end local function list_plugins(only_enabled, msg) local text = '' local nsum = 0 for k, v in pairs( plugins_names( )) do -- ✔ enabled, ❌ disabled local status = '*|✖️|>*' nsum = nsum+1 nact = 0 -- Check if is enabled for k2, v2 in pairs(_config.enabled_plugins) do if v == v2..'.lua' then status = '*|✔|>*' end nact = nact+1 end if not only_enabled or status == '*|✔|>*'then -- get the name v = string.match (v, "(.*)%.lua") -- text = text..v..' '..status..'\n' end end text = "\n_🔃All Plugins Reloaded_\n\n"..nact.." *✔️Plugins Enabled*\n"..nsum.." *📂Plugins Installed*\n\n@BeyondTeam" tdcli.sendMessage(msg.to.id, msg.id_, 1, text, 1, 'md') end local function reload_plugins(checks, msg) plugins = {} load_plugins() return list_plugins(true, msg) end local function enable_plugin( plugin_name, msg ) print('checking if '..plugin_name..' exists') -- Check if plugin is enabled if plugin_enabled(plugin_name) then local text = '<b>'..plugin_name..'</b> <i>is enabled.</i>' tdcli.sendMessage(msg.to.id, msg.id_, 1, text, 1, 'html') end -- Checks if plugin exists if plugin_exists(plugin_name) then -- Add to the config table table.insert(_config.enabled_plugins, plugin_name) print(plugin_name..' added to _config table') save_config() -- Reload the plugins return reload_plugins(true, msg) else local text = '<b>'..plugin_name..'</b> <i>does not exists.</i>' tdcli.sendMessage(msg.to.id, msg.id_, 1, text, 1, 'html') end end local function disable_plugin( name, msg ) -- Check if plugins exists if not plugin_exists(name) then local text = '<b>'..name..'</b> <i>does not exists.</i>' tdcli.sendMessage(msg.to.id, msg.id_, 1, text, 1, 'html') end local k = plugin_enabled(name) -- Check if plugin is enabled if not k then local text = '<b>'..name..'</b> <i>not enabled.</i>' tdcli.sendMessage(msg.to.id, msg.id_, 1, text, 1, 'html') end -- Disable and reload table.remove(_config.enabled_plugins, k) save_config( ) return reload_plugins(true, msg) end local function disable_plugin_on_chat(receiver, plugin, msg) if not plugin_exists(plugin) then return "_Plugin doesn't exists_" end if not _config.disabled_plugin_on_chat then _config.disabled_plugin_on_chat = {} end if not _config.disabled_plugin_on_chat[receiver] then _config.disabled_plugin_on_chat[receiver] = {} end _config.disabled_plugin_on_chat[receiver][plugin] = true save_config() local text = '<b>'..plugin..'</b> <i>disabled on this chat.</i>' tdcli.sendMessage(msg.to.id, msg.id_, 1, text, 1, 'html') end local function reenable_plugin_on_chat(receiver, plugin, msg) if not _config.disabled_plugin_on_chat then return 'There aren\'t any disabled plugins' end if not _config.disabled_plugin_on_chat[receiver] then return 'There aren\'t any disabled plugins for this chat' end if not _config.disabled_plugin_on_chat[receiver][plugin] then return '_This plugin is not disabled_' end _config.disabled_plugin_on_chat[receiver][plugin] = false save_config() local text = '<b>'..plugin..'</b> <i>is enabled again.</i>' tdcli.sendMessage(msg.to.id, msg.id_, 1, text, 1, 'html') end local function run(msg, matches) -- Show the available plugins if is_sudo(msg) then if matches[1]:lower() == 'plist' then --after changed to moderator mode, set only sudo return list_all_plugins(false, msg) end end -- Re-enable a plugin for this chat if matches[1]:lower() == 'pl' then if matches[2] == '+' and matches[4] == 'chat' then if is_mod(msg) then local receiver = msg.chat_id_ local plugin = matches[3] print("enable "..plugin..' on this chat') return reenable_plugin_on_chat(receiver, plugin, msg) end end -- Enable a plugin if matches[2] == '+' and is_sudo(msg) then --after changed to moderator mode, set only sudo local plugin_name = matches[3] print("enable: "..matches[3]) return enable_plugin(plugin_name, msg) end -- Disable a plugin on a chat if matches[2] == '-' and matches[4] == 'chat' then if is_mod(msg) then local plugin = matches[3] local receiver = msg.chat_id_ print("disable "..plugin..' on this chat') return disable_plugin_on_chat(receiver, plugin, msg) end end -- Disable a plugin if matches[2] == '-' and is_sudo(msg) then --after changed to moderator mode, set only sudo if matches[3] == 'plugins' then return 'This plugin can\'t be disabled' end print("disable: "..matches[3]) return disable_plugin(matches[3], msg) end -- Reload all the plugins! if matches[2] == '*' and is_sudo(msg) then --after changed to moderator mode, set only sudo return reload_plugins(true, msg) end end if matches[1]:lower() == 'reload' and is_sudo(msg) then --after changed to moderator mode, set only sudo return reload_plugins(true, msg) end end return { description = "Plugin to manage other plugins. Enable, disable or reload.", usage = { moderator = { "!pl - [plugin] chat : disable plugin only this chat.", "!pl + [plugin] chat : enable plugin only this chat.", }, sudo = { "!plist : list all plugins.", "!pl + [plugin] : enable plugin.", "!pl - [plugin] : disable plugin.", "!pl * : reloads all plugins." }, }, patterns = { "^[!/#]([Pp]list)$", "^[!/#]([Pp]l) (+) ([%w_%.%-]+)$", "^[!/#]([Pp]l) (-) ([%w_%.%-]+)$", "^[!/#]([Pp]l) (+) ([%w_%.%-]+) (chat)", "^[!/#]([Pp]l) (-) ([%w_%.%-]+) (chat)", "^[!/#]([Pp]l) (*)$", "^[!/#]([Rr]eload)$" }, run = run, moderated = true, -- set to moderator mode privileged = true } end
do -- #Begin plugins.lua by @BeyondTeam -- Returns the key (index) in the config.enabled_plugins table local function plugin_enabled( name ) for k,v in pairs(_config.enabled_plugins) do if name == v then return k end end -- If not found return false end -- Returns true if file exists in plugins folder local function plugin_exists( name ) for k,v in pairs(plugins_names()) do if name..'.lua' == v then return true end end return false end local function list_all_plugins(only_enabled, msg) local tmp = '\n\n@BeyondTeam' local text = '' local nsum = 0 for k, v in pairs( plugins_names( )) do -- ✔ enabled, ❌ disabled local status = '|✖️|>' nsum = nsum+1 nact = 0 -- Check if is enabled for k2, v2 in pairs(_config.enabled_plugins) do if v == v2..'.lua' then status = '|✔|>' end nact = nact+1 end if not only_enabled or status == '|✔|>'then -- get the name v = string.match (v, "(.*)%.lua") text = text..nsum..'.'..status..' '..v..' \n' end end text = '<code>'..text..'</code>\n\n'..nsum..' <b>📂plugins installed</b>\n\n'..nact..' <i>✔️plugins enabled</i>\n\n'..nsum-nact..' <i>❌plugins disabled</i>'..tmp tdcli.sendMessage(msg.to.id, msg.id_, 1, text, 1, 'html') end local function list_plugins(only_enabled, msg) local text = '' local nsum = 0 for k, v in pairs( plugins_names( )) do -- ✔ enabled, ❌ disabled local status = '*|✖️|>*' nsum = nsum+1 nact = 0 -- Check if is enabled for k2, v2 in pairs(_config.enabled_plugins) do if v == v2..'.lua' then status = '*|✔|>*' end nact = nact+1 end if not only_enabled or status == '*|✔|>*'then -- get the name v = string.match (v, "(.*)%.lua") -- text = text..v..' '..status..'\n' end end text = "\n_🔃All Plugins Reloaded_\n\n"..nact.." *✔️Plugins Enabled*\n"..nsum.." *📂Plugins Installed*\n\n@BeyondTeam" tdcli.sendMessage(msg.to.id, msg.id_, 1, text, 1, 'md') end local function reload_plugins(checks, msg) plugins = {} load_plugins() return list_plugins(true, msg) end local function enable_plugin( plugin_name, msg ) print('checking if '..plugin_name..' exists') -- Check if plugin is enabled if plugin_enabled(plugin_name) then local text = '<b>'..plugin_name..'</b> <i>is enabled.</i>' tdcli.sendMessage(msg.to.id, msg.id_, 1, text, 1, 'html') return end -- Checks if plugin exists if plugin_exists(plugin_name) then -- Add to the config table table.insert(_config.enabled_plugins, plugin_name) print(plugin_name..' added to _config table') save_config() -- Reload the plugins return reload_plugins(true, msg) else local text = '<b>'..plugin_name..'</b> <i>does not exists.</i>' tdcli.sendMessage(msg.to.id, msg.id_, 1, text, 1, 'html') end end local function disable_plugin( name, msg ) local k = plugin_enabled(name) -- Check if plugin is enabled if not k then local text = '<b>'..name..'</b> <i>not enabled.</i>' tdcli.sendMessage(msg.to.id, msg.id_, 1, text, 1, 'html') return end -- Check if plugins exists if not plugin_exists(name) then local text = '<b>'..name..'</b> <i>does not exists.</i>' tdcli.sendMessage(msg.to.id, msg.id_, 1, text, 1, 'html') else -- Disable and reload table.remove(_config.enabled_plugins, k) save_config( ) return reload_plugins(true, msg) end end local function disable_plugin_on_chat(receiver, plugin, msg) if not plugin_exists(plugin) then return "_Plugin doesn't exists_" end if not _config.disabled_plugin_on_chat then _config.disabled_plugin_on_chat = {} end if not _config.disabled_plugin_on_chat[receiver] then _config.disabled_plugin_on_chat[receiver] = {} end _config.disabled_plugin_on_chat[receiver][plugin] = true save_config() local text = '<b>'..plugin..'</b> <i>disabled on this chat.</i>' tdcli.sendMessage(msg.to.id, msg.id_, 1, text, 1, 'html') end local function reenable_plugin_on_chat(receiver, plugin, msg) if not _config.disabled_plugin_on_chat then return 'There aren\'t any disabled plugins' end if not _config.disabled_plugin_on_chat[receiver] then return 'There aren\'t any disabled plugins for this chat' end if not _config.disabled_plugin_on_chat[receiver][plugin] then return '_This plugin is not disabled_' end _config.disabled_plugin_on_chat[receiver][plugin] = false save_config() local text = '<b>'..plugin..'</b> <i>is enabled again.</i>' tdcli.sendMessage(msg.to.id, msg.id_, 1, text, 1, 'html') end local function run(msg, matches) -- Show the available plugins if is_sudo(msg) then if matches[1]:lower() == 'plist' then --after changed to moderator mode, set only sudo return list_all_plugins(false, msg) end end -- Re-enable a plugin for this chat if matches[1]:lower() == 'pl' then if matches[2] == '+' and matches[4] == 'chat' then if is_mod(msg) then local receiver = msg.chat_id_ local plugin = matches[3] print("enable "..plugin..' on this chat') return reenable_plugin_on_chat(receiver, plugin, msg) end end -- Enable a plugin if matches[2] == '+' and is_sudo(msg) then --after changed to moderator mode, set only sudo local plugin_name = matches[3] print("enable: "..matches[3]) return enable_plugin(plugin_name, msg) end -- Disable a plugin on a chat if matches[2] == '-' and matches[4] == 'chat' then if is_mod(msg) then local plugin = matches[3] local receiver = msg.chat_id_ print("disable "..plugin..' on this chat') return disable_plugin_on_chat(receiver, plugin, msg) end end -- Disable a plugin if matches[2] == '-' and is_sudo(msg) then --after changed to moderator mode, set only sudo if matches[3] == 'plugins' then return 'This plugin can\'t be disabled' end print("disable: "..matches[3]) return disable_plugin(matches[3], msg) end -- Reload all the plugins! if matches[2] == '*' and is_sudo(msg) then --after changed to moderator mode, set only sudo return reload_plugins(true, msg) end end if matches[1]:lower() == 'reload' and is_sudo(msg) then --after changed to moderator mode, set only sudo return reload_plugins(true, msg) end end return { description = "Plugin to manage other plugins. Enable, disable or reload.", usage = { moderator = { "!pl - [plugin] chat : disable plugin only this chat.", "!pl + [plugin] chat : enable plugin only this chat.", }, sudo = { "!plist : list all plugins.", "!pl + [plugin] : enable plugin.", "!pl - [plugin] : disable plugin.", "!pl * : reloads all plugins." }, }, patterns = { "^[!/#]([Pp]list)$", "^[!/#]([Pp]l) (+) ([%w_%.%-]+)$", "^[!/#]([Pp]l) (-) ([%w_%.%-]+)$", "^[!/#]([Pp]l) (+) ([%w_%.%-]+) (chat)", "^[!/#]([Pp]l) (-) ([%w_%.%-]+) (chat)", "^[!/#]([Pp]l) (*)$", "^[!/#]([Rr]eload)$" }, run = run, moderated = true, -- set to moderator mode privileged = true } end
Bug Fixed!
Bug Fixed!
Lua
unlicense
MobinDehghani/iManager
63c08494e4347e436a3a12aeb20f06312ef9638b
durden/browser.lua
durden/browser.lua
-- Copyright: 2015, Björn Ståhl -- License: 3-Clause BSD -- Reference: http://durden.arcan-fe.com -- Description: Brower covers a lbar- based resource picker for -- existing resources. local last_path = {}; local function match_ext(v, tbl) if (tbl == nil) then return true; end local ext = string.match(v, "^.+(%..+)$"); ext = ext ~= nil and string.sub(ext, 2) or ext; if (ext == nil or string.len(ext) == 0) then return false; end return tbl[ext]; end local function browse_cb(ctx, instr, done, lastv, inputv) if (done) then if (inputv == "/") then while (#ctx.path > ctx.minlen) do table.remove(ctx.path, #ctx.path); end browse_file(ctx.path, ctx.fltext, ctx.namespace, ctx.trigger, 0); return; end if (instr == "..") then local path = ctx.path; if (#path > ctx.minlen) then table.remove(path, #path); end browse_file(path, ctx.fltext, ctx.namespace, ctx.trigger, 0); return; elseif (instr == "/") then browse_file(ctx.initial, ctx.fltext, ctx.namespace, ctx.trigger, 0); return; end string.gsub(instr, "..", ""); local pn = string.format("%s/%s", table.concat(ctx.path, "/"), instr); local r, v = resource(pn, ctx.namespace); if (v == "directory") then table.insert(ctx.path, instr); browse_file(ctx.path, ctx.fltext, ctx.namespace, ctx.trigger, 0); else local fn = match_ext(pn, ctx.fltext); if (type(fn) == "function") then fn(pn, ctx.path); elseif (ctx.trigger) then ctx.trigger(pn, ctx.path); end local m1, m2 = dispatch_meta(); if (m1) then browse_file(ctx.path, ctx.fltext, ctx.namespace, ctx.trigger, 0); end end return; end -- glob and tag the resulting table with the type, current solution isn't -- ideal as this may be I/O operations stalling heavily on weird filesystems -- so we need an asynch glob_resource and all the problems that come there. last_path = ctx.path; local path = table.concat(ctx.path, "/"); if (ctx.paths[path] == nil) then ctx.paths[path] = glob_resource(path .. "/*", ctx.namespace); ctx.paths[path] = ctx.paths[path] and ctx.paths[path] or {}; for i=1,#ctx.paths[path] do local elem = ctx.paths[path][i]; local ign; ign, ctx.paths[path][elem] = resource(path .. "/" .. elem, ctx.namespace); end end -- sweep through and color code accordingly, filter matches local mlbl = gconfig_get("lbar_menulblstr"); local msellbl = gconfig_get("lbar_menulblselstr"); local res = {}; for i,v in ipairs(ctx.paths[path]) do if (string.sub(v,1,string.len(instr)) == instr) then if (ctx.paths[path][v] == "directory") then table.insert(res, {mlbl, msellbl, v}); elseif (match_ext(v, ctx.fltext)) then table.insert(res, v); end end end table.insert(res, ".."); return {set = res, valid = false}; end function browse_file(pathtbl, extensions, mask, donecb, tblmin, opts) pathtbl = pathtbl and pathtbl or last_path; local dup = {}; for k,v in ipairs(pathtbl) do dup[k] = v; end active_display():lbar(browse_cb, { base = prefix, path = pathtbl, initial = dup, paths = {}, minlen = tblmin ~= nil and tblmin or #pathtbl, fltext = extensions, namespace = mask, trigger = donecb, opts = opts and opts or {}, }, {force_completion = true}); end
-- Copyright: 2015, Björn Ståhl -- License: 3-Clause BSD -- Reference: http://durden.arcan-fe.com -- Description: Brower covers a lbar- based resource picker for -- existing resources. local last_path = {}; local last_min = 0; local function match_ext(v, tbl) if (tbl == nil) then return true; end local ext = string.match(v, "^.+(%..+)$"); ext = ext ~= nil and string.sub(ext, 2) or ext; if (ext == nil or string.len(ext) == 0) then return false; end return tbl[ext]; end local function browse_cb(ctx, instr, done, lastv, inputv) if (done) then if (inputv == "/") then while (#ctx.path > ctx.minlen) do table.remove(ctx.path, #ctx.path); end browse_file(ctx.path, ctx.fltext, ctx.namespace, ctx.trigger, 0); return; end if (instr == "..") then local path = ctx.path; if (#path > ctx.minlen) then table.remove(path, #path); end browse_file(path, ctx.fltext, ctx.namespace, ctx.trigger, 0); return; elseif (instr == "/") then browse_file(ctx.initial, ctx.fltext, ctx.namespace, ctx.trigger, 0); return; end string.gsub(instr, "..", ""); local pn = string.format("%s/%s", table.concat(ctx.path, "/"), instr); local r, v = resource(pn, ctx.namespace); if (v == "directory") then table.insert(ctx.path, instr); browse_file(ctx.path, ctx.fltext, ctx.namespace, ctx.trigger, 0); else local fn = match_ext(pn, ctx.fltext); if (type(fn) == "function") then fn(pn, ctx.path); elseif (ctx.trigger) then ctx.trigger(pn, ctx.path); end local m1, m2 = dispatch_meta(); if (m1) then browse_file(ctx.path, ctx.fltext, ctx.namespace, ctx.trigger, 0); end end return; end -- glob and tag the resulting table with the type, current solution isn't -- ideal as this may be I/O operations stalling heavily on weird filesystems -- so we need an asynch glob_resource and all the problems that come there. last_path = ctx.path; last_min = ctx.minlen; local path = table.concat(ctx.path, "/"); if (ctx.paths[path] == nil) then ctx.paths[path] = glob_resource(path .. "/*", ctx.namespace); ctx.paths[path] = ctx.paths[path] and ctx.paths[path] or {}; for i=1,#ctx.paths[path] do local elem = ctx.paths[path][i]; local ign; ign, ctx.paths[path][elem] = resource(path .. "/" .. elem, ctx.namespace); end end -- sweep through and color code accordingly, filter matches local mlbl = gconfig_get("lbar_menulblstr"); local msellbl = gconfig_get("lbar_menulblselstr"); local res = {}; for i,v in ipairs(ctx.paths[path]) do if (string.sub(v,1,string.len(instr)) == instr) then if (ctx.paths[path][v] == "directory") then table.insert(res, {mlbl, msellbl, v}); elseif (match_ext(v, ctx.fltext)) then table.insert(res, v); end end end table.insert(res, ".."); return {set = res, valid = false}; end function browse_file(pathtbl, extensions, mask, donecb, tblmin, opts) if (not pathtbl) then pathtbl = last_path; tblmin = last_min; end local dup = {}; for k,v in ipairs(pathtbl) do dup[k] = v; end active_display():lbar(browse_cb, { base = prefix, path = pathtbl, initial = dup, paths = {}, minlen = tblmin ~= nil and tblmin or #pathtbl, fltext = extensions, namespace = mask, trigger = donecb, opts = opts and opts or {}, }, {force_completion = true}); end
fixed .. twice bug in browse
fixed .. twice bug in browse
Lua
bsd-3-clause
letoram/durden
0bbeeaf0929835a155d1072e19c67d4a06ffbed2
config/nvim/lua/settings/startify.lua
config/nvim/lua/settings/startify.lua
local nmap = require("utils").nmap local g = vim.g g.startify_files_number = 10 g.startify_change_to_dir = 0 local ascii = { [[ ____ ]], [[ /___/\_ ]], [[ _\ \/_/\__ __ ]], [[ __\ \/_/\ .--.--.|__|.--.--.--. ]], [[ \ __ __ \ \ | | || || | ]], [[ __\ \_\ \_\ \ \ __ \___/ |__||__|__|__| ]], [[ /_/\\ __ __ \ \_/_/\ ]], [[ \_\/_\__\/\__\/\__\/_\_\/ ]], [[ \_\/_/\ /_\_\/ ]], [[ \_\/ \_\/ ]] } -- g.startify_custom_header = 'startify#center(g:ascii)' g.startify_custom_header = ascii g.startify_relative_path = 1 g.startify_use_env = 1 g.startify_lists = { {type = "dir", header = {"Recent Files "}}, {type = "sessions", header = {"Sessions"}}, {type = "bookmarks", header = {"Bookmarks"}}, {type = "commands", header = {"Commands"}} } g.startify_commands = { {up = {"Update Plugins", ":PlugUpdate"}}, {ug = {"Upgrade Plugin Manager", ":PlugUpgrade"}}, {ts = {"Update Treesitter", "TSUpdate"}}, {ch = {"Check Health", "checkhealth"}} } g.startify_bookmarks = { {c = "~/.config/nvim/init.vim"}, {g = "~/.gitconfig"}, {z = "~/.zshrc"} } nmap("<leader>st", ":Startify<cr>")
local nmap = require("utils").nmap local g = vim.g local fn = vim.fn g.startify_files_number = 10 g.startify_change_to_dir = 0 local ascii = { [[ ____ ]], [[ /___/\_ ]], [[ _\ \/_/\__ __ ]], [[ __\ \/_/\ .--.--.|__|.--.--.--. ]], [[ \ __ __ \ \ | | || || | ]], [[ __\ \_\ \_\ \ \ __ \___/ |__||__|__|__| ]], [[ /_/\\ __ __ \ \_/_/\ ]], [[ \_\/_\__\/\__\/\__\/_\_\/ ]], [[ \_\/_/\ /_\_\/ ]], [[ \_\/ \_\/ ]] } -- g.startify_custom_header = 'startify#center(g:ascii)' g.startify_custom_header = ascii g.startify_relative_path = 1 g.startify_use_env = 1 g.startify_lists = { {type = "dir", header = {"Files: " .. fn.getcwd()}}, {type = "sessions", header = {"Sessions"}}, {type = "bookmarks", header = {"Bookmarks"}}, {type = "commands", header = {"Commands"}} } g.startify_commands = { {up = {"Update Plugins", ":PlugUpdate"}}, {ug = {"Upgrade Plugin Manager", ":PlugUpgrade"}}, {ts = {"Update Treesitter", "TSUpdate"}}, {ch = {"Check Health", "checkhealth"}} } g.startify_bookmarks = { {c = "~/.config/nvim/init.vim"}, {g = "~/.gitconfig"}, {z = "~/.zshrc"} } nmap("<leader>st", ":Startify<cr>")
chore(nvim): fix startify recent files header
chore(nvim): fix startify recent files header add current file path to list
Lua
mit
nicknisi/dotfiles,nicknisi/dotfiles,nicknisi/dotfiles
d46c580e1de5e9677589662f38566d065acaf7e0
actor_socket.lua
actor_socket.lua
-- Integration of actor post office with sockets. -- local socket = require("socket") function actor_socket_create() local reading = {} -- Array of sockets for next select(). local writing = {} -- Array of sockets for next select(). local reverse_r = {} -- Reverse lookup from socket to reading/writing index. local reverse_w = {} -- Reverse lookup from socket to reading/writing index. local waiting_actor = {} -- Keyed by socket, value is actor addr. ------------------------------------------ local function skt_unwait(skt, sockets, reverse) waiting_actor[skt] = nil local cur = reverse[skt] if cur then reverse[skt] = nil local num = #sockets local top = sockets[num] assert(cur >= 1 and cur <= num) sockets[num] = nil if cur < num then sockets[cur] = top reverse[top] = cur end end end local function skt_wait(skt, sockets, reverse, actor_addr) assert(not waiting_actor[skt]) assert(not reverse[skt]) waiting_actor[skt] = actor_addr table.insert(sockets, skt) reverse[skt] = #sockets end ------------------------------------------ local function awake_actor(skt) assert(skt) local actor_addr = waiting_actor[skt] skt_unwait(skt, reading, reverse_r) skt_unwait(skt, writing, reverse_w) if actor_addr then apo.send_later(actor_addr, skt) end end local function process_ready(ready, name) for i = 1, #ready do awake_actor(ready[i]) end end local function step(timeout) if (#reading + #writing) <= 0 then return nil end local readable, writable, err = socket.select(reading, writing, timeout) process_ready(writable, "w") process_ready(readable, "r") if err == "timeout" and (#readable + #writable) > 0 then return nil end return err end ------------------------------------------ local function recv(actor_addr, skt, pattern, part) local s, err repeat skt_unwait(skt, reading, reverse_r) skt_unwait(skt, writing, reverse_w) s, err, part = skt:receive(pattern, part) if s or err ~= "timeout" then return s, err, part end skt_wait(skt, reading, reverse_r, actor_addr) assert(skt == coroutine.yield()) until false end local function send(actor_addr, skt, data, from, to) from = from or 1 local lastIndex = from - 1 repeat skt_unwait(skt, reading, reverse_r) skt_unwait(skt, writing, reverse_w) local s, err, lastIndex = skt:send(data, lastIndex + 1, to) if s or err ~= "timeout" then return s, err, lastIndex end skt_wait(skt, writing, reverse_w, actor_addr) assert(skt == coroutine.yield()) until false end local function loop_accept(actor_addr, skt, handler, timeout) skt:settimeout(timeout or 0) repeat skt_unwait(skt, reading, reverse_r) skt_unwait(skt, writing, reverse_w) local client_skt, err = skt:accept() if client_skt then handler(client_skt) end skt_wait(skt, reading, reverse_r, actor_addr) assert(skt == coroutine.yield()) until false end ------------------------------------------ return { step = step, recv = recv, send = send, loop_accept = loop_accept } end ------------------------------------------ return actor_socket_create()
-- Integration of actor post office with sockets. -- local socket = require("socket") function actor_socket_create() local reading = {} -- Array of sockets for next select(). local writing = {} -- Array of sockets for next select(). local reverse_r = {} -- Reverse lookup from socket to reading/writing index. local reverse_w = {} -- Reverse lookup from socket to reading/writing index. local waiting_actor = {} -- Keyed by socket, value is actor addr. ------------------------------------------ local function skt_unwait(skt, sockets, reverse) waiting_actor[skt] = nil local cur = reverse[skt] if cur then reverse[skt] = nil local num = #sockets local top = sockets[num] assert(cur >= 1 and cur <= num) sockets[num] = nil if cur < num then sockets[cur] = top reverse[top] = cur end end end local function skt_wait(skt, sockets, reverse, actor_addr) assert(not waiting_actor[skt]) assert(not reverse[skt]) waiting_actor[skt] = actor_addr table.insert(sockets, skt) reverse[skt] = #sockets end ------------------------------------------ local function awake_actor(skt) assert(skt) local actor_addr = waiting_actor[skt] skt_unwait(skt, reading, reverse_r) skt_unwait(skt, writing, reverse_w) if actor_addr then apo.send_later(actor_addr, "skt", skt) end end local function process_ready(ready, name) for i = 1, #ready do awake_actor(ready[i]) end end local function step(timeout) if (#reading + #writing) <= 0 then return nil end local readable, writable, err = socket.select(reading, writing, timeout) process_ready(writable, "w") process_ready(readable, "r") if err == "timeout" and (#readable + #writable) > 0 then return nil end return err end ------------------------------------------ -- A filter for apo.recv(), where we only want awake_actor() calls. -- local function filter_skt(s, skt) return (s == "skt") and skt end ------------------------------------------ local function recv(actor_addr, skt, pattern, part) local s, err repeat skt_unwait(skt, reading, reverse_r) skt_unwait(skt, writing, reverse_w) s, err, part = skt:receive(pattern, part) if s or err ~= "timeout" then return s, err, part end skt_wait(skt, reading, reverse_r, actor_addr) s, skt_recv = apo.recv(filter_skt) assert(skt == skt_recv) until false end local function send(actor_addr, skt, data, from, to) from = from or 1 local lastIndex = from - 1 repeat skt_unwait(skt, reading, reverse_r) skt_unwait(skt, writing, reverse_w) local s, err, lastIndex = skt:send(data, lastIndex + 1, to) if s or err ~= "timeout" then return s, err, lastIndex end skt_wait(skt, writing, reverse_w, actor_addr) s, skt_recv = apo.recv(filter_skt) assert(skt == skt_recv) until false end local function loop_accept(actor_addr, skt, handler, timeout) skt:settimeout(timeout or 0) repeat skt_unwait(skt, reading, reverse_r) skt_unwait(skt, writing, reverse_w) local client_skt, err = skt:accept() if client_skt then handler(client_skt) end skt_wait(skt, reading, reverse_r, actor_addr) s, skt_recv = apo.recv(filter_skt) assert(skt == skt_recv) until false end ------------------------------------------ return { step = step, recv = recv, send = send, loop_accept = loop_accept } end ------------------------------------------ return actor_socket_create()
fix for actor_socket concurrency using apo.recv(filters)
fix for actor_socket concurrency using apo.recv(filters)
Lua
apache-2.0
steveyen/moxilua
5a8daac9c519da3a8021f15a0288b2c4cfd44f15
src_trunk/resources/irc/s_irc.lua
src_trunk/resources/irc/s_irc.lua
server = "irc.gtanet.com" port = 6667 username = "ValhallaGaming" channel = "#vgmta.admins" pubchannel = "#mta" password = "adminmtavg" conn = nil timer = nil function initIRC() ircInit() conn = ircOpen(server, port, username, channel, password) sendMessage("Server Started.") displayStatus() timer = setTimer(displayStatus, 600000, 0) ircJoin(conn, pubchannel) end addEventHandler("onResourceStart", getResourceRootElement(getThisResource()), initIRC) function stopIRC() sendMessage("Server Stopped.") ircPart(conn, channel) ircDisconnect(conn) killTimer(timer) timer = nil conn = nil end addEventHandler("onResourceStop", getResourceRootElement(getThisResource()), stopIRC) function sendMessage(message) local time = getRealTime() local hour = time.hour local mins = time.minute hour = hour + 8 if (hour==24) then hour = 0 elseif (hour>24) then hour = hour - 24 end -- Fix time if (hour<10) then hour = 0 .. tostring(hour) end if (mins<10) then mins = 0 .. tostring(mins) end outputDebugString(tostring(message)) ircMessage(conn, channel, "[" .. hour .. ":" .. mins .. "] " .. tostring(message)) end function displayStatus() local playerCount = getPlayerCount() local maxPlayers = getMaxPlayers() local servername = getServerName() local ip = "67.210.235.106:22003" local totalping = 0 local averageping = 0 for key, value in ipairs(exports.pool:getPoolElementsByType("player")) do totalping = totalping + getPlayerPing(value) end if (playerCount>0) then averageping = math.floor(totalping / playerCount) end local output = servername .. " - " .. playerCount .. "/" .. maxPlayers .. "(" .. math.ceil((playerCount/maxPlayers)*100) .. "%) - " .. ip .. " - GameMode: Roleplay - Average Ping: " .. averageping .. "." ircMessage(conn, channel, output) end
server = "irc.gtanet.com" port = 6667 username = "ValhallaGaming" channel = "#vgmta.admins" pubchannel = "#mta" password = "adminmtavg" conn = nil conn2 = nil timer = nil useSecond = false function initIRC() ircInit() conn = ircOpen(server, port, username, channel, password) conn2 = ircOpen(server, port, username, channel, password) sendMessage("Server Started.") displayStatus() timer = setTimer(displayStatus, 300000, 0) ircJoin(conn, pubchannel) ircJoin(conn2, pubchannel) end addEventHandler("onResourceStart", getResourceRootElement(getThisResource()), initIRC) function stopIRC() sendMessage("Server Stopped.") ircPart(conn, channel) ircDisconnect(conn) killTimer(timer) timer = nil conn = nil end addEventHandler("onResourceStop", getResourceRootElement(getThisResource()), stopIRC) function sendMessage(message) local time = getRealTime() local hour = time.hour local mins = time.minute hour = hour + 8 if (hour==24) then hour = 0 elseif (hour>24) then hour = hour - 24 end -- Fix time if (hour<10) then hour = 0 .. tostring(hour) end if (mins<10) then mins = 0 .. tostring(mins) end outputDebugString(tostring(message)) if not (useSecond) then ircMessage(conn, channel, "[" .. hour .. ":" .. mins .. "] " .. tostring(message)) else ircMessage(conn2, channel, "[" .. hour .. ":" .. mins .. "] " .. tostring(message)) end end function displayStatus() local playerCount = getPlayerCount() local maxPlayers = getMaxPlayers() local servername = getServerName() local ip = "67.210.235.106:22003" local totalping = 0 local averageping = 0 for key, value in ipairs(exports.pool:getPoolElementsByType("player")) do totalping = totalping + getPlayerPing(value) end if (playerCount>0) then averageping = math.floor(totalping / playerCount) end local output = servername .. " - " .. playerCount .. "/" .. maxPlayers .. "(" .. math.ceil((playerCount/maxPlayers)*100) .. "%) - " .. ip .. " - GameMode: Roleplay - Average Ping: " .. averageping .. "." if not (useSecond) then ircMessage(conn, channel, output) else ircMessage(conn2, channel, output) end end
Fix to stop echo being kicked from IRC.
Fix to stop echo being kicked from IRC. git-svn-id: 8769cb08482c9977c94b72b8e184ec7d2197f4f7@541 64450a49-1f69-0410-a0a2-f5ebb52c4f5b
Lua
bsd-3-clause
valhallaGaming/uno,valhallaGaming/uno,valhallaGaming/uno
265a1bb1ddf204f329614a221d4fdab3210d1552
examples/flames.lua
examples/flames.lua
<<<<<<< HEAD ======= -- Flames.lua, contributed by pmprog in the OpenPandora board. -- See http://boards.openpandora.org/index.php?/topic/7405-here-is-a-pnd-for-load81/ function setup() local x, y, l MaxFlames = 150 FlameLife = 40 FlameSize = 10 refreshCount = 0 skipCount = 0 Flames = { } filled(false) for i=1,MaxFlames do x = math.random(WIDTH/3) + (WIDTH/3) y = math.random(FlameSize) l = math.random(FlameLife) a = { x = x, y = y, l = l } table.insert(Flames,a) end end -- can't find this in .math, but lets have it here for later transformation anyway .. function map(x, in_min, in_max, out_min, out_max) return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min; end function draw() local i, f, minMove; -- user can move joystick to get different flame effects local joyLengths = { 5, 15, 20, 45, 60, 95, 140, 170, 200}; local joyFlames = { 5, 10, 15, 30, 60, 75, 90, 150 }; background(0,0,0) -- ahem .. change properties of the flame according to joystick input FlameSize = joyLengths[math.floor(map (joystick[1].x, 32767, -32767, 1, #joyLengths) + .5)] FlameLife = joyFlames[math.floor(map (joystick[1].y, 32767, -32767, 1, #joyFlames) + .5)] ellipse(dot_x, dot_y, 30, 20); for i,f in pairs(Flames) do if f.l > 35 then filled(true) fill(255, 255, 255, 0.9) minMove = 0 elseif f.l > 30 then filled(false) fill(255, 255, 192, 0.8) minMove = 1 elseif f.l > 20 then fill(255, 192, 128, 0.7) minMove = 2 elseif f.l > 10 then fill(220, 128, 100, 0.5) minMove = 3 else fill(160, 128, 80, 0.3) minMove = 5 end ellipse(f.x,f.y,FlameSize,FlameSize) f.l = f.l - math.random(3) if f.l <= 0 then f.x = math.random(WIDTH/3) + (WIDTH/3) f.y = math.random(FlameSize) f.l = FlameLife else f.y = f.y + (math.random(6) + minMove) f.x = f.x + math.random(7) - 3 end end end >>>>>>> 2392e99884e31aadac3e0c4bfb9cb35dd53d5f35
-- Flames.lua, contributed by pmprog in the OpenPandora board. -- See http://boards.openpandora.org/index.php?/topic/7405-here-is-a-pnd-for-load81/ function setup() local x, y, l MaxFlames = 150 FlameLife = 40 FlameSize = 10 refreshCount = 0 skipCount = 0 Flames = { } filled(false) for i=1,MaxFlames do x = math.random(WIDTH/3) + (WIDTH/3) y = math.random(FlameSize) l = math.random(FlameLife) a = { x = x, y = y, l = l } table.insert(Flames,a) end end -- can't find this in .math, but lets have it here for later transformation anyway .. function map(x, in_min, in_max, out_min, out_max) return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min; end function draw() local i, f, minMove; -- user can move joystick to get different flame effects local joyLengths = { 5, 15, 20, 45, 60, 95, 140, 170, 200}; local joyFlames = { 5, 10, 15, 30, 60, 75, 90, 150 }; background(0,0,0) -- ahem .. change properties of the flame according to joystick input if joystick.count ~= 0 then FlameSize = joyLengths[math.floor(map (joystick[1].x, 32767, -32767, 1, #joyLengths) + .5)] FlameLife = joyFlames[math.floor(map (joystick[1].y, 32767, -32767, 1, #joyFlames) + .5)] end ellipse(dot_x, dot_y, 30, 20); for i,f in pairs(Flames) do if f.l > 35 then filled(true) fill(255, 255, 255, 0.9) minMove = 0 elseif f.l > 30 then filled(false) fill(255, 255, 192, 0.8) minMove = 1 elseif f.l > 20 then fill(255, 192, 128, 0.7) minMove = 2 elseif f.l > 10 then fill(220, 128, 100, 0.5) minMove = 3 else fill(160, 128, 80, 0.3) minMove = 5 end ellipse(f.x,f.y,FlameSize,FlameSize) f.l = f.l - math.random(3) if f.l <= 0 then f.x = math.random(WIDTH/3) + (WIDTH/3) f.y = math.random(FlameSize) f.l = FlameLife else f.y = f.y + (math.random(6) + minMove) f.x = f.x + math.random(7) - 3 end end end
fix for case where no joysticks are available
fix for case where no joysticks are available
Lua
bsd-2-clause
seclorum/load81,seclorum/load81,seclorum/load81,seclorum/load81,seclorum/load81
912ff6bcb7cec6bd3a1c2897ef2e4cad1cff283c
libs/core/luasrc/fs.lua
libs/core/luasrc/fs.lua
--[[ LuCI - Filesystem tools Description: A module offering often needed filesystem manipulation functions FileId: $Id$ License: Copyright 2008 Steven Barth <steven@midlink.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ]]-- module("luci.fs", package.seeall) require("posix") -- Access access = posix.access -- Glob glob = posix.glob -- Checks whether a file exists function isfile(filename) local fp = io.open(filename, "r") if fp then fp:close() end return fp ~= nil end -- Returns the content of file function readfile(filename) local fp, err = io.open(filename) if fp == nil then return nil, err end local data = fp:read("*a") fp:close() return data end -- Writes given data to a file function writefile(filename, data) local fp, err = io.open(filename, "w") if fp == nil then return nil, err end fp:write(data) fp:close() return true end -- Returns the file modification date/time of "path" function mtime(path) return posix.stat(path, "mtime") end -- basename wrapper basename = posix.basename -- dirname wrapper dirname = posix.dirname -- dir wrapper dir = posix.dir -- wrapper for posix.mkdir function mkdir(path, recursive) if recursive then local base = "." if path:sub(1,1) == "/" then base = "" path = path:gsub("^/+","") end for elem in path:gmatch("([^/]+)/*") do base = base .. "/" .. elem local stat = posix.stat( base ) if not stat then local stat, errmsg, errno = posix.mkdir( base ) if type(stat) ~= "number" or stat ~= 0 then return stat, errmsg, errno end else if stat.type ~= "directory" then return nil, base .. ": File exists", 17 end end end return 0 else return posix.mkdir( path ) end end -- Alias for posix.rmdir rmdir = posix.rmdir -- Alias for posix.stat stat = posix.stat -- Alias for posix.chmod chmod = posix.chmod -- Alias for posix.link link = posix.link -- Alias for posix.unlink unlink = posix.unlink
--[[ LuCI - Filesystem tools Description: A module offering often needed filesystem manipulation functions FileId: $Id$ License: Copyright 2008 Steven Barth <steven@midlink.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ]]-- module("luci.fs", package.seeall) require("posix") -- Access access = posix.access -- Glob glob = posix.glob -- Checks whether a file exists function isfile(filename) return posix.stat(filename, "type") == "regular" end -- Returns the content of file function readfile(filename) local fp, err = io.open(filename) if fp == nil then return nil, err end local data = fp:read("*a") fp:close() return data end -- Writes given data to a file function writefile(filename, data) local fp, err = io.open(filename, "w") if fp == nil then return nil, err end fp:write(data) fp:close() return true end -- Returns the file modification date/time of "path" function mtime(path) return posix.stat(path, "mtime") end -- basename wrapper basename = posix.basename -- dirname wrapper dirname = posix.dirname -- dir wrapper dir = posix.dir -- wrapper for posix.mkdir function mkdir(path, recursive) if recursive then local base = "." if path:sub(1,1) == "/" then base = "" path = path:gsub("^/+","") end for elem in path:gmatch("([^/]+)/*") do base = base .. "/" .. elem local stat = posix.stat( base ) if not stat then local stat, errmsg, errno = posix.mkdir( base ) if type(stat) ~= "number" or stat ~= 0 then return stat, errmsg, errno end else if stat.type ~= "directory" then return nil, base .. ": File exists", 17 end end end return 0 else return posix.mkdir( path ) end end -- Alias for posix.rmdir rmdir = posix.rmdir -- Alias for posix.stat stat = posix.stat -- Alias for posix.chmod chmod = posix.chmod -- Alias for posix.link link = posix.link -- Alias for posix.unlink unlink = posix.unlink
libs/core: Fixed luci.fs.isfile
libs/core: Fixed luci.fs.isfile
Lua
apache-2.0
deepak78/luci,8devices/luci,deepak78/luci,deepak78/luci,8devices/luci,deepak78/luci,8devices/luci,8devices/luci,deepak78/luci,8devices/luci,deepak78/luci,deepak78/luci,8devices/luci,deepak78/luci
276e19537aeffacbbbadaf28025fc2ea75378afe
nvim/lua/config/cmp.lua
nvim/lua/config/cmp.lua
local has_words_before = function() if vim.api.nvim_buf_get_option(0, 'buftype') == 'prompt' then return false end local line, col = unpack(vim.api.nvim_win_get_cursor(0)) return col ~= 0 and vim.api.nvim_buf_get_lines(0, line - 1, line, true)[1]:sub(col, col):match('%s') == nil end local feedkey = function(key, mode) vim.api.nvim_feedkeys(vim.api.nvim_replace_termcodes(key, true, true, true), mode, true) end local cmp = require('cmp') cmp.setup({ snippet = { expand = function(args) -- For `vsnip` user. -- vim.fn["vsnip#anonymous"](args.body) -- For `vsnip` user. -- For `luasnip` user. -- require('luasnip').lsp_expand(args.body) -- For `ultisnips` user. -- vim.fn["UltiSnips#Anon"](args.body) end, }, mapping = { ['<C-d>'] = cmp.mapping.scroll_docs(-4), ['<C-f>'] = cmp.mapping.scroll_docs(4), ['<C-Space>'] = cmp.mapping.complete(), ['<C-e>'] = cmp.mapping.close(), ['<CR>'] = cmp.mapping.confirm({ select = true }), ['<Tab>'] = cmp.mapping(function(fallback) if cmp.visible() then cmp.select_next_item() elseif vim.fn['vsnip#available'](1) == 1 then feedkey('<Plug>(vsnip-expand-or-jump)', '') elseif has_words_before() then cmp.complete() else fallback() -- The fallback function sends a already mapped key. In this case, it's probably `<Tab>`. end end, { 'i', 's', }), ['<S-Tab>'] = cmp.mapping(function() if cmp.visible() then cmp.select_prev_item() elseif vim.fn['vsnip#jumpable'](-1) == 1 then feedkey('<Plug>(vsnip-jump-prev)', '') end end, { 'i', 's', }), }, sources = { { name = 'nvim_lsp' }, { name = 'nvim_lsp_signature_help' }, -- For vsnip user. -- { name = 'vsnip' }, -- For luasnip user. -- { name = 'luasnip' }, -- For ultisnips user. -- { name = 'ultisnips' }, { name = 'buffer' }, { name = 'nvim_lua' }, }, })
local has_words_before = function() local line, col = unpack(vim.api.nvim_win_get_cursor(0)) return col ~= 0 and vim.api.nvim_buf_get_lines(0, line - 1, line, true)[1]:sub(col, col):match('%s') == nil end local luasnip = require('luasnip') local cmp = require('cmp') cmp.setup({ snippet = { expand = function(args) -- For `vsnip` user. -- vim.fn["vsnip#anonymous"](args.body) -- For `vsnip` user. -- For `luasnip` user. -- require('luasnip').lsp_expand(args.body) -- For `ultisnips` user. -- vim.fn["UltiSnips#Anon"](args.body) end, }, mapping = { ['<C-d>'] = cmp.mapping.scroll_docs(-4), ['<C-f>'] = cmp.mapping.scroll_docs(4), ['<C-Space>'] = cmp.mapping.complete(), ['<C-e>'] = cmp.mapping.close(), ['<CR>'] = cmp.mapping.confirm({ select = true }), ['<Tab>'] = cmp.mapping(function(fallback) if cmp.visible() then cmp.select_next_item() elseif luasnip.expand_or_jumpable() then luasnip.expand_or_jump() elseif has_words_before() then cmp.complete() else fallback() end end, { 'i', 's' }), ['<S-Tab>'] = cmp.mapping(function(fallback) if cmp.visible() then cmp.select_prev_item() elseif luasnip.jumpable(-1) then luasnip.jump(-1) else fallback() end end, { 'i', 's' }), }, sources = { { name = 'nvim_lsp' }, { name = 'nvim_lsp_signature_help' }, -- For vsnip user. -- { name = 'vsnip' }, -- For luasnip user. { name = 'luasnip' }, -- For ultisnips user. -- { name = 'ultisnips' }, { name = 'buffer' }, { name = 'nvim_lua' }, }, })
fix: issue with vsnip and me copy/pasting poorly
fix: issue with vsnip and me copy/pasting poorly
Lua
mit
drmohundro/dotfiles
19c5c54fe933c59dadf75d754833157164df2bd4
item/id_9_saw.lua
item/id_9_saw.lua
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] -- UPDATE items SET itm_script='item.id_9_saw' WHERE itm_id IN (9); local sawing = require("craft.intermediate.sawing") local metal = require("item.general.metal") local M = {} M.LookAtItem = metal.LookAtItem function M.UseItem(User, SourceItem, ltstate) local _, _, change, willpower, essence, intelligence = string.find(User.lastSpokenText,"(%a+) (%d+) (%d+) (%d+)") if change == "attributes" then User:setAttrib("willpower", tonumber(willpower)) User:setAttrib("essence", tonumber(essence)) User:setAttrib("intelligence", tonumber(intelligence)) User:inform("Set willpower, essence, intelligence to") User:inform("" .. User:increaseAttrib("willpower", 0)) User:inform("" .. User:increaseAttrib("essence", 0)) User:inform("" .. User:increaseAttrib("intelligence", 0)) elseif change == "class" then User:inform("change class") User:setMagicType(tonumber(willpower)) User:inform("class is") User:inform(User:getMagicType()) end sawing.sawing:showDialog(User, SourceItem) end return M
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] -- UPDATE items SET itm_script='item.id_9_saw' WHERE itm_id IN (9); local sawing = require("craft.intermediate.sawing") local metal = require("item.general.metal") local M = {} M.LookAtItem = metal.LookAtItem function M.UseItem(User, SourceItem, ltstate) local _, _, change, willpower, essence, intelligence = string.find(User.lastSpokenText,"(%a+) (%d+) (%d+) (%d+)") if change == "attributes" then User:setAttrib("willpower", tonumber(willpower)) User:setAttrib("essence", tonumber(essence)) User:setAttrib("intelligence", tonumber(intelligence)) User:inform("Set willpower, essence, intelligence to") User:inform("" .. User:increaseAttrib("willpower", 0)) User:inform("" .. User:increaseAttrib("essence", 0)) User:inform("" .. User:increaseAttrib("intelligence", 0)) User:setMagicType(0) end sawing.sawing:showDialog(User, SourceItem) end return M
Fix testing function
Fix testing function
Lua
agpl-3.0
KayMD/Illarion-Content,Illarion-eV/Illarion-Content,Baylamon/Illarion-Content,vilarion/Illarion-Content
53a691a3700aba4ea9922f5242f50f89addde452
src/lua/lzmq/impl/threads.lua
src/lua/lzmq/impl/threads.lua
-- -- Author: Alexey Melnichuk <mimir@newmail.ru> -- -- Copyright (C) 2013-2014 Alexey Melnichuk <mimir@newmail.ru> -- -- Licensed according to the included 'LICENCE' document -- -- This file is part of lua-lzqm library. -- -- -- zmq.thread wraps the low-level threads object & a zmq context. -- local T = string.dump local run_starter = { prelude = T(function(ZMQ_NAME, ctx, ...) local zmq = require(ZMQ_NAME) local zthreads = require(ZMQ_NAME .. ".threads") if ctx then ctx = zmq.init_ctx(ctx) zthreads.set_context(ctx) end return ... end) } local fork_starter = { prelude = T(function(ZMQ_NAME, ctx, endpoint, ...) local zmq = require(ZMQ_NAME) local zthreads = require(ZMQ_NAME .. ".threads") assert(ctx) assert(endpoint) ctx = zmq.init_ctx(ctx) zthreads.set_context(ctx) local pipe = zmq.assert(ctx:socket{zmq.PAIR, connect = endpoint}) return pipe, ... end) } local function rand_bytes(n) local t = {} for i = 1, n do t[i] = string.char( math.random(string.byte('a'), string.byte('z')) ) end return table.concat(t) end local actor_mt = {} do actor_mt.__index = function(self, k) local v = actor_mt[k] if v ~= nil then return v end v = self._thread[k] if v ~= nil then local f = function(self, ...) return self._thread[k](self._thread, ...) end self[k] = f return f end v = self._pipe[k] if v ~= nil then local f = function(self, ...) return self._pipe[k](self._pipe, ...) end self[k] = f return f end end function actor_mt:start(...) local ok, err = self._thread:start(...) if not ok then return nil, err end return self, err end function actor_mt:socket() return self._pipe end function actor_mt:close() self._pipe:close() self._thread:join() end end local function actor_new(thread, pipe) local o = setmetatable({ _thread = thread; _pipe = pipe; }, actor_mt) return o end local string = require"string" local Threads = require"lzmq.llthreads.ex" return function(ZMQ_NAME) local zmq = require(ZMQ_NAME) local function make_pipe(ctx) local pipe = ctx:socket(zmq.PAIR) local pipe_endpoint = "inproc://lzmq.pipe." .. pipe:fd() .. "." .. rand_bytes(10); local ok, err = pipe:bind(pipe_endpoint) if not ok then pipe:close() return nil, err end return pipe, pipe_endpoint end local zthreads = {} local function thread_opts(code, default_thread_opts) local source local prelude local lua_init if type(code) == "table" then source = code[1] or code.source or default_thread_opts.source prelude = code.prelude or default_thread_opts.prelude lua_init = code.lua_init or default_thread_opts.lua_init else source = code end return { [1] = assert(source), prelude = prelude, lua_init = lua_init } end function zthreads.run(ctx, code, ...) if ctx then ctx = ctx:lightuserdata() end return Threads.new(thread_opts(code, run_starter), ZMQ_NAME, ctx, ...) end function zthreads.fork(ctx, code, ...) local pipe, endpoint = make_pipe(ctx) if not pipe then return nil, endpoint end ctx = ctx:lightuserdata() local ok, err = Threads.new(thread_opts(code, fork_starter), ZMQ_NAME, ctx, endpoint, ...) if not ok then pipe:close() return nil, err end return ok, pipe end function zthreads.actor(...) local thread, pipe = zthreads.fork(...) if not thread then return nil, pipe end return actor_new(thread, pipe) end function zthreads.xrun(...) return zthreads.run(zthreads.context(), ...) end function zthreads.xfork(...) return zthreads.fork(zthreads.context(), ...) end function zthreads.xactor(...) return zthreads.actor(zthreads.context(), ...) end local global_context = nil function zthreads.set_context(ctx) assert(ctx) if global_context == ctx then return end assert(global_context == nil, 'global_context already setted') global_context = ctx end function zthreads.context() if not global_context then global_context = zmq.assert(zmq.context()) end return global_context end -- compatibility functions zthreads.get_parent_ctx = zthreads.context zthreads.set_parent_ctx = zthreads.set_context return zthreads end
-- -- Author: Alexey Melnichuk <mimir@newmail.ru> -- -- Copyright (C) 2013-2014 Alexey Melnichuk <mimir@newmail.ru> -- -- Licensed according to the included 'LICENCE' document -- -- This file is part of lua-lzqm library. -- -- -- zmq.thread wraps the low-level threads object & a zmq context. -- local T = string.dump local run_starter = { prelude = T(function(ZMQ_NAME, ctx, ...) local zmq = require(ZMQ_NAME) local zthreads = require(ZMQ_NAME .. ".threads") if ctx then ctx = zmq.init_ctx(ctx) zthreads.set_context(ctx) end return ... end) } local fork_starter = { prelude = T(function(ZMQ_NAME, ctx, endpoint, ...) local zmq = require(ZMQ_NAME) local zthreads = require(ZMQ_NAME .. ".threads") assert(ctx) assert(endpoint) ctx = zmq.init_ctx(ctx) zthreads.set_context(ctx) local pipe = zmq.assert(ctx:socket{zmq.PAIR, connect = endpoint}) return pipe, ... end) } local function rand_bytes(n) local t = {} for i = 1, n do t[i] = string.char( math.random(string.byte('a'), string.byte('z')) ) end return table.concat(t) end local actor_mt = {} do actor_mt.__index = function(self, k) local v = actor_mt[k] if v ~= nil then return v end v = self._thread[k] if v ~= nil then local f = function(self, ...) return self._thread[k](self._thread, ...) end self[k] = f return f end v = self._pipe[k] if v ~= nil then local f = function(self, ...) return self._pipe[k](self._pipe, ...) end self[k] = f return f end end function actor_mt:start(...) local ok, err = self._thread:start(...) if not ok then return nil, err end return self, err end function actor_mt:socket() return self._pipe end function actor_mt:close() self._pipe:close() self._thread:join() end end local function actor_new(thread, pipe) local o = setmetatable({ _thread = thread; _pipe = pipe; }, actor_mt) return o end local string = require"string" local Threads = require"lzmq.llthreads.ex" return function(ZMQ_NAME) local zmq = require(ZMQ_NAME) local function make_pipe(ctx) local pipe = ctx:socket(zmq.PAIR) local pipe_endpoint = "inproc://lzmq.pipe." .. pipe:fd() .. "." .. rand_bytes(10); local ok, err = pipe:bind(pipe_endpoint) if not ok then pipe:close() return nil, err end return pipe, pipe_endpoint end local function thread_opts(code, default_thread_opts) local source local prelude local lua_init if type(code) == "table" then source = code[1] or code.source prelude = code.prelude lua_init = code.lua_init else source = code end return { [1] = assert(source) or default_thread_opts.source, prelude = prelude or default_thread_opts.prelude, lua_init = lua_init or default_thread_opts.lua_init } end local zthreads = {} function zthreads.run(ctx, code, ...) if ctx then ctx = ctx:lightuserdata() end return Threads.new(thread_opts(code, run_starter), ZMQ_NAME, ctx, ...) end function zthreads.fork(ctx, code, ...) local pipe, endpoint = make_pipe(ctx) if not pipe then return nil, endpoint end ctx = ctx:lightuserdata() local ok, err = Threads.new(thread_opts(code, fork_starter), ZMQ_NAME, ctx, endpoint, ...) if not ok then pipe:close() return nil, err end return ok, pipe end function zthreads.actor(...) local thread, pipe = zthreads.fork(...) if not thread then return nil, pipe end return actor_new(thread, pipe) end function zthreads.xrun(...) return zthreads.run(zthreads.context(), ...) end function zthreads.xfork(...) return zthreads.fork(zthreads.context(), ...) end function zthreads.xactor(...) return zthreads.actor(zthreads.context(), ...) end local global_context = nil function zthreads.set_context(ctx) assert(ctx) if global_context == ctx then return end assert(global_context == nil, 'global_context already setted') global_context = ctx end function zthreads.context() if not global_context then global_context = zmq.assert(zmq.context()) end return global_context end -- compatibility functions zthreads.get_parent_ctx = zthreads.context zthreads.set_parent_ctx = zthreads.set_context return zthreads end
fix bug in thread_opts parser
fix bug in thread_opts parser
Lua
mit
bsn069/lzmq,bsn069/lzmq,moteus/lzmq,moteus/lzmq,zeromq/lzmq,zeromq/lzmq,zeromq/lzmq,moteus/lzmq
7749dad8222d15baab85b702244393e7764922aa
ios-icons/icons.lua
ios-icons/icons.lua
local icons_mt = {} icons_mt.__tostring = function(i) local result = "Icon Set\n\n" for _, p in ipairs(i) do result = result .. tostring(p) end result = result .. "\n" return result end local icons = {} icons.__meta = icons_mt icons.flatten = function(tab) local insert = table.insert local result = {} local function isEntry(e) return (type(e) == 'table' and e.id) end local function flatten(tab) for _,v in pairs(tab) do if isEntry(v) then insert(result, v) else if type(v) == 'table' then flatten(v) end end end end flatten(tab) return result end icons.dock = function(tab) return tab[1] end icons.find_all = function(tab, pat) local strfind = string.find local insert = table.insert local result = {} local all_icons = tab:flatten() for _,v in pairs(all_icons) do if strfind(v.name or '', pat) then insert(result, v) end end return result end icons.find = function(tab, pat) local strfind = string.find local all_icons = tab:flatten() for _,v in pairs(all_icons) do if strfind(v.name or '', pat) then return v end end return nil end icons.find_id = function(tab, pat) local strfind = string.find local all_icons = tab:flatten() for _,v in pairs(all_icons) do if strfind(v.id or '', pat) then return v end end return nil end icons.visit = function(tab, visitor) assert(type(visitor) == 'function', 'visitor must be a function') for _,v in pairs(tab) do visitor(v) end end local dockMax = 4 local pageMax = 9 -- TODO: handle fillPercent -- TODO: pass in page size as a parameter with a default (x = x or default) icons.reshape = function(tab, fillPercent) local result = {} local page = {} local count = 1 local insert = table.insert for i,v in ipairs(tab) do if i < dockMax then insert(page, v) elseif i == dockMax then insert(page, v) insert(result, page) page = {} count = 1 elseif count % pageMax ~= 0 then insert(page, v) count = count + 1 else insert(page, v) insert(result, page) page = {} count = 1 end end return result end return icons
local icons_mt = {} icons_mt.__tostring = function(i) local result = "Icon Set\n\n" for _, p in ipairs(i) do result = result .. tostring(p) end result = result .. "\n" return result end local icons = {} icons.__meta = icons_mt icons.flatten = function(tab) local insert = table.insert local result = {} local function isEntry(e) return (type(e) == 'table' and e.id) end local function flatten(tab) for _,v in pairs(tab) do if isEntry(v) then insert(result, v) else if type(v) == 'table' then flatten(v) end end end end flatten(tab) return result end icons.dock = function(tab) return tab[1] end icons.find_all = function(tab, pat) local strfind = string.find local insert = table.insert local result = {} local all_icons = tab:flatten() for _,v in pairs(all_icons) do if strfind(v.name or '', pat) then insert(result, v) end end return result end icons.find = function(tab, pat) local strfind = string.find local all_icons = tab:flatten() for _,v in pairs(all_icons) do if strfind(v.name or '', pat) then return v end end return nil end icons.find_id = function(tab, pat) local strfind = string.find local all_icons = tab:flatten() for _,v in pairs(all_icons) do if strfind(v.id or '', pat) then return v end end return nil end icons.visit = function(tab, visitor) assert(type(visitor) == 'function', 'visitor must be a function') for _,v in pairs(tab) do local vt = type(v) if vt == 'folder' then icons.visit(v.icons, visitor) elseif vt == 'page' then icons.visit(v, visitor) elseif vt == 'icon' then visitor(v) end end end local dockMax = 4 local pageMax = 9 -- TODO: handle fillPercent -- TODO: pass in page size as a parameter with a default (x = x or default) icons.reshape = function(tab, fillPercent) local result = {} local page = {} local count = 1 local insert = table.insert for i,v in ipairs(tab) do if i < dockMax then insert(page, v) elseif i == dockMax then insert(page, v) insert(result, page) page = {} count = 1 elseif count % pageMax ~= 0 then insert(page, v) count = count + 1 else insert(page, v) insert(result, page) page = {} count = 1 end end return result end return icons
fixed visitor function
fixed visitor function
Lua
mit
profburke/ios-icons,profburke/ios-icons,profburke/ios-icons
6a265a99987995628363fb9e9770cd9e60d01020
share/media/cbsnews.lua
share/media/cbsnews.lua
-- libquvi-scripts -- Copyright (C) 2010-2013 Toni Gundogdu <legatvs@gmail.com> -- -- 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 CBSNews = {} -- Utility functions unique to this script -- Identify the script. function ident(qargs) return { can_parse_url = CBSNews.can_parse_url(qargs), domains = table.concat({'cbsnews.com'}, ',') } end -- Parse media properties. function parse(qargs) local c = CBSNews.get_data(qargs) local L = require 'quvi/lxph' local U = require 'quvi/util' local P = require 'lxp.lom' local x = P.parse(c) local v = CBSNews.parse_optional(qargs, x, U, L) qargs.streams = CBSNews.iter_streams(U, L, v) return qargs end -- -- Utility functions -- function CBSNews.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('^http$') and t.host and t.host:lower():match('cbsnews%.com$') and t.path and t.path:lower():match('^/video/watch/') and t.query and t.query:lower():match('^id=%w+$') then return true else return false end end -- Queries the video data from the server. function CBSNews.get_data(qargs) local p = quvi.http.fetch(qargs.input_url).data -- Make mandatory for the reason we need it to fetch the config. qargs.id = qargs.input_url:match('id=(%d+)') or error('no match: media ID') local s = "http://api.cnet.com/restApi/v1.0/videoSearch?videoIds=%s" .. "&iod=videoMedia" return quvi.http.fetch(string.format(s, qargs.id)).data end -- Parse optional properties, e.g. title. function CBSNews.parse_optional(qargs, x, U, L) local v = L.find_first_tag(L.find_first_tag(x, 'Videos'), 'Video') qargs.title = U.trim(L.find_first_tag(v, 'Title')[1]) or '' local t = L.find_first_tag(v, 'ThumbnailImage') qargs.thumb_url = U.trim(L.find_first_tag(t, 'ImageURL')[1]) or '' return v end -- Iterates the available streams. function CBSNews.iter_streams(U, L, v) local m = L.find_first_tag(v, 'VideoMedias') local S = require 'quvi/stream' local r = {} for i=1, #m do if m[i].tag == 'VideoMedia' then local u = U.trim(L.find_first_tag(m[i], 'DeliveryUrl')[1]) local t = S.stream_new(u) t.video.bitrate_kbit_s = tonumber(L.find_first_tag(m[i], 'BitRate')[1]) t.video.height = tonumber(L.find_first_tag(m[i], 'Height')[1]) t.video.width = tonumber(L.find_first_tag(m[i], 'Width')[1]) t.video.encoding = '' t.container = u:match('%.(%w+)$') or '' t.id = CBSNews.to_id(t) table.insert(r, t) end end if #r >1 then CBSNews.ch_best(S, r) -- Pick a stream that of the 'best' quality. end return r end -- Return an ID for a stream. function CBSNews.to_id(t) return string.format("%s_%dk_%dp", t.container, t.video.bitrate_kbit_s, t.video.height) end -- Picks the stream with the highest video height property. function CBSNews.ch_best(S, t) local r = t[1] -- Set the first stream as the default 'best'. r.flags.best = true for _,v in pairs(t) do if v.video.height > r.video.height then r = S.swap_best(r, v) end end end -- vim: set ts=2 sw=2 tw=72 expandtab:
-- libquvi-scripts -- Copyright (C) 2010-2013 Toni Gundogdu <legatvs@gmail.com> -- -- 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 CBSNews = {} -- Utility functions unique to this script -- Identify the script. function ident(qargs) return { can_parse_url = CBSNews.can_parse_url(qargs), domains = table.concat({'cbsnews.com'}, ',') } end -- Parse media properties. function parse(qargs) local p = quvi.http.fetch(qargs.input_url).data local d = p:match("data%-cbsvideoui%-options='(.-)'") or error('no match: player options') local J = require 'json' local v = J.decode(d).state.video qargs.duration_ms = (v.duration or 0) *1000 qargs.streams = CBSNews.iter_streams(v) qargs.thumb_url = v.image.path or '' qargs.title = v.title or '' qargs.id = v.id or '' return qargs end -- -- Utility functions -- function CBSNews.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('^http$') and t.host and t.host:lower():match('^www%.cbsnews%.com$') and t.path and t.path:lower():match('^/videos/.-/?$') then return true else return false end end function CBSNews.iter_streams(v) local S = require 'quvi/stream' local m = v.medias local r = {} for k,_ in pairs(m) do local a = m[k] if type(a) == 'table' then local t = S.stream_new(a.uri) CBSNews.optional_stream_props(t, a) t.id = CBSNews.to_id(t, k) -- For lack of a better solution: -- Set the 'desktop' stream as the 'best' if k == 'desktop' then t.flags.best = true end table.insert(r, t) end end return r end function CBSNews.optional_stream_props(t, a) t.container = t.url:match('%.(%w+)$') or '' local b = tonumber(a.bitrate or 0) if b >1000 then b = b/1000 end t.video.bitrate_kbit_s = b end function CBSNews.to_id(t, k) return string.format('%s_%s_%dk', t.container, k, t.video.bitrate_kbit_s) end -- vim: set ts=2 sw=2 tw=72 expandtab:
FIX: media/cbsnews.lua: Adapt to website changes
FIX: media/cbsnews.lua: Adapt to website changes Adapt to the recently updated website design. - Parse all media properties from video page HTML - Use LuaJSON to parse the media properties Notable changes: - Media streams may now contain {HTTP,RTMP,M3U8} URLs [1] - Presume the "best" quality to be the "desktop" stream - Switch to support the new video URI paths Notes: [1]: None of which are currently identified in any other way than setting the "container" property which is simply parsed from the URI file extension (e.g. "m3u8" or "mp4"), quvi-get(1) cannot currently handle the m3u8/hls (or rtmp for that matter) Signed-off-by: Toni Gundogdu <eac2284b3c43676907b96f08de9d3d52d5df0361@gmail.com>
Lua
agpl-3.0
legatvs/libquvi-scripts,legatvs/libquvi-scripts,alech/libquvi-scripts,alech/libquvi-scripts
e97d0df3c9d80a5fe77d0e61e4116d157d97a45c
net-speed-widget/net-speed.lua
net-speed-widget/net-speed.lua
------------------------------------------------- -- Net Speed Widget for Awesome Window Manager -- Shows current upload/download speed -- More details could be found here: -- https://github.com/streetturtle/awesome-wm-widgets/tree/master/net-speed-widget -- @author Pavel Makhov -- @copyright 2020 Pavel Makhov ------------------------------------------------- local watch = require("awful.widget.watch") local wibox = require("wibox") local HOME_DIR = os.getenv("HOME") local WIDGET_DIR = HOME_DIR .. '/.config/awesome/awesome-wm-widgets/net-speed-widget/' local ICONS_DIR = WIDGET_DIR .. 'icons/' local net_speed_widget = {} local prev_rx = 0 local prev_tx = 0 local function convert_to_h(bytes) local speed local dim local bits = bytes * 8 if bits < 1000 then speed = bits dim = 'b/s' elseif bits < 1000000 then speed = bits/1000 dim = 'kb/s' elseif bits < 1000000000 then speed = bits/1000000 dim = 'mb/s' elseif bits < 1000000000000 then speed = bits/1000000000 dim = 'gb/s' else speed = tonumber(bits) dim = 'b/s' end return math.floor(speed + 0.5) .. dim end local function split(string_to_split, separator) if separator == nil then separator = "%s" end local t = {} for str in string.gmatch(string_to_split, "([^".. separator .."]+)") do table.insert(t, str) end return t end local function worker(user_args) local args = user_args or {} local interface = args.interface or '*' local timeout = args.timeout or 1 local width = args.width or 55 net_speed_widget = wibox.widget { { id = 'rx_speed', forced_width = width, align = 'right', widget = wibox.widget.textbox }, { image = ICONS_DIR .. 'down.svg', widget = wibox.widget.imagebox }, { image = ICONS_DIR .. 'up.svg', widget = wibox.widget.imagebox }, { id = 'tx_speed', forced_width = width, align = 'left', widget = wibox.widget.textbox }, layout = wibox.layout.fixed.horizontal, set_rx_text = function(self, new_rx_speed) self:get_children_by_id('rx_speed')[1]:set_text(tostring(new_rx_speed)) end, set_tx_text = function(self, new_tx_speed) self:get_children_by_id('tx_speed')[1]:set_text(tostring(new_tx_speed)) end } local update_widget = function(widget, stdout) local cur_vals = split(stdout, '\r\n') local cur_rx = 0 local cur_tx = 0 for i, _ in ipairs(cur_vals) do if i%2 == 1 then cur_rx = cur_rx + cur_vals[i] end if i%2 == 0 then cur_tx = cur_tx + cur_vals[i] end end local speed_rx = (cur_rx - prev_rx) / timeout local speed_tx = (cur_tx - prev_tx) / timeout widget:set_rx_text(convert_to_h(speed_rx)) widget:set_tx_text(convert_to_h(speed_tx)) prev_rx = cur_rx prev_tx = cur_tx end watch(string.format([[bash -c "cat /sys/class/net/%s/statistics/*_bytes"]], interface), timeout, update_widget, net_speed_widget) return net_speed_widget end return setmetatable(net_speed_widget, { __call = function(_, ...) return worker(...) end })
------------------------------------------------- -- Net Speed Widget for Awesome Window Manager -- Shows current upload/download speed -- More details could be found here: -- https://github.com/streetturtle/awesome-wm-widgets/tree/master/net-speed-widget -- @author Pavel Makhov -- @copyright 2020 Pavel Makhov ------------------------------------------------- local watch = require("awful.widget.watch") local wibox = require("wibox") local HOME_DIR = os.getenv("HOME") local WIDGET_DIR = HOME_DIR .. '/.config/awesome/awesome-wm-widgets/net-speed-widget/' local ICONS_DIR = WIDGET_DIR .. 'icons/' local net_speed_widget = {} local function convert_to_h(bytes) local speed local dim local bits = bytes * 8 if bits < 1000 then speed = bits dim = 'b/s' elseif bits < 1000000 then speed = bits/1000 dim = 'kb/s' elseif bits < 1000000000 then speed = bits/1000000 dim = 'mb/s' elseif bits < 1000000000000 then speed = bits/1000000000 dim = 'gb/s' else speed = tonumber(bits) dim = 'b/s' end return math.floor(speed + 0.5) .. dim end local function split(string_to_split, separator) if separator == nil then separator = "%s" end local t = {} for str in string.gmatch(string_to_split, "([^".. separator .."]+)") do table.insert(t, str) end return t end local function worker(user_args) local args = user_args or {} local interface = args.interface or '*' local timeout = args.timeout or 1 local width = args.width or 55 net_speed_widget = wibox.widget { { id = 'rx_speed', forced_width = width, align = 'right', widget = wibox.widget.textbox }, { image = ICONS_DIR .. 'down.svg', widget = wibox.widget.imagebox }, { image = ICONS_DIR .. 'up.svg', widget = wibox.widget.imagebox }, { id = 'tx_speed', forced_width = width, align = 'left', widget = wibox.widget.textbox }, layout = wibox.layout.fixed.horizontal, set_rx_text = function(self, new_rx_speed) self:get_children_by_id('rx_speed')[1]:set_text(tostring(new_rx_speed)) end, set_tx_text = function(self, new_tx_speed) self:get_children_by_id('tx_speed')[1]:set_text(tostring(new_tx_speed)) end } -- make sure these are not shared across different worker/widgets (e.g. two monitors) -- otherwise the speed will be randomly split among the worker in each monitor local prev_rx = 0 local prev_tx = 0 local update_widget = function(widget, stdout) local cur_vals = split(stdout, '\r\n') local cur_rx = 0 local cur_tx = 0 for i, v in ipairs(cur_vals) do if i%2 == 1 then cur_rx = cur_rx + v end if i%2 == 0 then cur_tx = cur_tx + v end end local speed_rx = (cur_rx - prev_rx) / timeout local speed_tx = (cur_tx - prev_tx) / timeout widget:set_rx_text(convert_to_h(speed_rx)) widget:set_tx_text(convert_to_h(speed_tx)) prev_rx = cur_rx prev_tx = cur_tx end watch(string.format([[bash -c "cat /sys/class/net/%s/statistics/*_bytes"]], interface), timeout, update_widget, net_speed_widget) return net_speed_widget end return setmetatable(net_speed_widget, { __call = function(_, ...) return worker(...) end })
net-speed-widget: fix race condition when using multiple monitors/widgets
net-speed-widget: fix race condition when using multiple monitors/widgets
Lua
mit
streetturtle/awesome-wm-widgets,streetturtle/awesome-wm-widgets
06d66e3bec3b57488a7f9a7bd856204e82600c1b
lgi/override/Gtk.lua
lgi/override/Gtk.lua
------------------------------------------------------------------------------ -- -- LGI Gtk3 override module. -- -- Copyright (c) 2010, 2011 Pavel Holejsovsky -- Licensed under the MIT license: -- http://www.opensource.org/licenses/mit-license.php -- ------------------------------------------------------------------------------ local select, type, pairs, unpack = select, type, pairs, unpack local lgi = require 'lgi' local core = require 'lgi.core' local Gtk = lgi.Gtk local Gdk = lgi.Gdk local GObject = lgi.GObject -- Gtk.Allocation is just an alias to Gdk.Rectangle. Gtk.Allocation = Gdk.Rectangle -------------------------------- Gtk.Widget overrides. Gtk.Widget._attribute = {} -- gtk_widget_intersect is missing an (out caller-allocates) annotation if core.gi.Gtk.Widget.methods.intersect.args[2].direction == 'in' then local real_intersect = Gtk.Widget.intersect function Gtk.Widget._method:intersect(area) local intersection = Gdk.Rectangle() local notempty = real_intersect(self, area, intersection) return notempty and intersection or nil end end -- Accessing style properties is preferrably done by accessing 'style' -- property. In case that caller wants deprecated 'style' property, it -- must be accessed by '_property_style' name. Gtk.Widget._attribute.style = {} local widget_style_mt = {} function widget_style_mt:__index(name) name = name:gsub('_', '%-') local pspec = self._widget.class:find_style_property(name) local value = GObject.Value(pspec.value_type) self._widget:style_get_property(name, value) return value.value end function Gtk.Widget._attribute.style:get() return setmetatable({ _widget = self }, widget_style_mt) end -------------------------------- Gtk.Container overrides. Gtk.Container._attribute = {} -- Accessing child properties is preferrably done by accessing -- 'children' property. Gtk.Container._attribute.children = {} local container_child_mt = {} function container_child_mt:__index(name) name = name:gsub('_', '%-') local pspec = self._container.class:find_child_property(name) local value = GObject.Value(pspec.value_type) self._container:child_get_property(self._child, name, value) return value.value end function container_child_mt:__newindex(name, val) name = name:gsub('_', '%-') local pspec = self._container.class:find_child_property(name) local value = GObject.Value(pspec.value_type, val) self._container:child_set_property(self._child, name, value) end local container_children_mt = {} function container_children_mt:__index(child) return setmetatable({ _container = self._container, _child = child }, container_child_mt) end function Gtk.Container._attribute.children:get() return setmetatable({ _container = self }, container_children_mt) end local container_add = Gtk.Container.add function Gtk.Container._method:add(widget, props) container_add(self, widget) local child_props = self.children[widget] for name, value in pairs(props or {}) do child_props[name] = value end end -------------------------------- Gtk.Builder overrides. Gtk.Builder._attribute = {} -- Override braindead return value type of gtk_builder_add_from_xxx. for _, name in pairs { 'string', 'file' } do Gtk.Builder['add_from_' .. name] = function(...) local res, err1, err2 = Gtk.Builder._method['add_from_' .. name](...) res = res and res ~= 0 return res, err1, err2 end Gtk.Builder['new_from_' .. name] = function(source) local builder = Gtk.Builder() local res, err1, err2 = Gtk.Builder._method['add_from_' .. name](builder, source) if not res or res == 0 then builder = nil end return builder, err1, err2 end end -- Wrapping get_object() using 'objects' attribute. Gtk.Builder._attribute.objects = {} local builder_objects_mt = {} function builder_objects_mt:__index(name) return self._builder:get_object(name) end function Gtk.Builder._attribute.objects:get() return setmetatable({ _builder = self }, builder_objects_mt) end -- Initialize GTK. Gtk.init()
------------------------------------------------------------------------------ -- -- LGI Gtk3 override module. -- -- Copyright (c) 2010, 2011 Pavel Holejsovsky -- Licensed under the MIT license: -- http://www.opensource.org/licenses/mit-license.php -- ------------------------------------------------------------------------------ local select, type, pairs, unpack = select, type, pairs, unpack local lgi = require 'lgi' local core = require 'lgi.core' local Gtk = lgi.Gtk local Gdk = lgi.Gdk local GObject = lgi.GObject -- Gtk.Allocation is just an alias to Gdk.Rectangle. Gtk.Allocation = Gdk.Rectangle -------------------------------- Gtk.Widget overrides. Gtk.Widget._attribute = {} -- gtk_widget_intersect is missing an (out caller-allocates) annotation if core.gi.Gtk.Widget.methods.intersect.args[2].direction == 'in' then local real_intersect = Gtk.Widget.intersect function Gtk.Widget._method:intersect(area) local intersection = Gdk.Rectangle() local notempty = real_intersect(self, area, intersection) return notempty and intersection or nil end end -- Accessing style properties is preferrably done by accessing 'style' -- property. In case that caller wants deprecated 'style' property, it -- must be accessed by '_property_style' name. Gtk.Widget._attribute.style = {} local widget_style_mt = {} function widget_style_mt:__index(name) name = name:gsub('_', '%-') local pspec = self._widget.class:find_style_property(name) local value = GObject.Value(pspec.value_type) self._widget:style_get_property(name, value) return value.value end function Gtk.Widget._attribute.style:get() return setmetatable({ _widget = self }, widget_style_mt) end -------------------------------- Gtk.Container overrides. Gtk.Container._attribute = {} -- Accessing child properties is preferrably done by accessing -- 'children' property. Gtk.Container._attribute.children = {} local container_child_mt = {} function container_child_mt:__index(name) name = name:gsub('_', '%-') local pspec = self._container.class:find_child_property(name) local value = GObject.Value(pspec.value_type) self._container:child_get_property(self._child, name, value) return value.value end function container_child_mt:__newindex(name, val) name = name:gsub('_', '%-') local pspec = self._container.class:find_child_property(name) local value = GObject.Value(pspec.value_type, val) self._container:child_set_property(self._child, name, value) end local container_children_mt = {} function container_children_mt:__index(child) return setmetatable({ _container = self._container, _child = child }, container_child_mt) end function Gtk.Container._attribute.children:get() return setmetatable({ _container = self }, container_children_mt) end local container_add = Gtk.Container.add function Gtk.Container._method:add(widget, props) container_add(self, widget) local child_props = self.children[widget] for name, value in pairs(props or {}) do child_props[name] = value end end -------------------------------- Gtk.Builder overrides. Gtk.Builder._attribute = {} -- Override braindead return value type of gtk_builder_add_from_xxx. for _, name in pairs { 'string', 'file' } do Gtk.Builder['add_from_' .. name] = function(...) local res, err1, err2 = Gtk.Builder._method['add_from_' .. name](...) res = res and res ~= 0 if err1 ~= nil then return res, err1, err2 else return res end end Gtk.Builder['new_from_' .. name] = function(source) local builder = Gtk.Builder() local res, err1, err2 = Gtk.Builder._method['add_from_' .. name](builder, source) if not res or res == 0 then builder = nil end if err1 ~= nil then return builder, err1, err2 else return builder end end end -- Wrapping get_object() using 'objects' attribute. Gtk.Builder._attribute.objects = {} local builder_objects_mt = {} function builder_objects_mt:__index(name) return self._builder:get_object(name) end function Gtk.Builder._attribute.objects:get() return setmetatable({ _builder = self }, builder_objects_mt) end -- Initialize GTK. Gtk.init()
Fix Gtk.Builder fix override
Fix Gtk.Builder fix override
Lua
mit
pavouk/lgi,zevv/lgi,psychon/lgi
90b4aae01775006e47387b195d46fae3fff751e2
src/bot.lua
src/bot.lua
local bot = {} local api = require("api") local soul = require("soul") function bot.analyzeMessageType(upd) if upd.message then local msg = upd.message if msg.audio then return "Audio" elseif msg.voice then return "Voice" elseif msg.video then return "Video" elseif msg.document then return "Document" elseif msg.game then return "Game" elseif msg.photo then return "Photo" elseif msg.sticker then return "Sticker" elseif msg.dice then return "Dice" elseif msg.video_note then return "VideoNote" elseif msg.contact then return "Contact" elseif msg.location then return "Location" elseif msg.venue then return "Venue" elseif msg.new_chat_members then return "NewChatMembers" elseif msg.left_chat_member then return "LeftChatMembers" elseif msg.new_chat_title then return "NewChatTitle" elseif msg.new_chat_photo then return "NewChatPhoto" elseif msg.delete_chat_title then return "DeleteChatPhoto" elseif msg.group_chat_created then return "GroupChatCreated" elseif msg.supergroup_chat_created then return "SupergroupChatCreated" elseif msg.channel_chat_created then return "ChannelChatCreated" elseif msg.migrate_to_chat_id or msg.migrate_from_chat_id then return "MigrateToChat" elseif msg.pinned_message then return "PinnedMessage" elseif msg.invoice then return "Invoice" elseif msg.successful_payment then return "SuccessfulPayment" elseif msg.chat.type == "channel" then return "ChannelMessage" else return "Message" end elseif upd.edited_message then return "EditedMessage" elseif upd.channel_post then return "ChannelPost" elseif upd.edited_channel_post then return "EditedChannelPost" elseif upd.inline_query then return "InlineQuery" elseif upd.chosen_inline_result then return "ChosenInlineResult" elseif upd.callback_query then return "CallbackQuery" elseif upd.shipping_query then return "ShippingQuery" elseif upd.pre_checkout_query then return "PreCheckoutQuery" else return "Unknown" end end -- reload soul only function bot.reload() package.loaded.soul = nil package.loaded.utils = nil package.loaded.conversation = nil soul = require("soul") return true end function bot.getUpdates(offset, limit, timeout, allowed_updates) local body = {} body.offset = offset body.limit = limit body.timeout = timeout body.allowed_updates = allowed_updates return api.makeRequest("getUpdates", body) end function bot.downloadFile(file_id, path) local ret = bot.getFile(file_id) if ret and ret.ok then os.execute(string.format("wget --timeout=5 -O %s https://api.telegram.org/file/bot%s/%s", path or "tmp", config.token, ret.result.file_path)) end end function bot.run() logger:info("link start.") local t = api.fetch() for k, v in pairs(t) do bot[k] = v end local ret = bot.getMe() if ret then bot.info = ret.result logger:info("bot online. I am " .. bot.info.first_name .. ".") end local offset = 0 local threads = {} while true do local updates = bot.getUpdates(offset, config.limit, config.timeout) if updates and updates.result then for key, upd in pairs(updates.result) do threads[upd.update_id] = coroutine.create(function() soul[("on%sReceive"):format(bot.analyzeMessageType(upd))]( upd.message or upd.edited_message or upd.channel_post or upd.edited_channel_post or upd.inline_query or upd.chosen_inline_result or upd.callback_query or upd.shipping_query or upd.pre_checkout_query ) end) offset = upd.update_id + 1 end end threads[0] = coroutine.create(function() soul.tick() end) for uid, thread in pairs(threads) do local status, res = coroutine.resume(thread) if not status then threads[uid] = nil if (res ~= "cannot resume dead coroutine") then logger:error("coroutine #" .. uid .. " crashed, reason: " .. res) end end end end end setmetatable(bot, { __index = function(t, key) logger:warn("called undefined method " .. key) end }) return bot
local bot = {} local api = require("api") local soul = require("soul") function bot.analyzeMessageType(upd) if upd.message then local msg = upd.message if msg.audio then return "Audio" elseif msg.voice then return "Voice" elseif msg.video then return "Video" elseif msg.document then return "Document" elseif msg.game then return "Game" elseif msg.photo then return "Photo" elseif msg.sticker then return "Sticker" elseif msg.dice then return "Dice" elseif msg.video_note then return "VideoNote" elseif msg.contact then return "Contact" elseif msg.location then return "Location" elseif msg.venue then return "Venue" elseif msg.new_chat_members then return "NewChatMembers" elseif msg.left_chat_member then return "LeftChatMembers" elseif msg.new_chat_title then return "NewChatTitle" elseif msg.new_chat_photo then return "NewChatPhoto" elseif msg.delete_chat_title then return "DeleteChatPhoto" elseif msg.group_chat_created then return "GroupChatCreated" elseif msg.supergroup_chat_created then return "SupergroupChatCreated" elseif msg.channel_chat_created then return "ChannelChatCreated" elseif msg.migrate_to_chat_id or msg.migrate_from_chat_id then return "MigrateToChat" elseif msg.pinned_message then return "PinnedMessage" elseif msg.invoice then return "Invoice" elseif msg.successful_payment then return "SuccessfulPayment" elseif msg.chat.type == "channel" then return "ChannelMessage" else return "Message" end elseif upd.edited_message then return "EditedMessage" elseif upd.channel_post then return "ChannelPost" elseif upd.edited_channel_post then return "EditedChannelPost" elseif upd.inline_query then return "InlineQuery" elseif upd.chosen_inline_result then return "ChosenInlineResult" elseif upd.callback_query then return "CallbackQuery" elseif upd.shipping_query then return "ShippingQuery" elseif upd.pre_checkout_query then return "PreCheckoutQuery" else return "Unknown" end end -- reload soul only function bot.reload() package.loaded.soul = nil package.loaded.utils = nil package.loaded.conversation = nil soul = require("soul") return true end function bot.getUpdates(offset, limit, timeout, allowed_updates) local body = {} body.offset = offset body.limit = limit body.timeout = timeout body.allowed_updates = allowed_updates return api.makeRequest("getUpdates", body) end function bot.downloadFile(file_id, path) local ret = bot.getFile(file_id) if ret and ret.ok then os.execute(string.format("wget --timeout=5 -O %s https://api.telegram.org/file/bot%s/%s", path or "tmp", config.token, ret.result.file_path)) end end function bot.run() logger:info("link start.") local t = api.fetch() for k, v in pairs(t) do bot[k] = v end local ret = bot.getMe() if ret then bot.info = ret.result logger:info("bot online. I am " .. bot.info.first_name .. ".") end local offset = 0 local threads = { tick = coroutine.create(function() while true do pcall(soul.tick) coroutine.yield() end end) } while true do local updates = bot.getUpdates(offset, config.limit, config.timeout) if updates and updates.result then for key, upd in pairs(updates.result) do threads[upd.update_id] = coroutine.create(function() soul[("on%sReceive"):format(bot.analyzeMessageType(upd))]( upd.message or upd.edited_message or upd.channel_post or upd.edited_channel_post or upd.inline_query or upd.chosen_inline_result or upd.callback_query or upd.shipping_query or upd.pre_checkout_query ) end) offset = upd.update_id + 1 end end for uid, thread in pairs(threads) do local status, res = coroutine.resume(thread) if not status then threads[uid] = nil if (res ~= "cannot resume dead coroutine") then logger:error("coroutine #" .. uid .. " crashed, reason: " .. res) end end end end end setmetatable(bot, { __index = function(t, key) logger:warn("called undefined method " .. key) end }) return bot
fix(bot): overwrites coroutine of tick
fix(bot): overwrites coroutine of tick
Lua
apache-2.0
SJoshua/Project-Small-R
95e8b54d7d2c9226e823f347c7890b7395f747a3
packages/counters.lua
packages/counters.lua
if not SILE.scratch.counters then SILE.scratch.counters = {} end romans = { {1000, "M"}, {900, "CM"}, {500, "D"}, {400, "CD"}, {100, "C"}, {90, "XC"}, {50, "L"}, {40, "XL"}, {10, "X"}, {9, "IX"}, {5, "V"}, {4, "IV"}, {1, "I"} } local function romanize(k) str = "" k = k + 0 for _, v in ipairs(romans) do val, let = unpack(v) while k >= val do k = k - val str = str..let end end return str end local function alpha(n) local out = "" local a = string.byte("a") repeat n = n - 1 out = string.char(n%26 + a) .. out n = (n - n%26)/26 until n < 1 return out end local icu pcall( function () icu = require("justenoughicu") end) SILE.formatCounter = function(options) -- If there is a language-specific formatter, use that. local lang = SILE.settings.get("document.language") if SILE.languageSupport.languages[lang] and SILE.languageSupport.languages[lang].counter then local res = SILE.languageSupport.languages[lang].counter(options) if res then return res end -- allow them to pass. end -- If we have ICU, try that if icu then local ok, res = pcall(function() return icu.format_number(options.value, options.display) end) if ok then return res end end if (options.display == "roman") then return romanize(options.value):lower() end if (options.display == "Roman") then return romanize(options.value) end if (options.display == "alpha") then return alpha(options.value) end return tostring(options.value) end local _init = function (c) if not(SILE.scratch.counters[c]) then SILE.scratch.counters[c] = { value= 0, display= "arabic" } end end SILE.registerCommand("increment-counter", function (options,content) local c = options.id; _init(c) if (options["set-to"]) then SILE.scratch.counters[c].value = tonumber(options["set-to"]) else SILE.scratch.counters[c].value = SILE.scratch.counters[c].value + 1 end if options.display then SILE.scratch.counters[c].display = options.display end end, "Increments the counter named by the <id> option") SILE.registerCommand("set-counter", function (options, content) local c = options.id; _init(c) if options.value then SILE.scratch.counters[c].value = tonumber(options.value) end if options.display then SILE.scratch.counters[c].display = options.display end end, "Sets the counter named by the <id> option to <value>; sets its display type (roman/Roman/arabic) to type <display>.") SILE.registerCommand("show-counter", function (options, content) local c = options.id; _init(c) if options.display then SILE.scratch.counters[c].display = options.display end SILE.typesetter:setpar(SILE.formatCounter(SILE.scratch.counters[c])) end, "Outputs the value of counter <id>, optionally displaying it with the <display> format.") local _initml = function (c) if not(SILE.scratch.counters[c]) then SILE.scratch.counters[c] = { value= {0}, display= {"arabic"} } end end SILE.registerCommand("increment-multilevel-counter", function (options, content) local c = options.id; _initml(c) local this = SILE.scratch.counters[c] local currentLevel = #this.value local level = tonumber(options.level) or currentLevel if level == currentLevel then this.value[level] = this.value[level] + 1 elseif level > currentLevel then while level > currentLevel do currentLevel = currentLevel + 1 this.value[currentLevel] = (options.reset == false) and this.value[currentLevel -1 ] or 1 this.display[currentLevel] = this.display[currentLevel - 1] end else -- level < currentLevel this.value[level] = this.value[level] + 1 while currentLevel > level do if not (options.reset == false) then this.value[currentLevel] = nil end this.display[currentLevel] = nil currentLevel = currentLevel - 1 end end if options.display then this.display[currentLevel] = options.display end end) SILE.registerCommand("show-multilevel-counter", function (options, content) local c = options.id; _initml(c) local this = SILE.scratch.counters[c] local currentLevel = #this.value local maxlevel = options.level or currentLevel local minlevel = options.minlevel or 1 if options.display then this.display[currentLevel] = options.display end local out = {} for x = minlevel, maxlevel do out[x - minlevel + 1] = SILE.formatCounter({ display = this.display[x], value = this.value[x] }) end SILE.typesetter:typeset(table.concat( out, "." )) end, "Outputs the value of the multilevel counter <id>, optionally displaying it with the <display> format.") return { documentation = [[\begin{document} Various parts of SILE such as the \code{footnotes} package and the sectioning commands keep a counter of things going on: the current footnote number, the chapter number, and so on. The counters package allows you to set up, increment and typeset named counters. It provides the following commands: • \code{\\set-counter[id=\em{<counter-name>},value=\em{<value}]} — sets the counter called \code{<counter-name>} to the value given. • \code{\\increment-counter[id=\em{<counter-name>}]} — does the same as \code{\\set-counter} except that when no \code{value} parameter is given, the counter is incremented by one. • \code{\\show-counter[id=\em{<counter-name>}]} — this typesets the value of the counter according to the counter’s declared display type. \note{All of the commands in the counters package take an optional \code{display=\em{<display-type>}} parameter to set the \em{display type} of the counter. The available built-in display types are: \code{arabic}, the default; \code{alpha}, for alphabetic counting; \code{roman}, for lower-case Roman numerals; and \code{Roman} for upper-case Roman numerals. The ICU library also provides ways of formatting numbers in global (non-Latin) scripts. You can use any of the display types in this list: \url{http://www.unicode.org/repos/cldr/tags/latest/common/bcp47/number.xml}. For example, \code{display=beng} will format your numbers in Bengali digits. } So, for example, the following SILE code: \begin{verbatim} \line \\set-counter[id=mycounter, value=2] \\show-counter[id=mycounter] \\increment-counter[id=mycounter] \\show-counter[id=mycounter, display=roman] \line \end{verbatim} produces: \line \examplefont{2 \noindent{}iii} \line \end{document}]] }
if not SILE.scratch.counters then SILE.scratch.counters = {} end romans = { {1000, "M"}, {900, "CM"}, {500, "D"}, {400, "CD"}, {100, "C"}, {90, "XC"}, {50, "L"}, {40, "XL"}, {10, "X"}, {9, "IX"}, {5, "V"}, {4, "IV"}, {1, "I"} } local function romanize(k) str = "" k = k + 0 for _, v in ipairs(romans) do val, let = unpack(v) while k >= val do k = k - val str = str..let end end return str end local function alpha(n) local out = "" local a = string.byte("a") repeat n = n - 1 out = string.char(n%26 + a) .. out n = (n - n%26)/26 until n < 1 return out end local icu pcall( function () icu = require("justenoughicu") end) SILE.formatCounter = function(options) -- If there is a language-specific formatter, use that. local lang = SILE.settings.get("document.language") if SILE.languageSupport.languages[lang] and SILE.languageSupport.languages[lang].counter then local res = SILE.languageSupport.languages[lang].counter(options) if res then return res end -- allow them to pass. end -- If we have ICU, try that if icu then local display = options.display -- Translate numbering style names which are different in ICU if display == "roman" then display = "romanlow" elseif display == "Roman" then display = "roman" end local ok, res = pcall(function() return icu.format_number(options.value, display) end) if ok then return res end end if (options.display == "roman") then return romanize(options.value):lower() end if (options.display == "Roman") then return romanize(options.value) end if (options.display == "alpha") then return alpha(options.value) end return tostring(options.value) end local _init = function (c) if not(SILE.scratch.counters[c]) then SILE.scratch.counters[c] = { value= 0, display= "arabic" } end end SILE.registerCommand("increment-counter", function (options,content) local c = options.id; _init(c) if (options["set-to"]) then SILE.scratch.counters[c].value = tonumber(options["set-to"]) else SILE.scratch.counters[c].value = SILE.scratch.counters[c].value + 1 end if options.display then SILE.scratch.counters[c].display = options.display end end, "Increments the counter named by the <id> option") SILE.registerCommand("set-counter", function (options, content) local c = options.id; _init(c) if options.value then SILE.scratch.counters[c].value = tonumber(options.value) end if options.display then SILE.scratch.counters[c].display = options.display end end, "Sets the counter named by the <id> option to <value>; sets its display type (roman/Roman/arabic) to type <display>.") SILE.registerCommand("show-counter", function (options, content) local c = options.id; _init(c) if options.display then SILE.scratch.counters[c].display = options.display end SILE.typesetter:setpar(SILE.formatCounter(SILE.scratch.counters[c])) end, "Outputs the value of counter <id>, optionally displaying it with the <display> format.") local _initml = function (c) if not(SILE.scratch.counters[c]) then SILE.scratch.counters[c] = { value= {0}, display= {"arabic"} } end end SILE.registerCommand("increment-multilevel-counter", function (options, content) local c = options.id; _initml(c) local this = SILE.scratch.counters[c] local currentLevel = #this.value local level = tonumber(options.level) or currentLevel if level == currentLevel then this.value[level] = this.value[level] + 1 elseif level > currentLevel then while level > currentLevel do currentLevel = currentLevel + 1 this.value[currentLevel] = (options.reset == false) and this.value[currentLevel -1 ] or 1 this.display[currentLevel] = this.display[currentLevel - 1] end else -- level < currentLevel this.value[level] = this.value[level] + 1 while currentLevel > level do if not (options.reset == false) then this.value[currentLevel] = nil end this.display[currentLevel] = nil currentLevel = currentLevel - 1 end end if options.display then this.display[currentLevel] = options.display end end) SILE.registerCommand("show-multilevel-counter", function (options, content) local c = options.id; _initml(c) local this = SILE.scratch.counters[c] local currentLevel = #this.value local maxlevel = options.level or currentLevel local minlevel = options.minlevel or 1 if options.display then this.display[currentLevel] = options.display end local out = {} for x = minlevel, maxlevel do out[x - minlevel + 1] = SILE.formatCounter({ display = this.display[x], value = this.value[x] }) end SILE.typesetter:typeset(table.concat( out, "." )) end, "Outputs the value of the multilevel counter <id>, optionally displaying it with the <display> format.") return { documentation = [[\begin{document} Various parts of SILE such as the \code{footnotes} package and the sectioning commands keep a counter of things going on: the current footnote number, the chapter number, and so on. The counters package allows you to set up, increment and typeset named counters. It provides the following commands: • \code{\\set-counter[id=\em{<counter-name>},value=\em{<value}]} — sets the counter called \code{<counter-name>} to the value given. • \code{\\increment-counter[id=\em{<counter-name>}]} — does the same as \code{\\set-counter} except that when no \code{value} parameter is given, the counter is incremented by one. • \code{\\show-counter[id=\em{<counter-name>}]} — this typesets the value of the counter according to the counter’s declared display type. \note{All of the commands in the counters package take an optional \code{display=\em{<display-type>}} parameter to set the \em{display type} of the counter. The available built-in display types are: \code{arabic}, the default; \code{alpha}, for alphabetic counting; \code{roman}, for lower-case Roman numerals; and \code{Roman} for upper-case Roman numerals. The ICU library also provides ways of formatting numbers in global (non-Latin) scripts. You can use any of the display types in this list: \url{http://www.unicode.org/repos/cldr/tags/latest/common/bcp47/number.xml}. For example, \code{display=beng} will format your numbers in Bengali digits. } So, for example, the following SILE code: \begin{verbatim} \line \\set-counter[id=mycounter, value=2] \\show-counter[id=mycounter] \\increment-counter[id=mycounter] \\show-counter[id=mycounter, display=roman] \line \end{verbatim} produces: \line \examplefont{2 \noindent{}iii} \line \end{document}]] }
[counters] Fix roman style capitalization (#572)
[counters] Fix roman style capitalization (#572) ICU uses different convention for roman numeral capitalization than SILE. This adds a translation which fixes this issue. Closes #571
Lua
mit
simoncozens/sile,simoncozens/sile,alerque/sile,alerque/sile,simoncozens/sile,alerque/sile,simoncozens/sile,alerque/sile
3782419cbb73321723cea8c840ca2bc91ee6c39b
gumbo.lua
gumbo.lua
local have_ffi, ffi = pcall(require, "ffi") if not have_ffi then -- load the C module instead local oldpath = package.path package.path = "" local gumbo_c_module = require "gumbo" package.path = oldpath return gumbo_c_module end local gumbo = require "gumbo-cdef" local build local typemap = { [tonumber(gumbo.GUMBO_NODE_DOCUMENT)] = "document", [tonumber(gumbo.GUMBO_NODE_ELEMENT)] = "element", [tonumber(gumbo.GUMBO_NODE_TEXT)] = "text", [tonumber(gumbo.GUMBO_NODE_CDATA)] = "cdata", [tonumber(gumbo.GUMBO_NODE_COMMENT)] = "comment", [tonumber(gumbo.GUMBO_NODE_WHITESPACE)] = "whitespace" } local quirksmap = { [tonumber(gumbo.GUMBO_DOCTYPE_NO_QUIRKS)] = "no-quirks", [tonumber(gumbo.GUMBO_DOCTYPE_QUIRKS)] = "quirks", [tonumber(gumbo.GUMBO_DOCTYPE_LIMITED_QUIRKS)] = "limited-quirks" } local function add_children(t, children) for i = 0, children.length-1 do t[i+1] = build(ffi.cast("GumboNode*", children.data[i])) end end local function get_attributes(attrs) if attrs.length ~= 0 then local t = {} for i = 0, attrs.length-1 do local attr = ffi.cast("GumboAttribute*", attrs.data[i]) t[ffi.string(attr.name)] = ffi.string(attr.value) end return t end end local function create_document(node, root_index) local document = node.v.document local ret = { type = "document", name = ffi.string(document.name), public_identifier = ffi.string(document.public_identifier), system_identifier = ffi.string(document.system_identifier), has_doctype = document.has_doctype, quirks_mode = quirksmap[tonumber(document.doc_type_quirks_mode)] } add_children(ret, document.children) ret.root = ret[root_index] return ret end local function get_tag_name(element) if element.tag == gumbo.GUMBO_TAG_UNKNOWN then local original_tag = element.original_tag gumbo.gumbo_tag_from_original_text(original_tag) return ffi.string(original_tag.data, original_tag.length) else return ffi.string(gumbo.gumbo_normalized_tagname(element.tag)) end end local function create_element(node) local element = node.v.element local ret = { type = "element", tag = get_tag_name(element), parse_flags = tonumber(node.parse_flags), start_pos = { line = element.start_pos.line, column = element.start_pos.column, offset = element.start_pos.offset }, end_pos = { line = element.end_pos.line, column = element.end_pos.column, offset = element.end_pos.offset }, attr = get_attributes(element.attributes) } add_children(ret, element.children) return ret end local function create_text(node) local text = node.v.text return { type = typemap[tonumber(node.type)], text = ffi.string(text.text), start_pos = { line = text.start_pos.line, column = text.start_pos.column, offset = text.start_pos.offset } } end build = function(node) if tonumber(node.type) == tonumber(gumbo.GUMBO_NODE_ELEMENT) then return create_element(node) else return create_text(node) end end local function parse(input, tab_stop) local options = ffi.new("GumboOptions") ffi.copy(options, gumbo.kGumboDefaultOptions, ffi.sizeof("GumboOptions")) options.tab_stop = tab_stop or 8 local output = gumbo.gumbo_parse_with_options(options, input, #input) local root_index = output.root.index_within_parent + 1 local document = create_document(output.document, root_index) gumbo.gumbo_destroy_output(options, output) return document end return {parse = parse}
local have_ffi, ffi = pcall(require, "ffi") if not have_ffi then -- load the C module instead local oldpath = package.path package.path = "" local gumbo_c_module = require "gumbo" package.path = oldpath return gumbo_c_module end local gumbo = require "gumbo-cdef" local build local typemap = { [tonumber(gumbo.GUMBO_NODE_DOCUMENT)] = "document", [tonumber(gumbo.GUMBO_NODE_ELEMENT)] = "element", [tonumber(gumbo.GUMBO_NODE_TEXT)] = "text", [tonumber(gumbo.GUMBO_NODE_CDATA)] = "cdata", [tonumber(gumbo.GUMBO_NODE_COMMENT)] = "comment", [tonumber(gumbo.GUMBO_NODE_WHITESPACE)] = "whitespace" } local quirksmap = { [tonumber(gumbo.GUMBO_DOCTYPE_NO_QUIRKS)] = "no-quirks", [tonumber(gumbo.GUMBO_DOCTYPE_QUIRKS)] = "quirks", [tonumber(gumbo.GUMBO_DOCTYPE_LIMITED_QUIRKS)] = "limited-quirks" } local function add_children(t, children) for i = 0, children.length - 1 do t[i+1] = build(ffi.cast("GumboNode*", children.data[i])) end end local function get_attributes(attrs) if attrs.length ~= 0 then local t = {} for i = 0, attrs.length - 1 do local attr = ffi.cast("GumboAttribute*", attrs.data[i]) t[ffi.string(attr.name)] = ffi.string(attr.value) end return t end end local function get_tag_name(element) if element.tag == gumbo.GUMBO_TAG_UNKNOWN then local original_tag = element.original_tag gumbo.gumbo_tag_from_original_text(original_tag) return ffi.string(original_tag.data, original_tag.length) else return ffi.string(gumbo.gumbo_normalized_tagname(element.tag)) end end local function create_document(node, root_index) local document = node.v.document local ret = { type = "document", name = ffi.string(document.name), public_identifier = ffi.string(document.public_identifier), system_identifier = ffi.string(document.system_identifier), has_doctype = document.has_doctype, quirks_mode = quirksmap[tonumber(document.doc_type_quirks_mode)] } add_children(ret, document.children) ret.root = ret[root_index] return ret end local function create_element(node) local element = node.v.element local ret = { type = "element", tag = get_tag_name(element), parse_flags = tonumber(node.parse_flags), start_pos = { line = element.start_pos.line, column = element.start_pos.column, offset = element.start_pos.offset }, end_pos = { line = element.end_pos.line, column = element.end_pos.column, offset = element.end_pos.offset }, attr = get_attributes(element.attributes) } add_children(ret, element.children) return ret end local function create_text(node) local text = node.v.text return { type = typemap[tonumber(node.type)], text = ffi.string(text.text), start_pos = { line = text.start_pos.line, column = text.start_pos.column, offset = text.start_pos.offset } } end build = function(node) if tonumber(node.type) == tonumber(gumbo.GUMBO_NODE_ELEMENT) then return create_element(node) else return create_text(node) end end local function parse(input, tab_stop) local options = ffi.new("GumboOptions") ffi.copy(options, gumbo.kGumboDefaultOptions, ffi.sizeof("GumboOptions")) options.tab_stop = tab_stop or 8 local output = gumbo.gumbo_parse_with_options(options, input, #input) local root_index = output.root.index_within_parent + 1 local document = create_document(output.document, root_index) gumbo.gumbo_destroy_output(options, output) return document end return {parse = parse}
Minor style fixes
Minor style fixes
Lua
apache-2.0
craigbarnes/lua-gumbo,craigbarnes/lua-gumbo,craigbarnes/lua-gumbo
38d6f9c959140088e7c52554310e20358ea530b4
hammerspoon/window.lua
hammerspoon/window.lua
----------------------------------------------- -- Set hyper to ctrl + shift ----------------------------------------------- local hyper = {"cmd", "ctrl", "shift"} function tolerance(a, b) return math.abs(a - b) < 32 end local STEP = 10 function resizeWindow(f) local win = hs.window.focusedWindow() local frame = win:frame() frame.x = frame.x + (f.x or 0) frame.y = frame.y + (f.y or 0) frame.w = frame.w + (f.w or 0) frame.h = frame.h + (f.h or 0) win:setFrame(frame) end function resizeWindowWider() resizeWindow({x = -STEP, w = 2 * STEP}) end function resizeWindowTaller() resizeWindow({y = -STEP, h = 2 * STEP}) end function resizeWindowShorter() resizeWindow({x = STEP, w = -2 * STEP}) end function resizeWindowThinner() resizeWindow({y = STEP, h = -2 * STEP}) end -- TODO: Add comments function resize(x, y, w, h) local win = hs.window.focusedWindow() local f = win:frame() local max = win:screen():frame() local ww = max.w / w local hh = max.h / h local xx = max.x + (x * ww) local yy = max.y + (y * hh) if ischatmode and x == 0 then xx = xx + CHAT_MODE_WIDTH ww = ww - CHAT_MODE_WIDTH end if tolerance(f.x, xx) and tolerance(f.y, yy) and tolerance(f.w, ww) and tolerance(f.h, hh) then if w > h then x = (x + 1) % w elseif h > w then y = (y + 1) % h else x = (x == 0) and 0.9999 or 0 y = (y == 0) and 0.9999 or 0 end return resize(x, y, w, h) end f.x = xx f.y = yy f.w = ww f.h = hh return win:setFrame(f) end function fullscreen() local win = hs.window.focusedWindow() local f = win:frame() local max = win:screen():frame() if ischatmode then f.x = max.x + CHAT_MODE_WIDTH f.w = max.w - CHAT_MODE_WIDTH else f.x = max.x f.w = max.w end f.y = max.y f.h = max.h win:setFrame(f) end function center() local win = hs.window.focusedWindow() local f = win:frame() local max = win:screen():frame() f.x = (max.w - max.x - f.w) / 2 f.y = (max.h - max.y - f.h) / 2 win:setFrame(f) end ischatmode = false function chatmode() ischatmode = not ischatmode if ischatmode then hs.alert.show("enable chat mode") local win = hs.window.focusedWindow() local f = win:frame() local max = win:screen():frame() CHAT_MODE_WIDTH = max.w * 0.18 f.x = max.x f.y = max.y f.w = CHAT_MODE_WIDTH f.h = max.h win:setFrame(f) else hs.alert.show("disable chat mode") end end ----------------------------------------------- -- hyper h, j, k, l for left, down, up, right half window ----------------------------------------------- function leftHalf() resize(0, 0, 2, 1) end function bottomHalf() resize(0, 1, 1, 2) end function topHalf() resize(0, 0, 1, 2) end function rightHalf() resize(1, 0, 2, 1) end hs.hotkey.bind(hyper, "h", leftHalf) hs.hotkey.bind(hyper, "j", bottomHalf) hs.hotkey.bind(hyper, "k", topHalf) hs.hotkey.bind(hyper, "l", rightHalf) hs.hotkey.bind(hyper, "m", function() resize(0, 0, 1, 1) end) ----------------------------------------------- -- hyper g, ; for horizontal, vertical fold window ----------------------------------------------- local lx = 2 local lw = 3 hs.hotkey.bind(hyper, ";", function() resize(lx, 0, lw, 1) lx = (lx + 1) % lw end) local hy = 0 local hh = 3 hs.hotkey.bind(hyper, "g", function() resize(0, hy, 1, hh) hy = (hy + 1) % hh end) ----------------------------------------------- -- hyper p, n for move between monitors ----------------------------------------------- hs.hotkey.bind(hyper, "p", function() hs.window.focusedWindow():moveOneScreenEast(0) end) hs.hotkey.bind(hyper, "n", function() hs.window.focusedWindow():moveOneScreenWest(0) end) ----------------------------------------------- -- hyper 1, 2 for diagonal quarter window ----------------------------------------------- function topLeftCorner() resize(0, 0, 2, 2) end function topRightCorner() resize(1, 0, 2, 2) end hs.hotkey.bind(hyper, "1", topLeftCorner, nil, topLeftCorner) hs.hotkey.bind(hyper, "2", topRightCorner, nil, topRightCorner) ----------------------------------------------- -- Hyper i to show window hints ----------------------------------------------- hs.hotkey.bind(hyper, "i", function() hs.hints.windowHints() end) hs.hotkey.bind(hyper, "q", function() chatmode() end) -- ----------------------------------------------- -- -- Hyper wsad to set window size -- ----------------------------------------------- hs.hotkey.bind(hyper, "w", resizeWindowTaller, nil, resizeWindowTaller) hs.hotkey.bind(hyper, "a", resizeWindowShorter, nil, resizeWindowShorter) hs.hotkey.bind(hyper, "s", resizeWindowThinner, nil, resizeWindowThinner) hs.hotkey.bind(hyper, "d", resizeWindowWider, nil, resizeWindowWider) ----------------------------------------------- -- hyper f for fullscreen, c for center ----------------------------------------------- hs.hotkey.bind(hyper, "c", center) hs.hotkey.bind(hyper, "f", fullscreen) ----------------------------------------------- -- CMD+Ctrl+f for fullscreen ----------------------------------------------- hs.hotkey.bind({"cmd", "ctrl"}, "f", fullscreen) -- Set hotkey modal function getIndicator() local frame = hs.screen.mainScreen():fullFrame() local width = 600 local height = 90 local f = { x = frame.w / 2 - width / 2, y = height * 2, w = width, h = height } return hs.canvas.new(f):appendElements({ action = "fill", fillColor = { alpha = 0.8, black = 1 }, type = "rectangle", }, { action = "fill", type = "text", textColor = { red = 1 }, textSize = 64, textAlignment = "center", text = "Escape to exit" }) end local inidcator = getIndicator() local winHotkeyModal = hs.hotkey.modal.new(hyper, "o") function winHotkeyModal:entered() hs.alert.closeAll() hs.alert.show("Open window hotkey modal") indicator = inidcator:show(1) end function winHotkeyModal:exited() hs.alert.closeAll() hs.alert.show("Exit window hotkey modal") indicator = indicator:hide(0.2) end winHotkeyModal:bind("", "escape", function() winHotkeyModal:exit() end) winHotkeyModal:bind("", "1", "", topLeftCorner, nil, topLeftCorner) winHotkeyModal:bind("", "2", "", topRightCorner, nil, topRightCorner) winHotkeyModal:bind("", "h", "", leftHalf, nil, leftHalf) winHotkeyModal:bind("", "j", "", bottomHalf, nil, bottomHalf) winHotkeyModal:bind("", "k", "", topHalf, nil, topHalf) winHotkeyModal:bind("", "l", "", rightHalf, nil, rightHalf) winHotkeyModal:bind("", "c", "", center, nil, center) winHotkeyModal:bind("", "f", "", fullscreen, nil, fullscreen) winHotkeyModal:bind("", "w", resizeWindowTaller, nil, resizeWindowTaller) winHotkeyModal:bind("", "a", resizeWindowShorter, nil, resizeWindowShorter) winHotkeyModal:bind("", "s", resizeWindowThinner, nil, resizeWindowThinner) winHotkeyModal:bind("", "d", resizeWindowWider, nil, resizeWindowWider)
----------------------------------------------- -- Set hyper to ctrl + shift ----------------------------------------------- local hyper = {"cmd", "ctrl", "shift"} function tolerance(a, b) return math.abs(a - b) < 32 end local STEP = 10 function resizeWindow(f) local win = hs.window.focusedWindow() local frame = win:frame() frame.x = frame.x + (f.x or 0) frame.y = frame.y + (f.y or 0) frame.w = frame.w + (f.w or 0) frame.h = frame.h + (f.h or 0) win:setFrame(frame) end function resizeWindowWider() resizeWindow({x = -STEP, w = 2 * STEP}) end function resizeWindowTaller() resizeWindow({y = -STEP, h = 2 * STEP}) end function resizeWindowShorter() resizeWindow({x = STEP, w = -2 * STEP}) end function resizeWindowThinner() resizeWindow({y = STEP, h = -2 * STEP}) end -- TODO: Add comments function resize(x, y, w, h) local win = hs.window.focusedWindow() local f = win:frame() local max = win:screen():frame() local ww = max.w / w local hh = max.h / h local xx = max.x + (x * ww) local yy = max.y + (y * hh) if ischatmode and x == 0 then xx = xx + CHAT_MODE_WIDTH ww = ww - CHAT_MODE_WIDTH end if tolerance(f.x, xx) and tolerance(f.y, yy) and tolerance(f.w, ww) and tolerance(f.h, hh) then if w > h then x = (x + 1) % w elseif h > w then y = (y + 1) % h else x = (x == 0) and 0.9999 or 0 y = (y == 0) and 0.9999 or 0 end return resize(x, y, w, h) end f.x = xx f.y = yy f.w = ww f.h = hh return win:setFrame(f) end function fullscreen() local win = hs.window.focusedWindow() local f = win:frame() local max = win:screen():frame() if ischatmode then f.x = max.x + CHAT_MODE_WIDTH f.w = max.w - CHAT_MODE_WIDTH else f.x = max.x f.w = max.w end f.y = max.y f.h = max.h win:setFrame(f) end function center() local win = hs.window.focusedWindow() local f = win:frame() local max = win:screen():frame() f.x = (max.w - max.x - f.w) / 2 f.y = (max.h - max.y - f.h) / 2 win:setFrame(f) end ischatmode = false function chatmode() ischatmode = not ischatmode if ischatmode then hs.alert.show("enable chat mode") local win = hs.window.focusedWindow() local f = win:frame() local max = win:screen():frame() CHAT_MODE_WIDTH = max.w * 0.18 f.x = max.x f.y = max.y f.w = CHAT_MODE_WIDTH f.h = max.h win:setFrame(f) else hs.alert.show("disable chat mode") end end ----------------------------------------------- -- hyper h, j, k, l for left, down, up, right half window ----------------------------------------------- function leftHalf() resize(0, 0, 2, 1) end function bottomHalf() resize(0, 1, 1, 2) end function topHalf() resize(0, 0, 1, 2) end function rightHalf() resize(1, 0, 2, 1) end hs.hotkey.bind(hyper, "h", leftHalf) hs.hotkey.bind(hyper, "j", bottomHalf) hs.hotkey.bind(hyper, "k", topHalf) hs.hotkey.bind(hyper, "l", rightHalf) hs.hotkey.bind(hyper, "m", function() resize(0, 0, 1, 1) end) ----------------------------------------------- -- hyper g, ; for horizontal, vertical fold window ----------------------------------------------- local lx = 2 local lw = 3 hs.hotkey.bind(hyper, ";", function() resize(lx, 0, lw, 1) lx = (lx + 1) % lw end) local hy = 0 local hh = 3 hs.hotkey.bind(hyper, "g", function() resize(0, hy, 1, hh) hy = (hy + 1) % hh end) ----------------------------------------------- -- hyper p, n for move between monitors ----------------------------------------------- hs.hotkey.bind(hyper, "p", function() hs.window.focusedWindow():moveOneScreenEast(0) end) hs.hotkey.bind(hyper, "n", function() hs.window.focusedWindow():moveOneScreenWest(0) end) ----------------------------------------------- -- hyper 1, 2 for diagonal quarter window ----------------------------------------------- function topLeftCorner() resize(0, 0, 2, 2) end function topRightCorner() resize(1, 0, 2, 2) end hs.hotkey.bind(hyper, "1", topLeftCorner, nil, topLeftCorner) hs.hotkey.bind(hyper, "2", topRightCorner, nil, topRightCorner) ----------------------------------------------- -- Hyper i to show window hints ----------------------------------------------- hs.hotkey.bind(hyper, "i", function() hs.hints.windowHints() end) hs.hotkey.bind(hyper, "q", function() chatmode() end) -- ----------------------------------------------- -- -- Hyper wsad to set window size -- ----------------------------------------------- hs.hotkey.bind(hyper, "w", resizeWindowTaller, nil, resizeWindowTaller) hs.hotkey.bind(hyper, "a", resizeWindowShorter, nil, resizeWindowShorter) hs.hotkey.bind(hyper, "s", resizeWindowThinner, nil, resizeWindowThinner) hs.hotkey.bind(hyper, "d", resizeWindowWider, nil, resizeWindowWider) ----------------------------------------------- -- hyper f for fullscreen, c for center ----------------------------------------------- hs.hotkey.bind(hyper, "c", center) hs.hotkey.bind(hyper, "f", fullscreen) ----------------------------------------------- -- CMD+Ctrl+f for fullscreen ----------------------------------------------- hs.hotkey.bind({"cmd", "ctrl"}, "f", fullscreen) -- Set hotkey modal function getIndicator() local frame = hs.screen.mainScreen():fullFrame() local width = 600 local height = 90 local f = { x = frame.x + frame.w / 2 - width / 2, y = frame.y + height * 2, w = width, h = height } return hs.canvas.new(f):appendElements({ action = "fill", fillColor = { alpha = 0.8, black = 1 }, type = "rectangle", }, { action = "fill", type = "text", textColor = { red = 1 }, textSize = 64, textAlignment = "center", text = "Escape to exit" }) end local inidcator = nil local winHotkeyModal = hs.hotkey.modal.new(hyper, "o") function winHotkeyModal:entered() hs.alert.closeAll() hs.alert.show("Open window hotkey modal") indicator = getIndicator():show(1) end function winHotkeyModal:exited() hs.alert.closeAll() hs.alert.show("Exit window hotkey modal") indicator:delete(0.2) indicator = nil end winHotkeyModal:bind("", "escape", function() winHotkeyModal:exit() end) winHotkeyModal:bind("", "1", "", topLeftCorner, nil, topLeftCorner) winHotkeyModal:bind("", "2", "", topRightCorner, nil, topRightCorner) winHotkeyModal:bind("", "h", "", leftHalf, nil, leftHalf) winHotkeyModal:bind("", "j", "", bottomHalf, nil, bottomHalf) winHotkeyModal:bind("", "k", "", topHalf, nil, topHalf) winHotkeyModal:bind("", "l", "", rightHalf, nil, rightHalf) winHotkeyModal:bind("", "c", "", center, nil, center) winHotkeyModal:bind("", "f", "", fullscreen, nil, fullscreen) winHotkeyModal:bind("", "w", resizeWindowTaller, nil, resizeWindowTaller) winHotkeyModal:bind("", "a", resizeWindowShorter, nil, resizeWindowShorter) winHotkeyModal:bind("", "s", resizeWindowThinner, nil, resizeWindowThinner) winHotkeyModal:bind("", "d", resizeWindowWider, nil, resizeWindowWider)
Fix window hotkey modal indicator issue
Fix window hotkey modal indicator issue
Lua
mit
xcv58/Hammerspoon-xcv58
5426d1807c96c558b116aab4ec9191a2f9a34bbe
src/lib/fibers/file.lua
src/lib/fibers/file.lua
-- Use of this source code is governed by the Apache 2.0 license; see COPYING. -- Timeout events. module(..., package.seeall) local op = require('lib.fibers.op') local fiber = require('lib.fibers.fiber') local epoll = require('lib.fibers.epoll') local file = require('lib.stream.file') local bit = require('bit') local PollIOHandler = {} local PollIOHandler_mt = { __index=PollIOHandler } function new_poll_io_handler() return setmetatable( { epoll=epoll.new(), waiting_for_readable={}, -- sock descriptor => array of task waiting_for_writable={} }, -- sock descriptor => array of task PollIOHandler_mt) end -- These three methods are "blocking handler" methods and are called by -- lib.stream.file. function PollIOHandler:init_nonblocking(fd) fd:nonblock() end function PollIOHandler:wait_for_readable(fd) self:fd_readable_op(fd):perform() end function PollIOHandler:wait_for_writable(fd) self:fd_writable_op(fd):perform() end local function add_waiter(fd, waiters, task) local tasks = waiters[fd] if tasks == nil then tasks = {}; waiters[fd] = tasks end table.insert(tasks, task) end local function make_block_fn(fd, waiting, epoll, events) return function(suspension, wrap_fn) local task = suspension:complete_task(wrap_fn) local fd = fd:getfd() add_waiter(fd, waiting, task) epoll:add(fd, events) end end function PollIOHandler:fd_readable_op(fd) local function try() return false end local block = make_block_fn( fd, self.waiting_for_readable, self.epoll, epoll.RD) return op.new_base_op(nil, try, block) end function PollIOHandler:fd_writable_op(fd) local function try() return false end local block = make_block_fn( fd, self.waiting_for_writable, self.epoll, epoll.WR) return op.new_base_op(nil, try, block) end function PollIOHandler:stream_readable_op(stream) local fd = assert(stream.io.fd) local function try() return not stream.rx:is_empty() end local block = make_block_fn( fd, self.waiting_for_readable, self.epoll, epoll.RD) return op.new_base_op(nil, try, block) end -- A stream_writable_op is the same as fd_writable_op, as a stream's -- buffer is never left full -- any stream method that fills the buffer -- flushes it directly. Knowing something about the buffer state -- doesn't tell us anything useful. function PollIOHandler:stream_writable_op(stream) local fd = assert(stream.io.fd) return self:fd_writable_op(fd) end local function schedule_tasks(sched, tasks) -- It's possible for tasks to be nil, as an IO error will notify for -- both readable and writable, and maybe we only have tasks waiting -- for one side. if tasks == nil then return end for i=1,#tasks do sched:schedule(tasks[i]) tasks[i] = nil end end -- These method is called by the fibers scheduler. function PollIOHandler:schedule_tasks(sched, now, timeout) if timeout == nil then timeout = 0 end for _, event in self.epoll:poll(timeout) do if bit.band(event.events, epoll.RD + epoll.ERR) ~= 0 then local tasks = self.waiting_for_readable[event.data.fd] schedule_tasks(sched, tasks) end if bit.band(event.events, epoll.WR + epoll.ERR) ~= 0 then local tasks = self.waiting_for_writable[event.data.fd] schedule_tasks(sched, tasks) end end end -- These method is called by the fibers scheduler. function PollIOHandler:schedule_tasks(sched, now, timeout) if timeout == nil then timeout = 0 end if timeout >= 0 then timeout = timeout * 1e3 end for _, event in self.epoll:poll(timeout) do if bit.band(event.events, epoll.RD + epoll.ERR) ~= 0 then local tasks = self.waiting_for_readable[event.data.fd] schedule_tasks(sched, tasks) end if bit.band(event.events, epoll.WR + epoll.ERR) ~= 0 then local tasks = self.waiting_for_writable[event.data.fd] schedule_tasks(sched, tasks) end end end PollIOHandler.wait_for_events = PollIOHandler.schedule_tasks function PollIOHandler:cancel_tasks_for_fd(fd) local function cancel_tasks(waiting) local tasks = waiting[fd] if tasks ~= nil then for i=1,#tasks do tasks[i]:cancel() end waiting[fd] = nil end end cancel_tasks(self.waiting_for_readable) cancel_tasks(self.waiting_for_writable) end function PollIOHandler:cancel_all_tasks() for fd,_ in pairs(self.waiting_for_readable) do self:cancel_tasks_for_fd(fd) end for fd,_ in pairs(self.waiting_for_writable) do self:cancel_tasks_for_fd(fd) end end local installed = 0 local installed_poll_handler function install_poll_io_handler() installed = installed + 1 if installed == 1 then installed_poll_handler = new_poll_io_handler() file.set_blocking_handler(installed_poll_handler) fiber.current_scheduler:add_task_source(installed_poll_handler) end return installed_poll_handler end function uninstall_poll_io_handler() installed = installed - 1 if installed == 0 then file.set_blocking_handler(nil) -- FIXME: Remove task source. for i,source in ipairs(fiber.current_scheduler.sources) do if source == installed_poll_handler then table.remove(fiber.current_scheduler.sources, i) break end end installed_poll_handler.epoll:close() installed_poll_handler = nil end end function fd_readable_op(fd) return assert(installed_poll_handler):fd_readable_op(fd) end function fd_writable_op(fd) return assert(installed_poll_handler):fd_writable_op(fd) end function stream_readable_op(stream) return assert(installed_poll_handler):stream_readable_op(stream) end function stream_writable_op(stream) return assert(installed_poll_handler):stream_writable_op(stream) end function selftest() print('selftest: lib.fibers.file') local lib = require('core.lib') local log = {} local function record(x) table.insert(log, x) end local handler = new_poll_io_handler() file.set_blocking_handler(handler) fiber.current_scheduler:add_task_source(handler) fiber.current_scheduler:run() assert(lib.equal(log, {})) local rd, wr = file.pipe() local message = "hello, world\n" fiber.spawn(function() record('rd-a') local str = rd:read_some_chars() record('rd-b') record(str) end) fiber.spawn(function() record('wr-a') wr:write(message) record('wr-b') wr:flush() record('wr-c') end) fiber.current_scheduler:run() assert(lib.equal(log, {'rd-a', 'wr-a', 'wr-b', 'wr-c'})) fiber.current_scheduler:run() assert(lib.equal(log, {'rd-a', 'wr-a', 'wr-b', 'wr-c', 'rd-b', message})) print('selftest: ok') end
-- Use of this source code is governed by the Apache 2.0 license; see COPYING. -- Timeout events. module(..., package.seeall) local op = require('lib.fibers.op') local fiber = require('lib.fibers.fiber') local epoll = require('lib.fibers.epoll') local file = require('lib.stream.file') local bit = require('bit') local PollIOHandler = {} local PollIOHandler_mt = { __index=PollIOHandler } function new_poll_io_handler() return setmetatable( { epoll=epoll.new(), waiting_for_readable={}, -- sock descriptor => array of task waiting_for_writable={} }, -- sock descriptor => array of task PollIOHandler_mt) end -- These three methods are "blocking handler" methods and are called by -- lib.stream.file. function PollIOHandler:init_nonblocking(fd) fd:nonblock() end function PollIOHandler:wait_for_readable(fd) self:fd_readable_op(fd):perform() end function PollIOHandler:wait_for_writable(fd) self:fd_writable_op(fd):perform() end local function add_waiter(fd, waiters, task) local tasks = waiters[fd] if tasks == nil then tasks = {}; waiters[fd] = tasks end table.insert(tasks, task) end local function make_block_fn(fd, waiting, epoll, events) return function(suspension, wrap_fn) local task = suspension:complete_task(wrap_fn) local fd = fd:getfd() add_waiter(fd, waiting, task) epoll:add(fd, events) end end function PollIOHandler:fd_readable_op(fd) local function try() return false end local block = make_block_fn( fd, self.waiting_for_readable, self.epoll, epoll.RD) return op.new_base_op(nil, try, block) end function PollIOHandler:fd_writable_op(fd) local function try() return false end local block = make_block_fn( fd, self.waiting_for_writable, self.epoll, epoll.WR) return op.new_base_op(nil, try, block) end function PollIOHandler:stream_readable_op(stream) local fd = assert(stream.io.fd) local function try() return not stream.rx:is_empty() end local block = make_block_fn( fd, self.waiting_for_readable, self.epoll, epoll.RD) return op.new_base_op(nil, try, block) end -- A stream_writable_op is the same as fd_writable_op, as a stream's -- buffer is never left full -- any stream method that fills the buffer -- flushes it directly. Knowing something about the buffer state -- doesn't tell us anything useful. function PollIOHandler:stream_writable_op(stream) local fd = assert(stream.io.fd) return self:fd_writable_op(fd) end local function schedule_tasks(sched, tasks) -- It's possible for tasks to be nil, as an IO error will notify for -- both readable and writable, and maybe we only have tasks waiting -- for one side. if tasks == nil then return end for i=1,#tasks do sched:schedule(tasks[i]) tasks[i] = nil end end -- These method is called by the fibers scheduler. function PollIOHandler:schedule_tasks(sched, now, timeout) if timeout == nil then timeout = 0 end if timeout >= 0 then timeout = timeout * 1e3 end for _, event in self.epoll:poll(timeout) do if bit.band(event.events, epoll.RD + epoll.ERR) ~= 0 then local tasks = self.waiting_for_readable[event.data.fd] schedule_tasks(sched, tasks) end if bit.band(event.events, epoll.WR + epoll.ERR) ~= 0 then local tasks = self.waiting_for_writable[event.data.fd] schedule_tasks(sched, tasks) end end end PollIOHandler.wait_for_events = PollIOHandler.schedule_tasks function PollIOHandler:cancel_tasks_for_fd(fd) local function cancel_tasks(waiting) local tasks = waiting[fd] if tasks ~= nil then for i=1,#tasks do tasks[i]:cancel() end waiting[fd] = nil end end cancel_tasks(self.waiting_for_readable) cancel_tasks(self.waiting_for_writable) end function PollIOHandler:cancel_all_tasks() for fd,_ in pairs(self.waiting_for_readable) do self:cancel_tasks_for_fd(fd) end for fd,_ in pairs(self.waiting_for_writable) do self:cancel_tasks_for_fd(fd) end end local installed = 0 local installed_poll_handler function install_poll_io_handler() installed = installed + 1 if installed == 1 then installed_poll_handler = new_poll_io_handler() file.set_blocking_handler(installed_poll_handler) fiber.current_scheduler:add_task_source(installed_poll_handler) end return installed_poll_handler end function uninstall_poll_io_handler() installed = installed - 1 if installed == 0 then file.set_blocking_handler(nil) -- FIXME: Remove task source. for i,source in ipairs(fiber.current_scheduler.sources) do if source == installed_poll_handler then table.remove(fiber.current_scheduler.sources, i) break end end installed_poll_handler.epoll:close() installed_poll_handler = nil end end function fd_readable_op(fd) return assert(installed_poll_handler):fd_readable_op(fd) end function fd_writable_op(fd) return assert(installed_poll_handler):fd_writable_op(fd) end function stream_readable_op(stream) return assert(installed_poll_handler):stream_readable_op(stream) end function stream_writable_op(stream) return assert(installed_poll_handler):stream_writable_op(stream) end function selftest() print('selftest: lib.fibers.file') local lib = require('core.lib') local log = {} local function record(x) table.insert(log, x) end local handler = new_poll_io_handler() file.set_blocking_handler(handler) fiber.current_scheduler:add_task_source(handler) fiber.current_scheduler:run() assert(lib.equal(log, {})) local rd, wr = file.pipe() local message = "hello, world\n" fiber.spawn(function() record('rd-a') local str = rd:read_some_chars() record('rd-b') record(str) end) fiber.spawn(function() record('wr-a') wr:write(message) record('wr-b') wr:flush() record('wr-c') end) fiber.current_scheduler:run() assert(lib.equal(log, {'rd-a', 'wr-a', 'wr-b', 'wr-c'})) fiber.current_scheduler:run() assert(lib.equal(log, {'rd-a', 'wr-a', 'wr-b', 'wr-c', 'rd-b', message})) print('selftest: ok') end
Fix duplicated method
Fix duplicated method
Lua
apache-2.0
SnabbCo/snabbswitch,snabbco/snabb,Igalia/snabb,snabbco/snabb,Igalia/snabb,snabbco/snabb,SnabbCo/snabbswitch,Igalia/snabb,eugeneia/snabb,alexandergall/snabbswitch,eugeneia/snabb,snabbco/snabb,eugeneia/snabb,alexandergall/snabbswitch,Igalia/snabbswitch,alexandergall/snabbswitch,SnabbCo/snabbswitch,Igalia/snabb,snabbco/snabb,Igalia/snabbswitch,eugeneia/snabb,eugeneia/snabb,snabbco/snabb,Igalia/snabb,alexandergall/snabbswitch,snabbco/snabb,alexandergall/snabbswitch,Igalia/snabbswitch,snabbco/snabb,eugeneia/snabb,eugeneia/snabb,Igalia/snabbswitch,Igalia/snabb,alexandergall/snabbswitch,alexandergall/snabbswitch,SnabbCo/snabbswitch,Igalia/snabb,eugeneia/snabb,alexandergall/snabbswitch,Igalia/snabbswitch,Igalia/snabb
4d2a793befdd8406079b3a14b9d44503a9cfb0b1
genie.lua
genie.lua
newoption { trigger = "UWP", description = "Generates Universal Windows Platform application type", } if not _ACTION then _ACTION="vs2012" end outFolderRoot = "Bin/" .. _ACTION .. "/"; isVisualStudio = false isUWP = false if _ACTION == "vs2010" or _ACTION == "vs2012" or _ACTION == "vs2015" or _ACTION == "vs2017" then if _OPTIONS['platform'] ~= "orbis" then isVisualStudio = true end end if _OPTIONS["UWP"] then isUWP = true end if isUWP then premake.vstudio.toolset = "v140" premake.vstudio.storeapp = "10.0" end outputFolder = "Build/" .. _ACTION if isUWP then outputFolder = outputFolder .. "_UWP" end solution "Brofiler" language "C++" windowstargetplatformversion "10.0.15063.0" startproject "BrofilerWindowsTest" location ( outputFolder ) flags { "NoManifest", "ExtraWarnings", "Unicode" } optimization_flags = { "OptimizeSpeed" } if isVisualStudio then debugdir (outFolderRoot) buildoptions { "/wd4127", -- Conditional expression is constant "/wd4091" -- 'typedef ': ignored on left of '' when no variable is declared } end if isUWP then defines { "BRO_UWP=1" } end defines { "USE_BROFILER=1"} defines { "BRO_FIBERS=1"} local config_list = { "Release", "Debug", } local platform_list = { "x32", "x64", "Native", } configurations(config_list) platforms(platform_list) -- CONFIGURATIONS if _ACTION == "vs2010" then defines { "_DISABLE_DEPRECATE_STATIC_CPPLIB", "_STATIC_CPPLIB"} end configuration "Release" targetdir(outFolderRoot .. "/Native/Release") defines { "NDEBUG", "MT_INSTRUMENTED_BUILD" } flags { "Symbols", optimization_flags } configuration "Debug" targetdir(outFolderRoot .. "/Native/Debug") defines { "_DEBUG", "_CRTDBG_MAP_ALLOC", "MT_INSTRUMENTED_BUILD", "_ITERATOR_DEBUG_LEVEL=1"} flags { "Symbols" } -- give each configuration/platform a unique output directory for _, config in ipairs(config_list) do for _, plat in ipairs(platform_list) do configuration { config, plat } objdir ( outputFolder .. "/Temp/" ) tgtDir = outFolderRoot .. plat .. "/" .. config targetdir (tgtDir) end end os.mkdir("./" .. outFolderRoot) -- SUBPROJECTS project "BrofilerCore" uuid "830934D9-6F6C-C37D-18F2-FB3304348F00" defines { "_CRT_SECURE_NO_WARNINGS", "BROFILER_LIB=1" } if _OPTIONS['platform'] ~= "orbis" then kind "SharedLib" defines { "BROFILER_EXPORTS" } else kind "StaticLib" end includedirs { "ThirdParty/TaskScheduler/Scheduler/Include", "BrofilerCore" } files { "BrofilerCore/**.cpp", "BrofilerCore/**.h", } vpaths { ["API"] = { "BrofilerCore/Brofiler.h", }, ["Core"] = { "BrofilerCore/Core.h", "BrofilerCore/Core.cpp", "BrofilerCore/ETW.h", "BrofilerCore/Event.h", "BrofilerCore/Event.cpp", "BrofilerCore/EventDescription.h", "BrofilerCore/EventDescription.cpp", "BrofilerCore/EventDescriptionBoard.h", "BrofilerCore/EventDescriptionBoard.cpp", "BrofilerCore/Sampler.h", "BrofilerCore/Sampler.cpp", "BrofilerCore/SymEngine.h", "BrofilerCore/SymEngine.cpp", }, ["Network"] = { "BrofilerCore/Message.h", "BrofilerCore/Message.cpp", "BrofilerCore/ProfilerServer.h", "BrofilerCore/ProfilerServer.cpp", "BrofilerCore/Socket.h", "BrofilerCore/Serialization.h", "BrofilerCore/Serialization.cpp", }, ["System"] = { "BrofilerCore/Common.h", "BrofilerCore/Concurrency.h", "BrofilerCore/HPTimer.h", "BrofilerCore/HPTimer.cpp", "BrofilerCore/MemoryPool.h", "BrofilerCore/Thread.h", "BrofilerCore/Types.h", }, } project "TaskScheduler" excludes { "ThirdParty/TaskScheduler/Scheduler/Source/MTDefaultAppInterop.cpp", } kind "StaticLib" flags {"NoPCH"} defines {"USE_BROFILER=1"} files { "ThirdParty/TaskScheduler/Scheduler/**.*", } includedirs { "ThirdParty/TaskScheduler/Scheduler/Include", "BrofilerCore" } excludes { "Src/Platform/Posix/**.*" } vpaths { ["*"] = "TaskScheduler" } links { "BrofilerCore", } project "BrofilerTest" flags {"NoPCH"} kind "StaticLib" uuid "9A313DD9-8694-CC7D-2F1A-05341B5C9800" files { "BrofilerTest/**.*", } includedirs { "BrofilerCore", "ThirdParty/TaskScheduler/Scheduler/Include" } links { "BrofilerCore", "TaskScheduler" } if isUWP then -- Genie can't generate proper UWP application -- It's a dummy project to match existing project file project "BrofilerDurangoTest" location( "BrofilerDurangoTest" ) kind "WindowedApp" uuid "5CA6AF66-C2CB-412E-B335-B34357F2FBB6" files { "BrofilerDurangoTest/**.*", } else project "BrofilerWindowsTest" flags {"NoPCH"} kind "ConsoleApp" uuid "C50A1240-316C-EF4D-BAD9-3500263A260D" files { "BrofilerWindowsTest/**.*", "ThirdParty/TaskScheduler/Scheduler/Source/MTDefaultAppInterop.cpp", } vpaths { ["*"] = "BrofilerWindowsTest" } includedirs { "BrofilerCore", "BrofilerTest", "ThirdParty/TaskScheduler/Scheduler/Include" } links { "BrofilerCore", "BrofilerTest", "TaskScheduler" } end
newoption { trigger = "UWP", description = "Generates Universal Windows Platform application type", } if not _ACTION then _ACTION="vs2012" end outFolderRoot = "Bin/" .. _ACTION .. "/"; isVisualStudio = false isUWP = false if _ACTION == "vs2010" or _ACTION == "vs2012" or _ACTION == "vs2015" or _ACTION == "vs2017" then if _OPTIONS['platform'] ~= "orbis" then isVisualStudio = true end end if _OPTIONS["UWP"] then isUWP = true end if isUWP then premake.vstudio.toolset = "v140" premake.vstudio.storeapp = "10.0" end outputFolder = "Build/" .. _ACTION if isUWP then outputFolder = outputFolder .. "_UWP" end solution "Brofiler" language "C++" if _ACTION == "vs2017" then windowstargetplatformversion "10.0.15063.0" end startproject "BrofilerWindowsTest" location ( outputFolder ) flags { "NoManifest", "ExtraWarnings", "Unicode" } optimization_flags = { "OptimizeSpeed" } if isVisualStudio then debugdir (outFolderRoot) buildoptions { "/wd4127", -- Conditional expression is constant "/wd4091" -- 'typedef ': ignored on left of '' when no variable is declared } end if isUWP then defines { "BRO_UWP=1" } end defines { "USE_BROFILER=1"} defines { "BRO_FIBERS=1"} local config_list = { "Release", "Debug", } local platform_list = { "x32", "x64", "Native", } configurations(config_list) platforms(platform_list) -- CONFIGURATIONS if _ACTION == "vs2010" then defines { "_DISABLE_DEPRECATE_STATIC_CPPLIB", "_STATIC_CPPLIB"} end configuration "Release" targetdir(outFolderRoot .. "/Native/Release") defines { "NDEBUG", "MT_INSTRUMENTED_BUILD" } flags { "Symbols", optimization_flags } configuration "Debug" targetdir(outFolderRoot .. "/Native/Debug") defines { "_DEBUG", "_CRTDBG_MAP_ALLOC", "MT_INSTRUMENTED_BUILD", "_ITERATOR_DEBUG_LEVEL=1"} flags { "Symbols" } -- give each configuration/platform a unique output directory for _, config in ipairs(config_list) do for _, plat in ipairs(platform_list) do configuration { config, plat } objdir ( outputFolder .. "/Temp/" ) tgtDir = outFolderRoot .. plat .. "/" .. config targetdir (tgtDir) end end os.mkdir("./" .. outFolderRoot) -- SUBPROJECTS project "BrofilerCore" uuid "830934D9-6F6C-C37D-18F2-FB3304348F00" defines { "_CRT_SECURE_NO_WARNINGS", "BROFILER_LIB=1" } if _OPTIONS['platform'] ~= "orbis" then kind "SharedLib" defines { "BROFILER_EXPORTS" } else kind "StaticLib" end includedirs { "ThirdParty/TaskScheduler/Scheduler/Include", "BrofilerCore" } files { "BrofilerCore/**.cpp", "BrofilerCore/**.h", } vpaths { ["API"] = { "BrofilerCore/Brofiler.h", }, ["Core"] = { "BrofilerCore/Core.h", "BrofilerCore/Core.cpp", "BrofilerCore/ETW.h", "BrofilerCore/Event.h", "BrofilerCore/Event.cpp", "BrofilerCore/EventDescription.h", "BrofilerCore/EventDescription.cpp", "BrofilerCore/EventDescriptionBoard.h", "BrofilerCore/EventDescriptionBoard.cpp", "BrofilerCore/Sampler.h", "BrofilerCore/Sampler.cpp", "BrofilerCore/SymEngine.h", "BrofilerCore/SymEngine.cpp", }, ["Network"] = { "BrofilerCore/Message.h", "BrofilerCore/Message.cpp", "BrofilerCore/ProfilerServer.h", "BrofilerCore/ProfilerServer.cpp", "BrofilerCore/Socket.h", "BrofilerCore/Serialization.h", "BrofilerCore/Serialization.cpp", }, ["System"] = { "BrofilerCore/Common.h", "BrofilerCore/Concurrency.h", "BrofilerCore/HPTimer.h", "BrofilerCore/HPTimer.cpp", "BrofilerCore/MemoryPool.h", "BrofilerCore/Thread.h", "BrofilerCore/Types.h", }, } project "TaskScheduler" excludes { "ThirdParty/TaskScheduler/Scheduler/Source/MTDefaultAppInterop.cpp", } kind "StaticLib" flags {"NoPCH"} defines {"USE_BROFILER=1"} files { "ThirdParty/TaskScheduler/Scheduler/**.*", } includedirs { "ThirdParty/TaskScheduler/Scheduler/Include", "BrofilerCore" } excludes { "Src/Platform/Posix/**.*" } vpaths { ["*"] = "TaskScheduler" } links { "BrofilerCore", } project "BrofilerTest" flags {"NoPCH"} kind "StaticLib" uuid "9A313DD9-8694-CC7D-2F1A-05341B5C9800" files { "BrofilerTest/**.*", } includedirs { "BrofilerCore", "ThirdParty/TaskScheduler/Scheduler/Include" } links { "BrofilerCore", "TaskScheduler" } if isUWP then -- Genie can't generate proper UWP application -- It's a dummy project to match existing project file project "BrofilerDurangoTest" location( "BrofilerDurangoTest" ) kind "WindowedApp" uuid "5CA6AF66-C2CB-412E-B335-B34357F2FBB6" files { "BrofilerDurangoTest/**.*", } else project "BrofilerWindowsTest" flags {"NoPCH"} kind "ConsoleApp" uuid "C50A1240-316C-EF4D-BAD9-3500263A260D" files { "BrofilerWindowsTest/**.*", "ThirdParty/TaskScheduler/Scheduler/Source/MTDefaultAppInterop.cpp", } vpaths { ["*"] = "BrofilerWindowsTest" } includedirs { "BrofilerCore", "BrofilerTest", "ThirdParty/TaskScheduler/Scheduler/Include" } links { "BrofilerCore", "BrofilerTest", "TaskScheduler" } end
Compilation fix
Compilation fix
Lua
mit
bombomby/brofiler,bombomby/brofiler,bombomby/brofiler
21f8e10147677a64c809a621222390995dc53401
plugins/chatter.lua
plugins/chatter.lua
local PLUGIN = {} PLUGIN.triggers = { '^@' .. bot.username .. ', ', '^' .. bot.first_name .. ', ' } function PLUGIN.action(msg) local input = get_input(msg.text) local url = 'http://www.simsimi.com/requestChat?lc=es&ft=1.0&req=' .. URL.escape(input) local jstr, res = HTTP.request(url) if res ~= 200 then return send_message(msg.chat.id, "I don't feel like talking right now.") end local jdat = JSON.decode(jstr) if string.match(jdat.res, '^I HAVE NO RESPONSE.') then jdat.res = "I don't know what to say to that." end send_message(msg.chat.id, jdat.res) end return PLUGIN
-- shout-out to @luksi_reiku for showing me this site local PLUGIN = {} PLUGIN.triggers = { '^@' .. bot.username .. ', ', '^' .. bot.first_name .. ', ' } function PLUGIN.action(msg) local input = get_input(msg.text) local url = 'http://www.simsimi.com/requestChat?lc=en&ft=1.0&req=' .. URL.escape(input) local jstr, res = HTTP.request(url) if res ~= 200 then return send_message(msg.chat.id, "I don't feel like talking right now.") end local jdat = JSON.decode(jstr) if string.match(jdat.res, '^I HAVE NO RESPONSE.') then jdat.res = "I don't know what to say to that." end -- Let's clean up the response a little. Capitalization & punctuation. local message = jdat.res:gsub('simsimi', 'clive') local message = message:gsub("^%l", string.upper) if not string.match(message, '%p$') then message = message .. '.' end send_message(msg.chat.id, jdat.res) end return PLUGIN
bugfix
bugfix
Lua
mit
barreeeiroo/BarrePolice,Brawl345/Brawlbot-v2,TiagoDanin/SiD,bb010g/otouto,topkecleon/otouto
007513af4377b5129a86544c2f560190f86bb78d
base/gatheringcraft.lua
base/gatheringcraft.lua
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] local common = require("base.common") local treasure = require("item.base.treasure") module("base.gatheringcraft", package.seeall) RandomItem = { ID = 0, Quantity = 1, Quality = 333, Data = {}, Probability = 0, MessageDE = nil, MessageEN = nil, }; GatheringCraft = { RandomItems = { }, InterruptMsg = { }, Monsters = { }, LeadSkill = 0, SavedWorkTime = { }, Treasure = 0, TreasureMsg = { }, FoodLevel = 100, FastActionFactor = 1, LearnLimit = 20 }; Monster = { MonsterID = 0, Probability = 100, MessageDE = "", MessageEN = "", Sound = nil, GFX = nil }; function GatheringCraft:new(gc) gc = gc or {}; setmetatable(gc, self); self.__index = self; gc.RandomItems = {}; gc.InterruptMsg = {}; gc.Monsters = {}; gc.TreasureMsg = {}; return gc; end function RandomItem:new(item) item = item or {}; setmetatable(item, self); self.__index = self; return item; end function Monster:new(m) m = m or {}; setmetatable(m, self); self.__index = self; return m; end function GatheringCraft:SetFoodLevel(FoodLevel) self.FoodLevel = FoodLevel; end function GatheringCraft:SetTreasureMap(Probability, MessageDE, MessageEN) self.Treasure = Probability; self.TreasureMsg[1] = MessageDE; self.TreasureMsg[2] = MessageEN; end function GatheringCraft:AddInterruptMessage(MessageDE, MessageEN) table.insert(self.InterruptMsg, { MessageDE, MessageEN }); return; end function GatheringCraft:AddMonster(MonsterID, Probability, MessageDE, MessageEN, Sound, GFX) table.insert(self.Monsters, Monster:new{["MonsterID"] = MonsterID, ["Probability"] = Probability, ["MessageDE"] = MessageDE, ["MessageEN"] = MessageEN, ["Sound"] = Sound, ["GFX"] = GFX}); return; end function GatheringCraft:AddRandomItem(ItemID, Quantity, Quality, Data, Probability, MessageDE, MessageEN) table.insert(self.RandomItems, RandomItem:new{["ID"] = ItemID, ["Quantity"] = Quantity, ["Quality"] = Quality, ["Data"] = Data, ["Probability"] = Probability, ["MessageDE"] = MessageDE, ["MessageEN"] = MessageEN}); return; end -- @return If something was done function GatheringCraft:FindRandomItem(User) --[[Deactivate the call of interrupting messages. if math.random(1,100) == 50 then --why complicated if you can solve it simple... 1% chance for an interruption if(#self.InterruptMsg > 0) then local m = math.random(#self.InterruptMsg); common.InformNLS(User, self.InterruptMsg[m][1], self.InterruptMsg[m][2]); return true; end end --]] common.GetHungry(User, self.FoodLevel); -- FindRandomItem is called when the User is currently working. If there was -- a reload, the working time will be nil. Check for this case. if (self.SavedWorkTime[User.id] == nil) then -- Just generate the work time again. Does not matter really if this is not -- exactly the original value. self.SavedWorkTime[User.id] = self:GenWorkTime(User,nil); end -- check for Noobia if (common.isOnNoobia(User.pos)) then return false; end -- check for Prison Mine if (common.isInPrison(User.pos)) then return false end if (self.Treasure > 0) then local rand = math.random(); if(rand < self.Treasure*self.FastActionFactor) and treasure.createMap(User) then common.InformNLS(User, self.TreasureMsg[1], self.TreasureMsg[2]); return true; end end if (#self.Monsters > 0) then local ra = math.random(#self.Monsters); local pa = math.random(); if (pa < self.Monsters[ra].Probability*self.FastActionFactor) then local TargetPos = common.getFreePos(User.pos, 1) world:createMonster(self.Monsters[ra].MonsterID, TargetPos, 20); if ( self.Monsters[ra].GFX ~= nil ) then world:gfx(self.Monsters[ra].GFX, TargetPos); end if(self.Monsters[ra].Sound ~= nil) then world:makeSound(self.Monsters[ra].Sound, TargetPos); end common.InformNLS(User, self.Monsters[ra].MessageDE, self.Monsters[ra].MessageEN); return true; end end if(#self.RandomItems > 0) then -- check all items with same random number and choose any possible item again randomly local itemIndexList = {}; -- list all items that are possible for it = 1, #self.RandomItems, 1 do local rand = math.random(); if (rand <= self.RandomItems[it].Probability*self.FastActionFactor) then table.insert(itemIndexList, it); end end if ( #itemIndexList > 0 ) then -- For the unlikely case that two items were found at once, we just give one to the player local ind = itemIndexList[math.random(1,#itemIndexList)]; common.InformNLS(User, self.RandomItems[ind].MessageDE, self.RandomItems[ind].MessageEN); local notCreated = User:createItem(self.RandomItems[ind].ID, self.RandomItems[ind].Quantity, self.RandomItems[ind].Quality, self.RandomItems[ind].Data); if ( notCreated > 0 ) then -- too many items -> character can't carry anymore world:createItemFromId( self.RandomItems[ind].ID, notCreated, User.pos, true, self.RandomItems[ind].Quality, self.RandomItems[ind].Data ); common.HighInformNLS(User, "Du kannst nichts mehr halten.", "You can't carry any more."); end return true; end end return false; end -- Generate working time for gathering actions function GatheringCraft:GenWorkTime(User, toolItem) local minTime = 12; --Minimum time for skill 100 and normal tool local maxTime = 60; --Maximum time for skill 0 and normal tool local skill = common.Limit(User:getSkill(self.LeadSkill), 0, 100); local workTime = common.Scale(maxTime, minTime, skill); --scaling with the skill -- apply the quality bonus if ( toolItem ~= nil ) then local qual = common.Limit(math.floor(toolItem.quality/100), 1, 9); -- quality integer in [1,9] workTime = workTime - workTime*0.20*((qual-5)/4); --+/-20% depending on tool quality end workTime = workTime*self.FastActionFactor; --for fast actions. return math.ceil(workTime); end
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] local common = require("base.common") local treasure = require("item.base.treasure") module("base.gatheringcraft", package.seeall) RandomItem = { ID = 0, Quantity = 1, Quality = 333, Data = {}, Probability = 0, MessageDE = nil, MessageEN = nil, }; GatheringCraft = { RandomItems = { }, InterruptMsg = { }, Monsters = { }, LeadSkill = 0, SavedWorkTime = { }, Treasure = 0, TreasureMsg = { }, FoodLevel = 100, FastActionFactor = 1, LearnLimit = 20 }; Monster = { MonsterID = 0, Probability = 100, MessageDE = "", MessageEN = "", Sound = nil, GFX = nil }; function GatheringCraft:new(gc) gc = gc or {}; setmetatable(gc, self); self.__index = self; gc.RandomItems = {}; gc.InterruptMsg = {}; gc.Monsters = {}; gc.TreasureMsg = {}; return gc; end function RandomItem:new(item) item = item or {}; setmetatable(item, self); self.__index = self; return item; end function Monster:new(m) m = m or {}; setmetatable(m, self); self.__index = self; return m; end function GatheringCraft:SetFoodLevel(FoodLevel) self.FoodLevel = FoodLevel; end function GatheringCraft:SetTreasureMap(Probability, MessageDE, MessageEN) self.Treasure = Probability; self.TreasureMsg[1] = MessageDE; self.TreasureMsg[2] = MessageEN; end function GatheringCraft:AddInterruptMessage(MessageDE, MessageEN) table.insert(self.InterruptMsg, { MessageDE, MessageEN }); return; end function GatheringCraft:AddMonster(MonsterID, Probability, MessageDE, MessageEN, Sound, GFX) table.insert(self.Monsters, Monster:new{["MonsterID"] = MonsterID, ["Probability"] = Probability, ["MessageDE"] = MessageDE, ["MessageEN"] = MessageEN, ["Sound"] = Sound, ["GFX"] = GFX}); return; end function GatheringCraft:AddRandomItem(ItemID, Quantity, Quality, Data, Probability, MessageDE, MessageEN) table.insert(self.RandomItems, RandomItem:new{["ID"] = ItemID, ["Quantity"] = Quantity, ["Quality"] = Quality, ["Data"] = Data, ["Probability"] = Probability, ["MessageDE"] = MessageDE, ["MessageEN"] = MessageEN}); return; end -- @return If something was done function GatheringCraft:FindRandomItem(User) --[[Deactivate the call of interrupting messages. if math.random(1,100) == 50 then --why complicated if you can solve it simple... 1% chance for an interruption if(#self.InterruptMsg > 0) then local m = math.random(#self.InterruptMsg); common.InformNLS(User, self.InterruptMsg[m][1], self.InterruptMsg[m][2]); return true; end end --]] common.GetHungry(User, self.FoodLevel); -- FindRandomItem is called when the User is currently working. If there was -- a reload, the working time will be nil. Check for this case. if (self.SavedWorkTime[User.id] == nil) then -- Just generate the work time again. Does not matter really if this is not -- exactly the original value. self.SavedWorkTime[User.id] = self:GenWorkTime(User,nil); end -- check for Noobia if (common.isOnNoobia(User.pos)) then return false; end -- check for Prison Mine if (common.isInPrison(User.pos)) then return false end if (self.Treasure > 0) then local rand = math.random(); if(rand < self.Treasure*self.FastActionFactor) and treasure.createMap(User) then common.InformNLS(User, self.TreasureMsg[1], self.TreasureMsg[2]); return true; end end if (#self.Monsters > 0) then local ra = math.random(#self.Monsters); local pa = math.random(); if (pa < self.Monsters[ra].Probability*self.FastActionFactor) then local TargetPos = common.getFreePositions(User.pos, 1, true, true) if TargetPos == nil then return true end world:createMonster(self.Monsters[ra].MonsterID, TargetPos, 20); if ( self.Monsters[ra].GFX ~= nil ) then world:gfx(self.Monsters[ra].GFX, TargetPos); end if(self.Monsters[ra].Sound ~= nil) then world:makeSound(self.Monsters[ra].Sound, TargetPos); end common.InformNLS(User, self.Monsters[ra].MessageDE, self.Monsters[ra].MessageEN); return true; end end if(#self.RandomItems > 0) then -- check all items with same random number and choose any possible item again randomly local itemIndexList = {}; -- list all items that are possible for it = 1, #self.RandomItems, 1 do local rand = math.random(); if (rand <= self.RandomItems[it].Probability*self.FastActionFactor) then table.insert(itemIndexList, it); end end if ( #itemIndexList > 0 ) then -- For the unlikely case that two items were found at once, we just give one to the player local ind = itemIndexList[math.random(1,#itemIndexList)]; common.InformNLS(User, self.RandomItems[ind].MessageDE, self.RandomItems[ind].MessageEN); local notCreated = User:createItem(self.RandomItems[ind].ID, self.RandomItems[ind].Quantity, self.RandomItems[ind].Quality, self.RandomItems[ind].Data); if ( notCreated > 0 ) then -- too many items -> character can't carry anymore world:createItemFromId( self.RandomItems[ind].ID, notCreated, User.pos, true, self.RandomItems[ind].Quality, self.RandomItems[ind].Data ); common.HighInformNLS(User, "Du kannst nichts mehr halten.", "You can't carry any more."); end return true; end end return false; end -- Generate working time for gathering actions function GatheringCraft:GenWorkTime(User, toolItem) local minTime = 12; --Minimum time for skill 100 and normal tool local maxTime = 60; --Maximum time for skill 0 and normal tool local skill = common.Limit(User:getSkill(self.LeadSkill), 0, 100); local workTime = common.Scale(maxTime, minTime, skill); --scaling with the skill -- apply the quality bonus if ( toolItem ~= nil ) then local qual = common.Limit(math.floor(toolItem.quality/100), 1, 9); -- quality integer in [1,9] workTime = workTime - workTime*0.20*((qual-5)/4); --+/-20% depending on tool quality end workTime = workTime*self.FastActionFactor; --for fast actions. return math.ceil(workTime); end
fix #10591: dont spawn monster on same field as character, and allow spawning on positions with items on them
fix #10591: dont spawn monster on same field as character, and allow spawning on positions with items on them
Lua
agpl-3.0
Illarion-eV/Illarion-Content,KayMD/Illarion-Content,Baylamon/Illarion-Content,vilarion/Illarion-Content
773b371cb4084720f3e729c2b4fc6a95a5547c09
spotify-widget/spotify.lua
spotify-widget/spotify.lua
------------------------------------------------- -- Spotify Widget for Awesome Window Manager -- Shows currently playing song on Spotify for Linux client -- More details could be found here: -- https://github.com/streetturtle/awesome-wm-widgets/tree/master/spotify-widget -- @author Pavel Makhov -- @copyright 2020 Pavel Makhov ------------------------------------------------- local awful = require("awful") local wibox = require("wibox") local watch = require("awful.widget.watch") local GET_SPOTIFY_STATUS_CMD = 'sp status' local GET_CURRENT_SONG_CMD = 'sp current' local function ellipsize(text, length) return (text:len() > length and length > 0) and text:sub(0, length - 3) .. '...' or text end local spotify_widget = {} local function worker(user_args) local args = user_args or {} local play_icon = args.play_icon or '/usr/share/icons/Arc/actions/24/player_play.png' local pause_icon = args.pause_icon or '/usr/share/icons/Arc/actions/24/player_pause.png' local font = args.font or 'Play 9' local dim_when_paused = args.dim_when_paused == nil and false or args.dim_when_paused local dim_opacity = args.dim_opacity or 0.2 local max_length = args.max_length or 15 local show_tooltip = args.show_tooltip == nil and true or args.show_tooltip local timeout = args.timeout or 1 local cur_artist = '' local cur_title = '' local cur_album = '' spotify_widget = wibox.widget { { id = 'artistw', font = font, widget = wibox.widget.textbox, }, { id = "icon", widget = wibox.widget.imagebox, }, { layout = wibox.container.scroll.horizontal, max_size = 100, step_function = wibox.container.scroll.step_functions.waiting_nonlinear_back_and_forth, speed = 40, { id = 'titlew', font = font, widget = wibox.widget.textbox } }, layout = wibox.layout.align.horizontal, set_status = function(self, is_playing) self.icon.image = (is_playing and play_icon or pause_icon) if dim_when_paused then self:get_children_by_id('icon')[1]:set_opacity(is_playing and 1 or dim_opacity) self:get_children_by_id('titlew')[1]:set_opacity(is_playing and 1 or dim_opacity) self:get_children_by_id('titlew')[1]:emit_signal('widget::redraw_needed') self:get_children_by_id('artistw')[1]:set_opacity(is_playing and 1 or dim_opacity) self:get_children_by_id('artistw')[1]:emit_signal('widget::redraw_needed') end end, set_text = function(self, artist, song) local artist_to_display = ellipsize(artist, max_length) if self:get_children_by_id('artistw')[1]:get_markup() ~= artist_to_display then self:get_children_by_id('artistw')[1]:set_markup(artist_to_display) end local title_to_display = ellipsize(song, max_length) if self:get_children_by_id('titlew')[1]:get_markup() ~= title_to_display then self:get_children_by_id('titlew')[1]:set_markup(title_to_display) end end } local update_widget_icon = function(widget, stdout, _, _, _) stdout = string.gsub(stdout, "\n", "") widget:set_status(stdout == 'Playing' and true or false) end local update_widget_text = function(widget, stdout, _, _, _) if string.find(stdout, 'Error: Spotify is not running.') ~= nil then widget:set_text('','') widget:set_visible(false) return end local escaped = string.gsub(stdout, "&", '&amp;') local album, _, artist, title = string.match(escaped, 'Album%s*(.*)\nAlbumArtist%s*(.*)\nArtist%s*(.*)\nTitle%s*(.*)\n') if album ~= nil and title ~=nil and artist ~= nil then cur_artist = artist cur_title = title cur_album = album widget:set_text(artist, title) widget:set_visible(true) end end watch(GET_SPOTIFY_STATUS_CMD, timeout, update_widget_icon, spotify_widget) watch(GET_CURRENT_SONG_CMD, timeout, update_widget_text, spotify_widget) --- Adds mouse controls to the widget: -- - left click - play/pause -- - scroll up - play next song -- - scroll down - play previous song spotify_widget:connect_signal("button::press", function(_, _, _, button) if (button == 1) then awful.spawn("sp play", false) -- left click elseif (button == 4) then awful.spawn("sp next", false) -- scroll up elseif (button == 5) then awful.spawn("sp prev", false) -- scroll down end awful.spawn.easy_async(GET_SPOTIFY_STATUS_CMD, function(stdout, stderr, exitreason, exitcode) update_widget_icon(spotify_widget, stdout, stderr, exitreason, exitcode) end) end) if show_tooltip then local spotify_tooltip = awful.tooltip { mode = 'outside', preferred_positions = {'bottom'}, } spotify_tooltip:add_to_object(spotify_widget) spotify_widget:connect_signal('mouse::enter', function() spotify_tooltip.markup = '<b>Album</b>: ' .. cur_album .. '\n<b>Artist</b>: ' .. cur_artist .. '\n<b>Song</b>: ' .. cur_title end) end return spotify_widget end return setmetatable(spotify_widget, { __call = function(_, ...) return worker(...) end })
------------------------------------------------- -- Spotify Widget for Awesome Window Manager -- Shows currently playing song on Spotify for Linux client -- More details could be found here: -- https://github.com/streetturtle/awesome-wm-widgets/tree/master/spotify-widget -- @author Pavel Makhov -- @copyright 2020 Pavel Makhov ------------------------------------------------- local awful = require("awful") local wibox = require("wibox") local watch = require("awful.widget.watch") local GET_SPOTIFY_STATUS_CMD = 'sp status' local GET_CURRENT_SONG_CMD = 'sp current' local function ellipsize(text, length) return (utf8.len(text) > length and length > 0) and text:sub(0, utf8.offset(text, length - 2) - 1) .. '...' or text end local spotify_widget = {} local function worker(user_args) local args = user_args or {} local play_icon = args.play_icon or '/usr/share/icons/Arc/actions/24/player_play.png' local pause_icon = args.pause_icon or '/usr/share/icons/Arc/actions/24/player_pause.png' local font = args.font or 'Play 9' local dim_when_paused = args.dim_when_paused == nil and false or args.dim_when_paused local dim_opacity = args.dim_opacity or 0.2 local max_length = args.max_length or 15 local show_tooltip = args.show_tooltip == nil and true or args.show_tooltip local timeout = args.timeout or 1 local cur_artist = '' local cur_title = '' local cur_album = '' spotify_widget = wibox.widget { { id = 'artistw', font = font, widget = wibox.widget.textbox, }, { id = "icon", widget = wibox.widget.imagebox, }, { layout = wibox.container.scroll.horizontal, max_size = 100, step_function = wibox.container.scroll.step_functions.waiting_nonlinear_back_and_forth, speed = 40, { id = 'titlew', font = font, widget = wibox.widget.textbox } }, layout = wibox.layout.align.horizontal, set_status = function(self, is_playing) self.icon.image = (is_playing and play_icon or pause_icon) if dim_when_paused then self:get_children_by_id('icon')[1]:set_opacity(is_playing and 1 or dim_opacity) self:get_children_by_id('titlew')[1]:set_opacity(is_playing and 1 or dim_opacity) self:get_children_by_id('titlew')[1]:emit_signal('widget::redraw_needed') self:get_children_by_id('artistw')[1]:set_opacity(is_playing and 1 or dim_opacity) self:get_children_by_id('artistw')[1]:emit_signal('widget::redraw_needed') end end, set_text = function(self, artist, song) local artist_to_display = ellipsize(artist, max_length) if self:get_children_by_id('artistw')[1]:get_markup() ~= artist_to_display then self:get_children_by_id('artistw')[1]:set_markup(artist_to_display) end local title_to_display = ellipsize(song, max_length) if self:get_children_by_id('titlew')[1]:get_markup() ~= title_to_display then self:get_children_by_id('titlew')[1]:set_markup(title_to_display) end end } local update_widget_icon = function(widget, stdout, _, _, _) stdout = string.gsub(stdout, "\n", "") widget:set_status(stdout == 'Playing' and true or false) end local update_widget_text = function(widget, stdout, _, _, _) if string.find(stdout, 'Error: Spotify is not running.') ~= nil then widget:set_text('','') widget:set_visible(false) return end local escaped = string.gsub(stdout, "&", '&amp;') local album, _, artist, title = string.match(escaped, 'Album%s*(.*)\nAlbumArtist%s*(.*)\nArtist%s*(.*)\nTitle%s*(.*)\n') if album ~= nil and title ~=nil and artist ~= nil then cur_artist = artist cur_title = title cur_album = album widget:set_text(artist, title) widget:set_visible(true) end end watch(GET_SPOTIFY_STATUS_CMD, timeout, update_widget_icon, spotify_widget) watch(GET_CURRENT_SONG_CMD, timeout, update_widget_text, spotify_widget) --- Adds mouse controls to the widget: -- - left click - play/pause -- - scroll up - play next song -- - scroll down - play previous song spotify_widget:connect_signal("button::press", function(_, _, _, button) if (button == 1) then awful.spawn("sp play", false) -- left click elseif (button == 4) then awful.spawn("sp next", false) -- scroll up elseif (button == 5) then awful.spawn("sp prev", false) -- scroll down end awful.spawn.easy_async(GET_SPOTIFY_STATUS_CMD, function(stdout, stderr, exitreason, exitcode) update_widget_icon(spotify_widget, stdout, stderr, exitreason, exitcode) end) end) if show_tooltip then local spotify_tooltip = awful.tooltip { mode = 'outside', preferred_positions = {'bottom'}, } spotify_tooltip:add_to_object(spotify_widget) spotify_widget:connect_signal('mouse::enter', function() spotify_tooltip.markup = '<b>Album</b>: ' .. cur_album .. '\n<b>Artist</b>: ' .. cur_artist .. '\n<b>Song</b>: ' .. cur_title end) end return spotify_widget end return setmetatable(spotify_widget, { __call = function(_, ...) return worker(...) end })
fixed unicode truncation bug
fixed unicode truncation bug
Lua
mit
streetturtle/awesome-wm-widgets,streetturtle/awesome-wm-widgets
59a7e8c01d73c892c289d8fa0a59b617dcb3f7be
inventory.lua
inventory.lua
local component = require("component") local ic = component.inventory_controller local robot = require("robot") local sides = require("sides") local util = require("util") local inventory = {} function inventory.isOneOf(item, checkList) for _,chk in ipairs(checkList) do if chk == "!tool" then if item.maxDamage > 0 then return true end elseif string.match(item.name, chk) then return true end end return false end function inventory.dropAll(side, fromSlotNumber, exceptFor) -- tries to drop all the robot's inventory into the storage on the given side -- returns true if all if it could be unloaded, false if none or only some could --robot.drop([number]) -- Returns true if at least one item was dropped, false otherwise. local couldDropAll = true exceptFor = exceptFor or {} fromSlotNumber = fromSlotNumber or 1 for i=fromSlotNumber,robot.inventorySize() do local c = robot.count(i) if c > 0 then local stack = ic.getStackInInternalSlot(i) if not inventory.isOneOf(stack, exceptFor) then robot.select(i) if side == nil or side == sides.front then robot.drop() elseif side == sides.bottom then robot.dropDown() elseif side == sides.top then robot.dropUp() end -- see if all the items were successfully dropped c = robot.count(i) if c > 0 then -- at least one item couldn't be dropped. -- but we keep trying to drop all so we still drop as much as we can. couldDropAll = false end end --isOneOf end end return couldDropAll end function inventory.isIdealTorchSpot(x, z) local isZ = (z % 7) local isX = (x % 12) if isZ ~= 0 or (isX ~= 0 and isX ~= 6) then return false end -- we skip every other x torch in the first row, -- and the 'other' every other torch in the next row local zRow = math.floor(z / 7) % 2 if (zRow == 0 and isX == 6) or (zRow == 1 and isX == 0) then return false end return true end function inventory.selectItem(pattern) for i=1,robot.inventorySize() do local stack = ic.getStackInInternalSlot(i) if stack ~= nil and string.find(stack.name, pattern) ~= nil then robot.select(i) return true end end return false end function inventory.placeTorch(sideOfRobot, sideOfBlock) if inventory.selectItem("torch$") then local success if sideOfRobot == nil or sideOfRobot == sides.down then success = robot.placeDown(sideOfBlock or sides.bottom) elseif sideOfRobot == sides.front then success = robot.place(sideOfBlock or sides.bottom) end if success then return true end end return false end function inventory.isLocalFull() -- backwards cuz the later slots fill up last for i=robot.inventorySize(),1,-1 do local stack = ic.getStackInInternalSlot(i) if stack == nil then return false end end return true end function inventory.toolIsBroken() local d = robot.durability() d = util.trunc(d or 0, 2) return d <= 0 end function inventory.pickUpFreshTools(sideOfRobot, toolName) sideOfRobot = sideOfRobot or sides.bottom local size = ic.getInventorySize() if size == nil then return false end local count = 0 for i=1,size do local stack = ic.getStackInSlot(sideOfRobot, i) -- is this the tool we want and fully repaired? if stack ~= nil and (stack.name == toolName or string.match(stack.name, toolName)) and stack.damage == stack.maxDamage then -- found one, get it! robot.select(1) -- select 1 cuz it will fill into an empty slot at or after that if not ic.suckFromSlot(sideOfRobot, i) then return false end count = count + 1 end end return true, count end function inventory.dropBrokenTools(sideOfRobot, toolName) sideOfRobot = sideOfRobot or sides.bottom local brokenToolsCount = 0 for i=1,robot.inventorySize() do local stack = ic.getStackInInternalSlot(i) if stack ~= nil and (stack.name == toolName or string.match(stack.name, toolName)) then -- is this a broken tool? local isBroken = util.trunc((stack.maxDamage-stack.damage) / stack.maxDamage, 2) <= 0 if isBroken then brokenToolsCount = brokenToolsCount + 1 -- drop it robot.select(i) local result = (sideOfRobot == sides.bottom and robot.dropDown(1)) or (sideOfRobot == sides.front and robot.drop(1)) if not result then return false, brokenToolsCount end end end end -- finally we need to see if the tool we are holding is broken robot.select(1) ic.equip() local stack = ic.getStackInInternalSlot(1) if stack ~= nil and stack.name == toolName then -- is this a broken tool? local isBroken = util.trunc((stack.maxDamage-stack.damage) / stack.maxDamage, 2) <= 0 if isBroken then brokenToolsCount = brokenToolsCount + 1 if not robot.dropDown(1) then ic.equip() return false, brokenToolsCount end end end ic.equip() return true, brokenToolsCount end function inventory.equipFreshTool(itemName) if itemName == nil then -- use the currently selected tool as the pattern. -- first we must see what tool it is we currently have -- swap it with slot 1 robot.select(1) ic.equip() local currentTool = ic.getStackInInternalSlot() -- equip it back since whatever was in slot 1 might be important ic.equip() if currentTool == nil then -- no current tool, sorry return false end itemName = currentTool.name end for i=1,robot.inventorySize() do local stack = ic.getStackInInternalSlot(i) if itemName == "!empty" then if stack == nil or (stack.maxDamage == nil or stack.maxDamage == 0) then -- found an empty slot or at least something that doesn't use durability robot.select(i) ic.equip() return true end elseif stack ~= nil and (stack.name == itemName or string.match(stack.name, itemName)) then robot.select(i) ic.equip() -- found one but we need to check if it's got durability if not inventory.toolIsBroken() then return true end -- not durable enough, so put it back and keep looking ic.equip() end end return false end return inventory
local component = require("component") local ic = component.inventory_controller local robot = require("robot") local sides = require("sides") local util = require("util") local inventory = {} function inventory.isOneOf(item, checkList) for _,chk in ipairs(checkList) do if chk == "!tool" then if item.maxDamage > 0 then return true end elseif string.match(item.name, chk) then return true end end return false end function inventory.dropAll(side, fromSlotNumber, exceptFor) -- tries to drop all the robot's inventory into the storage on the given side -- returns true if all if it could be unloaded, false if none or only some could --robot.drop([number]) -- Returns true if at least one item was dropped, false otherwise. local couldDropAll = true exceptFor = exceptFor or {} fromSlotNumber = fromSlotNumber or 1 for i=fromSlotNumber,robot.inventorySize() do local c = robot.count(i) if c > 0 then local stack = ic.getStackInInternalSlot(i) if not inventory.isOneOf(stack, exceptFor) then robot.select(i) if side == nil or side == sides.front then robot.drop() elseif side == sides.bottom then robot.dropDown() elseif side == sides.top then robot.dropUp() end -- see if all the items were successfully dropped c = robot.count(i) if c > 0 then -- at least one item couldn't be dropped. -- but we keep trying to drop all so we still drop as much as we can. couldDropAll = false end end --isOneOf end end return couldDropAll end function inventory.isIdealTorchSpot(x, z) local isZ = (z % 7) local isX = (x % 12) if isZ ~= 0 or (isX ~= 0 and isX ~= 6) then return false end -- we skip every other x torch in the first row, -- and the 'other' every other torch in the next row local zRow = math.floor(z / 7) % 2 if (zRow == 0 and isX == 6) or (zRow == 1 and isX == 0) then return false end return true end function inventory.selectItem(pattern) for i=1,robot.inventorySize() do local stack = ic.getStackInInternalSlot(i) if stack ~= nil and string.find(stack.name, pattern) ~= nil then robot.select(i) return true end end return false end function inventory.placeTorch(sideOfRobot, sideOfBlock) if inventory.selectItem("torch$") then local success if sideOfRobot == nil or sideOfRobot == sides.down then success = robot.placeDown(sideOfBlock or sides.bottom) elseif sideOfRobot == sides.front then success = robot.place(sideOfBlock or sides.bottom) end if success then return true end end return false end function inventory.isLocalFull() -- backwards cuz the later slots fill up last for i=robot.inventorySize(),1,-1 do local stack = ic.getStackInInternalSlot(i) if stack == nil then return false end end return true end function inventory.toolIsBroken() local d = robot.durability() d = util.trunc(d or 0, 2) return d <= 0 end function inventory.pickUpFreshTools(sideOfRobot, toolName) sideOfRobot = sideOfRobot or sides.bottom local size = ic.getInventorySize() if size == nil then return false end local count = 0 for i=1,size do local stack = ic.getStackInSlot(sideOfRobot, i) -- is this the tool we want and fully repaired? if stack ~= nil and (stack.name == toolName or string.match(stack.name, toolName)) and stack.damage == stack.maxDamage then -- found one, get it! robot.select(1) -- select 1 cuz it will fill into an empty slot at or after that if not ic.suckFromSlot(sideOfRobot, i) then return false end count = count + 1 end end return true, count end function inventory.dropBrokenTools(sideOfRobot, toolName) sideOfRobot = sideOfRobot or sides.bottom local brokenToolsCount = 0 for i=1,robot.inventorySize() do local stack = ic.getStackInInternalSlot(i) if stack ~= nil and (stack.name == toolName or string.match(stack.name, toolName)) then -- is this a broken tool? local isBroken = util.trunc((stack.maxDamage-stack.damage) / stack.maxDamage, 2) <= 0 if isBroken then brokenToolsCount = brokenToolsCount + 1 -- drop it robot.select(i) local result = (sideOfRobot == sides.bottom and robot.dropDown(1)) or (sideOfRobot == sides.front and robot.drop(1)) if not result then return false, brokenToolsCount end end end end -- finally we need to see if the tool we are holding is broken robot.select(1) ic.equip() local stack = ic.getStackInInternalSlot(1) if stack ~= nil and (stack.name == toolName or string.match(stack.name, toolName)) then -- is this a broken tool? local isBroken = util.trunc((stack.maxDamage-stack.damage) / stack.maxDamage, 2) <= 0 if isBroken then brokenToolsCount = brokenToolsCount + 1 if not robot.dropDown(1) then ic.equip() return false, brokenToolsCount end end end ic.equip() return true, brokenToolsCount end function inventory.equipFreshTool(itemName) if itemName == nil then -- use the currently selected tool as the pattern. -- first we must see what tool it is we currently have -- swap it with slot 1 robot.select(1) ic.equip() local currentTool = ic.getStackInInternalSlot() -- equip it back since whatever was in slot 1 might be important ic.equip() if currentTool == nil then -- no current tool, sorry return false end itemName = currentTool.name end for i=1,robot.inventorySize() do local stack = ic.getStackInInternalSlot(i) if itemName == "!empty" then if stack == nil or (stack.maxDamage == nil or stack.maxDamage == 0) then -- found an empty slot or at least something that doesn't use durability robot.select(i) ic.equip() return true end elseif stack ~= nil and (stack.name == itemName or string.match(stack.name, itemName)) then robot.select(i) ic.equip() -- found one but we need to check if it's got durability if not inventory.toolIsBroken() then return true end -- not durable enough, so put it back and keep looking ic.equip() end end return false end return inventory
fixes issue with checking current tool
fixes issue with checking current tool
Lua
apache-2.0
InfinitiesLoop/oclib
ffd48633c2a7570da81b277743eb7ba196a4a78b
lualib/redis.lua
lualib/redis.lua
local skynet = require "skynet" local socket = require "socket" local config = require "config" local redis_conf = skynet.getenv "redis" local name = config (redis_conf) local readline = socket.readline local readbytes = socket.read local table = table local string = string local redis = {} local command = {} local meta = { __index = command, __gc = function(self) socket.close(self.__handle) end, } function redis.connect(dbname) local db_conf = name[dbname] local fd = assert(socket.open(db_conf.host, db_conf.port or 6379)) local r = setmetatable( { __handle = fd, __mode = false }, meta ) if db_conf.db ~= nil then r:select(db_conf.db) end return r end function command:disconnect() socket.close(self.__handle) setmetatable(self, nil) end local function compose_message(msg) if #msg == 1 then return msg[1] .. "\r\n" end local lines = { "*" .. #msg } for _,v in ipairs(msg) do local t = type(v) if t == "number" then v = tostring(v) elseif t == "userdata" then v = int64.tostring(int64.new(v),10) end table.insert(lines,"$"..#v) table.insert(lines,v) end table.insert(lines,"") local cmd = table.concat(lines,"\r\n") return cmd end local redcmd = {} redcmd[42] = function(fd, data) -- '*' local n = tonumber(data) if n < 0 then return true, nil end local bulk = {} for i = 1,n do local line = readline(fd,"\r\n") local bytes = tonumber(string.sub(line,2)) if bytes >= 0 then local data = readbytes(fd, bytes + 2) -- bulk[i] = nil when bytes < 0 bulk[i] = string.sub(data,1,-3) end end return true, bulk end redcmd[36] = function(fd, data) -- '$' local bytes = tonumber(data) if bytes < 0 then return true,nil end local firstline = readbytes(fd, 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 = readline(fd, "\r\n") local firstchar = string.byte(result) local data = string.sub(result,2) return redcmd[firstchar](fd,data) end setmetatable(command, { __index = function(t,k) local cmd = string.upper(k) local f = function (self, ...) local fd = self.__handle if self.__mode then socket.write(fd, compose_message { cmd, ... }) self.__batch = self.__batch + 1 else socket.lock(fd) socket.write(fd, compose_message { cmd, ... }) local ok, ret = read_response(fd) socket.unlock(fd) assert(ok, ret) return ret end end t[k] = f return f end}) function command:exists(key) assert(not self.__mode, "exists can't used in batch mode") local fd = self.__handle socket.lock(fd) socket.write(fd, compose_message { "EXISTS", key }) local ok, exists = read_response(fd) socket.unlock(fd) assert(ok, exists) return exists ~= 0 end function command:sismember(key, value) assert(not self.__mode, "sismember can't used in batch mode") local fd = self.__handle socket.lock(fd) socket.write(fd, compose_message { "SISMEMBER", key, value }) local ok, ismember = read_response(fd) socket.unlock(fd) assert(ok, ismember) return ismember ~= 0 end function command:batch(mode) if mode == "end" then local fd = self.__handle if self.__mode == "read" then local allok = true local allret = {} for i = 1, self.__batch do local ok, ret = read_response(fd) allok = allok and ok allret[i] = ret end self.__mode = false socket.unlock(self.__handle) assert(allok, "batch read failed") return allret else local allok = true for i = 1, self.__batch do local ok = read_response(fd) allok = allok and ok end self.__mode = false socket.unlock(self.__handle) return allok end else assert(mode == "read" or mode == "write") socket.lock(self.__handle) self.__mode = mode self.__batch = 0 end end function command:multi() local fd = self.__handle socket.lock(fd) self.__mode = "multi" self.__batch = 0 socket.write(fd, "MULTI\r\n") end local function read_exec(fd) local result = readline(fd, "\r\n") local firstchar = string.byte(result) local data = string.sub(result,2) if firstchar ~= 42 then return false, data end local n = tonumber(data) local result = {} local err = nil for i = 1,n do local ok, r = read_response(fd) result[i] = r if not err then err = {} for j = 1, i-1 do err[j] = true end end err[i] = ok end return result, err end function command:exec() if self.__mode ~= "multi" then error "call multi first" end local fd = self.__handle socket.write(fd, "EXEC\r\n") local allok = true for i = 0, self.__batch do local ok, queue = read_response(fd) allok = allok and ok end if not allok then self.__mode = false socket.unlock(fd) error "Queue command error" end local result, err = read_exec(fd) self.__mode = false socket.unlock(fd) if not result then error(err) elseif err then local errmsg = "" for k,v in ipairs(err) do if v == false then errmsg = errmsg .. k .. ":" .. result[k] end end error(errmsg) end return result end return redis
local skynet = require "skynet" local socket = require "socket" local config = require "config" local redis_conf = skynet.getenv "redis" local name = config (redis_conf) local readline = socket.readline local readbytes = socket.read local table = table local string = string local redis = {} local command = {} local meta = { __index = command, __gc = function(self) socket.close(self.__handle) end, } function redis.connect(dbname) local db_conf = name[dbname] local fd = assert(socket.open(db_conf.host, db_conf.port or 6379)) local r = setmetatable( { __handle = fd, __mode = false }, meta ) if db_conf.db ~= nil then r:select(db_conf.db) end return r end function command:disconnect() socket.close(self.__handle) setmetatable(self, nil) end local function compose_message(msg) if #msg == 1 then return msg[1] .. "\r\n" end local lines = { "*" .. #msg } for _,v in ipairs(msg) do local t = type(v) if t == "number" then v = tostring(v) elseif t == "userdata" then v = int64.tostring(int64.new(v),10) end table.insert(lines,"$"..#v) table.insert(lines,v) end table.insert(lines,"") local cmd = table.concat(lines,"\r\n") return cmd end local redcmd = {} redcmd[42] = function(fd, data) -- '*' local n = tonumber(data) if n < 0 then return true, nil end local bulk = {} for i = 1,n do local line = readline(fd,"\r\n") local bytes = tonumber(string.sub(line,2)) if bytes >= 0 then local data = readbytes(fd, bytes + 2) -- bulk[i] = nil when bytes < 0 bulk[i] = string.sub(data,1,-3) end end return true, bulk end redcmd[36] = function(fd, data) -- '$' local bytes = tonumber(data) if bytes < 0 then return true,nil end local firstline = readbytes(fd, 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 = readline(fd, "\r\n") local firstchar = string.byte(result) local data = string.sub(result,2) return redcmd[firstchar](fd,data) end setmetatable(command, { __index = function(t,k) local cmd = string.upper(k) local f = function (self, ...) local fd = self.__handle if self.__mode then socket.write(fd, compose_message { cmd, ... }) self.__batch = self.__batch + 1 else socket.lock(fd) socket.write(fd, compose_message { cmd, ... }) local ok, ret = read_response(fd) socket.unlock(fd) assert(ok, ret) return ret end end t[k] = f return f end}) function command:exists(key) assert(not self.__mode, "exists can't used in batch mode") local fd = self.__handle socket.lock(fd) socket.write(fd, compose_message { "EXISTS", key }) local ok, exists = read_response(fd) socket.unlock(fd) assert(ok, exists) return exists ~= 0 end function command:sismember(key, value) assert(not self.__mode, "sismember can't used in batch mode") local fd = self.__handle socket.lock(fd) socket.write(fd, compose_message { "SISMEMBER", key, value }) local ok, ismember = read_response(fd) socket.unlock(fd) assert(ok, ismember) return ismember ~= 0 end function command:batch(mode) if mode == "end" then local fd = self.__handle if self.__mode == "read" then local allok = true local allret = {} for i = 1, self.__batch do local ok, ret = read_response(fd) allok = allok and ok allret[i] = ret end self.__mode = false socket.unlock(self.__handle) assert(allok, "batch read failed") return allret else local allok = true for i = 1, self.__batch do local ok = read_response(fd) allok = allok and ok end self.__mode = false socket.unlock(self.__handle) return allok end else assert(mode == "read" or mode == "write") socket.lock(self.__handle) self.__mode = mode self.__batch = 0 end end function command:multi() local fd = self.__handle socket.lock(fd) self.__mode = "multi" self.__batch = 0 socket.write(fd, "MULTI\r\n") end local function read_exec(fd) local result = readline(fd, "\r\n") local firstchar = string.byte(result) local data = string.sub(result,2) if firstchar ~= 42 then return false, data end local n = tonumber(data) local result = {} local err = nil for i = 1,n do local ok, r = read_response(fd) result[i] = r if err then err[i] = ok else if ok == false then err = {} for j = 1, i-1 do err[j] = true end err[i] = false end end end return result, err end function command:exec() if self.__mode ~= "multi" then error "call multi first" end local fd = self.__handle socket.write(fd, "EXEC\r\n") local allok = true for i = 0, self.__batch do local ok, queue = read_response(fd) allok = allok and ok end if not allok then self.__mode = false socket.unlock(fd) error "Queue command error" end local result, err = read_exec(fd) self.__mode = false socket.unlock(fd) if not result then error(err) elseif err then local errmsg = "" for k,v in ipairs(err) do if v == false then errmsg = errmsg .. k .. ":" .. result[k] end end error(errmsg) end return result end return redis
bugfix #53
bugfix #53
Lua
mit
iskygame/skynet,sdgdsffdsfff/skynet,bingo235/skynet,Zirpon/skynet,icetoggle/skynet,cmingjian/skynet,ruleless/skynet,qyli/test,zzh442856860/skynet-Note,togolwb/skynet,pichina/skynet,enulex/skynet,codingabc/skynet,fhaoquan/skynet,boyuegame/skynet,zzh442856860/skynet,hongling0/skynet,leezhongshan/skynet,chuenlungwang/skynet,zhouxiaoxiaoxujian/skynet,cdd990/skynet,qyli/test,firedtoad/skynet,longmian/skynet,MRunFoss/skynet,JiessieDawn/skynet,vizewang/skynet,vizewang/skynet,catinred2/skynet,LuffyPan/skynet,dymx101/skynet,LuffyPan/skynet,letmefly/skynet,jxlczjp77/skynet,MoZhonghua/skynet,xjdrew/skynet,lawnight/skynet,czlc/skynet,zhaijialong/skynet,puXiaoyi/skynet,QuiQiJingFeng/skynet,catinred2/skynet,ilylia/skynet,enulex/skynet,boyuegame/skynet,peimin/skynet,cuit-zhaxin/skynet,ruleless/skynet,KittyCookie/skynet,zhangshiqian1214/skynet,bttscut/skynet,rainfiel/skynet,codingabc/skynet,cdd990/skynet,chenjiansnail/skynet,asanosoyokaze/skynet,chuenlungwang/skynet,lynx-seu/skynet,yunGit/skynet,u20024804/skynet,wangjunwei01/skynet,jxlczjp77/skynet,jxlczjp77/skynet,ag6ag/skynet,jiuaiwo1314/skynet,gitfancode/skynet,great90/skynet,czlc/skynet,ludi1991/skynet,harryzeng/skynet,leezhongshan/skynet,bingo235/skynet,peimin/skynet,javachengwc/skynet,lawnight/skynet,zzh442856860/skynet-Note,firedtoad/skynet,great90/skynet,Zirpon/skynet,liuxuezhan/skynet,cloudwu/skynet,wangyi0226/skynet,sanikoyes/skynet,xinjuncoding/skynet,zzh442856860/skynet,bingo235/skynet,hongling0/skynet,winglsh/skynet,MetSystem/skynet,liuxuezhan/skynet,samael65535/skynet,winglsh/skynet,chenjiansnail/skynet,ruleless/skynet,cpascal/skynet,your-gatsby/skynet,chfg007/skynet,dymx101/skynet,korialuo/skynet,iskygame/skynet,zhouxiaoxiaoxujian/skynet,yinjun322/skynet,lc412/skynet,kyle-wang/skynet,lawnight/skynet,MoZhonghua/skynet,ypengju/skynet_comment,microcai/skynet,xinjuncoding/skynet,letmefly/skynet,peimin/skynet_v0.1_with_notes,zzh442856860/skynet-Note,pigparadise/skynet,nightcj/mmo,chenjiansnail/skynet,wangjunwei01/skynet,sanikoyes/skynet,cpascal/skynet,pigparadise/skynet,zhaijialong/skynet,firedtoad/skynet,zzh442856860/skynet-Note,liuxuezhan/skynet,kebo/skynet,KAndQ/skynet,KAndQ/skynet,yunGit/skynet,cuit-zhaxin/skynet,matinJ/skynet,xcjmine/skynet,zhoukk/skynet,longmian/skynet,felixdae/skynet,matinJ/skynet,plsytj/skynet,LiangMa/skynet,qyli/test,Markal128/skynet,xubigshu/skynet,xinmingyao/skynet,togolwb/skynet,wangjunwei01/skynet,plsytj/skynet,nightcj/mmo,bttscut/skynet,cdd990/skynet,xjdrew/skynet,leezhongshan/skynet,QuiQiJingFeng/skynet,harryzeng/skynet,helling34/skynet,qyli/test,MoZhonghua/skynet,your-gatsby/skynet,ag6ag/skynet,cmingjian/skynet,Ding8222/skynet,bigrpg/skynet,cloudwu/skynet,LiangMa/skynet,ilylia/skynet,Markal128/skynet,zhoukk/skynet,lc412/skynet,bigrpg/skynet,ludi1991/skynet,lynx-seu/skynet,hongling0/skynet,catinred2/skynet,yunGit/skynet,lc412/skynet,ludi1991/skynet,zhouxiaoxiaoxujian/skynet,ag6ag/skynet,kebo/skynet,your-gatsby/skynet,letmefly/skynet,u20024804/skynet,zhaijialong/skynet,wangyi0226/skynet,pigparadise/skynet,Zirpon/skynet,wangyi0226/skynet,Ding8222/skynet,enulex/skynet,QuiQiJingFeng/skynet,asanosoyokaze/skynet,KittyCookie/skynet,nightcj/mmo,cuit-zhaxin/skynet,helling34/skynet,letmefly/skynet,rainfiel/skynet,xcjmine/skynet,bttscut/skynet,Markal128/skynet,microcai/skynet,harryzeng/skynet,vizewang/skynet,puXiaoyi/skynet,zhangshiqian1214/skynet,felixdae/skynet,cloudwu/skynet,rainfiel/skynet,matinJ/skynet,MetSystem/skynet,zhangshiqian1214/skynet,Ding8222/skynet,fhaoquan/skynet,jiuaiwo1314/skynet,zhangshiqian1214/skynet,bigrpg/skynet,KittyCookie/skynet,xubigshu/skynet,czlc/skynet,zzh442856860/skynet,pichina/skynet,sundream/skynet,iskygame/skynet,MRunFoss/skynet,gitfancode/skynet,fhaoquan/skynet,boyuegame/skynet,korialuo/skynet,ludi1991/skynet,LuffyPan/skynet,ilylia/skynet,sundream/skynet,zhangshiqian1214/skynet,microcai/skynet,fztcjjl/skynet,javachengwc/skynet,gitfancode/skynet,chfg007/skynet,korialuo/skynet,yinjun322/skynet,samael65535/skynet,LiangMa/skynet,felixdae/skynet,pichina/skynet,codingabc/skynet,yinjun322/skynet,winglsh/skynet,sdgdsffdsfff/skynet,sdgdsffdsfff/skynet,asanosoyokaze/skynet,kyle-wang/skynet,longmian/skynet,plsytj/skynet,zhangshiqian1214/skynet,JiessieDawn/skynet,kebo/skynet,fztcjjl/skynet,cmingjian/skynet,javachengwc/skynet,puXiaoyi/skynet,sanikoyes/skynet,chfg007/skynet,xjdrew/skynet,xinjuncoding/skynet,lynx-seu/skynet,chuenlungwang/skynet,cpascal/skynet,MetSystem/skynet,u20024804/skynet,JiessieDawn/skynet,jiuaiwo1314/skynet,kyle-wang/skynet,great90/skynet,helling34/skynet,xcjmine/skynet,KAndQ/skynet,togolwb/skynet,ypengju/skynet_comment,lawnight/skynet,peimin/skynet_v0.1_with_notes,icetoggle/skynet,zhoukk/skynet,sundream/skynet,fztcjjl/skynet,samael65535/skynet,icetoggle/skynet,dymx101/skynet,MRunFoss/skynet,xinmingyao/skynet,liuxuezhan/skynet,ypengju/skynet_comment
2acaf8b918f6a009a1650b9fbb77cbea66a18e7a
modules/note.lua
modules/note.lua
local date = require'date' local ev = require'ev' local notes = ivar2.persist local handleOutput = function(self, source, destination) -- Only accept notes on channels. if(destination:sub(1,1) ~= '#') then return end local nick = source.nick local key = 'notes:' .. destination .. ':' .. nick:lower() local nick_notes = notes[key] local numNotes = tonumber(#nick_notes) if(not numNotes or numNotes == 0) then return end for i = 1, numNotes do local note = nick_notes[i] local time = tonumber(note.time) local from = note.from self:Msg('privmsg', destination, source, "%s: %s left a note %s ago: %s", nick, from, date.relativeTimeShort(time), note.message) end local globalNumNotes = tonumber(notes['global:' .. nick:lower()]) if(globalNumNotes) then note['global:' .. nick:lower()] = globalNumNotes - numNotes end notes[key] = {} end return { NICK = { function(self, source, nick) if(not notes['global:' .. nick:lower()]) then return end -- source still contains the old nick. source.nick = nick handleOutput(self, source, channel) end, }, JOIN = { -- Check if we have notes for the person who joined the channel. function(self, source, destination) return handleOutput(self, source, destination) end, }, PRIVMSG = { -- Check if we have notes for the person who sent the message. handleOutput, ['^%pnote (%S+)%s+(.+)$'] = function(self, source, destination, recipient, message) -- Only accept notes on channels. if(destination:sub(1,1) ~= '#') then return end local globalNumNotes = tonumber(notes['global:' .. recipient:lower()]) or 0 if(globalNumNotes >= 5) then say("I'm sorry, Dave. I'm afraid I can't do that. Too many notes.") else self:Notice(source.nick, "%s will be notified!", recipient) end local key = 'notes:' .. destination .. ':' .. recipient:lower() local nick_notes = notes[key] or {} local note = { message = message, time = os.time(), from = source.nick, } table.insert(nick_notes, note) notes[key] = nick_notes notes['global:' .. recipient:lower()] = globalNumNotes + 1 end } }
local date = require'date' local ev = require'ev' local notes = ivar2.persist local handleOutput = function(self, source, destination) -- Only accept notes on channels. if(destination:sub(1,1) ~= '#') then return end local nick = source.nick local key = 'notes:' .. destination .. ':' .. nick:lower() local nick_notes = notes[key] local numNotes = tonumber(#nick_notes) if(not numNotes or numNotes == 0) then return end for i = 1, numNotes do local note = nick_notes[i] local time = tonumber(note.time) local from = note.from self:Msg('privmsg', destination, source, "%s: %s left a note %s ago: %s", nick, from, date.relativeTimeShort(time), note.message) end notes[key] = {} local globalNumNotes = tonumber(notes['global:' .. nick:lower()]) if(globalNumNotes) then notes['global:' .. nick:lower()] = globalNumNotes - numNotes end end return { NICK = { function(self, source, nick) if(not notes['global:' .. nick:lower()]) then return end -- source still contains the old nick. source.nick = nick handleOutput(self, source, channel) end, }, JOIN = { -- Check if we have notes for the person who joined the channel. function(self, source, destination) return handleOutput(self, source, destination) end, }, PRIVMSG = { -- Check if we have notes for the person who sent the message. handleOutput, ['^%pnote (%S+)%s+(.+)$'] = function(self, source, destination, recipient, message) -- Only accept notes on channels. if(destination:sub(1,1) ~= '#') then return end local globalNumNotes = tonumber(notes['global:' .. recipient:lower()]) or 0 if(globalNumNotes >= 5) then say("I'm sorry, Dave. I'm afraid I can't do that. Too many notes.") else self:Notice(source.nick, "%s will be notified!", recipient) end local key = 'notes:' .. destination .. ':' .. recipient:lower() local nick_notes = notes[key] or {} local note = { message = message, time = os.time(), from = source.nick, } table.insert(nick_notes, note) notes[key] = nick_notes notes['global:' .. recipient:lower()] = globalNumNotes + 1 end } }
note: fix problem with global notes checking
note: fix problem with global notes checking Former-commit-id: 812994c97664bcd3aba4e68174faab330b4f53db [formerly 14c091baa0e273fc17f403bcbedee5d2f8f4f21e] Former-commit-id: 23e56c5d81f608d414cb7503fcd8cd2d70924186
Lua
mit
torhve/ivar2,torhve/ivar2,torhve/ivar2,haste/ivar2
8cad6531e45e066ca4f1289c64f9fc2d31808288
src/wiola/handler.lua
src/wiola/handler.lua
-- -- Project: wiola -- User: Konstantin Burkalev -- Date: 16.03.14 -- local wsServer = require "resty.websocket.server" local wiola = require "wiola" local wampServer = wiola:new() local webSocket, err = wsServer:new({ timeout = tonumber(ngx.var.wiola_socket_timeout, 10) or 100, max_payload_len = tonumber(ngx.var.wiola_max_payload_len, 10) or 65535 }) if not webSocket then ngx.log(ngx.ERR, "Failed to create new websocket: ", err) return ngx.exit(444) end ngx.log(ngx.DEBUG, "Created websocket") local redisOk, redisErr = wampServer:setupRedis() if not redisOk then ngx.log(ngx.DEBUG, "Failed to connect to redis: ", redisErr) return ngx.exit(444) end local sessionId, dataType = wampServer:addConnection(ngx.var.connection, ngx.header["Sec-WebSocket-Protocol"]) ngx.log(ngx.DEBUG, "Adding connection to list. Conn Id: ", ngx.var.connection) ngx.log(ngx.DEBUG, "Session Id: ", sessionId, " selected protocol: ", ngx.header["Sec-WebSocket-Protocol"]) local function removeConnection(premature, sessionId) ngx.log(ngx.DEBUG, "removeConnection callback fired!") local redisOk, redisErr local redisLib = require "resty.redis" local wiola_config = require "wiola.config" local redis = redisLib:new() local conf = wiola_config.config() if conf.redis.port == nil then redisOk, redisErr = redis:connect(conf.redis.host) else redisOk, redisErr = redis:connect(conf.redis.host, conf.redis.port) end if redisOk and conf.redis.db ~= nil then redis:select(conf.redis.db) end local wiola_cleanup = require "wiola.cleanup" wiola_cleanup.cleanupSession(redis, sessionId) end local function removeConnectionWrapper() ngx.log(ngx.DEBUG, "client on_abort removeConnection callback fired!") removeConnection(true, sessionId) end local ok, err = ngx.on_abort(removeConnectionWrapper) if not ok then ngx.log(ngx.ERR, "failed to register the on_abort callback: ", err) ngx.exit(444) end while true do ngx.log(ngx.DEBUG, "Started handler loop!") ngx.log(ngx.DEBUG, "Checking data for client...") local cliData, cliErr = wampServer:getPendingData(sessionId) while cliData ~= ngx.null do ngx.log(ngx.DEBUG, "Got data for client. DataType is ", dataType, ". Sending...") if dataType == 'binary' then local bytes, err = webSocket:send_binary(cliData) else local bytes, err = webSocket:send_text(cliData) end if not bytes then ngx.log(ngx.ERR, "Failed to send data: ", err) end cliData, cliErr = wampServer:getPendingData(sessionId) end if webSocket.fatal then ngx.log(ngx.ERR, "Failed to receive frame: ", err) ngx.timer.at(0, removeConnection, sessionId) return ngx.exit(444) end local data, typ, err = webSocket:recv_frame() if not data then local bytes, err = webSocket:send_ping() if not bytes then ngx.log(ngx.ERR, "Failed to send ping: ", err) ngx.timer.at(0, removeConnection, sessionId) return ngx.exit(444) end elseif typ == "close" then ngx.log(ngx.DEBUG, "Normal closing websocket. SID: ", ngx.var.connection) local bytes, err = webSocket:send_close(1000, "Closing connection") if not bytes then ngx.log(ngx.ERR, "Failed to send the close frame: ", err) return end ngx.timer.at(0, removeConnection, sessionId) webSocket:send_close() break elseif typ == "ping" then local bytes, err = webSocket:send_pong() if not bytes then ngx.log(ngx.ERR, "Failed to send pong: ", err) ngx.timer.at(0, removeConnection, sessionId) return ngx.exit(444) end elseif typ == "pong" then -- ngx.log(ngx.DEBUG, "client ponged") elseif typ == "text" then -- Received something texty ngx.log(ngx.DEBUG, "Received text data: ", data) wampServer:receiveData(sessionId, data) elseif typ == "binary" then -- Received something binary ngx.log(ngx.DEBUG, "Received binary data") wampServer:receiveData(sessionId, data) end ngx.log(ngx.DEBUG, "Finished handler loop!") end
-- -- Project: wiola -- User: Konstantin Burkalev -- Date: 16.03.14 -- local wsServer = require "resty.websocket.server" local wiola = require "wiola" local wampServer = wiola:new() local webSocket, err = wsServer:new({ timeout = tonumber(ngx.var.wiola_socket_timeout, 10) or 100, max_payload_len = tonumber(ngx.var.wiola_max_payload_len, 10) or 65535 }) if not webSocket then ngx.log(ngx.ERR, "Failed to create new websocket: ", err) return ngx.exit(444) end ngx.log(ngx.DEBUG, "Created websocket") local redisOk, redisErr = wampServer:setupRedis() if not redisOk then ngx.log(ngx.DEBUG, "Failed to connect to redis: ", redisErr) return ngx.exit(444) end local sessionId, dataType = wampServer:addConnection(ngx.var.connection, ngx.header["Sec-WebSocket-Protocol"]) ngx.log(ngx.DEBUG, "Adding connection to list. Conn Id: ", ngx.var.connection) ngx.log(ngx.DEBUG, "Session Id: ", sessionId, " selected protocol: ", ngx.header["Sec-WebSocket-Protocol"]) local function removeConnection(premature, sessionId) ngx.log(ngx.DEBUG, "removeConnection callback fired!") local redisOk, redisErr local redisLib = require "resty.redis" local wiola_config = require "wiola.config" local redis = redisLib:new() local conf = wiola_config.config() if conf.redis.port == nil then redisOk, redisErr = redis:connect(conf.redis.host) else redisOk, redisErr = redis:connect(conf.redis.host, conf.redis.port) end if redisOk and conf.redis.db ~= nil then redis:select(conf.redis.db) end local wiola_cleanup = require "wiola.cleanup" wiola_cleanup.cleanupSession(redis, sessionId) end local function removeConnectionWrapper() ngx.log(ngx.DEBUG, "client on_abort removeConnection callback fired!") removeConnection(true, sessionId) end local ok, err = ngx.on_abort(removeConnectionWrapper) if not ok then ngx.log(ngx.ERR, "failed to register the on_abort callback: ", err) ngx.exit(444) end while true do ngx.log(ngx.DEBUG, "Started handler loop!") ngx.log(ngx.DEBUG, "Checking data for client...") local cliData, cliErr = wampServer:getPendingData(sessionId) while cliData ~= ngx.null do ngx.log(ngx.DEBUG, "Got data for client. DataType is ", dataType, ". Sending...") local bytes, err if dataType == 'binary' then bytes, err = webSocket:send_binary(cliData) else bytes, err = webSocket:send_text(cliData) end if not bytes then ngx.log(ngx.ERR, "Failed to send data: ", err) end cliData, cliErr = wampServer:getPendingData(sessionId) end if webSocket.fatal then ngx.log(ngx.ERR, "Failed to receive frame: ", err) ngx.timer.at(0, removeConnection, sessionId) return ngx.exit(444) end local data, typ, err = webSocket:recv_frame() if not data then local bytes, err = webSocket:send_ping() if not bytes then ngx.log(ngx.ERR, "Failed to send ping: ", err) ngx.timer.at(0, removeConnection, sessionId) return ngx.exit(444) end elseif typ == "close" then ngx.log(ngx.DEBUG, "Normal closing websocket. SID: ", ngx.var.connection) local bytes, err = webSocket:send_close(1000, "Closing connection") if not bytes then ngx.log(ngx.ERR, "Failed to send the close frame: ", err) return end ngx.timer.at(0, removeConnection, sessionId) webSocket:send_close() break elseif typ == "ping" then local bytes, err = webSocket:send_pong() if not bytes then ngx.log(ngx.ERR, "Failed to send pong: ", err) ngx.timer.at(0, removeConnection, sessionId) return ngx.exit(444) end elseif typ == "pong" then -- ngx.log(ngx.DEBUG, "client ponged") elseif typ == "text" then -- Received something texty ngx.log(ngx.DEBUG, "Received text data: ", data) wampServer:receiveData(sessionId, data) elseif typ == "binary" then -- Received something binary ngx.log(ngx.DEBUG, "Received binary data") wampServer:receiveData(sessionId, data) end ngx.log(ngx.DEBUG, "Finished handler loop!") end
Fix scoping of 'bytes' to fix case where "Failed to send data: " error was always being logged.
Fix scoping of 'bytes' to fix case where "Failed to send data: " error was always being logged.
Lua
bsd-2-clause
KSDaemon/wiola,KSDaemon/wiola,KSDaemon/wiola
a299089e151065d7bf9e028f8d62181a02f44276
limeparse.lua
limeparse.lua
-- limeparse.lua: Parses the input file -- Copyright © 2012 Zachary Catlin. See LICENSE for terms. -- The package table local P = {} if _REQUIREDNAME == nil then limeparse = P else _G[_REQUIREDNAME] = P end -- External imports local coroutine = coroutine local string = string local error = error setfenv(1, P) -- How much of a file do we read at one time? blockSize = 8192 -- The file parser is structure as a top-level function (readFile) that -- chooses a sub-parser based on the initial bytes of a section (regexp, -- directive, comment, etc.); the sub-parser is run as a coroutine with the -- following flow, where s is the read-in but unparsed portion of the file -- and conf is the object representing the parsed file configuration: -- -- readFile sub-parser -- initial call: -- -> (conf, s) -- -- sub-parser needs more bytes: -- <- (false, nil) -- -- readFile gives more bytes: -- -> (more-bytes) -- -- readFile can't give more bytes, since it's at EOF: -- -> (nil) -- -- sub-parser is done, and returns any trailing bytes it didn't parse: -- <- (true, s) -- -- sub-parser finds an error in the file: -- error(message) -- A simple sub-parser: skip through a C-style comment local function readCComment(conf, s) local isDone = false local moreS -- Skip past the initial '/*' while string.len(s) < 2 do moreS = coroutine.yield(false, nil) if moreS == nil then return true, '' end s = s .. moreS end s = string.sub(s, 3, -1) -- Search for ending '*/' while not isDone do local a,b = string.find(s, '*/', 1, true) if a ~= nil then s = string.sub(s, b+1, -1) isDone = true else -- no '*/'; any possible match will involve only the last byte of -- the current s, if that moreS = coroutine.yield(false, nil) if moreS == nil then return true, '' end s = string.sub(s, -1, -1) .. moreS end end return true, s end -- An even simpler sub-parser: skip through whitespace local function readWhitespace(conf, s) local moreS = '' local a,b while moreS ~= nil do s = s .. moreS a,b = string.find(s, '[^ \t\n]') if a ~= nil then return true, string.sub(s, b, -1) else moreS = coroutine.yield(false, nil) end end return true, '' end -- Skip through a C++-style short comment local function readShortComment(conf, s) local moreS = '' local a,b -- Skip past intial '//' while string.len(s) < 2 do moreS = coroutine.yield(false, nil) if moreS == nil then return true, '' end s = s .. moreS end s = string.sub(s, 3, -1) while moreS ~= nil do s = s .. moreS a,b = string.find(s, '\n', 1, true) if a ~= nil then return true, string.sub(s, b+1, -1) else moreS = coroutine.yield(false, nil) end s = '' end return true, '' end -- Based on the first bytes of s, choose a sub-parser to handle the first -- part of s; returns two values, the sub-parser as a coroutine or nil, -- and whether or not s is not sufficient to determine the next sub-parser. local function chooseSubparser(s) local firstByte = string.sub(s, 1, 1) if firstByte == ' ' or firstByte == '\t' or firstByte == '\n' then return coroutine.create(readWhitespace), false elseif firstByte == '/' then local secondByte = string.sub(s, 2, 2) if secondByte == '' then return nil, true elseif secondByte == '*' then return coroutine.create(readCComment), false elseif secondByte == '/' then return coroutine.create(readShortComment), false else error('Unknown thing ' .. string.sub(s, 1, 2)) end else error('Unknown thing ' .. firstByte) end end -- The top-level file parser function readFile(f) local conf, state = {}, nil local buf, inString = '', f:read(blockSize) local co = nil local coFirst = false local needMoreBytes = false local runSubparser = function() if co == nil then -- No running sub-parser; start one up co, needMoreBytes = chooseSubparser(buf) coFirst = true else local isOK, isDone, s if coFirst then isOK, isDone, s = coroutine.resume(co, conf, buf) coFirst = false else isOK, isDone, s = coroutine.resume(co, buf) end if not isOK then error('Uhhh, something wrong... ' .. isDone) end if isDone then co = nil buf = s else buf = '' end end end while inString ~= nil do buf = buf .. inString while buf ~= '' and not needMoreBytes do runSubparser() end inString = f:read(blockSize) end -- We may have hit EOF, but there may still be unparsed parts of the file... needMoreBytes = false while buf ~= '' and not needMoreBytes do runSubparser() end if needMoreBytes then error('Ambiguous EOF: ' .. buf) end return conf end return P
-- limeparse.lua: Parses the input file -- Copyright © 2012 Zachary Catlin. See LICENSE for terms. -- The package table local P = {} if _REQUIREDNAME == nil then limeparse = P else _G[_REQUIREDNAME] = P end -- External imports local coroutine = coroutine local string = string local error = error setfenv(1, P) -- How much of a file do we read at one time? blockSize = 8192 -- The file parser is structure as a top-level function (readFile) that -- chooses a sub-parser based on the initial bytes of a section (regexp, -- directive, comment, etc.); the sub-parser is run as a coroutine with the -- following flow, where s is the read-in but unparsed portion of the file -- and conf is the object representing the parsed file configuration: -- -- readFile sub-parser -- initial call: -- -> (conf, s) -- -- sub-parser needs more bytes: -- <- (false, nil) -- -- readFile gives more bytes: -- -> (more-bytes) -- -- readFile can't give more bytes, since it's at EOF: -- -> (nil) -- -- sub-parser is done, and returns any trailing bytes it didn't parse: -- <- (true, s) -- -- sub-parser finds an error in the file: -- error(message) -- A simple sub-parser: skip through a C-style comment local function readCComment(conf, s) local isDone = false local moreS -- Skip past the initial '/*' while string.len(s) < 2 do moreS = coroutine.yield(false, nil) if moreS == nil then return true, '' end s = s .. moreS end s = string.sub(s, 3, -1) -- Search for ending '*/' while not isDone do local a,b = string.find(s, '*/', 1, true) if a ~= nil then s = string.sub(s, b+1, -1) isDone = true else -- no '*/'; any possible match will involve only the last byte of -- the current s, if that moreS = coroutine.yield(false, nil) if moreS == nil then return true, '' end s = string.sub(s, -1, -1) .. moreS end end return true, s end -- An even simpler sub-parser: skip through whitespace local function readWhitespace(conf, s) local moreS = '' local a,b while moreS ~= nil do s = s .. moreS a,b = string.find(s, '[^ \t\n]') if a ~= nil then return true, string.sub(s, b, -1) else moreS = coroutine.yield(false, nil) end end return true, '' end -- Skip through a C++-style short comment local function readShortComment(conf, s) local moreS = '' local a,b -- Skip past intial '//' while string.len(s) < 2 do moreS = coroutine.yield(false, nil) if moreS == nil then return true, '' end s = s .. moreS end s = string.sub(s, 3, -1) while moreS ~= nil do s = s .. moreS a,b = string.find(s, '\n', 1, true) if a ~= nil then return true, string.sub(s, b+1, -1) else moreS = coroutine.yield(false, nil) end s = '' end return true, '' end -- Based on the first bytes of s, choose a sub-parser to handle the first -- part of s; returns two values, the sub-parser as a coroutine or nil, -- and whether or not s is not sufficient to determine the next sub-parser. local function chooseSubparser(s) local firstByte = string.sub(s, 1, 1) if firstByte == ' ' or firstByte == '\t' or firstByte == '\n' then return coroutine.create(readWhitespace), false elseif firstByte == '/' then local secondByte = string.sub(s, 2, 2) if secondByte == '' then return nil, true elseif secondByte == '*' then return coroutine.create(readCComment), false elseif secondByte == '/' then return coroutine.create(readShortComment), false else error('Unknown thing ' .. string.sub(s, 1, 2)) end else error('Unknown thing ' .. firstByte) end end -- The top-level file parser. Either returns a table corresponding to the -- successfully-parsed file or raises an error. function readFile(f) local conf, state = {}, nil local buf, inString = '', f:read(blockSize) local co = nil local coFirst = false local needMoreBytes = false local isDone = false local atEOF = false local runSubparser = function() if co == nil then -- No running sub-parser; start one up co, needMoreBytes = chooseSubparser(buf) coFirst = true else local isOK, s local buf2 = buf if atEOF and buf == '' then buf2 = nil end if coFirst then isOK, isDone, s = coroutine.resume(co, conf, buf2) coFirst = false else isOK, isDone, s = coroutine.resume(co, buf2) end if not isOK then error('Uhhh, something wrong... ' .. isDone) end if isDone then co = nil buf = s else buf = '' end end end while inString ~= nil do buf = buf .. inString while buf ~= '' and not needMoreBytes do runSubparser() end inString = f:read(blockSize) end atEOF = true -- We may have hit EOF, but there may still be unparsed parts of the file... needMoreBytes = false while (buf ~= '' or not isDone) and not needMoreBytes do runSubparser() end if needMoreBytes then error('Ambiguous EOF: ' .. buf) end return conf end return P
Fixed EOF bug in limeparse.readFile
Fixed EOF bug in limeparse.readFile readFile wasn't sending nil to the sub-parser coroutine at EOF, like it ought to have.
Lua
mit
zec/moonlime,zec/moonlime
dfb38c26280ab1522f5276492d3e750074fbfe04
openLuup/hag.lua
openLuup/hag.lua
#!/usr/bin/env wsapi.cgi --module(..., package.seeall) local ABOUT = { NAME = "upnp.control.hag", VERSION = "2016.05.15", DESCRIPTION = "a handler for redirected port_49451 /upnp/control/hag requests", AUTHOR = "@akbooer", COPYRIGHT = "(c) 2013-2016 AKBooer", DOCUMENTATION = "https://github.com/akbooer/openLuup/tree/master/Documentation", } -- see: http://wiki.micasaverde.com/index.php/ModifyUserData local xml = require "openLuup.xml" local json = require "openLuup.json" local luup = require "openLuup.luup" local _log -- defined from WSAPI environment as wsapi.error:write(...) in run() method. --[[ The request is a POST with xml CONTENT_LENGTH = 681, CONTENT_TYPE = "text/xml;charset=UTF-8", <s:envelope s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"> <s:body> <u:modifyuserdata xmlns:u="urn:schemas-micasaverde-org:service:HomeAutomationGateway:1"> <inuserdata>{...some JSON structure...}</inuserdata> <DataFormat>json</DataFormat> </u:modifyuserdata> </s:body> </s:envelope> JSON structure contains: { InstalledPlugins = {}, PluginSettings = {}, StartupCode = "...", devices = {}, rooms = {}, scenes = {}, sections = {}, users = {} } --]] function run(wsapi_env) local response = "OK" local headers = { ["Content-type"] = "text/plain" } _log = function (...) wsapi_env.error:write(...) end -- set up the log output, note colon syntax local function iterator() -- one-shot 'iterator', returns response, then nil local x = response response = nil return x end local content = wsapi_env.input.read () local x = xml.decode(content) local m = xml.extract(x, "s:Envelope", "s:Body", "u:ModifyUserData") [1] or {} -- unpack one-element list if m.DataFormat == "json" and m.inUserData then local j,msg = json.decode (m.inUserData) if not j then response = msg _log (msg) else if j.StartupCode then luup.attr_set ("StartupCode", j.StartupCode) _log "modified StartupCode" end end else -- not yet implemented _log (content) end return 200, headers, iterator end -----
#!/usr/bin/env wsapi.cgi --module(..., package.seeall) local ABOUT = { NAME = "upnp.control.hag", VERSION = "2016.06.05", DESCRIPTION = "a handler for redirected port_49451 /upnp/control/hag requests", AUTHOR = "@akbooer", COPYRIGHT = "(c) 2013-2016 AKBooer", DOCUMENTATION = "https://github.com/akbooer/openLuup/tree/master/Documentation", } -- see: http://wiki.micasaverde.com/index.php/ModifyUserData -- 2016.06.05 add scene processing (for AltUI long scene POST requests) local xml = require "openLuup.xml" local json = require "openLuup.json" local luup = require "openLuup.luup" local scenes = require "openLuup.scenes" local _log -- defined from WSAPI environment as wsapi.error:write(...) in run() method. --[[ The request is a POST with xml CONTENT_LENGTH = 681, CONTENT_TYPE = "text/xml;charset=UTF-8", <s:envelope s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"> <s:body> <u:modifyuserdata xmlns:u="urn:schemas-micasaverde-org:service:HomeAutomationGateway:1"> <inuserdata>{...some JSON structure...}</inuserdata> <DataFormat>json</DataFormat> </u:modifyuserdata> </s:body> </s:envelope> JSON structure contains: { InstalledPlugins = {}, PluginSettings = {}, StartupCode = "...", devices = {}, rooms = {}, scenes = {}, sections = {}, users = {} } --]] function run(wsapi_env) local response = "OK" local headers = { ["Content-type"] = "text/plain" } _log = function (...) wsapi_env.error:write(...) end -- set up the log output, note colon syntax local function iterator() -- one-shot 'iterator', returns response, then nil local x = response response = nil return x end local content = wsapi_env.input.read () local x = xml.decode(content) local m = xml.extract(x, "s:Envelope", "s:Body", "u:ModifyUserData") [1] or {} -- unpack one-element list if m.DataFormat == "json" and m.inUserData then local j,msg = json.decode (m.inUserData) if not j then response = msg _log (msg) else -- Startup if j.StartupCode then luup.attr_set ("StartupCode", j.StartupCode) _log "modified StartupCode" end -- Scenes if j.scenes then -- 2016.06.05 for name, scene in pairs (j.scenes) do local id = tonumber (scene.id) if id >= 1e6 then scene.id = nil end -- remove bogus scene number local new_scene, msg = scenes.create (scene) id = tonumber (scene.id) -- may have changed if id and new_scene then luup.scenes[id] = new_scene -- slot into scenes table _log ("modified scene #" .. id) else response = msg _log (msg) break end end end -- also devices, sections, rooms, users... end else -- not yet implemented _log (content) end return 200, headers, iterator end -----
hot-fix-modifyuserdata-scenes
hot-fix-modifyuserdata-scenes - to enable POST requests for large scene definitions
Lua
apache-2.0
akbooer/openLuup
4f4386c0a87e1227f00fcfad3b7df9151f54cc61
test_scripts/Polices/build_options/032_ATF_P_TC_PTU_Retry_Sequence_Retry_Timeout_Expiration_HTTP.lua
test_scripts/Polices/build_options/032_ATF_P_TC_PTU_Retry_Sequence_Retry_Timeout_Expiration_HTTP.lua
--UNREADY: Need to add json file from https://github.com/smartdevicelink/sdl_atf_test_scripts/pull/363/ -- Also the sequence array is filled in with BasicCommunication.OnSystemRequest -- r_actual also returns nil and this invalidates the whole check --------------------------------------------------------------------------------------------- -- Requirement summary: -- [PolicyTableUpdate] Local Policy Table retry timeout expiration -- -- Description: -- In case the corresponding retry timeout expires, PoliciesManager must send -- the new PTU request to mobile app until successful Policy Table Update has finished -- or the number of retry attempts is limited by the number of elements -- in "seconds_between_retries" section of LPT. -- -- 1. Used preconditions -- SDL is built with "-DEXTENDED_POLICY: HTTP" flag -- Application 1 is registered and activated -- PTU with updated 'timeout_after_x_seconds' and 'seconds_between_retries' params -- is performed to speed up the test -- PTU finished successfully (UP_TO_DATE) -- 2. Performed steps -- Trigger new PTU by registering Application 2 -- SDL -> mobile BC.OnSystemRequest (params, url) -- PTU does not come within defined timeout -- Check timestamps of BC.PolicyUpdate() requests -- Calculate timeouts -- -- Expected result: -- Timeouts correspond to 'timeout_after_x_seconds' and 'seconds_between_retries' params --------------------------------------------------------------------------------------------- --[[ 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') local testCasesForPolicyTable = require('user_modules/shared_testcases/testCasesForPolicyTable') local commonPreconditions = require('user_modules/shared_testcases/commonPreconditions') --[[ General Precondition before ATF start ]] commonSteps:DeleteLogsFileAndPolicyTable() testCasesForPolicyTable:Precondition_updatePolicy_By_overwriting_preloaded_pt("files/jsons/Policies/build_options/retry_seq.json") commonPreconditions:Connecttest_without_ExitBySDLDisconnect_WithoutOpenConnectionRegisterApp("connecttest_ConnectMobile.lua") --TODO: Should be removed when issue: "ATF does not stop HB timers by closing session and connection" is fixed config.defaultProtocolVersion = 2 --[[ Local variables ]] local time_system_request_prev = 0 local time_system_request_curr = 0 --[[ General Settings for configuration ]] Test = require('user_modules/connecttest_ConnectMobile') require('cardinalities') require('user_modules/AppTypes') local mobile_session = require('mobile_session') --[[ Preconditions ]] commonFunctions:newTestCasesGroup("Preconditions") function Test:Precondition_Connect_device() self:connectMobile() end function Test:Precondition_StartSession() self.mobileSession = mobile_session.MobileSession(self, self.mobileConnection) self.mobileSession:StartService(7) end --[[ Test ]] commonFunctions:newTestCasesGroup("Test") function Test:TestStep_OnStatusUpdate_UPDATE_NEEDED_new_PTU_request() local correlationId = self.mobileSession:SendRPC("RegisterAppInterface", config.application1.registerAppInterfaceParams) EXPECT_HMINOTIFICATION("BasicCommunication.OnAppRegistered", {application = { appName = config.application1.registerAppInterfaceParams.appName } }) EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate", { status = "UPDATE_NEEDED" }, {status = "UPDATING"}):Times(2) EXPECT_NOTIFICATION("OnSystemRequest", {requestType = "HTTP"}) :Do(function() time_system_request_prev = timestamp() end) self.mobileSession:ExpectResponse(correlationId, { success = true, resultCode = "SUCCESS" }) self.mobileSession:ExpectNotification("OnHMIStatus", {hmiLevel = "NONE", audioStreamingState = "NOT_AUDIBLE", systemContext = "MAIN"}) end --[[ Test ]] commonFunctions:newTestCasesGroup("Test") function Test:TestStep_Retry_Timeout_Expiration() local is_test_fail = false local timeout_after_x_seconds = 30 local time_wait = {} local sec_btw_ret = {1, 2, 3, 4, 5} local total_time time_wait[1] = timeout_after_x_seconds time_wait[2] = sec_btw_ret[1] + timeout_after_x_seconds time_wait[3] = sec_btw_ret[1] + sec_btw_ret[2] + timeout_after_x_seconds time_wait[4] = sec_btw_ret[2] + sec_btw_ret[3] + timeout_after_x_seconds time_wait[5] = sec_btw_ret[3] + sec_btw_ret[4] + timeout_after_x_seconds time_wait[6] = sec_btw_ret[4] + sec_btw_ret[5] + timeout_after_x_seconds total_time = (time_wait[1] + time_wait[2] + time_wait[3] + time_wait[4] + time_wait[5] + time_wait[6])*1000 local function verify_retry_sequence(occurences) local time_1 = time_system_request_curr local time_2 = time_system_request_prev local timeout = (time_1 - time_2) if (time_wait[occurences] == nil) then time_wait[occurences] = time_wait[6] commonFunctions:printError("ERROR: OnSystemRequest is received more than expected.") is_test_fail = true end if( ( timeout > (time_wait[occurences]*1000 + 2000) ) or ( timeout < (time_wait[occurences]*1000 - 2000) )) then is_test_fail = true commonFunctions:printError("ERROR: timeout for retry sequence "..occurences.." is not as expected: "..(time_wait[occurences]*1000).."msec(2sec tolerance). real: "..timeout.."ms") else print("timeout is as expected for retry sequence "..occurences..": "..(time_wait[occurences]*1000).."ms. real: "..timeout) end return true end if(time_wait == 0) then time_wait = 63000 end EXPECT_NOTIFICATION("OnSystemRequest", { requestType = "HTTP", fileType = "JSON"}):Timeout(total_time+60000):Times(5) :Do(function(exp) if(time_system_request_curr ~= 0) then time_system_request_prev = time_system_request_curr end time_system_request_curr = timestamp() verify_retry_sequence(exp.occurences) end) commonTestCases:DelayedExp(total_time) if(is_test_fail == true) then self:FailTestCase("Test is FAILED. See prints.") end end --[[ Postconditions ]] commonFunctions:newTestCasesGroup("Postconditions") function Test.Postcondition_Stop_SDL() StopSDL() end return Test
--UNREADY: Need to add json file from https://github.com/smartdevicelink/sdl_atf_test_scripts/pull/363/ -- Also the sequence array is filled in with BasicCommunication.OnSystemRequest -- r_actual also returns nil and this invalidates the whole check --------------------------------------------------------------------------------------------- -- Requirement summary: -- [PolicyTableUpdate] Local Policy Table retry timeout expiration -- -- Description: -- In case the corresponding retry timeout expires, PoliciesManager must send -- the new PTU request to mobile app until successful Policy Table Update has finished -- or the number of retry attempts is limited by the number of elements -- in "seconds_between_retries" section of LPT. -- -- 1. Used preconditions -- SDL is built with "-DEXTENDED_POLICY: HTTP" flag -- Application 1 is registered and activated -- PTU with updated 'timeout_after_x_seconds' and 'seconds_between_retries' params -- is performed to speed up the test -- PTU finished successfully (UP_TO_DATE) -- 2. Performed steps -- Trigger new PTU by registering Application 2 -- SDL -> mobile BC.OnSystemRequest (params, url) -- PTU does not come within defined timeout -- Check timestamps of BC.PolicyUpdate() requests -- Calculate timeouts -- -- Expected result: -- Timeouts correspond to 'timeout_after_x_seconds' and 'seconds_between_retries' params --------------------------------------------------------------------------------------------- --[[ 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') local testCasesForPolicyTable = require('user_modules/shared_testcases/testCasesForPolicyTable') local commonPreconditions = require('user_modules/shared_testcases/commonPreconditions') --[[ General Precondition before ATF start ]] commonSteps:DeleteLogsFileAndPolicyTable() testCasesForPolicyTable:Precondition_updatePolicy_By_overwriting_preloaded_pt("files/jsons/Policies/build_options/retry_seq.json") commonPreconditions:Connecttest_without_ExitBySDLDisconnect_WithoutOpenConnectionRegisterApp("connecttest_ConnectMobile.lua") --TODO: Should be removed when issue: "ATF does not stop HB timers by closing session and connection" is fixed config.defaultProtocolVersion = 2 --[[ Local variables ]] local time_system_request_prev = 0 local time_system_request_curr = 0 --[[ General Settings for configuration ]] Test = require('user_modules/connecttest_ConnectMobile') require('cardinalities') require('user_modules/AppTypes') local mobile_session = require('mobile_session') --[[ Preconditions ]] commonFunctions:newTestCasesGroup("Preconditions") function Test:Precondition_Connect_device() self:connectMobile() end function Test:Precondition_StartSession() self.mobileSession = mobile_session.MobileSession(self, self.mobileConnection) self.mobileSession:StartService(7) end --[[ Test ]] commonFunctions:newTestCasesGroup("Test") function Test:TestStep_OnStatusUpdate_UPDATE_NEEDED_new_PTU_request() local correlationId = self.mobileSession:SendRPC("RegisterAppInterface", config.application1.registerAppInterfaceParams) EXPECT_HMINOTIFICATION("BasicCommunication.OnAppRegistered", {application = { appName = config.application1.registerAppInterfaceParams.appName } }) EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate", { status = "UPDATE_NEEDED" }, {status = "UPDATING"}):Times(2) EXPECT_NOTIFICATION("OnSystemRequest"):Times(2) :ValidIf(function(_, data) time_system_request_prev = timestamp() if not data then return false end if not data.payload then return false end if data.payload.requestType == "HTTP" or data.payload.requestType == "LOCK_SCREEN_ICON_URL" then print("Got requestType = "..tostring(data.payload.requestType)) return true else print("Got something wrong instead of data.requestType = HTTP or LOCK_SCREEN_ICON_URL: "..tostring(data.payload.requestType)) return false end end) self.mobileSession:ExpectResponse(correlationId, { success = true, resultCode = "SUCCESS" }) self.mobileSession:ExpectNotification("OnHMIStatus", {hmiLevel = "NONE", audioStreamingState = "NOT_AUDIBLE", systemContext = "MAIN"}) end --[[ Test ]] commonFunctions:newTestCasesGroup("Test") function Test:TestStep_Retry_Timeout_Expiration() local is_test_fail = false local timeout_after_x_seconds = 30 local time_wait = {} local sec_btw_ret = {1, 2, 3, 4, 5} local total_time time_wait[1] = sec_btw_ret[1] + timeout_after_x_seconds time_wait[2] = sec_btw_ret[2] + time_wait[1] + timeout_after_x_seconds time_wait[3] = sec_btw_ret[3] + time_wait[2] + timeout_after_x_seconds time_wait[4] = sec_btw_ret[4] + time_wait[3] + timeout_after_x_seconds time_wait[5] = sec_btw_ret[5] + time_wait[4] + timeout_after_x_seconds total_time = (time_wait[1] + time_wait[2] + time_wait[3] + time_wait[4] + time_wait[5] )*1000 local function verify_retry_sequence(occurences) local time_1 = time_system_request_curr local time_2 = time_system_request_prev local timeout = (time_1 - time_2) if (time_wait[occurences] == nil) then time_wait[occurences] = time_wait[5] commonFunctions:printError("ERROR: OnSystemRequest is received more than expected.") is_test_fail = true end if( ( timeout > (time_wait[occurences]*1000 + 2000) ) or ( timeout < (time_wait[occurences]*1000 - 2000) )) then is_test_fail = true commonFunctions:printError("ERROR: timeout for retry sequence "..occurences.." is not as expected: "..(time_wait[occurences]*1000).."msec(2sec tolerance). real: "..timeout.."ms") else print("timeout is as expected for retry sequence "..occurences..": "..(time_wait[occurences]*1000).."ms. real: "..timeout) end return true end if(time_wait == 0) then time_wait = 63000 end EXPECT_NOTIFICATION("OnSystemRequest", { requestType = "HTTP", fileType = "JSON"}):Timeout(total_time+60000):Times(5) :Do(function(exp) if(time_system_request_curr ~= 0) then time_system_request_prev = time_system_request_curr end time_system_request_curr = timestamp() verify_retry_sequence(exp.occurences) end) commonTestCases:DelayedExp(total_time) if(is_test_fail == true) then self:FailTestCase("Test is FAILED. See prints.") end end --[[ Postconditions ]] commonFunctions:newTestCasesGroup("Postconditions") function Test.Postcondition_Stop_SDL() StopSDL() end return Test
Fix check retry timeout
Fix check retry timeout LOCK_SCREEN_ICON_URL can come when app registered Fix calculation of time according requirements
Lua
bsd-3-clause
smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts
37dc74a79042e10220856f071fc17fe7c58dd7eb
node/File.lua
node/File.lua
local cache = require "cache" local Node = require "node.Node" local File = Node:clone("node.File") File.icon = emufun.images.file function File:__init(...) Node.__init(self, ...) -- load configuration from disk, if present local cfg = new "Configuration" (self) self:loadConfig() self:configure(cfg) cfg:finalize() -- load cache data self.metadata = lfs.attributes(self:path()) self.cache = cache.get(self:path()) if self.metadata.modification ~= self.cache.ts then LOG.DEBUG("File '%s' updated (%d ~= %d), updating cache", self:path(), self.metadata.modification, self.cache.ts) self.cache.ts = self.metadata.modification cache.save() end end function File:colour() if self.cache.flags.seen then return 0, 192, 255 else return Node.colour(self) end end function File:loadConfig() if self.name:match("%.emufun$") then self.config = assert(loadfile(self:path())) end end if love._os == "Windows" then function File:expandcommand(string) return '"' .. string:gsub("$%b{}", function(match) match = match:sub(3,-2) if type(self[match]) == "function" then return '"' .. tostring(self[match](self)) .. '"' else return '"' .. tostring(self[match]) .. '"' end end) .. '"' end else function File:expandcommand(string) local function escape(string) return (string:gsub("'", [['\'']])) end return (string:gsub("$%b{}", function(match) match = match:sub(3,-2) if type(self[match]) == "function" then return "'" .. escape(tostring(self[match](self))) .. "'" else return "'" .. escape(tostring(self[match])) .. "'" end end)) end end function File:run() local function exec(v) if type(v) == "function" then return v(self) elseif type(v) == "string" then local cmd = self:expandcommand(v) LOG.INFO("Executing command: %s", cmd) LOG.DEBUG(" => %s", tostring(os.execute(cmd))) return false elseif type(v) == "table" then local rv for _,command in ipairs(v) do rv = exec(v) end return rv else return new "node.Message" { name = "Error executing commands for " .. self:path(), message = "Unknown command type " .. type(v), parent = self.parent } end end -- the configuration file should define a command to execute -- if not, we fall through to the error if self.execute then if emufun.config.fullscreen then love.window.toggleFullscreen() end local rv = exec(self.execute) or 0 if not self.cache.flags.seen then self.cache.flags.seen = true cache.save() end if emufun.config.fullscreen then love.window.toggleFullscreen() end return rv end return new "node.Message" { name = "Error!", message = "No configuration available to execute this file", parent = self.parent } end function File:dir() return self.parent:path() end function File:extension() return self.name:match("%.([^%.]+)$") end return File
local cache = require "cache" local Node = require "node.Node" local File = Node:clone("node.File") File.icon = emufun.images.file function File:__init(...) Node.__init(self, ...) -- load configuration from disk, if present local cfg = new "Configuration" (self) self:loadConfig() self:configure(cfg) cfg:finalize() -- load cache data self.metadata = lfs.attributes(self:path()) self.cache = cache.get(self:path()) if self.metadata.modification ~= self.cache.ts then LOG.DEBUG("File '%s' updated (%d ~= %d), updating cache", self:path(), self.metadata.modification, self.cache.ts) self.cache.ts = self.metadata.modification cache.save() end end function File:colour() if self.cache.flags.seen then return 0, 192, 255 else return Node.colour(self) end end function File:loadConfig() if self.name:match("%.emufun$") then self.config = assert(loadfile(self:path())) end end if love._os == "Windows" then function File:expandcommand(string) return '"' .. string:gsub("$%b{}", function(match) match = match:sub(3,-2) if type(self[match]) == "function" then return '"' .. tostring(self[match](self)) .. '"' else return '"' .. tostring(self[match]) .. '"' end end) .. '"' end else function File:expandcommand(string) local function escape(string) return (string:gsub("'", [['\'']])) end return (string:gsub("$%b{}", function(match) match = match:sub(3,-2) if type(self[match]) == "function" then return "'" .. escape(tostring(self[match](self))) .. "'" else return "'" .. escape(tostring(self[match])) .. "'" end end)) end end function File:run() local function exec(v) if type(v) == "function" then return v(self) elseif type(v) == "string" then local cmd = self:expandcommand(v) LOG.INFO("Executing command: %s", cmd) LOG.DEBUG(" => %s", tostring(os.execute(cmd))) return false elseif type(v) == "table" then local rv for _,command in ipairs(v) do rv = exec(v) end return rv else return new "node.Message" { name = "Error executing commands for " .. self:path(), message = "Unknown command type " .. type(v), parent = self.parent } end end -- the configuration file should define a command to execute -- if not, we fall through to the error if self.execute then local fs = love.window.getFullscreen() love.window.setFullscreen(false) local rv = exec(self.execute) or 0 if not self.cache.flags.seen then self.cache.flags.seen = true cache.save() end love.window.setFullscreen(fs) return rv end return new "node.Message" { name = "Error!", message = "No configuration available to execute this file", parent = self.parent } end function File:dir() return self.parent:path() end function File:extension() return self.name:match("%.([^%.]+)$") end return File
Toggle fullscreen off when launching based on current fullscreen state
Toggle fullscreen off when launching based on current fullscreen state This should hopefully fix the issue on windows where in borderless fullscreen mode, VLC pops up behind emufun.
Lua
mit
ToxicFrog/EmuFun
f4c94e04ac198f02ad8b3cc024143b8a5470da0a
dashboard/routes/dashboard.lua
dashboard/routes/dashboard.lua
local ipairs = ipairs local pairs = pairs local type = type local xpcall = xpcall local string_lower = string.lower local lor = require("lor.index") local function load_plugin_api(plugin, dashboard_router, store) local plugin_api_path = "orange.plugins." .. plugin .. ".api" ngx.log(ngx.ERR, "[plugin's api load], plugin_api_path:", plugin_api_path) local ok, plugin_api, e ok = xpcall(function() plugin_api = require(plugin_api_path) end, function() e = debug.traceback() end) if not ok or not plugin_api or type(plugin_api) ~= "table" then ngx.log(ngx.ERR, "[plugin's api load error], plugin_api_path:", plugin_api_path, " error:", e) return end local plugin_apis if plugin_api.get_mode and plugin_api:get_mode() == 2 then plugin_apis = plugin_api:get_apis() else plugin_apis = plugin_api end for uri, api_methods in pairs(plugin_apis) do ngx.log(ngx.INFO, "load route, uri:", uri) if type(api_methods) == "table" then for method, func in pairs(api_methods) do local m = string_lower(method) if m == "get" or m == "post" or m == "put" or m == "delete" then dashboard_router[m](dashboard_router, uri, func(store)) end end end end end return function(config, store) local dashboard_router = lor:Router() local orange_db = require("orange.store.orange_db") dashboard_router:get("/", function(req, res, next) --- 全局信息 -- 当前加载的插件,开启与关闭情况 -- 每个插件的规则条数等 local data = {} local plugins = config.plugins data.plugins = plugins local plugin_configs = {} for i, v in ipairs(plugins) do local tmp if v ~= "kvstore" then tmp = { enable = orange_db.get(v .. ".enable"), name = v, active_selector_count = 0, inactive_selector_count = 0, active_rule_count = 0, inactive_rule_count = 0 } local plugin_selectors = orange_db.get_json(v .. ".selectors") if plugin_selectors then for sid, s in pairs(plugin_selectors) do if s.enable == true then tmp.active_selector_count = tmp.active_selector_count + 1 local selector_rules = orange_db.get_json(v .. ".selector." .. sid .. ".rules") for _, r in ipairs(selector_rules) do if r.enable == true then tmp.active_rule_count = tmp.active_rule_count + 1 else tmp.inactive_rule_count = tmp.inactive_rule_count + 1 end end else tmp.inactive_selector_count = tmp.inactive_selector_count + 1 end end end plugin_configs[v] = tmp else tmp = { enable = orange_db.get(v .. ".enable"), name = v } end plugin_configs[v] = tmp end data.plugin_configs = plugin_configs res:render("index", data) end) dashboard_router:get("/status", function(req, res, next) res:render("status") end) dashboard_router:get("/monitor", function(req, res, next) res:render("monitor") end) dashboard_router:get("/monitor/rule/statistic", function(req, res, next) local rule_id = req.query.rule_id; local rule_name = req.query.rule_name or ""; res:render("monitor-rule-stat", { rule_id = rule_id, rule_name = rule_name }) end) dashboard_router:get("/rewrite", function(req, res, next) res:render("rewrite") end) dashboard_router:get("/redirect", function(req, res, next) res:render("redirect") end) dashboard_router:get("/rate_limiting", function(req, res, next) res:render("rate_limiting") end) dashboard_router:get("/basic_auth", function(req, res, next) res:render("basic_auth/basic_auth") end) dashboard_router:get("/key_auth", function(req, res, next) res:render("key_auth/key_auth") end) dashboard_router:get("/waf", function(req, res, next) res:render("waf") end) dashboard_router:get("/divide", function(req, res, next) res:render("divide") end) dashboard_router:get("/kvstore", function(req, res, next) res:render("kvstore") end) dashboard_router:get("/help", function(req, res, next) res:render("help") end) --- 加载其他"可用"插件API local available_plugins = config.plugins if not available_plugins or type(available_plugins) ~= "table" or #available_plugins<1 then ngx.log(ngx.ERR, "no available plugins, maybe you should check `orange.conf`.") else for _, p in ipairs(available_plugins) do load_plugin_api(p, dashboard_router, store) end end return dashboard_router end
local ipairs = ipairs local pairs = pairs local type = type local xpcall = xpcall local string_lower = string.lower local lor = require("lor.index") local function load_plugin_api(plugin, dashboard_router, store) local plugin_api_path = "orange.plugins." .. plugin .. ".api" ngx.log(ngx.ERR, "[plugin's api load], plugin_api_path:", plugin_api_path) local ok, plugin_api, e ok = xpcall(function() plugin_api = require(plugin_api_path) end, function() e = debug.traceback() end) if not ok or not plugin_api or type(plugin_api) ~= "table" then ngx.log(ngx.ERR, "[plugin's api load error], plugin_api_path:", plugin_api_path, " error:", e) return end local plugin_apis if plugin_api.get_mode and plugin_api:get_mode() == 2 then plugin_apis = plugin_api:get_apis() else plugin_apis = plugin_api end for uri, api_methods in pairs(plugin_apis) do ngx.log(ngx.INFO, "load route, uri:", uri) if type(api_methods) == "table" then for method, func in pairs(api_methods) do local m = string_lower(method) if m == "get" or m == "post" or m == "put" or m == "delete" then dashboard_router[m](dashboard_router, uri, func(store)) end end end end end return function(config, store) local dashboard_router = lor:Router() local orange_db = require("orange.store.orange_db") dashboard_router:get("/", function(req, res, next) --- 全局信息 -- 当前加载的插件,开启与关闭情况 -- 每个插件的规则条数等 local data = {} local plugins = config.plugins data.plugins = plugins local plugin_configs = {} for i, v in ipairs(plugins) do local tmp if v ~= "kvstore" then tmp = { enable = orange_db.get(v .. ".enable"), name = v, active_selector_count = 0, inactive_selector_count = 0, active_rule_count = 0, inactive_rule_count = 0 } local plugin_selectors = orange_db.get_json(v .. ".selectors") if plugin_selectors then for sid, s in pairs(plugin_selectors) do if s.enable == true then tmp.active_selector_count = tmp.active_selector_count + 1 local selector_rules = orange_db.get_json(v .. ".selector." .. sid .. ".rules") if not selector_rules then tmp.active_rule_count = 0 tmp.inactive_rule_count = 0 else for _, r in ipairs(selector_rules) do if r.enable == true then tmp.active_rule_count = tmp.active_rule_count + 1 else tmp.inactive_rule_count = tmp.inactive_rule_count + 1 end end end else tmp.inactive_selector_count = tmp.inactive_selector_count + 1 end end end plugin_configs[v] = tmp else tmp = { enable = orange_db.get(v .. ".enable"), name = v } end plugin_configs[v] = tmp end data.plugin_configs = plugin_configs res:render("index", data) end) dashboard_router:get("/status", function(req, res, next) res:render("status") end) dashboard_router:get("/monitor", function(req, res, next) res:render("monitor") end) dashboard_router:get("/monitor/rule/statistic", function(req, res, next) local rule_id = req.query.rule_id; local rule_name = req.query.rule_name or ""; res:render("monitor-rule-stat", { rule_id = rule_id, rule_name = rule_name }) end) dashboard_router:get("/rewrite", function(req, res, next) res:render("rewrite") end) dashboard_router:get("/redirect", function(req, res, next) res:render("redirect") end) dashboard_router:get("/rate_limiting", function(req, res, next) res:render("rate_limiting") end) dashboard_router:get("/basic_auth", function(req, res, next) res:render("basic_auth/basic_auth") end) dashboard_router:get("/key_auth", function(req, res, next) res:render("key_auth/key_auth") end) dashboard_router:get("/waf", function(req, res, next) res:render("waf") end) dashboard_router:get("/divide", function(req, res, next) res:render("divide") end) dashboard_router:get("/kvstore", function(req, res, next) res:render("kvstore") end) dashboard_router:get("/help", function(req, res, next) res:render("help") end) --- 加载其他"可用"插件API local available_plugins = config.plugins if not available_plugins or type(available_plugins) ~= "table" or #available_plugins<1 then ngx.log(ngx.ERR, "no available plugins, maybe you should check `orange.conf`.") else for _, p in ipairs(available_plugins) do load_plugin_api(p, dashboard_router, store) end end return dashboard_router end
fix: possible nil table variable
fix: possible nil table variable
Lua
mit
wuhuatianbao007/orange,thisverygoodhhhh/orange,sumory/orange,wuhuatianbao007/orange,jxskiss/orange,sumory/orange,sumory/orange,thisverygoodhhhh/orange,jxskiss/orange,wuhuatianbao007/orange,thisverygoodhhhh/orange,jxskiss/orange
e1e9c8035b97c66e0ec8fab2600ae3633e130c23
npc/base/trade.lua
npc/base/trade.lua
--- Base NPC script for trader NPCs -- -- This script offers the functions that are required to turn a NPC into a trader -- -- Author: Martin Karing require("base.class") require("base.common") require("base.messages") require("base.money") require("npc.base.basic") module("npc.base.trade", package.seeall) tradeNPC = base.class.class(function(self, rootNPC) if (rootNPC == nil or not rootNPC:is_a(npc.base.basic.baseNPC)) then return; end; self["_parent"] = rootNPC; self["_sellItems"] = nil; self["_buyItems"] = nil; self["_notEnoughMoneyMsg"] = base.messages.Messages(); self["_dialogClosedMsg"] = base.messages.Messages(); self["_dialogClosedNoTradeMsg"] = base.messages.Messages(); end); function tradeNPC:addItem(item) if (item == nil or not item:is_a(tradeNPCItem)) then return; end; if (item._type == "sell") then table.insert(self._sellItems, item); elseif (item._type == "buyPrimary" or item._type == "buySecondary") then table.insert(self._buyItems, item); end; end; function tradeNPC:addNotEnoughMoneyMsg(msgGerman, msgEnglish) self._notEnoughMoneyMsg:addMessage(msgGerman, msgEnglish); end; function tradeNPC:addDialogClosedMsg(msgGerman, msgEnglish) self._dialogClosedMsg:addMessage(msgGerman, msgEnglish); end; function tradeNPC:addDialogClosedNoTradeMsg(msgGerman, msgEnglish) self._dialogClosedNoTradeMsg:addMessage(msgGerman, msgEnglish); end; function tradeNPC:showDialog(npcChar, player) local anyTradeAction = false; local callback = function(dialog) local result = dialog:getResult() if result == MerchantDialog.playerSells then self:buyItemFromPlayer(npcChar, player, dialog:getSaleItem()); anyTradeAction = true; else if result == MerchantDialog.playerBuys then self:sellItemToPlayer(npcChar, player, dialog:getPurchaseIndex(), dialog:getPurchaseAmount()); anyTradeAction = true; elseif (not anyTradeAction and self._dialogClosedNoTradeMsg:hasMessages()) then local msgGerman, msgEnglish = self._dialogClosedNoTradeMsg:getRandomMessage(); npcChar:talkLanguage(Character.say, Player.german, msgGerman); npcChar:talkLanguage(Character.say, Player.english, msgEnglish); elseif (self._dialogClosedMsg:hasMessages()) then local msgGerman, msgEnglish = self._dialogClosedMsg:getRandomMessage(); npcChar:talkLanguage(Character.say, Player.german, msgGerman); npcChar:talkLanguage(Character.say, Player.english, msgEnglish); end; end; end; local dialog = MerchantDialog(base.common.GetNLS(player, "Handel", "Trade"), callback) table.foreach(self._sellItems, function(_, item) item:addToDialog(player, dialog); end); table.foreach(self._buyItems, function(_, item) item:addToDialog(player, dialog); end); player:requestMerchantDialog(dialog) end; local function isFittingItem(tradeItem, boughtItem) if (tradeItem._itemId ~= boughtItem.id) then return false; end; if (tradeItem._data ~= nil and tradeItem._data ~= boughtItem.data) then return false; end; return true; end; function tradeNPC:buyItemFromPlayer(npcChar, player, boughtItem) for index, item in pairs(self._buyItems) do if isFittingItem(item, boughtItem) then local price = item._price * boughtItem.number; if world:erase(boughtItem, boughtItem.number) then base.money.GiveMoneyToChar(player, price); end; break; end; end end; function tradeNPC:sellItemToPlayer(npcChar, player, itemIndex, amount) local item = self._sellItems[itemIndex]; if (item == nil) then base.common.InformNLS(player, "Ein Fehler ist beim Kauf des Items aufgetreten", "And error occurred while buying the item"); return; end; if (base.money.CharHasMoney(player, item._price * amount)) then base.money.TakeMoneyFromChar(player, item._price * amount); local notCreated = player:createItem(item._itemId, amount, item._quality, item._data); if (notCreated > 0) then world:createItemFromId(item._itemId, amount, player.pos, true, item._quality, item._data); end; elseif (self._notEnoughMoneyMsg:hasMessages()) then local msgGerman, msgEnglish = self._notEnoughMoneyMsg:getRandomMessage(); npcChar:talkLanguage(Character.say, Player.german, msgGerman); npcChar:talkLanguage(Character.say, Player.english, msgEnglish); end; end; tradeNPCItem = base.class.class(function(self, id, itemType, nameDe, nameEn, price, stack, quality, data) if (id == nil or id <= 0) then error("Invalid ItemID for trade item"); end; if (itemType ~= "sell" and itemType ~= "buyPrimary" and itemType ~= "buySecondary") then error("Invalid type for trade item"); end; self["_itemId"] = id; self["_type"] = itemType; if (nameDe == nil or nameEn == nil) then self["_nameDe"] = world:getItemName(id, Player.german); self["_nameEn"] = world:getItemName(id, Player.english); else self["_nameDe"] = nameDe; self["_nameEn"] = nameEn; end; if (price == nil) then if (itemType == "sell") then self["_price"] = world:getItemStatsFromId(id).Worth * 100; elseif (itemType == "buyPrimary") then self["_price"] = world:getItemStatsFromId(id).Worth * 10; elseif (itemType == "buySecondary") then self["_price"] = world:getItemStatsFromId(id).Worth * 5; end; else self["_price"] = price; end; if (itemType == "sell" and stack ~= nil) then self["_stack"] = stack; else self["_stack"] = nil; end; if (quality ~= nil or itemType ~= "sell") then self["_quality"] = quality; else self["_quality"] = 580; end; if (data ~= nil or itemType ~= "sell") then self["_data"] = data; else self["_data"] = 0; end; end); function tradeNPCItem:addToDialog(player, dialog) local name = base.common.GetNLS(player, self._nameDe, self._nameEn); if (self._type == "sell") then if (self._stack == nil) then dialog:addOffer(self._itemId, name, self._price); else dialog:addOffer(self._itemId, name, self._price, self._stack); end; elseif (self._type == "buyPrimary") then dialog:addPrimaryRequest(self._itemId, name, self._price); else dialog:addSecondaryRequest(self._itemId, name, self._price) end; end;
--- Base NPC script for trader NPCs -- -- This script offers the functions that are required to turn a NPC into a trader -- -- Author: Martin Karing require("base.class") require("base.common") require("base.messages") require("base.money") require("npc.base.basic") module("npc.base.trade", package.seeall) tradeNPC = base.class.class(function(self, rootNPC) if (rootNPC == nil or not rootNPC:is_a(npc.base.basic.baseNPC)) then return; end; self["_parent"] = rootNPC; self["_sellItems"] = nil; self["_buyItems"] = nil; self["_notEnoughMoneyMsg"] = base.messages.Messages(); self["_dialogClosedMsg"] = base.messages.Messages(); self["_dialogClosedNoTradeMsg"] = base.messages.Messages(); end); function tradeNPC:addItem(item) if (item == nil or not item:is_a(tradeNPCItem)) then return; end; if (item._type == "sell") then if (self._sellItems == nil) then self._sellItems = {}; end; table.insert(self._sellItems, item); elseif (item._type == "buyPrimary" or item._type == "buySecondary") then if (self._buyItems == nil) then self._buyItems = {}; end; table.insert(self._buyItems, item); end; end; function tradeNPC:addNotEnoughMoneyMsg(msgGerman, msgEnglish) self._notEnoughMoneyMsg:addMessage(msgGerman, msgEnglish); end; function tradeNPC:addDialogClosedMsg(msgGerman, msgEnglish) self._dialogClosedMsg:addMessage(msgGerman, msgEnglish); end; function tradeNPC:addDialogClosedNoTradeMsg(msgGerman, msgEnglish) self._dialogClosedNoTradeMsg:addMessage(msgGerman, msgEnglish); end; function tradeNPC:showDialog(npcChar, player) local anyTradeAction = false; local callback = function(dialog) local result = dialog:getResult() if result == MerchantDialog.playerSells then self:buyItemFromPlayer(npcChar, player, dialog:getSaleItem()); anyTradeAction = true; else if result == MerchantDialog.playerBuys then self:sellItemToPlayer(npcChar, player, dialog:getPurchaseIndex(), dialog:getPurchaseAmount()); anyTradeAction = true; elseif (not anyTradeAction and self._dialogClosedNoTradeMsg:hasMessages()) then local msgGerman, msgEnglish = self._dialogClosedNoTradeMsg:getRandomMessage(); npcChar:talkLanguage(Character.say, Player.german, msgGerman); npcChar:talkLanguage(Character.say, Player.english, msgEnglish); elseif (self._dialogClosedMsg:hasMessages()) then local msgGerman, msgEnglish = self._dialogClosedMsg:getRandomMessage(); npcChar:talkLanguage(Character.say, Player.german, msgGerman); npcChar:talkLanguage(Character.say, Player.english, msgEnglish); end; end; end; local dialog = MerchantDialog(base.common.GetNLS(player, "Handel", "Trade"), callback) table.foreach(self._sellItems, function(_, item) item:addToDialog(player, dialog); end); table.foreach(self._buyItems, function(_, item) item:addToDialog(player, dialog); end); player:requestMerchantDialog(dialog) end; local function isFittingItem(tradeItem, boughtItem) if (tradeItem._itemId ~= boughtItem.id) then return false; end; if (tradeItem._data ~= nil and tradeItem._data ~= boughtItem.data) then return false; end; return true; end; function tradeNPC:buyItemFromPlayer(npcChar, player, boughtItem) for index, item in pairs(self._buyItems) do if isFittingItem(item, boughtItem) then local price = item._price * boughtItem.number; if world:erase(boughtItem, boughtItem.number) then base.money.GiveMoneyToChar(player, price); end; break; end; end end; function tradeNPC:sellItemToPlayer(npcChar, player, itemIndex, amount) local item = self._sellItems[itemIndex]; if (item == nil) then base.common.InformNLS(player, "Ein Fehler ist beim Kauf des Items aufgetreten", "And error occurred while buying the item"); return; end; if (base.money.CharHasMoney(player, item._price * amount)) then base.money.TakeMoneyFromChar(player, item._price * amount); local notCreated = player:createItem(item._itemId, amount, item._quality, item._data); if (notCreated > 0) then world:createItemFromId(item._itemId, amount, player.pos, true, item._quality, item._data); end; elseif (self._notEnoughMoneyMsg:hasMessages()) then local msgGerman, msgEnglish = self._notEnoughMoneyMsg:getRandomMessage(); npcChar:talkLanguage(Character.say, Player.german, msgGerman); npcChar:talkLanguage(Character.say, Player.english, msgEnglish); end; end; tradeNPCItem = base.class.class(function(self, id, itemType, nameDe, nameEn, price, stack, quality, data) if (id == nil or id <= 0) then error("Invalid ItemID for trade item"); end; if (itemType ~= "sell" and itemType ~= "buyPrimary" and itemType ~= "buySecondary") then error("Invalid type for trade item"); end; self["_itemId"] = id; self["_type"] = itemType; if (nameDe == nil or nameEn == nil) then self["_nameDe"] = world:getItemName(id, Player.german); self["_nameEn"] = world:getItemName(id, Player.english); else self["_nameDe"] = nameDe; self["_nameEn"] = nameEn; end; if (price == nil) then if (itemType == "sell") then self["_price"] = world:getItemStatsFromId(id).Worth * 100; elseif (itemType == "buyPrimary") then self["_price"] = world:getItemStatsFromId(id).Worth * 10; elseif (itemType == "buySecondary") then self["_price"] = world:getItemStatsFromId(id).Worth * 5; end; else self["_price"] = price; end; if (itemType == "sell" and stack ~= nil) then self["_stack"] = stack; else self["_stack"] = nil; end; if (quality ~= nil or itemType ~= "sell") then self["_quality"] = quality; else self["_quality"] = 580; end; if (data ~= nil or itemType ~= "sell") then self["_data"] = data; else self["_data"] = 0; end; end); function tradeNPCItem:addToDialog(player, dialog) local name = base.common.GetNLS(player, self._nameDe, self._nameEn); if (self._type == "sell") then if (self._stack == nil) then dialog:addOffer(self._itemId, name, self._price); else dialog:addOffer(self._itemId, name, self._price, self._stack); end; elseif (self._type == "buyPrimary") then dialog:addPrimaryRequest(self._itemId, name, self._price); else dialog:addSecondaryRequest(self._itemId, name, self._price) end; end;
Bugfix in trader script
Bugfix in trader script
Lua
agpl-3.0
Baylamon/Illarion-Content,vilarion/Illarion-Content,LaFamiglia/Illarion-Content,KayMD/Illarion-Content,Illarion-eV/Illarion-Content
256fa6189af56a02bf45cd7a11c3bc929d3bc9f7
kong/plugins/session/access.lua
kong/plugins/session/access.lua
local constants = require "kong.constants" local responses = require "kong.tools.responses" local session = require "kong.plugins.session.session" local ngx_set_header = ngx.req.set_header local log = ngx.log local kong = kong local _M = {} local function load_consumer(consumer_id) local result, err = kong.db.consumers:select { id = consumer_id } if not result then return nil, err end return result end local function set_consumer(consumer, credential_id) ngx_set_header(constants.HEADERS.CONSUMER_ID, consumer.id) ngx_set_header(constants.HEADERS.CONSUMER_CUSTOM_ID, consumer.custom_id) ngx_set_header(constants.HEADERS.CONSUMER_USERNAME, consumer.username) ngx.ctx.authenticated_consumer = consumer if credential_id then ngx.ctx.authenticated_credential = { id = credential_id or consumer.id, consumer_id = consumer.id } ngx_set_header(constants.HEADERS.ANONYMOUS, true) end end function _M.execute(conf) local s = session.open_session(conf) if not s.present then log(ngx.DEBUG, "Session not present") return end -- check if incoming request is trying to logout if session.logout(conf) then log(ngx.DEBUG, "Session logging out") s:destroy() return responses.send_HTTP_OK() end local cid, credential = session.retrieve_session_data(s) local consumer_cache_key = kong.dao.consumers:cache_key(cid) local consumer, err = kong.cache:get(consumer_cache_key, nil, load_consumer, cid) if err then ngx.log(ngx.ERR, "Error loading consumer: ", err) return end -- destroy sessions with invalid consumer_id if not consumer then ngx.log(ngx.DEBUG, "No consumer, destroying session") return s:destroy() end s:start() set_consumer(consumer, credential) ngx.ctx.authenticated_session = s end return _M
local constants = require "kong.constants" local session = require "kong.plugins.session.session" local ngx_set_header = ngx.req.set_header local log = ngx.log local kong = kong local _M = {} local function load_consumer(consumer_id) local result, err = kong.db.consumers:select { id = consumer_id } if not result then return nil, err end return result end local function set_consumer(consumer, credential_id) ngx_set_header(constants.HEADERS.CONSUMER_ID, consumer.id) ngx_set_header(constants.HEADERS.CONSUMER_CUSTOM_ID, consumer.custom_id) ngx_set_header(constants.HEADERS.CONSUMER_USERNAME, consumer.username) ngx.ctx.authenticated_consumer = consumer if credential_id then ngx.ctx.authenticated_credential = { id = credential_id or consumer.id, consumer_id = consumer.id } ngx_set_header(constants.HEADERS.ANONYMOUS, true) end end function _M.execute(conf) local s = session.open_session(conf) if not s.present then log(ngx.DEBUG, "Session not present") return end -- check if incoming request is trying to logout if session.logout(conf) then log(ngx.DEBUG, "Session logging out") s:destroy() return ngx.exit(200) end local cid, credential = session.retrieve_session_data(s) local consumer_cache_key = kong.dao.consumers:cache_key(cid) local consumer, err = kong.cache:get(consumer_cache_key, nil, load_consumer, cid) if err then ngx.log(ngx.ERR, "Error loading consumer: ", err) return end -- destroy sessions with invalid consumer_id if not consumer then ngx.log(ngx.DEBUG, "No consumer, destroying session") return s:destroy() end s:start() set_consumer(consumer, credential) ngx.ctx.authenticated_session = s end return _M
fix(session) remove deprecated responses utils
fix(session) remove deprecated responses utils * add ngx.exit to make sure it works with 0.15 and 1.0
Lua
apache-2.0
Kong/kong,Kong/kong,Kong/kong
830f93a38c49bf6c2227255068594c3998a4f54e
scripts/embed.lua
scripts/embed.lua
-- -- Embed the Lua scripts into src/host/scripts.c as static data buffers. -- I embed the actual scripts, rather than Lua bytecodes, because the -- bytecodes are not portable to different architectures, which causes -- issues in Mac OS X Universal builds. -- local function loadScript(fname) local f = io.open(fname) local s = assert(f:read("*a")) f:close() -- strip tabs s = s:gsub("[\t]", "") -- strip any CRs s = s:gsub("[\r]", "") -- strip out block comments s = s:gsub("[^\"']%-%-%[%[.-%]%]", "") s = s:gsub("[^\"']%-%-%[=%[.-%]=%]", "") s = s:gsub("[^\"']%-%-%[==%[.-%]==%]", "") -- strip out inline comments s = s:gsub("\n%-%-[^\n]*", "\n") -- escape backslashes s = s:gsub("\\", "\\\\") -- strip duplicate line feeds s = s:gsub("\n+", "\n") -- strip out leading comments s = s:gsub("^%-%-[^\n]*\n", "") -- escape line feeds s = s:gsub("\n", "\\n") -- escape double quote marks s = s:gsub("\"", "\\\"") return s end local function appendScript(result, contents) -- break up large strings to fit in Visual Studio's string length limit local max = 4096 local start = 1 local len = contents:len() while start <= len do local n = len - start if n > max then n = max end local finish = start + n -- make sure I don't cut an escape sequence while contents:sub(finish, finish) == "\\" do finish = finish - 1 end local s = contents:sub(start, finish) table.insert(result, "\t\"" .. s .. iif(finish < len, '"', '",')) start = finish + 1 end table.insert(result, "") end -- Prepare the file header local result = {} table.insert(result, "/* Premake's Lua scripts, as static data buffers for release mode builds */") table.insert(result, "/* DO NOT EDIT - this file is autogenerated - see BUILD.txt */") table.insert(result, "/* To regenerate this file, run: premake5 embed */") table.insert(result, "") table.insert(result, '#include "premake.h"') table.insert(result, "") -- Find all of the _manifest.lua files within the project local mask = path.join(_MAIN_SCRIPT_DIR, "**/_manifest.lua") local manifests = os.matchfiles(mask) -- Generate an index of the script file names. Script names are stored -- relative to the directory containing the manifest, i.e. the main -- Xcode script, which is at $/modules/xcode/xcode.lua is stored as -- "xcode/xcode.lua". Core scripts currently get special treatment and -- are stored as "base/os.lua" instead of "core/base/os.lua"; I would -- like to treat core like just another module eventually. table.insert(result, "const char* builtin_scripts_index[] = {") for mi = 1, #manifests do local manifestName = manifests[mi] local manifestDir = path.getdirectory(manifestName) local baseDir = path.getdirectory(manifestDir) local files = dofile(manifests[mi]) for fi = 1, #files do local filename = path.join(manifestDir, files[fi]) filename = path.getrelative(baseDir, filename) -- core files fix-up for backward compatibility if filename:startswith("src/") then filename = filename:sub(5) end table.insert(result, '\t"' .. filename .. '",') end end table.insert(result, "\tNULL") table.insert(result, "};") table.insert(result, "") -- Embed the actual script contents table.insert(result, "const char* builtin_scripts[] = {") for mi = 1, #manifests do local manifestName = manifests[mi] local manifestDir = path.getdirectory(manifestName) local files = dofile(manifests[mi]) for fi = 1, #files do local filename = path.join(manifestDir, files[fi]) local scr = loadScript(filename) appendScript(result, scr) end end table.insert(result, "\tNULL") table.insert(result, "};") table.insert(result, "") -- Write it all out. Check against the current contents of scripts.c first, -- and only overwrite it if there are actual changes. result = table.concat(result, "\n") local scriptsFile = path.getabsolute(path.join(_SCRIPT_DIR, "../src/host/scripts.c")) local oldVersion local file = io.open(scriptsFile, "r") if file then oldVersion = file:read("*a") file:close() end if oldVersion ~= result then print("Writing scripts.c") file = io.open(scriptsFile, "w+b") file:write(result) file:close() end
-- -- Embed the Lua scripts into src/host/scripts.c as static data buffers. -- I embed the actual scripts, rather than Lua bytecodes, because the -- bytecodes are not portable to different architectures, which causes -- issues in Mac OS X Universal builds. -- local function loadScript(fname) local f = io.open(fname) local s = assert(f:read("*a")) f:close() -- strip tabs s = s:gsub("[\t]", "") -- strip any CRs s = s:gsub("[\r]", "") -- strip out block comments s = s:gsub("[^\"']%-%-%[%[.-%]%]", "") s = s:gsub("[^\"']%-%-%[=%[.-%]=%]", "") s = s:gsub("[^\"']%-%-%[==%[.-%]==%]", "") -- strip out inline comments s = s:gsub("\n%-%-[^\n]*", "\n") -- escape backslashes s = s:gsub("\\", "\\\\") -- strip duplicate line feeds s = s:gsub("\n+", "\n") -- strip out leading comments s = s:gsub("^%-%-[^\n]*\n", "") -- escape line feeds s = s:gsub("\n", "\\n") -- escape double quote marks s = s:gsub("\"", "\\\"") return s end local function appendScript(result, contents) -- break up large strings to fit in Visual Studio's string length limit local max = 4096 local start = 1 local len = contents:len() while start <= len do local n = len - start if n > max then n = max end local finish = start + n -- make sure I don't cut an escape sequence while contents:sub(finish, finish) == "\\" do finish = finish - 1 end local s = contents:sub(start, finish) table.insert(result, "\t\"" .. s .. iif(finish < len, '"', '",')) start = finish + 1 end table.insert(result, "") end -- Prepare the file header local result = {} table.insert(result, "/* Premake's Lua scripts, as static data buffers for release mode builds */") table.insert(result, "/* DO NOT EDIT - this file is autogenerated - see BUILD.txt */") table.insert(result, "/* To regenerate this file, run: premake5 embed */") table.insert(result, "") table.insert(result, '#include "premake.h"') table.insert(result, "") -- Find all of the _manifest.lua files within the project local mask = path.join(_MAIN_SCRIPT_DIR, "**/_manifest.lua") local manifests = os.matchfiles(mask) -- Generate an index of the script file names. Script names are stored -- relative to the directory containing the manifest, i.e. the main -- Xcode script, which is at $/modules/xcode/xcode.lua is stored as -- "xcode/xcode.lua". Core scripts currently get special treatment and -- are stored as "base/os.lua" instead of "core/base/os.lua"; I would -- like to treat core like just another module eventually. table.insert(result, "const char* builtin_scripts_index[] = {") for mi = 1, #manifests do local manifestName = manifests[mi] local manifestDir = path.getdirectory(manifestName) local baseDir = path.getdirectory(manifestDir) local files = dofile(manifests[mi]) for fi = 1, #files do local filename = path.join(manifestDir, files[fi]) filename = path.getrelative(baseDir, filename) -- core files fix-up for backward compatibility if filename:startswith("src/") then filename = filename:sub(5) end table.insert(result, '\t"' .. filename .. '",') end end table.insert(result, '\t"_premake_main.lua",') table.insert(result, '\t"_manifest.lua",') table.insert(result, "\tNULL") table.insert(result, "};") table.insert(result, "") -- Embed the actual script contents table.insert(result, "const char* builtin_scripts[] = {") for mi = 1, #manifests do local manifestName = manifests[mi] local manifestDir = path.getdirectory(manifestName) local files = dofile(manifests[mi]) for fi = 1, #files do local filename = path.join(manifestDir, files[fi]) local scr = loadScript(filename) appendScript(result, scr) end end appendScript(result, loadScript(path.join(_SCRIPT_DIR, "../src/_premake_main.lua"))) appendScript(result, loadScript(path.join(_SCRIPT_DIR, "../src/_manifest.lua"))) table.insert(result, "\tNULL") table.insert(result, "};") table.insert(result, "") -- Write it all out. Check against the current contents of scripts.c first, -- and only overwrite it if there are actual changes. result = table.concat(result, "\n") local scriptsFile = path.getabsolute(path.join(_SCRIPT_DIR, "../src/host/scripts.c")) local oldVersion local file = io.open(scriptsFile, "r") if file then oldVersion = file:read("*a") file:close() end if oldVersion ~= result then print("Writing scripts.c") file = io.open(scriptsFile, "w+b") file:write(result) file:close() end
Fix embedding of main script and manifest
Fix embedding of main script and manifest --HG-- branch : feature/improved-embedding
Lua
bsd-3-clause
annulen/premake,annulen/premake,annulen/premake,annulen/premake
dff3dc381091322f1750489164b1c319ad6f5922
xmake.lua
xmake.lua
set_project("UBWindow") if is_mode("debug") then set_symbols("debug") set_optimize("none") end if is_mode("release") then set_symbols("hidden") set_optimize("fastest") set_strip("all") end add_includedirs("include") target("demo_blank") set_kind("binary") set_targetdir("bin") add_linkdirs("lib") add_files("demo/*.c") add_links("ubwindow") if is_plat("linux") then add_links("X11") end if is_plat("macosx") then add_ldflags("-framework Cocoa") end target("ubwindow") set_kind("static") set_targetdir("lib") add_includedirs("src") add_files("src/*.c") if is_plat("macosx") then add_files("src/*.m") end
set_project("UBWindow") if is_mode("debug") then set_symbols("debug") set_optimize("none") end if is_mode("release") then set_symbols("hidden") set_optimize("fastest") set_strip("all") end add_includedirs("include") target("ubwindow") set_kind("static") set_targetdir("lib") add_includedirs("src") add_files("src/*.c") if is_plat("macosx") then add_files("src/*.m") end target("demo_blank") add_deps("ubwindow") set_kind("binary") set_targetdir("bin") add_linkdirs("lib") add_files("demo/*.c") add_links("ubwindow") if is_plat("windows") then add_links("user32") end if is_plat("mingw") then add_ldflags("-static") end if is_plat("linux") then add_links("X11") end if is_plat("macosx") then add_ldflags("-framework Cocoa") end
Fixed xmake.lua
Fixed xmake.lua
Lua
mit
yulon/pwre
2c9223a98c85bb8f63cb34348b9335c8a77d09c5
src/cosy/websocket.lua
src/cosy/websocket.lua
local Configuration = require "cosy.configuration" .whole local Platform = require "cosy.platform" local Methods = require "cosy.methods" local LuaRpc = {} function LuaRpc.message (message) local ok, res = Platform.table.decode (message) if not ok then return Platform.table.encode ({ version = "2.0", id = nil, error = { code = -32700, message = "Parse error", data = res, }, }) end local results = {} if #res == 0 then results [#results+1] = LuaRpc.request (res) else for i = 1, #res do results [#results+1] = LuaRpc.request (res [i]) if res [i].id == nil then results [#results] = nil end end end if #results == 0 then return elseif #results == 1 then return Platform.table.encode (results [1]) else return Platform.table.encode (results) end end function LuaRpc.request (request) if request.version ~= "2.0" or type (request.method) ~= "string" then return { LuaRpc = "2.0", id = request.id, error = { code = -32600, message = "Invalid Request", }, } end local method = Methods [request.method:gsub ("-", "_")] if not method then return { version = "2.0", id = request.id, error = { code = -32601, message = "Method not found", }, } end local ok, result = pcall (method, request.params.token, request.params.request) if not ok and type (result) == "table" and result._ == "check:error" then return { version = "2.0", id = request.id, error = { code = -32602, message = "Invalid params", data = result, }, } end if not ok then return { version = "2.0", id = request.id, error = { code = -32603, message = "Internal error", data = result, }, } end if request.id then return { version = "2.0", id = request.id, result = result, } end end local copas = require "copas" local websocket = require "websocket" Platform:register ("email", function () Platform.email = {} Platform.email.last_sent = {} Platform.email.send = function (t) Platform.email.last_sent [t.to.email] = t end end) websocket.server.copas.listen { interface = Configuration.server.host._, port = Configuration.server.port._, protocols = { cosy = function (client) while true do local message = client:receive () if message then local result = LuaRpc.message (message) if result then client:send (result) end else client:close () return end end end, }, default = function (client) client:send "'cosy' is the only supported protocol" client:close () end } copas.loop ()
local coevas = require "copas.ev" coevas:make_default () local Configuration = require "cosy.configuration" local Platform = require "cosy.platform" local Methods = require "cosy.methods" local function translate (x) x.locale = x.locale or Configuration.locale._ for _, v in pairs (x) do if type (v) == "table" and not getmetatable (v) then local vl = v.locale v.locale = x.locale v.message = translate (v) v.locale = vl end end if x._ then x.message = Platform.i18n.translate (x._, x) end return x end local function request (message) local decoded, request = Platform.table.decode (message) if not decoded then return Platform.table.encode (translate { success = false, error = { _ = "rpc:format", reason = message, }, }) end local identifier = request.identifier local operation = request.operation local parameters = request.parameters local method = Methods [operation] if not method then return Platform.table.encode (translate { identifier = identifier, success = false, error = { _ = "rpc:no-operation", reason = operation, }, }) end local called, result = pcall (method, parameters or {}) if not called then return Platform.table.encode (translate { identifier = identifier, success = false, error = result, }) end return Platform.table.encode (translate { identifier = identifier, success = true, response = result, }) end local copas = require "copas" local websocket = require "websocket" Platform:register ("email", function () Platform.email = {} Platform.email.last_sent = {} Platform.email.send = function (t) Platform.email.last_sent [t.to.email] = t end end) websocket.server.copas.listen { interface = Configuration.server.host._, port = Configuration.server.port._, protocols = { cosy = function (client) while true do local message = client:receive () if message then local result = request (message) if result then client:send (result) end else client:close () return end end end, }, default = function (client) client:send "'cosy' is the only supported protocol" client:close () end } copas.loop ()
Fix remote procedure call.
Fix remote procedure call.
Lua
mit
CosyVerif/library,CosyVerif/library,CosyVerif/library
0bb7af38bd50ae7c9aa4a1f750eee5c2c6f66e28
server/lualib/channelhub.lua
server/lualib/channelhub.lua
local core = require "silly.core" local np = require "netpacket" local token = require "token" local sproto = require "protocol.server" local master = require "cluster.master" local pack = string.pack local unpack = string.unpack ----------------socket local function sendserver(fd, uid, cmd, ack) cmd = sproto:querytag(cmd) local hdr = pack("<I4I4", uid, cmd) local dat = sproto:encode(cmd, ack) return master.sendslave(fd, hdr .. dat) end local function forwardserver(fd, uid, dat) local hdr = pack("<I4", uid) return master.sendslave(fd, hdr .. dat) end ----------------channel router local NIL = {} local CMD = {} local readonly = {__newindex = function() assert("read only table") end} local router_handler = {} local function router_regserver(cmd, func) local cmd = sproto:querytag(cmd) local cb = function(uid, dat, fd) local req if #dat > 8 then dat = dat:sub(8 + 1) req = sproto:decode(cmd, dat) else req = NIL end func(uid, req, fd) end CMD[cmd] = cb end ----------------online local LOGIN_TYPE = 1 * 10000 local ROLE_TYPE = 2 * 10000 local agent_serverkey = { [LOGIN_TYPE] = "slogin", [ROLE_TYPE] = "srole", } local online_agent = {} local function online_login(uid, agent) online_agent[uid] = agent agent.slogin = 1 agent.srole = 1 end local function online_logout(uid) local a = online_agent[uid] if not a then return end a.slogin = false s.srole = false online_agent[uid] = nil end local function online_kickout(uid) local a = online_agent[uid] if not a then return end a.slogin = false a.srole = false a:kickout() online_agent[uid] = nil end --------------channel forward local channel_type_key = { --login ["login"] = LOGIN_TYPE, [LOGIN_TYPE] = "login", --role ["role"] = ROLE_TYPE, [ROLE_TYPE] = "role" } local channel_fd_typeid = { --[fd] = 'channel_type_key[type] + serverid' } local channel_typeid_fd = { --[channel_type_key[type] + serverid] = fd } local channel_cmd_typeid = { --[cmd] = typeid } local function channel_regclient(typ, id, fd, list_cmd) local typeid = assert(channel_type_key[typ], typ) for _, v in pairs(list_cmd) do local typ = channel_cmd_typeid[v] if typ then assert(typ == typeid) else channel_cmd_typeid[v] = typeid end end typeid = typeid + id channel_fd_typeid[fd] = typeid channel_typeid_fd[typeid] = fd end local function channel_clear(fd) local typeid = channel_fd_typeid[fd] if not typeid then return end channel_fd_typeid[fd] = nil channel_typeid_fd[typeid] = nil end local function channel_tryforward(agent, cmd, dat) --dat:[cmd][packet] local typeid = channel_cmd_typeid[cmd] if not typeid then return false end local key = agent_serverkey[typeid] local id = agent[key] typeid = typeid + id local fd = channel_typeid_fd[typeid] if not fd then return false end return forwardserver(fd, agent.uid, dat) end ----------------protocol local function sr_register(uid, req, fd) print("[gate] sr_register:", req.typ, req.id) for _, v in pairs(req.handler) do print(string.format("[gate] sr_register %s", v)) end channel_regclient(req.typ, req.id, fd, req.handler) sendserver(fd, uid, "sa_register", req) end local function sr_fetchtoken(uid, req, fd) local tk = token.fetch(uid) req.token = tk sendserver(fd, uid, "sa_fetchtoken", req) print("[gate] fetch token", uid, tk) end local function sr_kickout(uid, req, fd) online_kickout(uid) sendserver(fd, uid, "sa_kickout", req) print("[gate]fetch kickout uid:", uid, "gatefd", gatefd) end local function s_multicast(uid, req, fd) print("muticast") end router_regserver("sr_register", sr_register) router_regserver("sr_fetchtoken", sr_fetchtoken) router_regserver("sr_kickout", sr_kickout) router_regserver("s_multicast", s_multicast) --------------entry local M = { login = online_login, logout = online_logout, tryforward = channel_tryforward, --event accept = function(fd, addr) end, close = function(fd, errno) channel_clear(fd) end, data = function(fd, d, sz) local dat = core.tostring(d, sz) np.drop(d) local uid, cmd = unpack("<I4I4", dat) local func = CMD[cmd] if func then func(uid, dat, fd) return end local a = online_agent[uid] if not a then print("[gate] broker data uid:", uid, " logout") return end a:slavedata(cmd, dat) end, } return M
local core = require "silly.core" local np = require "netpacket" local token = require "token" local sproto = require "protocol.server" local master = require "cluster.master" local pack = string.pack local unpack = string.unpack ----------------socket local function sendserver(fd, uid, cmd, ack) cmd = sproto:querytag(cmd) local hdr = pack("<I4I4", uid, cmd) local dat = sproto:encode(cmd, ack) return master.sendslave(fd, hdr .. dat) end local function forwardserver(fd, uid, dat) local hdr = pack("<I4", uid) return master.sendslave(fd, hdr .. dat) end ----------------channel router local NIL = {} local CMD = {} local readonly = {__newindex = function() assert("read only table") end} local router_handler = {} local function router_regserver(cmd, func) local cmd = sproto:querytag(cmd) local cb = function(uid, dat, fd) local req if #dat > 8 then dat = dat:sub(8 + 1) req = sproto:decode(cmd, dat) else req = NIL end func(uid, req, fd) end CMD[cmd] = cb end ----------------online local LOGIN_TYPE = 1 * 10000 local ROLE_TYPE = 2 * 10000 local agent_serverkey = { [LOGIN_TYPE] = "slogin", [ROLE_TYPE] = "srole", } local online_agent = {} local function online_login(uid, agent) online_agent[uid] = agent agent.slogin = 1 agent.srole = 1 end local function online_logout(uid) local a = online_agent[uid] if not a then return end a.slogin = false s.srole = false online_agent[uid] = nil end local function online_kickout(uid) local a = online_agent[uid] if not a then return end a.slogin = false a.srole = false a:kickout() online_agent[uid] = nil end --------------channel forward local channel_type_key = { --login ["login"] = LOGIN_TYPE, [LOGIN_TYPE] = "login", --role ["role"] = ROLE_TYPE, [ROLE_TYPE] = "role" } local channel_fd_typeid = { --[fd] = 'channel_type_key[type] + serverid' } local channel_typeid_fd = { --[channel_type_key[type] + serverid] = fd } local channel_cmd_typeid = { --[cmd] = typeid } local function channel_regclient(typ, id, fd, list_cmd) local typeid = assert(channel_type_key[typ], typ) for _, v in pairs(list_cmd) do local typ = channel_cmd_typeid[v] if typ then assert(typ == typeid) else channel_cmd_typeid[v] = typeid end end typeid = typeid + id channel_fd_typeid[fd] = typeid channel_typeid_fd[typeid] = fd end local function channel_clear(fd) local typeid = channel_fd_typeid[fd] if not typeid then return end channel_fd_typeid[fd] = nil channel_typeid_fd[typeid] = nil end local function channel_tryforward(agent, cmd, dat) --dat:[cmd][packet] local typeid = channel_cmd_typeid[cmd] if not typeid then return false end local id = agent[key] if not id then return false end local key = agent_serverkey[typeid] typeid = typeid + id local fd = channel_typeid_fd[typeid] if not fd then return false end return forwardserver(fd, agent.uid, dat) end ----------------protocol local function sr_register(uid, req, fd) print("[gate] sr_register:", req.typ, req.id) for _, v in pairs(req.handler) do print(string.format("[gate] sr_register %s", v)) end channel_regclient(req.typ, req.id, fd, req.handler) sendserver(fd, uid, "sa_register", req) end local function sr_fetchtoken(uid, req, fd) local tk = token.fetch(uid) req.token = tk sendserver(fd, uid, "sa_fetchtoken", req) print("[gate] fetch token", uid, tk) end local function sr_kickout(uid, req, fd) online_kickout(uid) sendserver(fd, uid, "sa_kickout", req) print("[gate]fetch kickout uid:", uid, "gatefd", gatefd) end local function s_multicast(uid, req, fd) print("muticast") end router_regserver("sr_register", sr_register) router_regserver("sr_fetchtoken", sr_fetchtoken) router_regserver("sr_kickout", sr_kickout) router_regserver("s_multicast", s_multicast) --------------entry local M = { login = online_login, logout = online_logout, tryforward = channel_tryforward, --event accept = function(fd, addr) end, close = function(fd, errno) channel_clear(fd) end, data = function(fd, d, sz) local dat = core.tostring(d, sz) np.drop(d) local uid, cmd = unpack("<I4I4", dat) local func = CMD[cmd] if func then func(uid, dat, fd) return end local a = online_agent[uid] if not a then print("[gate] broker data uid:", uid, " logout") return end a:slavedata(cmd, dat) end, } return M
bugfix: channel_tryforward
bugfix: channel_tryforward
Lua
mit
findstr/mmorpg-demo,findstr/mmorpg-demo
adf3cf57cef5b5e1cfe0f26de5f0848f30e96a15
lua/wire/client/WireMenus.lua
lua/wire/client/WireMenus.lua
-- $Rev: 1366 $ -- $LastChangedDate: 2009-07-20 00:09:28 -0700 (Mon, 20 Jul 2009) $ -- $LastChangedBy: tad2020 $ local Wire_Categories = { "Wire - Advanced", "Wire - Beacon", "Wire - Control", "Wire - Data", "Wire - Detection", "Wire - Display", "Wire - Render", "Wire - I/O", "Wire - Physics", "Wire - Tools", -- "Administration", --unused } local function WireTab() spawnmenu.AddToolTab( "Wire", "Wire" ) for _,Category in ipairs(Wire_Categories) do spawnmenu.AddToolCategory("Wire", Category, Category) end --start: UGLY HACK, BAD BAD BAD D: local oldspawnmenuAddToolMenuOption = spawnmenu.AddToolMenuOption function spawnmenu.AddToolMenuOption(tab, category, ...) if tab == "Main" and string.lower(string.Left(category, 4)) == "wire" then tab = "Wire" end oldspawnmenuAddToolMenuOption(tab, category, ...) end --end: UGLY HACK, BAD BAD BAD D: end hook.Add( "AddToolMenuTabs", "WireTab", WireTab) --[[ -- TODO: add these to the device files themselves??? local devs = { ["#Max Wiremod Wheels"] = "wheels", ["#Max Wiremod Waypoints"] = "waypoints", ["#Max Wiremod Values"] = "values", ["#Max Wiremod Two-way Radios"] = "twoway_radioes", ["#Max Wiremod Turrets"] = "turrets", ["#Max Wiremod Thrusters"] = "thrusters", ["#Max Wiremod Target Finders"] = "target_finders", ["#Max Wiremod Speedometers"] = "speedometers", ["#Max Wiremod Spawners"] = "spawners", ["#Max Wiremod Simple Explosives"] = "simple_explosive", ["#Max Wiremod Sensors"] = "sensors", ["#Max Wiremod Relays"] = "relays", ["#Max Wiremod Rangers"] = "rangers", ["#Max Wiremod Radios"] = "radioes", ["#Max Wiremod Pods"] = "pods", ["#Max Wiremod Sockets"] = "sockets", ["#Max Wiremod Plugs"] = "plugs", ["#Max Wiremod Outputs"] = "outputs", ["#Max Wiremod Oscilloscopes"] = "oscilloscopes", ["#Max Wiremod Numpads"] = "numpads", ["#Max Wiremod Nailers"] = "nailers", ["#Max Wiremod Locators"] = "locators", ["#Max Wiremod Inputs"] = "inputs", ["#Max Wiremod Hoverballs"] = "hoverballs", ["#Max Wiremod Gyroscopes"] = "gyroscopes", ["#Max Wiremod GPSes"] = "gpss", ["#Max Wiremod Gates - Trig"] = "gate_trigs", ["#Max Wiremod Gates - Time"] = "gate_times", ["#Max Wiremod Gates - Selection"] = "gate_selections", ["#Max Wiremod Gates - Memory"] = "gate_memorys", ["#Max Wiremod Gates - Logic"] = "gate_logics", ["#Max Wiremod Gates - Comparison"] = "gate_logics", ["#Max Wiremod Gates"] = "gates", ["#Max Wiremod Forcers"] = "forcers", ["#Max Wiremod Explosives"] = "explosive", ["#Max Wiremod Dual Inputs"] = "dual_inputs", ["#Max Wiremod Detonators"] = "detonators", ["#Max Wiremod CPUs"] = "cpus", ["#Max Wiremod Buttons"] = "buttons", ["#Max Wiremod Adv. Inputs"] = "adv_inputs", } function AddWireAdminMaxDevice(pluralname, dev) devs["Max Wiremod "..pluralname] = dev end local function BuildAdminControlPanel(Panel) for name,dev in pairs(devs) do local slider = Panel:NumSlider(name, "sbox_maxwire_"..dev, 0, 999, 0) slider.dev = dev end end local function AddWireAdminControlPanelMenu() spawnmenu.AddToolMenuOption("Wire", "Administration", "WireAdminControlPanel", "Max Wire Devices", "", "", BuildAdminControlPanel, {}) end hook.Add("PopulateToolMenu", "AddAddWireAdminControlPanelMenu", AddWireAdminControlPanelMenu) ]]--
-- $Rev: 1366 $ -- $LastChangedDate: 2009-07-20 00:09:28 -0700 (Mon, 20 Jul 2009) $ -- $LastChangedBy: tad2020 $ local Wire_Categories = { "Wire - Advanced", "Wire - Beacon", "Wire - Control", "Wire - Data", "Wire - Detection", "Wire - Display", "Wire - Render", "Wire - I/O", "Wire - Physics", "Wire - Tools", -- "Administration", --unused } local function WireTab() spawnmenu.AddToolTab( "Wire", "Wire" ) for _,Category in ipairs(Wire_Categories) do spawnmenu.AddToolCategory("Wire", Category, Category) end --start: UGLY HACK, BAD BAD BAD D: local oldspawnmenuAddToolMenuOption = spawnmenu.AddToolMenuOption function spawnmenu.AddToolMenuOption(tab, category, ...) if tab == "Main" and string.lower(string.Left(category, 4)) == "wire" then tab = "Wire" end oldspawnmenuAddToolMenuOption(tab, category, ...) end --end: UGLY HACK, BAD BAD BAD D: end hook.Add( "AddToolMenuTabs", "WireTab", WireTab) -- TODO: add these to the device files themselves??? local devs = { ["#Max Wiremod Wheels"] = "wheels", ["#Max Wiremod Waypoints"] = "waypoints", ["#Max Wiremod Values"] = "values", ["#Max Wiremod Two-way Radios"] = "twoway_radioes", ["#Max Wiremod Turrets"] = "turrets", ["#Max Wiremod Thrusters"] = "thrusters", ["#Max Wiremod Target Finders"] = "target_finders", ["#Max Wiremod Speedometers"] = "speedometers", ["#Max Wiremod Spawners"] = "spawners", ["#Max Wiremod Simple Explosives"] = "simple_explosive", ["#Max Wiremod Sensors"] = "sensors", ["#Max Wiremod Relays"] = "relays", ["#Max Wiremod Rangers"] = "rangers", ["#Max Wiremod Radios"] = "radioes", ["#Max Wiremod Pods"] = "pods", ["#Max Wiremod Sockets"] = "sockets", ["#Max Wiremod Plugs"] = "plugs", ["#Max Wiremod Outputs"] = "outputs", ["#Max Wiremod Oscilloscopes"] = "oscilloscopes", ["#Max Wiremod Numpads"] = "numpads", ["#Max Wiremod Nailers"] = "nailers", ["#Max Wiremod Locators"] = "locators", ["#Max Wiremod Inputs"] = "inputs", ["#Max Wiremod Hoverballs"] = "hoverballs", ["#Max Wiremod Gyroscopes"] = "gyroscopes", ["#Max Wiremod GPSes"] = "gpss", ["#Max Wiremod Gates - Trig"] = "gate_trigs", ["#Max Wiremod Gates - Time"] = "gate_times", ["#Max Wiremod Gates - Selection"] = "gate_selections", ["#Max Wiremod Gates - Memory"] = "gate_memorys", ["#Max Wiremod Gates - Logic"] = "gate_logics", ["#Max Wiremod Gates - Comparison"] = "gate_logics", ["#Max Wiremod Gates"] = "gates", ["#Max Wiremod Forcers"] = "forcers", ["#Max Wiremod Explosives"] = "explosive", ["#Max Wiremod Dual Inputs"] = "dual_inputs", ["#Max Wiremod Detonators"] = "detonators", ["#Max Wiremod CPUs"] = "cpus", ["#Max Wiremod Buttons"] = "buttons", ["#Max Wiremod Adv. Inputs"] = "adv_inputs", } function AddWireAdminMaxDevice(pluralname, dev) devs["Max Wiremod "..pluralname] = dev end if SinglePlayer() then local function BuildAdminControlPanel(Panel) for name,dev in pairs(devs) do local slider = Panel:NumSlider(name, "sbox_maxwire_"..dev, 0, 999, 0) slider.dev = dev end end local function AddWireAdminControlPanelMenu() spawnmenu.AddToolMenuOption("Wire", "Administration", "WireAdminControlPanel", "Max Wire Devices", "", "", BuildAdminControlPanel, {}) end hook.Add("PopulateToolMenu", "AddAddWireAdminControlPanelMenu", AddWireAdminControlPanelMenu) end
WireMenus.lua: Fixed screens. See http://www.wiremod.com/forum/help-support/16161-displays-not-working-wire-revision-1914-a.html
WireMenus.lua: Fixed screens. See http://www.wiremod.com/forum/help-support/16161-displays-not-working-wire-revision-1914-a.html Doh, committed 5 seconds before me -Anticept
Lua
apache-2.0
immibis/wiremod,rafradek/wire,mitterdoo/wire,sammyt291/wire,Python1320/wire,bigdogmat/wire,thegrb93/wire,notcake/wire,CaptainPRICE/wire,Grocel/wire,mms92/wire,dvdvideo1234/wire,plinkopenguin/wiremod,NezzKryptic/Wire,wiremod/wire,garrysmodlua/wire
f41ccc32a932158d48ad049b304f8e42b881bd40
MMOCoreORB/bin/scripts/object/tangible/scout/trap/trap_melee_ranged_def_1.lua
MMOCoreORB/bin/scripts/object/tangible/scout/trap/trap_melee_ranged_def_1.lua
--Copyright (C) 2010 <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 object_tangible_scout_trap_trap_melee_ranged_def_1 = object_tangible_scout_trap_shared_trap_melee_ranged_def_1:new { templateType = TRAP, objectMenuComponent = {"cpp", "TrapMenuComponent"}, useCount = 5, skillRequired = 20, skillMods = {{"ranged_defense", -60}, {"melee_defense", -60}}, healthCost = 17, actionCost = 30, mindCost = 17, maxRange = 32, poolToDamage = HEALTH, minDamage = 90, maxDamage = 170, duration = 10, state = IMMOBILIZED, defenseMod = "", successMessage = "trap_melee_ranged_def_1_effect", failMessage = "trap_melee_ranged_def_1_effect_no", startSpam = "melee_ranged_def_1_on", stopSpam = "melee_ranged_def_1_off", animation = "throw_trap_melee_ranged_def_1", numberExperimentalProperties = {1, 1, 1, 1}, experimentalProperties = {"XX", "XX", "XX", "XX"}, experimentalWeights = {1, 1, 1, 1}, experimentalGroupTitles = {"null", "null", "null", "null"}, experimentalSubGroupTitles = {"null", "null", "hitpoints", "quality"}, experimentalMin = {0, 0, 1000, 1}, experimentalMax = {0, 0, 1000, 100}, experimentalPrecision = {0, 0, 0, 0}, } ObjectTemplates:addTemplate(object_tangible_scout_trap_trap_melee_ranged_def_1, "object/tangible/scout/trap/trap_melee_ranged_def_1.iff")
--Copyright (C) 2010 <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 object_tangible_scout_trap_trap_melee_ranged_def_1 = object_tangible_scout_trap_shared_trap_melee_ranged_def_1:new { templateType = TRAP, objectMenuComponent = {"cpp", "TrapMenuComponent"}, useCount = 5, skillRequired = 20, skillMods = {{"ranged_defense", -60}, {"melee_defense", -60}}, healthCost = 17, actionCost = 30, mindCost = 17, maxRange = 32, poolToDamage = HEALTH, minDamage = 90, maxDamage = 170, duration = 10, state = IMMOBILIZED, defenseMod = "", successMessage = "trap_melee_ranged_def_1_effect", failMessage = "", startSpam = "melee_ranged_def_1_on", stopSpam = "melee_ranged_def_1_off", animation = "throw_trap_melee_ranged_def_1", numberExperimentalProperties = {1, 1, 1, 1}, experimentalProperties = {"XX", "XX", "XX", "XX"}, experimentalWeights = {1, 1, 1, 1}, experimentalGroupTitles = {"null", "null", "null", "null"}, experimentalSubGroupTitles = {"null", "null", "hitpoints", "quality"}, experimentalMin = {0, 0, 1000, 1}, experimentalMax = {0, 0, 1000, 100}, experimentalPrecision = {0, 0, 0, 0}, } ObjectTemplates:addTemplate(object_tangible_scout_trap_trap_melee_ranged_def_1, "object/tangible/scout/trap/trap_melee_ranged_def_1.iff")
[Fixed] Glow Juice trap message
[Fixed] Glow Juice trap message git-svn-id: c34995188cc7e843f8a799edec2d9d4b36f36456@4657 c3d1530f-68f5-4bd0-87dc-8ef779617e40
Lua
agpl-3.0
lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/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,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo
ec5cbf6b40ba2e7f3c11a7d3db4abd9a9719920f
src/nn-modules/EncoderPool.lua
src/nn-modules/EncoderPool.lua
local EncoderPool, parent = torch.class('nn.EncoderPool', 'nn.Container') function EncoderPool:__init(mapper,reducer) parent.__init(self) self.mapper = mapper self.reducer = reducer self.modules = {} table.insert(self.modules,mapper) table.insert(self.modules,reducer) end function EncoderPool:updateOutput(input) --first, reshape the data by pulling the second dimension into the first self.inputSize = input:size() local numPerExample = self.inputSize[2] local minibatchSize = self.inputSize[1] self.sizes = self.sizes or torch.LongStorage(self.inputSize:size() -1) self.sizes[1] = minibatchSize*numPerExample for i = 2,self.sizes:size() do self.sizes[i] = self.inputSize[i+1] end self.reshapedInput = input:view(self.sizes) self.mapped = self.mapper:updateOutput(self.reshapedInput) self.sizes3 = self.mapped:size() self.sizes2 = self.sizes2 or torch.LongStorage(self.mapped:dim() + 1) self.sizes2[1] = minibatchSize self.sizes2[2] = numPerExample for i = 2,self.mapped:dim() do self.sizes2[i+1] = self.mapped:size(i) end self.mappedAndReshaped = self.mapped:view(self.sizes2) self.output = self.reducer:updateOutput(self.mappedAndReshaped) return self.output end function EncoderPool:backward(input,gradOutput) local function operator(module,input,gradOutput) return module:backward(input,gradOutput) end return self:genericBackward(operator,input,gradOutput) end function EncoderPool:updateGradInput(input,gradOutput) local function operator(module,input,gradOutput) return module:updateGradInput(input,gradOutput) end return self:genericBackward(operator,input,gradOutput) end function EncoderPool:accUpdateGradParameters(input,gradOutput,lr) local function operator(module,input,gradOutput) return module:accUpdateGradParameters(input,gradOutput,lr) end return self:genericBackward(operator,input,gradOutput) end function EncoderPool:accGradParameters(input,gradOutput,lr) local function operator(module,input,gradOutput) return module:accGradParameters(input,gradOutput,lr) end return self:genericBackward(operator,input,gradOutput) end function EncoderPool:genericBackward(operator,input, gradOutput) local db = self.reducer:forward(self.mappedAndReshaped) self.reducer:backward(self.mappedAndReshaped,db:clone():fill(1.0)) operator(self.reducer,self.mappedAndReshaped,gradOutput) local reducerGrad = self.reducer.gradInput local reshapedReducerGrad = reducerGrad:view(self.sizes3) operator(self.mapper,self.reshapedInput,reshapedReducerGrad) local mapperGrad = self.mapper.gradInput self.gradInput = (mapperGrad:dim() > 0) and mapperGrad:view(self.inputSize) or nil --some modules return nil from backwards, such as the lookup table return self.gradInput end
local EncoderPool, parent = torch.class('nn.EncoderPool', 'nn.Container') function EncoderPool:__init(mapper,reducer) parent.__init(self) self.mapper = mapper self.reducer = reducer self.modules = {} table.insert(self.modules,mapper) table.insert(self.modules,reducer) end function EncoderPool:updateOutput(input) --first, reshape the data by pulling the second dimension into the first self.inputSize = input:size() local numPerExample = self.inputSize[2] local minibatchSize = self.inputSize[1] self.sizes = self.sizes or torch.LongStorage(self.inputSize:size() -1) self.sizes[1] = minibatchSize*numPerExample for i = 2,self.sizes:size() do self.sizes[i] = self.inputSize[i+1] end self.reshapedInput = input:view(self.sizes) self.mapped = self.mapper:updateOutput(self.reshapedInput) self.sizes3 = self.mapped:size() self.sizes2 = self.sizes2 or torch.LongStorage(self.mapped:dim() + 1) self.sizes2[1] = minibatchSize self.sizes2[2] = numPerExample for i = 2,self.mapped:dim() do self.sizes2[i+1] = self.mapped:size(i) end self.mappedAndReshaped = self.mapped:view(self.sizes2) self.output = self.reducer:updateOutput(self.mappedAndReshaped) return self.output end function EncoderPool:backward(input,gradOutput) local function operator(module,input,gradOutput) return module:backward(input,gradOutput) end return self:genericBackward(operator,input,gradOutput) end function EncoderPool:updateGradInput(input,gradOutput) local function operator(module,input,gradOutput) return module:updateGradInput(input,gradOutput) end return self:genericBackward(operator,input,gradOutput) end function EncoderPool:accUpdateGradParameters(input,gradOutput,lr) local function operator(module,input,gradOutput) return module:accUpdateGradParameters(input,gradOutput,lr) end return self:genericBackward(operator,input,gradOutput) end function EncoderPool:accGradParameters(input,gradOutput,lr) local function operator(module,input,gradOutput) return module:accGradParameters(input,gradOutput,lr) end return self:genericBackward(operator,input,gradOutput) end function EncoderPool:genericBackward(operator, input, gradOutput) local db = self.reducer:forward(self.mappedAndReshaped) self.reducer:backward(self.mappedAndReshaped,db:clone():fill(1.0)) operator(self.reducer,self.mappedAndReshaped,gradOutput) local reducerGrad = self.reducer.gradInput local reshapedReducerGrad if reducerGrad:isContiguous() then reshapedReducerGrad = reducerGrad:view(self.sizes3) -- doesn't work with non-contiguous tensors else -- reshapedReducerGrad = reducerGrad:resize(self.sizes3) -- slower because of memory reallocation and changes gradOutput reshapedReducerGrad = reducerGrad:clone():resize(self.sizes3) -- doesn't change gradOutput; safer and even slower end operator(self.mapper,self.reshapedInput,reshapedReducerGrad) local mapperGrad = self.mapper.gradInput self.gradInput = (mapperGrad:dim() > 0) and mapperGrad:view(self.inputSize) or nil --some modules return nil from backwards, such as the lookup table return self.gradInput end
fix contiguous bug in encoder pool
fix contiguous bug in encoder pool
Lua
mit
patverga/torch-relation-extraction,patverga/torch-relation-extraction,patverga/torch-relation-extraction
ebade4ed012ae5268da9315d99fc2d67db9ab142
lua/entities/gmod_wire_button.lua
lua/entities/gmod_wire_button.lua
AddCSLuaFile() DEFINE_BASECLASS( "base_wire_entity" ) ENT.PrintName = "Wire Button" ENT.WireDebugName = "Button" function ENT:SetupDataTables() self:NetworkVar( "Bool", 0, "On" ) end if CLIENT then local halo_ent, halo_blur function ENT:Initialize() self.PosePosition = 0.0 end function ENT:Think() baseclass.Get("gmod_button").UpdateLever(self) end function ENT:Draw() self:DoNormalDraw(true,false) if LocalPlayer():GetEyeTrace().Entity == self and EyePos():Distance( self:GetPos() ) < 512 then if self:GetOn() then halo_ent = self halo_blur = 4 + math.sin(CurTime()*20)*2 else self:DrawEntityOutline() end end Wire_Render(self) end hook.Add("PreDrawHalos", "Wiremod_button_overlay_halos", function() if halo_ent then halo.Add({halo_ent}, Color(255,100,100), halo_blur, halo_blur, 1, true, true) halo_ent = nil end end) return -- No more client end ENT.OutputEntID = false ENT.EntToOutput = NULL local anims = { -- ["model"] = { on_anim, off_anim } ["models/props/switch001.mdl"] = { 2, 1 }, ["models/props_combine/combinebutton.mdl"] = { 3, 2 }, ["models/props_mining/control_lever01.mdl"] = { 1, 4 }, ["models/props_mining/freightelevatorbutton01.mdl"] = { 1, 2 }, ["models/props_mining/freightelevatorbutton02.mdl"] = { 1, 2 }, ["models/props_mining/switch01.mdl"] = { 1, 2 }, ["models/bull/buttons/rocker_switch.mdl"] = { 1, 2 }, ["models/bull/buttons/toggle_switch.mdl"] = { 1, 2 }, ["models/bull/buttons/key_switch.mdl"] = { 1, 2 }, ["models/props_mining/switch_updown01.mdl"] = { 2, 3 }, } function ENT:Initialize() self:PhysicsInit( SOLID_VPHYSICS ) self:SetMoveType( MOVETYPE_VPHYSICS ) self:SetSolid( SOLID_VPHYSICS ) self:SetUseType( SIMPLE_USE ) self.Outputs = Wire_CreateOutputs(self, { "Out" }) self.Inputs = Wire_CreateInputs(self, { "Set" }) local anim = anims[self:GetModel()] if anim then self:SetSequence(anim[2]) end end function ENT:TriggerInput(iname, value) if iname == "Set" then if (self.toggle) then self:Switch(value ~= 0) self.PrevUser = nil self.podpress = nil end end end function ENT:Use(ply, caller) if (not ply:IsPlayer()) then return end if (self.PrevUser) and (self.PrevUser:IsValid()) then return end if self.OutputEntID then self.EntToOutput = ply end if (self:GetOn()) then if (self.toggle) then self:Switch(false) end return end if IsValid(caller) and caller:GetClass() == "gmod_wire_pod" then self.podpress = true end self:Switch(true) self.PrevUser = ply end function ENT:Think() BaseClass.Think(self) if ( self:GetOn() ) then if (not self.PrevUser) or (not self.PrevUser:IsValid()) or (not self.podpress and not self.PrevUser:KeyDown(IN_USE)) or (self.podpress and not self.PrevUser:KeyDown( IN_ATTACK )) then if (not self.toggle) then self:Switch(false) end self.PrevUser = nil self.podpress = nil end self:NextThink(CurTime()+0.05) return true end end function ENT:Setup(toggle, value_off, value_on, description, entityout) self.toggle = toggle self.value_off = value_off self.value_on = value_on self.entityout = entityout if entityout then WireLib.AdjustSpecialOutputs(self, { "Out", "EntID" , "Entity" }, { "NORMAL", "NORMAL" , "ENTITY" }) Wire_TriggerOutput(self, "EntID", 0) Wire_TriggerOutput(self, "Entity", nil) self.OutputEntID=true else Wire_AdjustOutputs(self, { "Out" }) self.OutputEntID=false end if toggle then Wire_AdjustInputs(self, { "Set" }) else Wire_AdjustInputs(self, {}) end self:Switch(self:GetOn()) end function ENT:Switch(on) if (not self:IsValid()) then return end self:SetOn( on ) if (on) then self:ShowOutput(self.value_on) self.Value = self.value_on local anim = anims[self:GetModel()] if anim then self:SetSequence(anim[1]) end else self:ShowOutput(self.value_off) self.Value = self.value_off local anim = anims[self:GetModel()] if anim then self:SetSequence(anim[2]) end if self.OutputEntID then self.EntToOutput = NULL end end Wire_TriggerOutput(self, "Out", self.Value) if self.OutputEntID then Wire_TriggerOutput(self, "EntID", self.EntToOutput:EntIndex()) Wire_TriggerOutput(self, "Entity", self.EntToOutput) end return true end function ENT:ShowOutput(value) self:SetOverlayText( "(" .. self.value_off .. " - " .. self.value_on .. ") = " .. value ) end duplicator.RegisterEntityClass("gmod_wire_button", WireLib.MakeWireEnt, "Data", "toggle", "value_off", "value_on", "description", "entityout" )
AddCSLuaFile() DEFINE_BASECLASS( "base_wire_entity" ) ENT.PrintName = "Wire Button" ENT.WireDebugName = "Button" function ENT:SetupDataTables() self:NetworkVar( "Bool", 0, "On" ) end if CLIENT then local halo_ent, halo_blur function ENT:Initialize() self.PosePosition = 0.0 end function ENT:Think() baseclass.Get("gmod_button").UpdateLever(self) end function ENT:Draw() self:DoNormalDraw(true,false) if LocalPlayer():GetEyeTrace().Entity == self and EyePos():DistToSqr( self:GetPos() ) < 512^2 and GetConVarNumber("wire_drawoutline")~=0 then if self:GetOn() then halo_ent = self halo_blur = 4 + math.sin(CurTime()*20)*2 else self:DrawEntityOutline() end end Wire_Render(self) end hook.Add("PreDrawHalos", "Wiremod_button_overlay_halos", function() if halo_ent then halo.Add({halo_ent}, Color(255,100,100), halo_blur, halo_blur, 1, true, true) halo_ent = nil end end) return -- No more client end ENT.OutputEntID = false ENT.EntToOutput = NULL local anims = { -- ["model"] = { on_anim, off_anim } ["models/props/switch001.mdl"] = { 2, 1 }, ["models/props_combine/combinebutton.mdl"] = { 3, 2 }, ["models/props_mining/control_lever01.mdl"] = { 1, 4 }, ["models/props_mining/freightelevatorbutton01.mdl"] = { 1, 2 }, ["models/props_mining/freightelevatorbutton02.mdl"] = { 1, 2 }, ["models/props_mining/switch01.mdl"] = { 1, 2 }, ["models/bull/buttons/rocker_switch.mdl"] = { 1, 2 }, ["models/bull/buttons/toggle_switch.mdl"] = { 1, 2 }, ["models/bull/buttons/key_switch.mdl"] = { 1, 2 }, ["models/props_mining/switch_updown01.mdl"] = { 2, 3 }, } function ENT:Initialize() self:PhysicsInit( SOLID_VPHYSICS ) self:SetMoveType( MOVETYPE_VPHYSICS ) self:SetSolid( SOLID_VPHYSICS ) self:SetUseType( SIMPLE_USE ) self.Outputs = Wire_CreateOutputs(self, { "Out" }) self.Inputs = Wire_CreateInputs(self, { "Set" }) local anim = anims[self:GetModel()] if anim then self:SetSequence(anim[2]) end end function ENT:TriggerInput(iname, value) if iname == "Set" then if (self.toggle) then self:Switch(value ~= 0) self.PrevUser = nil self.podpress = nil end end end function ENT:Use(ply, caller) if (not ply:IsPlayer()) then return end if (self.PrevUser) and (self.PrevUser:IsValid()) then return end if self.OutputEntID then self.EntToOutput = ply end if (self:GetOn()) then if (self.toggle) then self:Switch(false) end return end if IsValid(caller) and caller:GetClass() == "gmod_wire_pod" then self.podpress = true end self:Switch(true) self.PrevUser = ply end function ENT:Think() BaseClass.Think(self) if ( self:GetOn() ) then if (not self.PrevUser) or (not self.PrevUser:IsValid()) or (not self.podpress and not self.PrevUser:KeyDown(IN_USE)) or (self.podpress and not self.PrevUser:KeyDown( IN_ATTACK )) then if (not self.toggle) then self:Switch(false) end self.PrevUser = nil self.podpress = nil end self:NextThink(CurTime()+0.05) return true end end function ENT:Setup(toggle, value_off, value_on, description, entityout) self.toggle = toggle self.value_off = value_off self.value_on = value_on self.entityout = entityout if entityout then WireLib.AdjustSpecialOutputs(self, { "Out", "EntID" , "Entity" }, { "NORMAL", "NORMAL" , "ENTITY" }) Wire_TriggerOutput(self, "EntID", 0) Wire_TriggerOutput(self, "Entity", nil) self.OutputEntID=true else Wire_AdjustOutputs(self, { "Out" }) self.OutputEntID=false end if toggle then Wire_AdjustInputs(self, { "Set" }) else Wire_AdjustInputs(self, {}) end self:Switch(self:GetOn()) end function ENT:Switch(on) if (not self:IsValid()) then return end self:SetOn( on ) if (on) then self:ShowOutput(self.value_on) self.Value = self.value_on local anim = anims[self:GetModel()] if anim then self:SetSequence(anim[1]) end else self:ShowOutput(self.value_off) self.Value = self.value_off local anim = anims[self:GetModel()] if anim then self:SetSequence(anim[2]) end if self.OutputEntID then self.EntToOutput = NULL end end Wire_TriggerOutput(self, "Out", self.Value) if self.OutputEntID then Wire_TriggerOutput(self, "EntID", self.EntToOutput:EntIndex()) Wire_TriggerOutput(self, "Entity", self.EntToOutput) end return true end function ENT:ShowOutput(value) self:SetOverlayText( "(" .. self.value_off .. " - " .. self.value_on .. ") = " .. value ) end duplicator.RegisterEntityClass("gmod_wire_button", WireLib.MakeWireEnt, "Data", "toggle", "value_off", "value_on", "description", "entityout" )
Fix button halo drawing despite wire_drawoutline 0 (#2088)
Fix button halo drawing despite wire_drawoutline 0 (#2088)
Lua
apache-2.0
Grocel/wire,wiremod/wire,dvdvideo1234/wire
2118efbbbfce4ba2f817b8394781debf7d36a487
vrp/__resource.lua
vrp/__resource.lua
description "RP module/framework" dependency "vrp_mysql" ui_page "gui/index.html" -- server scripts server_scripts{ "lib/utils.lua", "base.lua", "modules/gui.lua", "modules/group.lua", "modules/admin.lua", "modules/survival.lua", "modules/player_state.lua", "modules/map.lua", "modules/money.lua", "modules/inventory.lua", "modules/identity.lua", "modules/business.lua", "modules/item_transformer.lua", "modules/emotes.lua", "modules/police.lua", "modules/home.lua", "modules/home_components.lua", "modules/mission.lua", "modules/aptitude.lua", -- basic implementations "modules/basic_phone.lua", "modules/basic_atm.lua", "modules/basic_market.lua", "modules/basic_gunshop.lua", "modules/basic_garage.lua", "modules/basic_items.lua", "modules/basic_skinshop.lua", "modules/cloakroom.lua" } -- client scripts client_scripts{ "lib/utils.lua", "client/Tunnel.lua", "client/Proxy.lua", "client/iplloader.lua", "client/base.lua", "client/gui.lua", "client/player_state.lua", "client/survival.lua", "client/map.lua", "client/identity.lua", "client/basic_garage.lua", "client/police.lua", "client/admin.lua" } -- client files files{ "gui/index.html", "gui/design.css", "gui/main.js", "gui/Menu.js", "gui/ProgressBar.js", "gui/WPrompt.js", "gui/RequestManager.js", "gui/AnnounceManager.js", "gui/Div.js" }
description "RP module/framework" dependency "vrp_mysql" ui_page "gui/index.html" -- server scripts server_scripts{ "lib/utils.lua", "base.lua", "modules/gui.lua", "modules/group.lua", "modules/admin.lua", "modules/survival.lua", "modules/player_state.lua", "modules/map.lua", "modules/money.lua", "modules/inventory.lua", "modules/identity.lua", "modules/business.lua", "modules/item_transformer.lua", "modules/emotes.lua", "modules/police.lua", "modules/home.lua", "modules/home_components.lua", "modules/mission.lua", "modules/aptitude.lua", -- basic implementations "modules/basic_phone.lua", "modules/basic_atm.lua", "modules/basic_market.lua", "modules/basic_gunshop.lua", "modules/basic_garage.lua", "modules/basic_items.lua", "modules/basic_skinshop.lua", "modules/cloakroom.lua" } -- client scripts client_scripts{ "lib/utils.lua", "client/Tunnel.lua", "client/Proxy.lua", "client/base.lua", "client/iplloader.lua", "client/gui.lua", "client/player_state.lua", "client/survival.lua", "client/map.lua", "client/identity.lua", "client/basic_garage.lua", "client/police.lua", "client/admin.lua" } -- client files files{ "cfg/client.lua", "gui/index.html", "gui/design.css", "gui/main.js", "gui/Menu.js", "gui/ProgressBar.js", "gui/WPrompt.js", "gui/RequestManager.js", "gui/AnnounceManager.js", "gui/Div.js" }
Fix some client config issues.
Fix some client config issues.
Lua
mit
ImagicTheCat/vRP,ImagicTheCat/vRP
dd8987c60acf795ad2eb043ff3fa785a4f441aea
core/sessionmanager.lua
core/sessionmanager.lua
local tonumber, tostring = tonumber, tostring; local ipairs, pairs, print, next= ipairs, pairs, print, next; local collectgarbage = collectgarbage; local m_random = import("math", "random"); local format = import("string", "format"); local hosts = hosts; local sessions = sessions; local modulemanager = require "core.modulemanager"; local log = require "util.logger".init("sessionmanager"); local error = error; local uuid_generate = require "util.uuid".generate; local rm_load_roster = require "core.rostermanager".load_roster; local newproxy = newproxy; local getmetatable = getmetatable; module "sessionmanager" local open_sessions = 0; function new_session(conn) local session = { conn = conn, priority = 0, type = "c2s_unauthed" }; if true then session.trace = newproxy(true); getmetatable(session.trace).__gc = function () open_sessions = open_sessions - 1; print("Session got collected, now "..open_sessions.." sessions are allocated") end; end open_sessions = open_sessions + 1; local w = conn.write; session.send = function (t) w(tostring(t)); end return session; end function destroy_session(session) (session.log or log)("info", "Destroying session"); -- Send unavailable presence if session.presence then local pres = st.presence{ type = "unavailable" }; if err == "closed" then err = "connection closed"; end pres:tag("status"):text("Disconnected: "..err); session.stanza_dispatch(pres); end -- Remove session/resource from user's session list if session.host and session.username then if session.resource then hosts[session.host].sessions[session.username].sessions[session.resource] = nil; end if hosts[session.host] and hosts[session.host].sessions[session.username] then if not next(hosts[session.host].sessions[session.username].sessions) then log("debug", "All resources of %s are now offline", session.username); hosts[session.host].sessions[session.username] = nil; end end end for k in pairs(session) do if k ~= "trace" then session[k] = nil; end end end function make_authenticated(session, username) session.username = username; if session.type == "c2s_unauthed" then session.type = "c2s"; end return true; end -- returns true, nil on success -- returns nil, err_type, err, err_message on failure function bind_resource(session, resource) if not session.username then return nil, "auth", "not-authorized", "Cannot bind resource before authentication"; end if session.resource then return nil, "cancel", "already-bound", "Cannot bind multiple resources on a single connection"; end -- We don't support binding multiple resources resource = resource or uuid_generate(); --FIXME: Randomly-generated resources must be unique per-user, and never conflict with existing if not hosts[session.host].sessions[session.username] then hosts[session.host].sessions[session.username] = { sessions = {} }; else if hosts[session.host].sessions[session.username].sessions[resource] then -- Resource conflict return nil, "cancel", "conflict", "Resource already exists"; -- TODO kick old resource end end session.resource = resource; session.full_jid = session.username .. '@' .. session.host .. '/' .. resource; hosts[session.host].sessions[session.username].sessions[resource] = session; session.roster = rm_load_roster(session.username, session.host); return true; end function streamopened(session, attr) local send = session.send; session.host = attr.to or error("Client failed to specify destination hostname"); session.version = tonumber(attr.version) or 0; session.streamid = m_random(1000000, 99999999); (session.log or session)("debug", "Client sent opening <stream:stream> to %s", session.host); send("<?xml version='1.0'?>"); send(format("<stream:stream xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' id='%s' from='%s' version='1.0'>", session.streamid, session.host)); if not hosts[session.host] then -- We don't serve this host... session:close{ condition = "host-unknown", text = "This server does not serve "..tostring(session.host)}; return; end local features = {}; modulemanager.fire_event("stream-features", session, features); -- FIXME: Need to send() this all at once send("<stream:features>"); for _, feature in ipairs(features) do send(tostring(feature)); end send("</stream:features>"); log("info", "Stream opened successfully"); session.notopen = nil; end function send_to_available_resources(user, host, stanza) local count = 0; local to = stanza.attr.to; stanza.attr.to = nil; local h = hosts[host]; if h and h.type == "local" then local u = h.sessions[user]; if u then for k, session in pairs(u.sessions) do if session.presence then session.send(stanza); count = count + 1; end end end end stanza.attr.to = to; return count; end return _M;
local tonumber, tostring = tonumber, tostring; local ipairs, pairs, print, next= ipairs, pairs, print, next; local collectgarbage = collectgarbage; local m_random = import("math", "random"); local format = import("string", "format"); local hosts = hosts; local sessions = sessions; local modulemanager = require "core.modulemanager"; local log = require "util.logger".init("sessionmanager"); local error = error; local uuid_generate = require "util.uuid".generate; local rm_load_roster = require "core.rostermanager".load_roster; local st = require "util.stanza"; local newproxy = newproxy; local getmetatable = getmetatable; module "sessionmanager" local open_sessions = 0; function new_session(conn) local session = { conn = conn, priority = 0, type = "c2s_unauthed" }; if true then session.trace = newproxy(true); getmetatable(session.trace).__gc = function () open_sessions = open_sessions - 1; print("Session got collected, now "..open_sessions.." sessions are allocated") end; end open_sessions = open_sessions + 1; local w = conn.write; session.send = function (t) w(tostring(t)); end return session; end function destroy_session(session, err) (session.log or log)("info", "Destroying session"); -- Send unavailable presence if session.presence then local pres = st.presence{ type = "unavailable" }; if (not err) or err == "closed" then err = "connection closed"; end pres:tag("status"):text("Disconnected: "..err); session.stanza_dispatch(pres); end -- Remove session/resource from user's session list if session.host and session.username then if session.resource then hosts[session.host].sessions[session.username].sessions[session.resource] = nil; end if hosts[session.host] and hosts[session.host].sessions[session.username] then if not next(hosts[session.host].sessions[session.username].sessions) then log("debug", "All resources of %s are now offline", session.username); hosts[session.host].sessions[session.username] = nil; end end end for k in pairs(session) do if k ~= "trace" then session[k] = nil; end end end function make_authenticated(session, username) session.username = username; if session.type == "c2s_unauthed" then session.type = "c2s"; end return true; end -- returns true, nil on success -- returns nil, err_type, err, err_message on failure function bind_resource(session, resource) if not session.username then return nil, "auth", "not-authorized", "Cannot bind resource before authentication"; end if session.resource then return nil, "cancel", "already-bound", "Cannot bind multiple resources on a single connection"; end -- We don't support binding multiple resources resource = resource or uuid_generate(); --FIXME: Randomly-generated resources must be unique per-user, and never conflict with existing if not hosts[session.host].sessions[session.username] then hosts[session.host].sessions[session.username] = { sessions = {} }; else if hosts[session.host].sessions[session.username].sessions[resource] then -- Resource conflict return nil, "cancel", "conflict", "Resource already exists"; -- TODO kick old resource end end session.resource = resource; session.full_jid = session.username .. '@' .. session.host .. '/' .. resource; hosts[session.host].sessions[session.username].sessions[resource] = session; session.roster = rm_load_roster(session.username, session.host); return true; end function streamopened(session, attr) local send = session.send; session.host = attr.to or error("Client failed to specify destination hostname"); session.version = tonumber(attr.version) or 0; session.streamid = m_random(1000000, 99999999); (session.log or session)("debug", "Client sent opening <stream:stream> to %s", session.host); send("<?xml version='1.0'?>"); send(format("<stream:stream xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' id='%s' from='%s' version='1.0'>", session.streamid, session.host)); if not hosts[session.host] then -- We don't serve this host... session:close{ condition = "host-unknown", text = "This server does not serve "..tostring(session.host)}; return; end local features = {}; modulemanager.fire_event("stream-features", session, features); -- FIXME: Need to send() this all at once send("<stream:features>"); for _, feature in ipairs(features) do send(tostring(feature)); end send("</stream:features>"); log("info", "Stream opened successfully"); session.notopen = nil; end function send_to_available_resources(user, host, stanza) local count = 0; local to = stanza.attr.to; stanza.attr.to = nil; local h = hosts[host]; if h and h.type == "local" then local u = h.sessions[user]; if u then for k, session in pairs(u.sessions) do if session.presence then session.send(stanza); count = count + 1; end end end end stanza.attr.to = to; return count; end return _M;
Fix sending of unavailable presence on disconnect
Fix sending of unavailable presence on disconnect
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
27994417f34618e05c3cd793f6d0c47596f5d185
tests/AceDB-3.0.lua
tests/AceDB-3.0.lua
dofile("wow_api.lua") dofile("LibStub.lua") dofile("../CallbackHandler-1.0/CallbackHandler-1.0.lua") dofile("../AceDB-3.0/AceDB-3.0.lua") dofile("serialize.lua") -- Test the defaults system do local defaults = { profile = { singleEntry = "singleEntry", tableEntry = { tableDefault = "tableDefault", }, starTest = { ["*"] = { starDefault = "starDefault", }, sibling = { siblingDefault = "siblingDefault", }, }, doubleStarTest = { ["**"] = { doubleStarDefault = "doubleStarDefault", }, sibling = { siblingDefault = "siblingDefault", }, }, }, } local db = LibStub("AceDB-3.0"):New("MyDB", defaults) assert(db.profile.singleEntry == "singleEntry") assert(db.profile.tableEntry.tableDefault == "tableDefault") assert(db.profile.starTest.randomkey.starDefault == "starDefault") assert(db.profile.starTest.sibling.siblingDefault == "siblingDefault") assert(db.profile.starTest.sibling.starDefault == nil) assert(db.profile.doubleStarTest.randomkey.doubleStarDefault == "doubleStarDefault") assert(db.profile.doubleStarTest.sibling.siblingDefault == "siblingDefault") assert(db.profile.doubleStarTest.sibling.doubleStarDefault == "doubleStarDefault") end -- Test the dynamic creation of sections do local defaults = { char = { alpha = "alpha",}, realm = { beta = "beta",}, class = { gamma = "gamma",}, race = { delta = "delta",}, faction = { epsilon = "epsilon",}, factionrealm = { zeta = "zeta",}, profile = { eta = "eta",}, global = { theta = "theta",}, } local db = LibStub("AceDB-3.0"):New({}, defaults) assert(rawget(db, "char") == nil) assert(rawget(db, "realm") == nil) assert(rawget(db, "class") == nil) assert(rawget(db, "race") == nil) assert(rawget(db, "faction") == nil) assert(rawget(db, "factionrealm") == nil) assert(rawget(db, "profile") == nil) assert(rawget(db, "global") == nil) assert(rawget(db, "profiles") == nil) -- Check dynamic default creation assert(db.char.alpha == "alpha") assert(db.realm.beta == "beta") assert(db.class.gamma == "gamma") assert(db.race.delta == "delta") assert(db.faction.epsilon == "epsilon") assert(db.factionrealm.zeta == "zeta") assert(db.profile.eta == "eta") assert(db.global.theta == "theta") end -- Test OnProfileChanged do local testdb = LibStub("AceDB-3.0"):New({}) local triggers = {} local function OnProfileChanged(message, db, ...) if message == "OnProfileChanged" and db == testdb then local profile = ... assert(profile == "Healers") triggers[message] = true end end testdb:RegisterCallback("OnProfileChanged", OnProfileChanged) testdb:SetProfile("Healers") assert(triggers.OnProfileChanged) end -- Test GetProfiles() fix for ACE-35 do local db = LibStub("AceDB-3.0"):New({}) local profiles = { "Healers", "Tanks", "Hunter", } for idx,profile in ipairs(profiles) do db:SetProfile(profile) end local profileList = db:GetProfiles() table.sort(profileList) assert(profileList[1] == "Healers") assert(profileList[2] == "Hunter") assert(profileList[3] == "Tanks") assert(profileList[4] == UnitName("player" .. " - " .. GetRealmName())) end -- Very simple default test do local defaults = { profile = { sub = { ["*"] = { sub2 = {}, sub3 = {}, }, }, }, } local db = LibStub("AceDB-3.0"):New({}, defaults) assert(type(db.profile.sub.monkey.sub2) == "table") assert(type(db.profile.sub.apple.sub3) == "table") db.profile.sub.random.sub2.alpha = "alpha" end -- Table insert kills us do local defaults = { profile = { ["*"] = {}, }, } local db = LibStub("AceDB-3.0"):New({}, defaults) table.insert(db.profile.monkey, "alpha") table.insert(db.profile.random, "beta") -- Here, the tables db.profile.monkey should be REAL, not cached assert(rawget(db.profile, "monkey")) end -- Test multi-level defaults for hyper do local defaults = { profile = { autoSendRules = { ['*'] = { include = { ['*'] = {}, }, exclude = { ['*'] = {}, }, }, }, } } local db = LibStub("AceDB-3.0"):New({}, defaults) assert(rawget(db.profile.autoSendRules.Cairthas.include, "ptSets") == nil) assert(rawget(db.profile.autoSendRules.Cairthas.include, "items") == nil) table.insert(db.profile.autoSendRules.Cairthas.include.ptSets, "TradeSkill.Mat.ByProfession.Leatherworking") table.insert(db.profile.autoSendRules.Cairthas.include.items, "Light Leather") db.profile.autoSendRules.Cairthas.include.ptSets.boo = true -- Tables should be real now, not cached. assert(rawget(db.profile.autoSendRules.Cairthas.include, "ptSets")) assert(rawget(db.profile.autoSendRules.Cairthas.include, "items")) end do local testdb = LibStub("AceDB-3.0"):New("testdbtable", {profile = { test = 2, test3 = { a=1}}}) assert(testdb.profile.test == 2) --true testdb.profile.test = 3 testdb.profile.test2 = 4 testdb.profile.test3.b = 2 assert(testdb.profile.test == 3) --true assert(testdb.profile.test2 == 4) --true local firstprofile = testdb:GetCurrentProfile() testdb:SetProfile("newprofile") assert(testdb.profile.test == 2) --true testdb:CopyProfile(firstprofile) assert(testdb.profile.test == 3) --false, the value is 2 assert(testdb.profile.test2 == 4) --true assert(testdb.profile.test3.a == 1) end
dofile("wow_api.lua") dofile("LibStub.lua") dofile("../CallbackHandler-1.0/CallbackHandler-1.0.lua") dofile("../AceDB-3.0/AceDB-3.0.lua") dofile("serialize.lua") -- Test the defaults system do local defaults = { profile = { singleEntry = "singleEntry", tableEntry = { tableDefault = "tableDefault", }, starTest = { ["*"] = { starDefault = "starDefault", }, sibling = { siblingDefault = "siblingDefault", }, }, doubleStarTest = { ["**"] = { doubleStarDefault = "doubleStarDefault", }, sibling = { siblingDefault = "siblingDefault", }, }, }, } local db = LibStub("AceDB-3.0"):New("MyDB", defaults) assert(db.profile.singleEntry == "singleEntry") assert(db.profile.tableEntry.tableDefault == "tableDefault") assert(db.profile.starTest.randomkey.starDefault == "starDefault") assert(db.profile.starTest.sibling.siblingDefault == "siblingDefault") assert(db.profile.starTest.sibling.starDefault == nil) assert(db.profile.doubleStarTest.randomkey.doubleStarDefault == "doubleStarDefault") assert(db.profile.doubleStarTest.sibling.siblingDefault == "siblingDefault") assert(db.profile.doubleStarTest.sibling.doubleStarDefault == "doubleStarDefault") end -- Test the dynamic creation of sections do local defaults = { char = { alpha = "alpha",}, realm = { beta = "beta",}, class = { gamma = "gamma",}, race = { delta = "delta",}, faction = { epsilon = "epsilon",}, factionrealm = { zeta = "zeta",}, profile = { eta = "eta",}, global = { theta = "theta",}, } local db = LibStub("AceDB-3.0"):New({}, defaults) assert(rawget(db, "char") == nil) assert(rawget(db, "realm") == nil) assert(rawget(db, "class") == nil) assert(rawget(db, "race") == nil) assert(rawget(db, "faction") == nil) assert(rawget(db, "factionrealm") == nil) assert(rawget(db, "profile") == nil) assert(rawget(db, "global") == nil) assert(rawget(db, "profiles") == nil) -- Check dynamic default creation assert(db.char.alpha == "alpha") assert(db.realm.beta == "beta") assert(db.class.gamma == "gamma") assert(db.race.delta == "delta") assert(db.faction.epsilon == "epsilon") assert(db.factionrealm.zeta == "zeta") assert(db.profile.eta == "eta") assert(db.global.theta == "theta") end -- Test OnProfileChanged do local testdb = LibStub("AceDB-3.0"):New({}) local triggers = {} local function OnProfileChanged(message, db, ...) if message == "OnProfileChanged" and db == testdb then local profile = ... assert(profile == "Healers") triggers[message] = true end end testdb:RegisterCallback("OnProfileChanged", OnProfileChanged) testdb:SetProfile("Healers") assert(triggers.OnProfileChanged) end -- Test GetProfiles() fix for ACE-35 do local db = LibStub("AceDB-3.0"):New({}) local profiles = { "Healers", "Tanks", "Hunter", } for idx,profile in ipairs(profiles) do db:SetProfile(profile) end local profileList = db:GetProfiles() table.sort(profileList) assert(profileList[2] == "Healers") assert(profileList[3] == "Hunter") assert(profileList[4] == "Tanks") assert(profileList[1] == "Default") end -- Very simple default test do local defaults = { profile = { sub = { ["*"] = { sub2 = {}, sub3 = {}, }, }, }, } local db = LibStub("AceDB-3.0"):New({}, defaults) assert(type(db.profile.sub.monkey.sub2) == "table") assert(type(db.profile.sub.apple.sub3) == "table") db.profile.sub.random.sub2.alpha = "alpha" end -- Table insert kills us do local defaults = { profile = { ["*"] = {}, }, } local db = LibStub("AceDB-3.0"):New({}, defaults) table.insert(db.profile.monkey, "alpha") table.insert(db.profile.random, "beta") -- Here, the tables db.profile.monkey should be REAL, not cached assert(rawget(db.profile, "monkey")) end -- Test multi-level defaults for hyper do local defaults = { profile = { autoSendRules = { ['*'] = { include = { ['*'] = {}, }, exclude = { ['*'] = {}, }, }, }, } } local db = LibStub("AceDB-3.0"):New({}, defaults) assert(rawget(db.profile.autoSendRules.Cairthas.include, "ptSets") == nil) assert(rawget(db.profile.autoSendRules.Cairthas.include, "items") == nil) table.insert(db.profile.autoSendRules.Cairthas.include.ptSets, "TradeSkill.Mat.ByProfession.Leatherworking") table.insert(db.profile.autoSendRules.Cairthas.include.items, "Light Leather") db.profile.autoSendRules.Cairthas.include.ptSets.boo = true -- Tables should be real now, not cached. assert(rawget(db.profile.autoSendRules.Cairthas.include, "ptSets")) assert(rawget(db.profile.autoSendRules.Cairthas.include, "items")) end do local testdb = LibStub("AceDB-3.0"):New("testdbtable", {profile = { test = 2, test3 = { a=1}}}) assert(testdb.profile.test == 2) --true testdb.profile.test = 3 testdb.profile.test2 = 4 testdb.profile.test3.b = 2 assert(testdb.profile.test == 3) --true assert(testdb.profile.test2 == 4) --true local firstprofile = testdb:GetCurrentProfile() testdb:SetProfile("newprofile") assert(testdb.profile.test == 2) --true testdb:CopyProfile(firstprofile) assert(testdb.profile.test == 3) --false, the value is 2 assert(testdb.profile.test2 == 4) --true assert(testdb.profile.test3.a == 1) end
Ace3 - tests: - fix AceDB test for new default profile
Ace3 - tests: - fix AceDB test for new default profile git-svn-id: d324031ee001e5fbb202928c503a4bc65708d41c@434 5debad98-a965-4143-8383-f471b3509dcf
Lua
bsd-3-clause
sarahgerweck/Ace3
c08fd59a29b67edaff3eb372783456f600c40ea1
reddit.lua
reddit.lua
dofile("urlcode.lua") dofile("table_show.lua") local url_count = 0 local tries = 0 local item_type = os.getenv('item_type') local item_value = os.getenv('item_value') local downloaded = {} local addedtolist = {} read_file = function(file) if file then local f = assert(io.open(file)) local data = f:read("*all") f:close() return data else return "" end end wget.callbacks.download_child_p = function(urlpos, parent, depth, start_url_parsed, iri, verdict, reason) local url = urlpos["url"]["url"] local html = urlpos["link_expect_html"] if downloaded[url] == true or addedtolist[url] == true then return false end if (downloaded[url] ~= true or addedtolist[url] ~= true) then if (string.match(url, "[^a-z0-9]"..item_value.."[0-9a-z]") and not string.match(url, "[^a-z0-9]"..item_value.."[0-9a-z][0-9a-z]")) or html == 0 then return true else return false end end end wget.callbacks.get_urls = function(file, url, is_css, iri) local urls = {} local html = nil if downloaded[url] ~= true then downloaded[url] = true end local function check(url) if (downloaded[url] ~= true and addedtolist[url] ~= true) and (string.match(url, "[^a-z0-9]"..item_value.."[0-9a-z]") or string.match(url, "redditmedia%.com")) and not string.match(url, "[^a-z0-9]"..item_value.."[0-9a-z][0-9a-z]") then if string.match(url, "&amp;") then table.insert(urls, { url=string.gsub(url, "&amp;", "&") }) addedtolist[url] = true addedtolist[string.gsub(url, "&amp;", "&")] = true elseif string.match(url, "#") then table.insert(urls, { url=string.match(url, "(https?:[^#]+)#") }) addedtolist[url] = true addedtolist[string.match(url, "(https?:[^#]+)#")] = true else table.insert(urls, { url=url }) addedtolist[url] = true end end end if string.match(url, "[^a-z0-9]"..item_value.."[0-9a-z]") and not string.match(url, "[^a-z0-9]"..item_value.."[0-9a-z][0-9a-z]") then html = read_file(file) for newurl in string.gmatch(html, '"(https?://[^"]+)"') do check(newurl) end for newurl in string.gmatch(html, "'(https?://[^']+)'") do check(newurl) end for newurl in string.gmatch(html, '("/[^"]+)"') do if string.match(newurl, '"//') then check(string.gsub(newurl, '"//', 'http://')) elseif not string.match(newurl, '"//') then check(string.match(url, "(https?://[^/]+)/")..string.match(newurl, '"(/.+)')) end end for newurl in string.gmatch(html, "('/[^']+)'") do if string.match(newurl, "'//") then check(string.gsub(newurl, "'//", "http://")) elseif not string.match(newurl, "'//") then check(string.match(url, '(https?://[^/]+)/')..string.match(newurl, "'(/.+)")) end end end return urls end wget.callbacks.httploop_result = function(url, err, http_stat) -- NEW for 2014: Slightly more verbose messages because people keep -- complaining that it's not moving or not working status_code = http_stat["statcode"] url_count = url_count + 1 io.stdout:write(url_count .. "=" .. status_code .. " " .. url["url"] .. ". \n") io.stdout:flush() if (status_code >= 200 and status_code <= 399) then if string.match(url.url, "https://") then local newurl = string.gsub(url.url, "https://", "http://") downloaded[newurl] = true else downloaded[url.url] = true end end if status_code >= 500 or (status_code >= 400 and status_code ~= 404 and status_code ~= 403) then io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n") io.stdout:flush() os.execute("sleep 10") tries = tries + 1 if tries >= 6 then io.stdout:write("\nI give up...\n") io.stdout:flush() tries = 0 return wget.actions.ABORT else return wget.actions.CONTINUE end elseif status_code == 0 then io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n") io.stdout:flush() os.execute("sleep 10") tries = tries + 1 if tries >= 6 then io.stdout:write("\nI give up...\n") io.stdout:flush() tries = 0 return wget.actions.ABORT else return wget.actions.CONTINUE end end tries = 0 local sleep_time = 0 if sleep_time > 0.001 then os.execute("sleep " .. sleep_time) end return wget.actions.NOTHING end
dofile("urlcode.lua") dofile("table_show.lua") local url_count = 0 local tries = 0 local item_type = os.getenv('item_type') local item_value = os.getenv('item_value') local downloaded = {} local addedtolist = {} -- Do not download these urls: downloaded["http://pixel.redditmedia.com/pixel/of_destiny.png?v=q1Ga4BM4n71zceWwjRg4266wx1BqgGjx8isnnrLeBUv%2FXq%2Bk60QeBpQruPDKFQFv%2FDWVNxp63YPBIKv8pMk%2BhrkV3HA5b7GO"] = true downloaded["http://pixel.redditmedia.com/pixel/of_doom.png"] = true downloaded["http://pixel.redditmedia.com/pixel/of_delight.png"] = true downloaded["http://pixel.redditmedia.com/pixel/of_discovery.png"] = true downloaded["http://pixel.redditmedia.com/pixel/of_diversity.png"] = true downloaded["http://pixel.redditmedia.com/click"] = true downloaded["https://stats.redditmedia.com/"] = true read_file = function(file) if file then local f = assert(io.open(file)) local data = f:read("*all") f:close() return data else return "" end end wget.callbacks.download_child_p = function(urlpos, parent, depth, start_url_parsed, iri, verdict, reason) local url = urlpos["url"]["url"] local html = urlpos["link_expect_html"] if downloaded[url] == true or addedtolist[url] == true then return false end if (downloaded[url] ~= true or addedtolist[url] ~= true) then if string.match(url, "[^a-z0-9]"..item_value.."[0-9a-z]") and not (string.match(url, "[^a-z0-9]"..item_value.."[0-9a-z][0-9a-z]") or string.match(url, "%?sort=") or string.match(url, "%?ref=") or string.match(url, "%?count=") or string.match(url, "%.rss") or string.match(url, "%?originalUrl=") or string.match(url, "m%.reddit%.com") or string.match(url, "thumbs%.redditmedia%.com")) then addedtolist[url] = true return true else return false end else return false end end wget.callbacks.get_urls = function(file, url, is_css, iri) local urls = {} local html = nil if downloaded[url] ~= true then downloaded[url] = true end local function check(url) if (downloaded[url] ~= true and addedtolist[url] ~= true) and (string.match(url, "[^a-z0-9]"..item_value.."[0-9a-z]") or (string.match(url, "redditmedia%.com")) and not (string.match(url, "[^a-z0-9]"..item_value.."[0-9a-z][0-9a-z]") or string.match(url, "thumbs%.redditmedia%.com") or string.match(url, "%?sort=") or string.match(url, "%?ref=") or string.match(url, "%?count=") or string.match(url, "%.rss") or string.match(url, "%?originalUrl=") or string.match(url, "m%.reddit%.com")) then if string.match(url, "&amp;") then table.insert(urls, { url=string.gsub(url, "&amp;", "&") }) addedtolist[url] = true addedtolist[string.gsub(url, "&amp;", "&")] = true elseif string.match(url, "#") then table.insert(urls, { url=string.match(url, "(https?//:[^#]+)#") }) addedtolist[url] = true addedtolist[string.match(url, "(https?//:[^#]+)#")] = true else table.insert(urls, { url=url }) addedtolist[url] = true end end end if string.match(url, "[^a-z0-9]"..item_value.."[0-9a-z]") and not (string.match(url, "[^a-z0-9]"..item_value.."[0-9a-z][0-9a-z]") or string.match(url, "/related/"..item_value)) then html = read_file(file) for newurl in string.gmatch(html, '"thumbnail[^"]+"[^"]+"[^"]+"[^"]+"(//[^"]+)"') do if downloaded[string.gsub(newurl, "//", "http://")] ~= true and addedtolist[string.gsub(newurl, "//", "http://")] ~= true then table.insert(urls, { url=string.gsub(newurl, "//", "http://") }) addedtolist[string.gsub(newurl, "//", "http://")] = true end end for newurl in string.gmatch(html, '"(https?://[^"]+)"') do check(newurl) end for newurl in string.gmatch(html, "'(https?://[^']+)'") do check(newurl) end for newurl in string.gmatch(html, '("/[^"]+)"') do if string.match(newurl, '"//') then check(string.gsub(newurl, '"//', 'http://')) elseif not string.match(newurl, '"//') then check(string.match(url, "(https?://[^/]+)/")..string.match(newurl, '"(/.+)')) end end for newurl in string.gmatch(html, "('/[^']+)'") do if string.match(newurl, "'//") then check(string.gsub(newurl, "'//", "http://")) elseif not string.match(newurl, "'//") then check(string.match(url, '(https?://[^/]+)/')..string.match(newurl, "'(/.+)")) end end end return urls end wget.callbacks.httploop_result = function(url, err, http_stat) -- NEW for 2014: Slightly more verbose messages because people keep -- complaining that it's not moving or not working status_code = http_stat["statcode"] url_count = url_count + 1 io.stdout:write(url_count .. "=" .. status_code .. " " .. url["url"] .. ". \n") io.stdout:flush() if (status_code >= 200 and status_code <= 399) then if string.match(url.url, "https://") then local newurl = string.gsub(url.url, "https://", "http://") downloaded[newurl] = true else downloaded[url.url] = true end end if status_code >= 500 or (status_code >= 400 and status_code ~= 404 and status_code ~= 403) then io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n") io.stdout:flush() os.execute("sleep 10") tries = tries + 1 if tries >= 6 then io.stdout:write("\nI give up...\n") io.stdout:flush() tries = 0 if string.match(url["url"], "[^a-z0-9]"..item_value.."[0-9a-z]") and not string.match(url["url"], "[^a-z0-9]"..item_value.."[0-9a-z][0-9a-z]") then return wget.actions.ABORT else return wget.actions.EXIT end else return wget.actions.CONTINUE end elseif status_code == 0 then io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n") io.stdout:flush() os.execute("sleep 10") tries = tries + 1 if tries >= 6 then io.stdout:write("\nI give up...\n") io.stdout:flush() tries = 0 return wget.actions.ABORT else return wget.actions.CONTINUE end end tries = 0 local sleep_time = 0 if sleep_time > 0.001 then os.execute("sleep " .. sleep_time) end return wget.actions.NOTHING end
reddit.lua: ignore urls, fixes
reddit.lua: ignore urls, fixes
Lua
unlicense
ArchiveTeam/reddit-grab,ArchiveTeam/reddit-grab
c807bdd49576691d593a78bf948829e29e9a8ef6
src/viewport/src/Client/Viewport.lua
src/viewport/src/Client/Viewport.lua
--[=[ @class Viewport ]=] local require = require(script.Parent.loader).load(script) local BasicPane = require("BasicPane") local Blend = require("Blend") local ValueObject = require("ValueObject") local CameraUtils = require("CameraUtils") local AdorneeUtils = require("AdorneeUtils") local Maid = require("Maid") local Observable = require("Observable") local ViewportControls = require("ViewportControls") local SpringObject = require("SpringObject") local CircleUtils = require("CircleUtils") local Math = require("Math") local MAX_PITCH = math.pi/3 local MIN_PITCH = -math.pi/3 local TAU = math.pi*2 local Viewport = setmetatable({}, BasicPane) Viewport.ClassName = "Viewport" Viewport.__index = Viewport function Viewport.new() local self = setmetatable(BasicPane.new(), Viewport) self._current = ValueObject.new(nil) self._maid:GiveTask(self._current) self._transparency = ValueObject.new(0) self._maid:GiveTask(self._transparency) self._absoluteSize = ValueObject.new(Vector2.new()) self._maid:GiveTask(self._absoluteSize) self._fieldOfView = ValueObject.new(20) self._maid:GiveTask(self._fieldOfView) self._rotationYawSpring = SpringObject.new(math.pi/4) self._rotationYawSpring.Speed = 30 self._maid:GiveTask(self._rotationYawSpring) self._rotationPitchSpring = SpringObject.new(-math.pi/6) self._rotationPitchSpring.Speed = 30 self._maid:GiveTask(self._rotationPitchSpring) return self end function Viewport.blend(props) assert(type(props) == "table", "Bad props") return Observable.new(function(sub) local maid = Maid.new() local viewport = Viewport.new() local function bindObservable(propName, callback) if props[propName] then local observe = Blend.toPropertyObservable(props[propName]) if observe then maid:GiveTask(observe:Subscribe(function(value) callback(value) end)) else callback(props[propName]) end end end bindObservable("FieldOfView", function(value) viewport:SetFieldOfView(value) end) bindObservable("Instance", function(value) viewport:SetInstance(value) end) bindObservable("Transparency", function(value) viewport:SetTransparency(value) end) maid:GiveTask(viewport:Render(props):Subscribe(function(result) sub:Fire(result) end)) return maid end) end function Viewport:SetTransparency(transparency) assert(type(transparency) == "number", "Bad transparency") self._transparency.Value = transparency end function Viewport:SetFieldOfView(fieldOfView) assert(type(fieldOfView) == "number", "Bad fieldOfView") self._fieldOfView.Value = fieldOfView end function Viewport:SetInstance(instance) assert(typeof(instance) == "Instance" or instance == nil, "Bad instance") self._current.Value = instance end function Viewport:RotateBy(deltaV2, doNotAnimate) local target = (self._rotationYawSpring.Value + deltaV2.x) % TAU self._rotationYawSpring.Position = CircleUtils.updatePositionToSmallestDistOnCircle(self._rotationYawSpring.Position, target, TAU) self._rotationYawSpring.Target = target if doNotAnimate then self._rotationYawSpring.Position = self._rotationYawSpring.Target end self._rotationPitchSpring.Target = math.clamp(self._rotationPitchSpring.Value + deltaV2.y, MIN_PITCH, MAX_PITCH) if doNotAnimate then self._rotationPitchSpring.Position = self._rotationPitchSpring.Target end end function Viewport:Render(props) local currentCamera = ValueObject.new() return Blend.New "ViewportFrame" { Parent = props.Parent; Size = props.Size or UDim2.new(1, 0, 1, 0); AnchorPoint = props.AnchorPoint; Position = props.Position; LayoutOrder = props.LayoutOrder; BackgroundTransparency = 1; CurrentCamera = currentCamera; LightColor = props.LightColor or Color3.new(1, 1, 1); Ambient = props.Ambient or Color3.new(1, 1, 1); ImageTransparency = Blend.Computed(props.Transparency or 0, self._transparency, function(propTransparency, selfTransparency) return Math.map(propTransparency, 0, 1, selfTransparency, 1) end); [Blend.OnChange "AbsoluteSize"] = self._absoluteSize; [Blend.Attached(function(viewport) return ViewportControls.new(viewport, self) end)] = true; [Blend.Attached(function(viewport) -- custom parenting scheme to ensure we don't call destroy on children local maid = Maid.new() local function update() local value = self._current.Value if value then value.Parent = viewport end end maid:GiveTask(self._current.Changed:Connect(update)) update() maid:GiveTask(function() local value = self._current.Value -- Ensure we don't call :Destroy() on our preview instance. if value then value.Parent = nil end end) return maid end)] = true; [Blend.Children] = { self._current; Blend.New "Camera" { [Blend.Instance] = currentCamera; Name = "CurrentCamera"; FieldOfView = self._fieldOfView; CFrame = Blend.Computed(self._current, self._absoluteSize, self._fieldOfView, self._rotationYawSpring:ObserveRenderStepped(), self._rotationPitchSpring:ObserveRenderStepped(), function(inst, absSize, fov, rotationYaw, rotationPitch) if typeof(inst) ~= "Instance" then return CFrame.new() end local aspectRatio = absSize.x/absSize.y local bbCFrame, bbSize = AdorneeUtils.getBoundingBox(inst) if not bbCFrame then return CFrame.new() end local fit = CameraUtils.fitBoundingBoxToCamera(bbSize, fov, aspectRatio) return CFrame.new(bbCFrame.Position) * CFrame.Angles(0, rotationYaw, 0) * CFrame.Angles(rotationPitch, 0, 0) * CFrame.new(0, 0, fit) end); } } }; end return Viewport
--[=[ @class Viewport ]=] local require = require(script.Parent.loader).load(script) local BasicPane = require("BasicPane") local Blend = require("Blend") local ValueObject = require("ValueObject") local CameraUtils = require("CameraUtils") local AdorneeUtils = require("AdorneeUtils") local Maid = require("Maid") local Observable = require("Observable") local ViewportControls = require("ViewportControls") local SpringObject = require("SpringObject") local CircleUtils = require("CircleUtils") local Math = require("Math") local MAX_PITCH = math.pi/3 local MIN_PITCH = -math.pi/3 local TAU = math.pi*2 local Viewport = setmetatable({}, BasicPane) Viewport.ClassName = "Viewport" Viewport.__index = Viewport function Viewport.new() local self = setmetatable(BasicPane.new(), Viewport) self._current = ValueObject.new(nil) self._maid:GiveTask(self._current) self._transparency = ValueObject.new(0) self._maid:GiveTask(self._transparency) self._absoluteSize = ValueObject.new(Vector2.new()) self._maid:GiveTask(self._absoluteSize) self._fieldOfView = ValueObject.new(20) self._maid:GiveTask(self._fieldOfView) self._rotationYawSpring = SpringObject.new(math.pi/4) self._rotationYawSpring.Speed = 30 self._maid:GiveTask(self._rotationYawSpring) self._rotationPitchSpring = SpringObject.new(-math.pi/6) self._rotationPitchSpring.Speed = 30 self._maid:GiveTask(self._rotationPitchSpring) return self end function Viewport.blend(props) assert(type(props) == "table", "Bad props") return Observable.new(function(sub) local maid = Maid.new() local viewport = Viewport.new() local function bindObservable(propName, callback) if props[propName] then local observe = Blend.toPropertyObservable(props[propName]) if observe then maid:GiveTask(observe:Subscribe(function(value) callback(value) end)) else callback(props[propName]) end end end bindObservable("FieldOfView", function(value) viewport:SetFieldOfView(value) end) bindObservable("Instance", function(value) viewport:SetInstance(value) end) bindObservable("Transparency", function(value) viewport:SetTransparency(value) end) maid:GiveTask(viewport:Render(props):Subscribe(function(result) sub:Fire(result) end)) return maid end) end function Viewport:SetTransparency(transparency) assert(type(transparency) == "number", "Bad transparency") self._transparency.Value = transparency end function Viewport:SetFieldOfView(fieldOfView) assert(type(fieldOfView) == "number", "Bad fieldOfView") self._fieldOfView.Value = fieldOfView end function Viewport:SetInstance(instance) assert(typeof(instance) == "Instance" or instance == nil, "Bad instance") self._current.Value = instance end function Viewport:RotateBy(deltaV2, doNotAnimate) local target = (self._rotationYawSpring.Value + deltaV2.x) % TAU self._rotationYawSpring.Position = CircleUtils.updatePositionToSmallestDistOnCircle(self._rotationYawSpring.Position, target, TAU) self._rotationYawSpring.Target = target if doNotAnimate then self._rotationYawSpring.Position = self._rotationYawSpring.Target end self._rotationPitchSpring.Target = math.clamp(self._rotationPitchSpring.Value + deltaV2.y, MIN_PITCH, MAX_PITCH) if doNotAnimate then self._rotationPitchSpring.Position = self._rotationPitchSpring.Target end end function Viewport:Render(props) local currentCamera = ValueObject.new() self._maid:GiveTask(currentCamera) return Blend.New "ViewportFrame" { Parent = props.Parent; Size = props.Size or UDim2.new(1, 0, 1, 0); AnchorPoint = props.AnchorPoint; Position = props.Position; LayoutOrder = props.LayoutOrder; BackgroundTransparency = 1; CurrentCamera = currentCamera; LightColor = props.LightColor or Color3.new(1, 1, 1); Ambient = props.Ambient or Color3.new(1, 1, 1); ImageTransparency = Blend.Computed(props.Transparency or 0, self._transparency, function(propTransparency, selfTransparency) return Math.map(propTransparency, 0, 1, selfTransparency, 1) end); [Blend.OnChange "AbsoluteSize"] = self._absoluteSize; [Blend.Attached(function(viewport) return ViewportControls.new(viewport, self) end)] = true; [Blend.Attached(function(viewport) -- custom parenting scheme to ensure we don't call destroy on children local maid = Maid.new() local function update() local value = self._current.Value if value then value.Parent = viewport end end maid:GiveTask(self._current.Changed:Connect(update)) update() maid:GiveTask(function() local value = self._current.Value -- Ensure we don't call :Destroy() on our preview instance. if value then value.Parent = nil end end) return maid end)] = true; [Blend.Children] = { self._current; Blend.New "Camera" { [Blend.Instance] = currentCamera; Name = "CurrentCamera"; FieldOfView = self._fieldOfView; CFrame = Blend.Computed(self._current, self._absoluteSize, self._fieldOfView, self._rotationYawSpring:ObserveRenderStepped(), self._rotationPitchSpring:ObserveRenderStepped(), function(inst, absSize, fov, rotationYaw, rotationPitch) if typeof(inst) ~= "Instance" then return CFrame.new() end local aspectRatio = absSize.x/absSize.y local bbCFrame, bbSize = AdorneeUtils.getBoundingBox(inst) if not bbCFrame then return CFrame.new() end local fit = CameraUtils.fitBoundingBoxToCamera(bbSize, fov, aspectRatio) return CFrame.new(bbCFrame.Position) * CFrame.Angles(0, rotationYaw, 0) * CFrame.Angles(rotationPitch, 0, 0) * CFrame.new(0, 0, fit) end); } } }; end return Viewport
fix: Ensure currentCamera object GCs
fix: Ensure currentCamera object GCs
Lua
mit
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
dc9394f94d29f88e956403c105ee2c27da3ae137
applications/luci-wol/luasrc/model/cbi/wol.lua
applications/luci-wol/luasrc/model/cbi/wol.lua
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id: olsrd.lua 5560 2009-11-21 00:22:35Z jow $ ]]-- local sys = require "luci.sys" local fs = require "nixio.fs" m = SimpleForm("wol", translate("Wake on LAN"), translate("Wake on LAN is a mechanism to remotely boot computers in the local network.")) m.submit = translate("Wake up host") m.reset = false local has_ewk = fs.access("/usr/bin/etherwake") local has_wol = fs.access("/usr/bin/wol") if luci.http.formvalue("cbi.submit") then local host = luci.http.formvalue("cbid.wol.1.mac") if host and #host > 0 then local cmd local util = luci.http.formvalue("cbid.wol.1.binary") or ( has_ewk and "/usr/bin/etherwake" or "/usr/bin/wol" ) if util == "/usr/bin/etherwake" then local iface = luci.http.formvalue("cbid.wol.1.iface") cmd = "%s -D%s %q" %{ util, (iface ~= "" and " -i %q" % iface or ""), host } else cmd = "%s -v %q" %{ util, host } end is = m:section(SimpleSection) function is.render() luci.http.write( "<p><br /><strong>%s</strong><br /><br /><code>%s<br /><br />" %{ translate("Starting WoL utility:"), cmd } ) local p = io.popen(cmd .. " 2>&1") if p then while true do local l = p:read("*l") if l then if #l > 100 then l = l:sub(1, 100) .. "..." end luci.http.write(l .. "<br />") else break end end p:close() end luci.http.write("</code><br /></p>") end end end s = m:section(SimpleSection) local arp = { } local e, ip, mac, name if has_ewk and has_wol then bin = s:option(ListValue, "binary", translate("WoL program"), translate("Sometimes only one of both tools work. If one of fails, try the other one")) bin:value("/usr/bin/etherwake", "Etherwake") bin:value("/usr/bin/wol", "WoL") end if has_ewk then iface = s:option(ListValue, "iface", translate("Network interface to use"), translate("Specifies the interface the WoL packet is sent on")) if has_wol then iface:depends("binary", "/usr/bin/etherwake") end iface:value("", translate("Broadcast on all interfaces")) for _, e in ipairs(sys.net.devices()) do if e ~= "lo" then iface:value(e) end end end for _, e in ipairs(sys.net.arptable()) do arp[e["HW address"]] = { e["IP address"] } end for e in io.lines("/etc/ethers") do mac, ip = e:match("^([a-f0-9]%S+) (%S+)") if mac and ip then arp[mac] = { ip } end end for e in io.lines("/var/dhcp.leases") do mac, ip, name = e:match("^%d+ (%S+) (%S+) (%S+)") if mac and ip then arp[mac] = { ip, name ~= "*" and name } end end host = s:option(Value, "mac", translate("Host to wake up"), translate("Choose the host to wake up or enter a custom MAC address to use")) for mac, ip in pairs(arp) do host:value(mac, "%s (%s)" %{ mac, ip[2] or ip[1] }) end return m
--[[ LuCI - Lua Configuration Interface Copyright 2010 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 ]]-- local sys = require "luci.sys" local fs = require "nixio.fs" m = SimpleForm("wol", translate("Wake on LAN"), translate("Wake on LAN is a mechanism to remotely boot computers in the local network.")) m.submit = translate("Wake up host") m.reset = false local has_ewk = fs.access("/usr/bin/etherwake") local has_wol = fs.access("/usr/bin/wol") if luci.http.formvalue("cbi.submit") then local host = luci.http.formvalue("cbid.wol.1.mac") if host and #host > 0 then local cmd local util = luci.http.formvalue("cbid.wol.1.binary") or ( has_ewk and "/usr/bin/etherwake" or "/usr/bin/wol" ) if util == "/usr/bin/etherwake" then local iface = luci.http.formvalue("cbid.wol.1.iface") cmd = "%s -D%s %q" %{ util, (iface ~= "" and " -i %q" % iface or ""), host } else cmd = "%s -v %q" %{ util, host } end is = m:section(SimpleSection) function is.render() luci.http.write( "<p><br /><strong>%s</strong><br /><br /><code>%s<br /><br />" %{ translate("Starting WoL utility:"), cmd } ) local p = io.popen(cmd .. " 2>&1") if p then while true do local l = p:read("*l") if l then if #l > 100 then l = l:sub(1, 100) .. "..." end luci.http.write(l .. "<br />") else break end end p:close() end luci.http.write("</code><br /></p>") end end end s = m:section(SimpleSection) local arp = { } local e, ip, mac, name if has_ewk and has_wol then bin = s:option(ListValue, "binary", translate("WoL program"), translate("Sometimes only one of both tools work. If one of fails, try the other one")) bin:value("/usr/bin/etherwake", "Etherwake") bin:value("/usr/bin/wol", "WoL") end if has_ewk then iface = s:option(ListValue, "iface", translate("Network interface to use"), translate("Specifies the interface the WoL packet is sent on")) if has_wol then iface:depends("binary", "/usr/bin/etherwake") end iface:value("", translate("Broadcast on all interfaces")) for _, e in ipairs(sys.net.devices()) do if e ~= "lo" then iface:value(e) end end end for _, e in ipairs(sys.net.arptable()) do arp[e["HW address"]] = { e["IP address"] } end for e in io.lines("/etc/ethers") do mac, ip = e:match("^([a-f0-9]%S+) (%S+)") if mac and ip then arp[mac] = { ip } end end for e in io.lines("/var/dhcp.leases") do mac, ip, name = e:match("^%d+ (%S+) (%S+) (%S+)") if mac and ip then arp[mac] = { ip, name ~= "*" and name } end end host = s:option(Value, "mac", translate("Host to wake up"), translate("Choose the host to wake up or enter a custom MAC address to use")) for mac, ip in pairs(arp) do host:value(mac, "%s (%s)" %{ mac, ip[2] or ip[1] }) end return m
applications/luci-wol: fix copyright
applications/luci-wol: fix copyright
Lua
apache-2.0
openwrt/luci,ReclaimYourPrivacy/cloak-luci,openwrt-es/openwrt-luci,tcatm/luci,lcf258/openwrtcn,db260179/openwrt-bpi-r1-luci,slayerrensky/luci,dwmw2/luci,RuiChen1113/luci,david-xiao/luci,hnyman/luci,forward619/luci,tobiaswaldvogel/luci,cshore-firmware/openwrt-luci,oyido/luci,lbthomsen/openwrt-luci,zhaoxx063/luci,aa65535/luci,LuttyYang/luci,palmettos/cnLuCI,Sakura-Winkey/LuCI,marcel-sch/luci,RuiChen1113/luci,ReclaimYourPrivacy/cloak-luci,lbthomsen/openwrt-luci,MinFu/luci,joaofvieira/luci,male-puppies/luci,db260179/openwrt-bpi-r1-luci,sujeet14108/luci,tobiaswaldvogel/luci,kuoruan/lede-luci,maxrio/luci981213,LazyZhu/openwrt-luci-trunk-mod,jchuang1977/luci-1,forward619/luci,daofeng2015/luci,openwrt-es/openwrt-luci,wongsyrone/luci-1,nmav/luci,MinFu/luci,maxrio/luci981213,david-xiao/luci,ff94315/luci-1,harveyhu2012/luci,keyidadi/luci,aa65535/luci,lbthomsen/openwrt-luci,dwmw2/luci,obsy/luci,RedSnake64/openwrt-luci-packages,mumuqz/luci,openwrt/luci,teslamint/luci,bright-things/ionic-luci,bittorf/luci,thesabbir/luci,palmettos/cnLuCI,keyidadi/luci,thesabbir/luci,chris5560/openwrt-luci,joaofvieira/luci,981213/luci-1,artynet/luci,thesabbir/luci,aircross/OpenWrt-Firefly-LuCI,dwmw2/luci,nmav/luci,taiha/luci,Noltari/luci,palmettos/test,cshore-firmware/openwrt-luci,teslamint/luci,artynet/luci,harveyhu2012/luci,remakeelectric/luci,david-xiao/luci,Kyklas/luci-proto-hso,palmettos/cnLuCI,david-xiao/luci,RuiChen1113/luci,nmav/luci,schidler/ionic-luci,palmettos/cnLuCI,wongsyrone/luci-1,jlopenwrtluci/luci,jlopenwrtluci/luci,Kyklas/luci-proto-hso,fkooman/luci,lcf258/openwrtcn,cshore/luci,daofeng2015/luci,bittorf/luci,zhaoxx063/luci,RedSnake64/openwrt-luci-packages,cappiewu/luci,wongsyrone/luci-1,openwrt-es/openwrt-luci,remakeelectric/luci,urueedi/luci,fkooman/luci,schidler/ionic-luci,shangjiyu/luci-with-extra,kuoruan/luci,tcatm/luci,aa65535/luci,Noltari/luci,openwrt-es/openwrt-luci,bright-things/ionic-luci,cappiewu/luci,nwf/openwrt-luci,palmettos/test,Noltari/luci,oneru/luci,thess/OpenWrt-luci,cshore/luci,florian-shellfire/luci,mumuqz/luci,dwmw2/luci,florian-shellfire/luci,Kyklas/luci-proto-hso,oyido/luci,tobiaswaldvogel/luci,cshore-firmware/openwrt-luci,florian-shellfire/luci,ReclaimYourPrivacy/cloak-luci,oyido/luci,MinFu/luci,lcf258/openwrtcn,artynet/luci,Hostle/luci,bright-things/ionic-luci,fkooman/luci,zhaoxx063/luci,Wedmer/luci,marcel-sch/luci,bright-things/ionic-luci,slayerrensky/luci,opentechinstitute/luci,artynet/luci,opentechinstitute/luci,Hostle/luci,kuoruan/luci,jlopenwrtluci/luci,nmav/luci,sujeet14108/luci,cappiewu/luci,cshore/luci,kuoruan/lede-luci,oyido/luci,Hostle/openwrt-luci-multi-user,NeoRaider/luci,kuoruan/luci,tcatm/luci,nwf/openwrt-luci,bittorf/luci,NeoRaider/luci,jorgifumi/luci,nwf/openwrt-luci,shangjiyu/luci-with-extra,ollie27/openwrt_luci,obsy/luci,Hostle/luci,ollie27/openwrt_luci,MinFu/luci,openwrt/luci,taiha/luci,ff94315/luci-1,marcel-sch/luci,openwrt-es/openwrt-luci,marcel-sch/luci,nmav/luci,rogerpueyo/luci,LazyZhu/openwrt-luci-trunk-mod,shangjiyu/luci-with-extra,forward619/luci,lcf258/openwrtcn,kuoruan/lede-luci,marcel-sch/luci,db260179/openwrt-bpi-r1-luci,lcf258/openwrtcn,LuttyYang/luci,dwmw2/luci,fkooman/luci,urueedi/luci,Kyklas/luci-proto-hso,MinFu/luci,mumuqz/luci,thess/OpenWrt-luci,LazyZhu/openwrt-luci-trunk-mod,chris5560/openwrt-luci,cshore/luci,aircross/OpenWrt-Firefly-LuCI,Noltari/luci,opentechinstitute/luci,kuoruan/lede-luci,taiha/luci,tobiaswaldvogel/luci,keyidadi/luci,tcatm/luci,chris5560/openwrt-luci,florian-shellfire/luci,joaofvieira/luci,taiha/luci,jorgifumi/luci,bright-things/ionic-luci,RedSnake64/openwrt-luci-packages,palmettos/cnLuCI,obsy/luci,rogerpueyo/luci,tcatm/luci,LazyZhu/openwrt-luci-trunk-mod,RuiChen1113/luci,nwf/openwrt-luci,slayerrensky/luci,zhaoxx063/luci,daofeng2015/luci,artynet/luci,teslamint/luci,urueedi/luci,openwrt-es/openwrt-luci,oneru/luci,david-xiao/luci,bright-things/ionic-luci,981213/luci-1,mumuqz/luci,lbthomsen/openwrt-luci,cshore/luci,openwrt/luci,MinFu/luci,oneru/luci,ReclaimYourPrivacy/cloak-luci,daofeng2015/luci,chris5560/openwrt-luci,rogerpueyo/luci,Wedmer/luci,harveyhu2012/luci,Noltari/luci,cappiewu/luci,Wedmer/luci,maxrio/luci981213,Wedmer/luci,Hostle/openwrt-luci-multi-user,Wedmer/luci,obsy/luci,remakeelectric/luci,marcel-sch/luci,taiha/luci,schidler/ionic-luci,aircross/OpenWrt-Firefly-LuCI,kuoruan/lede-luci,aircross/OpenWrt-Firefly-LuCI,thesabbir/luci,ollie27/openwrt_luci,oyido/luci,maxrio/luci981213,nwf/openwrt-luci,bittorf/luci,jchuang1977/luci-1,male-puppies/luci,thess/OpenWrt-luci,teslamint/luci,dismantl/luci-0.12,teslamint/luci,cshore-firmware/openwrt-luci,lcf258/openwrtcn,Noltari/luci,RedSnake64/openwrt-luci-packages,oneru/luci,jchuang1977/luci-1,kuoruan/luci,remakeelectric/luci,deepak78/new-luci,RuiChen1113/luci,schidler/ionic-luci,palmettos/cnLuCI,db260179/openwrt-bpi-r1-luci,obsy/luci,jorgifumi/luci,jorgifumi/luci,Noltari/luci,lcf258/openwrtcn,hnyman/luci,teslamint/luci,Hostle/openwrt-luci-multi-user,tcatm/luci,Hostle/openwrt-luci-multi-user,Hostle/luci,ReclaimYourPrivacy/cloak-luci,jchuang1977/luci-1,obsy/luci,NeoRaider/luci,Kyklas/luci-proto-hso,fkooman/luci,aircross/OpenWrt-Firefly-LuCI,981213/luci-1,cshore-firmware/openwrt-luci,mumuqz/luci,fkooman/luci,ollie27/openwrt_luci,aircross/OpenWrt-Firefly-LuCI,bright-things/ionic-luci,aa65535/luci,schidler/ionic-luci,Wedmer/luci,kuoruan/luci,openwrt/luci,forward619/luci,openwrt/luci,bittorf/luci,ReclaimYourPrivacy/cloak-luci,keyidadi/luci,LuttyYang/luci,daofeng2015/luci,artynet/luci,chris5560/openwrt-luci,deepak78/new-luci,Wedmer/luci,joaofvieira/luci,Hostle/openwrt-luci-multi-user,sujeet14108/luci,daofeng2015/luci,thesabbir/luci,jorgifumi/luci,openwrt-es/openwrt-luci,jlopenwrtluci/luci,obsy/luci,keyidadi/luci,shangjiyu/luci-with-extra,jchuang1977/luci-1,male-puppies/luci,NeoRaider/luci,daofeng2015/luci,oyido/luci,taiha/luci,sujeet14108/luci,aa65535/luci,jlopenwrtluci/luci,tobiaswaldvogel/luci,harveyhu2012/luci,slayerrensky/luci,dismantl/luci-0.12,slayerrensky/luci,florian-shellfire/luci,lbthomsen/openwrt-luci,artynet/luci,rogerpueyo/luci,RuiChen1113/luci,maxrio/luci981213,nmav/luci,slayerrensky/luci,bright-things/ionic-luci,maxrio/luci981213,ff94315/luci-1,slayerrensky/luci,wongsyrone/luci-1,male-puppies/luci,jchuang1977/luci-1,db260179/openwrt-bpi-r1-luci,ollie27/openwrt_luci,palmettos/cnLuCI,rogerpueyo/luci,LazyZhu/openwrt-luci-trunk-mod,ollie27/openwrt_luci,hnyman/luci,deepak78/new-luci,kuoruan/luci,thess/OpenWrt-luci,Noltari/luci,bittorf/luci,shangjiyu/luci-with-extra,NeoRaider/luci,maxrio/luci981213,Hostle/luci,shangjiyu/luci-with-extra,artynet/luci,thesabbir/luci,sujeet14108/luci,rogerpueyo/luci,thess/OpenWrt-luci,palmettos/test,tobiaswaldvogel/luci,kuoruan/lede-luci,nmav/luci,hnyman/luci,taiha/luci,urueedi/luci,palmettos/test,zhaoxx063/luci,thess/OpenWrt-luci,dwmw2/luci,palmettos/test,hnyman/luci,male-puppies/luci,remakeelectric/luci,lbthomsen/openwrt-luci,kuoruan/lede-luci,teslamint/luci,oyido/luci,LazyZhu/openwrt-luci-trunk-mod,remakeelectric/luci,remakeelectric/luci,hnyman/luci,openwrt-es/openwrt-luci,cappiewu/luci,palmettos/test,NeoRaider/luci,aa65535/luci,shangjiyu/luci-with-extra,Sakura-Winkey/LuCI,opentechinstitute/luci,lcf258/openwrtcn,chris5560/openwrt-luci,Sakura-Winkey/LuCI,remakeelectric/luci,Hostle/openwrt-luci-multi-user,deepak78/new-luci,thesabbir/luci,jorgifumi/luci,male-puppies/luci,deepak78/new-luci,thess/OpenWrt-luci,aa65535/luci,oneru/luci,NeoRaider/luci,Hostle/luci,palmettos/test,ReclaimYourPrivacy/cloak-luci,Hostle/openwrt-luci-multi-user,Noltari/luci,forward619/luci,dismantl/luci-0.12,keyidadi/luci,palmettos/cnLuCI,aa65535/luci,wongsyrone/luci-1,oneru/luci,nmav/luci,joaofvieira/luci,keyidadi/luci,db260179/openwrt-bpi-r1-luci,lbthomsen/openwrt-luci,cappiewu/luci,hnyman/luci,LazyZhu/openwrt-luci-trunk-mod,openwrt/luci,sujeet14108/luci,harveyhu2012/luci,urueedi/luci,cshore-firmware/openwrt-luci,nmav/luci,db260179/openwrt-bpi-r1-luci,sujeet14108/luci,thesabbir/luci,Sakura-Winkey/LuCI,kuoruan/luci,981213/luci-1,bittorf/luci,jchuang1977/luci-1,Sakura-Winkey/LuCI,fkooman/luci,ollie27/openwrt_luci,MinFu/luci,LazyZhu/openwrt-luci-trunk-mod,wongsyrone/luci-1,joaofvieira/luci,zhaoxx063/luci,forward619/luci,nwf/openwrt-luci,bittorf/luci,RuiChen1113/luci,ff94315/luci-1,Wedmer/luci,urueedi/luci,fkooman/luci,ff94315/luci-1,lcf258/openwrtcn,urueedi/luci,david-xiao/luci,palmettos/test,forward619/luci,cshore/luci,deepak78/new-luci,LuttyYang/luci,Hostle/openwrt-luci-multi-user,deepak78/new-luci,oneru/luci,mumuqz/luci,opentechinstitute/luci,chris5560/openwrt-luci,tcatm/luci,ollie27/openwrt_luci,schidler/ionic-luci,chris5560/openwrt-luci,harveyhu2012/luci,kuoruan/luci,artynet/luci,taiha/luci,rogerpueyo/luci,jlopenwrtluci/luci,deepak78/new-luci,cshore/luci,jorgifumi/luci,dwmw2/luci,aircross/OpenWrt-Firefly-LuCI,dismantl/luci-0.12,db260179/openwrt-bpi-r1-luci,dwmw2/luci,tcatm/luci,mumuqz/luci,schidler/ionic-luci,kuoruan/lede-luci,LuttyYang/luci,harveyhu2012/luci,Kyklas/luci-proto-hso,dismantl/luci-0.12,ff94315/luci-1,ff94315/luci-1,ff94315/luci-1,oyido/luci,oneru/luci,nwf/openwrt-luci,Sakura-Winkey/LuCI,marcel-sch/luci,dismantl/luci-0.12,male-puppies/luci,hnyman/luci,Sakura-Winkey/LuCI,RuiChen1113/luci,opentechinstitute/luci,Hostle/luci,openwrt/luci,joaofvieira/luci,florian-shellfire/luci,slayerrensky/luci,981213/luci-1,florian-shellfire/luci,urueedi/luci,wongsyrone/luci-1,lbthomsen/openwrt-luci,cappiewu/luci,MinFu/luci,jlopenwrtluci/luci,florian-shellfire/luci,tobiaswaldvogel/luci,nwf/openwrt-luci,marcel-sch/luci,maxrio/luci981213,LuttyYang/luci,981213/luci-1,shangjiyu/luci-with-extra,daofeng2015/luci,981213/luci-1,david-xiao/luci,keyidadi/luci,LuttyYang/luci,opentechinstitute/luci,dismantl/luci-0.12,cappiewu/luci,cshore/luci,Sakura-Winkey/LuCI,rogerpueyo/luci,LuttyYang/luci,lcf258/openwrtcn,thess/OpenWrt-luci,Hostle/luci,cshore-firmware/openwrt-luci,forward619/luci,zhaoxx063/luci,male-puppies/luci,jorgifumi/luci,opentechinstitute/luci,jchuang1977/luci-1,RedSnake64/openwrt-luci-packages,Kyklas/luci-proto-hso,obsy/luci,teslamint/luci,schidler/ionic-luci,cshore-firmware/openwrt-luci,tobiaswaldvogel/luci,jlopenwrtluci/luci,mumuqz/luci,sujeet14108/luci,david-xiao/luci,RedSnake64/openwrt-luci-packages,wongsyrone/luci-1,NeoRaider/luci,joaofvieira/luci,ReclaimYourPrivacy/cloak-luci,zhaoxx063/luci,RedSnake64/openwrt-luci-packages
51d9aa8d8ac1f272f941b74ded5146db50905e46
packages/lime-system/files/usr/lib/lua/lime/utils.lua
packages/lime-system/files/usr/lib/lua/lime/utils.lua
#!/usr/bin/lua utils = {} local config = require("lime.config") function utils.split(string, sep) local ret = {} for token in string.gmatch(string, "[^"..sep.."]+") do table.insert(ret, token) end return ret end function utils.stringStarts(string, start) return (string.sub(string, 1, string.len(start)) == start) end function utils.stringEnds(string, _end) return ( _end == '' or string.sub( string, -string.len(_end) ) == _end) end function utils.hex(x) return string.format("%02x", x) end function utils.printf(fmt, ...) print(string.format(fmt, ...)) end function utils.isModuleAvailable(name) if package.loaded[name] then return true else for _, searcher in ipairs(package.searchers or package.loaders) do local loader = searcher(name) if type(loader) == 'function' then package.preload[name] = loader return true end end return false end end function utils.applyMacTemplate16(template, mac) for i=1,6,1 do template = template:gsub("%%M"..i, mac[i]) end local macid = utils.get_id(mac) for i=1,6,1 do template = template:gsub("%%m"..i, macid[i]) end return template end function utils.applyMacTemplate10(template, mac) for i=1,6,1 do template = template:gsub("%%M"..i, tonumber(mac[i], 16)) end local macid = utils.get_id(mac) for i=1,6,1 do template = template:gsub("%%m"..i, tonumber(macid[i], 16)) end return template end function utils.applyHostnameTemplate(template) local system = require("lime.system") return template:gsub("%%H", system.get_hostname()) end function utils.get_id(string) local id = {} local fd = io.popen('echo "' .. string .. '" | md5sum') if fd then local md5 = fd:read("*a") local j = 1 for i=1,16,1 do id[i] = string.sub(md5, j, j + 1) j = j + 2 end fd:close() end return id end function utils.network_id() local network_essid = config.get("wifi", "ap_ssid") return utils.get_id(network_essid) end function utils.applyNetTemplate16(template) local netid = utils.network_id() for i=1,3,1 do template = template:gsub("%%N"..i, netid[i]) end return template end function utils.applyNetTemplate10(template) local netid = utils.network_id() for i=1,3,1 do template = template:gsub("%%N"..i, tonumber(netid[i], 16)) end return template end --! This function is inspired to http://lua-users.org/wiki/VarExpand --! version: 0.0.1 --! code: Ketmar // Avalon Group --! licence: public domain --! expand $var and ${var} in string --! ${var} can call Lua functions: ${string.rep(' ', 10)} --! `$' can be screened with `\' --! `...': args for $<number> --! if `...' is just a one table -- take it as args function utils.expandVars(s, ...) local args = {...} args = #args == 1 and type(args[1]) == "table" and args[1] or args; --! return true if there was an expansion local function DoExpand(iscode) local was = false local mask = iscode and "()%$(%b{})" or "()%$([%a%d_]*)" local drepl = iscode and "\\$" or "\\\\$" s = s:gsub(mask, function(pos, code) if s:sub(pos-1, pos-1) == "\\" then return "$"..code else was = true local v, err if iscode then code = code:sub(2, -2) else local n = tonumber(code) if n then v = args[n] else v = args[code] end end if not v then v, err = loadstring("return "..code) if not v then error(err) end v = v() end if v == nil then v = "" end v = tostring(v):gsub("%$", drepl) return v end end) if not (iscode or was) then s = s:gsub("\\%$", "$") end return was end repeat DoExpand(true); until not DoExpand(false) return s end function utils.sanitize_hostname(hostname) hostname = hostname:gsub(' ', '-') hostname = hostname:gsub('[^-a-zA-Z0-9]', '') hostname = hostname:gsub('^-*', '') hostname = hostname:gsub('-*$', '') hostname = hostname:sub(1, 32) return hostname end function utils.file_exists(name) local f=io.open(name,"r") if f~=nil then io.close(f) return true else return false end end function utils.is_installed(pkg) return utils.file_exists('/usr/lib/opkg/info/'..pkg..'.control') end function utils.has_value(tab, val) for index, value in ipairs(tab) do if value == val then return true end end return false end --! contact array t2 to the end of array t1 function utils.arrayConcat(t1,t2) for _,i in ipairs(t2) do table.insert(t1,i) end return t1 end return utils
#!/usr/bin/lua utils = {} local config = require("lime.config") function utils.split(string, sep) local ret = {} for token in string.gmatch(string, "[^"..sep.."]+") do table.insert(ret, token) end return ret end function utils.stringStarts(string, start) return (string.sub(string, 1, string.len(start)) == start) end function utils.stringEnds(string, _end) return ( _end == '' or string.sub( string, -string.len(_end) ) == _end) end function utils.hex(x) return string.format("%02x", x) end function utils.printf(fmt, ...) print(string.format(fmt, ...)) end function utils.isModuleAvailable(name) if package.loaded[name] then return true else for _, searcher in ipairs(package.searchers or package.loaders) do local loader = searcher(name) if type(loader) == 'function' then package.preload[name] = loader return true end end return false end end function utils.applyMacTemplate16(template, mac) for i=1,6,1 do template = template:gsub("%%M"..i, mac[i]) end local macid = utils.get_id(mac) for i=1,6,1 do template = template:gsub("%%m"..i, macid[i]) end return template end function utils.applyMacTemplate10(template, mac) for i=1,6,1 do template = template:gsub("%%M"..i, tonumber(mac[i], 16)) end local macid = utils.get_id(mac) for i=1,6,1 do template = template:gsub("%%m"..i, tonumber(macid[i], 16)) end return template end function utils.applyHostnameTemplate(template) local system = require("lime.system") return template:gsub("%%H", system.get_hostname()) end function utils.get_id(input) if type(input) == "table" then input = table.concat(input, "") end local id = {} local fd = io.popen('echo "' .. input .. '" | md5sum') if fd then local md5 = fd:read("*a") local j = 1 for i=1,16,1 do id[i] = string.sub(md5, j, j + 1) j = j + 2 end fd:close() end return id end function utils.network_id() local network_essid = config.get("wifi", "ap_ssid") return utils.get_id(network_essid) end function utils.applyNetTemplate16(template) local netid = utils.network_id() for i=1,3,1 do template = template:gsub("%%N"..i, netid[i]) end return template end function utils.applyNetTemplate10(template) local netid = utils.network_id() for i=1,3,1 do template = template:gsub("%%N"..i, tonumber(netid[i], 16)) end return template end --! This function is inspired to http://lua-users.org/wiki/VarExpand --! version: 0.0.1 --! code: Ketmar // Avalon Group --! licence: public domain --! expand $var and ${var} in string --! ${var} can call Lua functions: ${string.rep(' ', 10)} --! `$' can be screened with `\' --! `...': args for $<number> --! if `...' is just a one table -- take it as args function utils.expandVars(s, ...) local args = {...} args = #args == 1 and type(args[1]) == "table" and args[1] or args; --! return true if there was an expansion local function DoExpand(iscode) local was = false local mask = iscode and "()%$(%b{})" or "()%$([%a%d_]*)" local drepl = iscode and "\\$" or "\\\\$" s = s:gsub(mask, function(pos, code) if s:sub(pos-1, pos-1) == "\\" then return "$"..code else was = true local v, err if iscode then code = code:sub(2, -2) else local n = tonumber(code) if n then v = args[n] else v = args[code] end end if not v then v, err = loadstring("return "..code) if not v then error(err) end v = v() end if v == nil then v = "" end v = tostring(v):gsub("%$", drepl) return v end end) if not (iscode or was) then s = s:gsub("\\%$", "$") end return was end repeat DoExpand(true); until not DoExpand(false) return s end function utils.sanitize_hostname(hostname) hostname = hostname:gsub(' ', '-') hostname = hostname:gsub('[^-a-zA-Z0-9]', '') hostname = hostname:gsub('^-*', '') hostname = hostname:gsub('-*$', '') hostname = hostname:sub(1, 32) return hostname end function utils.file_exists(name) local f=io.open(name,"r") if f~=nil then io.close(f) return true else return false end end function utils.is_installed(pkg) return utils.file_exists('/usr/lib/opkg/info/'..pkg..'.control') end function utils.has_value(tab, val) for index, value in ipairs(tab) do if value == val then return true end end return false end --! contact array t2 to the end of array t1 function utils.arrayConcat(t1,t2) for _,i in ipairs(t2) do table.insert(t1,i) end return t1 end return utils
lime-system: fixup mac table handling
lime-system: fixup mac table handling the mac is stored as a table and thereby causes an error when trying concat it with another string. Signed-off-by: Paul Spooren <7a88a1f62d18f609867b9792771bed5b7c6b9095@informatik.uni-leipzig.de>
Lua
agpl-3.0
libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages
d7e2c4c656f88e9b4f92e60b2da4921b60a23c34
triggerfield/galmair_guard_rules.lua
triggerfield/galmair_guard_rules.lua
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] -- Quest: As a Galmair Guard (155) local common = require("base.common") local M = {} function M.MoveToField(User) if char:isInRangeToPosition((position (368 , 250, 0)), 2) and char:getQuestProgress(155) == 1 then -- doing quest to read the rules of Galmair char:setQuestProgress(155, 2) common.InformNLS(char,"[Queststatus] Du hast lesen die Regeln auf den Statuen des Dons die vor Galmairs Krone stehen. Kehre zu Boumaug zurck.", "[Quest status] You read the rules on the Don's statues in front of the Crest of Galmair. Return to Boumaug.") end end return M
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] -- Quest: As a Galmair Guard (155) local common = require("base.common") local M = {} function M.MoveToField(User) if char:getType() ~= Character.player then return end if char.pos == position (368 , 250, 0) and char:getQuestProgress(155) == 1 then -- doing quest to read the rules of Galmair char:setQuestProgress(155, 2) common.InformNLS(char,"[Queststatus] Du hast lesen die Regeln auf den Statuen des Dons die vor Galmairs Krone stehen. Kehre zu Boumaug zurck.", "[Quest status] You read the rules on the Don's statues in front of the Crest of Galmair. Return to Boumaug.") end end return M
Fix triggerfield script
Fix triggerfield script
Lua
agpl-3.0
vilarion/Illarion-Content,Illarion-eV/Illarion-Content,KayMD/Illarion-Content,Baylamon/Illarion-Content
d0a9e68a4125c043a6ee6a4d92ac244f2feb7ccb
src/luarocks/command_line.lua
src/luarocks/command_line.lua
--- Functions for command-line scripts. local command_line = {} local unpack = unpack or table.unpack local util = require("luarocks.util") local cfg = require("luarocks.cfg") local path = require("luarocks.path") local dir = require("luarocks.dir") local deps = require("luarocks.deps") local fs = require("luarocks.fs") local program = util.this_program("luarocks") local function error_handler(err) return debug.traceback("LuaRocks "..cfg.program_version.. " bug (please report at https://github.com/keplerproject/luarocks/issues).\n"..err, 2) end --- Display an error message and exit. -- @param message string: The error message. -- @param exitcode number: the exitcode to use local function die(message, exitcode) assert(type(message) == "string") util.printerr("\nError: "..message) local ok, err = xpcall(util.run_scheduled_functions, error_handler) if not ok then util.printerr("\nError: "..err) exitcode = cfg.errorcodes.CRASH end os.exit(exitcode or cfg.errorcodes.UNSPECIFIED) end local function replace_tree(flags, tree) tree = dir.normalize(tree) flags["tree"] = tree path.use_tree(tree) end --- Main command-line processor. -- Parses input arguments and calls the appropriate driver function -- to execute the action requested on the command-line, forwarding -- to it any additional arguments passed by the user. -- Uses the global table "commands", which contains -- the loaded modules representing commands. -- @param ... string: Arguments given on the command-line. function command_line.run_command(...) local args = {...} local cmdline_vars = {} for i = #args, 1, -1 do local arg = args[i] if arg:match("^[^-][^=]*=") then local var, val = arg:match("^([A-Z_][A-Z0-9_]*)=(.*)") if val then cmdline_vars[var] = val table.remove(args, i) else die("Invalid assignment: "..arg) end end end local nonflags = { util.parse_flags(unpack(args)) } local flags = table.remove(nonflags, 1) if flags.ERROR then die(flags.ERROR.." See --help.") end if flags["from"] then flags["server"] = flags["from"] end if flags["only-from"] then flags["only-server"] = flags["only-from"] end if flags["only-sources-from"] then flags["only-sources"] = flags["only-sources-from"] end if flags["to"] then flags["tree"] = flags["to"] end if flags["nodeps"] then flags["deps-mode"] = "none" end cfg.flags = flags local command if flags["verbose"] then -- setting it in the config file will kick-in earlier in the process cfg.verbose = true fs.verbose() end if flags["timeout"] then -- setting it in the config file will kick-in earlier in the process local timeout = tonumber(flags["timeout"]) if timeout then cfg.connection_timeout = timeout else die "Argument error: --timeout expects a numeric argument." end end if flags["version"] then util.printout(program.." "..cfg.program_version) util.printout(program_description) util.printout() os.exit(cfg.errorcodes.OK) elseif flags["help"] or #nonflags == 0 then command = "help" else command = table.remove(nonflags, 1) end command = command:gsub("-", "_") if cfg.local_by_default then flags["local"] = true end if flags["deps-mode"] and not deps.check_deps_mode_flag(flags["deps-mode"]) then die("Invalid entry for --deps-mode.") end if flags["branch"] then cfg.branch = flags["branch"] end if flags["tree"] then local named = false for _, tree in ipairs(cfg.rocks_trees) do if type(tree) == "table" and flags["tree"] == tree.name then if not tree.root then die("Configuration error: tree '"..tree.name.."' has no 'root' field.") end replace_tree(flags, tree.root) named = true break end end if not named then local root_dir = fs.absolute_name(flags["tree"]) replace_tree(flags, root_dir) end elseif flags["local"] then if not cfg.home_tree then die("The --local flag is meant for operating in a user's home directory.\n".. "You are running as a superuser, which is intended for system-wide operation.\n".. "To force using the superuser's home, use --tree explicitly.") end replace_tree(flags, cfg.home_tree) else local trees = cfg.rocks_trees path.use_tree(trees[#trees]) end if type(cfg.root_dir) == "string" then cfg.root_dir = cfg.root_dir:gsub("/+$", "") else cfg.root_dir.root = cfg.root_dir.root:gsub("/+$", "") end cfg.rocks_dir = cfg.rocks_dir:gsub("/+$", "") cfg.deploy_bin_dir = cfg.deploy_bin_dir:gsub("/+$", "") cfg.deploy_lua_dir = cfg.deploy_lua_dir:gsub("/+$", "") cfg.deploy_lib_dir = cfg.deploy_lib_dir:gsub("/+$", "") cfg.variables.ROCKS_TREE = cfg.rocks_dir cfg.variables.SCRIPTS_DIR = cfg.deploy_bin_dir if flags["server"] then local protocol, path = dir.split_url(flags["server"]) table.insert(cfg.rocks_servers, 1, protocol.."://"..path) end if flags["only-server"] then cfg.rocks_servers = { flags["only-server"] } end if flags["only-sources"] then cfg.only_sources_from = flags["only-sources"] end if command ~= "help" then for k, v in pairs(cmdline_vars) do cfg.variables[k] = v end end if (not fs.current_dir()) or fs.current_dir() == "" then die("Current directory does not exist. Please run LuaRocks from an existing directory.") end if fs.attributes(cfg.local_cache, "owner") ~= fs.current_user() or fs.attributes(dir.dir_name(cfg.local_cache), "owner") ~= fs.current_user() then util.warning("The directory '" .. cfg.local_cache .. "' or its parent directory ".. "is not owned by the current user and the cache has been disabled. ".. "Please check the permissions and owner of that directory. ".. "If executing pip with sudo, you may want sudo's -H flag.") cfg.local_cache = fs.make_temp_dir("local_cache") util.schedule_function(fs.delete, cfg.local_cache) end if commands[command] then local cmd = require(commands[command]) local call_ok, ok, err, exitcode = xpcall(function() return cmd.command(flags, unpack(nonflags)) end, error_handler) if not call_ok then die(ok, cfg.errorcodes.CRASH) elseif not ok then die(err, exitcode) end else die("Unknown command: "..command) end util.run_scheduled_functions() end return command_line
--- Functions for command-line scripts. local command_line = {} local unpack = unpack or table.unpack local util = require("luarocks.util") local cfg = require("luarocks.cfg") local path = require("luarocks.path") local dir = require("luarocks.dir") local deps = require("luarocks.deps") local fs = require("luarocks.fs") local program = util.this_program("luarocks") local function error_handler(err) return debug.traceback("LuaRocks "..cfg.program_version.. " bug (please report at https://github.com/keplerproject/luarocks/issues).\n"..err, 2) end --- Display an error message and exit. -- @param message string: The error message. -- @param exitcode number: the exitcode to use local function die(message, exitcode) assert(type(message) == "string") util.printerr("\nError: "..message) local ok, err = xpcall(util.run_scheduled_functions, error_handler) if not ok then util.printerr("\nError: "..err) exitcode = cfg.errorcodes.CRASH end os.exit(exitcode or cfg.errorcodes.UNSPECIFIED) end local function replace_tree(flags, tree) tree = dir.normalize(tree) flags["tree"] = tree path.use_tree(tree) end --- Main command-line processor. -- Parses input arguments and calls the appropriate driver function -- to execute the action requested on the command-line, forwarding -- to it any additional arguments passed by the user. -- Uses the global table "commands", which contains -- the loaded modules representing commands. -- @param ... string: Arguments given on the command-line. function command_line.run_command(...) local args = {...} local cmdline_vars = {} for i = #args, 1, -1 do local arg = args[i] if arg:match("^[^-][^=]*=") then local var, val = arg:match("^([A-Z_][A-Z0-9_]*)=(.*)") if val then cmdline_vars[var] = val table.remove(args, i) else die("Invalid assignment: "..arg) end end end local nonflags = { util.parse_flags(unpack(args)) } local flags = table.remove(nonflags, 1) if flags.ERROR then die(flags.ERROR.." See --help.") end if flags["from"] then flags["server"] = flags["from"] end if flags["only-from"] then flags["only-server"] = flags["only-from"] end if flags["only-sources-from"] then flags["only-sources"] = flags["only-sources-from"] end if flags["to"] then flags["tree"] = flags["to"] end if flags["nodeps"] then flags["deps-mode"] = "none" end cfg.flags = flags local command if flags["verbose"] then -- setting it in the config file will kick-in earlier in the process cfg.verbose = true fs.verbose() end if flags["timeout"] then -- setting it in the config file will kick-in earlier in the process local timeout = tonumber(flags["timeout"]) if timeout then cfg.connection_timeout = timeout else die "Argument error: --timeout expects a numeric argument." end end if flags["version"] then util.printout(program.." "..cfg.program_version) util.printout(program_description) util.printout() os.exit(cfg.errorcodes.OK) elseif flags["help"] or #nonflags == 0 then command = "help" else command = table.remove(nonflags, 1) end command = command:gsub("-", "_") if cfg.local_by_default then flags["local"] = true end if flags["deps-mode"] and not deps.check_deps_mode_flag(flags["deps-mode"]) then die("Invalid entry for --deps-mode.") end if flags["branch"] then cfg.branch = flags["branch"] end if flags["tree"] then local named = false for _, tree in ipairs(cfg.rocks_trees) do if type(tree) == "table" and flags["tree"] == tree.name then if not tree.root then die("Configuration error: tree '"..tree.name.."' has no 'root' field.") end replace_tree(flags, tree.root) named = true break end end if not named then local root_dir = fs.absolute_name(flags["tree"]) replace_tree(flags, root_dir) end elseif flags["local"] then if not cfg.home_tree then die("The --local flag is meant for operating in a user's home directory.\n".. "You are running as a superuser, which is intended for system-wide operation.\n".. "To force using the superuser's home, use --tree explicitly.") end replace_tree(flags, cfg.home_tree) else local trees = cfg.rocks_trees path.use_tree(trees[#trees]) end if type(cfg.root_dir) == "string" then cfg.root_dir = cfg.root_dir:gsub("/+$", "") else cfg.root_dir.root = cfg.root_dir.root:gsub("/+$", "") end cfg.rocks_dir = cfg.rocks_dir:gsub("/+$", "") cfg.deploy_bin_dir = cfg.deploy_bin_dir:gsub("/+$", "") cfg.deploy_lua_dir = cfg.deploy_lua_dir:gsub("/+$", "") cfg.deploy_lib_dir = cfg.deploy_lib_dir:gsub("/+$", "") cfg.variables.ROCKS_TREE = cfg.rocks_dir cfg.variables.SCRIPTS_DIR = cfg.deploy_bin_dir if flags["server"] then local protocol, path = dir.split_url(flags["server"]) table.insert(cfg.rocks_servers, 1, protocol.."://"..path) end if flags["only-server"] then cfg.rocks_servers = { flags["only-server"] } end if flags["only-sources"] then cfg.only_sources_from = flags["only-sources"] end if command ~= "help" then for k, v in pairs(cmdline_vars) do cfg.variables[k] = v end end if (not fs.current_dir()) or fs.current_dir() == "" then die("Current directory does not exist. Please run LuaRocks from an existing directory.") end if fs.attributes(cfg.local_cache, "owner") ~= fs.current_user() or fs.attributes(dir.dir_name(cfg.local_cache), "owner") ~= fs.current_user() then util.warning("The directory '" .. cfg.local_cache .. "' or its parent directory ".. "is not owned by the current user and the cache has been disabled. ".. "Please check the permissions and owner of that directory. ".. (cfg.is_platform("unix") and ("If executing "..util.this_program("luarocks").." with sudo, you may want sudo's -H flag.") or "")) cfg.local_cache = fs.make_temp_dir("local_cache") util.schedule_function(fs.delete, cfg.local_cache) end if commands[command] then local cmd = require(commands[command]) local call_ok, ok, err, exitcode = xpcall(function() return cmd.command(flags, unpack(nonflags)) end, error_handler) if not call_ok then die(ok, cfg.errorcodes.CRASH) elseif not ok then die(err, exitcode) end else die("Unknown command: "..command) end util.run_scheduled_functions() end return command_line
Oops! Fix warning message.
Oops! Fix warning message.
Lua
mit
tarantool/luarocks,luarocks/luarocks,keplerproject/luarocks,luarocks/luarocks,keplerproject/luarocks,tarantool/luarocks,keplerproject/luarocks,luarocks/luarocks,tarantool/luarocks,keplerproject/luarocks
2c98bc0a75c1e8b0eb7c1c0bdf52e304295f31b7
examples/undocumented/lua_modular/evaluation_contingencytableevaluation_modular.lua
examples/undocumented/lua_modular/evaluation_contingencytableevaluation_modular.lua
require 'shogun' require 'load' ground__truth = load_labels('../data/label_train_twoclass.dat') math.randomseed(17) --predicted = random.randn(len(ground_truth)) predicte = {} for i = 1, #ground__truth do table.insert(predicte, math.random()) end parameter_list = {{ground__truth,predicte}} function evaluation_contingencytableevaluation_modular(ground_truth, predicted) ground_truth_labels = Labels(ground_truth) predicted_labels = Labels(predicted) base_evaluator = ContingencyTableEvaluation() base_evaluator:evaluate(predicted_labels,ground_truth_labels) evaluator = AccuracyMeasure() accuracy = evaluator:evaluate(predicted_labels,ground_truth_labels) evaluator = ErrorRateMeasure() errorrate = evaluator:evaluate(predicted_labels,ground_truth_labels) evaluator = BALMeasure() bal = evaluator:evaluate(predicted_labels,ground_truth_labels) evaluator = WRACCMeasure() wracc = evaluator:evaluate(predicted_labels,ground_truth_labels) evaluator = F1Measure() f1 = evaluator:evaluate(predicted_labels,ground_truth_labels) evaluator = CrossCorrelationMeasure() crosscorrelation = evaluator:evaluate(predicted_labels,ground_truth_labels) evaluator = RecallMeasure() recall = evaluator:evaluate(predicted_labels,ground_truth_labels) evaluator = PrecisionMeasure() precision = evaluator:evaluate(predicted_labels,ground_truth_labels) evaluator = SpecificityMeasure() specificity = evaluator:evaluate(predicted_labels,ground_truth_labels) return accuracy, errorrate, bal, wracc, f1, crosscorrelation, recall, precision, specificity end print 'ContingencyTableEvaluation' evaluation_contingencytableevaluation_modular(unpack(parameter_list[1]))
require 'shogun' require 'load' ground_truth = load_labels('../data/label_train_twoclass.dat') math.randomseed(17) predicted = {} for i = 1, #ground_truth do table.insert(predicted, math.random()) end parameter_list = {{ground_truth,predicted}} function evaluation_contingencytableevaluation_modular(ground_truth, predicted) ground_truth_labels = Labels(ground_truth) predicted_labels = Labels(predicted) base_evaluator = ContingencyTableEvaluation() base_evaluator:evaluate(predicted_labels,ground_truth_labels) evaluator = AccuracyMeasure() accuracy = evaluator:evaluate(predicted_labels,ground_truth_labels) evaluator = ErrorRateMeasure() errorrate = evaluator:evaluate(predicted_labels,ground_truth_labels) evaluator = BALMeasure() bal = evaluator:evaluate(predicted_labels,ground_truth_labels) evaluator = WRACCMeasure() wracc = evaluator:evaluate(predicted_labels,ground_truth_labels) evaluator = F1Measure() f1 = evaluator:evaluate(predicted_labels,ground_truth_labels) evaluator = CrossCorrelationMeasure() crosscorrelation = evaluator:evaluate(predicted_labels,ground_truth_labels) evaluator = RecallMeasure() recall = evaluator:evaluate(predicted_labels,ground_truth_labels) evaluator = PrecisionMeasure() precision = evaluator:evaluate(predicted_labels,ground_truth_labels) evaluator = SpecificityMeasure() specificity = evaluator:evaluate(predicted_labels,ground_truth_labels) return accuracy, errorrate, bal, wracc, f1, crosscorrelation, recall, precision, specificity end print 'ContingencyTableEvaluation' evaluation_contingencytableevaluation_modular(unpack(parameter_list[1]))
fix typo
fix typo
Lua
bsd-3-clause
sorig/shogun,karlnapf/shogun,Saurabh7/shogun,shogun-toolbox/shogun,shogun-toolbox/shogun,karlnapf/shogun,shogun-toolbox/shogun,Saurabh7/shogun,sorig/shogun,karlnapf/shogun,lambday/shogun,besser82/shogun,besser82/shogun,Saurabh7/shogun,Saurabh7/shogun,lisitsyn/shogun,besser82/shogun,geektoni/shogun,lisitsyn/shogun,karlnapf/shogun,sorig/shogun,geektoni/shogun,shogun-toolbox/shogun,lambday/shogun,shogun-toolbox/shogun,geektoni/shogun,lisitsyn/shogun,sorig/shogun,sorig/shogun,lisitsyn/shogun,shogun-toolbox/shogun,karlnapf/shogun,besser82/shogun,lambday/shogun,Saurabh7/shogun,Saurabh7/shogun,geektoni/shogun,lambday/shogun,lambday/shogun,lisitsyn/shogun,geektoni/shogun,besser82/shogun,Saurabh7/shogun,Saurabh7/shogun,geektoni/shogun,sorig/shogun,lisitsyn/shogun,besser82/shogun,karlnapf/shogun,Saurabh7/shogun,lambday/shogun
f6a5264715c11f0846b263efbe474c4e8fae39e3
src/firstpersoncharactertransparency/src/Client/FirstPersonCharacterTransparency.lua
src/firstpersoncharactertransparency/src/Client/FirstPersonCharacterTransparency.lua
--- Allows transparency to manually be controlled for a character in first-person -- mode -- @classmod FirstPersonCharacterTransparency -- @author Quenty local require = require(script.Parent.loader).load(script) local BaseObject = require("BaseObject") local TransparencyService = require("TransparencyService") local FirstPersonCharacterTransparency = setmetatable({}, BaseObject) FirstPersonCharacterTransparency.ClassName = "FirstPersonCharacterTransparency" FirstPersonCharacterTransparency.__index = FirstPersonCharacterTransparency function FirstPersonCharacterTransparency.new(humanoid) local self = setmetatable(BaseObject.new(humanoid), FirstPersonCharacterTransparency) self._humanoid = humanoid or error("No humanoid") self._character = self._humanoid.Parent or error("No character") self._parts = {} self._transparency = 0 -- Listen to parts for _, part in pairs(self._character:GetDescendants()) do self:_handlePartAdded(part) end -- Listen to children self._maid:GiveTask(self._character.DescendantAdded:Connect(function(part) self:_handlePartAdded(part) end)) self._maid:GiveTask(self._character.DescendantRemoving:Connect(function(part) self:_handlePartRemoving(part) end)) self._maid:GiveTask(function() self:_reset() end) return self end function FirstPersonCharacterTransparency:SetTransparency(transparency) assert(type(transparency) == "number", "Bad transparency") if transparency >= 0.999 then transparency = 1 elseif transparency <= 0.001 then transparency = 0 end if self._transparency == transparency then return end self._transparency = transparency for part, _ in pairs(self._parts) do TransparencyService:SetTransparency(self, part, self._transparency) end end function FirstPersonCharacterTransparency:_reset() for part, _ in pairs(self._parts) do TransparencyService:ResetTransparency(self, part) end end function FirstPersonCharacterTransparency:_shouldAddPart(part) if not part:IsA("BasePart") then return false end return part:FindFirstAncestorWhichIsA("Accessory") or part.Name ~= "Head" end function FirstPersonCharacterTransparency:_handlePartAdded(part) if self:_shouldAddPart(part) then self._parts[part] = true if self._transparency then TransparencyService:SetTransparency(self, part, self._transparency) end end end function FirstPersonCharacterTransparency:_handlePartRemoving(part) if part:IsA("BasePart") then self._parts[part] = nil TransparencyService:ResetTransparency(self, part) end end return FirstPersonCharacterTransparency
--- Allows transparency to manually be controlled for a character in first-person -- mode -- @classmod FirstPersonCharacterTransparency -- @author Quenty local require = require(script.Parent.loader).load(script) local BaseObject = require("BaseObject") local TransparencyService = require("TransparencyService") local FirstPersonCharacterTransparency = setmetatable({}, BaseObject) FirstPersonCharacterTransparency.ClassName = "FirstPersonCharacterTransparency" FirstPersonCharacterTransparency.__index = FirstPersonCharacterTransparency function FirstPersonCharacterTransparency.new(humanoid, serviceBag) local self = setmetatable(BaseObject.new(humanoid), FirstPersonCharacterTransparency) self._humanoid = humanoid or error("No humanoid") self._character = self._humanoid.Parent or error("No character") self._transparencyService = serviceBag:GetService(TransparencyService) self._parts = {} self._transparency = 0 -- Listen to parts for _, part in pairs(self._character:GetDescendants()) do self:_handlePartAdded(part) end -- Listen to children self._maid:GiveTask(self._character.DescendantAdded:Connect(function(part) self:_handlePartAdded(part) end)) self._maid:GiveTask(self._character.DescendantRemoving:Connect(function(part) self:_handlePartRemoving(part) end)) self._maid:GiveTask(function() self:_reset() end) return self end function FirstPersonCharacterTransparency:SetTransparency(transparency) assert(type(transparency) == "number", "Bad transparency") if transparency >= 0.999 then transparency = 1 elseif transparency <= 0.001 then transparency = 0 end if self._transparency == transparency then return end self._transparency = transparency for part, _ in pairs(self._parts) do self._transparencyService:SetTransparency(self, part, self._transparency) end end function FirstPersonCharacterTransparency:_reset() for part, _ in pairs(self._parts) do self._transparencyService:ResetTransparency(self, part) end end function FirstPersonCharacterTransparency:_shouldAddPart(part) if not part:IsA("BasePart") then return false end return part:FindFirstAncestorWhichIsA("Accessory") or part.Name ~= "Head" end function FirstPersonCharacterTransparency:_handlePartAdded(part) if self:_shouldAddPart(part) then self._parts[part] = true if self._transparency then self._transparencyService:SetTransparency(self, part, self._transparency) end end end function FirstPersonCharacterTransparency:_handlePartRemoving(part) if part:IsA("BasePart") then self._parts[part] = nil self._transparencyService:ResetTransparency(self, part) end end return FirstPersonCharacterTransparency
fix: FirstPersonCharacterTransparency uses service bag
fix: FirstPersonCharacterTransparency uses service bag
Lua
mit
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
a9fac16e50c53ffe452777d8206ff920ac05f4f2
middleware/burningman-demultiply/burningman_demultiply.lua
middleware/burningman-demultiply/burningman_demultiply.lua
return function(request, next_middleware) local response = next_middleware() local events = json.decode(response.body) local newresponse ={} for i=1,#events do local e ={} local currentEvent = events[i]; e.title = currentEvent.title e.desc = currentEvent.description e.id = currentEvent.id e.host = currentEvent.hosted_by_camp e.url =currentEvent.url e.location = currentEvent.other_location e.category = currentEvent.event_type.abbr for j=1,#currentEvent.occurrence_set do e.start_time = currentEvent.occurrence_set[j].start_time e.end_time = currentEvent.occurrence_set[j].end_time table.insert(newresponse,e) end end response.body = json.encode(newresponse) return next_middleware() end
return function(request, next_middleware) local response = next_middleware() local events = json.decode(response.body) local newresponse ={} for i=1,#events do local currentEvent = events[i]; for j=1,#currentEvent.occurrence_set do table.insert(newresponse,{ title = currentEvent.title, desc = currentEvent.description, id = currentEvent.id, host = currentEvent.hosted_by_camp, url = currentEvent.url, location = currentEvent.other_location, category = currentEvent.event_type.abbr, start_time = currentEvent.occurrence_set[j].start_time, end_time = currentEvent.occurrence_set[j].end_time }) end end response.body = json.encode(newresponse) return response end
fix burningman_demultiply
fix burningman_demultiply
Lua
mit
APItools/middleware
59015045555f1038478ff48a5a04404e47c74ff6
modules/admin-mini/luasrc/model/cbi/mini/network.lua
modules/admin-mini/luasrc/model/cbi/mini/network.lua
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- require("luci.tools.webadmin") require("luci.sys") m0 = Map("network", translate("network")) m0.stateful = true local netstat = luci.sys.net.deviceinfo() m0.parse = function() end s = m0:section(TypedSection, "interface", translate("status")) s.template = "cbi/tblsection" s.rowcolors = true function s.filter(self, section) return section ~= "loopback" and section end hwaddr = s:option(DummyValue, "_hwaddr") function hwaddr.cfgvalue(self, section) local ix = self.map:get(section, "ifname") or "" return luci.fs.readfile("/sys/class/net/" .. ix .. "/address") or "n/a" end s:option(DummyValue, "ipaddr", translate("ipaddress")) s:option(DummyValue, "netmask", translate("netmask")) txrx = s:option(DummyValue, "_txrx") function txrx.cfgvalue(self, section) local ix = self.map:get(section, "ifname") local rx = netstat and netstat[ix] and netstat[ix][1] rx = rx and luci.tools.webadmin.byte_format(tonumber(rx)) or "-" local tx = netstat and netstat[ix] and netstat[ix][9] tx = tx and luci.tools.webadmin.byte_format(tonumber(tx)) or "-" return string.format("%s / %s", tx, rx) end errors = s:option(DummyValue, "_err") function errors.cfgvalue(self, section) local ix = self.map:get(section, "ifname") local rx = netstat and netstat[ix] and netstat[ix][3] local tx = netstat and netstat[ix] and netstat[ix][11] rx = rx and tostring(rx) or "-" tx = tx and tostring(tx) or "-" return string.format("%s / %s", tx, rx) end m = Map("network", "") s = m:section(NamedSection, "lan", "interface", translate("m_n_local")) s:option(Value, "ipaddr", translate("ipaddress")) nm = s:option(Value, "netmask", translate("netmask")) nm:value("255.255.255.0") nm:value("255.255.0.0") nm:value("255.0.0.0") gw = s:option(Value, "gateway", translate("gateway") .. translate("cbi_optional")) gw.rmempty = true dns = s:option(Value, "dns", translate("dnsserver") .. translate("cbi_optional")) dns.rmempty = true s = m:section(NamedSection, "wan", "interface", translate("m_n_inet")) p = s:option(ListValue, "proto", translate("protocol")) p:value("none", "disabled") p:value("static", translate("manual", "manual")) p:value("dhcp", translate("automatic", "automatic")) p:value("pppoe", "PPPoE") p:value("pptp", "PPTP") ip = s:option(Value, "ipaddr", translate("ipaddress")) ip:depends("proto", "static") nm = s:option(Value, "netmask", translate("netmask")) nm:depends("proto", "static") gw = s:option(Value, "gateway", translate("gateway")) gw:depends("proto", "static") gw.rmempty = true dns = s:option(Value, "dns", translate("dnsserver")) dns:depends("proto", "static") dns.rmempty = true usr = s:option(Value, "username", translate("username")) usr:depends("proto", "pppoe") usr:depends("proto", "pptp") pwd = s:option(Value, "password", translate("password")) pwd:depends("proto", "pppoe") pwd:depends("proto", "pptp") kea = s:option(Flag, "keepalive", translate("m_n_keepalive")) kea:depends("proto", "pppoe") kea:depends("proto", "pptp") kea.rmempty = true kea.enabled = "10" cod = s:option(Value, "demand", translate("m_n_dialondemand"), "s") cod:depends("proto", "pppoe") cod:depends("proto", "pptp") cod.rmempty = true srv = s:option(Value, "server", translate("m_n_pptp_server")) srv:depends("proto", "pptp") srv.rmempty = true return m0, m
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- require("luci.tools.webadmin") require("luci.sys") luci.model.uci.load_state("network") local wireless = luci.model.uci.get_all("network") luci.model.uci.unload("network") local netstat = luci.sys.net.deviceinfo() local ifaces = {} for k, v in pairs(wireless) do if v[".type"] == "interface" and k ~= "loopback" then table.insert(ifaces, v) end end m = Map("network", translate("network")) s = m:section(Table, ifaces, translate("status")) s.parse = function() end s:option(DummyValue, ".name", translate("network")) hwaddr = s:option(DummyValue, "_hwaddr", translate("network_interface_hwaddr"), translate("network_interface_hwaddr_desc")) function hwaddr.cfgvalue(self, section) local ix = self.map:get(section, "ifname") or "" return luci.fs.readfile("/sys/class/net/" .. ix .. "/address") or "n/a" end s:option(DummyValue, "ipaddr", translate("ipaddress")) s:option(DummyValue, "netmask", translate("netmask")) txrx = s:option(DummyValue, "_txrx", translate("network_interface_txrx"), translate("network_interface_txrx_desc")) function txrx.cfgvalue(self, section) local ix = self.map:get(section, "ifname") local rx = netstat and netstat[ix] and netstat[ix][1] rx = rx and luci.tools.webadmin.byte_format(tonumber(rx)) or "-" local tx = netstat and netstat[ix] and netstat[ix][9] tx = tx and luci.tools.webadmin.byte_format(tonumber(tx)) or "-" return string.format("%s / %s", tx, rx) end errors = s:option(DummyValue, "_err", translate("network_interface_err"), translate("network_interface_err_desc")) function errors.cfgvalue(self, section) local ix = self.map:get(section, "ifname") local rx = netstat and netstat[ix] and netstat[ix][3] local tx = netstat and netstat[ix] and netstat[ix][11] rx = rx and tostring(rx) or "-" tx = tx and tostring(tx) or "-" return string.format("%s / %s", tx, rx) end s = m:section(NamedSection, "lan", "interface", translate("m_n_local")) s:option(Value, "ipaddr", translate("ipaddress")) nm = s:option(Value, "netmask", translate("netmask")) nm:value("255.255.255.0") nm:value("255.255.0.0") nm:value("255.0.0.0") gw = s:option(Value, "gateway", translate("gateway") .. translate("cbi_optional")) gw.rmempty = true dns = s:option(Value, "dns", translate("dnsserver") .. translate("cbi_optional")) dns.rmempty = true s = m:section(NamedSection, "wan", "interface", translate("m_n_inet")) p = s:option(ListValue, "proto", translate("protocol")) p:value("none", "disabled") p:value("static", translate("manual", "manual")) p:value("dhcp", translate("automatic", "automatic")) p:value("pppoe", "PPPoE") p:value("pptp", "PPTP") ip = s:option(Value, "ipaddr", translate("ipaddress")) ip:depends("proto", "static") nm = s:option(Value, "netmask", translate("netmask")) nm:depends("proto", "static") gw = s:option(Value, "gateway", translate("gateway")) gw:depends("proto", "static") gw.rmempty = true dns = s:option(Value, "dns", translate("dnsserver")) dns:depends("proto", "static") dns.rmempty = true usr = s:option(Value, "username", translate("username")) usr:depends("proto", "pppoe") usr:depends("proto", "pptp") pwd = s:option(Value, "password", translate("password")) pwd:depends("proto", "pppoe") pwd:depends("proto", "pptp") kea = s:option(Flag, "keepalive", translate("m_n_keepalive")) kea:depends("proto", "pppoe") kea:depends("proto", "pptp") kea.rmempty = true kea.enabled = "10" cod = s:option(Value, "demand", translate("m_n_dialondemand"), "s") cod:depends("proto", "pppoe") cod:depends("proto", "pptp") cod.rmempty = true srv = s:option(Value, "server", translate("m_n_pptp_server")) srv:depends("proto", "pptp") srv.rmempty = true return m
Fixed duplicate tables
Fixed duplicate tables git-svn-id: edf5ee79c2c7d29460bbb5b398f55862cc26620d@2892 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
Lua
apache-2.0
alxhh/piratenluci,gwlim/luci,projectbismark/luci-bismark,eugenesan/openwrt-luci,zwhfly/openwrt-luci,gwlim/luci,alxhh/piratenluci,Canaan-Creative/luci,ThingMesh/openwrt-luci,8devices/carambola2-luci,dtaht/cerowrt-luci-3.3,eugenesan/openwrt-luci,ReclaimYourPrivacy/cloak-luci,ThingMesh/openwrt-luci,projectbismark/luci-bismark,dtaht/cerowrt-luci-3.3,ThingMesh/openwrt-luci,alxhh/piratenluci,eugenesan/openwrt-luci,ch3n2k/luci,Canaan-Creative/luci,ch3n2k/luci,ReclaimYourPrivacy/cloak-luci,ch3n2k/luci,dtaht/cerowrt-luci-3.3,freifunk-gluon/luci,jschmidlapp/luci,8devices/carambola2-luci,projectbismark/luci-bismark,vhpham80/luci,phi-psi/luci,stephank/luci,gwlim/luci,8devices/carambola2-luci,Flexibity/luci,eugenesan/openwrt-luci,Canaan-Creative/luci,dtaht/cerowrt-luci-3.3,Canaan-Creative/luci,gwlim/luci,vhpham80/luci,yeewang/openwrt-luci,zwhfly/openwrt-luci,saraedum/luci-packages-old,vhpham80/luci,Flexibity/luci,ch3n2k/luci,jschmidlapp/luci,freifunk-gluon/luci,Flexibity/luci,jschmidlapp/luci,jschmidlapp/luci,phi-psi/luci,jschmidlapp/luci,freifunk-gluon/luci,yeewang/openwrt-luci,ch3n2k/luci,zwhfly/openwrt-luci,ReclaimYourPrivacy/cloak-luci,yeewang/openwrt-luci,projectbismark/luci-bismark,Flexibity/luci,zwhfly/openwrt-luci,yeewang/openwrt-luci,saraedum/luci-packages-old,ReclaimYourPrivacy/cloak-luci,Flexibity/luci,yeewang/openwrt-luci,saraedum/luci-packages-old,yeewang/openwrt-luci,gwlim/luci,Canaan-Creative/luci,ThingMesh/openwrt-luci,zwhfly/openwrt-luci,ThingMesh/openwrt-luci,ThingMesh/openwrt-luci,stephank/luci,Flexibity/luci,eugenesan/openwrt-luci,Canaan-Creative/luci,projectbismark/luci-bismark,ThingMesh/openwrt-luci,eugenesan/openwrt-luci,ch3n2k/luci,gwlim/luci,projectbismark/luci-bismark,stephank/luci,projectbismark/luci-bismark,stephank/luci,stephank/luci,Canaan-Creative/luci,8devices/carambola2-luci,zwhfly/openwrt-luci,Canaan-Creative/luci,jschmidlapp/luci,8devices/carambola2-luci,projectbismark/luci-bismark,vhpham80/luci,jschmidlapp/luci,phi-psi/luci,saraedum/luci-packages-old,freifunk-gluon/luci,ch3n2k/luci,phi-psi/luci,saraedum/luci-packages-old,yeewang/openwrt-luci,freifunk-gluon/luci,alxhh/piratenluci,freifunk-gluon/luci,ReclaimYourPrivacy/cloak-luci,eugenesan/openwrt-luci,zwhfly/openwrt-luci,8devices/carambola2-luci,vhpham80/luci,Flexibity/luci,dtaht/cerowrt-luci-3.3,phi-psi/luci,alxhh/piratenluci,ReclaimYourPrivacy/cloak-luci,phi-psi/luci,alxhh/piratenluci,jschmidlapp/luci,gwlim/luci,vhpham80/luci,zwhfly/openwrt-luci,phi-psi/luci,ReclaimYourPrivacy/cloak-luci,8devices/carambola2-luci,ReclaimYourPrivacy/cloak-luci,dtaht/cerowrt-luci-3.3,alxhh/piratenluci,stephank/luci,saraedum/luci-packages-old,freifunk-gluon/luci,saraedum/luci-packages-old,zwhfly/openwrt-luci,freifunk-gluon/luci,Flexibity/luci
91cbddeba755764cc4f05582769ae78ef84f5987
utils/_actions/dots.lua
utils/_actions/dots.lua
-- Based on Szymon Kaliski's code found at https://github.com/szymonkaliski/Dotfiles/blob/ae42c100a56c26bc65f6e3ca2ad36e30b558ba10/Dotfiles/hammerspoon/utils/spaces/dots.lua local spaces = require('hs._asm.undocumented.spaces') local cache = { watchers = {}, dots = {} } local module = {} module.size = 8 module.distance = 16 module.selectedAlpha = 0.95 module.alpha = 0.45 module.cache = cache module.color = { white = .7} module.draw = function() local activeSpace = spaces.activeSpace() -- FIXME: what if I remove screen, the dots are still being drawn? hs.fnutils.each(hs.screen.allScreens(), function(screen) local screenFrame = screen:fullFrame() local screenUUID = screen:spacesUUID() local screenSpaces = spaces.layout()[screenUUID] if not cache.dots[screenUUID] then cache.dots[screenUUID] = {} end for i = 1, math.max(#screenSpaces, #cache.dots[screenUUID]) do local dot if not cache.dots[screenUUID][i] then dot = hs.drawing.circle({ x = 0, y = 0, w = module.size, h = module.size }) dot :setStroke(false) :setBehaviorByLabels({ 'canJoinAllSpaces', 'stationary' }) -- :setLevel(hs.drawing.windowLevels.desktopIcon) :setLevel(hs.drawing.windowLevels.popUpMenu) else dot = cache.dots[screenUUID][i] end local x = screenFrame.w / 2 - (#screenSpaces / 2) * module.distance + i * module.distance - module.size * 3 / 2 local y = screenFrame.h - (module.distance/2) -- local y = module.distance -- local y = screenFrame.h - module.distance local alpha = screenSpaces[i] == activeSpace and module.selectedAlpha or module.alpha module.color.alpha = alpha dot :setTopLeft({ x = x, y = y }) :setFillColor(module.color) if i <= #screenSpaces then dot:show() else dot:hide() end cache.dots[screenUUID][i] = dot end end) end module.start = function() -- we need to redraw dots on screen and space events cache.watchers.spaces = hs.spaces.watcher.new(module.draw):start() cache.watchers.screen = hs.screen.watcher.new(module.draw):start() module.draw() end module.stop = function() hs.fnutils.each(cache.watchers, function(watcher) watcher:stop() end) cache.dots = {} end module.start() return module
-- Based on Szymon Kaliski's code found at https://github.com/szymonkaliski/Dotfiles/blob/ae42c100a56c26bc65f6e3ca2ad36e30b558ba10/Dotfiles/hammerspoon/utils/spaces/dots.lua local spaces = require('hs._asm.undocumented.spaces') local cache = { watchers = {}, dots = {} } local module = {} module.size = 8 module.distance = 16 module.selectedAlpha = 0.95 module.alpha = 0.45 module.cache = cache module.color = { white = .7} module.draw = function() local activeSpace = spaces.activeSpace() -- FIXME: what if I remove screen, the dots are still being drawn? hs.fnutils.each(hs.screen.allScreens(), function(screen) local screenFrame = screen:fullFrame() local screenUUID = screen:spacesUUID() local screenSpaces = spaces.layout()[screenUUID] if not cache.dots[screenUUID] then cache.dots[screenUUID] = {} end for i = 1, math.max(#screenSpaces, #cache.dots[screenUUID]) do local dot if not cache.dots[screenUUID][i] then dot = hs.drawing.circle({ x = 0, y = 0, w = module.size, h = module.size }) dot :setStroke(false) -- :setBehaviorByLabels({ 'canJoinAllSpaces', 'stationary' }) :setBehaviorByLabels({ 'canJoinAllSpaces' }) -- :setLevel(hs.drawing.windowLevels.desktopIcon) :setLevel(hs.drawing.windowLevels.popUpMenu) else dot = cache.dots[screenUUID][i] end local x = screenFrame.w / 2 - (#screenSpaces / 2) * module.distance + i * module.distance - module.size * 3 / 2 local y = screenFrame.h - (module.distance/2) -- local y = module.distance -- local y = screenFrame.h - module.distance local alpha = screenSpaces[i] == activeSpace and module.selectedAlpha or module.alpha module.color.alpha = alpha dot :setTopLeft({ x = x, y = y }) :setFillColor(module.color) if i <= #screenSpaces then dot:show() else dot:hide() end cache.dots[screenUUID][i] = dot end end) end module.start = function() -- we need to redraw dots on screen and space events cache.watchers.spaces = hs.spaces.watcher.new(module.draw):start() cache.watchers.screen = hs.screen.watcher.new(module.draw):start() module.draw() end module.stop = function() hs.fnutils.each(cache.watchers, function(watcher) watcher:stop() end) cache.dots = {} end module.start() return module
stopped showing on full-screen apps; this seems to fix it
stopped showing on full-screen apps; this seems to fix it
Lua
mit
asmagill/hammerspoon-config,asmagill/hammerspoon-config,asmagill/hammerspoon-config
00482cbc9145121a5c1a9a010d8eb38fa2d70a47
_glua-tests/os.lua
_glua-tests/os.lua
local osname = "linux" if string.find(os.getenv("OS") or "", "Windows") then osname = "windows" end if osname == "linux" then assert(os.execute("date") == 0) assert(os.execute("date -a") == 1) else assert(os.execute("date /T") == 0) assert(os.execute("md") == 1) end assert(os.getenv("PATH") ~= "") assert(os.getenv("_____GLUATEST______") == nil) assert(os.setenv("_____GLUATEST______", "1")) assert(os.getenv("_____GLUATEST______") == "1")
local osname = "linux" if string.find(os.getenv("OS") or "", "Windows") then osname = "windows" end if osname == "linux" then -- travis ci failed to start date command? -- assert(os.execute("date") == 0) assert(os.execute("date -a") == 1) else assert(os.execute("date /T") == 0) assert(os.execute("md") == 1) end assert(os.getenv("PATH") ~= "") assert(os.getenv("_____GLUATEST______") == nil) assert(os.setenv("_____GLUATEST______", "1")) assert(os.getenv("_____GLUATEST______") == "1")
fix test cases
fix test cases
Lua
mit
cokeboL/gopher-lua,insionng/gopher-lua,trigrass2/gopher-lua,toophy/gopher-lua,insionng/gopher-lua,kohkimakimoto/gopher-lua,gale320/gopher-lua,yuin/gopher-lua,yuin/gopher-lua,kohkimakimoto/gopher-lua
174dc27ea5a5cefd93bcbb54ad31cef81817e602
lunamark/writer/man.lua
lunamark/writer/man.lua
-- (c) 2009-2011 John MacFarlane. Released under MIT license. -- See the file LICENSE in the source for details. --- Groff man writer for lunamark. -- Extends [lunamark.writer.groff]. -- -- Note: continuation paragraphs in lists are not -- handled properly. local M = {} local groff = require("lunamark.writer.groff") local util = require("lunamark.util") local gsub = string.gsub local format = string.format --- Returns a new groff writer. -- For a list of fields, see [lunamark.writer.generic]. function M.new(options) local options = options or {} local Man = groff.new(options) local endnotes = {} function Man.link(lab,src,tit) return format("%s (%s)",lab,src) end function Man.image(lab,src,tit) return format("[IMAGE (%s)]",lab) end -- TODO handle continuations properly. -- pandoc does this: -- .IP \[bu] 2 -- one -- .RS 2 -- .PP -- cont -- .RE function Man.paragraph(contents) return format(".PP\n%s", contents) end function Man.bulletlist(items,tight) local buffer = {} for _,item in ipairs(items) do buffer[#buffer + 1] = format(".IP \[bu] 2\n%s",item) end return table.concat(buffer, Man.containersep) end function Man.orderedlist(items,tight,startnum) local buffer = {} local num = startnum or 1 for _,item in ipairs(items) do buffer[#buffer + 1] = format(".IP \"%d.\" 4\n%s",num,item) num = num + 1 end return table.concat(buffer, Man.containersep) end function Man.blockquote(s) return format(".RS\n%s\n.RE", s) end function Man.verbatim(s) return format(".IP\n.nf\n\\f[C]\n%s.fi",s) end function Man.section(s,level,contents) local hcode = ".SS" if level == 1 then hcode = ".SH" end return format("%s %s\n%s", hcode, s, contents) end Man.hrule = ".PP\n * * * * *" function Man.note(contents) local num = #endnotes + 1 endnotes[num] = format('.SS [%d]\n%s', num, contents) return format('[%d]', num) end function Man.definitionlist(items) local buffer = {} for _,item in ipairs(items) do buffer[#buffer + 1] = format(".TP\n.B %s\n%s\n.RS\n.RE", item.term, table.concat(item.definitions, "\n.RS\n.RE\n")) end local contents = table.concat(buffer, "\n") return contents end function Man.start_document() endnotes = {} return "" end function Man.stop_document() if #endnotes == 0 then return "" else return format('\n.SH NOTES\n%s', table.concat(endnotes, "\n")) end end Man.template = [===[ .TH "$title" "$section" "$date" "$left_footer" "$center_header" $body ]===] return Man end return M
-- (c) 2009-2011 John MacFarlane. Released under MIT license. -- See the file LICENSE in the source for details. --- Groff man writer for lunamark. -- Extends [lunamark.writer.groff]. -- -- Note: continuation paragraphs in lists are not -- handled properly. local M = {} local groff = require("lunamark.writer.groff") local util = require("lunamark.util") local gsub = string.gsub local format = string.format --- Returns a new groff writer. -- For a list of fields, see [lunamark.writer.generic]. function M.new(options) local options = options or {} local Man = groff.new(options) local endnotes = {} function Man.link(lab,src,tit) return format("%s (%s)",lab,src) end function Man.image(lab,src,tit) return format("[IMAGE (%s)]",lab) end -- TODO handle continuations properly. -- pandoc does this: -- .IP \[bu] 2 -- one -- .RS 2 -- .PP -- cont -- .RE function Man.paragraph(contents) return format(".PP\n%s", contents) end function Man.bulletlist(items,tight) local buffer = {} for _,item in ipairs(items) do buffer[#buffer + 1] = format(".IP \\[bu] 2\n%s",item) end return table.concat(buffer, Man.containersep) end function Man.orderedlist(items,tight,startnum) local buffer = {} local num = startnum or 1 for _,item in ipairs(items) do buffer[#buffer + 1] = format(".IP \"%d.\" 4\n%s",num,item) num = num + 1 end return table.concat(buffer, Man.containersep) end function Man.blockquote(s) return format(".RS\n%s\n.RE", s) end function Man.verbatim(s) return format(".IP\n.nf\n\\f[C]\n%s.fi",s) end function Man.section(s,level,contents) local hcode = ".SS" if level == 1 then hcode = ".SH" end return format("%s %s\n%s", hcode, s, contents) end Man.hrule = ".PP\n * * * * *" function Man.note(contents) local num = #endnotes + 1 endnotes[num] = format('.SS [%d]\n%s', num, contents) return format('[%d]', num) end function Man.definitionlist(items,tight) local buffer = {} local fmt if tight then fmt = ".TP\n.B %s\n%s\n.RS\n.RE" else fmt = ".TP\n.B %s\n.RS\n%s\n.RE" end for _,item in ipairs(items) do buffer[#buffer + 1] = format(fmt, item.term, table.concat(item.definitions, "\n.RS\n.RE\n")) end local contents = table.concat(buffer, "\n") return contents end function Man.start_document() endnotes = {} return "" end function Man.stop_document() if #endnotes == 0 then return "" else return format('\n.SH NOTES\n%s', table.concat(endnotes, "\n")) end end Man.template = [===[ .TH "$title" "$section" "$date" "$left_footer" "$center_header" $body ]===] return Man end return M
Fixed bullet and definition lists in man output.
Fixed bullet and definition lists in man output.
Lua
mit
jgm/lunamark,tst2005/lunamark,simoncozens/lunamark,jgm/lunamark,tst2005/lunamark,simoncozens/lunamark,jgm/lunamark,tst2005/lunamark,simoncozens/lunamark
819d75afa5d67630f130fa14a0d523b0b3400401
data/dist/shooter/main.lua
data/dist/shooter/main.lua
oldprint = print print = function(...) local args = { n = select("#", ...), ... } local t = "" for i=1,args.n do t = t .. tostring(args[i]) end oldprint(t) end print('Hello world') IsDown = function(key) return key.state > 0.1 end WasDown = function(key) return key.last_state > 0.1 end JustPressed = function(key) return IsDown(key) and not WasDown(key) end StarRandom = Math.NewRandom() Types = { Pos2= Registry.GetPosition2Id(), Sprite= Registry.GetSpriteId(), Player= Registry.New("Player"), MoveUp= Registry.New("MoveUp"), Star= Registry.New("Star", function(args) c = {} c.speed = args:GetNumber("speed") + StarRandom:NextRangeFloat(args:GetNumber("random_boost")) return c end), DestroyOutside= Registry.New("DestroyOutside"), TimeOut= Registry.New("TimeOut", function() c = {} c.time = 4 return c end) } -- todo: create some on init callback, to spawn the stars -- or enter level callback -- or init callback on entity that is directly destroyed, or keep spawning points -- move sprite anchor to config Systems.OnInit("place star", {Types.Pos2, Types.Star}, function(entity) local vec = Registry.GetPosition2vec(entity) local p = StarRandom:NextPoint2(Camera.GetRect()) vec.x = p.x vec.y = p.y end) Systems.AddUpdate("star movement", function(dt) local ents = Registry.Entities({Types.Sprite, Types.Star}) for _, entity in pairs(ents) do local star = Registry.Get(entity, Types.Star) local vec = Registry.GetPosition2vec(entity) if vec ~= null then vec.y = vec.y - dt * star.speed; local vy = vec.y -- print("Moving star to ", vy) if vy < 0.0 then vec.x = StarRandom:NextRangeFloat(Camera.GetRect():GetWidth()) vec.y = vec.y + Camera.GetRect():GetHeight() print("Reseting star to ", vec.x, " ", vec.y) end end end end) -- todo: new update function -- Systems.OnUpdate("move up", [Types.Pos2, Types.MoveUp], function(dt, entities) { }); time = 0 bark = 0 Systems.AddUpdate("bark", function(dt) time = time + dt if time>1 then time = time - 1 bark = bark + 1 print('Bark!', bark) end end) Systems.AddUpdate("move up", function(dt) local ents = Registry.Entities({Types.Pos2, Types.MoveUp}) for _, entity in pairs(ents) do local vec = Registry.GetPosition2vec(entity) if vec ~= null then local speed = 250 vec.y = vec.y + dt * speed end end end) Systems.AddUpdate("time out", function(dt) local ents = Registry.Entities({Types.TimeOut}); for _, entity in pairs(ents) do local data = Registry.Get(entity, Types.TimeOut) data.time = data.time - dt if data.time < 0 then print("Timeout") Registry.DestroyEntity(entity) end end end) Systems.AddUpdate("destroy outside", function (dt) local ents = Registry.Entities({Types.Sprite, Types.Pos2, Types.DestroyOutside}) for _, entity in pairs(ents) do local sp = Registry.GetSprite(entity) local p = Registry.GetPosition2(entity) if sp ~= null then local cam = Camera.GetRect() local r = sp.GetRect(p) if not cam:Contains(r) then Registry.DestroyEntity(entity) end end end end) shotTemplate = Templates.Find("shot") Systems.AddUpdate("player", function(dt) ents = Registry.Entities({Types.Pos2, Types.Player}) for _, entity in pairs(ents) do local vec = Registry.GetPosition2vec(entity) if vec ~= null then local speed = 150 local vertical = Input.up.state - Input.down.state local horizontal = Input.right.state - Input.left.state if JustPressed(Input.fire) then if not shotTemplate then print("no shot") else local shot = shotTemplate:Create() local v = Registry.GetPosition2vec(shot) if v ~= null then v.x = vec.x v.y = vec.y end end end vec.y = vec.y + dt * speed * vertical vec.x = vec.x + dt * speed * horizontal end end end)
oldprint = print print = function(...) local args = { n = select("#", ...), ... } local t = "" for i=1,args.n do t = t .. tostring(args[i]) end oldprint(t) end print('Hello world') IsDown = function(key) return key.state > 0.1 end WasDown = function(key) return key.last_state > 0.1 end JustPressed = function(key) return IsDown(key) and not WasDown(key) end StarRandom = Math.NewRandom() Types = { Pos2= Registry.GetPosition2Id(), Sprite= Registry.GetSpriteId(), Player= Registry.New("Player"), MoveUp= Registry.New("MoveUp"), Star= Registry.New("Star", function(args) c = {} c.speed = args:GetNumber("speed") + StarRandom:NextRangeFloat(args:GetNumber("random_boost")) return c end), DestroyOutside= Registry.New("DestroyOutside"), TimeOut= Registry.New("TimeOut", function() c = {} c.time = 4 return c end) } -- todo: create some on init callback, to spawn the stars -- or enter level callback -- or init callback on entity that is directly destroyed, or keep spawning points -- move sprite anchor to config Systems.OnInit("place star", {Types.Pos2, Types.Star}, function(entity) local vec = Registry.GetPosition2vec(entity) local p = StarRandom:NextPoint2(Camera.GetRect()) vec.x = p.x vec.y = p.y end) Systems.AddUpdate("star movement", function(dt) local ents = Registry.Entities({Types.Sprite, Types.Star}) for _, entity in pairs(ents) do local star = Registry.Get(entity, Types.Star) local vec = Registry.GetPosition2vec(entity) if vec ~= null then vec.y = vec.y - dt * star.speed; if vec.y < 0 then vec.x = StarRandom:NextRangeFloat(Camera.GetRect():GetWidth()) vec.y = vec.y + Camera.GetRect():GetHeight() end end end end) -- todo: new update function -- Systems.OnUpdate("move up", [Types.Pos2, Types.MoveUp], function(dt, entities) { }); time = 0 bark = 0 Systems.AddUpdate("bark", function(dt) time = time + dt if time>1 then time = time - 1 bark = bark + 1 print('Bark!', bark) end end) Systems.AddUpdate("move up", function(dt) local ents = Registry.Entities({Types.Pos2, Types.MoveUp}) for _, entity in pairs(ents) do local vec = Registry.GetPosition2vec(entity) if vec ~= null then local speed = 250 vec.y = vec.y + dt * speed end end end) Systems.AddUpdate("time out", function(dt) local ents = Registry.Entities({Types.TimeOut}); for _, entity in pairs(ents) do local data = Registry.Get(entity, Types.TimeOut) data.time = data.time - dt if data.time < 0 then print("Timeout") Registry.DestroyEntity(entity) end end end) Systems.AddUpdate("destroy outside", function (dt) local ents = Registry.Entities({Types.Sprite, Types.Pos2, Types.DestroyOutside}) for _, entity in pairs(ents) do local sp = Registry.GetSprite(entity) local p = Registry.GetPosition2(entity) if sp ~= null then local cam = Camera.GetRect() local r = sp:GetRect(p) if not cam:Contains(r) then Registry.DestroyEntity(entity) end end end end) shotTemplate = Templates.Find("shot") Systems.AddUpdate("player", function(dt) ents = Registry.Entities({Types.Pos2, Types.Player}) for _, entity in pairs(ents) do local vec = Registry.GetPosition2vec(entity) if vec ~= null then local speed = 150 local vertical = Input.up.state - Input.down.state local horizontal = Input.right.state - Input.left.state if JustPressed(Input.fire) then if not shotTemplate then print("no shot") else local shot = shotTemplate:Create() local v = Registry.GetPosition2vec(shot) if v ~= null then v.x = vec.x v.y = vec.y end end end vec.y = vec.y + dt * speed * vertical vec.x = vec.x + dt * speed * horizontal end end end)
last lua fixes for now... shooter runs fine :)
last lua fixes for now... shooter runs fine :)
Lua
mit
madeso/euphoria,madeso/euphoria,madeso/euphoria,madeso/euphoria,madeso/euphoria,madeso/euphoria
ad3fd652150f27f9902aaeb52263d0ad8f30e87e
controllers/dynamic.lua
controllers/dynamic.lua
--[[ Dynamic Resource Controller Adjusts the number of threads executing within each stage. The goal is to avoid allocating too many threads, but still have enough threads to meet the concurrency demands of the stage. The controller periodically samples the input queue and adds a thread when the queue length exceeds some threshold, up to a maximum number of threads per stage. Threads are removed from a stage when they are idle for a specified period of time. Reference: http://www.eecs.harvard.edu/~mdw/papers/seda-sosp01.pdf **************************************** PUC-RIO 2014 **************************************** Implemented by: - Ana Lúcia de Moura - Breno Riba - Noemi Rodriguez - Tiago Salmito Implemented on May 2014 ********************************************************************************************** ]]-- local lstage = require 'lstage' local pool = require 'lstage.pool' local dynamic = {} local stages = {} --[[ <summary> Dynamic Resource Controller configure method </summary> <param name="stagesTable">LEDA stages table</param> <param name="refreshSeconds">Time (in seconds) to refresh stage's rate</param> ]]-- function dynamic.configure (stagesTable, refreshSeconds) stages = stagesTable -- Creating a pool per stage for index=1,#stages do -- New pool local currentPool=pool.new(0) currentPool:add(stages[index].minThreads) -- Set this pool to stage stages[index].stage:setpool(currentPool) stages[index].pool = currentPool end -- Every "refreshSeconds" with ID = 100 lstage.add_timer(refreshSeconds, 100) end --[[ <summary> Used to refresh stage's rate </summary> <param name="id">Timer ID</param> ]]-- on_timer=function(id) -- Validate ID number if (id ~= 100) then return end -- Check stage's queue for index=1,#stages do local current = stages[index] local stage = current.stage local queueSize = stage:size() local currentPool = current.pool -- Check queue threshold and compare current pool size with -- max number of threads per stage if (queueSize >= current.queueThreshold and currentPool:size() < current.maxThreads) then -- We have to add one more thread currentPool:add(1) -- Stage is IDLE - so we have to kill a thread elseif (queueSize == 0 and currentPool:size() > current.minThreads) then currentPool:kill() end end end return dynamic
--[[ Dynamic Resource Controller Adjusts the number of threads executing within each stage. The goal is to avoid allocating too many threads, but still have enough threads to meet the concurrency demands of the stage. The controller periodically samples the input queue and adds a thread when the queue length exceeds some threshold, up to a maximum number of threads per stage. Threads are removed from a stage when they are idle for a specified period of time. Reference: http://www.eecs.harvard.edu/~mdw/papers/seda-sosp01.pdf **************************************** PUC-RIO 2014 **************************************** Implemented by: - Ana Lúcia de Moura - Breno Riba - Noemi Rodriguez - Tiago Salmito Implemented on May 2014 ********************************************************************************************** ]]-- local lstage = require 'lstage' local pool = require 'lstage.pool' local dynamic = {} local stages = {} --[[ <summary> Dynamic Resource Controller configure method </summary> <param name="stagesTable">LEDA stages table</param> <param name="refreshSeconds">Time (in seconds) to refresh stage's rate</param> ]]-- function dynamic.configure (stagesTable, refreshSeconds) stages = stagesTable -- Creating a pool per stage for index=1,#stages do -- New pool local currentPool=pool.new(0) currentPool:add(stages[index].minThreads) -- Set this pool to stage stages[index].stage:setpool(currentPool) stages[index].pool = currentPool end -- Every "refreshSeconds" with ID = 100 lstage.add_timer(refreshSeconds, 100) end --[[ <summary> Used to refresh stage's rate </summary> <param name="id">Timer ID</param> ]]-- on_timer=function(id) -- Validate ID number if (id ~= 100) then return end -- Initialize vars local current = nil local stage = nil local queueSize = nil local currentPool = nil local poolSize = nil -- Check stage's queue for index=1,#stages do current = stages[index] stage = current.stage queueSize = stage:size() currentPool = current.pool poolSize = currentPool:size() -- Check queue threshold and compare current pool size with -- max number of threads per stage if (queueSize >= current.queueThreshold and poolSize < current.maxThreads) then -- We have to add one more thread currentPool:add(1) -- Stage is IDLE - so we have to kill a thread elseif (queueSize == 0 and poolSize > current.minThreads) then currentPool:kill() end end end return dynamic
Fixes
Fixes
Lua
mit
brenoriba/lstage,brenoriba/lstage
3afc56812074b1a3b16975bfea8abaca540ab809
extensions/spoons/init.lua
extensions/spoons/init.lua
local module={} --- === hs.spoons === --- --- Utility and management functions for spoons module._keys = {} -- Interpolate table values into a string -- From http://lua-users.org/wiki/StringInterpolation local function interp(s, tab) return (s:gsub('($%b{})', function(w) return tab[w:sub(3, -2)] or w end)) end -- Read a whole file into a string local function slurp(path) local f = assert(io.open(path)) local s = f:read("*a") f:close() return s end --- hs.spoons.newSpoon(name, basedir, metadata) --- Method --- Create a skeleton for a new Spoon --- --- Parameters: --- * name: name of the new spoon, without the `.spoon` extension --- * basedir: (optional) directory where to create the template. Defaults to `~/.hammerspoon/Spoons` --- * metadata: (optional) table containing metadata values to be inserted in the template. Provided values are merged with the defaults. Defaults to: --- ``` --- { --- version = "0.1", --- author = "Your Name <your@email.org>", --- homepage = "https://github.com/Hammerspoon/Spoons", --- license = "MIT - https://opensource.org/licenses/MIT", --- download_url = "https://github.com/Hammerspoon/Spoons/raw/master/Spoons/"..name..".spoon.zip" --- } --- ``` --- * template: (optional) absolute path of the template to use for the `init.lua` file of the new Spoon. Defaults to the `templates/init.tpl` file included with Hammerspoon. --- --- Returns: --- * The full directory path where the template was created, or `nil` if there was an error. function module.newSpoon(name, basedir, metadata, template) if basedir == nil or basedir == "" then basedir = hs.configdir .. "/Spoons" end local meta={ version = "0.1", author = "Your Name <your@email.org>", homepage = "https://github.com/Hammerspoon/Spoons", license = "MIT - https://opensource.org/licenses/MIT", download_url = "https://github.com/Hammerspoon/Spoons/raw/master/Spoons/"..name..".spoon.zip", description = "A new Sample Spoon" } if metadata then for k,v in pairs(metadata) do meta[k] = v end end meta["name"]=name local dirname = basedir .. "/" .. name .. ".spoon" if hs.fs.mkdir(dirname) and hs.fs.chdir(dirname) then local f=assert(io.open(dirname .. "/init.lua", "w")) local template_file = template or module.resource_path("templates/init.tpl") local text=slurp(template_file) f:write(interp(text, meta)) f:close() return dirname end return nil end --- hs.spoons.script_path() --- Method --- Return path of the current spoon. --- --- Parameters: --- * n - (optional) stack level for which to get the path. Defaults to 2, which will return the path of the spoon which called `script_path()` --- --- Returns: --- * String with the path from where the calling code was loaded. function module.script_path(n) if n == nil then n = 2 end local str = debug.getinfo(n, "S").source:sub(2) return str:match("(.*/)") end --- hs.spoons.resource_path(partial) --- Method --- Return full path of an object within a spoon directory, given its partial path. --- --- Parameters: --- * partial - path of a file relative to the Spoon directory. For example `images/img1.png` will refer to a file within the `images` directory of the Spoon. --- --- Returns: --- * Absolute path of the file. Note: no existence or other checks are done on the path. function module.resource_path(partial) return(module.script_path(3) .. partial) end --- hs.spoons.bindHotkeysToSpec(def, map) --- Method --- Map a number of hotkeys according to a definition table --- --- Parameters: --- * def - table containing name-to-function definitions for the hotkeys supported by the Spoon. Each key is a hotkey name, and its value must be a function that will be called when the hotkey is invoked. --- * map - table containing name-to-hotkey definitions, as supported by [bindHotkeys in the Spoon API](https://github.com/Hammerspoon/hammerspoon/blob/master/SPOONS.md#hotkeys). Not all the entries in `def` must be bound, but if any keys in `map` don't have a definition, an error will be produced. --- --- Returns: --- * None function module.bindHotkeysToSpec(def,map) local spoonpath = module.script_path(3) for name,key in pairs(map) do if def[name] ~= nil then local keypath = spoonpath .. name if module._keys[keypath] then module._keys[keypath]:delete() end module._keys[keypath]=hs.hotkey.bindSpec(key, def[name]) else module.logger.ef("Error: Hotkey requested for undefined action '%s'", name) end end end --- hs.spoons.list() --- Method --- Return a list of installed/loaded Spoons --- --- Parameters: --- * only_loaded - only return loaded Spoons (skips those that are installed but not loaded). Defaults to `false` --- --- Returns: --- * Table with a list of installed/loaded spoons (depending on the value of `only_loaded`). Each entry is a table with the following entries: --- * `name` - Spoon name --- * `loaded` - boolean indication of whether the Spoon is loaded (`true`) or only installed (`false`) --- * `version` - Spoon version number. Available only for loaded Spoons. function module.list(only_loaded) local iterfn, dirobj = hs.fs.dir(hs.configdir .. "/Spoons") local res = {} repeat local f = dirobj:next() if f then if string.match(f, ".spoon$") then local s = f:gsub(".spoon$", "") local l = (spoon[s] ~= nil) if (not only_loaded) or l then local new = { name = s, loaded = l } if l then new.version = spoon[s].version end table.insert(res, new) end end end until f == nil return res end --- hs.spoons.printList() --- Method --- Print a list of installed/loaded Spoons. Has the same interface as `list()` but prints the list instead of returning it. --- --- Parameters: --- * only_loaded - only return loaded Spoons (skips those that are installed but not loaded). Defaults to `false` --- --- Returns: --- * None function module.printList(only_loaded) local list = module.list(only_loaded) for i,s in ipairs(list) do local lstr = " - installed" if s.loaded then lstr = " " .. s.version .. " loaded" end print(s.name .. lstr) end end return module
local module={} --- === hs.spoons === --- --- Utility and management functions for spoons module._keys = {} local log = hs.logger.new("spoons") -- Interpolate table values into a string -- From http://lua-users.org/wiki/StringInterpolation local function interp(s, tab) return (s:gsub('($%b{})', function(w) return tab[w:sub(3, -2)] or w end)) end -- Read a whole file into a string local function slurp(path) local f = assert(io.open(path)) local s = f:read("*a") f:close() return s end --- hs.spoons.newSpoon(name, basedir, metadata) --- Method --- Create a skeleton for a new Spoon --- --- Parameters: --- * name: name of the new spoon, without the `.spoon` extension --- * basedir: (optional) directory where to create the template. Defaults to `~/.hammerspoon/Spoons` --- * metadata: (optional) table containing metadata values to be inserted in the template. Provided values are merged with the defaults. Defaults to: --- ``` --- { --- version = "0.1", --- author = "Your Name <your@email.org>", --- homepage = "https://github.com/Hammerspoon/Spoons", --- license = "MIT - https://opensource.org/licenses/MIT", --- download_url = "https://github.com/Hammerspoon/Spoons/raw/master/Spoons/"..name..".spoon.zip" --- } --- ``` --- * template: (optional) absolute path of the template to use for the `init.lua` file of the new Spoon. Defaults to the `templates/init.tpl` file included with Hammerspoon. --- --- Returns: --- * The full directory path where the template was created, or `nil` if there was an error. function module.newSpoon(name, basedir, metadata, template) -- Default value for basedir if basedir == nil or basedir == "" then basedir = hs.configdir .. "/Spoons/" end -- Ensure basedir ends with a slash if not string.find(basedir, "/$") then basedir = basedir .. "/" end local meta={ version = "0.1", author = "Your Name <your@email.org>", homepage = "https://github.com/Hammerspoon/Spoons", license = "MIT - https://opensource.org/licenses/MIT", download_url = "https://github.com/Hammerspoon/Spoons/raw/master/Spoons/"..name..".spoon.zip", description = "A new Sample Spoon" } if metadata then for k,v in pairs(metadata) do meta[k] = v end end meta["name"]=name local dirname = basedir .. name .. ".spoon" if hs.fs.mkdir(dirname) then local f=assert(io.open(dirname .. "/init.lua", "w")) local template_file = template or module.resource_path("templates/init.tpl") local text=slurp(template_file) f:write(interp(text, meta)) f:close() return dirname end return nil end --- hs.spoons.script_path() --- Method --- Return path of the current spoon. --- --- Parameters: --- * n - (optional) stack level for which to get the path. Defaults to 2, which will return the path of the spoon which called `script_path()` --- --- Returns: --- * String with the path from where the calling code was loaded. function module.script_path(n) if n == nil then n = 2 end local str = debug.getinfo(n, "S").source:sub(2) return str:match("(.*/)") end --- hs.spoons.resource_path(partial) --- Method --- Return full path of an object within a spoon directory, given its partial path. --- --- Parameters: --- * partial - path of a file relative to the Spoon directory. For example `images/img1.png` will refer to a file within the `images` directory of the Spoon. --- --- Returns: --- * Absolute path of the file. Note: no existence or other checks are done on the path. function module.resource_path(partial) return(module.script_path(3) .. partial) end --- hs.spoons.bindHotkeysToSpec(def, map) --- Method --- Map a number of hotkeys according to a definition table --- --- Parameters: --- * def - table containing name-to-function definitions for the hotkeys supported by the Spoon. Each key is a hotkey name, and its value must be a function that will be called when the hotkey is invoked. --- * map - table containing name-to-hotkey definitions, as supported by [bindHotkeys in the Spoon API](https://github.com/Hammerspoon/hammerspoon/blob/master/SPOONS.md#hotkeys). Not all the entries in `def` must be bound, but if any keys in `map` don't have a definition, an error will be produced. --- --- Returns: --- * None function module.bindHotkeysToSpec(def,map) local spoonpath = module.script_path(3) for name,key in pairs(map) do if def[name] ~= nil then local keypath = spoonpath .. name if module._keys[keypath] then module._keys[keypath]:delete() end module._keys[keypath]=hs.hotkey.bindSpec(key, def[name]) else log.ef("Error: Hotkey requested for undefined action '%s'", name) end end end --- hs.spoons.list() --- Method --- Return a list of installed/loaded Spoons --- --- Parameters: --- * only_loaded - only return loaded Spoons (skips those that are installed but not loaded). Defaults to `false` --- --- Returns: --- * Table with a list of installed/loaded spoons (depending on the value of `only_loaded`). Each entry is a table with the following entries: --- * `name` - Spoon name --- * `loaded` - boolean indication of whether the Spoon is loaded (`true`) or only installed (`false`) --- * `version` - Spoon version number. Available only for loaded Spoons. function module.list(only_loaded) local iterfn, dirobj = hs.fs.dir(hs.configdir .. "/Spoons") local res = {} repeat local f = dirobj:next() if f then if string.match(f, ".spoon$") then local s = f:gsub(".spoon$", "") local l = (spoon[s] ~= nil) if (not only_loaded) or l then local new = { name = s, loaded = l } if l then new.version = spoon[s].version end table.insert(res, new) end end end until f == nil return res end --- hs.spoons.printList() --- Method --- Print a list of installed/loaded Spoons. Has the same interface as `list()` but prints the list instead of returning it. --- --- Parameters: --- * only_loaded - only return loaded Spoons (skips those that are installed but not loaded). Defaults to `false` --- --- Returns: --- * None function module.printList(only_loaded) local list = module.list(only_loaded) for i,s in ipairs(list) do local lstr = " - installed" if s.loaded then lstr = " " .. s.version .. " loaded" end print(s.name .. lstr) end end return module
Clean up and bug fixes
Clean up and bug fixes - Fixed bug in path handling - Cleaned up code
Lua
mit
knu/hammerspoon,bradparks/hammerspoon,Hammerspoon/hammerspoon,Habbie/hammerspoon,Hammerspoon/hammerspoon,Habbie/hammerspoon,knu/hammerspoon,asmagill/hammerspoon,knu/hammerspoon,Hammerspoon/hammerspoon,bradparks/hammerspoon,cmsj/hammerspoon,asmagill/hammerspoon,knu/hammerspoon,latenitefilms/hammerspoon,Hammerspoon/hammerspoon,asmagill/hammerspoon,latenitefilms/hammerspoon,bradparks/hammerspoon,cmsj/hammerspoon,CommandPost/CommandPost-App,Habbie/hammerspoon,CommandPost/CommandPost-App,asmagill/hammerspoon,cmsj/hammerspoon,zzamboni/hammerspoon,Habbie/hammerspoon,Habbie/hammerspoon,zzamboni/hammerspoon,zzamboni/hammerspoon,cmsj/hammerspoon,Habbie/hammerspoon,CommandPost/CommandPost-App,latenitefilms/hammerspoon,latenitefilms/hammerspoon,cmsj/hammerspoon,bradparks/hammerspoon,zzamboni/hammerspoon,zzamboni/hammerspoon,asmagill/hammerspoon,knu/hammerspoon,knu/hammerspoon,latenitefilms/hammerspoon,CommandPost/CommandPost-App,latenitefilms/hammerspoon,Hammerspoon/hammerspoon,CommandPost/CommandPost-App,zzamboni/hammerspoon,asmagill/hammerspoon,Hammerspoon/hammerspoon,cmsj/hammerspoon,bradparks/hammerspoon,CommandPost/CommandPost-App
8544a4db9bbfffb1cb4d5555c0a2bd74f1b1dceb
hammerspoon/config.lua
hammerspoon/config.lua
-- hyper key hyper = { 'alt', 'ctrl', 'cmd' } -- disable anymations hs.window.animationDuration = 0 -- middle left hs.hotkey.bind(hyper, "Left", function() local win = hs.window.focusedWindow() local f = win:frame() local screen = win:screen() local max = screen:frame() f.x = max.x f.y = max.y f.w = max.w / 2 f.h = max.h win:setFrame(f) end) -- middle right hs.hotkey.bind(hyper, "Right", function() local win = hs.window.focusedWindow() local f = win:frame() local screen = win:screen() local max = screen:frame() f.x = max.x + (max.w / 2) f.y = max.y f.w = max.w / 2 f.h = max.h win:setFrame(f) end) -- centralize at 80% screen size hs.hotkey.bind(hyper, 'C', function() local win = hs.window.focusedWindow() local f = win:frame() local max = win:screen():frame() f.x = max.x * 0.8 f.y = max.y * 0.8 f.w = max.w * 0.8 f.h = max.h * 0.8 win:setFrame(f) win:centerOnScreen() end) -- maximize hs.hotkey.bind(hyper, 'M', function() local win = hs.window.focusedWindow() local f = win:frame() local max = win:screen():frame() f.x = max.x f.y = max.y f.w = max.w f.h = max.h win:setFrame(f) end)
local hotkey = require "hs.hotkey" -- hyper key hyper = { 'alt', 'ctrl', 'cmd' } -- disable anymations hs.window.animationDuration = 0 -- middle left hotkey.bind(hyper, "Left", function() local win = hs.window.focusedWindow() local f = win:frame() local screen = win:screen() local max = screen:frame() f.x = max.x f.y = max.y f.w = max.w / 2 f.h = max.h win:setFrame(f) end) -- middle right hotkey.bind(hyper, "Right", function() local win = hs.window.focusedWindow() local f = win:frame() local screen = win:screen() local max = screen:frame() f.x = max.x + (max.w / 2) f.y = max.y f.w = max.w / 2 f.h = max.h win:setFrame(f) end) -- centralize at 80% screen size hotkey.bind(hyper, 'C', function() local win = hs.window.focusedWindow() local f = win:frame() local max = win:screen():frame() f.x = max.x * 0.8 f.y = max.y * 0.8 f.w = max.w * 0.8 f.h = max.h * 0.8 win:setFrame(f) win:centerOnScreen() end) -- maximize hotkey.bind(hyper, 'M', function() local win = hs.window.focusedWindow() local f = win:frame() local max = win:screen():frame() f.x = max.x f.y = max.y f.w = max.w f.h = max.h win:setFrame(f) end)
fix(hammerspoon): improved config
fix(hammerspoon): improved config Signed-off-by: Carlos Alexandro Becker <e0d37fc92b01fb634d204904d4d347b3805c9003@gmail.com>
Lua
mit
caarlos0/dotfiles
a0a8d6e6610044b85160e56225c72f50d79611a4
busted/outputHandlers/junit.lua
busted/outputHandlers/junit.lua
local xml = require 'pl.xml' local socket = require("socket") local string = require("string") return function(options, busted) local handler = require 'busted.outputHandlers.base'(busted) local xml_doc local suiteStartTime, suiteEndTime handler.suiteStart = function() suiteStartTime = socket.gettime() xml_doc = xml.new('testsuite', { tests = 0, errors = 0, failures = 0, skip = 0, }) return nil, true end local function now() return string.format("%.2f", (socket.gettime() - suiteStartTime)) end handler.suiteEnd = function() xml_doc.attr.time = now() print(xml.tostring(xml_doc, '', '\t', nil, false)) return nil, true end handler.testEnd = function(element, parent, status) xml_doc.attr.tests = xml_doc.attr.tests + 1 local testcase_node = xml.new('testcase', { classname = element.trace.short_src .. ':' .. element.trace.currentline, name = handler.getFullName(element), time = now() }) xml_doc:add_direct_child(testcase_node) if status == 'failure' then xml_doc.attr.failures = xml_doc.attr.failures + 1 testcase_node:addtag('failure') testcase_node:text(element.trace.traceback) testcase_node:up() end return nil, true end handler.errorFile = function() if status == 'failure' then xml_doc.attr.errors = xml_doc.attr.errors + 1 end xml_doc:addtag('failure', {}):text(trace.traceback):up() return nil, true end busted.subscribe({ 'suite', 'start' }, handler.suiteStart) busted.subscribe({ 'suite', 'end' }, handler.suiteEnd) busted.subscribe({ 'test', 'end' }, handler.testEnd, { predicate = handler.cancelOnPending }) busted.subscribe({ 'error', 'file' }, handler.errorFile) return handler end
local xml = require 'pl.xml' local socket = require("socket") local string = require("string") return function(options, busted) local handler = require 'busted.outputHandlers.base'(busted) local xml_doc local suiteStartTime, suiteEndTime handler.suiteStart = function() suiteStartTime = socket.gettime() xml_doc = xml.new('testsuite', { tests = 0, errors = 0, failures = 0, skip = 0, }) return nil, true end local function now() return string.format("%.2f", (socket.gettime() - suiteStartTime)) end handler.suiteEnd = function() xml_doc.attr.time = now() print(xml.tostring(xml_doc, '', '\t', nil, false)) return nil, true end handler.testEnd = function(element, parent, status) xml_doc.attr.tests = xml_doc.attr.tests + 1 local testcase_node = xml.new('testcase', { classname = element.trace.short_src .. ':' .. element.trace.currentline, name = handler.getFullName(element), time = now() }) xml_doc:add_direct_child(testcase_node) if status == 'failure' then xml_doc.attr.failures = xml_doc.attr.failures + 1 testcase_node:addtag('failure') testcase_node:text(element.trace.traceback) testcase_node:up() end return nil, true end handler.errorFile = function(element, parent, message, trace) xml_doc.attr.errors = xml_doc.attr.errors + 1 xml_doc:addtag('error') xml_doc:text(trace.traceback) xml_doc:up() return nil, true end busted.subscribe({ 'suite', 'start' }, handler.suiteStart) busted.subscribe({ 'suite', 'end' }, handler.suiteEnd) busted.subscribe({ 'test', 'end' }, handler.testEnd, { predicate = handler.cancelOnPending }) busted.subscribe({ 'error', 'file' }, handler.errorFile) busted.subscribe({ 'failure', 'file' }, handler.errorFile) return handler end
Fix junit output for file errors
Fix junit output for file errors
Lua
mit
ryanplusplus/busted,nehz/busted,leafo/busted,o-lim/busted,istr/busted,xyliuke/busted,mpeterv/busted,DorianGray/busted,Olivine-Labs/busted,sobrinho/busted
46c61acd06b3c54f3d98fa809e4b9450bae04975
modules/admin-full/luasrc/model/cbi/admin_system/fstab/mount.lua
modules/admin-full/luasrc/model/cbi/admin_system/fstab/mount.lua
--[[ LuCI - Lua Configuration Interface Copyright 2010 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local fs = require "nixio.fs" local util = require "nixio.util" local has_extroot = fs.access("/lib/preinit/00_extroot.conf") local has_fscheck = fs.access("/lib/functions/fsck.sh") local devices = {} util.consume((fs.glob("/dev/sd*")), devices) util.consume((fs.glob("/dev/hd*")), devices) util.consume((fs.glob("/dev/scd*")), devices) util.consume((fs.glob("/dev/mmc*")), devices) local size = {} for i, dev in ipairs(devices) do local s = tonumber((fs.readfile("/sys/class/block/%s/size" % dev:sub(6)))) size[dev] = s and math.floor(s / 2048) end m = Map("fstab", translate("Mount Points - Mount Entry")) m.redirect = luci.dispatcher.build_url("admin/system/fstab") if not arg[1] or m.uci:get("fstab", arg[1]) ~= "mount" then luci.http.redirect(m.redirect) return end mount = m:section(NamedSection, arg[1], "mount", translate("Mount Entry")) mount.anonymous = true mount.addremove = false mount:tab("general", translate("General Settings")) mount:tab("advanced", translate("Advanced Settings")) mount:taboption("general", Flag, "enabled", translate("Enable this mount")).rmempty = false o = mount:taboption("general", Value, "device", translate("Device"), translate("The device file of the memory or partition (<abbr title=\"for example\">e.g.</abbr> <code>/dev/sda1</code>)")) for i, d in ipairs(devices) do o:value(d, size[d] and "%s (%s MB)" % {d, size[d]}) end o = mount:taboption("advanced", Value, "uuid", translate("UUID"), translate("If specified, mount the device by its UUID instead of a fixed device node")) o = mount:taboption("advanced", Value, "label", translate("Label"), translate("If specified, mount the device by the partition label instead of a fixed device node")) o = mount:taboption("general", Value, "target", translate("Mount point"), translate("Specifies the directory the device is attached to")) o:depends("is_rootfs", "") o = mount:taboption("general", Value, "fstype", translate("Filesystem"), translate("The filesystem that was used to format the memory (<abbr title=\"for example\">e.g.</abbr> <samp><abbr title=\"Third Extended Filesystem\">ext3</abbr></samp>)")) local fs for fs in io.lines("/proc/filesystems") do fs = fs:match("%S+") if fs ~= "nodev" then o:value(fs) end end o = mount:taboption("advanced", Value, "options", translate("Mount options"), translate("See \"mount\" manpage for details")) o.placeholder = "defaults" if has_extroot then o = mount:taboption("general", Flag, "is_rootfs", translate("Use as root filesystem"), translate("Configures this mount as overlay storage for block-extroot")) o:depends("fstype", "jffs") o:depends("fstype", "ext2") o:depends("fstype", "ext3") o:depends("fstype", "ext4") end if has_fscheck then o = mount:taboption("general", Flag, "enabled_fsck", translate("Run filesystem check"), translate("Run a filesystem check before mounting the device")) end return m
--[[ LuCI - Lua Configuration Interface Copyright 2010 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local fs = require "nixio.fs" local util = require "nixio.util" local has_extroot = fs.access("/sbin/block") local has_fscheck = fs.access("/usr/sbin/e2fsck") local devices = {} util.consume((fs.glob("/dev/sd*")), devices) util.consume((fs.glob("/dev/hd*")), devices) util.consume((fs.glob("/dev/scd*")), devices) util.consume((fs.glob("/dev/mmc*")), devices) local size = {} for i, dev in ipairs(devices) do local s = tonumber((fs.readfile("/sys/class/block/%s/size" % dev:sub(6)))) size[dev] = s and math.floor(s / 2048) end m = Map("fstab", translate("Mount Points - Mount Entry")) m.redirect = luci.dispatcher.build_url("admin/system/fstab") if not arg[1] or m.uci:get("fstab", arg[1]) ~= "mount" then luci.http.redirect(m.redirect) return end mount = m:section(NamedSection, arg[1], "mount", translate("Mount Entry")) mount.anonymous = true mount.addremove = false mount:tab("general", translate("General Settings")) mount:tab("advanced", translate("Advanced Settings")) mount:taboption("general", Flag, "enabled", translate("Enable this mount")).rmempty = false o = mount:taboption("general", Value, "device", translate("Device"), translate("The device file of the memory or partition (<abbr title=\"for example\">e.g.</abbr> <code>/dev/sda1</code>)")) for i, d in ipairs(devices) do o:value(d, size[d] and "%s (%s MB)" % {d, size[d]}) end o = mount:taboption("advanced", Value, "uuid", translate("UUID"), translate("If specified, mount the device by its UUID instead of a fixed device node")) o = mount:taboption("advanced", Value, "label", translate("Label"), translate("If specified, mount the device by the partition label instead of a fixed device node")) o = mount:taboption("general", Value, "target", translate("Mount point"), translate("Specifies the directory the device is attached to")) o:depends("is_rootfs", "") o = mount:taboption("general", Value, "fstype", translate("Filesystem"), translate("The filesystem that was used to format the memory (<abbr title=\"for example\">e.g.</abbr> <samp><abbr title=\"Third Extended Filesystem\">ext3</abbr></samp>)")) local fs for fs in io.lines("/proc/filesystems") do fs = fs:match("%S+") if fs ~= "nodev" then o:value(fs) end end o = mount:taboption("advanced", Value, "options", translate("Mount options"), translate("See \"mount\" manpage for details")) o.placeholder = "defaults" if has_extroot then o = mount:taboption("general", Flag, "is_rootfs", translate("Use as root filesystem"), translate("Configures this mount as overlay storage for block-extroot")) o:depends("fstype", "jffs") o:depends("fstype", "ext2") o:depends("fstype", "ext3") o:depends("fstype", "ext4") end if has_fscheck then o = mount:taboption("general", Flag, "enabled_fsck", translate("Run filesystem check"), translate("Run a filesystem check before mounting the device")) end return m
modules/admin-full: fix extroot and fsck availability check (https://dev.openwrt.org/ticket/13837)
modules/admin-full: fix extroot and fsck availability check (https://dev.openwrt.org/ticket/13837)
Lua
apache-2.0
cshore-firmware/openwrt-luci,jchuang1977/luci-1,MinFu/luci,kuoruan/luci,slayerrensky/luci,lcf258/openwrtcn,RuiChen1113/luci,Hostle/openwrt-luci-multi-user,Wedmer/luci,palmettos/test,LuttyYang/luci,cshore-firmware/openwrt-luci,joaofvieira/luci,fkooman/luci,dwmw2/luci,florian-shellfire/luci,NeoRaider/luci,jorgifumi/luci,thess/OpenWrt-luci,cappiewu/luci,slayerrensky/luci,keyidadi/luci,openwrt/luci,daofeng2015/luci,keyidadi/luci,taiha/luci,cshore/luci,ff94315/luci-1,maxrio/luci981213,Wedmer/luci,jlopenwrtluci/luci,981213/luci-1,tcatm/luci,oneru/luci,nmav/luci,MinFu/luci,dwmw2/luci,zhaoxx063/luci,kuoruan/lede-luci,oyido/luci,ollie27/openwrt_luci,oneru/luci,cshore-firmware/openwrt-luci,ff94315/luci-1,aa65535/luci,LuttyYang/luci,oyido/luci,oneru/luci,jorgifumi/luci,zhaoxx063/luci,fkooman/luci,Hostle/openwrt-luci-multi-user,daofeng2015/luci,openwrt/luci,981213/luci-1,kuoruan/luci,opentechinstitute/luci,cappiewu/luci,aa65535/luci,jchuang1977/luci-1,cshore/luci,daofeng2015/luci,joaofvieira/luci,forward619/luci,tobiaswaldvogel/luci,fkooman/luci,LuttyYang/luci,RuiChen1113/luci,daofeng2015/luci,dwmw2/luci,dismantl/luci-0.12,Noltari/luci,jlopenwrtluci/luci,openwrt-es/openwrt-luci,RuiChen1113/luci,taiha/luci,artynet/luci,ff94315/luci-1,openwrt-es/openwrt-luci,db260179/openwrt-bpi-r1-luci,thesabbir/luci,david-xiao/luci,rogerpueyo/luci,mumuqz/luci,deepak78/new-luci,Noltari/luci,aa65535/luci,remakeelectric/luci,thess/OpenWrt-luci,mumuqz/luci,remakeelectric/luci,lbthomsen/openwrt-luci,MinFu/luci,cshore/luci,jchuang1977/luci-1,cshore-firmware/openwrt-luci,joaofvieira/luci,maxrio/luci981213,florian-shellfire/luci,Wedmer/luci,maxrio/luci981213,thesabbir/luci,male-puppies/luci,cshore/luci,rogerpueyo/luci,Hostle/openwrt-luci-multi-user,bittorf/luci,taiha/luci,fkooman/luci,RedSnake64/openwrt-luci-packages,david-xiao/luci,Kyklas/luci-proto-hso,dwmw2/luci,tobiaswaldvogel/luci,jchuang1977/luci-1,keyidadi/luci,chris5560/openwrt-luci,david-xiao/luci,cappiewu/luci,urueedi/luci,thesabbir/luci,remakeelectric/luci,RedSnake64/openwrt-luci-packages,harveyhu2012/luci,Sakura-Winkey/LuCI,ReclaimYourPrivacy/cloak-luci,sujeet14108/luci,male-puppies/luci,obsy/luci,schidler/ionic-luci,opentechinstitute/luci,cshore/luci,ollie27/openwrt_luci,sujeet14108/luci,Kyklas/luci-proto-hso,jorgifumi/luci,obsy/luci,oyido/luci,nwf/openwrt-luci,db260179/openwrt-bpi-r1-luci,zhaoxx063/luci,NeoRaider/luci,palmettos/test,aircross/OpenWrt-Firefly-LuCI,981213/luci-1,LazyZhu/openwrt-luci-trunk-mod,Kyklas/luci-proto-hso,kuoruan/lede-luci,schidler/ionic-luci,fkooman/luci,jorgifumi/luci,obsy/luci,bittorf/luci,harveyhu2012/luci,NeoRaider/luci,urueedi/luci,palmettos/cnLuCI,aircross/OpenWrt-Firefly-LuCI,Hostle/luci,hnyman/luci,lbthomsen/openwrt-luci,palmettos/test,jchuang1977/luci-1,ff94315/luci-1,Sakura-Winkey/LuCI,RuiChen1113/luci,RedSnake64/openwrt-luci-packages,kuoruan/lede-luci,MinFu/luci,Hostle/openwrt-luci-multi-user,nwf/openwrt-luci,bittorf/luci,oyido/luci,Wedmer/luci,oneru/luci,maxrio/luci981213,kuoruan/lede-luci,fkooman/luci,hnyman/luci,shangjiyu/luci-with-extra,palmettos/test,ollie27/openwrt_luci,dwmw2/luci,ReclaimYourPrivacy/cloak-luci,opentechinstitute/luci,LazyZhu/openwrt-luci-trunk-mod,slayerrensky/luci,marcel-sch/luci,jlopenwrtluci/luci,cshore-firmware/openwrt-luci,urueedi/luci,NeoRaider/luci,openwrt/luci,Hostle/openwrt-luci-multi-user,hnyman/luci,Hostle/luci,openwrt/luci,bittorf/luci,shangjiyu/luci-with-extra,slayerrensky/luci,wongsyrone/luci-1,wongsyrone/luci-1,remakeelectric/luci,kuoruan/luci,Kyklas/luci-proto-hso,lcf258/openwrtcn,keyidadi/luci,marcel-sch/luci,teslamint/luci,Sakura-Winkey/LuCI,forward619/luci,nwf/openwrt-luci,harveyhu2012/luci,dismantl/luci-0.12,harveyhu2012/luci,ReclaimYourPrivacy/cloak-luci,openwrt/luci,sujeet14108/luci,aa65535/luci,teslamint/luci,jlopenwrtluci/luci,db260179/openwrt-bpi-r1-luci,palmettos/cnLuCI,ollie27/openwrt_luci,chris5560/openwrt-luci,dismantl/luci-0.12,marcel-sch/luci,kuoruan/lede-luci,rogerpueyo/luci,db260179/openwrt-bpi-r1-luci,dismantl/luci-0.12,dismantl/luci-0.12,wongsyrone/luci-1,teslamint/luci,LuttyYang/luci,forward619/luci,cappiewu/luci,deepak78/new-luci,chris5560/openwrt-luci,artynet/luci,sujeet14108/luci,zhaoxx063/luci,sujeet14108/luci,oyido/luci,joaofvieira/luci,rogerpueyo/luci,jchuang1977/luci-1,tcatm/luci,rogerpueyo/luci,mumuqz/luci,mumuqz/luci,tcatm/luci,florian-shellfire/luci,palmettos/test,LazyZhu/openwrt-luci-trunk-mod,rogerpueyo/luci,openwrt-es/openwrt-luci,hnyman/luci,oyido/luci,Noltari/luci,opentechinstitute/luci,male-puppies/luci,mumuqz/luci,maxrio/luci981213,nwf/openwrt-luci,maxrio/luci981213,bright-things/ionic-luci,aircross/OpenWrt-Firefly-LuCI,lbthomsen/openwrt-luci,kuoruan/luci,dwmw2/luci,lcf258/openwrtcn,thess/OpenWrt-luci,bittorf/luci,981213/luci-1,thesabbir/luci,MinFu/luci,shangjiyu/luci-with-extra,urueedi/luci,Hostle/luci,jorgifumi/luci,slayerrensky/luci,urueedi/luci,tcatm/luci,ReclaimYourPrivacy/cloak-luci,db260179/openwrt-bpi-r1-luci,RedSnake64/openwrt-luci-packages,thesabbir/luci,palmettos/test,zhaoxx063/luci,bittorf/luci,schidler/ionic-luci,oyido/luci,openwrt-es/openwrt-luci,Hostle/luci,tobiaswaldvogel/luci,schidler/ionic-luci,kuoruan/luci,kuoruan/luci,florian-shellfire/luci,florian-shellfire/luci,wongsyrone/luci-1,cappiewu/luci,lcf258/openwrtcn,forward619/luci,hnyman/luci,bright-things/ionic-luci,mumuqz/luci,chris5560/openwrt-luci,schidler/ionic-luci,bright-things/ionic-luci,florian-shellfire/luci,taiha/luci,MinFu/luci,nmav/luci,mumuqz/luci,Kyklas/luci-proto-hso,teslamint/luci,Wedmer/luci,Noltari/luci,MinFu/luci,Sakura-Winkey/LuCI,dismantl/luci-0.12,nmav/luci,openwrt-es/openwrt-luci,maxrio/luci981213,nmav/luci,cappiewu/luci,bittorf/luci,male-puppies/luci,bittorf/luci,cshore-firmware/openwrt-luci,palmettos/test,florian-shellfire/luci,jlopenwrtluci/luci,zhaoxx063/luci,marcel-sch/luci,LazyZhu/openwrt-luci-trunk-mod,deepak78/new-luci,981213/luci-1,joaofvieira/luci,Kyklas/luci-proto-hso,Noltari/luci,thess/OpenWrt-luci,Hostle/openwrt-luci-multi-user,ollie27/openwrt_luci,remakeelectric/luci,remakeelectric/luci,Hostle/openwrt-luci-multi-user,RedSnake64/openwrt-luci-packages,cshore-firmware/openwrt-luci,Sakura-Winkey/LuCI,zhaoxx063/luci,taiha/luci,schidler/ionic-luci,male-puppies/luci,oneru/luci,male-puppies/luci,palmettos/cnLuCI,shangjiyu/luci-with-extra,sujeet14108/luci,RedSnake64/openwrt-luci-packages,ff94315/luci-1,ReclaimYourPrivacy/cloak-luci,NeoRaider/luci,artynet/luci,keyidadi/luci,ollie27/openwrt_luci,nwf/openwrt-luci,NeoRaider/luci,joaofvieira/luci,artynet/luci,Noltari/luci,sujeet14108/luci,jchuang1977/luci-1,palmettos/cnLuCI,openwrt-es/openwrt-luci,david-xiao/luci,david-xiao/luci,cappiewu/luci,cshore/luci,urueedi/luci,thess/OpenWrt-luci,keyidadi/luci,LuttyYang/luci,slayerrensky/luci,MinFu/luci,shangjiyu/luci-with-extra,aa65535/luci,lcf258/openwrtcn,obsy/luci,Wedmer/luci,nmav/luci,ff94315/luci-1,thess/OpenWrt-luci,opentechinstitute/luci,male-puppies/luci,forward619/luci,zhaoxx063/luci,jlopenwrtluci/luci,thesabbir/luci,openwrt/luci,cshore/luci,remakeelectric/luci,jchuang1977/luci-1,fkooman/luci,artynet/luci,Hostle/openwrt-luci-multi-user,ReclaimYourPrivacy/cloak-luci,thesabbir/luci,bright-things/ionic-luci,harveyhu2012/luci,Sakura-Winkey/LuCI,artynet/luci,marcel-sch/luci,tcatm/luci,LuttyYang/luci,mumuqz/luci,ff94315/luci-1,aircross/OpenWrt-Firefly-LuCI,RuiChen1113/luci,RuiChen1113/luci,bright-things/ionic-luci,hnyman/luci,db260179/openwrt-bpi-r1-luci,dwmw2/luci,keyidadi/luci,db260179/openwrt-bpi-r1-luci,schidler/ionic-luci,deepak78/new-luci,shangjiyu/luci-with-extra,bright-things/ionic-luci,jorgifumi/luci,dismantl/luci-0.12,deepak78/new-luci,forward619/luci,palmettos/cnLuCI,ollie27/openwrt_luci,openwrt-es/openwrt-luci,slayerrensky/luci,NeoRaider/luci,thesabbir/luci,kuoruan/lede-luci,Sakura-Winkey/LuCI,shangjiyu/luci-with-extra,marcel-sch/luci,tcatm/luci,obsy/luci,joaofvieira/luci,cshore-firmware/openwrt-luci,ollie27/openwrt_luci,kuoruan/luci,wongsyrone/luci-1,lcf258/openwrtcn,harveyhu2012/luci,lbthomsen/openwrt-luci,dwmw2/luci,rogerpueyo/luci,david-xiao/luci,lcf258/openwrtcn,Hostle/luci,rogerpueyo/luci,tobiaswaldvogel/luci,tcatm/luci,fkooman/luci,bright-things/ionic-luci,lbthomsen/openwrt-luci,florian-shellfire/luci,slayerrensky/luci,nmav/luci,aircross/OpenWrt-Firefly-LuCI,aa65535/luci,Kyklas/luci-proto-hso,hnyman/luci,openwrt/luci,jorgifumi/luci,Hostle/luci,schidler/ionic-luci,deepak78/new-luci,thess/OpenWrt-luci,RuiChen1113/luci,teslamint/luci,jorgifumi/luci,daofeng2015/luci,palmettos/cnLuCI,nwf/openwrt-luci,bright-things/ionic-luci,palmettos/cnLuCI,LazyZhu/openwrt-luci-trunk-mod,chris5560/openwrt-luci,kuoruan/lede-luci,aa65535/luci,oneru/luci,obsy/luci,artynet/luci,urueedi/luci,Hostle/luci,kuoruan/luci,sujeet14108/luci,RuiChen1113/luci,palmettos/cnLuCI,lcf258/openwrtcn,palmettos/test,daofeng2015/luci,harveyhu2012/luci,maxrio/luci981213,wongsyrone/luci-1,LuttyYang/luci,tcatm/luci,marcel-sch/luci,tobiaswaldvogel/luci,chris5560/openwrt-luci,cshore/luci,opentechinstitute/luci,ReclaimYourPrivacy/cloak-luci,Hostle/luci,thess/OpenWrt-luci,jlopenwrtluci/luci,taiha/luci,aircross/OpenWrt-Firefly-LuCI,teslamint/luci,Noltari/luci,Sakura-Winkey/LuCI,remakeelectric/luci,tobiaswaldvogel/luci,teslamint/luci,Noltari/luci,joaofvieira/luci,lbthomsen/openwrt-luci,ff94315/luci-1,openwrt/luci,oneru/luci,db260179/openwrt-bpi-r1-luci,oneru/luci,deepak78/new-luci,oyido/luci,cappiewu/luci,Noltari/luci,artynet/luci,nwf/openwrt-luci,Wedmer/luci,lcf258/openwrtcn,david-xiao/luci,shangjiyu/luci-with-extra,opentechinstitute/luci,male-puppies/luci,wongsyrone/luci-1,lcf258/openwrtcn,urueedi/luci,taiha/luci,forward619/luci,kuoruan/lede-luci,aircross/OpenWrt-Firefly-LuCI,nmav/luci,LuttyYang/luci,lbthomsen/openwrt-luci,ReclaimYourPrivacy/cloak-luci,taiha/luci,tobiaswaldvogel/luci,LazyZhu/openwrt-luci-trunk-mod,obsy/luci,openwrt-es/openwrt-luci,lbthomsen/openwrt-luci,hnyman/luci,daofeng2015/luci,RedSnake64/openwrt-luci-packages,nwf/openwrt-luci,teslamint/luci,daofeng2015/luci,aa65535/luci,LazyZhu/openwrt-luci-trunk-mod,artynet/luci,nmav/luci,opentechinstitute/luci,wongsyrone/luci-1,chris5560/openwrt-luci,tobiaswaldvogel/luci,LazyZhu/openwrt-luci-trunk-mod,obsy/luci,Wedmer/luci,jlopenwrtluci/luci,981213/luci-1,forward619/luci,981213/luci-1,marcel-sch/luci,nmav/luci,NeoRaider/luci,david-xiao/luci,deepak78/new-luci,keyidadi/luci,chris5560/openwrt-luci
7949fdbe776d5ecd7564ecf9ced8fa7f62d0d464
src_trunk/resources/job-system/s_job_system.lua
src_trunk/resources/job-system/s_job_system.lua
-- //////////////////////////////////// -- // MYSQL // -- //////////////////////////////////// sqlUsername = exports.mysql:getMySQLUsername() sqlPassword = exports.mysql:getMySQLPassword() sqlDB = exports.mysql:getMySQLDBName() sqlHost = exports.mysql:getMySQLHost() sqlPort = exports.mysql:getMySQLPort() handler = mysql_connect(sqlHost, sqlUsername, sqlPassword, sqlDB, sqlPort) function checkMySQL() if not (mysql_ping(handler)) then handler = mysql_connect(sqlHost, sqlUsername, sqlPassword, sqlDB, sqlPort) end end setTimer(checkMySQL, 300000, 0) function closeMySQL() if (handler) then mysql_close(handler) end end addEventHandler("onResourceStop", getResourceRootElement(getThisResource()), closeMySQL) -- //////////////////////////////////// -- // MYSQL END // -- //////////////////////////////////// chDimension = 125 chInterior = 3 employmentCollision = createColSphere(360.8212890625, 173.62351989746, 1009.109375, 5) exports.pool:allocateElement(employmentCollision) -- /employment at cityhall function employment(thePlayer, matchingDimension) if (matchingDimension) then local logged = getElementData(thePlayer, "loggedin") if (logged==1) then if (isElementWithinColShape(thePlayer, employmentCollision)) then triggerClientEvent(thePlayer, "onEmployment", thePlayer) end end end end addEventHandler("onColShapeHit", employmentCollision, employment) -- CALL BACKS FROM CLIENT function givePlayerJob(jobID) local charname = getPlayerName(source) setElementData(source, "job", jobID) exports.global:givePlayerAchievement(source, 30) if (jobID==4) then -- CITY MAINTENANCE giveWeapon(source, 41, 2500, true) outputChatBox("Use this paint to paint over tags you find.", source, 255, 194, 14) setElementData(source, "tag", 9) end end addEvent("acceptJob", true) addEventHandler("acceptJob", getRootElement(), givePlayerJob)
-- //////////////////////////////////// -- // MYSQL // -- //////////////////////////////////// sqlUsername = exports.mysql:getMySQLUsername() sqlPassword = exports.mysql:getMySQLPassword() sqlDB = exports.mysql:getMySQLDBName() sqlHost = exports.mysql:getMySQLHost() sqlPort = exports.mysql:getMySQLPort() handler = mysql_connect(sqlHost, sqlUsername, sqlPassword, sqlDB, sqlPort) function checkMySQL() if not (mysql_ping(handler)) then handler = mysql_connect(sqlHost, sqlUsername, sqlPassword, sqlDB, sqlPort) end end setTimer(checkMySQL, 300000, 0) function closeMySQL() if (handler) then mysql_close(handler) end end addEventHandler("onResourceStop", getResourceRootElement(getThisResource()), closeMySQL) -- //////////////////////////////////// -- // MYSQL END // -- //////////////////////////////////// chDimension = 125 chInterior = 3 employmentCollision = createColSphere(360.8212890625, 173.62351989746, 1009.109375, 5) exports.pool:allocateElement(employmentCollision) -- /employment at cityhall function employment(thePlayer, matchingDimension) local logged = getElementData(thePlayer, "loggedin") if (logged==1) then if (isElementWithinColShape(thePlayer, employmentCollision)) then triggerClientEvent(thePlayer, "onEmployment", thePlayer) end end end addEventHandler("onColShapeHit", employmentCollision, employment) -- CALL BACKS FROM CLIENT function givePlayerJob(jobID) local charname = getPlayerName(source) setElementData(source, "job", jobID) exports.global:givePlayerAchievement(source, 30) if (jobID==4) then -- CITY MAINTENANCE giveWeapon(source, 41, 2500, true) outputChatBox("Use this paint to paint over tags you find.", source, 255, 194, 14) setElementData(source, "tag", 9) end end addEvent("acceptJob", true) addEventHandler("acceptJob", getRootElement(), givePlayerJob)
Job bug fix
Job bug fix git-svn-id: 8769cb08482c9977c94b72b8e184ec7d2197f4f7@619 64450a49-1f69-0410-a0a2-f5ebb52c4f5b
Lua
bsd-3-clause
valhallaGaming/uno,valhallaGaming/uno,valhallaGaming/uno
fd0265817dbfd457e8b3c63db15fab19a2aa3803
src_trunk/resources/social-system/c_friends.lua
src_trunk/resources/social-system/c_friends.lua
wFriends, bClose, imgSelf, lName, imgFlag, paneFriends, tMessage, bSendMessage, tFriends = nil paneFriend = { } local width, height = 300, 500 local scrWidth, scrHeight = guiGetScreenSize() x = scrWidth/2 - (width/2) y = scrHeight/2 - (height/2) function showFriendsUI(friends) wFriends = guiCreateWindow(x, y, width, height, "Friends List", false) guiWindowSetSizable(wFriends, false) addEventHandler("onClientGUIMove", wFriends, storeCoords) tFriends = friends -- SELF imgSelf = guiCreateStaticImage(0.05, 0.075, 0.9, 0.1, "images/friendsme.png", true, wFriends) bClose = guiCreateButton(0.825, 0.0375, 0.15, 0.04, "Close", true, wFriends) addEventHandler("onClientGUIClick", bClose, hideFriendsUI, false) local uname = getElementData(getLocalPlayer(), "gameaccountusername") local charname = string.gsub(getPlayerName(getLocalPlayer()), "_", " ") lName = guiCreateLabel(0.17, 0.084, 0.6, 0.2, uname .. " (" .. charname .. ")", true, wFriends) guiSetFont(lName, "default-bold-small") local country = tostring(getElementData(getLocalPlayer(), "country")) imgFlag = guiCreateStaticImage(0.0875, 0.0875, 0.025806*3, 0.021154, "images/flags/" .. string.lower(country) .. ".png", true, wFriends) local fmess = getElementData(getLocalPlayer(), "friends.message") tMessage = guiCreateEdit(0.08, 0.12, 0.6, 0.04, tostring(fmess), true, wFriends) bSendMessage = guiCreateButton(0.68, 0.12, 0.25, 0.04, "Update", true, wFriends) addEventHandler("onClientGUIClick", bSendMessage, sendMessage, false) paneFriends = guiCreateScrollPane(0.05, 0.2, 0.9, 0.85, true, wFriends) local dy = 0.0 local dheight = 0.2 for key, value in ipairs(friends) do local id = friends[key][1] local username = friends[key][2] local message = friends[key][3] local country = friends[key][4] local status = friends[key][5] local operatingsystem = friends[key][7] local name = nil -- Fix for blank messages if (tostring(message)=="nil") then message = "No Message" else message = "'" .. message .. "'" end if (status=="Online") then name = string.gsub(friends[key][6], "_", " ") end -- STANDARD UI paneFriend[key] = {} paneFriend[key][7] = guiCreateScrollPane(0.05, dy, 1.0, 0.35, true, paneFriends) paneFriend[key][1] = guiCreateStaticImage(0.0, 0.1, 0.9, 0.5, "img/charbg0.png", true, paneFriend[key][7], getResourceFromName("account-system")) if (name~=nil) then paneFriend[key][2] = guiCreateLabel(0.12, 0.1, 0.8, 0.2, username .. " as " .. name, true, paneFriend[key][7]) else paneFriend[key][2] = guiCreateLabel(0.12, 0.1, 0.8, 0.2, username, true, paneFriend[key][7]) end guiSetFont(paneFriend[key][2], "default-bold-small") paneFriend[key][3] = guiCreateStaticImage(0.0175, 0.125, 0.09, 0.08, "images/flags/" .. string.lower(country) .. ".png", true, paneFriend[key][7]) paneFriend[key][4] = guiCreateLabel(0.12, 0.2, 0.8, 0.2, tostring(status), true, paneFriend[key][7]) guiSetFont(paneFriend[key][4], "default-bold-small") paneFriend[key][5] = guiCreateLabel(0.12, 0.3, 0.8, 0.2, tostring(message), true, paneFriend[key][7]) guiSetFont(paneFriend[key][5], "default-bold-small") paneFriend[key][6] = guiCreateStaticImage(0.08, 0.42, 0.1, 0.16, "images/" .. operatingsystem .. ".png", true, paneFriend[key][7]) paneFriend[key][10] = guiCreateLabel(0.22, 0.45, 0.5, 0.2, tostring(friends[key][8]) .. " Achievements", true, paneFriend[key][7]) guiSetFont(paneFriend[key][10], "default-bold-small") paneFriend[key][8] = guiCreateButton(0.63, 0.43, 0.25, 0.15, "Remove", true, paneFriend[key][7]) addEventHandler("onClientGUIClick", paneFriend[key][8], removeFriend, false) --paneFriend[key][9] = guiCreateButton(0.72, 0.43, 0.25, 0.15, "Compare", true, paneFriend[key][7]) --addEventHandler("onClientGUIClick", paneFriend[key][8], removeFriend, false) dy = dy + 0.205 end guiSetInputEnabled(true) end addEvent("showFriendsList", true) addEventHandler("showFriendsList", getRootElement(), showFriendsUI) function unload(res) if (res==getThisResource()) then guiSetInputEnabled(false) end end addEventHandler("onClientResourceStop", getRootElement(), unload) function sendMessage() local message = guiGetText(tMessage) hideFriendsUI() triggerServerEvent("updateFriendsMessage", getLocalPlayer(), message) end function storeCoords() if (wFriends~=nil) then x, y = guiGetPosition(wFriends, false) end end function hideFriendsUI() destroyElement(wFriends) guiSetInputEnabled(false) setElementData(getLocalPlayer(), "friends.visible", 0, true) tFriends = nil end function removeFriend(button) if (button=="left") then local targetvalue = nil for key, value in ipairs(paneFriend) do if (tostring(paneFriend[key][8])==tostring(source)) then targetvalue = key end end if (targetvalue) then local id = tFriends[targetvalue][1] local username = tFriends[targetvalue][2] hideFriendsUI() triggerServerEvent("removeFriend", getLocalPlayer(), id, username) end end end function toggleCursor() if (isCursorShowing()) then showCursor(false) else showCursor(true) end end bindKey("m", "down", toggleCursor) function cursorHide() showCursor(false) end addEvent("cursorHide", false) addEventHandler("cursorHide", getRootElement(), cursorHide) function cursorShow() showCursor(true) end addEvent("cursorShow", false) addEventHandler("cursorShow", getRootElement(), cursorShow)
wFriends, bClose, imgSelf, lName, imgFlag, paneFriends, tMessage, bSendMessage, tFriends = nil paneFriend = { } local width, height = 300, 500 local scrWidth, scrHeight = guiGetScreenSize() x = scrWidth/2 - (width/2) y = scrHeight/2 - (height/2) function showFriendsUI(friends) wFriends = guiCreateWindow(x, y, width, height, "Friends List", false) guiWindowSetSizable(wFriends, false) addEventHandler("onClientGUIMove", wFriends, storeCoords) tFriends = friends -- SELF imgSelf = guiCreateStaticImage(0.05, 0.075, 0.9, 0.1, "images/friendsme.png", true, wFriends) bClose = guiCreateButton(0.825, 0.0375, 0.15, 0.04, "Close", true, wFriends) addEventHandler("onClientGUIClick", bClose, hideFriendsUI, false) local uname = getElementData(getLocalPlayer(), "gameaccountusername") local charname = string.gsub(getPlayerName(getLocalPlayer()), "_", " ") lName = guiCreateLabel(0.17, 0.084, 0.6, 0.2, uname .. " (" .. charname .. ")", true, wFriends) guiSetFont(lName, "default-bold-small") local country = tostring(getElementData(getLocalPlayer(), "country")) imgFlag = guiCreateStaticImage(0.0875, 0.0875, 0.025806*3, 0.021154, "images/flags/" .. string.lower(country) .. ".png", true, wFriends) local fmess = getElementData(getLocalPlayer(), "friends.message") tMessage = guiCreateEdit(0.08, 0.12, 0.6, 0.04, tostring(fmess), true, wFriends) bSendMessage = guiCreateButton(0.68, 0.12, 0.25, 0.04, "Update", true, wFriends) addEventHandler("onClientGUIClick", bSendMessage, sendMessage, false) paneFriends = guiCreateScrollPane(0.05, 0.2, 0.9, 0.85, true, wFriends) local dy = 0.0 local dheight = 0.2 for key, value in ipairs(friends) do local id = friends[key][1] local username = friends[key][2] local message = friends[key][3] local country = friends[key][4] local status = friends[key][5] local operatingsystem = friends[key][7] local name = nil -- Fix for blank messages if (tostring(message)=="nil") then message = "No Message" else message = "'" .. message .. "'" end if (status=="Online") then name = string.gsub(friends[key][6], "_", " ") end -- STANDARD UI paneFriend[key] = {} paneFriend[key][7] = guiCreateScrollPane(0.05, dy, 1.0, 0.35, true, paneFriends) paneFriend[key][1] = guiCreateStaticImage(0.0, 0.1, 0.9, 0.5, ":account-system/img/charbg0.png", true, paneFriend[key][7]) if (name~=nil) then paneFriend[key][2] = guiCreateLabel(0.12, 0.1, 0.8, 0.2, username .. " as " .. name, true, paneFriend[key][7]) else paneFriend[key][2] = guiCreateLabel(0.12, 0.1, 0.8, 0.2, username, true, paneFriend[key][7]) end guiSetFont(paneFriend[key][2], "default-bold-small") paneFriend[key][3] = guiCreateStaticImage(0.0175, 0.125, 0.09, 0.08, "images/flags/" .. string.lower(country) .. ".png", true, paneFriend[key][7]) paneFriend[key][4] = guiCreateLabel(0.12, 0.2, 0.8, 0.2, tostring(status), true, paneFriend[key][7]) guiSetFont(paneFriend[key][4], "default-bold-small") paneFriend[key][5] = guiCreateLabel(0.12, 0.3, 0.8, 0.2, tostring(message), true, paneFriend[key][7]) guiSetFont(paneFriend[key][5], "default-bold-small") paneFriend[key][6] = guiCreateStaticImage(0.08, 0.42, 0.1, 0.16, "images/" .. operatingsystem .. ".png", true, paneFriend[key][7]) paneFriend[key][10] = guiCreateLabel(0.22, 0.45, 0.5, 0.2, tostring(friends[key][8]) .. " Achievements", true, paneFriend[key][7]) guiSetFont(paneFriend[key][10], "default-bold-small") paneFriend[key][8] = guiCreateButton(0.63, 0.43, 0.25, 0.15, "Remove", true, paneFriend[key][7]) addEventHandler("onClientGUIClick", paneFriend[key][8], removeFriend, false) --paneFriend[key][9] = guiCreateButton(0.72, 0.43, 0.25, 0.15, "Compare", true, paneFriend[key][7]) --addEventHandler("onClientGUIClick", paneFriend[key][8], removeFriend, false) dy = dy + 0.205 end guiSetInputEnabled(true) end addEvent("showFriendsList", true) addEventHandler("showFriendsList", getRootElement(), showFriendsUI) function unload(res) if (res==getThisResource()) then guiSetInputEnabled(false) end end addEventHandler("onClientResourceStop", getRootElement(), unload) function sendMessage() local message = guiGetText(tMessage) hideFriendsUI() triggerServerEvent("updateFriendsMessage", getLocalPlayer(), message) end function storeCoords() if (wFriends~=nil) then x, y = guiGetPosition(wFriends, false) end end function hideFriendsUI() destroyElement(wFriends) guiSetInputEnabled(false) setElementData(getLocalPlayer(), "friends.visible", 0, true) tFriends = nil end function removeFriend(button) if (button=="left") then local targetvalue = nil for key, value in ipairs(paneFriend) do if (tostring(paneFriend[key][8])==tostring(source)) then targetvalue = key end end if (targetvalue) then local id = tFriends[targetvalue][1] local username = tFriends[targetvalue][2] hideFriendsUI() triggerServerEvent("removeFriend", getLocalPlayer(), id, username) end end end function toggleCursor() if (isCursorShowing()) then showCursor(false) else showCursor(true) end end bindKey("m", "down", toggleCursor) function cursorHide() showCursor(false) end addEvent("cursorHide", false) addEventHandler("cursorHide", getRootElement(), cursorHide) function cursorShow() showCursor(true) end addEvent("cursorShow", false) addEventHandler("cursorShow", getRootElement(), cursorShow)
Fixed a bug with background on friends system
Fixed a bug with background on friends system git-svn-id: 8769cb08482c9977c94b72b8e184ec7d2197f4f7@453 64450a49-1f69-0410-a0a2-f5ebb52c4f5b
Lua
bsd-3-clause
valhallaGaming/uno,valhallaGaming/uno,valhallaGaming/uno
9c366fa199c149509288f460e9ee0658a4859f7b
applications/luci-firewall/luasrc/model/cbi/luci_fw/rrule.lua
applications/luci-firewall/luasrc/model/cbi/luci_fw/rrule.lua
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2010 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local sys = require "luci.sys" local dsp = require "luci.dispatcher" arg[1] = arg[1] or "" m = Map("firewall", translate("Traffic Redirection"), translate("Traffic redirection allows you to change the " .. "destination address of forwarded packets.")) m.redirect = dsp.build_url("admin", "network", "firewall") if not m.uci:get(arg[1]) == "redirect" then luci.http.redirect(m.redirect) return end local has_v2 = nixio.fs.access("/lib/firewall/fw.sh") local wan_zone = nil m.uci:foreach("firewall", "zone", function(s) local n = s.network or s.name if n then local i for i in n:gmatch("%S+") do if i == "wan" then wan_zone = s.name return false end end end end) s = m:section(NamedSection, arg[1], "redirect", "") s.anonymous = true s.addremove = false s:tab("general", translate("General Settings")) s:tab("advanced", translate("Advanced Settings")) name = s:taboption("general", Value, "_name", translate("Name")) name.rmempty = true name.size = 10 src = s:taboption("general", Value, "src", translate("Source zone")) src.nocreate = true src.default = "wan" src.template = "cbi/firewall_zonelist" proto = s:taboption("general", Value, "proto", translate("Protocol")) proto.optional = true proto:value("tcpudp", "TCP+UDP") proto:value("tcp", "TCP") proto:value("udp", "UDP") dport = s:taboption("general", Value, "src_dport", translate("External port"), translate("Match incoming traffic directed at the given " .. "destination port or port range on this host")) dport.datatype = "portrange" dport:depends("proto", "tcp") dport:depends("proto", "udp") dport:depends("proto", "tcpudp") to = s:taboption("general", Value, "dest_ip", translate("Internal IP address"), translate("Redirect matched incoming traffic to the specified " .. "internal host")) to.datatype = "ip4addr" for i, dataset in ipairs(luci.sys.net.arptable()) do to:value(dataset["IP address"]) end toport = s:taboption("general", Value, "dest_port", translate("Internal port (optional)"), translate("Redirect matched incoming traffic to the given port on " .. "the internal host")) toport.optional = true toport.placeholder = "0-65535" toport.datatype = "portrange" toport:depends("proto", "tcp") toport:depends("proto", "udp") toport:depends("proto", "tcpudp") target = s:taboption("advanced", ListValue, "target", translate("Redirection type")) target:value("DNAT") target:value("SNAT") dest = s:taboption("advanced", Value, "dest", translate("Destination zone")) dest.nocreate = true dest.default = "lan" dest.template = "cbi/firewall_zonelist" src_dip = s:taboption("advanced", Value, "src_dip", translate("Intended destination address"), translate( "For DNAT, match incoming traffic directed at the given destination ".. "ip address. For SNAT rewrite the source address to the given address." )) src_dip.optional = true src_dip.datatype = "ip4addr" src_dip.placeholder = translate("any") src_mac = s:taboption("advanced", Value, "src_mac", translate("Source MAC address")) src_mac.optional = true src_mac.datatype = "macaddr" src_mac.placeholder = translate("any") src_ip = s:taboption("advanced", Value, "src_ip", translate("Source IP address")) src_ip.optional = true src_ip.datatype = "neg_ip4addr" src_ip.placeholder = translate("any") sport = s:taboption("advanced", Value, "src_port", translate("Source port"), translate("Match incoming traffic originating from the given " .. "source port or port range on the client host")) sport.optional = true sport.datatype = "portrange" sport.placeholder = "0-65536" sport:depends("proto", "tcp") sport:depends("proto", "udp") sport:depends("proto", "tcpudp") reflection = s:taboption("advanced", Flag, "reflection", translate("Enable NAT Loopback")) reflection.rmempty = true reflection:depends({ target = "DNAT", src = wan_zone }) reflection.cfgvalue = function(...) return Flag.cfgvalue(...) or "1" end return m
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2010 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local sys = require "luci.sys" local dsp = require "luci.dispatcher" arg[1] = arg[1] or "" m = Map("firewall", translate("Traffic Redirection"), translate("Traffic redirection allows you to change the " .. "destination address of forwarded packets.")) m.redirect = dsp.build_url("admin", "network", "firewall") if not m.uci:get(arg[1]) == "redirect" then luci.http.redirect(m.redirect) return end local has_v2 = nixio.fs.access("/lib/firewall/fw.sh") local wan_zone = nil m.uci:foreach("firewall", "zone", function(s) local n = s.network or s.name if n then local i for i in n:gmatch("%S+") do if i == "wan" then wan_zone = s.name return false end end end end) s = m:section(NamedSection, arg[1], "redirect", "") s.anonymous = true s.addremove = false s:tab("general", translate("General Settings")) s:tab("advanced", translate("Advanced Settings")) name = s:taboption("general", Value, "_name", translate("Name")) name.rmempty = true name.size = 10 src = s:taboption("general", Value, "src", translate("Source zone")) src.nocreate = true src.default = "wan" src.template = "cbi/firewall_zonelist" proto = s:taboption("general", Value, "proto", translate("Protocol")) proto.optional = true proto:value("tcpudp", "TCP+UDP") proto:value("tcp", "TCP") proto:value("udp", "UDP") dport = s:taboption("general", Value, "src_dport", translate("External port"), translate("Match incoming traffic directed at the given " .. "destination port or port range on this host")) dport.datatype = "portrange" dport:depends("proto", "tcp") dport:depends("proto", "udp") dport:depends("proto", "tcpudp") to = s:taboption("general", Value, "dest_ip", translate("Internal IP address"), translate("Redirect matched incoming traffic to the specified " .. "internal host")) to.datatype = "ip4addr" for i, dataset in ipairs(luci.sys.net.arptable()) do to:value(dataset["IP address"]) end toport = s:taboption("general", Value, "dest_port", translate("Internal port (optional)"), translate("Redirect matched incoming traffic to the given port on " .. "the internal host")) toport.optional = true toport.placeholder = "0-65535" toport.datatype = "portrange" toport:depends("proto", "tcp") toport:depends("proto", "udp") toport:depends("proto", "tcpudp") target = s:taboption("advanced", ListValue, "target", translate("Redirection type")) target:value("DNAT") target:value("SNAT") dest = s:taboption("advanced", Value, "dest", translate("Destination zone")) dest.nocreate = true dest.default = "lan" dest.template = "cbi/firewall_zonelist" src_dip = s:taboption("advanced", Value, "src_dip", translate("Intended destination address"), translate( "For DNAT, match incoming traffic directed at the given destination ".. "ip address. For SNAT rewrite the source address to the given address." )) src_dip.optional = true src_dip.datatype = "ip4addr" src_dip.placeholder = translate("any") src_mac = s:taboption("advanced", Value, "src_mac", translate("Source MAC address")) src_mac.optional = true src_mac.datatype = "macaddr" src_mac.placeholder = translate("any") src_ip = s:taboption("advanced", Value, "src_ip", translate("Source IP address")) src_ip.optional = true src_ip.datatype = "neg_ip4addr" src_ip.placeholder = translate("any") sport = s:taboption("advanced", Value, "src_port", translate("Source port"), translate("Match incoming traffic originating from the given " .. "source port or port range on the client host")) sport.optional = true sport.datatype = "portrange" sport.placeholder = "0-65536" sport:depends("proto", "tcp") sport:depends("proto", "udp") sport:depends("proto", "tcpudp") reflection = s:taboption("advanced", Flag, "reflection", translate("Enable NAT Loopback")) reflection.rmempty = true reflection.default = reflection.enabled reflection:depends({ target = "DNAT", src = wan_zone }) reflection.cfgvalue = function(...) return Flag.cfgvalue(...) or "1" end return m
applications/luci-firewall: fix turning off nat reflection
applications/luci-firewall: fix turning off nat reflection git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@7338 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
1ebc2831ccb2cafb4455b6955879cadb3a99523a
tests/06-multi-emit.lua
tests/06-multi-emit.lua
local _ = require("underscore")._ , assert = require("assert") , One = require("../lib/tally_ho").Tally_Ho.new() , Two = require("../lib/tally_ho").Tally_Ho.new() , Third = require("../lib/tally_ho").Tally_Ho.new() ; One:on('one', function (o) o.data.l.push(1) end) One:on('two', function (o) o.data.l.push(2) end) One:on('after two', function (o) o.data.l.push(3) end) describe( 'multi run', function () it( 'runs functions in sequential order', function () local o = {l={}}; One:run('one', 'two', o) assert.same(o.l, {1,2,3}) end) it( 'runs last callback at end', function () local o = {l={}}; One:run('one', 'two', o, function (o) o.data.l.push('4') end) assert.same(o.l, {1,2,3,'4'}) end) end) -- === end desc
local _ = require("underscore") local Jam = require "jam_bo_ree" local One = Jam.new() local Two = Jam.new() local Third = Jam.new() One:on('one', function (o) _.push(o.l, 1) end) One:on('two', function (o) _.push(o.l, 2) end) One:on('after two', function (o) _.push(o.l, 3) end) describe( 'multi run', function () it( 'runs functions in sequential order', function () local o = {l={}}; One:run('one', 'two', o) assert.same(o.l, {1,2,3}) end) it( 'runs last callback at end', function () local o = {l={}}; One:run('one', 'two', o, function (o) _.push(o.l, '4') end) assert.same(o.l, {1,2,3,'4'}) end) end) -- === end desc
Fixed: tests for multi-emit
Fixed: tests for multi-emit
Lua
mit
da99/jam_bo_ree
ce6051440267f90ad0241aed7b729007d837165d
modules/admin-mini/luasrc/model/cbi/mini/wifi.lua
modules/admin-mini/luasrc/model/cbi/mini/wifi.lua
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- m = Map("wireless", translate("wifi"), translate("a_w_devices1")) s = m:section(TypedSection, "wifi-device", translate("devices")) en = s:option(Flag, "disabled", translate("enable")) en.enabled = "0" en.disabled = "1" mode = s:option(ListValue, "mode", translate("mode")) mode:value("", "standard") mode:value("11b", "802.11b") mode:value("11g", "802.11g") mode:value("11a", "802.11a") mode:value("11bg", "802.11b+g") mode.rmempty = true s:option(Value, "channel", translate("a_w_channel")) s = m:section(TypedSection, "wifi-iface", translate("m_n_local")) s.anonymous = true s:option(Value, "ssid", translate("a_w_netid")).maxlength = 32 local devs = {} luci.model.uci.foreach("wireless", "wifi-device", function (section) table.insert(devs, section[".name"]) end) if #devs > 1 then device = s:option(DummyValue, "device", translate("device")) else s.defaults.device = devs[1] end mode = s:option(ListValue, "mode", translate("mode")) mode:value("ap", translate("m_w_ap")) mode:value("adhoc", translate("m_w_adhoc")) mode:value("sta", translate("m_w_client")) function mode.write(self, section, value) if value == "sta" then -- ToDo: Move this away if not luci.model.uci.get("network", "wan") then luci.model.uci.set("network", "wan", "interface") luci.model.uci.set("network", "wan", "proto", "none") end luci.model.uci.set("network", "wan", "type", "bridge") luci.model.uci.save("network") self.map:set(section, "network", "wan") else self.map:set(section, "network", "lan") end return ListValue.write(self, section, value) end encr = s:option(ListValue, "encryption", translate("encryption")) encr:value("none", "keine") encr:value("wep", "WEP") encr:value("psk", "WPA-PSK") encr:value("wpa", "WPA-Radius") encr:value("psk2", "WPA2-PSK") encr:value("wpa2", "WPA2-Radius") key = s:option(Value, "key", translate("key")) key:depends("encryption", "wep") key:depends("encryption", "psk") key:depends("encryption", "wpa") key:depends("encryption", "psk2") key:depends("encryption", "wpa2") key.rmempty = true server = s:option(Value, "server", translate("a_w_radiussrv")) server:depends("encryption", "wpa") server:depends("encryption", "wpa2") server.rmempty = true port = s:option(Value, "port", translate("a_w_radiusport")) port:depends("encryption", "wpa") port:depends("encryption", "wpa2") port.rmempty = true iso = s:option(Flag, "isolate", translate("a_w_apisolation"), translate("a_w_apisolation1")) iso.rmempty = true iso:depends("mode", "ap") hide = s:option(Flag, "hidden", translate("a_w_hideessid")) hide.rmempty = true hide:depends("mode", "ap") return m
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- m = Map("wireless", translate("wifi"), translate("a_w_devices1")) s = m:section(TypedSection, "wifi-device", translate("devices")) en = s:option(Flag, "disabled", translate("enable")) en.enabled = "0" en.disabled = "1" mode = s:option(ListValue, "mode", translate("mode")) mode:value("", "standard") mode:value("11b", "802.11b") mode:value("11g", "802.11g") mode:value("11a", "802.11a") mode:value("11bg", "802.11b+g") mode.rmempty = true s:option(Value, "channel", translate("a_w_channel")) s = m:section(TypedSection, "wifi-iface", translate("m_n_local")) s.anonymous = true s:option(Value, "ssid", translate("a_w_netid")).maxlength = 32 local devs = {} luci.model.uci.foreach("wireless", "wifi-device", function (section) table.insert(devs, section[".name"]) end) if #devs > 1 then device = s:option(DummyValue, "device", translate("device")) else s.defaults.device = devs[1] end mode = s:option(ListValue, "mode", translate("mode")) mode:value("ap", translate("m_w_ap")) mode:value("adhoc", translate("m_w_adhoc")) mode:value("sta", translate("m_w_client")) function mode.write(self, section, value) if value == "sta" then -- ToDo: Move this away if not luci.model.uci.get("network", "wan") then luci.model.uci.set("network", "wan", "proto", "none") luci.model.uci.set("network", "wan", "ifname", " ") end luci.model.uci.set("network", "wan", "_ifname", luci.model.uci.get("network", "wan", "ifname") or " ") luci.model.uci.set("network", "wan", "ifname", " ") luci.model.uci.save("network") luci.model.uci.unload("network") self.map:set(section, "network", "wan") else if luci.model.uci.get("network", "wan", "_ifname") then luci.model.uci.set("network", "wan", "ifname", luci.model.uci.get("network", "wan", "_ifname")) end self.map:set(section, "network", "lan") end return ListValue.write(self, section, value) end encr = s:option(ListValue, "encryption", translate("encryption")) encr:value("none", "keine") encr:value("wep", "WEP") encr:value("psk", "WPA-PSK") encr:value("wpa", "WPA-Radius") encr:value("psk2", "WPA2-PSK") encr:value("wpa2", "WPA2-Radius") key = s:option(Value, "key", translate("key")) key:depends("encryption", "wep") key:depends("encryption", "psk") key:depends("encryption", "wpa") key:depends("encryption", "psk2") key:depends("encryption", "wpa2") key.rmempty = true server = s:option(Value, "server", translate("a_w_radiussrv")) server:depends("encryption", "wpa") server:depends("encryption", "wpa2") server.rmempty = true port = s:option(Value, "port", translate("a_w_radiusport")) port:depends("encryption", "wpa") port:depends("encryption", "wpa2") port.rmempty = true iso = s:option(Flag, "isolate", translate("a_w_apisolation"), translate("a_w_apisolation1")) iso.rmempty = true iso:depends("mode", "ap") hide = s:option(Flag, "hidden", translate("a_w_hideessid")) hide.rmempty = true hide:depends("mode", "ap") return m
modules/admin-mini: Fixed WLAN client mode
modules/admin-mini: Fixed WLAN client mode
Lua
apache-2.0
oneru/luci,LazyZhu/openwrt-luci-trunk-mod,tcatm/luci,wongsyrone/luci-1,RuiChen1113/luci,dwmw2/luci,Noltari/luci,jchuang1977/luci-1,LazyZhu/openwrt-luci-trunk-mod,RuiChen1113/luci,kuoruan/lede-luci,schidler/ionic-luci,RuiChen1113/luci,urueedi/luci,schidler/ionic-luci,cshore-firmware/openwrt-luci,oyido/luci,nmav/luci,forward619/luci,cshore/luci,schidler/ionic-luci,remakeelectric/luci,openwrt/luci,Noltari/luci,opentechinstitute/luci,Noltari/luci,981213/luci-1,openwrt-es/openwrt-luci,ollie27/openwrt_luci,aircross/OpenWrt-Firefly-LuCI,rogerpueyo/luci,lcf258/openwrtcn,Hostle/luci,Sakura-Winkey/LuCI,bright-things/ionic-luci,ff94315/luci-1,obsy/luci,wongsyrone/luci-1,jlopenwrtluci/luci,aa65535/luci,jorgifumi/luci,981213/luci-1,NeoRaider/luci,kuoruan/lede-luci,LazyZhu/openwrt-luci-trunk-mod,LazyZhu/openwrt-luci-trunk-mod,david-xiao/luci,Wedmer/luci,chris5560/openwrt-luci,nwf/openwrt-luci,palmettos/test,RedSnake64/openwrt-luci-packages,palmettos/test,fkooman/luci,lbthomsen/openwrt-luci,keyidadi/luci,zhaoxx063/luci,fkooman/luci,MinFu/luci,mumuqz/luci,ollie27/openwrt_luci,MinFu/luci,db260179/openwrt-bpi-r1-luci,obsy/luci,cshore/luci,marcel-sch/luci,daofeng2015/luci,david-xiao/luci,ollie27/openwrt_luci,lbthomsen/openwrt-luci,Hostle/openwrt-luci-multi-user,marcel-sch/luci,palmettos/test,bittorf/luci,oneru/luci,ff94315/luci-1,jorgifumi/luci,Hostle/openwrt-luci-multi-user,palmettos/cnLuCI,Hostle/luci,marcel-sch/luci,openwrt-es/openwrt-luci,urueedi/luci,ff94315/luci-1,palmettos/cnLuCI,deepak78/new-luci,MinFu/luci,LuttyYang/luci,thesabbir/luci,kuoruan/lede-luci,RuiChen1113/luci,deepak78/new-luci,Noltari/luci,chris5560/openwrt-luci,chris5560/openwrt-luci,aircross/OpenWrt-Firefly-LuCI,thess/OpenWrt-luci,Kyklas/luci-proto-hso,jchuang1977/luci-1,harveyhu2012/luci,marcel-sch/luci,ollie27/openwrt_luci,aa65535/luci,NeoRaider/luci,dwmw2/luci,nmav/luci,palmettos/cnLuCI,bright-things/ionic-luci,palmettos/test,florian-shellfire/luci,nwf/openwrt-luci,thess/OpenWrt-luci,Sakura-Winkey/LuCI,hnyman/luci,kuoruan/luci,aa65535/luci,david-xiao/luci,dwmw2/luci,daofeng2015/luci,bright-things/ionic-luci,tobiaswaldvogel/luci,kuoruan/luci,oneru/luci,zhaoxx063/luci,NeoRaider/luci,oyido/luci,urueedi/luci,slayerrensky/luci,Sakura-Winkey/LuCI,db260179/openwrt-bpi-r1-luci,mumuqz/luci,hnyman/luci,remakeelectric/luci,Wedmer/luci,aa65535/luci,kuoruan/luci,jlopenwrtluci/luci,jlopenwrtluci/luci,jorgifumi/luci,zhaoxx063/luci,Noltari/luci,aircross/OpenWrt-Firefly-LuCI,daofeng2015/luci,ReclaimYourPrivacy/cloak-luci,Wedmer/luci,ReclaimYourPrivacy/cloak-luci,teslamint/luci,maxrio/luci981213,hnyman/luci,cappiewu/luci,artynet/luci,openwrt-es/openwrt-luci,bittorf/luci,marcel-sch/luci,dwmw2/luci,openwrt/luci,shangjiyu/luci-with-extra,db260179/openwrt-bpi-r1-luci,lbthomsen/openwrt-luci,NeoRaider/luci,Sakura-Winkey/LuCI,mumuqz/luci,palmettos/test,dismantl/luci-0.12,ollie27/openwrt_luci,teslamint/luci,mumuqz/luci,oyido/luci,LuttyYang/luci,lbthomsen/openwrt-luci,jlopenwrtluci/luci,florian-shellfire/luci,wongsyrone/luci-1,oyido/luci,taiha/luci,chris5560/openwrt-luci,lcf258/openwrtcn,Hostle/openwrt-luci-multi-user,cshore-firmware/openwrt-luci,db260179/openwrt-bpi-r1-luci,shangjiyu/luci-with-extra,Hostle/luci,joaofvieira/luci,ff94315/luci-1,dismantl/luci-0.12,cshore/luci,tobiaswaldvogel/luci,tcatm/luci,aircross/OpenWrt-Firefly-LuCI,jorgifumi/luci,RuiChen1113/luci,fkooman/luci,981213/luci-1,Noltari/luci,taiha/luci,nwf/openwrt-luci,dismantl/luci-0.12,schidler/ionic-luci,cappiewu/luci,LazyZhu/openwrt-luci-trunk-mod,jchuang1977/luci-1,Hostle/openwrt-luci-multi-user,aa65535/luci,forward619/luci,maxrio/luci981213,opentechinstitute/luci,nmav/luci,florian-shellfire/luci,dismantl/luci-0.12,ReclaimYourPrivacy/cloak-luci,cshore-firmware/openwrt-luci,tcatm/luci,jorgifumi/luci,thesabbir/luci,bright-things/ionic-luci,slayerrensky/luci,lcf258/openwrtcn,jorgifumi/luci,LuttyYang/luci,kuoruan/lede-luci,tobiaswaldvogel/luci,jchuang1977/luci-1,Hostle/openwrt-luci-multi-user,opentechinstitute/luci,kuoruan/luci,deepak78/new-luci,harveyhu2012/luci,fkooman/luci,jlopenwrtluci/luci,daofeng2015/luci,tobiaswaldvogel/luci,bright-things/ionic-luci,remakeelectric/luci,cshore-firmware/openwrt-luci,david-xiao/luci,male-puppies/luci,Hostle/openwrt-luci-multi-user,openwrt/luci,obsy/luci,jchuang1977/luci-1,nmav/luci,wongsyrone/luci-1,Wedmer/luci,chris5560/openwrt-luci,mumuqz/luci,florian-shellfire/luci,ollie27/openwrt_luci,nwf/openwrt-luci,openwrt-es/openwrt-luci,kuoruan/lede-luci,cappiewu/luci,LuttyYang/luci,ReclaimYourPrivacy/cloak-luci,urueedi/luci,keyidadi/luci,teslamint/luci,keyidadi/luci,rogerpueyo/luci,fkooman/luci,db260179/openwrt-bpi-r1-luci,db260179/openwrt-bpi-r1-luci,thesabbir/luci,slayerrensky/luci,ReclaimYourPrivacy/cloak-luci,RedSnake64/openwrt-luci-packages,shangjiyu/luci-with-extra,wongsyrone/luci-1,chris5560/openwrt-luci,joaofvieira/luci,tobiaswaldvogel/luci,981213/luci-1,teslamint/luci,bittorf/luci,forward619/luci,keyidadi/luci,sujeet14108/luci,tcatm/luci,wongsyrone/luci-1,LazyZhu/openwrt-luci-trunk-mod,thess/OpenWrt-luci,joaofvieira/luci,Kyklas/luci-proto-hso,artynet/luci,shangjiyu/luci-with-extra,jlopenwrtluci/luci,joaofvieira/luci,RuiChen1113/luci,Hostle/openwrt-luci-multi-user,MinFu/luci,bittorf/luci,oyido/luci,deepak78/new-luci,NeoRaider/luci,oneru/luci,oneru/luci,981213/luci-1,RedSnake64/openwrt-luci-packages,thess/OpenWrt-luci,fkooman/luci,cshore/luci,sujeet14108/luci,lcf258/openwrtcn,shangjiyu/luci-with-extra,joaofvieira/luci,kuoruan/lede-luci,maxrio/luci981213,lcf258/openwrtcn,forward619/luci,nwf/openwrt-luci,kuoruan/luci,aa65535/luci,cappiewu/luci,lbthomsen/openwrt-luci,hnyman/luci,Wedmer/luci,remakeelectric/luci,tcatm/luci,teslamint/luci,dismantl/luci-0.12,palmettos/cnLuCI,kuoruan/luci,thesabbir/luci,ReclaimYourPrivacy/cloak-luci,Kyklas/luci-proto-hso,ReclaimYourPrivacy/cloak-luci,male-puppies/luci,dwmw2/luci,rogerpueyo/luci,taiha/luci,sujeet14108/luci,zhaoxx063/luci,deepak78/new-luci,wongsyrone/luci-1,mumuqz/luci,urueedi/luci,rogerpueyo/luci,db260179/openwrt-bpi-r1-luci,Sakura-Winkey/LuCI,ff94315/luci-1,teslamint/luci,daofeng2015/luci,RedSnake64/openwrt-luci-packages,keyidadi/luci,obsy/luci,Wedmer/luci,oneru/luci,cshore/luci,lbthomsen/openwrt-luci,daofeng2015/luci,Wedmer/luci,Sakura-Winkey/LuCI,zhaoxx063/luci,dwmw2/luci,thesabbir/luci,obsy/luci,urueedi/luci,forward619/luci,remakeelectric/luci,thesabbir/luci,thesabbir/luci,openwrt/luci,RedSnake64/openwrt-luci-packages,aircross/OpenWrt-Firefly-LuCI,dismantl/luci-0.12,LazyZhu/openwrt-luci-trunk-mod,palmettos/cnLuCI,sujeet14108/luci,maxrio/luci981213,joaofvieira/luci,marcel-sch/luci,palmettos/test,florian-shellfire/luci,sujeet14108/luci,hnyman/luci,oyido/luci,artynet/luci,schidler/ionic-luci,LuttyYang/luci,david-xiao/luci,slayerrensky/luci,obsy/luci,jorgifumi/luci,hnyman/luci,keyidadi/luci,dismantl/luci-0.12,Noltari/luci,Sakura-Winkey/LuCI,Wedmer/luci,Noltari/luci,florian-shellfire/luci,slayerrensky/luci,male-puppies/luci,palmettos/cnLuCI,cshore-firmware/openwrt-luci,openwrt-es/openwrt-luci,nwf/openwrt-luci,taiha/luci,florian-shellfire/luci,NeoRaider/luci,bittorf/luci,openwrt-es/openwrt-luci,cshore-firmware/openwrt-luci,dwmw2/luci,forward619/luci,harveyhu2012/luci,cappiewu/luci,slayerrensky/luci,MinFu/luci,nwf/openwrt-luci,openwrt/luci,opentechinstitute/luci,jorgifumi/luci,opentechinstitute/luci,maxrio/luci981213,obsy/luci,Hostle/luci,openwrt/luci,david-xiao/luci,Hostle/luci,aircross/OpenWrt-Firefly-LuCI,ReclaimYourPrivacy/cloak-luci,Hostle/luci,florian-shellfire/luci,jchuang1977/luci-1,bittorf/luci,tcatm/luci,nmav/luci,keyidadi/luci,cappiewu/luci,kuoruan/luci,ollie27/openwrt_luci,zhaoxx063/luci,Kyklas/luci-proto-hso,tobiaswaldvogel/luci,deepak78/new-luci,maxrio/luci981213,artynet/luci,mumuqz/luci,remakeelectric/luci,kuoruan/luci,thess/OpenWrt-luci,LuttyYang/luci,david-xiao/luci,ff94315/luci-1,teslamint/luci,openwrt-es/openwrt-luci,cshore-firmware/openwrt-luci,kuoruan/lede-luci,david-xiao/luci,mumuqz/luci,aa65535/luci,artynet/luci,cshore/luci,nmav/luci,thess/OpenWrt-luci,nmav/luci,opentechinstitute/luci,MinFu/luci,rogerpueyo/luci,shangjiyu/luci-with-extra,LuttyYang/luci,lbthomsen/openwrt-luci,cshore/luci,dwmw2/luci,thess/OpenWrt-luci,maxrio/luci981213,male-puppies/luci,cappiewu/luci,nwf/openwrt-luci,taiha/luci,nmav/luci,RuiChen1113/luci,RedSnake64/openwrt-luci-packages,tcatm/luci,cshore-firmware/openwrt-luci,sujeet14108/luci,forward619/luci,chris5560/openwrt-luci,chris5560/openwrt-luci,palmettos/cnLuCI,hnyman/luci,palmettos/test,Kyklas/luci-proto-hso,Noltari/luci,MinFu/luci,LuttyYang/luci,maxrio/luci981213,openwrt-es/openwrt-luci,wongsyrone/luci-1,aircross/OpenWrt-Firefly-LuCI,harveyhu2012/luci,kuoruan/lede-luci,bright-things/ionic-luci,harveyhu2012/luci,artynet/luci,lcf258/openwrtcn,jlopenwrtluci/luci,tcatm/luci,Hostle/openwrt-luci-multi-user,taiha/luci,lcf258/openwrtcn,artynet/luci,lbthomsen/openwrt-luci,marcel-sch/luci,slayerrensky/luci,lcf258/openwrtcn,Hostle/luci,rogerpueyo/luci,nmav/luci,male-puppies/luci,lcf258/openwrtcn,joaofvieira/luci,ff94315/luci-1,taiha/luci,tobiaswaldvogel/luci,Kyklas/luci-proto-hso,artynet/luci,thesabbir/luci,tobiaswaldvogel/luci,jchuang1977/luci-1,oneru/luci,marcel-sch/luci,schidler/ionic-luci,jchuang1977/luci-1,openwrt/luci,zhaoxx063/luci,keyidadi/luci,aa65535/luci,sujeet14108/luci,lcf258/openwrtcn,Hostle/luci,981213/luci-1,fkooman/luci,daofeng2015/luci,male-puppies/luci,urueedi/luci,sujeet14108/luci,slayerrensky/luci,oyido/luci,jlopenwrtluci/luci,palmettos/test,daofeng2015/luci,remakeelectric/luci,cappiewu/luci,bright-things/ionic-luci,rogerpueyo/luci,bittorf/luci,artynet/luci,schidler/ionic-luci,shangjiyu/luci-with-extra,taiha/luci,deepak78/new-luci,981213/luci-1,deepak78/new-luci,RuiChen1113/luci,schidler/ionic-luci,NeoRaider/luci,ollie27/openwrt_luci,ff94315/luci-1,Sakura-Winkey/LuCI,Kyklas/luci-proto-hso,NeoRaider/luci,fkooman/luci,bittorf/luci,thess/OpenWrt-luci,harveyhu2012/luci,hnyman/luci,remakeelectric/luci,rogerpueyo/luci,forward619/luci,joaofvieira/luci,cshore/luci,palmettos/cnLuCI,opentechinstitute/luci,openwrt/luci,teslamint/luci,bright-things/ionic-luci,harveyhu2012/luci,zhaoxx063/luci,LazyZhu/openwrt-luci-trunk-mod,male-puppies/luci,urueedi/luci,db260179/openwrt-bpi-r1-luci,oneru/luci,obsy/luci,MinFu/luci,shangjiyu/luci-with-extra,opentechinstitute/luci,male-puppies/luci,RedSnake64/openwrt-luci-packages,oyido/luci
03b5681d47e5af0c2d92e165bba0c50a35ec791c
src/lua/api-gateway/util/logger.lua
src/lua/api-gateway/util/logger.lua
local set = false function getLogFormat(level, debugInfo, ...) return level, "[", debugInfo.short_src, ":", debugInfo.currentline, ":", debugInfo.name, "() req_id=", tostring(ngx.var.requestId), "] ", ... end function _decorateLogger() if not set then local oldNgx = ngx.log ngx.log = function(level, ...) local debugInfo = debug.getinfo(2) pcall(function(...) oldNgx(getLogFormat(level, debugInfo, ...)) end, ...) end set = true end end return { decorateLogger = _decorateLogger }
local set = false --- -- Checks and returns the ngx.var.requestId if possible -- ngx.var is not accessible in some nginx phases like init phase and so we also check this -- local function is_in_init_phase() return ngx.var.requestId end --- -- Get an error log format level, [file:currentline:function_name() req_id=<request_id>], message. This is passed to the -- original ngx.log function -- @param level - the log level like ngx.DEBUG, ngx.INFO, etc. -- @param debugInfo - the debug.getinfo() table needed for the stacktrace -- @param ... - other variables normally passed to ngx.log(), in general string concatenation -- local function getLogFormat(level, debugInfo, ...) local status, request_id = pcall(is_in_init_phase) --- testing for init phase if not status then request_id = "N/A" end return level, "[", debugInfo.short_src, ":", debugInfo.currentline, ":", debugInfo.name, "() req_id=", tostring(request_id), "] ", ... end --- -- Replaces the ngx.log function with the original ngx.log but redecorate the message -- local function _decorateLogger() if not set then local oldNgx = ngx.log ngx.log = function(level, ...) -- gets the level 2 because level 1 is this function and I need my caller -- nSl means line, name, source local debugInfo = debug.getinfo(2, "nSl") pcall(function(...) oldNgx(getLogFormat(level, debugInfo, ...)) end, ...) end set = true end end return { decorateLogger = _decorateLogger }
[WS-11856] Fix logger decorator for callbacks (#60)
[WS-11856] Fix logger decorator for callbacks (#60) * fixing logger * fixing the logger * better getinfo * update format for logger * fixing logger * fixing the logger * better getinfo * update format for logger * update logger * update docs * additional docs * update docs
Lua
mit
adobe-apiplatform/api-gateway-request-validation,adobe-apiplatform/api-gateway-request-validation
f8d00f587abf29b1482cc89cc88b3bd42f204f64
mod_webpresence/mod_webpresence.lua
mod_webpresence/mod_webpresence.lua
module:depends("http"); local jid_split = require "util.jid".prepped_split; local b64 = require "util.encodings".base64.encode; local sha1 = require "util.hashes".sha1; local stanza = require "util.stanza".stanza; local json = require "util.json".encode_ordered; local function require_resource(name) local icon_path = module:get_option_string("presence_icons", "icons"); local f, err = module:load_resource(icon_path.."/"..name); if f then return f:read("*a"); end module:log("warn", "Failed to open image file %s", icon_path..name); return ""; end local statuses = { online = {}, away = {}, xa = {}, dnd = {}, chat = {}, offline = {} }; local function handle_request(event, path) local status, message; local jid, type = path:match("([^/]+)/?(.*)$"); if jid then local user, host = jid_split(jid); if host and not user then user, host = host, event.request.headers.host; if host then host = host:gsub(":%d+$", ""); end end if user and host then local user_sessions = hosts[host] and hosts[host].sessions[user]; if user_sessions then status = user_sessions.top_resources[1]; if status and status.presence then message = status.presence:child_with_name("status"); status = status.presence:child_with_name("show"); if not status then status = "online"; else status = status:get_text(); end if message then message = message:get_text(); end end end end end status = status or "offline"; if type == "" then type = "image" end; statuses[status].image = function() return { status_code = 200, headers = { content_type = "image/png" }, body = require_resource("status_"..status..".png") }; end; statuses[status].html = function() local jid_hash = sha1(jid, true); return { status_code = 200, headers = { content_type = "text/html" }, body = [[<!DOCTYPE html>]].. tostring( stanza("html") :tag("head") :tag("title"):text("XMPP Status Page for "..jid):up():up() :tag("body") :tag("div", { id = jid_hash.."_status", class = "xmpp_status" }) :tag("img", { id = jid_hash.."_img", class = "xmpp_status_image xmpp_status_"..status, src = "data:image/png;base64,"..b64(require_resource("status_"..status..".png")) }):up() :tag("span", { id = jid_hash.."_status_name", class = "xmpp_status_name" }) :text("\194\160"..status):up() :tag("span", { id = jid_hash.."_status_message", class = "xmpp_status_message" }) :text(message and "\194\160"..message.."" or "") ) }; end; statuses[status].text = function() return { status_code = 200, headers = { content_type = "text/plain" }, body = status }; end; statuses[status].message = function() return { status_code = 200, headers = { content_type = "text/plain" }, body = (message and message or "") }; end; statuses[status].json = function() return { status_code = 200, headers = { content_type = "application/json" }, body = json({ jid = jid, show = status, status = (message and message or "null") }) }; end; statuses[status].xml = function() return { status_code = 200, headers = { content_type = "application/xml" }, body = [[<?xml version="1.0" encoding="utf-8"?>]].. tostring( stanza("result") :tag("jid"):text(jid):up() :tag("show"):text(status):up() :tag("status"):text(message) ) }; end return statuses[status][type](); end module:provides("http", { default_path = "/status"; route = { ["GET /*"] = handle_request; }; });
module:depends("http"); local jid_split = require "util.jid".prepped_split; local b64 = require "util.encodings".base64.encode; local sha1 = require "util.hashes".sha1; local stanza = require "util.stanza".stanza; local json = require "util.json".encode_ordered; local function require_resource(name) local icon_path = module:get_option_string("presence_icons", "icons"); local f, err = module:load_resource(icon_path.."/"..name); if f then return f:read("*a"); end module:log("warn", "Failed to open image file %s", icon_path..name); return ""; end local statuses = { online = {}, away = {}, xa = {}, dnd = {}, chat = {}, offline = {} }; local function handle_request(event, path) local status, message; local jid, type = path:match("([^/]+)/?(.*)$"); if jid then local user, host = jid_split(jid); if host and not user then user, host = host, event.request.headers.host; if host then host = host:gsub(":%d+$", ""); end end if user and host then local user_sessions = hosts[host] and hosts[host].sessions[user]; if user_sessions then status = user_sessions.top_resources[1]; if status and status.presence then message = status.presence:child_with_name("status"); status = status.presence:child_with_name("show"); if not status then status = "online"; else status = status:get_text(); end if message then message = message:get_text(); end end end end end status = status or "offline"; statuses[status].image = function() return { status_code = 200, headers = { content_type = "image/png" }, body = require_resource("status_"..status..".png") }; end; statuses[status].html = function() local jid_hash = sha1(jid, true); return { status_code = 200, headers = { content_type = "text/html" }, body = [[<!DOCTYPE html>]].. tostring( stanza("html") :tag("head") :tag("title"):text("XMPP Status Page for "..jid):up():up() :tag("body") :tag("div", { id = jid_hash.."_status", class = "xmpp_status" }) :tag("img", { id = jid_hash.."_img", class = "xmpp_status_image xmpp_status_"..status, src = "data:image/png;base64,"..b64(require_resource("status_"..status..".png")) }):up() :tag("span", { id = jid_hash.."_status_name", class = "xmpp_status_name" }) :text("\194\160"..status):up() :tag("span", { id = jid_hash.."_status_message", class = "xmpp_status_message" }) :text(message and "\194\160"..message.."" or "") ) }; end; statuses[status].text = function() return { status_code = 200, headers = { content_type = "text/plain" }, body = status }; end; statuses[status].message = function() return { status_code = 200, headers = { content_type = "text/plain" }, body = (message and message or "") }; end; statuses[status].json = function() return { status_code = 200, headers = { content_type = "application/json" }, body = json({ jid = jid, show = status, status = (message and message or "null") }) }; end; statuses[status].xml = function() return { status_code = 200, headers = { content_type = "application/xml" }, body = [[<?xml version="1.0" encoding="utf-8"?>]].. tostring( stanza("result") :tag("jid"):text(jid):up() :tag("show"):text(status):up() :tag("status"):text(message) ) }; end if ((type == "") or (not statuses[status][type])) then type = "image" end; return statuses[status][type](); end module:provides("http", { default_path = "/status"; route = { ["GET /*"] = handle_request; }; });
mod_webpresence: fixed render-type handling (thanks to biszkopcik and Zash)
mod_webpresence: fixed render-type handling (thanks to biszkopcik and Zash)
Lua
mit
Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules
0985ba0ef13f664f31b8f844165b3684bf963dd1
src/websocket/server_ev.lua
src/websocket/server_ev.lua
local socket = require'socket' local tools = require'websocket.tools' local frame = require'websocket.frame' local handshake = require'websocket.handshake' local tconcat = table.concat local tinsert = table.insert local ev local loop local clients = {} clients[true] = {} local client = function(sock,protocol) assert(sock) sock:setoption('tcp-nodelay',true) local fd = sock:getfd() local message_io local close_timer local async_send = require'websocket.ev_common'.async_send(sock,loop) local self = {} self.state = 'OPEN' local user_on_error local on_error = function(s,err) clients[protocol][self] = nil if user_on_error then user_on_error(self,err) else print('Websocket server error',err) end end local user_on_close local on_close = function(was_clean,code,reason) clients[protocol][self] = nil if close_timer then close_timer:stop(loop) close_timer = nil end message_io:stop(loop) self.state = 'CLOSED' if user_on_close then user_on_close(self,was_clean,code,reason or '') end sock:shutdown() sock:close() end local handle_sock_err = function(err) if err == 'closed' then if self.state ~= 'CLOSED' then on_close(false,1006,'') end else on_error(err) end end local user_on_message local on_message = function(message,opcode) if opcode == frame.TEXT or opcode == frame.BINARY then if user_on_message then user_on_message(self,message,opcode) end elseif opcode == frame.CLOSE then if self.state ~= 'CLOSING' then self.state = 'CLOSING' local code,reason = frame.decode_close(message) local encoded = frame.encode_close(code) encoded = frame.encode(encoded,frame.CLOSE) async_send(encoded, function() on_close(true,code or 1006,reason) end,handle_sock_err) else on_close(true,code or 1006,reason) end end end self.send = function(_,message,opcode) local encoded = frame.encode(message,opcode or frame.TEXT) async_send(encoded) end self.on_close = function(_,on_close_arg) user_on_close = on_close_arg end self.on_error = function(_,on_error_arg) user_on_error = on_error_arg end self.on_message = function(_,on_message_arg) user_on_message = on_message_arg end self.broadcast = function(_,...) for client in pairs(clients[protocol]) do if client.state == 'OPEN' then client:send(...) end end end self.close = function(_,code,reason,timeout) clients[protocol][self] = nil if not message_io then self:start() end if self.state == 'OPEN' then self.state = 'CLOSING' assert(message_io) timeout = timeout or 3 local encoded = frame.encode_close(code or 1000,reason or '') encoded = frame.encode(encoded,frame.CLOSE) async_send(encoded) close_timer = ev.Timer.new(function() close_timer = nil on_close(false,1006,'timeout') end,timeout) close_timer:start(loop) end end self.start = function() message_io = require'websocket.ev_common'.message_io( sock,loop, on_message, handle_sock_err) end return self end local listen = function(opts) assert(opts and (opts.protocols or opts.default)) ev = require'ev' loop = opts.loop or ev.Loop.default local on_error = function(s,err) print(err) end local protocols = {} if opts.protocols then for protocol in pairs(opts.protocols) do clients[protocol] = {} tinsert(protocols,protocol) end end local self = {} local listener,err = socket.bind(opts.interface or '*',opts.port or 80) assert(listener,err) listener:settimeout(0) local listen_io = ev.IO.new( function() local client_sock = listener:accept() client_sock:settimeout(0) assert(client_sock) local request = {} ev.IO.new( function(loop,read_io) repeat local line,err,part = client_sock:receive('*l') if line then if last then line = last..line last = nil end request[#request+1] = line elseif err ~= 'timeout' then on_error(self,'Websocket Handshake failed due to socket err:'..err) read_io:stop(loop) return else last = part return end until line == '' read_io:stop(loop) local upgrade_request = tconcat(request,'\r\n') local response,protocol = handshake.accept_upgrade(upgrade_request,protocols) if not response then print('Handshake failed, Request:') print(upgrade_request) client_sock:close() return end local index ev.IO.new( function(loop,write_io) local len = #response local sent,err = client_sock:send(response,index) if not sent then write_io:stop(loop) print('Websocket client closed while handshake',err) elseif sent == len then write_io:stop(loop) local handler local new_client local protocol_index if protocol and opts.protocols[protocol] then protocol_index = protocol handler = opts.protocols[protocol] elseif opts.default then -- true is the 'magic' index for the default handler protocol_index = true handler = opts.default else client_sock:close() if on_error then on_error('bad protocol') end return end new_client = client(client_sock,protocol_index) clients[protocol_index][new_client] = true handler(new_client) new_client:start(loop) else assert(sent < len) index = sent end end,client_sock:getfd(),ev.WRITE):start(loop) end,client_sock:getfd(),ev.READ):start(loop) end,listener:getfd(),ev.READ) self.close = function(keep_clients) listen_io:stop(loop) listener:close() listener = nil if not keep_clients then for protocol,clients in pairs(clients) do for client in pairs(clients) do client:close() end end end end listen_io:start(loop) return self end return { listen = listen }
local socket = require'socket' local tools = require'websocket.tools' local frame = require'websocket.frame' local handshake = require'websocket.handshake' local tconcat = table.concat local tinsert = table.insert local ev local loop local clients = {} clients[true] = {} local client = function(sock,protocol) assert(sock) sock:setoption('tcp-nodelay',true) local fd = sock:getfd() local message_io local close_timer local async_send = require'websocket.ev_common'.async_send(sock,loop) local self = {} self.state = 'OPEN' local user_on_error local on_error = function(s,err) if clients[protocol] ~= nil and clients[protocol][self] ~= nil then clients[protocol][self] = nil end if user_on_error then user_on_error(self,err) else print('Websocket server error',err) end end local user_on_close local on_close = function(was_clean,code,reason) if clients[protocol] ~= nil and clients[protocol][self] ~= nil then clients[protocol][self] = nil end if close_timer then close_timer:stop(loop) close_timer = nil end message_io:stop(loop) self.state = 'CLOSED' if user_on_close then user_on_close(self,was_clean,code,reason or '') end sock:shutdown() sock:close() end local handle_sock_err = function(err) if err == 'closed' then if self.state ~= 'CLOSED' then on_close(false,1006,'') end else on_error(err) end end local user_on_message local on_message = function(message,opcode) if opcode == frame.TEXT or opcode == frame.BINARY then if user_on_message then user_on_message(self,message,opcode) end elseif opcode == frame.CLOSE then if self.state ~= 'CLOSING' then self.state = 'CLOSING' local code,reason = frame.decode_close(message) local encoded = frame.encode_close(code) encoded = frame.encode(encoded,frame.CLOSE) async_send(encoded, function() on_close(true,code or 1006,reason) end,handle_sock_err) else on_close(true,code or 1006,reason) end end end self.send = function(_,message,opcode) local encoded = frame.encode(message,opcode or frame.TEXT) async_send(encoded) end self.on_close = function(_,on_close_arg) user_on_close = on_close_arg end self.on_error = function(_,on_error_arg) user_on_error = on_error_arg end self.on_message = function(_,on_message_arg) user_on_message = on_message_arg end self.broadcast = function(_,...) for client in pairs(clients[protocol]) do if client.state == 'OPEN' then client:send(...) end end end self.close = function(_,code,reason,timeout) if clients[protocol] ~= nil and clients[protocol][self] ~= nil then clients[protocol][self] = nil end if not message_io then self:start() end if self.state == 'OPEN' then self.state = 'CLOSING' assert(message_io) timeout = timeout or 3 local encoded = frame.encode_close(code or 1000,reason or '') encoded = frame.encode(encoded,frame.CLOSE) async_send(encoded) close_timer = ev.Timer.new(function() close_timer = nil on_close(false,1006,'timeout') end,timeout) close_timer:start(loop) end end self.start = function() message_io = require'websocket.ev_common'.message_io( sock,loop, on_message, handle_sock_err) end return self end local listen = function(opts) assert(opts and (opts.protocols or opts.default)) ev = require'ev' loop = opts.loop or ev.Loop.default local on_error = function(s,err) print(err) end local protocols = {} if opts.protocols then for protocol in pairs(opts.protocols) do clients[protocol] = {} tinsert(protocols,protocol) end end local self = {} local listener,err = socket.bind(opts.interface or '*',opts.port or 80) assert(listener,err) listener:settimeout(0) local listen_io = ev.IO.new( function() local client_sock = listener:accept() client_sock:settimeout(0) assert(client_sock) local request = {} ev.IO.new( function(loop,read_io) repeat local line,err,part = client_sock:receive('*l') if line then if last then line = last..line last = nil end request[#request+1] = line elseif err ~= 'timeout' then on_error(self,'Websocket Handshake failed due to socket err:'..err) read_io:stop(loop) return else last = part return end until line == '' read_io:stop(loop) local upgrade_request = tconcat(request,'\r\n') local response,protocol = handshake.accept_upgrade(upgrade_request,protocols) if not response then print('Handshake failed, Request:') print(upgrade_request) client_sock:close() return end local index ev.IO.new( function(loop,write_io) local len = #response local sent,err = client_sock:send(response,index) if not sent then write_io:stop(loop) print('Websocket client closed while handshake',err) elseif sent == len then write_io:stop(loop) local handler local new_client local protocol_index if protocol and opts.protocols[protocol] then protocol_index = protocol handler = opts.protocols[protocol] elseif opts.default then -- true is the 'magic' index for the default handler protocol_index = true handler = opts.default else client_sock:close() if on_error then on_error('bad protocol') end return end new_client = client(client_sock,protocol_index) clients[protocol_index][new_client] = true handler(new_client) new_client:start(loop) else assert(sent < len) index = sent end end,client_sock:getfd(),ev.WRITE):start(loop) end,client_sock:getfd(),ev.READ):start(loop) end,listener:getfd(),ev.READ) self.close = function(keep_clients) listen_io:stop(loop) listener:close() listener = nil if not keep_clients then for protocol,clients in pairs(clients) do for client in pairs(clients) do client:close() end end end end listen_io:start(loop) return self end return { listen = listen }
[hotfix] Fix fail when try to close client connected with unsupported protocol name
[hotfix] Fix fail when try to close client connected with unsupported protocol name
Lua
mit
KSDaemon/lua-websockets,lipp/lua-websockets,enginix/lua-websockets,KSDaemon/lua-websockets,enginix/lua-websockets,lipp/lua-websockets,OptimusLime/lua-websockets,KSDaemon/lua-websockets,OptimusLime/lua-websockets,OptimusLime/lua-websockets,enginix/lua-websockets,lipp/lua-websockets
2895647e0878fd7aae554635832f378aa0878f2f
src/apps/lwaftr/V4V6.lua
src/apps/lwaftr/V4V6.lua
module(..., package.seeall) local constants = require("apps.lwaftr.constants") local lwutil = require("apps.lwaftr.lwutil") local shm = require("core.shm") local link = require("core.link") local engine = require("core.app") local transmit, receive = link.transmit, link.receive local rd16, rd32 = lwutil.rd16, lwutil.rd32 local ethernet_header_size = constants.ethernet_header_size local n_ethertype_ipv4 = constants.n_ethertype_ipv4 local n_ethertype_arp = constants.n_ethertype_arp local o_ethernet_ethertype = constants.o_ethernet_ethertype local o_ipv4_dst_addr = constants.o_ipv4_dst_addr local o_ipv4_src_addr = constants.o_ipv4_src_addr local ipv6_fixed_header_size = constants.ipv6_fixed_header_size local v4v6_mirror = shm.create("v4v6_mirror", "struct { uint32_t ipv4; }") local MIRROR_EVERYTHING = 0xffffffff local function is_ipv4 (pkt) local ethertype = rd16(pkt.data + o_ethernet_ethertype) return ethertype == n_ethertype_ipv4 or ethertype == n_ethertype_arp end local function get_ethernet_payload (pkt) return pkt.data + ethernet_header_size end local function get_ipv4_dst_num (ptr) return rd32(ptr + o_ipv4_dst_addr) end local function get_ipv4_src_num (ptr) return rd32(ptr + o_ipv4_src_addr) end local function get_ipv6_payload (ptr) return ptr + ipv6_fixed_header_size end local function mirror_ipv4 (pkt, output, ipv4_num) if ipv4_num == MIRROR_EVERYTHING then transmit(output, packet.clone(pkt)) else local ipv4_hdr = get_ethernet_payload(pkt) if get_ipv4_dst_num(ipv4_hdr) == ipv4_num or get_ipv4_src_num(ipv4_hdr) == ipv4_num then transmit(output, packet.clone(pkt)) end end end local function mirror_ipv6 (pkt, output, ipv4_num) if ipv4_num == MIRROR_EVERYTHING then transmit(output, packet.clone(pkt)) else local ipv6_hdr = get_ethernet_payload(pkt) local ipv4_hdr = get_ipv6_payload(ipv6_hdr) if get_ipv4_dst_num(ipv4_hdr) == ipv4_num or get_ipv4_src_num(ipv4_hdr) == ipv4_num then transmit(output, packet.clone(pkt)) end end end V4V6 = { config = { description = {default="V4V6"}, mirror = {default=false}, } } function V4V6:new (conf) local o = { description = conf.description, mirror = conf.mirror, } return setmetatable(o, {__index = V4V6}) end function V4V6:push() local input, output = self.input.input, self.output.output local v4_tx, v6_tx = self.output.v4, self.output.v6 local v4_rx, v6_rx = self.input.v4, self.input.v6 local mirror = self.output.mirror local ipv4_num if self.mirror then mirror = self.output.mirror ipv4_num = v4v6_mirror.ipv4 end -- Split input to IPv4 and IPv6 traffic. if input then while not link.empty(input) do local pkt = receive(input) if is_ipv4(pkt) then if mirror then mirror_ipv4(pkt, mirror, ipv4_num) end transmit(v4_tx, pkt) else if mirror then mirror_ipv6(pkt, mirror, ipv4_num) end transmit(v6_tx, pkt) end end end -- Join IPv4 and IPv6 traffic to output. if output then while not link.empty(v4_rx) do local pkt = receive(v4_rx) if mirror and not link.full(mirror) then mirror_ipv4(pkt, mirror, ipv4_num) end transmit(output, pkt) end while not link.empty(v6_rx) do local pkt = receive(v6_rx) if mirror then mirror_ipv6(pkt, mirror, ipv4_num) end transmit(output, pkt) end end end -- Tests. local function ipv4_pkt () local lib = require("core.lib") return packet.from_string(lib.hexundump([[ 02 aa aa aa aa aa 02 99 99 99 99 99 08 00 45 00 02 18 00 00 00 00 0f 11 d3 61 0a 0a 0a 01 c1 05 01 64 30 39 14 00 00 20 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ]], 66)) end local function ipv6_pkt () local lib = require("core.lib") return packet.from_string(lib.hexundump([[ 02 aa aa aa aa aa 02 99 99 99 99 99 86 dd 60 00 01 f0 01 f0 04 ff fc 00 00 01 00 02 00 03 00 04 00 05 00 00 44 2d fc 00 00 00 00 00 00 00 00 00 00 00 00 00 01 00 45 00 01 f0 00 00 00 00 0f 11 d2 76 c1 05 02 77 0a 0a 0a 01 0c 00 30 39 00 20 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ]], 106)) end local function arp_pkt () local lib = require("core.lib") return packet.from_string(lib.hexundump([[ ff ff ff ff ff ff 22 22 22 22 22 22 08 06 00 01 08 00 06 04 00 01 22 22 22 22 22 22 0a 0a 0a 0a 00 00 00 00 00 00 04 05 06 07 ]], 42)) end local function test_split () local basic_apps = require("apps.basic.basic_apps") engine.configure(config.new()) -- Clean up engine. local c = config.new() config.app(c, 'source', basic_apps.Join) config.app(c, 'v4v6', V4V6) config.app(c, 'sink', basic_apps.Sink) config.link(c, 'source.output -> v4v6.input') config.link(c, 'v4v6.v4 -> sink.in1') config.link(c, 'v4v6.v6 -> sink.in2') engine.configure(c) link.transmit(engine.app_table.source.output.output, arp_pkt()) link.transmit(engine.app_table.source.output.output, ipv4_pkt()) link.transmit(engine.app_table.source.output.output, ipv6_pkt()) engine.main({duration = 0.1, noreport = true}) assert(link.stats(engine.app_table.sink.input.in1).rxpackets == 2) assert(link.stats(engine.app_table.sink.input.in2).rxpackets == 1) end local function test_join () local basic_apps = require("apps.basic.basic_apps") engine.configure(config.new()) -- Clean up engine. local c = config.new() config.app(c, 'source', basic_apps.Join) config.app(c, 'v4v6', V4V6) config.app(c, 'sink', basic_apps.Sink) config.link(c, 'source.output -> v4v6.v4') config.link(c, 'source.output -> v4v6.v6') config.link(c, 'v4v6.output -> sink.input') engine.configure(c) link.transmit(engine.app_table.source.output.output, arp_pkt()) link.transmit(engine.app_table.source.output.output, ipv4_pkt()) link.transmit(engine.app_table.source.output.output, ipv6_pkt()) engine.main({duration = 0.1, noreport = true}) assert(link.stats(engine.app_table.sink.input.input).rxpackets == 3) end function selftest () print("V4V6: selftest") test_split() test_join() print("OK") end
module(..., package.seeall) local constants = require("apps.lwaftr.constants") local lwutil = require("apps.lwaftr.lwutil") local shm = require("core.shm") local link = require("core.link") local engine = require("core.app") local transmit, receive = link.transmit, link.receive local rd16, rd32 = lwutil.rd16, lwutil.rd32 local ethernet_header_size = constants.ethernet_header_size local n_ethertype_ipv4 = constants.n_ethertype_ipv4 local n_ethertype_arp = constants.n_ethertype_arp local o_ethernet_ethertype = constants.o_ethernet_ethertype local o_ipv4_dst_addr = constants.o_ipv4_dst_addr local o_ipv4_src_addr = constants.o_ipv4_src_addr local ipv6_fixed_header_size = constants.ipv6_fixed_header_size local v4v6_mirror = shm.create("v4v6_mirror", "struct { uint32_t ipv4; }") local MIRROR_EVERYTHING = 0xffffffff local function is_ipv4 (pkt) local ethertype = rd16(pkt.data + o_ethernet_ethertype) return ethertype == n_ethertype_ipv4 or ethertype == n_ethertype_arp end local function get_ethernet_payload (pkt) return pkt.data + ethernet_header_size end local function get_ipv4_dst_num (ptr) return rd32(ptr + o_ipv4_dst_addr) end local function get_ipv4_src_num (ptr) return rd32(ptr + o_ipv4_src_addr) end local function get_ipv6_payload (ptr) return ptr + ipv6_fixed_header_size end local function mirror_ipv4 (pkt, output, ipv4_num) if ipv4_num == MIRROR_EVERYTHING then transmit(output, packet.clone(pkt)) else local ipv4_hdr = get_ethernet_payload(pkt) if get_ipv4_dst_num(ipv4_hdr) == ipv4_num or get_ipv4_src_num(ipv4_hdr) == ipv4_num then transmit(output, packet.clone(pkt)) end end end local function mirror_ipv6 (pkt, output, ipv4_num) if ipv4_num == MIRROR_EVERYTHING then transmit(output, packet.clone(pkt)) else local ipv6_hdr = get_ethernet_payload(pkt) local ipv4_hdr = get_ipv6_payload(ipv6_hdr) if get_ipv4_dst_num(ipv4_hdr) == ipv4_num or get_ipv4_src_num(ipv4_hdr) == ipv4_num then transmit(output, packet.clone(pkt)) end end end V4V6 = { config = { description = {default="V4V6"}, mirror = {default=false}, } } function V4V6:new (conf) local o = { description = conf.description, mirror = conf.mirror, } return setmetatable(o, {__index = V4V6}) end function V4V6:push() local input, output = self.input.input, self.output.output local v4_tx, v6_tx = self.output.v4, self.output.v6 local v4_rx, v6_rx = self.input.v4, self.input.v6 local mirror = self.output.mirror local ipv4_num if self.mirror then mirror = self.output.mirror ipv4_num = v4v6_mirror.ipv4 end -- Split input to IPv4 and IPv6 traffic. if input then while not link.empty(input) do local pkt = receive(input) if is_ipv4(pkt) then if mirror then mirror_ipv4(pkt, mirror, ipv4_num) end transmit(v4_tx, pkt) else if mirror then mirror_ipv6(pkt, mirror, ipv4_num) end transmit(v6_tx, pkt) end end end -- Join IPv4 and IPv6 traffic to output. if output then while not link.empty(v4_rx) do local pkt = receive(v4_rx) if mirror and not link.full(mirror) then mirror_ipv4(pkt, mirror, ipv4_num) end transmit(output, pkt) end while not link.empty(v6_rx) do local pkt = receive(v6_rx) if mirror then mirror_ipv6(pkt, mirror, ipv4_num) end transmit(output, pkt) end end end -- Tests. local function ipv4_pkt () local lib = require("core.lib") return packet.from_string(lib.hexundump([[ 02 aa aa aa aa aa 02 99 99 99 99 99 08 00 45 00 02 18 00 00 00 00 0f 11 d3 61 0a 0a 0a 01 c1 05 01 64 30 39 14 00 00 20 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ]], 66)) end local function ipv6_pkt () local lib = require("core.lib") return packet.from_string(lib.hexundump([[ 02 aa aa aa aa aa 02 99 99 99 99 99 86 dd 60 00 01 f0 01 f0 04 ff fc 00 00 01 00 02 00 03 00 04 00 05 00 00 44 2d fc 00 00 00 00 00 00 00 00 00 00 00 00 00 01 00 45 00 01 f0 00 00 00 00 0f 11 d2 76 c1 05 02 77 0a 0a 0a 01 0c 00 30 39 00 20 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ]], 106)) end local function arp_pkt () local lib = require("core.lib") return packet.from_string(lib.hexundump([[ ff ff ff ff ff ff 22 22 22 22 22 22 08 06 00 01 08 00 06 04 00 01 22 22 22 22 22 22 0a 0a 0a 0a 00 00 00 00 00 00 04 05 06 07 ]], 42)) end local function test_split () local basic_apps = require("apps.basic.basic_apps") engine.configure(config.new()) -- Clean up engine. local c = config.new() config.app(c, 'source', basic_apps.Join) config.app(c, 'v4v6', V4V6) config.app(c, 'sink', basic_apps.Sink) config.link(c, 'source.output -> v4v6.input') config.link(c, 'v4v6.v4 -> sink.in1') config.link(c, 'v4v6.v6 -> sink.in2') engine.configure(c) link.transmit(engine.app_table.source.output.output, arp_pkt()) link.transmit(engine.app_table.source.output.output, ipv4_pkt()) link.transmit(engine.app_table.source.output.output, ipv6_pkt()) engine.main({duration = 0.1, noreport = true}) assert(link.stats(engine.app_table.sink.input.in1).rxpackets == 2) assert(link.stats(engine.app_table.sink.input.in2).rxpackets == 1) end local function test_join () local basic_apps = require("apps.basic.basic_apps") engine.configure(config.new()) -- Clean up engine. local c = config.new() config.app(c, 'source', basic_apps.Join) config.app(c, 'v4v6', V4V6) config.app(c, 'sink', basic_apps.Sink) config.link(c, 'source.v4 -> v4v6.v4') config.link(c, 'source.v6 -> v4v6.v6') config.link(c, 'v4v6.output -> sink.input') engine.configure(c) for _, output in ipairs{'v4', 'v6'} do link.transmit(engine.app_table.source.output[output], arp_pkt()) link.transmit(engine.app_table.source.output[output], ipv4_pkt()) link.transmit(engine.app_table.source.output[output], ipv6_pkt()) end engine.main({duration = 0.1, noreport = true}) assert(link.stats(engine.app_table.sink.input.input).rxpackets == 3*2) end function selftest () print("V4V6: selftest") test_split() test_join() print("OK") end
apps.lwaftr.V4V6: fix selftest (test_join)
apps.lwaftr.V4V6: fix selftest (test_join)
Lua
apache-2.0
eugeneia/snabb,snabbco/snabb,snabbco/snabb,eugeneia/snabb,eugeneia/snabb,snabbco/snabb,snabbco/snabb,eugeneia/snabb,eugeneia/snabb,snabbco/snabb,eugeneia/snabb,snabbco/snabb,eugeneia/snabb,snabbco/snabb,snabbco/snabb,eugeneia/snabb
cea771c5803f15e822cb45a47e2d94d9a9ffaaf5
capptain.lua
capptain.lua
#!/usr/bin/env carbon -- Capptain! -- Hosts small apps. kvstore.set("capptain:appdir", arg[1] or "./apps") srv.GET("/", mw.new(function() local apps = (fs.list or io.list)("./apps") local list = {} for _, app in pairs(apps) do local appname = app:gsub("%.lua$", "") table.insert(list, tag"a"[{href=appname}](appname)) table.insert(list, tag"br") end content(doctype()( tag"head"( tag"title" "CApptain | App List" ), tag"body"( tag"h1" "Welcome to CApptain! This is the current App List:", tag"br", unpack(list) ) )) end, {page=mainpage})) handler = function() local app = params("app") local apps = (fs.list or io.list)("./apps") for k, v in pairs(apps) do if v == app..".lua" then local suc, res, code, ctype = pcall(dofile, kvstore.get("capptain:appdir") .. "/"..app..".lua") if not suc then content(doctype()( tag"head"( tag"title" "Error in App "..app ), tag"body"( tag"h1" "Error in App "..app, res ) )) else if res then content(res, code, ctype) end end return end end content("No such app.", 404) end srv.GET("/:app", handler) srv.GET("/:app/*args", handler) print("CApptain loaded up.")
#!/usr/bin/env carbon -- Capptain! -- Hosts small apps. kvstore.set("capptain:appdir", arg[1] or "apps") srv.GET("/", mw.new(function() local apps = (fs.list or io.list)(kvstore.get("capptain:appdir")) local list = {} for _, app in pairs(apps) do local appname = app:gsub("%.lua$", "") table.insert(list, tag"a"[{href=appname}](appname)) table.insert(list, tag"br") end content(doctype()( tag"head"( tag"title" "CApptain | App List" ), tag"body"( tag"h1" "Welcome to CApptain! This is the current App List:", tag"br", unpack(list) ) )) end, {page=mainpage})) handler = function() local app = params("app") local apps = (fs.list or io.list)(kvstore.get("capptain:appdir")) for k, v in pairs(apps) do if v == app..".lua" then local suc, res, code, ctype if fs.readfile then local src = fs.readfile(kvstore.get("capptain:appdir") .. "/"..app..".lua") local f, err = loadstring(src) if f then suc, res, code, ctype = pcall(f) else suc = false res = err end else local suc, res, code, ctype = pcall(dofile, kvstore.get("capptain:appdir") .. "/"..app..".lua") end if not suc then content(doctype()( tag"head"( tag"title"("Error in App "..app) ), tag"body"( tag"h1"("Error in App "..app), res ) )) else if res then content(res, code, ctype) end end return end end content("No such app.", 404) end srv.GET("/:app", handler) srv.GET("/:app/*args", handler) print("CApptain loaded up.")
More fixes for the latest carbon version.
More fixes for the latest carbon version.
Lua
mit
carbonsrv/capptain
4c2ff029696336de23d03dee934b6519c26009da
source/scenes/game.lua
source/scenes/game.lua
module(..., package.seeall) require "source/GuiUtilities" -- import local flower = flower -- local variables local layer = nil local game_thread = nil -- Game singleton Game = {} Game.texture = "hex-tiles.png" Game.width = 50 Game.height = 100 Game.tileWidth = 128 Game.tileHeight = 111 Game.radius = 24 Game.default_tile = 0 Game.algorithms = {} Game.selectedTower = -1 Game.currentCash = 200 Game.currentInterest = "0%" Game.currentScore = 0 -- This function is used by the GuiUtilities file to generate -- the status field in the UI function Game.generateStatus() return "Cash: " .. Game.currentCash .. "\nInterest: " .. Game.currentInterest .. "\nScore: " .. Game.currentScore end function Game.buildGrid() --params = params or {} --Game.texture = params.texture or Game.texture Game.width = Map.width or Game.width Game.height = Map.height or Game.height Game.default_tile = Map.default_tile or Game.default_tile --Game.tileWidth = params.tileWidth or Game.tileWidth --Game.tileHeight = params.tileHeight or Game.tileHeight --Game.radius = params.radius or Game.radius Game.grid = flower.MapImage(Game.texture, Game.width, Game.height, Game.tileWidth, Game.tileHeight, Game.radius) Game.grid:setShape(MOAIGridSpace.HEX_SHAPE) Game.grid:setLayer(layer) Game.grid:setRepeat(false, false) Game.grid:setPos(0,0) --print(Game.height, Game.width) for i = 1,Game.width do for j = 1,Game.height do Game.grid.grid:setTile(i, j, Game.default_tile) end end for i, data in ipairs(Map.tiles) do for j, pos in ipairs(data) do Game.grid.grid:setTile(pos[1], pos[2], i) end end end function onCreate(e) layer = flower.Layer() layer:setTouchEnabled(true) scene:addChild(layer) Game.buildGrid() buildUI("SinglePlayer", e.data.view, Game) end -- TODO: Make this suck less local my_rectangle = nil local current_pos = nil local speed = 10 local direction = 1 function onStart(e) my_rectangle = flower.Rect(10,10) local x, y = Game.grid.grid:getTileLoc(Map.paths[1][1][1], Map.paths[1][1][2], MOAIGridSpace.TILE_CENTER) current_pos = 1 my_rectangle:setPos(x, y) my_rectangle:setColor(1,0,0,1) my_rectangle:setLayer(layer) flower.Executors.callLoop(Game.run) end function Game.run() local m_x, m_y = my_rectangle:getPos() if (current_pos == (#Map.paths[1]) and direction > 0) or (current_pos == 1 and direction < 0) then direction = -direction end local f_x, f_y = Game.grid.grid:getTileLoc(Map.paths[1][current_pos + direction][1], Map.paths[1][current_pos + direction][2], MOAIGridSpace.TILE_CENTER) local angle = math.atan2(f_y - m_y, f_x - m_x) local d_x, d_y = speed * math.cos(angle), speed * math.sin(angle) if math.abs(d_x) >= math.abs(f_x - m_x) and math.abs(d_y) >= math.abs(f_y - m_y) then d_x = f_x - m_x d_y = f_y - m_y current_pos = (current_pos + direction) end my_rectangle:setPos(m_x + d_x, m_y + d_y) end function onStop(e) end
module(..., package.seeall) require "source/GuiUtilities" -- import local flower = flower local math = math local MOAIGridSpace = MOAIGridSpace -- local variables local layer = nil -- Game singleton Game = {} Game.texture = "hex-tiles.png" Game.width = 50 Game.height = 100 Game.tileWidth = 128 Game.tileHeight = 111 Game.radius = 24 Game.default_tile = 0 Game.algorithms = {} Game.selectedTower = -1 Game.direction = 1 Game.speed = 10 Game.currentCash = 200 Game.currentInterest = "0%" Game.currentScore = 0 -- This function is used by the GuiUtilities file to generate -- the status field in the UI function Game.generateStatus() return "Cash: " .. Game.currentCash .. "\nInterest: " .. Game.currentInterest .. "\nScore: " .. Game.currentScore end function Game.buildGrid() --params = params or {} --Game.texture = params.texture or Game.texture Game.width = Map.width or Game.width Game.height = Map.height or Game.height Game.default_tile = Map.default_tile or Game.default_tile --Game.tileWidth = params.tileWidth or Game.tileWidth --Game.tileHeight = params.tileHeight or Game.tileHeight --Game.radius = params.radius or Game.radius Game.grid = flower.MapImage(Game.texture, Game.width, Game.height, Game.tileWidth, Game.tileHeight, Game.radius) Game.grid:setShape(MOAIGridSpace.HEX_SHAPE) Game.grid:setLayer(layer) Game.grid:setRepeat(false, false) Game.grid:setPos(0,0) --print(Game.height, Game.width) for i = 1,Game.width do for j = 1,Game.height do Game.grid.grid:setTile(i, j, Game.default_tile) end end for i, data in ipairs(Map.tiles) do for j, pos in ipairs(data) do Game.grid.grid:setTile(pos[1], pos[2], i) end end end function Game.run() Game.my_rectangle = flower.Rect(10,10) local x, y = Game.grid.grid:getTileLoc(Map.paths[1][1][1], Map.paths[1][1][2], MOAIGridSpace.TILE_CENTER) Game.current_pos = 1 Game.my_rectangle:setPos(x, y) Game.my_rectangle:setColor(1,0,0,1) Game.my_rectangle:setLayer(layer) flower.Executors.callLoop(Game.loop) end function Game.loop() local m_x, m_y = Game.my_rectangle:getPos() if (Game.current_pos == (#Map.paths[1]) and Game.direction > 0) or (Game.current_pos == 1 and Game.direction < 0) then Game.direction = -Game.direction end local f_x, f_y = Game.grid.grid:getTileLoc(Map.paths[1][Game.current_pos + Game.direction][1], Map.paths[1][Game.current_pos + Game.direction][2], MOAIGridSpace.TILE_CENTER) local angle = math.atan2(f_y - m_y, f_x - m_x) local d_x, d_y = Game.speed * math.cos(angle), Game.speed * math.sin(angle) if math.abs(d_x) >= math.abs(f_x - m_x) and math.abs(d_y) >= math.abs(f_y - m_y) then d_x = f_x - m_x d_y = f_y - m_y Game.current_pos = (Game.current_pos + Game.direction) end Game.my_rectangle:setPos(m_x + d_x, m_y + d_y) return Game.stopped end function onCreate(e) layer = flower.Layer() layer:setTouchEnabled(true) scene:addChild(layer) Game.buildGrid() buildUI("SinglePlayer", e.data.view, Game) end function onStart(e) Game.stopped = false Game.run() end function onStop(e) Game.stopped = true end
Fixed single player loop thread from not finishing. Minor refactoring to put all game related code into the Game singleton.
Fixed single player loop thread from not finishing. Minor refactoring to put all game related code into the Game singleton.
Lua
mit
BryceMehring/Hexel
22587f7a42b8328f5668748af6261766b26d660d
WitherSpawner/wither.lua
WitherSpawner/wither.lua
local minFuelLevel = 200 -- Lowest acceptable fuel level. function checkFuel() while turtle.getFuelLevel() < minFuelLevel do turtle.turnRight() turtle.select(3) turtle.suck() turtle.refuel() end end function checkItems() for i=1, 2 do turtle.select(i) n = (64-turtle.getItemCount(turtle.getSelectedSlot())) if i == 1 and n ~= 0 then turtle.turnLeft() turtle.suck(n) end if i == 2 and n ~= 0 then turtle.turnRight() turtle.suckUp(n) end end end while true do if redstone.getAnalogInput("back") == 15 then checkItems() checkFuel() print("Making a wither...") turtle.select(1) turtle.forward() turtle.forward() turtle.down() turtle.place() turtle.up() turtle.place() turtle.turnLeft() turtle.forward() turtle.turnRight() turtle.place() turtle.select(2) turtle.up() turtle.place() turtle.turnRight() turtle.forward() turtle.turnLeft() turtle.place() turtle.down() turtle.select(1) turtle.turnRight() turtle.forward() turtle.turnLeft() turtle.place() turtle.up() turtle.select(2) turtle.place() turtle.down() turtle.turnLeft() turtle.forward() turtle.turnRight() turtle.back() turtle.back() redstone.setOutput("bottom", true) sleep(10) -- Time for spawning a Wither. redstone.setOutput("bottom", false) else sleep(20) end end
local minFuelLevel = 200 -- Lowest acceptable fuel level. function checkFuel() while turtle.getFuelLevel() < minFuelLevel do turtle.turnRight() turtle.select(3) turtle.suck() turtle.refuel() turtle.turnLeft() end end function checkItems() for i=1, 2 do turtle.select(i) n = (64-turtle.getItemCount(turtle.getSelectedSlot())) if i == 1 and n ~= 0 then turtle.turnLeft() turtle.suck(n) turtle.turnRight() end if i == 2 and n ~= 0 then turtle.suckUp(n) end end end while true do if redstone.getAnalogInput("back") == 15 then checkItems() checkFuel() print("Making a wither...") turtle.select(1) turtle.forward() turtle.forward() turtle.down() turtle.place() turtle.up() turtle.place() turtle.turnLeft() turtle.forward() turtle.turnRight() turtle.place() turtle.select(2) turtle.up() turtle.place() turtle.turnRight() turtle.forward() turtle.turnLeft() turtle.place() turtle.down() turtle.select(1) turtle.turnRight() turtle.forward() turtle.turnLeft() turtle.place() turtle.up() turtle.select(2) turtle.place() turtle.down() turtle.turnLeft() turtle.forward() turtle.turnRight() turtle.back() turtle.back() redstone.setOutput("bottom", true) sleep(10) -- Time for spawning a Wither. redstone.setOutput("bottom", false) else sleep(20) end end
Fix movement bug
Fix movement bug
Lua
unlicense
Carlgo11/computercraft
5effbb274bfabbaa23c1281ef144d2e9e8bb0f02
src/lib/nfv/config.lua
src/lib/nfv/config.lua
module(...,package.seeall) local Intel82599 = require("apps.intel.intel_app").Intel82599 local VhostUser = require("apps.vhost.vhost_user").VhostUser local PacketFilter = require("apps.packet_filter.packet_filter").PacketFilter local RateLimiter = require("apps.rate_limiter.rate_limiter").RateLimiter local nd_light = require("apps.ipv6.nd_light") local L2TPv3 = require("apps.keyed_ipv6_tunnel.tunnel").SimpleKeyedTunnel local ffi = require("ffi") local C = ffi.C local lib = require("core.lib") -- Return name of port in <port_config>. function port_name (port_config) return port_config.port_id:gsub("-", "_") end -- Compile app configuration from <file> for <pciaddr> and vhost_user -- <socket>. Returns configuration and zerocopy pairs. function load (file, pciaddr, sockpath) local ports = lib.load_conf(file) local c = config.new() local zerocopy = {} -- {NIC->Virtio} app names to zerocopy link for _,t in ipairs(ports) do local vlan, mac_address = t.vlan, t.mac_address local name = port_name(t) local NIC = "NIC_"..name local Virtio = "Virtio_"..name config.app(c, NIC, Intel82599, {pciaddr = pciaddr, vmdq = true, macaddr = mac_address, vlan = vlan}) config.app(c, Virtio, VhostUser, {socket_path=sockpath:format(name)}) local VM_rx, VM_tx = Virtio..".rx", Virtio..".tx" if t.ingress_filter then local Filter = "Filter_in_"..name config.app(c, Filter, PacketFilter, t.ingress_filter) config.link(c, Filter..".tx -> " .. VM_rx) VM_rx = Filter..".rx" end if t.egress_filter then local Filter = 'Filter_out_'..name config.app(c, Filter, PacketFilter, t.egress_filter) config.link(c, VM_tx..' -> '..Filter..'.rx') VM_tx = Filter..'.tx' end if t.tunnel and t.tunnel.type == "L2TPv3" then local Tunnel = "Tunnel_"..name local conf = {local_address = t.tunnel.local_ip, remote_address = t.tunnel.remote_ip, local_cookie = t.tunnel.local_cookie, remote_cookie = t.tunnel.remote_cookie, local_session = t.tunnel.session} config.app(c, Tunnel, L2TPv3, conf) -- Setup IPv6 neighbor discovery/solicitation responder. -- This will talk to our local gateway. local ND = "ND_"..name config.app(c, ND, nd_light, {local_mac = mac_address, local_ip = t.tunnel.local_ip, next_hop = t.tunnel.next_hop}) -- VM -> Tunnel -> ND <-> Network config.link(c, VM_tx.." -> "..Tunnel..".decapsulated") config.link(c, Tunnel..".encapsulated -> "..ND..".north") -- Network <-> ND -> Tunnel -> VM config.link(c, ND..".north -> "..Tunnel..".encapsulated") config.link(c, Tunnel..".decapsulated -> "..VM_rx) VM_rx, VM_tx = ND..".south", ND..".south" end if t.rx_police_gbps then local QoS = "QoS_"..name local rate = t.rx_police_gbps * 1e9 / 8 config.app(c, QoS, RateLimiter, {rate = rate, bucket_capacity = rate}) config.link(c, VM_tx.." -> "..QoS..".input") VM_tx = QoS..".output" end config.link(c, NIC..".tx -> "..VM_rx) config.link(c, VM_tx.." -> "..NIC..".rx") zerocopy[NIC] = Virtio end -- Return configuration c, and zerocopy pairs. return c, zerocopy end -- Apply configuration <c> to engine and reset <zerocopy> buffers. function apply (c, zerocopy) -- print(config.graphviz(c)) -- main.exit(0) engine.configure(c) for nic, virtio in pairs(zerocopy) do local n = engine.app_table[nic] local v = engine.app_table[virtio] n:set_rx_buffer_freelist(v:rx_buffers()) end end function selftest () print("selftest: lib.nfv.config") local pcideva = os.getenv("SNABB_TEST_INTEL10G_PCIDEVA") if not pcideva then print("SNABB_TEST_INTEL10G_PCIDEVA was not set\nTest skipped") os.exit(engine.test_skipped_code) end engine.log = true for i, confpath in ipairs({"test_fixtures/nfvconfig/switch_nic/x", "test_fixtures/nfvconfig/switch_filter/x", "test_fixtures/nfvconfig/switch_qos/x", "test_fixtures/nfvconfig/switch_tunnel/x", "test_fixtures/nfvconfig/scale_up/y", "test_fixtures/nfvconfig/scale_up/x", "test_fixtures/nfvconfig/scale_change/x", "test_fixtures/nfvconfig/scale_change/y"}) do print("testing:", confpath) apply(load(confpath, pcideva, "/dev/null")) engine.main({duration = 0.25}) end end
module(...,package.seeall) local Intel82599 = require("apps.intel.intel_app").Intel82599 local VhostUser = require("apps.vhost.vhost_user").VhostUser local PacketFilter = require("apps.packet_filter.packet_filter").PacketFilter local RateLimiter = require("apps.rate_limiter.rate_limiter").RateLimiter local nd_light = require("apps.ipv6.nd_light") local L2TPv3 = require("apps.keyed_ipv6_tunnel.tunnel").SimpleKeyedTunnel local ffi = require("ffi") local C = ffi.C local lib = require("core.lib") -- Return name of port in <port_config>. function port_name (port_config) return port_config.port_id:gsub("-", "_") end -- Compile app configuration from <file> for <pciaddr> and vhost_user -- <socket>. Returns configuration and zerocopy pairs. function load (file, pciaddr, sockpath) local ports = lib.load_conf(file) local c = config.new() local zerocopy = {} -- {NIC->Virtio} app names to zerocopy link for _,t in ipairs(ports) do local vlan, mac_address = t.vlan, t.mac_address local name = port_name(t) local NIC = "NIC_"..name local Virtio = "Virtio_"..name config.app(c, NIC, Intel82599, {pciaddr = pciaddr, vmdq = true, macaddr = mac_address, vlan = vlan}) config.app(c, Virtio, VhostUser, {socket_path=sockpath:format(t.port_id)}) local VM_rx, VM_tx = Virtio..".rx", Virtio..".tx" if t.ingress_filter and #t.ingress_filter > 0 then local Filter = "Filter_in_"..name config.app(c, Filter, PacketFilter, t.ingress_filter) config.link(c, Filter..".tx -> " .. VM_rx) VM_rx = Filter..".rx" end if t.egress_filter and #t.egress_filter > 0 then local Filter = 'Filter_out_'..name config.app(c, Filter, PacketFilter, t.egress_filter) config.link(c, VM_tx..' -> '..Filter..'.rx') VM_tx = Filter..'.tx' end if t.tunnel and t.tunnel.type == "L2TPv3" then local Tunnel = "Tunnel_"..name local conf = {local_address = t.tunnel.local_ip, remote_address = t.tunnel.remote_ip, local_cookie = t.tunnel.local_cookie, remote_cookie = t.tunnel.remote_cookie, local_session = t.tunnel.session} config.app(c, Tunnel, L2TPv3, conf) -- Setup IPv6 neighbor discovery/solicitation responder. -- This will talk to our local gateway. local ND = "ND_"..name config.app(c, ND, nd_light, {local_mac = mac_address, local_ip = t.tunnel.local_ip, next_hop = t.tunnel.next_hop}) -- VM -> Tunnel -> ND <-> Network config.link(c, VM_tx.." -> "..Tunnel..".decapsulated") config.link(c, Tunnel..".encapsulated -> "..ND..".north") -- Network <-> ND -> Tunnel -> VM config.link(c, ND..".north -> "..Tunnel..".encapsulated") config.link(c, Tunnel..".decapsulated -> "..VM_rx) VM_rx, VM_tx = ND..".south", ND..".south" end if t.rx_police_gbps then local QoS = "QoS_"..name local rate = t.rx_police_gbps * 1e9 / 8 config.app(c, QoS, RateLimiter, {rate = rate, bucket_capacity = rate}) config.link(c, VM_tx.." -> "..QoS..".input") VM_tx = QoS..".output" end config.link(c, NIC..".tx -> "..VM_rx) config.link(c, VM_tx.." -> "..NIC..".rx") zerocopy[NIC] = Virtio end -- Return configuration c, and zerocopy pairs. return c, zerocopy end -- Apply configuration <c> to engine and reset <zerocopy> buffers. function apply (c, zerocopy) -- print(config.graphviz(c)) -- main.exit(0) engine.configure(c) for nic, virtio in pairs(zerocopy) do local n = engine.app_table[nic] local v = engine.app_table[virtio] n:set_rx_buffer_freelist(v:rx_buffers()) end end function selftest () print("selftest: lib.nfv.config") local pcideva = os.getenv("SNABB_TEST_INTEL10G_PCIDEVA") if not pcideva then print("SNABB_TEST_INTEL10G_PCIDEVA was not set\nTest skipped") os.exit(engine.test_skipped_code) end engine.log = true for i, confpath in ipairs({"test_fixtures/nfvconfig/switch_nic/x", "test_fixtures/nfvconfig/switch_filter/x", "test_fixtures/nfvconfig/switch_qos/x", "test_fixtures/nfvconfig/switch_tunnel/x", "test_fixtures/nfvconfig/scale_up/y", "test_fixtures/nfvconfig/scale_up/x", "test_fixtures/nfvconfig/scale_change/x", "test_fixtures/nfvconfig/scale_change/y"}) do print("testing:", confpath) apply(load(confpath, pcideva, "/dev/null")) engine.main({duration = 0.25}) end end
NFV config: fix function load
NFV config: fix function load - pass t.port_id do virtio - create filter only if there are actually rules (# is >0) Signed-off-by: Nikolay Nikolaev <5fb6ff14f2a3b931c007d120a649a55e86928f6a@virtualopensystems.com>
Lua
apache-2.0
dpino/snabb,heryii/snabb,virtualopensystems/snabbswitch,Igalia/snabb,snabbco/snabb,eugeneia/snabb,eugeneia/snabb,eugeneia/snabb,kellabyte/snabbswitch,lukego/snabb,aperezdc/snabbswitch,fhanik/snabbswitch,SnabbCo/snabbswitch,lukego/snabb,Igalia/snabb,wingo/snabbswitch,snabbco/snabb,alexandergall/snabbswitch,javierguerragiraldez/snabbswitch,Igalia/snabbswitch,eugeneia/snabb,mixflowtech/logsensor,andywingo/snabbswitch,eugeneia/snabb,Igalia/snabbswitch,snabbco/snabb,wingo/snabb,snabbco/snabb,justincormack/snabbswitch,kbara/snabb,snabbnfv-goodies/snabbswitch,lukego/snabb,eugeneia/snabbswitch,alexandergall/snabbswitch,wingo/snabb,andywingo/snabbswitch,wingo/snabb,eugeneia/snabbswitch,justincormack/snabbswitch,kbara/snabb,alexandergall/snabbswitch,SnabbCo/snabbswitch,hb9cwp/snabbswitch,heryii/snabb,lukego/snabbswitch,virtualopensystems/snabbswitch,kbara/snabb,dpino/snabb,heryii/snabb,mixflowtech/logsensor,kellabyte/snabbswitch,pavel-odintsov/snabbswitch,heryii/snabb,justincormack/snabbswitch,mixflowtech/logsensor,fhanik/snabbswitch,snabbco/snabb,snabbnfv-goodies/snabbswitch,dpino/snabb,kbara/snabb,dpino/snabbswitch,javierguerragiraldez/snabbswitch,plajjan/snabbswitch,wingo/snabb,fhanik/snabbswitch,xdel/snabbswitch,pirate/snabbswitch,heryii/snabb,aperezdc/snabbswitch,lukego/snabbswitch,pavel-odintsov/snabbswitch,hb9cwp/snabbswitch,SnabbCo/snabbswitch,andywingo/snabbswitch,wingo/snabbswitch,dpino/snabb,pirate/snabbswitch,dwdm/snabbswitch,xdel/snabbswitch,kellabyte/snabbswitch,alexandergall/snabbswitch,alexandergall/snabbswitch,dpino/snabbswitch,wingo/snabb,Igalia/snabb,andywingo/snabbswitch,Igalia/snabbswitch,aperezdc/snabbswitch,eugeneia/snabb,wingo/snabb,virtualopensystems/snabbswitch,pavel-odintsov/snabbswitch,mixflowtech/logsensor,Igalia/snabb,wingo/snabbswitch,Igalia/snabb,alexandergall/snabbswitch,dpino/snabbswitch,pirate/snabbswitch,heryii/snabb,alexandergall/snabbswitch,xdel/snabbswitch,Igalia/snabbswitch,dpino/snabb,wingo/snabbswitch,hb9cwp/snabbswitch,eugeneia/snabbswitch,aperezdc/snabbswitch,lukego/snabb,justincormack/snabbswitch,eugeneia/snabb,snabbnfv-goodies/snabbswitch,dwdm/snabbswitch,plajjan/snabbswitch,dpino/snabb,dpino/snabbswitch,javierguerragiraldez/snabbswitch,mixflowtech/logsensor,Igalia/snabb,snabbco/snabb,snabbnfv-goodies/snabbswitch,Igalia/snabbswitch,plajjan/snabbswitch,dpino/snabb,lukego/snabbswitch,kbara/snabb,hb9cwp/snabbswitch,alexandergall/snabbswitch,plajjan/snabbswitch,kbara/snabb,eugeneia/snabbswitch,SnabbCo/snabbswitch,eugeneia/snabb,snabbco/snabb,dwdm/snabbswitch,Igalia/snabb,snabbco/snabb,Igalia/snabb,lukego/snabbswitch
3ba00be9dd8e26cc649f4373a748f18da743b305
xmake/modules/core/tools/rc.lua
xmake/modules/core/tools/rc.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 rc.lua -- -- imports import("core.base.option") import("core.project.project") -- init it function init(self) end -- make the define flag function nf_define(self, macro) return "-D" .. macro end -- make the undefine flag function nf_undefine(self, macro) return "-U" .. macro end -- make the includedir flag function nf_includedir(self, dir) return "-I" .. os.args(dir) end -- make the compile arguments list function _compargv1(self, sourcefile, objectfile, flags) return self:program(), table.join(flags, "-Fo" .. objectfile, sourcefile) end -- compile the source file function _compile1(self, sourcefile, objectfile, dependinfo, flags) -- ensure the object directory os.mkdir(path.directory(objectfile)) -- compile it try { function () local outdata, errdata = os.iorunv(_compargv1(self, sourcefile, objectfile, flags)) return (outdata or "") .. (errdata or "") end, catch { function (errors) -- compiling errors os.raise(errors) end }, finally { function (ok, warnings) -- print some warnings if warnings and #warnings > 0 and option.get("verbose") then cprint("${color.warning}%s", table.concat(table.slice(warnings:split('\n'), 1, 8), '\n')) end end } } end -- make the compile arguments list function compargv(self, sourcefiles, objectfile, flags) -- only support single source file now assert(type(sourcefiles) ~= "table", "'object:sources' not support!") -- for only single source file return _compargv1(self, sourcefiles, objectfile, flags) end -- compile the source file function compile(self, sourcefiles, objectfile, dependinfo, flags) -- only support single source file now assert(type(sourcefiles) ~= "table", "'object:sources' not support!") -- for only single source file _compile1(self, sourcefiles, objectfile, dependinfo, flags) end
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-2020, TBOOX Open Source Group. -- -- @author ruki -- @file rc.lua -- -- imports import("core.base.option") import("core.project.project") -- init it function init(self) end -- make the define flag function nf_define(self, macro) return "-D" .. macro end -- make the undefine flag function nf_undefine(self, macro) return "-U" .. macro end -- make the includedir flag function nf_includedir(self, dir) return "-I" .. os.args(dir) end -- make the compile arguments list function _compargv1(self, sourcefile, objectfile, flags) return self:program(), table.join(flags, "-Fo" .. objectfile, sourcefile) end -- compile the source file function _compile1(self, sourcefile, objectfile, dependinfo, flags) -- ensure the object directory os.mkdir(path.directory(objectfile)) -- compile it try { function () local outdata, errdata = vstool.iorunv(_compargv1(self, sourcefile, objectfile, flags)) return (outdata or "") .. (errdata or "") end, catch { function (errors) -- use stdout as errors first from vstool.iorunv() if type(errors) == "table" then local errs = errors.stdout or "" if #errs:trim() == 0 then errs = errors.stderr or "" end errors = errs end os.raise(tostring(errors)) end }, finally { function (ok, warnings) -- print some warnings if warnings and #warnings > 0 and option.get("verbose") then cprint("${color.warning}%s", table.concat(table.slice(warnings:split('\n'), 1, 8), '\n')) end end } } end -- make the compile arguments list function compargv(self, sourcefiles, objectfile, flags) -- only support single source file now assert(type(sourcefiles) ~= "table", "'object:sources' not support!") -- for only single source file return _compargv1(self, sourcefiles, objectfile, flags) end -- compile the source file function compile(self, sourcefiles, objectfile, dependinfo, flags) -- only support single source file now assert(type(sourcefiles) ~= "table", "'object:sources' not support!") -- for only single source file _compile1(self, sourcefiles, objectfile, dependinfo, flags) end
fix rc errors
fix rc errors
Lua
apache-2.0
waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake
f0086c20defa053c2e80f39728d9ac58ee593d44
src/actions/vstudio/vs2005.lua
src/actions/vstudio/vs2005.lua
-- -- actions/vstudio/vs2005.lua -- Add support for the Visual Studio 2005 project formats. -- Copyright (c) 2008-2013 Jason Perkins and the Premake project -- premake.vstudio.vs2005 = {} local vs2005 = premake.vstudio.vs2005 local vstudio = premake.vstudio --- -- Register a command-line action for Visual Studio 2006. --- function vs2005.generateSolution(sln) io.eol = "\r\n" io.esc = vs2005.esc premake.generate(sln, ".sln", vstudio.sln2005.generate) end function vs2005.generateProject(prj) io.eol = "\r\n" io.esc = vs2005.esc if premake.project.isdotnet(prj) then premake.generate(prj, ".csproj", vstudio.cs2005.generate) premake.generate(prj, ".csproj.user", vstudio.cs2005.generate_user) elseif premake.project.iscpp(prj) then premake.generate(prj, ".vcproj", vstudio.vc200x.generate) premake.generate(prj, ".vcproj.user", vstudio.vc200x.generate_user) end end --- -- Apply XML escaping on a value to be included in an -- exported project file. --- function vs2005.esc(value) value = string.gsub(value, '&', "&amp;") value = value:gsub('"', "&quot;") value = value:gsub("'", "&apos;") value = value:gsub('<', "&lt;") value = value:gsub('>', "&gt;") value = value:gsub('\r', "&#x0D;") value = value:gsub('\n', "&#x0A;") return value end --- -- Define the Visual Studio 2005 export action. --- newaction { -- Metadata for the command line and help system trigger = "vs2005", shortname = "Visual Studio 2005", description = "Generate Visual Studio 2005 project files", -- Visual Studio always uses Windows path and naming conventions os = "windows", -- The capabilities of this action valid_kinds = { "ConsoleApp", "WindowedApp", "StaticLib", "SharedLib", "Makefile", "None" }, valid_languages = { "C", "C++", "C#" }, valid_tools = { cc = { "msc" }, dotnet = { "msnet" }, }, -- Solution and project generation logic onsolution = vstudio.vs2005.generateSolution, onproject = vstudio.vs2005.generateProject, oncleansolution = vstudio.cleanSolution, oncleanproject = vstudio.cleanProject, oncleantarget = vstudio.cleanTarget, -- This stuff is specific to the Visual Studio exporters vstudio = { csprojSchemaVersion = "2.0", productVersion = "8.0.50727", solutionVersion = "9", versionName = "2005", } }
-- -- actions/vstudio/vs2005.lua -- Add support for the Visual Studio 2005 project formats. -- Copyright (c) 2008-2013 Jason Perkins and the Premake project -- premake.vstudio.vs2005 = {} local vs2005 = premake.vstudio.vs2005 local vstudio = premake.vstudio --- -- Register a command-line action for Visual Studio 2006. --- function vs2005.generateSolution(sln) io.indent = nil -- back to default io.eol = "\r\n" io.esc = vs2005.esc premake.generate(sln, ".sln", vstudio.sln2005.generate) end function vs2005.generateProject(prj) io.eol = "\r\n" io.esc = vs2005.esc if premake.project.isdotnet(prj) then premake.generate(prj, ".csproj", vstudio.cs2005.generate) premake.generate(prj, ".csproj.user", vstudio.cs2005.generate_user) elseif premake.project.iscpp(prj) then premake.generate(prj, ".vcproj", vstudio.vc200x.generate) premake.generate(prj, ".vcproj.user", vstudio.vc200x.generate_user) end end --- -- Apply XML escaping on a value to be included in an -- exported project file. --- function vs2005.esc(value) value = string.gsub(value, '&', "&amp;") value = value:gsub('"', "&quot;") value = value:gsub("'", "&apos;") value = value:gsub('<', "&lt;") value = value:gsub('>', "&gt;") value = value:gsub('\r', "&#x0D;") value = value:gsub('\n', "&#x0A;") return value end --- -- Define the Visual Studio 2005 export action. --- newaction { -- Metadata for the command line and help system trigger = "vs2005", shortname = "Visual Studio 2005", description = "Generate Visual Studio 2005 project files", -- Visual Studio always uses Windows path and naming conventions os = "windows", -- The capabilities of this action valid_kinds = { "ConsoleApp", "WindowedApp", "StaticLib", "SharedLib", "Makefile", "None" }, valid_languages = { "C", "C++", "C#" }, valid_tools = { cc = { "msc" }, dotnet = { "msnet" }, }, -- Solution and project generation logic onsolution = vstudio.vs2005.generateSolution, onproject = vstudio.vs2005.generateProject, oncleansolution = vstudio.cleanSolution, oncleanproject = vstudio.cleanProject, oncleantarget = vstudio.cleanTarget, -- This stuff is specific to the Visual Studio exporters vstudio = { csprojSchemaVersion = "2.0", productVersion = "8.0.50727", solutionVersion = "9", versionName = "2005", } }
This fixes issue #41 by simply resetting the indentation to its default at the beginning of solution generation, i.e. in vs2005.generateSolution, shared by all VS implementations
This fixes issue #41 by simply resetting the indentation to its default at the beginning of solution generation, i.e. in vs2005.generateSolution, shared by all VS implementations
Lua
bsd-3-clause
prapin/premake-core,TurkeyMan/premake-core,Yhgenomics/premake-core,premake/premake-core,dcourtois/premake-core,martin-traverse/premake-core,PlexChat/premake-core,noresources/premake-core,starkos/premake-core,CodeAnxiety/premake-core,Tiger66639/premake-core,aleksijuvani/premake-core,PlexChat/premake-core,saberhawk/premake-core,dcourtois/premake-core,jstewart-amd/premake-core,noresources/premake-core,lizh06/premake-core,alarouche/premake-core,felipeprov/premake-core,akaStiX/premake-core,mendsley/premake-core,bravnsgaard/premake-core,grbd/premake-core,mandersan/premake-core,bravnsgaard/premake-core,noresources/premake-core,akaStiX/premake-core,lizh06/premake-core,sleepingwit/premake-core,jstewart-amd/premake-core,Blizzard/premake-core,sleepingwit/premake-core,tritao/premake-core,tvandijck/premake-core,dcourtois/premake-core,bravnsgaard/premake-core,Zefiros-Software/premake-core,noresources/premake-core,felipeprov/premake-core,soundsrc/premake-core,starkos/premake-core,mandersan/premake-core,resetnow/premake-core,mandersan/premake-core,kankaristo/premake-core,resetnow/premake-core,starkos/premake-core,dcourtois/premake-core,CodeAnxiety/premake-core,Blizzard/premake-core,dcourtois/premake-core,lizh06/premake-core,premake/premake-core,Meoo/premake-core,Tiger66639/premake-core,xriss/premake-core,noresources/premake-core,xriss/premake-core,grbd/premake-core,premake/premake-core,dcourtois/premake-core,grbd/premake-core,PlexChat/premake-core,TurkeyMan/premake-core,prapin/premake-core,premake/premake-core,grbd/premake-core,aleksijuvani/premake-core,TurkeyMan/premake-core,aleksijuvani/premake-core,martin-traverse/premake-core,soundsrc/premake-core,sleepingwit/premake-core,felipeprov/premake-core,tvandijck/premake-core,mandersan/premake-core,starkos/premake-core,tvandijck/premake-core,tritao/premake-core,Blizzard/premake-core,saberhawk/premake-core,jsfdez/premake-core,soundsrc/premake-core,CodeAnxiety/premake-core,martin-traverse/premake-core,alarouche/premake-core,jsfdez/premake-core,soundsrc/premake-core,Blizzard/premake-core,dcourtois/premake-core,jsfdez/premake-core,kankaristo/premake-core,Meoo/premake-core,LORgames/premake-core,starkos/premake-core,jstewart-amd/premake-core,sleepingwit/premake-core,premake/premake-core,CodeAnxiety/premake-core,LORgames/premake-core,prapin/premake-core,Tiger66639/premake-core,soundsrc/premake-core,bravnsgaard/premake-core,premake/premake-core,noresources/premake-core,kankaristo/premake-core,Meoo/premake-core,PlexChat/premake-core,tritao/premake-core,Zefiros-Software/premake-core,jsfdez/premake-core,Yhgenomics/premake-core,mendsley/premake-core,alarouche/premake-core,Meoo/premake-core,Tiger66639/premake-core,lizh06/premake-core,aleksijuvani/premake-core,xriss/premake-core,mendsley/premake-core,starkos/premake-core,Yhgenomics/premake-core,LORgames/premake-core,tvandijck/premake-core,Zefiros-Software/premake-core,tvandijck/premake-core,mandersan/premake-core,resetnow/premake-core,resetnow/premake-core,noresources/premake-core,akaStiX/premake-core,xriss/premake-core,tritao/premake-core,Blizzard/premake-core,Yhgenomics/premake-core,kankaristo/premake-core,bravnsgaard/premake-core,premake/premake-core,TurkeyMan/premake-core,felipeprov/premake-core,xriss/premake-core,Zefiros-Software/premake-core,Blizzard/premake-core,akaStiX/premake-core,jstewart-amd/premake-core,TurkeyMan/premake-core,CodeAnxiety/premake-core,mendsley/premake-core,resetnow/premake-core,prapin/premake-core,sleepingwit/premake-core,LORgames/premake-core,LORgames/premake-core,saberhawk/premake-core,saberhawk/premake-core,jstewart-amd/premake-core,aleksijuvani/premake-core,Zefiros-Software/premake-core,alarouche/premake-core,mendsley/premake-core,martin-traverse/premake-core,starkos/premake-core
394f08d4f50c2421039fc543b1462905bbdcfea0
pages/shop/view/get.lua
pages/shop/view/get.lua
require "bbcode" function get() if not app.Shop.Enabled then http:redirect("/") return end local data = {} data.categories = db:query("SELECT id, name, description FROM castro_shop_categories ORDER BY id") data.players = db:query("SELECT name FROM players WHERE account_id = ?", session:loggedAccount().ID) for _, category in ipairs(data.categories) do category.offers = db:query("SELECT id, image, name, description, price FROM castro_shop_offers WHERE category_id = ?", category.id) end data.success = session:getFlash("success") data.error = session:getFlash("error") if not session:isLogged() then http:render("shopview.html", data) return end local cart = session:get("shop-cart") if cart ~= nil then data.cart = {} for name, count in pairs(cart) do data.cart[name] = {} data.cart[name].offer = db:singleQuery("SELECT name, price FROM castro_shop_offers WHERE name = ?", name) data.cart[name].count = count end end http:render("shopview.html", data) end
require "bbcode" function get() if not app.Shop.Enabled then http:redirect("/") return end local data = {} data.categories = db:query("SELECT id, name, description FROM castro_shop_categories ORDER BY id") if data.categories == nil then data.error = 'There are no shop categories on the shop' http:render("shopview.html", data) return end for _, category in ipairs(data.categories) do category.offers = db:query("SELECT id, image, name, description, price FROM castro_shop_offers WHERE category_id = ?", category.id) end data.players = db:query("SELECT name FROM players WHERE account_id = ?", session:loggedAccount().ID) data.success = session:getFlash("success") data.error = session:getFlash("error") if not session:isLogged() then http:render("shopview.html", data) return end local cart = session:get("shop-cart") if cart ~= nil then data.cart = {} for name, count in pairs(cart) do data.cart[name] = {} data.cart[name].offer = db:singleQuery("SELECT name, price FROM castro_shop_offers WHERE name = ?", name) data.cart[name].count = count end end http:render("shopview.html", data) end
Fix #92
Fix #92
Lua
mit
Raggaer/castro,Raggaer/castro,Raggaer/castro
51e43681f2db6881e38b1af35bd5f3d372c94118
modules/admin-core/luasrc/controller/admin/uci.lua
modules/admin-core/luasrc/controller/admin/uci.lua
module("luci.controller.admin.uci", package.seeall) require("luci.util") require("luci.sys") function index() node("admin", "uci", "changes").target = call("action_changes") node("admin", "uci", "revert").target = call("action_revert") node("admin", "uci", "apply").target = call("action_apply") 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 = "="..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.changes()) luci.template.render("admin_uci/changes", {changes=changes}) end function action_apply() local changes = luci.model.uci.changes() local output = "" 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 luci.model.uci.load(r) luci.model.uci.commit(r) luci.model.uci.unload(r) 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.sys.exec(cmd) .. "\n" end end luci.template.render("admin_uci/apply", {changes=convert_changes(changes), output=output}) end function action_revert() local changes = luci.model.uci.changes() if changes then local revert = {} -- Collect files to be reverted for r, tbl in pairs(changes) do luci.model.uci.load(r) luci.model.uci.revert(r) luci.model.uci.unload(r) end end luci.template.render("admin_uci/revert", {changes=convert_changes(changes)}) end
module("luci.controller.admin.uci", package.seeall) function index() node("admin", "uci", "changes").target = call("action_changes") node("admin", "uci", "revert").target = call("action_revert") node("admin", "uci", "apply").target = call("action_apply") 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 = "="..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.changes()) luci.template.render("admin_uci/changes", {changes=changes}) end function action_apply() local changes = luci.model.uci.changes() local output = "" 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 luci.model.uci.load(r) luci.model.uci.commit(r) luci.model.uci.unload(r) 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.sys.exec(cmd) .. "\n" end end luci.template.render("admin_uci/apply", {changes=convert_changes(changes), output=output}) end function action_revert() local changes = luci.model.uci.changes() if changes then local revert = {} -- Collect files to be reverted for r, tbl in pairs(changes) do luci.model.uci.load(r) luci.model.uci.revert(r) luci.model.uci.unload(r) end end luci.template.render("admin_uci/revert", {changes=convert_changes(changes)}) end
* Fixed an issue that prevented the controller from working with fastindex
* Fixed an issue that prevented the controller from working with fastindex git-svn-id: edf5ee79c2c7d29460bbb5b398f55862cc26620d@2300 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
Lua
apache-2.0
gwlim/luci,zwhfly/openwrt-luci,Canaan-Creative/luci,vhpham80/luci,projectbismark/luci-bismark,vhpham80/luci,dtaht/cerowrt-luci-3.3,zwhfly/openwrt-luci,stephank/luci,stephank/luci,alxhh/piratenluci,freifunk-gluon/luci,gwlim/luci,saraedum/luci-packages-old,phi-psi/luci,Canaan-Creative/luci,ch3n2k/luci,ReclaimYourPrivacy/cloak-luci,projectbismark/luci-bismark,jschmidlapp/luci,Canaan-Creative/luci,dtaht/cerowrt-luci-3.3,saraedum/luci-packages-old,projectbismark/luci-bismark,yeewang/openwrt-luci,alxhh/piratenluci,Flexibity/luci,Flexibity/luci,eugenesan/openwrt-luci,saraedum/luci-packages-old,phi-psi/luci,vhpham80/luci,ReclaimYourPrivacy/cloak-luci,zwhfly/openwrt-luci,jschmidlapp/luci,Flexibity/luci,alxhh/piratenluci,yeewang/openwrt-luci,gwlim/luci,zwhfly/openwrt-luci,jschmidlapp/luci,saraedum/luci-packages-old,8devices/carambola2-luci,ReclaimYourPrivacy/cloak-luci,Flexibity/luci,Canaan-Creative/luci,phi-psi/luci,8devices/carambola2-luci,zwhfly/openwrt-luci,eugenesan/openwrt-luci,freifunk-gluon/luci,Canaan-Creative/luci,dtaht/cerowrt-luci-3.3,alxhh/piratenluci,yeewang/openwrt-luci,phi-psi/luci,zwhfly/openwrt-luci,ch3n2k/luci,dtaht/cerowrt-luci-3.3,yeewang/openwrt-luci,saraedum/luci-packages-old,saraedum/luci-packages-old,ch3n2k/luci,jschmidlapp/luci,ThingMesh/openwrt-luci,freifunk-gluon/luci,gwlim/luci,freifunk-gluon/luci,alxhh/piratenluci,gwlim/luci,gwlim/luci,stephank/luci,gwlim/luci,stephank/luci,ThingMesh/openwrt-luci,yeewang/openwrt-luci,zwhfly/openwrt-luci,Canaan-Creative/luci,dtaht/cerowrt-luci-3.3,eugenesan/openwrt-luci,ReclaimYourPrivacy/cloak-luci,vhpham80/luci,freifunk-gluon/luci,projectbismark/luci-bismark,jschmidlapp/luci,alxhh/piratenluci,ch3n2k/luci,jschmidlapp/luci,ThingMesh/openwrt-luci,freifunk-gluon/luci,ch3n2k/luci,projectbismark/luci-bismark,ThingMesh/openwrt-luci,phi-psi/luci,ReclaimYourPrivacy/cloak-luci,ReclaimYourPrivacy/cloak-luci,Flexibity/luci,vhpham80/luci,Canaan-Creative/luci,jschmidlapp/luci,Canaan-Creative/luci,yeewang/openwrt-luci,projectbismark/luci-bismark,eugenesan/openwrt-luci,yeewang/openwrt-luci,phi-psi/luci,alxhh/piratenluci,ch3n2k/luci,8devices/carambola2-luci,zwhfly/openwrt-luci,ch3n2k/luci,stephank/luci,Flexibity/luci,jschmidlapp/luci,eugenesan/openwrt-luci,phi-psi/luci,ReclaimYourPrivacy/cloak-luci,vhpham80/luci,dtaht/cerowrt-luci-3.3,zwhfly/openwrt-luci,freifunk-gluon/luci,8devices/carambola2-luci,Flexibity/luci,8devices/carambola2-luci,ReclaimYourPrivacy/cloak-luci,eugenesan/openwrt-luci,projectbismark/luci-bismark,stephank/luci,ThingMesh/openwrt-luci,Flexibity/luci,ThingMesh/openwrt-luci,8devices/carambola2-luci,freifunk-gluon/luci,ThingMesh/openwrt-luci,projectbismark/luci-bismark,eugenesan/openwrt-luci,8devices/carambola2-luci,saraedum/luci-packages-old
bbb209761e7b716e7aa8b3288796501859959e21
src/nodes/platform.lua
src/nodes/platform.lua
local Timer = require 'vendor/timer' local Platform = {} Platform.__index = Platform Platform.isPlatform = true function Platform.new(node, collider) local platform = {} setmetatable(platform, Platform) --If the node is a polyline, we need to draw a polygon rather than rectangle if node.polyline or node.polygon then local polygon = node.polyline or node.polygon local vertices = {} for i, point in ipairs(polygon) do table.insert(vertices, node.x + point.x) table.insert(vertices, node.y + point.y) end platform.bb = collider:addPolygon(unpack(vertices)) platform.bb.polyline = polygon else platform.bb = collider:addRectangle(node.x, node.y, node.width, node.height) platform.bb.polyline = nil end platform.node = node platform.drop = node.properties.drop ~= 'false' platform.down_dt = 0 platform.bb.node = platform collider:setPassive(platform.bb) return platform end function Platform:update( dt, player) assert(player,"platform update requires a node") assert(player.isPlayer,"platform update requires a player") --TODO:reimplement platform dropping --controls.isDown is deprecated in multiplayer if player.key_down['DOWN'] then player.down_dt = 0 else player.down_dt = player.down_dt or 0 player.down_dt = player.down_dt + dt end end function Platform:collide( node, dt, mtv_x, mtv_y ) if not node.floor_pushback then return end if node.isPlayer then self.players_touched[node] = true if node.platform_dropping then return end end if not node.bb then return end local _, wy1, _, wy2 = self.bb:bbox() local px1, py1, px2, py2 = node.bb:bbox() local distance = math.abs(node.velocity.y * dt) + 2.10 if self.bb.polyline and node.velocity.y >= 0 -- Prevent the player from being treadmilled through an object and ( self.bb:contains(px2,py2) or self.bb:contains(px1,py2) ) then -- Use the MTV to keep players feet on the ground, -- fudge the Y a bit to prevent falling into steep angles node:floor_pushback(self, (py1 - 4 ) + mtv_y) elseif node.velocity.y >= 0 and math.abs(wy1 - py2) <= distance then node:floor_pushback(self, wy1 - node.height) end end function Platform:collide_end(node) if node.isPlayer then self.players_touched[node] = nil node.platform_dropping = false end end function Platform:keypressed( button, player ) if player.controlState:is('ignoreMovement') then return end if self.drop and button == 'DOWN' and player.down_dt > 0 and player.down_dt < 3.0 then player.platform_dropping = true Timer.add( 0.25, function() player.platform_dropping = false end ) end end return Platform
local Timer = require 'vendor/timer' local Platform = {} Platform.__index = Platform Platform.isPlatform = true function Platform.new(node, collider) local platform = {} setmetatable(platform, Platform) --If the node is a polyline, we need to draw a polygon rather than rectangle if node.polyline or node.polygon then local polygon = node.polyline or node.polygon local vertices = {} for i, point in ipairs(polygon) do table.insert(vertices, node.x + point.x) table.insert(vertices, node.y + point.y) end platform.bb = collider:addPolygon(unpack(vertices)) platform.bb.polyline = polygon else platform.bb = collider:addRectangle(node.x, node.y, node.width, node.height) platform.bb.polyline = nil end platform.node = node platform.drop = node.properties.drop ~= 'false' platform.down_dt = 0 platform.bb.node = platform collider:setPassive(platform.bb) return platform end function Platform:update( dt, player) assert(player,"platform update requires a node") assert(player.isPlayer,"platform update requires a player") --TODO:reimplement platform dropping --controls.isDown is deprecated in multiplayer if player.key_down['DOWN'] then player.down_dt = 0 else player.down_dt = player.down_dt or 0 player.down_dt = player.down_dt + dt end end function Platform:collide( node, dt, mtv_x, mtv_y ) if not node.floor_pushback then return end if node.isPlayer then self.players_touched[node] = true if node.platform_dropping then return end end if not node.bb then return end local _, wy1, _, wy2 = self.bb:bbox() local px1, py1, px2, py2 = node.bb:bbox() local distance = math.abs(node.velocity.y * dt) + 2.10 if self.bb.polyline and node.velocity.y >= 0 -- Prevent the player from being treadmilled through an object and ( self.bb:contains(px2,py2) or self.bb:contains(px1,py2) ) then -- Use the MTV to keep players feet on the ground, -- fudge the Y a bit to prevent falling into steep angles node:floor_pushback(self, (py1 - 4 ) + mtv_y) elseif node.velocity.y >= 0 and math.abs(wy1 - py2) <= distance then node:floor_pushback(self, wy1 - node.height) end end function Platform:collide_end(node) if node.isPlayer then self.players_touched[node] = nil node.platform_dropping = false end end function Platform:keypressed( button, player ) if player.controlState:is('ignoreMovement') then return end if self.drop and button == 'DOWN' and player.down_dt > 0 and player.down_dt < 3.0 then player.platform_dropping = true end end return Platform
fixed platform dropping
fixed platform dropping
Lua
mit
hawkthorne/hawkthorne-server-lua,hawkthorne/hawkthorne-server-lua
b9006d52543294f10a3eaa5f822bd352b5d79b97
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', host = "127.0.0.1", port = 50061, 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) async.series({ function(callback) child = helper.start_server(callback) end, function(callback) client:on('handshake_success', misc.nCallbacks(callback, 3)) local endpoints = get_endpoints() client:createConnections(endpoints, function() end) end, function(callback) helper.stop_server(child) client:on('reconnect', counterTrigger(3, callback)) end, function(callback) child = helper.start_server(function() client:on('handshake_success', counterTrigger(3, callback)) 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 -- Override the default download path consts.DEFAULT_DOWNLOAD_PATH = path.join('.', 'tmp') options = { datacenter = 'test', stateDirectory = './tests', host = "127.0.0.1", port = 50061, tls = { rejectUnauthorized = false } } endpoints = get_endpoints() 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 exports = {} local child exports['test_reconnects'] = function(test, asserts) local options = { datacenter = 'test', stateDirectory = './tests', host = "127.0.0.1", port = 50061, 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) 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', counterTrigger(3, callback)) end, function(callback) child = helper.start_server(function() client:on('handshake_success', counterTrigger(3, callback)) 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 -- Override the default download path consts.DEFAULT_DOWNLOAD_PATH = path.join('.', 'tmp') options = { datacenter = 'test', stateDirectory = './tests', host = "127.0.0.1", port = 50061, tls = { rejectUnauthorized = false } } endpoints = get_endpoints() 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
fix merge
fix merge
Lua
apache-2.0
kans/zirgo,kans/zirgo,kans/zirgo
a0db69fbac97e0c982ae61930008a426d76a0b40
gateway/src/apicast/policy/upstream/upstream.lua
gateway/src/apicast/policy/upstream/upstream.lua
--- Upstream policy -- This policy allows to modify the host of a request based on its path. local resty_resolver = require('resty.resolver') local resty_url = require('resty.url') local format = string.format local ipairs = ipairs local match = ngx.re.match local table = table local balancer = require('apicast.balancer') local _M = require('apicast.policy').new('Upstream policy') local new = _M.new local function proxy_pass(url) local res = format('%s://upstream%s', url.scheme, url.path or '') local args = ngx.var.args if url.path and args then res = format('%s?%s', res, args) end return res end local function change_upstream(url) ngx.ctx.upstream = resty_resolver:instance():get_servers( url.host, { port = url.port }) ngx.var.proxy_pass = proxy_pass(url) ngx.req.set_header('Host', url.host) -- We need to check that the headers have not already been sent. They could -- have been sent in a different policy, for example. if not ngx.headers_sent then ngx.exec("@upstream") end end -- Parses the urls in the config so we do not have to do it on each request. local function init_config(config) if not config or not config.rules then return {} end local res = {} for _, rule in ipairs(config.rules) do local parsed_url = resty_url.parse(rule.url) table.insert(res, { regex = rule.regex, url = parsed_url }) end return res end --- Initialize an upstream policy. -- @tparam[opt] table config Contains the host rewriting rules. -- Each rule consists of: -- -- - regex: regular expression to be matched. -- - url: new url in case of match. function _M.new(config) local self = new(config) self.rules = init_config(config) return self end function _M:content(context) local req_uri = ngx.var.uri for _, rule in ipairs(self.rules) do if match(req_uri, rule.regex) then ngx.log(ngx.DEBUG, 'upstream policy uri: ', req_uri, ' regex: ', rule.regex, ' match: true') context.upstream_changed = true return change_upstream(rule.url) elseif ngx.config.debug then ngx.log(ngx.DEBUG, 'upstream policy uri: ', req_uri, ' regex: ', rule.regex, ' match: false') end end end function _M.balancer(_, context) if context.upstream_changed then balancer.call() end end return _M
--- Upstream policy -- This policy allows to modify the host of a request based on its path. local resty_resolver = require('resty.resolver') local resty_url = require('resty.url') local format = string.format local ipairs = ipairs local match = ngx.re.match local table = table local balancer = require('apicast.balancer') local _M = require('apicast.policy').new('Upstream policy') local new = _M.new local function proxy_pass(url) local res = format('%s://upstream%s', url.scheme, url.path or '') local args = ngx.var.args if url.path and args then res = format('%s?%s', res, args) end return res end local function change_upstream(url) ngx.ctx.upstream = resty_resolver:instance():get_servers( url.host, { port = url.port }) ngx.var.proxy_pass = proxy_pass(url) ngx.req.set_header('Host', url.host) -- We need to check that the headers have not already been sent. They could -- have been sent in a different policy, for example. if not ngx.headers_sent then ngx.exec("@upstream") end end -- Parses the urls in the config so we do not have to do it on each request. local function init_config(config) if not config or not config.rules then return {} end local res = {} for _, rule in ipairs(config.rules) do local parsed_url = resty_url.parse(rule.url) table.insert(res, { regex = rule.regex, url = parsed_url }) end return res end --- Initialize an upstream policy. -- @tparam[opt] table config Contains the host rewriting rules. -- Each rule consists of: -- -- - regex: regular expression to be matched. -- - url: new url in case of match. function _M.new(config) local self = new(config) self.rules = init_config(config) return self end function _M:rewrite(context) local req_uri = ngx.var.uri for _, rule in ipairs(self.rules) do if match(req_uri, rule.regex) then ngx.log(ngx.DEBUG, 'upstream policy uri: ', req_uri, ' regex: ', rule.regex, ' match: true') context.new_upstream = rule.url break else ngx.log(ngx.DEBUG, 'upstream policy uri: ', req_uri, ' regex: ', rule.regex, ' match: false') end end end function _M.content(_, context) local new_upstream = context.new_upstream if new_upstream then context.upstream_changed = true return change_upstream(new_upstream) end end function _M.balancer(_, context) if context.upstream_changed then balancer.call() end end return _M
policy/upstream: match rules in rewrite phase
policy/upstream: match rules in rewrite phase This way this policy will be easier to combine with others, for example the URL rewriting policy. Before this change, the upstream policy ran on the content phase, whereas the URL rewriting one ran on the rewrite phase. This means that the upstream policy always took into account the rewritten path instead of the original one, regardless of the position of the policies in the chain. This commit fixes the issue.
Lua
mit
3scale/docker-gateway,3scale/apicast,3scale/docker-gateway,3scale/apicast,3scale/apicast,3scale/apicast
61e0335c4990118d86a72e6286fbeae45c2fe68a
openLuup/userdata.lua
openLuup/userdata.lua
local ABOUT = { NAME = "openLuup.userdata", VERSION = "2016.04.30", DESCRIPTION = "user_data saving and loading, plus utility functions used by HTTP requests", AUTHOR = "@akbooer", COPYRIGHT = "(c) 2013-2016 AKBooer", DOCUMENTATION = "https://github.com/akbooer/openLuup/tree/master/Documentation", } -- user_data -- saving and loading, plus utility functions used by HTTP requests id=user_data, etc. local json = require "openLuup.json" -- -- Here a complete list of top-level (scalar) attributes taken from an actual Vera user_data2 request -- the commented out items are either vital tables, or useless parameters. local attributes = { -- AltEventServer = "127.0.0.1", -- AutomationDevices = 0, BuildVersion = "*1.7.0*", City_description = "Greenwich", Country_description = "UNITED KINGDOM", -- DataVersion = 563952001, -- DataVersion_Static = "32", -- DeviceSync = "1426564006", Device_Num_Next = "1", -- ExtraLuaFiles = {}, -- InstalledPlugins = {}, -- InstalledPlugins2 = {}, KwhPrice = "0.15", LoadTime = os.time(), Mode = "1", -- House Mode ModeSetting = "1:DC*;2:DC*;3:DC*;4:DC*", -- see: http://wiki.micasaverde.com/index.php/House_Modes PK_AccessPoint = "88800000", -- TODO: pick up machine serial number from EPROM or such like, -- PluginSettings = {}, -- PluginsSynced = "0", -- RA_Server = "vera-us-oem-relay41.mios.com", -- RA_Server_Back = "vera-us-oem-relay11.mios.com", Region_description = "England", -- ServerBackup = "1", -- Server_Device = "vera-us-oem-device12.mios.com", -- Server_Device_Alt = "vera-us-oem-device11.mios.com", -- SetupDevices = {}, -- ShowIndividualJobs = 0, StartupCode = "", -- SvnVersion = "*13875*", TemperatureFormat = "C", -- UnassignedDevices = 0, -- Using_2G = 0, -- breach_delay = "30", -- category_filter = {}, currency = "£", date_format = "dd/mm/yy", -- device_sync = "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,18,19,20,21", -- devices = {}, -- energy_dev_log = "41,", -- firmware_version = "1", gmt_offset = "0", -- ip_requests = {}, -- ir = 0, latitude = "51.48", -- local_udn = "uuid:4d494342-5342-5645-0000-000002b03069", longitude = "0.0", mode_change_delay = "30", model = "Not a Vera", -- net_pnp = "0", -- overview_tabs = {}, -- rooms = {}, -- scenes = {}, -- sections = {}, -- setup_wizard_finished = "1", -- shouldHelpOverlayBeHidden = true, -- skin = "mios", -- static_data = {}, -- sync_kit = "0000-00-00 00:00:00", timeFormat = "24hr", timezone = "0", -- users = {}, -- weatherSettings = { -- weatherCountry = "UNITED KINGDOM", -- weatherCity = "Oxford England", -- tempFormat = "C" }, -- zwave_heal = "1426331082", -- openLuup specials GitHubVersion = "unknown", GitHubLatest = "unknown", ShutdownCode = '', } local function parse_user_data (user_data_json) return json.decode (user_data_json) end local function load_user_data (filename) local user_data, message, err local f = io.open (filename or "user_data.json", 'r') if f then local user_data_json = f:read "*a" f:close () user_data, err = parse_user_data (user_data_json) if not user_data then message = "error in user_data: " .. err end else user_data = {} message = "cannot open user_data file" -- not an error, _per se_, there may just be no file end return user_data, message end -- -- user_data devices table local function devices_table (device_list) local info = {} local serviceNo = 0 for _,d in pairs (device_list) do local states = {} for i,item in ipairs(d.variables) do states[i] = { id = item.id, service = item.srv, variable = item.name, value = item.value, } end local curls if d.serviceList then -- add the ControlURLs curls = {} for _,x in ipairs (d.serviceList) do serviceNo = serviceNo + 1 curls["service_" .. serviceNo] = { service = x.serviceId, serviceType = x.serviceType, ControlURL = "upnp/control/dev_" .. serviceNo, EventURL = "/upnp/event/dev_" .. serviceNo, } end end local status = d:status_get() or -1 -- 2016.04.29 -- if status == -1 then status = nil end -- don't report 'normal' status ??? local tbl = { ControlURLs = curls, states = states, status = status, } for a,b in pairs (d.attributes) do tbl[a] = b end info[#info+1] = tbl end return info end -- save () -- top-level attributes and key tables: devices, rooms, scenes -- TODO: [, sections, users, weatherSettings] local function save_user_data (localLuup, filename) local luup = localLuup or luup local result, message local f = io.open (filename or "user_data.json", 'w') if not f then message = "error writing user_data" else local data = {rooms = {}, scenes = {}} -- scalar attributes for a,b in pairs (attributes) do if type(b) ~= "table" then data[a] = b end end -- devices data.devices = devices_table (luup.devices or {}) -- plugins data.InstalledPlugins2 = {} -- TODO: replace with plugins.installed() -- rooms local rooms = data.rooms for i, name in pairs (luup.rooms or {}) do rooms[#rooms+1] = {id = i, name = name} end -- scenes local scenes = data.scenes for _, s in pairs (luup.scenes or {}) do scenes[#scenes+1] = s: user_table () end -- local j, msg = json.encode (data) if j then f:write (j) f:write '\n' result = true else message = "syntax error in user_data: " .. (msg or '?') end f:close () end return result, message end return { ABOUT = ABOUT, attributes = attributes, devices_table = devices_table, -- load = load_user_data, parse = parse_user_data, save = save_user_data, }
local ABOUT = { NAME = "openLuup.userdata", VERSION = "2016.04.30", DESCRIPTION = "user_data saving and loading, plus utility functions used by HTTP requests", AUTHOR = "@akbooer", COPYRIGHT = "(c) 2013-2016 AKBooer", DOCUMENTATION = "https://github.com/akbooer/openLuup/tree/master/Documentation", } -- user_data -- saving and loading, plus utility functions used by HTTP requests id=user_data, etc. local json = require "openLuup.json" -- -- Here a complete list of top-level (scalar) attributes taken from an actual Vera user_data2 request -- the commented out items are either vital tables, or useless parameters. local attributes = { -- AltEventServer = "127.0.0.1", -- AutomationDevices = 0, BuildVersion = "*1.7.0*", City_description = "Greenwich", Country_description = "UNITED KINGDOM", -- DataVersion = 563952001, -- DataVersion_Static = "32", -- DeviceSync = "1426564006", Device_Num_Next = "1", -- ExtraLuaFiles = {}, -- InstalledPlugins = {}, -- InstalledPlugins2 = {}, KwhPrice = "0.15", LoadTime = os.time(), Mode = "1", -- House Mode ModeSetting = "1:DC*;2:DC*;3:DC*;4:DC*", -- see: http://wiki.micasaverde.com/index.php/House_Modes PK_AccessPoint = "88800000", -- TODO: pick up machine serial number from EPROM or such like, -- PluginSettings = {}, -- PluginsSynced = "0", -- RA_Server = "vera-us-oem-relay41.mios.com", -- RA_Server_Back = "vera-us-oem-relay11.mios.com", Region_description = "England", -- ServerBackup = "1", -- Server_Device = "vera-us-oem-device12.mios.com", -- Server_Device_Alt = "vera-us-oem-device11.mios.com", -- SetupDevices = {}, -- ShowIndividualJobs = 0, StartupCode = "", -- SvnVersion = "*13875*", TemperatureFormat = "C", -- UnassignedDevices = 0, -- Using_2G = 0, -- breach_delay = "30", -- category_filter = {}, currency = "£", date_format = "dd/mm/yy", -- device_sync = "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,18,19,20,21", -- devices = {}, -- energy_dev_log = "41,", -- firmware_version = "1", gmt_offset = "0", -- ip_requests = {}, -- ir = 0, latitude = "51.48", -- local_udn = "uuid:4d494342-5342-5645-0000-000002b03069", longitude = "0.0", mode_change_delay = "30", model = "Not a Vera", -- net_pnp = "0", -- overview_tabs = {}, -- rooms = {}, -- scenes = {}, -- sections = {}, -- setup_wizard_finished = "1", -- shouldHelpOverlayBeHidden = true, -- skin = "mios", -- static_data = {}, -- sync_kit = "0000-00-00 00:00:00", timeFormat = "24hr", timezone = "0", -- users = {}, -- weatherSettings = { -- weatherCountry = "UNITED KINGDOM", -- weatherCity = "Oxford England", -- tempFormat = "C" }, -- zwave_heal = "1426331082", -- openLuup specials GitHubVersion = "unknown", GitHubLatest = "unknown", ShutdownCode = '', } local function parse_user_data (user_data_json) return json.decode (user_data_json) end local function load_user_data (filename) local user_data, message, err local f = io.open (filename or "user_data.json", 'r') if f then local user_data_json = f:read "*a" f:close () user_data, err = parse_user_data (user_data_json) if not user_data then message = "error in user_data: " .. err end else user_data = {} message = "cannot open user_data file" -- not an error, _per se_, there may just be no file end return user_data, message end -- -- user_data devices table local function devices_table (device_list) local info = {} local serviceNo = 0 for _,d in pairs (device_list) do local states = {} for i,item in ipairs(d.variables) do states[i] = { id = item.id, service = item.srv, variable = item.name, value = item.value, } end local curls if d.serviceList then -- add the ControlURLs curls = {} for _,x in ipairs (d.serviceList) do serviceNo = serviceNo + 1 curls["service_" .. serviceNo] = { service = x.serviceId, serviceType = x.serviceType, ControlURL = "upnp/control/dev_" .. serviceNo, EventURL = "/upnp/event/dev_" .. serviceNo, } end end local status = d:status_get() or -1 -- 2016.04.29 -- if status == -1 then status = nil end -- don't report 'normal' status ??? local tbl = { ControlURLs = curls, states = states, status = status, } for a,b in pairs (d.attributes) do tbl[a] = b end info[#info+1] = tbl end return info end -- save () -- top-level attributes and key tables: devices, rooms, scenes -- TODO: [, sections, users, weatherSettings] local function save_user_data (localLuup, filename) -- refactored thanks to @explorer local luup = localLuup or luup local result, message local data = {rooms = {}, scenes = {}} -- scalar attributes for a,b in pairs (attributes) do if type(b) ~= "table" then data[a] = b end end -- devices data.devices = devices_table (luup.devices or {}) -- plugins data.InstalledPlugins2 = {} -- TODO: replace with plugins.installed() -- rooms local rooms = data.rooms for i, name in pairs (luup.rooms or {}) do rooms[#rooms+1] = {id = i, name = name} end -- scenes local scenes = data.scenes for _, s in pairs (luup.scenes or {}) do scenes[#scenes+1] = s: user_table () end -- local j, msg = json.encode (data) if not j then message = "syntax error in user_data: " .. (msg or '?') else local f, err = io.open (filename or "user_data.json", 'w') if not f then message = "error writing user_data: " .. (err or '?') else f:write (j) f:write '\n' f:close () result = true end end return result, message end return { ABOUT = ABOUT, attributes = attributes, devices_table = devices_table, -- load = load_user_data, parse = parse_user_data, save = save_user_data, }
hot-fix-refactor-userdata-save
hot-fix-refactor-userdata-save - thanks to @explorer for refactoring suggestion.
Lua
apache-2.0
akbooer/openLuup
606f36be1bac718874eac9bcd6b114e4b7541ece
src/loader.lua
src/loader.lua
local Gamestate = require 'vendor/gamestate' local Level = require 'level' local window = require 'window' local fonts = require 'fonts' local state = Gamestate.new() local home = require 'menu' local nextState = 'home' function state:init() state.finished = false state.current = 1 state.assets = {} fonts.set( 'big' ) table.insert(state.assets, function() Gamestate.load('valley', Level.new('valley')) end) table.insert(state.assets, function() Gamestate.load('gay-island', Level.new('gay-island')) end) table.insert(state.assets, function() Gamestate.load('gay-island2', Level.new('gay-island2')) end) table.insert(state.assets, function() Gamestate.load('abedtown', Level.new('newtown')) end) table.insert(state.assets, function() Gamestate.load('lab', Level.new('lab')) end) table.insert(state.assets, function() Gamestate.load('house', Level.new('house')) end) table.insert(state.assets, function() Gamestate.load('studyroom', Level.new('studyroom')) end) table.insert(state.assets, function() Gamestate.load('hallway', Level.new('hallway')) end) table.insert(state.assets, function() Gamestate.load('forest', Level.new('forest')) end) table.insert(state.assets, function() Gamestate.load('forest2', Level.new('forest2')) end) table.insert(state.assets, function() Gamestate.load('village-forest', Level.new('village-forest')) end) table.insert(state.assets, function() Gamestate.load('town', Level.new('town')) end) table.insert(state.assets, function() Gamestate.load('tavern', Level.new('tavern')) end) table.insert(state.assets, function() Gamestate.load('blacksmith', Level.new('blacksmith')) end) table.insert(state.assets, function() Gamestate.load('greendale-exterior', Level.new('greendale-exterior')) end) table.insert(state.assets, function() Gamestate.load('deans-office-1', Level.new('deans-office-1')) end) table.insert(state.assets, function() Gamestate.load('deans-office-2', Level.new('deans-office-2')) end) table.insert(state.assets, function() Gamestate.load('deans-closet', Level.new('deans-closet')) end) table.insert(state.assets, function() Gamestate.load('baseball', Level.new('baseball')) end) table.insert(state.assets, function() Gamestate.load('dorm-lobby', Level.new('dorm-lobby')) end) table.insert(state.assets, function() Gamestate.load('borchert-hallway', Level.new('borchert-hallway')) end) table.insert(state.assets, function() Gamestate.load('admin-hallway', Level.new('admin-hallway')) end) table.insert(state.assets, function() Gamestate.load('class-hallway-1', Level.new('class-hallway-1')) end) table.insert(state.assets, function() Gamestate.load('class-hallway-2', Level.new('class-hallway-2')) end) table.insert(state.assets, function() Gamestate.load('rave-hallway', Level.new('rave-hallway')) end) table.insert(state.assets, function() Gamestate.load('class-basement', Level.new('class-basement')) end) table.insert(state.assets, function() Gamestate.load('gazette-office-1', Level.new('gazette-office-1')) end) table.insert(state.assets, function() Gamestate.load('gazette-office-2', Level.new('gazette-office-2')) end) table.insert(state.assets, function() Gamestate.load('overworld', require 'overworld') end) table.insert(state.assets, function() Gamestate.load('credits', require 'credits') end) table.insert(state.assets, function() Gamestate.load('select', require 'select') end) table.insert(state.assets, function() Gamestate.load('home', require 'menu') end) table.insert(state.assets, function() Gamestate.load('pause', require 'pause') end) table.insert(state.assets, function() Gamestate.load('cheatscreen', require 'cheatscreen') end) table.insert(state.assets, function() Gamestate.load('instructions', require 'instructions') end) table.insert(state.assets, function() Gamestate.load('options', require 'options') end) table.insert(state.assets, function() Gamestate.load('blackjackgame', require 'blackjackgame') end) state.step = 240 / # self.assets end function state:update(dt) if self.finished then return end local asset = state.assets[self.current] if asset ~= nil then asset() self.current = self.current + 1 else self.finished = true self:switch() end end function state:switch() Gamestate.switch(nextState) end function state:target(state) nextState = state end function state:draw() love.graphics.rectangle('line', window.width / 2 - 120, window.height / 2 - 10, 240, 20) love.graphics.rectangle('fill', window.width / 2 - 120, window.height / 2 - 10, (self.current - 1) * self.step, 20) end return state
local Gamestate = require 'vendor/gamestate' local Level = require 'level' local window = require 'window' local fonts = require 'fonts' local state = Gamestate.new() local home = require 'menu' local nextState = 'home' function state:init() state.finished = false state.current = 1 state.assets = {} fonts.set( 'courier' ) table.insert(state.assets, function() Gamestate.load('valley', Level.new('valley')) end) table.insert(state.assets, function() Gamestate.load('gay-island', Level.new('gay-island')) end) table.insert(state.assets, function() Gamestate.load('gay-island2', Level.new('gay-island2')) end) table.insert(state.assets, function() Gamestate.load('abedtown', Level.new('newtown')) end) table.insert(state.assets, function() Gamestate.load('lab', Level.new('lab')) end) table.insert(state.assets, function() Gamestate.load('house', Level.new('house')) end) table.insert(state.assets, function() Gamestate.load('studyroom', Level.new('studyroom')) end) table.insert(state.assets, function() Gamestate.load('hallway', Level.new('hallway')) end) table.insert(state.assets, function() Gamestate.load('forest', Level.new('forest')) end) table.insert(state.assets, function() Gamestate.load('forest2', Level.new('forest2')) end) table.insert(state.assets, function() Gamestate.load('village-forest', Level.new('village-forest')) end) table.insert(state.assets, function() Gamestate.load('town', Level.new('town')) end) table.insert(state.assets, function() Gamestate.load('tavern', Level.new('tavern')) end) table.insert(state.assets, function() Gamestate.load('blacksmith', Level.new('blacksmith')) end) table.insert(state.assets, function() Gamestate.load('greendale-exterior', Level.new('greendale-exterior')) end) table.insert(state.assets, function() Gamestate.load('deans-office-1', Level.new('deans-office-1')) end) table.insert(state.assets, function() Gamestate.load('deans-office-2', Level.new('deans-office-2')) end) table.insert(state.assets, function() Gamestate.load('deans-closet', Level.new('deans-closet')) end) table.insert(state.assets, function() Gamestate.load('baseball', Level.new('baseball')) end) table.insert(state.assets, function() Gamestate.load('dorm-lobby', Level.new('dorm-lobby')) end) table.insert(state.assets, function() Gamestate.load('borchert-hallway', Level.new('borchert-hallway')) end) table.insert(state.assets, function() Gamestate.load('admin-hallway', Level.new('admin-hallway')) end) table.insert(state.assets, function() Gamestate.load('class-hallway-1', Level.new('class-hallway-1')) end) table.insert(state.assets, function() Gamestate.load('class-hallway-2', Level.new('class-hallway-2')) end) table.insert(state.assets, function() Gamestate.load('rave-hallway', Level.new('rave-hallway')) end) table.insert(state.assets, function() Gamestate.load('class-basement', Level.new('class-basement')) end) table.insert(state.assets, function() Gamestate.load('gazette-office-1', Level.new('gazette-office-1')) end) table.insert(state.assets, function() Gamestate.load('gazette-office-2', Level.new('gazette-office-2')) end) table.insert(state.assets, function() Gamestate.load('overworld', require 'overworld') end) table.insert(state.assets, function() Gamestate.load('credits', require 'credits') end) table.insert(state.assets, function() Gamestate.load('select', require 'select') end) table.insert(state.assets, function() Gamestate.load('home', require 'menu') end) table.insert(state.assets, function() Gamestate.load('pause', require 'pause') end) table.insert(state.assets, function() Gamestate.load('cheatscreen', require 'cheatscreen') end) table.insert(state.assets, function() Gamestate.load('instructions', require 'instructions') end) table.insert(state.assets, function() Gamestate.load('options', require 'options') end) table.insert(state.assets, function() Gamestate.load('blackjackgame', require 'blackjackgame') end) state.step = 240 / # self.assets state.messages = { "terminal://", "operations://load program:(true)", "program: journey_to_the_center_of_hawkthorne", "loading simulation...", "5465415151", "5413572495", "7342195434", "8432159965", "3141592653", "5897932384", "1678942348", "1123581321", "9437832123", "1359756423" } end function state:update(dt) if self.finished then return end local asset = state.assets[self.current] if asset ~= nil then asset() self.current = self.current + 1 else self.finished = true self:switch() end end function state:switch() Gamestate.switch(nextState) end function state:target(state) nextState = state end function state:draw() local progress = (self.current-1) / #self.assets local lineCount = math.floor(#self.messages * progress) -- Set the color to dark green for the loading font love.graphics.setColor(88, 246, 0) for i = 1,lineCount do -- Draw the first lines larger if i <= 4 then love.graphics.print(self.messages[i], 50, 15*(i+1), 0, 0.5, 0.5) else -- Draw the rest of the lines smaller and multiple times for j = 1,math.min(lineCount-i+1, 5) do love.graphics.print(self.messages[i], 60*j, 15*(i+1), 0, 0.4, 0.4) end end end love.graphics.setColor(255, 255, 255) end return state
Fixed new loading screen
Fixed new loading screen
Lua
mit
hawkthorne/hawkthorne-client-lua,hawkthorne/hawkthorne-server-lua,hawkthorne/hawkthorne-client-lua,hawkthorne/hawkthorne-server-lua