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
d59f931edacf92297cc01b885f63058ba54a3ba2
src/apps/ddos/ddos.lua
src/apps/ddos/ddos.lua
module(..., package.seeall) local app = require("core.app") local buffer = require("core.buffer") local datagram = require("lib.protocol.datagram") local ffi = require("ffi") local filter = require("lib.pcap.filter") local ipv4 = require("lib.protocol.ipv4") local lib = require("core.lib") local link = require("core.link") local packet = require("core.packet") local AF_INET = 2 local ETHERTYPE_OFFSET = 12 local ETHERTYPE_IPV6 = 0xDD86 local ETHERTYPE_IPV4 = 0x0008 DDoS = {} -- I don't know what I'm doing function DDoS:new (arg) print("-- DDoS Init --") local conf = arg and config.parse_app_arg(arg) or {} assert(conf.block_period >= 5, "block_period must be at least 5 seconds") local o = { blocklist = {}, rules = conf.rules, block_period = conf.block_period } self = setmetatable(o, {__index = DDoS}) -- pre-process rules for rule_name, rule in pairs(self.rules) do rule.srcs = {} -- compile the filter local filter, errmsg = filter:new(rule.filter) assert(filter, errmsg and ffi.string(errmsg)) rule.cfilter = filter end -- schedule periodic task every second timer.activate(timer.new( "periodic", function () self:periodic() end, 1e9, -- every second 'repeating' )) return self end function DDoS:periodic() for src_ip, blocklist in pairs(self.blocklist) do print("Checking block for: " .. src_ip) if blocklist.block_until < tonumber(app.now()) then self.blocklist[src_ip] = nil end end end function DDoS:push () local i = assert(self.input.input, "input port not found") local o = assert(self.output.output, "output port not found") -- TODO: should establish one rule-set per destination IP (ie the target IP we are mitigation for) -- TODO: need to write ethernet headers on egress to match the MAC address of our "default gateway" while not link.empty(i) and not link.full(o) do local p = link.receive(i) local iovec = p.iovecs[0] -- dig out src IP from packet -- TODO: do we really need to do ntop on this? is that an expensive operation? -- TODO: don't use a fixed offset - it'll break badly on non-IPv4 packet :/ local src_ip = ipv4:ntop(iovec.buffer.pointer + iovec.offset + 26) -- short cut for stuff in blocklist that is in state block --if self.blocklist[src_ip] ~= nil and self.blocklist[src_ip].action == "block" then if self.blocklist[src_ip] ~= nil then -- TODO: this is weird. When this "shortcut" is enabled we lower CPU -- usage but legitimate traffic that shouldn't be blacklisted is dropped -- as well, why? packet.deref(p) return end dgram = datagram:new(p) -- match up against our filter rules local rule_match = nil for rule_name, rule in pairs(self.rules) do if rule.cfilter:match(dgram:payload()) then --print(src_ip .. " Matched rule: " .. rule_name .. " [ " .. rule.filter .. " ]") rule_match = rule_name end end -- didn't match any rule, so permit it if rule_match == nil then link.transmit(o, p) return end local cur_now = tonumber(app.now()) -- get our data struct on that source IP -- TODO: we need to periodically clean this data struct up so it doesn't just fill up and consume all memory if self.rules[rule_match].srcs[src_ip] == nil then self.rules[rule_match].srcs[src_ip] = { last_time = cur_now, pps_rate = self.rules[rule_match].pps_rate, pps_tokens = self.rules[rule_match].pps_burst, pps_capacity = self.rules[rule_match].pps_burst, bucket_content = self.bucket_capacity, bucket_capacity = self.bucket_capacity, block_until = nil } end local src = self.rules[rule_match].srcs[src_ip] -- figure out rates n shit src.pps_tokens = math.max(0,math.min( src.pps_tokens + src.pps_rate * (cur_now - src.last_time), src.pps_capacity )) src.last_time = cur_now -- TODO: this is for pps, do the same for bps src.pps_tokens = src.pps_tokens - 1 if src.pps_tokens <= 0 then src.block_until = tonumber(app.now()) + self.block_period self.blocklist[src_ip] = { action = "block", block_until = tonumber(app.now()) + self.block_period-5} end if src.block_until ~= nil and src.block_until < tonumber(app.now()) then src.block_until = nil end if src.block_until ~= nil then packet.deref(p) else link.transmit(o, p) end end end function DDoS:report() print("-- DDoS report --") print("Configured block period: " .. self.block_period .. " seconds") print("Block list:") for src_ip,blocklist in pairs(self.blocklist) do print(" " .. src_ip .. " blocked for another " .. string.format("%0.1f", tostring(blocklist.block_until - tonumber(app.now()))) .. " seconds") end print("Traffic rules:") for rule_name,rule in pairs(self.rules) do print(" - " .. rule_name .. " [ " .. rule.filter .. " ] pps_rate: " .. rule.pps_rate) for src_ip,src_info in pairs(rule.srcs) do -- calculate rate of packets if self.blocklist[src_ip] ~= nil then -- if source is in blocklist it means we shortcut and thus don't -- calculate pps, so we write '-' rate = " -" else -- TODO: calculate real PPS rate rate = string.format("%5.0f", src_info.pps_tokens) end str = string.format(" %15s last: %d tokens: %s ", src_ip, tonumber(app.now())-src_info.last_time, rate) if src_info.block_until == nil then str = string.format("%s %-7s", str, "allowed") else str = string.format("%s %-7s", str, "blocked for another " .. string.format("%0.1f", tostring(src_info.block_until - tonumber(app.now()))) .. " seconds") end print(str) end end end
module(..., package.seeall) local app = require("core.app") local buffer = require("core.buffer") local datagram = require("lib.protocol.datagram") local ffi = require("ffi") local filter = require("lib.pcap.filter") local ipv4 = require("lib.protocol.ipv4") local lib = require("core.lib") local link = require("core.link") local packet = require("core.packet") local AF_INET = 2 local ETHERTYPE_OFFSET = 12 local ETHERTYPE_IPV6 = 0xDD86 local ETHERTYPE_IPV4 = 0x0008 DDoS = {} -- I don't know what I'm doing function DDoS:new (arg) print("-- DDoS Init --") local conf = arg and config.parse_app_arg(arg) or {} assert(conf.block_period >= 5, "block_period must be at least 5 seconds") local o = { blocklist = {}, rules = conf.rules, block_period = conf.block_period } self = setmetatable(o, {__index = DDoS}) -- pre-process rules for rule_name, rule in pairs(self.rules) do rule.srcs = {} -- compile the filter local filter, errmsg = filter:new(rule.filter) assert(filter, errmsg and ffi.string(errmsg)) rule.cfilter = filter end -- schedule periodic task every second timer.activate(timer.new( "periodic", function () self:periodic() end, 1e9, -- every second 'repeating' )) return self end function DDoS:periodic() for src_ip, blocklist in pairs(self.blocklist) do print("Checking block for: " .. src_ip) if blocklist.block_until < tonumber(app.now()) then self.blocklist[src_ip] = nil end end end function DDoS:push () local i = assert(self.input.input, "input port not found") local o = assert(self.output.output, "output port not found") -- TODO: should establish one rule-set per destination IP (ie the target IP we are mitigation for) -- TODO: need to write ethernet headers on egress to match the MAC address of our "default gateway" while not link.empty(i) and not link.full(o) do local p = link.receive(i) local iovec = p.iovecs[0] -- dig out src IP from packet -- TODO: do we really need to do ntop on this? is that an expensive operation? -- TODO: don't use a fixed offset - it'll break badly on non-IPv4 packet :/ local src_ip = ipv4:ntop(iovec.buffer.pointer + iovec.offset + 26) -- short cut for stuff in blocklist that is in state block if self.blocklist[src_ip] ~= nil and self.blocklist[src_ip].action == "block" then -- TODO: this is weird. When this "shortcut" is enabled we lower CPU -- usage but legitimate traffic that shouldn't be blacklisted is dropped -- as well, why? packet.deref(p) else dgram = datagram:new(p) -- match up against our filter rules local rule_match = nil for rule_name, rule in pairs(self.rules) do if rule.cfilter:match(dgram:payload()) then --print(src_ip .. " Matched rule: " .. rule_name .. " [ " .. rule.filter .. " ]") rule_match = rule_name end end -- didn't match any rule, so permit it if rule_match == nil then link.transmit(o, p) return end local cur_now = tonumber(app.now()) -- get our data struct on that source IP -- TODO: we need to periodically clean this data struct up so it doesn't just fill up and consume all memory if self.rules[rule_match].srcs[src_ip] == nil then self.rules[rule_match].srcs[src_ip] = { last_time = cur_now, pps_rate = self.rules[rule_match].pps_rate, pps_tokens = self.rules[rule_match].pps_burst, pps_capacity = self.rules[rule_match].pps_burst, bucket_content = self.bucket_capacity, bucket_capacity = self.bucket_capacity, block_until = nil } end local src = self.rules[rule_match].srcs[src_ip] -- figure out rates n shit src.pps_tokens = math.max(0,math.min( src.pps_tokens + src.pps_rate * (cur_now - src.last_time), src.pps_capacity )) src.last_time = cur_now -- TODO: this is for pps, do the same for bps src.pps_tokens = src.pps_tokens - 1 if src.pps_tokens <= 0 then src.block_until = tonumber(app.now()) + self.block_period self.blocklist[src_ip] = { action = "block", block_until = tonumber(app.now()) + self.block_period-5} end if src.block_until ~= nil and src.block_until < tonumber(app.now()) then src.block_until = nil end if src.block_until ~= nil then packet.deref(p) else link.transmit(o, p) end end end end function DDoS:report() print("-- DDoS report --") print("Configured block period: " .. self.block_period .. " seconds") print("Block list:") for src_ip,blocklist in pairs(self.blocklist) do print(" " .. src_ip .. " blocked for another " .. string.format("%0.1f", tostring(blocklist.block_until - tonumber(app.now()))) .. " seconds") end print("Traffic rules:") for rule_name,rule in pairs(self.rules) do print(" - " .. rule_name .. " [ " .. rule.filter .. " ] pps_rate: " .. rule.pps_rate) for src_ip,src_info in pairs(rule.srcs) do -- calculate rate of packets if self.blocklist[src_ip] ~= nil then -- if source is in blocklist it means we shortcut and thus don't -- calculate pps, so we write '-' rate = " -" else -- TODO: calculate real PPS rate rate = string.format("%5.0f", src_info.pps_tokens) end str = string.format(" %15s last: %d tokens: %s ", src_ip, tonumber(app.now())-src_info.last_time, rate) if src_info.block_until == nil then str = string.format("%s %-7s", str, "allowed") else str = string.format("%s %-7s", str, "blocked for another " .. string.format("%0.1f", tostring(src_info.block_until - tonumber(app.now()))) .. " seconds") end print(str) end end end
Fix slowdown
Fix slowdown So it seems that "return" causes a real slow down for some reason. This refactors code so that it avoids calling return (still there in one location though) and thus achieves a great speedup compared to before. Now doing 0.5Mpps at 70% CPU utilization. Passing all legitimate traffic with no extra latency.
Lua
apache-2.0
plajjan/snabbswitch,plajjan/snabbswitch,plajjan/snabbswitch,plajjan/snabbswitch
d8c53fe2821571b293f1ecfdbeb7a30efb688218
src/builtin/macros.lua
src/builtin/macros.lua
-- Extra macros for automating proof construction using Lua. -- This macro creates the syntax-sugar -- name bindings ',' expr -- For a function f with signature -- f : ... (A : Type) ... (Pi x : A, ...) -- -- farity is the arity of f -- typepos is the position of (A : Type) argument -- lambdapos is the position of the (Pi x : A, ...) argument -- function binder_macro(name, f, farity, typepos, lambdapos) local precedence = 0 macro(name, { macro_arg.Parameters, macro_arg.Comma, macro_arg.Expr }, function (env, bindings, body) local r = body for i = #bindings, 1, -1 do local bname = bindings[i][1] local btype = bindings[i][2] local args = {} args[#args + 1] = f for j = 1, farity, 1 do if j == typepos then args[#args + 1] = btype elseif j == lambdapos then args[#args + 1] = fun(bname, btype, r) else args[#args + 1] = mk_placeholder() end end r = mk_app(unpack(args)) end return r end, precedence) end -- The following macro is used to create nary versions of operators such as mp. -- Example: suppose we invoke -- -- nary_macro("eqmp'", Const("eqmp"), 4) -- -- Then, the macro expression -- -- eqmp' Foo H1 H2 H3 -- -- produces the expression -- -- (eqmp (eqmp (eqmp Foo H1) H2) H3) function nary_macro(name, f, farity) local bin_app = function(e1, e2) local args = {} args[#args + 1] = f for i = 1, farity - 2, 1 do args[#args + 1] = mk_placeholder() end args[#args + 1] = e1 args[#args + 1] = e2 return mk_app(unpack(args)) end macro(name, { macro_arg.Expr, macro_arg.Expr, macro_arg.Exprs }, function (env, e1, e2, rest) local r = bin_app(e1, e2) for i = 1, #rest do r = bin_app(r, rest[i]) end return r end) end -- exists::elim syntax-sugar -- Example: -- Assume we have the following two axioms -- Axiom Ax1: exists x y, P x y -- Axiom Ax2: forall x y, not P x y -- Now, the following macro expression -- obtain (a b : Nat) (H : P a b) from Ax1, -- show false, from absurd H (instantiate Ax2 a b) -- expands to -- exists::elim Ax1 -- (fun (a : Nat) (Haux : ...), -- exists::elim Haux -- (fun (b : Na) (H : P a b), -- show false, from absurd H (instantiate Ax2 a b) macro("obtain", { macro_arg.Parameters, macro_arg.Comma, macro_arg.Id, macro_arg.Expr, macro_arg.Comma, macro_arg.Expr }, function (env, bindings, fromid, exPr, body) local n = #bindings if n < 2 then error("invalid 'obtain' expression at least two bindings must be provided") end if fromid ~= name("from") then error("invalid 'obtain' expression, 'from' keyword expected, got '" .. tostring(fromid) .. "'") end local exElim = mk_constant("exists_elim") local H_name = bindings[n][1] local H_type = bindings[n][2] local a_name = bindings[n-1][1] local a_type = bindings[n-1][2] for i = n - 2, 1, -1 do local Haux = name("obtain", "macro", "H", i) body = mk_app(exElim, mk_placeholder(), mk_placeholder(), mk_placeholder(), mk_constant(Haux), fun(a_name, a_type, fun(H_name, H_type, body))) H_name = Haux H_type = mk_placeholder() a_name = bindings[i][1] a_type = bindings[i][2] -- We added a new binding, so we must lift free vars body = body:lift_free_vars(0, 1) end -- exPr occurs after the bindings, so it is in the context of them. -- However, this is not the case for ExistsElim. -- So, we must lower the free variables there exPr = exPr:lower_free_vars(n, n) return mk_app(exElim, mk_placeholder(), mk_placeholder(), mk_placeholder(), exPr, fun(a_name, a_type, fun(H_name, H_type, body))) end, 0) function mk_lambdas(bindings, body) local r = body for i = #bindings, 1, -1 do r = fun(bindings[i][1], bindings[i][2], r) end return r end -- Allow (assume x : A, B) to be used instead of (fun x : A, B). -- It can be used to make scripts more readable, when (fun x : A, B) is being used to encode a discharge macro("assume", { macro_arg.Parameters, macro_arg.Comma, macro_arg.Expr}, function (env, bindings, body) return mk_lambdas(bindings, body) end, 0) -- Allow (assume x : A, B) to be used instead of (fun x : A, B). -- It can be used to make scripts more readable, when (fun x : A, B) is being used to encode a forall_intro macro("take", { macro_arg.Parameters, macro_arg.Comma, macro_arg.Expr}, function (env, bindings, body) return mk_lambdas(bindings, body) end, 0)
-- Extra macros for automating proof construction using Lua. -- This macro creates the syntax-sugar -- name bindings ',' expr -- For a function f with signature -- f : ... (A : Type) ... (Pi x : A, ...) -- -- farity is the arity of f -- typepos is the position of (A : Type) argument -- lambdapos is the position of the (Pi x : A, ...) argument -- function binder_macro(name, f, farity, typepos, lambdapos) local precedence = 0 macro(name, { macro_arg.Parameters, macro_arg.Comma, macro_arg.Expr }, function (env, bindings, body) local r = body for i = #bindings, 1, -1 do local bname = bindings[i][1] local btype = bindings[i][2] local args = {} args[#args + 1] = f for j = 1, farity, 1 do if j == typepos then args[#args + 1] = btype elseif j == lambdapos then args[#args + 1] = fun(bname, btype, r) else args[#args + 1] = mk_placeholder() end end r = mk_app(unpack(args)) end return r end, precedence) end -- The following macro is used to create nary versions of operators such as mp. -- Example: suppose we invoke -- -- nary_macro("eqmp'", Const("eqmp"), 4) -- -- Then, the macro expression -- -- eqmp' Foo H1 H2 H3 -- -- produces the expression -- -- (eqmp (eqmp (eqmp Foo H1) H2) H3) function nary_macro(name, f, farity) local bin_app = function(e1, e2) local args = {} args[#args + 1] = f for i = 1, farity - 2, 1 do args[#args + 1] = mk_placeholder() end args[#args + 1] = e1 args[#args + 1] = e2 return mk_app(unpack(args)) end macro(name, { macro_arg.Expr, macro_arg.Expr, macro_arg.Exprs }, function (env, e1, e2, rest) local r = bin_app(e1, e2) for i = 1, #rest do r = bin_app(r, rest[i]) end return r end) end -- exists::elim syntax-sugar -- Example: -- Assume we have the following two axioms -- Axiom Ax1: exists x y, P x y -- Axiom Ax2: forall x y, not P x y -- Now, the following macro expression -- obtain (a b : Nat) (H : P a b) from Ax1, -- show false, from absurd H (instantiate Ax2 a b) -- expands to -- exists::elim Ax1 -- (fun (a : Nat) (Haux : ...), -- exists::elim Haux -- (fun (b : Na) (H : P a b), -- show false, from absurd H (instantiate Ax2 a b) macro("obtain", { macro_arg.Parameters, macro_arg.Comma, macro_arg.Id, macro_arg.Expr, macro_arg.Comma, macro_arg.Expr }, function (env, bindings, fromid, exPr, body) local n = #bindings if n < 2 then error("invalid 'obtain' expression at least two bindings must be provided") end if fromid ~= name("from") then error("invalid 'obtain' expression, 'from' keyword expected, got '" .. tostring(fromid) .. "'") end local exElim = mk_constant("exists_elim") local H_name = bindings[n][1] local H_type = bindings[n][2] local a_name = bindings[n-1][1] local a_type = bindings[n-1][2] for i = n - 2, 1, -1 do local Haux = name("obtain", "macro", "H", i) body = mk_app(exElim, mk_placeholder(), mk_placeholder(), mk_placeholder(), mk_constant(Haux), fun(a_name, a_type, fun(H_name, H_type, body))) H_name = Haux H_type = mk_placeholder() a_name = bindings[i][1] a_type = bindings[i][2] -- We added a new binding, so we must lift free vars body = body:lift_free_vars(0, 1) end -- exPr occurs after the bindings, so it is in the context of them. -- However, this is not the case for ExistsElim. -- So, we must lower the free variables there if exPr:has_free_var(0, n) then error("you hit a limitation of the current macro package, the term after 'from' is accidentally capturing a local variable declared by 'obtain'. Workaround: variables declared in 'obtain' should not occur in the 'from' term.") end exPr = exPr:lower_free_vars(n, n) return mk_app(exElim, mk_placeholder(), mk_placeholder(), mk_placeholder(), exPr, fun(a_name, a_type, fun(H_name, H_type, body))) end, 0) function mk_lambdas(bindings, body) local r = body for i = #bindings, 1, -1 do r = fun(bindings[i][1], bindings[i][2], r) end return r end -- Allow (assume x : A, B) to be used instead of (fun x : A, B). -- It can be used to make scripts more readable, when (fun x : A, B) is being used to encode a discharge macro("assume", { macro_arg.Parameters, macro_arg.Comma, macro_arg.Expr}, function (env, bindings, body) return mk_lambdas(bindings, body) end, 0) -- Allow (assume x : A, B) to be used instead of (fun x : A, B). -- It can be used to make scripts more readable, when (fun x : A, B) is being used to encode a forall_intro macro("take", { macro_arg.Parameters, macro_arg.Comma, macro_arg.Expr}, function (env, bindings, body) return mk_lambdas(bindings, body) end, 0)
fix(builtin/macros): test whether there is an accidental variable capture in 'obtain' macro applications
fix(builtin/macros): test whether there is an accidental variable capture in 'obtain' macro applications Signed-off-by: Leonardo de Moura <[email protected]>
Lua
apache-2.0
codyroux/lean0.1,codyroux/lean0.1,codyroux/lean0.1,codyroux/lean0.1
ac5ffd9edf2d54f38adbaf956876e9df8416ba26
otouto/plugins/ping.lua
otouto/plugins/ping.lua
--[[ ping.lua Sends a response, then updates it with the time it took to send. I added marco/polo because a cute girl asked and I'm a sellout. Copyright 2016 topkecleon <[email protected]> This code is licensed under the GNU AGPLv3. See /LICENSE for details. ]]-- local bindings = require('otouto.bindings') local utilities = require('otouto.utilities') local socket = require('socket') local ping = {} function ping:init() ping.triggers = utilities.triggers(self.info.username, self.config.cmd_pat):t('ping'):t('marco').table ping.command = 'ping' ping.doc = self.config.cmd_pat .. [[ping Pong! Updates the message with the time used, in seconds, to send the response.]] end function ping:action(msg) local a = socket.gettime() local answer = msg.text_lower:match('marco') and 'Polo!' or 'Pong!' local message = utilities.send_reply(msg, answer) local b = socket.gettime()-a b = string.format('%.3f', b) if message then bindings.editMessageText{ chat_id = msg.chat.id, message_id = message.result.message_id, text = answer .. '\n`' .. b .. '`', parse_mode = 'Markdown' } end end return ping
--[[ ping.lua Sends a response, then updates it with the time it took to send. I added marco/polo because a cute girl asked and I'm a sellout. Copyright 2016 topkecleon <[email protected]> This code is licensed under the GNU AGPLv3. See /LICENSE for details. ]]-- local bindings = require('otouto.bindings') local utilities = require('otouto.utilities') local socket = require('socket') local ping = {} function ping:init() ping.triggers = utilities.triggers(self.info.username, self.config.cmd_pat):t('ping'):t('marco'):t('annyong').table ping.command = 'ping' ping.doc = self.config.cmd_pat .. [[ping Pong! Updates the message with the time used, in seconds, to send the response.]] end function ping:action(msg) local a = socket.gettime() local answer = msg.text_lower:match('ping') and 'Pong!' or (msg.text_lower:match('marco') and 'Marco!' or 'Annyong.') local message = utilities.send_reply(msg, answer) local b = socket.gettime()-a b = string.format('%.3f', b) if message then bindings.editMessageText{ chat_id = msg.chat.id, message_id = message.result.message_id, text = answer .. '\n`' .. b .. '`', parse_mode = 'Markdown' } end end return ping
Fix an important regression in ping.lua
Fix an important regression in ping.lua
Lua
agpl-3.0
bb010g/otouto,topkecleon/otouto
0e8eb83668f83d230a6f63afb7a52f544b762027
entities/entities/info_node_base/shared.lua
entities/entities/info_node_base/shared.lua
ENT.Type = "anim" ENT.Model = "" ENT.RenderGroup = RENDERGROUP_BOTH function ENT:SetupDataTables() self:NetworkVar("Int", 0, "Cost") self:NetworkVar("Int", 1, "TrapCost") self:NetworkVar("Bool", 0, "Active") self:NetworkVar("String", 0, "Description") end function ENT:Initialize() self:SetModel(self.Model) self:AddSolidFlags(FSOLID_NOT_STANDABLE) self:SetSolid(SOLID_BBOX) self:SetMoveType(MOVETYPE_NOCLIP) self:SetCollisionBounds(Vector(-32, -32, -32), Vector(32, 32, 32)) self:SetCollisionGroup(COLLISION_GROUP_WORLD) self:DrawShadow(false) self.IsTriggerNode = true if SERVER then timer.Simple(1, function() if self.GetTrapCost and self:GetTrapCost() == 0 then self:SetTrapCost(self:GetCost() + 100) end end) end end
ENT.Type = "anim" ENT.Model = "" ENT.RenderGroup = RENDERGROUP_BOTH function ENT:SetupDataTables() self:NetworkVar("Int", 0, "Cost") self:NetworkVar("Int", 1, "TrapCost") self:NetworkVar("Bool", 0, "Active") self:NetworkVar("String", 0, "Description") end function ENT:Initialize() self:SetModel(self.Model) self:AddSolidFlags(FSOLID_NOT_STANDABLE) self:SetSolid(SOLID_BBOX) self:SetMoveType(MOVETYPE_NOCLIP) self:SetCollisionBounds(Vector(-32, -32, -32), Vector(32, 32, 32)) self:SetCollisionGroup(COLLISION_GROUP_WORLD) self:DrawShadow(false) self.IsTriggerNode = true self:CollisionRulesChanged() if SERVER then timer.Simple(1, function() if self.GetTrapCost and self:GetTrapCost() == 0 then self:SetTrapCost(self:GetCost() + 100) end end) end end
More attempts to fix physics crashes
More attempts to fix physics crashes
Lua
apache-2.0
ForrestMarkX/glua-ZombieMaster
2374f3dd1d4e268b0a492efefd298b3e8a96b5b6
src/nodes/platform.lua
src/nodes/platform.lua
local Timer = require 'vendor/timer' local Platform = {} Platform.__index = Platform function Platform.new(node, collider) local platform = {} setmetatable(platform, Platform) --If the node is a polyline, we need to draw a polygon rather than rectangle if node.polyline or node.polygon then local polygon = node.polyline or node.polygon local vertices = {} for i, point in ipairs(polygon) do table.insert(vertices, node.x + point.x) table.insert(vertices, node.y + point.y) end platform.bb = collider:addPolygon(unpack(vertices)) platform.bb.polyline = polygon else platform.bb = collider:addRectangle(node.x, node.y, node.width, node.height) platform.bb.polyline = nil end platform.drop = node.properties.drop ~= 'false' platform.bb.node = platform collider:setPassive(platform.bb) return platform end function Platform:collide(player, dt, mtv_x, mtv_y) local _, wy1, _, wy2 = self.bb:bbox() local px1, py1, px2, py2 = player.bb:bbox() local distance = math.abs(player.velocity.y * dt) + 0.10 function updatePlayer() player:moveBoundingBox() player.jumping = false player.rebounding = false player:impactDamage() end if self.bb.polyline and player.velocity.y >= 0 -- Prevent the player from being treadmilled through an object and ( self.bb:contains(px2,py2) or self.bb:contains(px1,py2) ) then if self.drop and player.state == 'crouch' and player.velocity.x == 0 and not self.hasdropped then if not self.dropdelay then self.dropdelay = Timer.add(0.5, function() self.hasdropped = true self.dropdelay = nil end) end end if self.dropdelay and ( player.state ~= 'crouch' or player.jumping ) and not self.hasdropped then Timer.cancel(self.dropdelay) self.dropdelay = nil end if self.hasdropped then Timer.add(0.5, function() self.hasdropped = nil end) player.jumping = true player.state = 'crouch' else player.velocity.y = 0 -- Use the MTV to keep players feet on the ground, -- fudge the Y a bit to prevent falling into steep angles player.position.y = (py1 - 4 ) + mtv_y updatePlayer() end elseif player.velocity.y >= 0 and math.abs(wy1 - py2) <= distance then if self.drop and player.state == 'crouch' and player.velocity.x == 0 and not self.hasdropped then if not self.dropdelay then self.dropdelay = Timer.add(0.5, function() self.hasdropped = true self.dropdelay = nil end) end end if self.dropdelay and ( player.state ~= 'crouch' or player.jumping ) and not self.hasdropped then Timer.cancel(self.dropdelay) self.dropdelay = nil end if self.hasdropped then Timer.add(0.5, function() self.hasdropped = nil end) player.jumping = true player.state = 'crouch' else player.velocity.y = 0 player.position.y = wy1 - player.height updatePlayer() end end end return Platform
local Timer = require 'vendor/timer' local Platform = {} Platform.__index = Platform function Platform.new(node, collider) local platform = {} setmetatable(platform, Platform) --If the node is a polyline, we need to draw a polygon rather than rectangle if node.polyline or node.polygon then local polygon = node.polyline or node.polygon local vertices = {} for i, point in ipairs(polygon) do table.insert(vertices, node.x + point.x) table.insert(vertices, node.y + point.y) end platform.bb = collider:addPolygon(unpack(vertices)) platform.bb.polyline = polygon else platform.bb = collider:addRectangle(node.x, node.y, node.width, node.height) platform.bb.polyline = nil end platform.drop = node.properties.drop ~= 'false' platform.bb.node = platform collider:setPassive(platform.bb) return platform end function Platform:collide(player, dt, mtv_x, mtv_y) local _, wy1, _, wy2 = self.bb:bbox() local px1, py1, px2, py2 = player.bb:bbox() local distance = math.abs(player.velocity.y * dt) + 0.10 function updatePlayer() player:moveBoundingBox() player.jumping = false player.rebounding = false player:impactDamage() end if self.bb.polyline and player.velocity.y >= 0 -- Prevent the player from being treadmilled through an object and ( self.bb:contains(px2,py2) or self.bb:contains(px1,py2) ) then if self.drop and player.state == 'crouch' and player.velocity.x == 0 and not self.hasdropped then if not self.dropdelay then self.dropdelay = Timer.add(0.5, function() self.hasdropped = true self.dropdelay = nil end) end end if self.dropdelay and ( player.state ~= 'crouch' or player.jumping ) and not self.hasdropped then Timer.cancel(self.dropdelay) self.dropdelay = nil end if self.hasdropped then Timer.add(0.5, function() self.hasdropped = nil end) player.jumping = true player.state = 'crouch' else player.velocity.y = 0 -- Use the MTV to keep players feet on the ground, -- fudge the Y a bit to prevent falling into steep angles player.position.y = (py1 - 4 ) + mtv_y updatePlayer() end elseif player.velocity.y >= 0 and math.abs(wy1 - py2) <= distance then if self.drop and player.state == 'crouch' and player.velocity.x == 0 and not self.hasdropped then if not self.dropdelay then self.dropdelay = Timer.add(0.5, function() self.hasdropped = true self.dropdelay = nil end) end end if player.state ~= 'crouch' or player.jumping then self.hasdropped = false if self.dropdelay then Timer.cancel(self.dropdelay) self.dropdelay = nil end end if self.hasdropped then Timer.add(0.5, function() self.hasdropped = nil end) player.jumping = true player.state = 'crouch' else player.velocity.y = 0 player.position.y = wy1 - player.height updatePlayer() end end end return Platform
FIX Issue 244
FIX Issue 244
Lua
mit
hawkthorne/hawkthorne-client-lua,hawkthorne/hawkthorne-client-lua,hawkthorne/hawkthorne-server-lua,hawkthorne/hawkthorne-server-lua
827470992479358f7a65a0d03d27851c65fcbd8b
service/service_mgr.lua
service/service_mgr.lua
local skynet = require "skynet" local cmd = {} local service = {} function cmd.LAUNCH(service_name, ...) local s = service[service_name] if type(s) == "number" then return s end if s == nil then s = {} service[service_name] = s else assert(type(s) == "table") local co = coroutine.running() table.insert(s, co) skynet.wait() s = service[service_name] assert(type(s) == "number") return s end local handle = skynet.newservice(service_name, ...) for _,v in ipairs(s) do skynet.wakeup(v) end service[service_name] = handle return handle end function cmd.QUERY(service_name) local s = service[service_name] if type(s) == "number" then return s end if s == nil then s = {} service[service_name] = s end assert(type(s) == "table") local co = coroutine.running() table.insert(s, co) skynet.wait() s = service[service_name] assert(type(s) == "number") return s end skynet.start(function() skynet.dispatch("lua", function(session, address, command, service_name , ...) local f = cmd[command] if f == nil then skynet.ret(skynet.pack(nil)) return end local ok, r = pcall(f, service_name, ...) if ok then skynet.ret(skynet.pack(r)) else skynet.ret(skynet.pack(nil)) end end) skynet.register(".service") if skynet.getenv "standalone" then skynet.register("SERVICE") end end)
local skynet = require "skynet" local cmd = {} local service = {} function cmd.LAUNCH(service_name, ...) local s = service[service_name] if type(s) == "number" then return s end if s == nil then s = { launch = true } service[service_name] = s elseif s.launch then assert(type(s) == "table") local co = coroutine.running() table.insert(s, co) skynet.wait() s = service[service_name] assert(type(s) == "number") return s end local handle = skynet.newservice(service_name, ...) for _,v in ipairs(s) do skynet.wakeup(v) end service[service_name] = handle return handle end function cmd.QUERY(service_name) local s = service[service_name] if type(s) == "number" then return s end if s == nil then s = {} service[service_name] = s end assert(type(s) == "table") local co = coroutine.running() table.insert(s, co) skynet.wait() s = service[service_name] assert(type(s) == "number") return s end skynet.start(function() skynet.dispatch("lua", function(session, address, command, service_name , ...) local f = cmd[command] if f == nil then skynet.ret(skynet.pack(nil)) return end local ok, r = pcall(f, service_name, ...) if ok then skynet.ret(skynet.pack(r)) else skynet.ret(skynet.pack(nil)) end end) skynet.register(".service") if skynet.getenv "standalone" then skynet.register("SERVICE") end end)
bugfix: service manager dead lock
bugfix: service manager dead lock
Lua
mit
iskygame/skynet,zzh442856860/skynet,microcai/skynet,kebo/skynet,ruleless/skynet,sanikoyes/skynet,zhaijialong/skynet,chenjiansnail/skynet,sundream/skynet,samael65535/skynet,zhangshiqian1214/skynet,ludi1991/skynet,Zirpon/skynet,xinjuncoding/skynet,catinred2/skynet,rainfiel/skynet,QuiQiJingFeng/skynet,pigparadise/skynet,xubigshu/skynet,bigrpg/skynet,zhoukk/skynet,cuit-zhaxin/skynet,JiessieDawn/skynet,great90/skynet,chfg007/skynet,xjdrew/skynet,kyle-wang/skynet,asanosoyokaze/skynet,MoZhonghua/skynet,ruleless/skynet,chfg007/skynet,javachengwc/skynet,zhangshiqian1214/skynet,yinjun322/skynet,felixdae/skynet,dymx101/skynet,ludi1991/skynet,KAndQ/skynet,firedtoad/skynet,u20024804/skynet,lynx-seu/skynet,lynx-seu/skynet,lc412/skynet,zhangshiqian1214/skynet,zhouxiaoxiaoxujian/skynet,gitfancode/skynet,MRunFoss/skynet,pichina/skynet,harryzeng/skynet,cloudwu/skynet,KittyCookie/skynet,codingabc/skynet,cdd990/skynet,cpascal/skynet,iskygame/skynet,wangjunwei01/skynet,hongling0/skynet,leezhongshan/skynet,LuffyPan/skynet,fhaoquan/skynet,zhoukk/skynet,chuenlungwang/skynet,xinjuncoding/skynet,rainfiel/skynet,javachengwc/skynet,nightcj/mmo,winglsh/skynet,qyli/test,fztcjjl/skynet,cpascal/skynet,MoZhonghua/skynet,liuxuezhan/skynet,microcai/skynet,chenjiansnail/skynet,ilylia/skynet,QuiQiJingFeng/skynet,zhaijialong/skynet,xcjmine/skynet,gitfancode/skynet,JiessieDawn/skynet,sanikoyes/skynet,cdd990/skynet,your-gatsby/skynet,xubigshu/skynet,icetoggle/skynet,korialuo/skynet,cuit-zhaxin/skynet,zhouxiaoxiaoxujian/skynet,MRunFoss/skynet,zzh442856860/skynet,chenjiansnail/skynet,pichina/skynet,KAndQ/skynet,xjdrew/skynet,MetSystem/skynet,bingo235/skynet,winglsh/skynet,ludi1991/skynet,great90/skynet,dymx101/skynet,boyuegame/skynet,pigparadise/skynet,chuenlungwang/skynet,peimin/skynet,czlc/skynet,ag6ag/skynet,plsytj/skynet,qyli/test,ypengju/skynet_comment,matinJ/skynet,zhoukk/skynet,asanosoyokaze/skynet,winglsh/skynet,u20024804/skynet,fhaoquan/skynet,microcai/skynet,fztcjjl/skynet,Zirpon/skynet,bttscut/skynet,chuenlungwang/skynet,cmingjian/skynet,zhaijialong/skynet,leezhongshan/skynet,jxlczjp77/skynet,LiangMa/skynet,Ding8222/skynet,gitfancode/skynet,firedtoad/skynet,LuffyPan/skynet,catinred2/skynet,longmian/skynet,sdgdsffdsfff/skynet,vizewang/skynet,zhangshiqian1214/skynet,hongling0/skynet,longmian/skynet,czlc/skynet,u20024804/skynet,plsytj/skynet,cmingjian/skynet,lc412/skynet,jiuaiwo1314/skynet,togolwb/skynet,Markal128/skynet,wangjunwei01/skynet,MoZhonghua/skynet,helling34/skynet,letmefly/skynet,yinjun322/skynet,catinred2/skynet,pichina/skynet,plsytj/skynet,samael65535/skynet,cpascal/skynet,zhouxiaoxiaoxujian/skynet,puXiaoyi/skynet,LiangMa/skynet,wangyi0226/skynet,jiuaiwo1314/skynet,asanosoyokaze/skynet,lawnight/skynet,cuit-zhaxin/skynet,helling34/skynet,zhangshiqian1214/skynet,qyli/test,zzh442856860/skynet-Note,sdgdsffdsfff/skynet,yunGit/skynet,KAndQ/skynet,Ding8222/skynet,zhangshiqian1214/skynet,cloudwu/skynet,javachengwc/skynet,kyle-wang/skynet,KittyCookie/skynet,chfg007/skynet,yinjun322/skynet,bingo235/skynet,ilylia/skynet,sdgdsffdsfff/skynet,puXiaoyi/skynet,cloudwu/skynet,bttscut/skynet,codingabc/skynet,lawnight/skynet,MetSystem/skynet,pigparadise/skynet,sundream/skynet,QuiQiJingFeng/skynet,kyle-wang/skynet,lc412/skynet,Markal128/skynet,matinJ/skynet,great90/skynet,zzh442856860/skynet,letmefly/skynet,samael65535/skynet,boyuegame/skynet,czlc/skynet,enulex/skynet,xinmingyao/skynet,xinjuncoding/skynet,nightcj/mmo,cmingjian/skynet,icetoggle/skynet,letmefly/skynet,KittyCookie/skynet,MRunFoss/skynet,matinJ/skynet,hongling0/skynet,kebo/skynet,bigrpg/skynet,yunGit/skynet,korialuo/skynet,nightcj/mmo,lawnight/skynet,firedtoad/skynet,bttscut/skynet,wangjunwei01/skynet,longmian/skynet,LiangMa/skynet,ypengju/skynet_comment,zzh442856860/skynet-Note,codingabc/skynet,your-gatsby/skynet,liuxuezhan/skynet,xcjmine/skynet,Markal128/skynet,yunGit/skynet,Zirpon/skynet,felixdae/skynet,vizewang/skynet,qyli/test,rainfiel/skynet,harryzeng/skynet,sundream/skynet,kebo/skynet,ilylia/skynet,korialuo/skynet,boyuegame/skynet,letmefly/skynet,liuxuezhan/skynet,zzh442856860/skynet-Note,jiuaiwo1314/skynet,wangyi0226/skynet,iskygame/skynet,jxlczjp77/skynet,harryzeng/skynet,fztcjjl/skynet,helling34/skynet,wangyi0226/skynet,peimin/skynet_v0.1_with_notes,enulex/skynet,vizewang/skynet,togolwb/skynet,jxlczjp77/skynet,bigrpg/skynet,leezhongshan/skynet,felixdae/skynet,enulex/skynet,icetoggle/skynet,MetSystem/skynet,lawnight/skynet,ypengju/skynet_comment,peimin/skynet_v0.1_with_notes,ag6ag/skynet,xjdrew/skynet,peimin/skynet,xinmingyao/skynet,ag6ag/skynet,LuffyPan/skynet,Ding8222/skynet,sanikoyes/skynet,ludi1991/skynet,ruleless/skynet,zzh442856860/skynet-Note,JiessieDawn/skynet,your-gatsby/skynet,fhaoquan/skynet,xcjmine/skynet,cdd990/skynet,bingo235/skynet,dymx101/skynet,lynx-seu/skynet,puXiaoyi/skynet,liuxuezhan/skynet,togolwb/skynet
0e493d86ebcfb62fb1b7a7a7afd39dbf2b0a416e
Modules/Client/Ragdoll/Classes/RagdollableClient.lua
Modules/Client/Ragdoll/Classes/RagdollableClient.lua
--- -- @classmod RagdollableClient -- @author Quenty local require = require(game:GetService("ReplicatedStorage"):WaitForChild("Nevermore")) local Players = game:GetService("Players") local BaseObject = require("BaseObject") local RagdollableConstants = require("RagdollableConstants") local CharacterUtils = require("CharacterUtils") local RagdollRigging = require("RagdollRigging") local HumanoidAnimatorUtils = require("HumanoidAnimatorUtils") local Maid = require("Maid") local RagdollBindersClient = require("RagdollBindersClient") local RagdollUtils = require("RagdollUtils") local RagdollableClient = setmetatable({}, BaseObject) RagdollableClient.ClassName = "RagdollableClient" RagdollableClient.__index = RagdollableClient require("PromiseRemoteEventMixin"):Add(RagdollableClient, RagdollableConstants.REMOTE_EVENT_NAME) function RagdollableClient.new(humanoid) local self = setmetatable(BaseObject.new(humanoid), RagdollableClient) self._player = CharacterUtils.getPlayerFromCharacter(self._obj) if self._player == Players.LocalPlayer then self:PromiseRemoteEvent():Then(function(remoteEvent) self._localPlayerRemoteEvent = remoteEvent or error("No remoteEvent") self:_setupLocal() end) else self:_setupLocal() end return self end function RagdollableClient:_setupLocal() self._maid:GiveTask(RagdollBindersClient.Ragdoll:ObserveInstance(self._obj, function() self:_onRagdollChanged() end)) self:_onRagdollChanged() end function RagdollableClient:_onRagdollChanged() if RagdollBindersClient.Ragdoll:Get(self._obj) then self._maid._ragdoll = self:_ragdollLocal() if self._localPlayerRemoteEvent then -- Tell the server that we started simulating our ragdoll self._localPlayerRemoteEvent:FireServer(true) end else self._maid._ragdoll = nil if self._localPlayerRemoteEvent then -- Let server know to reset! self._localPlayerRemoteEvent:FireServer(false) end end end function RagdollableClient:_ragdollLocal() local maid = Maid.new() if self._localPlayerRemoteEvent then -- Hopefully these are already created. Intent here is to reset friction. RagdollRigging.createRagdollJoints(self._obj.Parent, self._obj.RigType) maid:GiveTask(RagdollUtils.setupState(self._obj)) maid:GiveTask(RagdollUtils.setupMotors(self._obj)) maid:GiveTask(RagdollUtils.setupHead(self._obj)) end -- Do this after we setup motors HumanoidAnimatorUtils.stopAnimations(self._obj, 0) maid:GiveTask(self._obj.AnimationPlayed:Connect(function(track) track:Stop(0) end)) maid:GiveTask(RagdollUtils.preventAnimationTransformLoop(self._obj)) return maid end return RagdollableClient
--- -- @classmod RagdollableClient -- @author Quenty local require = require(game:GetService("ReplicatedStorage"):WaitForChild("Nevermore")) local Players = game:GetService("Players") local BaseObject = require("BaseObject") local RagdollableConstants = require("RagdollableConstants") local CharacterUtils = require("CharacterUtils") local RagdollRigging = require("RagdollRigging") local HumanoidAnimatorUtils = require("HumanoidAnimatorUtils") local Maid = require("Maid") local RagdollBindersClient = require("RagdollBindersClient") local RagdollUtils = require("RagdollUtils") local RagdollableClient = setmetatable({}, BaseObject) RagdollableClient.ClassName = "RagdollableClient" RagdollableClient.__index = RagdollableClient require("PromiseRemoteEventMixin"):Add(RagdollableClient, RagdollableConstants.REMOTE_EVENT_NAME) function RagdollableClient.new(humanoid) local self = setmetatable(BaseObject.new(humanoid), RagdollableClient) self._player = CharacterUtils.getPlayerFromCharacter(self._obj) if self._player == Players.LocalPlayer then self:PromiseRemoteEvent():Then(function(remoteEvent) self._localPlayerRemoteEvent = remoteEvent or error("No remoteEvent") self:_setupLocal() end) else self:_setupLocal() end return self end function RagdollableClient:_setupLocal() self._maid:GiveTask(RagdollBindersClient.Ragdoll:ObserveInstance(self._obj, function() self:_onRagdollChanged() end)) self:_onRagdollChanged() end function RagdollableClient:_onRagdollChanged() if RagdollBindersClient.Ragdoll:Get(self._obj) then self._maid._ragdoll = self:_ragdollLocal() if self._localPlayerRemoteEvent then -- Tell the server that we started simulating our ragdoll self._localPlayerRemoteEvent:FireServer(true) end else self._maid._ragdoll = nil if self._localPlayerRemoteEvent then -- Let server know to reset! self._localPlayerRemoteEvent:FireServer(false) end end end function RagdollableClient:_ragdollLocal() local maid = Maid.new() -- Really hard to infer whether or not we're the network owner, so we just try to do this for every single one. -- Hopefully these are already created. Intent here is to reset friction. RagdollRigging.createRagdollJoints(self._obj.Parent, self._obj.RigType) maid:GiveTask(RagdollUtils.setupState(self._obj)) maid:GiveTask(RagdollUtils.setupMotors(self._obj)) maid:GiveTask(RagdollUtils.setupHead(self._obj)) -- Do this after we setup motors HumanoidAnimatorUtils.stopAnimations(self._obj, 0) maid:GiveTask(self._obj.AnimationPlayed:Connect(function(track) track:Stop(0) end)) maid:GiveTask(RagdollUtils.preventAnimationTransformLoop(self._obj)) return maid end return RagdollableClient
Fix ragdolling with swapped network owner
Fix ragdolling with swapped network owner
Lua
mit
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
27c581142457b64561067aa7e41f83f991bcf559
app/templates/_main.lua
app/templates/_main.lua
-- hide the status bar display.setStatusBar( display.HiddenStatusBar ) -- Fix music audio.setSessionProperty(audio.MixMode, audio.AmbientMixMode) -- Require local cacharro = require("bower_components.cacharro.cacharro") local middleclass = require("bower_components.middleclass.middleclass") local inspect = require("bower_components.inspect.inspect") local ads = require("ads") local storyboard = require("storyboard") local gameNetwork = require("gameNetwork") local analytics = require("analytics") dbconfig.init() timesPlayed = 0 --Random numbers now more random math.randomseed( os.time() ) -- local fps = require("helpers.fps") -- local performance = fps.PerformanceOutput.new(); -- performance.group.x, performance.group.y = (display.contentWidth/2) + (display.viewableContentWidth/2) - 115, (display.contentHeight / 2) + (display.viewableContentHeight / 2) - 45; -- performance.group.alpha = 0.5; local centerX = display.contentWidth / 2 local centerY = display.contentHeight / 2 local halfViewX = display.viewableContentWidth / 2 local halfViewY = display.viewableContentHeight / 2 if cacharro.isSimulator then audio.setVolume(0) storyboard.gotoScene("src.scenes.home") else -- ADDS local function adListener( event ) local msg = event.response if event.isError then -- Failed to receive an ad, we print the error message returned from the library. log(msg) end end if cacharro.isAndroid then ads.init( "admob", "ca-app-pub-***", adListener ) local function initCallback( event ) if not event.isError then -- Tries to automatically log in the user without displaying the login screen if the user doesn't want to login gameNetwork.request("login",{ userInitiated = true }) end end local function onKeyEvent( event ) if (event.keyName == "back" and event.phase == 'up') then local function onComplete( event ) if "clicked" == event.action then local i = event.index if 1 == i then native.requestExit( ) end end end local alert = native.showAlert( "Hey Listen!", "Don't go!", {"OK", "Cancel"}, onComplete) return true end return false end Runtime:addEventListener( "key", onKeyEvent ) gameNetwork.init( "google", initCallback ) analytics.init( "***" ) native.setProperty( "androidSystemUiVisibility", "lowProfile" ) elseif cacharro.isApple then ads.init( "admob", "ca-app-pub-***", adListener ) gameNetwork.init( "gamecenter") analytics.init( "***" ) end analytics.logEvent( "AppStarted" ) local splash = display.newImage("img/splash.png") splash.x = centerX splash.y = centerY timer.performWithDelay( 5000, function() display.remove( splash ) splash = nil back = nil storyboard.gotoScene("src.scenes.home") end) end local function onSystemEvent( event ) log( "System event name and type: " .. event.name, event.type ) if event.type == "applicationExit" or event.type == "applicationSuspend" then system.cancelNotification( ) local futureTime = 3600 * 24 local futureTime2 = futureTime * 7 local text1 = "Title1" local text2 = "Title2" local options, options2 if cacharro.isAndroid then options = { alert = text1, } options2 = { alert = text2, } elseif cacharro.isApple then options = { alert = text1, badge = native.getProperty( "applicationIconBadgeNumber" ) + 1, } options2 = { alert = text2, badge = native.getProperty( "applicationIconBadgeNumber" ) + 1, } end local notificationID = system.scheduleNotification( futureTime, options ) local notificationID2 = system.scheduleNotification( futureTime2, options2 ) elseif event.type == "applicationStart" or event.type == "applicationResume" then system.cancelNotification( ) end end Runtime:addEventListener( "system", onSystemEvent ) local function notificationListener( event ) if ( event.type == "local" ) then analytics.logEvent("Notification") -- log("NOTIFICATION") end end Runtime:addEventListener( "notification", notificationListener ) local launchArgs = ... if ( launchArgs and launchArgs.notification ) then -- log( "event via launchArgs" ) notificationListener( launchArgs.notification ) end --handle the local notification native.setProperty( "applicationIconBadgeNumber", 0 )
-- hide the status bar display.setStatusBar( display.HiddenStatusBar ) -- Fix music audio.setSessionProperty(audio.MixMode, audio.AmbientMixMode) -- Require local cacharro = require("bower_components.cacharro.cacharro") local middleclass = require("bower_components.middleclass.middleclass") local ads = require("ads") local storyboard = require("storyboard") local gameNetwork = require("gameNetwork") local analytics = require("analytics") --dbconfig.init() timesPlayed = 0 --Random numbers now more random math.randomseed( os.time() ) -- local fps = require("helpers.fps") -- local performance = fps.PerformanceOutput.new(); -- performance.group.x, performance.group.y = (display.contentWidth/2) + (display.viewableContentWidth/2) - 115, (display.contentHeight / 2) + (display.viewableContentHeight / 2) - 45; -- performance.group.alpha = 0.5; local centerX = display.contentWidth / 2 local centerY = display.contentHeight / 2 local halfViewX = display.viewableContentWidth / 2 local halfViewY = display.viewableContentHeight / 2 if cacharro.isSimulator then audio.setVolume(0) storyboard.gotoScene("src.scenes.home") else -- ADDS local function adListener( event ) local msg = event.response if event.isError then -- Failed to receive an ad, we print the error message returned from the library. --log(msg) end end if cacharro.isAndroid then ads.init( "admob", "ca-app-pub-***", adListener ) local function initCallback( event ) if not event.isError then -- Tries to automatically log in the user without displaying the login screen if the user doesn't want to login gameNetwork.request("login",{ userInitiated = true }) end end local function onKeyEvent( event ) if (event.keyName == "back" and event.phase == 'up') then local function onComplete( event ) if "clicked" == event.action then local i = event.index if 1 == i then native.requestExit( ) end end end local alert = native.showAlert( "Hey Listen!", "Don't go!", {"OK", "Cancel"}, onComplete) return true end return false end Runtime:addEventListener( "key", onKeyEvent ) gameNetwork.init( "google", initCallback ) analytics.init( "***" ) native.setProperty( "androidSystemUiVisibility", "lowProfile" ) elseif cacharro.isApple then ads.init( "admob", "ca-app-pub-***", adListener ) gameNetwork.init( "gamecenter") analytics.init( "***" ) end analytics.logEvent( "AppStarted" ) local splash = display.newImage("img/splash.png") splash.x = centerX splash.y = centerY timer.performWithDelay( 5000, function() display.remove( splash ) splash = nil back = nil storyboard.gotoScene("src.scenes.home") end) end local function onSystemEvent( event ) if event.type == "applicationExit" or event.type == "applicationSuspend" then system.cancelNotification( ) local futureTime = 3600 * 24 local futureTime2 = futureTime * 7 local text1 = "Title1" local text2 = "Title2" local options, options2 if cacharro.isAndroid then options = { alert = text1, } options2 = { alert = text2, } elseif cacharro.isApple then options = { alert = text1, badge = native.getProperty( "applicationIconBadgeNumber" ) + 1, } options2 = { alert = text2, badge = native.getProperty( "applicationIconBadgeNumber" ) + 1, } end local notificationID = system.scheduleNotification( futureTime, options ) local notificationID2 = system.scheduleNotification( futureTime2, options2 ) elseif event.type == "applicationStart" or event.type == "applicationResume" then system.cancelNotification( ) end end Runtime:addEventListener( "system", onSystemEvent ) local function notificationListener( event ) if ( event.type == "local" ) then analytics.logEvent("Notification") -- log("NOTIFICATION") end end Runtime:addEventListener( "notification", notificationListener ) local launchArgs = ... if ( launchArgs and launchArgs.notification ) then -- log( "event via launchArgs" ) notificationListener( launchArgs.notification ) end --handle the local notification native.setProperty( "applicationIconBadgeNumber", 0 )
Fixed sme errors
Fixed sme errors
Lua
mit
Arlefreak/generator-coronasdk
a7f70f9746af3354e2f8a5332eddeb322ed50e76
src/npge/alignment/move_identical.lua
src/npge/alignment/move_identical.lua
-- use C version if available local has_c, cmove_identical = pcall(require, 'npge.alignment.cmove_identical') if has_c then return cmove_identical end return function(rows) -- Input: -- ...... -- ..... -- ....... -- Output: -- *** .... -- *** , .. -- *** .... local aligned = {} for _, row in ipairs(rows) do -- list of char's table.insert(aligned, {}) end local pos = 1 while true do local first = rows[1]:sub(pos, pos) if #first == 0 then break end local bad for _, row in ipairs(rows) do local letter = row:sub(pos, pos) if letter ~= first then bad = true end end if bad then break end for _, aligned_row in ipairs(aligned) do table.insert(aligned_row, first) end pos = pos + 1 end local aligned_row = table.concat(aligned[1] or {}) local result = {} local tails = {} for i, _ in ipairs(aligned) do table.insert(result, aligned_row) table.insert(tails, rows[i]:sub(pos)) end return result, tails end
-- use C version if available local has_c, cmove_identical = pcall(require, 'npge.alignment.cmove_identical') if has_c then return cmove_identical end return function(rows) -- Input: -- ...... -- ..... -- ....... -- Output: -- *** .... -- *** , .. -- *** .... if #rows == 0 then return {}, {} end local aligned = {} for _, row in ipairs(rows) do -- list of char's table.insert(aligned, {}) end local pos = 1 while true do local first = rows[1]:sub(pos, pos) if #first == 0 then break end local bad for _, row in ipairs(rows) do local letter = row:sub(pos, pos) if letter ~= first then bad = true end end if bad then break end for _, aligned_row in ipairs(aligned) do table.insert(aligned_row, first) end pos = pos + 1 end local aligned_row = table.concat(aligned[1]) local result = {} local tails = {} for i, _ in ipairs(aligned) do table.insert(result, aligned_row) table.insert(tails, rows[i]:sub(pos)) end return result, tails end
fix Lua version of move_identical
fix Lua version of move_identical (failed against empty rows list)
Lua
mit
npge/lua-npge,starius/lua-npge,starius/lua-npge,npge/lua-npge,starius/lua-npge,npge/lua-npge
bc978841c86e077817f41f5daa42a332071a1fd0
src/patch/ui/lib/mppatch_modutils.lua
src/patch/ui/lib/mppatch_modutils.lua
-- Copyright (c) 2015-2016 Lymia Alusyia <[email protected]> -- -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -- copies of the Software, and to permit persons to whom the Software is -- furnished to do so, subject to the following conditions: -- -- The above copyright notice and this permission notice shall be included in -- all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -- THE SOFTWARE. local patch = _mpPatch.patch function _mpPatch.overrideWithModList(list) _mpPatch.debugPrint("Overriding mods...") patch.NetPatch.reset() for _, mod in ipairs(list) do _mpPatch.debugPrint("- Adding mod ".._mpPatch.getModName(mod.ID, mod.Version).."...") patch.NetPatch.pushMod(mod.ID, mod.Version) end patch.NetPatch.overrideModList() patch.NetPatch.install() end function _mpPatch.overrideModsFromActivatedList() local modList = Modding.GetActivatedMods() if modList and #modList > 0 then _mpPatch.overrideWithModList(modList) end end function _mpPatch.overrideModsFromPreGame() local modList = _mpPatch.decodeModsList() if modList and _mpPatch.isModding then _mpPatch.overrideWithModList(modList) end end function _mpPatch.overrideModsFromSaveFile(file) local _, requiredMods = Modding.GetSavedGameRequirements(file) if type(requiredMods) == "table" then _mpPatch.overrideWithModList(requiredMods) end end _mpPatch._mt.registerProperty("areModsEnabled", function() return #Modding.GetActivatedMods() > 0 end) function _mpPatch.getModName(uuid, version) local details = Modding.GetInstalledModDetails(uuid, version) or {} return details.Name or "<unknown mod "..uuid.." v"..version..">" end local modInstalledQuery = [[select count(*) from Mods where ModID = ? and Version = ? and Installed = 1]] function _mpPatch.isModInstalled(uuid, version) for row in DB.Query(modInstalledQuery, uuid, version) do return row.count > 0 end return false end -- Mod dependency listing function _mpPatch.normalizeDlcName(name) return name:gsub("-", ""):upper() end function _mpPatch.getModDependencies(modList) local dlcDependencies = {} for row in GameInfo.DownloadableContent() do dlcDependencies[_mpPatch.normalizeDlcName(row.PackageID)] = {} end for _, mod in ipairs(modList) do local info = { ID = mod.ID, Version = mod.Version, Name = _mpPatch.getModName(mod.ID, mod.Version) } for _, assoc in ipairs(Modding.GetDlcAssociations(mod.ID, mod.Version)) do if assoc.Type == 2 then if assoc.PackageID == "*" then for row in GameInfo.DownloadableContent() do table.insert(dlcDependencies[_mpPatch.normalizeDlcName(row.PackageID)], info) end else local normName = _mpPatch.normalizeDlcName(assoc.PackageID) if dlcDependencies[normName] then table.insert(dlcDependencies[normName], info) end end end end end return dlcDependencies end -- UUID encoding/decoding for storing a mod list in PreGame's options table local uuidRegex = ("("..("[0-9a-fA-F]"):rep(4)..")"):rep(8) local function encodeUUID(uuidString) uuidString = uuidString:gsub("-", "") local uuids = {uuidString:match(uuidRegex)} if #uuids ~= 8 or not uuids[1] then error("could not parse UUID") end return _mpPatch.map(uuids, function(x) return tonumber(x, 16) end) end local function decodeUUID(table) return string.format("%04x%04x-%04x-%04x-%04x-%04x%04x%04x", unpack(table)) end -- Enroll/decode mods into the PreGame option table _mpPatch._mt.registerProperty("isModding", function() return _mpPatch.getGameOption("HAS_MODS") == 1 end) local function enrollModName(id, name) _mpPatch.setGameOption("MOD_"..id.."_NAME_LENGTH", #name) for i=1,#name do _mpPatch.setGameOption("MOD_"..id.."_NAME_"..i, name:byte(i)) end end local function enrollMod(id, uuid, version) local modName = _mpPatch.getModName(uuid, version) _mpPatch.debugPrint("- Enrolling mod "..modName) _mpPatch.setGameOption("MOD_"..id.."_VERSION", version) for i, v in ipairs(encodeUUID(uuid)) do _mpPatch.setGameOption("MOD_"..id.."_"..i, v) end enrollModName(id, modName) end function _mpPatch.enrollModsList(modList) _mpPatch.debugPrint("Enrolling mods...") if #modList > 0 then _mpPatch.setGameOption("HAS_MODS", 1) _mpPatch.setGameOption("MOD_COUNT", #modList) for i, v in ipairs(modList) do enrollMod(i, v.ID, v.Version) end else _mpPatch.setGameOption("HAS_MODS", 0) end end local function decodeModName(id) local charTable = {} for i=1,_mpPatch.getGameOption("MOD_"..id.."_NAME_LENGTH") do charTable[i] = string.char(_mpPatch.getGameOption("MOD_"..id.."_NAME_"..i)) end return table.concat(charTable) end local function decodeMod(id) local uuidTable = {} for i=1,8 do uuidTable[i] = _mpPatch.getGameOption("MOD_"..id.."_"..i) end return { ID = decodeUUID(uuidTable), Version = _mpPatch.getGameOption("MOD_"..id.."_VERSION"), Name = decodeModName(id) } end function _mpPatch.decodeModsList() if not _mpPatch.isModding then return nil end local modList = {} for i=1,_mpPatch.getGameOption("MOD_COUNT") do modList[i] = decodeMod(i) end return modList end
-- Copyright (c) 2015-2016 Lymia Alusyia <[email protected]> -- -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -- copies of the Software, and to permit persons to whom the Software is -- furnished to do so, subject to the following conditions: -- -- The above copyright notice and this permission notice shall be included in -- all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -- THE SOFTWARE. local patch = _mpPatch.patch function _mpPatch.overrideWithModList(list) _mpPatch.debugPrint("Overriding mods...") patch.NetPatch.reset() for _, mod in ipairs(list) do _mpPatch.debugPrint("- Adding mod ".._mpPatch.getModName(mod.ID, mod.Version).."...") patch.NetPatch.pushMod(mod.ID, mod.Version) end patch.NetPatch.overrideModList() patch.NetPatch.install() end function _mpPatch.overrideModsFromActivatedList() local modList = Modding.GetActivatedMods() if modList and #modList > 0 then _mpPatch.overrideWithModList(modList) end end function _mpPatch.overrideModsFromPreGame() local modList = _mpPatch.decodeModsList() if modList and _mpPatch.isModding then _mpPatch.overrideWithModList(modList) end end function _mpPatch.overrideModsFromSaveFile(file) local _, requiredMods = Modding.GetSavedGameRequirements(file) if type(requiredMods) == "table" then _mpPatch.overrideWithModList(requiredMods) end end _mpPatch._mt.registerProperty("areModsEnabled", function() return #Modding.GetActivatedMods() > 0 end) function _mpPatch.getModName(uuid, version) local details = Modding.GetInstalledModDetails(uuid, version) or {} return details.Name or "<unknown mod "..uuid.." v"..version..">" end _mpPatch._mt.registerLazyVal("installedMods", function() local installed = {} for _, v in pairs(Modding.GetInstalledMods()) do installed[v.ID.."_"..v.Version] = true end return installed end) function _mpPatch.isModInstalled(uuid, version) return not not _mppatch.installedMods[uuid.."_"..version] end -- Mod dependency listing function _mpPatch.normalizeDlcName(name) return name:gsub("-", ""):upper() end function _mpPatch.getModDependencies(modList) local dlcDependencies = {} for row in GameInfo.DownloadableContent() do dlcDependencies[_mpPatch.normalizeDlcName(row.PackageID)] = {} end for _, mod in ipairs(modList) do local info = { ID = mod.ID, Version = mod.Version, Name = _mpPatch.getModName(mod.ID, mod.Version) } for _, assoc in ipairs(Modding.GetDlcAssociations(mod.ID, mod.Version)) do if assoc.Type == 2 then if assoc.PackageID == "*" then for row in GameInfo.DownloadableContent() do table.insert(dlcDependencies[_mpPatch.normalizeDlcName(row.PackageID)], info) end else local normName = _mpPatch.normalizeDlcName(assoc.PackageID) if dlcDependencies[normName] then table.insert(dlcDependencies[normName], info) end end end end end return dlcDependencies end -- UUID encoding/decoding for storing a mod list in PreGame's options table local uuidRegex = ("("..("[0-9a-fA-F]"):rep(4)..")"):rep(8) local function encodeUUID(uuidString) uuidString = uuidString:gsub("-", "") local uuids = {uuidString:match(uuidRegex)} if #uuids ~= 8 or not uuids[1] then error("could not parse UUID") end return _mpPatch.map(uuids, function(x) return tonumber(x, 16) end) end local function decodeUUID(table) return string.format("%04x%04x-%04x-%04x-%04x-%04x%04x%04x", unpack(table)) end -- Enroll/decode mods into the PreGame option table _mpPatch._mt.registerProperty("isModding", function() return _mpPatch.getGameOption("HAS_MODS") == 1 end) local function enrollModName(id, name) _mpPatch.setGameOption("MOD_"..id.."_NAME_LENGTH", #name) for i=1,#name do _mpPatch.setGameOption("MOD_"..id.."_NAME_"..i, name:byte(i)) end end local function enrollMod(id, uuid, version) local modName = _mpPatch.getModName(uuid, version) _mpPatch.debugPrint("- Enrolling mod "..modName) _mpPatch.setGameOption("MOD_"..id.."_VERSION", version) for i, v in ipairs(encodeUUID(uuid)) do _mpPatch.setGameOption("MOD_"..id.."_"..i, v) end enrollModName(id, modName) end function _mpPatch.enrollModsList(modList) _mpPatch.debugPrint("Enrolling mods...") if #modList > 0 then _mpPatch.setGameOption("HAS_MODS", 1) _mpPatch.setGameOption("MOD_COUNT", #modList) for i, v in ipairs(modList) do enrollMod(i, v.ID, v.Version) end else _mpPatch.setGameOption("HAS_MODS", 0) end end local function decodeModName(id) local charTable = {} for i=1,_mpPatch.getGameOption("MOD_"..id.."_NAME_LENGTH") do charTable[i] = string.char(_mpPatch.getGameOption("MOD_"..id.."_NAME_"..i)) end return table.concat(charTable) end local function decodeMod(id) local uuidTable = {} for i=1,8 do uuidTable[i] = _mpPatch.getGameOption("MOD_"..id.."_"..i) end return { ID = decodeUUID(uuidTable), Version = _mpPatch.getGameOption("MOD_"..id.."_VERSION"), Name = decodeModName(id) } end function _mpPatch.decodeModsList() if not _mpPatch.isModding then return nil end local modList = {} for i=1,_mpPatch.getGameOption("MOD_COUNT") do modList[i] = decodeMod(i) end return modList end
Fixed isModInstalled.
Fixed isModInstalled.
Lua
mit
Lymia/CivV_Mod2DLC,Lymia/MultiverseModManager,Lymia/MPPatch,Lymia/MultiverseModManager,Lymia/MPPatch,Lymia/MPPatch,Lymia/MPPatch
f0135380a7f35589595f4819e98acdff4d4efb6d
src/lunajson/encode.lua
src/lunajson/encode.lua
local byte = string.byte local find = string.find local format = string.format local gsub = string.gsub local match = string.match local rawequal = rawequal local tostring = tostring local pairs = pairs local type = type local huge = 1/0 local tiny = -1/0 local function encode(v, nullv) local i = 1 local builder = {} local visited = {} local function f_tostring(v) builder[i] = tostring(v) i = i+1 end local radixmark = match(tostring(0.5), '[^0-9]') local delimmark = match(tostring(12345.12345), '[^0-9' .. radixmark .. ']') if radixmark == '.' then radixmark = nil end local radixordelim if radixmark or delimmark then radixordelim = true if radixmark and find(radixmark, '%W') then radixmark = '%' .. radixmark end if delimmark and find(delimmark, '%W') then delimmark = '%' .. delimmark end end local f_number = function(n) if tiny < n and n < huge then local s = format("%.17g", n) if radixordelim then if delimmark then s = gsub(s, delimmark, '') end if radixmark then s = gsub(s, radixmark, '.') end end builder[i] = s i = i+1 return end error('invalid number') end local doencode local f_string_subst = { ['"'] = '\\"', ['\\'] = '\\\\', ['\b'] = '\\b', ['\f'] = '\\f', ['\n'] = '\\n', ['\r'] = '\\r', ['\t'] = '\\t', __index = function(_, c) return format('\\u00%02X', byte(c)) end } setmetatable(f_string_subst, f_string_subst) local function f_string(s) -- use the cluttered pattern because lua 5.1 does not handle \0 in a pattern correctly local pat = '[^\32-\33\35-\91\93-\255]' builder[i] = '"' if find(s, pat) then s = gsub(s, pat, f_string_subst) end builder[i+1] = s builder[i+2] = '"' i = i+3 end local function f_table(o) if visited[o] then error("loop detected") end visited[o] = true local tmp = o[0] if type(tmp) == 'number' then -- arraylen available builder[i] = '[' i = i+1 for j = 1, tmp do doencode(o[j]) builder[i] = ',' i = i+1 end if tmp > 0 then i = i-1 end builder[i] = ']' else tmp = o[1] if tmp ~= nil then -- detected as array builder[i] = '[' i = i+1 local j = 2 repeat doencode(tmp) tmp = o[j] if tmp == nil then break end j = j+1 builder[i] = ',' i = i+1 until false builder[i] = ']' else -- detected as object builder[i] = '{' i = i+1 local tmp = i for k, v in pairs(o) do if type(k) ~= 'string' then error("non-string key") end f_string(k) builder[i] = ':' i = i+1 doencode(v) builder[i] = ',' i = i+1 end if i > tmp then i = i-1 end builder[i] = '}' end end i = i+1 visited[o] = nil end local dispatcher = { boolean = f_tostring, number = f_number, string = f_string, table = arraylen and f_table_arraylen or f_table, __index = function() error("invalid type value") end } setmetatable(dispatcher, dispatcher) function doencode(v) if v == nullv then builder[i] = 'null' i = i+1 return end return dispatcher[type(v)](v) end -- exec doencode(v) return table.concat(builder) end return encode
local byte = string.byte local find = string.find local format = string.format local gsub = string.gsub local match = string.match local rawequal = rawequal local tostring = tostring local pairs = pairs local type = type local huge = 1/0 local tiny = -1/0 local f_string_pat if _VERSION <= "Lua 5.1" then -- use the cluttered pattern because lua 5.1 does not handle \0 in a pattern correctly f_string_pat = '[^ -!#-[%]^-\255]' else f_string_pat = '[\0-\31"\\]' end local function encode(v, nullv) local i = 1 local builder = {} local visited = {} local function f_tostring(v) builder[i] = tostring(v) i = i+1 end local radixmark = match(tostring(0.5), '[^0-9]') local delimmark = match(tostring(12345.12345), '[^0-9' .. radixmark .. ']') if radixmark == '.' then radixmark = nil end local radixordelim if radixmark or delimmark then radixordelim = true if radixmark and find(radixmark, '%W') then radixmark = '%' .. radixmark end if delimmark and find(delimmark, '%W') then delimmark = '%' .. delimmark end end local f_number = function(n) if tiny < n and n < huge then local s = format("%.17g", n) if radixordelim then if delimmark then s = gsub(s, delimmark, '') end if radixmark then s = gsub(s, radixmark, '.') end end builder[i] = s i = i+1 return end error('invalid number') end local doencode local f_string_subst = { ['"'] = '\\"', ['\\'] = '\\\\', ['\b'] = '\\b', ['\f'] = '\\f', ['\n'] = '\\n', ['\r'] = '\\r', ['\t'] = '\\t', __index = function(_, c) return format('\\u00%02X', byte(c)) end } setmetatable(f_string_subst, f_string_subst) local function f_string(s) builder[i] = '"' if find(s, f_string_pat) then s = gsub(s, f_string_pat, f_string_subst) end builder[i+1] = s builder[i+2] = '"' i = i+3 end local function f_table(o) if visited[o] then error("loop detected") end visited[o] = true local tmp = o[0] if type(tmp) == 'number' then -- arraylen available builder[i] = '[' i = i+1 for j = 1, tmp do doencode(o[j]) builder[i] = ',' i = i+1 end if tmp > 0 then i = i-1 end builder[i] = ']' else tmp = o[1] if tmp ~= nil then -- detected as array builder[i] = '[' i = i+1 local j = 2 repeat doencode(tmp) tmp = o[j] if tmp == nil then break end j = j+1 builder[i] = ',' i = i+1 until false builder[i] = ']' else -- detected as object builder[i] = '{' i = i+1 local tmp = i for k, v in pairs(o) do if type(k) ~= 'string' then error("non-string key") end f_string(k) builder[i] = ':' i = i+1 doencode(v) builder[i] = ',' i = i+1 end if i > tmp then i = i-1 end builder[i] = '}' end end i = i+1 visited[o] = nil end local dispatcher = { boolean = f_tostring, number = f_number, string = f_string, table = arraylen and f_table_arraylen or f_table, __index = function() error("invalid type value") end } setmetatable(dispatcher, dispatcher) function doencode(v) if v == nullv then builder[i] = 'null' i = i+1 return end return dispatcher[type(v)](v) end -- exec doencode(v) return table.concat(builder) end return encode
fix pattern
fix pattern
Lua
mit
tst2005/lunajson,bigcrush/lunajson,tst2005/lunajson,grafi-tt/lunajson,bigcrush/lunajson,csteddy/lunajson,grafi-tt/lunajson,csteddy/lunajson,grafi-tt/lunajson
8000f6d1362fc38ebe349119554d291f6226e04e
lgi/override/Gdk.lua
lgi/override/Gdk.lua
------------------------------------------------------------------------------ -- -- LGI Gdk3 override module. -- -- Copyright (c) 2011 Pavel Holejsovsky -- Licensed under the MIT license: -- http://www.opensource.org/licenses/mit-license.php -- ------------------------------------------------------------------------------ local select, type, pairs, unpack, rawget = select, type, pairs, unpack, rawget local lgi = require 'lgi' local core = require 'lgi.core' local ffi = require 'lgi.ffi' local ti = ffi.types local Gdk = lgi.Gdk local cairo = lgi.cairo -- Take over internal GDK synchronization lock. core.registerlock(core.gi.Gdk.resolve.gdk_threads_set_lock_functions) Gdk.threads_init() -- Gdk.Rectangle does not exist at all, because it is aliased to -- cairo.RectangleInt. Make sure that we have it exists, because it -- is very commonly used in API documentation. Gdk.Rectangle = lgi.cairo.RectangleInt Gdk.Rectangle._method = rawget(Gdk.Rectangle, '_method') or {} Gdk.Rectangle._method.intersect = Gdk.rectangle_intersect Gdk.Rectangle._method.union = Gdk.rectangle_union -- Declare GdkAtoms which are #define'd in Gdk sources and not -- introspected in gir. local _ = Gdk.KEY_0 for name, val in pairs { SELECTION_PRIMARY = 1, SELECTION_SECONDARY = 2, SELECTION_CLIPBOARD = 69, TARGET_BITMAP = 5, TARGET_COLORMAP = 7, TARGET_DRAWABLE = 17, TARGET_PIXMAP = 20, TARGET_STRING = 31, SELECTION_TYPE_ATOM = 4, SELECTION_TYPE_BITMAP = 5, SELECTION_TYPE_COLORMAP = 7, SELECTION_TYPE_DRAWABLE = 17, SELECTION_TYPE_INTEGER = 19, SELECTION_TYPE_PIXMAP = 20, SELECTION_TYPE_WINDOW = 33, SELECTION_TYPE_STRING = 31, } do Gdk._constant[name] = Gdk.Atom(val) end -- Easier-to-use Gdk.RGBA.parse() override. local parse = Gdk.RGBA.parse function Gdk.RGBA._method.parse(arg1, arg2) if Gdk.RGBA:is_type_of(arg1) then -- Standard member method. return parse(arg1, arg2) else -- Static constructor variant. local rgba = Gdk.RGBA() return parse(rgba, arg1) and rgba or nil end end -- Gdk.Window.destroy() actually consumes 'self'. Prepare workaround -- with override doing ref on input arg first. local destroy = Gdk.Window.destroy local ref = core.callable.new { addr = core.gi.GObject.resolve.g_object_ref, ret = ti.ptr, ti.ptr } function Gdk.Window._method:destroy() ref(self._native) destroy(self) end -- Better integrate Gdk cairo helpers. Gdk.Window._method.cairo_create = Gdk.cairo_create cairo.Region._method.create_from_surface = Gdk.cairo_region_create_from_surface local cairo_set_source_rgba = cairo.Context._method.set_source_rgba function cairo.Context._method:set_source_rgba(...) if select('#', ...) == 1 then return Gdk.cairo_set_source_rgba(self, ...) else return cairo_set_source_rgba(self, ...) end end local cairo_rectangle = cairo.Context._method.rectangle function cairo.Context._method:rectangle(...) if select('#', ...) == 1 then return Gdk.cairo_rectangle(self, ...) else return cairo_rectangle(self, ...) end end for _, name in pairs { 'get_clip_rectangle', 'set_source_color', 'set_source_pixbuf', 'set_source_window', 'region' } do cairo.Context._method[name] = Gdk['cairo_' .. name] end for _, name in pairs { 'clip_rectangle', 'source_color', 'source_pixbuf', 'source_window' } do cairo.Context._attribute[name] = { get = cairo.Context._method['get_' .. name], set = cairo.Context._method['set_' .. name], } end
------------------------------------------------------------------------------ -- -- LGI Gdk3 override module. -- -- Copyright (c) 2011 Pavel Holejsovsky -- Licensed under the MIT license: -- http://www.opensource.org/licenses/mit-license.php -- ------------------------------------------------------------------------------ local select, type, pairs, unpack, rawget = select, type, pairs, unpack, rawget local lgi = require 'lgi' local core = require 'lgi.core' local ffi = require 'lgi.ffi' local ti = ffi.types local Gdk = lgi.Gdk local cairo = lgi.cairo -- Take over internal GDK synchronization lock. core.registerlock(core.gi.Gdk.resolve.gdk_threads_set_lock_functions) Gdk.threads_init() -- Gdk.Rectangle does not exist at all, because it is aliased to -- cairo.RectangleInt. Make sure that we have it exists, because it -- is very commonly used in API documentation. Gdk.Rectangle = lgi.cairo.RectangleInt Gdk.Rectangle._method = rawget(Gdk.Rectangle, '_method') or {} Gdk.Rectangle._method.intersect = Gdk.rectangle_intersect Gdk.Rectangle._method.union = Gdk.rectangle_union -- Declare GdkAtoms which are #define'd in Gdk sources and not -- introspected in gir. local _ = Gdk.KEY_0 for name, val in pairs { SELECTION_PRIMARY = 1, SELECTION_SECONDARY = 2, SELECTION_CLIPBOARD = 69, TARGET_BITMAP = 5, TARGET_COLORMAP = 7, TARGET_DRAWABLE = 17, TARGET_PIXMAP = 20, TARGET_STRING = 31, SELECTION_TYPE_ATOM = 4, SELECTION_TYPE_BITMAP = 5, SELECTION_TYPE_COLORMAP = 7, SELECTION_TYPE_DRAWABLE = 17, SELECTION_TYPE_INTEGER = 19, SELECTION_TYPE_PIXMAP = 20, SELECTION_TYPE_WINDOW = 33, SELECTION_TYPE_STRING = 31, } do Gdk._constant[name] = Gdk.Atom(val) end -- Easier-to-use Gdk.RGBA.parse() override. if Gdk.RGBA then local parse = Gdk.RGBA.parse function Gdk.RGBA._method.parse(arg1, arg2) if Gdk.RGBA:is_type_of(arg1) then -- Standard member method. return parse(arg1, arg2) else -- Static constructor variant. local rgba = Gdk.RGBA() return parse(rgba, arg1) and rgba or nil end end end -- Gdk.Window.destroy() actually consumes 'self'. Prepare workaround -- with override doing ref on input arg first. local destroy = Gdk.Window.destroy local ref = core.callable.new { addr = core.gi.GObject.resolve.g_object_ref, ret = ti.ptr, ti.ptr } function Gdk.Window._method:destroy() ref(self._native) destroy(self) end -- Better integrate Gdk cairo helpers. Gdk.Window._method.cairo_create = Gdk.cairo_create cairo.Region._method.create_from_surface = Gdk.cairo_region_create_from_surface local cairo_set_source_rgba = cairo.Context._method.set_source_rgba function cairo.Context._method:set_source_rgba(...) if select('#', ...) == 1 then return Gdk.cairo_set_source_rgba(self, ...) else return cairo_set_source_rgba(self, ...) end end local cairo_rectangle = cairo.Context._method.rectangle function cairo.Context._method:rectangle(...) if select('#', ...) == 1 then return Gdk.cairo_rectangle(self, ...) else return cairo_rectangle(self, ...) end end for _, name in pairs { 'get_clip_rectangle', 'set_source_color', 'set_source_pixbuf', 'set_source_window', 'region' } do cairo.Context._method[name] = Gdk['cairo_' .. name] end for _, name in pairs { 'clip_rectangle', 'source_color', 'source_pixbuf', 'source_window' } do cairo.Context._attribute[name] = { get = cairo.Context._method['get_' .. name], set = cairo.Context._method['set_' .. name], } end
Fix compatibility with Gtk+ 2.x: Gdk.RGBA is only available in Gtk+ 3.
Fix compatibility with Gtk+ 2.x: Gdk.RGBA is only available in Gtk+ 3.
Lua
mit
psychon/lgi,pavouk/lgi
25380fa5fa074ea74eae10a26299a83149fe485c
lua/entities/sent_deployableballoons.lua
lua/entities/sent_deployableballoons.lua
AddCSLuaFile() DEFINE_BASECLASS( "base_wire_entity" ) ENT.PrintName = "Wire Balloon Deployer" ENT.Author = "LuaPinapple" ENT.Contact = "[email protected]" ENT.Purpose = "It Deploys Balloons." ENT.Instructions = "Use wire." ENT.Category = "Wiremod" ENT.Spawnable = true ENT.AdminOnly = false ENT.WireDebugName = "Balloon Deployer" cleanup.Register("wire_deployers") if CLIENT then language.Add( "Cleanup_wire_deployers", "Balloon Deployers" ) language.Add( "Cleaned_wire_deployers", "Cleaned up Balloon Deployers" ) language.Add( "SBoxLimit_wire_deployers", "You have hit the Balloon Deployers limit!" ) return -- No more client end local material = "cable/rope" local BalloonTypes = { Model("models/MaxOfS2D/balloon_classic.mdl"), Model("models/balloons/balloon_classicheart.mdl"), Model("models/balloons/balloon_dog.mdl"), Model("models/balloons/balloon_star.mdl") } CreateConVar('sbox_maxwire_deployers', 2) local DmgFilter local function CreateDamageFilter() if IsValid(DmgFilter) then return end DmgFilter = ents.Create("filter_activator_name") DmgFilter:SetKeyValue("targetname", "DmgFilter") DmgFilter:SetKeyValue("negated", "1") DmgFilter:Spawn() end hook.Add("InitPostEntity", "CreateDamageFilter", CreateDamageFilter) local function MakeBalloonSpawner(pl, Data) if IsValid(pl) and not pl:CheckLimit("wire_deployers") then return nil end if Data.Model and not WireLib.CanModel(pl, Data.Model, Data.Skin) then return false end local ent = ents.Create("sent_deployableballoons") if not ent:IsValid() then return end duplicator.DoGeneric(ent, Data) ent:SetPlayer(pl) ent:Spawn() ent:Activate() duplicator.DoGenericPhysics(ent, pl, Data) if IsValid(pl) then pl:AddCount("wire_deployers", ent) pl:AddCleanup("wire_deployers", ent) end return ent end hook.Add("Initialize", "DamageFilter", DamageFilter) duplicator.RegisterEntityClass("sent_deployableballoons", MakeBalloonSpawner, "Data") scripted_ents.Alias("gmod_iballoon", "gmod_balloon") --Moves old "Lenght" input to new "Length" input for older dupes WireLib.AddInputAlias( "Lenght", "Length" ) function ENT:SpawnFunction( ply, tr ) if (not tr.Hit) then return end local SpawnPos = tr.HitPos+tr.HitNormal*16 local ent = MakeBalloonSpawner(ply, {Pos=SpawnPos}) return ent end function ENT:Initialize() self:SetModel("models/props_junk/PropaneCanister001a.mdl") self:PhysicsInit(SOLID_VPHYSICS) self:SetMoveType( MOVETYPE_VPHYSICS ) self:SetSolid(SOLID_VPHYSICS) self.Deployed = 0 self.Balloon = nil self.Constraints = {} self.force = 500 self.weld = false self.popable = true self.rl = 64 if WireAddon then self.Inputs = Wire_CreateInputs(self,{ "Force", "Length", "Weld?", "Popable?", "BalloonType", "Deploy" }) self.Outputs=WireLib.CreateSpecialOutputs(self, { "Deployed", "BalloonEntity" }, {"NORMAL","ENTITY" }) Wire_TriggerOutput(self,"Deployed", self.Deployed) --Wire_TriggerOutput(self,"Force", self.force) end local phys = self:GetPhysicsObject() if(phys:IsValid()) then phys:SetMass(250) phys:Wake() end self:UpdateOverlay() end function ENT:TriggerInput(key,value) if (key == "Deploy") then if value ~= 0 then if self.Deployed == 0 then self:DeployBalloons() self.Deployed = 1 end Wire_TriggerOutput(self, "Deployed", self.Deployed) else if self.Deployed ~= 0 then self:RetractBalloons() self.Deployed = 0 end Wire_TriggerOutput(self, "Deployed", self.Deployed) end elseif (key == "Force") then self.force = value if self.Deployed ~= 0 then self.Balloon:SetForce(value) end elseif (key == "Length") then self.rl = value elseif (key == "Weld?") then self.weld = value ~= 0 elseif (key == "Popable?") then self.popable = value ~= 0 self:UpdatePopable() elseif (key == "BalloonType") then self.balloonType=value+1 --To correct for 1 based indexing end self:UpdateOverlay() end local balloon_registry = {} hook.Add("EntityRemoved", "balloon_deployer", function(ent) local deployer = balloon_registry[ent] if IsValid(deployer) and deployer.TriggerInput then deployer.Deployed = 0 deployer:TriggerInput("Deploy", 0) end end) function ENT:UpdatePopable() local balloon = self.Balloon if balloon ~= nil and balloon:IsValid() then if not self.popable then balloon:Fire("setdamagefilter", "DmgFilter", 0); else balloon:Fire("setdamagefilter", "", 0); end end end function ENT:DeployBalloons() local balloon balloon = ents.Create("gmod_balloon") --normal balloon local model = BalloonTypes[self.balloonType] if(model==nil) then model = BalloonTypes[1] end balloon:SetModel(model) balloon:Spawn() balloon:SetColor(Color(math.random(0,255), math.random(0,255), math.random(0,255), 255)) balloon:SetForce(self.force) balloon:SetMaterial("models/balloon/balloon") balloon:SetPlayer(self:GetPlayer()) duplicator.DoGeneric(balloon,{Pos = self:GetPos() + (self:GetUp()*25)}) duplicator.DoGenericPhysics(balloon,pl,{Pos = Pos}) local balloonPos = balloon:GetPos() -- the origin the balloon is at the bottom local hitEntity = self local hitPos = self:LocalToWorld(Vector(0, 0, self:OBBMaxs().z)) -- the top of the spawner -- We trace from the balloon to us, and if there's anything in the way, we -- attach a constraint to that instead - that way, the balloon spawner can -- be hidden underneath a plate which magically gets balloons attached to it. local balloonToSpawner = (hitPos - balloonPos):GetNormalized() * 250 local trace = util.QuickTrace(balloon:GetPos(), balloonToSpawner, balloon) if constraint.CanConstrain(trace.Entity, trace.PhysicsBone) then local phys = trace.Entity:GetPhysicsObjectNum(trace.PhysicsBone) if IsValid(phys) then hitEntity = trace.Entity hitPos = trace.HitPos end end if self.weld then local constraint = constraint.Weld( balloon, hitEntity, 0, trace.PhysicsBone, 0) balloon:DeleteOnRemove(constraint) else balloonPos = balloon:WorldToLocal(balloonPos) hitPos = hitEntity:WorldToLocal(hitPos) local constraint, rope = constraint.Rope( balloon, hitEntity, 0, trace.PhysicsBone, balloonPos, hitPos, 0, self.rl, 0, 1.5, material, false) if constraint then balloon:DeleteOnRemove(constraint) balloon:DeleteOnRemove(rope) end end self:DeleteOnRemove(balloon) self.Balloon = balloon self:UpdatePopable() balloon_registry[balloon] = self Wire_TriggerOutput(self, "BalloonEntity", self.Balloon) end function ENT:OnRemove() if self.Balloon then balloon_registry[self.Balloon] = nil end Wire_Remove(self) end function ENT:RetractBalloons() if self.Balloon:IsValid() then local c = self.Balloon:GetColor() local effectdata = EffectData() effectdata:SetOrigin( self.Balloon:GetPos() ) effectdata:SetStart( Vector(c.r,c.g,c.b) ) util.Effect( "balloon_pop", effectdata ) self.Balloon:Remove() else self.Balloon = nil end end function ENT:UpdateOverlay() self:SetOverlayText( "Deployed = " .. ((self.Deployed ~= 0) and "yes" or "no") ) end
AddCSLuaFile() DEFINE_BASECLASS( "base_wire_entity" ) ENT.PrintName = "Wire Balloon Deployer" ENT.Author = "LuaPinapple" ENT.Contact = "[email protected]" ENT.Purpose = "It Deploys Balloons." ENT.Instructions = "Use wire." ENT.Category = "Wiremod" ENT.Spawnable = true ENT.AdminOnly = false ENT.WireDebugName = "Balloon Deployer" cleanup.Register("wire_deployers") if CLIENT then language.Add( "Cleanup_wire_deployers", "Balloon Deployers" ) language.Add( "Cleaned_wire_deployers", "Cleaned up Balloon Deployers" ) language.Add( "SBoxLimit_wire_deployers", "You have hit the Balloon Deployers limit!" ) return -- No more client end local material = "cable/rope" local BalloonTypes = { Model("models/MaxOfS2D/balloon_classic.mdl"), Model("models/balloons/balloon_classicheart.mdl"), Model("models/balloons/balloon_dog.mdl"), Model("models/balloons/balloon_star.mdl") } CreateConVar('sbox_maxwire_deployers', 2) local DmgFilter local function CreateDamageFilter() if IsValid(DmgFilter) then return end DmgFilter = ents.Create("filter_activator_name") DmgFilter:SetKeyValue("targetname", "DmgFilter") DmgFilter:SetKeyValue("negated", "1") DmgFilter:Spawn() end hook.Add("InitPostEntity", "CreateDamageFilter", CreateDamageFilter) local function MakeBalloonSpawner(pl, Data) if IsValid(pl) and not pl:CheckLimit("wire_deployers") then return nil end if Data.Model and not WireLib.CanModel(pl, Data.Model, Data.Skin) then return false end local ent = ents.Create("sent_deployableballoons") if not ent:IsValid() then return end duplicator.DoGeneric(ent, Data) ent:SetPlayer(pl) ent:Spawn() ent:Activate() duplicator.DoGenericPhysics(ent, pl, Data) if IsValid(pl) then pl:AddCount("wire_deployers", ent) pl:AddCleanup("wire_deployers", ent) end return ent end duplicator.RegisterEntityClass("sent_deployableballoons", MakeBalloonSpawner, "Data") scripted_ents.Alias("gmod_iballoon", "gmod_balloon") --Moves old "Lenght" input to new "Length" input for older dupes WireLib.AddInputAlias( "Lenght", "Length" ) function ENT:SpawnFunction( ply, tr ) if (not tr.Hit) then return end local SpawnPos = tr.HitPos+tr.HitNormal*16 local ent = MakeBalloonSpawner(ply, {Pos=SpawnPos}) return ent end function ENT:Initialize() self:SetModel("models/props_junk/PropaneCanister001a.mdl") self:PhysicsInit(SOLID_VPHYSICS) self:SetMoveType( MOVETYPE_VPHYSICS ) self:SetSolid(SOLID_VPHYSICS) self.Deployed = 0 self.Balloon = nil self.Constraints = {} self.force = 500 self.weld = false self.popable = true self.rl = 64 if WireAddon then self.Inputs = Wire_CreateInputs(self,{ "Force", "Length", "Weld?", "Popable?", "BalloonType", "Deploy" }) self.Outputs=WireLib.CreateSpecialOutputs(self, { "Deployed", "BalloonEntity" }, {"NORMAL","ENTITY" }) Wire_TriggerOutput(self,"Deployed", self.Deployed) --Wire_TriggerOutput(self,"Force", self.force) end local phys = self:GetPhysicsObject() if(phys:IsValid()) then phys:SetMass(250) phys:Wake() end self:UpdateOverlay() end function ENT:TriggerInput(key,value) if (key == "Deploy") then if value ~= 0 then if self.Deployed == 0 then self:DeployBalloons() self.Deployed = 1 end Wire_TriggerOutput(self, "Deployed", self.Deployed) else if self.Deployed ~= 0 then self:RetractBalloons() self.Deployed = 0 end Wire_TriggerOutput(self, "Deployed", self.Deployed) end elseif (key == "Force") then self.force = value if self.Deployed ~= 0 then self.Balloon:SetForce(value) end elseif (key == "Length") then self.rl = value elseif (key == "Weld?") then self.weld = value ~= 0 elseif (key == "Popable?") then self.popable = value ~= 0 self:UpdatePopable() elseif (key == "BalloonType") then self.balloonType=value+1 --To correct for 1 based indexing end self:UpdateOverlay() end local balloon_registry = {} hook.Add("EntityRemoved", "balloon_deployer", function(ent) local deployer = balloon_registry[ent] if IsValid(deployer) and deployer.TriggerInput then deployer.Deployed = 0 deployer:TriggerInput("Deploy", 0) end end) function ENT:UpdatePopable() local balloon = self.Balloon if balloon ~= nil and balloon:IsValid() then if not self.popable then balloon:Fire("setdamagefilter", "DmgFilter", 0); else balloon:Fire("setdamagefilter", "", 0); end end end function ENT:DeployBalloons() local balloon balloon = ents.Create("gmod_balloon") --normal balloon local model = BalloonTypes[self.balloonType] if(model==nil) then model = BalloonTypes[1] end balloon:SetModel(model) balloon:Spawn() balloon:SetColor(Color(math.random(0,255), math.random(0,255), math.random(0,255), 255)) balloon:SetForce(self.force) balloon:SetMaterial("models/balloon/balloon") balloon:SetPlayer(self:GetPlayer()) duplicator.DoGeneric(balloon,{Pos = self:GetPos() + (self:GetUp()*25)}) duplicator.DoGenericPhysics(balloon,pl,{Pos = Pos}) local balloonPos = balloon:GetPos() -- the origin the balloon is at the bottom local hitEntity = self local hitPos = self:LocalToWorld(Vector(0, 0, self:OBBMaxs().z)) -- the top of the spawner -- We trace from the balloon to us, and if there's anything in the way, we -- attach a constraint to that instead - that way, the balloon spawner can -- be hidden underneath a plate which magically gets balloons attached to it. local balloonToSpawner = (hitPos - balloonPos):GetNormalized() * 250 local trace = util.QuickTrace(balloon:GetPos(), balloonToSpawner, balloon) if constraint.CanConstrain(trace.Entity, trace.PhysicsBone) then local phys = trace.Entity:GetPhysicsObjectNum(trace.PhysicsBone) if IsValid(phys) then hitEntity = trace.Entity hitPos = trace.HitPos end end if self.weld then local constraint = constraint.Weld( balloon, hitEntity, 0, trace.PhysicsBone, 0) balloon:DeleteOnRemove(constraint) else balloonPos = balloon:WorldToLocal(balloonPos) hitPos = hitEntity:WorldToLocal(hitPos) local constraint, rope = constraint.Rope( balloon, hitEntity, 0, trace.PhysicsBone, balloonPos, hitPos, 0, self.rl, 0, 1.5, material, false) if constraint then balloon:DeleteOnRemove(constraint) balloon:DeleteOnRemove(rope) end end self:DeleteOnRemove(balloon) self.Balloon = balloon self:UpdatePopable() balloon_registry[balloon] = self Wire_TriggerOutput(self, "BalloonEntity", self.Balloon) end function ENT:OnRemove() if self.Balloon then balloon_registry[self.Balloon] = nil end Wire_Remove(self) end function ENT:RetractBalloons() if self.Balloon:IsValid() then local c = self.Balloon:GetColor() local effectdata = EffectData() effectdata:SetOrigin( self.Balloon:GetPos() ) effectdata:SetStart( Vector(c.r,c.g,c.b) ) util.Effect( "balloon_pop", effectdata ) self.Balloon:Remove() else self.Balloon = nil end end function ENT:UpdateOverlay() self:SetOverlayText( "Deployed = " .. ((self.Deployed ~= 0) and "yes" or "no") ) end
Balloon Deployer: remove unused Initialize hook Fixes #1511
Balloon Deployer: remove unused Initialize hook Fixes #1511
Lua
apache-2.0
wiremod/wire,NezzKryptic/Wire,Grocel/wire,garrysmodlua/wire,sammyt291/wire,thegrb93/wire,dvdvideo1234/wire,bigdogmat/wire
b7de920f94f6549da8f853573a667f8e2343dd6e
lib/pkg/protobuf.lua
lib/pkg/protobuf.lua
return { source = { type = 'git', location = 'https://github.com/google/protobuf.git', -- "stable" version, newer have problems with cross-compiling branch = '3.1.x' }, build = { type = 'GNU', generate = true, target_requires_host = true, options = { '--disable-maintainer-mode', '--disable-64bit-solaris', '--enable-shared', '--enable-static', '--without-zlib', } }, requires = { { 'unzip', 'system' }, }, configs = { target = { build = { options = { '--with-protoc=$jagen_host_dir/bin/protoc' } } } } }
return { source = { type = 'git', location = 'https://github.com/bazurbat/protobuf.git', branch = '3.5.x', exclude_submodules = true, }, build = { type = 'GNU', generate = true, target_requires_host = true, options = { '--disable-maintainer-mode', '--disable-64bit-solaris', '--enable-shared', '--enable-static', '--without-zlib', } }, requires = { { 'unzip', 'system' }, }, configs = { target = { build = { options = { '--disable-maintainer-mode', '--disable-64bit-solaris', '--enable-shared', '--enable-static', '--without-zlib', '--with-protoc=$jagen_host_dir/bin/protoc' } } } } }
Bump protobuf to 3.5.x, target build fixes
Bump protobuf to 3.5.x, target build fixes
Lua
mit
bazurbat/jagen
37f5a4350fcbec19975dea687e5741b3e29c3950
src/reactor/propTypes/tableShape.lua
src/reactor/propTypes/tableShape.lua
local getPrintableValue = require('reactor.helpers.getPrintableValue') local function getIncorrectKeyCountFailureReason(keyCount) return 'Failed to validate prop as tableShape, ' .. 'expected table to have ' .. keyCount .. 'properties' end local function getKeyMismatchFailureReason(expectedKey) return 'Failed to validate prop as tableShape, ' .. 'expected table to contain key: ' .. getPrintableValue(expectedKey) end local function getPropertyValidationFailureReason(key, reason) return 'Failed to validate prop as tableShape, ' .. 'property validation failed for key: ' .. getPrintableValue(key) .. '. Validation error: ' .. getPrintableValue(reason) end local function isTableType(toValidate) local isValid = type(toValidate) == 'table' local reason = nil if not isValid then reason = 'failed to validate prop as tableShape, ' .. 'expected table, but saw value of type ' .. type(toValidate) end return isValid, reason end local function getTableKeys(tableWithKeys) local keys = {} for key in pairs(tableWithKeys) do keys[#keys + 1] = key end table.sort(keys) return keys end local function hasAllKeys(toValidate, shapeDescription) local isValid = true local reason = nil local descritionKeys = getTableKeys(shapeDescription) local keysToValidate = getTableKeys(toValidate) isValid = #descritionKeys == #keysToValidate if not isValid then return isValid, getIncorrectKeyCountFailureReason(#descritionKeys) end for index, expectedKey in ipairs(descritionKeys) do local keyToValidate = keysToValidate[index] isValid = expectedKey == keyToValidate if not isValid then -- todo: this probably doesn't always return the right key! fix it return isValid, getKeyMismatchFailureReason(expectedKey) end end return true end local function hasValidProperties(toValidate, shapeDescription) for key, validator in pairs(shapeDescription) do -- todo: check that validator is function -- or use pcall to catch runtime errors local propertyToValidate = toValidate[key] local isValid, reason = validator(propertyToValidate) if not isValid then return isValid, getPropertyValidationFailureReason(key, reason) end end return true end local function tableShape(shapeDescription) assert(type(shapeDescription) == 'table', 'tableShape validator expected shapeDescription to be expressed as a table') return function(toValidate) local isValid = true local reason = nil isValid, reason = isTableType(toValidate) if not isValid then return isValid, reason end isValid, reason = hasAllKeys(toValidate, shapeDescription) if not isValid then return isValid, reason end isValid, reason = hasValidProperties(toValidate, shapeDescription) if not isValid then return isValid, reason end return isValid end end return tableShape
local getPrintableValue = require('reactor.helpers.getPrintableValue') local function getIncorrectKeyCountFailureReason(keyCount) return 'Failed to validate prop as tableShape, ' .. 'expected table to have ' .. keyCount .. 'properties' end local function getKeyMismatchFailureReason(expectedKey) return 'Failed to validate prop as tableShape, ' .. 'expected table to contain key: ' .. getPrintableValue(expectedKey) end local function getPropertyValidationFailureReason(key, reason) return 'Failed to validate prop as tableShape, ' .. 'property validation failed for key: ' .. getPrintableValue(key) .. '. Validation error: ' .. getPrintableValue(reason) end local function isTableType(toValidate) local isValid = type(toValidate) == 'table' local reason = nil if not isValid then reason = 'failed to validate prop as tableShape, ' .. 'expected table, but saw value of type ' .. type(toValidate) end return isValid, reason end local function getTableKeys(tableWithKeys) local keys = {} for key in pairs(tableWithKeys) do keys[#keys + 1] = key end table.sort(keys) return keys end local function hasAllKeys(toValidate, shapeDescription) local descritionKeys = getTableKeys(shapeDescription) local keysToValidate = getTableKeys(toValidate) local isValid = #descritionKeys == #keysToValidate if not isValid then return isValid, getIncorrectKeyCountFailureReason(#descritionKeys) end for index, expectedKey in ipairs(descritionKeys) do local keyToValidate = keysToValidate[index] isValid = expectedKey == keyToValidate if not isValid then -- todo: this probably doesn't always return the right key! fix it return isValid, getKeyMismatchFailureReason(expectedKey) end end return true end local function hasValidProperties(toValidate, shapeDescription) for key, validator in pairs(shapeDescription) do -- todo: check that validator is function -- or use pcall to catch runtime errors local propertyToValidate = toValidate[key] local isValid, reason = validator(propertyToValidate) if not isValid then return isValid, getPropertyValidationFailureReason(key, reason) end end return true end local function tableShape(shapeDescription) assert(type(shapeDescription) == 'table', 'tableShape validator expected shapeDescription to be expressed as a table') return function(toValidate) local isValid, reason = isTableType(toValidate) if not isValid then return isValid, reason end isValid, reason = hasAllKeys(toValidate, shapeDescription) if not isValid then return isValid, reason end isValid, reason = hasValidProperties(toValidate, shapeDescription) if not isValid then return isValid, reason end return isValid end end return tableShape
fix linting errors in tableShape proptype
fix linting errors in tableShape proptype
Lua
mit
talldan/lua-reactor
c52e70c594c3ed66a8f7f15c9440398f31009a13
src/copas/semaphore.lua
src/copas/semaphore.lua
local copas = require("copas") local DEFAULT_TIMEOUT = 10 local semaphore = {} semaphore.__index = semaphore -- registry, semaphore indexed by the coroutines using them. local registry = setmetatable({}, { __mode="kv" }) -- create a new semaphore -- @param max maximum number of resources the semaphore can hold (this maximum does NOT include resources that have been given but not yet returned). -- @param seconds (optional, default 10) default semaphore timeout in seconds -- @param start (optional, default 0) the initial resources available function semaphore.new(max, start, seconds) local timeout = tonumber(seconds or DEFAULT_TIMEOUT) or -1 if timeout < 0 then error("expected timeout (2nd argument) to be a number greater than or equal to 0, got: " .. tostring(seconds), 2) end if max < 1 then error("expected max resources (1st argument) to be a number greater than 0, got: " .. tostring(max), 2) end local self = setmetatable({ count = start or 0, max = max, timeout = timeout, q_tip = 1, -- position of next entry waiting q_tail = 1, -- position where next one will be inserted queue = {}, to_flags = setmetatable({}, { __mode = "k" }), -- timeout flags indexed by coroutine }, semaphore) return self end do local destroyed_func = function() return nil, "destroyed" end local destroyed_semaphore_mt = { __index = function() return destroyed_func end } -- destroy a semaphore. -- Releases all waiting threads with `nil+"destroyed"` function semaphore:destroy() self:give(math.huge) self.destroyed = true setmetatable(self, destroyed_semaphore_mt) return true end end -- Gives resources. -- @param given (optional, default 1) number of resources to return. If more -- than the maximum are returned then it will be capped at the maximum and -- error "too many" will be returned. function semaphore:give(given) local err given = given or 1 local count = self.count + given --print("now at",count, ", after +"..given) if count > self.max then count = self.max err = "too many" end while self.q_tip < self.q_tail do local i = self.q_tip local nxt = self.queue[i] -- there can be holes, so nxt might be nil if not nxt then self.q_tip = i + 1 else if count >= nxt.requested then -- release it self.queue[i] = nil self.to_flags[nxt.co] = nil count = count - nxt.requested self.q_tip = i + 1 copas.wakeup(nxt.co) else break -- we ran out of resources end end end if self.q_tip == self.q_tail then -- reset queue pointers if empty self.q_tip = 1 self.q_tail = 1 end self.count = count if err then return nil, err end return true end local function timeout_handler(co) local self = registry[co] --print("checking timeout ", co) for i = self.q_tip, self.q_tail do local item = self.queue[i] if item and co == item.co then self.queue[i] = nil self.to_flags[co] = true --print("marked timeout ", co) copas.wakeup(co) return end end -- nothing to do here... end -- Requests resources from the semaphore. -- Waits if there are not enough resources available before returning. -- @param requested (optional, default 1) the number of resources requested -- @param timeout (optional, defaults to semaphore timeout) timeout in -- seconds. If 0 it will either succeed or return immediately with error "timeout" -- @return true, or nil+"destroyed" function semaphore:take(requested, timeout) requested = requested or 1 if self.q_tail == 1 and self.count >= requested then -- nobody is waiting before us, and there is enough in store self.count = self.count - requested return true end if requested > self.max then return nil, "too many" end local to = timeout or self.timeout if to == 0 then return nil, "timeout" end -- get in line local co = coroutine.running() self.to_flags[co] = nil registry[co] = self copas.timeout(to, timeout_handler) self.queue[self.q_tail] = { co = co, requested = requested, --timeout = nil, -- flag indicating timeout } self.q_tail = self.q_tail + 1 copas.sleep(-1) -- block until woken if self.to_flags[co] then -- a timeout happened self.to_flags[co] = nil return nil, "timeout" elseif self.destroyed then return nil, "destroyed" end copas.timeout(0) return true end -- returns current available resources function semaphore:get_count() return self.count end -- returns total shortage for requested resources function semaphore:get_wait() local wait = 0 for i = self.q_tip, self.q_tail - 1 do wait = wait + ((self.queue[i] or {}).requested or 0) end return wait - self.count end return semaphore
local copas = require("copas") local DEFAULT_TIMEOUT = 10 local semaphore = {} semaphore.__index = semaphore -- registry, semaphore indexed by the coroutines using them. local registry = setmetatable({}, { __mode="kv" }) -- create a new semaphore -- @param max maximum number of resources the semaphore can hold (this maximum does NOT include resources that have been given but not yet returned). -- @param seconds (optional, default 10) default semaphore timeout in seconds -- @param start (optional, default 0) the initial resources available function semaphore.new(max, start, seconds) local timeout = tonumber(seconds or DEFAULT_TIMEOUT) or -1 if timeout < 0 then error("expected timeout (2nd argument) to be a number greater than or equal to 0, got: " .. tostring(seconds), 2) end if type(max) ~= "number" or max < 1 then error("expected max resources (1st argument) to be a number greater than 0, got: " .. tostring(max), 2) end local self = setmetatable({ count = start or 0, max = max, timeout = timeout, q_tip = 1, -- position of next entry waiting q_tail = 1, -- position where next one will be inserted queue = {}, to_flags = setmetatable({}, { __mode = "k" }), -- timeout flags indexed by coroutine }, semaphore) return self end do local destroyed_func = function() return nil, "destroyed" end local destroyed_semaphore_mt = { __index = function() return destroyed_func end } -- destroy a semaphore. -- Releases all waiting threads with `nil+"destroyed"` function semaphore:destroy() self:give(math.huge) self.destroyed = true setmetatable(self, destroyed_semaphore_mt) return true end end -- Gives resources. -- @param given (optional, default 1) number of resources to return. If more -- than the maximum are returned then it will be capped at the maximum and -- error "too many" will be returned. function semaphore:give(given) local err given = given or 1 local count = self.count + given --print("now at",count, ", after +"..given) if count > self.max then count = self.max err = "too many" end while self.q_tip < self.q_tail do local i = self.q_tip local nxt = self.queue[i] -- there can be holes, so nxt might be nil if not nxt then self.q_tip = i + 1 else if count >= nxt.requested then -- release it self.queue[i] = nil self.to_flags[nxt.co] = nil count = count - nxt.requested self.q_tip = i + 1 copas.wakeup(nxt.co) else break -- we ran out of resources end end end if self.q_tip == self.q_tail then -- reset queue pointers if empty self.q_tip = 1 self.q_tail = 1 end self.count = count if err then return nil, err end return true end local function timeout_handler(co) local self = registry[co] --print("checking timeout ", co) for i = self.q_tip, self.q_tail do -- TODO: fix error below -- ....3.2/1.19.3.2/luarocks/share/lua/5.1/copas/semaphore.lua:113: attempt to index local 'self' (a nil value) (coroutine: nil, socket: nil) -- stack traceback: -- ....3.2/1.19.3.2/luarocks/share/lua/5.1/copas/semaphore.lua:113: in function <....3.2/1.19.3.2/luarocks/share/lua/5.1/copas/semaphore.lua:109> -- [C]: in function 'xpcall' -- ....3.2/1.19.3.2/luarocks/share/lua/5.1/timerwheel/init.lua:136: in function 'step' -- [email protected]/1.19.3.2/luarocks/share/lua/5.1/copas.lua:1103: in function <[email protected]/1.19.3.2/luarocks/share/lua/5.1/copas.lua:1100> local item = self.queue[i] if item and co == item.co then self.queue[i] = nil self.to_flags[co] = true --print("marked timeout ", co) copas.wakeup(co) return end end -- nothing to do here... end -- Requests resources from the semaphore. -- Waits if there are not enough resources available before returning. -- @param requested (optional, default 1) the number of resources requested -- @param timeout (optional, defaults to semaphore timeout) timeout in -- seconds. If 0 it will either succeed or return immediately with error "timeout" -- @return true, or nil+"destroyed" function semaphore:take(requested, timeout) requested = requested or 1 if self.q_tail == 1 and self.count >= requested then -- nobody is waiting before us, and there is enough in store self.count = self.count - requested return true end if requested > self.max then return nil, "too many" end local to = timeout or self.timeout if to == 0 then return nil, "timeout" end -- get in line local co = coroutine.running() self.to_flags[co] = nil registry[co] = self copas.timeout(to, timeout_handler) self.queue[self.q_tail] = { co = co, requested = requested, --timeout = nil, -- flag indicating timeout } self.q_tail = self.q_tail + 1 copas.sleep(-1) -- block until woken if self.to_flags[co] then -- a timeout happened self.to_flags[co] = nil return nil, "timeout" elseif self.destroyed then return nil, "destroyed" end copas.timeout(0) return true end -- returns current available resources function semaphore:get_count() return self.count end -- returns total shortage for requested resources function semaphore:get_wait() local wait = 0 for i = self.q_tip, self.q_tail - 1 do wait = wait + ((self.queue[i] or {}).requested or 0) end return wait - self.count end return semaphore
fix(semaphore) better check on arguments
fix(semaphore) better check on arguments
Lua
mit
keplerproject/copas
675c414b59d78a79bb64e541c2be8187a0671c13
src/lunajson/decode.lua
src/lunajson/decode.lua
local floor = math.floor local pow = math.pow local byte = string.byte local char = string.char local find = string.find local gsub = string.gsub local len = string.len local match = string.match local sub = string.sub local concat = table.concat local tonumber = tonumber local band, bor, rshift if _VERSION == 'Lua 5.2' then band = bit32.band rshift = bit32.rshift elseif type(bit) == 'table' then band = bit.band rshift = bit.rshift else band = function(v, mask) -- mask must be 2^n-1 return v % (mask+1) end rshift = function(v, len) return floor(v / pow(2, len)) end end local function decode(json, pos, nullv) local jsonlen = len(json) local dodecode -- helper local function decodeerror(errmsg) error("parse error at " .. pos .. ": " .. errmsg) end -- parse constants local function f_nul() local str = sub(json, pos, pos+2) if str == 'ull' then pos = pos+3 return nullv end decodeerror('invalid value') end local function f_fls() local str = sub(json, pos, pos+3) if str == 'alse' then pos = pos+4 return false end decodeerror('invalid value') end local function f_tru() local str = sub(json, pos, pos+2) if str == 'rue' then pos = pos+3 return true end decodeerror('invalid value') end -- parse numbers local radixmark = match(tostring(0.5), '[^0-9]') local fixedtonumber = tonumber if radixmark ~= '.' then if find(radixmark, '%W') then radixmark = '%' .. radixmark end fixedtonumber = function(s) return tonumber(gsub(s, radixmark, '')) end end local function f_zro(mns, newpos) newpos = newpos or pos if byte(json, newpos) == 0x2E then _, newpos = find(json, '^[0-9]+', newpos+1) if not newpos then return decodeerror('invalid number') end newpos = newpos+1 end local expc = byte(json, newpos) if expc == 0x45 or expc == 0x65 then -- e or E? _, newpos = find(json, '^[+-]?[0-9]+', newpos+1) if not newpos then return decodeerror('invalid number') end newpos = newpos+1 end local num = fixedtonumber(sub(json, pos-1, newpos-1)) if mns then num = -num end pos = newpos return num end local function f_num(mns) local newpos = pos _, newpos = find(json, '^[0-9]*', newpos) newpos = newpos+1 return f_zro(mns, newpos) end local function f_mns() local c = byte(json, pos) if c then pos = pos+1 if c > 0x30 then if c < 0x3A then return f_num(true) end else if c > 0x2F then return f_zro(true) end end end decodeerror('invalid number') end -- parse strings local f_str_surrogateprev local function f_str_subst(ch, rest) local u8 if ch == 'u' then local l = len(rest) if l >= 4 then local ucode = tonumber(sub(rest, 1, 4), 16) rest = sub(rest, 5, l) if ucode < 0x80 then -- 1byte u8 = char(ucode) elseif ucode < 0x800 then -- 2byte u8 = char(0xC0 + rshift(ucode, 6), 0x80 + band(ucode, 0x3F)) elseif ucode < 0xD800 or 0xE000 <= ucode then -- 3byte u8 = char(0xE0 + rshift(ucode, 12), 0x80 + band(rshift(ucode, 6), 0x3F), 0x80 + band(ucode, 0x3F)) elseif 0xD800 <= ucode and ucode < 0xDC00 then -- surrogate pair 1st if f_str_surrogateprev == 0 then f_str_surrogateprev = ucode if l == 4 then return '' end end else -- surrogate pair 2nd if f_str_surrogateprev == 0 then f_str_surrogateprev = 1 else ucode = 0x10000 + (f_str_surrogateprev - 0xD800) * 0x400 + (ucode - 0xDC00) f_str_surrogateprev = 0 u8 = char(0xF0 + rshift(ucode, 18), 0x80 + band(rshift(ucode, 12), 0x3F), 0x80 + band(rshift(ucode, 6), 0x3F), 0x80 + band(ucode, 0x3F)) end end end end if f_str_surrogateprev ~= 0 then decodeerror("invalid surrogate pair") end local tbl = { ['"'] = '"', ['\\'] = '\\', ['/'] = '/', ['b'] = '\b', ['f'] = '\f', ['n'] = '\n', ['r'] = '\r', ['t'] = '\t' } return (u8 or tbl[ch] or decodeerror("invalid escape sequence")) .. rest end local function f_str() local newpos = pos-2 local pos2 repeat pos2 = newpos+2 newpos = find(json, '[\\"]', pos2) if not newpos then decodeerror("unterminated string") end until byte(json, newpos) == 0x22 local str = sub(json, pos, newpos-1) pos = newpos+1 if pos2 ~= pos then f_str_surrogateprev = 0 str = gsub(str, '\\(.)([^\\]*)', f_str_subst) end return str end -- parse arrays local function f_ary() local ary = {} local i = 0 _, pos = find(json, '^[ \n\r\t]*', pos) pos = pos+1 if byte(json, pos) ~= 0x5D then local newpos = pos-1 repeat i = i+1 pos = newpos+1 ary[i] = dodecode() _, newpos = find(json, '^[ \n\r\t]*,[ \n\r\t]*', pos) until not newpos _, newpos = find(json, '^[ \n\r\t]*%]', pos) if not newpos then return decodeerror("no closing bracket of an array") end pos = newpos end pos = pos+1 return ary end -- parse objects local function f_obj() local obj = {} _, pos = find(json, '^[ \n\r\t]*', pos) pos = pos+1 if byte(json, pos) ~= 0x7D then local newpos = pos-1 repeat pos = newpos+1 if byte(json, pos) ~= 0x22 then return decodeerror("not key") end pos = pos+1 local key = f_str() _, newpos = find(json, '^[ \n\r\t]*:[ \n\r\t]*', pos) if not newpos then return decodeerror("no colon after a key") end pos = newpos+1 obj[key] = dodecode() _, newpos = find(json, '^[ \n\r\t]*,[ \n\r\t]*', pos) until not newpos _, newpos = find(json, '^[ \n\r\t]*}', pos) if not newpos then return decodeerror("no closing bracket of an object") end pos = newpos end pos = pos+1 return obj end local dispatcher = { false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, f_str, false, false, false, false, false, false, false, false, false, false, f_mns, false, false, f_num, f_num, f_num, f_num, f_num, f_num, f_num, f_num, f_num, f_num, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, f_ary, false, false, false, false, false, false, false, false, false, false, f_fls, false, false, false, false, false, false, false, f_nul, false, false, false, false, false, f_tru, false, false, false, false, false, false, f_obj, false, false, false, false, } function dodecode() local c = byte(json, pos) if not c then decodeerror("unexpected termination") end local f = dispatcher[c+1] if not f then decodeerror("invalid value") end pos = pos+1 return f() end _, pos = find(json, '^[ \n\r\t]*', pos) pos = pos+1 local v = dodecode() return v, pos end return decode
local floor = math.floor local pow = math.pow local byte = string.byte local char = string.char local find = string.find local gsub = string.gsub local len = string.len local match = string.match local sub = string.sub local concat = table.concat local tonumber = tonumber local band, bor, rshift if _VERSION == 'Lua 5.2' then band = bit32.band rshift = bit32.rshift elseif type(bit) == 'table' then band = bit.band rshift = bit.rshift else band = function(v, mask) -- mask must be 2^n-1 return v % (mask+1) end rshift = function(v, len) return floor(v / pow(2, len)) end end local function decode(json, pos, nullv) local jsonlen = len(json) local dodecode -- helper local function decodeerror(errmsg) error("parse error at " .. pos .. ": " .. errmsg) end -- parse constants local function f_nul() local str = sub(json, pos, pos+2) if str == 'ull' then pos = pos+3 return nullv end decodeerror('invalid value') end local function f_fls() local str = sub(json, pos, pos+3) if str == 'alse' then pos = pos+4 return false end decodeerror('invalid value') end local function f_tru() local str = sub(json, pos, pos+2) if str == 'rue' then pos = pos+3 return true end decodeerror('invalid value') end -- parse numbers local radixmark = match(tostring(0.5), '[^0-9]') local fixedtonumber = tonumber if radixmark ~= '.' then if find(radixmark, '%W') then radixmark = '%' .. radixmark end fixedtonumber = function(s) return tonumber(gsub(s, radixmark, '')) end end local function f_zro(mns, newpos) newpos = newpos or pos if byte(json, newpos) == 0x2E then _, newpos = find(json, '^[0-9]+', newpos+1) if not newpos then return decodeerror('invalid number') end newpos = newpos+1 end local expc = byte(json, newpos) if expc == 0x45 or expc == 0x65 then -- e or E? _, newpos = find(json, '^[+-]?[0-9]+', newpos+1) if not newpos then return decodeerror('invalid number') end newpos = newpos+1 end local num = fixedtonumber(sub(json, pos-1, newpos-1)) if mns then num = -num end pos = newpos return num end local function f_num(mns) local newpos = pos _, newpos = find(json, '^[0-9]*', newpos) newpos = newpos+1 return f_zro(mns, newpos) end local function f_mns() local c = byte(json, pos) if c then pos = pos+1 if c > 0x30 then if c < 0x3A then return f_num(true) end else if c > 0x2F then return f_zro(true) end end end decodeerror('invalid number') end -- parse strings local f_str_surrogateprev local function f_str_subst(ch, rest) local u8 if ch == 'u' then local l = len(rest) if l >= 4 then local ucode = tonumber(sub(rest, 1, 4), 16) rest = sub(rest, 5, l) if ucode < 0x80 then -- 1byte u8 = char(ucode) elseif ucode < 0x800 then -- 2byte u8 = char(0xC0 + rshift(ucode, 6), 0x80 + band(ucode, 0x3F)) elseif ucode < 0xD800 or 0xE000 <= ucode then -- 3byte u8 = char(0xE0 + rshift(ucode, 12), 0x80 + band(rshift(ucode, 6), 0x3F), 0x80 + band(ucode, 0x3F)) elseif 0xD800 <= ucode and ucode < 0xDC00 then -- surrogate pair 1st if f_str_surrogateprev == 0 then f_str_surrogateprev = ucode if l == 4 then return '' end end else -- surrogate pair 2nd if f_str_surrogateprev == 0 then f_str_surrogateprev = 1 else ucode = 0x10000 + (f_str_surrogateprev - 0xD800) * 0x400 + (ucode - 0xDC00) f_str_surrogateprev = 0 u8 = char(0xF0 + rshift(ucode, 18), 0x80 + band(rshift(ucode, 12), 0x3F), 0x80 + band(rshift(ucode, 6), 0x3F), 0x80 + band(ucode, 0x3F)) end end end end if f_str_surrogateprev ~= 0 then decodeerror("invalid surrogate pair") end local tbl = { ['"'] = '"', ['\\'] = '\\', ['/'] = '/', ['b'] = '\b', ['f'] = '\f', ['n'] = '\n', ['r'] = '\r', ['t'] = '\t' } return (u8 or tbl[ch] or decodeerror("invalid escape sequence")) .. rest end local function f_str() local newpos = pos-2 local pos2 repeat pos2 = newpos+2 newpos = find(json, '[\\"]', pos2) if not newpos then decodeerror("unterminated string") end until byte(json, newpos) == 0x22 local str = sub(json, pos, newpos-1) if pos2 ~= pos then f_str_surrogateprev = 0 str = gsub(str, '\\(.)([^\\]*)', f_str_subst) end pos = newpos+1 return str end -- parse arrays local function f_ary() local ary = {} local i = 0 _, pos = find(json, '^[ \n\r\t]*', pos) pos = pos+1 if byte(json, pos) ~= 0x5D then local newpos = pos-1 repeat i = i+1 pos = newpos+1 ary[i] = dodecode() _, newpos = find(json, '^[ \n\r\t]*,[ \n\r\t]*', pos) until not newpos _, newpos = find(json, '^[ \n\r\t]*%]', pos) if not newpos then return decodeerror("no closing bracket of an array") end pos = newpos end pos = pos+1 return ary end -- parse objects local function f_obj() local obj = {} _, pos = find(json, '^[ \n\r\t]*', pos) pos = pos+1 if byte(json, pos) ~= 0x7D then local newpos = pos-1 repeat pos = newpos+1 if byte(json, pos) ~= 0x22 then return decodeerror("not key") end pos = pos+1 local key = f_str() _, newpos = find(json, '^[ \n\r\t]*:[ \n\r\t]*', pos) if not newpos then return decodeerror("no colon after a key") end pos = newpos+1 obj[key] = dodecode() _, newpos = find(json, '^[ \n\r\t]*,[ \n\r\t]*', pos) until not newpos _, newpos = find(json, '^[ \n\r\t]*}', pos) if not newpos then return decodeerror("no closing bracket of an object") end pos = newpos end pos = pos+1 return obj end local dispatcher = { false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, f_str, false, false, false, false, false, false, false, false, false, false, f_mns, false, false, f_num, f_num, f_num, f_num, f_num, f_num, f_num, f_num, f_num, f_num, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, f_ary, false, false, false, false, false, false, false, false, false, false, f_fls, false, false, false, false, false, false, false, f_nul, false, false, false, false, false, f_tru, false, false, false, false, false, false, f_obj, false, false, false, false, } function dodecode() local c = byte(json, pos) if not c then decodeerror("unexpected termination") end local f = dispatcher[c+1] if not f then decodeerror("invalid value") end pos = pos+1 return f() end _, pos = find(json, '^[ \n\r\t]*', pos) pos = pos+1 local v = dodecode() return v, pos end return decode
fix backslash detection
fix backslash detection
Lua
mit
grafi-tt/lunajson,grafi-tt/lunajson,tst2005/lunajson,csteddy/lunajson,grafi-tt/lunajson,bigcrush/lunajson,csteddy/lunajson,tst2005/lunajson,bigcrush/lunajson
a56af7d4f5944946d90174d60ef2bdcb7a92b3c8
applications/luci-diag-devinfo/luasrc/model/cbi/luci_diag/netdiscover_devinfo.lua
applications/luci-diag-devinfo/luasrc/model/cbi/luci_diag/netdiscover_devinfo.lua
--[[ netdiscover_devinfo - SIP Device Information (c) 2009 Daniel Dickinson 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.i18n") require("luci.util") require("luci.sys") require("luci.model.uci") require("luci.controller.luci_diag.netdiscover_common") require("luci.controller.luci_diag.devinfo_common") local debug = false m = SimpleForm("luci_devinfo", translate("Network Device Scan"), translate("l_d_d_nd_netdiscover_to_devinfo_descr")) m.reset = false m.submit = false local outnets = luci.controller.luci_diag.netdiscover_common.get_params() luci.controller.luci_diag.devinfo_common.run_processes(outnets, luci.controller.luci_diag.netdiscover_common.command_function) luci.controller.luci_diag.devinfo_common.parse_output(m, outnets, false, "netdiscover", false, debug) luci.controller.luci_diag.netdiscover_common.action_links(m, false) return m
--[[ netdiscover_devinfo - SIP Device Information (c) 2009 Daniel Dickinson 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.i18n") require("luci.util") require("luci.sys") require("luci.model.uci") require("luci.controller.luci_diag.netdiscover_common") require("luci.controller.luci_diag.devinfo_common") local debug = false m = SimpleForm("luci_devinfo", translate("Network Device Scan"), translate("Scans for devices on specified networks.")) m.reset = false m.submit = false local outnets = luci.controller.luci_diag.netdiscover_common.get_params() luci.controller.luci_diag.devinfo_common.run_processes(outnets, luci.controller.luci_diag.netdiscover_common.command_function) luci.controller.luci_diag.devinfo_common.parse_output(m, outnets, false, "netdiscover", false, debug) luci.controller.luci_diag.netdiscover_common.action_links(m, false) return m
applications/luci-diag-devinfo: fix lost description in netdiscover_devinfo.lua, patch by "BasicXP" <[email protected]>
applications/luci-diag-devinfo: fix lost description in netdiscover_devinfo.lua, patch by "BasicXP" <[email protected]> git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@9051 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
4004db41c14d8e0d6e0a4dfe51f10fa7865cce3a
assets/scripts/bots/workbot/WorkBot.lua
assets/scripts/bots/workbot/WorkBot.lua
-- Mining Job class 'WorkBot' (Bot) WorkBot.States = { WAITING_FOR_JOB, } function WorkBot:__init(homeCoord) Bot.__init(self) LuaDebug.Log('WorkBot:__init() called!') self._homeCoord = homeCoord self._state = WorkBot.States.WAITING_FOR_JOB self._job = nil end function WorkBot:getDestination() if self._state == WorkBot.States.WAITING_FOR_JOB then return self._homeCoord; else if self._state == WorkBot.States.MINING then if not self._job then error('ASSERT FAIL: In mining state without a job.') end return self._job:getStartLocation() end end function WorkBot:getSpeed() return 1.0 end function WorkBot:willAcceptJob(job) return class_info(job).name == 'MiningJob' end function WorkBot:acceptJob(job) _self._job = job end
-- Mining Job class 'WorkBot' (Bot) WorkBot.States = { WAITING_FOR_JOB = 0, MINING = 1 } function WorkBot:__init(homeCoord) Bot.__init(self) LuaDebug.Log('WorkBot:__init() called!') self._homeCoord = homeCoord self._state = WorkBot.States.WAITING_FOR_JOB self._job = nil end function WorkBot:getDestination() if self._state == WorkBot.States.WAITING_FOR_JOB then return self._homeCoord; end if self._state == WorkBot.States.MINING then if not self._job then error('ASSERT FAIL: In mining state without a job.') end return self._job:getStartLocation() end error('ASSERT FAIL: Workbot: Invalid State.') end function WorkBot:getSpeed() return 1.0 end function WorkBot:willAcceptJob(job) return class_info(job).name == 'MiningJob' end function WorkBot:acceptJob(job) _self._job = job end function WorkBot:update(deltaTime) end
Fixed syntax error in WorkBot code.
Fixed syntax error in WorkBot code.
Lua
mit
NoxHarmonium/spacestationkeeper,NoxHarmonium/spacestationkeeper
91a8d4091cc320bed714f51f2e32824d80b2a2f7
packages/unichar/init.lua
packages/unichar/init.lua
local base = require("packages.base") local package = pl.class(base) package._name = "unichar" function package:registerCommands () self:registerCommand("unichar", function(_, content) local cp = content[1] if type(cp) ~= "string" then SU.error("Bad argument to \\unicode") end local hlist = SILE.typesetter.state.nodes local char = SU.utf8charfromcodepoint(cp) if #hlist > 1 and hlist[#hlist].is_unshaped then hlist[#hlist].text = hlist[#hlist].text .. char else SILE.typesetter:typeset(char) end end) end package.documentation = [[ \begin{document} \use[module=packages.unichar] SILE is Unicode compatible, and expects its input files to be in the UTF-8 encoding. (The actual range of Unicode characters supported will depend on the supported ranges of the fonts that SILE is using to typeset.) Some Unicode characters are hard to locate on a standard keyboard, and so are difficult to enter into SILE documents. The \autodoc:package{unichar} package helps with this problem by providing a command to enter Unicode codepoints. After loading \autodoc:package{unichar}, the \autodoc:command{\unichar} command becomes available: \begin{verbatim} \line % Note we are directly outputing the unicode to workaround https://github.com/sile-typesetter/sile/issues/991 \\unichar\{U+263A\} \% produces \font[family=Symbola]{☺} \line \end{verbatim} If the argument to \autodoc:command{\unichar} begins \code{U+}, \code{u+}, \code{0x} or \code{0X}, then it is assumed to be a hexadecimal value. Otherwise it is assumed to be a decimal codepoint. \end{document} ]] return package
local base = require("packages.base") local package = pl.class(base) package._name = "unichar" function package:registerCommands () self:registerCommand("unichar", function(_, content) local cp = content[1] if type(cp) ~= "string" then SU.error("Bad argument to \\unicode") end local hlist = SILE.typesetter.state.nodes local char = SU.utf8charfromcodepoint(cp) if #hlist > 1 and hlist[#hlist].is_unshaped and pl.tablex.deepcompare(hlist[#hlist].options, SILE.font.loadDefaults({})) then -- Stack character with a preceeding unshaped node if its font is the -- same as the current one, so that combining characters (e.g. diacritics) -- and kerning works with \unichar'ed code points too. hlist[#hlist].text = hlist[#hlist].text .. char else SILE.typesetter:typeset(char) end end) end package.documentation = [[ \begin{document} \use[module=packages.unichar] SILE is Unicode compatible, and expects its input files to be in the UTF-8 encoding. (The actual range of Unicode characters supported will depend on the supported ranges of the fonts that SILE is using to typeset.) Some Unicode characters are hard to locate on a standard keyboard, and so are difficult to enter into SILE documents. The \autodoc:package{unichar} package helps with this problem by providing a command to enter Unicode codepoints. After loading \autodoc:package{unichar}, the \autodoc:command{\unichar} command becomes available: \begin{verbatim} \line % Note we are directly outputing the unicode to workaround https://github.com/sile-typesetter/sile/issues/991 \\unichar\{U+263A\} \% produces \font[family=Symbola]{☺} \line \end{verbatim} If the argument to \autodoc:command{\unichar} begins \code{U+}, \code{u+}, \code{0x} or \code{0X}, then it is assumed to be a hexadecimal value. Otherwise it is assumed to be a decimal codepoint. \end{document} ]] return package
fix(packages): Combine `\unichar`'ed chars with same font only
fix(packages): Combine `\unichar`'ed chars with same font only
Lua
mit
alerque/sile,alerque/sile,alerque/sile,alerque/sile
2afec592f8efd2ee234ec6936a7b4b2e804b2160
plugins/autostandby.koplugin/main.lua
plugins/autostandby.koplugin/main.lua
local Device = require("device") if not Device:isPocketBook() --[[and not Device:isKobo()]] then return { disabled = true } end local PowerD = Device:getPowerDevice() local DataStorage = require("datastorage") local LuaSettings = require("luasettings") local UIManager = require("ui/uimanager") local WidgetContainer = require("ui/widget/container/widgetcontainer") local SpinWidget = require("ui/widget/spinwidget") local logger = require("logger") local _ = require("gettext") local AutoStandby = WidgetContainer:new{ is_doc_only = false, name = "autostandby", settings = LuaSettings:open(DataStorage:getSettingsDir() .. "/autostandby.lua"), delay = 0, lastInput = 0, preventing = false, } function AutoStandby:init() if not self.settings:has("filter") then logger.dbg("AutoStandby: No settings found, initializing defaults") self.settings.data = { forbidden = false, -- If forbidden, standby is never allowed to occur filter = 1, -- Consider input only further than this many seconds apart min = 1, -- Initial delay period during which we won't standby mul = 1.5, -- Multiply the delay with each subsequent input that happens, scales up to max max = 30, -- Input that happens further than 30 seconds since last input one reset delay back to 'min' win = 5, -- Additional time window to consider input contributing to standby delay bat = 60, -- If battery is below this percent, make auto-standby aggressive again (disables scaling by mul) } self.settings:flush() end UIManager.event_hook:registerWidget("InputEvent", self) self.ui.menu:registerToMainMenu(self) end function AutoStandby:addToMainMenu(menu_items) menu_items.autostandby = { text = _("Auto-standby settings"), sub_item_table = { { keep_menu_open = true, text = _("Allow auto-standby"), checked_func = function() return self:isAllowedByConfig() end, callback = function() self.settings:saveSetting("forbidden", self:isAllowedByConfig()):flush() end, }, self:genSpinMenuItem(_("Min input idle seconds"), "min", function() return 0 end, function() return self.settings:readSetting("max") end), self:genSpinMenuItem(_("Max input idle seconds"), "max", function() return 0 end), self:genSpinMenuItem(_("Input window seconds"), "win", function() return 0 end, function() return self.settings:readSetting("max") end), self:genSpinMenuItem(_("Always standby if battery below"), "bat", function() return 0 end, function() return 100 end), } } end -- We've received touch/key event, so delay stadby accordingly function AutoStandby:onInputEvent() local config = self.settings.data local t = os.time() if t < self.lastInput + config.filter then -- packed too close together, ignore logger.dbg("AutoStandby: input packed too close to previous one, ignoring") return end -- Nuke past timer as we'll reschedule the allow (or not) UIManager:unschedule(self.allow) if PowerD:getCapacityHW() <= config.bat then -- battery is below threshold, so allow standby aggressively logger.dbg("AutoStandby: battery below threshold, enabling aggressive standby") self:allow() return elseif t > self.lastInput + config.max then -- too far apart, so reset delay logger.dbg("AutoStandby: input too far in future, resetting adaptive standby delay from", self.delay, "to", config.min) self.delay = config.min elseif t < self.lastInput + self.delay + config.win then -- otherwise widen the delay - "adaptive" - with frequent inputs, but don't grow beyonnd the max self.delay = math.min((self.delay+1) * config.mul, config.max) logger.dbg("AutoStandby: increasing standby delay to", self.delay) end -- equilibrium: when the event arrives beyond delay + win, but still below max, we keep the delay as-is self.lastInput = t if not self:isAllowedByConfig() then -- all standbys forbidden, always prevent self:prevent() return elseif self.delay == 0 then -- If delay is 0 now, just allow straight self:allow() return end -- otherwise prevent for a while for duration of the delay self:prevent() -- and schedule standby re-enable once delay expires UIManager:scheduleIn(self.delay, self.allow, self) end -- Prevent standby (by timer) function AutoStandby:prevent() if not self.preventing then self.preventing = true UIManager:preventStandby() end end -- Allow standby (by timer) function AutoStandby:allow() if self.preventing then self.preventing = false UIManager:allowStandby() end end function AutoStandby:isAllowedByConfig() return self.settings:isFalse("forbidden") end function AutoStandby:genSpinMenuItem(text, cfg, min, max) return { keep_menu_open = true, text = text, enabled_func = function() return self:isAllowedByConfig() end, callback = function() local spin = SpinWidget:new { width = math.floor(Device.screen:getWidth() * 0.6), value = self.settings:readSetting(cfg), value_min = min and min() or 0, value_max = max and max() or 9999, value_hold_step = 10, ok_text = "Update", title_text = text, callback = function(spin) self.settings:saveSetting(cfg, spin.value):flush() end, } UIManager:show(spin) end } end -- koreader is merely waiting for user input right now. -- UI signals us that standby is allowed at this very moment because nothing else goes on in the background. function AutoStandby:onAllowStandby() logger.dbg("AutoStandby: onAllowStandby()") -- In case the OS frontend itself doesn't manage power state, we can do it on our own here. -- One should also configure wake-up pins and perhaps wake alarm, -- if we want to enter deeper sleep states later on from within standby. --os.execute("echo mem > /sys/power/state") end return AutoStandby
local Device = require("device") if not Device:isPocketBook() --[[and not Device:isKobo()]] then return { disabled = true } end local PowerD = Device:getPowerDevice() local DataStorage = require("datastorage") local LuaSettings = require("luasettings") local UIManager = require("ui/uimanager") local WidgetContainer = require("ui/widget/container/widgetcontainer") local SpinWidget = require("ui/widget/spinwidget") local logger = require("logger") local _ = require("gettext") local AutoStandby = WidgetContainer:new{ is_doc_only = false, name = "autostandby", -- static for all plugin instances settings = LuaSettings:open(DataStorage:getSettingsDir() .. "/autostandby.lua"), delay = 0, lastInput = 0, preventing = false, } function AutoStandby:init() logger.dbg("AutoStandby:init() instance=", tostring(self)) if not self.settings:has("filter") then logger.dbg("AutoStandby: No settings found, initializing defaults") self.settings.data = { forbidden = false, -- If forbidden, standby is never allowed to occur filter = 1, -- Consider input only further than this many seconds apart min = 1, -- Initial delay period during which we won't standby mul = 1.5, -- Multiply the delay with each subsequent input that happens, scales up to max max = 30, -- Input that happens further than 30 seconds since last input one reset delay back to 'min' win = 5, -- Additional time window to consider input contributing to standby delay bat = 60, -- If battery is below this percent, make auto-standby aggressive again (disables scaling by mul) } self.settings:flush() end UIManager.event_hook:registerWidget("InputEvent", self) self.ui.menu:registerToMainMenu(self) end function AutoStandby:addToMainMenu(menu_items) menu_items.autostandby = { text = _("Auto-standby settings"), sub_item_table = { { keep_menu_open = true, text = _("Allow auto-standby"), checked_func = function() return self:isAllowedByConfig() end, callback = function() self.settings:saveSetting("forbidden", self:isAllowedByConfig()):flush() end, }, self:genSpinMenuItem(_("Min input idle seconds"), "min", function() return 0 end, function() return self.settings:readSetting("max") end), self:genSpinMenuItem(_("Max input idle seconds"), "max", function() return 0 end), self:genSpinMenuItem(_("Input window seconds"), "win", function() return 0 end, function() return self.settings:readSetting("max") end), self:genSpinMenuItem(_("Always standby if battery below"), "bat", function() return 0 end, function() return 100 end), } } end -- We've received touch/key event, so delay stadby accordingly function AutoStandby:onInputEvent() logger.dbg("AutoStandby:onInputevent() instance=", tostring(self)) local config = self.settings.data local t = os.time() if t < AutoStandby.lastInput + config.filter then -- packed too close together, ignore logger.dbg("AutoStandby: input packed too close to previous one, ignoring") return end -- Nuke past timer as we'll reschedule the allow (or not) UIManager:unschedule(AutoStandby.allow) if PowerD:getCapacityHW() <= config.bat then -- battery is below threshold, so allow standby aggressively logger.dbg("AutoStandby: battery below threshold, enabling aggressive standby") self:allow() return elseif t > AutoStandby.lastInput + config.max then -- too far apart, so reset delay logger.dbg("AutoStandby: input too far in future, resetting adaptive standby delay from", AutoStandby.delay, "to", config.min) AutoStandby.delay = config.min elseif t < AutoStandby.lastInput + AutoStandby.delay + config.win then -- otherwise widen the delay - "adaptive" - with frequent inputs, but don't grow beyonnd the max AutoStandby.delay = math.min((AutoStandby.delay+1) * config.mul, config.max) logger.dbg("AutoStandby: increasing standby delay to", AutoStandby.delay) end -- equilibrium: when the event arrives beyond delay + win, but still below max, we keep the delay as-is AutoStandby.lastInput = t if not self:isAllowedByConfig() then -- all standbys forbidden, always prevent self:prevent() return elseif AutoStandby.delay == 0 then -- If delay is 0 now, just allow straight self:allow() return end -- otherwise prevent for a while for duration of the delay self:prevent() -- and schedule standby re-enable once delay expires UIManager:scheduleIn(AutoStandby.delay, AutoStandby.allow, AutoStandby) end -- Prevent standby (by timer) function AutoStandby:prevent() if not AutoStandby.preventing then AutoStandby.preventing = true UIManager:preventStandby() end end -- Allow standby (by timer) function AutoStandby:allow() if AutoStandby.preventing then AutoStandby.preventing = false UIManager:allowStandby() end end function AutoStandby:isAllowedByConfig() return self.settings:isFalse("forbidden") end function AutoStandby:genSpinMenuItem(text, cfg, min, max) return { keep_menu_open = true, text = text, enabled_func = function() return self:isAllowedByConfig() end, callback = function() local spin = SpinWidget:new { width = math.floor(Device.screen:getWidth() * 0.6), value = self.settings:readSetting(cfg), value_min = min and min() or 0, value_max = max and max() or 9999, value_hold_step = 10, ok_text = "Update", title_text = text, callback = function(spin) self.settings:saveSetting(cfg, spin.value):flush() end, } UIManager:show(spin) end } end -- koreader is merely waiting for user input right now. -- UI signals us that standby is allowed at this very moment because nothing else goes on in the background. function AutoStandby:onAllowStandby() logger.dbg("AutoStandby: onAllowStandby()") -- In case the OS frontend itself doesn't manage power state, we can do it on our own here. -- One should also configure wake-up pins and perhaps wake alarm, -- if we want to enter deeper sleep states later on from within standby. --os.execute("echo mem > /sys/power/state") end return AutoStandby
Autostandby: Fix wrong assumptions about instance liveness. (#6666)
Autostandby: Fix wrong assumptions about instance liveness. (#6666) Got instantiated multiple times, when our state is meant to be global. Fixes #6647
Lua
agpl-3.0
Markismus/koreader,Frenzie/koreader,Frenzie/koreader,NiLuJe/koreader,poire-z/koreader,NiLuJe/koreader,pazos/koreader,koreader/koreader,Hzj-jie/koreader,koreader/koreader,poire-z/koreader,mwoz123/koreader
615a4eda0836a013e4a3dfa453116bae1530475e
pud/component/ControllerComponent.lua
pud/component/ControllerComponent.lua
local Class = require 'lib.hump.class' local Component = getClass 'pud.component.Component' local CommandEvent = getClass 'pud.event.CommandEvent' local ConsoleEvent = getClass 'pud.event.ConsoleEvent' local WaitCommand = getClass 'pud.command.WaitCommand' local MoveCommand = getClass 'pud.command.MoveCommand' local AttackCommand = getClass 'pud.command.AttackCommand' local OpenDoorCommand = getClass 'pud.command.OpenDoorCommand' local DoorMapType = getClass 'pud.map.DoorMapType' local message = require 'pud.component.message' local property = require 'pud.component.property' local CommandEvents = CommandEvents -- ControllerComponent -- local ControllerComponent = Class{name='ControllerComponent', inherits=Component, function(self, newProperties) Component._addRequiredProperties(self, {'CanOpenDoors'}) Component.construct(self, newProperties) self:_addMessages( 'COLLIDE_NONE', 'COLLIDE_BLOCKED', 'COLLIDE_ITEM', 'COLLIDE_ENEMY', 'COLLIDE_HERO') end } -- destructor function ControllerComponent:destroy() self._onGround = nil Component.destroy(self) end function ControllerComponent:_setProperty(prop, data) prop = property(prop) if nil == data then data = property.default(prop) end if prop == property('CanOpenDoors') then verify('boolean', data) end Component._setProperty(self, prop, data) end -- check for collisions at the given coordinates function ControllerComponent:_attemptMove(x, y) local pos = self._mediator:query(property('Position')) local newX, newY = pos[1] + x, pos[2] + y CollisionSystem:check(self._mediator, newX, newY) end function ControllerComponent:_wait() self:_sendCommand(WaitCommand(self._mediator)) end function ControllerComponent:_move(x, y) local canMove = self._mediator:query(property('CanMove')) if canMove then self:_sendCommand(MoveCommand(self._mediator, x, y)) else self:_wait() end end function ControllerComponent:_tryToManipulateMap(node) local wait = true if node then local mapType = node:getMapType() if mapType:isType(DoorMapType('shut')) then if self._mediator:query(property('CanOpenDoors')) then self:_sendCommand(OpenDoorCommand(self._mediator, node)) wait = false end end end if wait then self:_wait() end end function ControllerComponent:_attack(isHero, target) local etype = self._mediator:getEntityType() if isHero or 'hero' == etype then self:_sendCommand( AttackCommand(self._mediator, EntityRegistry:get(target))) else self:_wait() end end function ControllerComponent:_tryToPickup() if self._onGround then self:_sendCommand(PickupCommand(self._mediator, self._onGround)) end end function ControllerComponent:_sendCommand(command) CommandEvents:notify(CommandEvent(command)) end function ControllerComponent:receive(msg, ...) if msg == message('COLLIDE_NONE') then self._onGround = nil self:_move(...) elseif msg == message('COLLIDE_BLOCKED') then self:_tryToManipulateMap(...) elseif msg == message('COLLIDE_ENEMY') then self:_attack(false, ...) elseif msg == message('COLLIDE_HERO') then self:_attack(true, ...) elseif msg == message('COLLIDE_ITEM') then if self._mediator:getEntityType() == 'hero' then local id = select(1, ...) self._onGround = id if id then local item = EntityRegistry:get(id) local name = item:getName() local elevel = item:getELevel() GameEvents:push(ConsoleEvent('Item found: %s (%d)', name, elevel)) end end else Component.receive(self, msg, ...) end end -- the class return ControllerComponent
local Class = require 'lib.hump.class' local Component = getClass 'pud.component.Component' local CommandEvent = getClass 'pud.event.CommandEvent' local ConsoleEvent = getClass 'pud.event.ConsoleEvent' local WaitCommand = getClass 'pud.command.WaitCommand' local MoveCommand = getClass 'pud.command.MoveCommand' local AttackCommand = getClass 'pud.command.AttackCommand' local OpenDoorCommand = getClass 'pud.command.OpenDoorCommand' local PickupCommand = getClass 'pud.command.PickupCommand' --local DropCommand = getClass 'pud.command.DropCommand' local DoorMapType = getClass 'pud.map.DoorMapType' local message = require 'pud.component.message' local property = require 'pud.component.property' local CommandEvents = CommandEvents local vec2_equal = vec2.equal -- ControllerComponent -- local ControllerComponent = Class{name='ControllerComponent', inherits=Component, function(self, newProperties) Component._addRequiredProperties(self, {'CanOpenDoors'}) Component.construct(self, newProperties) self:_addMessages( 'COLLIDE_NONE', 'COLLIDE_BLOCKED', 'COLLIDE_ITEM', 'COLLIDE_ENEMY', 'COLLIDE_HERO') end } -- destructor function ControllerComponent:destroy() self._onGround = nil Component.destroy(self) end function ControllerComponent:_setProperty(prop, data) prop = property(prop) if nil == data then data = property.default(prop) end if prop == property('CanOpenDoors') then verify('boolean', data) end Component._setProperty(self, prop, data) end -- check for collisions at the given coordinates function ControllerComponent:_attemptMove(x, y) local pos = self._mediator:query(property('Position')) local newX, newY = pos[1] + x, pos[2] + y CollisionSystem:check(self._mediator, newX, newY) end function ControllerComponent:_wait() self:_sendCommand(WaitCommand(self._mediator)) end function ControllerComponent:_move(x, y) local canMove = self._mediator:query(property('CanMove')) if canMove then self:_sendCommand(MoveCommand(self._mediator, x, y)) else self:_wait() end end function ControllerComponent:_tryToManipulateMap(node) local wait = true if node then local mapType = node:getMapType() if mapType:isType(DoorMapType('shut')) then if self._mediator:query(property('CanOpenDoors')) then self:_sendCommand(OpenDoorCommand(self._mediator, node)) wait = false end end end if wait then self:_wait() end end function ControllerComponent:_attack(isHero, target) local etype = self._mediator:getEntityType() if isHero or 'hero' == etype then self:_sendCommand( AttackCommand(self._mediator, EntityRegistry:get(target))) else self:_wait() end end function ControllerComponent:_tryToPickup() if self._onGround then local item = EntityRegistry:get(self._onGround) local ipos = item:query(property('Position')) local mpos = self._mediator:query(property('Position')) if vec2_equal(ipos[1], ipos[2], mpos[1], mpos[2]) then self:_sendCommand(PickupCommand(self._mediator, self._onGround)) end end end function ControllerComponent:_sendCommand(command) CommandEvents:notify(CommandEvent(command)) end function ControllerComponent:receive(msg, ...) if msg == message('COLLIDE_NONE') then self:_move(...) elseif msg == message('COLLIDE_BLOCKED') then self:_tryToManipulateMap(...) elseif msg == message('COLLIDE_ENEMY') then self:_attack(false, ...) elseif msg == message('COLLIDE_HERO') then self:_attack(true, ...) elseif msg == message('COLLIDE_ITEM') then if self._mediator:getEntityType() == 'hero' then local id = select(1, ...) self._onGround = id if id then local item = EntityRegistry:get(id) local name = item:getName() local elevel = item:getELevel() GameEvents:push(ConsoleEvent('Item found: %s (%d)', name, elevel)) end end else Component.receive(self, msg, ...) end end -- the class return ControllerComponent
fix tryToPickup() to check positions
fix tryToPickup() to check positions
Lua
mit
scottcs/wyx
a60cfc4e10afb804bcd0da832472b3566cd73b31
frontend/ui/reader/readerfrontlight.lua
frontend/ui/reader/readerfrontlight.lua
package.cpath = package.cpath..";/usr/lib/lua/?.so" require "ui/device" ReaderFrontLight = InputContainer:new{ steps = {0,1,2,3,4,5,6,7,8,9,10}, intensity = nil, } function ReaderFrontLight:init() local dev_mod = Device:getModel() if dev_mod == "KindlePaperWhite" then require "liblipclua" self.lipc_handle = lipc.init("com.github.koreader") self.intensity = self.lipc_handle:get_int_property("com.lab126.powerd", "flIntensity") end self.ges_events = { Adjust = { GestureRange:new{ ges = "two_finger_pan", range = Geom:new{ x = 0, y = 0, w = Screen:getWidth(), h = Screen:getHeight(), }, rate = 2.0, } }, } end function ReaderFrontLight:onAdjust(arg, ges) if self.lipc_handle then local rel_proportion = ges.distance / Screen:getWidth() local delta_int = self.steps[math.ceil(#self.steps*rel_proportion)] local msg = "" if ges.direction == "north" then msg = _("Increase front light intensity to ") self.intensity = self.intensity + delta_int self:setIntensity(self.intensity, msg) elseif ges.direction == "south" then msg = _("Decrease front light intensity to ") self.intensity = self.intensity - delta_int self:setIntensity(self.intensity, msg) end end return true end function ReaderFrontLight:setIntensity(intensity, msg) if self.lipc_handle then intensity = intensity < 0 and 0 or intensity intensity = intensity > 24 and 24 or intensity self.lipc_handle:set_int_property("com.lab126.powerd", "flIntensity", intensity) UIManager:show(Notification:new{ text = msg..intensity, timeout = 1 }) end return true end
package.cpath = package.cpath..";/usr/lib/lua/?.so" require "ui/device" ReaderFrontLight = InputContainer:new{ steps = {0,1,2,3,4,5,6,7,8,9,10}, intensity = nil, } function ReaderFrontLight:init() local dev_mod = Device:getModel() if dev_mod == "KindlePaperWhite" then require "liblipclua" self.lipc_handle = lipc.init("com.github.koreader") if self.lipc_handle then self.intensity = self.lipc_handle:get_int_property("com.lab126.powerd", "flIntensity") end end self.ges_events = { Adjust = { GestureRange:new{ ges = "two_finger_pan", range = Geom:new{ x = 0, y = 0, w = Screen:getWidth(), h = Screen:getHeight(), }, rate = 2.0, } }, } end function ReaderFrontLight:onAdjust(arg, ges) if self.lipc_handle and self.intensity ~=nil then local rel_proportion = ges.distance / Screen:getWidth() local delta_int = self.steps[math.ceil(#self.steps*rel_proportion)] local msg = "" if ges.direction == "north" then msg = _("Increase front light intensity to ") self.intensity = self.intensity + delta_int self:setIntensity(self.intensity, msg) elseif ges.direction == "south" then msg = _("Decrease front light intensity to ") self.intensity = self.intensity - delta_int self:setIntensity(self.intensity, msg) end end return true end function ReaderFrontLight:setIntensity(intensity, msg) if self.lipc_handle then intensity = intensity < 0 and 0 or intensity intensity = intensity > 24 and 24 or intensity self.lipc_handle:set_int_property("com.lab126.powerd", "flIntensity", intensity) UIManager:show(Notification:new{ text = msg..intensity, timeout = 1 }) end return true end
fix occasionally failed lipc invocation
fix occasionally failed lipc invocation
Lua
agpl-3.0
chrox/koreader,houqp/koreader,NiLuJe/koreader,noname007/koreader,mwoz123/koreader,chihyang/koreader,ashhher3/koreader,apletnev/koreader,ashang/koreader,poire-z/koreader,NickSavage/koreader,frankyifei/koreader,koreader/koreader,poire-z/koreader,mihailim/koreader,Hzj-jie/koreader,koreader/koreader,pazos/koreader,robert00s/koreader,Markismus/koreader,Frenzie/koreader,Frenzie/koreader,lgeek/koreader,NiLuJe/koreader
5e0b3df698de71689bd2572ff950ebf555c9ec08
home/.config/nvim/lua/plugins/init.lua
home/.config/nvim/lua/plugins/init.lua
-- Automatically install packer local fn = vim.fn local install_path = fn.stdpath('data')..'/site/pack/packer/start/packer.nvim' if fn.empty(fn.glob(install_path)) > 0 then fn.system({'git', 'clone', '--depth', '1', 'https://github.com/wbthomason/packer.nvim', install_path}) vim.cmd 'packadd packer.nvim' end -- :PackerCompile -- :PackerClean -- :PackerInstall -- :PackerUpdate -- :PackerSync require('packer').startup(function(use) -- Plugins with too much config to have all in -- the same file require('plugins.highlighting')(use) require('plugins.statusline')(use) require('plugins.browsing')(use) require('plugins.finding')(use) -- NOTE: previously tried plugins -- twilight.nvim -- - loses highlights on dim -- shade.nvim -- - buggy, tries to dim buffer that doesn't exist -- - previous opacity: 85 ---------------------- -- Scripting Utilities use 'nvim-lua/plenary.nvim' -- use 'rcarriga/nvim-notify' ---------------------- -- Syntax / Theme ---------------------- use 'joshdick/onedark.vim' use 'sainnhe/edge' ---------------------- -- Editor Behavior ---------------------- use 'tpope/vim-surround' use 'tpope/vim-commentary' use 'tpope/vim-fugitive' use 'ntpeters/vim-better-whitespace' use 'windwp/nvim-autopairs' use 'editorconfig/editorconfig-vim' use 'abecodes/tabout.nvim' -- https://github.com/Pocco81/DAPInstall.nvim -- use { "rcarriga/nvim-dap-ui", requires = {"mfussenegger/nvim-dap"} } ---------------------- -- Information ---------------------- use { 'neoclide/coc.nvim', branch = 'release' } use 'airblade/vim-gitgutter' -- colorize various color-like tokens in code use 'norcalli/nvim-colorizer.lua' -- tree-sitter plugin, colorizez brackets and parens use 'p00f/nvim-ts-rainbow' -- ¯\_( ツ )_/¯ -- kinda broken -- overriding tab breaks everything -- issues are disabled on the repo, no support -- use { 'github/copilot.vim' } -- Automatically set up your configuration after cloning packer.nvim -- Put this at the end after all plugins if packer_bootstrap then require('packer').sync() end end)
-- Automatically install packer local fn = vim.fn local install_path = fn.stdpath('data')..'/site/pack/packer/start/packer.nvim' if fn.empty(fn.glob(install_path)) > 0 then fn.system({'git', 'clone', '--depth', '1', 'https://github.com/wbthomason/packer.nvim', install_path}) vim.cmd 'packadd packer.nvim' end -- :PackerCompile -- :PackerClean -- :PackerInstall -- :PackerUpdate -- :PackerSync require('packer').startup(function(use) -- Plugins with too much config to have all in -- the same file require('plugins.highlighting')(use) require('plugins.statusline')(use) require('plugins.browsing')(use) require('plugins.finding')(use) -- NOTE: previously tried plugins -- twilight.nvim -- - loses highlights on dim -- shade.nvim -- - buggy, tries to dim buffer that doesn't exist -- - previous opacity: 85 ---------------------- -- Scripting Utilities use 'nvim-lua/plenary.nvim' -- use 'rcarriga/nvim-notify' ---------------------- -- Syntax / Theme ---------------------- use 'joshdick/onedark.vim' use 'sainnhe/edge' ---------------------- -- Editor Behavior ---------------------- use 'tpope/vim-surround' use 'tpope/vim-commentary' use 'tpope/vim-fugitive' use 'ntpeters/vim-better-whitespace' use 'windwp/nvim-autopairs' use 'editorconfig/editorconfig-vim' use { 'abecodes/tabout.nvim', config = function() require('tabout').setup {} end, wants = { 'nvim-treesitter' }, after = { 'coc.nvim' } } -- https://github.com/Pocco81/DAPInstall.nvim -- use { "rcarriga/nvim-dap-ui", requires = {"mfussenegger/nvim-dap"} } ---------------------- -- Information ---------------------- use { 'neoclide/coc.nvim', branch = 'release' } use 'airblade/vim-gitgutter' -- colorize various color-like tokens in code use 'norcalli/nvim-colorizer.lua' -- tree-sitter plugin, colorizez brackets and parens use 'p00f/nvim-ts-rainbow' -- ¯\_( ツ )_/¯ -- kinda broken -- overriding tab breaks everything -- issues are disabled on the repo, no support -- use { 'github/copilot.vim' } -- Automatically set up your configuration after cloning packer.nvim -- Put this at the end after all plugins if packer_bootstrap then require('packer').sync() end end)
chore: fix tabout config
chore: fix tabout config
Lua
mit
NullVoxPopuli/dotfiles,NullVoxPopuli/dotfiles,NullVoxPopuli/dotfiles
a3d43a4ebeb5b1bda833565ee401144ee74ca516
cancel.lua
cancel.lua
-- Cancel(0, jid) -- -------------- -- Cancel a job from taking place. It will be deleted from the system, and any -- attempts to renew a heartbeat will fail, and any attempts to complete it -- will fail. If you try to get the data on the object, you will get nothing. -- -- Args: -- 1) jid if #KEYS > 0 then error('Cancel(): No Keys should be provided') end local jid = assert(ARGV[1], 'Cancel(): Arg "jid" missing.') -- Find any stage it's associated with and remove its from that stage local state, queue, failure, worker = unpack(redis.call('hmget', 'ql:j:' .. jid, 'state', 'queue', 'failure', 'worker')) if state == 'complete' then return False else -- If this job has dependents, then we should probably fail if redis.call('zcard', 'ql:j:' .. jid .. '-dependents') > 0 then error('Cancel(): ' .. jid .. ' has un-canceled jobs that depend on it') end -- Remove this job from whatever worker has it, if any if worker then redis.call('zrem', 'ql:w:' .. worker .. ':jobs', jid) end -- Remove it from that queue if queue then redis.call('zrem', 'ql:q:' .. queue .. '-work', jid) redis.call('zrem', 'ql:q:' .. queue .. '-locks', jid) redis.call('zrem', 'ql:q:' .. queue .. '-scheduled', jid) redis.call('zrem', 'ql:q:' .. queue .. '-depends', jid) end -- Delete any notion of dependencies it has redis.call('del', 'ql:j:' .. jid .. '-dependencies') -- If we're in the failed state, remove all of our data if state == 'failed' then failure = cjson.decode(failure) -- We need to make this remove it from the failed queues redis.call('lrem', 'ql:f:' .. failure.group, 0, jid) if redis.call('llen', 'ql:f:' .. failure.group) == 0 then redis.call('srem', 'ql:failures', failure.group) end end -- Remove it as a job that's tagged with this particular tag local tags = cjson.decode(redis.call('hget', 'ql:j:' .. jid, 'tags') or '{}') for i, tag in ipairs(tags) do redis.call('zrem', 'ql:t:' .. tag, jid) redis.call('zincrby', 'ql:tags', -1, tag) end -- Just go ahead and delete our data redis.call('del', 'ql:j:' .. jid) end
-- Cancel(0, jid) -- -------------- -- Cancel a job from taking place. It will be deleted from the system, and any -- attempts to renew a heartbeat will fail, and any attempts to complete it -- will fail. If you try to get the data on the object, you will get nothing. -- -- Args: -- 1) jid if #KEYS > 0 then error('Cancel(): No Keys should be provided') end local jid = assert(ARGV[1], 'Cancel(): Arg "jid" missing.') -- Find any stage it's associated with and remove its from that stage local state, queue, failure, worker = unpack(redis.call('hmget', 'ql:j:' .. jid, 'state', 'queue', 'failure', 'worker')) if state == 'complete' then return False else -- If this job has dependents, then we should probably fail if redis.call('scard', 'ql:j:' .. jid .. '-dependents') > 0 then error('Cancel(): ' .. jid .. ' has un-canceled jobs that depend on it') end -- Remove this job from whatever worker has it, if any if worker then redis.call('zrem', 'ql:w:' .. worker .. ':jobs', jid) end -- Remove it from that queue if queue then redis.call('zrem', 'ql:q:' .. queue .. '-work', jid) redis.call('zrem', 'ql:q:' .. queue .. '-locks', jid) redis.call('zrem', 'ql:q:' .. queue .. '-scheduled', jid) redis.call('zrem', 'ql:q:' .. queue .. '-depends', jid) end -- We should probably go through all our dependencies and remove ourselves -- from the list of dependents for i, j in ipairs(redis.call('smembers', 'ql:j:' .. jid .. '-dependencies')) do redis.call('srem', 'ql:j:' .. j .. '-dependents', jid) end -- Delete any notion of dependencies it has redis.call('del', 'ql:j:' .. jid .. '-dependencies') -- If we're in the failed state, remove all of our data if state == 'failed' then failure = cjson.decode(failure) -- We need to make this remove it from the failed queues redis.call('lrem', 'ql:f:' .. failure.group, 0, jid) if redis.call('llen', 'ql:f:' .. failure.group) == 0 then redis.call('srem', 'ql:failures', failure.group) end end -- Remove it as a job that's tagged with this particular tag local tags = cjson.decode(redis.call('hget', 'ql:j:' .. jid, 'tags') or '{}') for i, tag in ipairs(tags) do redis.call('zrem', 'ql:t:' .. tag, jid) redis.call('zincrby', 'ql:tags', -1, tag) end -- Just go ahead and delete our data redis.call('del', 'ql:j:' .. jid) end
Bug fix for cancel():
Bug fix for cancel(): 1) Jobs with dependencies are not allowed to be canceled. Unfortunately, qless was throwing a less-than-helpful error in place of a more meaningful one. That has been rectified with this commit. 2) When a job is canceled, if it had previously been dependent on jobs, it should remove itself from the lists of dependents of each of its dependencies.
Lua
mit
backupify/qless-core,seomoz/qless-core,seomoz/qless-core
ae252b6580037da6493734a34ce3738b02ca14b9
src/lua-factory/sources/grl-lastfm-cover.lua
src/lua-factory/sources/grl-lastfm-cover.lua
--[[ * Copyright (C) 2015 Bastien Nocera. * * Contact: Bastien Nocera <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; version 2.1 of * the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA * --]] --------------------------- -- Source initialization -- --------------------------- source = { id = "grl-lastfm-cover", name = "Last.fm Cover", description = "a source for music covers", goa_account_provider = 'lastfm', goa_account_feature = 'music', supported_keys = { 'thumbnail' }, supported_media = { 'audio' }, resolve_keys = { ["type"] = "audio", required = { "artist", "album" }, }, tags = { 'music', 'net:internet', 'net:plaintext' }, } ------------------ -- Source utils -- ------------------ LASTFM_SEARCH_ALBUM = 'http://ws.audioscrobbler.com/2.0/?method=album.getInfo&api_key=%s&artist=%s&album=%s' --------------------------------- -- Handlers of Grilo functions -- --------------------------------- function grl_source_resolve(media, options, callback) local url local artist, title if not media or not media.artist or not media.album or #media.artist == 0 or #media.album == 0 then callback() return end -- Prepare artist and title strings to the url artist = grl.encode(media.artist) album = grl.encode(media.album) url = string.format(LASTFM_SEARCH_ALBUM, grl.goa_consumer_key(), artist, album) local userdata = {callback = callback, media = media} grl.fetch(url, fetch_page_cb, userdata) end --------------- -- Utilities -- --------------- function fetch_page_cb(result, userdata) if not result then userdata.callback() return end userdata.media.thumbnail = {} for k, v in string.gmatch(result, '<image size="(.-)">(.-)</image>') do grl.debug ('Image size ' .. k .. ' = ' .. v) table.insert(userdata.media.thumbnail, v) end userdata.callback(userdata.media, 0) end
--[[ * Copyright (C) 2015 Bastien Nocera. * * Contact: Bastien Nocera <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; version 2.1 of * the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA * --]] --------------------------- -- Source initialization -- --------------------------- source = { id = "grl-lastfm-cover", name = "Last.fm Cover", description = "a source for music covers", goa_account_provider = 'lastfm', goa_account_feature = 'music', supported_keys = { 'thumbnail' }, supported_media = { 'audio' }, resolve_keys = { ["type"] = "audio", required = { "artist", "album" }, }, tags = { 'music', 'net:internet', 'net:plaintext' }, } ------------------ -- Source utils -- ------------------ LASTFM_SEARCH_ALBUM = 'http://ws.audioscrobbler.com/2.0/?method=album.getInfo&api_key=%s&artist=%s&album=%s' --------------------------------- -- Handlers of Grilo functions -- --------------------------------- function grl_source_resolve(media, options, callback) local url local artist, title if not media or not media.artist or not media.album or #media.artist == 0 or #media.album == 0 then callback() return end -- Prepare artist and title strings to the url artist = grl.encode(media.artist) album = grl.encode(media.album) url = string.format(LASTFM_SEARCH_ALBUM, grl.goa_consumer_key(), artist, album) local userdata = {callback = callback, media = media} grl.fetch(url, fetch_page_cb, userdata) end --------------- -- Utilities -- --------------- function fetch_page_cb(result, userdata) if not result then userdata.callback() return end userdata.media.thumbnail = {} local image_sizes = { "mega", "extralarge", "large", "medium", "small" } for _, size in pairs(image_sizes) do local url url = string.match(result, '<image size="' .. size .. '">(.-)</image>') grl.debug ('Image size ' .. size .. ' = ' .. url) table.insert(userdata.media.thumbnail, url) end userdata.callback(userdata.media, 0) end
lastfm-cover: thumbnails ordered from large to small
lastfm-cover: thumbnails ordered from large to small This makes the plugin return the largest cover first as was previously the behaviour with the standalone plugin and is expected by consumer applications. https://bugzilla.gnome.org/show_bug.cgi?id=761694
Lua
lgpl-2.1
MikePetullo/grilo-plugins,jasuarez/grilo-plugins,grilofw/grilo-plugins,grilofw/grilo-plugins,MikePetullo/grilo-plugins,GNOME/grilo-plugins,GNOME/grilo-plugins,jasuarez/grilo-plugins,MikePetullo/grilo-plugins
285e43226ddc9cea7ef1e07115996494e340ae15
lib/core/test/object/lua_interface.lua
lib/core/test/object/lua_interface.lua
local O = require "Quanta.Object" local T = require "Quanta.Time" function print_table(t, level) local function table_to_string(t, level) local ws = string.rep(" ", level) if t == nil then return ws .. "nil" end local output = "{\n" for k, v in pairs(t) do output = output .. ws .. " \"" .. tostring(k) .. "\" : " if type(v) == "table" then output = output .. table_to_string(v, level + 1) .. ",\n" else output = output .. tostring(v) .. ",\n" end end return output .. ws .. "}" end print(table_to_string(t, level or 0)) end -- print_table(O) do local a = O.create_mv [[ a, b ]] for i, v in O.children(a) do print(i, O.write_text_string(v, true), v) assert( (i == 1 and O.identifier(v) == "a") or (i == 2 and O.identifier(v) == "b") or false ) end assert(O.push_child(a, "c") ~= nil) assert(O.num_children(a) == 3 and O.identifier(O.child_at(a, 3)) == "c") O.remove_child(a, 2) assert(O.num_children(a) == 2 and O.identifier(O.child_at(a, 2)) == "c") O.remove_child(a, 1) assert(O.num_children(a) == 1 and O.identifier(O.child_at(a, 1)) == "c") O.pop_child(a) assert(O.num_children(a) == 0) assert(O.push_child(a, "x=") == nil) O.destroy(a) end do local a = O.create() assert( not O.is_named(a) and O.name_hash(a) == O.NAME_NULL and O.name(a) == "" ) assert(O.op(a) == O.Operator.none) assert( not O.has_source(a) and O.source(a) == 0 and O.sub_source(a) == 0 and not O.source_certain(a) and O.source_certain_or_unspecified(a) and not O.marker_source_uncertain(a) and not O.marker_sub_source_uncertain(a) ) assert( O.value_certain(a) and O.value_approximation(a) == 0 and not O.marker_value_uncertain(a) and not O.marker_value_guess(a) ) assert(O.is_null(a)) assert(not O.has_tags(a)) assert(not O.has_children(a)) assert(not O.has_quantity(a)) assert(not O.find_child(a, O.NAME_NULL)) assert(not O.find_child(a, "")) assert(not O.find_child(a, "a")) assert(not O.find_tag(a, O.NAME_NULL)) assert(not O.find_tag(a, "")) assert(not O.find_tag(a, "a")) O.destroy(a) end do local a = O.create() O.set_source(a, 1) O.set_sub_source(a, 2) assert( O.has_source(a) and O.source(a) == 1 and O.sub_source(a) == 2 and O.source_certain(a) and O.source_certain_or_unspecified(a) and not O.marker_source_uncertain(a) and not O.marker_sub_source_uncertain(a) ) O.set_source_certain(a, false) assert( not O.source_certain(a) and not O.source_certain_or_unspecified(a) and O.marker_source_uncertain(a) and not O.marker_sub_source_uncertain(a) ) O.set_sub_source_certain(a, false) assert( not O.source_certain(a) and not O.source_certain_or_unspecified(a) and O.marker_source_uncertain(a) and O.marker_sub_source_uncertain(a) ) O.clear_source(a) assert( not O.has_source(a) and O.source(a) == 0 and O.sub_source(a) == 0 and not O.source_certain(a) and O.source_certain_or_unspecified(a) and not O.marker_source_uncertain(a) and not O.marker_sub_source_uncertain(a) ) O.destroy(a) end do local a = O.create() O.set_value_certain(a, false) assert(not O.value_certain(a) and O.marker_value_uncertain(a) and not O.marker_value_guess(a)) O.set_value_guess(a, true) assert(not O.value_certain(a) and not O.marker_value_uncertain(a) and O.marker_value_guess(a)) O.set_value_certain(a, true) assert(O.value_certain(a) and not O.marker_value_uncertain(a) and not O.marker_value_guess(a)) O.set_value_approximation(a, -3) assert(not O.value_certain(a) and O.value_approximation(a) == -3) O.set_value_approximation(a, 0) assert(O.value_certain(a) and O.value_approximation(a) == 0) O.set_value_approximation(a, 3) assert(not O.value_certain(a) and O.value_approximation(a) == 3) O.clear_value_markers(a) assert( O.value_certain(a) and not O.marker_value_uncertain(a) and not O.marker_value_guess(a) and O.value_approximation(a) == 0 ) O.destroy(a) end do local a = O.create() O.set_name(a, "name") assert(O.is_named(a) and O.name(a) == "name" and O.name_hash(a) == O.hash_name("name")) O.clear_name(a) assert(not O.is_named(a) and O.name(a) == "" and O.name_hash(a) == O.NAME_NULL) O.destroy(a) end do local a = O.create() O.set_identifier(a, "brains") assert(O.identifier(a) == "brains" and O.identifier_hash(a) == O.hash_value("brains")) local q = O.make_quantity(a) O.set_integer(q, 42, "g") assert(O.integer(q) == 42) assert(O.unit(q) == "g") local c = O.push_child(a) O.set_name(c, "d") assert(O.name(c) == "d") O.set_string(c, "yum") assert(O.string(c) == "yum") assert(O.text(c) == "yum") assert(c == O.find_child(a, "d")) local t = O.push_tag(a) O.set_name(t, "leftover") assert(t == O.find_tag(a, "leftover")) O.destroy(a) end do local wow = T.temporary() -- treated as local when resolve_time() is called (from unzoned to -04:00) T.set(wow, 10,16,0) local a = O.create() O.set_time_value(a, wow) assert(O.is_zoned(a)) assert(not O.is_year_contextual(a) and not O.is_month_contextual(a)) assert(O.has_date(a) and O.has_clock(a) and O.time_type(a) == O.TimeType.date_and_clock) O.set_zoned(a, false) assert(not O.is_zoned(a)) O.set_time_type(a, O.TimeType.date) assert(O.has_date(a) and not O.has_clock(a) and O.time_type(a) == O.TimeType.date) O.set_time_type(a, O.TimeType.clock) assert(not O.has_date(a) and O.has_clock(a) and O.time_type(a) == O.TimeType.clock) T.adjust_zone_clock(wow, -4) T.Gregorian.set(wow, 1977,8,15) O.resolve_time(a, wow) assert(O.is_zoned(a)) assert(O.has_date(a) and O.has_clock(a) and O.time_type(a) == O.TimeType.date_and_clock) assert(T.compare_equal(O.time(a), wow)) O.destroy(a) end do local y, m, d local t = T.temporary() T.Gregorian.set(t, 1,10,15) local a = O.create() O.set_time_value(a, t) T.clear(t) O.set_year_contextual(a, true) T.Gregorian.set(t, 2,3,10) O.resolve_time(a, t) y, m, d = T.Gregorian.date(O.time(a)) assert(y == 2 and m == 10 and d == 15) O.set_month_contextual(a, true) -- implies contextual year T.Gregorian.set(t, 4,6,20) O.resolve_time(a, t) y, m, d = T.Gregorian.date(O.time(a)) assert(y == 4 and m == 6 and d == 15) O.destroy(a) end do local a = O.create() O.set_expression(a) assert(O.is_expression(a)) local e1 = O.push_child(a) O.set_integer(e1, 1) assert(O.op(e1) == O.Operator.none) local e2 = O.push_child(a) O.set_integer(e2, 2) O.set_op(e2, O.Operator.div) assert(O.op(e2) == O.Operator.div) O.destroy(a) end
local O = require "Quanta.Object" local T = require "Quanta.Time" require "Quanta.Time.Gregorian" function print_table(t, level) local function table_to_string(t, level) local ws = string.rep(" ", level) if t == nil then return ws .. "nil" end local output = "{\n" for k, v in pairs(t) do output = output .. ws .. " \"" .. tostring(k) .. "\" : " if type(v) == "table" then output = output .. table_to_string(v, level + 1) .. ",\n" else output = output .. tostring(v) .. ",\n" end end return output .. ws .. "}" end print(table_to_string(t, level or 0)) end -- print_table(O) do local a = O.create_mv [[ a, b ]] for i, v in O.children(a) do print(i, O.write_text_string(v, true), v) assert( (i == 1 and O.identifier(v) == "a") or (i == 2 and O.identifier(v) == "b") or false ) end assert(O.push_child(a, "c") ~= nil) assert(O.num_children(a) == 3 and O.identifier(O.child_at(a, 3)) == "c") O.remove_child(a, 2) assert(O.num_children(a) == 2 and O.identifier(O.child_at(a, 2)) == "c") O.remove_child(a, 1) assert(O.num_children(a) == 1 and O.identifier(O.child_at(a, 1)) == "c") O.pop_child(a) assert(O.num_children(a) == 0) assert(O.push_child(a, "x=") == nil) O.destroy(a) end do local a = O.create() assert( not O.is_named(a) and O.name_hash(a) == O.NAME_NULL and O.name(a) == "" ) assert(O.op(a) == O.Operator.none) assert( not O.has_source(a) and O.source(a) == 0 and O.sub_source(a) == 0 and not O.source_certain(a) and O.source_certain_or_unspecified(a) and not O.marker_source_uncertain(a) and not O.marker_sub_source_uncertain(a) ) assert( O.value_certain(a) and O.value_approximation(a) == 0 and not O.marker_value_uncertain(a) and not O.marker_value_guess(a) ) assert(O.is_null(a)) assert(not O.has_tags(a)) assert(not O.has_children(a)) assert(not O.has_quantity(a)) assert(not O.find_child(a, O.NAME_NULL)) assert(not O.find_child(a, "")) assert(not O.find_child(a, "a")) assert(not O.find_tag(a, O.NAME_NULL)) assert(not O.find_tag(a, "")) assert(not O.find_tag(a, "a")) O.destroy(a) end do local a = O.create() O.set_source(a, 1) O.set_sub_source(a, 2) assert( O.has_source(a) and O.source(a) == 1 and O.sub_source(a) == 2 and O.source_certain(a) and O.source_certain_or_unspecified(a) and not O.marker_source_uncertain(a) and not O.marker_sub_source_uncertain(a) ) O.set_source_certain(a, false) assert( not O.source_certain(a) and not O.source_certain_or_unspecified(a) and O.marker_source_uncertain(a) and not O.marker_sub_source_uncertain(a) ) O.set_sub_source_certain(a, false) assert( not O.source_certain(a) and not O.source_certain_or_unspecified(a) and O.marker_source_uncertain(a) and O.marker_sub_source_uncertain(a) ) O.clear_source(a) assert( not O.has_source(a) and O.source(a) == 0 and O.sub_source(a) == 0 and not O.source_certain(a) and O.source_certain_or_unspecified(a) and not O.marker_source_uncertain(a) and not O.marker_sub_source_uncertain(a) ) O.destroy(a) end do local a = O.create() O.set_value_certain(a, false) assert(not O.value_certain(a) and O.marker_value_uncertain(a) and not O.marker_value_guess(a)) O.set_value_guess(a, true) assert(not O.value_certain(a) and not O.marker_value_uncertain(a) and O.marker_value_guess(a)) O.set_value_certain(a, true) assert(O.value_certain(a) and not O.marker_value_uncertain(a) and not O.marker_value_guess(a)) O.set_value_approximation(a, -3) assert(not O.value_certain(a) and O.value_approximation(a) == -3) O.set_value_approximation(a, 0) assert(O.value_certain(a) and O.value_approximation(a) == 0) O.set_value_approximation(a, 3) assert(not O.value_certain(a) and O.value_approximation(a) == 3) O.clear_value_markers(a) assert( O.value_certain(a) and not O.marker_value_uncertain(a) and not O.marker_value_guess(a) and O.value_approximation(a) == 0 ) O.destroy(a) end do local a = O.create() O.set_name(a, "name") assert(O.is_named(a) and O.name(a) == "name" and O.name_hash(a) == O.hash_name("name")) O.clear_name(a) assert(not O.is_named(a) and O.name(a) == "" and O.name_hash(a) == O.NAME_NULL) O.destroy(a) end do local a = O.create() O.set_identifier(a, "brains") assert(O.identifier(a) == "brains" and O.identifier_hash(a) == O.hash_value("brains")) local q = O.make_quantity(a) O.set_integer(q, 42, "g") assert(O.integer(q) == 42) assert(O.unit(q) == "g") local c = O.push_child(a) O.set_name(c, "d") assert(O.name(c) == "d") O.set_string(c, "yum") assert(O.string(c) == "yum") assert(O.text(c) == "yum") assert(c == O.find_child(a, "d")) local t = O.push_tag(a) O.set_name(t, "leftover") assert(t == O.find_tag(a, "leftover")) O.destroy(a) end do local wow = T.temporary() -- treated as local when resolve_time() is called (from unzoned to -04:00) T.set(wow, 10,16,0) local a = O.create() O.set_time_value(a, wow) assert(O.is_zoned(a)) assert(not O.is_year_contextual(a) and not O.is_month_contextual(a)) assert(O.has_date(a) and O.has_clock(a) and O.time_type(a) == O.TimeType.date_and_clock) O.set_zoned(a, false) assert(not O.is_zoned(a)) O.set_time_type(a, O.TimeType.date) assert(O.has_date(a) and not O.has_clock(a) and O.time_type(a) == O.TimeType.date) O.set_time_type(a, O.TimeType.clock) assert(not O.has_date(a) and O.has_clock(a) and O.time_type(a) == O.TimeType.clock) T.adjust_zone_clock(wow, -4) T.G.set(wow, 1977,8,15) O.resolve_time(a, wow) assert(O.is_zoned(a)) assert(O.has_date(a) and O.has_clock(a) and O.time_type(a) == O.TimeType.date_and_clock) assert(T.compare_equal(O.time(a), wow)) O.destroy(a) end do local y, m, d local t = T.temporary() T.G.set(t, 1,10,15) local a = O.create() O.set_time_value(a, t) T.clear(t) O.set_year_contextual(a, true) T.G.set(t, 2,3,10) O.resolve_time(a, t) y, m, d = T.G.date(O.time(a)) assert(y == 2 and m == 10 and d == 15) O.set_month_contextual(a, true) -- implies contextual year T.G.set(t, 4,6,20) O.resolve_time(a, t) y, m, d = T.G.date(O.time(a)) assert(y == 4 and m == 6 and d == 15) O.destroy(a) end do local a = O.create() O.set_expression(a) assert(O.is_expression(a)) local e1 = O.push_child(a) O.set_integer(e1, 1) assert(O.op(e1) == O.Operator.none) local e2 = O.push_child(a) O.set_integer(e2, 2) O.set_op(e2, O.Operator.div) assert(O.op(e2) == O.Operator.div) O.destroy(a) end
lib/core/test/lua_interface.lua: fixed imports; tidy.
lib/core/test/lua_interface.lua: fixed imports; tidy.
Lua
mit
komiga/quanta,komiga/quanta,komiga/quanta
7d63a616fd9216ed1d60a11230b91768dbf2bd91
Interface/AddOns/RayUI/core/fonts.lua
Interface/AddOns/RayUI/core/fonts.lua
local R, L, P, G = unpack(select(2, ...)) --Import: Engine, Locales, ProfileDB, GlobalDB --Cache global variables --WoW API / Variables local GetChatWindowInfo = GetChatWindowInfo --Global variables that we don't cache, list them here for the mikk's Find Globals script -- GLOBALS: CHAT_FONT_HEIGHTS, UNIT_NAME_FONT, DAMAGE_TEXT_FONT, STANDARD_TEXT_FONT -- GLOBALS: GameTooltipHeader, SystemFont_Shadow_Large_Outline, NumberFont_OutlineThick_Mono_Small -- GLOBALS: NumberFont_Outline_Huge, NumberFont_Outline_Large, NumberFont_Outline_Med -- GLOBALS: NumberFont_Shadow_Med, NumberFont_Shadow_Small, QuestFont, QuestFont_Large -- GLOBALS: SystemFont_Large, GameFontNormalMed3, SystemFont_Shadow_Huge1, SystemFont_Med1 -- GLOBALS: SystemFont_Med3, SystemFont_OutlineThick_Huge2, SystemFont_Outline_Small -- GLOBALS: SystemFont_Shadow_Large, SystemFont_Shadow_Med1, SystemFont_Shadow_Med3 -- GLOBALS: SystemFont_Shadow_Outline_Huge2, SystemFont_Shadow_Small, SystemFont_Small -- GLOBALS: SystemFont_Tiny, Tooltip_Med, Tooltip_Small, ZoneTextString, SubZoneTextString -- GLOBALS: PVPInfoTextString, PVPArenaTextString, CombatTextFont, FriendsFont_Normal -- GLOBALS: FriendsFont_Small, FriendsFont_Large, FriendsFont_UserText -- GLOBALS: GameFontNormal, ErrorFont, SubZoneTextFont, ZoneTextFont, PVPInfoTextFont local function SetFont(obj, font, size, style, r, g, b, sr, sg, sb, sox, soy) obj:SetFont(font, size, style) if sr and sg and sb then obj:SetShadowColor(sr, sg, sb) end if sox and soy then obj:SetShadowOffset(sox, soy) end if r and g and b then obj:SetTextColor(r, g, b) elseif r then obj:SetAlpha(r) end end function R:UpdateBlizzardFonts() local NORMAL = self["media"].font local COMBAT = self["media"].dmgfont local NUMBER = self["media"].font local _, editBoxFontSize, _, _, _, _, _, _, _, _ = GetChatWindowInfo(1) CHAT_FONT_HEIGHTS = {12, 13, 14, 15, 16, 17, 18, 19, 20} UNIT_NAME_FONT = NORMAL -- NAMEPLATE_FONT = NORMAL DAMAGE_TEXT_FONT = COMBAT STANDARD_TEXT_FONT = NORMAL -- Base fonts SetFont(GameFontNormal, NORMAL, self.global.media.fontsize) -- SetFont(GameFontNormalSmall, NORMAL, self.global.media.fontsize) SetFont(GameTooltipHeader, NORMAL, self.global.media.fontsize) SetFont(NumberFont_OutlineThick_Mono_Small, NUMBER, self.global.media.fontsize, "OUTLINE") SetFont(SystemFont_Shadow_Large_Outline, NUMBER, 20, "OUTLINE") SetFont(NumberFont_Outline_Huge, NUMBER, 28, "THICKOUTLINE") SetFont(NumberFont_Outline_Large, NUMBER, 15, "OUTLINE") SetFont(NumberFont_Outline_Med, NUMBER, self.global.media.fontsize*1.1, "OUTLINE") SetFont(NumberFont_Shadow_Med, NORMAL, self.global.media.fontsize) --chat editbox uses this SetFont(NumberFont_Shadow_Small, NORMAL, self.global.media.fontsize) SetFont(QuestFont, NORMAL, self.global.media.fontsize) SetFont(ErrorFont, NORMAL, 15, "THINOUTLINE") -- Quest Progress & Errors SetFont(SubZoneTextFont, NORMAL, 26, "THINOUTLINE", nil, nil, nil, 0, 0, 0, R.mult, -R.mult) SetFont(ZoneTextFont, NORMAL, 112, "THINOUTLINE", nil, nil, nil, 0, 0, 0, R.mult, -R.mult) SetFont(PVPInfoTextFont, NORMAL, 20, "THINOUTLINE", nil, nil, nil, 0, 0, 0, R.mult, -R.mult) SetFont(QuestFont_Large, NORMAL, 14) SetFont(SystemFont_Large, NORMAL, 15) SetFont(SystemFont_Shadow_Huge1, NORMAL, 20, "THINOUTLINE") -- Raid Warning, Boss emote frame too SetFont(SystemFont_Med1, NORMAL, self.global.media.fontsize) SetFont(SystemFont_Med3, NORMAL, self.global.media.fontsize*1.1) SetFont(SystemFont_OutlineThick_Huge2, NORMAL, 20, "THICKOUTLINE") SetFont(SystemFont_Outline_Small, NUMBER, self.global.media.fontsize, "OUTLINE") SetFont(SystemFont_Shadow_Large, NORMAL, 15) SetFont(SystemFont_Shadow_Med1, NORMAL, self.global.media.fontsize) SetFont(SystemFont_Shadow_Med3, NORMAL, self.global.media.fontsize*1.1) SetFont(SystemFont_Shadow_Outline_Huge2, NORMAL, 20, "OUTLINE") SetFont(SystemFont_Shadow_Small, NORMAL, self.global.media.fontsize*0.9) SetFont(SystemFont_Small, NORMAL, self.global.media.fontsize) SetFont(SystemFont_Tiny, NORMAL, self.global.media.fontsize) SetFont(Tooltip_Med, NORMAL, self.global.media.fontsize) SetFont(Tooltip_Small, NORMAL, self.global.media.fontsize) SetFont(ZoneTextString, NORMAL, 32, "OUTLINE") SetFont(SubZoneTextString, NORMAL, 25, "OUTLINE") SetFont(PVPInfoTextString, NORMAL, 22, "THINOUTLINE") SetFont(PVPArenaTextString, NORMAL, 22, "THINOUTLINE") SetFont(CombatTextFont, COMBAT, 100, "THINOUTLINE") -- number here just increase the font quality. SetFont(FriendsFont_Normal, NORMAL, self.global.media.fontsize) SetFont(FriendsFont_Small, NORMAL, self.global.media.fontsize) SetFont(FriendsFont_Large, NORMAL, self.global.media.fontsize) SetFont(FriendsFont_UserText, NORMAL, self.global.media.fontsize) end
local R, L, P, G = unpack(select(2, ...)) --Import: Engine, Locales, ProfileDB, GlobalDB --Cache global variables --WoW API / Variables local GetChatWindowInfo = GetChatWindowInfo --Global variables that we don't cache, list them here for the mikk's Find Globals script -- GLOBALS: CHAT_FONT_HEIGHTS, UNIT_NAME_FONT, DAMAGE_TEXT_FONT, STANDARD_TEXT_FONT -- GLOBALS: GameTooltipHeader, SystemFont_Shadow_Large_Outline, NumberFont_OutlineThick_Mono_Small -- GLOBALS: NumberFont_Outline_Huge, NumberFont_Outline_Large, NumberFont_Outline_Med, GameFontHighlightMedium -- GLOBALS: NumberFont_Shadow_Med, NumberFont_Shadow_Small, QuestFont, QuestFont_Large -- GLOBALS: SystemFont_Large, GameFontNormalMed3, SystemFont_Shadow_Huge1, SystemFont_Med1 -- GLOBALS: SystemFont_Med3, SystemFont_OutlineThick_Huge2, SystemFont_Outline_Small -- GLOBALS: SystemFont_Shadow_Large, SystemFont_Shadow_Med1, SystemFont_Shadow_Med3 -- GLOBALS: SystemFont_Shadow_Outline_Huge2, SystemFont_Shadow_Small, SystemFont_Small -- GLOBALS: SystemFont_Tiny, Tooltip_Med, Tooltip_Small, ZoneTextString, SubZoneTextString -- GLOBALS: PVPInfoTextString, PVPArenaTextString, CombatTextFont, FriendsFont_Normal -- GLOBALS: FriendsFont_Small, FriendsFont_Large, FriendsFont_UserText local function SetFont(obj, font, size, style, r, g, b, sr, sg, sb, sox, soy) obj:SetFont(font, size, style) if sr and sg and sb then obj:SetShadowColor(sr, sg, sb) end if sox and soy then obj:SetShadowOffset(sox, soy) end if r and g and b then obj:SetTextColor(r, g, b) elseif r then obj:SetAlpha(r) end end function R:UpdateBlizzardFonts() local NORMAL = self["media"].font local COMBAT = self["media"].dmgfont local NUMBER = self["media"].font local _, editBoxFontSize, _, _, _, _, _, _, _, _ = GetChatWindowInfo(1) CHAT_FONT_HEIGHTS = {12, 13, 14, 15, 16, 17, 18, 19, 20} UNIT_NAME_FONT = NORMAL -- NAMEPLATE_FONT = NORMAL DAMAGE_TEXT_FONT = COMBAT STANDARD_TEXT_FONT = NORMAL -- Base fonts SetFont(GameTooltipHeader, NORMAL, self.global.media.fontsize) SetFont(NumberFont_OutlineThick_Mono_Small, NUMBER, self.global.media.fontsize, "OUTLINE") SetFont(SystemFont_Shadow_Large_Outline, NUMBER, 20, "OUTLINE") SetFont(NumberFont_Outline_Huge, NUMBER, 28, "THICKOUTLINE") SetFont(NumberFont_Outline_Large, NUMBER, 15, "OUTLINE") SetFont(NumberFont_Outline_Med, NUMBER, self.global.media.fontsize*1.1, "OUTLINE") SetFont(NumberFont_Shadow_Med, NORMAL, self.global.media.fontsize) --chat editbox uses this SetFont(NumberFont_Shadow_Small, NORMAL, self.global.media.fontsize) SetFont(QuestFont, NORMAL, self.global.media.fontsize) SetFont(QuestFont_Large, NORMAL, 14) SetFont(SystemFont_Large, NORMAL, 15) SetFont(GameFontNormalMed3, NORMAL, 15) SetFont(GameFontHighlightMedium, NORMAL, 15) SetFont(SystemFont_Shadow_Huge1, NORMAL, 20, "THINOUTLINE") -- Raid Warning, Boss emote frame too SetFont(SystemFont_Med1, NORMAL, self.global.media.fontsize) SetFont(SystemFont_Med3, NORMAL, self.global.media.fontsize*1.1) SetFont(SystemFont_OutlineThick_Huge2, NORMAL, 20, "THICKOUTLINE") SetFont(SystemFont_Outline_Small, NUMBER, self.global.media.fontsize, "OUTLINE") SetFont(SystemFont_Shadow_Large, NORMAL, 15) SetFont(SystemFont_Shadow_Med1, NORMAL, self.global.media.fontsize) SetFont(SystemFont_Shadow_Med3, NORMAL, self.global.media.fontsize*1.1) SetFont(SystemFont_Shadow_Outline_Huge2, NORMAL, 20, "OUTLINE") SetFont(SystemFont_Shadow_Small, NORMAL, self.global.media.fontsize*0.9) SetFont(SystemFont_Small, NORMAL, self.global.media.fontsize) SetFont(SystemFont_Tiny, NORMAL, self.global.media.fontsize) SetFont(Tooltip_Med, NORMAL, self.global.media.fontsize) SetFont(Tooltip_Small, NORMAL, self.global.media.fontsize) SetFont(ZoneTextString, NORMAL, 32, "OUTLINE") SetFont(SubZoneTextString, NORMAL, 25, "OUTLINE") SetFont(PVPInfoTextString, NORMAL, 22, "THINOUTLINE") SetFont(PVPArenaTextString, NORMAL, 22, "THINOUTLINE") SetFont(CombatTextFont, COMBAT, 100, "THINOUTLINE") -- number here just increase the font quality. SetFont(FriendsFont_Normal, NORMAL, self.global.media.fontsize) SetFont(FriendsFont_Small, NORMAL, self.global.media.fontsize) SetFont(FriendsFont_Large, NORMAL, self.global.media.fontsize) SetFont(FriendsFont_UserText, NORMAL, self.global.media.fontsize) end
fixed #68
fixed #68
Lua
mit
fgprodigal/RayUI
b91cfbb9e80e4330be5b9dc307d721513bbd462a
packages/image/init.lua
packages/image/init.lua
local base = require("packages.base") local package = pl.class(base) package._name = "image" function package:registerCommands () self:registerCommand("img", function (options, _) SU.required(options, "src", "including image file") local width = SILE.parseComplexFrameDimension(options.width or 0) or 0 local height = SILE.parseComplexFrameDimension(options.height or 0) or 0 local pageno = SU.cast("integer", options.page or 1) local src = SILE.resolveFile(options.src) or SU.error("Couldn't find file "..options.src) local box_width, box_height, _, _ = SILE.outputter:getImageSize(src, pageno) local sx, sy = 1, 1 if width > 0 or height > 0 then sx = width > 0 and box_width / width sy = height > 0 and box_height / height sx = sx or sy sy = sy or sx end SILE.typesetter:pushHbox({ width= box_width / (sx), height= box_height / (sy), depth= 0, value= src, outputYourself = function (node, typesetter, _) SILE.outputter:drawImage(node.value, typesetter.frame.state.cursorX, typesetter.frame.state.cursorY-node.height, node.width, node.height, pageno) typesetter.frame:advanceWritingDirection(node.width) end}) end, "Inserts the image specified with the <src> option in a box of size <width> by <height>") end package.documentation = [[ \begin{document} As well as processing text, SILE can also include images. Loading the \autodoc:package{image} package gives you the \autodoc:command{\img} command, fashioned after the HTML equivalent. It takes the following parameters: \autodoc:parameter{src=<file>} must be the path to an image file; you may also give \autodoc:parameter{height} and/or \autodoc:parameter{width} parameters to specify the output size of the image on the paper. If the size parameters are not given, then the image will be output at its ‘natural’ size, honoring its resolution if available. The command also supports a \autodoc:parameter{page=<number>} option, to specify the selected page in formats supporting several pages (such as PDF). \begin{note} With the libtexpdf backend (the default), the images can be in JPEG, PNG, EPS or PDF formats. \end{note} Here is a 200x243 pixel image output with \autodoc:command{\img[src=documentation/gutenberg.png]}. The image has a claimed resolution of 100 pixels per inch, so ends up being 2 inches (144pt) wide on the page:\par \img[src=documentation/gutenberg.png] \raggedright{ Here it is with (respectively) \autodoc:command{\img[src=documentation/gutenberg.png,width=120pt]}, \autodoc:command{\img[src=documentation/gutenberg.png,height=200pt]}, and \autodoc:command{\img[src=documentation/gutenberg.png,width=120pt,height=200pt]}:} \img[src=documentation/gutenberg.png,width=120pt] \img[src=documentation/gutenberg.png,height=200pt] \img[src=documentation/gutenberg.png,width=120pt,height=200pt] Notice that images are typeset on the baseline of a line of text, rather like a very big letter. \end{document} ]] return package
local base = require("packages.base") local package = pl.class(base) package._name = "image" function package:registerCommands () self:registerCommand("img", function (options, _) SU.required(options, "src", "including image file") local width = SU.cast("measurement", options.width or 0):tonumber() local height = SU.cast("measurement", options.height or 0):tonumber() local pageno = SU.cast("integer", options.page or 1) local src = SILE.resolveFile(options.src) or SU.error("Couldn't find file "..options.src) local box_width, box_height, _, _ = SILE.outputter:getImageSize(src, pageno) local sx, sy = 1, 1 if width > 0 or height > 0 then sx = width > 0 and box_width / width sy = height > 0 and box_height / height sx = sx or sy sy = sy or sx end SILE.typesetter:pushHbox({ width= box_width / (sx), height= box_height / (sy), depth= 0, value= src, outputYourself = function (node, typesetter, _) SILE.outputter:drawImage(node.value, typesetter.frame.state.cursorX, typesetter.frame.state.cursorY-node.height, node.width, node.height, pageno) typesetter.frame:advanceWritingDirection(node.width) end}) end, "Inserts the image specified with the <src> option in a box of size <width> by <height>") end package.documentation = [[ \begin{document} As well as processing text, SILE can also include images. Loading the \autodoc:package{image} package gives you the \autodoc:command{\img} command, fashioned after the HTML equivalent. It takes the following parameters: \autodoc:parameter{src=<file>} must be the path to an image file; you may also give \autodoc:parameter{height} and/or \autodoc:parameter{width} parameters to specify the output size of the image on the paper. If the size parameters are not given, then the image will be output at its ‘natural’ size, honoring its resolution if available. The command also supports a \autodoc:parameter{page=<number>} option, to specify the selected page in formats supporting several pages (such as PDF). \begin{note} With the libtexpdf backend (the default), the images can be in JPEG, PNG, EPS or PDF formats. \end{note} Here is a 200x243 pixel image output with \autodoc:command{\img[src=documentation/gutenberg.png]}. The image has a claimed resolution of 100 pixels per inch, so ends up being 2 inches (144pt) wide on the page:\par \img[src=documentation/gutenberg.png] \raggedright{ Here it is with (respectively) \autodoc:command{\img[src=documentation/gutenberg.png,width=120pt]}, \autodoc:command{\img[src=documentation/gutenberg.png,height=200pt]}, and \autodoc:command{\img[src=documentation/gutenberg.png,width=120pt,height=200pt]}:} \img[src=documentation/gutenberg.png,width=120pt] \img[src=documentation/gutenberg.png,height=200pt] \img[src=documentation/gutenberg.png,width=120pt,height=200pt] Notice that images are typeset on the baseline of a line of text, rather like a very big letter. \end{document} ]] return package
fix(packages): Homogenize image width and height as measurements
fix(packages): Homogenize image width and height as measurements As @alerque in #1506 (raiselower package): It used an old method that predates our SILE.length / SILE.measurement logic and units like `%fh` that are relative to the frame or page. It was being parsed as a frame dimension, which I assume was just a way to get user friendly string input and perhaps some expressiveness. I couldn't actually think of a use case for making this a full frame string and not accepting our standardized measurement types comes with lots of downfalls especially in programmatic usage. I'm not marking this as breaking because in most cases I think the new behavior will be expected and I doubt the edge cases where they differ are seeing much use.
Lua
mit
alerque/sile,alerque/sile,alerque/sile,alerque/sile
01c76f761ba290b7cf57fb29220593ff7739a710
kong/plugins/rate-limiting/handler.lua
kong/plugins/rate-limiting/handler.lua
-- Copyright (C) Kong Inc. local timestamp = require "kong.tools.timestamp" local policies = require "kong.plugins.rate-limiting.policies" local kong = kong local ngx = ngx local max = math.max local time = ngx.time local floor = math.floor local pairs = pairs local error = error local tostring = tostring local timer_at = ngx.timer.at local EMPTY = {} local EXPIRATION = require "kong.plugins.rate-limiting.expiration" local RATELIMIT_LIMIT = "RateLimit-Limit" local RATELIMIT_REMAINING = "RateLimit-Remaining" local RATELIMIT_RESET = "RateLimit-Reset" local RETRY_AFTER = "Retry-After" local X_RATELIMIT_LIMIT = { second = "X-RateLimit-Limit-Second", minute = "X-RateLimit-Limit-Minute", hour = "X-RateLimit-Limit-Hour", day = "X-RateLimit-Limit-Day", month = "X-RateLimit-Limit-Month", year = "X-RateLimit-Limit-Year", } local X_RATELIMIT_REMAINING = { second = "X-RateLimit-Remaining-Second", minute = "X-RateLimit-Remaining-Minute", hour = "X-RateLimit-Remaining-Hour", day = "X-RateLimit-Remaining-Day", month = "X-RateLimit-Remaining-Month", year = "X-RateLimit-Remaining-Year", } local RateLimitingHandler = {} RateLimitingHandler.PRIORITY = 901 RateLimitingHandler.VERSION = "2.2.0" local function get_identifier(conf) local identifier if conf.limit_by == "service" then identifier = (kong.router.get_service() or EMPTY).id elseif conf.limit_by == "consumer" then identifier = (kong.client.get_consumer() or kong.client.get_credential() or EMPTY).id elseif conf.limit_by == "credential" then identifier = (kong.client.get_credential() or EMPTY).id elseif conf.limit_by == "header" then identifier = kong.request.get_header(conf.header_name) elseif conf.limit_by == "path" then local req_path = kong.request.get_path() if req_path == conf.path then identifier = req_path end end return identifier or kong.client.get_forwarded_ip() end local function get_usage(conf, identifier, current_timestamp, limits) local usage = {} local stop for period, limit in pairs(limits) do local current_usage, err = policies[conf.policy].usage(conf, identifier, period, current_timestamp) if err then return nil, nil, err end -- What is the current usage for the configured limit name? local remaining = limit - current_usage -- Recording usage usage[period] = { limit = limit, remaining = remaining, } if remaining <= 0 then stop = period end end return usage, stop end local function increment(premature, conf, ...) if premature then return end policies[conf.policy].increment(conf, ...) end function RateLimitingHandler:access(conf) local current_timestamp = time() * 1000 -- Consumer is identified by ip address or authenticated_credential id local identifier = get_identifier(conf) local fault_tolerant = conf.fault_tolerant -- Load current metric for configured period local limits = { second = conf.second, minute = conf.minute, hour = conf.hour, day = conf.day, month = conf.month, year = conf.year, } local usage, stop, err = get_usage(conf, identifier, current_timestamp, limits) if err then if not fault_tolerant then return error(err) end kong.log.err("failed to get usage: ", tostring(err)) end if usage then -- Adding headers local reset if not conf.hide_client_headers then local headers = {} local timestamps local limit local window local remaining for k, v in pairs(usage) do local current_limit = v.limit local current_window = EXPIRATION[k] local current_remaining = v.remaining if stop == nil or stop == k then current_remaining = current_remaining - 1 end current_remaining = max(0, current_remaining) if not limit or (current_remaining < remaining) or (current_remaining == remaining and current_window > window) then limit = current_limit window = current_window remaining = current_remaining if not timestamps then timestamps = timestamp.get_timestamps(current_timestamp) end reset = max(1, window - floor((current_timestamp - timestamps[k]) / 1000)) end headers[X_RATELIMIT_LIMIT[k]] = current_limit headers[X_RATELIMIT_REMAINING[k]] = current_remaining end headers[RATELIMIT_LIMIT] = limit headers[RATELIMIT_REMAINING] = remaining headers[RATELIMIT_RESET] = reset kong.ctx.plugin.headers = headers end -- If limit is exceeded, terminate the request if stop then return kong.response.error(429, "API rate limit exceeded", { [RETRY_AFTER] = reset }) end end kong.ctx.plugin.timer = function() local ok, err = timer_at(0, increment, conf, limits, identifier, current_timestamp, 1) if not ok then kong.log.err("failed to create timer: ", err) end end end function RateLimitingHandler:header_filter(_) local headers = kong.ctx.plugin.headers if headers then kong.response.set_headers(headers) end end function RateLimitingHandler:log(_) if kong.ctx.plugin.timer then kong.ctx.plugin.timer() end end return RateLimitingHandler
-- Copyright (C) Kong Inc. local timestamp = require "kong.tools.timestamp" local policies = require "kong.plugins.rate-limiting.policies" local kong = kong local ngx = ngx local max = math.max local time = ngx.time local floor = math.floor local pairs = pairs local error = error local tostring = tostring local timer_at = ngx.timer.at local EMPTY = {} local EXPIRATION = require "kong.plugins.rate-limiting.expiration" local RATELIMIT_LIMIT = "RateLimit-Limit" local RATELIMIT_REMAINING = "RateLimit-Remaining" local RATELIMIT_RESET = "RateLimit-Reset" local RETRY_AFTER = "Retry-After" local X_RATELIMIT_LIMIT = { second = "X-RateLimit-Limit-Second", minute = "X-RateLimit-Limit-Minute", hour = "X-RateLimit-Limit-Hour", day = "X-RateLimit-Limit-Day", month = "X-RateLimit-Limit-Month", year = "X-RateLimit-Limit-Year", } local X_RATELIMIT_REMAINING = { second = "X-RateLimit-Remaining-Second", minute = "X-RateLimit-Remaining-Minute", hour = "X-RateLimit-Remaining-Hour", day = "X-RateLimit-Remaining-Day", month = "X-RateLimit-Remaining-Month", year = "X-RateLimit-Remaining-Year", } local RateLimitingHandler = {} RateLimitingHandler.PRIORITY = 901 RateLimitingHandler.VERSION = "2.2.1" local function get_identifier(conf) local identifier if conf.limit_by == "service" then identifier = (kong.router.get_service() or EMPTY).id elseif conf.limit_by == "consumer" then identifier = (kong.client.get_consumer() or kong.client.get_credential() or EMPTY).id elseif conf.limit_by == "credential" then identifier = (kong.client.get_credential() or EMPTY).id elseif conf.limit_by == "header" then identifier = kong.request.get_header(conf.header_name) elseif conf.limit_by == "path" then local req_path = kong.request.get_path() if req_path == conf.path then identifier = req_path end end return identifier or kong.client.get_forwarded_ip() end local function get_usage(conf, identifier, current_timestamp, limits) local usage = {} local stop for period, limit in pairs(limits) do local current_usage, err = policies[conf.policy].usage(conf, identifier, period, current_timestamp) if err then return nil, nil, err end -- What is the current usage for the configured limit name? local remaining = limit - current_usage -- Recording usage usage[period] = { limit = limit, remaining = remaining, } if remaining <= 0 then stop = period end end return usage, stop end local function increment(premature, conf, ...) if premature then return end policies[conf.policy].increment(conf, ...) end function RateLimitingHandler:access(conf) local current_timestamp = time() * 1000 -- Consumer is identified by ip address or authenticated_credential id local identifier = get_identifier(conf) local fault_tolerant = conf.fault_tolerant -- Load current metric for configured period local limits = { second = conf.second, minute = conf.minute, hour = conf.hour, day = conf.day, month = conf.month, year = conf.year, } local usage, stop, err = get_usage(conf, identifier, current_timestamp, limits) if err then if not fault_tolerant then return error(err) end kong.log.err("failed to get usage: ", tostring(err)) end if usage then -- Adding headers local reset local headers if not conf.hide_client_headers then headers = {} local timestamps local limit local window local remaining for k, v in pairs(usage) do local current_limit = v.limit local current_window = EXPIRATION[k] local current_remaining = v.remaining if stop == nil or stop == k then current_remaining = current_remaining - 1 end current_remaining = max(0, current_remaining) if not limit or (current_remaining < remaining) or (current_remaining == remaining and current_window > window) then limit = current_limit window = current_window remaining = current_remaining if not timestamps then timestamps = timestamp.get_timestamps(current_timestamp) end reset = max(1, window - floor((current_timestamp - timestamps[k]) / 1000)) end headers[X_RATELIMIT_LIMIT[k]] = current_limit headers[X_RATELIMIT_REMAINING[k]] = current_remaining end headers[RATELIMIT_LIMIT] = limit headers[RATELIMIT_REMAINING] = remaining headers[RATELIMIT_RESET] = reset end -- If limit is exceeded, terminate the request if stop then headers = headers or {} headers[RETRY_AFTER] = reset return kong.response.error(429, "API rate limit exceeded", headers) end if headers then kong.response.set_headers(headers) end end local ok, err = timer_at(0, increment, conf, limits, identifier, current_timestamp, 1) if not ok then kong.log.err("failed to create timer: ", err) end end return RateLimitingHandler
fix(rate-limiting) remove unneeded phase handlers for better accuracy (#6802)
fix(rate-limiting) remove unneeded phase handlers for better accuracy (#6802) ### Summary The PR #5460 tried to fix rate-limiting accuracy issues as reported with #5311. That PR has stayed open for over a year now. There is a smaller change in that PR that we can make without a lot of work or debating, and this PR contains that only: 1. it removes extra phase handlers and context passing of data and now does everything in `access` phase (this could make it more accurate as well, compared to post-poning that to log phase) 2. it now also sets rate-limiting headers when the limits have exceeded
Lua
apache-2.0
Kong/kong,Kong/kong,Kong/kong
a50106fad7630244ad26e78bbf697f122702eca7
lua/entities/gmod_wire_adv_emarker.lua
lua/entities/gmod_wire_adv_emarker.lua
AddCSLuaFile() DEFINE_BASECLASS( "base_wire_entity" ) ENT.PrintName = "Adv Wire Entity Marker" ENT.Author = "Divran" ENT.WireDebugName = "Adv EMarker" if CLIENT then return end -- No more client function ENT:Initialize() self:PhysicsInit( SOLID_VPHYSICS ) self:SetMoveType( MOVETYPE_VPHYSICS ) self:SetSolid( SOLID_VPHYSICS ) self.Marks = {} local outputs = {"Entities [ARRAY]", "Nr"} for i=3,12 do outputs[i] = "Entity" .. (i-2) .. " [ENTITY]" end self.Inputs = WireLib.CreateInputs( self, { "Entity [ENTITY]", "Add Entity", "Remove Entity", "Clear Entities" } ) self.Outputs = WireLib.CreateOutputs( self, outputs ) self:SetOverlayText( "Number of entities linked: 0" ) end function ENT:TriggerInput( name, value ) if (name == "Entity") then if IsValid(value) then self.Target = value end elseif (name == "Add Entity") then if IsValid(self.Target) then if (value != 0) then local bool, index = self:CheckEnt( self.Target ) if (!bool) then self:LinkEnt( self.Target ) end end end elseif (name == "Remove Entity") then if IsValid(self.Target) then if (value != 0) then local bool, index = self:CheckEnt( self.Target ) if (bool) then self:UnlinkEnt( self.Target ) end end end elseif (name == "Clear Entities") then self:ClearEntities() end end function ENT:UpdateOutputs() -- Trigger regular outputs WireLib.TriggerOutput( self, "Entities", self.Marks ) WireLib.TriggerOutput( self, "Nr", #self.Marks ) -- Trigger special outputs for i=3,12 do WireLib.TriggerOutput( self, "Entity" .. (i-2), self.Marks[i-2] ) end -- Overlay text self:SetOverlayText( "Number of entities linked: " .. #self.Marks ) -- Yellow lines information WireLib.SendMarks(self) end function ENT:CheckEnt( ent ) if IsValid(ent) then for index, e in pairs( self.Marks ) do if (e == ent) then return true, index end end end return false, 0 end function ENT:LinkEnt( ent ) if (self:CheckEnt( ent )) then return false end self.Marks[#self.Marks+1] = ent ent:CallOnRemove("AdvEMarker.Unlink", function(ent) if IsValid(self) then self:UnlinkEnt(ent) end end) self:UpdateOutputs() return true end function ENT:UnlinkEnt( ent ) local bool, index = self:CheckEnt( ent ) if (bool) then table.remove( self.Marks, index ) self:UpdateOutputs() end return bool end function ENT:ClearEntities() self.Marks = {} self:UpdateOutputs() end duplicator.RegisterEntityClass( "gmod_wire_adv_emarker", WireLib.MakeWireEnt, "Data" ) function ENT:BuildDupeInfo() local info = self.BaseClass.BuildDupeInfo(self) or {} if next(self.Marks) then local tbl = {} for index, e in pairs( self.Marks ) do tbl[index] = e:EntIndex() end info.marks = tbl end return info end function ENT:ApplyDupeInfo(ply, ent, info, GetEntByID) self.BaseClass.ApplyDupeInfo(self, ply, ent, info, GetEntByID) if (info.marks) then self.Marks = self.Marks or {} for index, entindex in pairs(info.marks) do self.Marks[index] = GetEntByID(entindex) end self:UpdateOutputs() end end
AddCSLuaFile() DEFINE_BASECLASS( "base_wire_entity" ) ENT.PrintName = "Adv Wire Entity Marker" ENT.Author = "Divran" ENT.WireDebugName = "Adv EMarker" if CLIENT then return end -- No more client function ENT:Initialize() self:PhysicsInit( SOLID_VPHYSICS ) self:SetMoveType( MOVETYPE_VPHYSICS ) self:SetSolid( SOLID_VPHYSICS ) self.Marks = {} local outputs = {"Entities [ARRAY]", "Nr"} for i=3,12 do outputs[i] = "Entity" .. (i-2) .. " [ENTITY]" end self.Inputs = WireLib.CreateInputs( self, { "Entity [ENTITY]", "Add Entity", "Remove Entity", "Clear Entities" } ) self.Outputs = WireLib.CreateOutputs( self, outputs ) self:SetOverlayText( "Number of entities linked: 0" ) end function ENT:TriggerInput( name, value ) if (name == "Entity") then if IsValid(value) then self.Target = value end elseif (name == "Add Entity") then if IsValid(self.Target) then if (value != 0) then local bool, index = self:CheckEnt( self.Target ) if (!bool) then self:LinkEnt( self.Target ) end end end elseif (name == "Remove Entity") then if IsValid(self.Target) then if (value != 0) then local bool, index = self:CheckEnt( self.Target ) if (bool) then self:UnlinkEnt( self.Target ) end end end elseif (name == "Clear Entities") then self:ClearEntities() end end function ENT:UpdateOutputs() -- Trigger regular outputs WireLib.TriggerOutput( self, "Entities", self.Marks ) WireLib.TriggerOutput( self, "Nr", #self.Marks ) -- Trigger special outputs for i=3,12 do WireLib.TriggerOutput( self, "Entity" .. (i-2), self.Marks[i-2] ) end -- Overlay text self:SetOverlayText( "Number of entities linked: " .. #self.Marks ) -- Yellow lines information WireLib.SendMarks(self) end function ENT:CheckEnt( ent ) if IsValid(ent) then for index, e in pairs( self.Marks ) do if (e == ent) then return true, index end end end return false, 0 end function ENT:LinkEnt( ent ) if (self:CheckEnt( ent )) then return false end self.Marks[#self.Marks+1] = ent ent:CallOnRemove("AdvEMarker.Unlink", function(ent) if IsValid(self) then self:UnlinkEnt(ent) end end) self:UpdateOutputs() return true end function ENT:UnlinkEnt( ent ) local bool, index = self:CheckEnt( ent ) if (bool) then table.remove( self.Marks, index ) self:UpdateOutputs() end return bool end function ENT:ClearEntities() self.Marks = {} self:UpdateOutputs() end duplicator.RegisterEntityClass( "gmod_wire_adv_emarker", WireLib.MakeWireEnt, "Data" ) function ENT:BuildDupeInfo() local info = self.BaseClass.BuildDupeInfo(self) or {} if next(self.Marks) then local tbl = {} for index, e in pairs( self.Marks ) do tbl[index] = e:EntIndex() end info.marks = tbl end return info end function ENT:ApplyDupeInfo(ply, ent, info, GetEntByID) self.BaseClass.ApplyDupeInfo(self, ply, ent, info, GetEntByID) if (info.marks) then self.Marks = self.Marks or {} for index, entindex in pairs(info.marks) do self.Marks[index] = GetEntByID(entindex) ent:CallOnRemove("AdvEMarker.Unlink", function(ent) if IsValid(self) then self:UnlinkEnt(ent) end end) end self:UpdateOutputs() end end
Fix #528. Fix adv. emarker duplication issue.
Fix #528. Fix adv. emarker duplication issue.
Lua
apache-2.0
mms92/wire,plinkopenguin/wiremod,Grocel/wire,sammyt291/wire,bigdogmat/wire,garrysmodlua/wire,CaptainPRICE/wire,dvdvideo1234/wire,NezzKryptic/Wire,immibis/wiremod,rafradek/wire,notcake/wire,mitterdoo/wire,Python1320/wire,wiremod/wire,thegrb93/wire
5f0add7ebd77ef8b42e48594f81298aea4a13389
data/pipelines/fxaa.lua
data/pipelines/fxaa.lua
function postprocess(env, transparent_phase, ldr_buffer, gbuffer0, gbuffer1, gbuffer_depth, shadowmap) if not enabled then return ldr_buffer end if transparent_phase ~= "post_tonemap" then return ldr_buffer end local format = "rgba8" if env.SCENE_VIEW ~= nil then format = "rgba16f" end local res = env.createRenderbuffer { width = env.viewport_w, height = env.viewport_h, format = "rgba8", debug_name = "fxaa" } env.beginBlock("fxaa") if env.fxaa_shader == nil then env.fxaa_shader = env.preloadShader("pipelines/fxaa.shd") end env.setRenderTargets(res) env.drawArray(0, 3, env.fxaa_shader, { ldr_buffer }, { depth_test = false, blending = ""} ) env.endBlock() return res end function awake() _G["postprocesses"] = _G["postprocesses"] or {} _G["postprocesses"]["fxaa"] = postprocess end function onDestroy() _G["postprocesses"]["fxaa"] = nil end
function postprocess(env, transparent_phase, ldr_buffer, gbuffer0, gbuffer1, gbuffer_depth, shadowmap) if not enabled then return ldr_buffer end if transparent_phase ~= "post_tonemap" then return ldr_buffer end local format = "rgba16f" if env.APP ~= nil or env.PREVIEW ~= nil then format = "rgba8" end local res = env.createRenderbuffer { width = env.viewport_w, height = env.viewport_h, format = format, debug_name = "fxaa" } env.beginBlock("fxaa") if env.fxaa_shader == nil then env.fxaa_shader = env.preloadShader("pipelines/fxaa.shd") end env.setRenderTargets(res) env.drawArray(0, 3, env.fxaa_shader, { ldr_buffer }, { depth_test = false, blending = ""} ) env.endBlock() return res end function awake() _G["postprocesses"] = _G["postprocesses"] or {} _G["postprocesses"]["fxaa"] = postprocess end function onDestroy() _G["postprocesses"]["fxaa"] = nil end
fixed fxaa colors again - #1285
fixed fxaa colors again - #1285
Lua
mit
nem0/LumixEngine,nem0/LumixEngine,nem0/LumixEngine
1fd07bdbbf59c77c9a668692d322977117ef783d
Bin/Data/LuaScripts/14_SoundEffects.lua
Bin/Data/LuaScripts/14_SoundEffects.lua
-- Sound effects example -- This sample demonstrates: -- - Playing sound effects and music -- - Controlling sound and music master volume require "LuaScripts/Utilities/Sample" local scene_ = nil local soundNames = { "Fist", "Explosion", "Power-up" } local soundResourceNames = { "Sounds/PlayerFistHit.wav", "Sounds/BigExplosion.wav", "Sounds/Powerup.wav" } function Start() -- Execute the common startup for samples SampleStart() -- Enable OS cursor input.mouseVisible = true -- Create the user interface CreateUI() end function CreateUI() -- Create a scene which will not be actually rendered, but is used to hold SoundSource components while they play sounds scene_ = Scene() local uiStyle = cache:GetResource("XMLFile", "UI/DefaultStyle.xml") -- Set style to the UI root so that elements will inherit it ui.root.defaultStyle = uiStyle -- Create buttons for playing back sounds for i, v in ipairs(soundNames) do local button = CreateButton((i - 1) * 140 + 20, 20, 120, 40, v) -- Store the sound effect resource name as a custom variable into the button --button:SetVar("SoundResource", soundResourceNames[i]) button["SoundResource"] = soundResourceNames[i] SubscribeToEvent(button, "Pressed", "HandlePlaySound") end -- Create buttons for playing/stopping music local button = CreateButton(20, 80, 120, 40, "Play Music") SubscribeToEvent(button, "Released", "HandlePlayMusic") button = CreateButton(160, 80, 120, 40, "Stop Music") SubscribeToEvent(button, "Released", "HandleStopMusic") -- Create sliders for controlling sound and music master volume local slider = CreateSlider(20, 140, 200, 20, "Sound Volume") slider.value = audio:GetMasterGain(SOUND_EFFECT) SubscribeToEvent(slider, "SliderChanged", "HandleSoundVolume") slider = CreateSlider(20, 200, 200, 20, "Music Volume") slider.value = audio:GetMasterGain(SOUND_MUSIC) SubscribeToEvent(slider, "SliderChanged", "HandleMusicVolume") end function CreateButton(x, y, xSize, ySize, text) local font = cache:GetResource("Font", "Fonts/Anonymous Pro.ttf") -- Create the button and center the text onto it local button = ui.root:CreateChild("Button") button:SetStyleAuto() button:SetPosition(x, y) button:SetSize(xSize, ySize) local buttonText = button:CreateChild("Text") buttonText:SetAlignment(HA_CENTER, VA_CENTER) buttonText:SetFont(font, 12) buttonText:SetText(text) return button end function CreateSlider(x, y, xSize, ySize, text) local font = cache:GetResource("Font", "Fonts/Anonymous Pro.ttf") -- Create text and slider below it local sliderText = ui.root:CreateChild("Text") sliderText:SetPosition(x, y) sliderText:SetFont(font, 12) sliderText:SetText(text) local slider = ui.root:CreateChild("Slider") slider:SetStyleAuto() slider:SetPosition(x, y + 20) slider:SetSize(xSize, ySize) -- Use 0-1 range for controlling sound/music master volume slider.range = 1.0 return slider end function HandlePlaySound(sender, eventType, eventData) local button = tolua.cast(GetEventSender(), "Button") --local soundResourceName = button:GetVar("SoundResource"):GetString() local soundResourceName = button["SoundResource"] -- Get the sound resource local sound = cache:GetResource("Sound", soundResourceName) if sound ~= nil then -- Create a scene node with a SoundSource component for playing the sound. The SoundSource component plays -- non-positional audio, so its 3D position in the scene does not matter. For positional sounds the -- SoundSource3D component would be used instead local soundNode = scene_:CreateChild("Sound") local soundSource = soundNode:CreateComponent("SoundSource") soundSource:Play(sound) -- In case we also play music, set the sound volume below maximum so that we don't clip the output soundSource.gain = 0.7 -- Set the sound component to automatically remove its scene node from the scene when the sound is done playing soundSource.autoRemove = true end end function HandlePlayMusic(eventType, eventData) -- Check if the music player node/component already exist if scene_:GetChild("Music") ~= nil then return end local music = cache:GetResource("Sound", "Music/Ninja Gods.ogg") -- Set the song to loop music.looped = true -- Create a scene node and a sound source for the music local musicNode = scene_:CreateChild("Music") local musicSource = musicNode:CreateComponent("SoundSource") -- Set the sound type to music so that master volume control works correctly musicSource.soundType = SOUND_MUSIC musicSource:Play(music) end function HandleStopMusic(eventType, eventData) -- Remove the music player node from the scene scene_:RemoveChild(scene_:GetChild("Music")) end function HandleSoundVolume(eventType, eventData) local newVolume = eventData:GetFloat("Value") audio:SetMasterGain(SOUND_EFFECT, newVolume) end function HandleMusicVolume(eventType, eventData) local newVolume = eventData:GetFloat("Value") audio:SetMasterGain(SOUND_MUSIC, newVolume) end
-- Sound effects example -- This sample demonstrates: -- - Playing sound effects and music -- - Controlling sound and music master volume require "LuaScripts/Utilities/Sample" local scene_ = nil local soundNames = { "Fist", "Explosion", "Power-up" } local soundResourceNames = { "Sounds/PlayerFistHit.wav", "Sounds/BigExplosion.wav", "Sounds/Powerup.wav" } function Start() -- Execute the common startup for samples SampleStart() -- Enable OS cursor input.mouseVisible = true -- Create the user interface CreateUI() end function CreateUI() -- Create a scene which will not be actually rendered, but is used to hold SoundSource components while they play sounds scene_ = Scene() local uiStyle = cache:GetResource("XMLFile", "UI/DefaultStyle.xml") -- Set style to the UI root so that elements will inherit it ui.root.defaultStyle = uiStyle -- Create buttons for playing back sounds for i, v in ipairs(soundNames) do local button = CreateButton((i - 1) * 140 + 20, 20, 120, 40, v) -- Store the sound effect resource name as a custom variable into the button button:SetVar(ShortStringHash("SoundResource"), Variant(soundResourceNames[i])) SubscribeToEvent(button, "Pressed", "HandlePlaySound") end -- Create buttons for playing/stopping music local button = CreateButton(20, 80, 120, 40, "Play Music") SubscribeToEvent(button, "Released", "HandlePlayMusic") button = CreateButton(160, 80, 120, 40, "Stop Music") SubscribeToEvent(button, "Released", "HandleStopMusic") -- Create sliders for controlling sound and music master volume local slider = CreateSlider(20, 140, 200, 20, "Sound Volume") slider.value = audio:GetMasterGain(SOUND_EFFECT) SubscribeToEvent(slider, "SliderChanged", "HandleSoundVolume") slider = CreateSlider(20, 200, 200, 20, "Music Volume") slider.value = audio:GetMasterGain(SOUND_MUSIC) SubscribeToEvent(slider, "SliderChanged", "HandleMusicVolume") end function CreateButton(x, y, xSize, ySize, text) local font = cache:GetResource("Font", "Fonts/Anonymous Pro.ttf") -- Create the button and center the text onto it local button = ui.root:CreateChild("Button") button:SetStyleAuto() button:SetPosition(x, y) button:SetSize(xSize, ySize) local buttonText = button:CreateChild("Text") buttonText:SetAlignment(HA_CENTER, VA_CENTER) buttonText:SetFont(font, 12) buttonText:SetText(text) return button end function CreateSlider(x, y, xSize, ySize, text) local font = cache:GetResource("Font", "Fonts/Anonymous Pro.ttf") -- Create text and slider below it local sliderText = ui.root:CreateChild("Text") sliderText:SetPosition(x, y) sliderText:SetFont(font, 12) sliderText:SetText(text) local slider = ui.root:CreateChild("Slider") slider:SetStyleAuto() slider:SetPosition(x, y + 20) slider:SetSize(xSize, ySize) -- Use 0-1 range for controlling sound/music master volume slider.range = 1.0 return slider end function HandlePlaySound(sender, eventType, eventData) local button = tolua.cast(GetEventSender(), "Button") local soundResourceName = button:GetVar(ShortStringHash("SoundResource")):GetString() -- Get the sound resource local sound = cache:GetResource("Sound", soundResourceName) if sound ~= nil then -- Create a scene node with a SoundSource component for playing the sound. The SoundSource component plays -- non-positional audio, so its 3D position in the scene does not matter. For positional sounds the -- SoundSource3D component would be used instead local soundNode = scene_:CreateChild("Sound") local soundSource = soundNode:CreateComponent("SoundSource") soundSource:Play(sound) -- In case we also play music, set the sound volume below maximum so that we don't clip the output soundSource.gain = 0.7 -- Set the sound component to automatically remove its scene node from the scene when the sound is done playing soundSource.autoRemove = true end end function HandlePlayMusic(eventType, eventData) -- Check if the music player node/component already exist if scene_:GetChild("Music") ~= nil then return end local music = cache:GetResource("Sound", "Music/Ninja Gods.ogg") -- Set the song to loop music.looped = true -- Create a scene node and a sound source for the music local musicNode = scene_:CreateChild("Music") local musicSource = musicNode:CreateComponent("SoundSource") -- Set the sound type to music so that master volume control works correctly musicSource.soundType = SOUND_MUSIC musicSource:Play(music) end function HandleStopMusic(eventType, eventData) -- Remove the music player node from the scene scene_:RemoveChild(scene_:GetChild("Music")) end function HandleSoundVolume(eventType, eventData) local newVolume = eventData:GetFloat("Value") audio:SetMasterGain(SOUND_EFFECT, newVolume) end function HandleMusicVolume(eventType, eventData) local newVolume = eventData:GetFloat("Value") audio:SetMasterGain(SOUND_MUSIC, newVolume) end
Fixed storing of sound resource names in SoundEffects Lua example (setting arbitrary properties on UIElement did not work.)
Fixed storing of sound resource names in SoundEffects Lua example (setting arbitrary properties on UIElement did not work.)
Lua
mit
fire/Urho3D-1,helingping/Urho3D,xiliu98/Urho3D,MeshGeometry/Urho3D,carnalis/Urho3D,helingping/Urho3D,MeshGeometry/Urho3D,iainmerrick/Urho3D,carnalis/Urho3D,tommy3/Urho3D,helingping/Urho3D,victorholt/Urho3D,xiliu98/Urho3D,SirNate0/Urho3D,codemon66/Urho3D,MeshGeometry/Urho3D,codedash64/Urho3D,rokups/Urho3D,cosmy1/Urho3D,SirNate0/Urho3D,iainmerrick/Urho3D,rokups/Urho3D,victorholt/Urho3D,299299/Urho3D,MonkeyFirst/Urho3D,cosmy1/Urho3D,orefkov/Urho3D,SuperWangKai/Urho3D,MeshGeometry/Urho3D,299299/Urho3D,cosmy1/Urho3D,c4augustus/Urho3D,SuperWangKai/Urho3D,rokups/Urho3D,eugeneko/Urho3D,codemon66/Urho3D,carnalis/Urho3D,orefkov/Urho3D,luveti/Urho3D,fire/Urho3D-1,bacsmar/Urho3D,abdllhbyrktr/Urho3D,PredatorMF/Urho3D,iainmerrick/Urho3D,PredatorMF/Urho3D,MonkeyFirst/Urho3D,orefkov/Urho3D,c4augustus/Urho3D,fire/Urho3D-1,299299/Urho3D,orefkov/Urho3D,cosmy1/Urho3D,xiliu98/Urho3D,abdllhbyrktr/Urho3D,rokups/Urho3D,bacsmar/Urho3D,helingping/Urho3D,henu/Urho3D,henu/Urho3D,codemon66/Urho3D,kostik1337/Urho3D,henu/Urho3D,weitjong/Urho3D,weitjong/Urho3D,c4augustus/Urho3D,codedash64/Urho3D,weitjong/Urho3D,kostik1337/Urho3D,rokups/Urho3D,codemon66/Urho3D,kostik1337/Urho3D,henu/Urho3D,iainmerrick/Urho3D,PredatorMF/Urho3D,tommy3/Urho3D,xiliu98/Urho3D,c4augustus/Urho3D,299299/Urho3D,rokups/Urho3D,cosmy1/Urho3D,abdllhbyrktr/Urho3D,urho3d/Urho3D,eugeneko/Urho3D,codedash64/Urho3D,luveti/Urho3D,codedash64/Urho3D,MonkeyFirst/Urho3D,PredatorMF/Urho3D,luveti/Urho3D,carnalis/Urho3D,kostik1337/Urho3D,SirNate0/Urho3D,tommy3/Urho3D,MonkeyFirst/Urho3D,eugeneko/Urho3D,henu/Urho3D,urho3d/Urho3D,codemon66/Urho3D,luveti/Urho3D,SirNate0/Urho3D,codedash64/Urho3D,SirNate0/Urho3D,c4augustus/Urho3D,tommy3/Urho3D,abdllhbyrktr/Urho3D,luveti/Urho3D,eugeneko/Urho3D,bacsmar/Urho3D,SuperWangKai/Urho3D,iainmerrick/Urho3D,tommy3/Urho3D,299299/Urho3D,fire/Urho3D-1,SuperWangKai/Urho3D,victorholt/Urho3D,carnalis/Urho3D,urho3d/Urho3D,helingping/Urho3D,abdllhbyrktr/Urho3D,victorholt/Urho3D,kostik1337/Urho3D,weitjong/Urho3D,xiliu98/Urho3D,urho3d/Urho3D,SuperWangKai/Urho3D,victorholt/Urho3D,fire/Urho3D-1,MeshGeometry/Urho3D,weitjong/Urho3D,MonkeyFirst/Urho3D,299299/Urho3D,bacsmar/Urho3D
da2de5add7be86d7b5e70c041e7b68e01de3131c
turbo/syscall.lua
turbo/syscall.lua
--- Turbo.lua syscall Module -- -- Copyright 2013 John Abrahamsen -- -- 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. -- modes local ffi = require "ffi" local util = require "turbo.util" local tm = util.tablemerge local octal = function (s) return tonumber(s, 8) end local flags = { O_DIRECTORY = octal('0200000'), O_NOFOLLOW = octal('0400000'), O_DIRECT = octal('040000'), S_IFMT = octal('0170000'), S_IFSOCK = octal('0140000'), S_IFLNK = octal('0120000'), S_IFREG = octal('0100000'), S_IFBLK = octal('0060000'), S_IFDIR = octal('0040000'), S_IFCHR = octal('0020000'), S_IFIFO = octal('0010000'), S_ISUID = octal('0004000'), S_ISGID = octal('0002000'), S_ISVTX = octal('0001000'), S_IRWXU = octal('00700'), S_IRUSR = octal('00400'), S_IWUSR = octal('00200'), S_IXUSR = octal('00100'), S_IRWXG = octal('00070'), S_IRGRP = octal('00040'), S_IWGRP = octal('00020'), S_IXGRP = octal('00010'), S_IRWXO = octal('00007'), S_IROTH = octal('00004'), S_IWOTH = octal('00002'), S_IXOTH = octal('00001') } local cmds --- ******* syscalls ******* if ffi.arch == "x86" then cmds = { SYS_stat = 106, SYS_fstat = 108, SYS_lstat = 107, SYS_getdents = 141, SYS_io_setup = 245, SYS_io_destroy = 246, SYS_io_getevents = 247, SYS_io_submit = 248, SYS_io_cancel = 249, SYS_clock_settime = 264, SYS_clock_gettime = 265, SYS_clock_getres = 266, SYS_clock_nanosleep = 267 } elseif ffi.arch == "x64" then cmds = { SYS_stat = 4, SYS_fstat = 5, SYS_lstat = 6, SYS_getdents = 78, SYS_io_setup = 206, SYS_io_destroy = 207, SYS_io_getevents = 208, SYS_io_submit = 209, SYS_io_cancel = 210, SYS_clock_settime = 227, SYS_clock_gettime = 228, SYS_clock_getres = 229, SYS_clock_nanosleep = 230 } elseif ffi.arch == "ppc" then cmds = { SYS_stat = 106, SYS_fstat = 108, SYS_lstat = 107, SYS_getdents = 141, SYS_io_setup = 227, SYS_io_destroy = 228, SYS_io_getevents = 229, SYS_io_submit = 230, SYS_io_cancel = 231, SYS_clock_settime = 245, SYS_clock_gettime = 246, SYS_clock_getres = 247, SYS_clock_nanosleep = 248 } end return tm(flags, cmds)
--- Turbo.lua syscall Module -- -- Copyright 2013 John Abrahamsen -- -- 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. -- modes local ffi = require "ffi" local util = require "turbo.util" local tm = util.tablemerge local octal = function (s) return tonumber(s, 8) end local flags = { O_DIRECTORY = octal('0200000'), O_NOFOLLOW = octal('0400000'), O_DIRECT = octal('040000'), S_IFMT = octal('0170000'), S_IFSOCK = octal('0140000'), S_IFLNK = octal('0120000'), S_IFREG = octal('0100000'), S_IFBLK = octal('0060000'), S_IFDIR = octal('0040000'), S_IFCHR = octal('0020000'), S_IFIFO = octal('0010000'), S_ISUID = octal('0004000'), S_ISGID = octal('0002000'), S_ISVTX = octal('0001000'), S_IRWXU = octal('00700'), S_IRUSR = octal('00400'), S_IWUSR = octal('00200'), S_IXUSR = octal('00100'), S_IRWXG = octal('00070'), S_IRGRP = octal('00040'), S_IWGRP = octal('00020'), S_IXGRP = octal('00010'), S_IRWXO = octal('00007'), S_IROTH = octal('00004'), S_IWOTH = octal('00002'), S_IXOTH = octal('00001') } local cmds --- ******* syscalls ******* if ffi.arch == "x86" then cmds = { SYS_stat = 106, SYS_fstat = 108, SYS_lstat = 107, SYS_getdents = 141, SYS_io_setup = 245, SYS_io_destroy = 246, SYS_io_getevents = 247, SYS_io_submit = 248, SYS_io_cancel = 249, SYS_clock_settime = 264, SYS_clock_gettime = 265, SYS_clock_getres = 266, SYS_clock_nanosleep = 267 } elseif ffi.arch == "x64" then cmds = { SYS_stat = 4, SYS_fstat = 5, SYS_lstat = 6, SYS_getdents = 78, SYS_io_setup = 206, SYS_io_destroy = 207, SYS_io_getevents = 208, SYS_io_submit = 209, SYS_io_cancel = 210, SYS_clock_settime = 227, SYS_clock_gettime = 228, SYS_clock_getres = 229, SYS_clock_nanosleep = 230 } elseif ffi.arch == "ppc" then cmds = { SYS_stat = 106, SYS_fstat = 108, SYS_lstat = 107, SYS_getdents = 141, SYS_io_setup = 227, SYS_io_destroy = 228, SYS_io_getevents = 229, SYS_io_submit = 230, SYS_io_cancel = 231, SYS_clock_settime = 245, SYS_clock_gettime = 246, SYS_clock_getres = 247, SYS_clock_nanosleep = 248 } elseif ffi.arch == "arm" then cmds = { SYS_stat = 106, SYS_fstat = 108, SYS_lstat = 107, SYS_getdents = 141, SYS_io_setup = 243, SYS_io_destroy = 244, SYS_io_getevents = 245, SYS_io_submit = 246, SYS_io_cancel = 247, SYS_clock_settime = 262, SYS_clock_gettime = 263, SYS_clock_getres = 264, SYS_clock_nanosleep = 265 } end return tm(flags, cmds)
Fix support for ARM in master branch. Tested on Raspberry PI.
Fix support for ARM in master branch. Tested on Raspberry PI.
Lua
apache-2.0
ddysher/turbo,zcsteele/turbo,ddysher/turbo,YuanPeir-Chen/turbo-support-mipsel,luastoned/turbo,luastoned/turbo,YuanPeir-Chen/turbo-support-mipsel,kernelsauce/turbo,zcsteele/turbo,mniestroj/turbo
b6b332e311a282f0f80dff24412197b2db5f1d6c
frontend/device/remarkable/device.lua
frontend/device/remarkable/device.lua
local Generic = require("device/generic/device") -- <= look at this file! local logger = require("logger") local function yes() return true end local function no() return false end -- returns isRm2, device_model local function getModel() local f = io.open("/sys/devices/soc0/machine") if not f then error("missing sysfs entry for a remarkable") end local model = f:read("*line") f:close() return model == "reMarkable 2.0", model end local EV_ABS = 3 local ABS_X = 00 local ABS_Y = 01 local ABS_MT_POSITION_X = 53 local ABS_MT_POSITION_Y = 54 -- Resolutions from libremarkable src/framebuffer/common.rs local screen_width = 1404 -- unscaled_size_check: ignore local screen_height = 1872 -- unscaled_size_check: ignore local wacom_width = 15725 -- unscaled_size_check: ignore local wacom_height = 20967 -- unscaled_size_check: ignore local wacom_scale_x = screen_width / wacom_width local wacom_scale_y = screen_height / wacom_height local isRm2, rm_model = getModel() local Remarkable = Generic:new{ isRemarkable = yes, model = rm_model, hasKeys = yes, needsScreenRefreshAfterResume = no, hasOTAUpdates = yes, canReboot = yes, canPowerOff = yes, isTouchDevice = yes, hasFrontlight = no, display_dpi = 226, -- Despite the SoC supporting it, it's finicky in practice (#6772) canHWInvert = no, home_dir = "/home/root", } local Remarkable1 = Remarkable:new{ mt_width = 767, -- unscaled_size_check: ignore mt_height = 1023, -- unscaled_size_check: ignore input_wacom = "/dev/input/event0", input_ts = "/dev/input/event1", input_buttons = "/dev/input/event2", battery_path = "/sys/class/power_supply/bq27441-0/capacity", status_path = "/sys/class/power_supply/bq27441-0/status", } function Remarkable1:adjustTouchEvent(ev, by) if ev.type == EV_ABS then -- Mirror X and Y and scale up both X & Y as touch input is different res from -- display if ev.code == ABS_MT_POSITION_X then ev.value = (Remarkable1.mt_width - ev.value) * by.mt_scale_x end if ev.code == ABS_MT_POSITION_Y then ev.value = (Remarkable1.mt_height - ev.value) * by.mt_scale_y end end end local Remarkable2 = Remarkable:new{ mt_width = 1403, -- unscaled_size_check: ignore mt_height = 1871, -- unscaled_size_check: ignore input_wacom = "/dev/input/event1", input_ts = "/dev/input/event2", input_buttons = "/dev/input/event0", battery_path = "/sys/class/power_supply/max77818_battery/capacity", status_path = "/sys/class/power_supply/max77818-charger/status", } function Remarkable2:adjustTouchEvent(ev, by) if ev.type == EV_ABS then -- Mirror Y and scale up both X & Y as touch input is different res from -- display if ev.code == ABS_MT_POSITION_X then ev.value = (ev.value) * by.mt_scale_x end if ev.code == ABS_MT_POSITION_Y then ev.value = (Remarkable2.mt_height - ev.value) * by.mt_scale_y end end end local adjustAbsEvt = function(self, ev) if ev.type == EV_ABS then if ev.code == ABS_X then ev.code = ABS_Y ev.value = (wacom_height - ev.value) * wacom_scale_y elseif ev.code == ABS_Y then ev.code = ABS_X ev.value = ev.value * wacom_scale_x end end end function Remarkable:init() self.screen = require("ffi/framebuffer_mxcfb"):new{device = self, debug = logger.dbg} self.powerd = require("device/remarkable/powerd"):new{ device = self, capacity_file = self.battery_path, status_file = self.status_path, } self.input = require("device/input"):new{ device = self, event_map = require("device/remarkable/event_map"), } self.input.open(self.input_wacom) -- Wacom self.input.open(self.input_ts) -- Touchscreen self.input.open(self.input_buttons) -- Buttons local scalex = screen_width / self.mt_width local scaley = screen_height / self.mt_height self.input:registerEventAdjustHook(adjustAbsEvt) self.input:registerEventAdjustHook(self.adjustTouchEvent, {mt_scale_x=scalex, mt_scale_y=scaley}) -- USB plug/unplug, battery charge/not charging are generated as fake events self.input.open("fake_events") local rotation_mode = self.screen.ORIENTATION_PORTRAIT self.screen.native_rotation_mode = rotation_mode self.screen.cur_rotation_mode = rotation_mode Generic.init(self) end function Remarkable:supportsScreensaver() return true end function Remarkable:initNetworkManager(NetworkMgr) function NetworkMgr:turnOnWifi(complete_callback) os.execute("./enable-wifi.sh") self:reconnectOrShowNetworkMenu(function() self:connectivityCheck(1, complete_callback) end) end function NetworkMgr:turnOffWifi(complete_callback) os.execute("./disable-wifi.sh") if complete_callback then complete_callback() end end function NetworkMgr:getNetworkInterfaceName() return "wlan0" end NetworkMgr:setWirelessBackend("wpa_supplicant", {ctrl_interface = "/var/run/wpa_supplicant/wlan0"}) NetworkMgr.isWifiOn = function() return NetworkMgr:isConnected() end end function Remarkable:setDateTime(year, month, day, hour, min, sec) if hour == nil or min == nil then return true end local command if year and month and day then command = string.format("timedatectl set-time '%d-%d-%d %d:%d:%d'", year, month, day, hour, min, sec) else command = string.format("timedatectl set-time '%d:%d'",hour, min) end return os.execute(command) == 0 end function Remarkable:resume() end function Remarkable:suspend() os.execute("./disable-wifi.sh") os.execute("systemctl suspend") end function Remarkable:powerOff() self.screen:clear() self.screen:refreshFull() os.execute("systemctl poweroff") end function Remarkable:reboot() os.execute("systemctl reboot") end logger.info(string.format("Starting %s", rm_model)) if isRm2 then if not os.getenv("RM2FB_SHIM") then error("reMarkable2 requires RM2FB to work (https://github.com/ddvk/remarkable2-framebuffer)") end return Remarkable2 else return Remarkable1 end
local Generic = require("device/generic/device") -- <= look at this file! local TimeVal = require("ui/timeval") local logger = require("logger") local ffi = require("ffi") local C = ffi.C require("ffi/linux_input_h") local function yes() return true end local function no() return false end -- returns isRm2, device_model local function getModel() local f = io.open("/sys/devices/soc0/machine") if not f then error("missing sysfs entry for a remarkable") end local model = f:read("*line") f:close() return model == "reMarkable 2.0", model end -- Resolutions from libremarkable src/framebuffer/common.rs local screen_width = 1404 -- unscaled_size_check: ignore local screen_height = 1872 -- unscaled_size_check: ignore local wacom_width = 15725 -- unscaled_size_check: ignore local wacom_height = 20967 -- unscaled_size_check: ignore local wacom_scale_x = screen_width / wacom_width local wacom_scale_y = screen_height / wacom_height local isRm2, rm_model = getModel() local Remarkable = Generic:new{ isRemarkable = yes, model = rm_model, hasKeys = yes, needsScreenRefreshAfterResume = no, hasOTAUpdates = yes, canReboot = yes, canPowerOff = yes, isTouchDevice = yes, hasFrontlight = no, display_dpi = 226, -- Despite the SoC supporting it, it's finicky in practice (#6772) canHWInvert = no, home_dir = "/home/root", } local Remarkable1 = Remarkable:new{ mt_width = 767, -- unscaled_size_check: ignore mt_height = 1023, -- unscaled_size_check: ignore input_wacom = "/dev/input/event0", input_ts = "/dev/input/event1", input_buttons = "/dev/input/event2", battery_path = "/sys/class/power_supply/bq27441-0/capacity", status_path = "/sys/class/power_supply/bq27441-0/status", } function Remarkable1:adjustTouchEvent(ev, by) if ev.type == C.EV_ABS then -- Mirror X and Y and scale up both X & Y as touch input is different res from -- display if ev.code == C.ABS_MT_POSITION_X then ev.value = (Remarkable1.mt_width - ev.value) * by.mt_scale_x end if ev.code == C.ABS_MT_POSITION_Y then ev.value = (Remarkable1.mt_height - ev.value) * by.mt_scale_y end end end local Remarkable2 = Remarkable:new{ mt_width = 1403, -- unscaled_size_check: ignore mt_height = 1871, -- unscaled_size_check: ignore input_wacom = "/dev/input/event1", input_ts = "/dev/input/event2", input_buttons = "/dev/input/event0", battery_path = "/sys/class/power_supply/max77818_battery/capacity", status_path = "/sys/class/power_supply/max77818-charger/status", } function Remarkable2:adjustTouchEvent(ev, by) if ev.type == C.EV_ABS then -- Mirror Y and scale up both X & Y as touch input is different res from -- display if ev.code == C.ABS_MT_POSITION_X then ev.value = (ev.value) * by.mt_scale_x end if ev.code == C.ABS_MT_POSITION_Y then ev.value = (Remarkable2.mt_height - ev.value) * by.mt_scale_y end end -- Wacom uses CLOCK_REALTIME, but the Touchscreen spits out frozen timestamps. -- Inject CLOCK_MONOTONIC timestamps at the end of every input frame in order to have consistent gesture detection across input devices. -- c.f., #7536 if ev.type == C.EV_SYN and ev.code == C.SYN_REPORT then ev.time = TimeVal:now() end end local adjustAbsEvt = function(self, ev) if ev.type == C.EV_ABS then if ev.code == C.ABS_X then ev.code = C.ABS_Y ev.value = (wacom_height - ev.value) * wacom_scale_y elseif ev.code == C.ABS_Y then ev.code = C.ABS_X ev.value = ev.value * wacom_scale_x end end end function Remarkable:init() self.screen = require("ffi/framebuffer_mxcfb"):new{device = self, debug = logger.dbg} self.powerd = require("device/remarkable/powerd"):new{ device = self, capacity_file = self.battery_path, status_file = self.status_path, } self.input = require("device/input"):new{ device = self, event_map = require("device/remarkable/event_map"), } self.input.open(self.input_wacom) -- Wacom self.input.open(self.input_ts) -- Touchscreen self.input.open(self.input_buttons) -- Buttons local scalex = screen_width / self.mt_width local scaley = screen_height / self.mt_height self.input:registerEventAdjustHook(adjustAbsEvt) self.input:registerEventAdjustHook(self.adjustTouchEvent, {mt_scale_x=scalex, mt_scale_y=scaley}) -- USB plug/unplug, battery charge/not charging are generated as fake events self.input.open("fake_events") local rotation_mode = self.screen.ORIENTATION_PORTRAIT self.screen.native_rotation_mode = rotation_mode self.screen.cur_rotation_mode = rotation_mode Generic.init(self) end function Remarkable:supportsScreensaver() return true end function Remarkable:initNetworkManager(NetworkMgr) function NetworkMgr:turnOnWifi(complete_callback) os.execute("./enable-wifi.sh") self:reconnectOrShowNetworkMenu(function() self:connectivityCheck(1, complete_callback) end) end function NetworkMgr:turnOffWifi(complete_callback) os.execute("./disable-wifi.sh") if complete_callback then complete_callback() end end function NetworkMgr:getNetworkInterfaceName() return "wlan0" end NetworkMgr:setWirelessBackend("wpa_supplicant", {ctrl_interface = "/var/run/wpa_supplicant/wlan0"}) NetworkMgr.isWifiOn = function() return NetworkMgr:isConnected() end end function Remarkable:setDateTime(year, month, day, hour, min, sec) if hour == nil or min == nil then return true end local command if year and month and day then command = string.format("timedatectl set-time '%d-%d-%d %d:%d:%d'", year, month, day, hour, min, sec) else command = string.format("timedatectl set-time '%d:%d'",hour, min) end return os.execute(command) == 0 end function Remarkable:resume() end function Remarkable:suspend() os.execute("./disable-wifi.sh") os.execute("systemctl suspend") end function Remarkable:powerOff() self.screen:clear() self.screen:refreshFull() os.execute("systemctl poweroff") end function Remarkable:reboot() os.execute("systemctl reboot") end logger.info(string.format("Starting %s", rm_model)) if isRm2 then if not os.getenv("RM2FB_SHIM") then error("reMarkable2 requires RM2FB to work (https://github.com/ddvk/remarkable2-framebuffer)") end return Remarkable2 else return Remarkable1 end
Fix for PR #7415 breaking reMarkable touch input (#7536)
Fix for PR #7415 breaking reMarkable touch input (#7536) The Wacom pen reports sane CLOCK_REALTIME timestamps, but the Touchscreen reports timestamps frozen at the boot time ts (in REALTIME) :s. So, make everyone use synthetic CLOCK_MONOTONIC timestamps in order to make gesture detection behave.
Lua
agpl-3.0
mwoz123/koreader,poire-z/koreader,NiLuJe/koreader,NiLuJe/koreader,poire-z/koreader,koreader/koreader,Frenzie/koreader,Frenzie/koreader,koreader/koreader
fb19753390f0a5baf9313b1970ddd61d528770a8
framework.lua
framework.lua
-- [author] Gabriel Nicolas Avellaneda <[email protected]> local boundary = require('boundary') local Emitter = require('core').Emitter local Error = require('core').Error local Object = require('core').Object local Process = require('uv').Process local timer = require('timer') local math = require('math') local string = require('string') local os = require('os') local io = require('io') local framework = {} local Plugin = Emitter:extend() framework.Plugin = Plugin framework.boundary = boundary function Plugin:initialize(params) self.pollInterval = 1000 self.source = os.hostname() self.minValue = 0 self.maxValue = 10 self.version = params.version or '0.0' self.name = params.name or 'Boundary Plugin' if params ~= nil then self.pollInterval = params.pollInterval or self.pollInterval self.source = params.source or self.source self.minValue = params.minValue or self.minValue self.maxvalue = params.maxValue or self.minValue end print("_bevent:" .. self.name .. " up : version " .. self.version .. "|t:info|tags:lua,plugin") end function Plugin:poll() self:emit('before_poll') self:onPoll() self:emit('after_poll') timer.setTimeout(self.pollInterval, function () self.poll(self) end) end function Plugin:onPoll() local metrics = self:getMetrics() self:report(metrics) end function Plugin:report(metrics) self:emit('report') self:onReport(metrics) end function currentTimestamp() return os.time() end function Plugin:onReport(metrics) for metric, value in pairs(metrics) do print(self:format(metric, value, self.source, currentTimestamp())) end end function Plugin:format(metric, value, source, timestamp) self:emit('format') return self:onFormat(metric, value, source, timestamp) end function Plugin:onFormat(metric, value, source, timestamp) return string.format('%s %f %s %s', metric, value, source, timestamp) end function Plugin:onGetMetrics() local value = math.random(self.minValue, self.maxValue) return {BOUNDARY_LUA_SAMPLE = value} end function Plugin:getMetrics() local metrics = self:onGetMetrics() return metrics end local CommandPlugin = Plugin:extend() framework.CommandPlugin = CommandPlugin function CommandPlugin:initialize(params) Plugin.initialize(self, params) if not params.command then error('params.command undefined. You need to define the command to excetue.') end self.command = params.command end function CommandPlugin:execCommand(callback) local proc = io.popen(self.command, 'r') local output = proc:read("*a") proc:close() if callback then callback(output) end end function CommandPlugin:onPoll() self:execCommand(function (output) self.parseCommandOutput(self, output) end) end function CommandPlugin:parseCommandOutput(output) local metrics = self:onParseCommandOutput(output) self:report(metrics) end function CommandPlugin:onParseCommandOutput(output) print(output) return {} end local NetPlugin : Plugin:extend() framework.NetPlugin = NetPlugin return framework
-- [author] Gabriel Nicolas Avellaneda <[email protected]> local boundary = require('boundary') local Emitter = require('core').Emitter local Error = require('core').Error local Object = require('core').Object local Process = require('uv').Process local timer = require('timer') local math = require('math') local string = require('string') local os = require('os') local io = require('io') local framework = {} local Plugin = Emitter:extend() framework.Plugin = Plugin framework.boundary = boundary function Plugin:initialize(params) self.pollInterval = 1000 self.source = os.hostname() self.minValue = 0 self.maxValue = 10 self.version = params.version or '0.0' self.name = params.name or 'Boundary Plugin' if params ~= nil then self.pollInterval = params.pollInterval or self.pollInterval self.source = params.source or self.source self.minValue = params.minValue or self.minValue self.maxvalue = params.maxValue or self.minValue end print("_bevent:" .. self.name .. " up : version " .. self.version .. "|t:info|tags:lua,plugin") end function Plugin:poll() self:emit('before_poll') self:onPoll() self:emit('after_poll') timer.setTimeout(self.pollInterval, function () self.poll(self) end) end function Plugin:onPoll() local metrics = self:getMetrics() self:report(metrics) end function Plugin:report(metrics) self:emit('report') self:onReport(metrics) end function currentTimestamp() return os.time() end function Plugin:onReport(metrics) for metric, value in pairs(metrics) do print(self:format(metric, value, self.source, currentTimestamp())) end end function Plugin:format(metric, value, source, timestamp) self:emit('format') return self:onFormat(metric, value, source, timestamp) end function Plugin:onFormat(metric, value, source, timestamp) return string.format('%s %f %s %s', metric, value, source, timestamp) end function Plugin:onGetMetrics() local value = math.random(self.minValue, self.maxValue) return {BOUNDARY_LUA_SAMPLE = value} end function Plugin:getMetrics() local metrics = self:onGetMetrics() return metrics end local CommandPlugin = Plugin:extend() framework.CommandPlugin = CommandPlugin function CommandPlugin:initialize(params) Plugin.initialize(self, params) if not params.command then error('params.command undefined. You need to define the command to excetue.') end self.command = params.command end function CommandPlugin:execCommand(callback) local proc = io.popen(self.command, 'r') local output = proc:read("*a") proc:close() if callback then callback(output) end end function CommandPlugin:onPoll() self:execCommand(function (output) self.parseCommandOutput(self, output) end) end function CommandPlugin:parseCommandOutput(output) local metrics = self:onParseCommandOutput(output) self:report(metrics) end function CommandPlugin:onParseCommandOutput(output) print(output) return {} end local NetPlugin = Plugin:extend() framework.NetPlugin = NetPlugin local HttpPlugin = Plugin:extend() framework.HttpPlugin = HttpPlugin return framework
Minor fixes
Minor fixes
Lua
apache-2.0
GabrielNicolasAvellaneda/boundary-plugins-vagrant
8d07a9c089121f5ea24826c8943c7a6386a27309
src/npge/alignment/move_identical.lua
src/npge/alignment/move_identical.lua
return function(rows) -- Input: -- ...... -- ..... -- ....... -- Output: -- *** .... -- *** , .. -- *** .... local aligned = {} for _, row in ipairs(rows) do -- list of char's table.insert(aligned, {}) end local pos = 1 while true do local first = rows[1]:sub(pos, pos) if #first == 0 then break end local bad for _, row in ipairs(rows) do local letter = row:sub(pos, pos) if letter ~= first then bad = true end end if bad then break end for _, aligned_row in ipairs(aligned) do table.insert(aligned_row, first) end pos = pos + 1 end local result = {} local tails = {} for i, aligned_row in ipairs(aligned) do table.insert(result, table.concat(aligned_row)) table.insert(tails, rows[i]:sub(pos)) end return result, tails end
return function(rows) -- Input: -- ...... -- ..... -- ....... -- Output: -- *** .... -- *** , .. -- *** .... local aligned = {} for _, row in ipairs(rows) do -- list of char's table.insert(aligned, {}) end local pos = 1 while true do local first = rows[1]:sub(pos, pos) if #first == 0 then break end local bad for _, row in ipairs(rows) do local letter = row:sub(pos, pos) if letter ~= first then bad = true end end if bad then break end for _, aligned_row in ipairs(aligned) do table.insert(aligned_row, first) end pos = pos + 1 end local aligned_row = table.concat(aligned[1] or {}) local result = {} local tails = {} for i, _ in ipairs(aligned) do table.insert(result, aligned_row) table.insert(tails, rows[i]:sub(pos)) end return result, tails end
move_identical: build common prefix once
move_identical: build common prefix once All rows include same prefix, which is returned in table of rows (result 1) multiple times.
Lua
mit
npge/lua-npge,starius/lua-npge,npge/lua-npge,starius/lua-npge,npge/lua-npge,starius/lua-npge
d430397be741d0e588fe79f57a6612e3747f8321
spec/dynamic_spec.lua
spec/dynamic_spec.lua
--[[ FHIR Formats Copyright (C) 2016 Vadim Peretokin 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 in_fhir_json = require("fhir-formats").to_json local in_fhir_xml = require("fhir-formats").to_xml local cjson = require("cjson") local xml = require("xml") local inspect = require("inspect") local tablex = require("pl.tablex") local data = { {"json-edge-cases.json", "json-edge-cases.xml"}, {"patient-example-good.json", "patient-example.xml"} } for _, testcase in ipairs(data) do local json_file = testcase[1] local xml_file = testcase[2] local case_name = json_file:gsub("%.json", '') describe(case_name.." xml to json", function() local t = {} setup(function() io.input("spec/"..json_file) t.json_data = io.read("*a") t.xml_data = in_fhir_json("spec/"..xml_file, {file = true}) t.json_example = cjson.decode(t.json_data) t.xml_example = cjson.decode(t.xml_data) t.keys_in_both_tables = tablex.keys(tablex.merge(t.json_example, t.xml_example)) -- for same div data test assert:set_parameter("TableFormatLevel", -1) for _, key in ipairs(t.keys_in_both_tables) do it("should have the same "..key.." objects", function() -- cut out the div's, since the whitespace doesn't matter as much in xml t.json_example.text.div = nil t.xml_example.text.div = nil assert.same(t.json_example[key], t.xml_example[key]) end) end end) before_each(function() t.json_example = cjson.decode(t.json_data) t.xml_example = cjson.decode(t.xml_data) end) it("should have xml-comparable div data", function() local json_example_div = xml.load(t.json_example.text.div) local xml_example_div = xml.load(t.xml_example.text.div) -- assert.same(json_example_div, xml_example_div) end) end) describe(case_name.. " json to xml", function() local t = {} setup(function() io.input("spec/"..xml_file) t.xml_data = io.read("*a") t.json_data = in_fhir_xml("spec/"..json_file, {file = true}) -- for same div data test assert:set_parameter("TableFormatLevel", -1) end) it("should have the same data", function() -- convert it down to JSON since order of elements doesn't matter in JSON, while it does in XML assert.same(cjson.decode(in_fhir_json(t.xml_data)), cjson.decode(in_fhir_json(t.json_data))) end) end) end
--[[ FHIR Formats Copyright (C) 2016 Vadim Peretokin 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 in_fhir_json = require("fhir-formats").to_json local in_fhir_xml = require("fhir-formats").to_xml local cjson = require("cjson") local xml = require("xml") local inspect = require("inspect") local tablex = require("pl.tablex") local data = { {"json-edge-cases.json", "json-edge-cases.xml"}, {"patient-example-good.json", "patient-example.xml"} } for _, testcase in ipairs(data) do local json_file = testcase[1] local xml_file = testcase[2] local case_name = json_file:gsub("%.json", '') describe(case_name.." xml to json", function() -- do the setup outside of setup(), as setup() can't handle creating it()'s within it local t = {} io.input("spec/"..json_file) t.json_data = io.read("*a") t.xml_data = in_fhir_json("spec/"..xml_file, {file = true}) t.json_example = cjson.decode(t.json_data) t.xml_example = cjson.decode(t.xml_data) t.keys_in_both_tables = tablex.keys(tablex.merge(t.json_example, t.xml_example)) -- for same div data test assert:set_parameter("TableFormatLevel", -1) for _, key in ipairs(t.keys_in_both_tables) do it("should have the same "..key.." objects", function() -- cut out the div's, since the whitespace doesn't matter as much in xml t.json_example.text.div = nil t.xml_example.text.div = nil assert.same(t.json_example[key], t.xml_example[key]) end) end before_each(function() t.json_example = cjson.decode(t.json_data) t.xml_example = cjson.decode(t.xml_data) end) it("should have xml-comparable div data", function() local json_example_div = xml.load(t.json_example.text.div) local xml_example_div = xml.load(t.xml_example.text.div) -- assert.same(json_example_div, xml_example_div) end) end) describe(case_name.. " json to xml", function() local t = {} setup(function() io.input("spec/"..xml_file) t.xml_data = io.read("*a") t.json_data = in_fhir_xml("spec/"..json_file, {file = true}) -- for same div data test assert:set_parameter("TableFormatLevel", -1) end) it("should have the same data", function() -- convert it down to JSON since order of elements doesn't matter in JSON, while it does in XML assert.same(cjson.decode(in_fhir_json(t.xml_data)), cjson.decode(in_fhir_json(t.json_data))) end) end) end
Fixed by doing setup outside of setup()
Fixed by doing setup outside of setup()
Lua
apache-2.0
vadi2/fhir-formats
4ad48b16f8d3651a17339a39eb5fd954979ffd7c
.Framework/src/MY.String.lua
.Framework/src/MY.String.lua
-------------------------------------------- -- @Desc : - ַ -- @Author: @˫ @׷Ӱ -- @Date : 2015-01-25 15:35:26 -- @Email : [email protected] -- @Last Modified by: һ @tinymins -- @Last Modified time: 2016-02-02 16:47:40 -- @Ref: Դ @haimanchajian.com -------------------------------------------- ------------------------------------------------------------------------ -- these global functions are accessed all the time by the event handler -- so caching them is worth the effort ------------------------------------------------------------------------ local ipairs, pairs, next, pcall = ipairs, pairs, next, pcall local tinsert, tremove, tconcat = table.insert, table.remove, table.concat local ssub, slen, schar, srep, sbyte, sformat, sgsub = string.sub, string.len, string.char, string.rep, string.byte, string.format, string.gsub local type, tonumber, tostring = type, tonumber, tostring local GetTime, GetLogicFrameCount = GetTime, GetLogicFrameCount local floor, mmin, mmax, mceil = math.floor, math.min, math.max, math.ceil local GetClientPlayer, GetPlayer, GetNpc, GetClientTeam, UI_GetClientPlayerID = GetClientPlayer, GetPlayer, GetNpc, GetClientTeam, UI_GetClientPlayerID local setmetatable = setmetatable -------------------------------------------- -- غͱ -------------------------------------------- MY = MY or {} MY.String = MY.String or {} -- ַָ -- (table) MY.String.Split(string szText, string szSpliter, bool bIgnoreEmptyPart) -- szText ԭʼַ -- szSpliter ָ -- bIgnoreEmptyPart ǷԿַ"123;234;"";"ֳ{"123","234"}{"123","234",""} function MY.String.Split(szText, szSep, bIgnoreEmptyPart) local nOff, tResult, szPart = 1, {} while true do local nEnd = StringFindW(szText, szSep, nOff) if not nEnd then szPart = string.sub(szText, nOff, string.len(szText)) if not bIgnoreEmptyPart or szPart ~= "" then table.insert(tResult, szPart) end break else szPart = string.sub(szText, nOff, nEnd - 1) if not bIgnoreEmptyPart or szPart ~= "" then table.insert(tResult, szPart) end nOff = nEnd + string.len(szSep) end end return tResult end -- תʽַ -- (string) MY.String.PatternEscape(string szText) function MY.String.PatternEscape(s) return (string.gsub(s, '([%(%)%.%%%+%-%*%?%[%^%$%]])', '%%%1')) end -- ַβĿհַ -- (string) MY.String.Trim(string szText) function MY.String.Trim(szText) if not szText or szText == "" then return "" end return (string.gsub(szText, "^%s*(.-)%s*$", "%1")) end -- תΪ URL -- (string) MY.String.UrlEncode(string szText) function MY.String.UrlEncode(szText) return szText:gsub("([^0-9a-zA-Z ])", function (c) return string.format ("%%%02X", string.byte(c)) end):gsub(" ", "+") end -- URL -- (string) MY.String.UrlDecode(string szText) function MY.String.UrlDecode(szText) return szText:gsub("+", " "):gsub("%%(%x%x)", function(h) return string.char(tonumber(h, 16)) end) end function MY.String.LenW(str) return wstring.len(str) end function MY.String.SubW(str,s,e) if s < 0 then s = wstring.len(str) + s end if e < 0 then e = wstring.len(str) + e end return wstring.sub(str, s, e) end function MY.String.SimpleEcrypt(szText) return szText:gsub('.', function (c) return string.format ("%02X", (string.byte(c) + 13) % 256) end):gsub(" ", "+") end local m_simpleMatchCache = setmetatable({}, { __mode = "v" }) function MY.String.SimpleMatch(szText, szFind, bDistinctCase) if not bDistinctCase then szFind = StringLowerW(szFind) szText = StringLowerW(szText) end local tFind = m_simpleMatchCache[szFind] if not tFind then tFind = {} for _, szKeyWordsLine in ipairs(MY.String.Split(szFind, ';', true)) do local tKeyWordsLine = {} for _, szKeyWords in ipairs(MY.String.Split(szKeyWordsLine, ',', true)) do local tKeyWords = {} for _, szKeyWord in ipairs(MY.String.Split(szKeyWords, '|', true)) do tinsert(tKeyWords, szKeyWord) end tinsert(tKeyWordsLine, tKeyWords) end tinsert(tFind, tKeyWordsLine) end m_simpleMatchCache[szFind] = tFind end local me = GetClientPlayer() if me then szFind = szFind:gsub("$zj", GetClientPlayer().szName) local szTongName = "" local tong = GetTongClient() if tong and me.dwTongID ~= 0 then szTongName = tong.ApplyGetTongName(me.dwTongID) or "" end szFind = szFind:gsub("$bh", szTongName) szFind = szFind:gsub("$gh", szTongName) end -- 10|ʮ,Ѫս|XZTC,!С,!;ս local bKeyWordsLine = false for _, tKeyWordsLine in ipairs(tFind) do -- һ -- 10|ʮ,Ѫս|XZTC,!С,! local bKeyWords = true for _, tKeyWords in ipairs(tKeyWordsLine) do -- ȫ -- 10|ʮ local bKeyWord = false for _, szKeyWord in ipairs(tKeyWords) do -- һ -- szKeyWord = MY.String.PatternEscape(szKeyWord) -- wstringEscapeݱ if szKeyWord:sub(1, 1) == "!" then -- !С szKeyWord = szKeyWord:sub(2) if not wstring.find(szText, szKeyWord) then bKeyWord = true end else -- ʮ -- 10 if wstring.find(szText, szKeyWord) then bKeyWord = true end end if bKeyWord then break end end bKeyWords = bKeyWords and bKeyWord if not bKeyWords then break end end bKeyWordsLine = bKeyWordsLine or bKeyWords if bKeyWordsLine then break end end return bKeyWordsLine end
-------------------------------------------- -- @Desc : - ַ -- @Author: @˫ @׷Ӱ -- @Date : 2015-01-25 15:35:26 -- @Email : [email protected] -- @Last Modified by: һ @tinymins -- @Last Modified time: 2016-02-02 16:47:40 -- @Ref: Դ @haimanchajian.com -------------------------------------------- ------------------------------------------------------------------------ -- these global functions are accessed all the time by the event handler -- so caching them is worth the effort ------------------------------------------------------------------------ local ipairs, pairs, next, pcall = ipairs, pairs, next, pcall local tinsert, tremove, tconcat = table.insert, table.remove, table.concat local ssub, slen, schar, srep, sbyte, sformat, sgsub = string.sub, string.len, string.char, string.rep, string.byte, string.format, string.gsub local type, tonumber, tostring = type, tonumber, tostring local GetTime, GetLogicFrameCount = GetTime, GetLogicFrameCount local floor, mmin, mmax, mceil = math.floor, math.min, math.max, math.ceil local GetClientPlayer, GetPlayer, GetNpc, GetClientTeam, UI_GetClientPlayerID = GetClientPlayer, GetPlayer, GetNpc, GetClientTeam, UI_GetClientPlayerID local setmetatable = setmetatable -------------------------------------------- -- غͱ -------------------------------------------- MY = MY or {} MY.String = MY.String or {} -- ַָ -- (table) MY.String.Split(string szText, string szSpliter, bool bIgnoreEmptyPart) -- szText ԭʼַ -- szSpliter ָ -- bIgnoreEmptyPart ǷԿַ"123;234;"";"ֳ{"123","234"}{"123","234",""} function MY.String.Split(szText, szSep, bIgnoreEmptyPart) local nOff, tResult, szPart = 1, {} while true do local nEnd = StringFindW(szText, szSep, nOff) if not nEnd then szPart = string.sub(szText, nOff, string.len(szText)) if not bIgnoreEmptyPart or szPart ~= "" then table.insert(tResult, szPart) end break else szPart = string.sub(szText, nOff, nEnd - 1) if not bIgnoreEmptyPart or szPart ~= "" then table.insert(tResult, szPart) end nOff = nEnd + string.len(szSep) end end return tResult end -- תʽַ -- (string) MY.String.PatternEscape(string szText) function MY.String.PatternEscape(s) return (string.gsub(s, '([%(%)%.%%%+%-%*%?%[%^%$%]])', '%%%1')) end -- ַβĿհַ -- (string) MY.String.Trim(string szText) function MY.String.Trim(szText) if not szText or szText == "" then return "" end return (string.gsub(szText, "^%s*(.-)%s*$", "%1")) end -- תΪ URL -- (string) MY.String.UrlEncode(string szText) function MY.String.UrlEncode(szText) return szText:gsub("([^0-9a-zA-Z ])", function (c) return string.format ("%%%02X", string.byte(c)) end):gsub(" ", "+") end -- URL -- (string) MY.String.UrlDecode(string szText) function MY.String.UrlDecode(szText) return szText:gsub("+", " "):gsub("%%(%x%x)", function(h) return string.char(tonumber(h, 16)) end) end function MY.String.LenW(str) return wstring.len(str) end function MY.String.SubW(str,s,e) if s < 0 then s = wstring.len(str) + s end if e < 0 then e = wstring.len(str) + e end return wstring.sub(str, s, e) end function MY.String.SimpleEcrypt(szText) return szText:gsub('.', function (c) return string.format ("%02X", (string.byte(c) + 13) % 256) end):gsub(" ", "+") end local m_simpleMatchCache = setmetatable({}, { __mode = "v" }) function MY.String.SimpleMatch(szText, szFind, bDistinctCase) if not bDistinctCase then szFind = StringLowerW(szFind) szText = StringLowerW(szText) end local me = GetClientPlayer() if me then szFind = szFind:gsub("$zj", me.szName) local szTongName = "" local tong = GetTongClient() if tong and me.dwTongID ~= 0 then szTongName = tong.ApplyGetTongName(me.dwTongID) or "" end szFind = szFind:gsub("$bh", szTongName) szFind = szFind:gsub("$gh", szTongName) end local tFind = m_simpleMatchCache[szFind] if not tFind then tFind = {} for _, szKeyWordsLine in ipairs(MY.String.Split(szFind, ';', true)) do local tKeyWordsLine = {} for _, szKeyWords in ipairs(MY.String.Split(szKeyWordsLine, ',', true)) do local tKeyWords = {} for _, szKeyWord in ipairs(MY.String.Split(szKeyWords, '|', true)) do tinsert(tKeyWords, szKeyWord) end tinsert(tKeyWordsLine, tKeyWords) end tinsert(tFind, tKeyWordsLine) end m_simpleMatchCache[szFind] = tFind end -- 10|ʮ,Ѫս|XZTC,!С,!;ս local bKeyWordsLine = false for _, tKeyWordsLine in ipairs(tFind) do -- һ -- 10|ʮ,Ѫս|XZTC,!С,! local bKeyWords = true for _, tKeyWords in ipairs(tKeyWordsLine) do -- ȫ -- 10|ʮ local bKeyWord = false for _, szKeyWord in ipairs(tKeyWords) do -- һ -- szKeyWord = MY.String.PatternEscape(szKeyWord) -- wstringEscapeݱ if szKeyWord:sub(1, 1) == "!" then -- !С szKeyWord = szKeyWord:sub(2) if not wstring.find(szText, szKeyWord) then bKeyWord = true end else -- ʮ -- 10 if wstring.find(szText, szKeyWord) then bKeyWord = true end end if bKeyWord then break end end bKeyWords = bKeyWords and bKeyWord if not bKeyWords then break end end bKeyWordsLine = bKeyWordsLine or bKeyWords if bKeyWordsLine then break end end return bKeyWordsLine end
字符串匹配中 $zj, $bh, $gh 模糊字不生效的BUG
字符串匹配中 $zj, $bh, $gh 模糊字不生效的BUG
Lua
bsd-3-clause
tinymins/MY
07f4735150204d3defee50f774049f21a8acda0d
tests/test-http-post-1mb.lua
tests/test-http-post-1mb.lua
--[[ Copyright 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 http = require('http') local string = require('string') local HOST = "127.0.0.1" local PORT = process.env.PORT or 10080 local server = nil local client = nil local a = string.rep('a', 1024) local data = string.rep(a, 1024) local MB = data:len() require('tap')(function(test) test('http-post-1mb', function(expect) server = http.createServer(function(request, response) p('server:onConnection') local postBuffer = '' assert(request.method == "POST") assert(request.url == "/foo") assert(request.headers.bar == "cats") request:on('data', function(chunk) postBuffer = postBuffer .. chunk end) request:on('end', expect(function() p('server:onEnd') assert(postBuffer == data) response:write(data) response:finish() end)) end) server:listen(PORT, HOST, function() local headers = { {'bar', 'cats'}, {'Content-Length', MB}, {'Transfer-Encoding', 'chunked'} } local body = {} local req = http.request({ host = HOST, port = PORT, method = 'POST', path = "/foo", headers = headers }, function(response) assert(response.statusCode == 200) assert(response.httpVersion == '1.1') response:on('data', expect(function(data) body[#body+1] = data p('chunk received',data:len()) end)) response:on('end', expect(function(data) data = table.concat(body) assert(data:len() == MB) p('Response ended') server:close() end)) end) req:write(data) req:done() end) end) end)
--[[ Copyright 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 http = require('http') local string = require('string') local HOST = "127.0.0.1" local PORT = process.env.PORT or 10080 local server = nil local client = nil local a = string.rep('a', 1024) local data = string.rep(a, 1024) local MB = data:len() require('tap')(function(test) test('http-post-1mb', function(expect) server = http.createServer(function(request, response) p('server:onConnection') local buffer = {} assert(request.method == "POST") assert(request.url == "/foo") assert(request.headers.bar == "cats") request:on('data', function(chunk) table.insert(buffer, chunk) end) request:on('end', expect(function() p('server:onEnd') assert(table.concat(buffer) == data) response:write(data) response:finish() end)) end) server:listen(PORT, HOST, function() local headers = { {'bar', 'cats'}, {'Content-Length', MB}, {'Transfer-Encoding', 'chunked'} } local body = {} local req = http.request({ host = HOST, port = PORT, method = 'POST', path = "/foo", headers = headers }, function(response) assert(response.statusCode == 200) assert(response.httpVersion == '1.1') response:on('data', function(data) body[#body+1] = data p('chunk received',data:len()) end) response:on('end', expect(function(data) data = table.concat(body) assert(data:len() == MB) p('Response ended') server:close() end)) end) req:write(data) req:done() end) end) end)
fix 1mb post
fix 1mb post
Lua
apache-2.0
zhaozg/luvit,luvit/luvit,kaustavha/luvit,bsn069/luvit,bsn069/luvit,kaustavha/luvit,bsn069/luvit,kaustavha/luvit,zhaozg/luvit,luvit/luvit
ed7674b3a4e4247f053482c2bd0fac4343487c7d
ledbar.lua
ledbar.lua
local PIXELS = 30*5 local BYTES_PER_LED = 3 --global LED buffer for all animations and PIXELS local wsbuf = ws2812.newBuffer(PIXELS, BYTES_PER_LED) local POST = node.task.post local PRIO = node.task.LOW_PRIORITY local animFunc, animParams, animNumParams local function off() wsbuf:fill(0, 0, 0) wsbuf:write() tmr.wdclr() end local function stop() tmr.unregister(2) end local timerTick local function animate() if animFunc then local delay = animFunc(wsbuf, unpack(animParams, 1, animNumParams)) wsbuf:write() if delay then tmr.interval(2, delay) tmr.start(2) return end end stop() end timerTick = function() POST(PRIO, animate) end local function init() ws2812.init() end local function start() tmr.register(2, 100, tmr.ALARM_SEMI, timerTick) return tmr.start(2) end local function setFunction(f, ...) animFunc = f animParams = { ... } animNumParams = select("#", ...) end local function ison() return tmr.state(2) end local function info() local on, mode = tmr.state(2) local s = "tmrOn: " .. tostring(on) .. ", tmrMode: " .. tostring(mode) .. ", func: " .. tostring(animFunc) print(s) return s end return { off = off, start = start, stop = stop, init = init, setFunction = setFunction, ison = ison, info = info, wsbuf = wsbuf, }
local PIXELS = 30*5 local BYTES_PER_LED = 3 --global LED buffer for all animations and PIXELS local wsbuf = ws2812.newBuffer(PIXELS, BYTES_PER_LED) local POST = node.task.post local PRIO = node.task.LOW_PRIORITY local W = ws2812.write local animFunc, animParams, animNumParams local function off() wsbuf:fill(0, 0, 0) W(wsbuf) tmr.wdclr() end local function stop() tmr.unregister(2) end local timerTick local function animate() if animFunc then local delay = animFunc(wsbuf, unpack(animParams, 1, animNumParams)) W(wsbuf) if delay then tmr.interval(2, delay) tmr.start(2) return end end stop() end timerTick = function() POST(PRIO, animate) end local function init() ws2812.init() end local function start() tmr.register(2, 100, tmr.ALARM_SEMI, timerTick) return tmr.start(2) end local function setFunction(f, ...) animFunc = f animParams = { ... } animNumParams = select("#", ...) end local function ison() return tmr.state(2) end local function info() local on, mode = tmr.state(2) local s = "tmrOn: " .. tostring(on) .. ", tmrMode: " .. tostring(mode) .. ", func: " .. tostring(animFunc) print(s) return s end return { off = off, start = start, stop = stop, init = init, setFunction = setFunction, ison = ison, info = info, wsbuf = wsbuf, }
Small fix for newer firmware versions
Small fix for newer firmware versions
Lua
mit
realraum/r3LoTHRPipeLEDs,realraum/r3LoTHRPipeLEDs
4531f6a27998cd533d89f1f3a21a88b22fde9d0f
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 <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ]]-- 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 <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ]]-- 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 git-svn-id: edf5ee79c2c7d29460bbb5b398f55862cc26620d@2605 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
Lua
apache-2.0
Flexibity/luci,saraedum/luci-packages-old,Canaan-Creative/luci,8devices/carambola2-luci,yeewang/openwrt-luci,dtaht/cerowrt-luci-3.3,ThingMesh/openwrt-luci,dtaht/cerowrt-luci-3.3,Flexibity/luci,Canaan-Creative/luci,jschmidlapp/luci,jschmidlapp/luci,stephank/luci,Canaan-Creative/luci,ch3n2k/luci,gwlim/luci,Flexibity/luci,projectbismark/luci-bismark,alxhh/piratenluci,gwlim/luci,jschmidlapp/luci,Canaan-Creative/luci,ThingMesh/openwrt-luci,vhpham80/luci,ThingMesh/openwrt-luci,saraedum/luci-packages-old,gwlim/luci,freifunk-gluon/luci,phi-psi/luci,ch3n2k/luci,yeewang/openwrt-luci,vhpham80/luci,ThingMesh/openwrt-luci,vhpham80/luci,phi-psi/luci,zwhfly/openwrt-luci,saraedum/luci-packages-old,eugenesan/openwrt-luci,stephank/luci,yeewang/openwrt-luci,jschmidlapp/luci,Canaan-Creative/luci,ThingMesh/openwrt-luci,dtaht/cerowrt-luci-3.3,phi-psi/luci,ch3n2k/luci,vhpham80/luci,zwhfly/openwrt-luci,alxhh/piratenluci,phi-psi/luci,eugenesan/openwrt-luci,saraedum/luci-packages-old,freifunk-gluon/luci,gwlim/luci,ThingMesh/openwrt-luci,ch3n2k/luci,gwlim/luci,ReclaimYourPrivacy/cloak-luci,Flexibity/luci,zwhfly/openwrt-luci,freifunk-gluon/luci,dtaht/cerowrt-luci-3.3,phi-psi/luci,Flexibity/luci,gwlim/luci,Flexibity/luci,jschmidlapp/luci,Canaan-Creative/luci,zwhfly/openwrt-luci,freifunk-gluon/luci,dtaht/cerowrt-luci-3.3,ch3n2k/luci,freifunk-gluon/luci,yeewang/openwrt-luci,zwhfly/openwrt-luci,eugenesan/openwrt-luci,saraedum/luci-packages-old,projectbismark/luci-bismark,freifunk-gluon/luci,stephank/luci,alxhh/piratenluci,ReclaimYourPrivacy/cloak-luci,alxhh/piratenluci,projectbismark/luci-bismark,stephank/luci,eugenesan/openwrt-luci,alxhh/piratenluci,8devices/carambola2-luci,saraedum/luci-packages-old,projectbismark/luci-bismark,yeewang/openwrt-luci,alxhh/piratenluci,projectbismark/luci-bismark,8devices/carambola2-luci,ReclaimYourPrivacy/cloak-luci,phi-psi/luci,ReclaimYourPrivacy/cloak-luci,ReclaimYourPrivacy/cloak-luci,Flexibity/luci,jschmidlapp/luci,alxhh/piratenluci,jschmidlapp/luci,phi-psi/luci,8devices/carambola2-luci,Canaan-Creative/luci,Flexibity/luci,yeewang/openwrt-luci,jschmidlapp/luci,zwhfly/openwrt-luci,ReclaimYourPrivacy/cloak-luci,vhpham80/luci,ch3n2k/luci,ReclaimYourPrivacy/cloak-luci,projectbismark/luci-bismark,8devices/carambola2-luci,yeewang/openwrt-luci,ReclaimYourPrivacy/cloak-luci,eugenesan/openwrt-luci,freifunk-gluon/luci,zwhfly/openwrt-luci,saraedum/luci-packages-old,projectbismark/luci-bismark,8devices/carambola2-luci,gwlim/luci,projectbismark/luci-bismark,ch3n2k/luci,eugenesan/openwrt-luci,zwhfly/openwrt-luci,eugenesan/openwrt-luci,ThingMesh/openwrt-luci,freifunk-gluon/luci,stephank/luci,Canaan-Creative/luci,8devices/carambola2-luci,zwhfly/openwrt-luci,stephank/luci,vhpham80/luci,dtaht/cerowrt-luci-3.3
8a1298ebc408a0d78a02cda18d7608c4dad88ecb
modulefiles/Core/binutils/2.26.lua
modulefiles/Core/binutils/2.26.lua
help( [[ This module loads binutils 2.26 The GNU Binutils are a collection of binary tools that do low level operations on binaries. ]]) whatis("Loads binutils 2.26" local version = "2.26" local base = "/cvmfs/oasis.opensciencegrid.org/osg/modules/binutils/"..version prepend_path("LD_LIBRARY_PATH", pathJoin(base, "lib")) prepend_path("CPATH", pathJoin(base, "include")) prepend_path("LIBRARY_PATH", pathJoin(base, "lib")) family('binutils')
help( [[ This module loads binutils 2.26 The GNU Binutils are a collection of binary tools that do low level operations on binaries. ]]) whatis("Loads binutils 2.26") local version = "2.26" local base = "/cvmfs/oasis.opensciencegrid.org/osg/modules/binutils/"..version prepend_path("PATH", pathJoin(base, "bin")) prepend_path("LD_LIBRARY_PATH", pathJoin(base, "lib")) prepend_path("CPATH", pathJoin(base, "include")) prepend_path("LIBRARY_PATH", pathJoin(base, "lib")) family('binutils')
Fix binutils module
Fix binutils module
Lua
apache-2.0
OSGConnect/modulefiles,OSGConnect/modulefiles,OSGConnect/modulefiles
5c5a6c914e1a4d3e4821196ecc20872576e13a8d
totem/asserts.lua
totem/asserts.lua
--[[ Test for tensor equality Parameters: - `ta` (tensor) - `tb` (tensor) - `condition` (number) maximum pointwise difference between `a` and `b` Returns two values: success (boolean), failure_message (string or nil) Tests whether the maximum pointwise difference between `a` and `b` is less than or equal to `condition`. ]] function totem.areTensorsEq(ta, tb, condition, neg) -- If neg is true, we invert success and failure -- This allows to easily implement Tester:assertTensorNe local invert = false if neg == nil then invert = false else invert = true end if ta:dim() ~= tb:dim() then return false, 'The tensors have different dimensions' end local sizea = torch.DoubleTensor(ta:size():totable()) local sizeb = torch.DoubleTensor(tb:size():totable()) local sizediff = sizea:clone():add(-1, sizeb) local sizeerr = sizediff:abs():max() if sizeerr ~= 0 then return false, 'The tensors have different sizes' end local function ensureHasAbs(t) -- Byte, Char and Short Tensors don't have abs if not t.abs then return t:double() else return t end end ta = ensureHasAbs(ta) tb = ensureHasAbs(tb) local diff = ta:clone():add(-1, tb) local err = diff:abs():max() local violation = invert and 'TensorNE(==)' or ' TensorEQ(==)' local errMessage = string.format('%s violation: val=%s, condition=%s', violation, tostring(err), tostring(condition)) local success = err <= condition if invert then success = not success end return success, (not success) and errMessage or nil end --[[ Assert tensor equality Parameters: - `ta` (tensor) - `tb` (tensor) - `condition` (number) maximum pointwise difference between `a` and `b` Asserts that the maximum pointwise difference between `a` and `b` is less than or equal to `condition`. ]] function totem.assertTensorEq(ta, tb, condition) return assert(totem.areTensorsEq(ta, tb, condition)) end --[[ Test for tensor inequality Parameters: - `ta` (tensor) - `tb` (tensor) - `condition` (number) The tensors are considered unequal if the maximum pointwise difference >= condition. ]] function totem.areTensorsNe(ta, tb, condition) return totem.areTensorsEq(ta, tb, condition, true) end --[[ Assert tensor inequality Parameters: - `ta` (tensor) - `tb` (tensor) - `condition` (number) The tensors are considered unequal if the maximum pointwise difference >= condition. ]] function totem.assertTensorNe(ta, tb, condition) assert(totem.areTensorsNe(ta, tb, condition)) end local function isIncludedIn(ta, tb) if type(ta) ~= 'table' or type(tb) ~= 'table' then return ta == tb end for k, v in pairs(tb) do if not totem.assertTableEq(ta[k], v) then return false end end return true end --[[ Assert that two tables are equal (comparing values, recursively) Parameters: - `actual` (table) - `expected` (table) ]] function totem.assertTableEq(ta, tb) return isIncludedIn(ta, tb) and isIncludedIn(tb, ta) end --[[ Assert that two tables are *not* equal (comparing values, recursively) Parameters: - `actual` (table) - `expected` (table) ]] function totem.assertTableNe(ta, tb) return not totem.assertTableEq(ta, tb) end
--[[ Test for tensor equality Parameters: - `ta` (tensor) - `tb` (tensor) - `condition` (number) maximum pointwise difference between `a` and `b` Returns two values: success (boolean), failure_message (string or nil) Tests whether the maximum pointwise difference between `a` and `b` is less than or equal to `condition`. ]] function totem.areTensorsEq(ta, tb, condition, neg) -- If neg is true, we invert success and failure -- This allows to easily implement Tester:assertTensorNe local invert = false if neg == nil then invert = false else invert = true end if ta:dim() ~= tb:dim() then return false, 'The tensors have different dimensions' end local sizea = torch.DoubleTensor(ta:size():totable()) local sizeb = torch.DoubleTensor(tb:size():totable()) local sizediff = sizea:clone():add(-1, sizeb) local sizeerr = sizediff:abs():max() if sizeerr ~= 0 then return false, 'The tensors have different sizes' end local function ensureHasAbs(t) -- Byte, Char and Short Tensors don't have abs if not t.abs then return t:double() else return t end end ta = ensureHasAbs(ta) tb = ensureHasAbs(tb) local diff = ta:clone():add(-1, tb) local err = diff:abs():max() local violation = invert and 'TensorNE(==)' or ' TensorEQ(==)' local errMessage = string.format('%s violation: val=%s, condition=%s', violation, tostring(err), tostring(condition)) local success = err <= condition if invert then success = not success end return success, (not success) and errMessage or nil end --[[ Assert tensor equality Parameters: - `ta` (tensor) - `tb` (tensor) - `condition` (number) maximum pointwise difference between `a` and `b` Asserts that the maximum pointwise difference between `a` and `b` is less than or equal to `condition`. ]] function totem.assertTensorEq(ta, tb, condition) return assert(totem.areTensorsEq(ta, tb, condition)) end --[[ Test for tensor inequality Parameters: - `ta` (tensor) - `tb` (tensor) - `condition` (number) The tensors are considered unequal if the maximum pointwise difference >= condition. ]] function totem.areTensorsNe(ta, tb, condition) return totem.areTensorsEq(ta, tb, condition, true) end --[[ Assert tensor inequality Parameters: - `ta` (tensor) - `tb` (tensor) - `condition` (number) The tensors are considered unequal if the maximum pointwise difference >= condition. ]] function totem.assertTensorNe(ta, tb, condition) assert(totem.areTensorsNe(ta, tb, condition)) end local function isIncludedIn(ta, tb) if type(ta) ~= 'table' or type(tb) ~= 'table' then return ta == tb end for k, v in pairs(tb) do if not totem.assertTableEq(ta[k], v) then return false end end return true end --[[ Assert that two tables are equal (comparing values, recursively) Parameters: - `actual` (table) - `expected` (table) ]] function totem.assertTableEq(ta, tb) return isIncludedIn(ta, tb) and isIncludedIn(tb, ta) end --[[ Assert that two tables are *not* equal (comparing values, recursively) Parameters: - `actual` (table) - `expected` (table) ]] function totem.assertTableNe(ta, tb) return not totem.assertTableEq(ta, tb) end
Fixing white space. (2-space indentation, not 4).
Fixing white space. (2-space indentation, not 4).
Lua
bsd-3-clause
GeorgOstrovski/torch-totem,yozw/torch-totem,clementfarabet/torch-totem,fzvinicius/torch-totem,fbesse/torch-totem,mevGDM/torch-totem,deepmind/torch-totem,dm-jrae/torch-totem
28e48c8c4b761fd641da8448d64a8680bd3bfd7c
examples/http-upload.lua
examples/http-upload.lua
local HTTP = require("http") local Utils = require("utils") local Table = require("table") HTTP.create_server("0.0.0.0", 8080, function (req, res) p("on_request", req) local chunks = {} local length = 0 req:on('data', function (chunk, len) p("on_data", {chunk=chunk, len=len}) length = length + 1 chunks[length] = chunk end) req:on('end', function () local body = Table.concat(chunks, "") p("on_end", {body=body}) res:write_head(200, { ["Content-Type"] = "text/plain", ["Content-Length"] = #body }) res:write(body) res:close() end) end) print("Server listening at http://localhost:8080/")
local HTTP = require("http") local Utils = require("utils") local Table = require("table") HTTP.create_server("0.0.0.0", 8080, function (req, res) p("on_request", req) local chunks = {} local length = 0 req:on('data', function (chunk, len) p("on_data", {len=len}) length = length + 1 chunks[length] = chunk end) req:on('end', function () local body = Table.concat(chunks, "") p("on_end", {total_len=#body}) body = "length = " .. tostring(#body) .. "\n" res:write_head(200, { ["Content-Type"] = "text/plain", ["Content-Length"] = #body }) res:write(body) res:close() end) end) print("Server listening at http://localhost:8080/")
Fix upload example to not dump the actual data
Fix upload example to not dump the actual data Change-Id: Icd849536e31061772e7fef953ddcea1a2f5c8a6d
Lua
apache-2.0
bsn069/luvit,rjeli/luvit,boundary/luvit,GabrielNicolasAvellaneda/luvit-upstream,luvit/luvit,bsn069/luvit,AndrewTsao/luvit,rjeli/luvit,sousoux/luvit,boundary/luvit,AndrewTsao/luvit,AndrewTsao/luvit,zhaozg/luvit,connectFree/lev,sousoux/luvit,luvit/luvit,kaustavha/luvit,rjeli/luvit,GabrielNicolasAvellaneda/luvit-upstream,GabrielNicolasAvellaneda/luvit-upstream,boundary/luvit,connectFree/lev,bsn069/luvit,boundary/luvit,DBarney/luvit,boundary/luvit,boundary/luvit,sousoux/luvit,kaustavha/luvit,GabrielNicolasAvellaneda/luvit-upstream,kaustavha/luvit,sousoux/luvit,zhaozg/luvit,DBarney/luvit,sousoux/luvit,rjeli/luvit,DBarney/luvit,DBarney/luvit,sousoux/luvit,brimworks/luvit
7fa35a8f4370ef18df54fd45800cde020008124a
AceGUI-3.0/widgets/AceGUIWidget-Slider.lua
AceGUI-3.0/widgets/AceGUIWidget-Slider.lua
local AceGUI = LibStub("AceGUI-3.0") -------------------------- -- Slider -- -------------------------- do local Type = "Slider" local Version = 0 local function Aquire(self) self:SetDisabled(false) self:SetSliderValues(0,100,1) self:SetIsPercent(nil) self:SetValue(0) end local function Release(self) self.frame:ClearAllPoints() self.frame:Hide() self:SetDisabled(false) end local function Control_OnEnter(this) this.obj:Fire("OnEnter") end local function Control_OnLeave(this) this.obj:Fire("OnLeave") end local function UpdateText(self) if self.ispercent then self.editbox:SetText((math.floor(self.value*1000+0.5)/10)..'%') else self.editbox:SetText(math.floor(self.value*100+0.5)/100) end end local function Slider_OnValueChanged(this) local self = this.obj if not this.setup then local newvalue newvalue = this:GetValue() if newvalue ~= self.value and not self.disabled then self.value = newvalue self:Fire("OnValueChanged", newvalue) end if self.value then local value = self.value UpdateText(self) end end end local function Slider_OnMouseUp(this) local self = this.obj self:Fire("OnMouseUp",this:GetValue()) end local function Slider_OnMouseWheel(this, v) local self = this.obj local value = self.value if v > 0 then value = math.min(value + (self.step or 1),self.max) else value = math.max(value - (self.step or 1), self.min) end self.slider:SetValue(value) end local function SetDisabled(self, disabled) self.disabled = disabled if disabled then self.slider:EnableMouse(false) self.label:SetTextColor(.5,.5,.5) self.hightext:SetTextColor(.5,.5,.5) self.lowtext:SetTextColor(.5,.5,.5) --self.valuetext:SetTextColor(.5,.5,.5) self.editbox:SetTextColor(.5,.5,.5) self.editbox:EnableMouse(false) self.editbox:ClearFocus() else self.slider:EnableMouse(true) self.label:SetTextColor(1,.82,0) self.hightext:SetTextColor(1,1,1) self.lowtext:SetTextColor(1,1,1) --self.valuetext:SetTextColor(1,1,1) self.editbox:SetTextColor(1,1,1) self.editbox:EnableMouse(true) end end local function SetValue(self, value) self.slider.setup = true self.slider:SetValue(value) self.value = value UpdateText(self) self.slider.setup = nil end local function SetLabel(self, text) self.label:SetText(text) end local function SetSliderValues(self,min, max, step) local frame = self.slider frame.setup = true self.min = min self.max = max self.step = step frame:SetMinMaxValues(min or 0,max or 100) self.lowtext:SetText(min or 0) self.hightext:SetText(max or 100) frame:SetValueStep(step or 1) frame.setup = nil end local function EditBox_OnEscapePressed(this) this:ClearFocus() end local function EditBox_OnEnterPressed(this) local self = this.obj local value = this:GetText() if self.ispercent then value = value:gsub('%%','') value = tonumber(value) / 100 else value = tonumber(value) end if value then self:Fire("OnMouseUp",value) end end local function SetIsPercent(self, value) self.ispercent = value end local SliderBackdrop = { bgFile = "Interface\\Buttons\\UI-SliderBar-Background", edgeFile = "Interface\\Buttons\\UI-SliderBar-Border", tile = true, tileSize = 8, edgeSize = 8, insets = { left = 3, right = 3, top = 6, bottom = 6 } } local function Constructor() local frame = CreateFrame("Frame",nil,UIParent) local self = {} self.type = Type self.Release = Release self.Aquire = Aquire self.frame = frame frame.obj = self self.SetDisabled = SetDisabled self.SetValue = SetValue self.SetSliderValues = SetSliderValues self.SetLabel = SetLabel self.SetIsPercent = SetIsPercent self.alignoffset = 25 self.slider = CreateFrame("Slider",nil,frame) local slider = self.slider slider:SetScript("OnEnter",Control_OnEnter) slider:SetScript("OnLeave",Control_OnLeave) slider:SetScript("OnMouseUp", Slider_OnMouseUp) slider.obj = self slider:SetOrientation("HORIZONTAL") slider:SetHeight(15) slider:SetHitRectInsets(0,0,-10,0) slider:SetBackdrop(SliderBackdrop) slider:EnableMouseWheel(true) slider:SetScript("OnMouseWheel", Slider_OnMouseWheel) local label = frame:CreateFontString(nil,"OVERLAY","GameFontNormal") label:SetPoint("TOPLEFT",frame,"TOPLEFT",0,0) label:SetPoint("TOPRIGHT",frame,"TOPRIGHT",0,0) label:SetJustifyH("CENTER") label:SetHeight(15) self.label = label self.lowtext = slider:CreateFontString(nil,"ARTWORK","GameFontHighlightSmall") self.lowtext:SetPoint("TOPLEFT",slider,"BOTTOMLEFT",2,3) self.hightext = slider:CreateFontString(nil,"ARTWORK","GameFontHighlightSmall") self.hightext:SetPoint("TOPRIGHT",slider,"BOTTOMRIGHT",-2,3) local editbox = CreateFrame("EditBox",nil,frame) editbox:SetAutoFocus(false) editbox:SetFontObject(GameFontHighlightSmall) editbox:SetPoint("TOP",slider,"BOTTOM",0,0) editbox:SetHeight(14) editbox:SetWidth(100) editbox:SetJustifyH("CENTER") editbox:EnableMouse(true) editbox:SetScript("OnEscapePressed",EditBox_OnEscapePressed) editbox:SetScript("OnEnterPressed",EditBox_OnEnterPressed) self.editbox = editbox editbox.obj = self slider:SetThumbTexture("Interface\\Buttons\\UI-SliderBar-Button-Horizontal") frame:SetWidth(200) frame:SetHeight(44) slider:SetPoint("TOP",label,"BOTTOM",0,0) slider:SetPoint("LEFT",frame,"LEFT",3,0) slider:SetPoint("RIGHT",frame,"RIGHT",-3,0) slider:SetValue(self.value or 0) slider:SetScript("OnValueChanged",Slider_OnValueChanged) AceGUI:RegisterAsWidget(self) return self end AceGUI:RegisterWidgetType(Type,Constructor,Version) end
local AceGUI = LibStub("AceGUI-3.0") -------------------------- -- Slider -- -------------------------- do local Type = "Slider" local Version = 0 local function Aquire(self) self:SetDisabled(false) self:SetSliderValues(0,100,1) self:SetIsPercent(nil) self:SetValue(0) end local function Release(self) self.frame:ClearAllPoints() self.frame:Hide() self:SetDisabled(false) end local function Control_OnEnter(this) this.obj:Fire("OnEnter") end local function Control_OnLeave(this) this.obj:Fire("OnLeave") end local function UpdateText(self) if self.ispercent then self.editbox:SetText((math.floor(self.value*1000+0.5)/10)..'%') else self.editbox:SetText(math.floor(self.value*100+0.5)/100) end end local function Slider_OnValueChanged(this) local self = this.obj if not this.setup then local newvalue newvalue = this:GetValue() if newvalue ~= self.value and not self.disabled then self.value = newvalue self:Fire("OnValueChanged", newvalue) end if self.value then local value = self.value UpdateText(self) end end end local function Slider_OnMouseUp(this) local self = this.obj self:Fire("OnMouseUp",this:GetValue()) end local function Slider_OnMouseWheel(this, v) local self = this.obj if not self.disabled then local value = self.value if v > 0 then value = math.min(value + (self.step or 1),self.max) else value = math.max(value - (self.step or 1), self.min) end self.slider:SetValue(value) end end local function SetDisabled(self, disabled) self.disabled = disabled if disabled then self.slider:EnableMouse(false) self.label:SetTextColor(.5,.5,.5) self.hightext:SetTextColor(.5,.5,.5) self.lowtext:SetTextColor(.5,.5,.5) --self.valuetext:SetTextColor(.5,.5,.5) self.editbox:SetTextColor(.5,.5,.5) self.editbox:EnableMouse(false) self.editbox:ClearFocus() else self.slider:EnableMouse(true) self.label:SetTextColor(1,.82,0) self.hightext:SetTextColor(1,1,1) self.lowtext:SetTextColor(1,1,1) --self.valuetext:SetTextColor(1,1,1) self.editbox:SetTextColor(1,1,1) self.editbox:EnableMouse(true) end end local function SetValue(self, value) self.slider.setup = true self.slider:SetValue(value) self.value = value UpdateText(self) self.slider.setup = nil end local function SetLabel(self, text) self.label:SetText(text) end local function SetSliderValues(self,min, max, step) local frame = self.slider frame.setup = true self.min = min self.max = max self.step = step frame:SetMinMaxValues(min or 0,max or 100) self.lowtext:SetText(min or 0) self.hightext:SetText(max or 100) frame:SetValueStep(step or 1) frame.setup = nil end local function EditBox_OnEscapePressed(this) this:ClearFocus() end local function EditBox_OnEnterPressed(this) local self = this.obj local value = this:GetText() if self.ispercent then value = value:gsub('%%','') value = tonumber(value) / 100 else value = tonumber(value) end if value then self:Fire("OnMouseUp",value) end end local function SetIsPercent(self, value) self.ispercent = value end local SliderBackdrop = { bgFile = "Interface\\Buttons\\UI-SliderBar-Background", edgeFile = "Interface\\Buttons\\UI-SliderBar-Border", tile = true, tileSize = 8, edgeSize = 8, insets = { left = 3, right = 3, top = 6, bottom = 6 } } local function Constructor() local frame = CreateFrame("Frame",nil,UIParent) local self = {} self.type = Type self.Release = Release self.Aquire = Aquire self.frame = frame frame.obj = self self.SetDisabled = SetDisabled self.SetValue = SetValue self.SetSliderValues = SetSliderValues self.SetLabel = SetLabel self.SetIsPercent = SetIsPercent self.alignoffset = 25 self.slider = CreateFrame("Slider",nil,frame) local slider = self.slider slider:SetScript("OnEnter",Control_OnEnter) slider:SetScript("OnLeave",Control_OnLeave) slider:SetScript("OnMouseUp", Slider_OnMouseUp) slider.obj = self slider:SetOrientation("HORIZONTAL") slider:SetHeight(15) slider:SetHitRectInsets(0,0,-10,0) slider:SetBackdrop(SliderBackdrop) slider:EnableMouseWheel(true) slider:SetScript("OnMouseWheel", Slider_OnMouseWheel) local label = frame:CreateFontString(nil,"OVERLAY","GameFontNormal") label:SetPoint("TOPLEFT",frame,"TOPLEFT",0,0) label:SetPoint("TOPRIGHT",frame,"TOPRIGHT",0,0) label:SetJustifyH("CENTER") label:SetHeight(15) self.label = label self.lowtext = slider:CreateFontString(nil,"ARTWORK","GameFontHighlightSmall") self.lowtext:SetPoint("TOPLEFT",slider,"BOTTOMLEFT",2,3) self.hightext = slider:CreateFontString(nil,"ARTWORK","GameFontHighlightSmall") self.hightext:SetPoint("TOPRIGHT",slider,"BOTTOMRIGHT",-2,3) local editbox = CreateFrame("EditBox",nil,frame) editbox:SetAutoFocus(false) editbox:SetFontObject(GameFontHighlightSmall) editbox:SetPoint("TOP",slider,"BOTTOM",0,0) editbox:SetHeight(14) editbox:SetWidth(100) editbox:SetJustifyH("CENTER") editbox:EnableMouse(true) editbox:SetScript("OnEscapePressed",EditBox_OnEscapePressed) editbox:SetScript("OnEnterPressed",EditBox_OnEnterPressed) self.editbox = editbox editbox.obj = self slider:SetThumbTexture("Interface\\Buttons\\UI-SliderBar-Button-Horizontal") frame:SetWidth(200) frame:SetHeight(44) slider:SetPoint("TOP",label,"BOTTOM",0,0) slider:SetPoint("LEFT",frame,"LEFT",3,0) slider:SetPoint("RIGHT",frame,"RIGHT",-3,0) slider:SetValue(self.value or 0) slider:SetScript("OnValueChanged",Slider_OnValueChanged) AceGUI:RegisterAsWidget(self) return self end AceGUI:RegisterWidgetType(Type,Constructor,Version) end
Ace3 - AceGUI: Fix slider widget moving with the mousewheel when disabled
Ace3 - AceGUI: Fix slider widget moving with the mousewheel when disabled git-svn-id: d324031ee001e5fbb202928c503a4bc65708d41c@493 5debad98-a965-4143-8383-f471b3509dcf
Lua
bsd-3-clause
sarahgerweck/Ace3
3723368c636b7d334f742386dd47e4741db87b82
loader.lua
loader.lua
#!/usr/bin/lua -- helper script basic logic: -- parse cmdline args, save all internal state into loader lable for use inside user config scripts -- TODO: define some basic config-script verification logic -- ??? -- sequentially, execute lua scripts from remaining args -- recursively iterate through global params, saving valid value contents to text files inside temp dir for later reuse inside bash scripts -- profit! -- storage for loader params loader={} loader["export"]={} -- show usage function loader_show_usage() print("usage: loader.lua <params>") print("") print("mandatory params:") print("-t <dir> : Temporary directory, where resulted global variables will be exported as text. It must exist.") print("-w <dir> : Work directory, may be reffered in used scripts as \"loader.workdir\"") print("-c <condif script path> : Main config script file.") print("-e <variable name> : Name of global variable, to be exported after script is run. You can specify multiple -e params. At least one must be specified.") print("") print("optional params:") print("-pre <script>: Optional lua script, executed before main config script. May contain some additional functions for use with main script. Non zero exit code aborts further execution.") print("-post <script>: Optional lua script, executed after main config script. May contain some some verification logic for use with main script. Non zero exit code aborts further execution.") os.exit(1) end function loader_param_set_check(par) if loader[par] ~= nil then print(string.format("param \"%s\" already set",par)) print() loader_show_usage() end end function loader_param_not_set_check(par) if loader[par] == nil then print(string.format("param \"%s\" is not set",par)) print() loader_show_usage() end end function loader_set_param (name, value) if name == nil then error(string.format("param \"%s\" is nil",name)) end if value == nil then error(string.format("param \"%s\" is not set",name)) end loader[name]=string.format("%s",value) end set=false par="none" exnum=-1 for i,ar in ipairs(arg) do if set == true then if par == "add_export" then loader.export[exnum]=string.format("%s",ar) else loader_set_param(par,ar) end set = false else if ar == "-t" then par="tmpdir" elseif ar == "-w" then par="workdir" elseif ar == "-c" then par="exec" elseif ar == "-pre" then par="preexec" elseif ar == "-post" then par="postexec" elseif ar == "-e" then par="add_export" exnum=exnum+1 else print(string.format("incorrect parameter: %s",ar)) print() loader_show_usage() end loader_param_set_check(par) set = true end end loader_param_not_set_check("tmpdir") loader_param_not_set_check("workdir") loader_param_not_set_check("exec") if loader.export[0] == nil then print("at least one global variable name to export must be provided!") print() loader_show_usage() end -- unset non-needed defines exnum=nil set=nil par=nil loader_show_usage=nil loader_param_set_check=nil loader_param_not_set_check=nil loader_set_param=nil -- TODO: define some config verification logic -- execute pre-script if loader.preexec ~= nil then print("running preexec script") dofile(loader.preexec) end -- execute main script print("running main config script") dofile(loader.exec) -- execute post-script if loader.postexec ~= nil then print("running postexec script") dofile(loader.postexec) end
#!/usr/bin/lua -- helper script basic logic: -- parse cmdline args, save all internal state into loader lable for use inside user config scripts -- TODO: define some basic config-script verification logic -- ??? -- sequentially, execute lua scripts from remaining args -- recursively iterate through global params, saving valid value contents to text files inside temp dir for later reuse inside bash scripts -- profit! -- storage for loader params loader={} loader["export"]={} -- logging function loader.log(msg) -- TODO: extend logging print(msg) end -- show usage function loader_show_usage() print("usage: loader.lua <params>") print("") print("mandatory params:") print("-t <dir> : Temporary directory, where resulted global variables will be exported as text. It must exist.") print("-w <dir> : Work directory, may be reffered in used scripts as \"loader.workdir\"") print("-c <condif script path> : Main config script file.") print("-e <variable name> : Name of global variable, to be exported after script is run. You can specify multiple -e params. At least one must be specified.") print("") print("optional params:") print("-pre <script>: Optional lua script, executed before main config script. May contain some additional functions for use with main script. Non zero exit code aborts further execution.") print("-post <script>: Optional lua script, executed after main config script. May contain some some verification logic for use with main script. Non zero exit code aborts further execution.") os.exit(1) end function loader_param_set_check(par) if loader[par] ~= nil then print(string.format("param \"%s\" already set",par)) print() loader_show_usage() end end function loader_param_not_set_check(par) if loader[par] == nil then print(string.format("param \"%s\" is not set",par)) print() loader_show_usage() end end function loader_set_param (name, value) if name == nil then error(string.format("param \"%s\" is nil",name)) end if value == nil then error(string.format("param \"%s\" is not set",name)) end loader[name]=string.format("%s",value) end set=false par="none" exnum=0 for i,ar in ipairs(arg) do if set == true then if par == "add_export" then loader.export[exnum] = string.format("%s",ar) else loader_set_param(par,ar) end set = false else if ar == "-t" then par="tmpdir" elseif ar == "-w" then par="workdir" elseif ar == "-c" then par="exec" elseif ar == "-pre" then par="preexec" elseif ar == "-post" then par="postexec" elseif ar == "-e" then par="add_export" exnum=exnum+1 else print("incorrect parameter: " .. ar) print() loader_show_usage() end loader_param_set_check(par) set = true end end loader_param_not_set_check("tmpdir") loader_param_not_set_check("workdir") loader_param_not_set_check("exec") if loader.export[1] == nil then print("at least one global variable name to export must be provided!") print() loader_show_usage() end -- unset non-needed defines exnum=nil set=nil par=nil loader_show_usage=nil loader_param_set_check=nil loader_param_not_set_check=nil loader_set_param=nil -- TODO: define some config verification logic -- execute pre-script if loader.preexec ~= nil then loader.log("running preexec script") dofile(loader.preexec) end -- execute main script print("running main config script") dofile(loader.exec) -- execute post-script if loader.postexec ~= nil then loader.log("running postexec script") dofile(loader.postexec) end
bash-lua-helper: loader.lua - minor fixes, added "loader.log" function template
bash-lua-helper: loader.lua - minor fixes, added "loader.log" function template
Lua
mit
DarkCaster/Bash-Lua-Helper
258b13d3443b24d7b3c8e5ba081eea42afafe6a6
frontend/ui/elements/font_settings.lua
frontend/ui/elements/font_settings.lua
local Device = require("device") local logger = require("logger") local util = require("util") local _ = require("gettext") --[[ Font settings for desktop linux and mac ]]-- local function getUserDir() return os.getenv("HOME").."/.local/share/fonts" end -- System fonts are common in linux local function getSystemDir() local path = "/usr/share/fonts" if util.pathExists(path) then return path else -- mac doesn't use ttf fonts return nil end end local function usesSystemFonts() return G_reader_settings:isTrue("system_fonts") end local function openFontDir() local user_dir = getUserDir() local openable = util.pathExists(user_dir) if not openable then logger.info("Font path not found, making one in ", user_dir) openable = util.makePath(user_dir) end if not openable then logger.warn("Unable to create the folder ", user_dir) return end if Device:canOpenLink() then Device:openLink(user_dir) end end local FontSettings = {} function FontSettings:getPath() if usesSystemFonts() then local system_path = getSystemDir() if system_path ~= nil then return getUserDir()..";"..system_path end end return getUserDir() end function FontSettings:getMenuTable() return { text = _("Font settings"), separator = true, sub_item_table = { { text = _("Enable system fonts"), checked_func = usesSystemFonts, callback = function() G_reader_settings:saveSetting("system_fonts", not usesSystemFonts()) local UIManager = require("ui/uimanager") local InfoMessage = require("ui/widget/infomessage") UIManager:show(InfoMessage:new{ text = _("This will take effect on next restart.") }) end, }, { text = _("Open fonts folder"), keep_menu_open = true, callback = openFontDir, }, } } end return FontSettings
local Device = require("device") local logger = require("logger") local util = require("util") local _ = require("gettext") --[[ Font settings for desktop linux and mac ]]-- local function getUserDir() local home = os.getenv("HOME") if home then return home.."/.local/share/fonts" end end -- System fonts are common in linux local function getSystemDir() local path = "/usr/share/fonts" if util.pathExists(path) then return path else -- mac doesn't use ttf fonts return nil end end local function usesSystemFonts() return G_reader_settings:isTrue("system_fonts") end local function openFontDir() if not Device:canOpenLink() then return end local user_dir = getUserDir() local openable = util.pathExists(user_dir) if not openable and user_dir then logger.info("Font path not found, making one in ", user_dir) openable = util.makePath(user_dir) end if not openable then logger.warn("Unable to create the folder ", user_dir) return end Device:openLink(user_dir) end local FontSettings = {} function FontSettings:getPath() if usesSystemFonts() then local system_path = getSystemDir() if system_path ~= nil then return getUserDir()..";"..system_path end end return getUserDir() end function FontSettings:getMenuTable() return { text = _("Font settings"), separator = true, sub_item_table = { { text = _("Enable system fonts"), checked_func = usesSystemFonts, callback = function() G_reader_settings:saveSetting("system_fonts", not usesSystemFonts()) local UIManager = require("ui/uimanager") local InfoMessage = require("ui/widget/infomessage") UIManager:show(InfoMessage:new{ text = _("This will take effect on next restart.") }) end, }, { text = _("Open fonts folder"), keep_menu_open = true, callback = openFontDir, }, } } end return FontSettings
[fix] Fallback in case of missing HOME variable
[fix] Fallback in case of missing HOME variable
Lua
agpl-3.0
NiLuJe/koreader,Frenzie/koreader,koreader/koreader,pazos/koreader,mihailim/koreader,Markismus/koreader,mwoz123/koreader,koreader/koreader,poire-z/koreader,Frenzie/koreader,Hzj-jie/koreader,poire-z/koreader,NiLuJe/koreader
1a41cacbe84a0fb93a0a44578a576eb2580bce7f
stdlib/utils/globals.lua
stdlib/utils/globals.lua
--- Additional lua globals -- @module Utils.Globals STDLIB = { config = require('__stdlib__/stdlib/config') } --Since debug can be overridden we define a fallback function here. local _traceback = function() return '' end traceback = type(debug) == 'table' and debug.traceback or _traceback serpent = serpent or require('__stdlib__/stdlib/vendor/serpent') inspect = require('__stdlib__/stdlib/vendor/inspect') local Table = require('__stdlib__/stdlib/utils/table') local Math = require('__stdlib__/stdlib/utils/math') local String = require('__stdlib__/stdlib/utils/string') _G.table_size = _G.table_size or Table.size -- Set up default stuff for testing, -- defines will already be available in an active mod or busted setup specs if not _G.defines then _G.table.unpack = _G.table.unpack or unpack _G.table.pack = _G.table.pack or pack if STDLIB.config.control or STDLIB.config.game then local world = require('__stdlib__/spec/setup/world').bootstrap() if STDLIB.config.game then world.init() end else require('__stdlib__/spec/setup/dataloader') end _G.log = function(msg) print(msg) end end -- Defines Mutates require('__stdlib__/stdlib/utils/defines/color') require('__stdlib__/stdlib/utils/defines/anticolor') require('__stdlib__/stdlib/utils/defines/lightcolor') require('__stdlib__/stdlib/utils/defines/time') --- Require a file that may not exist -- @tparam string module path to the module -- @tparam boolean suppress_all suppress all errors, not just file_not_found -- @treturn mixed function prequire(module, suppress_all) local ok, err = pcall(require, module) if ok then return err elseif not suppress_all and not err:find('^module .* not found') then error(err) end end --- Temporarily removes __tostring handlers and calls tostring -- @tparam mixed t object to call rawtostring on -- @treturn string function rawtostring(t) local m = getmetatable(t) if m then local f = m.__tostring m.__tostring = nil local s = tostring(t) m.__tostring = f return s else return tostring(t) end end --- Returns t if the expression is true. f if false -- @tparam mixed exp The expression to evaluate -- @tparam mixed t the true return -- @tparam mixed f the false return -- @treturn boolean function inline_if(exp, t, f) if exp then return t else return f end end function concat(lhs, rhs) return tostring(lhs) .. tostring(rhs) end --- install the Table library into global table function STDLIB.install_table() for k, v in pairs(Table) do _G.table[k] = v end end --- Install the Math library into global math function STDLIB.install_math() for k, v in pairs(Math) do _G.math[k] = v end end --- Install the string library into global string function STDLIB.install_string() for k, v in pairs(String) do _G.string[k] = v end setmetatable(string, nil) end --- Install Math, String, Table into their global counterparts. function STDLIB.install_all_utils() STDLIB.install.math() STDLIB.install.string() STDLIB.install.table() end --- Reload a required file, NOT IMPLEMENTED function STDLIB.reload_class() end --- load the stdlib into globals, by default it loads everything into an ALLCAPS name. -- Alternatively you can pass a dictionary of `[global names] -> [require path]`. -- @tparam[opt] table files -- @usage -- STDLIB.create_stdlib_globals() function STDLIB.create_stdlib_globals(files) files = files or { GAME = 'stdlib/game', AREA = 'stdlib/area/area', POSITION = 'stdlib/area/position', TILE = 'stdlib/area/tile', SURFACE = 'stdlib/area/surface', CHUNK = 'stdlib/area/chunk', COLOR = 'stdlib/utils/color', ENTITY = 'stdlib/entity/entity', INVENTORY = 'stdlib/entity/inventory', RESOURCE = 'stdlib/entity/resource', CONFIG = 'stdlib/misc/config', LOGGER = 'stdlib/misc/logger', QUEUE = 'stdlib/misc/queue', EVENT = 'stdlib/event/event', GUI = 'stdlib/event/gui', PLAYER = 'stdlib/event/player', FORCE = 'stdlib/event/force', TABLE = 'stdlib/utils/table', STRING = 'stdlib/utils/string', MATH = 'stdlib/utils/math' } for glob, path in pairs(files) do _G[glob] = require('__stdlib__/' .. (path:gsub('%.', '/'))) -- extra () required to emulate select(1) end end function STDLIB.create_stdlib_data_globals(files) files = files or { RECIPE = 'stdlib/data/recipe', ITEM = 'stdlib/data/item', FLUID = 'stdlib/data/fluid', ENTITY = 'stdlib/data/entity', TECHNOLOGY = 'stdlib/data/technology', CATEGORY = 'stdlib/data/category', DATA = 'stdlib/data/data' } STDLIB.create_stdlib_globals(files) end return STDLIB
--- Additional lua globals -- @module Utils.Globals STDLIB = { config = require('__stdlib__/stdlib/config') } --Since debug can be overridden we define a fallback function here. local _traceback = function() return '' end traceback = type(debug) == 'table' and debug.traceback or _traceback serpent = serpent or require('__stdlib__/stdlib/vendor/serpent') inspect = require('__stdlib__/stdlib/vendor/inspect') local Table = require('__stdlib__/stdlib/utils/table') local Math = require('__stdlib__/stdlib/utils/math') local String = require('__stdlib__/stdlib/utils/string') _G.table_size = _G.table_size or Table.size -- Set up default stuff for testing, -- defines will already be available in an active mod or busted setup specs if not _G.defines then _G.table.unpack = _G.table.unpack or unpack if STDLIB.config.control or STDLIB.config.game then local world = require('__stdlib__/spec/setup/world').bootstrap() if STDLIB.config.game then world.init() end else require('__stdlib__/spec/setup/dataloader') end _G.log = function(msg) print(msg) end end -- Defines Mutates require('__stdlib__/stdlib/utils/defines/color') require('__stdlib__/stdlib/utils/defines/anticolor') require('__stdlib__/stdlib/utils/defines/lightcolor') require('__stdlib__/stdlib/utils/defines/time') --- Require a file that may not exist -- @tparam string module path to the module -- @tparam boolean suppress_all suppress all errors, not just file_not_found -- @treturn mixed function prequire(module, suppress_all) local ok, err = pcall(require, module) if ok then return err elseif not suppress_all and not err:find('^module .* not found') then error(err) end end --- Temporarily removes __tostring handlers and calls tostring -- @tparam mixed t object to call rawtostring on -- @treturn string function rawtostring(t) local m = getmetatable(t) if m then local f = m.__tostring m.__tostring = nil local s = tostring(t) m.__tostring = f return s else return tostring(t) end end --- Returns t if the expression is true. f if false -- @tparam mixed exp The expression to evaluate -- @tparam mixed t the true return -- @tparam mixed f the false return -- @treturn boolean function inline_if(exp, t, f) if exp then return t else return f end end function concat(lhs, rhs) return tostring(lhs) .. tostring(rhs) end --- install the Table library into global table function STDLIB.install_table() for k, v in pairs(Table) do _G.table[k] = v end end --- Install the Math library into global math function STDLIB.install_math() for k, v in pairs(Math) do _G.math[k] = v end end --- Install the string library into global string function STDLIB.install_string() for k, v in pairs(String) do _G.string[k] = v end setmetatable(string, nil) end --- Install Math, String, Table into their global counterparts. function STDLIB.install_all_utils() STDLIB.install.math() STDLIB.install.string() STDLIB.install.table() end --- Reload a required file, NOT IMPLEMENTED function STDLIB.reload_class() end --- load the stdlib into globals, by default it loads everything into an ALLCAPS name. -- Alternatively you can pass a dictionary of `[global names] -> [require path]`. -- @tparam[opt] table files -- @usage -- STDLIB.create_stdlib_globals() function STDLIB.create_stdlib_globals(files) files = files or { GAME = 'stdlib/game', AREA = 'stdlib/area/area', POSITION = 'stdlib/area/position', TILE = 'stdlib/area/tile', SURFACE = 'stdlib/area/surface', CHUNK = 'stdlib/area/chunk', COLOR = 'stdlib/utils/color', ENTITY = 'stdlib/entity/entity', INVENTORY = 'stdlib/entity/inventory', RESOURCE = 'stdlib/entity/resource', CONFIG = 'stdlib/misc/config', LOGGER = 'stdlib/misc/logger', QUEUE = 'stdlib/misc/queue', EVENT = 'stdlib/event/event', GUI = 'stdlib/event/gui', PLAYER = 'stdlib/event/player', FORCE = 'stdlib/event/force', TABLE = 'stdlib/utils/table', STRING = 'stdlib/utils/string', MATH = 'stdlib/utils/math' } for glob, path in pairs(files) do _G[glob] = require('__stdlib__/' .. (path:gsub('%.', '/'))) -- extra () required to emulate select(1) end end function STDLIB.create_stdlib_data_globals(files) files = files or { RECIPE = 'stdlib/data/recipe', ITEM = 'stdlib/data/item', FLUID = 'stdlib/data/fluid', ENTITY = 'stdlib/data/entity', TECHNOLOGY = 'stdlib/data/technology', CATEGORY = 'stdlib/data/category', DATA = 'stdlib/data/data' } STDLIB.create_stdlib_globals(files) end return STDLIB
Fix global
Fix global
Lua
isc
Afforess/Factorio-Stdlib
2d235a3b0912d5663ff7a6376a69e4bbd2484e97
applications/luci-statistics/luasrc/statistics/i18n.lua
applications/luci-statistics/luasrc/statistics/i18n.lua
--[[ Luci statistics - diagram i18n helper (c) 2008 Freifunk Leipzig / Jo-Philipp Wich <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- module("luci.statistics.i18n", package.seeall) require("luci.util") require("luci.i18n") Instance = luci.util.class() function Instance.__init__( self, graph ) self.i18n = luci.i18n self.graph = graph self.i18n.loadc("rrdtool") self.i18n.loadc("statistics") end function Instance._subst( self, str, val ) str = str:gsub( "%%H", self.graph.opts.host or "" ) str = str:gsub( "%%pn", val.plugin or "" ) str = str:gsub( "%%pi", val.pinst or "" ) str = str:gsub( "%%dt", val.dtype or "" ) str = str:gsub( "%%di", val.dinst or "" ) str = str:gsub( "%%ds", val.dsrc or "" ) return str end function Instance.title( self, plugin, pinst, dtype, dinst ) local title = self.i18n.translate( string.format( "stat_dg_title_%s_%s_%s", plugin, pinst, dtype ), self.i18n.translate( string.format( "stat_dg_title_%s_%s", plugin, pinst ), self.i18n.translate( string.format( "stat_dg_title_%s__%s", plugin, dtype ), self.i18n.translate( string.format( "stat_dg_title_%s", plugin ), self.graph:_mkpath( plugin, pinst, dtype ) ) ) ) ) return self:_subst( title, { plugin = plugin, pinst = pinst, dtype = dtype, dinst = dinst } ) end function Instance.label( self, plugin, pinst, dtype, dinst ) local label = self.i18n.translate( string.format( "stat_dg_label_%s_%s_%s", plugin, pinst, dtype ), self.i18n.translate( string.format( "stat_dg_label_%s_%s", plugin, pinst ), self.i18n.translate( string.format( "stat_dg_label_%s__%s", plugin, dtype ), self.i18n.translate( string.format( "stat_dg_label_%s", plugin ), self.graph:_mkpath( plugin, pinst, dtype ) ) ) ) ) return self:_subst( label, { plugin = plugin, pinst = pinst, dtype = dtype, dinst = dinst } ) end function Instance.ds( self, source ) local label = self.i18n.translate( string.format( "stat_ds_%s_%s_%s", source.type, source.instance, source.ds ), self.i18n.translate( string.format( "stat_ds_%s_%s", source.type, source.instance ), self.i18n.translate( string.format( "stat_ds_label_%s__%s", source.type, source.ds ), self.i18n.translate( string.format( "stat_ds_%s", source.type ), source.type .. "_" .. source.instance:gsub("[^%w]","_") .. "_" .. source.ds ) ) ) ) return self:_subst( label, { dtype = source.type, dinst = source.instance, dsrc = source.ds } ) end
--[[ Luci statistics - diagram i18n helper (c) 2008 Freifunk Leipzig / Jo-Philipp Wich <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- module("luci.statistics.i18n", package.seeall) require("luci.util") require("luci.i18n") Instance = luci.util.class() function Instance.__init__( self, graph ) self.i18n = luci.i18n self.graph = graph self.i18n.loadc("rrdtool") self.i18n.loadc("statistics") end function Instance._subst( self, str, val ) str = str:gsub( "%%H", self.graph.opts.host or "" ) str = str:gsub( "%%pn", val.plugin or "" ) str = str:gsub( "%%pi", val.pinst or "" ) str = str:gsub( "%%dt", val.dtype or "" ) str = str:gsub( "%%di", val.dinst or "" ) str = str:gsub( "%%ds", val.dsrc or "" ) return str end function Instance.title( self, plugin, pinst, dtype, dinst ) local title = self.i18n.string( string.format( "stat_dg_title_%s_%s_%s", plugin, pinst, dtype ), self.i18n.string( string.format( "stat_dg_title_%s_%s", plugin, pinst ), self.i18n.string( string.format( "stat_dg_title_%s__%s", plugin, dtype ), self.i18n.string( string.format( "stat_dg_title_%s", plugin ), self.graph:_mkpath( plugin, pinst, dtype ) ) ) ) ) return self:_subst( title, { plugin = plugin, pinst = pinst, dtype = dtype, dinst = dinst } ) end function Instance.label( self, plugin, pinst, dtype, dinst ) local label = self.i18n.string( string.format( "stat_dg_label_%s_%s_%s", plugin, pinst, dtype ), self.i18n.string( string.format( "stat_dg_label_%s_%s", plugin, pinst ), self.i18n.string( string.format( "stat_dg_label_%s__%s", plugin, dtype ), self.i18n.string( string.format( "stat_dg_label_%s", plugin ), self.graph:_mkpath( plugin, pinst, dtype ) ) ) ) ) return self:_subst( label, { plugin = plugin, pinst = pinst, dtype = dtype, dinst = dinst } ) end function Instance.ds( self, source ) local label = self.i18n.string( string.format( "stat_ds_%s_%s_%s", source.type, source.instance, source.ds ), self.i18n.string( string.format( "stat_ds_%s_%s", source.type, source.instance ), self.i18n.string( string.format( "stat_ds_label_%s__%s", source.type, source.ds ), self.i18n.string( string.format( "stat_ds_%s", source.type ), source.type .. "_" .. source.instance:gsub("[^%w]","_") .. "_" .. source.ds ) ) ) ) return self:_subst( label, { dtype = source.type, dinst = source.instance, dsrc = source.ds } ) end
application/luci-statistics: fix i18n binding, use string() instead of translate
application/luci-statistics: fix i18n binding, use string() instead of translate
Lua
apache-2.0
deepak78/luci,8devices/luci,8devices/luci,deepak78/luci,deepak78/luci,deepak78/luci,deepak78/luci,8devices/luci,deepak78/luci,8devices/luci,8devices/luci,deepak78/luci,8devices/luci,deepak78/luci
391bc82dbeaea234ff6457b6775a0abf27a6beae
kong/clustering/init.lua
kong/clustering/init.lua
local _M = {} local pl_file = require("pl.file") local pl_tablex = require("pl.tablex") local ssl = require("ngx.ssl") local openssl_x509 = require("resty.openssl.x509") local ngx_null = ngx.null local ngx_md5 = ngx.md5 local tostring = tostring local assert = assert local concat = table.concat local sort = table.sort local type = type local MT = { __index = _M, } local function table_to_sorted_string(t) if t == ngx_null then return "/null/" end local typ = type(t) if typ == "table" then local i = 1 local o = { "{" } for k, v in pl_tablex.sort(t) do o[i+1] = table_to_sorted_string(k) o[i+2] = ":" o[i+3] = table_to_sorted_string(v) o[i+4] = ";" i=i+4 end if i == 1 then i = i + 1 end o[i] = "}" return concat(o, nil, 1, i) elseif typ == "string" then return '$' .. t .. '$' elseif typ == "number" then return '#' .. tostring(t) .. '#' elseif typ == "boolean" then return '?' .. tostring(t) .. '?' else return '(' .. tostring(t) .. ')' end end function _M.new(conf) assert(conf, "conf can not be nil", 2) local self = { conf = conf, } setmetatable(self, MT) -- note: pl_file.read throws error on failure so -- no need for error checking local cert = pl_file.read(conf.cluster_cert) self.cert = assert(ssl.parse_pem_cert(cert)) cert = openssl_x509.new(cert, "PEM") self.cert_digest = cert:digest("sha256") local key = pl_file.read(conf.cluster_cert_key) self.cert_key = assert(ssl.parse_pem_priv_key(key)) self.child = require("kong.clustering." .. conf.role).new(self) return self end function _M:calculate_config_hash(config_table) return ngx_md5(table_to_sorted_string(config_table)) end function _M:handle_cp_websocket() return self.child:handle_cp_websocket() end function _M:init_worker() self.plugins_list = assert(kong.db.plugins:get_handlers()) sort(self.plugins_list, function(a, b) return a.name:lower() < b.name:lower() end) self.plugins_list = pl_tablex.map(function(p) return { name = p.name, version = p.handler.VERSION, } end, self.plugins_list) self.child:init_worker() end return _M
local _M = {} local pl_file = require("pl.file") local pl_tablex = require("pl.tablex") local ssl = require("ngx.ssl") local openssl_x509 = require("resty.openssl.x509") local ngx_null = ngx.null local ngx_md5 = ngx.md5 local tostring = tostring local assert = assert local error = error local concat = table.concat local sort = table.sort local type = type local MT = { __index = _M, } local compare_sorted_strings local function to_sorted_string(value) if value == ngx_null then return "/null/" end local t = type(value) if t == "table" then local i = 1 local o = { "{" } for k, v in pl_tablex.sort(value, compare_sorted_strings) do o[i+1] = to_sorted_string(k) o[i+2] = ":" o[i+3] = to_sorted_string(v) o[i+4] = ";" i=i+4 end if i == 1 then i = i + 1 end o[i] = "}" return concat(o, nil, 1, i) elseif t == "string" then return "$" .. value .. "$" elseif t == "number" then return "#" .. tostring(value) .. "#" elseif t == "boolean" then return "?" .. tostring(value) .. "?" else error("invalid type to be sorted (JSON types are supported") end end compare_sorted_strings = function(a, b) a = to_sorted_string(a) b = to_sorted_string(b) return a < b end function _M.new(conf) assert(conf, "conf can not be nil", 2) local self = { conf = conf, } setmetatable(self, MT) -- note: pl_file.read throws error on failure so -- no need for error checking local cert = pl_file.read(conf.cluster_cert) self.cert = assert(ssl.parse_pem_cert(cert)) cert = openssl_x509.new(cert, "PEM") self.cert_digest = cert:digest("sha256") local key = pl_file.read(conf.cluster_cert_key) self.cert_key = assert(ssl.parse_pem_priv_key(key)) self.child = require("kong.clustering." .. conf.role).new(self) return self end function _M:calculate_config_hash(config_table) return ngx_md5(to_sorted_string(config_table)) end function _M:handle_cp_websocket() return self.child:handle_cp_websocket() end function _M:init_worker() self.plugins_list = assert(kong.db.plugins:get_handlers()) sort(self.plugins_list, function(a, b) return a.name:lower() < b.name:lower() end) self.plugins_list = pl_tablex.map(function(p) return { name = p.name, version = p.handler.VERSION, } end, self.plugins_list) self.child:init_worker() end return _M
fix(clustering) error on hashing when given invalid types
fix(clustering) error on hashing when given invalid types
Lua
apache-2.0
Kong/kong,Kong/kong,Kong/kong
9eb7dc6bc9fe776cbe15b92cb57f3cd815093309
realism/server/character_kill.lua
realism/server/character_kill.lua
--[[ The MIT License (MIT) Copyright (c) 2014 Socialz (+ soc-i-alz GitHub organization) 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 characterKill( characterID, causeOfDeath ) local characterPlayer = exports.common:getPlayerByCharacterID( characterID ) if ( characterPlayer ) then exports.accounts:saveCharacter( characterPlayer ) end local character = exports.accounts:getCharacter( characterID ) if ( character ) and ( character.is_dead == 0 ) then exports.database:execute( "UPDATE `characters` SET `is_dead` = '1', `cause_of_death` = ? WHERE `id` = ?", causeOfDeath, characterID ) local ped = createPed( character.skin_id, character.pos_x, character.pos_y, character.pos_z, character.rotation, false ) setElementInterior( ped, character.interior ) setElementDimension( ped, character.dimension ) killPed( ped ) exports.security:modifyElementData( ped, "npc:character_kill.id", character.id, true ) exports.security:modifyElementData( ped, "npc:character_kill.reason", causeOfDeath, true ) local player = exports.common:getPlayerByAccountID( character.account ) if ( player ) then if ( characterPlayer ) then exports.accounts:characterSelection( player ) outputChatBox( "You were character killed by an administrator.", player, 230, 180, 95, false ) outputChatBox( " Cause of death: " .. causeOfDeath, player, 230, 180, 95, false ) else exports.accounts:updateCharacters( player ) end end return true end return false end function characterResurrect( characterID ) local character = exports.accounts:getCharacter( characterID ) if ( character ) and ( character.is_dead ~= 0 ) then exports.database:execute( "UPDATE `characters` SET `is_dead` = '0', `cause_of_death` = '' WHERE `id` = ?", character.id ) local ped = findCharacterKillPed( character.id ) if ( ped ) then destroyElement( ped ) end local player = exports.common:getPlayerByAccountID( character.account ) if ( player ) and ( not exports.common:isPlayerPlaying( player ) ) then exports.accounts:updateCharacters( player ) end return true end return false end function findCharacterKillPed( characterID ) for _, ped in ipairs( getElementsByType( "ped", getResourceDynamicElementRoot( resource ) ) ) do if ( getElementData( ped, "npc:character_kill.id" ) ) and ( tonumber( getElementData( ped, "npc:character_kill.id" ) ) == characterID ) then return ped end end return false end function loadCharacterKills( ) for _, ped in ipairs( getElementsByType( "ped", getResourceDynamicElementRoot( resource ) ) ) do if ( getElementData( ped, "npc:character_kill.id" ) ) and ( tonumber( getElementData( ped, "npc:character_kill.id" ) ) == characterID ) then destroyElement( ped ) end end for _, data in ipairs( exports.database:query( "SELECT * FROM `characters` WHERE `is_dead` = '1'" ) ) do local ped = createPed( data.skin_id, data.pos_x, data.pos_y, data.pos_z ) setPedRotation( ped, data.rotation ) setElementInterior( ped, data.interior ) setElementDimension( ped, data.dimension ) killPed( ped ) exports.security:modifyElementData( ped, "npc:character_kill.id", data.id, true ) exports.security:modifyElementData( ped, "npc:character_kill.reason", data.cause_of_death, true ) end end addEventHandler( "onResourceStart", resourceRoot, function( ) loadCharacterKills( ) end )
--[[ The MIT License (MIT) Copyright (c) 2014 Socialz (+ soc-i-alz GitHub organization) 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 characterKill( characterID, causeOfDeath ) local characterPlayer = exports.common:getPlayerByCharacterID( characterID ) if ( characterPlayer ) then exports.accounts:saveCharacter( characterPlayer ) end local character = exports.accounts:getCharacter( characterID ) if ( character ) and ( character.is_dead == 0 ) then exports.database:execute( "UPDATE `characters` SET `is_dead` = '1', `cause_of_death` = ? WHERE `id` = ?", causeOfDeath, characterID ) local ped = createPed( character.skin_id, character.pos_x, character.pos_y, character.pos_z, character.rotation, false ) setElementInterior( ped, character.interior ) setElementDimension( ped, character.dimension ) killPed( ped ) exports.security:modifyElementData( ped, "npc:character_kill.id", character.id, true ) exports.security:modifyElementData( ped, "npc:character_kill.reason", causeOfDeath, true ) local player = exports.common:getPlayerByAccountID( character.account ) if ( player ) then if ( characterPlayer ) then exports.accounts:characterSelection( player ) outputChatBox( "You were character killed by an administrator.", player, 230, 180, 95, false ) outputChatBox( " Cause of death: " .. causeOfDeath, player, 230, 180, 95, false ) else exports.accounts:updateCharacters( player ) end end return true end return false end function characterResurrect( characterID ) local character = exports.accounts:getCharacter( characterID ) if ( character ) and ( character.is_dead ~= 0 ) then exports.database:execute( "UPDATE `characters` SET `is_dead` = '0', `cause_of_death` = '' WHERE `id` = ?", character.id ) local ped = findCharacterKillPed( character.id ) if ( ped ) then destroyElement( ped ) end local player = exports.common:getPlayerByAccountID( character.account ) if ( player ) and ( not exports.common:isPlayerPlaying( player ) ) then exports.accounts:updateCharacters( player ) end return true end return false end function findCharacterKillPed( characterID ) for _, ped in ipairs( getElementsByType( "ped", getResourceDynamicElementRoot( resource ) ) ) do if ( getElementData( ped, "npc:character_kill.id" ) ) and ( tonumber( getElementData( ped, "npc:character_kill.id" ) ) == characterID ) then return ped end end return false end function loadCharacterKills( ) for _, ped in ipairs( getElementsByType( "ped", getResourceDynamicElementRoot( resource ) ) ) do if ( getElementData( ped, "npc:character_kill.id" ) ) and ( tonumber( getElementData( ped, "npc:character_kill.id" ) ) == characterID ) then destroyElement( ped ) end end local characterKills = exports.database:query( "SELECT * FROM `characters` WHERE `is_dead` = '1'" ) if ( characterKills ) then for _, data in ipairs( characterKills ) do local ped = createPed( data.skin_id, data.pos_x, data.pos_y, data.pos_z ) setPedRotation( ped, data.rotation ) setElementInterior( ped, data.interior ) setElementDimension( ped, data.dimension ) killPed( ped ) exports.security:modifyElementData( ped, "npc:character_kill.id", data.id, true ) exports.security:modifyElementData( ped, "npc:character_kill.reason", data.cause_of_death, true ) end end end addEventHandler( "onResourceStart", resourceRoot, function( ) loadCharacterKills( ) end )
realism: fix for character kill load error
realism: fix for character kill load error No table exists, therefore fails. Should just prevent one error to popup about iterating a non-table.
Lua
mit
smile-tmb/lua-mta-fairplay-roleplay
6e72569ce2e9cf1ff5c76413fedff3df6e22a45c
screen.lua
screen.lua
--[[ Copyright (C) 2011 Hans-Werner Hilse <[email protected]> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]]-- --[[ Codes for rotation modes: 1 for no rotation, 2 for landscape with bottom on the right side of screen, etc. 2 +--------------+ | +----------+ | | | | | | | Freedom! | | | | | | | | | | 3 | | | | 1 | | | | | | | | | +----------+ | | | | | +--------------+ 0 --]] Screen = { cur_rotation_mode = 0, -- these two variabls are used to help switching from framework to reader native_rotation_mode = nil, kpv_rotation_mode = nil, saved_bb = nil, } -- @orien: 1 for clockwise rotate, -1 for anti-clockwise -- Remember to reread screen resolution after this function call function Screen:screenRotate(orien) if orien == "clockwise" then orien = -1 elseif orien == "anticlockwise" then orien = 1 else return end self.cur_rotation_mode = (self.cur_rotation_mode + orien) % 4 -- you have to reopen framebuffer after rotate fb:setOrientation(self.cur_rotation_mode) fb:close() fb = einkfb.open("/dev/fb0") end function Screen:updateRotationMode() if KEY_FW_DOWN == 116 then -- in EMU mode always set to 0 self.cur_rotation_mode = 0 else orie_fd = assert(io.open("/sys/module/eink_fb_hal_broads/parameters/bs_orientation", "r")) updown_fd = assert(io.open("/sys/module/eink_fb_hal_broads/parameters/bs_upside_down", "r")) self.cur_rotation_mode = orie_fd:read() + (updown_fd:read() * 2) end end function Screen:saveCurrentBB() local width, height = G_width, G_height if not self.saved_bb then self.saved_bb = Blitbuffer.new(width, height) end if self.saved_bb:getWidth() ~= width then self.saved_bb:free() self.saved_bb = Blitbuffer.new(width, height) end self.saved_bb:blitFullFrom(fb.bb) end function Screen:restoreFromSavedBB() self:restoreFromBB(self.saved_bb) end function Screen:getCurrentScreenBB() local bb = Blitbuffer.new(G_width, G_height) bb:blitFullFrom(fb.bb) return bb end function Screen:restoreFromBB(bb) fb.bb:blitFullFrom(bb) end
--[[ Copyright (C) 2011 Hans-Werner Hilse <[email protected]> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]]-- --[[ Codes for rotation modes: 1 for no rotation, 2 for landscape with bottom on the right side of screen, etc. 2 +--------------+ | +----------+ | | | | | | | Freedom! | | | | | | | | | | 3 | | | | 1 | | | | | | | | | +----------+ | | | | | +--------------+ 0 --]] Screen = { cur_rotation_mode = 0, -- these two variabls are used to help switching from framework to reader native_rotation_mode = nil, kpv_rotation_mode = nil, saved_bb = nil, } -- @orien: 1 for clockwise rotate, -1 for anti-clockwise -- Remember to reread screen resolution after this function call function Screen:screenRotate(orien) if orien == "clockwise" then orien = -1 elseif orien == "anticlockwise" then orien = 1 else return end self.cur_rotation_mode = (self.cur_rotation_mode + orien) % 4 -- you have to reopen framebuffer after rotate fb:setOrientation(self.cur_rotation_mode) fb:close() fb = einkfb.open("/dev/fb0") end function Screen:updateRotationMode() if KEY_FW_DOWN == 116 then -- in EMU mode always set to 0 self.cur_rotation_mode = 0 else orie_fd = assert(io.open("/sys/module/eink_fb_hal_broads/parameters/bs_orientation", "r")) updown_fd = assert(io.open("/sys/module/eink_fb_hal_broads/parameters/bs_upside_down", "r")) self.cur_rotation_mode = orie_fd:read() + (updown_fd:read() * 2) end end function Screen:saveCurrentBB() local width, height = G_width, G_height if not self.saved_bb then self.saved_bb = Blitbuffer.new(width, height) end if self.saved_bb:getWidth() ~= width then self.saved_bb:free() self.saved_bb = Blitbuffer.new(width, height) end self.saved_bb:blitFullFrom(fb.bb) end function Screen:restoreFromSavedBB() self:restoreFromBB(self.saved_bb) end function Screen:getCurrentScreenBB() local bb = Blitbuffer.new(G_width, G_height) bb:blitFullFrom(fb.bb) return bb end function Screen:restoreFromBB(bb) if bb then fb.bb:blitFullFrom(bb) else debug("Got nil bb in restoreFromSavedBB!") end end
fix: check nil argument in blitFullFrom method
fix: check nil argument in blitFullFrom method
Lua
agpl-3.0
Frenzie/koreader-base,frankyifei/koreader-base,koreader/koreader-base,houqp/koreader-base,Hzj-jie/koreader-base,noname007/koreader,Frenzie/koreader,houqp/koreader,NiLuJe/koreader,koreader/koreader,poire-z/koreader,apletnev/koreader-base,Hzj-jie/koreader-base,Frenzie/koreader-base,Markismus/koreader,NickSavage/koreader,koreader/koreader,apletnev/koreader-base,pazos/koreader,frankyifei/koreader,frankyifei/koreader-base,ashhher3/koreader,koreader/koreader-base,mihailim/koreader,NiLuJe/koreader,Hzj-jie/koreader-base,frankyifei/koreader-base,Hzj-jie/koreader,koreader/koreader-base,NiLuJe/koreader-base,Frenzie/koreader-base,robert00s/koreader,NiLuJe/koreader-base,poire-z/koreader,apletnev/koreader-base,lgeek/koreader,houqp/koreader-base,mwoz123/koreader,NiLuJe/koreader-base,chihyang/koreader,Frenzie/koreader,apletnev/koreader-base,apletnev/koreader,Hzj-jie/koreader-base,houqp/koreader-base,Frenzie/koreader-base,ashang/koreader,koreader/koreader-base,houqp/koreader-base,NiLuJe/koreader-base,frankyifei/koreader-base,chrox/koreader
1b48ae1188b829c71f9cdde4dc98ff1df41cfad0
modules/freifunk/luasrc/model/cbi/freifunk/public_status.lua
modules/freifunk/luasrc/model/cbi/freifunk/public_status.lua
require "luci.sys" require "luci.tools.webadmin" local uci = luci.model.uci.cursor_state() local ffzone = luci.tools.webadmin.firewall_find_zone("freifunk") local ffznet = ffzone and uci:get("firewall", ffzone, "network") local ffwifs = ffznet and luci.util.split(ffznet, " ") or {} -- System -- f = SimpleForm("system", "System") f.submit = false f.reset = false local system, model, memtotal, memcached, membuffers, memfree = luci.sys.sysinfo() local uptime = luci.sys.uptime() f:field(DummyValue, "_system", translate("system")).value = system f:field(DummyValue, "_cpu", translate("m_i_processor")).value = model local load1, load5, load15 = luci.sys.loadavg() f:field(DummyValue, "_la", translate("load")).value = string.format("%.2f, %.2f, %.2f", load1, load5, load15) f:field(DummyValue, "_memtotal", translate("m_i_memory")).value = string.format("%.2f MB (%.0f%% %s, %.0f%% %s, %.0f%% %s)", tonumber(memtotal) / 1024, 100 * memcached / memtotal, translate("mem_cached") or "", 100 * membuffers / memtotal, translate("mem_buffered") or "", 100 * memfree / memtotal, translate("mem_free") or "") f:field(DummyValue, "_systime", translate("m_i_systemtime")).value = os.date("%c") f:field(DummyValue, "_uptime", translate("m_i_uptime")).value = luci.tools.webadmin.date_format(tonumber(uptime)) -- Wireless -- local wireless = uci:get_all("wireless") local wifidata = luci.sys.wifi.getiwconfig() local ifaces = {} for k, v in pairs(wireless) do if v[".type"] == "wifi-iface" and luci.util.contains(ffwifs, v.device) then table.insert(ifaces, v) end end m = SimpleForm("wireless", "Freifunk WLAN") m.submit = false m.reset = false s = m:section(Table, ifaces, translate("networks")) link = s:option(DummyValue, "_link", translate("link")) function link.cfgvalue(self, section) local ifname = self.map:get(section, "ifname") return wifidata[ifname] and wifidata[ifname]["Link Quality"] or "-" end essid = s:option(DummyValue, "ssid", "ESSID") bssid = s:option(DummyValue, "_bsiid", "BSSID") function bssid.cfgvalue(self, section) local ifname = self.map:get(section, "ifname") return (wifidata[ifname] and (wifidata[ifname].Cell or wifidata[ifname]["Access Point"])) or "-" end channel = s:option(DummyValue, "channel", translate("channel")) function channel.cfgvalue(self, section) return wireless[self.map:get(section, "device")].channel end protocol = s:option(DummyValue, "_mode", translate("protocol")) function protocol.cfgvalue(self, section) local mode = wireless[self.map:get(section, "device")].mode return mode and "802." .. mode end mode = s:option(DummyValue, "mode", translate("mode")) encryption = s:option(DummyValue, "encryption", translate("iwscan_encr")) power = s:option(DummyValue, "_power", translate("power")) function power.cfgvalue(self, section) local ifname = self.map:get(section, "ifname") return wifidata[ifname] and wifidata[ifname]["Tx-Power"] or "-" end scan = s:option(Button, "_scan", translate("scan")) scan.inputstyle = "find" function scan.cfgvalue(self, section) return self.map:get(section, "ifname") or false end t2 = m:section(Table, {}, translate("iwscan"), translate("iwscan1")) function scan.write(self, section) t2.render = t2._render local ifname = self.map:get(section, "ifname") luci.util.update(t2.data, luci.sys.wifi.iwscan(ifname)) end t2._render = t2.render t2.render = function() end t2:option(DummyValue, "Quality", translate("iwscan_link")) essid = t2:option(DummyValue, "ESSID", "ESSID") function essid.cfgvalue(self, section) return luci.util.pcdata(self.map:get(section, "ESSID")) end t2:option(DummyValue, "Address", "BSSID") t2:option(DummyValue, "Mode", translate("mode")) chan = t2:option(DummyValue, "channel", translate("channel")) function chan.cfgvalue(self, section) return self.map:get(section, "Channel") or self.map:get(section, "Frequency") or "-" end t2:option(DummyValue, "Encryption key", translate("iwscan_encr")) t2:option(DummyValue, "Signal level", translate("iwscan_signal")) t2:option(DummyValue, "Noise level", translate("iwscan_noise")) -- Routes -- r = SimpleForm("routes", "Standardrouten") r.submit = false r.reset = false local routes = {} for i, route in ipairs(luci.sys.net.routes()) do if route.dest:prefix() == 0 then routes[#routes+1] = route end end v = r:section(Table, routes) net = v:option(DummyValue, "iface", translate("network")) function net.cfgvalue(self, section) return luci.tools.webadmin.iface_get_network(routes[section].device) or routes[section].device end target = v:option(DummyValue, "target", translate("target")) function target.cfgvalue(self, section) return routes[section].dest:network():string() end netmask = v:option(DummyValue, "netmask", translate("netmask")) function netmask.cfgvalue(self, section) return routes[section].dest:mask():string() end gateway = v:option(DummyValue, "gateway", translate("gateway")) function gateway.cfgvalue(self, section) return routes[section].gateway:string() end metric = v:option(DummyValue, "metric", translate("metric")) function metric.cfgvalue(self, section) return routes[section].metric end local routes6 = {} for i, route in ipairs(luci.sys.net.routes6() or {}) do if route.dest:prefix() == 0 then routes6[#routes6+1] = route end end if #routes6 > 0 then v6 = r:section(Table, routes6) net = v6:option(DummyValue, "iface", translate("network")) function net.cfgvalue(self, section) return luci.tools.webadmin.iface_get_network(routes[section].device) or routes6[section].device end target = v6:option(DummyValue, "target", translate("target")) function target.cfgvalue(self, section) return routes6[section].dest:string() end gateway = v6:option(DummyValue, "gateway6", translate("gateway6")) function gateway.cfgvalue(self, section) return routes6[section].source:string() end metric = v6:option(DummyValue, "metric", translate("metric")) function metric.cfgvalue(self, section) return string.format("%X", routes6[section].metric) end end return f, m, r
require "luci.sys" require "luci.tools.webadmin" local bit = require "bit" local uci = luci.model.uci.cursor_state() local ffzone = luci.tools.webadmin.firewall_find_zone("freifunk") local ffznet = ffzone and uci:get("firewall", ffzone, "network") local ffwifs = ffznet and luci.util.split(ffznet, " ") or {} -- System -- f = SimpleForm("system", "System") f.submit = false f.reset = false local system, model, memtotal, memcached, membuffers, memfree = luci.sys.sysinfo() local uptime = luci.sys.uptime() f:field(DummyValue, "_system", translate("system")).value = system f:field(DummyValue, "_cpu", translate("m_i_processor")).value = model local load1, load5, load15 = luci.sys.loadavg() f:field(DummyValue, "_la", translate("load")).value = string.format("%.2f, %.2f, %.2f", load1, load5, load15) f:field(DummyValue, "_memtotal", translate("m_i_memory")).value = string.format("%.2f MB (%.0f%% %s, %.0f%% %s, %.0f%% %s)", tonumber(memtotal) / 1024, 100 * memcached / memtotal, translate("mem_cached") or "", 100 * membuffers / memtotal, translate("mem_buffered") or "", 100 * memfree / memtotal, translate("mem_free") or "") f:field(DummyValue, "_systime", translate("m_i_systemtime")).value = os.date("%c") f:field(DummyValue, "_uptime", translate("m_i_uptime")).value = luci.tools.webadmin.date_format(tonumber(uptime)) -- Wireless -- local wireless = uci:get_all("wireless") local wifidata = luci.sys.wifi.getiwconfig() local ifaces = {} for k, v in pairs(wireless) do if v[".type"] == "wifi-iface" and luci.util.contains(ffwifs, v.device) then table.insert(ifaces, v) end end m = SimpleForm("wireless", "Freifunk WLAN") m.submit = false m.reset = false s = m:section(Table, ifaces, translate("networks")) link = s:option(DummyValue, "_link", translate("link")) function link.cfgvalue(self, section) local ifname = self.map:get(section, "ifname") return wifidata[ifname] and wifidata[ifname]["Link Quality"] or "-" end essid = s:option(DummyValue, "ssid", "ESSID") bssid = s:option(DummyValue, "_bsiid", "BSSID") function bssid.cfgvalue(self, section) local ifname = self.map:get(section, "ifname") return (wifidata[ifname] and (wifidata[ifname].Cell or wifidata[ifname]["Access Point"])) or "-" end channel = s:option(DummyValue, "channel", translate("channel")) function channel.cfgvalue(self, section) return wireless[self.map:get(section, "device")].channel end protocol = s:option(DummyValue, "_mode", translate("protocol")) function protocol.cfgvalue(self, section) local mode = wireless[self.map:get(section, "device")].mode return mode and "802." .. mode end mode = s:option(DummyValue, "mode", translate("mode")) encryption = s:option(DummyValue, "encryption", translate("iwscan_encr")) power = s:option(DummyValue, "_power", translate("power")) function power.cfgvalue(self, section) local ifname = self.map:get(section, "ifname") return wifidata[ifname] and wifidata[ifname]["Tx-Power"] or "-" end scan = s:option(Button, "_scan", translate("scan")) scan.inputstyle = "find" function scan.cfgvalue(self, section) return self.map:get(section, "ifname") or false end t2 = m:section(Table, {}, translate("iwscan"), translate("iwscan1")) function scan.write(self, section) t2.render = t2._render local ifname = self.map:get(section, "ifname") luci.util.update(t2.data, luci.sys.wifi.iwscan(ifname)) end t2._render = t2.render t2.render = function() end t2:option(DummyValue, "Quality", translate("iwscan_link")) essid = t2:option(DummyValue, "ESSID", "ESSID") function essid.cfgvalue(self, section) return luci.util.pcdata(self.map:get(section, "ESSID")) end t2:option(DummyValue, "Address", "BSSID") t2:option(DummyValue, "Mode", translate("mode")) chan = t2:option(DummyValue, "channel", translate("channel")) function chan.cfgvalue(self, section) return self.map:get(section, "Channel") or self.map:get(section, "Frequency") or "-" end t2:option(DummyValue, "Encryption key", translate("iwscan_encr")) t2:option(DummyValue, "Signal level", translate("iwscan_signal")) t2:option(DummyValue, "Noise level", translate("iwscan_noise")) -- Routes -- r = SimpleForm("routes", "Standardrouten") r.submit = false r.reset = false local routes = {} for i, route in ipairs(luci.sys.net.routes()) do if route.dest:prefix() == 0 then routes[#routes+1] = route end end v = r:section(Table, routes) net = v:option(DummyValue, "iface", translate("network")) function net.cfgvalue(self, section) return luci.tools.webadmin.iface_get_network(routes[section].device) or routes[section].device end target = v:option(DummyValue, "target", translate("target")) function target.cfgvalue(self, section) return routes[section].dest:network():string() end netmask = v:option(DummyValue, "netmask", translate("netmask")) function netmask.cfgvalue(self, section) return routes[section].dest:mask():string() end gateway = v:option(DummyValue, "gateway", translate("gateway")) function gateway.cfgvalue(self, section) return routes[section].gateway:string() end metric = v:option(DummyValue, "metric", translate("metric")) function metric.cfgvalue(self, section) return routes[section].metric end local routes6 = {} for i, route in ipairs(luci.sys.net.routes6() or {}) do if route.dest:prefix() == 0 then routes6[#routes6+1] = route end end if #routes6 > 0 then v6 = r:section(Table, routes6) net = v6:option(DummyValue, "iface", translate("network")) function net.cfgvalue(self, section) return luci.tools.webadmin.iface_get_network(routes[section].device) or routes6[section].device end target = v6:option(DummyValue, "target", translate("target")) function target.cfgvalue(self, section) return routes6[section].dest:string() end gateway = v6:option(DummyValue, "gateway6", translate("gateway6")) function gateway.cfgvalue(self, section) return routes6[section].source:string() end metric = v6:option(DummyValue, "metric", translate("metric")) function metric.cfgvalue(self, section) local metr = routes6[section].metric local lower = bit.band(metr, 0xffff) local higher = bit.rshift(bit.band(metr, 0xffff0000), 16) return "%04X%04X" % {higher, lower} end end return f, m, r
Fix display of v6 Routing metric on Freifunk status pages
Fix display of v6 Routing metric on Freifunk status pages
Lua
apache-2.0
thess/OpenWrt-luci,rogerpueyo/luci,oneru/luci,openwrt/luci,urueedi/luci,MinFu/luci,ReclaimYourPrivacy/cloak-luci,mumuqz/luci,wongsyrone/luci-1,LazyZhu/openwrt-luci-trunk-mod,dismantl/luci-0.12,sujeet14108/luci,oyido/luci,981213/luci-1,zhaoxx063/luci,981213/luci-1,teslamint/luci,RuiChen1113/luci,hnyman/luci,Wedmer/luci,hnyman/luci,nmav/luci,Hostle/openwrt-luci-multi-user,cappiewu/luci,kuoruan/luci,LuttyYang/luci,deepak78/new-luci,aa65535/luci,jchuang1977/luci-1,artynet/luci,remakeelectric/luci,hnyman/luci,sujeet14108/luci,deepak78/new-luci,bright-things/ionic-luci,openwrt/luci,LuttyYang/luci,nmav/luci,lbthomsen/openwrt-luci,male-puppies/luci,sujeet14108/luci,aa65535/luci,lcf258/openwrtcn,RedSnake64/openwrt-luci-packages,aa65535/luci,slayerrensky/luci,jchuang1977/luci-1,deepak78/new-luci,daofeng2015/luci,jlopenwrtluci/luci,LazyZhu/openwrt-luci-trunk-mod,obsy/luci,MinFu/luci,Kyklas/luci-proto-hso,zhaoxx063/luci,Sakura-Winkey/LuCI,Noltari/luci,tcatm/luci,lcf258/openwrtcn,marcel-sch/luci,kuoruan/lede-luci,RuiChen1113/luci,kuoruan/luci,cshore/luci,bright-things/ionic-luci,RedSnake64/openwrt-luci-packages,opentechinstitute/luci,oyido/luci,palmettos/test,tobiaswaldvogel/luci,Sakura-Winkey/LuCI,kuoruan/luci,marcel-sch/luci,chris5560/openwrt-luci,teslamint/luci,db260179/openwrt-bpi-r1-luci,thesabbir/luci,nwf/openwrt-luci,david-xiao/luci,MinFu/luci,taiha/luci,slayerrensky/luci,openwrt/luci,teslamint/luci,thess/OpenWrt-luci,dismantl/luci-0.12,Hostle/luci,florian-shellfire/luci,hnyman/luci,obsy/luci,981213/luci-1,Hostle/openwrt-luci-multi-user,lcf258/openwrtcn,remakeelectric/luci,tcatm/luci,artynet/luci,cshore/luci,ReclaimYourPrivacy/cloak-luci,chris5560/openwrt-luci,forward619/luci,nwf/openwrt-luci,mumuqz/luci,Hostle/luci,aircross/OpenWrt-Firefly-LuCI,obsy/luci,fkooman/luci,Hostle/openwrt-luci-multi-user,jorgifumi/luci,ff94315/luci-1,male-puppies/luci,nmav/luci,nwf/openwrt-luci,palmettos/cnLuCI,chris5560/openwrt-luci,lcf258/openwrtcn,keyidadi/luci,keyidadi/luci,deepak78/new-luci,db260179/openwrt-bpi-r1-luci,Hostle/luci,cappiewu/luci,dwmw2/luci,deepak78/new-luci,tcatm/luci,thesabbir/luci,cappiewu/luci,male-puppies/luci,openwrt-es/openwrt-luci,florian-shellfire/luci,tobiaswaldvogel/luci,ReclaimYourPrivacy/cloak-luci,zhaoxx063/luci,keyidadi/luci,jorgifumi/luci,zhaoxx063/luci,Kyklas/luci-proto-hso,fkooman/luci,chris5560/openwrt-luci,sujeet14108/luci,cshore/luci,db260179/openwrt-bpi-r1-luci,MinFu/luci,zhaoxx063/luci,cappiewu/luci,openwrt/luci,palmettos/test,artynet/luci,marcel-sch/luci,dwmw2/luci,tobiaswaldvogel/luci,slayerrensky/luci,RuiChen1113/luci,wongsyrone/luci-1,forward619/luci,Hostle/openwrt-luci-multi-user,kuoruan/luci,jchuang1977/luci-1,nmav/luci,dismantl/luci-0.12,artynet/luci,palmettos/test,981213/luci-1,NeoRaider/luci,urueedi/luci,wongsyrone/luci-1,artynet/luci,nmav/luci,opentechinstitute/luci,aircross/OpenWrt-Firefly-LuCI,jlopenwrtluci/luci,kuoruan/lede-luci,Wedmer/luci,LazyZhu/openwrt-luci-trunk-mod,LazyZhu/openwrt-luci-trunk-mod,oyido/luci,bright-things/ionic-luci,david-xiao/luci,Kyklas/luci-proto-hso,florian-shellfire/luci,Noltari/luci,teslamint/luci,marcel-sch/luci,taiha/luci,aircross/OpenWrt-Firefly-LuCI,ollie27/openwrt_luci,981213/luci-1,Hostle/openwrt-luci-multi-user,joaofvieira/luci,RedSnake64/openwrt-luci-packages,oneru/luci,nmav/luci,urueedi/luci,remakeelectric/luci,lcf258/openwrtcn,urueedi/luci,MinFu/luci,wongsyrone/luci-1,jchuang1977/luci-1,taiha/luci,Kyklas/luci-proto-hso,tcatm/luci,kuoruan/luci,taiha/luci,remakeelectric/luci,dismantl/luci-0.12,jlopenwrtluci/luci,schidler/ionic-luci,david-xiao/luci,schidler/ionic-luci,oneru/luci,aircross/OpenWrt-Firefly-LuCI,NeoRaider/luci,fkooman/luci,RuiChen1113/luci,jorgifumi/luci,jlopenwrtluci/luci,keyidadi/luci,bright-things/ionic-luci,Noltari/luci,nwf/openwrt-luci,thess/OpenWrt-luci,thesabbir/luci,bittorf/luci,cshore-firmware/openwrt-luci,oneru/luci,oyido/luci,palmettos/test,obsy/luci,Hostle/luci,nwf/openwrt-luci,db260179/openwrt-bpi-r1-luci,Kyklas/luci-proto-hso,ReclaimYourPrivacy/cloak-luci,chris5560/openwrt-luci,palmettos/test,daofeng2015/luci,obsy/luci,nmav/luci,ollie27/openwrt_luci,rogerpueyo/luci,fkooman/luci,david-xiao/luci,forward619/luci,jchuang1977/luci-1,kuoruan/luci,cshore-firmware/openwrt-luci,ollie27/openwrt_luci,openwrt/luci,zhaoxx063/luci,bittorf/luci,NeoRaider/luci,shangjiyu/luci-with-extra,NeoRaider/luci,florian-shellfire/luci,maxrio/luci981213,ollie27/openwrt_luci,cshore/luci,obsy/luci,daofeng2015/luci,Sakura-Winkey/LuCI,artynet/luci,ff94315/luci-1,tobiaswaldvogel/luci,tobiaswaldvogel/luci,bittorf/luci,palmettos/test,tcatm/luci,slayerrensky/luci,oyido/luci,cappiewu/luci,teslamint/luci,cshore/luci,RedSnake64/openwrt-luci-packages,oneru/luci,slayerrensky/luci,deepak78/new-luci,maxrio/luci981213,florian-shellfire/luci,fkooman/luci,shangjiyu/luci-with-extra,Hostle/luci,palmettos/cnLuCI,kuoruan/lede-luci,hnyman/luci,hnyman/luci,sujeet14108/luci,thess/OpenWrt-luci,cshore/luci,ff94315/luci-1,harveyhu2012/luci,palmettos/cnLuCI,ReclaimYourPrivacy/cloak-luci,Wedmer/luci,palmettos/cnLuCI,male-puppies/luci,remakeelectric/luci,dwmw2/luci,teslamint/luci,lbthomsen/openwrt-luci,slayerrensky/luci,forward619/luci,mumuqz/luci,bright-things/ionic-luci,thesabbir/luci,fkooman/luci,florian-shellfire/luci,Wedmer/luci,shangjiyu/luci-with-extra,ReclaimYourPrivacy/cloak-luci,daofeng2015/luci,opentechinstitute/luci,LazyZhu/openwrt-luci-trunk-mod,slayerrensky/luci,thesabbir/luci,RuiChen1113/luci,david-xiao/luci,teslamint/luci,Sakura-Winkey/LuCI,dwmw2/luci,daofeng2015/luci,forward619/luci,aircross/OpenWrt-Firefly-LuCI,dismantl/luci-0.12,jorgifumi/luci,bittorf/luci,Hostle/luci,Noltari/luci,urueedi/luci,forward619/luci,Sakura-Winkey/LuCI,bittorf/luci,lbthomsen/openwrt-luci,harveyhu2012/luci,lcf258/openwrtcn,schidler/ionic-luci,LuttyYang/luci,lbthomsen/openwrt-luci,david-xiao/luci,Wedmer/luci,dismantl/luci-0.12,oyido/luci,Kyklas/luci-proto-hso,RuiChen1113/luci,joaofvieira/luci,cappiewu/luci,schidler/ionic-luci,obsy/luci,mumuqz/luci,fkooman/luci,ollie27/openwrt_luci,LazyZhu/openwrt-luci-trunk-mod,joaofvieira/luci,RuiChen1113/luci,marcel-sch/luci,joaofvieira/luci,marcel-sch/luci,openwrt-es/openwrt-luci,aa65535/luci,aa65535/luci,openwrt/luci,lcf258/openwrtcn,Noltari/luci,zhaoxx063/luci,joaofvieira/luci,deepak78/new-luci,shangjiyu/luci-with-extra,lbthomsen/openwrt-luci,artynet/luci,harveyhu2012/luci,LuttyYang/luci,maxrio/luci981213,LazyZhu/openwrt-luci-trunk-mod,ff94315/luci-1,Wedmer/luci,marcel-sch/luci,ReclaimYourPrivacy/cloak-luci,lbthomsen/openwrt-luci,rogerpueyo/luci,sujeet14108/luci,lbthomsen/openwrt-luci,aa65535/luci,artynet/luci,NeoRaider/luci,jchuang1977/luci-1,openwrt-es/openwrt-luci,Noltari/luci,tcatm/luci,nmav/luci,remakeelectric/luci,mumuqz/luci,jlopenwrtluci/luci,keyidadi/luci,thess/OpenWrt-luci,harveyhu2012/luci,urueedi/luci,jorgifumi/luci,taiha/luci,maxrio/luci981213,jorgifumi/luci,kuoruan/lede-luci,cshore/luci,Kyklas/luci-proto-hso,palmettos/cnLuCI,harveyhu2012/luci,jlopenwrtluci/luci,thess/OpenWrt-luci,kuoruan/luci,openwrt-es/openwrt-luci,remakeelectric/luci,taiha/luci,bright-things/ionic-luci,dwmw2/luci,cshore-firmware/openwrt-luci,opentechinstitute/luci,male-puppies/luci,dwmw2/luci,kuoruan/lede-luci,ollie27/openwrt_luci,lbthomsen/openwrt-luci,david-xiao/luci,Sakura-Winkey/LuCI,cshore/luci,jchuang1977/luci-1,kuoruan/lede-luci,cshore-firmware/openwrt-luci,wongsyrone/luci-1,sujeet14108/luci,dismantl/luci-0.12,forward619/luci,cshore-firmware/openwrt-luci,db260179/openwrt-bpi-r1-luci,openwrt-es/openwrt-luci,981213/luci-1,maxrio/luci981213,joaofvieira/luci,schidler/ionic-luci,maxrio/luci981213,lcf258/openwrtcn,ollie27/openwrt_luci,openwrt/luci,rogerpueyo/luci,nmav/luci,Noltari/luci,florian-shellfire/luci,openwrt-es/openwrt-luci,openwrt-es/openwrt-luci,mumuqz/luci,nwf/openwrt-luci,mumuqz/luci,shangjiyu/luci-with-extra,jorgifumi/luci,jorgifumi/luci,wongsyrone/luci-1,ff94315/luci-1,RedSnake64/openwrt-luci-packages,aa65535/luci,thesabbir/luci,rogerpueyo/luci,LuttyYang/luci,LuttyYang/luci,tcatm/luci,harveyhu2012/luci,daofeng2015/luci,thess/OpenWrt-luci,thesabbir/luci,schidler/ionic-luci,oneru/luci,openwrt-es/openwrt-luci,kuoruan/lede-luci,tobiaswaldvogel/luci,opentechinstitute/luci,cshore-firmware/openwrt-luci,hnyman/luci,urueedi/luci,aa65535/luci,taiha/luci,marcel-sch/luci,schidler/ionic-luci,maxrio/luci981213,NeoRaider/luci,kuoruan/lede-luci,cshore-firmware/openwrt-luci,bright-things/ionic-luci,david-xiao/luci,MinFu/luci,joaofvieira/luci,MinFu/luci,Hostle/openwrt-luci-multi-user,male-puppies/luci,daofeng2015/luci,forward619/luci,palmettos/cnLuCI,jchuang1977/luci-1,oyido/luci,urueedi/luci,harveyhu2012/luci,schidler/ionic-luci,Noltari/luci,981213/luci-1,ff94315/luci-1,rogerpueyo/luci,Hostle/openwrt-luci-multi-user,keyidadi/luci,palmettos/test,shangjiyu/luci-with-extra,shangjiyu/luci-with-extra,jlopenwrtluci/luci,wongsyrone/luci-1,deepak78/new-luci,LuttyYang/luci,keyidadi/luci,chris5560/openwrt-luci,db260179/openwrt-bpi-r1-luci,RuiChen1113/luci,Sakura-Winkey/LuCI,bright-things/ionic-luci,LuttyYang/luci,ollie27/openwrt_luci,dwmw2/luci,mumuqz/luci,oyido/luci,ff94315/luci-1,remakeelectric/luci,db260179/openwrt-bpi-r1-luci,sujeet14108/luci,hnyman/luci,Hostle/luci,florian-shellfire/luci,cappiewu/luci,Wedmer/luci,bittorf/luci,taiha/luci,zhaoxx063/luci,opentechinstitute/luci,artynet/luci,joaofvieira/luci,obsy/luci,ReclaimYourPrivacy/cloak-luci,cshore-firmware/openwrt-luci,lcf258/openwrtcn,RedSnake64/openwrt-luci-packages,cappiewu/luci,fkooman/luci,Wedmer/luci,chris5560/openwrt-luci,Sakura-Winkey/LuCI,maxrio/luci981213,tobiaswaldvogel/luci,daofeng2015/luci,oneru/luci,rogerpueyo/luci,palmettos/test,male-puppies/luci,kuoruan/luci,teslamint/luci,ff94315/luci-1,thess/OpenWrt-luci,wongsyrone/luci-1,jlopenwrtluci/luci,oneru/luci,bittorf/luci,palmettos/cnLuCI,rogerpueyo/luci,chris5560/openwrt-luci,aircross/OpenWrt-Firefly-LuCI,lcf258/openwrtcn,Noltari/luci,palmettos/cnLuCI,slayerrensky/luci,Hostle/openwrt-luci-multi-user,male-puppies/luci,db260179/openwrt-bpi-r1-luci,Hostle/luci,keyidadi/luci,nwf/openwrt-luci,dwmw2/luci,LazyZhu/openwrt-luci-trunk-mod,NeoRaider/luci,thesabbir/luci,nwf/openwrt-luci,RedSnake64/openwrt-luci-packages,aircross/OpenWrt-Firefly-LuCI,opentechinstitute/luci,opentechinstitute/luci,MinFu/luci,openwrt/luci,shangjiyu/luci-with-extra,tcatm/luci,NeoRaider/luci,tobiaswaldvogel/luci,bittorf/luci
b8281244b2fec2ff43e195783c94d0f8a1cd99d5
premake4.lua
premake4.lua
solution "litehtml" configurations { "Release", "Debug" } targetname "litehtml" language "C++" kind "StaticLib" files { "src/**.cpp", "src/**.h" } configuration "Debug" defines { "_DEBUG" } flags { "Symbols" } configuration "Release" defines { "NDEBUG" } flags { "OptimizeSize" } configuration "windows" defines { "WIN32" } project "litehtml" configuration "Debug" targetdir "bin/debug" targetsuffix = "_d" configuration "Release" targetdir "bin/release"
solution "litehtml" configurations { "Release", "Debug" } targetname "litehtml" language "C++" kind "StaticLib" files { "src/**.cpp", "src/**.h" } configuration "Debug" defines { "_DEBUG" } flags { "Symbols" } targetsuffix "_d" configuration "Release" defines { "NDEBUG" } flags { "OptimizeSize" } configuration "windows" defines { "WIN32" } project "litehtml" configuration "Debug" targetdir "bin/debug" configuration "Release" targetdir "bin/release"
fixed _d suffix in debug.
fixed _d suffix in debug.
Lua
bsd-3-clause
FishingCactus/litehtml,FishingCactus/litehtml
676818e2490066c232b7b3e12b266a4ac3854cfa
hammerspoon/hammerspoon.symlink/modules/hyperkey.lua
hammerspoon/hammerspoon.symlink/modules/hyperkey.lua
-- Based on https://gist.github.com/prenagha/1c28f71cb4d52b3133a4bff1b3849c3e -- A global variable for the sub-key Hyper Mode k = hs.hotkey.modal.new({}, 'F19') -- Hyper+key for all the below are setup somewhere -- The handler already exists, usually in Keyboard Maestro -- we just have to get the right keystroke sent hyperBindings = {'c','r','f'} for i,key in ipairs(hyperBindings) do k:bind({}, key, nil, function() hs.eventtap.keyStroke({'cmd','alt','shift','ctrl'}, key) k.triggered = true end) end -- Enter Hyper Mode when F19 (left control) is pressed pressedF19 = function() k.triggered = false k:enter() end -- Leave Hyper Mode when F19 (left control) is pressed, -- send ESCAPE if no other keys are pressed. releasedF19 = function() k:exit() if not k.triggered then hs.eventtap.keyStroke({}, 'ESCAPE') end end -- Bind the Hyper key f19 = hs.hotkey.bind({}, 'F19', pressedF19, releasedF19)
-- -- Based on https://gist.github.com/prenagha/1c28f71cb4d52b3133a4bff1b3849c3e -- -- -- A global variable for the sub-key Hyper Mode -- k = hs.hotkey.modal.new({}, 'F19') -- -- -- Hyper+key for all the below are setup somewhere -- -- The handler already exists, usually in Keyboard Maestro -- -- we just have to get the right keystroke sent -- hyperBindings = {'c','r','f'} -- -- for i,key in ipairs(hyperBindings) do -- k:bind({}, key, nil, function() hs.eventtap.keyStroke({'cmd','alt','shift','ctrl'}, key) -- k.triggered = true -- end) -- end -- -- -- Enter Hyper Mode when F19 (left control) is pressed -- pressedF19 = function() -- k.triggered = false -- k:enter() -- end -- -- -- Leave Hyper Mode when F19 (left control) is pressed, -- -- send ESCAPE if no other keys are pressed. -- releasedF19 = function() -- k:exit() -- if not k.triggered then -- hs.eventtap.keyStroke({}, 'ESCAPE') -- end -- end -- -- -- Bind the Hyper key -- f19 = hs.hotkey.bind({}, 'F19', pressedF19, releasedF19)
feat(Hammerspoon): Comment out hyperkey config until it can be fixed
feat(Hammerspoon): Comment out hyperkey config until it can be fixed
Lua
mit
sethvoltz/dotfiles,sethvoltz/dotfiles,sethvoltz/dotfiles,sethvoltz/dotfiles
2bfc6d0b6410f98e5da60241319b52aa09f81886
[resources]/GTWsafeareas/safearea_s.lua
[resources]/GTWsafeareas/safearea_s.lua
--[[ ******************************************************************************** Project owner: RageQuit community Project name: GTW-RPG Developers: Mr_Moose Source code: https://github.com/GTWCode/GTW-RPG/ Bugtracker: http://forum.404rq.com/bug-reports/ Suggestions: http://forum.404rq.com/mta-servers-development/ Version: Open source License: BSD 2-Clause Status: Stable release ******************************************************************************** ]]-- -- Redcue damage made by minigun setWeaponProperty(38, "pro", "damage", 2) setWeaponProperty(38, "std", "damage", 2) setWeaponProperty(38, "poor", "damage", 2) -- Reduce health when falling into cold water setTimer(function() for k,v in pairs(getElementsByType("player")) do if isElementInWater(v) then local health = getElementHealth(v) local new_health = health - math.random(4, 12) local x,y,z = getElementPosition(v) -- Check if the area is north west (SF), south LS or if it's night local hour, minutes = getTime() if (y > 1500 and x < 1000) or y < -2800 or hour > 22 or hour < 9 then if new_health > 0 then setElementHealth(v, new_health) exports.GTWtopbar:dm("This water is cold! get up before you die!", v, 255, 0, 0) else killPed(v) exports.GTWtopbar:dm("You frooze to death in the cold water", v, 100, 255, 100) end end end end end, 3000, 0) addCommandHandler("gtwinfo", function(plr, cmd) outputChatBox("[GTW-RPG] "..getResourceName( getThisResource())..", by: "..getResourceInfo( getThisResource(), "author")..", v-"..getResourceInfo( getThisResource(), "version")..", is represented", plr) end)
--[[ ******************************************************************************** Project owner: RageQuit community Project name: GTW-RPG Developers: Mr_Moose Source code: https://github.com/GTWCode/GTW-RPG/ Bugtracker: http://forum.404rq.com/bug-reports/ Suggestions: http://forum.404rq.com/mta-servers-development/ Version: Open source License: BSD 2-Clause Status: Stable release ******************************************************************************** ]]-- -- Redcue damage made by minigun setWeaponProperty(38, "pro", "damage", 2) setWeaponProperty(38, "std", "damage", 2) setWeaponProperty(38, "poor", "damage", 2) -- Reduce health when falling into cold water setTimer(function() for k,v in pairs(getElementsByType("player")) do if isElementInWater(v) and not getPedOccupiedVehicle(v) then local health = getElementHealth(v) local new_health = health - math.random(4, 12) local x,y,z = getElementPosition(v) -- Check if the area is north west (SF), south LS or if it's night local hour, minutes = getTime() if (y > 1500 and x < 1000) or y < -2800 or hour > 22 or hour < 9 then if new_health > 0 then setElementHealth(v, new_health) exports.GTWtopbar:dm("This water is cold! get up before you die!", v, 255, 0, 0) else killPed(v) exports.GTWtopbar:dm("You frooze to death in the cold water", v, 100, 255, 100) end end end end end, 4000, 0) addCommandHandler("gtwinfo", function(plr, cmd) outputChatBox("[GTW-RPG] "..getResourceName( getThisResource())..", by: "..getResourceInfo( getThisResource(), "author")..", v-"..getResourceInfo( getThisResource(), "version")..", is represented", plr) end)
[Patch] Fixed cold water damaging players in boats
[Patch] Fixed cold water damaging players in boats
Lua
bsd-2-clause
404rq/GTW-RPG,GTWCode/GTW-RPG,404rq/GTW-RPG,GTWCode/GTW-RPG,GTWCode/GTW-RPG,404rq/GTW-RPG
8bda3a2b47d5fb5f9d02c64fb5b611d8e913712d
heka/sandbox/filters/firefox_usage.lua
heka/sandbox/filters/firefox_usage.lua
-- This Source Code Form is subject to the terms of the Mozilla Public -- License, v. 2.0. If a copy of the MPL was not distributed with this -- file, You can obtain one at http://mozilla.org/MPL/2.0/. --[[ Firefox Usage Hours Config: - mode (string, optional, default "match") Sets the subsessionLength extraction mode to 'match' or 'parse'. Match will simply search for the uptime key/value anywhere in the string. Parse will JSON decoded the entire message to extract this one value. *Example Heka Configuration* .. code-block:: ini [FirefoxUsage] type = "SandboxFilter" filename = "lua_filters/firefox_usage.lua" message_matcher = "Type == 'telemetry'" ticker_interval = 60 preserve_data = true --]] require "circular_buffer" require "cjson" require "math" require "os" require "string" local DAYS = 30 local SEC_IN_DAY = 60 * 60 * 24 local floor = math.floor local date = os.date day_cb = circular_buffer.new(DAYS, 1, SEC_IN_DAY) day_cb:set_header(1, "Active Hours") current_day = -1 local month_names = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"} local MONTHS = #month_names months = {} for i=1,MONTHS do months[i] = 0 end current_month = -1 local function clear_months(s, n) for i = 1, n do s = s + 1 if s > MONTHS then s = 1 end months[s] = 0 end end local function update_month(ts, uptime, day_changed) local month = current_month if current_month == -1 or day_changed then local t = date("*t", ts / 1e9) month = tonumber(t.month) if current_month == -1 then current_month = month end end local delta = month - current_month if delta > 0 then clear_months(current_month, delta) current_month = month elseif delta < -1 then -- if older than a month roll over the year clear_months(current_month, MONTHS + delta) current_month = month end months[month] = months[month] + uptime end local function parse() local json = read_message("Payload") local ok, json = pcall(cjson.decode, json) if not ok then return -1, json end if type(json.payload) ~= "table" then return -1, "Missing payload object" end if type(json.payload.info) ~= "table" then return -1, "Missing payload.info object" end local uptime = json.payload.info.subsessionLength if type(uptime) ~= "number" then return -1, "Missing payload.info.subsessionLength" end uptime = uptime / 3600 -- convert to hours local ts = read_message("Timestamp") local day = floor(ts / (SEC_IN_DAY * 1e9)) local day_changed = day ~= current_day if day > current_day then current_day = day end day_cb:add(ts, 1, uptime) update_month(ts, uptime, day_changed) return 0 end local function match() local json = read_message("Payload") local uptime = string.match(json, '"subsessionLength":%s*(%d+%.?%d*)') if not uptime then return -1, "Missing uptime" end uptime = tonumber(uptime) / 3600 -- convert to hours local ts = read_message("Timestamp") local day = floor(ts / (SEC_IN_DAY * 1e9)) local day_changed = day ~= current_day if day > current_day then current_day = day end day_cb:add(ts, 1, uptime) update_month(ts, uptime, day_changed) return 0 end ---- -- todo after reviewing the utilization numbers keep the 'best' mode and remove the other local mode = read_config("mode") or "match" if mode == "match" then process_message = match elseif mode == "parse" then process_message = parse else error("Invalid configuration mode: " .. mode) end function timer_event(ns) inject_payload("cbuf", "Firefox Daily Active Hours", day_cb) local json = {} local idx = current_month if idx == -1 then idx = 0 end for i=1,MONTHS do idx = idx + 1 if idx > MONTHS then idx = 1 end json[i] = {[month_names[idx]] = months[idx]} end inject_payload("json", "Firefox Monthly Active Hours", cjson.encode(json)) end
-- This Source Code Form is subject to the terms of the Mozilla Public -- License, v. 2.0. If a copy of the MPL was not distributed with this -- file, You can obtain one at http://mozilla.org/MPL/2.0/. --[[ Firefox Usage Hours *Example Heka Configuration* .. code-block:: ini [FirefoxUsage] type = "SandboxFilter" filename = "lua_filters/firefox_usage.lua" message_matcher = "Type == 'telemetry' && Fields[docType] == 'main'" ticker_interval = 60 preserve_data = true --]] require "circular_buffer" require "cjson" require "math" require "os" require "string" local DAYS = 30 local SEC_IN_DAY = 60 * 60 * 24 local floor = math.floor local date = os.date day_cb = circular_buffer.new(DAYS, 1, SEC_IN_DAY) day_cb:set_header(1, "Active Hours") current_day = -1 local month_names = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"} local MONTHS = #month_names months = {} for i=1,MONTHS do months[i] = 0 end current_month = -1 local function clear_months(s, n) for i = 1, n do s = s + 1 if s > MONTHS then s = 1 end months[s] = 0 end end local function update_month(ts, uptime, day_changed, day_advanced) local month = current_month if current_month == -1 or day_changed then local t = date("*t", ts / 1e9) month = tonumber(t.month) if current_month == -1 then current_month = month end end if day_advanced then local delta = month - current_month if delta > 0 then clear_months(current_month, delta) current_month = month elseif delta < 0 then -- roll over the year clear_months(current_month, MONTHS + delta) current_month = month end end months[month] = months[month] + uptime end ---- function process_message() local json = read_message("Fields[payload.info]") local ok, json = pcall(cjson.decode, json) if not ok then return -1, json end local uptime = json.subsessionLength if type(uptime) ~= "number" or uptime < 0 or uptime >= 180 * SEC_IN_DAY then return -1, "missing/invalid subsessionLength" end if uptime == 0 then return 0 end uptime = uptime / 3600 -- convert to hours local ts = read_message("Timestamp") local day = floor(ts / (SEC_IN_DAY * 1e9)) local day_changed = day ~= current_day local day_advanced = false if day > current_day then current_day = day day_advanced = true elseif current_day - day > 360 * SEC_IN_DAY then return -1, "data is too old" end day_cb:add(ts, 1, uptime) update_month(ts, uptime, day_changed, day_advanced) return 0 end function timer_event(ns) inject_payload("cbuf", "Firefox Daily Active Hours", day_cb) local json = {} local idx = current_month if idx == -1 then idx = 0 end for i=1,MONTHS do idx = idx + 1 if idx > MONTHS then idx = 1 end json[i] = {[month_names[idx]] = months[idx]} end inject_payload("json", "Firefox Monthly Active Hours", cjson.encode(json)) end
Firefox hourly usage plugin refinement
Firefox hourly usage plugin refinement - use the new split object telemetry message - add boundary checks as per https://bugzilla.mozilla.org/show_bug.cgi?id=1131822
Lua
mpl-2.0
mozilla-services/data-pipeline,acmiyaguchi/data-pipeline,mreid-moz/data-pipeline,whd/data-pipeline,sapohl/data-pipeline,acmiyaguchi/data-pipeline,mreid-moz/data-pipeline,kparlante/data-pipeline,mozilla-services/data-pipeline,kparlante/data-pipeline,kparlante/data-pipeline,acmiyaguchi/data-pipeline,nathwill/data-pipeline,acmiyaguchi/data-pipeline,whd/data-pipeline,mozilla-services/data-pipeline,mozilla-services/data-pipeline,kparlante/data-pipeline,mreid-moz/data-pipeline,whd/data-pipeline,nathwill/data-pipeline,sapohl/data-pipeline,sapohl/data-pipeline,whd/data-pipeline,sapohl/data-pipeline,nathwill/data-pipeline,nathwill/data-pipeline
56afb5b09c47eeeb9e29580f4e51e015b766a1dc
src/luarocks/loader.lua
src/luarocks/loader.lua
local global_env = _G local package, require, assert, ipairs, pairs, os, print, table, type, next, unpack = package, require, assert, ipairs, pairs, os, print, table, type, next, unpack module("luarocks.loader") local path = require("luarocks.path") local manif_core = require("luarocks.manif_core") local deps = require("luarocks.deps") local cfg = require("luarocks.cfg") context = {} -- Contains a table when rocks trees are loaded, -- or 'false' to indicate rocks trees failed to load. -- 'nil' indicates rocks trees were not attempted to be loaded yet. rocks_trees = nil local function load_rocks_trees() local any_ok = false local trees = {} for _, tree in pairs(cfg.rocks_trees) do local manifest, err = manif_core.load_local_manifest(path.rocks_dir(tree)) if manifest then any_ok = true table.insert(trees, {tree=tree, manifest=manifest}) end end if not any_ok then rocks_trees = false return false end rocks_trees = trees return true end --- Process the dependencies of a package to determine its dependency -- chain for loading modules. -- @parse name string: The name of an installed rock. -- @parse version string: The version of the rock, in string format function add_context(name, version) -- assert(type(name) == "string") -- assert(type(version) == "string") if context[name] then return end context[name] = version if not rocks_trees and not load_rocks_trees() then return nil end local providers = {} for _, tree in pairs(rocks_trees) do local manifest = tree.manifest local pkgdeps = manifest.dependencies and manifest.dependencies[name][version] if not pkgdeps then return end for _, dep in ipairs(pkgdeps) do local package, constraints = dep.name, dep.constraints for _, tree in pairs(rocks_trees) do local entries = tree.manifest.repository[package] if entries then for version, packages in pairs(entries) do if (not constraints) or deps.match_constraints(deps.parse_version(version), constraints) then add_context(package, version) end end end end end end end --- Internal sorting function. -- @param a table: A provider table. -- @param b table: Another provider table. -- @return boolean: True if the version of a is greater than that of b. local function sort_versions(a,b) return a.version > b.version end local function call_other_loaders(module, name, version, module_name) for i, loader in pairs(package.loaders) do if loader ~= luarocks_loader then local results = { loader(module_name) } if type(results[1]) == "function" then return unpack(results) end end end return nil, "Failed loading module "..module.." in LuaRocks rock "..name.." "..version end local function select_module(module, filter_module_name) --assert(type(module) == "string") --assert(type(filter_module_name) == "function") if not rocks_trees and not load_rocks_trees() then return nil end local providers = {} for _, tree in pairs(rocks_trees) do local entries = tree.manifest.modules[module] if entries then for i, entry in ipairs(entries) do local name, version = entry:match("^([^/]*)/(.*)$") local module_name = tree.manifest.repository[name][version][1].modules[module] module_name = filter_module_name(module_name, name, version, tree.tree, i) if context[name] == version then return name, version, module_name end version = deps.parse_version(version) table.insert(providers, {name = name, version = version, module_name = module_name}) end end end if next(providers) then table.sort(providers, sort_versions) local first = providers[1] return first.name, first.version.string, first.module_name end end local function pick_module(module) return select_module(module, function(module_name, name, version, tree, i) if i > 1 then module_name = path.versioned_name(module_name, "", name, version) end module_name = path.path_to_module(module_name) return module_name end) end function which(module) local name, version, module_name = select_module(module, function(module_name, name, version, tree, i) if module_name:match("%.lua$") then module_name = path.deploy_lua_dir(tree).."/"..module_name else module_name = path.deploy_lib_dir(tree).."/"..module_name end if i > 1 then module_name = path.versioned_name(module_name, tree, name, version) end return module_name end) return module_name end --- Package loader for LuaRocks support. -- A module is searched in installed rocks that match the -- current LuaRocks context. If module is not part of the -- context, or if a context has not yet been set, the module -- in the package with the highest version is used. -- @param module string: The module name, like in plain require(). -- @return table: The module table (typically), like in plain -- require(). See <a href="http://www.lua.org/manual/5.1/manual.html#pdf-require">require()</a> -- in the Lua reference manual for details. function luarocks_loader(module) local name, version, module_name = pick_module(module) if not name then return nil, "No LuaRocks module found for "..module else add_context(name, version) return call_other_loaders(module, name, version, module_name) end end table.insert(global_env.package.loaders, 1, luarocks_loader)
local global_env = _G local package, require, assert, ipairs, pairs, os, print, table, type, next, unpack = package, require, assert, ipairs, pairs, os, print, table, type, next, unpack module("luarocks.loader") local path = require("luarocks.path") local manif_core = require("luarocks.manif_core") local deps = require("luarocks.deps") local cfg = require("luarocks.cfg") context = {} -- Contains a table when rocks trees are loaded, -- or 'false' to indicate rocks trees failed to load. -- 'nil' indicates rocks trees were not attempted to be loaded yet. rocks_trees = nil local function load_rocks_trees() local any_ok = false local trees = {} for _, tree in pairs(cfg.rocks_trees) do local manifest, err = manif_core.load_local_manifest(path.rocks_dir(tree)) if manifest then any_ok = true table.insert(trees, {tree=tree, manifest=manifest}) end end if not any_ok then rocks_trees = false return false end rocks_trees = trees return true end --- Process the dependencies of a package to determine its dependency -- chain for loading modules. -- @parse name string: The name of an installed rock. -- @parse version string: The version of the rock, in string format function add_context(name, version) -- assert(type(name) == "string") -- assert(type(version) == "string") if context[name] then return end context[name] = version if not rocks_trees and not load_rocks_trees() then return nil end local providers = {} for _, tree in pairs(rocks_trees) do local manifest = tree.manifest local pkgdeps = manifest.dependencies and manifest.dependencies[name][version] if not pkgdeps then return end for _, dep in ipairs(pkgdeps) do local package, constraints = dep.name, dep.constraints for _, tree in pairs(rocks_trees) do local entries = tree.manifest.repository[package] if entries then for version, packages in pairs(entries) do if (not constraints) or deps.match_constraints(deps.parse_version(version), constraints) then add_context(package, version) end end end end end end end --- Internal sorting function. -- @param a table: A provider table. -- @param b table: Another provider table. -- @return boolean: True if the version of a is greater than that of b. local function sort_versions(a,b) return a.version > b.version end local function call_other_loaders(module, name, version, module_name) for i, loader in pairs(package.loaders) do if loader ~= luarocks_loader then local results = { loader(module_name) } if type(results[1]) == "function" then return unpack(results) end end end return nil, "Failed loading module "..module.." in LuaRocks rock "..name.." "..version end local function select_module(module, filter_module_name) --assert(type(module) == "string") --assert(type(filter_module_name) == "function") if not rocks_trees and not load_rocks_trees() then return nil end local providers = {} for _, tree in pairs(rocks_trees) do local entries = tree.manifest.modules[module] if entries then for i, entry in ipairs(entries) do local name, version = entry:match("^([^/]*)/(.*)$") local module_name = tree.manifest.repository[name][version][1].modules[module] module_name = filter_module_name(module_name, name, version, tree.tree, i) if context[name] == version then return name, version, module_name end version = deps.parse_version(version) table.insert(providers, {name = name, version = version, module_name = module_name}) end end end if next(providers) then table.sort(providers, sort_versions) local first = providers[1] return first.name, first.version.string, first.module_name end end local function pick_module(module) return select_module(module, function(module_name, name, version, tree, i) if i > 1 then module_name = path.versioned_name(module_name, "", name, version) end module_name = path.path_to_module(module_name) return module_name end) end function which(module) local name, version, module_name = select_module(module, function(module_name, name, version, tree, i) local deploy_dir if module_name:match("%.lua$") then deploy_dir = path.deploy_lua_dir(tree) module_name = deploy_dir.."/"..module_name else deploy_dir = path.deploy_lib_dir(tree) module_name = deploy_dir.."/"..module_name end if i > 1 then module_name = path.versioned_name(module_name, deploy_dir, name, version) end return module_name end) return module_name end --- Package loader for LuaRocks support. -- A module is searched in installed rocks that match the -- current LuaRocks context. If module is not part of the -- context, or if a context has not yet been set, the module -- in the package with the highest version is used. -- @param module string: The module name, like in plain require(). -- @return table: The module table (typically), like in plain -- require(). See <a href="http://www.lua.org/manual/5.1/manual.html#pdf-require">require()</a> -- in the Lua reference manual for details. function luarocks_loader(module) local name, version, module_name = pick_module(module) if not name then return nil, "No LuaRocks module found for "..module else add_context(name, version) return call_other_loaders(module, name, version, module_name) end end table.insert(global_env.package.loaders, 1, luarocks_loader)
fix implementation of which()
fix implementation of which() git-svn-id: b90ab2797f6146e3ba3e3d8b20782c4c2887e809@101 9ca3f7c1-7366-0410-b1a3-b5c78f85698c
Lua
mit
xpol/luainstaller,robooo/luarocks,xpol/luavm,ignacio/luarocks,luarocks/luarocks,keplerproject/luarocks,coderstudy/luarocks,aryajur/luarocks,xiaq/luarocks,robooo/luarocks,leafo/luarocks,tarantool/luarocks,xpol/luainstaller,ignacio/luarocks,xiaq/luarocks,usstwxy/luarocks,coderstudy/luarocks,usstwxy/luarocks,usstwxy/luarocks,xpol/luavm,robooo/luarocks,starius/luarocks,aryajur/luarocks,xpol/luarocks,xpol/luavm,tst2005/luarocks,usstwxy/luarocks,tst2005/luarocks,xpol/luarocks,luarocks/luarocks,ignacio/luarocks,robooo/luarocks,coderstudy/luarocks,aryajur/luarocks,xpol/luainstaller,leafo/luarocks,keplerproject/luarocks,xpol/luarocks,starius/luarocks,xiaq/luarocks,tarantool/luarocks,lxbgit/luarocks,lxbgit/luarocks,rrthomas/luarocks,starius/luarocks,xpol/luainstaller,rrthomas/luarocks,coderstudy/luarocks,keplerproject/luarocks,rrthomas/luarocks,starius/luarocks,tst2005/luarocks,keplerproject/luarocks,xpol/luavm,tst2005/luarocks,xpol/luarocks,lxbgit/luarocks,xpol/luavm,xiaq/luarocks,luarocks/luarocks,lxbgit/luarocks,leafo/luarocks,aryajur/luarocks,rrthomas/luarocks,tarantool/luarocks,ignacio/luarocks
f8e059afd05a3f11a35bf2a542c52c803ab688e7
kong/runloop/plugin_servers/mp_rpc.lua
kong/runloop/plugin_servers/mp_rpc.lua
local msgpack = require "MessagePack" local mp_pack = msgpack.pack local mp_unpacker = msgpack.unpacker local Rpc = {} Rpc.__index = Rpc Rpc.notifications_callbacks = {} function Rpc.new(socket_path, notifications) kong.log.debug("mp_rpc.new: ", socket_path) return setmetatable({ socket_path = socket_path, msg_id = 0, notifications_callbacks = notifications, }, Rpc) end -- add MessagePack empty array/map msgpack.packers['function'] = function (buffer, f) f(buffer) end local function mp_empty_array(buffer) msgpack.packers['array'](buffer, {}, 0) end local function mp_empty_map(buffer) msgpack.packers['map'](buffer, {}, 0) end --- fix_mmap(t) : preprocess complex maps function Rpc.fix_mmap(t) local o, empty = {}, true for k, v in pairs(t) do empty = false if v == true then o[k] = mp_empty_array elseif type(v) == "string" then o[k] = { v } else o[k] = v end end if empty then return mp_empty_map end return o end function Rpc:call(method, ...) self.msg_id = self.msg_id + 1 local c, err = ngx.socket.connect("unix:" .. self.socket_path) if not c then kong.log.err("trying to connect: ", err) return nil, err end -- request: [ 0, msg_id, method, args ] local bytes, err = c:send(mp_pack({0, self.msg_id, method, {...}})) if not bytes then c:setkeepalive() return nil, err end local reader = mp_unpacker(function() return c:receiveany(4096) end) while true do -- read an MP object local ok, data = reader() if not ok then c:setkeepalive() return nil, "no data" end if data[1] == 2 then -- notification: [ 2, label, args ] self:notification(data[2], data[3]) else -- response: [ 1, msg_id, error, result ] assert(data[1] == 1, "RPC response expected from Go plugin server") assert(data[2] == self.msg_id, "unexpected RPC response ID from Go plugin server") -- it's our answer c:setkeepalive() if data[3] ~= nil then return nil, data[3] end return data[4] end end end function Rpc:notification(label, args) local f = self.notifications_callbacks[label] if f then f(self, args) end end return Rpc
local msgpack = require "MessagePack" local mp_pack = msgpack.pack local mp_unpacker = msgpack.unpacker local Rpc = {} Rpc.__index = Rpc Rpc.notifications_callbacks = {} function Rpc.new(socket_path, notifications) kong.log.debug("mp_rpc.new: ", socket_path) return setmetatable({ socket_path = socket_path, msg_id = 0, notifications_callbacks = notifications, }, Rpc) end -- add MessagePack empty array/map msgpack.packers['function'] = function (buffer, f) f(buffer) end local function mp_empty_array(buffer) msgpack.packers['array'](buffer, {}, 0) end local function mp_empty_map(buffer) msgpack.packers['map'](buffer, {}, 0) end --- fix_mmap(t) : preprocess complex maps function Rpc.fix_mmap(t) local o, empty = {}, true for k, v in pairs(t) do empty = false if v == true then o[k] = mp_empty_array elseif type(v) == "string" then o[k] = { v } else o[k] = v end end if empty then return mp_empty_map end return o end function Rpc:call(method, ...) self.msg_id = self.msg_id + 1 local msg_id = self.msg_id local c, err = ngx.socket.connect("unix:" .. self.socket_path) if not c then kong.log.err("trying to connect: ", err) return nil, err end -- request: [ 0, msg_id, method, args ] local bytes, err = c:send(mp_pack({0, msg_id, method, {...}})) if not bytes then c:setkeepalive() return nil, err end local reader = mp_unpacker(function() return c:receiveany(4096) end) while true do -- read an MP object local ok, data = reader() if not ok then c:setkeepalive() return nil, "no data" end if data[1] == 2 then -- notification: [ 2, label, args ] self:notification(data[2], data[3]) else -- response: [ 1, msg_id, error, result ] assert(data[1] == 1, "RPC response expected from Go plugin server") assert(data[2] == msg_id, "unexpected RPC response ID from Go plugin server") -- it's our answer c:setkeepalive() if data[3] ~= nil then return nil, data[3] end return data[4] end end end function Rpc:notification(label, args) local f = self.notifications_callbacks[label] if f then f(self, args) end end return Rpc
fix(ext-plugin): store msg_id scope per-connection, not per-pluginserver to avoid races with concurrent calls
fix(ext-plugin): store msg_id scope per-connection, not per-pluginserver to avoid races with concurrent calls
Lua
apache-2.0
Kong/kong,Kong/kong,Kong/kong
f4bb54b106022e7de0deff0fe3e19e8c3d3a6e9f
src/split.lua
src/split.lua
--- split: string split function and iterator for Lua -- -- Peter Aronoff -- BSD 3-Clause License -- 2012-2015 -- -- There are many split functions for Lua. This is mine. Though, actually, -- I took lots of ideas and probably some code from the implementations on -- the Lua-Users Wiki, http://lua-users.org/wiki/SplitJoin. local find = string.find local fmt = string.format local cut = string.sub local error = error --- Helper functions -- -- Return a table composed of the individual characters from a string. local explode = function (str) local t = {} for i=1, #str do t[#t + 1] = cut(str, i, i) end return t end --- split(string, delimiter) => { results } -- Return a table composed of substrings divided by a delimiter or pattern. local split = function (str, delimiter) -- Handle an edge case concerning the str parameter. Immediately return an -- empty table if str == ''. if str == '' then return {} end -- Handle special cases concerning the delimiter parameter. -- 1. If the pattern is nil, split on contiguous whitespace. -- 2. If the pattern is an empty string, explode the string. -- 3. Protect against patterns that match too much. Such patterns would hang -- the caller. delimiter = delimiter or '%s+' if delimiter == '' then return explode(str) end if find('', delimiter, 1) then local msg = fmt('The delimiter (%s) would match the empty string.', delimiter) error(msg) end -- The table `t` will store the found items. `s` and `e` will keep -- track of the start and end of a match for the delimiter. Finally, -- `position` tracks where to start grabbing the next match. local t = {} local s, e local position = 1 s, e = find(str, delimiter, position) while s do t[#t+1] = cut(str, position, s-1) position = e + 1 s, e = find(str, delimiter, position) end -- To get the (potential) last item, check if the final position is -- still within the string. If it is, grab the rest of the string into -- a final element. if position <= #str then t[#t + 1] = cut(str, position) end -- Special handling for a (potential) final trailing delimiter. If the -- last found end position is identical to the end of the whole string, -- then add a trailing empty field. if position > #str then t[#t+1] = '' end return t end --- spliterator(str, delimiter) local spliterator = function (str, delimiter) delimiter = delimiter or '%s+' if delimiter == '' then delimiter = '.' end if find('', delimiter, 1) then local msg = fmt('The delimiter (%s) would match the empty string.', delimiter) error(msg) end local s, e, subsection local position = 1 local function iter() if str == '' then return nil end s, e = find(str, delimiter, position) if s then subsection = cut(str, position, s-1) position = e + 1 return subsection elseif position <= #str then subsection = cut(str, position) position = #str + 2 return subsection elseif position == #str + 1 then position = #str + 2 return '' end end return iter end return { split = split, spliterator = spliterator, _VERSION = "1.0-0-1", _AUTHOR = "Peter Aronoff", _URL = "https://bitbucket.org/telemachus/split", _LICENSE = 'BSD 3-Clause', }
--- split: string split function and iterator for Lua -- -- Peter Aronoff -- BSD 3-Clause License -- 2012-2015 -- -- There are many split functions for Lua. This is mine. Though, actually, -- I took lots of ideas and probably some code from the implementations on -- the Lua-Users Wiki, http://lua-users.org/wiki/SplitJoin. local find = string.find local fmt = string.format local cut = string.sub local gmatch = string.gmatch local error = error --- Helper functions -- -- Return a table composed of the individual characters from a string. local explode = function (str) local t = {} for i=1, #str do t[#t + 1] = cut(str, i, i) end return t end --- split(string, delimiter) => { results } -- Return a table composed of substrings divided by a delimiter or pattern. local split = function (str, delimiter) -- Handle an edge case concerning the str parameter. Immediately return an -- empty table if str == ''. if str == '' then return {} end -- Handle special cases concerning the delimiter parameter. -- 1. If the pattern is nil, split on contiguous whitespace. -- 2. If the pattern is an empty string, explode the string. -- 3. Protect against patterns that match too much. Such patterns would hang -- the caller. delimiter = delimiter or '%s+' if delimiter == '' then return explode(str) end if find('', delimiter, 1) then local msg = fmt('The delimiter (%s) would match the empty string.', delimiter) error(msg) end -- The table `t` will store the found items. `s` and `e` will keep -- track of the start and end of a match for the delimiter. Finally, -- `position` tracks where to start grabbing the next match. local t = {} local s, e local position = 1 s, e = find(str, delimiter, position) while s do t[#t+1] = cut(str, position, s-1) position = e + 1 s, e = find(str, delimiter, position) end -- To get the (potential) last item, check if the final position is -- still within the string. If it is, grab the rest of the string into -- a final element. if position <= #str then t[#t + 1] = cut(str, position) end -- Special handling for a (potential) final trailing delimiter. If the -- last found end position is identical to the end of the whole string, -- then add a trailing empty field. if position > #str then t[#t+1] = '' end return t end --- spliterator(str, delimiter) local spliterator = function (str, delimiter) delimiter = delimiter or '%s+' if delimiter == '' then return gmatch(str, '.') end if find('', delimiter, 1) then local msg = fmt('The delimiter (%s) would match the empty string.', delimiter) error(msg) end local s, e, subsection local position = 1 local function iter() if str == '' then return nil end s, e = find(str, delimiter, position) if s then subsection = cut(str, position, s-1) position = e + 1 return subsection elseif position <= #str then subsection = cut(str, position) position = #str + 2 return subsection elseif position == #str + 1 then position = #str + 2 return '' end end return iter end return { split = split, spliterator = spliterator, _VERSION = "1.0-0-1", _AUTHOR = "Peter Aronoff", _URL = "https://bitbucket.org/telemachus/split", _LICENSE = 'BSD 3-Clause', }
Fix iterator bug
Fix iterator bug
Lua
bsd-3-clause
telemachus/split
465891ff0239b8fdafb737d01e3f05205a14319b
modules/luci-base/luasrc/sgi/uhttpd.lua
modules/luci-base/luasrc/sgi/uhttpd.lua
-- Copyright 2010 Jo-Philipp Wich <[email protected]> -- Licensed to the public under the Apache License 2.0. require "nixio.util" require "luci.http" require "luci.sys" require "luci.dispatcher" require "luci.ltn12" function handle_request(env) exectime = os.clock() local renv = { CONTENT_LENGTH = env.CONTENT_LENGTH, CONTENT_TYPE = env.CONTENT_TYPE, REQUEST_METHOD = env.REQUEST_METHOD, REQUEST_URI = env.REQUEST_URI, PATH_INFO = env.PATH_INFO, SCRIPT_NAME = env.SCRIPT_NAME:gsub("/+$", ""), SCRIPT_FILENAME = env.SCRIPT_NAME, SERVER_PROTOCOL = env.SERVER_PROTOCOL, QUERY_STRING = env.QUERY_STRING } local k, v for k, v in pairs(env.headers) do k = k:upper():gsub("%-", "_") renv["HTTP_" .. k] = v end local len = tonumber(env.CONTENT_LENGTH) or 0 local function recv() if len > 0 then local rlen, rbuf = uhttpd.recv(4096) if rlen >= 0 then len = len - rlen return rbuf end end return nil end local send = uhttpd.send local req = luci.http.Request( renv, recv, luci.ltn12.sink.file(io.stderr) ) local x = coroutine.create(luci.dispatcher.httpdispatch) local hcache = { } local active = true while coroutine.status(x) ~= "dead" do local res, id, data1, data2 = coroutine.resume(x, req) if not res then send("Status: 500 Internal Server Error\r\n") send("Content-Type: text/plain\r\n\r\n") send(tostring(id)) break end if active then if id == 1 then send("Status: ") send(tostring(data1)) send(" ") send(tostring(data2)) send("\r\n") elseif id == 2 then hcache[data1] = data2 elseif id == 3 then for k, v in pairs(hcache) do send(tostring(k)) send(": ") send(tostring(v)) send("\r\n") end send("\r\n") elseif id == 4 then send(tostring(data1 or "")) elseif id == 5 then active = false elseif id == 6 then data1:copyz(nixio.stdout, data2) end end end end
-- Copyright 2010 Jo-Philipp Wich <[email protected]> -- Licensed to the public under the Apache License 2.0. require "nixio.util" require "luci.http" require "luci.sys" require "luci.dispatcher" require "luci.ltn12" function handle_request(env) exectime = os.clock() local renv = { CONTENT_LENGTH = env.CONTENT_LENGTH, CONTENT_TYPE = env.CONTENT_TYPE, REQUEST_METHOD = env.REQUEST_METHOD, REQUEST_URI = env.REQUEST_URI, PATH_INFO = env.PATH_INFO, SCRIPT_NAME = env.SCRIPT_NAME:gsub("/+$", ""), SCRIPT_FILENAME = env.SCRIPT_NAME, SERVER_PROTOCOL = env.SERVER_PROTOCOL, QUERY_STRING = env.QUERY_STRING, DOCUMENT_ROOT = env.DOCUMENT_ROOT, HTTPS = env.HTTPS, REDIRECT_STATUS = env.REDIRECT_STATUS, REMOTE_ADDR = env.REMOTE_ADDR, REMOTE_NAME = env.REMOTE_NAME, REMOTE_PORT = env.REMOTE_PORT, REMOTE_USER = env.REMOTE_USER, SERVER_ADDR = env.SERVER_ADDR, SERVER_NAME = env.SERVER_NAME, SERVER_PORT = env.SERVER_PORT } local k, v for k, v in pairs(env.headers) do k = k:upper():gsub("%-", "_") renv["HTTP_" .. k] = v end local len = tonumber(env.CONTENT_LENGTH) or 0 local function recv() if len > 0 then local rlen, rbuf = uhttpd.recv(4096) if rlen >= 0 then len = len - rlen return rbuf end end return nil end local send = uhttpd.send local req = luci.http.Request( renv, recv, luci.ltn12.sink.file(io.stderr) ) local x = coroutine.create(luci.dispatcher.httpdispatch) local hcache = { } local active = true while coroutine.status(x) ~= "dead" do local res, id, data1, data2 = coroutine.resume(x, req) if not res then send("Status: 500 Internal Server Error\r\n") send("Content-Type: text/plain\r\n\r\n") send(tostring(id)) break end if active then if id == 1 then send("Status: ") send(tostring(data1)) send(" ") send(tostring(data2)) send("\r\n") elseif id == 2 then hcache[data1] = data2 elseif id == 3 then for k, v in pairs(hcache) do send(tostring(k)) send(": ") send(tostring(v)) send("\r\n") end send("\r\n") elseif id == 4 then send(tostring(data1 or "")) elseif id == 5 then active = false elseif id == 6 then data1:copyz(nixio.stdout, data2) end end end end
luci-base: uhttpd.lua: expose all CGI variables
luci-base: uhttpd.lua: expose all CGI variables Fixes: #3873 Signed-off-by: Jo-Philipp Wich <[email protected]>
Lua
apache-2.0
tobiaswaldvogel/luci,openwrt/luci,lbthomsen/openwrt-luci,lbthomsen/openwrt-luci,lbthomsen/openwrt-luci,tobiaswaldvogel/luci,openwrt/luci,lbthomsen/openwrt-luci,tobiaswaldvogel/luci,hnyman/luci,lbthomsen/openwrt-luci,openwrt/luci,hnyman/luci,hnyman/luci,hnyman/luci,lbthomsen/openwrt-luci,tobiaswaldvogel/luci,lbthomsen/openwrt-luci,hnyman/luci,hnyman/luci,openwrt/luci,tobiaswaldvogel/luci,rogerpueyo/luci,openwrt/luci,rogerpueyo/luci,openwrt/luci,openwrt/luci,hnyman/luci,rogerpueyo/luci,rogerpueyo/luci,lbthomsen/openwrt-luci,tobiaswaldvogel/luci,tobiaswaldvogel/luci,rogerpueyo/luci,rogerpueyo/luci,rogerpueyo/luci,hnyman/luci,openwrt/luci,tobiaswaldvogel/luci,rogerpueyo/luci
f101db26ceeb0ccf5a48c8493850569b4017cffd
src_trunk/resources/carshop-system/s_carshop_system.lua
src_trunk/resources/carshop-system/s_carshop_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 // -- //////////////////////////////////// carshopPickup = createPickup(544.4990234375, -1292.7890625, 17.2421875, 3, 1239) exports.pool:allocateElement(carshopPickup) function pickupUse(thePlayer) triggerClientEvent(thePlayer, "showCarshopUI", thePlayer) end addEventHandler("onPickupHit", carshopPickup, pickupUse) function buyCar(car, cost, id, col1, col2) if not getElementData(source, "money") then return end local safemoney = tonumber(getElementData(source, "money")) local hackmoney = getPlayerMoney(source) if (safemoney == hackmoney and safemoney >= tonumber(cost)) then outputChatBox("You bought a " .. car .. " for " .. cost .. "$. Enjoy!", source, 255, 194, 14) outputChatBox("You can set this vehicles spawn position by parking it and typing /vehpos", source, 255, 194, 14) outputChatBox("Vehicles parked near the dealership or bus spawn point will be deleted without notice.", source, 255, 0, 0) outputChatBox("Press I and use your car key to unlock this vehicle.", source, 255, 194, 14) makeCar(source, car, cost, id, col1, col2) end end addEvent("buyCar", true) addEventHandler("buyCar", getRootElement(), buyCar) function makeCar(thePlayer, car, cost, id, col1, col2) if not getElementData(thePlayer, "money") then return end local safemoney = tonumber(getElementData(thePlayer, "money")) local hackmoney = getPlayerMoney(thePlayer) if (safemoney == hackmoney and safemoney > tonumber(cost)) then local rx = 0 local ry = 0 local rz = 333.74502563477 local x, y, z = 548.59375, -1276.373046875, 17.248237609863 setElementPosition(thePlayer, 541.6484375, -1274.1513671875, 17.2421875) setPedRotation(thePlayer, 266.69442749023) local username = getPlayerName(thePlayer) local dbid = getElementData(thePlayer, "dbid") exports.global:takePlayerSafeMoney(thePlayer, tonumber(cost)) local letter1 = string.char(math.random(65,90)) local letter2 = string.char(math.random(65,90)) local plate = letter1 .. letter2 .. math.random(0, 9) .. " " .. math.random(1000, 9999) local veh = createVehicle(id, x, y, z, 0, 0, rz, plate) exports.pool:allocateElement(veh) setElementData(veh, "fuel", 100) setElementData(veh, "Impounded", 0) setVehicleRespawnPosition(veh, x, y, z, 0, 0, rz) setVehicleLocked(veh, false) local locked = 0 setVehicleColor(veh, col1, col2, col1, col2) setVehicleOverrideLights(veh, 1) setVehicleEngineState(veh, false) setVehicleFuelTankExplodable(veh, false) local query = mysql_query(handler, "INSERT INTO vehicles SET model='" .. id .. "', x='" .. x .. "', y='" .. y .. "', z='" .. z .. "', rotx='" .. rx .. "', roty='" .. ry .. "', rotz='" .. rz .. "', color1='" .. col1 .. "', color2='" .. col2 .. "', faction='-1', owner='" .. dbid .. "', plate='" .. plate .. "', currx='" .. x .. "', curry='" .. y .. "', currz='" .. z .. "', currrx='0', currry='0', currrz='" .. rz .. "', locked='" .. locked .. "'") local insertid = mysql_insert_id ( handler ) if (query) then mysql_free_result(query) exports.global:givePlayerItem(thePlayer, 3, tonumber(insertid)) setElementData(veh, "dbid", tonumber(insertid)) setElementData(veh, "fuel", 100) setElementData(veh, "engine", 0, false) setElementData(veh, "oldx", x, false) setElementData(veh, "oldy", y, false) setElementData(veh, "oldz", z, false) setElementData(veh, "faction", -1, false) setElementData(veh, "owner", dbid, false) setElementData(veh, "job", 0, false) setElementData(veh, "locked", locked, false) triggerEvent("onVehicleSpawn", veh, false) exports.global:givePlayerAchievement(thePlayer, 17) -- my ride setElementData(veh, "requires.vehpos", 1, false) setTimer(checkVehpos, 3600000, 1, veh) end end end function checkVehpos(veh) local requires = getElementData(veh, "requires.vehpos") if (requires) then if (requires==1) then local id = tonumber(getElementData(veh, "dbid")) exports.irc:sendMessage("Removing vehicle #" .. id .. " (Did not get Vehpossed).") destroyElement(veh) local query = mysql_query(handler, "DELETE FROM vehicles WHERE id='" .. id .. "' LIMIT 1") mysql_free_result(query) end end end
-- //////////////////////////////////// -- // 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 // -- //////////////////////////////////// carshopPickup = createPickup(544.4990234375, -1292.7890625, 17.2421875, 3, 1239) exports.pool:allocateElement(carshopPickup) function pickupUse(thePlayer) triggerClientEvent(thePlayer, "showCarshopUI", thePlayer) end addEventHandler("onPickupHit", carshopPickup, pickupUse) function buyCar(car, cost, id, col1, col2) if not getElementData(source, "money") then return end local safemoney = tonumber(getElementData(source, "money")) local hackmoney = getPlayerMoney(source) if (safemoney == hackmoney and safemoney >= tonumber(cost)) then outputChatBox("You bought a " .. car .. " for " .. cost .. "$. Enjoy!", source, 255, 194, 14) outputChatBox("You can set this vehicles spawn position by parking it and typing /vehpos", source, 255, 194, 14) outputChatBox("Vehicles parked near the dealership or bus spawn point will be deleted without notice.", source, 255, 0, 0) outputChatBox("Press I and use your car key to unlock this vehicle.", source, 255, 194, 14) makeCar(source, car, cost, id, col1, col2) end end addEvent("buyCar", true) addEventHandler("buyCar", getRootElement(), buyCar) function makeCar(thePlayer, car, cost, id, col1, col2) local rx = 0 local ry = 0 local rz = 333.74502563477 local x, y, z = 548.59375, -1276.373046875, 17.248237609863 setElementPosition(thePlayer, 541.6484375, -1274.1513671875, 17.2421875) setPedRotation(thePlayer, 266.69442749023) local username = getPlayerName(thePlayer) local dbid = getElementData(thePlayer, "dbid") exports.global:takePlayerSafeMoney(thePlayer, tonumber(cost)) local letter1 = string.char(math.random(65,90)) local letter2 = string.char(math.random(65,90)) local plate = letter1 .. letter2 .. math.random(0, 9) .. " " .. math.random(1000, 9999) local veh = createVehicle(id, x, y, z, 0, 0, rz, plate) exports.pool:allocateElement(veh) setElementData(veh, "fuel", 100) setElementData(veh, "Impounded", 0) setVehicleRespawnPosition(veh, x, y, z, 0, 0, rz) setVehicleLocked(veh, false) local locked = 0 setVehicleColor(veh, col1, col2, col1, col2) setVehicleOverrideLights(veh, 1) setVehicleEngineState(veh, false) setVehicleFuelTankExplodable(veh, false) local query = mysql_query(handler, "INSERT INTO vehicles SET model='" .. id .. "', x='" .. x .. "', y='" .. y .. "', z='" .. z .. "', rotx='" .. rx .. "', roty='" .. ry .. "', rotz='" .. rz .. "', color1='" .. col1 .. "', color2='" .. col2 .. "', faction='-1', owner='" .. dbid .. "', plate='" .. plate .. "', currx='" .. x .. "', curry='" .. y .. "', currz='" .. z .. "', currrx='0', currry='0', currrz='" .. rz .. "', locked='" .. locked .. "'") local insertid = mysql_insert_id ( handler ) if (query) then mysql_free_result(query) exports.global:givePlayerItem(thePlayer, 3, tonumber(insertid)) setElementData(veh, "dbid", tonumber(insertid)) setElementData(veh, "fuel", 100) setElementData(veh, "engine", 0, false) setElementData(veh, "oldx", x, false) setElementData(veh, "oldy", y, false) setElementData(veh, "oldz", z, false) setElementData(veh, "faction", -1, false) setElementData(veh, "owner", dbid, false) setElementData(veh, "job", 0, false) setElementData(veh, "locked", locked, false) triggerEvent("onVehicleSpawn", veh, false) exports.global:givePlayerAchievement(thePlayer, 17) -- my ride setElementData(veh, "requires.vehpos", 1, false) setTimer(checkVehpos, 3600000, 1, veh) end end function checkVehpos(veh) local requires = getElementData(veh, "requires.vehpos") if (requires) then if (requires==1) then local id = tonumber(getElementData(veh, "dbid")) exports.irc:sendMessage("Removing vehicle #" .. id .. " (Did not get Vehpossed).") destroyElement(veh) local query = mysql_query(handler, "DELETE FROM vehicles WHERE id='" .. id .. "' LIMIT 1") mysql_free_result(query) end end end
Fixed r1197
Fixed r1197 git-svn-id: 8769cb08482c9977c94b72b8e184ec7d2197f4f7@1203 64450a49-1f69-0410-a0a2-f5ebb52c4f5b
Lua
bsd-3-clause
valhallaGaming/uno,valhallaGaming/uno,valhallaGaming/uno
41ec4c68adf7e6545aa10b359fea1883bec79b3e
applications/luci-app-statistics/luasrc/statistics/rrdtool/definitions/nut.lua
applications/luci-app-statistics/luasrc/statistics/rrdtool/definitions/nut.lua
-- Licensed to the public under the Apache License 2.0. module("luci.statistics.rrdtool.definitions.nut",package.seeall) function rrdargs( graph, plugin, plugin_instance, dtype ) local voltages = { title = "%H: Voltages on UPS \"%pi\"", vlabel = "V", number_format = "%5.1lfV", data = { instances = { voltage = { "battery", "input", "output" } }, options = { voltage_output = { color = "00e000", title = "Output voltage", noarea=true, overlay=true }, voltage_battery = { color = "0000ff", title = "Battery voltage", noarea=true, overlay=true }, voltage_input = { color = "ffb000", title = "Input voltage", noarea=true, overlay=true } } } } local currents = { title = "%H: Current on UPS \"%pi\"", vlabel = "A", number_format = "%5.3lfA", data = { instances = { current = { "battery", "output" } }, options = { current_output = { color = "00e000", title = "Output current", noarea=true, overlay=true }, current_battery = { color = "0000ff", title = "Battery current", noarea=true, overlay=true }, } } } local percentage = { title = "%H: Battery charge on UPS \"%pi\"", vlabel = "Percent", y_min = "0", y_max = "100", number_format = "%5.1lf%%", data = { sources = { percent = { "percent" } }, instances = { percent = "charge" }, options = { percent_charge = { color = "00ff00", title = "Charge level" } } } } -- Note: This is in ISO8859-1 for rrdtool. Welcome to the 20th century. local temperature = { title = "%H: Battery temperature on UPS \"%pi\"", vlabel = "\176C", number_format = "%5.1lf\176C", data = { instances = { temperature = "battery" }, options = { temperature_battery = { color = "ffb000", title = "Battery temperature" } } } } local timeleft = { title = "%H: Time left on UPS \"%pi\"", vlabel = "Minutes", number_format = "%.1lfm", data = { sources = { timeleft = { "timeleft" } }, instances = { timeleft = { "battery" } }, options = { timeleft_battery = { color = "0000ff", title = "Time left", transform_rpn = "60,/" } } } } return { voltages, currents, percentage, temperature, timeleft } end
-- Licensed to the public under the Apache License 2.0. module("luci.statistics.rrdtool.definitions.nut",package.seeall) function rrdargs( graph, plugin, plugin_instance, dtype ) local voltages = { title = "%H: Voltages on UPS \"%pi\"", vlabel = "V", number_format = "%5.1lfV", data = { instances = { voltage = { "battery", "input", "output" } }, options = { voltage_output = { color = "00e000", title = "Output voltage", noarea=true, overlay=true }, voltage_battery = { color = "0000ff", title = "Battery voltage", noarea=true, overlay=true }, voltage_input = { color = "ffb000", title = "Input voltage", noarea=true, overlay=true } } } } local currents = { title = "%H: Current on UPS \"%pi\"", vlabel = "A", number_format = "%5.3lfA", data = { instances = { current = { "battery", "output" } }, options = { current_output = { color = "00e000", title = "Output current", noarea=true, overlay=true }, current_battery = { color = "0000ff", title = "Battery current", noarea=true, overlay=true }, } } } local percentage = { title = "%H: Battery charge on UPS \"%pi\"", vlabel = "Percent", y_min = "0", y_max = "100", number_format = "%5.1lf%%", data = { instances = { percent = "charge" }, options = { percent_charge = { color = "00ff00", title = "Charge level" } } } } -- Note: This is in ISO8859-1 for rrdtool. Welcome to the 20th century. local temperature = { title = "%H: Battery temperature on UPS \"%pi\"", vlabel = "\176C", number_format = "%5.1lf\176C", data = { instances = { temperature = "battery" }, options = { temperature_battery = { color = "ffb000", title = "Battery temperature" } } } } local timeleft = { title = "%H: Time left on UPS \"%pi\"", vlabel = "Minutes", number_format = "%.1lfm", data = { instances = { timeleft = { "battery" } }, options = { timeleft_battery = { color = "0000ff", title = "Time left", transform_rpn = "60,/" } } } } return { voltages, currents, percentage, temperature, timeleft } end
luci/statistics: Fix nut UPS graphs
luci/statistics: Fix nut UPS graphs At some point since I last checked, the nut plugin for collectd changed the names of the timeleft and percent datasets. Update the luci module to match so that those graphs are generated correctly again. Signed-off-by: David Woodhouse <[email protected]>
Lua
apache-2.0
forward619/luci,lbthomsen/openwrt-luci,remakeelectric/luci,urueedi/luci,taiha/luci,cappiewu/luci,cshore/luci,981213/luci-1,daofeng2015/luci,mumuqz/luci,openwrt-es/openwrt-luci,thess/OpenWrt-luci,hnyman/luci,kuoruan/lede-luci,kuoruan/luci,cshore-firmware/openwrt-luci,openwrt-es/openwrt-luci,LuttyYang/luci,981213/luci-1,981213/luci-1,cappiewu/luci,bittorf/luci,cshore-firmware/openwrt-luci,aa65535/luci,kuoruan/luci,maxrio/luci981213,obsy/luci,jorgifumi/luci,cshore/luci,LuttyYang/luci,cshore/luci,NeoRaider/luci,daofeng2015/luci,openwrt-es/openwrt-luci,forward619/luci,openwrt/luci,LuttyYang/luci,chris5560/openwrt-luci,jorgifumi/luci,openwrt-es/openwrt-luci,ollie27/openwrt_luci,jlopenwrtluci/luci,teslamint/luci,schidler/ionic-luci,bittorf/luci,tobiaswaldvogel/luci,hnyman/luci,NeoRaider/luci,cshore-firmware/openwrt-luci,LuttyYang/luci,bittorf/luci,taiha/luci,LuttyYang/luci,obsy/luci,Wedmer/luci,Wedmer/luci,taiha/luci,openwrt/luci,forward619/luci,lbthomsen/openwrt-luci,forward619/luci,teslamint/luci,lbthomsen/openwrt-luci,nmav/luci,aa65535/luci,tobiaswaldvogel/luci,aa65535/luci,oneru/luci,jorgifumi/luci,artynet/luci,urueedi/luci,obsy/luci,rogerpueyo/luci,teslamint/luci,Wedmer/luci,obsy/luci,rogerpueyo/luci,artynet/luci,schidler/ionic-luci,dwmw2/luci,Wedmer/luci,ollie27/openwrt_luci,jlopenwrtluci/luci,Noltari/luci,NeoRaider/luci,mumuqz/luci,shangjiyu/luci-with-extra,hnyman/luci,jorgifumi/luci,schidler/ionic-luci,chris5560/openwrt-luci,wongsyrone/luci-1,NeoRaider/luci,urueedi/luci,remakeelectric/luci,obsy/luci,schidler/ionic-luci,Hostle/luci,rogerpueyo/luci,aa65535/luci,wongsyrone/luci-1,Noltari/luci,aa65535/luci,lbthomsen/openwrt-luci,dwmw2/luci,bright-things/ionic-luci,maxrio/luci981213,oneru/luci,thess/OpenWrt-luci,kuoruan/lede-luci,cshore/luci,remakeelectric/luci,ollie27/openwrt_luci,tobiaswaldvogel/luci,dwmw2/luci,chris5560/openwrt-luci,ollie27/openwrt_luci,NeoRaider/luci,taiha/luci,kuoruan/luci,lbthomsen/openwrt-luci,jlopenwrtluci/luci,openwrt-es/openwrt-luci,thess/OpenWrt-luci,rogerpueyo/luci,taiha/luci,ollie27/openwrt_luci,ollie27/openwrt_luci,remakeelectric/luci,rogerpueyo/luci,openwrt/luci,tobiaswaldvogel/luci,kuoruan/lede-luci,jlopenwrtluci/luci,wongsyrone/luci-1,wongsyrone/luci-1,openwrt/luci,maxrio/luci981213,cshore-firmware/openwrt-luci,tobiaswaldvogel/luci,remakeelectric/luci,Hostle/luci,ollie27/openwrt_luci,remakeelectric/luci,cshore/luci,cappiewu/luci,artynet/luci,openwrt/luci,shangjiyu/luci-with-extra,jlopenwrtluci/luci,chris5560/openwrt-luci,981213/luci-1,NeoRaider/luci,LuttyYang/luci,981213/luci-1,mumuqz/luci,hnyman/luci,artynet/luci,thess/OpenWrt-luci,thess/OpenWrt-luci,cappiewu/luci,kuoruan/lede-luci,kuoruan/luci,artynet/luci,nmav/luci,artynet/luci,nmav/luci,jlopenwrtluci/luci,wongsyrone/luci-1,jlopenwrtluci/luci,nmav/luci,artynet/luci,forward619/luci,wongsyrone/luci-1,aa65535/luci,cappiewu/luci,cshore-firmware/openwrt-luci,lbthomsen/openwrt-luci,teslamint/luci,daofeng2015/luci,schidler/ionic-luci,shangjiyu/luci-with-extra,bright-things/ionic-luci,bittorf/luci,chris5560/openwrt-luci,openwrt-es/openwrt-luci,NeoRaider/luci,hnyman/luci,taiha/luci,kuoruan/lede-luci,mumuqz/luci,mumuqz/luci,nmav/luci,cshore-firmware/openwrt-luci,NeoRaider/luci,LuttyYang/luci,urueedi/luci,jorgifumi/luci,taiha/luci,artynet/luci,dwmw2/luci,bright-things/ionic-luci,mumuqz/luci,jorgifumi/luci,tobiaswaldvogel/luci,dwmw2/luci,obsy/luci,teslamint/luci,forward619/luci,jlopenwrtluci/luci,Wedmer/luci,chris5560/openwrt-luci,daofeng2015/luci,Hostle/luci,bittorf/luci,urueedi/luci,kuoruan/luci,wongsyrone/luci-1,Hostle/luci,aa65535/luci,Noltari/luci,maxrio/luci981213,aa65535/luci,nmav/luci,oneru/luci,cappiewu/luci,Noltari/luci,cshore/luci,cshore/luci,Noltari/luci,cshore-firmware/openwrt-luci,rogerpueyo/luci,mumuqz/luci,urueedi/luci,bright-things/ionic-luci,hnyman/luci,urueedi/luci,kuoruan/luci,hnyman/luci,maxrio/luci981213,Hostle/luci,Noltari/luci,teslamint/luci,tobiaswaldvogel/luci,LuttyYang/luci,bittorf/luci,bright-things/ionic-luci,shangjiyu/luci-with-extra,kuoruan/lede-luci,bright-things/ionic-luci,openwrt/luci,dwmw2/luci,daofeng2015/luci,daofeng2015/luci,teslamint/luci,kuoruan/luci,chris5560/openwrt-luci,shangjiyu/luci-with-extra,bittorf/luci,Hostle/luci,oneru/luci,shangjiyu/luci-with-extra,remakeelectric/luci,rogerpueyo/luci,oneru/luci,hnyman/luci,Hostle/luci,schidler/ionic-luci,mumuqz/luci,oneru/luci,nmav/luci,taiha/luci,dwmw2/luci,cshore/luci,thess/OpenWrt-luci,schidler/ionic-luci,Wedmer/luci,bright-things/ionic-luci,artynet/luci,rogerpueyo/luci,thess/OpenWrt-luci,Wedmer/luci,teslamint/luci,jorgifumi/luci,Hostle/luci,forward619/luci,schidler/ionic-luci,oneru/luci,kuoruan/lede-luci,Noltari/luci,thess/OpenWrt-luci,maxrio/luci981213,openwrt/luci,shangjiyu/luci-with-extra,jorgifumi/luci,Noltari/luci,kuoruan/luci,daofeng2015/luci,chris5560/openwrt-luci,openwrt-es/openwrt-luci,lbthomsen/openwrt-luci,openwrt-es/openwrt-luci,obsy/luci,nmav/luci,bright-things/ionic-luci,tobiaswaldvogel/luci,shangjiyu/luci-with-extra,Wedmer/luci,dwmw2/luci,ollie27/openwrt_luci,daofeng2015/luci,oneru/luci,urueedi/luci,forward619/luci,maxrio/luci981213,openwrt/luci,cappiewu/luci,cappiewu/luci,maxrio/luci981213,Noltari/luci,nmav/luci,obsy/luci,lbthomsen/openwrt-luci,remakeelectric/luci,981213/luci-1,cshore-firmware/openwrt-luci,wongsyrone/luci-1,981213/luci-1,kuoruan/lede-luci,bittorf/luci
301c66b51b95dae454bd16148f834d318bba4d5b
src/lib/configure/external/Project.lua
src/lib/configure/external/Project.lua
--- @classmod configure.external.Project local Project = {} --- Create a new Project -- @param args -- @param args.build The build instance -- @param args.name Name of the project to add -- @param[opt] args.root_directory Where to place all project files function Project:new(o) assert(o ~= nil) assert(o.build ~= nil) o._build = o.build o.build = nil assert(o.name ~= nil) setmetatable(o, self) self.__index = self o:_init() return o end function Project:_init() if self.root_directory == nil then self.root_directory = self._build:directory() / self.name end if self.extract_directory == nil then self.extract_directory = self:step_directory('source') end if self.stamps_directory == nil then self.stamps_directory = self.root_directory / 'stamps' end self.steps = {} self.files = {} self._build:debug("Add project", self.name, "in", self.root_directory) end --- Checkout sources from git -- -- @param args -- @param args.url -- @param args.tag function Project:git_checkout(args) return self:add_step{ name = 'download', } end --- Download a tarball -- -- @param args -- @param args.url The download link -- @param args.filename The filename if it cannot be infered from the url. -- @param args.method Method used to retreive the sources (defaults to 'fetch') function Project:download(args) local args = table.update( {method = 'fetch'}, args ) local callbacks = { fetch = self._download_tarball, } local cb = callbacks[args.method] if cb == nil then self.build:error("The method " .. tostring(args.method) .. " does not exist") end return cb(self, args) end function Project:_download_tarball(args) local filename = args.filename if filename == nil then local index = args.url:find("/[^/]*$") filename = args.url:sub(index + 1, -1) end local download_dir = self:step_directory('download') local tarball = download_dir / filename return self:add_step{ name = 'download', targets = { [0] = { {self._build:configure_program(), '-E', 'fetch', args.url, tarball}, {self._build:configure_program(), '-E', 'extract', tarball, self:step_directory('extract')} } }, sources = args.sources, } end function Project:configure(args) return self:add_step{ name = 'configure', targets = { [0] = {args.command}, }, working_directory = args.working_directory, env = args.env, sources = args.sources, } end function Project:build(args) return self:add_step{ name = 'build', targets = { [0] = {args.command}, }, working_directory = args.working_directory, env = args.env, sources = args.sources, } end function Project:install(args) return self:add_step{ name = 'install', targets = { [0] = {args.command} }, working_directory = args.working_directory, env = args.env, sources = args.sources, } end function Project:stamp_node(name) return self._build:target_node(self.root_directory / 'stamps' / name) end --- Add a step to the project -- -- @param args -- @string args.name Step name -- @param args.targets A table of commands. Each key is either a `Path` -- to the target file or `0` if no specific file is required. The value is a -- list of commands to be triggered. -- @param[opt] args.working_directory Where to trigger the commands -- @param[opt] args.env Environ to use for the command -- @param[opt] args.directory The step directory -- @param[opt] args.sources Dependency nodes function Project:add_step(args) local name = args.name local directory = args.directory or self:step_directory(name) local stamp = self:stamp_node(name) local stamped_rule = Rule:new():add_target(stamp) for _, source in ipairs(args.sources or {}) do stamped_rule:add_source(source) end for target, commands in pairs(args.targets or {}) do local rule = stamped_rule if target ~= 0 then rule = Rule:new():add_target(self._build:target_node(target)) stamped_rule:add_source(self._build:target_node(target)) end for _, command in ipairs(commands) do local cmd = ShellCommand:new(table.unpack(command)) if args.working_directory ~= nil then cmd:working_directory(args.working_directory) end if args.env ~= nil then cmd:env(args.env) end rule:add_shell_command(cmd) end if rule ~= stamped_rule then self._build:add_rule(rule) end end stamped_rule:add_shell_command( ShellCommand:new(self._build:configure_program(), '-E', 'touch', stamp) ) local previous = table.update({}, args.dependencies or {}) if #previous == 0 then if #self.steps > 0 then table.append(previous, self.steps[#self.steps]) end end for _, p in ipairs(previous) do stamped_rule:add_source(p) end table.append(self.steps, stamp) self._build:add_rule(stamped_rule) return self end function Project:last_step() if #self.steps > 0 then return self.steps[#self.steps] end end function Project:step_directory(name) local attr = '_internal_' .. name .. '_directory' if self[attr] == nil then local dir = self[name .. '_directory'] if dir ~= nil then if type(dir) == 'string' then dir = Path:new(dir) elseif getmetatable(dir) == Node then dir = dir:path() elseif getmetatable(dir) ~= Path then self._build:error("Attribute '" .. name .. "_directory' is not a Path, a Node or a string") end if not dir:is_absolute() then dir = self.root_directory / dir end else dir = self.root_directory / name end self[attr] = dir self._build:directory_node(dir) -- Add the directory node to the build end return self[attr] end --- Node file created in a step. -- -- @param args -- @param args.path The relative path to the built file -- @param[opt] args.step The step where the file should be located (defaults to 'install') -- @param[opt] args.is_directory True when the node is a directory node (defaults to `false`) function Project:node(args) local step = args.step or 'install' local path = self:step_directory(step) / args.path local node = self.files[tostring(path)] if node == nil then if args.is_directory == true then node = self._build:directory_node(path) else node = self._build:target_node(path) self._build:add_rule( Rule:new():add_source(self:stamp_node(step)):add_target(node) ) end self.files[tostring(path)] = node end return node end function Project:directory_node(args) return self:node(table.update({is_directory = true}, args)) end return Project
--- @classmod configure.external.Project local Project = {} --- Create a new Project -- @param args -- @param args.build The build instance -- @param args.name Name of the project to add -- @param[opt] args.root_directory Where to place all project files function Project:new(o) assert(o ~= nil) assert(o.build ~= nil) o._build = o.build o.build = nil assert(o.name ~= nil) setmetatable(o, self) self.__index = self o:_init() return o end function Project:_init() if self.root_directory == nil then self.root_directory = self._build:directory() / self.name end if self.extract_directory == nil then self.extract_directory = self:step_directory('source') end if self.stamps_directory == nil then self.stamps_directory = self.root_directory / 'stamps' end self.steps = {} self.files = {} self._build:debug("Add project", self.name, "in", self.root_directory) end --- Checkout sources from git -- -- @param args -- @param args.url -- @param args.tag function Project:git_checkout(args) return self:add_step{ name = 'download', } end --- Download a tarball -- -- @param args -- @param args.url The download link -- @param args.filename The filename if it cannot be infered from the url. -- @param args.method Method used to retreive the sources (defaults to 'fetch') function Project:download(args) local args = table.update( {method = 'fetch'}, args ) local callbacks = { fetch = self._download_tarball, } local cb = callbacks[args.method] if cb == nil then self.build:error("The method " .. tostring(args.method) .. " does not exist") end return cb(self, args) end function Project:_download_tarball(args) local filename = args.filename if filename == nil then local index = args.url:find("/[^/]*$") filename = args.url:sub(index + 1, -1) end local download_dir = self:step_directory('download') local tarball = download_dir / filename return self:add_step{ name = 'download', targets = { [0] = { {self._build:configure_program(), '-E', 'fetch', args.url, tarball}, {self._build:configure_program(), '-E', 'extract', tarball, self:step_directory('extract')} } }, sources = args.sources, } end function Project:configure(args) return self:add_step{ name = 'configure', targets = { [0] = {args.command}, }, working_directory = args.working_directory, env = args.env, sources = args.sources, } end function Project:build(args) return self:add_step{ name = 'build', targets = { [0] = {args.command}, }, working_directory = args.working_directory, env = args.env, sources = args.sources, } end function Project:install(args) return self:add_step{ name = 'install', targets = { [0] = {args.command} }, working_directory = args.working_directory, env = args.env, sources = args.sources, } end function Project:stamp_node(name) return self._build:target_node(self.root_directory / 'stamps' / name) end --- Add a step to the project -- -- @param args -- @string args.name Step name -- @param args.targets A table of commands. Each key is either a `Path` -- to the target file or `0` if no specific file is required. The value is a -- list of commands to be triggered. -- @param[opt] args.working_directory Where to trigger the commands -- @param[opt] args.env Environ to use for the command -- @param[opt] args.directory The step directory -- @param[opt] args.sources Dependency nodes function Project:add_step(args) local name = args.name local directory = args.directory or self:step_directory(name) local stamp = self:stamp_node(name) local stamped_rule = Rule:new():add_target(stamp) for _, source in ipairs(args.sources or {}) do stamped_rule:add_source(source) end local previous = table.update({}, args.dependencies or {}) if #previous == 0 then if #self.steps > 0 then table.append(previous, self.steps[#self.steps]) end end for _, p in ipairs(previous) do stamped_rule:add_source(p) end for target, commands in pairs(args.targets or {}) do local rule = stamped_rule if target ~= 0 then rule = Rule:new():add_target(self._build:target_node(target)) for _, p in ipairs(previous) do rule:add_source(p) print(target, 'depends on', p) end stamped_rule:add_source(self._build:target_node(target)) end for _, command in ipairs(commands) do local cmd = ShellCommand:new(table.unpack(command)) if args.working_directory ~= nil then cmd:working_directory(args.working_directory) end if args.env ~= nil then cmd:env(args.env) end rule:add_shell_command(cmd) end if rule ~= stamped_rule then self._build:add_rule(rule) end end stamped_rule:add_shell_command( ShellCommand:new(self._build:configure_program(), '-E', 'touch', stamp) ) table.append(self.steps, stamp) self._build:add_rule(stamped_rule) return self end function Project:last_step() if #self.steps > 0 then return self.steps[#self.steps] end end function Project:step_directory(name) local attr = '_internal_' .. name .. '_directory' if self[attr] == nil then local dir = self[name .. '_directory'] if dir ~= nil then if type(dir) == 'string' then dir = Path:new(dir) elseif getmetatable(dir) == Node then dir = dir:path() elseif getmetatable(dir) ~= Path then self._build:error("Attribute '" .. name .. "_directory' is not a Path, a Node or a string") end if not dir:is_absolute() then dir = self.root_directory / dir end else dir = self.root_directory / name end self[attr] = dir self._build:directory_node(dir) -- Add the directory node to the build end return self[attr] end --- Node file created in a step. -- -- @param args -- @param args.path The relative path to the built file -- @param[opt] args.step The step where the file should be located (defaults to 'install') -- @param[opt] args.is_directory True when the node is a directory node (defaults to `false`) function Project:node(args) local step = args.step or 'install' local path = self:step_directory(step) / args.path local node = self.files[tostring(path)] if node == nil then if args.is_directory == true then node = self._build:directory_node(path) else node = self._build:target_node(path) self._build:add_rule( Rule:new():add_source(self:stamp_node(step)):add_target(node) ) end self.files[tostring(path)] = node end return node end function Project:directory_node(args) return self:node(table.update({is_directory = true}, args)) end return Project
external.Project: Fix dependencies on individual targets.
external.Project: Fix dependencies on individual targets.
Lua
bsd-3-clause
hotgloupi/configure,hotgloupi/configure,hotgloupi/configure,hotgloupi/configure,hotgloupi/configure
5232ce8dd42fae9005c36c4e04ad988d4afedb77
inputters/base.lua
inputters/base.lua
local _deprecated = [[ You appear to be using a document class '%s' programmed for SILE <= v0.12.5. This system was refactored in v0.13.0 and the shims trying to make it work temporarily without refactoring your classes have been removed in v0.14.0. Please see v0.13.0 release notes for help. ]] local inputter = pl.class() inputter.type = "inputter" inputter._name = "base" inputter._docclass = nil function inputter:_init (options) if options then self.options = options end end function inputter:classInit (options) options = pl.tablex.merge(options, SILE.input.options, true) local constructor, class if SILE.scratch.class_from_uses then constructor = SILE.scratch.class_from_uses class = constructor._name end class = SILE.input.class or class or options.class or "plain" constructor = self._docclass or constructor or SILE.require(class, "classes", true) if constructor.id then SU.deprecated("std.object", "pl.class", "0.13.0", "0.14.0", string.format(_deprecated, constructor.id)) end SILE.documentState.documentClass = constructor(options) end function inputter:requireClass (tree) local root = SILE.documentState.documentClass == nil if root then if #tree ~= 1 or (tree[1].command ~= "sile" and tree[1].command ~= "document") then SU.error("This isn't a SILE document!") end self:classInit(tree[1].options or {}) self:preamble() end end function inputter:process (doc) local tree = self:parse(doc) self:requireClass(tree) return SILE.process(tree) end -- Just a simple one-level find. We're not reimplementing XPath here. function inputter.findInTree (_, tree, command) for i=1, #tree do if type(tree[i]) == "table" and tree[i].command == command then return tree[i] end end end local function process_ambles (ambles) for _, amble in ipairs(ambles) do if type(amble) == "string" then SILE.processFile(amble) elseif type(amble) == "function" then SU.warn("Passing functions as pre/postambles is not officially sactioned and may go away without being marked as a breaking change.") amble() elseif type(amble) == "table" then local options = {} if amble.pack then amble, options = amble.pack, amble.options end if amble.type == "package" then amble(options) else SILE.documentState.documentClass:initPackage(amble, options) end end end end function inputter.preamble (_) process_ambles(SILE.input.preambles) end function inputter.postamble (_) process_ambles(SILE.input.postambles) end return inputter
local _deprecated = [[ You appear to be using a document class '%s' programmed for SILE <= v0.12.5. This system was refactored in v0.13.0 and the shims trying to make it work temporarily without refactoring your classes have been removed in v0.14.0. Please see v0.13.0 release notes for help. ]] local inputter = pl.class() inputter.type = "inputter" inputter._name = "base" inputter._docclass = nil function inputter:_init (options) if options then self.options = options end end function inputter:classInit (options) options = pl.tablex.merge(options, SILE.input.options, true) local constructor, class if SILE.scratch.class_from_uses then constructor = SILE.scratch.class_from_uses class = constructor._name end class = SILE.input.class or class or options.class or "plain" options.class = nil -- don't pass already consumed class option to contstructor constructor = self._docclass or constructor or SILE.require(class, "classes", true) if constructor.id then SU.deprecated("std.object", "pl.class", "0.13.0", "0.14.0", string.format(_deprecated, constructor.id)) end SILE.documentState.documentClass = constructor(options) end function inputter:requireClass (tree) local root = SILE.documentState.documentClass == nil if root then if #tree ~= 1 or (tree[1].command ~= "sile" and tree[1].command ~= "document") then SU.error("This isn't a SILE document!") end self:classInit(tree[1].options or {}) self:preamble() end end function inputter:process (doc) local tree = self:parse(doc) self:requireClass(tree) return SILE.process(tree) end -- Just a simple one-level find. We're not reimplementing XPath here. function inputter.findInTree (_, tree, command) for i=1, #tree do if type(tree[i]) == "table" and tree[i].command == command then return tree[i] end end end local function process_ambles (ambles) for _, amble in ipairs(ambles) do if type(amble) == "string" then SILE.processFile(amble) elseif type(amble) == "function" then SU.warn("Passing functions as pre/postambles is not officially sactioned and may go away without being marked as a breaking change.") amble() elseif type(amble) == "table" then local options = {} if amble.pack then amble, options = amble.pack, amble.options end if amble.type == "package" then amble(options) else SILE.documentState.documentClass:initPackage(amble, options) end end end end function inputter.preamble (_) process_ambles(SILE.input.preambles) end function inputter.postamble (_) process_ambles(SILE.input.postambles) end return inputter
fix(cli): Allow CLI option to override document specified class
fix(cli): Allow CLI option to override document specified class
Lua
mit
alerque/sile,alerque/sile,alerque/sile,alerque/sile
b3bc94a1372f377b03471b745d58ce36241db00f
mod_seclabels/mod_seclabels.lua
mod_seclabels/mod_seclabels.lua
local st = require "util.stanza"; local xmlns_label = "urn:xmpp:sec-label:0"; local xmlns_label_catalog = "urn:xmpp:sec-label:catalog:0"; module:add_feature(xmlns_label); local labels = { Classified = { SECRET = { color = "black", bgcolor = "aqua", label = "THISISSECRET" }; PUBLIC = { label = "THISISPUBLIC" }; }; }; module:hook("iq/self/"..xmlns_label_catalog..":catalog", function (request) local catalog_request = request.stanza.tags[1]; local reply = st.reply(request.stanza) :tag("catalog", { xmlns = xmlns_label_catalog, to = catalog_request.attr.to, name = "Default", desc = "My labels" }); local function add_labels(catalog, labels, selector) for name, value in pairs(labels) do if value.label then catalog:tag("securitylabel", { xmlns = xmlns_label, selector = selector..name }) :tag("displaymarking", { fgcolor = value.color or "black", bgcolor = value.bgcolor or "white", }):text(value.name or name):up() :tag("label"); if type(value.label) == "string" then catalog:text(value.label); else catalog:add_child(value.label); end catalog:up():up(); else add_labels(catalog, value, (selector or "")..name.."|"); end end end add_labels(reply, labels); request.origin.send(reply); return true; end);
local st = require "util.stanza"; local xmlns_label = "urn:xmpp:sec-label:0"; local xmlns_label_catalog = "urn:xmpp:sec-label:catalog:0"; module:add_feature(xmlns_label); module:hook("account-disco-info", function(event) local stanza = event.stanza; stanza:tag('feature', {var=xmlns_label}):up(); stanza:tag('feature', {var=xmlns_label_catalog}):up(); end); local labels = { Classified = { SECRET = { color = "black", bgcolor = "aqua", label = "THISISSECRET" }; PUBLIC = { label = "THISISPUBLIC" }; }; }; module:hook("iq/self/"..xmlns_label_catalog..":catalog", function (request) local catalog_request = request.stanza.tags[1]; local reply = st.reply(request.stanza) :tag("catalog", { xmlns = xmlns_label_catalog, to = catalog_request.attr.to, name = "Default", desc = "My labels" }); local function add_labels(catalog, labels, selector) for name, value in pairs(labels) do if value.label then catalog:tag("securitylabel", { xmlns = xmlns_label, selector = selector..name }) :tag("displaymarking", { fgcolor = value.color or "black", bgcolor = value.bgcolor or "white", }):text(value.name or name):up() :tag("label"); if type(value.label) == "string" then catalog:text(value.label); else catalog:add_child(value.label); end catalog:up():up(); else add_labels(catalog, value, (selector or "")..name.."|"); end end end add_labels(reply, labels); request.origin.send(reply); return true; end);
mod_seclabels: Advertise features in account disco#info, fixes interop with Swift
mod_seclabels: Advertise features in account disco#info, fixes interop with Swift
Lua
mit
Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules
563516f59035f643ddeb9965c7103fda74bf9345
scripts/RecordUpload.lua
scripts/RecordUpload.lua
---- -- Upload MP3 file to the CDR Server ---- uuid = argv[1]; domain = argv[2]; format = argv[3]; if format==nil then format = "mp3" end emails = argv[4]; if emails==nil then emails = "none" end name = argv[5]; if name==nil then name = "none" end email_sbj = argv[6]; if email_sbj==nil then email_sbj = "none" end email_msg = argv[7]; if email_msg==nil then email_msg = "none" end api = freeswitch.API(); freeswitch.msleep(2000); rec_file = "/recordings/"..uuid.."_"..name; cdr_url = freeswitch.getGlobalVariable("cdr_url"); freeswitch.consoleLog("info", "[RecordUpload.lua]: Session record stopped at "..uuid.."\n"); function shell(c) local o, h h = assert(io.popen(c,"r")) o = h:read("*all") h:close() return o end function file_exists(name) local f=io.open(name,"r") freeswitch.consoleLog("debug", "[RecordUpload.lua]: File exists "..name.."\n"); if f~=nil then io.close(f) return true else return false end end if (file_exists(rec_file.."."..format) ) then ::upload:: freeswitch.consoleLog("debug", "[RecordUpload.lua]: "..uuid.." - uploading file\n"); r = api:executeString("http_put "..cdr_url.."/sys/formLoadFile?domain="..domain.."&id="..uuid.."&type="..format.."&email="..emails.."&name="..name.."&email_sbj="..email_sbj.."&email_msg="..email_msg.." "..rec_file.."."..format); freeswitch.consoleLog("debug", "[RecordUpload.lua]: "..r); if (r:match("OK") == 'OK') then del = "/bin/rm -rf "..rec_file.."."..format; freeswitch.consoleLog("debug", "[RecordUpload.lua]: "..del.."\n"); shell(del); else freeswitch.consoleLog("debug", "[RecordUpload.lua]: "..uuid.." - retrying upload in 30 sec\n"); freeswitch.msleep(30000); goto upload end end
---- -- Upload MP3 file to the CDR Server ---- uuid = argv[1]; domain = argv[2]; format = argv[3]; if format==nil then format = "mp3" end emails = argv[4]; if emails==nil then emails = "none" end name = argv[5]; if name==nil then name = "none" end email_sbj = argv[6]; if email_sbj==nil then email_sbj = "none" end email_msg = argv[7]; if email_msg==nil then email_msg = "none" end cdr_url = freeswitch.getGlobalVariable("cdr_url"); rec_file = "/recordings/"..session:getVariable("webitel_record_file_name"); freeswitch.consoleLog("INFO", "[RecordUpload.lua]: Session record stopped at "..uuid.."\n"); transfer_disposition = session:getVariable("transfer_disposition"); if transfer_disposition==nil then transfer_disposition = "nope" end if ( transfer_disposition=="recv_replace" ) then freeswitch.consoleLog("INFO", "[RecordUpload.lua]: transfer_disposition is " ..transfer_disposition.. ". Exit!\n"); return end api = freeswitch.API(); freeswitch.msleep(1000); freeswitch.consoleLog("NOTICE", "[RecordUpload.lua]: transfer_disposition is " ..transfer_disposition.. "\n"); function shell(c) local o, h h = assert(io.popen(c,"r")) o = h:read("*all") h:close() return o end function file_exists(name) local f=io.open(name,"r") freeswitch.consoleLog("NOTICE", "[RecordUpload.lua]: File exists "..name.."\n"); if f~=nil then io.close(f) return true else return false end end if (file_exists(rec_fil) ) then ::upload:: freeswitch.consoleLog("INFO", "[RecordUpload.lua]: "..uuid.." - uploading file\n"); r = api:executeString("http_put "..cdr_url.."/sys/formLoadFile?domain="..domain.."&id="..uuid.."&type="..format.."&email="..emails.."&name="..name.."&email_sbj="..email_sbj.."&email_msg="..email_msg.." "..rec_file); freeswitch.consoleLog("DEBUG", "[RecordUpload.lua]: "..r); if (r:match("OK") == 'OK') then del = "/bin/rm -rf "..rec_file; freeswitch.consoleLog("DEBUG", "[RecordUpload.lua]: "..del.."\n"); shell(del); else freeswitch.consoleLog("NOTICE", "[RecordUpload.lua]: "..uuid.." - retrying upload in 30 sec\n"); freeswitch.msleep(30000); goto upload end else freeswitch.consoleLog("WARNING", "[RecordUpload.lua]: "..uuid.." File not found\n"); end
RecordUpload.lua - fixed problem with transfer
RecordUpload.lua - fixed problem with transfer
Lua
mit
webitel/docker-freeswitch
498bede773f6fc2900b793aef849f6553ba61f73
Peripherals/WEB/init.lua
Peripherals/WEB/init.lua
if (not love.thread) or (not jit) then error("WEB peripherals requires love.thread and luajit") end local perpath = select(1,...) --The path to the web folder local bit = require("bit") local events = require("Engine.events") local json = require("Engine.JSON") local hasLuaSec = pcall(require,"ssl") local thread = love.thread.newThread(perpath.."webthread.lua") local to_channel = love.thread.newChannel() local from_channel = love.thread.newChannel() local to_counter = 0 local from_counter = 0 thread:start(to_channel, from_channel) local function clearFuncsFromTable(t) for k,v in pairs(t) do if type(v) == "function" then t[k] = nil elseif type(v) == "table" then clearFuncsFromTable(v) end end end return function(config) --A function that creates a new WEB peripheral. if not thread:isRunning() then error("Failed to load luajit-request: "..tostring(thread:getError())) end local timeout = config.timeout or 5 local CPUKit = config.CPUKit if not CPUKit then error("WEB Peripheral can't work without the CPUKit passed") end local indirect = {} --List of functions that requires custom coroutine.resume local devkit = {} local WEB, yWEB = {}, {} function WEB.send(url,args) if type(url) ~= "string" then return error("URL must be a string, provided: "..type(url)) end local args = args or {} if type(args) ~= "table" then return error("Args Must be a table or nil, provided: "..type(args)) end clearFuncsFromTable(args) --Since JSON can't encode functions ! args.timeout = timeout args = json:encode(args) to_channel:push({url,args}) to_counter = to_counter + 1 return to_counter --Return the request ID end function WEB.urlEncode(str) if type(str) ~= "string" then return error("STR must be a string, provided: "..type(str)) end str = str:gsub("\n", "\r\n") str = str:gsub("\r\r\n", "\r\n") str = str:gsub("([^A-Za-z0-9 %-%_%.])", function(c) local n = string.byte(c) if n < 128 then -- ASCII return string.format("%%%02X", n) else -- Non-ASCII (encode as UTF-8) return string.format("%%%02X", 192 + bit.band( bit.arshift(n,6), 31 )) .. string.format("%%%02X", 128 + bit.band( n, 63 )) end end) str = str:gsub(" ", "+") return str end local luasocket_modules = { "http", "ltn12", "mime", "smtp", "socket", "tcp", "udp", "url" } for k,v in pairs(luasocket_modules) do luasocket_modules[v] = k end function WEB.luasocket(submodule) if type(submodule) ~= "string" then return error("Submodule should be a string, provided: "..submodule) end submodule = string.lower(submodule) if not luasocket_modules[submodule] then return error("Invalid submodule: "..submodule) end return require(submodule) end function WEB.hasLuaSec() return hasLuaSec and true or false end function WEB.luasec(submodule) if not hasLuaSec then return error("LuaSec is not supported at the current platform") end if type(submodule) ~= "string" then return error("Submodule should be a string, provided: "..submodule) end submodule = string.lower(submodule) if submodule ~= "ssl" and submodule ~= "https" then return error("Invalid submodule: "..submodule) end return require(submodule) end events:register("love:update",function(dt) local result = from_channel:pop() if result then from_counter = from_counter +1 local data = json:decode(result) CPUKit.triggerEvent("webrequest",from_counter,unpack(data)) end end) events:register("love:reboot",function() to_channel:clear() to_channel:push("shutdown") end) events:register("love:quit",function() love.window.close() to_channel:clear() to_channel:push("shutdown") thread:wait() end) return WEB, yWEB, devkit end
if (not love.thread) or (not jit) then error("WEB peripherals requires love.thread and luajit") end local perpath = select(1,...) --The path to the web folder local bit = require("bit") local events = require("Engine.events") local json = require("Engine.JSON") local hasLuaSec = pcall(require,"ssl") if hasLuaSec then require("ssl"); require("https") end local thread = love.thread.newThread(perpath.."webthread.lua") local to_channel = love.thread.newChannel() local from_channel = love.thread.newChannel() local to_counter = 0 local from_counter = 0 thread:start(to_channel, from_channel) local function clearFuncsFromTable(t) for k,v in pairs(t) do if type(v) == "function" then t[k] = nil elseif type(v) == "table" then clearFuncsFromTable(v) end end end return function(config) --A function that creates a new WEB peripheral. if not thread:isRunning() then error("Failed to load luajit-request: "..tostring(thread:getError())) end local timeout = config.timeout or 5 local CPUKit = config.CPUKit if not CPUKit then error("WEB Peripheral can't work without the CPUKit passed") end local indirect = {} --List of functions that requires custom coroutine.resume local devkit = {} local WEB, yWEB = {}, {} function WEB.send(url,args) if type(url) ~= "string" then return error("URL must be a string, provided: "..type(url)) end local args = args or {} if type(args) ~= "table" then return error("Args Must be a table or nil, provided: "..type(args)) end clearFuncsFromTable(args) --Since JSON can't encode functions ! args.timeout = timeout args = json:encode(args) to_channel:push({url,args}) to_counter = to_counter + 1 return to_counter --Return the request ID end function WEB.urlEncode(str) if type(str) ~= "string" then return error("STR must be a string, provided: "..type(str)) end str = str:gsub("\n", "\r\n") str = str:gsub("\r\r\n", "\r\n") str = str:gsub("([^A-Za-z0-9 %-%_%.])", function(c) local n = string.byte(c) if n < 128 then -- ASCII return string.format("%%%02X", n) else -- Non-ASCII (encode as UTF-8) return string.format("%%%02X", 192 + bit.band( bit.arshift(n,6), 31 )) .. string.format("%%%02X", 128 + bit.band( n, 63 )) end end) str = str:gsub(" ", "+") return str end local luasocket_modules = { "socket.http", "ltn12", "mime", "socket.smtp", "socket", "socket.url" } for k,v in pairs(luasocket_modules) do require(v) end for k,v in pairs(luasocket_modules) do luasocket_modules[v] = k end function WEB.luasocket(submodule) if type(submodule) ~= "string" then return error("Submodule should be a string, provided: "..submodule) end submodule = string.lower(submodule) if not luasocket_modules[submodule] then return error("Invalid submodule: "..submodule) end return require(submodule) end function WEB.hasLuaSec() return hasLuaSec and true or false end function WEB.luasec(submodule) if not hasLuaSec then return error("LuaSec is not supported at the current platform") end if type(submodule) ~= "string" then return error("Submodule should be a string, provided: "..submodule) end submodule = string.lower(submodule) if submodule ~= "ssl" and submodule ~= "https" then return error("Invalid submodule: "..submodule) end return require(submodule) end events:register("love:update",function(dt) local result = from_channel:pop() if result then from_counter = from_counter +1 local data = json:decode(result) CPUKit.triggerEvent("webrequest",from_counter,unpack(data)) end end) events:register("love:reboot",function() to_channel:clear() to_channel:push("shutdown") end) events:register("love:quit",function() love.window.close() to_channel:clear() to_channel:push("shutdown") thread:wait() end) return WEB, yWEB, devkit end
Bugfixes
Bugfixes Former-commit-id: 16a583171571ab9ed0cd51c85b9dccaaa67def17
Lua
mit
RamiLego4Game/LIKO-12
b53b318ab9b81f9a50eb2bbfaaf11fce48077473
otouto/plugins/gImages.lua
otouto/plugins/gImages.lua
-- You need a Google API key and a Google Custom Search Engine set up to use this, in config.google_api_key and config.google_cse_key, respectively. -- You must also sign up for the CSE in the Google Developer Console, and enable image results. local gImages = {} local HTTPS = require('ssl.https') local URL = require('socket.url') local JSON = require('dkjson') local utilities = require('otouto.utilities') local bindings = require('otouto.bindings') function gImages:init(config) if not cred_data.google_apikey then print('Missing config value: google_apikey.') print('gImages.lua will not be enabled.') return elseif not cred_data.google_cse_id then print('Missing config value: google_cse_id.') print('gImages.lua will not be enabled.') return end gImages.triggers = utilities.triggers(self.info.username, config.cmd_pat):t('img', true):t('i', true).table gImages.doc = [[* ]]..config.cmd_pat..[[img* _<Suchbegriff>_ Sucht Bild mit Google und versendet es (SafeSearch aktiv) Alias: *]]..config.cmd_pat..[[i*]] end gImages.command = 'img <Suchbegriff>' function gImages:callback(callback, msg, self, config, input) if not msg then return end utilities.answer_callback_query(self, callback, 'Suche nochmal nach "'..URL.unescape(input)..'"') utilities.send_typing(self, msg.chat.id, 'upload_photo') local img_url, mimetype, context = gImages:get_image(input) if img_url == 403 then utilities.send_reply(self, msg, config.errors.quotaexceeded, true) return elseif not img_url then utilities.send_reply(self, msg, config.errors.connection, true) return end if mimetype == 'image/gif' then local file = download_to_file(img_url, 'img.gif') result = utilities.send_document(self, msg.chat.id, file, nil, msg.message_id, '{"inline_keyboard":[[{"text":"Seite aufrufen","url":"'..context..'"},{"text":"Bild aufrufen","url":"'..img_url..'"},{"text":"Nochmal suchen","callback_data":"gImages:'..input..'"}]]}') elseif mimetype == 'image/png' then local file = download_to_file(img_url, 'img.png') result = utilities.send_photo(self, msg.chat.id, file, nil, msg.message_id, '{"inline_keyboard":[[{"text":"Seite aufrufen","url":"'..context..'"},{"text":"Bild aufrufen","url":"'..img_url..'"},{"text":"Nochmal suchen","callback_data":"gImages:'..input..'"}]]}') elseif mimetype == 'image/jpeg' then local file = download_to_file(img_url, 'img.jpg') result = utilities.send_photo(self, msg.chat.id, file, nil, msg.message_id, '{"inline_keyboard":[[{"text":"Seite aufrufen","url":"'..context..'"},{"text":"Bild aufrufen","url":"'..img_url..'"},{"text":"Nochmal suchen","callback_data":"gImages:'..input..'"}]]}') end if not result then utilities.send_reply(self, msg, config.errors.connection, true, '{"inline_keyboard":[[{"text":"Nochmal versuchen","callback_data":"gImages:'..input..'"}]]}') return end end function gImages:get_image(input) local apikey = cred_data.google_apikey_2 -- 100 requests is RIDICULOUS Google! local cseid = cred_data.google_cse_id_2 local BASE_URL = 'https://www.googleapis.com/customsearch/v1' local url = BASE_URL..'/?searchType=image&alt=json&num=10&key='..apikey..'&cx='..cseid..'&safe=high'..'&q=' .. input .. '&fields=searchInformation(totalResults),queries(request(count)),items(link,mime,image(contextLink))' local jstr, res = HTTPS.request(url) local jdat = JSON.decode(jstr) if jdat.error then if jdat.error.code == 403 then return 403 else return false end end if jdat.searchInformation.totalResults == '0' then utilities.send_reply(self, msg, config.errors.results, true) return end local i = math.random(jdat.queries.request[1].count) return jdat.items[i].link, jdat.items[i].mime, jdat.items[i].image.contextLink end function gImages:action(msg, config, matches) local input = utilities.input(msg.text) if not input then if msg.reply_to_message and msg.reply_to_message.text then input = msg.reply_to_message.text else utilities.send_message(self, msg.chat.id, gImages.doc, true, msg.message_id, true) return end end print ('Checking if search contains blacklisted word: '..input) if is_blacklisted(input) then utilities.send_reply(self, msg, 'Vergiss es! ._.') return end utilities.send_typing(self, msg.chat.id, 'upload_photo') local img_url, mimetype, context = gImages:get_image(URL.escape(input)) if img_url == 403 then utilities.send_reply(self, msg, config.errors.quotaexceeded, true) return elseif not img_url then utilities.send_reply(self, msg, config.errors.connection, true) return end if mimetype == 'image/gif' then local file = download_to_file(img_url, 'img.gif') result = utilities.send_document(self, msg.chat.id, file, nil, msg.message_id, '{"inline_keyboard":[[{"text":"Seite aufrufen","url":"'..context..'"},{"text":"Bild aufrufen","url":"'..img_url..'"}],[{"text":"Nochmal suchen","callback_data":"gImages:'..URL.escape(input)..'"}]]}') elseif mimetype == 'image/png' then local file = download_to_file(img_url, 'img.png') result = utilities.send_photo(self, msg.chat.id, file, nil, msg.message_id, '{"inline_keyboard":[[{"text":"Seite aufrufen","url":"'..context..'"},{"text":"Bild aufrufen","url":"'..img_url..'"},{"text":"Nochmal suchen","callback_data":"gImages:'..URL.escape(input)..'"}]]}') elseif mimetype == 'image/jpeg' then local file = download_to_file(img_url, 'img.jpg') result = utilities.send_photo(self, msg.chat.id, file, nil, msg.message_id, '{"inline_keyboard":[[{"text":"Seite aufrufen","url":"'..context..'"},{"text":"Bild aufrufen","url":"'..img_url..'"},{"text":"Nochmal suchen","callback_data":"gImages:'..URL.escape(input)..'"}]]}') end if not result then utilities.send_reply(self, msg, config.errors.connection, true, '{"inline_keyboard":[[{"text":"Nochmal versuchen","callback_data":"gImages:'..URL.escape(input)..'"}]]}') return end end return gImages
-- You need a Google API key and a Google Custom Search Engine set up to use this, in config.google_api_key and config.google_cse_key, respectively. -- You must also sign up for the CSE in the Google Developer Console, and enable image results. local gImages = {} local HTTPS = require('ssl.https') local URL = require('socket.url') local JSON = require('dkjson') local utilities = require('otouto.utilities') local bindings = require('otouto.bindings') function gImages:init(config) if not cred_data.google_apikey then print('Missing config value: google_apikey.') print('gImages.lua will not be enabled.') return elseif not cred_data.google_cse_id then print('Missing config value: google_cse_id.') print('gImages.lua will not be enabled.') return end gImages.triggers = utilities.triggers(self.info.username, config.cmd_pat):t('img', true):t('i', true).table gImages.doc = [[* ]]..config.cmd_pat..[[img* _<Suchbegriff>_ Sucht Bild mit Google und versendet es (SafeSearch aktiv) Alias: *]]..config.cmd_pat..[[i*]] end gImages.command = 'img <Suchbegriff>' function gImages:callback(callback, msg, self, config, input) if not msg then return end utilities.answer_callback_query(self, callback, 'Suche nochmal nach "'..URL.unescape(input)..'"') utilities.send_typing(self, msg.chat.id, 'upload_photo') local img_url, mimetype, context = gImages:get_image(input) if img_url == 403 then utilities.send_reply(self, msg, config.errors.quotaexceeded, true) return elseif img_url == 'NORESULTS' then utilities.send_reply(self, msg, config.errors.results, true) return elseif not img_url then utilities.send_reply(self, msg, config.errors.connection, true) return end if mimetype == 'image/gif' then local file = download_to_file(img_url, 'img.gif') result = utilities.send_document(self, msg.chat.id, file, nil, msg.message_id, '{"inline_keyboard":[[{"text":"Seite aufrufen","url":"'..context..'"},{"text":"Bild aufrufen","url":"'..img_url..'"},{"text":"Nochmal suchen","callback_data":"gImages:'..input..'"}]]}') elseif mimetype == 'image/png' then local file = download_to_file(img_url, 'img.png') result = utilities.send_photo(self, msg.chat.id, file, nil, msg.message_id, '{"inline_keyboard":[[{"text":"Seite aufrufen","url":"'..context..'"},{"text":"Bild aufrufen","url":"'..img_url..'"},{"text":"Nochmal suchen","callback_data":"gImages:'..input..'"}]]}') elseif mimetype == 'image/jpeg' then local file = download_to_file(img_url, 'img.jpg') result = utilities.send_photo(self, msg.chat.id, file, nil, msg.message_id, '{"inline_keyboard":[[{"text":"Seite aufrufen","url":"'..context..'"},{"text":"Bild aufrufen","url":"'..img_url..'"},{"text":"Nochmal suchen","callback_data":"gImages:'..input..'"}]]}') end if not result then utilities.send_reply(self, msg, config.errors.connection, true, '{"inline_keyboard":[[{"text":"Nochmal versuchen","callback_data":"gImages:'..input..'"}]]}') return end end function gImages:get_image(input) local apikey = cred_data.google_apikey_2 -- 100 requests is RIDICULOUS Google! local cseid = cred_data.google_cse_id_2 local BASE_URL = 'https://www.googleapis.com/customsearch/v1' local url = BASE_URL..'/?searchType=image&alt=json&num=10&key='..apikey..'&cx='..cseid..'&safe=high'..'&q=' .. input .. '&fields=searchInformation(totalResults),queries(request(count)),items(link,mime,image(contextLink))' local jstr, res = HTTPS.request(url) local jdat = JSON.decode(jstr) if jdat.error then if jdat.error.code == 403 then return 403 else return false end end if jdat.searchInformation.totalResults == '0' then return 'NORESULTS' end local i = math.random(jdat.queries.request[1].count) return jdat.items[i].link, jdat.items[i].mime, jdat.items[i].image.contextLink end function gImages:action(msg, config, matches) local input = utilities.input(msg.text) if not input then if msg.reply_to_message and msg.reply_to_message.text then input = msg.reply_to_message.text else utilities.send_message(self, msg.chat.id, gImages.doc, true, msg.message_id, true) return end end print ('Checking if search contains blacklisted word: '..input) if is_blacklisted(input) then utilities.send_reply(self, msg, 'Vergiss es! ._.') return end utilities.send_typing(self, msg.chat.id, 'upload_photo') local img_url, mimetype, context = gImages:get_image(URL.escape(input)) if img_url == 403 then utilities.send_reply(self, msg, config.errors.quotaexceeded, true) return elseif img_url == 'NORESULTS' then utilities.send_reply(self, msg, config.errors.results, true) return elseif not img_url then utilities.send_reply(self, msg, config.errors.connection, true) return end if mimetype == 'image/gif' then local file = download_to_file(img_url, 'img.gif') result = utilities.send_document(self, msg.chat.id, file, nil, msg.message_id, '{"inline_keyboard":[[{"text":"Seite aufrufen","url":"'..context..'"},{"text":"Bild aufrufen","url":"'..img_url..'"}],[{"text":"Nochmal suchen","callback_data":"gImages:'..URL.escape(input)..'"}]]}') elseif mimetype == 'image/png' then local file = download_to_file(img_url, 'img.png') result = utilities.send_photo(self, msg.chat.id, file, nil, msg.message_id, '{"inline_keyboard":[[{"text":"Seite aufrufen","url":"'..context..'"},{"text":"Bild aufrufen","url":"'..img_url..'"},{"text":"Nochmal suchen","callback_data":"gImages:'..URL.escape(input)..'"}]]}') elseif mimetype == 'image/jpeg' then local file = download_to_file(img_url, 'img.jpg') result = utilities.send_photo(self, msg.chat.id, file, nil, msg.message_id, '{"inline_keyboard":[[{"text":"Seite aufrufen","url":"'..context..'"},{"text":"Bild aufrufen","url":"'..img_url..'"},{"text":"Nochmal suchen","callback_data":"gImages:'..URL.escape(input)..'"}]]}') end if not result then utilities.send_reply(self, msg, config.errors.connection, true, '{"inline_keyboard":[[{"text":"Nochmal versuchen","callback_data":"gImages:'..URL.escape(input)..'"}]]}') return end end return gImages
gImages: Fix, wenn kein Bild gefunden wird
gImages: Fix, wenn kein Bild gefunden wird
Lua
agpl-3.0
Brawl345/Brawlbot-v2
d8f2ee0c6ea58800117bad44e2aec1769fd32e95
scene/result.lua
scene/result.lua
-- -- Ekran wyświetlający wyniki. -- -- Wymagane moduły local app = require( 'lib.app' ) local preference = require( 'preference' ) local composer = require( 'composer' ) local fx = require( 'com.ponywolf.ponyfx' ) local tiled = require( 'com.ponywolf.ponytiled' ) local json = require( 'json' ) -- Lokalne zmienne local scene = composer.newScene() local info, ui function scene:create( event ) local sceneGroup = self.view local buttonSound = audio.loadSound( 'scene/endless/sfx/select.wav' ) -- Wczytanie mapy local uiData = json.decodeFile( system.pathForFile( 'scene/menu/ui/result.json', system.ResourceDirectory ) ) info = tiled.new( uiData, 'scene/menu/ui' ) info.x, info.y = display.contentCenterX - info.designedWidth/2, display.contentCenterY - info.designedHeight/2 -- Obsługa przycisków info.extensions = 'scene.menu.lib.' info:extend( 'button', 'label' ) function ui( event ) local phase = event.phase local name = event.buttonName if phase == 'released' then if ( name == 'restart' ) then app.playSound( buttonSound ) fx.fadeOut( function() composer.hideOverlay() composer.gotoScene( 'scene.refresh', { params = {} } ) end ) elseif ( name == 'menu' ) then fx.fadeOut( function() composer.hideOverlay() composer.gotoScene( 'scene.menu', { params = {} } ) end ) end end return true end sceneGroup:insert( info ) end function scene:show( event ) local phase = event.phase local message = event.params.message if ( phase == 'will' ) then if message then info:findObject('message').text = message end elseif ( phase == 'did' ) then app.addRuntimeEvents( {'ui', ui} ) end end function scene:hide( event ) local phase = event.phase local previousScene = event.parent if ( phase == 'will' ) then app.removeAllRuntimeEvents() previousScene:resumeGame() elseif ( phase == 'did' ) then end end function scene:destroy( event ) audio.stop() audio.dispose( buttonSound ) --collectgarbage() end scene:addEventListener( 'create' ) scene:addEventListener( 'show' ) scene:addEventListener( 'hide' ) scene:addEventListener( 'destroy' ) return scene
-- -- Ekran wyświetlający wyniki. -- -- Wymagane moduły local app = require( 'lib.app' ) local preference = require( 'preference' ) local composer = require( 'composer' ) local fx = require( 'com.ponywolf.ponyfx' ) local tiled = require( 'com.ponywolf.ponytiled' ) local json = require( 'json' ) -- Lokalne zmienne local scene = composer.newScene() local info, ui function scene:create( event ) local sceneGroup = self.view local buttonSound = audio.loadSound( 'scene/endless/sfx/select.wav' ) -- Wczytanie mapy local uiData = json.decodeFile( system.pathForFile( 'scene/menu/ui/result.json', system.ResourceDirectory ) ) info = tiled.new( uiData, 'scene/menu/ui' ) info.x, info.y = display.contentCenterX - info.designedWidth/2, display.contentCenterY - info.designedHeight/2 -- Obsługa przycisków info.extensions = 'scene.menu.lib.' info:extend( 'button', 'label' ) function ui( event ) local phase = event.phase local name = event.buttonName if phase == 'released' then app.playSound( buttonSound ) if ( name == 'restart' ) then fx.fadeOut( function() composer.hideOverlay() composer.gotoScene( 'scene.refresh', { params = {} } ) end ) elseif ( name == 'menu' ) then fx.fadeOut( function() composer.hideOverlay() composer.gotoScene( 'scene.menu', { params = {} } ) end ) end end return true end sceneGroup:insert( info ) end function scene:show( event ) local phase = event.phase local message = event.params.message if ( phase == 'will' ) then if message then info:findObject('message').text = message end elseif ( phase == 'did' ) then app.addRuntimeEvents( {'ui', ui} ) end end function scene:hide( event ) local phase = event.phase local previousScene = event.parent if ( phase == 'will' ) then app.removeAllRuntimeEvents() previousScene:resumeGame() elseif ( phase == 'did' ) then end end function scene:destroy( event ) audio.stop() audio.dispose( buttonSound ) --collectgarbage() end scene:addEventListener( 'create' ) scene:addEventListener( 'show' ) scene:addEventListener( 'hide' ) scene:addEventListener( 'destroy' ) return scene
Bug fix
Bug fix
Lua
mit
ldurniat/My-Pong-Game,ldurniat/The-Great-Pong
f32d9c9a70a46f22b75972e146d778bffaec0264
src/main.lua
src/main.lua
-- Kong, the biggest ape in town -- -- /\ ____ -- <> ( oo ) -- <>_| ^^ |_ -- <> @ \ -- /~~\ . . _ | -- /~~~~\ | | -- /~~~~~~\/ _| | -- |[][][]/ / [m] -- |[][][[m] -- |[][][]| -- |[][][]| -- |[][][]| -- |[][][]| -- |[][][]| -- |[][][]| -- |[][][]| -- |[][][]| -- |[|--|]| -- |[| |]| -- ======== -- ========== -- |[[ ]]| -- ========== utils = require "kong.tools.utils" local constants = require "constants" -- Define the plugins to load here, in the appropriate order local plugins = {} local _M = {} local function load_plugin_conf(api_id, application_id, plugin_name) local data, err = dao.plugins:find_by_keys { api_id = api_id, application_id = application_id ~= nil and application_id or constants.DATABASE_NULL_ID, name = plugin_name } if err then ngx.log(ngx.ERROR, err) return nil end if #data > 0 then local plugin = table.remove(data, 1) if plugin.enabled then return plugin end end return nil end function _M.init() -- Loading configuration configuration, dao = utils.load_configuration_and_dao(os.getenv("KONG_CONF")) dao:prepare() -- core is the first plugin table.insert(plugins, { name = "core", handler = require("kong.core.handler")() }) -- Loading defined plugins for _, plugin_name in ipairs(configuration.plugins_enabled) do table.insert(plugins, { name = plugin_name, handler = require("kong.plugins."..plugin_name..".handler")() }) end end function _M.access() -- Setting a property that will be available for every plugin ngx.ctx.start = ngx.now() ngx.ctx.plugin_conf = {} -- Iterate over all the plugins for _, plugin in ipairs(plugins) do if ngx.ctx.api then ngx.ctx.plugin_conf[plugin.name] = load_plugin_conf(ngx.ctx.api.id, nil, plugin.name) -- Loading the "API-specific" configuration end if ngx.ctx.authenticated_entity then local plugin_conf = load_plugin_conf(ngx.ctx.api.id, ngx.ctx.authenticated_entity.id, plugin.name) if plugin_conf then -- Override only if not nil ngx.ctx.plugin_conf[plugin.name] = plugin_conf end end if not ngx.ctx.error then local conf = ngx.ctx.plugin_conf[plugin.name] if not ngx.ctx.api then -- If not ngx.ctx.api then it's the core plugin plugin.handler:access(nil) elseif conf then plugin.handler:access(conf.value) end end end ngx.ctx.proxy_start = ngx.now() -- Setting a property that will be available for every plugin end function _M.header_filter() ngx.ctx.proxy_end = ngx.now() -- Setting a property that will be available for every plugin if not ngx.ctx.error then for _, plugin in ipairs(plugins) do local conf = ngx.ctx.plugin_conf[plugin.name] if conf then plugin.handler:header_filter(conf.value) end end end end function _M.body_filter() if not ngx.ctx.error then for _, plugin in ipairs(plugins) do local conf = ngx.ctx.plugin_conf[plugin.name] if conf then plugin.handler:body_filter(conf.value) end end end end function _M.log() if not ngx.ctx.error then local now = ngx.now() -- Creating the log variable that will be serialized local message = { request = { headers = ngx.req.get_headers(), size = ngx.var.request_length }, response = { headers = ngx.resp.get_headers(), size = ngx.var.body_bytes_sent }, authenticated_entity = ngx.ctx.authenticated_entity, api = ngx.ctx.api, ip = ngx.var.remote_addr, status = ngx.status, url = ngx.var.uri, created_at = now } ngx.ctx.log_message = message for _, plugin in ipairs(plugins) do local conf = ngx.ctx.plugin_conf[plugin.name] if conf then plugin.handler:log(conf.value) end end end end return _M
-- Kong, the biggest ape in town -- -- /\ ____ -- <> ( oo ) -- <>_| ^^ |_ -- <> @ \ -- /~~\ . . _ | -- /~~~~\ | | -- /~~~~~~\/ _| | -- |[][][]/ / [m] -- |[][][[m] -- |[][][]| -- |[][][]| -- |[][][]| -- |[][][]| -- |[][][]| -- |[][][]| -- |[][][]| -- |[][][]| -- |[|--|]| -- |[| |]| -- ======== -- ========== -- |[[ ]]| -- ========== utils = require "kong.tools.utils" local constants = require "kong.constants" -- Define the plugins to load here, in the appropriate order local plugins = {} local _M = {} local function load_plugin_conf(api_id, application_id, plugin_name) local rows, err = dao.plugins:find_by_keys { api_id = api_id, application_id = application_id ~= nil and application_id or constants.DATABASE_NULL_ID, name = plugin_name } if err then ngx.log(ngx.ERROR, err) return nil end if #rows > 0 then local plugin = table.remove(rows, 1) if plugin.enabled then return plugin end end return nil end function _M.init() -- Loading configuration configuration, dao = utils.load_configuration_and_dao(os.getenv("KONG_CONF")) dao:prepare() -- core is the first plugin table.insert(plugins, { core = true, name = "core", handler = require("kong.core.handler")() }) -- Loading defined plugins for _, plugin_name in ipairs(configuration.plugins_enabled) do table.insert(plugins, { name = plugin_name, handler = require("kong.plugins."..plugin_name..".handler")() }) end end function _M.access() -- Setting a property that will be available for every plugin ngx.ctx.start = ngx.now() ngx.ctx.plugin_conf = {} -- Iterate over all the plugins for _, plugin in ipairs(plugins) do if ngx.ctx.api then ngx.ctx.plugin_conf[plugin.name] = load_plugin_conf(ngx.ctx.api.id, nil, plugin.name) local application_id = ngx.ctx.authenticated_entity and ngx.ctx.authenticated_entity.id or nil if application_id then local app_plugin_conf = load_plugin_conf(ngx.ctx.api.id, application_id, plugin.name) if app_plugin_conf then ngx.ctx.plugin_conf[plugin.name] = app_plugin_conf end end end local conf = ngx.ctx.plugin_conf[plugin.name] if not ngx.ctx.error and (plugin.core or conf) then plugin.handler:access(conf and conf.value or nil) end end ngx.ctx.proxy_start = ngx.now() -- Setting a property that will be available for every plugin end function _M.header_filter() ngx.ctx.proxy_end = ngx.now() -- Setting a property that will be available for every plugin if not ngx.ctx.error then for _, plugin in ipairs(plugins) do local conf = ngx.ctx.plugin_conf[plugin.name] if conf then plugin.handler:header_filter(conf.value) end end end end function _M.body_filter() if not ngx.ctx.error then for _, plugin in ipairs(plugins) do local conf = ngx.ctx.plugin_conf[plugin.name] if conf then plugin.handler:body_filter(conf.value) end end end end function _M.log() if not ngx.ctx.error then local now = ngx.now() -- Creating the log variable that will be serialized local message = { request = { headers = ngx.req.get_headers(), size = ngx.var.request_length }, response = { headers = ngx.resp.get_headers(), size = ngx.var.body_bytes_sent }, authenticated_entity = ngx.ctx.authenticated_entity, api = ngx.ctx.api, ip = ngx.var.remote_addr, status = ngx.status, url = ngx.var.uri, created_at = now } ngx.ctx.log_message = message for _, plugin in ipairs(plugins) do local conf = ngx.ctx.plugin_conf[plugin.name] if conf then plugin.handler:log(conf.value) end end end end return _M
Fix plugin configuration loading
Fix plugin configuration loading
Lua
apache-2.0
ind9/kong,kyroskoh/kong,Kong/kong,icyxp/kong,ccyphers/kong,vzaramel/kong,jebenexer/kong,rafael/kong,xvaara/kong,jerizm/kong,Kong/kong,rafael/kong,Vermeille/kong,shiprabehera/kong,Kong/kong,isdom/kong,beauli/kong,streamdataio/kong,Mashape/kong,smanolache/kong,kyroskoh/kong,streamdataio/kong,ejoncas/kong,isdom/kong,akh00/kong,salazar/kong,ejoncas/kong,ind9/kong,vzaramel/kong,li-wl/kong,ajayk/kong
2472451097d43c9cbcb888c2331b593c2f0d9949
lib/switchboard_modules/lua_script_debugger/premade_scripts/i2c/gyro-l3gd20h.lua
lib/switchboard_modules/lua_script_debugger/premade_scripts/i2c/gyro-l3gd20h.lua
--This is an example that uses the L3GD20H Gyroscope on the I2C Bus on EIO4(SCL) and EIO5(SDA) --Outputs data to Registers: --X gyro = 46012 --Y gyro = 46014 --Z gyro = 46016 fwver = MB.R(60004, 3) devType = MB.R(60000, 3) if (fwver < 1.0224 and devType == 7) or (fwver < 0.2037 and devType == 4) then print("This lua script requires a higher firmware version (T7 Requires 1.0224 or higher, T4 requires 0.2037 or higher). Program Stopping") MB.W(6000, 1, 0) end function convert_16_bit(msb, lsb, conv)--Returns a number, adjusted using the conversion factor. Use 1 if not desired res = 0 if msb >= 128 then res = (-0x7FFF+((msb-128)*256+lsb))/conv else res = (msb*256+lsb)/conv end return res end SLAVE_ADDRESS = 0x6B I2C.config(13, 12, 65516, 0, SLAVE_ADDRESS, 0)--configure the I2C Bus addrs = I2C.search(0, 127) addrsLen = table.getn(addrs) found = 0 for i=1, addrsLen do--verify that the target device was found if addrs[i] == SLAVE_ADDRESS then print("I2C Slave Detected") found = 1 break end end if found == 0 then print("No I2C Slave detected, program stopping") MB.W(6000, 1, 0) end --init slave I2C.write({0x21, 0x00})--1. Write CTRL2, disable filtering I2C.write({0x22, 0x00})--2. Write CTRL3, disable interupts I2C.write({0x23, 0x60})--3. Write CTRL4, continuous update, MSB at lower addr,2000 deg per second I2C.write({0x25, 0x00})--5. Write Reference to default 0 I2C.write({0x24, 0x00})--9. Write CTRL5, disable FIFO and interupts I2C.write({0x20, 0xBF})--10. Write CTRL1, enable all axes, 380Hz ODR LJ.IntervalConfig(0, 200) while true do if LJ.CheckInterval(0) then dataRaw = {} for i=0, 5 do I2C.write({0x28+i}) dataIn, errorIn = I2C.read(2) table.insert(dataRaw, dataIn[1]) end data = {} for i=0, 2 do table.insert(data, convert_16_bit(dataRaw[1+i*2], dataRaw[2+i*2], (0x7FFF/2000))) MB.W(46012+i*2, 3, data[i+1]) end print("X: "..data[1]) print("Y: "..data[2]) print("Z: "..data[3]) print("------") end end
--[[ Name: gyro-l3gd20h.lua Desc: This is an example that uses the L3GD20H Gyroscope on the I2C Bus on EIO4(SCL) and EIO5(SDA) --]] --Outputs data to Registers: --X gyro = 46012 --Y gyro = 46014 --Z gyro = 46016 ------------------------------------------------------------------------------- -- Desc: Returns a number adjusted using the conversion factor -- Use 1 if not desired ------------------------------------------------------------------------------- local function convert_16_bit(msb, lsb, conv) res = 0 if msb >= 128 then res = (-0x7FFF+((msb-128)*256+lsb))/conv else res = (msb*256+lsb)/conv end return res end SLAVE_ADDRESS = 0x6B --Configure the I2C Bus I2C.config(13, 12, 65516, 0, SLAVE_ADDRESS, 0) local addrs = I2C.search(0, 127) local addrsLen = table.getn(addrs) local found = 0 -- Verify that the target device was found for i=1, addrsLen do if addrs[i] == SLAVE_ADDRESS then print("I2C Slave Detected") found = 1 break end end if found == 0 then print("No I2C Slave detected, program stopping") MB.writeName("LUA_RUN", 0) end -- Write CTRL2, disable filtering I2C.write({0x21, 0x00}) -- Write CTRL3, disable interupts I2C.write({0x22, 0x00}) -- Write CTRL4, continuous update, MSB at lower addr,2000 deg per second I2C.write({0x23, 0x60}) -- Write Reference to default 0 I2C.write({0x25, 0x00}) -- Write CTRL5, disable FIFO and interupts I2C.write({0x24, 0x00}) -- Write CTRL1, enable all axes, 380Hz ODR I2C.write({0x20, 0xBF}) -- Configure a 200ms interval LJ.IntervalConfig(0, 200) while true do -- If an interval is done if LJ.CheckInterval(0) then local rawgyrodata = {} for i=0, 5 do I2C.write({0x28+i}) local indata = I2C.read(2) table.insert(rawgyrodata, indata[1]) end local gyrodata = {} -- Get the gyro data and store it in USER_RAM for i=0, 2 do table.insert(gyrodata, convert_16_bit(rawgyrodata[1+i*2], rawgyrodata[2+i*2], (0x7FFF/2000))) MB.W(46012+i*2, 3, gyrodata[i+1]) end print("X: "..gyrodata[1]) print("Y: "..gyrodata[2]) print("Z: "..gyrodata[3]) print("------") end end
Fixed up the l3gd20h gyro example
Fixed up the l3gd20h gyro example
Lua
mit
chrisJohn404/ljswitchboard-module_manager,chrisJohn404/ljswitchboard-module_manager,chrisJohn404/ljswitchboard-module_manager
305b25486af424d89ccfc2fd7607579f90735602
applications/luci-wol/luasrc/model/cbi/wol.lua
applications/luci-wol/luasrc/model/cbi/wol.lua
--[[ LuCI - Lua Configuration Interface Copyright 2010 Jo-Philipp Wich <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 ]]-- local uci = require "luci.model.uci".cursor() local utl = require "luci.util" 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") 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"]:upper()] = { 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:upper()] = { 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:upper()] = { ip, name ~= "*" and name } end end uci:foreach("dhcp", "host", function(s) if s.mac and s.ip then arp[s.mac:upper()] = { s.ip, s.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 utl.kspairs(arp) do host:value(mac, "%s (%s)" %{ mac, ip[2] or ip[1] }) end function host.write(self, s, val) 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 local msg = "<p><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 msg = msg .. l .. "<br />" else break end end p:close() end msg = msg .. "</code></p>" m.message = msg end end return m
--[[ LuCI - Lua Configuration Interface Copyright 2010 Jo-Philipp Wich <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 ]]-- local uci = require "luci.model.uci".cursor() local utl = require "luci.util" 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") 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"]:upper()] = { 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:upper()] = { 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:upper()] = { ip, name ~= "*" and name } end end uci:foreach("dhcp", "host", function(s) if s.mac and s.ip then arp[s.mac:upper()] = { s.ip, s.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 utl.kspairs(arp) do host:value(mac, "%s (%s)" %{ mac, ip[2] or ip[1] }) end function host.write(self, s, val) local host = luci.http.formvalue("cbid.wol.1.mac") if host and #host > 0 and host:match("^[a-fA-F0-9:]+$") 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 local msg = "<p><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 msg = msg .. l .. "<br />" else break end end p:close() end msg = msg .. "</code></p>" m.message = msg end end return m
applications/luci-wol: fix XSS
applications/luci-wol: fix XSS
Lua
apache-2.0
hnyman/luci,zhaoxx063/luci,mumuqz/luci,artynet/luci,lcf258/openwrtcn,marcel-sch/luci,thesabbir/luci,dismantl/luci-0.12,Kyklas/luci-proto-hso,maxrio/luci981213,palmettos/test,remakeelectric/luci,fkooman/luci,teslamint/luci,joaofvieira/luci,remakeelectric/luci,shangjiyu/luci-with-extra,981213/luci-1,db260179/openwrt-bpi-r1-luci,dwmw2/luci,cappiewu/luci,Noltari/luci,sujeet14108/luci,openwrt-es/openwrt-luci,bright-things/ionic-luci,lbthomsen/openwrt-luci,Kyklas/luci-proto-hso,NeoRaider/luci,lbthomsen/openwrt-luci,nmav/luci,rogerpueyo/luci,kuoruan/lede-luci,tcatm/luci,kuoruan/luci,tobiaswaldvogel/luci,obsy/luci,david-xiao/luci,Noltari/luci,MinFu/luci,cappiewu/luci,maxrio/luci981213,lbthomsen/openwrt-luci,LuttyYang/luci,openwrt-es/openwrt-luci,cshore/luci,male-puppies/luci,taiha/luci,rogerpueyo/luci,kuoruan/lede-luci,mumuqz/luci,keyidadi/luci,palmettos/cnLuCI,urueedi/luci,Hostle/openwrt-luci-multi-user,thess/OpenWrt-luci,david-xiao/luci,urueedi/luci,jchuang1977/luci-1,taiha/luci,ff94315/luci-1,harveyhu2012/luci,shangjiyu/luci-with-extra,RedSnake64/openwrt-luci-packages,tcatm/luci,taiha/luci,MinFu/luci,keyidadi/luci,kuoruan/luci,lcf258/openwrtcn,ff94315/luci-1,harveyhu2012/luci,LuttyYang/luci,teslamint/luci,kuoruan/luci,opentechinstitute/luci,cshore/luci,cappiewu/luci,male-puppies/luci,nwf/openwrt-luci,RuiChen1113/luci,male-puppies/luci,deepak78/new-luci,jorgifumi/luci,schidler/ionic-luci,deepak78/new-luci,daofeng2015/luci,Wedmer/luci,MinFu/luci,schidler/ionic-luci,thess/OpenWrt-luci,RuiChen1113/luci,Wedmer/luci,ollie27/openwrt_luci,aircross/OpenWrt-Firefly-LuCI,keyidadi/luci,RedSnake64/openwrt-luci-packages,obsy/luci,urueedi/luci,slayerrensky/luci,keyidadi/luci,teslamint/luci,Noltari/luci,Hostle/luci,mumuqz/luci,palmettos/cnLuCI,wongsyrone/luci-1,LazyZhu/openwrt-luci-trunk-mod,openwrt/luci,LuttyYang/luci,openwrt-es/openwrt-luci,florian-shellfire/luci,david-xiao/luci,obsy/luci,oneru/luci,ReclaimYourPrivacy/cloak-luci,slayerrensky/luci,LazyZhu/openwrt-luci-trunk-mod,kuoruan/luci,Sakura-Winkey/LuCI,remakeelectric/luci,palmettos/test,zhaoxx063/luci,ollie27/openwrt_luci,thesabbir/luci,palmettos/test,Wedmer/luci,maxrio/luci981213,lcf258/openwrtcn,shangjiyu/luci-with-extra,lbthomsen/openwrt-luci,chris5560/openwrt-luci,aircross/OpenWrt-Firefly-LuCI,joaofvieira/luci,jchuang1977/luci-1,thesabbir/luci,aa65535/luci,jorgifumi/luci,NeoRaider/luci,Noltari/luci,forward619/luci,marcel-sch/luci,opentechinstitute/luci,bright-things/ionic-luci,nmav/luci,aircross/OpenWrt-Firefly-LuCI,dwmw2/luci,forward619/luci,obsy/luci,opentechinstitute/luci,RedSnake64/openwrt-luci-packages,palmettos/cnLuCI,Sakura-Winkey/LuCI,jchuang1977/luci-1,NeoRaider/luci,Sakura-Winkey/LuCI,nmav/luci,aa65535/luci,jorgifumi/luci,thess/OpenWrt-luci,aa65535/luci,florian-shellfire/luci,Hostle/openwrt-luci-multi-user,slayerrensky/luci,ollie27/openwrt_luci,opentechinstitute/luci,rogerpueyo/luci,kuoruan/luci,taiha/luci,joaofvieira/luci,keyidadi/luci,ReclaimYourPrivacy/cloak-luci,palmettos/test,kuoruan/lede-luci,teslamint/luci,marcel-sch/luci,ReclaimYourPrivacy/cloak-luci,nwf/openwrt-luci,LazyZhu/openwrt-luci-trunk-mod,jchuang1977/luci-1,nmav/luci,joaofvieira/luci,mumuqz/luci,LuttyYang/luci,harveyhu2012/luci,tobiaswaldvogel/luci,hnyman/luci,urueedi/luci,Kyklas/luci-proto-hso,dwmw2/luci,tobiaswaldvogel/luci,cshore-firmware/openwrt-luci,Wedmer/luci,obsy/luci,Hostle/openwrt-luci-multi-user,forward619/luci,thesabbir/luci,LazyZhu/openwrt-luci-trunk-mod,wongsyrone/luci-1,thess/OpenWrt-luci,schidler/ionic-luci,keyidadi/luci,cshore-firmware/openwrt-luci,jlopenwrtluci/luci,thess/OpenWrt-luci,nmav/luci,thesabbir/luci,rogerpueyo/luci,dwmw2/luci,NeoRaider/luci,florian-shellfire/luci,florian-shellfire/luci,palmettos/cnLuCI,RuiChen1113/luci,hnyman/luci,chris5560/openwrt-luci,MinFu/luci,joaofvieira/luci,marcel-sch/luci,jchuang1977/luci-1,cshore-firmware/openwrt-luci,slayerrensky/luci,MinFu/luci,schidler/ionic-luci,palmettos/test,RedSnake64/openwrt-luci-packages,cshore/luci,slayerrensky/luci,teslamint/luci,ff94315/luci-1,Hostle/openwrt-luci-multi-user,RuiChen1113/luci,lbthomsen/openwrt-luci,fkooman/luci,tobiaswaldvogel/luci,981213/luci-1,maxrio/luci981213,florian-shellfire/luci,oyido/luci,artynet/luci,rogerpueyo/luci,Noltari/luci,fkooman/luci,ollie27/openwrt_luci,cappiewu/luci,daofeng2015/luci,jlopenwrtluci/luci,ollie27/openwrt_luci,chris5560/openwrt-luci,jorgifumi/luci,obsy/luci,cshore/luci,deepak78/new-luci,oneru/luci,cappiewu/luci,cappiewu/luci,deepak78/new-luci,artynet/luci,tcatm/luci,oneru/luci,nmav/luci,chris5560/openwrt-luci,NeoRaider/luci,fkooman/luci,Sakura-Winkey/LuCI,daofeng2015/luci,remakeelectric/luci,tobiaswaldvogel/luci,bittorf/luci,slayerrensky/luci,marcel-sch/luci,lcf258/openwrtcn,urueedi/luci,lcf258/openwrtcn,bright-things/ionic-luci,maxrio/luci981213,cshore/luci,981213/luci-1,cshore/luci,cappiewu/luci,oyido/luci,florian-shellfire/luci,jorgifumi/luci,981213/luci-1,taiha/luci,db260179/openwrt-bpi-r1-luci,daofeng2015/luci,kuoruan/lede-luci,palmettos/test,dwmw2/luci,db260179/openwrt-bpi-r1-luci,nwf/openwrt-luci,Hostle/luci,Wedmer/luci,male-puppies/luci,openwrt/luci,dismantl/luci-0.12,thesabbir/luci,ff94315/luci-1,tobiaswaldvogel/luci,981213/luci-1,jorgifumi/luci,kuoruan/lede-luci,jlopenwrtluci/luci,david-xiao/luci,remakeelectric/luci,ff94315/luci-1,urueedi/luci,RedSnake64/openwrt-luci-packages,joaofvieira/luci,dismantl/luci-0.12,harveyhu2012/luci,oyido/luci,RedSnake64/openwrt-luci-packages,ollie27/openwrt_luci,palmettos/cnLuCI,jlopenwrtluci/luci,chris5560/openwrt-luci,male-puppies/luci,bittorf/luci,bittorf/luci,Sakura-Winkey/LuCI,jchuang1977/luci-1,oyido/luci,shangjiyu/luci-with-extra,ReclaimYourPrivacy/cloak-luci,fkooman/luci,nwf/openwrt-luci,NeoRaider/luci,Hostle/openwrt-luci-multi-user,aa65535/luci,RuiChen1113/luci,oneru/luci,chris5560/openwrt-luci,fkooman/luci,cshore-firmware/openwrt-luci,Noltari/luci,hnyman/luci,oneru/luci,dismantl/luci-0.12,dismantl/luci-0.12,opentechinstitute/luci,openwrt-es/openwrt-luci,thess/OpenWrt-luci,cshore-firmware/openwrt-luci,bright-things/ionic-luci,Hostle/luci,lcf258/openwrtcn,chris5560/openwrt-luci,tcatm/luci,jlopenwrtluci/luci,RuiChen1113/luci,openwrt/luci,RuiChen1113/luci,Wedmer/luci,LazyZhu/openwrt-luci-trunk-mod,wongsyrone/luci-1,sujeet14108/luci,opentechinstitute/luci,RedSnake64/openwrt-luci-packages,shangjiyu/luci-with-extra,wongsyrone/luci-1,palmettos/cnLuCI,schidler/ionic-luci,bittorf/luci,slayerrensky/luci,marcel-sch/luci,sujeet14108/luci,david-xiao/luci,dwmw2/luci,jchuang1977/luci-1,aircross/OpenWrt-Firefly-LuCI,deepak78/new-luci,kuoruan/lede-luci,db260179/openwrt-bpi-r1-luci,sujeet14108/luci,tcatm/luci,Hostle/luci,david-xiao/luci,thesabbir/luci,openwrt/luci,sujeet14108/luci,kuoruan/luci,forward619/luci,mumuqz/luci,Kyklas/luci-proto-hso,opentechinstitute/luci,openwrt-es/openwrt-luci,LuttyYang/luci,ReclaimYourPrivacy/cloak-luci,schidler/ionic-luci,Noltari/luci,deepak78/new-luci,oneru/luci,urueedi/luci,Hostle/openwrt-luci-multi-user,artynet/luci,wongsyrone/luci-1,lbthomsen/openwrt-luci,dismantl/luci-0.12,LazyZhu/openwrt-luci-trunk-mod,marcel-sch/luci,schidler/ionic-luci,mumuqz/luci,oyido/luci,joaofvieira/luci,ollie27/openwrt_luci,keyidadi/luci,forward619/luci,ff94315/luci-1,palmettos/cnLuCI,david-xiao/luci,deepak78/new-luci,palmettos/test,zhaoxx063/luci,deepak78/new-luci,zhaoxx063/luci,shangjiyu/luci-with-extra,bittorf/luci,jlopenwrtluci/luci,urueedi/luci,ReclaimYourPrivacy/cloak-luci,oneru/luci,wongsyrone/luci-1,MinFu/luci,lcf258/openwrtcn,nmav/luci,bittorf/luci,male-puppies/luci,remakeelectric/luci,aa65535/luci,nmav/luci,palmettos/test,lcf258/openwrtcn,teslamint/luci,remakeelectric/luci,cshore-firmware/openwrt-luci,sujeet14108/luci,ReclaimYourPrivacy/cloak-luci,jlopenwrtluci/luci,harveyhu2012/luci,LuttyYang/luci,bright-things/ionic-luci,Hostle/luci,oneru/luci,jorgifumi/luci,dismantl/luci-0.12,taiha/luci,nwf/openwrt-luci,Sakura-Winkey/LuCI,aa65535/luci,nwf/openwrt-luci,openwrt/luci,bright-things/ionic-luci,artynet/luci,aa65535/luci,cshore/luci,maxrio/luci981213,kuoruan/luci,fkooman/luci,obsy/luci,joaofvieira/luci,nwf/openwrt-luci,artynet/luci,florian-shellfire/luci,male-puppies/luci,rogerpueyo/luci,wongsyrone/luci-1,lcf258/openwrtcn,maxrio/luci981213,forward619/luci,schidler/ionic-luci,daofeng2015/luci,dwmw2/luci,Wedmer/luci,remakeelectric/luci,shangjiyu/luci-with-extra,zhaoxx063/luci,opentechinstitute/luci,Noltari/luci,zhaoxx063/luci,david-xiao/luci,thess/OpenWrt-luci,tcatm/luci,jorgifumi/luci,bright-things/ionic-luci,artynet/luci,nmav/luci,obsy/luci,Wedmer/luci,981213/luci-1,mumuqz/luci,Kyklas/luci-proto-hso,jlopenwrtluci/luci,openwrt/luci,oyido/luci,MinFu/luci,thess/OpenWrt-luci,maxrio/luci981213,keyidadi/luci,dwmw2/luci,db260179/openwrt-bpi-r1-luci,daofeng2015/luci,kuoruan/lede-luci,lcf258/openwrtcn,wongsyrone/luci-1,daofeng2015/luci,NeoRaider/luci,bittorf/luci,ff94315/luci-1,LuttyYang/luci,sujeet14108/luci,cshore-firmware/openwrt-luci,marcel-sch/luci,MinFu/luci,LazyZhu/openwrt-luci-trunk-mod,tobiaswaldvogel/luci,db260179/openwrt-bpi-r1-luci,aa65535/luci,ReclaimYourPrivacy/cloak-luci,oyido/luci,Hostle/openwrt-luci-multi-user,lbthomsen/openwrt-luci,hnyman/luci,Kyklas/luci-proto-hso,harveyhu2012/luci,teslamint/luci,openwrt-es/openwrt-luci,kuoruan/luci,jchuang1977/luci-1,bright-things/ionic-luci,daofeng2015/luci,kuoruan/lede-luci,hnyman/luci,tcatm/luci,slayerrensky/luci,fkooman/luci,Hostle/luci,zhaoxx063/luci,db260179/openwrt-bpi-r1-luci,zhaoxx063/luci,teslamint/luci,Sakura-Winkey/LuCI,oyido/luci,hnyman/luci,shangjiyu/luci-with-extra,nwf/openwrt-luci,db260179/openwrt-bpi-r1-luci,NeoRaider/luci,tcatm/luci,bittorf/luci,LazyZhu/openwrt-luci-trunk-mod,male-puppies/luci,sujeet14108/luci,981213/luci-1,openwrt-es/openwrt-luci,LuttyYang/luci,hnyman/luci,taiha/luci,palmettos/cnLuCI,openwrt-es/openwrt-luci,taiha/luci,artynet/luci,Noltari/luci,openwrt/luci,Kyklas/luci-proto-hso,RuiChen1113/luci,Hostle/luci,aircross/OpenWrt-Firefly-LuCI,cappiewu/luci,mumuqz/luci,rogerpueyo/luci,aircross/OpenWrt-Firefly-LuCI,ff94315/luci-1,aircross/OpenWrt-Firefly-LuCI,thesabbir/luci,harveyhu2012/luci,florian-shellfire/luci,lbthomsen/openwrt-luci,forward619/luci,artynet/luci,rogerpueyo/luci,chris5560/openwrt-luci,openwrt/luci,tobiaswaldvogel/luci,cshore/luci,ollie27/openwrt_luci,Hostle/luci,cshore-firmware/openwrt-luci,forward619/luci,Hostle/openwrt-luci-multi-user,Sakura-Winkey/LuCI
28abfa4d7a19a9a137d4fd97148cd5244b409a01
lua/entities/sent_deployableballoons.lua
lua/entities/sent_deployableballoons.lua
AddCSLuaFile() DEFINE_BASECLASS( "base_wire_entity" ) ENT.PrintName = "Wire Balloon Deployer" ENT.Author = "LuaPinapple" ENT.Contact = "[email protected]" ENT.Purpose = "It Deploys Balloons." ENT.Instructions = "Use wire." ENT.Category = "Wiremod" ENT.Spawnable = true ENT.AdminOnly = false ENT.WireDebugName = "Balloon Deployer" cleanup.Register("wire_deployers") if CLIENT then language.Add( "Cleanup_wire_deployers", "Balloon Deployers" ) language.Add( "Cleaned_wire_deployers", "Cleaned up Balloon Deployers" ) language.Add( "SBoxLimit_wire_deployers", "You have hit the Balloon Deployers limit!" ) return -- No more client end local material = "cable/rope" local BalloonTypes = { Model("models/MaxOfS2D/balloon_classic.mdl"), Model("models/balloons/balloon_classicheart.mdl"), Model("models/balloons/balloon_dog.mdl"), Model("models/balloons/balloon_star.mdl") } CreateConVar('sbox_maxwire_deployers', 2) local DmgFilter local function CreateDamageFilter() if DmgFilter then return end local DmgFilter = ents.Create("filter_activator_name") DmgFilter:SetKeyValue("targetname", "DmgFilter") DmgFilter:SetKeyValue("negated", "1") DmgFilter:Spawn() end hook.Add("Initialize", "CreateDamageFilter", CreateDamageFilter) local function MakeBalloonSpawner(pl, Data) if not pl:CheckLimit("wire_deployers") then return nil end local ent = ents.Create("sent_deployableballoons") if not ent:IsValid() then return end duplicator.DoGeneric(ent, Data) ent:SetPlayer(pl) ent:Spawn() ent:Activate() duplicator.DoGenericPhysics(ent, pl, Data) pl:AddCount("wire_deployers", ent) pl:AddCleanup("wire_deployers", ent) return ent end hook.Add("Initialize", "DamageFilter", DamageFilter) duplicator.RegisterEntityClass("sent_deployableballoons", MakeBalloonSpawner, "Data") scripted_ents.Alias("gmod_iballoon", "gmod_balloon") --Moves old "Lenght" input to new "Length" input for older dupes WireLib.AddInputAlias( "Lenght", "Length" ) function ENT:SpawnFunction( ply, tr ) if (not tr.Hit) then return end local SpawnPos = tr.HitPos+tr.HitNormal*16 local ent = MakeBalloonSpawner(ply, {Pos=SpawnPos}) return ent end function ENT:Initialize() self:SetModel("models/props_junk/PropaneCanister001a.mdl") self:PhysicsInit(SOLID_VPHYSICS) self:SetMoveType( MOVETYPE_VPHYSICS ) self:SetSolid(SOLID_VPHYSICS) self.Deployed = 0 self.Balloon = nil self.Constraints = {} self.force = 500 self.weld = false self.popable = true self.rl = 64 if WireAddon then self.Inputs = Wire_CreateInputs(self,{ "Force", "Length", "Weld?", "Popable?", "BalloonType", "Deploy" }) self.Outputs=WireLib.CreateSpecialOutputs(self, { "Deployed", "BalloonEntity" }, {"NORMAL","ENTITY" }) Wire_TriggerOutput(self,"Deployed", self.Deployed) --Wire_TriggerOutput(self,"Force", self.force) end local phys = self:GetPhysicsObject() if(phys:IsValid()) then phys:SetMass(250) phys:Wake() end self:UpdateOverlay() end function ENT:TriggerInput(key,value) if (key == "Deploy") then if value ~= 0 then if self.Deployed == 0 then self:DeployBalloons() self.Deployed = 1 end Wire_TriggerOutput(self, "Deployed", self.Deployed) else if self.Deployed ~= 0 then self:RetractBalloons() self.Deployed = 0 end Wire_TriggerOutput(self, "Deployed", self.Deployed) end elseif (key == "Force") then self.force = value if self.Deployed ~= 0 then self.Balloon:SetForce(value) end elseif (key == "Length") then self.rl = value elseif (key == "Weld?") then self.weld = value ~= 0 elseif (key == "Popable?") then self.popable = value ~= 0 self:UpdatePopable() elseif (key == "BalloonType") then self.balloonType=value+1 --To correct for 1 based indexing end self:UpdateOverlay() end local balloon_registry = {} hook.Add("EntityRemoved", "balloon_deployer", function(ent) local deployer = balloon_registry[ent] if IsValid(deployer) and deployer.TriggerInput then deployer.Deployed = 0 deployer:TriggerInput("Deploy", 0) end end) function ENT:UpdatePopable() local balloon = self.Balloon if balloon ~= nil and balloon:IsValid() then if not self.popable then balloon:Fire("setdamagefilter", "DmgFilter", 0); else balloon:Fire("setdamagefilter", "", 0); end end end function ENT:DeployBalloons() local balloon balloon = ents.Create("gmod_balloon") --normal balloon local model = BalloonTypes[self.balloonType] if(model==nil) then model = BalloonTypes[1] end balloon:SetModel(model) balloon:Spawn() balloon:SetColor(Color(math.random(0,255), math.random(0,255), math.random(0,255), 255)) balloon:SetForce(self.force) balloon:SetMaterial("models/balloon/balloon") balloon:SetPlayer(self:GetPlayer()) duplicator.DoGeneric(balloon,{Pos = self:GetPos() + (self:GetUp()*25)}) duplicator.DoGenericPhysics(balloon,pl,{Pos = Pos}) local balloonPos = balloon:GetPos() -- the origin the balloon is at the bottom local hitEntity = self local hitPos = self:LocalToWorld(Vector(0, 0, self:OBBMaxs().z)) -- the top of the spawner -- We trace from the balloon to us, and if there's anything in the way, we -- attach a constraint to that instead - that way, the balloon spawner can -- be hidden underneath a plate which magically gets balloons attached to it. local balloonToSpawner = (hitPos - balloonPos):GetNormalized() * 250 local trace = util.QuickTrace(balloon:GetPos(), balloonToSpawner, balloon) if constraint.CanConstrain(trace.Entity, trace.PhysicsBone) then local phys = trace.Entity:GetPhysicsObjectNum(trace.PhysicsBone) if IsValid(phys) then hitEntity = trace.Entity hitPos = trace.HitPos end end if self.weld then local constraint = constraint.Weld( balloon, hitEntity, 0, trace.PhysicsBone, 0) balloon:DeleteOnRemove(constraint) else balloonPos = balloon:WorldToLocal(balloonPos) hitPos = hitEntity:WorldToLocal(hitPos) local constraint, rope = constraint.Rope( balloon, hitEntity, 0, trace.PhysicsBone, balloonPos, hitPos, 0, self.rl, 0, 1.5, material, false) if constraint then balloon:DeleteOnRemove(constraint) balloon:DeleteOnRemove(rope) end end self:DeleteOnRemove(balloon) self.Balloon = balloon self:UpdatePopable() balloon_registry[balloon] = self Wire_TriggerOutput(self, "BalloonEntity", self.Balloon) end function ENT:OnRemove() if self.Balloon then balloon_registry[self.Balloon] = nil end Wire_Remove(self) end function ENT:RetractBalloons() if self.Balloon:IsValid() then local c = self.Balloon:GetColor() local effectdata = EffectData() effectdata:SetOrigin( self.Balloon:GetPos() ) effectdata:SetStart( Vector(c.r,c.g,c.b) ) util.Effect( "balloon_pop", effectdata ) self.Balloon:Remove() else self.Balloon = nil end end function ENT:UpdateOverlay() self:SetOverlayText( "Deployed = " .. ((self.Deployed ~= 0) and "yes" or "no") ) end
AddCSLuaFile() DEFINE_BASECLASS( "base_wire_entity" ) ENT.PrintName = "Wire Balloon Deployer" ENT.Author = "LuaPinapple" ENT.Contact = "[email protected]" ENT.Purpose = "It Deploys Balloons." ENT.Instructions = "Use wire." ENT.Category = "Wiremod" ENT.Spawnable = true ENT.AdminOnly = false ENT.WireDebugName = "Balloon Deployer" cleanup.Register("wire_deployers") if CLIENT then language.Add( "Cleanup_wire_deployers", "Balloon Deployers" ) language.Add( "Cleaned_wire_deployers", "Cleaned up Balloon Deployers" ) language.Add( "SBoxLimit_wire_deployers", "You have hit the Balloon Deployers limit!" ) return -- No more client end local material = "cable/rope" local BalloonTypes = { Model("models/MaxOfS2D/balloon_classic.mdl"), Model("models/balloons/balloon_classicheart.mdl"), Model("models/balloons/balloon_dog.mdl"), Model("models/balloons/balloon_star.mdl") } CreateConVar('sbox_maxwire_deployers', 2) local DmgFilter local function CreateDamageFilter() if DmgFilter then return end local DmgFilter = ents.Create("filter_activator_name") DmgFilter:SetKeyValue("targetname", "DmgFilter") DmgFilter:SetKeyValue("negated", "1") DmgFilter:Spawn() end hook.Add("Initialize", "CreateDamageFilter", CreateDamageFilter) local function MakeBalloonSpawner(pl, Data) if IsValid(pl) and not pl:CheckLimit("wire_deployers") then return nil end local ent = ents.Create("sent_deployableballoons") if not ent:IsValid() then return end duplicator.DoGeneric(ent, Data) ent:SetPlayer(pl) ent:Spawn() ent:Activate() duplicator.DoGenericPhysics(ent, pl, Data) if IsValid(pl) then pl:AddCount("wire_deployers", ent) pl:AddCleanup("wire_deployers", ent) end return ent end hook.Add("Initialize", "DamageFilter", DamageFilter) duplicator.RegisterEntityClass("sent_deployableballoons", MakeBalloonSpawner, "Data") scripted_ents.Alias("gmod_iballoon", "gmod_balloon") --Moves old "Lenght" input to new "Length" input for older dupes WireLib.AddInputAlias( "Lenght", "Length" ) function ENT:SpawnFunction( ply, tr ) if (not tr.Hit) then return end local SpawnPos = tr.HitPos+tr.HitNormal*16 local ent = MakeBalloonSpawner(ply, {Pos=SpawnPos}) return ent end function ENT:Initialize() self:SetModel("models/props_junk/PropaneCanister001a.mdl") self:PhysicsInit(SOLID_VPHYSICS) self:SetMoveType( MOVETYPE_VPHYSICS ) self:SetSolid(SOLID_VPHYSICS) self.Deployed = 0 self.Balloon = nil self.Constraints = {} self.force = 500 self.weld = false self.popable = true self.rl = 64 if WireAddon then self.Inputs = Wire_CreateInputs(self,{ "Force", "Length", "Weld?", "Popable?", "BalloonType", "Deploy" }) self.Outputs=WireLib.CreateSpecialOutputs(self, { "Deployed", "BalloonEntity" }, {"NORMAL","ENTITY" }) Wire_TriggerOutput(self,"Deployed", self.Deployed) --Wire_TriggerOutput(self,"Force", self.force) end local phys = self:GetPhysicsObject() if(phys:IsValid()) then phys:SetMass(250) phys:Wake() end self:UpdateOverlay() end function ENT:TriggerInput(key,value) if (key == "Deploy") then if value ~= 0 then if self.Deployed == 0 then self:DeployBalloons() self.Deployed = 1 end Wire_TriggerOutput(self, "Deployed", self.Deployed) else if self.Deployed ~= 0 then self:RetractBalloons() self.Deployed = 0 end Wire_TriggerOutput(self, "Deployed", self.Deployed) end elseif (key == "Force") then self.force = value if self.Deployed ~= 0 then self.Balloon:SetForce(value) end elseif (key == "Length") then self.rl = value elseif (key == "Weld?") then self.weld = value ~= 0 elseif (key == "Popable?") then self.popable = value ~= 0 self:UpdatePopable() elseif (key == "BalloonType") then self.balloonType=value+1 --To correct for 1 based indexing end self:UpdateOverlay() end local balloon_registry = {} hook.Add("EntityRemoved", "balloon_deployer", function(ent) local deployer = balloon_registry[ent] if IsValid(deployer) and deployer.TriggerInput then deployer.Deployed = 0 deployer:TriggerInput("Deploy", 0) end end) function ENT:UpdatePopable() local balloon = self.Balloon if balloon ~= nil and balloon:IsValid() then if not self.popable then balloon:Fire("setdamagefilter", "DmgFilter", 0); else balloon:Fire("setdamagefilter", "", 0); end end end function ENT:DeployBalloons() local balloon balloon = ents.Create("gmod_balloon") --normal balloon local model = BalloonTypes[self.balloonType] if(model==nil) then model = BalloonTypes[1] end balloon:SetModel(model) balloon:Spawn() balloon:SetColor(Color(math.random(0,255), math.random(0,255), math.random(0,255), 255)) balloon:SetForce(self.force) balloon:SetMaterial("models/balloon/balloon") balloon:SetPlayer(self:GetPlayer()) duplicator.DoGeneric(balloon,{Pos = self:GetPos() + (self:GetUp()*25)}) duplicator.DoGenericPhysics(balloon,pl,{Pos = Pos}) local balloonPos = balloon:GetPos() -- the origin the balloon is at the bottom local hitEntity = self local hitPos = self:LocalToWorld(Vector(0, 0, self:OBBMaxs().z)) -- the top of the spawner -- We trace from the balloon to us, and if there's anything in the way, we -- attach a constraint to that instead - that way, the balloon spawner can -- be hidden underneath a plate which magically gets balloons attached to it. local balloonToSpawner = (hitPos - balloonPos):GetNormalized() * 250 local trace = util.QuickTrace(balloon:GetPos(), balloonToSpawner, balloon) if constraint.CanConstrain(trace.Entity, trace.PhysicsBone) then local phys = trace.Entity:GetPhysicsObjectNum(trace.PhysicsBone) if IsValid(phys) then hitEntity = trace.Entity hitPos = trace.HitPos end end if self.weld then local constraint = constraint.Weld( balloon, hitEntity, 0, trace.PhysicsBone, 0) balloon:DeleteOnRemove(constraint) else balloonPos = balloon:WorldToLocal(balloonPos) hitPos = hitEntity:WorldToLocal(hitPos) local constraint, rope = constraint.Rope( balloon, hitEntity, 0, trace.PhysicsBone, balloonPos, hitPos, 0, self.rl, 0, 1.5, material, false) if constraint then balloon:DeleteOnRemove(constraint) balloon:DeleteOnRemove(rope) end end self:DeleteOnRemove(balloon) self.Balloon = balloon self:UpdatePopable() balloon_registry[balloon] = self Wire_TriggerOutput(self, "BalloonEntity", self.Balloon) end function ENT:OnRemove() if self.Balloon then balloon_registry[self.Balloon] = nil end Wire_Remove(self) end function ENT:RetractBalloons() if self.Balloon:IsValid() then local c = self.Balloon:GetColor() local effectdata = EffectData() effectdata:SetOrigin( self.Balloon:GetPos() ) effectdata:SetStart( Vector(c.r,c.g,c.b) ) util.Effect( "balloon_pop", effectdata ) self.Balloon:Remove() else self.Balloon = nil end end function ENT:UpdateOverlay() self:SetOverlayText( "Deployed = " .. ((self.Deployed ~= 0) and "yes" or "no") ) end
Fix Balloon Deployer not spawning when loaded from a savegame (#1146)
Fix Balloon Deployer not spawning when loaded from a savegame (#1146) Fixes #1144
Lua
apache-2.0
bigdogmat/wire,garrysmodlua/wire,sammyt291/wire,Grocel/wire,thegrb93/wire,wiremod/wire,dvdvideo1234/wire,NezzKryptic/Wire,CaptainPRICE/wire
66d3e8e48566dab17863c23ffa69ec20ff9ec8dd
modules/twitch.lua
modules/twitch.lua
-- Module to display, search and alert twitch.tv streams -- vim: set noexpandtab: local util = require'util' local simplehttp = util.simplehttp local json = util.json local moduleName = 'twitch' local key = moduleName local store = ivar2.persist local parseData = function(self, source, destination, data) data = json.decode(data) if data._total == 0 then return {} end local streams = {} for i=1, #data.streams do local this = data.streams[i] --TODO configure filter languages ? if this.channel.broadcaster_language and (this.channel.broadcaster_language == 'en' or this.channel.broadcaster_language == 'no') then table.insert(streams, this) end end -- sort streams wrt viewer count table.sort(streams, function(a,b) return a.viewers>b.viewers end) return streams end local formatData = function(self, source, destination, streams, limit) limit = limit or 5 local i = 0 local out = {} for _, stream in pairs(streams) do local viewers = tostring(math.floor(stream.viewers/1000)) .. 'k' if viewers == '0k' then viewers = stream.viewers end local title = '' if stream.channel and stream.channel.status then title = ': '..stream.channel.status end out[#out+1] = string.format( "[%s] http://twitch.tv/%s %s %s", util.bold(viewers), stream.channel.display_name, stream.game, title ) i=i+1 if i > limit then break end end return out end local gameHandler= function(self, source, destination, input, limit) limit = limit or 5 -- 'http://api.twitch.tv/kraken/streams?limit=20&offset=0&game='..util.urlEncode(input)..'&on_site=1', simplehttp( 'https://api.twitch.tv/kraken/search/streams?limit='..tostring(limit)..'&offset=0&query='..util.urlEncode(input), function(data) local streams = parseData(self, source, destination, data) if #streams == 0 then local out = 'No streams found' self:Msg('privmsg', destination, source, out) else local out = formatData(self, source, destination, streams, limit) for _,line in pairs(out) do self:Msg('privmsg', destination, source, line) end end end ) end local allHandler = function(self, source, destination) local url = 'https://api.twitch.tv/kraken/streams' simplehttp( url, function(data) local streams = parseData(self, source, destination, data) local out = formatData(self, source, destination, streams) for _,line in pairs(out) do self:Msg('privmsg', destination, source, line) end end ) end local checkStreams = function() for c,_ in pairs(ivar2.channels) do local gamesKey = key..':'..c local games = store[gamesKey] or {} local alertsKey = gamesKey .. ':alerts' local alerts = store[alertsKey] or {} for name, game in pairs(games) do local limit = 5 simplehttp( 'https://api.twitch.tv/kraken/search/streams?limit=' ..tostring(limit).. '&offset=0&query=' ..util.urlEncode(game.name), function(data) local streams = parseData(ivar2, nil, c, data, limit) for _, stream in pairs(streams) do -- Use Created At to check for uniqueness if alerts[stream.channel.name] ~= stream.created_at and -- Check if we meet viewer limit stream.viewers > game.limit then alerts[stream.channel.name] = stream.created_at store[alertsKey] = alerts ivar2:Msg('privmsg', game.channel, ivar2.nick, "[%s] [%s] %s %s", util.bold(game.name), util.bold(tostring(math.floor(stream.viewers/1000))..'k'), 'http://twitch.tv/'..stream.channel.display_name, stream.channel.status ) end end end ) end end end -- Start the stream alert poller ivar2:Timer('twitch', 300, 300, checkStreams) local regAlert = function(self, source, destination, limit, name) local gamesKey = key..':'..destination local games = store[gamesKey] or {} games[name] = {channel=destination, name=name, limit=tonumber(limit)} store[gamesKey] = games reply('Ok. Added twitch alert.') checkStreams() end local listAlert = function(self, source, destination) local gamesKey = key..':'..destination local games = store[gamesKey] or {} local out = {} for name, game in pairs(games) do out[#out+1] = name end if #out > 0 then say('Alerting following terms: %s', table.concat(out, ', ')) else say('No alerting here.') end end local delAlert = function(self, source, destination, name) local gamesKey = key..':'..destination local games = store[gamesKey] or {} games[name] = nil store[gamesKey] = games reply('Ok. Removed twitch alert.') end return { PRIVMSG = { ['^%ptwitch$'] = allHandler, ['^%ptwitch (.*)$'] = gameHandler, ['^%ptwitchalert (%d+) (.*)$'] = regAlert, ['^%ptwitchalert list$'] = listAlert, ['^%ptwitchalert del (.*)$'] = delAlert, }, }
-- Module to display, search and alert twitch.tv streams -- vim: set noexpandtab: local util = require'util' local simplehttp = util.simplehttp local json = util.json local moduleName = 'twitch' local key = moduleName local store = ivar2.persist local parseData = function(self, source, destination, data) data = json.decode(data) if data._total == 0 then return {} end local streams = {} for i=1, #data.streams do local this = data.streams[i] local lang = this.channel.broadcaster_language --TODO configure filter languages ? if lang and (lang == 'en' or lang == 'no') then table.insert(streams, this) end end -- sort streams wrt viewer count table.sort(streams, function(a,b) return a.viewers>b.viewers end) return streams end local formatData = function(self, source, destination, streams, limit) limit = limit or 5 local i = 0 local out = {} for _, stream in pairs(streams) do local viewers = tostring(math.floor(stream.viewers/1000)) .. 'k' if viewers == '0k' then viewers = stream.viewers end local title = '' if stream.channel and stream.channel.status then title = ': '..stream.channel.status end out[#out+1] = string.format( "[%s] http://twitch.tv/%s %s %s", util.bold(viewers), stream.channel.display_name, stream.game, title ) i=i+1 if i > limit then break end end return out end local gameHandler= function(self, source, destination, input, limit) limit = limit or 5 -- 'http://api.twitch.tv/kraken/streams?limit=20&offset=0&game='..util.urlEncode(input)..'&on_site=1', simplehttp( 'https://api.twitch.tv/kraken/search/streams?limit='..tostring(limit)..'&offset=0&query='..util.urlEncode(input), function(data) local streams = parseData(self, source, destination, data) if #streams == 0 then local out = 'No streams found' self:Msg('privmsg', destination, source, out) else local out = formatData(self, source, destination, streams, limit) for _,line in pairs(out) do self:Msg('privmsg', destination, source, line) end end end ) end local allHandler = function(self, source, destination) local url = 'https://api.twitch.tv/kraken/streams' simplehttp( url, function(data) local streams = parseData(self, source, destination, data) local out = formatData(self, source, destination, streams) for _,line in pairs(out) do self:Msg('privmsg', destination, source, line) end end ) end local checkStreams = function() for c,_ in pairs(ivar2.channels) do local gamesKey = key..':'..c local games = store[gamesKey] or {} local alertsKey = gamesKey .. ':alerts' local alerts = store[alertsKey] or {} for name, game in pairs(games) do local limit = 5 simplehttp( string.format( 'https://api.twitch.tv/kraken/search/streams?limit=%s&offset=0&query=%s', tostring(limit), util.urlEncode(game.name) ), function(data) local streams = parseData(ivar2, nil, c, data, limit) for _, stream in pairs(streams) do -- Use Created At to check for uniqueness if alerts[stream.channel.name] ~= stream.created_at and -- Check if we meet viewer limit stream.viewers > game.limit then alerts[stream.channel.name] = stream.created_at store[alertsKey] = alerts ivar2:Msg('privmsg', game.channel, ivar2.nick, "[%s] [%s] %s %s", util.bold(game.name), util.bold(tostring(math.floor(stream.viewers/1000))..'k'), 'http://twitch.tv/'..stream.channel.display_name, stream.channel.status ) end end end ) end end end -- Start the stream alert poller ivar2:Timer('twitch', 300, 300, checkStreams) local regAlert = function(self, source, destination, limit, name) local gamesKey = key..':'..destination local games = store[gamesKey] or {} games[name] = {channel=destination, name=name, limit=tonumber(limit)} store[gamesKey] = games reply('Ok. Added twitch alert.') checkStreams() end local listAlert = function(self, source, destination) local gamesKey = key..':'..destination local games = store[gamesKey] or {} local out = {} for name, game in pairs(games) do out[#out+1] = name end if #out > 0 then say('Alerting following terms: %s', table.concat(out, ', ')) else say('No alerting here.') end end local delAlert = function(self, source, destination, name) local gamesKey = key..':'..destination local games = store[gamesKey] or {} games[name] = nil store[gamesKey] = games reply('Ok. Removed twitch alert.') end return { PRIVMSG = { ['^%ptwitch$'] = allHandler, ['^%ptwitch (.*)$'] = gameHandler, ['^%ptwitchalert (%d+) (.*)$'] = regAlert, ['^%ptwitchalert list$'] = listAlert, ['^%ptwitchalert del (.*)$'] = delAlert, }, }
twitch: Fix mixed indent.
twitch: Fix mixed indent.
Lua
mit
haste/ivar2,torhve/ivar2,torhve/ivar2,torhve/ivar2
afc66a69bcfb4a13602bed1cd68d02833fe79397
quest/neiran_el_nyarale_205_runewick.lua
quest/neiran_el_nyarale_205_runewick.lua
-- INSERT INTO "quests" ("qst_id", "qst_script") VALUES (205, 'quest.neiran_el_nyarale_205_runewick'); require("base.common") module("quest.neiran_el_nyarale_205_runewick", package.seeall) GERMAN = Player.german ENGLISH = Player.english -- Insert the quest title here, in both languages Title = {} Title[GERMAN] = "Die Schatzkammer Runewicks" Title[ENGLISH] = "Runewick Treasury" -- Insert an extensive description of each status here, in both languages -- Make sure that the player knows exactly where to go and what to do Description = {} Description[GERMAN] = {} Description[ENGLISH] = {} Description[GERMAN][1] = "Spende Gegenstnde oder Mnzen fr die Schatzkammer Runewicks. Lege dafr den Gegenstand auf das markierte Feld neben Neiran. Kehre dann zu Neiran el Nyarale zurck." Description[ENGLISH][1] = "Donate items or coins for Runewicks treasury. Put the item on the bordered area next to Neiran. Than go back to Neiran el Nyarale." Description[GERMAN][2] = "Kehre zu Neiran el Nyarale zurck." Description[ENGLISH][2] = "Go back to Neiran el Nyarale." Description[GERMAN][3] = "Du hast schon einmal fr Runewick gespendet, dies sollte dich aber nicht davon abhalten, weiter Gegenstnde oder Mnzen fr deine Stadt zu spenden." Description[ENGLISH][3] = "You have already donated to Runewick. But nevertheless you can donate more items or coins for your town." -- For each status insert a list of positions where the quest will continue, i.e. a new status can be reached there QuestTarget = {} QuestTarget[1] = {position(897, 779, 2), position(897, 781, 2)} QuestTarget[2] = {position(897, 781, 2)} QuestTarget[3] = {position(897, 779, 2)} -- Insert the quest status which is reached at the end of the quest FINAL_QUEST_STATUS = 3 function QuestTitle(user) return base.common.GetNLS(user, Title[GERMAN], Title[ENGLISH]) end function QuestDescription(user, status) local german = Description[GERMAN][status] or "" local english = Description[ENGLISH][status] or "" return base.common.GetNLS(user, german, english) end function QuestTargets(user, status) return QuestTarget[status] end function QuestFinalStatus() return FINAL_QUEST_STATUS end
-- INSERT INTO "quests" ("qst_id", "qst_script") VALUES (205, 'quest.neiran_el_nyarale_205_runewick'); require("base.common") module("quest.neiran_el_nyarale_205_runewick", package.seeall) GERMAN = Player.german ENGLISH = Player.english -- Insert the quest title here, in both languages Title = {} Title[GERMAN] = "Die Schatzkammer Runewicks" Title[ENGLISH] = "Runewick Treasury" -- Insert an extensive description of each status here, in both languages -- Make sure that the player knows exactly where to go and what to do Description = {} Description[GERMAN] = {} Description[ENGLISH] = {} Description[GERMAN][1] = "Spende Gegenstnde oder Mnzen fr die Schatzkammer Runewicks. Lege dafr den Gegenstand auf das markierte Feld neben Neiran. Kehre dann zu Neiran el Nyarale zurck." Description[ENGLISH][1] = "Donate items or coins for Runewicks treasury. Put the item on the bordered area next to Neiran. Than go back to Neiran el Nyarale." Description[GERMAN][2] = "Du hast schon einmal fr Runewick gespendet, dies sollte dich aber nicht davon abhalten, weiter Gegenstnde oder Mnzen fr deine Stadt zu spenden." Description[ENGLISH][2] = "You have already donated to Runewick. But nevertheless you can donate more items or coins for your town." -- For each status insert a list of positions where the quest will continue, i.e. a new status can be reached there QuestTarget = {} QuestTarget[1] = {position(897, 779, 2), position(897, 781, 2)} QuestTarget[2] = {position(897, 781, 2)} -- Insert the quest status which is reached at the end of the quest FINAL_QUEST_STATUS = 2 function QuestTitle(user) return base.common.GetNLS(user, Title[GERMAN], Title[ENGLISH]) end function QuestDescription(user, status) local german = Description[GERMAN][status] or "" local english = Description[ENGLISH][status] or "" return base.common.GetNLS(user, german, english) end function QuestTargets(user, status) return QuestTarget[status] end function QuestFinalStatus() return FINAL_QUEST_STATUS end
Bugfix
Bugfix
Lua
agpl-3.0
vilarion/Illarion-Content,KayMD/Illarion-Content,Illarion-eV/Illarion-Content,LaFamiglia/Illarion-Content,Baylamon/Illarion-Content
b4c907319664cd918aec63c4fac07ad62e5b50ab
src/lib/fibers/timer.lua
src/lib/fibers/timer.lua
-- Use of this source code is governed by the Apache 2.0 license; see COPYING. -- Hierarchical timer wheel inspired by Juho Snellman's "Ratas". For a -- detailed discussion, see: -- -- https://www.snellman.net/blog/archive/2016-07-27-ratas-hierarchical-timer-wheel/ module(...,package.seeall) local lib = require("core.lib") local bit = require("bit") local band = bit.band local TimerWheel = {} local WHEEL_SLOTS = 256 local SLOT_INDEX_MASK = 255 local function push_node(node, head) node.prev, node.next, head.prev.next, head.prev = head.prev, head, node, node end local function pop_node(head) local node = head.next head.next, node.next.prev = node.next, head return node end local function allocate_timer_entry() return { time=false, prev=false, next=false, obj=false } end local timer_entry_freelist = {} local function new_timer_entry() local pos = #timer_entry_freelist if pos ~= 0 then local ent = timer_entry_freelist[pos] timer_entry_freelist[pos] = nil return ent end return allocate_timer_entry() end local function make_timer_entry(t, obj) local ent = new_timer_entry() ent.time, ent.obj = t, obj return ent end local function recycle_timer_entry(ent) ent.time, ent.next, ent.prev, ent.obj = false, false, false, false timer_entry_freelist[#timer_entry_freelist+1] = ent end local function new_slots() local ret = {} for slot=0,WHEEL_SLOTS-1 do local head = make_timer_entry(false, false) head.prev, head.next = head, head ret[slot] = head end return ret end function new_timer_wheel(now, period) now, period = now or engine.now(), period or 1e-3 return setmetatable( { now=now, period=period, rate=1/period, cur=0, slots=new_slots(), outer=false }, {__index=TimerWheel}) end local function add_wheel(inner) local base = inner.now + inner.period * (WHEEL_SLOTS - inner.cur) inner.outer = new_timer_wheel(base, inner.period * WHEEL_SLOTS) end function TimerWheel:add_delta(dt, obj) return self:add_absolute(self.now + dt, obj) end function TimerWheel:add_absolute(t, obj) local offset = math.max(math.floor((t - self.now) * self.rate), 0) if offset < WHEEL_SLOTS then local idx = band(self.cur + offset, SLOT_INDEX_MASK) local ent = make_timer_entry(t, obj) push_node(ent, self.slots[idx]) return ent else if not self.outer then add_wheel(self) end return self.outer:add_absolute(t, obj) end end local function slot_min_time(head) local min = 1/0 local ent = head.next while ent ~= head do min = math.min(ent.time, min) ent = ent.next end return min end function TimerWheel:next_entry_time() for offset=0,WHEEL_SLOTS-1 do local idx = band(self.cur + offset, SLOT_INDEX_MASK) local head = self.slots[idx] if head ~= head.next then local t = slot_min_time(head) if self.outer then -- Unless we just migrated entries from outer to inner wheel -- on the last tick, outer wheel overlaps with inner. local outer_idx = band(self.outer.cur + offset, SLOT_INDEX_MASK) t = math.min(t, slot_min_time(self.outer.slots[outer_idx])) end return t end end if self.outer then return self.outer:next_entry_time() end return 1/0 end local function tick_outer(inner, outer) if not outer then return end local head = outer.slots[outer.cur] while head.next ~= head do local ent = pop_node(head) local idx = math.floor((ent.time - outer.now) * inner.rate) -- Because of floating-point imprecision it's possible to get an -- index that is too large by 1. idx = math.min(idx, WHEEL_SLOTS-1) push_node(ent, inner.slots[idx]) end outer.cur = band(outer.cur + 1, SLOT_INDEX_MASK) -- Adjust inner clock; outer period is more precise than N additions -- of the inner period. inner.now, outer.now = outer.now, outer.now + outer.period if outer.cur == 0 then tick_outer(outer, outer.outer) end end local function tick(wheel, sched) local head = wheel.slots[wheel.cur] while head.next ~= head do local ent = pop_node(head) local obj = ent.obj recycle_timer_entry(ent) sched:schedule(obj) end wheel.cur = band(wheel.cur + 1, SLOT_INDEX_MASK) wheel.now = wheel.now + wheel.period if wheel.cur == 0 then tick_outer(wheel, wheel.outer) end end function TimerWheel:advance(t, sched) while t >= self.now + self.period do tick(self, sched) end end function selftest () print("selftest: lib.fibers.timer") local wheel = new_timer_wheel(10, 1e-3) -- At millisecond precision, advancing the wheel by an hour shouldn't -- take perceptible time. local hour = 60*60 wheel:advance(hour) local event_count = 1e5 local t = wheel.now for i=1,event_count do local dt = math.random() t = t + dt wheel:add_absolute(t, t) end local last = 0 local count = 0 local check = {} function check:schedule(t) local now = wheel.now -- The timer wheel only guarantees ordering between ticks, not -- ordering within a tick. It doesn't even guarantee insertion -- order within a tick. However for this test we know that -- insertion order is preserved. assert(last <= t) last, count = t, count + 1 -- Check that timers fire within a tenth a tick of when they -- should. Floating-point imprecisions can cause either slightly -- early or slightly late ticks. assert(wheel.now - wheel.period*0.1 < t) assert(t < wheel.now + wheel.period*1.1) end wheel:advance(t+1, check) assert(count == event_count) print("selftest: ok") end
-- Use of this source code is governed by the Apache 2.0 license; see COPYING. -- Hierarchical timer wheel inspired by Juho Snellman's "Ratas". For a -- detailed discussion, see: -- -- https://www.snellman.net/blog/archive/2016-07-27-ratas-hierarchical-timer-wheel/ module(...,package.seeall) local lib = require("core.lib") local bit = require("bit") local band = bit.band local TimerWheel = {} local WHEEL_SLOTS = 256 local SLOT_INDEX_MASK = 255 local function push_node(node, head) node.prev, node.next, head.prev.next, head.prev = head.prev, head, node, node end local function pop_node(head) local node = head.next head.next, node.next.prev = node.next, head return node end local function allocate_timer_entry() return { time=false, prev=false, next=false, obj=false } end local timer_entry_freelist = {} local function new_timer_entry() local pos = #timer_entry_freelist if pos ~= 0 then local ent = timer_entry_freelist[pos] timer_entry_freelist[pos] = nil return ent end return allocate_timer_entry() end local function make_timer_entry(t, obj) local ent = new_timer_entry() ent.time, ent.obj = t, obj return ent end local function recycle_timer_entry(ent) ent.time, ent.next, ent.prev, ent.obj = false, false, false, false timer_entry_freelist[#timer_entry_freelist+1] = ent end local function new_slots() local ret = {} for slot=0,WHEEL_SLOTS-1 do local head = make_timer_entry(false, false) head.prev, head.next = head, head ret[slot] = head end return ret end function new_timer_wheel(now, period) now, period = now or engine.now(), period or 1e-3 return setmetatable( { now=now, period=period, rate=1/period, cur=0, slots=new_slots(), outer=false }, {__index=TimerWheel}) end local function add_wheel(inner) local base = inner.now + inner.period * (WHEEL_SLOTS - inner.cur) inner.outer = new_timer_wheel(base, inner.period * WHEEL_SLOTS) end function TimerWheel:add_delta(dt, obj) return self:add_absolute(self.now + dt, obj) end function TimerWheel:add_absolute(t, obj) local offset = math.max(math.floor((t - self.now) * self.rate), 0) if offset < WHEEL_SLOTS then local idx = band(self.cur + offset, SLOT_INDEX_MASK) local ent = make_timer_entry(t, obj) push_node(ent, self.slots[idx]) return ent else if not self.outer then add_wheel(self) end return self.outer:add_absolute(t, obj) end end local function slot_min_time(head) local min = 1/0 local ent = head.next while ent ~= head do min = math.min(ent.time, min) ent = ent.next end return min end function TimerWheel:next_entry_time() for offset=0,WHEEL_SLOTS-1 do local idx = band(self.cur + offset, SLOT_INDEX_MASK) local head = self.slots[idx] if head ~= head.next then local t = slot_min_time(head) if self.outer then -- Unless we just migrated entries from outer to inner wheel -- on the last tick, outer wheel overlaps with inner. local outer_idx = band(self.outer.cur + offset, SLOT_INDEX_MASK) t = math.min(t, slot_min_time(self.outer.slots[outer_idx])) end return t end end if self.outer then return self.outer:next_entry_time() end return 1/0 end local function tick_outer(inner, outer) if not outer then return end local head = outer.slots[outer.cur] while head.next ~= head do local ent = pop_node(head) local idx = math.floor((ent.time - outer.now) * inner.rate) -- Because of floating-point imprecision it's possible to get an -- index that falls just outside [0,WHEEL_SLOTS-1]. idx = math.max(math.min(idx, WHEEL_SLOTS-1), 0) push_node(ent, inner.slots[idx]) end outer.cur = band(outer.cur + 1, SLOT_INDEX_MASK) -- Adjust inner clock; outer period is more precise than N additions -- of the inner period. inner.now, outer.now = outer.now, outer.now + outer.period if outer.cur == 0 then tick_outer(outer, outer.outer) end end local function tick(wheel, sched) local head = wheel.slots[wheel.cur] while head.next ~= head do local ent = pop_node(head) local obj = ent.obj recycle_timer_entry(ent) sched:schedule(obj) end wheel.cur = band(wheel.cur + 1, SLOT_INDEX_MASK) wheel.now = wheel.now + wheel.period if wheel.cur == 0 then tick_outer(wheel, wheel.outer) end end function TimerWheel:advance(t, sched) while t >= self.now + self.period do tick(self, sched) end end function selftest () print("selftest: lib.fibers.timer") local wheel = new_timer_wheel(10, 1e-3) -- At millisecond precision, advancing the wheel by an hour shouldn't -- take perceptible time. local hour = 60*60 wheel:advance(hour) local event_count = 1e5 local t = wheel.now for i=1,event_count do local dt = math.random() t = t + dt wheel:add_absolute(t, t) end local last = 0 local count = 0 local check = {} function check:schedule(t) local now = wheel.now -- The timer wheel only guarantees ordering between ticks, not -- ordering within a tick. It doesn't even guarantee insertion -- order within a tick. However for this test we know that -- insertion order is preserved. assert(last <= t) last, count = t, count + 1 -- Check that timers fire within a tenth a tick of when they -- should. Floating-point imprecisions can cause either slightly -- early or slightly late ticks. assert(wheel.now - wheel.period*0.1 < t) assert(t < wheel.now + wheel.period*1.1) end wheel:advance(t+1, check) assert(count == event_count) print("selftest: ok") end
Fix promotion of lib.fibers.timer events from outer to inner wheel
Fix promotion of lib.fibers.timer events from outer to inner wheel An timer wheel advances by a fixed time-step and contains a fixed number of slots. If, when adding an event, we find that the event is too far in the future, it gets added to an outer wheel, whose time step is the inner wheel's time step, multiplied by the number of slots in the inner wheel. When the timer runs and an inner wheel's timer wraps around to 0, one timestep's worth of events are moved from the outer wheel to the inner wheel. This process had a bug. Given that floating-point arithmetic is inexact, it's possible that an event from the outer wheel may have a timestamp that's either slightly before or slightly after the time range covered by the inner wheel. We already protected against the latter, but we were missing a check against the former. See e.g. https://gist.github.com/lwaftr-igalia/e9479e1d9ff04f008b86d040ed9c403e for a failure log containing this error: ``` (3) Lua upvalue 'tick_outer' at file 'lib/fibers/timer.lua:134' Local variables: inner = table: 0x41b90250 {slots:table: 0x40a2a678, period:0.001, rate:1000, cur:0, now:17883918.881778 (more...)} outer = table: 0x40826950 {slots:table: 0x40826ae0, period:0.256, rate:3.90625, cur:52, now:17883918.881778 (more...)} head = table: 0x41b8f7f0 {prev:table: 0x41b8f7f0, next:table: 0x41b8f7f0, time:false, obj:false} ent = table: 0x41448d68 {prev:table: 0x41b8f7f0, next:table: 0x41b8f7f0, time:17883918.881778, obj:table: 0x41448d08 (more...)} idx = number: -1 ``` Note that `idx` here is -1, indicating a value just before the time range for the inner wheel.
Lua
apache-2.0
eugeneia/snabb,alexandergall/snabbswitch,alexandergall/snabbswitch,SnabbCo/snabbswitch,Igalia/snabb,snabbco/snabb,eugeneia/snabb,Igalia/snabbswitch,Igalia/snabb,alexandergall/snabbswitch,snabbco/snabb,snabbco/snabb,Igalia/snabbswitch,Igalia/snabbswitch,alexandergall/snabbswitch,eugeneia/snabb,eugeneia/snabb,alexandergall/snabbswitch,Igalia/snabb,Igalia/snabbswitch,Igalia/snabbswitch,Igalia/snabb,Igalia/snabb,Igalia/snabb,Igalia/snabb,eugeneia/snabb,alexandergall/snabbswitch,SnabbCo/snabbswitch,eugeneia/snabb,alexandergall/snabbswitch,snabbco/snabb,snabbco/snabb,snabbco/snabb,snabbco/snabb,alexandergall/snabbswitch,Igalia/snabb,eugeneia/snabb,SnabbCo/snabbswitch,snabbco/snabb,SnabbCo/snabbswitch,eugeneia/snabb
89b63da84234de05d8491469c1bb0e01d8b5b571
spec/plugins/basicauth/access_spec.lua
spec/plugins/basicauth/access_spec.lua
local spec_helper = require "spec.spec_helpers" local http_client = require "kong.tools.http_client" local cjson = require "cjson" local STUB_GET_URL = spec_helper.STUB_GET_URL local STUB_POST_URL = spec_helper.STUB_POST_URL describe("Authentication Plugin", function() setup(function() spec_helper.prepare_db() spec_helper.insert_fixtures { api = { {name = "tests basicauth", public_dns = "basicauth.com", target_url = "http://mockbin.org"} }, consumer = { {username = "basicauth_tests_consuser"} }, plugin_configuration = { {name = "basicauth", value = {}, __api = 1} }, basicauth_credential = { {username = "username", password = "password", __consumer = 1} } } spec_helper.start_kong() end) teardown(function() spec_helper.stop_kong() end) describe("Basic Authentication", function() it("should return invalid credentials when the credential is missing", function() local response, status = http_client.get(STUB_GET_URL, {}, {host = "basicauth.com"}) local body = cjson.decode(response) assert.equal(401, status) assert.equal("Unauthorized", body.message) end) it("should return invalid credentials when the credential value is wrong", function() local response, status = http_client.get(STUB_GET_URL, {}, {host = "basicauth.com", authorization = "asd"}) local body = cjson.decode(response) assert.equal(403, status) assert.equal("Invalid authentication credentials", body.message) end) it("should return invalid credentials when the credential value is wrong in proxy-authorization", function() local response, status = http_client.get(STUB_GET_URL, {}, {host = "basicauth.com", ["proxy-authorization"] = "asd"}) local body = cjson.decode(response) assert.equal(403, status) assert.equal("Invalid authentication credentials", body.message) end) it("should not pass when passing only the password", function() local response, status = http_client.get(STUB_GET_URL, {}, {host = "basicauth.com", authorization = "Basic OmFwaWtleTEyMw=="}) local body = cjson.decode(response) assert.equal(403, status) assert.equal("Invalid authentication credentials", body.message) end) it("should not pass when passing only the username", function() local response, status = http_client.get(STUB_GET_URL, {}, {host = "basicauth.com", authorization = "Basic dXNlcjEyMzo="}) local body = cjson.decode(response) assert.equal(403, status) assert.equal("Invalid authentication credentials", body.message) end) it("should reply 401 when authorization is missing", function() local response, status = http_client.get(STUB_GET_URL, {}, {host = "basicauth.com", authorization123 = "Basic dXNlcm5hbWU6cGFzc3dvcmQ="}) local body = cjson.decode(response) assert.equal(401, status) assert.equal("Unauthorized", body.message) end) it("should pass with GET", function() print(STUB_GET_URL) local response, status = http_client.get(STUB_GET_URL, {}, {host = "basicauth.com", authorization = "Basic dXNlcm5hbWU6cGFzc3dvcmQ="}) assert.equal(200, status) local parsed_response = cjson.decode(response) assert.equal("Basic dXNlcm5hbWU6cGFzc3dvcmQ=", parsed_response.headers.authorization) end) it("should pass with GET and proxy-authorization", function() local response, status = http_client.get(STUB_GET_URL, {}, {host = "basicauth.com", ["proxy-authorization"] = "Basic dXNlcm5hbWU6cGFzc3dvcmQ="}) assert.equal(200, status) local parsed_response = cjson.decode(response) assert.equal("Basic dXNlcm5hbWU6cGFzc3dvcmQ=", parsed_response.headers["proxy-authorization"]) end) it("should pass with POST", function() local response, status = http_client.post(STUB_POST_URL, {}, {host = "basicauth.com", authorization = "Basic dXNlcm5hbWU6cGFzc3dvcmQ="}) assert.equal(200, status) local parsed_response = cjson.decode(response) assert.equal("Basic dXNlcm5hbWU6cGFzc3dvcmQ=", parsed_response.headers.authorization) end) it("should pass with GET and valid authorization and wrong proxy-authorization", function() local response, status = http_client.get(STUB_GET_URL, {}, {host = "basicauth.com", ["proxy-authorization"] = "hello", authorization = "Basic dXNlcm5hbWU6cGFzc3dvcmQ="}) assert.equal(200, status) local parsed_response = cjson.decode(response) assert.equal("Basic dXNlcm5hbWU6cGFzc3dvcmQ=", parsed_response.headers["proxy-authorization"]) end) it("should pass with GET and invalid authorization and valid proxy-authorization", function() local response, status = http_client.get(STUB_GET_URL, {}, {host = "basicauth.com", authorization = "hello", ["proxy-authorization"] = "Basic dXNlcm5hbWU6cGFzc3dvcmQ="}) assert.equal(200, status) local parsed_response = cjson.decode(response) assert.equal("Basic dXNlcm5hbWU6cGFzc3dvcmQ=", parsed_response.headers["proxy-authorization"]) end) end) end)
local spec_helper = require "spec.spec_helpers" local http_client = require "kong.tools.http_client" local cjson = require "cjson" local PROXY_URL = spec_helper.PROXY_URL describe("Authentication Plugin", function() setup(function() spec_helper.prepare_db() spec_helper.insert_fixtures { api = { {name = "tests basicauth", public_dns = "basicauth.com", target_url = "http://httpbin.org"} }, consumer = { {username = "basicauth_tests_consuser"} }, plugin_configuration = { {name = "basicauth", value = {}, __api = 1} }, basicauth_credential = { {username = "username", password = "password", __consumer = 1} } } spec_helper.start_kong() end) teardown(function() spec_helper.stop_kong() end) describe("Basic Authentication", function() it("should return invalid credentials when the credential is missing", function() local response, status = http_client.get(PROXY_URL.."/get", {}, {host = "basicauth.com"}) local body = cjson.decode(response) assert.equal(401, status) assert.equal("Unauthorized", body.message) end) it("should return invalid credentials when the credential value is wrong", function() local response, status = http_client.get(PROXY_URL.."/get", {}, {host = "basicauth.com", authorization = "asd"}) local body = cjson.decode(response) assert.equal(403, status) assert.equal("Invalid authentication credentials", body.message) end) it("should return invalid credentials when the credential value is wrong in proxy-authorization", function() local response, status = http_client.get(PROXY_URL.."/get", {}, {host = "basicauth.com", ["proxy-authorization"] = "asd"}) local body = cjson.decode(response) assert.equal(403, status) assert.equal("Invalid authentication credentials", body.message) end) it("should not pass when passing only the password", function() local response, status = http_client.get(PROXY_URL.."/get", {}, {host = "basicauth.com", authorization = "Basic OmFwaWtleTEyMw=="}) local body = cjson.decode(response) assert.equal(403, status) assert.equal("Invalid authentication credentials", body.message) end) it("should not pass when passing only the username", function() local response, status = http_client.get(PROXY_URL.."/get", {}, {host = "basicauth.com", authorization = "Basic dXNlcjEyMzo="}) local body = cjson.decode(response) assert.equal(403, status) assert.equal("Invalid authentication credentials", body.message) end) it("should reply 401 when authorization is missing", function() local response, status = http_client.get(PROXY_URL.."/get", {}, {host = "basicauth.com", authorization123 = "Basic dXNlcm5hbWU6cGFzc3dvcmQ="}) local body = cjson.decode(response) assert.equal(401, status) assert.equal("Unauthorized", body.message) end) it("should pass with GET", function() local response, status = http_client.get(PROXY_URL.."/get", {}, {host = "basicauth.com", authorization = "Basic dXNlcm5hbWU6cGFzc3dvcmQ="}) assert.equal(200, status) local parsed_response = cjson.decode(response) assert.equal("Basic dXNlcm5hbWU6cGFzc3dvcmQ=", parsed_response.headers.Authorization) end) it("should pass with GET and proxy-authorization", function() local response, status = http_client.get(PROXY_URL.."/get", {}, {host = "basicauth.com", ["proxy-authorization"] = "Basic dXNlcm5hbWU6cGFzc3dvcmQ="}) assert.equal(200, status) local parsed_response = cjson.decode(response) assert.equal("Basic dXNlcm5hbWU6cGFzc3dvcmQ=", parsed_response.headers["Proxy-Authorization"]) end) it("should pass with POST", function() local response, status = http_client.post(PROXY_URL.."/post", {}, {host = "basicauth.com", authorization = "Basic dXNlcm5hbWU6cGFzc3dvcmQ="}) assert.equal(200, status) local parsed_response = cjson.decode(response) assert.equal("Basic dXNlcm5hbWU6cGFzc3dvcmQ=", parsed_response.headers.Authorization) end) it("should pass with GET and valid authorization and wrong proxy-authorization", function() local response, status = http_client.get(PROXY_URL.."/get", {}, {host = "basicauth.com", ["proxy-authorization"] = "hello", authorization = "Basic dXNlcm5hbWU6cGFzc3dvcmQ="}) assert.equal(200, status) local parsed_response = cjson.decode(response) assert.equal("hello", parsed_response.headers["Proxy-Authorization"]) assert.equal("Basic dXNlcm5hbWU6cGFzc3dvcmQ=", parsed_response.headers.Authorization) end) it("should pass with GET and invalid authorization and valid proxy-authorization", function() local response, status = http_client.get(PROXY_URL.."/get", {}, {host = "basicauth.com", authorization = "hello", ["proxy-authorization"] = "Basic dXNlcm5hbWU6cGFzc3dvcmQ="}) assert.equal(200, status) local parsed_response = cjson.decode(response) assert.equal("Basic dXNlcm5hbWU6cGFzc3dvcmQ=", parsed_response.headers["Proxy-Authorization"]) end) end) end)
Fixing test
Fixing test Former-commit-id: ae5e6b73341a96979fa8a9c1b46efb2a984e61c3
Lua
apache-2.0
Vermeille/kong,beauli/kong,Mashape/kong,xvaara/kong,salazar/kong,streamdataio/kong,kyroskoh/kong,ejoncas/kong,shiprabehera/kong,ejoncas/kong,vzaramel/kong,smanolache/kong,streamdataio/kong,Kong/kong,Kong/kong,ajayk/kong,icyxp/kong,vzaramel/kong,Kong/kong,akh00/kong,rafael/kong,jebenexer/kong,ind9/kong,ccyphers/kong,kyroskoh/kong,li-wl/kong,isdom/kong,ind9/kong,jerizm/kong,rafael/kong,isdom/kong
eba0d0265729ab74ae4c7f6887c41e34be22368d
parser.lua
parser.lua
-- See LICENSE file for copyright and license details local Misc = require('misc') local M = Misc.newType() M.new = function() local self = {} setmetatable(self, M) return self end M.setLexer = function(self, lexer) assert(lexer) self._lexer = lexer end local parseTypeField = function(lexer) local fieldNode = {} fieldNode.name = lexer:lexem().value lexer:next() lexer:eat{tag = 'space'} fieldNode.type = lexer:lexem().value lexer:next() lexer:eat{tag = 'endOfLine'} return fieldNode end local parseTypeDeclaration = function(lexer) local typeDeclarationNode = {} typeDeclarationNode.tag = 'typeDeclaration' lexer:eat{tag = 'type'} lexer:eat{tag = 'space'} typeDeclarationNode.name = lexer:lexem().value lexer:next() lexer:eat{tag = 'space'} lexer:eat{tag = 'struct'} lexer:eat{tag = ':'} lexer:eat{tag = 'endOfLine'} lexer:eat{tag = 'incIndent'} typeDeclarationNode.fields = {} while lexer:lexem().tag ~= 'decIndent' do local fieldNode = parseTypeField(lexer) table.insert(typeDeclarationNode.fields, fieldNode) end return typeDeclarationNode end local parseFuncDeclaration = function(lexer) local funcDeclarationNode = {} funcDeclarationNode.tag = 'functionDeclaration' lexer:next() lexer:eat{tag = 'space'} assert(lexer:lexem().tag == 'name') funcDeclarationNode.name = lexer:lexem().value lexer:next() lexer:eat{tag = '('} -- parameters funcDeclarationNode.parameters = {} -- сейчас точно должен быть аргумент local argExpected = false while lexer:lexem().tag ~= ')' do -- print('{'..lexer:lexem().tag..'}') local argNode = {} if argExpected and lexer:lexem().type ~= 'name' then -- func x(arg1 Int,) ?? assert(false) end argNode.name = lexer:lexem().value lexer:next() lexer:eat{tag = 'space'} argNode.type = lexer:lexem().value lexer:next() table.insert(funcDeclarationNode.parameters, argNode) if lexer:lexem().tag == ',' then lexer:eat{tag = ','} lexer:eat{tag = 'space'} end end lexer:eat{tag = ')'} funcDeclarationNode.returnValue = {} -- return value if lexer:lexem().tag == 'space' then lexer:eat{tag = 'space'} local returnValueNode = {} returnValueNode.type = lexer:lexem().value table.insert(funcDeclarationNode.returnValue, returnValueNode) lexer:next() end lexer:eat{tag = ':'} lexer:eat{tag = 'endOfLine'} lexer:eat{tag = 'incIndent'} funcDeclarationNode.body = {} while lexer:lexem().tag ~= 'decIndent' do -- print('{'..lexer:lexem().tag..'}') if lexer:lexem().tag == 'var' then lexer:eat{tag = 'var'} lexer:eat{tag = 'space'} local varNode = {} varNode.tag = 'variableDeclaration' varNode.name = lexer:lexem().value lexer:next() lexer:eat{tag = 'space'} varNode.type = lexer:lexem().value lexer:next() lexer:eat{tag = 'endOfLine'} table.insert(funcDeclarationNode.body, varNode) end if lexer:lexem().tag == 'name' then local callNode = {} callNode.tag = 'functionCall' callNode.name = lexer:lexem().value lexer:next() lexer:eat{tag = '('} -- TODO: parameters callNode.parameters = {} local isArgRequired = false while lexer:lexem().tag ~= ')' do local argNode = {} if isArgRequired and lexer:lexem().tag ~= 'name' then assert(false) end argNode.name = lexer:lexem().value table.insert(callNode.parameters, argNode) lexer:next() if lexer:lexem().tag == ',' then lexer:eat{tag = ','} lexer:eat{tag = 'space'} isArgRequired = true end end lexer:eat{tag = ')'} lexer:eat{tag = 'endOfLine'} table.insert(funcDeclarationNode.body, callNode) end end return funcDeclarationNode end M.parse = function(self) local ast = {} local lexer = self._lexer -- print(Misc.dump(self._lexer)) -- assert(not lexer:noMoreLexemsLeft()) while not lexer:noMoreLexemsLeft() do if lexer:lexem().tag == 'type' then local typeDeclarationNode = parseTypeDeclaration(lexer) table.insert(ast, typeDeclarationNode) elseif lexer:lexem().tag == 'func' then local funcDeclarationNode = parseFuncDeclaration(lexer) table.insert(ast, funcDeclarationNode) end lexer:next() end return ast end return M
-- See LICENSE file for copyright and license details local Misc = require('misc') local M = Misc.newType() M.new = function() local self = {} setmetatable(self, M) return self end M.setLexer = function(self, lexer) assert(lexer) self._lexer = lexer end local parseTypeField = function(lexer) local fieldNode = {} fieldNode.name = lexer:lexem().value lexer:next() lexer:eat{tag = 'space'} fieldNode.type = lexer:lexem().value lexer:next() lexer:eat{tag = 'endOfLine'} return fieldNode end local parseTypeDeclaration = function(lexer) local typeDeclarationNode = {} typeDeclarationNode.tag = 'typeDeclaration' lexer:eat{tag = 'type'} lexer:eat{tag = 'space'} typeDeclarationNode.name = lexer:lexem().value lexer:next() lexer:eat{tag = 'space'} lexer:eat{tag = 'struct'} lexer:eat{tag = ':'} lexer:eat{tag = 'endOfLine'} lexer:eat{tag = 'incIndent'} typeDeclarationNode.fields = {} while lexer:lexem().tag ~= 'decIndent' do local fieldNode = parseTypeField(lexer) table.insert(typeDeclarationNode.fields, fieldNode) end return typeDeclarationNode end local parseFuncDeclaration = function(lexer) local funcDeclarationNode = {} funcDeclarationNode.tag = 'functionDeclaration' lexer:next() lexer:eat{tag = 'space'} assert(lexer:lexem().tag == 'name') funcDeclarationNode.name = lexer:lexem().value lexer:next() lexer:eat{tag = '('} -- parameters funcDeclarationNode.parameters = {} -- сейчас точно должен быть аргумент local argExpected = false while lexer:lexem().tag ~= ')' do -- print('{'..lexer:lexem().tag..'}') local argNode = {} if argExpected and lexer:lexem().type ~= 'name' then -- func x(arg1 Int,) ?? assert(false) end argNode.name = lexer:lexem().value lexer:next() lexer:eat{tag = 'space'} argNode.type = lexer:lexem().value lexer:next() table.insert(funcDeclarationNode.parameters, argNode) if lexer:lexem().tag == ',' then lexer:eat{tag = ','} lexer:eat{tag = 'space'} end end lexer:eat{tag = ')'} funcDeclarationNode.returnValue = {} -- return value if lexer:lexem().tag == 'space' then lexer:eat{tag = 'space'} local returnValueNode = {} returnValueNode.type = lexer:lexem().value table.insert(funcDeclarationNode.returnValue, returnValueNode) lexer:next() end lexer:eat{tag = ':'} lexer:eat{tag = 'endOfLine'} lexer:eat{tag = 'incIndent'} funcDeclarationNode.body = {} while lexer:lexem().tag ~= 'decIndent' do -- print('{'..lexer:lexem().tag..'}') if lexer:lexem().tag == 'var' then lexer:eat{tag = 'var'} lexer:eat{tag = 'space'} local varNode = {} varNode.tag = 'variableDeclaration' varNode.name = lexer:lexem().value lexer:next() lexer:eat{tag = 'space'} varNode.type = lexer:lexem().value lexer:next() lexer:eat{tag = 'endOfLine'} table.insert(funcDeclarationNode.body, varNode) end if lexer:lexem().tag == 'name' then local callNode = {} callNode.tag = 'functionCall' callNode.name = lexer:lexem().value lexer:next() lexer:eat{tag = '('} -- TODO: parameters callNode.parameters = {} local isArgRequired = false while lexer:lexem().tag ~= ')' do local argNode = {} if isArgRequired and lexer:lexem().tag ~= 'name' then assert(false) end argNode.name = lexer:lexem().value table.insert(callNode.parameters, argNode) lexer:next() if lexer:lexem().tag == ',' then lexer:eat{tag = ','} lexer:eat{tag = 'space'} isArgRequired = true end end lexer:eat{tag = ')'} lexer:eat{tag = 'endOfLine'} table.insert(funcDeclarationNode.body, callNode) end end return funcDeclarationNode end M.parse = function(self) local ast = {} local lexer = self._lexer -- print(Misc.dump(self._lexer)) -- assert(not lexer:noMoreLexemsLeft()) while not lexer:noMoreLexemsLeft() do if lexer:lexem().tag == 'type' then local typeDeclarationNode = parseTypeDeclaration(lexer) table.insert(ast, typeDeclarationNode) elseif lexer:lexem().tag == 'func' then local funcDeclarationNode = parseFuncDeclaration(lexer) table.insert(ast, funcDeclarationNode) end lexer:next() end return ast end return M
parser.lua: Fixed indentation
parser.lua: Fixed indentation
Lua
mit
ozkriff/misery-lua
c0ea749f7dd3d9ced7f9f1f207c0da55aba9a2a7
mock/asset/FSMScheme.lua
mock/asset/FSMScheme.lua
module 'mock' ---DEAD LOCK DEBUG HELPER local DEADLOCK_THRESHOLD = 100 local DEADLOCK_TRACK = true local DEADLOCK_TRACK_ENABLED = true -------------------------------------------------------------------- local function buildFSMScheme( scheme ) -- assert(targetClass,'Target Class required') assert( scheme, 'FSM Data required' ) --for deadlock detection local trackedStates = {} -- local stateFuncs = {} for name, stateBody in pairs( scheme ) do local id = stateBody.id --current state id local jump = stateBody.jump --transition trigger by msg local outStates = stateBody.next --transition trigger by state return value local localName = stateBody.localName local stepname = id .. '__step' local exitname = id .. '__exit' local entername = id .. '__enter' --generated function local function stateStep( self, dt, switchCount ) ----PRE STEP TRANSISTION local nextState local transMsg, transMsgArg ---STEP local step = self[ stepname ] local out = true --step return name of next state if step then out = step( self, dt ) end ----POST STEP TRANSISTION if out and outStates then --approach next state nextState = outStates[ out ] if not nextState then _error( '! error in state:'..name ) if type( out ) ~= 'string' then return error( 'output state name expected' ) end error( 'output state not found:'..tostring( out ) ) end else --find triggering msg (post phase) while true do transMsg, transMsgArg = self:pollMsg() if not transMsg then return end nextState = jump and jump[ transMsg ] if nextState then break end end end if DEADLOCK_TRACK_ENABLED then --DEADLOCK DETECTOR switchCount = switchCount + 1 if switchCount == DEADLOCK_THRESHOLD then trackedStates = {} elseif switchCount > DEADLOCK_THRESHOLD then table.insert( trackedStates, name ) if switchCount > DEADLOCK_THRESHOLD + DEADLOCK_TRACK then --state traceback print( "state switch deadlock:" ) for i, s in ipairs( trackedStates ) do print( i, s ) end game:debugStop() error('TERMINATED') --terminate end end end local nextStateBody local nextStateName --TRANSITION local tt = type( nextState ) if tt == 'string' then --direct transition nextStateName = nextState local exit = self[ exitname ] if exit then --exit previous state exit( self, nextStateName, transMsg, transMsgArg ) end else --group transitions local l = #nextState nextStateName = nextState[l] local exit = self[ exitname ] if exit then --exit previous state exit( self, nextStateName, transMsg, transMsgArg ) end --extra state group exit/enter for i = 1, l-1 do local funcName = nextState[ i ] local func = self[ funcName ] if func then func( self, name, nextStateName, transMsg, transMsgArg ) end end end self:setState( nextStateName ) nextStateBody = scheme[ nextStateName ] if not nextStateBody then error( 'state body not found:' .. nextStateName, 2 ) end local enter = self[ nextStateBody.entername ] if enter then --entering new state enter( self, name, transMsg, transMsgArg ) end --activate and enter new state handler local nextFunc = nextStateBody.func self.currentStateFunc = nextFunc return nextFunc( self, dt, switchCount ) end stateBody.func = stateStep stateBody.entername = entername stateBody.exitname = exitname end local startEnterName = scheme['start'].entername local startFunc = scheme['start'].func scheme[0] = function( self, dt ) local f = self[ startEnterName ] if f then f( self ) --fsm.start:enter end return startFunc( self, dt, 0 ) end end -------------------------------------------------------------------- function FSMSchemeLoader( node ) local path = node:getObjectFile('def') local scheme = dofile( path ) buildFSMScheme( scheme ) return scheme end registerAssetLoader ( 'fsm_scheme', FSMSchemeLoader )
module 'mock' ---DEAD LOCK DEBUG HELPER local DEADLOCK_THRESHOLD = 100 local DEADLOCK_TRACK = true local DEADLOCK_TRACK_ENABLED = true -------------------------------------------------------------------- local function buildFSMScheme( scheme ) -- assert(targetClass,'Target Class required') assert( scheme, 'FSM Data required' ) --for deadlock detection local trackedStates = {} -- local stateFuncs = {} for name, stateBody in pairs( scheme ) do local id = stateBody.id --current state id local jump = stateBody.jump --transition trigger by msg local outStates = stateBody.next --transition trigger by state return value local localName = stateBody.localName local stepname = id .. '__step' local exitname = id .. '__exit' local entername = id .. '__enter' --generated function local function stateStep( self, dt, switchCount ) ----PRE STEP TRANSISTION local nextState local transMsg, transMsgArg ---STEP local step = self[ stepname ] local out = true --step return name of next state if step then out = step( self, dt ) end ----POST STEP TRANSISTION if out and outStates then --approach next state nextState = outStates[ out ] if not nextState then _error( '! error in state:'..name ) if type( out ) ~= 'string' then return error( 'output state name expected' ) end error( 'output state not found:'..tostring( out ) ) end else --find triggering msg (post phase) while true do transMsg, transMsgArg = self:pollMsg() if not transMsg then return end nextState = jump and jump[ transMsg ] if nextState then break end end end if DEADLOCK_TRACK_ENABLED then --DEADLOCK DETECTOR switchCount = switchCount + 1 if switchCount == DEADLOCK_THRESHOLD then trackedStates = {} elseif switchCount > DEADLOCK_THRESHOLD then table.insert( trackedStates, name ) if switchCount > DEADLOCK_THRESHOLD + DEADLOCK_TRACK then --state traceback print( "state switch deadlock:" ) for i, s in ipairs( trackedStates ) do print( i, s ) end game:debugStop() error('TERMINATED') --terminate end end end local nextStateBody local nextStateName --TRANSITION local tt = type( nextState ) if tt == 'string' then --direct transition nextStateName = nextState local exit = self[ exitname ] if exit then --exit previous state exit( self, nextStateName, transMsg, transMsgArg ) end else --group transitions local l = #nextState nextStateName = nextState[l] local exit = self[ exitname ] if exit then --exit previous state exit( self, nextStateName, transMsg, transMsgArg ) end --extra state group exit/enter for i = 1, l-1 do local funcName = nextState[ i ] local func = self[ funcName ] if func then func( self, name, nextStateName, transMsg, transMsgArg ) end end end self:setState( nextStateName ) nextStateBody = scheme[ nextStateName ] if not nextStateBody then error( 'state body not found:' .. nextStateName, 2 ) end local enter = self[ nextStateBody.entername ] if enter then --entering new state enter( self, name, transMsg, transMsgArg ) end --activate and enter new state handler local nextFunc = nextStateBody.func self.currentStateFunc = nextFunc return nextFunc( self, dt, switchCount ) end stateBody.func = stateStep stateBody.entername = entername stateBody.exitname = exitname end local startEnterName = scheme['start'].entername local startFunc = scheme['start'].func scheme[0] = function( self, dt ) local f = self[ startEnterName ] if f then f( self ) --fsm.start:enter end self.currentStateFunc = startFunc return startFunc( self, dt, 0 ) end end -------------------------------------------------------------------- function FSMSchemeLoader( node ) local path = node:getObjectFile('def') local scheme = dofile( path ) buildFSMScheme( scheme ) return scheme end registerAssetLoader ( 'fsm_scheme', FSMSchemeLoader )
[mock]fix initial FSM state func
[mock]fix initial FSM state func
Lua
mit
tommo/mock
0fbd5e16cf352d8055274b1f01525c671f7e6293
otouto/plugins/media.lua
otouto/plugins/media.lua
local media = {} mimetype = (loadfile "./otouto/mimetype.lua")() media.triggers = { "(https?://[%w-_%.%?%.:,/%+=&%[%]]+%.(gif))$", "^(https?://[%w-_%.%?%.:,/%+=&%[%]]+%.(mp4))$", "(https?://[%w-_%.%?%.:,/%+=&%[%]]+%.(pdf))$", "(https?://[%w-_%.%?%.:,/%+=&%[%]]+%.(ogg))$", "(https?://[%w-_%.%?%.:,/%+=&%[%]]+%.(zip))$", "(https?://[%w-_%.%?%.:,/%+=&%[%]]+%.(tar.gz))$", "(https?://[%w-_%.%?%.:,/%+=&%[%]]+%.(7z))$", "(https?://[%w-_%.%?%.:,/%+=&%[%]]+%.(mp3))$", "(https?://[%w-_%.%?%.:,/%+=&%[%]]+%.(rar))$", "(https?://[%w-_%.%?%.:,/%+=&%[%]]+%.(wmv))$", "(https?://[%w-_%.%?%.:,/%+=&%[%]]+%.(doc))$", "^(https?://[%w-_%.%?%.:,/%+=&%[%]]+%.(avi))$", "(https?://[%w-_%.%?%.:,/%+=&%[%]]+%.(wav))$", "(https?://[%w-_%.%?%.:,/%+=&%[%]]+%.(apk))$", "(https?://[%w-_%.%?%.:,/%+=&%[%]]+%.(webm))$", "^(https?://[%w-_%.%?%.:,/%+=&%[%]]+%.(ogv))$", "(https?://[%w-_%.%?%.:,/%+=&%[%]]+%.(webp))$" } function media:action(msg, config, matches) local url = matches[1] local ext = matches[2] local mime_type = mimetype:get_content_type_no_sub(ext) local receiver = msg.chat.id if mime_type == 'audio' then chat_action = 'upload_audio' elseif mime_type == 'video' then chat_action = 'upload_video' else chat_action = 'upload_document' end local file, last_modified, nocache = get_cached_file(url, nil, msg.chat.id, chat_action, self) if not file then return end if ext == 'gif' then result = utilities.send_document(self, receiver, file, nil, msg.message_id) elseif ext == 'ogg' then result = utilities.send_voice(self, receiver, file, nil, msg.message_id) elseif mime_type == 'audio' then result = utilities.send_audio(self, receiver, file, nil, msg.message_id) elseif mime_type == 'video' then result = utilities.send_video(self, receiver, file, nil, msg.message_id) else result = utilities.send_document(self, receiver, file, nil, msg.message_id) end if nocache then return end if not result then return end -- Cache File-ID und Last-Modified-Header in Redis cache_file(result, url, last_modified) end return media
local media = {} media.triggers = { "(https?://[%w-_%.%?%.:,/%+=&%[%]]+%.(gif))$", "^(https?://[%w-_%.%?%.:,/%+=&%[%]]+%.(mp4))$", "(https?://[%w-_%.%?%.:,/%+=&%[%]]+%.(pdf))$", "(https?://[%w-_%.%?%.:,/%+=&%[%]]+%.(ogg))$", "(https?://[%w-_%.%?%.:,/%+=&%[%]]+%.(zip))$", "(https?://[%w-_%.%?%.:,/%+=&%[%]]+%.(tar.gz))$", "(https?://[%w-_%.%?%.:,/%+=&%[%]]+%.(7z))$", "(https?://[%w-_%.%?%.:,/%+=&%[%]]+%.(mp3))$", "(https?://[%w-_%.%?%.:,/%+=&%[%]]+%.(rar))$", "(https?://[%w-_%.%?%.:,/%+=&%[%]]+%.(wmv))$", "(https?://[%w-_%.%?%.:,/%+=&%[%]]+%.(doc))$", "^(https?://[%w-_%.%?%.:,/%+=&%[%]]+%.(avi))$", "(https?://[%w-_%.%?%.:,/%+=&%[%]]+%.(wav))$", "(https?://[%w-_%.%?%.:,/%+=&%[%]]+%.(apk))$", "(https?://[%w-_%.%?%.:,/%+=&%[%]]+%.(webm))$", "^(https?://[%w-_%.%?%.:,/%+=&%[%]]+%.(ogv))$", "(https?://[%w-_%.%?%.:,/%+=&%[%]]+%.(webp))$" } function media:action(msg, config, matches) local url = matches[1] local ext = matches[2] local mime_type = mimetype.get_content_type_no_sub(ext) local receiver = msg.chat.id if mime_type == 'audio' then chat_action = 'upload_audio' elseif mime_type == 'video' then chat_action = 'upload_video' else chat_action = 'upload_document' end local file, last_modified, nocache = get_cached_file(url, nil, msg.chat.id, chat_action, self) if not file then return end if ext == 'gif' then result = utilities.send_document(self, receiver, file, nil, msg.message_id) elseif ext == 'ogg' then result = utilities.send_voice(self, receiver, file, nil, msg.message_id) elseif mime_type == 'audio' then result = utilities.send_audio(self, receiver, file, nil, msg.message_id) elseif mime_type == 'video' then result = utilities.send_video(self, receiver, file, nil, msg.message_id) else result = utilities.send_document(self, receiver, file, nil, msg.message_id) end if nocache then return end if not result then return end -- Cache File-ID und Last-Modified-Header in Redis cache_file(result, url, last_modified) end return media
Media: Fix
Media: Fix
Lua
agpl-3.0
Brawl345/Brawlbot-v2
761d01362d6543d68ccf8bc8170714d6e8117fb9
webpaste.lua
webpaste.lua
args = {} settings = args[1] return doctype()( tag"head"( tag"title" "CPaste WebPaste", tag"script"[{src="//code.jquery.com/jquery-1.11.3.min.js"}](), tag"script"[{src="//code.jquery.com/jquery-migrate-1.2.1.min.js"}](), tag"script"([[ $(document).ready(function() { $('#submit').click(function() { var sentType = "plain"; var pasteTypes = document.getElementsByName("pasteType"); var i = 0; while (true) { if (pasteTypes[i].checked) { var val = pasteTypes[i].id; if (val == "radio1") sentType = "plain"; if (val == "radio2") sentType = "raw"; if (val == "radio3") sentType = "html"; break; } } $.ajax({ data: { c: $('textarea').val(), type: sentType }, type: "POST", url: $('#submit').attr('action'), success: function(response) { $('#resultholder').css({ display: "block" }); $('#result').html(response); $('#result').attr("href", response); console.log( response ) } }); return false }); }); ]]), tag"style"[{type="text/css"}]([[ html, body, form { overflow: hidden; margin: 0px; width: 100%; height: 100%; background-color: #010101; } button { padding: 5px; background-color: #111; border: 2px solid #dcdcdc; color: #dcdcdc; text-decoration: none; position: absolute; left: 3px; bottom: 3px; transition: 0.2s; -webkit-transition: 0.2s; -moz-transition: 0.2s; -o-transition: 0.2s; } button:hover { background-color: #010101; } div.pasteTypeHolder { padding: 5px; background-color: #010101; color: #dcdcdc; position: absolute; bottom: 3px; left: 60px; } textarea { background-color: #010101; border: 0px; color: #fff; width: 100%; top: 0px; bottom: 40px; resize: none; position: absolute; outline: 0; } div#resultholder { padding: 5px; background-color: #010101; border: 2px solid #dcdcdc; position: fixed; left: 50%; top: 50%; -webkit-transform: translate( -50%, -50% ); -moz-transform: translate( -50%, -50% ); -ms-transform: translate( -50%, -50% ); transform: translate( -50%, -50% ); display: none; transition: 0.2s; -webkit-transition: 0.2s; -moz-transition: 0.2s; -o-transition: 0.2s; } a#result { color: #dcdcdc; } ]]) ), tag"body"( tag"textarea"[{name="c", placeholder="Hello World!"}](), tag"button"[{id="submit",action=ret.url}]("Paste!"), tag"div"[{class="pasteTypeHolder"}]( tag"input"[{type="radio",class="pasteType",name="pasteType",id="radio1",checked=""}]("Normal"), tag"input"[{type="radio",class="pasteType",name="pasteType",id="radio2"}]("Raw"), tag"input"[{type="radio",class="pasteType",name="pasteType",id="radio3"}]("HTML") ), tag"div"[{id="resultholder"}]( tag"a"[{id="result"}] ) ) ):render()
args = {} settings = args[1] return doctype()( tag"head"( tag"title" "CPaste WebPaste", tag"script"[{src="//code.jquery.com/jquery-1.11.3.min.js"}](), tag"script"[{src="//code.jquery.com/jquery-migrate-1.2.1.min.js"}](), tag"script"([[ $(document).ready(function() { $('#submit').click(function() { var sentType = "plain"; var pasteTypes = document.getElementsByName("pasteType"); if (pasteTypes[0].checked) sentType = "plain"; if (pasteTypes[1].checked) sentType = "raw"; if (pasteTypes[2].checked) sentType = "html"; $.ajax({ data: { c: $('textarea').val(), type: sentType }, type: "POST", url: $('#submit').attr('action'), success: function(response) { $('#resultholder').css({ display: "block" }); $('#result').html(response); $('#result').attr("href", response); console.log( response ) } }); return false }); }); ]]), tag"style"[{type="text/css"}]([[ html, body, form { overflow: hidden; margin: 0px; width: 100%; height: 100%; background-color: #010101; } button { padding: 5px; background-color: #111; border: 2px solid #dcdcdc; color: #dcdcdc; text-decoration: none; position: absolute; left: 3px; bottom: 3px; transition: 0.2s; -webkit-transition: 0.2s; -moz-transition: 0.2s; -o-transition: 0.2s; } button:hover { background-color: #010101; } div.pasteTypeHolder { padding: 5px; background-color: #010101; color: #dcdcdc; position: absolute; bottom: 3px; left: 60px; } textarea { background-color: #010101; border: 0px; color: #fff; width: 100%; top: 0px; bottom: 40px; resize: none; position: absolute; outline: 0; } div#resultholder { padding: 5px; background-color: #010101; border: 2px solid #dcdcdc; position: fixed; left: 50%; top: 50%; -webkit-transform: translate( -50%, -50% ); -moz-transform: translate( -50%, -50% ); -ms-transform: translate( -50%, -50% ); transform: translate( -50%, -50% ); display: none; transition: 0.2s; -webkit-transition: 0.2s; -moz-transition: 0.2s; -o-transition: 0.2s; } a#result { color: #dcdcdc; } ]]) ), tag"body"( tag"textarea"[{name="c", placeholder="Hello World!"}](), tag"button"[{id="submit",action=ret.url}]("Paste!"), tag"div"[{class="pasteTypeHolder"}]( tag"input"[{type="radio",class="pasteType",name="pasteType",id="radio1",checked=""}]("Normal"), tag"input"[{type="radio",class="pasteType",name="pasteType",id="radio2"}]("Raw"), tag"input"[{type="radio",class="pasteType",name="pasteType",id="radio3"}]("HTML") ), tag"div"[{id="resultholder"}]( tag"a"[{id="result"}] ) ) ):render()
Fixed hang
Fixed hang
Lua
mit
vifino/cpaste,carbonsrv/cpaste
d478eaeabe176a3e4d332f1d0cc2bd31956c215c
frontend/ui/network/wpa_supplicant.lua
frontend/ui/network/wpa_supplicant.lua
local UIManager = require("ui/uimanager") local WpaClient = require('lj-wpaclient/wpaclient') local InfoMessage = require("ui/widget/infomessage") local sleep = require("ffi/util").sleep local T = require("ffi/util").template local _ = require("gettext") local CLIENT_INIT_ERR_MSG = _("Failed to initialize network control client: %1.") local WpaSupplicant = {} function WpaSupplicant:getNetworkList() local wcli, err = WpaClient.new(self.wpa_supplicant.ctrl_interface) if wcli == nil then return nil, T(CLIENT_INIT_ERR_MSG, err) end local list = wcli:scanThenGetResults() wcli:close() local saved_networks = self:getAllSavedNetworks() local curr_network = self:getCurrentNetwork() for _,network in ipairs(list) do network.signal_quality = network:getSignalQuality() local saved_nw = saved_networks:readSetting(network.ssid) if saved_nw then -- TODO: verify saved_nw.flags == network.flags? This will break if user changed the -- network setting from [WPA-PSK-TKIP+CCMP][WPS][ESS] to [WPA-PSK-TKIP+CCMP][ESS] network.password = saved_nw.password end -- TODO: also verify bssid if it is not set to any if curr_network and curr_network.ssid == network.ssid then network.connected = true network.wpa_supplicant_id = curr_network.id end end return list end function WpaSupplicant:authenticateNetwork(network) -- TODO: support passwordless network local err, wcli, nw_id wcli, err = WpaClient.new(self.wpa_supplicant.ctrl_interface) if not wcli then return false, T(CLIENT_INIT_ERR_MSG, err) end nw_id, err = wcli:addNetwork() if err then return false, err end wcli:setNetwork(nw_id, "ssid", network.ssid) wcli:setNetwork(nw_id, "psk", network.password) wcli:enableNetworkByID(nw_id) wcli:attach() local cnt = 0 local failure_cnt = 0 local max_retry = 30 local info = InfoMessage:new{text = _("Authenticating…")} local re, msg UIManager:show(info) UIManager:forceRePaint() while cnt < max_retry do local ev = wcli:readEvent() if ev ~= nil then if not ev:isScanEvent() then UIManager:close(info) info = InfoMessage:new{text = ev.msg} UIManager:show(info) UIManager:forceRePaint() end if ev:isAuthSuccessful() then network.wpa_supplicant_id = nw_id re = true break elseif ev:isAuthFailed() then failure_cnt = failure_cnt + 1 if failure_cnt > 3 then re, msg = false, _('Failed to authenticate') break end end else sleep(1) cnt = cnt + 1 end end if re ~= true then wcli:removeNetwork(nw_id) end wcli:close() UIManager:close(info) UIManager:forceRePaint() if cnt >= max_retry then re, msg = false, _('Timed out') end return re, msg end function WpaSupplicant:disconnectNetwork(network) if not network.wpa_supplicant_id then return end local wcli, err = WpaClient.new(self.wpa_supplicant.ctrl_interface) if wcli == nil then return nil, T(CLIENT_INIT_ERR_MSG, err) end wcli:removeNetwork(network.wpa_supplicant_id) wcli:close() end function WpaSupplicant:getCurrentNetwork() local wcli, err = WpaClient.new(self.wpa_supplicant.ctrl_interface) if wcli == nil then return nil, T(CLIENT_INIT_ERR_MSG, err) end local nw = wcli:getCurrentNetwork() wcli:close() return nw end function WpaSupplicant.init(network_mgr, options) network_mgr.wpa_supplicant = {ctrl_interface = options.ctrl_interface} network_mgr.getNetworkList = WpaSupplicant.getNetworkList network_mgr.getCurrentNetwork = WpaSupplicant.getCurrentNetwork network_mgr.authenticateNetwork = WpaSupplicant.authenticateNetwork network_mgr.disconnectNetwork = WpaSupplicant.disconnectNetwork end return WpaSupplicant
local UIManager = require("ui/uimanager") local WpaClient = require('lj-wpaclient/wpaclient') local InfoMessage = require("ui/widget/infomessage") local sleep = require("ffi/util").sleep local T = require("ffi/util").template local _ = require("gettext") local CLIENT_INIT_ERR_MSG = _("Failed to initialize network control client: %1.") local WpaSupplicant = {} function WpaSupplicant:getNetworkList() local wcli, err = WpaClient.new(self.wpa_supplicant.ctrl_interface) if wcli == nil then return nil, T(CLIENT_INIT_ERR_MSG, err) end local list = wcli:scanThenGetResults() wcli:close() local saved_networks = self:getAllSavedNetworks() local curr_network = self:getCurrentNetwork() for _,network in ipairs(list) do network.signal_quality = network:getSignalQuality() local saved_nw = saved_networks:readSetting(network.ssid) if saved_nw then -- TODO: verify saved_nw.flags == network.flags? This will break if user changed the -- network setting from [WPA-PSK-TKIP+CCMP][WPS][ESS] to [WPA-PSK-TKIP+CCMP][ESS] network.password = saved_nw.password end -- TODO: also verify bssid if it is not set to any if curr_network and curr_network.ssid == network.ssid then network.connected = true network.wpa_supplicant_id = curr_network.id end end return list end function WpaSupplicant:authenticateNetwork(network) -- TODO: support passwordless network local err, wcli, nw_id wcli, err = WpaClient.new(self.wpa_supplicant.ctrl_interface) if not wcli then return false, T(CLIENT_INIT_ERR_MSG, err) end nw_id, err = wcli:addNetwork() if err then return false, err end local re = wcli:setNetwork(nw_id, "ssid", network.ssid) if re == 'FAIL' then wcli:removeNetwork(nw_id) return false, _("Failed to set network SSID.") end re = wcli:setNetwork(nw_id, "psk", network.password) if re == 'FAIL' then wcli:removeNetwork(nw_id) return false, _("Failed to set network password.") end wcli:enableNetworkByID(nw_id) wcli:attach() local cnt = 0 local failure_cnt = 0 local max_retry = 30 local info = InfoMessage:new{text = _("Authenticating…")} local msg UIManager:show(info) UIManager:forceRePaint() while cnt < max_retry do local ev = wcli:readEvent() if ev ~= nil then if not ev:isScanEvent() then UIManager:close(info) info = InfoMessage:new{text = ev.msg} UIManager:show(info) UIManager:forceRePaint() end if ev:isAuthSuccessful() then network.wpa_supplicant_id = nw_id re = true break elseif ev:isAuthFailed() then failure_cnt = failure_cnt + 1 if failure_cnt > 3 then re, msg = false, _('Failed to authenticate') break end end else sleep(1) cnt = cnt + 1 end end if re ~= true then wcli:removeNetwork(nw_id) end wcli:close() UIManager:close(info) UIManager:forceRePaint() if cnt >= max_retry then re, msg = false, _('Timed out') end return re, msg end function WpaSupplicant:disconnectNetwork(network) if not network.wpa_supplicant_id then return end local wcli, err = WpaClient.new(self.wpa_supplicant.ctrl_interface) if wcli == nil then return nil, T(CLIENT_INIT_ERR_MSG, err) end wcli:removeNetwork(network.wpa_supplicant_id) wcli:close() end function WpaSupplicant:getCurrentNetwork() local wcli, err = WpaClient.new(self.wpa_supplicant.ctrl_interface) if wcli == nil then return nil, T(CLIENT_INIT_ERR_MSG, err) end local nw = wcli:getCurrentNetwork() wcli:close() return nw end function WpaSupplicant.init(network_mgr, options) network_mgr.wpa_supplicant = {ctrl_interface = options.ctrl_interface} network_mgr.getNetworkList = WpaSupplicant.getNetworkList network_mgr.getCurrentNetwork = WpaSupplicant.getCurrentNetwork network_mgr.authenticateNetwork = WpaSupplicant.authenticateNetwork network_mgr.disconnectNetwork = WpaSupplicant.disconnectNetwork end return WpaSupplicant
fix:(wpa_supplicant): show error from set_network operations
fix:(wpa_supplicant): show error from set_network operations
Lua
agpl-3.0
Markismus/koreader,poire-z/koreader,mwoz123/koreader,apletnev/koreader,koreader/koreader,mihailim/koreader,Frenzie/koreader,poire-z/koreader,robert00s/koreader,Hzj-jie/koreader,Frenzie/koreader,pazos/koreader,lgeek/koreader,NiLuJe/koreader,koreader/koreader,houqp/koreader,NiLuJe/koreader
9ac2b9c2ea4c1a68677182fd77103fcd0b5c6864
src/servicebag/src/Shared/ServiceBag.lua
src/servicebag/src/Shared/ServiceBag.lua
--[=[ Service bags handle recursive initialization of services, and the retrieval of services from a given source. This allows the composition of services without the initialization of those services becoming a pain, which makes refactoring downstream services very easy. This also allows multiple copies of a service to exist at once, although many services right now are not designed for this. ```lua local serviceBag = ServiceBag.new() serviceBag:GetService({ Init = function(self) print("Service initialized") end; }) serviceBag:Init() serviceBag:Start() ``` @class ServiceBag ]=] local require = require(script.Parent.loader).load(script) local Signal = require("Signal") local BaseObject = require("BaseObject") --[=[ @interface Service .Init: function? .Start: function? .Destroy: function? @within ServiceBag ]=] --[=[ @type ServiceType Service | ModuleScript @within ServiceBag ]=] local ServiceBag = setmetatable({}, BaseObject) ServiceBag.ClassName = "ServiceBag" ServiceBag.__index = ServiceBag --[=[ Constructs a new ServiceBag @param parentProvider ServiceBag? -- Optional parent provider to find services in @return ServiceBag ]=] function ServiceBag.new(parentProvider) local self = setmetatable(BaseObject.new(), ServiceBag) self._services = {} self._parentProvider = parentProvider self._serviceTypesToInitializeSet = {} self._initializedServiceTypeSet = {} self._initializing = false self._serviceTypesToStart = {} self._destroying = Signal.new() self._maid:GiveTask(self._destroying) return self end --[=[ Returns whether the value is a serviceBag @param value ServiceBag? @return boolean ]=] function ServiceBag.isServiceBag(value) return type(value) == "table" and value.ClassName == "ServiceBag" end --[=[ Retrieves the service, ensuring initialization if we are in the initialization phase. @param serviceType ServiceType @return any ]=] function ServiceBag:GetService(serviceType) if typeof(serviceType) == "Instance" then serviceType = require(serviceType) end assert(type(serviceType) == "table", "Bad serviceType definition") local service = self._services[serviceType] if service then self:_ensureInitialization(serviceType) return self._services[serviceType] else if self._parentProvider then return self._parentProvider:GetService(serviceType) end -- Try to add the service if we're still initializing services self:_addServiceType(serviceType) self:_ensureInitialization(serviceType) return self._services[serviceType] end end --[=[ Returns whether the service bag has the service. @param serviceType ServiceType @return boolean ]=] function ServiceBag:HasService(serviceType) if typeof(serviceType) == "Instance" then serviceType = require(serviceType) end if self._services[serviceType] then return true else return false end end --[=[ Initializes the service bag and ensures recursive initialization can occur ]=] function ServiceBag:Init() assert(not self._initializing, "Already initializing") assert(self._serviceTypesToInitializeSet, "Already initialized") self._initializing = true while next(self._serviceTypesToInitializeSet) do local serviceType = next(self._serviceTypesToInitializeSet) self._serviceTypesToInitializeSet[serviceType] = nil self:_ensureInitialization(serviceType) end self._serviceTypesToInitializeSet = nil self._initializing = false end --[=[ Starts the service bag and all services ]=] function ServiceBag:Start() assert(self._serviceTypesToStart, "Already started") assert(not self._initializing, "Still initializing") while next(self._serviceTypesToStart) do local serviceType = table.remove(self._serviceTypesToStart) local service = assert(self._services[serviceType], "No service") if service.Start then local current task.spawn(function() current = coroutine.running() service:Start() end) assert(coroutine.status(current) == "dead", "Starting service yielded") end end self._serviceTypesToStart = nil end --[=[ Returns whether the service bag has fully started or not. @return boolean ]=] function ServiceBag:IsStarted() return self._serviceTypesToStart == nil end --[=[ Creates a scoped service bag, where services within the scope will not be accessible outside of the scope. @return ServiceBag ]=] function ServiceBag:CreateScope() local provider = ServiceBag.new(self) self:_addServiceType(provider) -- Remove from parent provider self._maid[provider] = provider._destroying:Connect(function() self._maid[provider] = nil self._services[provider] = nil end) return provider end -- Adds a service to this provider only function ServiceBag:_addServiceType(serviceType) if not self._serviceTypesToInitializeSet then error(("Already finished initializing, cannot add %q"):format(tostring(serviceType))) return end -- Already added if self._services[serviceType] then return end -- Construct a new version of this service so we're isolated local service = setmetatable({}, { __index = serviceType }) self._services[serviceType] = service self:_ensureInitialization(serviceType) end function ServiceBag:_ensureInitialization(serviceType) if self._initializedServiceTypeSet[serviceType] then return end if self._initializing then self._serviceTypesToInitializeSet[serviceType] = nil self._initializedServiceTypeSet[serviceType] = true self:_initService(serviceType) elseif self._serviceTypesToInitializeSet then self._serviceTypesToInitializeSet[serviceType] = true else error("[ServiceBag._ensureInitialization] - Cannot initialize past initializing phase ") end end function ServiceBag:_initService(serviceType) local service = assert(self._services[serviceType], "No service") if service.Init then local current task.spawn(function() current = coroutine.running() service:Init(self) end) assert(coroutine.status(current) == "dead", "Initializing service yielded") end table.insert(self._serviceTypesToStart, serviceType) end --[=[ Cleans up the service bag and all services that have been initialized in the service bag. ]=] function ServiceBag:Destroy() local super = getmetatable(ServiceBag) self._destroying:Fire() local services = self._services local key, service = next(services) while service ~= nil do services[key] = nil if service.Destroy then service:Destroy() end key, service = next(services) end super.Destroy(self) end return ServiceBag
--[=[ Service bags handle recursive initialization of services, and the retrieval of services from a given source. This allows the composition of services without the initialization of those services becoming a pain, which makes refactoring downstream services very easy. This also allows multiple copies of a service to exist at once, although many services right now are not designed for this. ```lua local serviceBag = ServiceBag.new() serviceBag:GetService({ Init = function(self) print("Service initialized") end; }) serviceBag:Init() serviceBag:Start() ``` @class ServiceBag ]=] local require = require(script.Parent.loader).load(script) local Signal = require("Signal") local BaseObject = require("BaseObject") --[=[ @interface Service .Init: function? .Start: function? .Destroy: function? @within ServiceBag ]=] --[=[ @type ServiceType Service | ModuleScript @within ServiceBag ]=] local ServiceBag = setmetatable({}, BaseObject) ServiceBag.ClassName = "ServiceBag" ServiceBag.__index = ServiceBag --[=[ Constructs a new ServiceBag @param parentProvider ServiceBag? -- Optional parent provider to find services in @return ServiceBag ]=] function ServiceBag.new(parentProvider) local self = setmetatable(BaseObject.new(), ServiceBag) self._services = {} self._parentProvider = parentProvider self._serviceTypesToInitializeSet = {} self._initializedServiceTypeSet = {} self._initializing = false self._serviceTypesToStart = {} self._destroying = Signal.new() self._maid:GiveTask(self._destroying) return self end --[=[ Returns whether the value is a serviceBag @param value ServiceBag? @return boolean ]=] function ServiceBag.isServiceBag(value) return type(value) == "table" and value.ClassName == "ServiceBag" end --[=[ Retrieves the service, ensuring initialization if we are in the initialization phase. @param serviceType ServiceType @return any ]=] function ServiceBag:GetService(serviceType) if typeof(serviceType) == "Instance" then serviceType = require(serviceType) end assert(type(serviceType) == "table", "Bad serviceType definition") local service = self._services[serviceType] if service then self:_ensureInitialization(serviceType) return self._services[serviceType] else if self._parentProvider then return self._parentProvider:GetService(serviceType) end -- Try to add the service if we're still initializing services self:_addServiceType(serviceType) self:_ensureInitialization(serviceType) return self._services[serviceType] end end --[=[ Returns whether the service bag has the service. @param serviceType ServiceType @return boolean ]=] function ServiceBag:HasService(serviceType) if typeof(serviceType) == "Instance" then serviceType = require(serviceType) end if self._services[serviceType] then return true else return false end end --[=[ Initializes the service bag and ensures recursive initialization can occur ]=] function ServiceBag:Init() assert(not self._initializing, "Already initializing") assert(self._serviceTypesToInitializeSet, "Already initialized") self._initializing = true while next(self._serviceTypesToInitializeSet) do local serviceType = next(self._serviceTypesToInitializeSet) self._serviceTypesToInitializeSet[serviceType] = nil self:_ensureInitialization(serviceType) end self._serviceTypesToInitializeSet = nil self._initializing = false end --[=[ Starts the service bag and all services ]=] function ServiceBag:Start() assert(self._serviceTypesToStart, "Already started") assert(not self._initializing, "Still initializing") while next(self._serviceTypesToStart) do local serviceType = table.remove(self._serviceTypesToStart) local service = assert(self._services[serviceType], "No service") if service.Start then local current task.spawn(function() current = coroutine.running() service:Start() end) assert(coroutine.status(current) == "dead", "Starting service yielded") end end self._serviceTypesToStart = nil end --[=[ Returns whether the service bag has fully started or not. @return boolean ]=] function ServiceBag:IsStarted() return self._serviceTypesToStart == nil end --[=[ Creates a scoped service bag, where services within the scope will not be accessible outside of the scope. @return ServiceBag ]=] function ServiceBag:CreateScope() local provider = ServiceBag.new(self) self:_addServiceType(provider) -- Remove from parent provider self._maid[provider] = provider._destroying:Connect(function() self._maid[provider] = nil self._services[provider] = nil end) return provider end -- Adds a service to this provider only function ServiceBag:_addServiceType(serviceType) if not self._serviceTypesToInitializeSet then error(("Already finished initializing, cannot add %q"):format(tostring(serviceType))) return end -- Already added if self._services[serviceType] then return end -- Construct a new version of this service so we're isolated local service = setmetatable({}, { __index = serviceType }) self._services[serviceType] = service self:_ensureInitialization(serviceType) end function ServiceBag:_ensureInitialization(serviceType) if self._initializedServiceTypeSet[serviceType] then return end if self._initializing then self._serviceTypesToInitializeSet[serviceType] = nil self._initializedServiceTypeSet[serviceType] = true self:_initService(serviceType) elseif self._serviceTypesToInitializeSet then self._serviceTypesToInitializeSet[serviceType] = true else error("[ServiceBag._ensureInitialization] - Cannot initialize past initializing phase ") end end function ServiceBag:_initService(serviceType) local service = assert(self._services[serviceType], "No service") if service.Init then local current task.spawn(function() current = coroutine.running() service:Init(self) end) assert(coroutine.status(current) == "dead", "Initializing service yielded") end table.insert(self._serviceTypesToStart, serviceType) end --[=[ Cleans up the service bag and all services that have been initialized in the service bag. ]=] function ServiceBag:Destroy() local super = getmetatable(ServiceBag) self._destroying:Fire() local services = self._services local key, service = next(services) while service ~= nil do services[key] = nil if not self._serviceTypesToInitializeSet[key] then task.spawn(function() if service.Destroy then service:Destroy() end end) end key, service = next(services) end super.Destroy(self) end return ServiceBag
fix: Ensure deconstructing service does not affect other services
fix: Ensure deconstructing service does not affect other services
Lua
mit
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
b7dbe77b934b4e4501a86849ed97bed5721c8104
lib/app.lua
lib/app.lua
-- -- Application -- local Utils = require('utils') local Path = require('path') local Table = require('table') local Emitter = require('core').Emitter local HTTP = require('http') local Stack = require('stack') local Log = require('./log') -- -- augment standard things -- require('./request') require('./response') -- require('./render') -- Application is EventEmitter local Application = Emitter:extend() -- -- create new application -- function Application:initialize(options) self.options = { } -- middleware stack layers self.stack = { } -- custom routes self.routes = { } -- set initial options self:set(options) return self end -- -- set application options -- function Application:set(option, value) -- option can be table if type(option) == 'table' then -- set a bunch of options for k, v in pairs(options or { }) do self:set(k, v) end return self end -- report the change and validate option if self.options[option] ~= value then -- FIXME: do handlers return values? if self:emit('change', option, value, self.options[option]) == false then error('Cannot set option "' .. option .. '"') end self.options[option] = value Log.debug('SET OPTION', option, value) end return self end -- -- add middleware layer -- function Application:use(handler, ...) local layer if type(handler) == 'string' then local plugin = require(Path.join(__dirname, 'stack', handler)) layer = plugin(...) else layer = handler end Table.insert(self.stack, layer) return self end -- -- mount a handler onto an exact path -- function Application:mount(path, handler, ...) local layer if type(handler) == 'string' then local plugin = require(Path.join(__dirname, 'stack', handler)) layer = plugin(...) else layer = handler end local plen = #path Table.insert(self.stack, function (req, res, nxt) if req.uri.pathname:sub(1, plen) == path then -- FIXME: this eats pathname forever -- if in layer we call nxt(), that handler receives cut pathname req.uri.pathname = req.uri.pathname:sub(plen + 1) layer(req, res, nxt) else nxt() end end) return self end -- -- router helpers -- function Application:GET(url_regexp, handler) return self:route('GET ' .. url_regexp, handler) end function Application:POST(url_regexp, handler) return self:route('POST ' .. url_regexp, handler) end function Application:PUT(url_regexp, handler) return self:route('PUT ' .. url_regexp, handler) end function Application:DELETE(url_regexp, handler) return self:route('DELETE ' .. url_regexp, handler) end -- -- mount a route handler onto a path and verb -- function Application:route(rule, handler, ...) Table.insert(self.routes, { rule, handler }) return self end -- -- start HTTP server at `host`:`port` -- function Application:run(port, host) if not port then port = 80 end if not host then host = '127.0.0.1' end -- local parse_url = require('url').parse local parse_query = require('querystring').parse -- copy stack local stack = { } for _, layer in ipairs(self.stack) do Table.insert(stack, layer) end -- append standard router Table.insert(stack, function (req, res, nxt) local str = req.method .. ' ' .. req.uri.pathname for _, pair in ipairs(self.routes) do local params = { str:match(pair[1]) } if params[1] then pair[2](res, nxt, unpack(params)) return end end nxt() end) -- compose request handler local handler = Stack.stack(unpack(stack)) -- start HTTP server self.server = HTTP.createServer(function (req, res) -- bootstrap response res.req = req res.app = self -- preparse request req.uri = parse_url(req.url, true) req.uri.query = parse_query(req.uri.query) --Log.debug('REQ', req) handler(req, res) end):listen(port, host) Log.info('Server listening at http://%s:%d/. Press CTRL+C to stop...', host, port) return self end -- module return Application
-- -- Application -- local Utils = require('utils') local Path = require('path') local Table = require('table') local Emitter = require('core').Emitter local HTTP = require('http') local Stack = require('stack') local Log = require('./log') -- -- augment standard things -- require('./request') require('./response') -- require('./render') -- Application is EventEmitter local Application = Emitter:extend() -- -- create new application -- function Application:initialize(options) self.options = { } -- middleware stack layers self.stack = { } -- custom routes self.routes = { } -- set initial options self:set(options) return self end -- -- set application options -- function Application:set(option, value) -- option can be table if type(option) == 'table' then -- set a bunch of options for k, v in pairs(options or { }) do self:set(k, v) end return self end -- report the change and validate option if self.options[option] ~= value then -- FIXME: do handlers return values? if self:emit('change', option, value, self.options[option]) == false then error('Cannot set option "' .. option .. '"') end self.options[option] = value Log.debug('SET OPTION', option, value) end return self end -- -- add middleware layer -- function Application:use(handler, ...) local layer if type(handler) == 'string' then local plugin = require(Path.join(__dirname, 'stack', handler)) layer = plugin(...) else layer = handler end Table.insert(self.stack, layer) return self end -- -- mount a handler onto an exact path -- function Application:mount(path, handler, ...) local layer if type(handler) == 'string' then local plugin = require(Path.join(__dirname, 'stack', handler)) layer = plugin(...) else layer = handler end local plen = #path Table.insert(self.stack, function (req, res, nxt) if req.uri.pathname:sub(1, plen) == path then local old_pathname = req.uri.pathname req.uri.pathname = req.uri.pathname:sub(plen + 1) layer(req, res, function() req.uri.pathname = old_pathname nxt() end) else nxt() end end) return self end -- -- router helpers -- function Application:GET(url_regexp, handler) return self:route('GET ' .. url_regexp, handler) end function Application:POST(url_regexp, handler) return self:route('POST ' .. url_regexp, handler) end function Application:PUT(url_regexp, handler) return self:route('PUT ' .. url_regexp, handler) end function Application:DELETE(url_regexp, handler) return self:route('DELETE ' .. url_regexp, handler) end -- -- mount a route handler onto a path and verb -- function Application:route(rule, handler, ...) Table.insert(self.routes, { rule, handler }) return self end -- -- start HTTP server at `host`:`port` -- function Application:run(port, host) if not port then port = 80 end if not host then host = '127.0.0.1' end -- local parse_url = require('url').parse local parse_query = require('querystring').parse -- copy stack local stack = { } for _, layer in ipairs(self.stack) do Table.insert(stack, layer) end -- append standard router Table.insert(stack, function (req, res, nxt) local str = req.method .. ' ' .. req.uri.pathname for _, pair in ipairs(self.routes) do local params = { str:match(pair[1]) } if params[1] then pair[2](res, nxt, unpack(params)) return end end nxt() end) -- compose request handler local handler = Stack.stack(unpack(stack)) -- start HTTP server self.server = HTTP.createServer(function (req, res) -- bootstrap response res.req = req res.app = self -- preparse request req.uri = parse_url(req.url, true) req.uri.query = parse_query(req.uri.query) --Log.debug('REQ', req) handler(req, res) end):listen(port, host) Log.info('Server listening at http://%s:%d/. Press CTRL+C to stop...', host, port) return self end -- module return Application
fix path of handler callback
fix path of handler callback
Lua
mit
dvv/luvit-app
8a00b3f2e5e04e97d45fafa7e4fdba19f3f85896
share/lua/modules/simplexml.lua
share/lua/modules/simplexml.lua
--[==========================================================================[ simplexml.lua: Lua simple xml parser wrapper --[==========================================================================[ Copyright (C) 2010 Antoine Cellerier $Id$ Authors: Antoine Cellerier <dionoea at videolan dot org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. --]==========================================================================] module("simplexml",package.seeall) --[[ Returns the xml tree structure -- Each node is of one of the following types: -- { name (string), attributes (key->value map), children (node array) } -- text content (string) --]] local function parsexml(stream) local xml = vlc.xml() local reader = xml:create_reader(stream) local tree local parents = {} while reader:read() > 0 do local nodetype = reader:node_type() --print(nodetype, reader:name()) if nodetype == 'startelem' then local name = reader:name() local node = { name= '', attributes= {}, children= {} } node.name = name while reader:next_attr() == 0 do node.attributes[reader:name()] = reader:value() end if tree then table.insert(tree.children, node) table.insert(parents, tree) end tree = node elseif nodetype == 'endelem' then if #parents > 0 then tree = parents[#parents] table.remove(parents) end elseif nodetype == 'text' then table.insert(tree.children, reader:value()) end end if #parents > 0 then error("XML parser error/Missing closing tags") end return tree end function parse_url(url) return parsexml(vlc.stream(url)) end function parse_string(str) return parsexml(vlc.memory_stream(str)) end
--[==========================================================================[ simplexml.lua: Lua simple xml parser wrapper --[==========================================================================[ Copyright (C) 2010 Antoine Cellerier $Id$ Authors: Antoine Cellerier <dionoea at videolan dot org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. --]==========================================================================] module("simplexml",package.seeall) --[[ Returns the xml tree structure -- Each node is of one of the following types: -- { name (string), attributes (key->value map), children (node array) } -- text content (string) --]] local function parsexml(stream) local xml = vlc.xml() local reader = xml:create_reader(stream) local tree local parents = {} while reader:read() > 0 do local nodetype = reader:node_type() --print(nodetype, reader:name()) if nodetype == 'startelem' then local name = reader:name() local node = { name= '', attributes= {}, children= {} } node.name = name while reader:next_attr() == 0 do node.attributes[reader:name()] = reader:value() end if tree then table.insert(tree.children, node) table.insert(parents, tree) end tree = node elseif nodetype == 'endelem' then if #parents > 0 then local name = reader:name() local tmp = {} --print(name, tree.name, #parents) while name ~= tree.name do if #parents == 0 then error("XML parser error/faulty logic") end local child = tree tree = parents[#parents] table.remove(parents) table.remove(tree.children) table.insert(tmp, 1, child) for i, node in pairs(child.children) do table.insert(tmp, i+1, node) end child.children = {} end for _, node in pairs(tmp) do table.insert(tree.children, node) end tree = parents[#parents] table.remove(parents) end elseif nodetype == 'text' then table.insert(tree.children, reader:value()) end end if #parents > 0 then error("XML parser error/Missing closing tags") end return tree end function parse_url(url) return parsexml(vlc.stream(url)) end function parse_string(str) return parsexml(vlc.memory_stream(str)) end
This should fix <tag/> cases.
This should fix <tag/> cases.
Lua
lgpl-2.1
xkfz007/vlc,vlc-mirror/vlc,vlc-mirror/vlc-2.1,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.2,xkfz007/vlc,xkfz007/vlc,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.1,krichter722/vlc,jomanmuk/vlc-2.2,shyamalschandra/vlc,jomanmuk/vlc-2.1,shyamalschandra/vlc,jomanmuk/vlc-2.1,vlc-mirror/vlc-2.1,vlc-mirror/vlc,jomanmuk/vlc-2.2,xkfz007/vlc,krichter722/vlc,vlc-mirror/vlc,krichter722/vlc,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.1,shyamalschandra/vlc,vlc-mirror/vlc,jomanmuk/vlc-2.1,shyamalschandra/vlc,krichter722/vlc,jomanmuk/vlc-2.1,jomanmuk/vlc-2.2,jomanmuk/vlc-2.2,krichter722/vlc,vlc-mirror/vlc,xkfz007/vlc,shyamalschandra/vlc,vlc-mirror/vlc-2.1,xkfz007/vlc,shyamalschandra/vlc,vlc-mirror/vlc-2.1,xkfz007/vlc,krichter722/vlc,krichter722/vlc,vlc-mirror/vlc,jomanmuk/vlc-2.2,jomanmuk/vlc-2.1,vlc-mirror/vlc,shyamalschandra/vlc,jomanmuk/vlc-2.2
0f7ff6781a818f60d28872b50c5cac26e3b72995
AceGUI-3.0/widgets/AceGUIWidget-Label.lua
AceGUI-3.0/widgets/AceGUIWidget-Label.lua
--[[----------------------------------------------------------------------------- Label Widget Displays text and optionally an icon. -------------------------------------------------------------------------------]] local Type, Version = "Label", 20 local AceGUI = LibStub and LibStub("AceGUI-3.0", true) if not AceGUI or (AceGUI:GetWidgetVersion(Type) or 0) >= Version then return end -- Lua APIs local max, select = math.max, select -- WoW APIs local CreateFrame, UIParent = CreateFrame, UIParent -- Global vars/functions that we don't upvalue since they might get hooked, or upgraded -- List them here for Mikk's FindGlobals script -- GLOBALS: GameFontHighlightSmall --[[----------------------------------------------------------------------------- Support functions -------------------------------------------------------------------------------]] local function UpdateImageAnchor(self) local frame = self.frame local width = frame.width or frame:GetWidth() or 0 local image = self.image local label = self.label local height label:ClearAllPoints() image:ClearAllPoints() if self.imageshown then local imagewidth = image:GetWidth() if (width - imagewidth) < 200 or (label:GetText() or "") == "" then -- image goes on top centered when less than 200 width for the text, or if there is no text image:SetPoint("TOP") label:SetPoint("TOP", image, "BOTTOM") label:SetPoint("LEFT") label:SetWidth(width) height = image:GetHeight() + label:GetHeight() else -- image on the left image:SetPoint("TOPLEFT") label:SetPoint("TOPLEFT", image, "TOPRIGHT", 4, 0) label:SetWidth(width - imagewidth - 4) height = max(image:GetHeight(), label:GetHeight()) end else -- no image shown label:SetPoint("TOPLEFT") label:SetWidth(width) height = label:GetHeight() end self.resizing = true frame:SetHeight(height) frame.height = height self.resizing = nil end --[[----------------------------------------------------------------------------- Methods -------------------------------------------------------------------------------]] local methods = { ["OnAcquire"] = function(self) self:SetHeight(18) self:SetWidth(200) self:SetText("") self:SetImage(nil) self:SetImageSize(16, 16) self:SetColor() self.label:SetFontObject(nil) self.label:SetFont(GameFontHighlightSmall:GetFont()) end, -- ["OnRelease"] = nil, ["SetText"] = function(self, text) self.label:SetText(text or "") UpdateImageAnchor(self) end, ["SetColor"] = function(self, r, g, b) if not (r and g and b) then r, g, b = 1, 1, 1 end self.label:SetVertexColor(r, g, b) end, ["OnWidthSet"] = function(self, width) if self.resizing then return end UpdateImageAnchor(self) end, ["SetImage"] = function(self, path, ...) local image = self.image image:SetTexture(path) if image:GetTexture() then self.imageshown = true local n = select("#", ...) if n == 4 or n == 8 then image:SetTexCoord(...) else image:SetTexCoord(0, 1, 0, 1) end else self.imageshown = nil end UpdateImageAnchor(self) end, ["SetFont"] = function(self, font, height, flags) self.label:SetFont(font, height, flags) end, ["SetFontObject"] = function(self, font) self.label:SetFontObject(font or GameFontHighlightSmall) end, ["SetImageSize"] = function(self, width, height) self.image:SetWidth(width) self.image:SetHeight(height) UpdateImageAnchor(self) end, } --[[----------------------------------------------------------------------------- Constructor -------------------------------------------------------------------------------]] local function Constructor() local frame = CreateFrame("Frame", nil, UIParent) frame:Hide() local label = frame:CreateFontString(nil, "BACKGROUND", "GameFontHighlightSmall") label:SetJustifyH("LEFT") label:SetJustifyV("TOP") local image = frame:CreateTexture(nil, "BACKGROUND") -- create widget local widget = { label = label, image = image, frame = frame, type = Type } for method, func in pairs(methods) do widget[method] = func end return AceGUI:RegisterAsWidget(widget) end AceGUI:RegisterWidgetType(Type, Constructor, Version)
--[[----------------------------------------------------------------------------- Label Widget Displays text and optionally an icon. -------------------------------------------------------------------------------]] local Type, Version = "Label", 21 local AceGUI = LibStub and LibStub("AceGUI-3.0", true) if not AceGUI or (AceGUI:GetWidgetVersion(Type) or 0) >= Version then return end -- Lua APIs local max, select = math.max, select -- WoW APIs local CreateFrame, UIParent = CreateFrame, UIParent -- Global vars/functions that we don't upvalue since they might get hooked, or upgraded -- List them here for Mikk's FindGlobals script -- GLOBALS: GameFontHighlightSmall --[[----------------------------------------------------------------------------- Support functions -------------------------------------------------------------------------------]] local function UpdateImageAnchor(self) if self.resizing then return end local frame = self.frame local width = frame.width or frame:GetWidth() or 0 local image = self.image local label = self.label local height label:ClearAllPoints() image:ClearAllPoints() if self.imageshown then local imagewidth = image:GetWidth() if (width - imagewidth) < 200 or (label:GetText() or "") == "" then -- image goes on top centered when less than 200 width for the text, or if there is no text image:SetPoint("TOP") label:SetPoint("TOP", image, "BOTTOM") label:SetPoint("LEFT") label:SetWidth(width) height = image:GetHeight() + label:GetHeight() else -- image on the left image:SetPoint("TOPLEFT") label:SetPoint("TOPLEFT", image, "TOPRIGHT", 4, 0) label:SetWidth(width - imagewidth - 4) height = max(image:GetHeight(), label:GetHeight()) end else -- no image shown label:SetPoint("TOPLEFT") label:SetWidth(width) height = label:GetHeight() end self.resizing = true frame:SetHeight(height) frame.height = height self.resizing = nil end --[[----------------------------------------------------------------------------- Methods -------------------------------------------------------------------------------]] local methods = { ["OnAcquire"] = function(self) -- set the flag to stop constant size updates self.resizing = true -- height is set dynamically by the text and image size self:SetWidth(200) self:SetText("") self:SetImage(nil) self:SetImageSize(16, 16) self:SetColor() self:SetFontObject() -- reset the flag self.resizing = nil -- run the update explicitly UpdateImageAnchor(self) end, -- ["OnRelease"] = nil, ["SetText"] = function(self, text) self.label:SetText(text or "") UpdateImageAnchor(self) end, ["SetColor"] = function(self, r, g, b) if not (r and g and b) then r, g, b = 1, 1, 1 end self.label:SetVertexColor(r, g, b) end, ["OnWidthSet"] = function(self, width) UpdateImageAnchor(self) end, ["SetImage"] = function(self, path, ...) local image = self.image image:SetTexture(path) if image:GetTexture() then self.imageshown = true local n = select("#", ...) if n == 4 or n == 8 then image:SetTexCoord(...) else image:SetTexCoord(0, 1, 0, 1) end else self.imageshown = nil end UpdateImageAnchor(self) end, ["SetFont"] = function(self, font, height, flags) self.label:SetFont(font, height, flags) end, ["SetFontObject"] = function(self, font) self:SetFont((font or GameFontHighlightSmall):GetFont()) end, ["SetImageSize"] = function(self, width, height) self.image:SetWidth(width) self.image:SetHeight(height) UpdateImageAnchor(self) end, } --[[----------------------------------------------------------------------------- Constructor -------------------------------------------------------------------------------]] local function Constructor() local frame = CreateFrame("Frame", nil, UIParent) frame:Hide() local label = frame:CreateFontString(nil, "BACKGROUND", "GameFontHighlightSmall") label:SetJustifyH("LEFT") label:SetJustifyV("TOP") local image = frame:CreateTexture(nil, "BACKGROUND") -- create widget local widget = { label = label, image = image, frame = frame, type = Type } for method, func in pairs(methods) do widget[method] = func end return AceGUI:RegisterAsWidget(widget) end AceGUI:RegisterWidgetType(Type, Constructor, Version)
AceGUI-3.0: Label: - Fix using SetFontObject. We'll internally wrap that to a :SetFont call now, since any font set with SetFont will override any font set with SetFontObject. - Avoid unnecessary re-layouts of the anchors during widget creation
AceGUI-3.0: Label: - Fix using SetFontObject. We'll internally wrap that to a :SetFont call now, since any font set with SetFont will override any font set with SetFontObject. - Avoid unnecessary re-layouts of the anchors during widget creation git-svn-id: e768786be8df873dac9515156656ebbdc6d77160@928 5debad98-a965-4143-8383-f471b3509dcf
Lua
bsd-3-clause
sarahgerweck/Ace3
35c26cde99298141acf292fe65b507064e7fca40
game/scripts/vscripts/gamemode.lua
game/scripts/vscripts/gamemode.lua
GameMode = GameMode or class({}) ARENA_VERSION = LoadKeyValues("addoninfo.txt").version GAMEMODE_INITIALIZATION_STATUS = {} local requirements = { "libraries/keyvalues", "libraries/timers", "libraries/physics", "libraries/projectiles", "libraries/notifications", "libraries/animations", "libraries/attachments", "libraries/playertables", "libraries/containers", -- "libraries/modmaker", -- "libraries/pathgraph", "libraries/selection", "libraries/worldpanels", "libraries/CosmeticLib", "libraries/PopupNumbers", "libraries/statcollection/init", -------------------------------------------------- "data/constants", "data/globals", "data/kv_data", "data/modifiers", "data/abilities", "data/ability_functions", "data/ability_shop", "data/commands", -------------------------------------------------- "internal/gamemode", "internal/events", -------------------------------------------------- "events", "custom_events", "filters", "modules/index" } local modifiers = { modifier_apocalypse_apocalypse = "heroes/hero_apocalypse/modifier_apocalypse_apocalypse", modifier_set_attack_range = "modifiers/modifier_set_attack_range", modifier_charges = "modifiers/modifier_charges", modifier_hero_selection_transformation = "modifiers/modifier_hero_selection_transformation", modifier_max_attack_range = "modifiers/modifier_max_attack_range", modifier_arena_hero = "modifiers/modifier_arena_hero", modifier_item_demon_king_bar_curse = "items/modifier_item_demon_king_bar_curse", modifier_hero_out_of_game = "modifiers/modifier_hero_out_of_game", modifier_item_shard_attackspeed_stack = "modifiers/modifier_item_shard_attackspeed_stack", modifier_item_casino_drug_pill1_addiction = "modifiers/modifier_item_casino_drug_pill1_addiction", modifier_item_casino_drug_pill2_addiction = "modifiers/modifier_item_casino_drug_pill2_addiction", modifier_item_casino_drug_pill3_addiction = "modifiers/modifier_item_casino_drug_pill3_addiction", } for k,v in pairs(modifiers) do LinkLuaModifier(k, v, LUA_MODIFIER_MOTION_NONE) end AllPlayersInterval = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23} for i = 1, #requirements do require(requirements[i]) end JSON = require("libraries/json") Options:Preload() function GameMode:InitGameMode() GameMode = self if GAMEMODE_INITIALIZATION_STATUS[2] then return end GAMEMODE_INITIALIZATION_STATUS[2] = true GameMode:InitFilters() HeroSelection:Initialize() GameMode:RegisterCustomListeners() DynamicWearables:Init() HeroSelection:PrepareTables() PanoramaShop:InitializeItemTable() Structures:AddHealers() Structures:CreateShops() Containers:SetItemLimit(50) Containers:UsePanoramaInventory(false) StatsClient:Init() Teams:Initialize() PlayerTables:CreateTable("arena", {}, AllPlayersInterval) PlayerTables:CreateTable("player_hero_indexes", {}, AllPlayersInterval) PlayerTables:CreateTable("players_abandoned", {}, AllPlayersInterval) PlayerTables:CreateTable("gold", {}, AllPlayersInterval) PlayerTables:CreateTable("disable_help_data", {[0] = {}, [1] = {}, [2] = {}, [3] = {}, [4] = {}, [5] = {}, [6] = {}, [7] = {}, [8] = {}, [9] = {}, [10] = {}, [11] = {}, [12] = {}, [13] = {}, [14] = {}, [15] = {}, [16] = {}, [17] = {}, [18] = {}, [19] = {}, [20] = {}, [21] = {}, [22] = {}, [23] = {}}, AllPlayersInterval) end function GameMode:PostLoadPrecache() end function GameMode:OnFirstPlayerLoaded() if Options:IsEquals("MainHeroList", "NoAbilities") then CustomAbilities:PrepareData() end StatsClient:FetchTopPlayers() end function GameMode:OnAllPlayersLoaded() if GAMEMODE_INITIALIZATION_STATUS[4] then return end GAMEMODE_INITIALIZATION_STATUS[4] = true StatsClient:FetchPreGameData() Events:Emit("AllPlayersLoaded") end function GameMode:OnHeroSelectionStart() Teams:PostInitialize() Options:CalculateVotes() DynamicMinimap:Init() Spawner:PreloadSpawners() Bosses:InitAllBosses() CustomRunes:Init() CustomTalents:Init() end function GameMode:OnHeroSelectionEnd() Timers:CreateTimer(CUSTOM_GOLD_TICK_TIME, Dynamic_Wrap(GameMode, "GameModeThink")) --Timers:CreateTimer(1/30, Dynamic_Wrap(GameMode, "QuickGameModeThink")) PanoramaShop:StartItemStocks() Duel:CreateGlobalTimer() Timers:CreateTimer(10, function() for playerID = 0, DOTA_MAX_TEAM_PLAYERS - 1 do if PlayerResource:IsValidPlayerID(playerID) and GetConnectionState(playerID) == DOTA_CONNECTION_STATE_CONNECTED then local heroName = HeroSelection:GetSelectedHeroName(playerID) or "" if heroName == "" or heroName == FORCE_PICKED_HERO then GameMode:BreakGame() return end end end end) end function GameMode:OnHeroInGame(hero) Timers:CreateTimer(function() if IsValidEntity(hero) and hero:IsTrueHero() then if not TEAMS_COURIERS[hero:GetTeamNumber()] then Structures:GiveCourier(hero) end HeroVoice:OnHeroInGame(hero) end end) end function GameMode:OnGameInProgress() if GAMEMODE_INITIALIZATION_STATUS[3] then return end GAMEMODE_INITIALIZATION_STATUS[3] = true Spawner:RegisterTimers() Timers:CreateTimer(function() CustomRunes:SpawnRunes() return CUSTOM_RUNE_SPAWN_TIME end) end function CDOTAGamerules:SetKillGoal(iGoal) KILLS_TO_END_GAME_FOR_TEAM = iGoal PlayerTables:SetTableValue("arena", "kill_goal", KILLS_TO_END_GAME_FOR_TEAM) end function CDOTAGamerules:GetKillGoal() return KILLS_TO_END_GAME_FOR_TEAM end function GameMode:PrecacheUnitQueueed(name) if not table.contains(RANDOM_OMG_PRECACHED_HEROES, name) then if not IS_PRECACHE_PROCESS_RUNNING then IS_PRECACHE_PROCESS_RUNNING = true table.insert(RANDOM_OMG_PRECACHED_HEROES, name) PrecacheUnitByNameAsync(name, function() IS_PRECACHE_PROCESS_RUNNING = nil end) else Timers:CreateTimer(0.5, function() GameMode:PrecacheUnitQueueed(name) end) end end end function GameMode:GameModeThink() for i = 0, 23 do if PlayerResource:IsValidPlayerID(i) then local hero = PlayerResource:GetSelectedHeroEntity(i) if hero then hero:SetNetworkableEntityInfo("unit_name", hero:GetFullName()) MeepoFixes:ShareItems(hero) end if GameRules:State_Get() == DOTA_GAMERULES_STATE_GAME_IN_PROGRESS then local gold_per_tick = CUSTOM_GOLD_PER_TICK if hero then if hero.talent_keys and hero.talent_keys.bonus_gold_per_minute then gold_per_tick = gold_per_tick + hero.talent_keys.bonus_gold_per_minute / 60 * CUSTOM_GOLD_TICK_TIME end if hero.talent_keys and hero.talent_keys.bonus_xp_per_minute then hero:AddExperience(hero.talent_keys.bonus_xp_per_minute / 60 * CUSTOM_GOLD_TICK_TIME, 0, false, false) end end Gold:AddGold(i, gold_per_tick) end AntiAFK:Think(i) end end return CUSTOM_GOLD_TICK_TIME end function GameMode:BreakGame() GameMode.Broken = true Tutorial:ForceGameStart() GameMode:OnOneTeamLeft(-1) end
GameMode = GameMode or class({}) ARENA_VERSION = LoadKeyValues("addoninfo.txt").version GAMEMODE_INITIALIZATION_STATUS = {} local requirements = { "libraries/keyvalues", "libraries/timers", "libraries/physics", "libraries/projectiles", "libraries/notifications", "libraries/animations", "libraries/attachments", "libraries/playertables", "libraries/containers", -- "libraries/modmaker", -- "libraries/pathgraph", "libraries/selection", "libraries/worldpanels", "libraries/CosmeticLib", "libraries/PopupNumbers", "libraries/statcollection/init", -------------------------------------------------- "data/constants", "data/globals", "data/kv_data", "data/modifiers", "data/abilities", "data/ability_functions", "data/ability_shop", "data/commands", -------------------------------------------------- "internal/gamemode", "internal/events", -------------------------------------------------- "events", "custom_events", "filters", "modules/index" } local modifiers = { modifier_apocalypse_apocalypse = "heroes/hero_apocalypse/modifier_apocalypse_apocalypse", modifier_set_attack_range = "modifiers/modifier_set_attack_range", modifier_charges = "modifiers/modifier_charges", modifier_hero_selection_transformation = "modifiers/modifier_hero_selection_transformation", modifier_max_attack_range = "modifiers/modifier_max_attack_range", modifier_arena_hero = "modifiers/modifier_arena_hero", modifier_item_demon_king_bar_curse = "items/modifier_item_demon_king_bar_curse", modifier_hero_out_of_game = "modifiers/modifier_hero_out_of_game", modifier_item_shard_attackspeed_stack = "modifiers/modifier_item_shard_attackspeed_stack", modifier_item_casino_drug_pill1_addiction = "modifiers/modifier_item_casino_drug_pill1_addiction", modifier_item_casino_drug_pill2_addiction = "modifiers/modifier_item_casino_drug_pill2_addiction", modifier_item_casino_drug_pill3_addiction = "modifiers/modifier_item_casino_drug_pill3_addiction", } for k,v in pairs(modifiers) do LinkLuaModifier(k, v, LUA_MODIFIER_MOTION_NONE) end AllPlayersInterval = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23} for i = 1, #requirements do require(requirements[i]) end JSON = require("libraries/json") Options:Preload() function GameMode:InitGameMode() GameMode = self if GAMEMODE_INITIALIZATION_STATUS[2] then return end GAMEMODE_INITIALIZATION_STATUS[2] = true GameMode:InitFilters() HeroSelection:Initialize() GameMode:RegisterCustomListeners() DynamicWearables:Init() HeroSelection:PrepareTables() PanoramaShop:InitializeItemTable() Structures:AddHealers() Structures:CreateShops() Containers:SetItemLimit(50) Containers:UsePanoramaInventory(false) StatsClient:Init() Teams:Initialize() PlayerTables:CreateTable("arena", {}, AllPlayersInterval) PlayerTables:CreateTable("player_hero_indexes", {}, AllPlayersInterval) PlayerTables:CreateTable("players_abandoned", {}, AllPlayersInterval) PlayerTables:CreateTable("gold", {}, AllPlayersInterval) PlayerTables:CreateTable("disable_help_data", {[0] = {}, [1] = {}, [2] = {}, [3] = {}, [4] = {}, [5] = {}, [6] = {}, [7] = {}, [8] = {}, [9] = {}, [10] = {}, [11] = {}, [12] = {}, [13] = {}, [14] = {}, [15] = {}, [16] = {}, [17] = {}, [18] = {}, [19] = {}, [20] = {}, [21] = {}, [22] = {}, [23] = {}}, AllPlayersInterval) end function GameMode:PostLoadPrecache() end function GameMode:OnFirstPlayerLoaded() if Options:IsEquals("MainHeroList", "NoAbilities") then CustomAbilities:PrepareData() end StatsClient:FetchTopPlayers() end function GameMode:OnAllPlayersLoaded() if GAMEMODE_INITIALIZATION_STATUS[4] then return end GAMEMODE_INITIALIZATION_STATUS[4] = true StatsClient:FetchPreGameData() Events:Emit("AllPlayersLoaded") end function GameMode:OnHeroSelectionStart() Teams:PostInitialize() Options:CalculateVotes() DynamicMinimap:Init() Spawner:PreloadSpawners() Bosses:InitAllBosses() CustomRunes:Init() CustomTalents:Init() end function GameMode:OnHeroSelectionEnd() Timers:CreateTimer(CUSTOM_GOLD_TICK_TIME, Dynamic_Wrap(GameMode, "GameModeThink")) --Timers:CreateTimer(1/30, Dynamic_Wrap(GameMode, "QuickGameModeThink")) PanoramaShop:StartItemStocks() Duel:CreateGlobalTimer() Timers:CreateTimer(10, function() for playerID = 0, DOTA_MAX_TEAM_PLAYERS - 1 do if PlayerResource:IsValidPlayerID(playerID) and not PlayerResource:IsFakeClient(playerID) and GetConnectionState(playerID) == DOTA_CONNECTION_STATE_CONNECTED then local heroName = HeroSelection:GetSelectedHeroName(playerID) or "" if heroName == "" or heroName == FORCE_PICKED_HERO then GameMode:BreakGame() return end end end end) end function GameMode:OnHeroInGame(hero) Timers:CreateTimer(function() if IsValidEntity(hero) and hero:IsTrueHero() then if not TEAMS_COURIERS[hero:GetTeamNumber()] then Structures:GiveCourier(hero) end HeroVoice:OnHeroInGame(hero) end end) end function GameMode:OnGameInProgress() if GAMEMODE_INITIALIZATION_STATUS[3] then return end GAMEMODE_INITIALIZATION_STATUS[3] = true Spawner:RegisterTimers() Timers:CreateTimer(function() CustomRunes:SpawnRunes() return CUSTOM_RUNE_SPAWN_TIME end) end function CDOTAGamerules:SetKillGoal(iGoal) KILLS_TO_END_GAME_FOR_TEAM = iGoal PlayerTables:SetTableValue("arena", "kill_goal", KILLS_TO_END_GAME_FOR_TEAM) end function CDOTAGamerules:GetKillGoal() return KILLS_TO_END_GAME_FOR_TEAM end function GameMode:PrecacheUnitQueueed(name) if not table.contains(RANDOM_OMG_PRECACHED_HEROES, name) then if not IS_PRECACHE_PROCESS_RUNNING then IS_PRECACHE_PROCESS_RUNNING = true table.insert(RANDOM_OMG_PRECACHED_HEROES, name) PrecacheUnitByNameAsync(name, function() IS_PRECACHE_PROCESS_RUNNING = nil end) else Timers:CreateTimer(0.5, function() GameMode:PrecacheUnitQueueed(name) end) end end end function GameMode:GameModeThink() for i = 0, 23 do if PlayerResource:IsValidPlayerID(i) then local hero = PlayerResource:GetSelectedHeroEntity(i) if hero then hero:SetNetworkableEntityInfo("unit_name", hero:GetFullName()) MeepoFixes:ShareItems(hero) end if GameRules:State_Get() == DOTA_GAMERULES_STATE_GAME_IN_PROGRESS then local gold_per_tick = CUSTOM_GOLD_PER_TICK if hero then if hero.talent_keys and hero.talent_keys.bonus_gold_per_minute then gold_per_tick = gold_per_tick + hero.talent_keys.bonus_gold_per_minute / 60 * CUSTOM_GOLD_TICK_TIME end if hero.talent_keys and hero.talent_keys.bonus_xp_per_minute then hero:AddExperience(hero.talent_keys.bonus_xp_per_minute / 60 * CUSTOM_GOLD_TICK_TIME, 0, false, false) end end Gold:AddGold(i, gold_per_tick) end AntiAFK:Think(i) end end return CUSTOM_GOLD_TICK_TIME end function GameMode:BreakGame() GameMode.Broken = true Tutorial:ForceGameStart() GameMode:OnOneTeamLeft(-1) end
Fixed having fake client before first 10 seconds after hero selection end caused game to end
Fixed having fake client before first 10 seconds after hero selection end caused game to end
Lua
mit
ark120202/aabs
61f39542b7a8ce7b8ce5307b91309d77d6fb4e8d
lua/entities/gmod_wire_soundemitter.lua
lua/entities/gmod_wire_soundemitter.lua
--[[ The Wire Sound Emitter emits a sound whose parameters can be tweaked. See http://wiki.garrysmod.com/page/Category:CSoundPatch --]] AddCSLuaFile() DEFINE_BASECLASS( "base_wire_entity" ) ENT.PrintName = "Wire Sound Emitter" ENT.RenderGroup = RENDERGROUP_OPAQUE ENT.WireDebugName = "Sound Emitter" if CLIENT then return end function ENT:Initialize() self:PhysicsInit( SOLID_VPHYSICS ) self:SetMoveType( MOVETYPE_VPHYSICS ) self:SetSolid( SOLID_VPHYSICS ) self.Inputs = Wire_CreateInputs(self, { "A", "Toggle", "Volume", "Play", "Stop", "PitchRelative", "Sample", "SampleName [STRING]" }) self.Outputs = Wire_CreateOutputs(self, { "Memory" }) self.Samples = { [1] = "synth/square.wav", [2] = "synth/saw.wav", [3] = "synth/tri.wav", [4] = "synth/sine.wav" } self.Active = false self.Volume = 5 self.Pitch = 100 self.Sample = self.Samples[1] end function ENT:OnRemove() self:StopSounds() self.BaseClass.OnRemove(self) end function ENT:ReadCell(address) return nil end local cells = { [0] = "A", [1] = "Volume", [2] = "PitchRelative", [3] = "Sample", [4] = "LFOType", [5] = "LFORate", [6] = "LFOModPitch", [7]= "LFOModVolume" } function ENT:WriteCell(address, value) if cells[address] then self:TriggerInput(cells[address], value) return true else return false end end function ENT:TriggerInput(iname, value) if iname == "Toggle" and value ~= 0 then self:TriggerInput("A", not self.Active) elseif iname == "A" then if value ~= 0 then self:TriggerInput("Play", 1) else self:TriggerInput("Stop", 1) end elseif iname == "Play" and value ~= 0 then self.Active = true self:StartSounds() elseif iname == "Stop" and value ~= 0 then self.Active = false self:StopSounds() elseif iname == "Volume" then self.Volume = math.Clamp(math.floor(value*100), 0, 100) elseif iname == "PitchRelative" then self.Pitch = math.Clamp(math.floor(value*100), 0, 255) elseif iname == "Sample" then self:TriggerInput("SampleName", self.Samples[value] or self.Samples[1]) elseif iname == "SampleName" then self:SetSound(value) end self:UpdateSound() end function ENT:UpdateSound() if self.Sample ~= self.ActiveSample then self.Sound = CreateSound(self, Sound(self.Sample)) self.ActiveSample = self.Sample if self.Active then self:StartSounds() end end self.Sound:ChangePitch(self.Pitch, 0) self.Sound:ChangeVolume(self.Volume, 0) end function ENT:SetSound(soundName) self:StopSounds() if soundName:match('["?]') then return end parsedsound = soundName:Trim() util.PrecacheSound(parsedsound) self.Sample = parsedsound self:SetOverlayText( parsedsound:gsub("[/\\]+","/") ) end function ENT:StartSounds() if self.Sound then self.Sound:Play() end end function ENT:StopSounds() if self.Sound then self.Sound:Stop() end end function ENT:Setup(sample) self.Sample = sample end duplicator.RegisterEntityClass("gmod_wire_soundemitter", MakeWireEnt, "Data", "Sample")
--[[ The Wire Sound Emitter emits a sound whose parameters can be tweaked. See http://wiki.garrysmod.com/page/Category:CSoundPatch --]] AddCSLuaFile() DEFINE_BASECLASS( "base_wire_entity" ) ENT.PrintName = "Wire Sound Emitter" ENT.RenderGroup = RENDERGROUP_OPAQUE ENT.WireDebugName = "Sound Emitter" if CLIENT then return end function ENT:Initialize() self:PhysicsInit( SOLID_VPHYSICS ) self:SetMoveType( MOVETYPE_VPHYSICS ) self:SetSolid( SOLID_VPHYSICS ) self.Inputs = Wire_CreateInputs(self, { "A", "Toggle", "Volume", "Play", "Stop", "PitchRelative", "Sample", "SampleName [STRING]" }) self.Outputs = Wire_CreateOutputs(self, { "Memory" }) self.Samples = { [1] = "synth/square.wav", [2] = "synth/saw.wav", [3] = "synth/tri.wav", [4] = "synth/sine.wav" } self.Active = false self.Volume = 5 self.Pitch = 100 self.Sample = self.Samples[1] self.NeedsRefresh = true hook.Add("PlayerConnect", self:GetClass() .. self:EntIndex(), function() self.NeedsRefresh = true end) end function ENT:OnRemove() hook.Remove("PlayerConnect", self:GetClass() .. self:EntIndex()) self:StopSounds() self.BaseClass.OnRemove(self) end function ENT:ReadCell(address) return nil end local cells = { [0] = "A", [1] = "Volume", [2] = "PitchRelative", [3] = "Sample", [4] = "LFOType", [5] = "LFORate", [6] = "LFOModPitch", [7]= "LFOModVolume" } function ENT:WriteCell(address, value) if cells[address] then self:TriggerInput(cells[address], value) return true else return false end end function ENT:TriggerInput(iname, value) if iname == "Toggle" and value ~= 0 then self:TriggerInput("A", not self.Active) elseif iname == "A" then if value ~= 0 then self:TriggerInput("Play", 1) else self:TriggerInput("Stop", 1) end elseif iname == "Play" and value ~= 0 then self.Active = true self:StartSounds() elseif iname == "Stop" and value ~= 0 then self.Active = false self:StopSounds() elseif iname == "Volume" then self.Volume = math.Clamp(math.floor(value*100), 0, 100) elseif iname == "PitchRelative" then self.Pitch = math.Clamp(math.floor(value*100), 0, 255) elseif iname == "Sample" then self:TriggerInput("SampleName", self.Samples[value] or self.Samples[1]) elseif iname == "SampleName" then self:SetSound(value) end self:UpdateSound() end function ENT:UpdateSound() if self.NeedsRefresh or self.Sample ~= self.ActiveSample then self.NeedsRefresh = nil self.Sound = CreateSound(self, Sound(self.Sample)) self.ActiveSample = self.Sample if self.Active then self:StartSounds() end end self.Sound:ChangePitch(self.Pitch, 0) self.Sound:ChangeVolume(self.Volume, 0) end function ENT:SetSound(soundName) self:StopSounds() if soundName:match('["?]') then return end parsedsound = soundName:Trim() util.PrecacheSound(parsedsound) self.Sample = parsedsound self:SetOverlayText( parsedsound:gsub("[/\\]+","/") ) end function ENT:StartSounds() if self.NeedsRefresh then self:UpdateSound() end if self.Sound then self.Sound:Play() end end function ENT:StopSounds() if self.Sound then self.Sound:Stop() end end function ENT:Setup(sample) self.Sample = sample end duplicator.RegisterEntityClass("gmod_wire_soundemitter", MakeWireEnt, "Data", "Sample")
gmod_wire_soundemitter: Fix #354. Sound will automatically refresh when a player joins (but you will need to stop and start the sound)
gmod_wire_soundemitter: Fix #354. Sound will automatically refresh when a player joins (but you will need to stop and start the sound)
Lua
apache-2.0
CaptainPRICE/wire,NezzKryptic/Wire,plinkopenguin/wiremod,notcake/wire,mms92/wire,rafradek/wire,Grocel/wire,wiremod/wire,garrysmodlua/wire,dvdvideo1234/wire,Python1320/wire,thegrb93/wire,immibis/wiremod,mitterdoo/wire,sammyt291/wire,bigdogmat/wire
9f2df910b7961fe954d4983f411da7119d1fea04
src/bot.lua
src/bot.lua
local bot = {} local api = require("api") local utils = require("utils") local soul = require("soul") function bot.analyzeMessageType(upd) if upd.message then local msg = upd.message if msg.audio then return "Audio" elseif msg.video then return "Video" elseif msg.document then return "Document" elseif msg.game then return "Game" elseif msg.photo then return "Photo" elseif msg.sticker then return "Sticker" elseif msg.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 function bot.reload() package.loaded.soul = nil package.loaded.bot = nil package.loaded.api = nil package.loaded.utils = nil package.loaded.conversation = nil soul = require("soul") bot = require("bot") api = require("api") local t = api.fetch() for k, v in pairs(t) do bot[k] = v end 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 ret = bot.getMe() if ret then bot.info = ret.result logger:info("bot online. I am " .. bot.info.first_name .. ".") end local offset = 0 local threads = {} while true do local updates = bot.getUpdates(offset, config.limit, config.timeout) if updates and updates.result then for key, upd in pairs(updates.result) do threads[upd.update_id] = coroutine.create(function() soul[("on%sReceive"):format(bot.analyzeMessageType(upd))]( upd.message or upd.edited_message or upd.channel_post or upd.edited_channel_post or upd.inline_query or upd.chosen_inline_result or upd.callback_query or upd.shipping_query or upd.pre_checkout_query ) end) offset = upd.update_id + 1 end end for uid, thread in pairs(threads) do local status, res = coroutine.resume(thread) if not status then threads[uid] = nil if (res ~= "cannot resume dead coroutine") then logger:error("coroutine #" .. uid .. " crashed, reason: " .. res) end end end end end setmetatable(bot, { __index = function(t, key) logger:warn("called undefined method " .. key) end }) return bot
local bot = {} local api = require("api") local soul = require("soul") function bot.analyzeMessageType(upd) if upd.message then local msg = upd.message if msg.audio then return "Audio" elseif msg.video then return "Video" elseif msg.document then return "Document" elseif msg.game then return "Game" elseif msg.photo then return "Photo" elseif msg.sticker then return "Sticker" elseif msg.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 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: did not load api functions in bot.run
fix: did not load api functions in bot.run
Lua
apache-2.0
SJoshua/Project-Small-R
8688bbeaeea7a109baf7c455ddc5a9b90d45f8b6
scripts/lua/policies/backendRouting.lua
scripts/lua/policies/backendRouting.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 backendRouting -- Used to set the backend Url either statically or dynamically local url = require "url" local utils = require "lib/utils" local request = require "lib/request" local logger = require "lib/logger" local _M = {} --- Set upstream based on the backendUrl function _M.setRoute(backendUrl) local u = url.parse(backendUrl) if u.scheme == nil then u = url.parse(utils.concatStrings({'http://', backendUrl})) end ngx.var.backendUrl = backendUrl ngx.req.set_uri(getUriPath(u.path)) setUpstream(u) end --- Set dynamic route based on the based on the header that is passed in function _M.setDynamicRoute(obj) local whitelist = obj.whitelist for k in pairs(whitelist) do whitelist[k] = whitelist[k]:lower() end local header = obj.header ~= nil and obj.header or 'X-Cf-Forwarded-Url' local dynamicBackend = ngx.req.get_headers()[header]; if dynamicBackend ~= nil and dynamicBackend ~= '' then local u = url.parse(dynamicBackend) if u.scheme == nil or u.scheme == '' then u = url.parse(utils.concatStrings({'http://', dynamicBackend})) end if utils.tableContains(whitelist, u.host) then ngx.req.set_uri(getUriPath(u.path)) setUpstream(u) else request.err(403, 'Dynamic backend host not part of whitelist.') end else logger.info('Header for dynamic routing not found. Defaulting to backendUrl.') end end function getUriPath(backendPath) local gatewayPath = ngx.unescape_uri(ngx.var.gatewayPath) gatewayPath = gatewayPath:gsub('-', '%%-') local _, j = ngx.var.request_uri:find(gatewayPath) local incomingPath = ((j and ngx.var.request_uri:sub(j + 1)) or nil) -- Check for backendUrl path if backendPath == nil or backendPath == '' or backendPath == '/' then incomingPath = (incomingPath and incomingPath ~= '') and incomingPath or '/' incomingPath = string.sub(incomingPath, 1, 1) == '/' and incomingPath or utils.concatStrings({'/', incomingPath}) return incomingPath else return utils.concatStrings({backendPath, incomingPath}) end end function setUpstream(u) local upstream = utils.concatStrings({u.scheme, '://', u.host}) if u.port ~= nil and u.port ~= '' then upstream = utils.concatStrings({upstream, ':', u.port}) end ngx.var.upstream = upstream 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 backendRouting -- Used to set the backend Url either statically or dynamically local url = require "url" local utils = require "lib/utils" local request = require "lib/request" local logger = require "lib/logger" local _M = {} --- Set upstream based on the backendUrl function _M.setRoute(backendUrl) local u = url.parse(backendUrl) if u.scheme == nil then u = url.parse(utils.concatStrings({'http://', backendUrl})) end ngx.var.backendUrl = backendUrl ngx.req.set_uri(getUriPath(u.path)) setUpstream(u) end --- Set dynamic route based on the based on the header that is passed in function _M.setDynamicRoute(obj) local whitelist = obj.whitelist for k in pairs(whitelist) do whitelist[k] = whitelist[k]:lower() end local header = obj.header ~= nil and obj.header or 'X-Cf-Forwarded-Url' local dynamicBackend = ngx.req.get_headers()[header]; if dynamicBackend ~= nil and dynamicBackend ~= '' then local u = url.parse(dynamicBackend) if u.scheme == nil or u.scheme == '' then u = url.parse(utils.concatStrings({'http://', dynamicBackend})) end if utils.tableContains(whitelist, u.host) then ngx.req.set_uri(getUriPath(u.path)) setUpstream(u) else request.err(403, 'Dynamic backend host not part of whitelist.') end else logger.info('Header for dynamic routing not found. Defaulting to backendUrl.') end end function getUriPath(backendPath) local gatewayPath = ngx.unescape_uri(ngx.var.gatewayPath) gatewayPath = gatewayPath:gsub('-', '%%-') local uri = string.gsub(ngx.var.request_uri, '?.*', '') local _, j = uri:find(gatewayPath) local incomingPath = ((j and uri:sub(j + 1)) or nil) -- Check for backendUrl path if backendPath == nil or backendPath == '' or backendPath == '/' then incomingPath = (incomingPath and incomingPath ~= '') and incomingPath or '/' incomingPath = string.sub(incomingPath, 1, 1) == '/' and incomingPath or utils.concatStrings({'/', incomingPath}) return incomingPath else return utils.concatStrings({backendPath, incomingPath}) end end function setUpstream(u) local upstream = utils.concatStrings({u.scheme, '://', u.host}) if u.port ~= nil and u.port ~= '' then upstream = utils.concatStrings({upstream, ':', u.port}) end ngx.var.upstream = upstream end return _M
Fix proxying query parameters (#125)
Fix proxying query parameters (#125)
Lua
apache-2.0
LukeFarrell/incubator-openwhisk-apigateway,alexsong93/openwhisk-apigateway,openwhisk/apigateway,LukeFarrell/incubator-openwhisk-apigateway,alexsong93/openwhisk-apigateway,openwhisk/openwhisk-apigateway,alexsong93/openwhisk-apigateway,openwhisk/apigateway,openwhisk/openwhisk-apigateway,openwhisk/openwhisk-apigateway,openwhisk/apigateway,LukeFarrell/incubator-openwhisk-apigateway
4db7192f6253f996b54263fc4610188b2f87c879
lua/entities/gmod_wire_panel/cl_init.lua
lua/entities/gmod_wire_panel/cl_init.lua
include('shared.lua') ENT.RenderGroup = RENDERGROUP_BOTH function ENT:Initialize() self.menu = nil self.chan = 1 self.disp1 = 0 -- Edit the menu here. Maximum of 10 lines. self.menus = { [-1] = { "Channel", nil }, [ 0] = { "Index", nil }, { "Ch. 1", "Channel 1" }, { "Ch. 2", "Channel 2" }, { "Ch. 3", "Channel 3" }, { "Ch. 4", "Channel 4" }, { "Ch. 5", "Channel 5" }, { "Ch. 6", "Channel 6" }, { "Ch. 7", "Channel 7" }, { "Ch. 8", "Channel 8" }, } surface.CreateFont( "coolvetica", 80, 400, false, false, "panel_font" ) RunConsoleCommand("wire_panel_data", self:EntIndex(), "r") -- request registration and channel value transmission self:InitializeShared() self.GPU = WireGPU(self, true) self.workingDistance = 64*128 end function ENT:OnRemove() self.GPU:Finalize() end function ENT:Think() local ply = LocalPlayer() if ply:KeyDown(IN_USE) and not ply:KeyDownLast(IN_USE) and ply:GetEyeTraceNoCursor().Entity == self.GPU.Entity then self:Use() end end function ENT:Use() if self.lasthovermenu then self.menu = self.lasthovermenu end if self.lasthoverchan then self:ChangeChannelNumber(self.lasthoverchan) end end function ENT:Draw() self.Entity:DrawModel() self.GPU:RenderToWorld(nil, 184, function(x, y, w, h, monitor, pos, ang, res) surface.SetDrawColor(0,0,0,255) surface.DrawRect(x,y,w,h) local ply = LocalPlayer() local trace = ply:GetEyeTraceNoCursor() local ent = trace.Entity if not ent:IsValid() then return end local dist = trace.Normal:Dot(trace.HitNormal)*trace.Fraction*-16384 dist = math.max(dist, trace.Fraction*16384-ent:BoundingRadius()) local onscreen = false local cx, cy = 100,100 local control = dist < self.workingDistance and ent == self.GPU.Entity if control then local cpos = WorldToLocal(trace.HitPos, Angle(), pos, ang) cx = 0.5+cpos.x/(res*w) cy = 0.5-cpos.y/(res*h) if cx >= 0 and cy >= 0 and cx <= 1 and cy <= 1 then onscreen = true end end local cxp, cyp = x+cx*w, y+cy*h if self.menu then -- "SET" button local onbutton = onscreen and cxp>=x+50 and cy>=0.5 self.lasthoverchan = onbutton and self.menu or nil local intensity = onbutton and 150 or 100 if self.menu == self.chan then surface.SetDrawColor(0,intensity,0,255) else surface.SetDrawColor(intensity,0,0,255) end surface.DrawRect(x+50,y+h/2,w-50,h/2) surface.SetFont("panel_font") surface.SetTextColor(Color(255,255,255,255)) local textw, texth = surface.GetTextSize("SET") surface.SetTextPos(x+25+w/2-textw/2, y+h*3/4-texth/2) surface.DrawText("SET") end -- selection bar on the left surface.SetDrawColor(100,100,100,255) surface.DrawRect(x, y, 50, h) do local onbar = cxp >= x and cxp < x+50 -- menu text surface.SetFont("Trebuchet18") surface.SetTextColor(Color(255,255,255,255)) local yp = y self.lasthovermenu = nil for i = -1,8 do local disp = self.menus[i][1] local textw, texth = surface.GetTextSize(disp) if self.menus[i][2] then if onbar and cyp >= yp and cyp < yp+texth then surface.SetDrawColor(80,120,180,255) surface.DrawRect(x,yp,50,texth) self.lasthovermenu = i elseif self.chan == i then surface.SetDrawColor(60,160,60,255) surface.DrawRect(x,yp,50,texth) elseif self.menu == i then surface.SetDrawColor(60,60,60,255) surface.DrawRect(x,yp,50,texth) end end surface.SetTextPos(x+2, yp) surface.DrawText(disp) yp = yp+texth end end --draw.DrawText(out,"Trebuchet18",x+2,y,Color(255,255,255,255)) if self.menu then local ChannelValue = self:GetChannelValue( self.menu ) local disp = self.menus[self.menu][2].."\n\n"..string.format("%.2f", ChannelValue) draw.DrawText(disp,"Trebuchet18",x+54,y,Color(255,255,255,255)) end if onscreen then surface.SetDrawColor(255, 255, 255, 255) surface.SetTexture(surface.GetTextureID("gui/arrow")) surface.DrawTexturedRectRotated(x+cx*w+11,y+cy*h+11,32,32,45) elseif not control then surface.SetDrawColor(255,255,255,255) surface.SetTexture(surface.GetTextureID("gui/info")) local infow, infoh = h*0.2,h*0.2 surface.DrawTexturedRect(x+(w-infow)/2, y+(h-infoh)/2, infow, infoh) end end) Wire_Render(self.Entity) end function ENT:IsTranslucent() return true end
include('shared.lua') ENT.RenderGroup = RENDERGROUP_BOTH function ENT:Initialize() self.menu = nil self.chan = 1 self.disp1 = 0 -- Edit the menu here. Maximum of 10 lines. self.menus = { [-1] = { "Channel", nil }, [ 0] = { "Index", nil }, { "Ch. 1", "Channel 1" }, { "Ch. 2", "Channel 2" }, { "Ch. 3", "Channel 3" }, { "Ch. 4", "Channel 4" }, { "Ch. 5", "Channel 5" }, { "Ch. 6", "Channel 6" }, { "Ch. 7", "Channel 7" }, { "Ch. 8", "Channel 8" }, } surface.CreateFont( "coolvetica", 80, 400, false, false, "panel_font" ) RunConsoleCommand("wire_panel_data", self:EntIndex(), "r") -- request registration and channel value transmission self:InitializeShared() self.GPU = WireGPU(self, true) self.workingDistance = 64 end function ENT:OnRemove() self.GPU:Finalize() end function ENT:Think() local ply = LocalPlayer() if ply:KeyDown(IN_USE) and not ply:KeyDownLast(IN_USE) and ply:GetEyeTraceNoCursor().Entity == self.GPU.Entity then self:Use() end end function ENT:Use() if self.lasthovermenu then self.menu = self.lasthovermenu end if self.lasthoverchan then self:ChangeChannelNumber(self.lasthoverchan) end end function ENT:Draw() self.Entity:DrawModel() self.GPU:RenderToWorld(nil, 184, function(x, y, w, h, monitor, pos, ang, res) surface.SetDrawColor(0,0,0,255) surface.DrawRect(x,y,w,h) local ply = LocalPlayer() local trace = ply:GetEyeTraceNoCursor() local ent = trace.Entity local dist = trace.Normal:Dot(trace.HitNormal)*trace.Fraction*-16384 dist = math.max(dist, trace.Fraction*16384-self.GPU.Entity:BoundingRadius()) local onscreen = false if dist < self.workingDistance and ent == self.GPU.Entity then local cpos = WorldToLocal(trace.HitPos, Angle(), pos, ang) local cx = 0.5+cpos.x/(res*w) local cy = 0.5-cpos.y/(res*h) if cx >= 0 and cy >= 0 and cx <= 1 and cy <= 1 then onscreen = true end local cxp, cyp = x+cx*w, y+cy*h if self.menu then -- "SET" button local onbutton = onscreen and cxp>=x+50 and cy>=0.5 self.lasthoverchan = onbutton and self.menu or nil local intensity = onbutton and 150 or 100 if self.menu == self.chan then surface.SetDrawColor(0,intensity,0,255) else surface.SetDrawColor(intensity,0,0,255) end surface.DrawRect(x+50,y+h/2,w-50,h/2) surface.SetFont("panel_font") surface.SetTextColor(Color(255,255,255,255)) local textw, texth = surface.GetTextSize("SET") surface.SetTextPos(x+25+w/2-textw/2, y+h*3/4-texth/2) surface.DrawText("SET") end -- selection bar on the left surface.SetDrawColor(100,100,100,255) surface.DrawRect(x, y, 50, h) do local onbar = cxp >= x and cxp < x+50 -- menu text surface.SetFont("Trebuchet18") surface.SetTextColor(Color(255,255,255,255)) local yp = y self.lasthovermenu = nil for i = -1,8 do local disp = self.menus[i][1] local textw, texth = surface.GetTextSize(disp) if self.menus[i][2] then if onbar and cyp >= yp and cyp < yp+texth then surface.SetDrawColor(80,120,180,255) surface.DrawRect(x,yp,50,texth) self.lasthovermenu = i elseif self.chan == i then surface.SetDrawColor(60,160,60,255) surface.DrawRect(x,yp,50,texth) elseif self.menu == i then surface.SetDrawColor(48,48,48,255) surface.DrawRect(x,yp,50,texth) end end surface.SetTextPos(x+2, yp) surface.DrawText(disp) yp = yp+texth end end --draw.DrawText(out,"Trebuchet18",x+2,y,Color(255,255,255,255)) if self.menu then local ChannelValue = self:GetChannelValue( self.menu ) local disp = self.menus[self.menu][2].."\n\n"..string.format("%.2f", ChannelValue) draw.DrawText(disp,"Trebuchet18",x+54,y,Color(255,255,255,255)) end if onscreen then surface.SetDrawColor(255, 255, 255, 255) surface.SetTexture(surface.GetTextureID("gui/arrow")) surface.DrawTexturedRectRotated(x+cx*w+11,y+cy*h+11,32,32,45) end else surface.SetDrawColor(255,255,255,255) surface.SetTexture(surface.GetTextureID("gui/info")) local infow, infoh = h*0.2,h*0.2 surface.DrawTexturedRect(x+(w-infow)/2, y+(h-infoh)/2, infow, infoh) end end) Wire_Render(self.Entity) end function ENT:IsTranslucent() return true end
[Panel] Fixed menu visibility.
[Panel] Fixed menu visibility.
Lua
apache-2.0
notcake/wire,rafradek/wire,immibis/wiremod,sammyt291/wire,plinkopenguin/wiremod,mitterdoo/wire,NezzKryptic/Wire,wiremod/wire,mms92/wire,dvdvideo1234/wire,Grocel/wire,CaptainPRICE/wire,thegrb93/wire,bigdogmat/wire,garrysmodlua/wire,Python1320/wire
eef99f0f886e994d82cfb2505881af77469d6c33
lua/autorun/includes/modules/control.lua
lua/autorun/includes/modules/control.lua
local IsValid = IsValid local pairs = pairs local RealTime = RealTime local type = type local IsKeyDown = input.IsKeyDown local IsGameUIVisible = gui.IsGameUIVisible local IsConsoleVisible = gui.IsConsoleVisible _G.control = {} local HoldTime = 0.3 local LastPress = nil local LastKey = nil local KeyControls = {} local function dispatch(name, func, down, held) -- Use same behavior as the hook system if type(name) == 'table' then if IsValid(name) then func( name, down, held ) else handles[ name ] = nil end else func( down, held ) end end local function InputThink() if IsGameUIVisible() or IsConsoleVisible() then return end for key, handles in pairs( KeyControls ) do for name, tbl in pairs( handles ) do if tbl.Enabled then -- Key hold (repeat press) if tbl.LastPress and tbl.LastPress + HoldTime < RealTime() then dispatch(name, tbl.Toggle, true, true) tbl.LastPress = RealTime() end -- Key release if not IsKeyDown( key ) then dispatch(name, tbl.Toggle, false) tbl.Enabled = false end else -- Key press if IsKeyDown( key ) then dispatch(name, tbl.Toggle, true) tbl.Enabled = true tbl.LastPress = RealTime() end end end end end hook.Add( "Think", "InputManagerThink", InputThink ) function control.Add( key, name, onToggle ) if not (key and onToggle) then return end if not KeyControls[ key ] then KeyControls[ key ] = {} end KeyControls[ key ][ name ] = { Enabled = false, LastPress = 0, Toggle = onToggle --[[Toggle = function(...) local msg, err = pcall( onToggle, ... ) if err then print( "ERROR: " .. msg ) end end]] } end function control.Remove( key, name ) if not KeyControls[ key ] then return end KeyControls[ key ][ name ] = nil end
local IsValid = IsValid local pairs = pairs local RealTime = RealTime local type = type local IsKeyDown = input.IsKeyDown local IsGameUIVisible = gui.IsGameUIVisible local IsConsoleVisible = gui.IsConsoleVisible _G.control = {} local HoldTime = 0.3 local LastPress = nil local LastKey = nil local KeyControls = {} local function InputThink() if IsGameUIVisible() or IsConsoleVisible() then return end local dispatch, down, held for key, handles in pairs( KeyControls ) do for name, tbl in pairs( handles ) do dispatch = false if tbl.Enabled then -- Key hold (repeat press) if tbl.LastPress and tbl.LastPress + HoldTime < RealTime() then dispatch = true down = true held = true tbl.LastPress = RealTime() end -- Key release if not IsKeyDown( key ) then dispatch = true down = false tbl.Enabled = false end else -- Key press if IsKeyDown( key ) then dispatch = true down = true tbl.Enabled = true tbl.LastPress = RealTime() end end if dispatch then -- Use same behavior as the hook system if type(name) == 'table' then if IsValid(name) then tbl.Toggle( name, down, held ) else handles[ name ] = nil end else tbl.Toggle( down, held ) end end end end end hook.Add( "Think", "InputManagerThink", InputThink ) --- -- Adds a callback to be dispatched when a key is pressed. -- -- @param key `KEY_` enum. -- @param name Unique identifier or a valid object. -- @param onToggle Callback function. -- function control.Add( key, name, onToggle ) if not (key and onToggle) then return end if not KeyControls[ key ] then KeyControls[ key ] = {} end KeyControls[ key ][ name ] = { Enabled = false, LastPress = 0, Toggle = onToggle } end --- -- Removes a registered key callback. -- -- @param key `KEY_` enum. -- @param name Unique identifier or a valid object. -- function control.Remove( key, name ) if not KeyControls[ key ] then return end KeyControls[ key ][ name ] = nil end
Fixed undefined index 'handles' error in control module
Fixed undefined index 'handles' error in control module
Lua
mit
pixeltailgames/gm-mediaplayer,pixeltailgames/gm-mediaplayer
04d4c4334cb3404036c1c1dadab0a4a9f23cd214
qq.lua
qq.lua
local ffi = require "ffi" local packetLib = require "packet" local memory = require "memory" local qqlib = ffi.load("build/qq") ffi.cdef [[ typedef struct packet_header { uint64_t ts_vlan; uint16_t len; uint8_t data[]; } packet_header_t; typedef struct qq { } qq_t; void qq_init(); qq_t* qq_create(uint32_t storage_capacity); void qq_delete(qq_t*); size_t qq_size(qq_t*); size_t qq_capacity(qq_t*); typedef struct { } storage_t; storage_t* qq_storage_dequeue(qq_t*); storage_t* qq_storage_try_dequeue(qq_t*); storage_t* qq_storage_enqueue(qq_t*); storage_t* qq_storage_peek(qq_t*); size_t qq_get_enqueue_counter(qq_t*); size_t qq_get_dequeue_counter(qq_t*); void qq_set_priority(qq_t* q, const uint8_t new_priority); void qq_storage_release(storage_t*); size_t qq_storage_size(storage_t*); bool qq_storage_store(storage_t*, uint64_t ts, uint16_t vlan, uint16_t len, const uint8_t* data); const packet_header_t& qq_storage_get_packet(storage_t*, const size_t); uint64_t qq_packet_header_get_timestamp(const packet_header_t&); uint64_t qq_packet_header_get_vlan(const packet_header_t& h); uint16_t qq_packet_header_get_len(const packet_header_t& h); void* qq_packet_header_get_data(const packet_header_t& h); void dummy_enqueue(qq_t* q); void qq_inserter_loop(uint8_t device, uint16_t queue_id, qq_t* qq); ]] local C = ffi.C local mod = {} --- @param storageSize desired storage capacity in GiB function mod.createQQ(storageSize) qqlib.qq_init() -- idempotent return qqlib.qq_create(storageSize * 1024) end local qq = {} qq.__index = qq local storage = {} storage.__index = storage local packetHeader = {} packetHeader.__index = packetHeader function qq:delete() qqlib.qq_delete(self) end function qq:size() return tonumber(qqlib.qq_size(self)) end function qq:capacity() return qqlib.qq_capacity(self) end function qq:dequeue() return qqlib.qq_storage_dequeue(self) end function qq:tryDequeue() return qqlib.qq_storage_try_dequeue(self) end function qq:enqueue() return qqlib.qq_storage_enqueue(self) end function qq:peek() return qqlib.qq_storage_peek(self) end function qq:getEnqueueCounter() return qqlib.qq_get_enqueue_counter(self) end function qq:getDequeueCounter() return qqlib.qq_get_dequeue_counter(self) end function qq:setPriority(new_priority) return qqlib.qq_set_priority(self, new_priority) end function qq:dummy() qqlib.dummy_enqueue(self) end function storage:release() qqlib.qq_storage_release(self) end function storage:size() return tonumber(qqlib.qq_storage_size(self)) end function storage:store(ts, vlan, len, data) return qqlib.qq_storage_store(self, ts, vlan, len, data) end function storage:getPacket(idx) return qqlib.qq_storage_get_packet(self, idx) end local band, rshift, lshift = bit.band, bit.rshift, bit.lshift function packetHeader:getTimestamp() -- timestamp relative to libmoon.getTime(), i.e. the TSC in seconds return tonumber(band(self.ts_vlan, 0xffffffffffffULL)) / 10^6 end function packetHeader:getVlan() return rshift(self.ts_vlan, 48) end function packetHeader:getLength() return self.len end function packetHeader:getData() return ffi.cast("void*", self.data) end function packetHeader:dump() return packetLib.getEthernetPacket(self):resolveLastHeader():dump() end function packetHeader:clone() local pkt = memory.alloc("packet_header_t*", ffi.sizeof("packet_header_t") + self.len) pkt.ts_vlan = self.ts_vlan pkt.len = self.len ffi.copy(pkt.data, self.data, self.len) return pkt end function qq:inserterLoop(queue) qqlib.qq_inserter_loop(queue.id, queue.qid, self) end ffi.metatype("qq_t", qq) ffi.metatype("storage_t", storage) ffi.metatype("packet_header_t", packetHeader) return mod
local ffi = require "ffi" local packetLib = require "packet" local memory = require "memory" local qqlib = ffi.load("build/qq") ffi.cdef [[ typedef struct packet_header { uint64_t ts_vlan; uint16_t len; uint8_t data[]; } packet_header_t; typedef struct qq { } qq_t; void qq_init(); qq_t* qq_create(uint32_t storage_capacity); void qq_delete(qq_t*); size_t qq_size(qq_t*); size_t qq_capacity(qq_t*); typedef struct { } storage_t; storage_t* qq_storage_dequeue(qq_t*); storage_t* qq_storage_try_dequeue(qq_t*); storage_t* qq_storage_enqueue(qq_t*); storage_t* qq_storage_peek(qq_t*); size_t qq_get_enqueue_counter(qq_t*); size_t qq_get_dequeue_counter(qq_t*); void qq_set_priority(qq_t* q, const uint8_t new_priority); void qq_storage_release(storage_t*); size_t qq_storage_size(storage_t*); bool qq_storage_store(storage_t*, uint64_t ts, uint16_t vlan, uint16_t len, const uint8_t* data); const packet_header_t& qq_storage_get_packet(storage_t*, const size_t); uint64_t qq_packet_header_get_timestamp(const packet_header_t&); uint64_t qq_packet_header_get_vlan(const packet_header_t& h); uint16_t qq_packet_header_get_len(const packet_header_t& h); void* qq_packet_header_get_data(const packet_header_t& h); void dummy_enqueue(qq_t* q); void qq_inserter_loop(uint8_t device, uint16_t queue_id, qq_t* qq); ]] local C = ffi.C local mod = {} --- @param storageSize desired storage capacity in GiB function mod.createQQ(storageSize) qqlib.qq_init() -- idempotent return qqlib.qq_create(storageSize * 1024) end local qq = {} qq.__index = qq local storage = {} storage.__index = storage local packetHeader = {} packetHeader.__index = packetHeader function qq:delete() qqlib.qq_delete(self) end function qq:size() return tonumber(qqlib.qq_size(self)) end function qq:capacity() return tonumber(qqlib.qq_capacity(self)) end function qq:dequeue() return qqlib.qq_storage_dequeue(self) end function qq:tryDequeue() return qqlib.qq_storage_try_dequeue(self) end function qq:enqueue() return qqlib.qq_storage_enqueue(self) end function qq:peek() return qqlib.qq_storage_peek(self) end function qq:getEnqueueCounter() return qqlib.qq_get_enqueue_counter(self) end function qq:getDequeueCounter() return qqlib.qq_get_dequeue_counter(self) end function qq:setPriority(new_priority) return qqlib.qq_set_priority(self, new_priority) end function qq:dummy() qqlib.dummy_enqueue(self) end function storage:release() qqlib.qq_storage_release(self) end function storage:size() return tonumber(qqlib.qq_storage_size(self)) end function storage:store(ts, vlan, len, data) return qqlib.qq_storage_store(self, ts, vlan, len, data) end function storage:getPacket(idx) return qqlib.qq_storage_get_packet(self, idx) end local band, rshift, lshift = bit.band, bit.rshift, bit.lshift function packetHeader:getTimestamp() -- timestamp relative to libmoon.getTime(), i.e. the TSC in seconds return tonumber(band(self.ts_vlan, 0xffffffffffffULL)) / 10^6 end function packetHeader:getVlan() return rshift(self.ts_vlan, 48) end function packetHeader:getLength() return self.len end function packetHeader:getData() return ffi.cast("void*", self.data) end function packetHeader:dump() return packetLib.getEthernetPacket(self):resolveLastHeader():dump() end function packetHeader:clone() local pkt = memory.alloc("packet_header_t*", ffi.sizeof("packet_header_t") + self.len) pkt.ts_vlan = self.ts_vlan pkt.len = self.len ffi.copy(pkt.data, self.data, self.len) return pkt end function qq:inserterLoop(queue) qqlib.qq_inserter_loop(queue.id, queue.qid, self) end ffi.metatype("qq_t", qq) ffi.metatype("storage_t", storage) ffi.metatype("packet_header_t", packetHeader) return mod
Fix qq:capacity()
Fix qq:capacity()
Lua
mit
emmericp/FlowScope
bf3d8225af89583727fd914344a2a90e8e3d014c
lib/luvit.lua
lib/luvit.lua
-- clear some globals -- This will break lua code written for other lua runtimes _G.io = nil _G.os = nil _G.math = nil _G.string = nil _G.coroutine = nil _G.jit = nil _G.bit = nil _G.debug = nil _G.table = nil local loadfile = _G.loadfile _G.loadfile = nil local dofile = _G.dofile _G.dofile = nil _G.print = nil -- Load libraries used in this file local Debug = require('debug') local UV = require('uv') local Env = require('env') local Table = require('table') local Utils = require('utils') local FS = require('fs') local TTY = require('tty') local Emitter = require('emitter') local Constants = require('constants') local Path = require('path') process = Emitter.new() function process.exit(exit_code) process:emit('exit', exit_code) exit_process(exit_code or 0) end function process:add_handler_type(name) local code = Constants[name] if code then UV.activate_signal_handler(code) UV.unref() end end function process:missing_handler_type(name, ...) if name == "error" then error(...) elseif name == "SIGINT" or name == "SIGTERM" then process.exit() end end process.cwd = getcwd _G.getcwd = nil process.argv = argv _G.argv = nil local base_path = process.cwd() -- Hide some stuff behind a metatable local hidden = {} setmetatable(_G, {__index=function(table, key) if key == "__dirname" then local source = Debug.getinfo(2, "S").source if source:sub(1,1) == "@" then return Path.join(base_path, Path.dirname(source:sub(2))) end return elseif key == "__filename" then local source = Debug.getinfo(2, "S").source if source:sub(1,1) == "@" then return Path.join(base_path, source:sub(2)) end return else return hidden[key] end end}) local function hide(name) hidden[name] = _G[name] _G[name] = nil end hide("_G") hide("exit_process") -- Ignore sigpipe and exit cleanly on SIGINT and SIGTERM -- These shouldn't hold open the event loop UV.activate_signal_handler(Constants.SIGPIPE) UV.unref() UV.activate_signal_handler(Constants.SIGINT) UV.unref() UV.activate_signal_handler(Constants.SIGTERM) UV.unref() -- Load the tty as a pair of pipes -- But don't hold the event loop open for them process.stdin = TTY.new(0) UV.unref() process.stdout = TTY.new(1) UV.unref() local stdout = process.stdout -- Replace print function print(...) local n = select('#', ...) local arguments = { ... } for i = 1, n do arguments[i] = tostring(arguments[i]) end stdout:write(Table.concat(arguments, "\t") .. "\n") end -- A nice global data dumper function p(...) local n = select('#', ...) local arguments = { ... } for i = 1, n do arguments[i] = Utils.dump(arguments[i]) end stdout:write(Table.concat(arguments, "\t") .. "\n") end -- Add global access to the environment variables using a dynamic table process.env = setmetatable({}, { __pairs = function (table) local keys = Env.keys() local index = 0 return function (...) index = index + 1 local name = keys[index] if name then return name, table[name] end end end, __index = function (table, name) return Env.get(name) end, __newindex = function (table, name, value) if value then Env.set(name, value, 1) else Env.unset(name) end end }) -- This is called by all the event sources from C -- The user can override it to hook into event sources function event_source(name, fn, ...) local args = {...} return assert(xpcall(function () return fn(unpack(args)) end, Debug.traceback)) end -- tries to load a module at a specified absolute path -- TODO: make these error messages a little prettier local function load_module(path) local errors = {} local cname = "luaopen_" .. Path.basename(path) local fn, error_message -- Try the exact match first fn, error_message = loadfile(path) if fn then return fn end errors[#errors + 1] = "\n\t" .. error_message -- Then try with lua appended fn, error_message = loadfile(path .. ".lua") if fn then return fn end errors[#errors + 1] = "\n\t" .. error_message -- Then try C addon with luvit appended fn, error_message = package.loadlib(path .. ".luvit", cname) if fn then return fn end errors[#errors + 1] = "\n\t" .. error_message -- Then Try a folder with init.lua in it fn, error_message = loadfile(path .. "/init.lua") if fn then return fn end errors[#errors + 1] = "\n\t" .. error_message -- Finally try the same for a C addon fn, error_message = package.loadlib(path .. "/init.luvit", cname) if fn then return fn end errors[#errors + 1] = "\n\t" .. error_message return Table.concat(errors, "") end -- Remove the cwd based loaders, we don't want them package.loaders[2] = nil package.loaders[3] = nil package.loaders[4] = nil package.path = nil package.cpath = nil package.searchpath = nil package.seeall = nil package.config = nil _G.module = nil -- Write our own loader that does proper relative requires of both lua scripts -- and binary addons package.loaders[2] = function (path) local errors = {} local first = path:sub(1, 1) -- Relative requires if first == "." then local source = Debug.getinfo(3, "S").source if not source:sub(1, 1) == "@" then path = Path.join(base_path, path) else path = Path.join(base_path, Path.dirname(source:sub(2)), path) end local fn, error_message = load_module(path) return fn, error_message end error("TODO: Implement the rest of the load path styles") end -- Load the file given or start the interactive repl if process.argv[1] then dofile(process.argv[1]) else require('repl') end -- Start the event loop UV.run() -- trigger exit handlers and exit cleanly process.exit(0)
-- clear some globals -- This will break lua code written for other lua runtimes _G.io = nil _G.os = nil _G.math = nil _G.string = nil _G.coroutine = nil _G.jit = nil _G.bit = nil _G.debug = nil _G.table = nil local loadfile = _G.loadfile _G.loadfile = nil local dofile = _G.dofile _G.dofile = nil _G.print = nil -- Load libraries used in this file local Debug = require('debug') local UV = require('uv') local Env = require('env') local Table = require('table') local Utils = require('utils') local FS = require('fs') local TTY = require('tty') local Emitter = require('emitter') local Constants = require('constants') local Path = require('path') process = Emitter.new() function process.exit(exit_code) process:emit('exit', exit_code) exit_process(exit_code or 0) end function process:add_handler_type(name) local code = Constants[name] if code then UV.activate_signal_handler(code) UV.unref() end end function process:missing_handler_type(name, ...) if name == "error" then error(...) elseif name == "SIGINT" or name == "SIGTERM" then process.exit() end end process.cwd = getcwd _G.getcwd = nil process.argv = argv _G.argv = nil local base_path = process.cwd() -- Hide some stuff behind a metatable local hidden = {} setmetatable(_G, {__index=function(table, key) if key == "__dirname" then local source = Debug.getinfo(2, "S").source if source:sub(1,1) == "@" then return Path.join(base_path, Path.dirname(source:sub(2))) end return elseif key == "__filename" then local source = Debug.getinfo(2, "S").source if source:sub(1,1) == "@" then return Path.join(base_path, source:sub(2)) end return else return hidden[key] end end}) local function hide(name) hidden[name] = _G[name] _G[name] = nil end hide("_G") hide("exit_process") -- Ignore sigpipe and exit cleanly on SIGINT and SIGTERM -- These shouldn't hold open the event loop UV.activate_signal_handler(Constants.SIGPIPE) UV.unref() UV.activate_signal_handler(Constants.SIGINT) UV.unref() UV.activate_signal_handler(Constants.SIGTERM) UV.unref() -- Load the tty as a pair of pipes -- But don't hold the event loop open for them process.stdin = TTY.new(0) UV.unref() process.stdout = TTY.new(1) UV.unref() local stdout = process.stdout -- Replace print function print(...) local n = select('#', ...) local arguments = { ... } for i = 1, n do arguments[i] = tostring(arguments[i]) end stdout:write(Table.concat(arguments, "\t") .. "\n") end -- A nice global data dumper function p(...) local n = select('#', ...) local arguments = { ... } for i = 1, n do arguments[i] = Utils.dump(arguments[i]) end stdout:write(Table.concat(arguments, "\t") .. "\n") end -- Add global access to the environment variables using a dynamic table process.env = setmetatable({}, { __pairs = function (table) local keys = Env.keys() local index = 0 return function (...) index = index + 1 local name = keys[index] if name then return name, table[name] end end end, __index = function (table, name) return Env.get(name) end, __newindex = function (table, name, value) if value then Env.set(name, value, 1) else Env.unset(name) end end }) -- This is called by all the event sources from C -- The user can override it to hook into event sources function event_source(name, fn, ...) local args = {...} return assert(xpcall(function () return fn(unpack(args)) end, Debug.traceback)) end -- tries to load a module at a specified absolute path -- TODO: make these error messages a little prettier local function load_module(path) local errors = {} local cname = "luaopen_" .. Path.basename(path) local fn, error_message -- Try the exact match first fn, error_message = loadfile(path) if fn then return fn end errors[#errors + 1] = "\n\t" .. error_message -- Then try with lua appended fn, error_message = loadfile(path .. ".lua") if fn then return fn end errors[#errors + 1] = "\n\t" .. error_message -- Then try C addon with luvit appended fn, error_message = package.loadlib(path .. ".luvit", cname) if fn then return fn end errors[#errors + 1] = "\n\t" .. error_message -- Then Try a folder with init.lua in it fn, error_message = loadfile(path .. "/init.lua") if fn then return fn end errors[#errors + 1] = "\n\t" .. error_message -- Finally try the same for a C addon fn, error_message = package.loadlib(path .. "/init.luvit", cname) if fn then return fn end errors[#errors + 1] = "\n\t" .. error_message return Table.concat(errors, "") end -- Remove the cwd based loaders, we don't want them package.loaders[2] = nil package.loaders[3] = nil package.loaders[4] = nil package.path = nil package.cpath = nil package.searchpath = nil package.seeall = nil package.config = nil _G.module = nil -- Write our own loader that does proper relative requires of both lua scripts -- and binary addons package.loaders[2] = function (path) local first = path:sub(1, 1) -- Absolute requires if first == "/" then path = Path.normalize(path) return load_module(path) end -- Relative requires if first == "." then local source = Debug.getinfo(3, "S").source if not source:sub(1, 1) == "@" then path = Path.join(base_path, path) else path = Path.join(base_path, Path.dirname(source:sub(2)), path) end return load_module(path) end error("TODO: Implement 'module' folder style path search") end -- Load the file given or start the interactive repl if process.argv[1] then dofile(process.argv[1]) else require('repl') end -- Start the event loop UV.run() -- trigger exit handlers and exit cleanly process.exit(0)
Implement absolute requires, but is pending a fix to loadfile
Implement absolute requires, but is pending a fix to loadfile Change-Id: I77c76c1e2d788bf229a30eb30fd482477663b377
Lua
apache-2.0
sousoux/luvit,boundary/luvit,AndrewTsao/luvit,rjeli/luvit,GabrielNicolasAvellaneda/luvit-upstream,DBarney/luvit,DBarney/luvit,sousoux/luvit,bsn069/luvit,GabrielNicolasAvellaneda/luvit-upstream,AndrewTsao/luvit,luvit/luvit,GabrielNicolasAvellaneda/luvit-upstream,boundary/luvit,sousoux/luvit,connectFree/lev,sousoux/luvit,brimworks/luvit,GabrielNicolasAvellaneda/luvit-upstream,sousoux/luvit,zhaozg/luvit,kaustavha/luvit,sousoux/luvit,connectFree/lev,zhaozg/luvit,kaustavha/luvit,AndrewTsao/luvit,rjeli/luvit,boundary/luvit,bsn069/luvit,DBarney/luvit,bsn069/luvit,boundary/luvit,kaustavha/luvit,rjeli/luvit,boundary/luvit,DBarney/luvit,rjeli/luvit,boundary/luvit,luvit/luvit
1f026bb5a687411e5a4c9c0efb8130f50efa9b29
kong/api/routes/kong.lua
kong/api/routes/kong.lua
local singletons = require "kong.singletons" local conf_loader = require "kong.conf_loader" local cjson = require "cjson" local api_helpers = require "kong.api.api_helpers" local Schema = require "kong.db.schema" local Errors = require "kong.db.errors" local process = require "ngx.process" local kong = kong local knode = (kong and kong.node) and kong.node or require "kong.pdk.node".new() local errors = Errors.new() local tagline = "Welcome to " .. _KONG._NAME local version = _KONG._VERSION local lua_version = jit and jit.version or _VERSION local strip_foreign_schemas = function(fields) for _, field in ipairs(fields) do local fname = next(field) local fdata = field[fname] if fdata["type"] == "foreign" then fdata.schema = nil end end end return { ["/"] = { GET = function(self, dao, helpers) local distinct_plugins = setmetatable({}, cjson.array_mt) local pids = { master = process.get_master_pid() } do local set = {} for row, err in kong.db.plugins:each() do if err then kong.log.err(err) return kong.response.exit(500, { message = "An unexpected error happened" }) end if not set[row.name] then distinct_plugins[#distinct_plugins+1] = row.name set[row.name] = true end end end do local kong_shm = ngx.shared.kong local worker_count = ngx.worker.count() - 1 for i = 0, worker_count do local worker_pid, err = kong_shm:get("pids:" .. i) if not worker_pid then err = err or "not found" ngx.log(ngx.ERR, "could not get worker process id for worker #", i , ": ", err) else if not pids.workers then pids.workers = {} end pids.workers[i + 1] = worker_pid end end end local node_id, err = knode.get_id() if node_id == nil then ngx.log(ngx.ERR, "could not get node id: ", err) end return kong.response.exit(200, { tagline = tagline, version = version, hostname = knode.get_hostname(), node_id = node_id, timers = { running = ngx.timer.running_count(), pending = ngx.timer.pending_count() }, plugins = { available_on_server = singletons.configuration.loaded_plugins, enabled_in_cluster = distinct_plugins }, lua_version = lua_version, configuration = conf_loader.remove_sensitive(singletons.configuration), pids = pids, }) end }, ["/endpoints"] = { GET = function(self, dao, helpers) local endpoints = setmetatable({}, cjson.array_mt) local lapis_endpoints = require("kong.api").ordered_routes for k, v in pairs(lapis_endpoints) do if type(k) == "string" then -- skip numeric indices endpoints[#endpoints + 1] = k:gsub(":([^/:]+)", function(m) return "{" .. m .. "}" end) end end table.sort(endpoints, function(a, b) -- when sorting use lower-ascii char for "/" to enable segment based -- sorting, so not this: -- /a -- /ab -- /ab/a -- /a/z -- But this: -- /a -- /a/z -- /ab -- /ab/a return a:gsub("/", "\x00") < b:gsub("/", "\x00") end) return kong.response.exit(200, { data = endpoints }) end }, ["/schemas/:name"] = { GET = function(self, db, helpers) local entity = kong.db[self.params.name] local schema = entity and entity.schema or nil if not schema then return kong.response.exit(404, { message = "No entity named '" .. self.params.name .. "'" }) end local copy = api_helpers.schema_to_jsonable(schema) strip_foreign_schemas(copy.fields) return kong.response.exit(200, copy) end }, ["/schemas/:db_entity_name/validate"] = { POST = function(self, db, helpers) local db_entity_name = self.params.db_entity_name -- What happens when db_entity_name is a field name in the schema? self.params.db_entity_name = nil local entity = kong.db[db_entity_name] local schema = entity and entity.schema or nil if not schema then return kong.response.exit(404, { message = "No entity named '" .. db_entity_name .. "'" }) end local schema = assert(Schema.new(schema)) local _, err_t = schema:validate(schema:process_auto_fields( self.params, "insert")) if err_t then return kong.response.exit(400, errors:schema_violation(err_t)) end return kong.response.exit(200, { message = "schema validation successful" }) end }, ["/schemas/plugins/:name"] = { GET = function(self, db, helpers) local subschema = kong.db.plugins.schema.subschemas[self.params.name] if not subschema then return kong.response.exit(404, { message = "No plugin named '" .. self.params.name .. "'" }) end local copy = api_helpers.schema_to_jsonable(subschema) strip_foreign_schemas(copy.fields) return kong.response.exit(200, copy) end }, }
local singletons = require "kong.singletons" local conf_loader = require "kong.conf_loader" local cjson = require "cjson" local api_helpers = require "kong.api.api_helpers" local Schema = require "kong.db.schema" local Errors = require "kong.db.errors" local process = require "ngx.process" local kong = kong local knode = (kong and kong.node) and kong.node or require "kong.pdk.node".new() local errors = Errors.new() local tagline = "Welcome to " .. _KONG._NAME local version = _KONG._VERSION local lua_version = jit and jit.version or _VERSION local strip_foreign_schemas = function(fields) for _, field in ipairs(fields) do local fname = next(field) local fdata = field[fname] if fdata["type"] == "foreign" then fdata.schema = nil end end end local function validate_schema(db_entity_name, params) local entity = kong.db[db_entity_name] local schema = entity and entity.schema or nil if not schema then return kong.response.exit(404, { message = "No entity named '" .. db_entity_name .. "'" }) end local schema = assert(Schema.new(schema)) local _, err_t = schema:validate(schema:process_auto_fields(params, "insert")) if err_t then return kong.response.exit(400, errors:schema_violation(err_t)) end return kong.response.exit(200, { message = "schema validation successful" }) end return { ["/"] = { GET = function(self, dao, helpers) local distinct_plugins = setmetatable({}, cjson.array_mt) local pids = { master = process.get_master_pid() } do local set = {} for row, err in kong.db.plugins:each() do if err then kong.log.err(err) return kong.response.exit(500, { message = "An unexpected error happened" }) end if not set[row.name] then distinct_plugins[#distinct_plugins+1] = row.name set[row.name] = true end end end do local kong_shm = ngx.shared.kong local worker_count = ngx.worker.count() - 1 for i = 0, worker_count do local worker_pid, err = kong_shm:get("pids:" .. i) if not worker_pid then err = err or "not found" ngx.log(ngx.ERR, "could not get worker process id for worker #", i , ": ", err) else if not pids.workers then pids.workers = {} end pids.workers[i + 1] = worker_pid end end end local node_id, err = knode.get_id() if node_id == nil then ngx.log(ngx.ERR, "could not get node id: ", err) end return kong.response.exit(200, { tagline = tagline, version = version, hostname = knode.get_hostname(), node_id = node_id, timers = { running = ngx.timer.running_count(), pending = ngx.timer.pending_count() }, plugins = { available_on_server = singletons.configuration.loaded_plugins, enabled_in_cluster = distinct_plugins }, lua_version = lua_version, configuration = conf_loader.remove_sensitive(singletons.configuration), pids = pids, }) end }, ["/endpoints"] = { GET = function(self, dao, helpers) local endpoints = setmetatable({}, cjson.array_mt) local lapis_endpoints = require("kong.api").ordered_routes for k, v in pairs(lapis_endpoints) do if type(k) == "string" then -- skip numeric indices endpoints[#endpoints + 1] = k:gsub(":([^/:]+)", function(m) return "{" .. m .. "}" end) end end table.sort(endpoints, function(a, b) -- when sorting use lower-ascii char for "/" to enable segment based -- sorting, so not this: -- /a -- /ab -- /ab/a -- /a/z -- But this: -- /a -- /a/z -- /ab -- /ab/a return a:gsub("/", "\x00") < b:gsub("/", "\x00") end) return kong.response.exit(200, { data = endpoints }) end }, ["/schemas/:name"] = { GET = function(self, db, helpers) local entity = kong.db[self.params.name] local schema = entity and entity.schema or nil if not schema then return kong.response.exit(404, { message = "No entity named '" .. self.params.name .. "'" }) end local copy = api_helpers.schema_to_jsonable(schema) strip_foreign_schemas(copy.fields) return kong.response.exit(200, copy) end }, ["/schemas/plugins/validate"] = { POST = function(self, db, helpers) return validate_schema("plugins", self.params) end }, ["/schemas/:db_entity_name/validate"] = { POST = function(self, db, helpers) local db_entity_name = self.params.db_entity_name -- What happens when db_entity_name is a field name in the schema? self.params.db_entity_name = nil return validate_schema(db_entity_name, self.params) end }, ["/schemas/plugins/:name"] = { GET = function(self, db, helpers) local subschema = kong.db.plugins.schema.subschemas[self.params.name] if not subschema then return kong.response.exit(404, { message = "No plugin named '" .. self.params.name .. "'" }) end local copy = api_helpers.schema_to_jsonable(subschema) strip_foreign_schemas(copy.fields) return kong.response.exit(200, copy) end }, }
fix(api) ensure that /schemas/* apis are correctly prioritized
fix(api) ensure that /schemas/* apis are correctly prioritized ### Summary The api's there are not really well done and they have conflicting paths. As Lapis prioritizes plain matches more, this makes the priority more of expected, and this is what this commit does and fixes.
Lua
apache-2.0
Kong/kong,Kong/kong,Kong/kong
91b0f25735b8b29526e2a71168a7578c5532c1e3
mods/soundset/init.lua
mods/soundset/init.lua
minetest.log("action","[mod soundset] Loading...") sounds = {} sounds.file = minetest.get_worldpath() .. "/sounds_config.txt" sounds.gainplayers = {} sounds.tmp = {} local function save_sounds_config() local input = io.open(sounds.file, "w") if input then input:write(minetest.serialize(sounds.gainplayers)) input:close() else minetest.log("action","echec d'ouverture (mode:w) de " .. sounds.file) end end local function load_sounds_config() local file = io.open(sounds.file, "r") if file then sounds.gainplayers = minetest.deserialize(file:read("*all")) file:close() end print("type: "..tostring(type(sounds.gainplayers))) if sounds.gainplayers == nil or type(sounds.gainplayers) ~= "table" then sounds.gainplayers = {} end end load_sounds_config() sounds.set_sound = function(name, param) if param == "" then minetest.chat_send_player(name, "/setsound <music|ambience|mobs|other> <number>") return end local param_name, param_value = param:match("^(%S+)%s(%S+)$") if param_name == nil or param_value == nil then minetest.chat_send_player(name, "invalid param, /setsound <music|ambience|mobs|other> <number>") return end if param_name ~= "music" and param_name ~= "ambience" and param_name ~= "mobs" and param_name ~= "other" then minetest.chat_send_player(name, "invalid param " .. param_name) return end local value = tonumber(param_value) if value == nil then minetest.chat_send_player(name, "invalid value, " ..param_value .. " must be number") return end if value < 0 then value = 0 elseif value > 100 then value = 100 end if sounds.gainplayers[name][param_name] == value then minetest.chat_send_player(name, "volume " .. param_name .. " already set to " .. value) return end sounds.gainplayers[name][param_name] = value minetest.chat_send_player(name, "sound " .. param_name .. " set to " .. value) save_sounds_config() end sounds.get_gain = function(name, sound_type) if name == nil or name == "" then return 1 end local gain = sounds.gainplayers[name][sound_type] if gain == nil then return 1 end return gain/50 end local formspec = "size[6,6]".. "label[2,0;Sound Menu]".. "label[0.3,1.2;MUSIC]".. "image_button[1.6,1;1,1;soundset_dec.png;vmusic;-]".. "label[2.7,1.2;%s]".. "image_button[3.5,1;1,1;soundset_inc.png;vmusic;+]".. "label[0,2.2;AMBIENCE]".. "image_button[1.6,2;1,1;soundset_dec.png;vambience;-]".. "label[2.7,2.2;%s]".. "image_button[3.5,2;1,1;soundset_inc.png;vambience;+]".. "button_exit[0.5,5.2;1.5,1;abort;Abort]".. "button_exit[4,5.2;1.5,1;abort;Ok]" local on_show_settings = function(name, music, ambience) if not sounds.tmp[name] then sounds.tmp[name] = {} end sounds.tmp[name]["music"] = music sounds.tmp[name]["ambience"] = ambience minetest.show_formspec( name, "soundset:settings", string.format(formspec, tostring(music), tostring(ambience) )) end minetest.register_on_player_receive_fields(function(player, formname, fields) if formname == "soundset:settings" then local name = player:get_player_name() local fmusic = sounds.tmp[name]["music"] local fambience = sounds.tmp[name]["ambience"] if fields["abort"] == "Ok" then if sounds.gainplayers[name]["music"] ~= fmusic or sounds.gainplayers[name]["ambience"] ~= fambience then sounds.gainplayers[name]["music"] = fmusic sounds.gainplayers[name]["ambience"] = fambience save_sounds_config() end sounds.tmp[name] = nil return elseif fields["abort"] == "Abort" then sounds.tmp[name] = nil return elseif fields["vmusic"] == "+" then if fmusic < 100 then fmusic = fmusic +5 if fmusic > 100 then fmusic = 100 end end elseif fields["vmusic"] == "-" then if fmusic > 0 then fmusic = fmusic -5 if fmusic < 0 then fmusic = 0 end end elseif fields["vambience"] == "+" then if fambience < 100 then fambience = fambience +5 if fambience > 100 then fambience = 100 end end elseif fields["vambience"] == "-" then if fambience > 0 then fambience = fambience -5 if fambience < 0 then fambience = 0 end end elseif fields["quit"] == "true" then sounds.tmp[name] = nil return else return end on_show_settings(name, fmusic, fambience) end end) if (minetest.get_modpath("unified_inventory")) then unified_inventory.register_button("menu_soundset", { type = "image", image = "soundset_menu_icon.png", tooltip = "sounds menu ", action = function(player) local name = player:get_player_name() on_show_settings(name, sounds.gainplayers[name]["music"], sounds.gainplayers[name]["ambience"]) end, }) end minetest.register_chatcommand("soundset", { params = "", description = "Display volume menu formspec", privs = {interact=true}, func = function(name, param) on_show_settings(name, sounds.gainplayers[name]["music"], sounds.gainplayers[name]["ambience"]) end }) minetest.register_chatcommand("soundsets", { params = "<music|ambience|mobs|other> <number>", description = "Set volume sound <music|ambience|mobs|other>", privs = {interact=true}, func = sounds.set_sound, }) minetest.register_chatcommand("soundsetg", { params = "", description = "Display volume sound <music|ambience|mobs|other>", privs = {interact=true}, func = function(name, param) local conf = "" for k, v in pairs(sounds.gainplayers[name]) do conf = conf .. " " .. k .. ":" .. v end minetest.chat_send_player(name, "sounds conf " .. conf) minetest.log("action","Player ".. name .. " sound conf " .. conf) end }) minetest.register_on_joinplayer(function(player) local name = player:get_player_name() if sounds.gainplayers[name] == nil then sounds.gainplayers[name] = { ["music"] = 50, ["ambience"] = 50, ["mobs"] = 50, ["other"] = 50 } end end) minetest.log("action","[mod soundset] Loaded")
minetest.log("action","[mod soundset] Loading...") sounds = {} sounds.file = minetest.get_worldpath() .. "/sounds_config.txt" sounds.gainplayers = {} sounds.tmp = {} local function save_sounds_config() local input = io.open(sounds.file, "w") if input then input:write(minetest.serialize(sounds.gainplayers)) input:close() else minetest.log("action","echec d'ouverture (mode:w) de " .. sounds.file) end end local function load_sounds_config() local file = io.open(sounds.file, "r") if file then sounds.gainplayers = minetest.deserialize(file:read("*all")) file:close() end if sounds.gainplayers == nil or type(sounds.gainplayers) ~= "table" then sounds.gainplayers = {} end end load_sounds_config() sounds.set_sound = function(name, param) if param == "" then minetest.chat_send_player(name, "/setsound <music|ambience|mobs|other> <number>") return end local param_name, param_value = param:match("^(%S+)%s(%S+)$") if param_name == nil or param_value == nil then minetest.chat_send_player(name, "invalid param, /setsound <music|ambience|mobs|other> <number>") return end if param_name ~= "music" and param_name ~= "ambience" and param_name ~= "mobs" and param_name ~= "other" then minetest.chat_send_player(name, "invalid param " .. param_name) return end local value = tonumber(param_value) if value == nil then minetest.chat_send_player(name, "invalid value, " ..param_value .. " must be number") return end if value < 0 then value = 0 elseif value > 100 then value = 100 end if sounds.gainplayers[name][param_name] == value then minetest.chat_send_player(name, "volume " .. param_name .. " already set to " .. value) return end sounds.gainplayers[name][param_name] = value minetest.chat_send_player(name, "sound " .. param_name .. " set to " .. value) save_sounds_config() end sounds.get_gain = function(name, sound_type) if name == nil or name == "" then return 1 end local gain = sounds.gainplayers[name][sound_type] if gain == nil then return 1 end return gain/50 end local formspec = "size[6,6]".. "label[2,0;Sound Menu]".. "label[0.3,1.2;MUSIC]".. "image_button[1.6,1;1,1;soundset_dec.png;vmusic;-]".. "label[2.7,1.2;%s]".. "image_button[3.5,1;1,1;soundset_inc.png;vmusic;+]".. "label[0,2.2;AMBIENCE]".. "image_button[1.6,2;1,1;soundset_dec.png;vambience;-]".. "label[2.7,2.2;%s]".. "image_button[3.5,2;1,1;soundset_inc.png;vambience;+]".. "button_exit[0.5,5.2;1.5,1;abort;Abort]".. "button_exit[4,5.2;1.5,1;abort;Ok]" local on_show_settings = function(name, music, ambience) if not sounds.tmp[name] then sounds.tmp[name] = {} end sounds.tmp[name]["music"] = music sounds.tmp[name]["ambience"] = ambience minetest.show_formspec( name, "soundset:settings", string.format(formspec, tostring(music), tostring(ambience) )) end minetest.register_on_player_receive_fields(function(player, formname, fields) if formname == "soundset:settings" then local name = player:get_player_name() if not name then return end local fmusic = sounds.tmp[name]["music"] local fambience = sounds.tmp[name]["ambience"] if fields["abort"] == "Ok" then if sounds.gainplayers[name]["music"] ~= fmusic or sounds.gainplayers[name]["ambience"] ~= fambience then sounds.gainplayers[name]["music"] = fmusic sounds.gainplayers[name]["ambience"] = fambience save_sounds_config() end sounds.tmp[name] = nil return elseif fields["abort"] == "Abort" then sounds.tmp[name] = nil return elseif fields["vmusic"] == "+" then if fmusic < 100 then fmusic = fmusic +5 if fmusic > 100 then fmusic = 100 end end elseif fields["vmusic"] == "-" then if fmusic > 0 then fmusic = fmusic -5 if fmusic < 0 then fmusic = 0 end end elseif fields["vambience"] == "+" then if fambience < 100 then fambience = fambience +5 if fambience > 100 then fambience = 100 end end elseif fields["vambience"] == "-" then if fambience > 0 then fambience = fambience -5 if fambience < 0 then fambience = 0 end end elseif fields["quit"] == "true" then sounds.tmp[name] = nil return else return end on_show_settings(name, fmusic, fambience) end end) if (minetest.get_modpath("unified_inventory")) then unified_inventory.register_button("menu_soundset", { type = "image", image = "soundset_menu_icon.png", tooltip = "sounds menu ", action = function(player) local name = player:get_player_name() if not name then return end on_show_settings(name, sounds.gainplayers[name]["music"], sounds.gainplayers[name]["ambience"]) end, }) end minetest.register_chatcommand("soundset", { params = "", description = "Display volume menu formspec", privs = {interact=true}, func = function(name, param) if not name then return end on_show_settings(name, sounds.gainplayers[name]["music"], sounds.gainplayers[name]["ambience"]) end }) minetest.register_chatcommand("soundsets", { params = "<music|ambience|mobs|other> <number>", description = "Set volume sound <music|ambience|mobs|other>", privs = {interact=true}, func = sounds.set_sound, }) minetest.register_chatcommand("soundsetg", { params = "", description = "Display volume sound <music|ambience|mobs|other>", privs = {interact=true}, func = function(name, param) local conf = "" for k, v in pairs(sounds.gainplayers[name]) do conf = conf .. " " .. k .. ":" .. v end minetest.chat_send_player(name, "sounds conf " .. conf) minetest.log("action","Player ".. name .. " sound conf " .. conf) end }) minetest.register_on_joinplayer(function(player) local name = player:get_player_name() if sounds.gainplayers[name] == nil then sounds.gainplayers[name] = { ["music"] = 50, ["ambience"] = 50, ["mobs"] = 50, ["other"] = 50 } end end) minetest.log("action","[mod soundset] Loaded")
fix crash soundset fix crash soundset init.lua:111: attempt to index field '?'
fix crash soundset fix crash soundset init.lua:111: attempt to index field '?'
Lua
unlicense
MinetestForFun/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,paly2/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,crabman77/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,Coethium/server-minetestforfun,MinetestForFun/server-minetestforfun,crabman77/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,paly2/minetest-minetestforfun-server,Coethium/server-minetestforfun,Gael-de-Sailly/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,sys4-fr/server-minetestforfun,MinetestForFun/server-minetestforfun,sys4-fr/server-minetestforfun,Gael-de-Sailly/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,Coethium/server-minetestforfun
c759892d09b9ffa1c3c2d25d69d0324b34884b13
packages/rules.lua
packages/rules.lua
SILE.baseClass:loadPackage("raiselower") SILE.baseClass:loadPackage("rebox") SILE.registerCommand("hrule", function (options, _) local width = SU.cast("length", options.width) local height = SU.cast("length", options.height) local depth = SU.cast("length", options.depth) SILE.typesetter:pushHbox({ width = width:absolute(), height = height:absolute(), depth = depth:absolute(), value = options.src, outputYourself= function (self, typesetter, line) local outputWidth = SU.rationWidth(self.width, self.width, line.ratio) typesetter.frame:advancePageDirection(-self.height) local oldx = typesetter.frame.state.cursorX local oldy = typesetter.frame.state.cursorY typesetter.frame:advanceWritingDirection(outputWidth) typesetter.frame:advancePageDirection(self.height + self.depth) local newx = typesetter.frame.state.cursorX local newy = typesetter.frame.state.cursorY SILE.outputter:drawRule(oldx, oldy, newx - oldx, newy - oldy) end }) end, "Creates a line of width <width> and height <height>") SILE.registerCommand("fullrule", function (options, _) SILE.call("raise", { height = options.raise or "0.5em" }, function () SILE.call("hrule", { height = options.height or "0.2pt", width = options.width or "100%lw" }) end) end, "Draw a full width hrule centered on the current line") SILE.registerCommand("underline", function (_, content) local ot = SILE.require("core/opentype-parser") local fontoptions = SILE.font.loadDefaults({}) local face = SILE.font.cache(fontoptions, SILE.shaper.getFace) local font = ot.parseFont(face) local upem = font.head.unitsPerEm local underlinePosition = -font.post.underlinePosition / upem * fontoptions.size local underlineThickness = font.post.underlineThickness / upem * fontoptions.size local hbox = SILE.call("hbox", {}, content) table.remove(SILE.typesetter.state.nodes) -- steal it back... -- Re-wrap the hbox in another hbox responsible for boxing it at output -- time, when we will know the line contribution and can compute the scaled width -- of the box, taking into account possible stretching and shrinking. SILE.typesetter:pushHbox({ inner = hbox, width = hbox.width, height = hbox.height, depth = hbox.depth, outputYourself = function(self, typesetter, line) local oldX = typesetter.frame.state.cursorX local Y = typesetter.frame.state.cursorY -- Build the original hbox. -- Cursor will be moved by the actual definitive size. self.inner:outputYourself(SILE.typesetter, line) local newX = typesetter.frame.state.cursorX -- Output a line. -- NOTE: According to the OpenType specs, underlinePosition is "the suggested distance of -- the top of the underline from the baseline" so it seems implied that the thickness -- should expand downwards SILE.outputter:drawRule(oldX, Y + underlinePosition, newX - oldX, underlineThickness) end }) end, "Underlines some content") SILE.registerCommand("boxaround", function (_, content) -- This command was not documented and lacks feature. -- Plan replacement with a better suited package. SU.deprecated("\\boxaround (undocumented)", "\\framebox (package)", "0.12.0", "0.13.0") local hbox = SILE.call("hbox", {}, content) table.remove(SILE.typesetter.state.nodes) -- steal it back... -- Re-wrap the hbox in another hbox responsible for boxing it at output -- time, when we will know the line contribution and can compute the scaled width -- of the box, taking into account possible stretching and shrinking. SILE.typesetter:pushHbox({ inner = hbox, width = hbox.width, height = hbox.height, depth = hbox.depth, outputYourself = function(self, typesetter, line) local oldX = typesetter.frame.state.cursorX local Y = typesetter.frame.state.cursorY -- Build the original hbox. -- Cursor will be moved by the actual definitive size. self.inner:outputYourself(SILE.typesetter, line) local newX = typesetter.frame.state.cursorX -- Output a border -- NOTE: Drawn inside the hbox, so borders overlap with inner content. local w = newX - oldX local h = self.height:tonumber() local d = self.depth:tonumber() local thickness = 0.5 SILE.outputter:drawRule(oldX, Y + d - thickness, w, thickness) SILE.outputter:drawRule(oldX, Y - h, w, thickness) SILE.outputter:drawRule(oldX, Y - h, thickness, h + d) SILE.outputter:drawRule(oldX + w - thickness, Y - h, thickness, h + d) end }) end, "Draws a box around some content") return { documentation = [[\begin{document} The \autodoc:package{rules} package draws lines. It provides three commands. The first command is \autodoc:command{\hrule}, which draws a line of a given length and thickness, although it calls these \autodoc:parameter{width} and \autodoc:parameter{height}. (A box is just a square line.) Lines are treated just like other text to be output, and so can appear in the middle of a paragraph, like this: \hrule[width=20pt, height=0.5pt] (that one was generated with \autodoc:command{\hrule[width=20pt, height=0.5pt]}.) Like images, rules are placed along the baseline of a line of text. The second command provided by this package is \autodoc:command{\underline}, which underlines its contents. \note{ Underlining is horrible typographic practice, and you should \underline{never} do it.} (That was produced with \autodoc:command{\underline{never}}.) Finally, \autodoc:command{\fullrule} draws a thin line across the width of the current frame. \end{document}]] }
SILE.baseClass:loadPackage("raiselower") SILE.baseClass:loadPackage("rebox") SILE.registerCommand("hrule", function (options, _) local width = SU.cast("length", options.width) local height = SU.cast("length", options.height) local depth = SU.cast("length", options.depth) SILE.typesetter:pushHbox({ width = width:absolute(), height = height:absolute(), depth = depth:absolute(), value = options.src, outputYourself= function (self, typesetter, line) local outputWidth = SU.rationWidth(self.width, self.width, line.ratio) typesetter.frame:advancePageDirection(-self.height) local oldx = typesetter.frame.state.cursorX local oldy = typesetter.frame.state.cursorY typesetter.frame:advanceWritingDirection(outputWidth) typesetter.frame:advancePageDirection(self.height + self.depth) local newx = typesetter.frame.state.cursorX local newy = typesetter.frame.state.cursorY SILE.outputter:drawRule(oldx, oldy, newx - oldx, newy - oldy) typesetter.frame:advancePageDirection(-self.depth) end }) end, "Draws a blob of ink of width <width>, height <height> and depth <depth>") SILE.registerCommand("fullrule", function (options, _) SILE.call("raise", { height = options.raise or "0.5em" }, function () SILE.call("hrule", { height = options.height or "0.2pt", width = options.width or "100%lw" }) end) end, "Draw a full width hrule centered on the current line") SILE.registerCommand("underline", function (_, content) local ot = SILE.require("core/opentype-parser") local fontoptions = SILE.font.loadDefaults({}) local face = SILE.font.cache(fontoptions, SILE.shaper.getFace) local font = ot.parseFont(face) local upem = font.head.unitsPerEm local underlinePosition = -font.post.underlinePosition / upem * fontoptions.size local underlineThickness = font.post.underlineThickness / upem * fontoptions.size local hbox = SILE.call("hbox", {}, content) table.remove(SILE.typesetter.state.nodes) -- steal it back... -- Re-wrap the hbox in another hbox responsible for boxing it at output -- time, when we will know the line contribution and can compute the scaled width -- of the box, taking into account possible stretching and shrinking. SILE.typesetter:pushHbox({ inner = hbox, width = hbox.width, height = hbox.height, depth = hbox.depth, outputYourself = function(self, typesetter, line) local oldX = typesetter.frame.state.cursorX local Y = typesetter.frame.state.cursorY -- Build the original hbox. -- Cursor will be moved by the actual definitive size. self.inner:outputYourself(SILE.typesetter, line) local newX = typesetter.frame.state.cursorX -- Output a line. -- NOTE: According to the OpenType specs, underlinePosition is "the suggested distance of -- the top of the underline from the baseline" so it seems implied that the thickness -- should expand downwards SILE.outputter:drawRule(oldX, Y + underlinePosition, newX - oldX, underlineThickness) end }) end, "Underlines some content") SILE.registerCommand("boxaround", function (_, content) -- This command was not documented and lacks feature. -- Plan replacement with a better suited package. SU.deprecated("\\boxaround (undocumented)", "\\framebox (package)", "0.12.0", "0.13.0") local hbox = SILE.call("hbox", {}, content) table.remove(SILE.typesetter.state.nodes) -- steal it back... -- Re-wrap the hbox in another hbox responsible for boxing it at output -- time, when we will know the line contribution and can compute the scaled width -- of the box, taking into account possible stretching and shrinking. SILE.typesetter:pushHbox({ inner = hbox, width = hbox.width, height = hbox.height, depth = hbox.depth, outputYourself = function(self, typesetter, line) local oldX = typesetter.frame.state.cursorX local Y = typesetter.frame.state.cursorY -- Build the original hbox. -- Cursor will be moved by the actual definitive size. self.inner:outputYourself(SILE.typesetter, line) local newX = typesetter.frame.state.cursorX -- Output a border -- NOTE: Drawn inside the hbox, so borders overlap with inner content. local w = newX - oldX local h = self.height:tonumber() local d = self.depth:tonumber() local thickness = 0.5 SILE.outputter:drawRule(oldX, Y + d - thickness, w, thickness) SILE.outputter:drawRule(oldX, Y - h, w, thickness) SILE.outputter:drawRule(oldX, Y - h, thickness, h + d) SILE.outputter:drawRule(oldX + w - thickness, Y - h, thickness, h + d) end }) end, "Draws a box around some content") return { documentation = [[\begin{document} The \autodoc:package{rules} package draws lines. It provides three commands. The first command is \autodoc:command{\hrule}, which draws a blob of ink of a given \autodoc:parameter{width} (length), \autodoc:parameter{height} (above the current baseline) and \autodoc:parameter{depth} (below the current baseline). Such rules are horizontal boxes, placed along the baseline of a line of text and treated just like other text to be output. So, they can appear in the middle of a paragraph, like this: \hrule[width=20pt, height=0.5pt] (that one was generated with \autodoc:command{\hrule[width=20pt, height=0.5pt]}.) The second command provided by this package is \autodoc:command{\underline}, which underlines its contents. \note{ Underlining is horrible typographic practice, and you should \underline{never} do it.} (That was produced with \autodoc:command{\underline{never}}.) Finally, \autodoc:command{\fullrule} draws a thin line across the width of the current frame. \end{document}]] }
fix(packages): An hrule with depth shall not affect current baseline
fix(packages): An hrule with depth shall not affect current baseline
Lua
mit
alerque/sile,alerque/sile,alerque/sile,alerque/sile
13a754bdd946e5a200a0bc1f5f1fec24d21a1e42
modes/nomap/fs_rules.lua
modes/nomap/fs_rules.lua
-- Copyright (C) 2007 Lauri Leukkunen <[email protected]> -- Copyright (C) 2007 Nokia Corporation. -- Licensed under MIT license. -- "nomap" mapping mode: Does not map any paths anywhere, but still pushes -- all paths thru SB2's path mapping logic, handles execs, etc. -- -- This is useful for benchmarking, debugging (SB2's logs are available, if -- needed), and of course this makes SB2 fully symmetric because now SB2 -- can be used both for cross-compiling and for native builds! :-) ;-) -- -- Note that the target architecture should be set to host architecture -- while using this mode; usually a special "nomap" target should be created. -- Example: -- for 64-bit intel/amd architectures ("uname -m" displays "x86_64"): -- sb2-init -A amd64 -M x86_64 -n -m nomap nomap -- Next, use "sb2 -t nomap" to enter this mode (i.e. things usually go wrong -- if you try to use the the "-m" option to enter this mode, but the target -- is still something else than the host. The destination architecture is not -- selected by the mapping mode...) -- Rule file interface version, mandatory. -- rule_file_interface_version = "103" ---------------------------------- fs_mapping_rules = { -- Don't map. {prefix = "/", force_orig_path = true}, }
-- Copyright (C) 2007 Lauri Leukkunen <[email protected]> -- Copyright (C) 2007 Nokia Corporation. -- Licensed under MIT license. -- "nomap" mapping mode: Does not map any paths anywhere, but still pushes -- all paths thru SB2's path mapping logic, handles execs, etc. -- -- This is useful for benchmarking, debugging (SB2's logs are available, if -- needed), and of course this makes SB2 fully symmetric because now SB2 -- can be used both for cross-compiling and for native builds! :-) ;-) -- -- Note that the target architecture should be set to host architecture -- while using this mode; usually a special "nomap" target should be created. -- Example: -- for 64-bit intel/amd architectures ("uname -m" displays "x86_64"): -- sb2-init -A amd64 -M x86_64 -n -m nomap nomap -- Next, use "sb2 -t nomap" to enter this mode (i.e. things usually go wrong -- if you try to use the the "-m" option to enter this mode, but the target -- is still something else than the host. The destination architecture is not -- selected by the mapping mode...) -- Rule file interface version, mandatory. -- rule_file_interface_version = "103" ---------------------------------- fs_mapping_rules = { {prefix = "/sb2/wrappers", replace_by = session_dir .. "/wrappers." .. active_mapmode, protection = readonly_fs_always}, -- Don't map anything else. {prefix = "/", force_orig_path = true}, }
"nomap" mode: fixed handling of /sb2/wrappers
"nomap" mode: fixed handling of /sb2/wrappers - because the fakeroot wrapper is now enabled for "nomap", /sb2/wrappers must be mapped..
Lua
lgpl-2.1
OlegGirko/ldbox,ldbox/ldbox,OlegGirko/ldbox,h113331pp/scratchbox2,h113331pp/scratchbox2,ldbox/ldbox,OlegGirko/ldbox,h113331pp/scratchbox2,h113331pp/scratchbox2,OlegGirko/ldbox,ldbox/ldbox,ldbox/ldbox,OlegGirko/ldbox,h113331pp/scratchbox2,OlegGirko/ldbox,h113331pp/scratchbox2,ldbox/ldbox,ldbox/ldbox