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
|
---|---|---|---|---|---|---|---|---|---|
861d4c5db36310493c59d28435c7f51270fa084a
|
scen_edit/view/trigger/panels/position_panel.lua
|
scen_edit/view/trigger/panels/position_panel.lua
|
PositionPanel = AbstractTypePanel:extends{}
function PositionPanel:MakePredefinedOpt()
--PREDEFINED
local stackPositionPanel = MakeComponentPanel(self.parent)
self.cbPredefined = Checkbox:New {
caption = "Predefined position: ",
right = 100 + 10,
x = 1,
checked = false,
parent = stackPositionPanel,
}
table.insert(self.radioGroup, self.cbPredefined)
self.btnPredefined = Button:New {
caption = '...',
right = 40,
width = 60,
height = SB.conf.B_HEIGHT,
parent = stackPositionPanel,
position = nil,
}
self.OnSelectPosition = {
function(position)
self.btnPredefined.position = position
self.btnPredefined.caption = 'pos'
self.btnPredefined.tooltip = "(" .. tostring(position.x) .. ", " .. tostring(position.y) .. ", " .. tostring(position.z) .. ")"
self.btnPredefined:Invalidate()
if not self.cbPredefined.checked then
self.cbPredefined:Toggle()
end
end
}
self.btnPredefined.OnClick = {
function()
SB.stateManager:SetState(SelectPositionState(self.OnSelectPosition))
end
}
self.btnPredefinedZoom = Button:New {
caption = "",
right = 1,
width = SB.conf.B_HEIGHT,
height = SB.conf.B_HEIGHT,
parent = stackPositionPanel,
padding = {0, 0, 0, 0},
children = {
Image:New {
tooltip = "Select position",
file=SB_IMG_DIR .. "search.png",
height = SB.conf.B_HEIGHT,
width = SB.conf.B_HEIGHT,
padding = {0, 0, 0, 0},
margin = {0, 0, 0, 0},
},
},
OnClick = {
function()
local position = self.btnPredefined.position
if position ~= nil then
Spring.MarkerAddPoint(position.x, position.y, position.z, "")
end
end
}
}
end
function PositionPanel:UpdateModel(field)
if self.cbPredefined and self.cbPredefined.checked and self.btnPredefined.position ~= nil then
field.type = "pred"
field.value = self.btnPredefined.position
return true
elseif self.cbSpecialPosition and self.cbSpecialPosition.checked then
field.type = "spec"
field.name = self.cmbSpecialPosition.items[self.cmbSpecialPosition.selected]
return true
end
return self:super('UpdateModel', field)
end
function PositionPanel:UpdatePanel(field)
if field.type == "pred" then
if not self.cbPredefined.checked then
self.cbPredefined:Toggle()
end
self.OnSelectPosition(field.value)
return true
elseif field.type == "spec" then
if not self.cbSpecialPosition.checked then
self.cbSpecialPosition:Toggle()
end
self.cmbSpecialPosition:Select(1) --TODO:fix it
return true
end
return self:super('UpdatePanel', field)
end
|
PositionPanel = AbstractTypePanel:extends{}
function PositionPanel:MakePredefinedOpt()
--PREDEFINED
local stackPositionPanel = MakeComponentPanel(self.parent)
self.cbPredefined = Checkbox:New {
caption = "Predefined position: ",
right = 100 + 10,
x = 1,
checked = false,
parent = stackPositionPanel,
}
table.insert(self.radioGroup, self.cbPredefined)
self.btnPredefined = Button:New {
caption = '...',
right = 40,
width = 60,
height = SB.conf.B_HEIGHT,
parent = stackPositionPanel,
position = nil,
}
self.OnSelectPosition = function(position)
self.btnPredefined.position = position
self.btnPredefined.caption = 'pos'
self.btnPredefined.tooltip = "(" .. tostring(position.x) .. ", " .. tostring(position.y) .. ", " .. tostring(position.z) .. ")"
self.btnPredefined:Invalidate()
if not self.cbPredefined.checked then
self.cbPredefined:Toggle()
end
end
self.btnPredefined.OnClick = {
function()
SB.stateManager:SetState(SelectPositionState(self.OnSelectPosition))
end
}
self.btnPredefinedZoom = Button:New {
caption = "",
right = 1,
width = SB.conf.B_HEIGHT,
height = SB.conf.B_HEIGHT,
parent = stackPositionPanel,
padding = {0, 0, 0, 0},
children = {
Image:New {
tooltip = "Select position",
file=SB_IMG_DIR .. "search.png",
height = SB.conf.B_HEIGHT,
width = SB.conf.B_HEIGHT,
padding = {0, 0, 0, 0},
margin = {0, 0, 0, 0},
},
},
OnClick = {
function()
local position = self.btnPredefined.position
if position ~= nil then
Spring.MarkerAddPoint(position.x, position.y, position.z, "")
end
end
}
}
end
function PositionPanel:UpdateModel(field)
if self.cbPredefined and self.cbPredefined.checked and self.btnPredefined.position ~= nil then
field.type = "pred"
field.value = self.btnPredefined.position
return true
elseif self.cbSpecialPosition and self.cbSpecialPosition.checked then
field.type = "spec"
field.name = self.cmbSpecialPosition.items[self.cmbSpecialPosition.selected]
return true
end
return self:super('UpdateModel', field)
end
function PositionPanel:UpdatePanel(field)
if field.type == "pred" then
if not self.cbPredefined.checked then
self.cbPredefined:Toggle()
end
self.OnSelectPosition(field.value)
return true
elseif field.type == "spec" then
if not self.cbSpecialPosition.checked then
self.cbSpecialPosition:Toggle()
end
self.cmbSpecialPosition:Select(1) --TODO:fix it
return true
end
return self:super('UpdatePanel', field)
end
|
fix position panel
|
fix position panel
|
Lua
|
mit
|
Spring-SpringBoard/SpringBoard-Core,Spring-SpringBoard/SpringBoard-Core
|
fffa3984933e407e63dad0bec8eb068b1677202d
|
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
git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@6545 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
|
Lua
|
apache-2.0
|
saraedum/luci-packages-old,jschmidlapp/luci,Canaan-Creative/luci,zwhfly/openwrt-luci,dtaht/cerowrt-luci-3.3,saraedum/luci-packages-old,jschmidlapp/luci,dtaht/cerowrt-luci-3.3,yeewang/openwrt-luci,saraedum/luci-packages-old,zwhfly/openwrt-luci,jschmidlapp/luci,Canaan-Creative/luci,saraedum/luci-packages-old,Canaan-Creative/luci,ReclaimYourPrivacy/cloak-luci,Flexibity/luci,Flexibity/luci,phi-psi/luci,ThingMesh/openwrt-luci,Canaan-Creative/luci,eugenesan/openwrt-luci,Canaan-Creative/luci,Canaan-Creative/luci,Canaan-Creative/luci,gwlim/luci,ch3n2k/luci,Flexibity/luci,ThingMesh/openwrt-luci,freifunk-gluon/luci,jschmidlapp/luci,freifunk-gluon/luci,stephank/luci,stephank/luci,freifunk-gluon/luci,ReclaimYourPrivacy/cloak-luci,phi-psi/luci,zwhfly/openwrt-luci,zwhfly/openwrt-luci,vhpham80/luci,phi-psi/luci,stephank/luci,freifunk-gluon/luci,Flexibity/luci,phi-psi/luci,saraedum/luci-packages-old,stephank/luci,yeewang/openwrt-luci,ThingMesh/openwrt-luci,projectbismark/luci-bismark,yeewang/openwrt-luci,dtaht/cerowrt-luci-3.3,8devices/carambola2-luci,projectbismark/luci-bismark,projectbismark/luci-bismark,vhpham80/luci,stephank/luci,jschmidlapp/luci,phi-psi/luci,dtaht/cerowrt-luci-3.3,jschmidlapp/luci,projectbismark/luci-bismark,Flexibity/luci,jschmidlapp/luci,ch3n2k/luci,eugenesan/openwrt-luci,gwlim/luci,freifunk-gluon/luci,8devices/carambola2-luci,projectbismark/luci-bismark,zwhfly/openwrt-luci,ReclaimYourPrivacy/cloak-luci,freifunk-gluon/luci,gwlim/luci,ThingMesh/openwrt-luci,saraedum/luci-packages-old,phi-psi/luci,Canaan-Creative/luci,ch3n2k/luci,yeewang/openwrt-luci,yeewang/openwrt-luci,zwhfly/openwrt-luci,Flexibity/luci,eugenesan/openwrt-luci,ch3n2k/luci,yeewang/openwrt-luci,ThingMesh/openwrt-luci,dtaht/cerowrt-luci-3.3,vhpham80/luci,ReclaimYourPrivacy/cloak-luci,ReclaimYourPrivacy/cloak-luci,ReclaimYourPrivacy/cloak-luci,zwhfly/openwrt-luci,ThingMesh/openwrt-luci,ReclaimYourPrivacy/cloak-luci,stephank/luci,jschmidlapp/luci,ThingMesh/openwrt-luci,eugenesan/openwrt-luci,gwlim/luci,gwlim/luci,Flexibity/luci,vhpham80/luci,gwlim/luci,saraedum/luci-packages-old,dtaht/cerowrt-luci-3.3,projectbismark/luci-bismark,eugenesan/openwrt-luci,ch3n2k/luci,8devices/carambola2-luci,ReclaimYourPrivacy/cloak-luci,ch3n2k/luci,8devices/carambola2-luci,8devices/carambola2-luci,8devices/carambola2-luci,zwhfly/openwrt-luci,vhpham80/luci,8devices/carambola2-luci,gwlim/luci,eugenesan/openwrt-luci,freifunk-gluon/luci,eugenesan/openwrt-luci,projectbismark/luci-bismark,projectbismark/luci-bismark,phi-psi/luci,freifunk-gluon/luci,yeewang/openwrt-luci,ch3n2k/luci,vhpham80/luci,zwhfly/openwrt-luci,Flexibity/luci
|
c3d96600618add7768f713ccf1fcdddaf06dd1fb
|
share/lua/sd/appletrailers.lua
|
share/lua/sd/appletrailers.lua
|
--[[
$Id$
Copyright © 2010 VideoLAN and AUTHORS
Authors: Ilkka Ollakka <ileoo 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.
--]]
function descriptor()
return { title="Apple Trailers" }
end
function find( haystack, needle )
local _,_,r = string.find( haystack, needle )
return r
end
function main()
fd = vlc.stream( "http://trailers.apple.com/trailers/home/feeds/just_hd.json" )
if not fd then return nil end
options = {":http-user-agent=QuickTime/7.2",":demux=avformat,ffmpeg",":play-and-pause"}
line = fd:readline()
while line ~= nil
do
if string.match( line, "title" ) then
title = vlc.strings.resolve_xml_special_chars( find( line, "title\":\"(.-)\""))
art = find( line, "poster\":\"(.-)\"")
art = "http://trailers.apple.com"..art
url = find( line, "url\":\"(.-)\"")
playlist = vlc.stream( "http://trailers.apple.com"..url.."includes/playlists/web.inc" )
if not playlist then
vlc.msg.info("Didn't get playlist...")
end
node = vlc.sd.add_node( {title=title,arturl=art} )
playlistline = playlist:readline()
description =""
if not playlistline then vlc.msg.info("Empty playlists-file") end
while playlistline ~= nil
do
if string.match( playlistline, "class=\".-first" ) then
description = find( playlistline, "h%d.->(.-)</h%d")
end
if string.match( playlistline, "class=\"hd\".-\.mov") then
for urlline,resolution in string.gmatch(playlistline, "class=\"hd\".-href=\"(.-.mov)\".-(%d+.-p)") do
urlline = string.gsub( urlline, "_"..resolution, "_h"..resolution )
node:add_subitem( {path = urlline,
title=title.." "..description.." ("..resolution..")",
options=options, arturl=art })
end
end
playlistline = playlist:readline()
end
end
line = fd:readline()
end
end
|
--[[
$Id$
Copyright © 2010 VideoLAN and AUTHORS
Authors: Ilkka Ollakka <ileoo 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.
--]]
function descriptor()
return { title="Apple Trailers" }
end
function find( haystack, needle )
local _,_,r = string.find( haystack, needle )
return r
end
function main()
fd = vlc.stream( "http://trailers.apple.com/trailers/home/feeds/just_hd.json" )
if not fd then return nil end
options = {":http-user-agent=QuickTime/7.2",":demux=avformat,ffmpeg",":play-and-pause"}
line = fd:readline()
while line ~= nil
do
if string.match( line, "title" ) then
title = vlc.strings.resolve_xml_special_chars( find( line, "title\":\"(.-)\""))
art = find( line, "poster\":\"(.-)\"")
if string.match( art, "http://" ) then
else
art = "http://trailers.apple.com"..art
end
url = find( line, "location\":\"(.-)\"")
playlist = vlc.stream( "http://trailers.apple.com"..url.."includes/playlists/web.inc" )
if not playlist then
vlc.msg.info("Didn't get playlist...")
end
node = vlc.sd.add_node( {title=title,arturl=art} )
playlistline = playlist:readline()
description =""
if not playlistline then vlc.msg.info("Empty playlists-file") end
while playlistline ~= nil
do
if string.match( playlistline, "class=\".-first" ) then
description = find( playlistline, "h%d.->(.-)</h%d")
end
if string.match( playlistline, "class=\"hd\".-\.mov") then
for urlline,resolution in string.gmatch(playlistline, "class=\"hd\".-href=\"(.-.mov)\".-(%d+.-p)") do
urlline = string.gsub( urlline, "_"..resolution, "_h"..resolution )
node:add_subitem( {path = urlline,
title=title.." "..description.." ("..resolution..")",
options=options, arturl=art })
end
end
playlistline = playlist:readline()
end
end
line = fd:readline()
end
end
|
appletrailers: fix location finding
|
appletrailers: fix location finding
|
Lua
|
lgpl-2.1
|
shyamalschandra/vlc,vlc-mirror/vlc-2.1,xkfz007/vlc,vlc-mirror/vlc-2.1,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.1,jomanmuk/vlc-2.2,jomanmuk/vlc-2.2,jomanmuk/vlc-2.2,xkfz007/vlc,vlc-mirror/vlc-2.1,xkfz007/vlc,jomanmuk/vlc-2.2,jomanmuk/vlc-2.2,krichter722/vlc,shyamalschandra/vlc,jomanmuk/vlc-2.2,jomanmuk/vlc-2.1,krichter722/vlc,shyamalschandra/vlc,vlc-mirror/vlc,krichter722/vlc,vlc-mirror/vlc,jomanmuk/vlc-2.1,jomanmuk/vlc-2.1,jomanmuk/vlc-2.1,shyamalschandra/vlc,vlc-mirror/vlc,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.2,krichter722/vlc,xkfz007/vlc,vlc-mirror/vlc,vlc-mirror/vlc,vlc-mirror/vlc,xkfz007/vlc,jomanmuk/vlc-2.1,krichter722/vlc,vlc-mirror/vlc,shyamalschandra/vlc,shyamalschandra/vlc,xkfz007/vlc,krichter722/vlc,vlc-mirror/vlc-2.1,xkfz007/vlc,jomanmuk/vlc-2.1,shyamalschandra/vlc,krichter722/vlc,vlc-mirror/vlc-2.1
|
82980102afe6ae4a4aaae1252b48a1e33fbd8c9f
|
mod_register_json/mod_register_json.lua
|
mod_register_json/mod_register_json.lua
|
-- Expose a simple servlet to handle user registrations from web pages
-- via JSON.
--
-- A Good chunk of the code is from mod_data_access.lua by Kim Alvefur
-- aka Zash.
local usermanager = require "core.usermanager";
local b64_decode = require "util.encodings".base64.decode;
local json_decode = require "util.json".decode;
module.host = "*" -- HTTP/BOSH Servlets need to be global.
-- Pick up configuration.
local set_realm_name = module:get_option("reg_servlet_realm") or "Restricted";
local throttle_time = module:get_option("reg_servlet_ttime") or false;
local whitelist = module:get_option("reg_servlet_wl") or {};
local blacklist = module:get_option("reg_servlet_bl") or {};
local recent_ips = {};
-- Begin
for _, ip in ipairs(whitelist) do whitelisted_ips[ip] = true; end
for _, ip in ipairs(blacklist) do blacklisted_ips[ip] = true; end
local function http_response(code, message, extra_headers)
local response = {
status = code .. " " .. message;
body = message .. "\n"; }
if extra_headers then response.headers = extra_headers; end
return response
end
local function handle_req(method, body, request)
if request.method ~= "POST" then
return http_response(405, "Bad method...", {["Allow"] = "POST"});
end
if not request.headers["authorization"] then
return http_response(401, "No... No...",
{["WWW-Authenticate"]='Basic realm="'.. set_realm_name ..'"'})
end
local user, password = b64_decode(request.headers.authorization
:match("[^ ]*$") or ""):match("([^:]*):(.*)");
user = jid_prep(user);
if not user or not password then return http_response(400, "What's this..?"); end
local user_node, user_host = jid_split(user)
if not hosts[user_host] then return http_response(401, "Negative."); end
module:log("warn", "%s is authing to submit a new user registration data", user)
if not usermanager.test_password(user_node, user_host, password) then
module:log("warn", "%s failed authentication", user)
return http_response(401, "Who the hell are you?! Guards!");
end
local req_body; pcall(function() req_body = json.decode(body) end);
-- Check if user is an admin of said host
if not usermanager.is_admin(user, req_body["host"]) then
module:log("warn", "%s tried to submit registration data for %s but he's not an admin", user, req_body["host"])
return http_response(401, "I obey only to my masters... Have a nice day.");
else
-- Various sanity checks.
if req_body == nil then module:log("debug", "JSON data submitted for user registration by %s failed to Decode.", user); return http_response(400, "JSON Decoding failed."); end
-- Checks for both Throttling/Whitelist and Blacklist (basically copycatted from prosody's register.lua code)
if blacklist[req_body["ip"]] then module:log("warn", "Attempt of reg. submission to the JSON servlet from blacklisted address: %s", req_body["ip"]); return http_response(403, "The specified address is blacklisted, sorry sorry."); end
if throttle_time and not whitelist[req_body["ip"]] then
if not recent_ips[req_body["ip"]] then
recent_ips[req_body["ip"]] = { time = os_time(), count = 1 };
else
local ip = recent_ips[req_body["ip"]];
ip.count = ip.count + 1;
if os_time() - ip.time < throttle_time then
ip.time = os_time();
module:log("warn", "JSON Registration request from %s has been throttled.", req_body["ip"]);
return http_response(503, "Woah... How many users you want to register..? Request throttled, wait a bit and try again.");
end
ip.time = os_time();
end
end
-- We first check if the supplied username for registration is already there.
if not usermanager.user_exists(req_body["username"], req_body["host"]) then
usermanager.create_user(req_body["username"], req_body["password"], req_body["host"]);
module:log("debug", "%s registration data submission for %s is successful", user, req_body["user"]);
return http_response(200, "Done.");
else
module:log("debug", "%s registration data submission for %s failed (user already exists)", user, req_body["user"]);
return http_response(409, "User already exists.");
end
end
end
-- Set it up!
local function setup()
local ports = module:get_option("reg_servlet_port") or { 9280 };
local base_name = module:get_option("reg_servlet_base") or "register_account";
local ssl_cert = module:get_option("reg_servlet_sslcert") or false;
local ssl_key = module:get_option("reg_servlet_sslkey") or false;
if not ssl_cert or not ssl_key then
require "net.httpserver".new_from_config(ports, handle_req, { base = base_name });
else
if module:get_option("reg_servlet_port") == nil then ports = { 9443 }; end
require "net.httpserver".new_from_config(ports, handle_req, { ssl = { key = ssl_key, certificate = ssl_cert }, base = base_name });
end
end
if prosody.start_time then -- already started
setup();
else
prosody.events.add_handler("server-started", setup);
end
|
-- Expose a simple servlet to handle user registrations from web pages
-- via JSON.
--
-- A Good chunk of the code is from mod_data_access.lua by Kim Alvefur
-- aka Zash.
local jid_prep = require "util.jid".prep;
local jid_split = require "util.jid".split;
local usermanager = require "core.usermanager";
local b64_decode = require "util.encodings".base64.decode;
local json_decode = require "util.json".decode;
module.host = "*" -- HTTP/BOSH Servlets need to be global.
-- Pick up configuration.
local set_realm_name = module:get_option("reg_servlet_realm") or "Restricted";
local throttle_time = module:get_option("reg_servlet_ttime") or false;
local whitelist = module:get_option("reg_servlet_wl") or {};
local blacklist = module:get_option("reg_servlet_bl") or {};
local recent_ips = {};
-- Begin
for _, ip in ipairs(whitelist) do whitelisted_ips[ip] = true; end
for _, ip in ipairs(blacklist) do blacklisted_ips[ip] = true; end
local function http_response(code, message, extra_headers)
local response = {
status = code .. " " .. message;
body = message .. "\n"; }
if extra_headers then response.headers = extra_headers; end
return response
end
local function handle_req(method, body, request)
if request.method ~= "POST" then
return http_response(405, "Bad method...", {["Allow"] = "POST"});
end
if not request.headers["authorization"] then
return http_response(401, "No... No...",
{["WWW-Authenticate"]='Basic realm="'.. set_realm_name ..'"'})
end
local user, password = b64_decode(request.headers.authorization
:match("[^ ]*$") or ""):match("([^:]*):(.*)");
user = jid_prep(user);
if not user or not password then return http_response(400, "What's this..?"); end
local user_node, user_host = jid_split(user)
if not hosts[user_host] then return http_response(401, "Negative."); end
module:log("warn", "%s is authing to submit a new user registration data", user)
if not usermanager.test_password(user_node, user_host, password) then
module:log("warn", "%s failed authentication", user)
return http_response(401, "Who the hell are you?! Guards!");
end
local req_body;
-- We check that what we have is valid JSON wise else we throw an error...
if not pcall(function() req_body = json_decode(body) end) then
module:log("debug", "JSON data submitted for user registration by %s failed to Decode.", user);
return http_response(400, "JSON Decoding failed.");
else
-- Check if user is an admin of said host
if not usermanager.is_admin(user, req_body["host"]) then
module:log("warn", "%s tried to submit registration data for %s but he's not an admin", user, req_body["host"]);
return http_response(401, "I obey only to my masters... Have a nice day.");
else
-- Checks for both Throttling/Whitelist and Blacklist (basically copycatted from prosody's register.lua code)
if blacklist[req_body["ip"]] then then module:log("warn", "Attempt of reg. submission to the JSON servlet from blacklisted address: %s", req_body["ip"]); return http_response(403, "The specified address is blacklisted, sorry sorry."); end
if throttle_time and not whitelist[req_body["ip"]] then
if not recent_ips[req_body["ip"]] then
recent_ips[req_body["ip"]] = { time = os_time(), count = 1 };
else
local ip = recent_ips[req_body["ip"]];
ip.count = ip.count + 1;
if os_time() - ip.time < throttle_time then
ip.time = os_time();
module:log("warn", "JSON Registration request from %s has been throttled.", req_body["ip"]);
return http_response(503, "Woah... How many users you want to register..? Request throttled, wait a bit and try again.");
end
ip.time = os_time();
end
end
-- We first check if the supplied username for registration is already there.
if not usermanager.user_exists(req_body["username"], req_body["host"]) then
usermanager.create_user(req_body["username"], req_body["password"], req_body["host"]);
module:log("debug", "%s registration data submission for %s is successful", user, req_body["user"]);
return http_response(200, "Done.");
else
module:log("debug", "%s registration data submission for %s failed (user already exists)", user, req_body["user"]);
return http_response(409, "User already exists.");
end
end
end
end
-- Set it up!
local function setup()
local ports = module:get_option("reg_servlet_port") or { 9280 };
local base_name = module:get_option("reg_servlet_base") or "register_account";
local ssl_cert = module:get_option("reg_servlet_sslcert") or false;
local ssl_key = module:get_option("reg_servlet_sslkey") or false;
if not ssl_cert or not ssl_key then
require "net.httpserver".new_from_config(ports, handle_req, { base = base_name });
else
if module:get_option("reg_servlet_port") == nil then ports = { 9443 }; end
require "net.httpserver".new_from_config(ports, handle_req, { ssl = { key = ssl_key, certificate = ssl_cert }, base = base_name });
end
end
if prosody.start_time then -- already started
setup();
else
prosody.events.add_handler("server-started", setup);
end
|
mod_register_json: Failed at JSON successful decode check, fixed with a code refactor.
|
mod_register_json: Failed at JSON successful decode check, fixed with a code refactor.
|
Lua
|
mit
|
prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2
|
8f8af0d8e8a4d7ca8ef93400417644b5e9fe865b
|
PluginsFolder/protoplug/include/core/script.lua
|
PluginsFolder/protoplug/include/core/script.lua
|
--- Use `script` to handle script-related events.
-- The `script` global is available to every protoplug script after including the
-- main protoplug header :
-- require "include/protoplug"
-- @module script
local script = {}
--- Add a handler for a script event.
-- The following events are available :
--
-- - `"init"` - Emitted after the script has been compiled and run.
-- - `"preClose"` - Emitted before the script state gets destroyed.
-- @see plugin.addHandler
-- @see gui.addHandler
-- @tparam string event the event to handle
-- @tparam function handler a function to add the event's handlers
function script.addHandler(event, handler)
if not script[event] then script[event] = {} end
table.insert(script[event], handler)
end
--- Save script data.
-- Override this function to save any custom data.
--
-- This gets called :
-- - when the host saves the plugin's state (eg. when saving a project)
-- - right before the script is recompiled, to keep custom data across compilations.
-- @treturn string the data to be saved
-- @function script.saveData
script_saveData = script.saveData
--- Load script data.
-- Override this function to load any custom data.
-- Be warned that the data might originate from another script, so it's a good
-- idea to start the data with a header confirming the format.
--
-- This gets called :
-- - when the host loads the plugin's state (eg. when loading a project)
-- - right after the script is recompiled, to keep custom data across compilations.
-- @tparam string data the data to be loaded
-- @function script.loadData
script_loadData = script.loadData
--- Load shared libraries.
-- Protoplug scripts should use this wrapper function instead of LuaJIT's
-- [ffi.load](http://luajit.org/ext_ffi_api.html#ffi_load).
-- It has the same behaviour as `ffi.load`, but it adds `protoplug/lib` as a
-- search path, and can accept multiple arguments to test for different
-- library names. The names are tested from left to right until one load
-- successfully. If none of them work, an error is raised.
-- sdl = script.ffiLoad("sdl")
-- This looks for `libsdl.so` or `sdl.dll` in protoplug's lib folder and
-- in the system paths.
--
-- fftw = script.ffiLoad("libfftw3.so.3", "libfftw3-3.dll")
-- This looks for the supplied names in the same locations as above. This is
-- necessary for libs like FFTW, that have has platform-dependent names.
-- @tparam string libName
-- @tparam[opt] string ... alternate names for the same library
-- @return The library's ffi namespace
-- @function script.ffiLoad
local function file_exists(name)
local f=io.open(name,"r")
if f~=nil then io.close(f) return true else return false end
end
local function tryLoad(lib)
if string.find(lib, "/") or string.find(lib, "\\") then
return ffi.load(lib)
end
local libfile = lib
if ffi.os=="Windows" then
if not string.find(lib, "%.") then
libfile = libfile..".dll"
end
else -- assuming posix
if not string.find(lib,"%.") then
libfile = libfile..".so"
end
if string.sub(lib, 1, 3) ~= "lib" then
libfile = "lib"..libfile
end
end
libfile = protoplug_dir.."/lib/"..libfile
if file_exists(libfile) then
return ffi.load(libfile)
end
local success, ret = pcall(ffi.load, lib)
if success then return ret end
end
function script.ffiLoad(...)
local args={...}
local ret
for _,lib in ipairs(args) do
ret = tryLoad(lib)
if ret then break end
end
return ret and ret or error("could not find library "..
table.concat({...}, ", "))
end
-- Wrap the raw global override called by protoplug
function script_init()
if script.preClose then
function script_preClose()
for _,v in ipairs(script.preClose) do
v()
end
end
end
if script.init then
for _,v in ipairs(script.init) do
v()
end
end
end
-- add handler to repaint gui after recompiling
script.addHandler("init", function ()
local gui = require "include/core/gui"
local guiComp = gui.getComponent()
if guiComp ~= nil then
guiComp:repaint()
end
end)
return script
|
--- Use `script` to handle script-related events.
-- The `script` global is available to every protoplug script after including the
-- main protoplug header :
-- require "include/protoplug"
-- @module script
local script = {}
--- Add a handler for a script event.
-- The following events are available :
--
-- - `"init"` - Emitted after the script has been compiled and run.
-- - `"preClose"` - Emitted before the script state gets destroyed.
-- @see plugin.addHandler
-- @see gui.addHandler
-- @tparam string event the event to handle
-- @tparam function handler a function to add the event's handlers
function script.addHandler(event, handler)
if not script[event] then script[event] = {} end
table.insert(script[event], handler)
end
--- Save script data.
-- Override this function to save any custom data.
--
-- This gets called :
-- - when the host saves the plugin's state (eg. when saving a project)
-- - right before the script is recompiled, to keep custom data across compilations.
-- @treturn string the data to be saved
-- @function script.saveData
--- Load script data.
-- Override this function to load any custom data.
-- Be warned that the data might originate from another script, so it's a good
-- idea to start the data with a header confirming the format.
--
-- This gets called :
-- - when the host loads the plugin's state (eg. when loading a project)
-- - right after the script is recompiled, to keep custom data across compilations.
-- @tparam string data the data to be loaded
-- @function script.loadData
--- Load shared libraries.
-- Protoplug scripts should use this wrapper function instead of LuaJIT's
-- [ffi.load](http://luajit.org/ext_ffi_api.html#ffi_load).
-- It has the same behaviour as `ffi.load`, but it adds `protoplug/lib` as a
-- search path, and can accept multiple arguments to test for different
-- library names. The names are tested from left to right until one load
-- successfully. If none of them work, an error is raised.
-- sdl = script.ffiLoad("sdl")
-- This looks for `libsdl.so` or `sdl.dll` in protoplug's lib folder and
-- in the system paths.
--
-- fftw = script.ffiLoad("libfftw3.so.3", "libfftw3-3.dll")
-- This looks for the supplied names in the same locations as above. This is
-- necessary for libs like FFTW, that have has platform-dependent names.
-- @tparam string libName
-- @tparam[opt] string ... alternate names for the same library
-- @return The library's ffi namespace
-- @function script.ffiLoad
local function file_exists(name)
local f=io.open(name,"r")
if f~=nil then io.close(f) return true else return false end
end
local function tryLoad(lib)
if string.find(lib, "/") or string.find(lib, "\\") then
return ffi.load(lib)
end
local libfile = lib
if ffi.os=="Windows" then
if not string.find(lib, "%.") then
libfile = libfile..".dll"
end
else -- assuming posix
if not string.find(lib,"%.") then
libfile = libfile..".so"
end
if string.sub(lib, 1, 3) ~= "lib" then
libfile = "lib"..libfile
end
end
libfile = protoplug_dir.."/lib/"..libfile
if file_exists(libfile) then
return ffi.load(libfile)
end
local success, ret = pcall(ffi.load, lib)
if success then return ret end
end
function script.ffiLoad(...)
local args={...}
local ret
for _,lib in ipairs(args) do
ret = tryLoad(lib)
if ret then break end
end
return ret and ret or error("could not find library "..
table.concat({...}, ", "))
end
-- Wrap the raw global override called by protoplug
function script_init()
if script.preClose then
function script_preClose()
for _,v in ipairs(script.preClose) do
v()
end
end
end
if script.init then
for _,v in ipairs(script.init) do
v()
end
end
script_saveData = script.saveData
script_loadData = script.loadData
end
-- add handler to repaint gui after recompiling
script.addHandler("init", function ()
local gui = require "include/core/gui"
local guiComp = gui.getComponent()
if guiComp ~= nil then
guiComp:repaint()
end
end)
return script
|
fixed script.saveData / loadData
|
fixed script.saveData / loadData
|
Lua
|
mit
|
JTriggerFish/protoplug,JTriggerFish/protoplug,JTriggerFish/protoplug,JTriggerFish/protoplug,JTriggerFish/protoplug,JTriggerFish/protoplug
|
d5d28e9660697d156d2793e8387a9ca4e3d1a282
|
src_trunk/resources/job-system/fishing/s_fishing_job.lua
|
src_trunk/resources/job-system/fishing/s_fishing_job.lua
|
local totalCatch = 0
local fishSize = 0
-- /fish to start fishing.
function startFishing(thePlayer)
local element = getPedContactElement(thePlayer)
if not (isElement(element)) then
outputChatBox("You must be on a boat to fish.", thePlayer, 255, 0, 0)
else
if not (getElementType(element)=="vehicle") then
outputChatBox("You must be on a boat to fish.", thePlayer, 255, 0, 0)
else
if not (getVehicleType(element)=="Boat") then
outputChatBox("You must be on a boat to fish.", thePlayer, 255, 0, 0)
else
local x, y, z = getElementPosition(thePlayer)
if (x < 3000) or (y > 4000) then -- the further out to sea you go the bigger the fish you will catch.
outputChatBox("You must be out at sea to fish.", thePlayer, 255, 0, 0)
else
if not(exports.global:doesPlayerHaveItem(thePlayer, 49)) then -- does the player have the fishing rod item?
outputChatBox("You need a fishing rod to fish.", thePlayer, 255, 0, 0)
else
if (catchTimer) then -- Are they already fishing?
outputChatBox("You have already cast your line. Wait for a fish to bite.", thePlayer, 255, 0, 0)
else
if (totalCatch >= 2000) then
outputChatBox("#FF9933The boat can't hold any more fish. #FF66CCSell#FF9933 the fish you have caught before continuing.", thePlayer, 255, 104, 91, true)
else
local biteTimer = math.random(60000,300000)
--catchTimer = setTimer( theyHaveABite, biteTimer, 1, thePlayer) -- A fish will bite within 1 and 5 minutes.
catchTimer = setTimer( theyHaveABite, 10000, 1, thePlayer)
exports.global:sendLocalMeAction(thePlayer,"casts a fishing line.")
if not (colsphere) then -- If the /sellfish marker isnt already being shown...
blip = createBlip( 2243.7339, 578.905, 6.78, 0, 2, 255, 0, 255, 255 )
marker = createMarker( 2243.7339, 578.905, 6.78, "cylinder", 2, 255, 0, 255, 150 )
colsphere = createColSphere (2243.7339, 578.905, 6.78, 3)
exports.pool:allocateElement(blip)
exports.pool:allocateElement(marker)
exports.pool:allocateElement(colsphere)
setElementVisibleTo(blip, getRootElement(), false)
setElementVisibleTo(blip, thePlayer, true)
setElementVisibleTo(marker, getRootElement(), false)
setElementVisibleTo(marker, thePlayer, true)
outputChatBox("#FF9933When you are done fishing you can sell your catch at the fish market ((#FF66CCblip#FF9933 added to radar)).", thePlayer, 255, 104, 91, true)
outputChatBox("#FF9933((/totalcatch to see how much you have caught. To sell your catch enter /sellfish in the #FF66CCmarker#FF9933.))", thePlayer, 255, 104, 91, true)
end
end
end
end
end
end
end
end
end
addCommandHandler("fish", startFishing, false, false)
addEvent("fish")
addEventHandler("fish", getRootElement(), startFishing)
------ triggers the mini game.
function theyHaveABite(source)
killTimer(catchTimer)
catchTimer=nil
triggerClientEvent("createReel", source)
exports.global:sendLocalMeAction(source,"has a bite!")
end
----- Snapped line.
function lineSnap()
exports.global:takePlayerItem(source, 49, 1) -- fishing rod
exports.global:sendLocalMeAction(source,"snaps their fishing line.")
outputChatBox("The monster of a fish has broken your line. You need to buy a new fishing rod to continue fishing.", source, 255, 0, 0)
end
addEvent("lineSnap",true)
addEventHandler("lineSnap", getRootElement(), lineSnap)
----- Successfully reeled in the fish.
function catchFish(fishSize)
exports.global:sendLocalMeAction(source,"catches a fish weighing ".. fishSize .."lbs.")
totalCatch = math.floor(totalCatch + fishSize)
outputChatBox("You have caught "..totalCatch.."lbs of fish so far.", source, 255, 194, 14)
if (fishSize >= 100) then
exports.global:givePlayerAchievement(source, 35)
end
end
addEvent("catchFish", true)
addEventHandler("catchFish", getRootElement(), catchFish)
------ /totalcatch command
function currentCatch(thePlayer)
outputChatBox("You have "..totalCatch.."lbs of fish caught so far.", thePlayer, 255, 194, 14)
end
addCommandHandler("totalcatch", currentCatch, false, false)
------ /sellfish
function unloadCatch(thePlayer)
if (isElementWithinColShape(thePlayer, colsphere)) then
if (totalCatch == 0) then
outputChatBox("You need to catch some fish to sell first." ,thePlayer, 255, 0, 0)
else
local profit = math.floor(totalCatch/2)
exports.global:sendLocalMeAction(thePlayer,"sells " .. totalCatch .."lbs of fish.")
exports.global:givePlayerSafeMoney(thePlayer, profit)
outputChatBox("You made $".. profit .." from the fish you caught." ,thePlayer, 255, 104, 91)
totalCatch = 0
destroyElement(blip)
destroyElement(marker)
destroyElement(colsphere)
blip=nil
marker=nil
colsphere=nil
end
else
outputChatBox("You need to be at the fish market to sell your catch.", thePlayer, 255, 0, 0)
end
end
addCommandHandler("sellFish", unloadCatch, false, false)
|
local totalCatch = 0
local fishSize = 0
-- /fish to start fishing.
function startFishing(thePlayer)
local element = getPedContactElement(thePlayer)
if not (thePlayer) then thePlayer = source end
if not (isElement(element)) then
outputChatBox("You must be on a boat to fish.", thePlayer, 255, 0, 0)
else
if not (getElementType(element)=="vehicle") then
outputChatBox("You must be on a boat to fish.", thePlayer, 255, 0, 0)
else
if not (getVehicleType(element)=="Boat") then
outputChatBox("You must be on a boat to fish.", thePlayer, 255, 0, 0)
else
local x, y, z = getElementPosition(thePlayer)
if (x < 3000) or (y > 4000) then -- the further out to sea you go the bigger the fish you will catch.
outputChatBox("You must be out at sea to fish.", thePlayer, 255, 0, 0)
else
if not(exports.global:doesPlayerHaveItem(thePlayer, 49)) then -- does the player have the fishing rod item?
outputChatBox("You need a fishing rod to fish.", thePlayer, 255, 0, 0)
else
if (catchTimer) then -- Are they already fishing?
outputChatBox("You have already cast your line. Wait for a fish to bite.", thePlayer, 255, 0, 0)
else
if (totalCatch >= 2000) then
outputChatBox("#FF9933The boat can't hold any more fish. #FF66CCSell#FF9933 the fish you have caught before continuing.", thePlayer, 255, 104, 91, true)
else
local biteTimer = math.random(60000,300000)
--catchTimer = setTimer( theyHaveABite, biteTimer, 1, thePlayer) -- A fish will bite within 1 and 5 minutes.
catchTimer = setTimer( theyHaveABite, 10000, 1, thePlayer)
exports.global:sendLocalMeAction(thePlayer,"casts a fishing line.")
if not (colsphere) then -- If the /sellfish marker isnt already being shown...
blip = createBlip( 2243.7339, 578.905, 6.78, 0, 2, 255, 0, 255, 255 )
marker = createMarker( 2243.7339, 578.905, 6.78, "cylinder", 2, 255, 0, 255, 150 )
colsphere = createColSphere (2243.7339, 578.905, 6.78, 3)
exports.pool:allocateElement(blip)
exports.pool:allocateElement(marker)
exports.pool:allocateElement(colsphere)
setElementVisibleTo(blip, getRootElement(), false)
setElementVisibleTo(blip, thePlayer, true)
setElementVisibleTo(marker, getRootElement(), false)
setElementVisibleTo(marker, thePlayer, true)
outputChatBox("#FF9933When you are done fishing you can sell your catch at the fish market ((#FF66CCblip#FF9933 added to radar)).", thePlayer, 255, 104, 91, true)
outputChatBox("#FF9933((/totalcatch to see how much you have caught. To sell your catch enter /sellfish in the #FF66CCmarker#FF9933.))", thePlayer, 255, 104, 91, true)
end
end
end
end
end
end
end
end
end
addCommandHandler("fish", startFishing, false, false)
addEvent("fish")
addEventHandler("fish", getRootElement(), startFishing)
------ triggers the mini game.
function theyHaveABite(source)
killTimer(catchTimer)
catchTimer=nil
triggerClientEvent("createReel", source)
exports.global:sendLocalMeAction(source,"has a bite!")
end
----- Snapped line.
function lineSnap()
exports.global:takePlayerItem(source, 49, 1) -- fishing rod
exports.global:sendLocalMeAction(source,"snaps their fishing line.")
outputChatBox("The monster of a fish has broken your line. You need to buy a new fishing rod to continue fishing.", source, 255, 0, 0)
end
addEvent("lineSnap",true)
addEventHandler("lineSnap", getRootElement(), lineSnap)
----- Successfully reeled in the fish.
function catchFish(fishSize)
exports.global:sendLocalMeAction(source,"catches a fish weighing ".. fishSize .."lbs.")
totalCatch = math.floor(totalCatch + fishSize)
outputChatBox("You have caught "..totalCatch.."lbs of fish so far.", source, 255, 194, 14)
if (fishSize >= 100) then
exports.global:givePlayerAchievement(source, 35)
end
end
addEvent("catchFish", true)
addEventHandler("catchFish", getRootElement(), catchFish)
------ /totalcatch command
function currentCatch(thePlayer)
outputChatBox("You have "..totalCatch.."lbs of fish caught so far.", thePlayer, 255, 194, 14)
end
addCommandHandler("totalcatch", currentCatch, false, false)
------ /sellfish
function unloadCatch(thePlayer)
if (isElementWithinColShape(thePlayer, colsphere)) then
if (totalCatch == 0) then
outputChatBox("You need to catch some fish to sell first." ,thePlayer, 255, 0, 0)
else
local profit = math.floor(totalCatch/2)
exports.global:sendLocalMeAction(thePlayer,"sells " .. totalCatch .."lbs of fish.")
exports.global:givePlayerSafeMoney(thePlayer, profit)
outputChatBox("You made $".. profit .." from the fish you caught." ,thePlayer, 255, 104, 91)
totalCatch = 0
destroyElement(blip)
destroyElement(marker)
destroyElement(colsphere)
blip=nil
marker=nil
colsphere=nil
end
else
outputChatBox("You need to be at the fish market to sell your catch.", thePlayer, 255, 0, 0)
end
end
addCommandHandler("sellFish", unloadCatch, false, false)
|
Fishing fix.
|
Fishing fix.
git-svn-id: 8769cb08482c9977c94b72b8e184ec7d2197f4f7@508 64450a49-1f69-0410-a0a2-f5ebb52c4f5b
|
Lua
|
bsd-3-clause
|
valhallaGaming/uno,valhallaGaming/uno,valhallaGaming/uno
|
ac428d37fcf57cb3ea9aa8923ec1d4ba299e8dd1
|
roles/neovim/config/lua/irubataru/lsp/servers/sumneko_lua.lua
|
roles/neovim/config/lua/irubataru/lsp/servers/sumneko_lua.lua
|
local path = vim.split(package.path, ";")
table.insert(path, "lua/?.lua")
table.insert(path, "lua/?/init.lua")
local function setup_libraries()
local library = {}
local function add(lib)
for _, p in pairs(vim.fn.expand(lib, false, true)) do
p = vim.loop.fs_realpath(p)
library[p] = true
end
end
local homedir = vim.env.HOME
local filedir = vim.fn.expand("%:p")
local function dev_vim()
return filedir:find("^" .. homedir .. "/.config/nvim") ~= nil or filedir:find("^" .. homedir .. "/.dotfiles/roles/neovim/config") ~= nil
end
local function dev_awesome()
return filedir:find("^" .. homedir .. "/.config/awesome") ~= nil or filedir:find("^" .. homedir .. "/.dotfiles/roles/awesome/config") ~= nil
end
local function dev_awesome_custom()
return filedir:find("^" .. homedir .. "/config/awesome") ~= nil
end
if dev_vim() then
-- add runtime
add("$VIMRUNTIME")
-- add your config
add("~/.config/nvim")
-- add plugins
-- if you're not using packer, then you might need to change the paths below
add("~/.local/share/nvim/site/pack/packer/opt/*")
add("~/.local/share/nvim/site/pack/packer/start/*")
elseif dev_awesome() then
add(homedir .. "/.dotfiles/roles/awesome/config")
add(homedir .. "/.dotfiles/roles/awesome/config/*")
add("/usr/share/awesome/lib")
add("/usr/share/awesome/lib/*")
elseif dev_awesome_custom() then
add("$PWD")
add("/usr/share/awesome/lib")
add("/usr/share/awesome/lib/*")
else
add("$PWD")
end
for k, _ in pairs(library) do
print(k)
end
return library
end
local M = {}
M.config = {
on_attach_post = function(client, _)
client.config.settings.Lua.workspace.library = setup_libraries()
end,
settings = {
Lua = {
runtime = {
-- Tell the language server which version of Lua you're using (most likely LuaJIT in the case of Neovim)
version = "LuaJIT",
-- Setup your lua path
path = path,
},
completion = { callSnippet = "Both" },
diagnostics = {
-- Get the language server to recognize the `vim` global
globals = {
-- neovim
"vim",
-- awesome
"awesome",
"client",
"root",
"screen",
},
},
workspace = {
-- Make the server aware of Neovim runtime files
library = setup_libraries(),
},
-- Do not send telemetry data containing a randomized but unique identifier
telemetry = { enable = false },
},
},
filetypes = { "lua", "lua.luapad", "luapad" },
}
return M
|
local path = vim.split(package.path, ";")
table.insert(path, "lua/?.lua")
table.insert(path, "lua/?/init.lua")
local function setup_libraries()
local library = {}
local function add(lib)
for _, p in pairs(vim.fn.expand(lib, false, true)) do
p = vim.loop.fs_realpath(p)
library[p] = true
end
end
local homedir = vim.env.HOME
local filedir = vim.fn.expand("%:p")
local function dev_vim()
return filedir:find("^" .. homedir .. "/.config/nvim") ~= nil or filedir:find("^" .. homedir .. "/.dotfiles/roles/neovim/config") ~= nil
end
local function dev_awesome()
return filedir:find("^" .. homedir .. "/.config/awesome") ~= nil or filedir:find("^" .. homedir .. "/.dotfiles/roles/awesome/config") ~= nil
end
local function dev_awesome_custom()
return filedir:find("^" .. homedir .. "/config/awesome") ~= nil
end
if dev_vim() then
-- add runtime
add("$VIMRUNTIME")
-- add your config
add("~/.config/nvim")
-- add plugins
-- if you're not using packer, then you might need to change the paths below
add("~/.local/share/nvim/site/pack/packer/opt/*")
add("~/.local/share/nvim/site/pack/packer/start/*")
elseif dev_awesome() then
add(homedir .. "/.dotfiles/roles/awesome/config")
add(homedir .. "/.dotfiles/roles/awesome/config/*")
add("/usr/share/awesome/lib")
add("/usr/share/awesome/lib/*")
elseif dev_awesome_custom() then
add("$PWD")
add("/usr/share/awesome/lib")
add("/usr/share/awesome/lib/*")
else
add("$PWD")
end
return library
end
local M = {}
M.config = {
on_attach_post = function(client, _)
client.config.settings.Lua.workspace.library = setup_libraries()
end,
settings = {
Lua = {
runtime = {
-- Tell the language server which version of Lua you're using (most likely LuaJIT in the case of Neovim)
version = "LuaJIT",
-- Setup your lua path
path = path,
},
completion = { callSnippet = "Both" },
diagnostics = {
-- Get the language server to recognize the `vim` global
globals = {
-- neovim
"vim",
-- awesome
"awesome",
"client",
"root",
"screen",
},
},
workspace = {
-- Make the server aware of Neovim runtime files
library = setup_libraries(),
},
-- Do not send telemetry data containing a randomized but unique identifier
telemetry = { enable = false },
},
},
filetypes = { "lua", "lua.luapad", "luapad" },
}
return M
|
fix(neovim): forgot to remove debug printing from sumneko
|
fix(neovim): forgot to remove debug printing from sumneko
|
Lua
|
mit
|
Irubataru/dotfiles,Irubataru/dotfiles,Irubataru/dotfiles
|
624798f56182caf80f062e547bf3b584320f0669
|
src/extensions/cp/apple/finalcutpro/timeline/IndexRolesArea.lua
|
src/extensions/cp/apple/finalcutpro/timeline/IndexRolesArea.lua
|
--- === cp.apple.finalcutpro.timeline.IndexRolesArea ===
---
--- Represents the list of Roles in the [IndexRoles](cp.apple.finalcutpro.timeline.IndexRoles.md).
-- local log = require "hs.logger" .new "IndexRolesArea"
local axutils = require "cp.ui.axutils"
local ScrollArea = require "cp.ui.ScrollArea"
local IndexRolesList = require "cp.apple.finalcutpro.timeline.IndexRolesList"
local childMatching = axutils.childMatching
local IndexRolesArea = ScrollArea:subclass("cp.apple.finalcutpro.timeline.IndexRolesArea")
--- cp.apple.finalcutpro.timeline.IndexRolesArea.matches(element) -> boolean
--- Function
--- Checks if the `element` matches an `IndexRolesArea`.
---
--- Parameters:
--- * element - The `axuielement` to check.
---
--- Returns:
--- * `true` if it matches, otherwise `false`.
function IndexRolesArea.static.matches(element)
if ScrollArea.matches(element) then
local contents = element:attributeValue("AXContents")
return #contents == 1 and IndexRolesList.matches(contents[1])
end
return false
end
--- cp.apple.finalcutpro.timeline.IndexRolesArea.list <cp.ui.Outline>
--- Field
--- The [Outline](cp.ui.Outline.md) that serves as the list of the scroll area.
function IndexRolesArea.lazy.value:list()
return IndexRolesList(self, self.UI:mutate(function(original)
return childMatching(original(), IndexRolesList.matches)
end))
end
function IndexRolesArea:saveLayout()
local layout = ScrollArea.saveLayout(self)
layout.list = self.list:saveLayout()
return layout
end
function IndexRolesArea:loadLayout(layout)
layout = layout or {}
ScrollArea.loadLayout(self, layout)
self.list:loadLayout(layout.list)
end
return IndexRolesArea
|
--- === cp.apple.finalcutpro.timeline.IndexRolesArea ===
---
--- Represents the list of Roles in the [IndexRoles](cp.apple.finalcutpro.timeline.IndexRoles.md).
-- local log = require "hs.logger" .new "IndexRolesArea"
local axutils = require "cp.ui.axutils"
local ScrollArea = require "cp.ui.ScrollArea"
local IndexRolesList = require "cp.apple.finalcutpro.timeline.IndexRolesList"
local childMatching = axutils.childMatching
local IndexRolesArea = ScrollArea:subclass("cp.apple.finalcutpro.timeline.IndexRolesArea")
--- cp.apple.finalcutpro.timeline.IndexRolesArea.matches(element) -> boolean
--- Function
--- Checks if the `element` matches an `IndexRolesArea`.
---
--- Parameters:
--- * element - The `axuielement` to check.
---
--- Returns:
--- * `true` if it matches, otherwise `false`.
function IndexRolesArea.static.matches(element)
if ScrollArea.matches(element) then
local contents = element:attributeValue("AXContents")
return #contents == 1 and IndexRolesList.matches(contents[1])
end
return false
end
--- cp.apple.finalcutpro.timeline.IndexRolesArea.list <cp.apple.finalcutpro.timeline.IndexRolesList>
--- Field
--- The [IndexRolesList](cp.apple.finalcutpro.timeline.IndexRolesList.md) that serves as the list of the scroll area.
function IndexRolesArea.lazy.value:list()
return IndexRolesList(self, self.UI:mutate(function(original)
return childMatching(original(), IndexRolesList.matches)
end))
end
function IndexRolesArea:saveLayout()
local layout = ScrollArea.saveLayout(self)
layout.list = self.list:saveLayout()
return layout
end
function IndexRolesArea:loadLayout(layout)
layout = layout or {}
ScrollArea.loadLayout(self, layout)
self.list:loadLayout(layout.list)
end
return IndexRolesArea
|
Fixed documentation
|
Fixed documentation
|
Lua
|
mit
|
CommandPost/CommandPost,CommandPost/CommandPost,CommandPost/CommandPost
|
7c675e4a4b09c9090ec75d539459f4e45f82825c
|
mods/BeardLib-Editor/Classes/Map/UndoUnitHandler.lua
|
mods/BeardLib-Editor/Classes/Map/UndoUnitHandler.lua
|
UndoUnitHandler = UndoUnitHandler or class()
core:import("CoreStack")
local UHandler = UndoUnitHandler
function UHandler:init()
self._unit_data = {}
self._undo_stack = CoreStack.Stack:new()
self._redo_stack = CoreStack.Stack:new()
self._undo_history_size = BLE.Options:GetValue("UndoHistorySize")
end
function UHandler:SaveUnitValues(units, action_type)
local jump_table = {
pos = function(u) table.insert(self._unit_data[u:key()].pos, 1, u:unit_data()._prev_pos) end, -- I have to insert them into the first pos as
rot = function(u) table.insert(self._unit_data[u:key()].rot, 1, u:unit_data()._prev_rot) end -- to make it easier to get the first inserted element
}
if self._undo_stack:size() > self._undo_history_size then
local dif = self._undo_stack:size() - self._undo_history_size
table.remove(self._undo_stack:stack_table(), 1, dif)
self._undo_stack._last = self._undo_stack._last - dif
managers.editor:Log("Stack history too big, removing elements")
end -- TODO also remove the last unit value based on the last action in undo_stack
local unit_keys = {}
for _, unit in pairs(units) do
table.insert(unit_keys, unit:key())
if not self._unit_data[unit:key()] then
self._unit_data[unit:key()] = {
unit_data = unit,
pos = {},
rot = {}
}
jump_table[action_type](unit) -- ugly
else
jump_table[action_type](unit)
end
end
local element = {unit_keys, action_type}
self._undo_stack:push(element)
end
function UHandler:Undo()
local jump_table = {
pos = function(k) self:restore_unit_pos(k) end,
rot = function(k) self:restore_unit_rot(k) end
}
if not self._undo_stack:is_empty() then
local element = self._undo_stack:pop()
for _, key in pairs(element[1]) do
jump_table[element[2]](key)
end
self._redo_stack:push(element)
else managers.editor:Log("Undo stack is empty!")
end
end
function UHandler:restore_unit_pos(key) -- with the current implementation i have to have 2 different methods for unit restore
local pos = table.remove(self._unit_data[key].pos, 1)
managers.editor:Log("Restoring unit to position: " .. tostring(pos))
local unit = self._unit_data[key].unit_data
BLE.Utils:SetPosition(unit, pos)
end
function UHandler:restore_unit_rot(key) -- unit rotation is completely fucked, and causes dumb crashes
local pos = self._unit_data[key].pos[1]
local rot = table.remove(self._unit_data[key].rot, 1)
managers.editor:Log("Restoring unit rotation: " .. tostring(rot))
local unit = self._unit_data[key].unit_data
BLE.Utils:SetPosition(unit, pos, rot)
end
|
UndoUnitHandler = UndoUnitHandler or class()
core:import("CoreStack")
local UHandler = UndoUnitHandler
function UHandler:init()
self._unit_data = {}
self._undo_stack = CoreStack.Stack:new()
self._redo_data = {}
self._undo_history_size = BLE.Options:GetValue("UndoHistorySize")
end
function UHandler:SaveUnitValues(units, action_type)
local jump_table = {
pos = function(u) table.insert(self._unit_data[u:key()].pos, 1, u:unit_data()._prev_pos) end,
rot = function(u)
table.insert(self._unit_data[u:key()].rot, 1, u:unit_data()._prev_rot)
table.insert(self._unit_data[u:key()].pos, 1, u:unit_data()._prev_pos)
end
}
if self._undo_stack:size() > self._undo_history_size then
local dif = self._undo_stack:size() - self._undo_history_size
table.remove(self._undo_stack:stack_table(), 1, dif)
self._undo_stack._last = self._undo_stack._last - dif
managers.editor:Log("Stack history too big, removing elements")
end -- TODO also remove the last unit value based on the last action in undo_stack
local unit_keys = {}
for _, unit in pairs(units) do
table.insert(unit_keys, unit:key())
if not self._unit_data[unit:key()] then
self._unit_data[unit:key()] = {
unit_data = unit,
pos = {},
rot = {}
}
jump_table[action_type](unit) -- ugly
else
jump_table[action_type](unit)
end
end
local element = {unit_keys, action_type}
self._undo_stack:push(element)
end
function UHandler:Undo()
if self._undo_stack:is_empty() then
managers.editor:Log("Undo stack is empty!")
return
end
local element = self._undo_stack:pop()
for _, key in pairs(element[1]) do
self:restore_unit_pos_rot(key, element[2])
end
end
function UHandler:set_redo_values(key)
--empty
end
function UHandler:restore_unit_pos_rot(key, action)
local action_string = action == "rot" and "rotation " or "to position "
local pos = table.remove(self._unit_data[key].pos, 1)
local rot = action == "rot" and table.remove(self._unit_data[key].rot, 1) or nil
local unit = self._unit_data[key].unit_data
managers.editor:Log("Restoring unit " .. action_string .. tostring(rot or pos))
BLE.Utils:SetPosition(unit, pos, rot)
end
|
fixed unit rotations, shortened the code
|
fixed unit rotations, shortened the code
|
Lua
|
mit
|
simon-wh/PAYDAY-2-BeardLib-Editor
|
31c5d92f3c316983479afbf3da1042beec809305
|
packages/bandwidth-test/files/bin/bandwidth-test.lua
|
packages/bandwidth-test/files/bin/bandwidth-test.lua
|
#!/usr/bin/lua
local libuci_loaded, libuci = pcall(require, "uci")
local function config_uci_get(option)
local result
if libuci_loaded then
result = libuci:cursor():get("bandwidth-test","bandwidth_test",option)
else
result = nil
end
return result
end
local PIDfile = "/tmp/bandwidth-test-wget-pid"
local singleTestDuration = tonumber(arg[1]) or tonumber(config_uci_get("single_test_duration")) or 20
local nonzeroTests = tonumber(arg[2]) or tonumber(config_uci_get("nonzero_tests")) or 5
local defaultServersList = {
"http://speedtest-lon1.digitalocean.com/10mb.test",
"http://www.ovh.net/files/10Mio.dat",
"http://cloudharmony.com/probe/test10mb.jpg",
"http://frf1-speed-02.host.twtelecom.net.prod.hosts.ooklaserver.net:8080/download?size=12000000",
"http://cdn.google.cloudharmony.net/probe/test10mb.jpg",
"http://deb.debian.org/debian/ls-lR.gz",
"http://speedtest.catnix.cat.prod.hosts.ooklaserver.net:8080/download?size=12000000",
"http://ubuntu.inode.at/ubuntu/dists/bionic/main/installer-amd64/current/images/hd-media/initrd.gz",
"http://cdn.kernel.org/pub/linux/kernel/v4.x/patch-4.9.gz",
"http://ftp.belnet.be/ubuntu.com/ubuntu/dists/bionic/main/installer-amd64/current/images/hd-media/initrd.gz"
}
local serversList
if arg[3] then
serversList = {}
for i = 3,#arg,1
do
serversList[#serversList + 1] = tostring(arg[i])
end
else
local temp = config_uci_get("server")
serversList = type(temp) == "table" and temp or defaultServersList
end
if not singleTestDuration or not nonzeroTests or not serversList[1]:find("http") then
local help = {"Usage: "..arg[0].." [SINGLE_TEST_DURATION] [NONZERO_TESTS] [SERVERS_LIST]",
"Measures maximum available download bandwidth downloading a list of files from the internet.",
"The measurement will take approximately SINGLE_TEST_DURATION*NONZERO_TESTS seconds.",
"Download of each URL is attempted at most one time: multiple URLs should be provided.",
"Speed in B/s is printed to STDOUT.",
"",
" SINGLE_TEST_DURATION fixed duration of each download process,",
" if missing reads from UCI status-report (default 20)",
" NONZERO_TESTS minimum number of successful downloads,",
" if missing reads from UCI status-report (default 5)",
" SERVERS_LIST a space-separated list of files' URLs to download,",
" preferably large files.",
" When running with Busybox wget, has to include http://",
" and will likely fail with https://",
" if missing reads from UCI status-report",
" (defaults to a list of 10 MB files on various domains)"}
for i = 1,#help,1 do
io.stderr:write(help[i],"\n")
end
os.exit(1)
end
local function do_split(str,pat)
local tbl = {}
str:gsub(pat, function(x) tbl[#tbl+1]=x end)
return tbl
end
local function do_test(server)
io.stderr:write("Attempting connection to "..server.."\n")
local timeout = singleTestDuration * 0.75
local pvCommand = "(wget -T"..timeout.." -q "..server..
" -O- & echo $! >&3) 3> "..PIDfile..
" | pv -n -b -t 2>&1 >/dev/null"
local handlePv = io.popen(pvCommand, 'r')
local handleKill = io.popen("sleep "..singleTestDuration.."; kill $(cat "..PIDfile.." 2>/dev/null) 2>/dev/null")
local pvRaw = handlePv:read("*a")
handleKill:close()
handlePv:close()
local pvArray = do_split(pvRaw,"[.%d]+")
return pvArray
end
local function get_speed(pvArray)
local t1 = tonumber(pvArray[#pvArray-3]) or 0
local d1 = tonumber(pvArray[#pvArray-2]) or 0
local t2 = tonumber(pvArray[#pvArray-1])
local d2 = tonumber(pvArray[#pvArray])
local speed = 0
if t2 and d2 then
speed = (d2 - d1) / (t2 - t1)
end
return speed
end
local function remove_zeros(array)
local tbl = {}
for i = 1, #array do
if(array[i] ~= 0) then
table.insert(tbl, array[i])
end
end
return tbl
end
local function do_median(array)
local temp = array
local median = 0
if #temp ~= 0 then
table.sort(temp)
median = temp[math.floor(#array/2)+1]
end
return median
end
local function do_tests_serie()
local results = {}
local i = 1
while #results < nonzeroTests and serversList[i] do
local test = do_test(serversList[i])
local testResult = get_speed(test)
io.stderr:write(math.floor(testResult).." B/s\n")
results[#results + 1] = testResult
results = remove_zeros(results)
i = i + 1
end
local median = do_median(results)
local attempted = i - 1
return median, attempted, #results
end
local result, attempted, successful = do_tests_serie()
print(result)
local message = "Maximum available bandwidth "..math.floor(result)..
" B/s, attempted connection to "..attempted..
" servers, successful connection to "..successful..
" servers."
io.stderr:write(message.."\n")
local handle = io.popen("logger -t bandwidth-test "..message)
handle:close()
|
#!/usr/bin/lua
local libuci_loaded, libuci = pcall(require, "uci")
local function config_uci_get(option)
local result
if libuci_loaded then
result = libuci:cursor():get("bandwidth-test","bandwidth_test",option)
else
result = nil
end
return result
end
local PIDfile = "/tmp/bandwidth-test-wget-pid"
local singleTestDuration = tonumber(arg[1]) or tonumber(config_uci_get("single_test_duration")) or 20
local nonzeroTests = tonumber(arg[2]) or tonumber(config_uci_get("nonzero_tests")) or 5
local defaultServersList = {
"http://speedtest-lon1.digitalocean.com/10mb.test",
"http://www.ovh.net/files/10Mio.dat",
"http://cloudharmony.com/probe/test10mb.jpg",
"http://frf1-speed-02.host.twtelecom.net.prod.hosts.ooklaserver.net:8080/download?size=12000000",
"http://cdn.google.cloudharmony.net/probe/test10mb.jpg",
"http://deb.debian.org/debian/ls-lR.gz",
"http://speedtest.catnix.cat.prod.hosts.ooklaserver.net:8080/download?size=12000000",
"http://ubuntu.inode.at/ubuntu/dists/bionic/main/installer-amd64/current/images/hd-media/initrd.gz",
"http://cdn.kernel.org/pub/linux/kernel/v4.x/patch-4.9.gz",
"http://ftp.belnet.be/ubuntu.com/ubuntu/dists/bionic/main/installer-amd64/current/images/hd-media/initrd.gz"
}
local serversList
if arg[3] then
serversList = {}
for i = 3,#arg,1
do
serversList[#serversList + 1] = tostring(arg[i])
end
else
local temp = config_uci_get("server")
serversList = type(temp) == "table" and temp or defaultServersList
end
if arg[1] == "-h" or arg[1] == "--help" or not serversList[1]:find("http") then
local help = {"Usage: "..arg[0].." [SINGLE_TEST_DURATION] [NONZERO_TESTS] [SERVERS_LIST]",
"Measures maximum available download bandwidth downloading a list of files from the internet.",
"The measurement will take approximately SINGLE_TEST_DURATION*NONZERO_TESTS seconds.",
"Download of each URL is attempted at most one time: multiple URLs should be provided.",
"Speed in B/s is printed to STDOUT.",
"",
" SINGLE_TEST_DURATION fixed duration of each download process,",
" if missing reads from UCI status-report (default 20)",
" NONZERO_TESTS minimum number of successful downloads,",
" if missing reads from UCI status-report (default 5)",
" SERVERS_LIST a space-separated list of files' URLs to download,",
" preferably large files.",
" When running with Busybox wget, has to include http://",
" and will likely fail with https://",
" if missing reads from UCI status-report",
" (defaults to a list of 10 MB files on various domains)"}
for i = 1,#help,1 do
io.stderr:write(help[i],"\n")
end
os.exit(1)
end
local function do_split(str,pat)
local tbl = {}
str:gsub(pat, function(x) tbl[#tbl+1]=x end)
return tbl
end
local function do_test(server)
io.stderr:write("Attempting connection to "..server.."\n")
local timeout = singleTestDuration * 0.75
local pvCommand = "(wget -T"..timeout.." -q "..server..
" -O- & echo $! >&3) 3> "..PIDfile..
" | pv -n -b -t 2>&1 >/dev/null"
local handlePv = io.popen(pvCommand, 'r')
local handleKill = io.popen("sleep "..singleTestDuration.."; kill $(cat "..PIDfile.." 2>/dev/null) 2>/dev/null")
local pvRaw = handlePv:read("*a")
handleKill:close()
handlePv:close()
local pvArray = do_split(pvRaw,"[.%d]+")
return pvArray
end
local function get_speed(pvArray)
local t1 = tonumber(pvArray[#pvArray-3]) or 0
local d1 = tonumber(pvArray[#pvArray-2]) or 0
local t2 = tonumber(pvArray[#pvArray-1])
local d2 = tonumber(pvArray[#pvArray])
local speed = 0
if t2 and d2 then
speed = (d2 - d1) / (t2 - t1)
end
return speed
end
local function remove_zeros(array)
local tbl = {}
for i = 1, #array do
if(array[i] ~= 0) then
table.insert(tbl, array[i])
end
end
return tbl
end
local function do_median(array)
local temp = array
local median = 0
if #temp ~= 0 then
table.sort(temp)
median = temp[math.floor(#array/2)+1]
end
return median
end
local function do_tests_serie()
local results = {}
local i = 1
while #results < nonzeroTests and serversList[i] do
local test = do_test(serversList[i])
local testResult = get_speed(test)
io.stderr:write(math.floor(testResult).." B/s\n")
results[#results + 1] = testResult
results = remove_zeros(results)
i = i + 1
end
local median = do_median(results)
local attempted = i - 1
return median, attempted, #results
end
local result, attempted, successful = do_tests_serie()
print(result)
local message = "Maximum available bandwidth "..math.floor(result)..
" B/s, attempted connection to "..attempted..
" servers, successful connection to "..successful..
" servers."
io.stderr:write(message.."\n")
local handle = io.popen("logger -t bandwidth-test "..message)
handle:close()
|
fix -h in bandwidth-test
|
fix -h in bandwidth-test
|
Lua
|
agpl-3.0
|
libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages
|
beb85c3967fd49f0a7b8c9514e537d35785d6850
|
core/certmanager.lua
|
core/certmanager.lua
|
-- Prosody IM
-- Copyright (C) 2008-2010 Matthew Wild
-- Copyright (C) 2008-2010 Waqas Hussain
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
local configmanager = require "core.configmanager";
local log = require "util.logger".init("certmanager");
local ssl = ssl;
local ssl_newcontext = ssl and ssl.newcontext;
local tostring = tostring;
local pairs = pairs;
local type = type;
local io_open = io.open;
local t_concat = table.concat;
local prosody = prosody;
local resolve_path = configmanager.resolve_relative_path;
local config_path = prosody.paths.config;
local luasec_has_noticket, luasec_has_verifyext, luasec_has_no_compression;
if ssl then
local luasec_major, luasec_minor = ssl._VERSION:match("^(%d+)%.(%d+)");
luasec_has_noticket = tonumber(luasec_major)>0 or tonumber(luasec_minor)>=4;
luasec_has_verifyext = tonumber(luasec_major)>0 or tonumber(luasec_minor)>=5;
luasec_has_no_compression = tonumber(luasec_major)>0 or tonumber(luasec_minor)>=5;
end
module "certmanager"
-- Global SSL options if not overridden per-host
local global_ssl_config = configmanager.get("*", "ssl");
-- Built-in defaults
local core_defaults = {
capath = "/etc/ssl/certs";
protocol = "tlsv1+";
verify = (ssl and ssl.x509 and { "peer", "client_once", }) or "none";
options = {
cipher_server_preference = true;
no_ticket = luasec_has_noticket;
no_compression = luasec_has_no_compression and configmanager.get("*", "ssl_compression") ~= true;
-- Has no_compression? Then it has these too...
single_dh_use = luasec_has_no_compression;
single_ecdh_use = luasec_has_no_compression;
};
verifyext = { "lsec_continue", "lsec_ignore_purpose" };
curve = "secp384r1";
ciphers = "HIGH+kEDH:HIGH+kEECDH:HIGH:!PSK:!SRP:!3DES:!aNULL";
}
local path_options = { -- These we pass through resolve_path()
key = true, certificate = true, cafile = true, capath = true, dhparam = true
}
local set_options = {
options = true, verify = true, verifyext = true
}
if ssl and not luasec_has_verifyext and ssl.x509 then
-- COMPAT mw/luasec-hg
for i=1,#core_defaults.verifyext do -- Remove lsec_ prefix
core_defaults.verify[#core_defaults.verify+1] = core_defaults.verifyext[i]:sub(6);
end
end
local function merge_set(t, o)
if type(t) ~= "table" then t = { t } end
for k,v in pairs(t) do
if v == true or v == false then
o[k] = v;
else
o[v] = true;
end
end
return o;
end
local protocols = { "sslv2", "sslv3", "tlsv1", "tlsv1_1", "tlsv1_2" };
for i = 1, #protocols do protocols[protocols[i] .. "+"] = i - 1; end
function create_context(host, mode, user_ssl_config)
user_ssl_config = user_ssl_config or {}
user_ssl_config.mode = mode;
if not ssl then return nil, "LuaSec (required for encryption) was not found"; end
if global_ssl_config then
for option,default_value in pairs(global_ssl_config) do
if user_ssl_config[option] == nil then
user_ssl_config[option] = default_value;
end
end
end
for option,default_value in pairs(core_defaults) do
if user_ssl_config[option] == nil then
user_ssl_config[option] = default_value;
end
end
local min_protocol = protocols[user_ssl_config.protocol];
if min_protocol then
user_ssl_config.protocol = "sslv23";
for i = min_protocol, 1, -1 do
user_ssl_config.options["no_"..protocols[i]] = true;
end
end
for option in pairs(set_options) do
local merged = {};
merge_set(core_defaults[option], merged);
merge_set(global_ssl_config[option], merged);
merge_set(user_ssl_config[option], merged);
local final_array = {};
for opt, enable in pairs(merged) do
if enable then
final_array[#final_array+1] = opt;
end
end
user_ssl_config[option] = final_array;
end
-- We can't read the password interactively when daemonized
user_ssl_config.password = user_ssl_config.password or
function() log("error", "Encrypted certificate for %s requires 'ssl' 'password' to be set in config", host); end;
for option in pairs(path_options) do
if type(user_ssl_config[option]) == "string" then
user_ssl_config[option] = resolve_path(config_path, user_ssl_config[option]);
end
end
-- Allow the cipher list to be a table
if type(user_ssl_config.ciphers) == "table" then
user_ssl_config.ciphers = t_concat(user_ssl_config.ciphers, ":")
end
if mode == "server" then
if not user_ssl_config.key then return nil, "No key present in SSL/TLS configuration for "..host; end
if not user_ssl_config.certificate then return nil, "No certificate present in SSL/TLS configuration for "..host; end
end
-- LuaSec expects dhparam to be a callback that takes two arguments.
-- We ignore those because it is mostly used for having a separate
-- set of params for EXPORT ciphers, which we don't have by default.
if type(user_ssl_config.dhparam) == "string" then
local f, err = io_open(user_ssl_config.dhparam);
if not f then return nil, "Could not open DH parameters: "..err end
local dhparam = f:read("*a");
f:close();
user_ssl_config.dhparam = function() return dhparam; end
end
local ctx, err = ssl_newcontext(user_ssl_config);
-- COMPAT Older LuaSec ignores the cipher list from the config, so we have to take care
-- of it ourselves (W/A for #x)
if ctx and user_ssl_config.ciphers then
local success;
success, err = ssl.context.setcipher(ctx, user_ssl_config.ciphers);
if not success then ctx = nil; end
end
if not ctx then
err = err or "invalid ssl config"
local file = err:match("^error loading (.-) %(");
if file then
if file == "private key" then
file = user_ssl_config.key or "your private key";
elseif file == "certificate" then
file = user_ssl_config.certificate or "your certificate file";
end
local reason = err:match("%((.+)%)$") or "some reason";
if reason == "Permission denied" then
reason = "Check that the permissions allow Prosody to read this file.";
elseif reason == "No such file or directory" then
reason = "Check that the path is correct, and the file exists.";
elseif reason == "system lib" then
reason = "Previous error (see logs), or other system error.";
elseif reason == "(null)" or not reason then
reason = "Check that the file exists and the permissions are correct";
else
reason = "Reason: "..tostring(reason):lower();
end
log("error", "SSL/TLS: Failed to load '%s': %s (for %s)", file, reason, host);
else
log("error", "SSL/TLS: Error initialising for %s: %s", host, err);
end
end
return ctx, err;
end
function reload_ssl_config()
global_ssl_config = configmanager.get("*", "ssl");
if luasec_has_no_compression then
core_defaults.options.no_compression = configmanager.get("*", "ssl_compression") ~= true;
end
end
prosody.events.add_handler("config-reloaded", reload_ssl_config);
return _M;
|
-- Prosody IM
-- Copyright (C) 2008-2010 Matthew Wild
-- Copyright (C) 2008-2010 Waqas Hussain
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
local configmanager = require "core.configmanager";
local log = require "util.logger".init("certmanager");
local ssl = ssl;
local ssl_newcontext = ssl and ssl.newcontext;
local tostring = tostring;
local pairs = pairs;
local type = type;
local io_open = io.open;
local t_concat = table.concat;
local prosody = prosody;
local resolve_path = configmanager.resolve_relative_path;
local config_path = prosody.paths.config;
local luasec_has_noticket, luasec_has_verifyext, luasec_has_no_compression;
if ssl then
local luasec_major, luasec_minor = ssl._VERSION:match("^(%d+)%.(%d+)");
luasec_has_noticket = tonumber(luasec_major)>0 or tonumber(luasec_minor)>=4;
luasec_has_verifyext = tonumber(luasec_major)>0 or tonumber(luasec_minor)>=5;
luasec_has_no_compression = tonumber(luasec_major)>0 or tonumber(luasec_minor)>=5;
end
module "certmanager"
-- Global SSL options if not overridden per-host
local global_ssl_config = configmanager.get("*", "ssl");
-- Built-in defaults
local core_defaults = {
capath = "/etc/ssl/certs";
protocol = "tlsv1+";
verify = (ssl and ssl.x509 and { "peer", "client_once", }) or "none";
options = {
cipher_server_preference = true;
no_ticket = luasec_has_noticket;
no_compression = luasec_has_no_compression and configmanager.get("*", "ssl_compression") ~= true;
-- Has no_compression? Then it has these too...
single_dh_use = luasec_has_no_compression;
single_ecdh_use = luasec_has_no_compression;
};
verifyext = { "lsec_continue", "lsec_ignore_purpose" };
curve = "secp384r1";
ciphers = "HIGH+kEDH:HIGH+kEECDH:HIGH:!PSK:!SRP:!3DES:!aNULL";
}
local path_options = { -- These we pass through resolve_path()
key = true, certificate = true, cafile = true, capath = true, dhparam = true
}
local set_options = {
options = true, verify = true, verifyext = true
}
if ssl and not luasec_has_verifyext and ssl.x509 then
-- COMPAT mw/luasec-hg
for i=1,#core_defaults.verifyext do -- Remove lsec_ prefix
core_defaults.verify[#core_defaults.verify+1] = core_defaults.verifyext[i]:sub(6);
end
end
local function merge_set(t, o)
if type(t) ~= "table" then t = { t } end
for k,v in pairs(t) do
if v == true or v == false then
o[k] = v;
else
o[v] = true;
end
end
return o;
end
local protocols = { "sslv2", "sslv3", "tlsv1", "tlsv1_1", "tlsv1_2" };
for i = 1, #protocols do protocols[protocols[i] .. "+"] = i - 1; end
function create_context(host, mode, user_ssl_config)
user_ssl_config = user_ssl_config or {}
user_ssl_config.mode = mode;
if not ssl then return nil, "LuaSec (required for encryption) was not found"; end
if global_ssl_config then
for option,default_value in pairs(global_ssl_config) do
if user_ssl_config[option] == nil then
user_ssl_config[option] = default_value;
end
end
end
for option,default_value in pairs(core_defaults) do
if user_ssl_config[option] == nil then
user_ssl_config[option] = default_value;
end
end
local min_protocol = protocols[user_ssl_config.protocol];
if min_protocol then
user_ssl_config.protocol = "sslv23";
for i = min_protocol, 1, -1 do
user_ssl_config.options["no_"..protocols[i]] = true;
end
end
for option in pairs(set_options) do
local merged = {};
merge_set(core_defaults[option], merged);
if global_ssl_config then
merge_set(global_ssl_config[option], merged);
end
merge_set(user_ssl_config[option], merged);
local final_array = {};
for opt, enable in pairs(merged) do
if enable then
final_array[#final_array+1] = opt;
end
end
user_ssl_config[option] = final_array;
end
-- We can't read the password interactively when daemonized
user_ssl_config.password = user_ssl_config.password or
function() log("error", "Encrypted certificate for %s requires 'ssl' 'password' to be set in config", host); end;
for option in pairs(path_options) do
if type(user_ssl_config[option]) == "string" then
user_ssl_config[option] = resolve_path(config_path, user_ssl_config[option]);
end
end
-- Allow the cipher list to be a table
if type(user_ssl_config.ciphers) == "table" then
user_ssl_config.ciphers = t_concat(user_ssl_config.ciphers, ":")
end
if mode == "server" then
if not user_ssl_config.key then return nil, "No key present in SSL/TLS configuration for "..host; end
if not user_ssl_config.certificate then return nil, "No certificate present in SSL/TLS configuration for "..host; end
end
-- LuaSec expects dhparam to be a callback that takes two arguments.
-- We ignore those because it is mostly used for having a separate
-- set of params for EXPORT ciphers, which we don't have by default.
if type(user_ssl_config.dhparam) == "string" then
local f, err = io_open(user_ssl_config.dhparam);
if not f then return nil, "Could not open DH parameters: "..err end
local dhparam = f:read("*a");
f:close();
user_ssl_config.dhparam = function() return dhparam; end
end
local ctx, err = ssl_newcontext(user_ssl_config);
-- COMPAT Older LuaSec ignores the cipher list from the config, so we have to take care
-- of it ourselves (W/A for #x)
if ctx and user_ssl_config.ciphers then
local success;
success, err = ssl.context.setcipher(ctx, user_ssl_config.ciphers);
if not success then ctx = nil; end
end
if not ctx then
err = err or "invalid ssl config"
local file = err:match("^error loading (.-) %(");
if file then
if file == "private key" then
file = user_ssl_config.key or "your private key";
elseif file == "certificate" then
file = user_ssl_config.certificate or "your certificate file";
end
local reason = err:match("%((.+)%)$") or "some reason";
if reason == "Permission denied" then
reason = "Check that the permissions allow Prosody to read this file.";
elseif reason == "No such file or directory" then
reason = "Check that the path is correct, and the file exists.";
elseif reason == "system lib" then
reason = "Previous error (see logs), or other system error.";
elseif reason == "(null)" or not reason then
reason = "Check that the file exists and the permissions are correct";
else
reason = "Reason: "..tostring(reason):lower();
end
log("error", "SSL/TLS: Failed to load '%s': %s (for %s)", file, reason, host);
else
log("error", "SSL/TLS: Error initialising for %s: %s", host, err);
end
end
return ctx, err;
end
function reload_ssl_config()
global_ssl_config = configmanager.get("*", "ssl");
if luasec_has_no_compression then
core_defaults.options.no_compression = configmanager.get("*", "ssl_compression") ~= true;
end
end
prosody.events.add_handler("config-reloaded", reload_ssl_config);
return _M;
|
certmanager: Fix traceback if no global 'ssl' section set (thanks albert)
|
certmanager: Fix traceback if no global 'ssl' section set (thanks albert)
|
Lua
|
mit
|
sarumjanuch/prosody,sarumjanuch/prosody
|
15d0c26811df0baf0bd9035805a14fc23baa3c1b
|
MMOCoreORB/bin/scripts/screenplays/tasks/epic_quests/zicxBugBomb.lua
|
MMOCoreORB/bin/scripts/screenplays/tasks/epic_quests/zicxBugBomb.lua
|
local ObjectManager = require("managers.object.object_manager")
jowir_arlensa_missions =
{
{
missionType = "confiscate",
preReq = { type = "item", itemTemplate = "object/tangible/loot/quest/quest_item_goru_calling_card.iff", destroy = true },
primarySpawns =
{
{ npcTemplate = "jowir_valarian_assassin", planetName = "tatooine", npcName = "Valarian Assassin" },
},
secondarySpawns =
{
{ npcTemplate = "valarian_assassin", planetName = "tatooine", npcName = "Valarian Assassin" },
{ npcTemplate = "valarian_enforcer", planetName = "tatooine", npcName = "Valarian Enforcer" },
{ npcTemplate = "valarian_enforcer", planetName = "tatooine", npcName = "Valarian Enforcer" },
{ npcTemplate = "valarian_henchman", planetName = "tatooine", npcName = "Valarian Henchman" },
{ npcTemplate = "valarian_scout", planetName = "tatooine", npcName = "Valarian Scout" },
},
itemSpawns =
{
{ itemTemplate = "object/tangible/loot/quest/quest_item_spice_jar.iff", itemName = "" }
},
rewards =
{
{ rewardType = "loot", lootGroup = "task_reward_jowir_arlensa" },
}
}
}
palu_zerk_missions =
{
{
missionType = "escort",
primarySpawns =
{
{ npcTemplate = "feinu_zerk", planetName = "tatooine", npcName = "Feinu Zerk" }
},
secondarySpawns = {
{ npcTemplate = "valarian_swooper_leader", planetName = "tatooine", npcName = "Valarian Swooper Leader" },
{ npcTemplate = "valarian_thug", planetName = "tatooine", npcName = "Valarian Thug" },
{ npcTemplate = "valarian_thug", planetName = "tatooine", npcName = "Valarian Thug" },
{ npcTemplate = "valarian_thug", planetName = "tatooine", npcName = "Valarian Thug" },
},
itemSpawns = {},
rewards =
{
{ rewardType = "loot", lootGroup = "task_reward_palu_zerk" },
}
},
}
npcMapZicx =
{
{
spawnData = { planetName = "rori", npcTemplate = "goru_rainstealer", x = -5431.4, z = 80, y = -2241.3, direction = 33, cellID = 0, position = STAND },
worldPosition = { x = -5430, y = -2240 },
stfFile = "@epic_quest/zicx_bug_bomb/rori_goru_rainstealer",
},
{
spawnData = { planetName = "tatooine", npcTemplate = "jowir_arlensa", x = -5252.74, z = 75, y = -6553.42, direction = 46.6563, cellID = 0, position = STAND },
worldPosition = { x = -5249, y = -6551 },
npcNumber = 1,
stfFile = "@spawning/static_npc/tato_zicx_jowir",
missions = jowir_arlensa_missions
},
{
spawnData = { planetName = "tatooine", npcTemplate = "palu_zerk", x = -5049.46, z = 75, y = -6585.53, direction = 60, cellID = 0, position = STAND },
worldPosition = { x = -5048, y = -6586 },
npcNumber = 2,
stfFile = "@spawning/static_npc/tato_zicx_palu",
missions = palu_zerk_missions
}
}
ZicxBugBomb = ThemeParkLogic:new {
numberOfActs = 1,
npcMap = npcMapZicx,
className = "ZicxBugBomb",
screenPlayState = "zicx_bug_bomb",
distance = 200,
}
ZicxContainerComponent = {}
function ZicxContainerComponent:transferObject(pContainer, pObj, slot)
local pPlayer = ZicxBugBomb:getObjOwner(pObj)
return ObjectManager.withSceneObject(pObj, function(object)
return ObjectManager.withCreatureObject(pPlayer, function(player)
if player:hasScreenPlayState(1, "zicx_bug_bomb_goruNpc") ~= 1 or player:hasScreenPlayState(8, "zicx_bug_bomb_goruNpc") == 1 then
return 0
elseif (object:getTemplateObjectPath() == "object/tangible/loot/quest/quest_item_zicx_bug_jar.iff") then
if (player:hasScreenPlayState(4, "zicx_bug_bomb_goruNpc") ~= 1) then
spatialChat(pContainer, "@epic_quest/zicx_bug_bomb/rori_goru_rainstealer:get_the_bile")
else
spatialChat(pContainer, "@epic_quest/zicx_bug_bomb/rori_goru_rainstealer:give_a_minute")
end
ZicxBugBomb:setState(player, 2, "zicx_bug_bomb_goruNpc")
elseif (object:getTemplateObjectPath() == "object/tangible/loot/quest/quest_item_sarlacc_bile_jar.iff") then
if (player:hasScreenPlayState(2, "zicx_bug_bomb_goruNpc") ~= 1) then
spatialChat(pContainer, "@epic_quest/zicx_bug_bomb/rori_goru_rainstealer:get_the_bugs")
else
spatialChat(pContainer, "@epic_quest/zicx_bug_bomb/rori_goru_rainstealer:give_a_minute")
end
ZicxBugBomb:setState(player, 4, "zicx_bug_bomb_goruNpc")
else
spatialChat(pContainer, "@epic_quest/zicx_bug_bomb/rori_goru_rainstealer:what_is_this")
return 0
end
object:destroyObjectFromWorld()
object:destroyObjectFromDatabase()
return 0
end)
end)
end
function ZicxContainerComponent:canAddObject(pContainer, pObj, slot)
local pPlayer = ZicxBugBomb:getObjOwner(pObj)
return ObjectManager.withCreatureObject(pPlayer, function(player)
if player:hasScreenPlayState(1, "zicx_bug_bomb_goruNpc") == 1 and player:hasScreenPlayState(8, "zicx_bug_bomb_goruNpc") ~= 1 then
return true
else
return -1
end
end)
end
function ZicxBugBomb:getObjOwner(pObj)
local pPlayerInv = SceneObject(pObj):getParent()
return SceneObject(pPlayerInv):getParent()
end
function ZicxContainerComponent:removeObject(pContainer, pObj, slot)
return -1
end
function ZicxBugBomb:setState(creatureObject, state, questGiver)
creatureObject:setScreenPlayState(state, questGiver)
end
function ZicxBugBomb:removeState(creatureObject, state, questGiver)
creatureObject:removeScreenPlayState(state, questGiver)
end
-- Custom spawnNpcs to handle setting npcs as containers for quest item turnin
function ZicxBugBomb:spawnNpcs()
for i = 1, # self.npcMap do
local npcSpawnData = self.npcMap[i].spawnData
if isZoneEnabled(npcSpawnData.planetName) then
local pNpc = spawnMobile(npcSpawnData.planetName, npcSpawnData.npcTemplate, 1, npcSpawnData.x, npcSpawnData.z, npcSpawnData.y, npcSpawnData.direction, npcSpawnData.cellID)
ObjectManager.withCreatureObject(pNpc, function(npc)
if npcSpawnData.position == SIT then
npc:setState(STATESITTINGONCHAIR)
end
if (npcSpawnData.npcTemplate == "goru_rainstealer") then
ObjectManager.withSceneObject(pNpc, function(zicxNpc)
zicxNpc:setContainerComponent("ZicxContainerComponent")
end)
end
end)
end
end
end
registerScreenPlay("ZicxBugBomb", true)
zicx_bug_bomb_mission_giver_conv_handler = mission_giver_conv_handler:new {
themePark = ZicxBugBomb
}
zicx_bug_bomb_mission_target_conv_handler = mission_target_conv_handler:new {
themePark = ZicxBugBomb
}
epic_quest_zicx_bug_bomb_goru = GoruConvoHandler:new {
themePark = ZicxBugBomb
}
-- Overrides themepark logic to allow custom function to be called to be called
function ZicxBugBomb:start()
if (isZoneEnabled("rori") and isZoneEnabled("tatooine")) then
ZicxBugBomb:spawnNpcs()
self:spawnSceneObjects()
self:permissionObservers()
end
end
|
local ObjectManager = require("managers.object.object_manager")
jowir_arlensa_missions =
{
{
missionType = "confiscate",
preReq = { type = "item", itemTemplate = "object/tangible/loot/quest/quest_item_goru_calling_card.iff", destroy = true },
primarySpawns =
{
{ npcTemplate = "jowir_valarian_assassin", planetName = "tatooine", npcName = "Valarian Assassin" },
},
secondarySpawns =
{
{ npcTemplate = "valarian_assassin", planetName = "tatooine", npcName = "Valarian Assassin" },
{ npcTemplate = "valarian_enforcer", planetName = "tatooine", npcName = "Valarian Enforcer" },
{ npcTemplate = "valarian_enforcer", planetName = "tatooine", npcName = "Valarian Enforcer" },
{ npcTemplate = "valarian_henchman", planetName = "tatooine", npcName = "Valarian Henchman" },
{ npcTemplate = "valarian_scout", planetName = "tatooine", npcName = "Valarian Scout" },
},
itemSpawns =
{
{ itemTemplate = "object/tangible/loot/quest/quest_item_spice_jar.iff", itemName = "" }
},
rewards =
{
{ rewardType = "loot", lootGroup = "task_reward_jowir_arlensa" },
}
}
}
palu_zerk_missions =
{
{
missionType = "escort",
primarySpawns =
{
{ npcTemplate = "feinu_zerk", planetName = "tatooine", npcName = "Feinu Zerk" }
},
secondarySpawns = {
{ npcTemplate = "valarian_swooper_leader", planetName = "tatooine", npcName = "Valarian Swooper Leader" },
{ npcTemplate = "valarian_thug", planetName = "tatooine", npcName = "Valarian Thug" },
{ npcTemplate = "valarian_thug", planetName = "tatooine", npcName = "Valarian Thug" },
{ npcTemplate = "valarian_thug", planetName = "tatooine", npcName = "Valarian Thug" },
},
itemSpawns = {},
rewards =
{
{ rewardType = "loot", lootGroup = "task_reward_palu_zerk" },
}
},
}
npcMapZicx =
{
{
spawnData = { planetName = "rori", npcTemplate = "goru_rainstealer", x = -5431.4, z = 80, y = -2241.3, direction = 33, cellID = 0, position = STAND },
worldPosition = { x = -5430, y = -2240 },
stfFile = "@epic_quest/zicx_bug_bomb/rori_goru_rainstealer",
},
{
spawnData = { planetName = "tatooine", npcTemplate = "jowir_arlensa", x = -5252.74, z = 75, y = -6553.42, direction = 46.6563, cellID = 0, position = STAND },
worldPosition = { x = -5249, y = -6551 },
npcNumber = 1,
stfFile = "@spawning/static_npc/tato_zicx_jowir",
missions = jowir_arlensa_missions
},
{
spawnData = { planetName = "tatooine", npcTemplate = "palu_zerk", x = -5049.46, z = 75, y = -6585.53, direction = 60, cellID = 0, position = STAND },
worldPosition = { x = -5048, y = -6586 },
npcNumber = 2,
stfFile = "@spawning/static_npc/tato_zicx_palu",
missions = palu_zerk_missions
}
}
ZicxBugBomb = ThemeParkLogic:new {
numberOfActs = 1,
npcMap = npcMapZicx,
className = "ZicxBugBomb",
screenPlayState = "zicx_bug_bomb",
distance = 200,
}
ZicxContainerComponent = {}
function ZicxContainerComponent:transferObject(pContainer, pObj, slot)
local pPlayer = ZicxBugBomb:getObjOwner(pObj)
if (pPlayer == nil) then
return 0
end
return ObjectManager.withSceneObject(pObj, function(object)
return ObjectManager.withCreatureObject(pPlayer, function(player)
if player:hasScreenPlayState(1, "zicx_bug_bomb_goruNpc") ~= 1 or player:hasScreenPlayState(8, "zicx_bug_bomb_goruNpc") == 1 then
return 0
elseif (object:getTemplateObjectPath() == "object/tangible/loot/quest/quest_item_zicx_bug_jar.iff") then
if (player:hasScreenPlayState(4, "zicx_bug_bomb_goruNpc") ~= 1) then
spatialChat(pContainer, "@epic_quest/zicx_bug_bomb/rori_goru_rainstealer:get_the_bile")
else
spatialChat(pContainer, "@epic_quest/zicx_bug_bomb/rori_goru_rainstealer:give_a_minute")
end
ZicxBugBomb:setState(player, 2, "zicx_bug_bomb_goruNpc")
elseif (object:getTemplateObjectPath() == "object/tangible/loot/quest/quest_item_sarlacc_bile_jar.iff") then
if (player:hasScreenPlayState(2, "zicx_bug_bomb_goruNpc") ~= 1) then
spatialChat(pContainer, "@epic_quest/zicx_bug_bomb/rori_goru_rainstealer:get_the_bugs")
else
spatialChat(pContainer, "@epic_quest/zicx_bug_bomb/rori_goru_rainstealer:give_a_minute")
end
ZicxBugBomb:setState(player, 4, "zicx_bug_bomb_goruNpc")
else
spatialChat(pContainer, "@epic_quest/zicx_bug_bomb/rori_goru_rainstealer:what_is_this")
return 0
end
object:destroyObjectFromWorld()
object:destroyObjectFromDatabase()
return 0
end)
end)
end
function ZicxContainerComponent:canAddObject(pContainer, pObj, slot)
local pPlayer = ZicxBugBomb:getObjOwner(pObj)
if (pPlayer == nil) then
return -1
end
return ObjectManager.withCreatureObject(pPlayer, function(player)
if player:hasScreenPlayState(1, "zicx_bug_bomb_goruNpc") == 1 and player:hasScreenPlayState(8, "zicx_bug_bomb_goruNpc") ~= 1 then
return true
else
return -1
end
end)
end
function ZicxBugBomb:getObjOwner(pObj)
local pPlayerInv = SceneObject(pObj):getParent()
if (pPlayerInv == nil) then
return nil
end
local parent = SceneObject(pPlayerInv):getParent()
if (parent == nil) then
return nil
end
if (SceneObject(parent):isCreatureObject()) then
return parent
end
return nil
end
function ZicxContainerComponent:removeObject(pContainer, pObj, slot)
return -1
end
function ZicxBugBomb:setState(creatureObject, state, questGiver)
creatureObject:setScreenPlayState(state, questGiver)
end
function ZicxBugBomb:removeState(creatureObject, state, questGiver)
creatureObject:removeScreenPlayState(state, questGiver)
end
-- Custom spawnNpcs to handle setting npcs as containers for quest item turnin
function ZicxBugBomb:spawnNpcs()
for i = 1, # self.npcMap do
local npcSpawnData = self.npcMap[i].spawnData
if isZoneEnabled(npcSpawnData.planetName) then
local pNpc = spawnMobile(npcSpawnData.planetName, npcSpawnData.npcTemplate, 1, npcSpawnData.x, npcSpawnData.z, npcSpawnData.y, npcSpawnData.direction, npcSpawnData.cellID)
ObjectManager.withCreatureObject(pNpc, function(npc)
if npcSpawnData.position == SIT then
npc:setState(STATESITTINGONCHAIR)
end
if (npcSpawnData.npcTemplate == "goru_rainstealer") then
ObjectManager.withSceneObject(pNpc, function(zicxNpc)
zicxNpc:setContainerComponent("ZicxContainerComponent")
end)
end
end)
end
end
end
registerScreenPlay("ZicxBugBomb", true)
zicx_bug_bomb_mission_giver_conv_handler = mission_giver_conv_handler:new {
themePark = ZicxBugBomb
}
zicx_bug_bomb_mission_target_conv_handler = mission_target_conv_handler:new {
themePark = ZicxBugBomb
}
epic_quest_zicx_bug_bomb_goru = GoruConvoHandler:new {
themePark = ZicxBugBomb
}
-- Overrides themepark logic to allow custom function to be called to be called
function ZicxBugBomb:start()
if (isZoneEnabled("rori") and isZoneEnabled("tatooine")) then
ZicxBugBomb:spawnNpcs()
self:spawnSceneObjects()
self:permissionObservers()
end
end
|
[fixed] stability issue
|
[fixed] stability issue
Change-Id: I1881a4c06fda26409beeab44a00aca5ec1a1c94a
|
Lua
|
agpl-3.0
|
Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo
|
5a068835ce173ae2a5be2cb92fd2d66db4737404
|
hammerspoon/init.lua
|
hammerspoon/init.lua
|
-- Helper Functions
function sleep(n)
os.execute("sleep " .. tonumber(n))
end
-- Reload config on write.
function reloadConfig(files)
doReload = false
for _,file in pairs(files) do
if file:sub(-4) == ".lua" then
doReload = true
end
end
if doReload then
hs.reload()
end
end
hs.pathwatcher.new(os.getenv("HOME") .. "/.dotfiles/hammerspoon/", reloadConfig):start()
hs.alert.show("Config loaded")
-- Music Hotkeys
function displayCurrentTrack(player)
sleep(1)
if player.getCurrentTrack() then
player.displayCurrentTrack()
end
end
hs.hotkey.bind({"ctrl"}, "f7", function ()
if hs.appfinder.appFromName("iTunes") then
hs.itunes.previous()
displayCurrentTrack(hs.itunes)
elseif hs.appfinder.appFromName("Spotify") then
hs.spotify.previous()
displayCurrentTrack(hs.spotify)
end
end)
paused = false
hs.hotkey.bind({"ctrl"}, "f8", function ()
if hs.appfinder.appFromName("iTunes") then
if not paused then
paused = true
hs.itunes.pause()
else
paused = false
hs.itunes.play()
displayCurrentTrack(hs.itunes)
end
elseif hs.appfinder.appFromName("Spotify") then
if not paused then
paused = true
hs.spotify.pause()
else
paused = false
hs.spotify.play()
displayCurrentTrack(hs.spotify)
end
end
end)
hs.hotkey.bind({"ctrl"}, "f9", function ()
if hs.appfinder.appFromName("iTunes") then
hs.itunes.next()
displayCurrentTrack(hs.itunes)
elseif hs.appfinder.appFromName("Spotify") then
hs.spotify.next()
displayCurrentTrack(hs.spotify)
end
end)
hs.hotkey.bind({"ctrl"}, "f10", function ()
if hs.audiodevice.current().muted then
hs.audiodevice.defaultOutputDevice():setMuted(false)
else
hs.audiodevice.defaultOutputDevice():setMuted(true)
end
end)
hs.hotkey.bind({"ctrl"}, "f11", function ()
if hs.audiodevice.current().volume > 0 then
newVolume = math.floor(hs.audiodevice.current().volume - 5)
if newVolume < 0 then
newVolume = 0
end
hs.audiodevice.defaultOutputDevice():setVolume(newVolume)
hs.alert.show(string.format("Volume is now %.0f", newVolume))
end
end)
hs.hotkey.bind({"ctrl"}, "f12", function ()
if hs.audiodevice.current().volume < 100 then
newVolume = math.ceil(hs.audiodevice.current().volume + 5)
if newVolume > 100 then
newVolume = 100
end
hs.audiodevice.defaultOutputDevice():setVolume(newVolume)
hs.alert.show(string.format("Volume is now %.0f", newVolume))
end
end)
-- Window Hotkeys
function fullsizeWindow()
local win = hs.window.focusedWindow()
local f = win:frame()
local screen = win:screen()
local max = screen:frame()
f.x = max.x
f.y = max.y
f.w = max.w
f.h = max.h
win:setFrame(f)
end
hs.hotkey.bind({"ctrl", "alt"}, "m", fullsizeWindow)
hs.hotkey.bind({"ctrl", "alt"}, "Up", function()
local win = hs.window.focusedWindow()
local f = win:frame()
local screen = win:screen()
local max = screen:frame()
f.x = max.x
f.y = max.y
f.w = max.w
f.h = max.h / 2
win:setFrame(f)
end)
hs.hotkey.bind({"ctrl", "alt"}, "Down", function()
local win = hs.window.focusedWindow()
local f = win:frame()
local screen = win:screen()
local max = screen:frame()
f.x = max.x
f.y = max.y + (max.h / 2)
f.w = max.w
f.h = max.h / 2
win:setFrame(f)
end)
hs.hotkey.bind({"ctrl", "alt"}, "Left", function()
local win = hs.window.focusedWindow()
local f = win:frame()
local screen = win:screen()
local max = screen:frame()
f.x = max.x
f.y = max.y
f.w = max.w / 2
f.h = max.h
win:setFrame(f)
end)
hs.hotkey.bind({"ctrl", "alt"}, "Right", function()
local win = hs.window.focusedWindow()
local f = win:frame()
local screen = win:screen()
local max = screen:frame()
f.x = max.x + (max.w / 2)
f.y = max.y
f.w = max.w / 2
f.h = max.h
win:setFrame(f)
end)
-- g right
hs.hotkey.bind({"ctrl", "alt"}, "g", function()
local win = hs.window.focusedWindow()
local f = win:frame()
local w = f.w / 2
f.x = f.x + w
f.w = w
win:setFrame(f)
end)
-- d left
hs.hotkey.bind({"ctrl", "alt"}, "d", function()
local win = hs.window.focusedWindow()
local f = win:frame()
f.w = f.w / 2
win:setFrame(f)
end)
-- r up
hs.hotkey.bind({"ctrl", "alt"}, "r", function()
local win = hs.window.focusedWindow()
local f = win:frame()
f.h = f.h / 2
win:setFrame(f)
end)
-- f down
hs.hotkey.bind({"ctrl", "alt"}, "f", function()
local win = hs.window.focusedWindow()
local f = win:frame()
local h = f.h / 2
f.y = f.y + h
f.h = h
win:setFrame(f)
end)
hs.hotkey.bind({"ctrl", "alt"}, "j", function()
local win = hs.window.focusedWindow()
win:moveToScreen(win:screen():next())
end)
hs.hotkey.bind({"ctrl", "alt"}, "k", function()
local win = hs.window.focusedWindow()
win:moveToScreen(win:screen():previous())
end)
|
-- Helper Functions
function sleep(n)
os.execute("sleep " .. tonumber(n))
end
-- Reload config on write.
function reloadConfig(files)
doReload = false
for _,file in pairs(files) do
if file:sub(-4) == ".lua" then
doReload = true
end
end
if doReload then
hs.reload()
end
end
hs.pathwatcher.new(os.getenv("HOME") .. "/.dotfiles/hammerspoon/", reloadConfig):start()
hs.alert.show("Config loaded")
-- Music Hotkeys
function displayCurrentTrack(player)
sleep(1)
if player.getCurrentTrack() then
player.displayCurrentTrack()
end
end
hs.hotkey.bind({"ctrl"}, "f7", function ()
if hs.application.find("Spotify") then
hs.spotify.previous()
displayCurrentTrack(hs.spotify)
elseif hs.application.find("iTunes") then
hs.itunes.previous()
displayCurrentTrack(hs.itunes)
end
end)
paused = false
hs.hotkey.bind({"ctrl"}, "f8", function ()
if hs.application.find("Spotify") then
if not paused then
paused = true
hs.spotify.pause()
else
paused = false
hs.spotify.play()
displayCurrentTrack(hs.spotify)
end
elseif hs.application.find("iTunes") then
if not paused then
paused = true
hs.itunes.pause()
else
paused = false
hs.itunes.play()
displayCurrentTrack(hs.itunes)
end
end
end)
hs.hotkey.bind({"ctrl"}, "f9", function ()
if hs.application.find("Spotify") then
hs.spotify.next()
displayCurrentTrack(hs.spotify)
elseif hs.application.find("iTunes") then
hs.itunes.next()
displayCurrentTrack(hs.itunes)
end
end)
hs.hotkey.bind({"ctrl"}, "f10", function ()
if hs.audiodevice.current().muted then
hs.audiodevice.defaultOutputDevice():setMuted(false)
else
hs.audiodevice.defaultOutputDevice():setMuted(true)
end
end)
hs.hotkey.bind({"ctrl"}, "f11", function ()
if hs.audiodevice.current().volume > 0 then
newVolume = math.floor(hs.audiodevice.current().volume - 5)
if newVolume < 0 then
newVolume = 0
end
hs.audiodevice.defaultOutputDevice():setVolume(newVolume)
hs.alert.show(string.format("Volume is now %.0f", newVolume))
end
end)
hs.hotkey.bind({"ctrl"}, "f12", function ()
if hs.audiodevice.current().volume < 100 then
newVolume = math.ceil(hs.audiodevice.current().volume + 5)
if newVolume > 100 then
newVolume = 100
end
hs.audiodevice.defaultOutputDevice():setVolume(newVolume)
hs.alert.show(string.format("Volume is now %.0f", newVolume))
end
end)
-- Window Hotkeys
function fullsizeWindow()
local win = hs.window.focusedWindow()
local f = win:frame()
local screen = win:screen()
local max = screen:frame()
f.x = max.x
f.y = max.y
f.w = max.w
f.h = max.h
win:setFrame(f)
end
hs.hotkey.bind({"ctrl", "alt"}, "m", fullsizeWindow)
-- h for half
hs.hotkey.bind({"ctrl", "alt"}, "c", function()
local win = hs.window.focusedWindow()
local f = win:frame()
local screen = win:screen()
local max = screen:frame()
f.x = max.x
f.y = max.y + (max.h * 1/6)
f.w = max.w
f.h = max.h * 2/3
win:setFrame(f)
end)
hs.hotkey.bind({"ctrl", "alt"}, "Up", function()
local win = hs.window.focusedWindow()
local f = win:frame()
local screen = win:screen()
local max = screen:frame()
f.x = max.x
f.y = max.y
f.w = max.w
f.h = max.h / 2
win:setFrame(f)
end)
hs.hotkey.bind({"ctrl", "alt"}, "Down", function()
local win = hs.window.focusedWindow()
local f = win:frame()
local screen = win:screen()
local max = screen:frame()
f.x = max.x
f.y = max.y + (max.h / 2)
f.w = max.w
f.h = max.h / 2
win:setFrame(f)
end)
hs.hotkey.bind({"ctrl", "alt"}, "Left", function()
local win = hs.window.focusedWindow()
local f = win:frame()
local screen = win:screen()
local max = screen:frame()
f.x = max.x
f.y = max.y
f.w = max.w / 2
f.h = max.h
win:setFrame(f)
end)
hs.hotkey.bind({"ctrl", "alt"}, "Right", function()
local win = hs.window.focusedWindow()
local f = win:frame()
local screen = win:screen()
local max = screen:frame()
f.x = max.x + (max.w / 2)
f.y = max.y
f.w = max.w / 2
f.h = max.h
win:setFrame(f)
end)
-- g right
hs.hotkey.bind({"ctrl", "alt"}, "g", function()
local win = hs.window.focusedWindow()
local f = win:frame()
local w = f.w / 2
f.x = f.x + w
f.w = w
win:setFrame(f)
end)
-- d left
hs.hotkey.bind({"ctrl", "alt"}, "d", function()
local win = hs.window.focusedWindow()
local f = win:frame()
f.w = f.w / 2
win:setFrame(f)
end)
-- r up
hs.hotkey.bind({"ctrl", "alt"}, "r", function()
local win = hs.window.focusedWindow()
local f = win:frame()
f.h = f.h / 2
win:setFrame(f)
end)
-- f down
hs.hotkey.bind({"ctrl", "alt"}, "f", function()
local win = hs.window.focusedWindow()
local f = win:frame()
local h = f.h / 2
f.y = f.y + h
f.h = h
win:setFrame(f)
end)
hs.hotkey.bind({"ctrl", "alt"}, "j", function()
local win = hs.window.focusedWindow()
win:moveToScreen(win:screen():next())
end)
hs.hotkey.bind({"ctrl", "alt"}, "k", function()
local win = hs.window.focusedWindow()
win:moveToScreen(win:screen():previous())
end)
|
Fix hammerspoon music keys and add one to center a window.
|
Fix hammerspoon music keys and add one to center a window.
|
Lua
|
mit
|
squaresurf/dotfiles,squaresurf/dotfiles,squaresurf/dotfiles
|
a30df2a269e57cf15e5a9f29022aa2e3d08cbebc
|
src/patch/ui/hooks/after_stagingroom.lua
|
src/patch/ui/hooks/after_stagingroom.lua
|
if _mpPatch and _mpPatch.enabled and _mpPatch.isModding then
local confirmChat = "mppatch:gamelaunchcountdown:WgUUz7wWuxWFmjY02WFS0mka53nFDzJvD00zmuQHKyJT2wNHuWZvrDcejHv5rTyl"
local gameLaunchSet = false
local gameLaunchCountdown = 3
local StartCountdownOld = StartCountdown
function StartCountdown(...)
if gameLaunchSet then return end
return StartCountdownOld(...)
end
local StopCountdownOld = StopCountdown
function StopCountdown(...)
if gameLaunchSet then return end
return StopCountdownOld(...)
end
local HandleExitRequestOld = HandleExitRequest
function HandleExitRequest(...)
if gameLaunchSet then return end
return HandleExitRequestOld(...)
end
local LaunchGameOld = LaunchGame
local function LaunchGameCountdown(timeDiff)
gameLaunchCountdown = gameLaunchCountdown - timeDiff
if gameLaunchCountdown <= 0 then
LaunchGameOld()
ContextPtr:ClearUpdate()
end
end
function LaunchGame(...)
if PreGame.IsHotSeatGame() then
return LaunchGameOld(...)
else
SendChat(confirmChat)
ContextPtr:ClearUpdate()
gameLaunchSet = true
ContextPtr:SetUpdate(LaunchGameCountdown)
end
end
Controls.LaunchButton:RegisterCallback(Mouse.eLClick, LaunchGame)
local OnChatOld = OnChat
function OnChat(...)
local fromPlayer, toPlayer, text = ...
if and fromPlayer == m_HostID and text == confirmChat then
if not Matchmaking.IsHost() then
gameLaunchSet = true
_mpPatch.overrideModsFromPreGame()
end
return
end
return OnChatOld(...)
end
local DequeuePopup = UIManager.DequeuePopup
_mpPatch.patch.globals.rawset(UIManager, "DequeuePopup", function(this, ...)
local context = ...
if context == ContextPtr and not Matchmaking.IsHost() then
_mpPatch.debugPrint("Cancelling override.")
_mpPatch.patch.NetPatch.reset()
end
return DequeuePopup(UIManager, ...)
end)
end
|
if _mpPatch and _mpPatch.enabled and _mpPatch.isModding then
local confirmChat = "mppatch:gamelaunchcountdown:WgUUz7wWuxWFmjY02WFS0mka53nFDzJvD00zmuQHKyJT2wNHuWZvrDcejHv5rTyl"
local gameLaunchSet = false
local gameLaunchCountdown = 3
local StartCountdownOld = StartCountdown
function StartCountdown(...)
if gameLaunchSet then return end
return StartCountdownOld(...)
end
local StopCountdownOld = StopCountdown
function StopCountdown(...)
if gameLaunchSet then return end
return StopCountdownOld(...)
end
local HandleExitRequestOld = HandleExitRequest
function HandleExitRequest(...)
if gameLaunchSet then return end
return HandleExitRequestOld(...)
end
local LaunchGameOld = LaunchGame
local function LaunchGameCountdown(timeDiff)
gameLaunchCountdown = gameLaunchCountdown - timeDiff
if gameLaunchCountdown <= 0 then
LaunchGameOld()
ContextPtr:ClearUpdate()
end
end
function LaunchGame(...)
if PreGame.IsHotSeatGame() then
return LaunchGameOld(...)
else
SendChat(confirmChat)
ContextPtr:ClearUpdate()
gameLaunchSet = true
ContextPtr:SetUpdate(LaunchGameCountdown)
end
end
Controls.LaunchButton:RegisterCallback(Mouse.eLClick, LaunchGame)
local OnChatOld = OnChat
function OnChat(...)
local fromPlayer, _, text = ...
if not ContextPtr:IsHidden() and m_PlayerNames[fromPlayer] and
fromPlayer == m_HostID and text == confirmChat then
if not Matchmaking.IsHost() then
gameLaunchSet = true
_mpPatch.overrideModsFromPreGame()
end
return
end
return OnChatOld(...)
end
Events.GameMessageChat.Remove(OnChatOld)
Events.GameMessageChat.Add(OnChat)
local DequeuePopup = UIManager.DequeuePopup
_mpPatch.patch.globals.rawset(UIManager, "DequeuePopup", function(this, ...)
local context = ...
if context == ContextPtr and not Matchmaking.IsHost() then
_mpPatch.debugPrint("Cancelling override.")
_mpPatch.patch.NetPatch.reset()
end
return DequeuePopup(UIManager, ...)
end)
end
|
Fix stagingroom more.
|
Fix stagingroom more.
|
Lua
|
mit
|
Lymia/MPPatch,Lymia/MultiverseModManager,Lymia/MPPatch,Lymia/MultiverseModManager,Lymia/MPPatch,Lymia/MPPatch,Lymia/CivV_Mod2DLC
|
788fd7cdca9d681763a31df05b98a234733d3402
|
xmake/actions/install/install.lua
|
xmake/actions/install/install.lua
|
--!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015 - 2019, TBOOX Open Source Group.
--
-- @author ruki
-- @file install.lua
--
-- imports
import("core.base.task")
import("core.project.rule")
import("core.project.project")
-- install files
function _install_files(target)
local srcfiles, dstfiles = target:installfiles()
if srcfiles and dstfiles then
local i = 1
for _, srcfile in ipairs(srcfiles) do
local dstfile = dstfiles[i]
if dstfile then
os.vcp(srcfile, dstfile)
end
i = i + 1
end
end
end
-- install binary
function _install_binary(target)
-- is phony target?
if target:isphony() then
return
end
-- the binary directory
local binarydir = path.join(target:installdir(), "bin")
-- make the binary directory
os.mkdir(binarydir)
-- copy the target file
os.vcp(target:targetfile(), binarydir)
end
-- install library
function _install_library(target)
-- is phony target?
if target:isphony() then
return
end
-- the library directory
local librarydir = path.join(target:installdir(), "lib")
-- the include directory
local includedir = path.join(target:installdir(), "include")
-- make the library directory
os.mkdir(librarydir)
-- make the include directory
os.mkdir(includedir)
-- copy the target file
os.vcp(target:targetfile(), librarydir)
-- copy headers to the include directory
local srcheaders, dstheaders = target:headerfiles(includedir)
if srcheaders and dstheaders then
local i = 1
for _, srcheader in ipairs(srcheaders) do
local dstheader = dstheaders[i]
if dstheader then
os.vcp(srcheader, dstheader)
end
i = i + 1
end
end
end
-- do install target
function _do_install_target(target)
-- the scripts
local scripts =
{
binary = _install_binary
, static = _install_library
, shared = _install_library
}
-- call script
local script = scripts[target:targetkind()]
if script then
script(target)
end
-- install other files
_install_files(target)
end
-- on install target
function _on_install_target(target)
-- has been disabled?
if target:get("enabled") == false then
return
end
-- get install directory
local installdir = target:installdir()
if not installdir then
return
end
-- trace
print("installing %s to %s ...", target:name(), installdir)
-- build target with rules
local done = false
for _, r in ipairs(target:orderules()) do
local on_install = r:script("install")
if on_install then
on_install(target, {origin = _do_install_target})
done = true
end
end
if done then return end
-- do install
_do_install_target(target)
end
-- install the given target
function _install_target(target)
-- enter project directory
local oldir = os.cd(project.directory())
-- enter the environments of the target packages
local oldenvs = {}
for name, values in pairs(target:pkgenvs()) do
oldenvs[name] = os.getenv(name)
os.addenv(name, unpack(values))
end
-- the target scripts
local scripts =
{
target:script("install_before")
, function (target)
-- has been disabled?
if target:get("enabled") == false then
return
end
-- install rules
for _, r in ipairs(target:orderules()) do
local before_install = r:script("install_before")
if before_install then
before_install(target)
end
end
end
, target:script("install", _on_install_target)
, function (target)
-- has been disabled?
if target:get("enabled") == false then
return
end
-- install rules
for _, r in ipairs(target:orderules()) do
local after_install = r:script("install_after")
if after_install then
after_install(target)
end
end
end
, target:script("install_after")
}
-- install the target scripts
for i = 1, 5 do
local script = scripts[i]
if script ~= nil then
script(target, {origin = (i == 3 and _do_install_target or nil)})
end
end
-- leave the environments of the target packages
for name, values in pairs(oldenvs) do
os.setenv(name, values)
end
-- leave project directory
os.cd(oldir)
end
-- install the given target and deps
function _install_target_and_deps(target)
-- this target have been finished?
if _g.finished[target:name()] then
return
end
-- install for all dependent targets
for _, depname in ipairs(target:get("deps")) do
_install_target_and_deps(project.target(depname))
end
-- install target
_install_target(target)
-- finished
_g.finished[target:name()] = true
end
-- install targets
function main(targetname)
-- init finished states
_g.finished = {}
-- install the given target?
if targetname and not targetname:startswith("__") then
_install_target_and_deps(project.target(targetname))
else
-- install default or all targets
for _, target in pairs(project.targets()) do
local default = target:get("default")
if default == nil or default == true or targetname == "__all" then
_install_target_and_deps(target)
end
end
end
end
|
--!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015 - 2019, TBOOX Open Source Group.
--
-- @author ruki
-- @file install.lua
--
-- imports
import("core.base.task")
import("core.project.rule")
import("core.project.project")
-- install files
function _install_files(target)
local srcfiles, dstfiles = target:installfiles()
if srcfiles and dstfiles then
local i = 1
for _, srcfile in ipairs(srcfiles) do
local dstfile = dstfiles[i]
if dstfile then
os.vcp(srcfile, dstfile)
end
i = i + 1
end
end
end
-- install binary
function _install_binary(target)
-- is phony target?
if target:isphony() then
return
end
-- the binary directory
local binarydir = path.join(target:installdir(), "bin")
-- make the binary directory
os.mkdir(binarydir)
-- copy the target file
os.vcp(target:targetfile(), binarydir)
end
-- install library
function _install_library(target)
-- is phony target?
if target:isphony() then
return
end
-- the library directory
local librarydir = path.join(target:installdir(), "lib")
-- the include directory
local includedir = path.join(target:installdir(), "include")
-- make the library directory
os.mkdir(librarydir)
-- make the include directory
os.mkdir(includedir)
-- copy the target file
os.vcp(target:targetfile(), librarydir)
-- copy headers to the include directory
local srcheaders, dstheaders = target:headerfiles(includedir)
if srcheaders and dstheaders then
local i = 1
for _, srcheader in ipairs(srcheaders) do
local dstheader = dstheaders[i]
if dstheader then
os.vcp(srcheader, dstheader)
end
i = i + 1
end
end
end
-- do install target
function _do_install_target(target)
-- get install directory
local installdir = target:installdir()
if not installdir then
return
end
-- trace
print("installing to %s ...", installdir)
-- the scripts
local scripts =
{
binary = _install_binary
, static = _install_library
, shared = _install_library
}
-- call script
local script = scripts[target:targetkind()]
if script then
script(target)
end
-- install other files
_install_files(target)
end
-- on install target
function _on_install_target(target)
-- has been disabled?
if target:get("enabled") == false then
return
end
-- trace
print("installing %s ...", target:name())
-- build target with rules
local done = false
for _, r in ipairs(target:orderules()) do
local on_install = r:script("install")
if on_install then
on_install(target, {origin = _do_install_target})
done = true
end
end
if done then return end
-- do install
_do_install_target(target)
end
-- install the given target
function _install_target(target)
-- enter project directory
local oldir = os.cd(project.directory())
-- enter the environments of the target packages
local oldenvs = {}
for name, values in pairs(target:pkgenvs()) do
oldenvs[name] = os.getenv(name)
os.addenv(name, unpack(values))
end
-- the target scripts
local scripts =
{
target:script("install_before")
, function (target)
-- has been disabled?
if target:get("enabled") == false then
return
end
-- install rules
for _, r in ipairs(target:orderules()) do
local before_install = r:script("install_before")
if before_install then
before_install(target)
end
end
end
, target:script("install", _on_install_target)
, function (target)
-- has been disabled?
if target:get("enabled") == false then
return
end
-- install rules
for _, r in ipairs(target:orderules()) do
local after_install = r:script("install_after")
if after_install then
after_install(target)
end
end
end
, target:script("install_after")
}
-- install the target scripts
for i = 1, 5 do
local script = scripts[i]
if script ~= nil then
script(target, {origin = (i == 3 and _do_install_target or nil)})
end
end
-- leave the environments of the target packages
for name, values in pairs(oldenvs) do
os.setenv(name, values)
end
-- leave project directory
os.cd(oldir)
end
-- install the given target and deps
function _install_target_and_deps(target)
-- this target have been finished?
if _g.finished[target:name()] then
return
end
-- install for all dependent targets
for _, depname in ipairs(target:get("deps")) do
_install_target_and_deps(project.target(depname))
end
-- install target
_install_target(target)
-- finished
_g.finished[target:name()] = true
end
-- install targets
function main(targetname)
-- init finished states
_g.finished = {}
-- install the given target?
if targetname and not targetname:startswith("__") then
_install_target_and_deps(project.target(targetname))
else
-- install default or all targets
for _, target in pairs(project.targets()) do
local default = target:get("default")
if default == nil or default == true or targetname == "__all" then
_install_target_and_deps(target)
end
end
end
end
|
fix install tips
|
fix install tips
|
Lua
|
apache-2.0
|
waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake
|
2be2fca375588dd502ad2336e6d657b663afea2b
|
applications/luci-firewall/luasrc/model/cbi/firewall/zone-details.lua
|
applications/luci-firewall/luasrc/model/cbi/firewall/zone-details.lua
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
local nw = require "luci.model.network"
local fw = require "luci.model.firewall"
local ds = require "luci.dispatcher"
local ut = require "luci.util"
local m, p, i, v
local s, name, net, family, msrc, mdest, log, lim
local s2, out, inp
m = Map("firewall", translate("Firewall - Zone Settings"))
m.redirect = luci.dispatcher.build_url("admin/network/firewall/zones")
fw.init(m.uci)
nw.init(m.uci)
local zone = fw:get_zone(arg[1])
if not zone then
luci.http.redirect(dsp.build_url("admin/network/firewall/zones"))
return
else
m.title = "%s - %s" %{
translate("Firewall - Zone Settings"),
translatef("Zone %q", zone:name() or "?")
}
end
s = m:section(NamedSection, zone.sid, "zone",
translatef("Zone %q", zone:name()),
translatef("This section defines common properties of %q. \
The <em>input</em> and <em>output</em> options set the default \
policies for traffic entering and leaving this zone while the \
<em>forward</em> option describes the policy for forwarded traffic \
between different networks within the zone. \
<em>Covered networks</em> specifies which available networks are \
member of this zone.", zone:name()))
s.anonymous = true
s.addremove = false
m.on_commit = function(map)
local zone = fw:get_zone(arg[1])
if zone then
s.section = zone.sid
s2.section = zone.sid
end
end
s:tab("general", translate("General Settings"))
s:tab("advanced", translate("Advanced Settings"))
name = s:taboption("general", Value, "name", translate("Name"))
name.optional = false
name.forcewrite = true
name.datatype = "uciname"
function name.write(self, section, value)
if zone:name() ~= value then
fw:rename_zone(zone:name(), value)
out.exclude = value
inp.exclude = value
end
m.redirect = ds.build_url("admin/network/firewall/zones", value)
m.title = "%s - %s" %{
translate("Firewall - Zone Settings"),
translatef("Zone %q", value or "?")
}
end
p = {
s:taboption("general", ListValue, "input", translate("Input")),
s:taboption("general", ListValue, "output", translate("Output")),
s:taboption("general", ListValue, "forward", translate("Forward"))
}
for i, v in ipairs(p) do
v:value("REJECT", translate("reject"))
v:value("DROP", translate("drop"))
v:value("ACCEPT", translate("accept"))
end
s:taboption("general", Flag, "masq", translate("Masquerading"))
s:taboption("general", Flag, "mtu_fix", translate("MSS clamping"))
net = s:taboption("general", Value, "network", translate("Covered networks"))
net.template = "cbi/network_netlist"
net.widget = "checkbox"
net.cast = "string"
function net.formvalue(self, section)
return Value.formvalue(self, section) or "-"
end
function net.cfgvalue(self, section)
return Value.cfgvalue(self, section) or name:cfgvalue(section)
end
function net.write(self, section, value)
zone:clear_networks()
local n
for n in ut.imatch(value) do
zone:add_network(n)
end
end
family = s:taboption("advanced", ListValue, "family",
translate("Restrict to address family"))
family.rmempty = true
family:value("", translate("IPv4 and IPv6"))
family:value("ipv4", translate("IPv4 only"))
family:value("ipv6", translate("IPv6 only"))
msrc = s:taboption("advanced", DynamicList, "masq_src",
translate("Restrict Masquerading to given source subnets"))
msrc.optional = true
msrc.datatype = "neg_network_ip4addr"
msrc.placeholder = "0.0.0.0/0"
msrc:depends("family", "")
msrc:depends("family", "ipv4")
mdest = s:taboption("advanced", DynamicList, "masq_dest",
translate("Restrict Masquerading to given destination subnets"))
mdest.optional = true
mdest.datatype = "neg_network_ip4addr"
mdest.placeholder = "0.0.0.0/0"
mdest:depends("family", "")
mdest:depends("family", "ipv4")
s:taboption("advanced", Flag, "conntrack",
translate("Force connection tracking"))
log = s:taboption("advanced", Flag, "log",
translate("Enable logging on this zone"))
log.rmempty = true
log.enabled = "1"
lim = s:taboption("advanced", Value, "log_limit",
translate("Limit log messages"))
lim.placeholder = "10/minute"
lim:depends("log", "1")
s2 = m:section(NamedSection, zone.sid, "fwd_out",
translate("Inter-Zone Forwarding"),
translatef("The options below control the forwarding policies between \
this zone (%s) and other zones. <em>Destination zones</em> cover \
forwarded traffic <strong>originating from %q</strong>. \
<em>Source zones</em> match forwarded traffic from other zones \
<strong>targeted at %q</strong>. The forwarding rule is \
<em>unidirectional</em>, e.g. a forward from lan to wan does \
<em>not</em> imply a permission to forward from wan to lan as well.",
zone:name(), zone:name(), zone:name()
))
out = s2:option(Value, "out",
translate("Allow forward to <em>destination zones</em>:"))
out.nocreate = true
out.widget = "checkbox"
out.exclude = zone:name()
out.template = "cbi/firewall_zonelist"
inp = s2:option(Value, "in",
translate("Allow forward from <em>source zones</em>:"))
inp.nocreate = true
inp.widget = "checkbox"
inp.exclude = zone:name()
inp.template = "cbi/firewall_zonelist"
function out.cfgvalue(self, section)
local v = { }
local f
for _, f in ipairs(zone:get_forwardings_by("src")) do
v[#v+1] = f:dest()
end
return table.concat(v, " ")
end
function inp.cfgvalue(self, section)
local v = { }
local f
for _, f in ipairs(zone:get_forwardings_by("dest")) do
v[#v+1] = f:src()
end
return v
end
function out.formvalue(self, section)
return Value.formvalue(self, section) or "-"
end
function inp.formvalue(self, section)
return Value.formvalue(self, section) or "-"
end
function out.write(self, section, value)
zone:del_forwardings_by("src")
local f
for f in ut.imatch(value) do
zone:add_forwarding_to(f)
end
end
function inp.write(self, section, value)
zone:del_forwardings_by("dest")
local f
for f in ut.imatch(value) do
zone:add_forwarding_from(f)
end
end
return m
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <[email protected]>
Copyright 2010-2011 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$
]]--
local nw = require "luci.model.network"
local fw = require "luci.model.firewall"
local ds = require "luci.dispatcher"
local ut = require "luci.util"
local m, p, i, v
local s, name, net, family, msrc, mdest, log, lim
local s2, out, inp
m = Map("firewall", translate("Firewall - Zone Settings"))
m.redirect = luci.dispatcher.build_url("admin/network/firewall/zones")
fw.init(m.uci)
nw.init(m.uci)
local zone = fw:get_zone(arg[1])
if not zone then
luci.http.redirect(dsp.build_url("admin/network/firewall/zones"))
return
else
m.title = "%s - %s" %{
translate("Firewall - Zone Settings"),
translatef("Zone %q", zone:name() or "?")
}
end
s = m:section(NamedSection, zone.sid, "zone",
translatef("Zone %q", zone:name()),
translatef("This section defines common properties of %q. \
The <em>input</em> and <em>output</em> options set the default \
policies for traffic entering and leaving this zone while the \
<em>forward</em> option describes the policy for forwarded traffic \
between different networks within the zone. \
<em>Covered networks</em> specifies which available networks are \
member of this zone.", zone:name()))
s.anonymous = true
s.addremove = false
m.on_commit = function(map)
local zone = fw:get_zone(arg[1])
if zone then
s.section = zone.sid
s2.section = zone.sid
end
end
s:tab("general", translate("General Settings"))
s:tab("advanced", translate("Advanced Settings"))
name = s:taboption("general", Value, "name", translate("Name"))
name.optional = false
name.forcewrite = true
name.datatype = "uciname"
function name.write(self, section, value)
if zone:name() ~= value then
fw:rename_zone(zone:name(), value)
out.exclude = value
inp.exclude = value
end
m.redirect = ds.build_url("admin/network/firewall/zones", value)
m.title = "%s - %s" %{
translate("Firewall - Zone Settings"),
translatef("Zone %q", value or "?")
}
end
p = {
s:taboption("general", ListValue, "input", translate("Input")),
s:taboption("general", ListValue, "output", translate("Output")),
s:taboption("general", ListValue, "forward", translate("Forward"))
}
for i, v in ipairs(p) do
v:value("REJECT", translate("reject"))
v:value("DROP", translate("drop"))
v:value("ACCEPT", translate("accept"))
end
s:taboption("general", Flag, "masq", translate("Masquerading"))
s:taboption("general", Flag, "mtu_fix", translate("MSS clamping"))
net = s:taboption("general", Value, "network", translate("Covered networks"))
net.template = "cbi/network_netlist"
net.widget = "checkbox"
net.cast = "string"
function net.formvalue(self, section)
return Value.formvalue(self, section) or "-"
end
function net.cfgvalue(self, section)
return Value.cfgvalue(self, section) or name:cfgvalue(section)
end
function net.write(self, section, value)
zone:clear_networks()
local n
for n in ut.imatch(value) do
zone:add_network(n)
end
end
family = s:taboption("advanced", ListValue, "family",
translate("Restrict to address family"))
family.rmempty = true
family:value("", translate("IPv4 and IPv6"))
family:value("ipv4", translate("IPv4 only"))
family:value("ipv6", translate("IPv6 only"))
msrc = s:taboption("advanced", DynamicList, "masq_src",
translate("Restrict Masquerading to given source subnets"))
msrc.optional = true
msrc.datatype = "list(neg,network)"
msrc.placeholder = "0.0.0.0/0"
msrc:depends("family", "")
msrc:depends("family", "ipv4")
mdest = s:taboption("advanced", DynamicList, "masq_dest",
translate("Restrict Masquerading to given destination subnets"))
mdest.optional = true
mdest.datatype = "list(neg,network)"
mdest.placeholder = "0.0.0.0/0"
mdest:depends("family", "")
mdest:depends("family", "ipv4")
s:taboption("advanced", Flag, "conntrack",
translate("Force connection tracking"))
log = s:taboption("advanced", Flag, "log",
translate("Enable logging on this zone"))
log.rmempty = true
log.enabled = "1"
lim = s:taboption("advanced", Value, "log_limit",
translate("Limit log messages"))
lim.placeholder = "10/minute"
lim:depends("log", "1")
s2 = m:section(NamedSection, zone.sid, "fwd_out",
translate("Inter-Zone Forwarding"),
translatef("The options below control the forwarding policies between \
this zone (%s) and other zones. <em>Destination zones</em> cover \
forwarded traffic <strong>originating from %q</strong>. \
<em>Source zones</em> match forwarded traffic from other zones \
<strong>targeted at %q</strong>. The forwarding rule is \
<em>unidirectional</em>, e.g. a forward from lan to wan does \
<em>not</em> imply a permission to forward from wan to lan as well.",
zone:name(), zone:name(), zone:name()
))
out = s2:option(Value, "out",
translate("Allow forward to <em>destination zones</em>:"))
out.nocreate = true
out.widget = "checkbox"
out.exclude = zone:name()
out.template = "cbi/firewall_zonelist"
inp = s2:option(Value, "in",
translate("Allow forward from <em>source zones</em>:"))
inp.nocreate = true
inp.widget = "checkbox"
inp.exclude = zone:name()
inp.template = "cbi/firewall_zonelist"
function out.cfgvalue(self, section)
local v = { }
local f
for _, f in ipairs(zone:get_forwardings_by("src")) do
v[#v+1] = f:dest()
end
return table.concat(v, " ")
end
function inp.cfgvalue(self, section)
local v = { }
local f
for _, f in ipairs(zone:get_forwardings_by("dest")) do
v[#v+1] = f:src()
end
return v
end
function out.formvalue(self, section)
return Value.formvalue(self, section) or "-"
end
function inp.formvalue(self, section)
return Value.formvalue(self, section) or "-"
end
function out.write(self, section, value)
zone:del_forwardings_by("src")
local f
for f in ut.imatch(value) do
zone:add_forwarding_to(f)
end
end
function inp.write(self, section, value)
zone:del_forwardings_by("dest")
local f
for f in ut.imatch(value) do
zone:add_forwarding_from(f)
end
end
return m
|
applications/luci-firewall: fix datatype validation for masq src/dest; allow list of negated ucinames, hostnames, ip-ranges or -addresses
|
applications/luci-firewall: fix datatype validation for masq src/dest; allow list of negated ucinames, hostnames, ip-ranges or -addresses
git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@8154 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
|
3cffc5e5de199d944fef4298a629fef30efbedc1
|
game/scripts/vscripts/items/item_scythe_of_the_ancients.lua
|
game/scripts/vscripts/items/item_scythe_of_the_ancients.lua
|
LinkLuaModifier("modifier_item_scythe_of_the_ancients_passive", "items/item_scythe_of_the_ancients.lua", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_item_scythe_of_the_ancients_stun", "items/item_scythe_of_the_ancients.lua", LUA_MODIFIER_MOTION_NONE)
item_scythe_of_the_ancients = class({
GetIntrinsicModifierName = function() return "modifier_item_scythe_of_the_ancients_passive" end,
})
if IsServer() then
function item_scythe_of_the_ancients:OnSpellStart()
local caster = self:GetCaster()
local target = self:GetCursorTarget()
if not target:TriggerSpellAbsorb(self) then
target:TriggerSpellReflect(self)
local particle = ParticleManager:CreateParticle("particles/econ/events/ti4/dagon_beam_black_ti4.vpcf", PATTACH_ABSORIGIN_FOLLOW, caster)
ParticleManager:SetParticleControlEnt(particle, 1, target, PATTACH_POINT_FOLLOW, "attach_hitloc", target:GetAbsOrigin(), false)
ParticleManager:SetParticleControl(particle, 1, Vector(800))
caster:EmitSound("DOTA_Item.Dagon.Activate")
target:EmitSound("DOTA_Item.Dagon5.Target")
caster:EmitSound("Hero_Necrolyte.ReapersScythe.Cast")
target:EmitSound("Hero_Necrolyte.ReapersScythe.Target")
ApplyDamage({
attacker = caster,
victim = target,
damage = self:GetSpecialValueFor("cast_damage") + (self:GetSpecialValueFor("cast_damage_pct") * target:GetHealth() * 0.01),
damage_type = self:GetAbilityDamageType(),
damage_flags = DOTA_DAMAGE_FLAG_NO_SPELL_AMPLIFICATION,
ability = self
})
target:AddNewModifier(caster, self, "modifier_item_scythe_of_the_ancients_stun", {duration = self:GetSpecialValueFor("stun_duration")})
end
end
end
modifier_item_scythe_of_the_ancients_passive = class({
RemoveOnDeath = function() return false end,
IsHidden = function() return true end,
GetAttributes = function() return MODIFIER_ATTRIBUTE_MULTIPLE end,
IsPurgable = function() return false end,
})
function modifier_item_scythe_of_the_ancients_passive:DeclareFunctions()
return {
MODIFIER_EVENT_ON_TAKEDAMAGE,
MODIFIER_PROPERTY_IS_SCEPTER,
MODIFIER_PROPERTY_STATS_STRENGTH_BONUS,
MODIFIER_PROPERTY_STATS_AGILITY_BONUS,
MODIFIER_PROPERTY_STATS_INTELLECT_BONUS,
MODIFIER_PROPERTY_HEALTH_BONUS,
MODIFIER_PROPERTY_MANA_BONUS,
MODIFIER_PROPERTY_HEALTH_REGEN_CONSTANT,
MODIFIER_PROPERTY_MANA_REGEN_CONSTANT,
MODIFIER_PROPERTY_CAST_RANGE_BONUS,
MODIFIER_PROPERTY_SPELL_AMPLIFY_PERCENTAGE,
MODIFIER_PROPERTY_TOTALDAMAGEOUTGOING_PERCENTAGE
}
end
function modifier_item_scythe_of_the_ancients_passive:GetModifierScepter()
return 1
end
function modifier_item_scythe_of_the_ancients_passive:GetModifierBonusStats_Strength()
return self:GetAbility():GetSpecialValueFor("bonus_strength")
end
function modifier_item_scythe_of_the_ancients_passive:GetModifierBonusStats_Agility()
return self:GetAbility():GetSpecialValueFor("bonus_agility")
end
function modifier_item_scythe_of_the_ancients_passive:GetModifierBonusStats_Intellect()
return self:GetAbility():GetSpecialValueFor("bonus_intellect")
end
function modifier_item_scythe_of_the_ancients_passive:GetModifierSpellAmplify_Percentage()
return self:GetAbility():GetSpecialValueFor("spell_amp_pct")
end
function modifier_item_scythe_of_the_ancients_passive:GetModifierConstantHealthRegen()
return self:GetAbility():GetSpecialValueFor("bonus_health_regen")
end
function modifier_item_scythe_of_the_ancients_passive:GetModifierHealthBonus()
return self:GetAbility():GetSpecialValueFor("bonus_health")
end
function modifier_item_scythe_of_the_ancients_passive:GetModifierManaBonus()
return self:GetAbility():GetSpecialValueFor("bonus_mana")
end
function modifier_item_scythe_of_the_ancients_passive:GetModifierConstantManaRegen()
return self:GetAbility():GetSpecialValueFor("bonus_mana_regen")
end
function modifier_item_scythe_of_the_ancients_passive:GetModifierCastRangeBonus()
return self:GetAbility():GetSpecialValueFor("cast_range_bonus")
end
function modifier_item_scythe_of_the_ancients_passive:GetModifierTotalDamageOutgoing_Percentage()
return self:GetAbility():GetSpecialValueFor("all_damage_bonus_pct")
end
if IsServer() then
function modifier_item_scythe_of_the_ancients_passive:OnCreated()
local parent = self:GetParent()
for i = 0, parent:GetAbilityCount() - 1 do
local ability = parent:GetAbilityByIndex(i)
if ability and ability:GetKeyValue("IsGrantedByScepter") == 1 then
if ability:GetKeyValue("ScepterGrantedLevel") ~= 0 then
ability:SetLevel(1)
end
ability:SetHidden(false)
end
end
end
function modifier_item_scythe_of_the_ancients_passive:OnDestroy()
local parent = self:GetParent()
if not parent:HasScepter() then
for i = 0, parent:GetAbilityCount() - 1 do
local ability = parent:GetAbilityByIndex(i)
if ability and ability:GetKeyValue("IsGrantedByScepter") == 1 then
if ability:GetKeyValue("ScepterGrantedLevel") ~= 0 then
ability:SetLevel(0)
end
ability:SetHidden(true)
end
end
end
end
function modifier_item_scythe_of_the_ancients_passive:OnTakeDamage(keys)
local parent = self:GetParent()
local damage = keys.original_damage
local ability = self:GetAbility()
if keys.attacker == parent and not keys.unit:IsMagicImmune() and keys.damage_type == 2 then
ApplyDamage({
attacker = parent,
victim = keys.unit,
damage = keys.original_damage * ability:GetSpecialValueFor("magic_damage_to_pure_pct") * 0.01,
damage_type = ability:GetAbilityDamageType(),
damage_flags = DOTA_DAMAGE_FLAG_NO_SPELL_AMPLIFICATION,
ability = ability
})
end
end
end
modifier_item_scythe_of_the_ancients_stun = class({
IsHidden = function() return false end,
IsPurgable = function() return false end,
})
if IsServer() then
function modifier_item_scythe_of_the_ancients_stun:OnCreated()
local parent = self:GetParent()
self.particle = ParticleManager:CreateParticle("particles/arena/items_fx/scythe_of_the_ancients_start.vpcf", PATTACH_ABSORIGIN_FOLLOW, parent)
ParticleManager:SetParticleControlEnt(self.particle, 1, self:GetParent(), PATTACH_POINT_FOLLOW, "attach_hitloc", parent:GetAbsOrigin(), true)
end
function modifier_item_scythe_of_the_ancients_stun:OnDestroy()
local ability = self:GetAbility()
local caster = self:GetCaster()
local target = self:GetParent()
local team = caster:GetTeamNumber()
ParticleManager:DestroyParticle(self.particle, false)
local damage = (target:GetMaxHealth() - target:GetHealth()) * ability:GetSpecialValueFor("delayed_damage_per_health")
ApplyDamage({
attacker = caster,
victim = target,
damage = damage,
damage_type = ability:GetAbilityDamageType(),
damage_flags = DOTA_DAMAGE_FLAG_NO_SPELL_AMPLIFICATION,
ability = ability
})
end
end
function modifier_item_scythe_of_the_ancients_stun:CheckState()
return {
[ MODIFIER_STATE_STUNNED ] = true,
[ MODIFIER_STATE_PROVIDES_VISION ] = true,
}
end
|
LinkLuaModifier("modifier_item_scythe_of_the_ancients_passive", "items/item_scythe_of_the_ancients.lua", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_item_scythe_of_the_ancients_stun", "items/item_scythe_of_the_ancients.lua", LUA_MODIFIER_MOTION_NONE)
item_scythe_of_the_ancients = class({
GetIntrinsicModifierName = function() return "modifier_item_scythe_of_the_ancients_passive" end,
})
if IsServer() then
function item_scythe_of_the_ancients:OnSpellStart()
local caster = self:GetCaster()
local target = self:GetCursorTarget()
if not target:TriggerSpellAbsorb(self) then
target:TriggerSpellReflect(self)
local particle = ParticleManager:CreateParticle("particles/econ/events/ti4/dagon_beam_black_ti4.vpcf", PATTACH_ABSORIGIN_FOLLOW, caster)
ParticleManager:SetParticleControlEnt(particle, 1, target, PATTACH_POINT_FOLLOW, "attach_hitloc", target:GetAbsOrigin(), false)
ParticleManager:SetParticleControl(particle, 1, Vector(800))
caster:EmitSound("DOTA_Item.Dagon.Activate")
target:EmitSound("DOTA_Item.Dagon5.Target")
caster:EmitSound("Hero_Necrolyte.ReapersScythe.Cast")
target:EmitSound("Hero_Necrolyte.ReapersScythe.Target")
ApplyDamage({
attacker = caster,
victim = target,
damage = self:GetSpecialValueFor("cast_damage") + (self:GetSpecialValueFor("cast_damage_pct") * target:GetHealth() * 0.01),
damage_type = self:GetAbilityDamageType(),
damage_flags = DOTA_DAMAGE_FLAG_NO_SPELL_AMPLIFICATION,
ability = self
})
target:AddNewModifier(caster, self, "modifier_item_scythe_of_the_ancients_stun", {duration = self:GetSpecialValueFor("stun_duration")})
end
end
end
modifier_item_scythe_of_the_ancients_passive = class({
RemoveOnDeath = function() return false end,
IsHidden = function() return true end,
GetAttributes = function() return MODIFIER_ATTRIBUTE_MULTIPLE end,
IsPurgable = function() return false end,
})
function modifier_item_scythe_of_the_ancients_passive:DeclareFunctions()
return {
MODIFIER_EVENT_ON_TAKEDAMAGE,
MODIFIER_PROPERTY_IS_SCEPTER,
MODIFIER_PROPERTY_STATS_STRENGTH_BONUS,
MODIFIER_PROPERTY_STATS_AGILITY_BONUS,
MODIFIER_PROPERTY_STATS_INTELLECT_BONUS,
MODIFIER_PROPERTY_HEALTH_BONUS,
MODIFIER_PROPERTY_MANA_BONUS,
MODIFIER_PROPERTY_HEALTH_REGEN_CONSTANT,
MODIFIER_PROPERTY_MANA_REGEN_CONSTANT,
MODIFIER_PROPERTY_CAST_RANGE_BONUS,
MODIFIER_PROPERTY_SPELL_AMPLIFY_PERCENTAGE,
MODIFIER_PROPERTY_TOTALDAMAGEOUTGOING_PERCENTAGE
}
end
function modifier_item_scythe_of_the_ancients_passive:GetModifierScepter()
return 1
end
function modifier_item_scythe_of_the_ancients_passive:GetModifierBonusStats_Strength()
return self:GetAbility():GetSpecialValueFor("bonus_strength")
end
function modifier_item_scythe_of_the_ancients_passive:GetModifierBonusStats_Agility()
return self:GetAbility():GetSpecialValueFor("bonus_agility")
end
function modifier_item_scythe_of_the_ancients_passive:GetModifierBonusStats_Intellect()
return self:GetAbility():GetSpecialValueFor("bonus_intellect")
end
function modifier_item_scythe_of_the_ancients_passive:GetModifierSpellAmplify_Percentage()
return self:GetAbility():GetSpecialValueFor("spell_amp_pct")
end
function modifier_item_scythe_of_the_ancients_passive:GetModifierConstantHealthRegen()
return self:GetAbility():GetSpecialValueFor("bonus_health_regen")
end
function modifier_item_scythe_of_the_ancients_passive:GetModifierHealthBonus()
return self:GetAbility():GetSpecialValueFor("bonus_health")
end
function modifier_item_scythe_of_the_ancients_passive:GetModifierManaBonus()
return self:GetAbility():GetSpecialValueFor("bonus_mana")
end
function modifier_item_scythe_of_the_ancients_passive:GetModifierConstantManaRegen()
return self:GetAbility():GetSpecialValueFor("bonus_mana_regen")
end
function modifier_item_scythe_of_the_ancients_passive:GetModifierCastRangeBonus()
return self:GetAbility():GetSpecialValueFor("cast_range_bonus")
end
function modifier_item_scythe_of_the_ancients_passive:GetModifierTotalDamageOutgoing_Percentage()
return self:GetAbility():GetSpecialValueFor("all_damage_bonus_pct")
end
if IsServer() then
function modifier_item_scythe_of_the_ancients_passive:OnCreated()
local parent = self:GetParent()
for i = 0, parent:GetAbilityCount() - 1 do
local ability = parent:GetAbilityByIndex(i)
if ability and ability:GetKeyValue("IsGrantedByScepter") == 1 then
if ability:GetKeyValue("ScepterGrantedLevel") ~= 0 then
ability:SetLevel(1)
end
ability:SetHidden(false)
end
end
end
function modifier_item_scythe_of_the_ancients_passive:OnDestroy()
local parent = self:GetParent()
if not parent:HasScepter() then
for i = 0, parent:GetAbilityCount() - 1 do
local ability = parent:GetAbilityByIndex(i)
if ability and ability:GetKeyValue("IsGrantedByScepter") == 1 then
if ability:GetKeyValue("ScepterGrantedLevel") ~= 0 then
ability:SetLevel(0)
end
ability:SetHidden(true)
end
end
end
end
function modifier_item_scythe_of_the_ancients_passive:OnTakeDamage(keys)
local parent = self:GetParent()
local damage = keys.original_damage
local ability = self:GetAbility()
if keys.attacker == parent and not keys.unit:IsMagicImmune() and keys.damage_type == 2 and not (keys.inflictor and keys.inflictor:GetAbilityName() == "batrider_sticky_napalm") then
ApplyDamage({
attacker = parent,
victim = keys.unit,
damage = keys.original_damage * ability:GetSpecialValueFor("magic_damage_to_pure_pct") * 0.01,
damage_type = ability:GetAbilityDamageType(),
damage_flags = DOTA_DAMAGE_FLAG_NO_SPELL_AMPLIFICATION,
ability = ability
})
end
end
end
modifier_item_scythe_of_the_ancients_stun = class({
IsHidden = function() return false end,
IsPurgable = function() return false end,
})
if IsServer() then
function modifier_item_scythe_of_the_ancients_stun:OnCreated()
local parent = self:GetParent()
self.particle = ParticleManager:CreateParticle("particles/arena/items_fx/scythe_of_the_ancients_start.vpcf", PATTACH_ABSORIGIN_FOLLOW, parent)
ParticleManager:SetParticleControlEnt(self.particle, 1, self:GetParent(), PATTACH_POINT_FOLLOW, "attach_hitloc", parent:GetAbsOrigin(), true)
end
function modifier_item_scythe_of_the_ancients_stun:OnDestroy()
local ability = self:GetAbility()
local caster = self:GetCaster()
local target = self:GetParent()
local team = caster:GetTeamNumber()
ParticleManager:DestroyParticle(self.particle, false)
local damage = (target:GetMaxHealth() - target:GetHealth()) * ability:GetSpecialValueFor("delayed_damage_per_health")
ApplyDamage({
attacker = caster,
victim = target,
damage = damage,
damage_type = ability:GetAbilityDamageType(),
damage_flags = DOTA_DAMAGE_FLAG_NO_SPELL_AMPLIFICATION,
ability = ability
})
end
end
function modifier_item_scythe_of_the_ancients_stun:CheckState()
return {
[ MODIFIER_STATE_STUNNED ] = true,
[ MODIFIER_STATE_PROVIDES_VISION ] = true,
}
end
|
fix(items): scythe of the ancients reflects batrider's sticky napalm
|
fix(items): scythe of the ancients reflects batrider's sticky napalm
Fixes #383.
|
Lua
|
mit
|
ark120202/aabs
|
34e3e6900ac2037aabd5475065d68ac454b1447d
|
kong/plugins/liamp/iam-ecs-credentials.lua
|
kong/plugins/liamp/iam-ecs-credentials.lua
|
-- This code is reverse engineered from the original AWS sdk. Specifically:
-- https://github.com/aws/aws-sdk-js/blob/c175cb2b89576f01c08ebf39b232584e4fa2c0e0/lib/credentials/remote_credentials.js
local function makeset(t)
for i = 1, #t do
t[t[i]] = true
end
return t
end
local plugin_name = ({...})[1]:match("^kong%.plugins%.([^%.]+)")
local LOG_PREFIX = "[" .. plugin_name .. " ecs] "
local ENV_RELATIVE_URI = os.getenv 'AWS_CONTAINER_CREDENTIALS_RELATIVE_URI'
local ENV_FULL_URI = os.getenv 'AWS_CONTAINER_CREDENTIALS_FULL_URI'
local FULL_URI_UNRESTRICTED_PROTOCOLS = makeset { "https" }
local FULL_URI_ALLOWED_PROTOCOLS = makeset { "http", "https" }
local FULL_URI_ALLOWED_HOSTNAMES = makeset { "localhost", "127.0.0.1" }
local RELATIVE_URI_HOST = '169.254.170.2'
local DEFAULT_SERVICE_REQUEST_TIMEOUT = 5000
local url = require "socket.url"
local http = require "resty.http"
local json = require "cjson"
local parse_date = require("luatz").parse.rfc_3339
local ECSFullUri
do
if not (ENV_RELATIVE_URI or ENV_FULL_URI) then
-- No variables found, so we're not running on ECS containers
ngx.log(ngx.NOTICE, LOG_PREFIX, "No ECS environment variables found for IAM")
else
-- construct the URL
local function getECSFullUri()
if ENV_RELATIVE_URI then
return 'http://' .. RELATIVE_URI_HOST .. ENV_RELATIVE_URI
elseif ENV_FULL_URI then
local parsed_url = url.parse(ENV_FULL_URI)
if not FULL_URI_ALLOWED_PROTOCOLS[parsed_url.scheme] then
return nil, 'Unsupported protocol: AWS.RemoteCredentials supports '
.. table.concat(FULL_URI_ALLOWED_PROTOCOLS, ',') .. ' only; '
.. parsed_url.scheme .. ' requested.'
end
if (not FULL_URI_UNRESTRICTED_PROTOCOLS[parsed_url.scheme]) and
(not FULL_URI_ALLOWED_HOSTNAMES[parsed_url.hostname]) then
return nil, 'Unsupported hostname: AWS.RemoteCredentials only supports '
.. table.concat(FULL_URI_ALLOWED_HOSTNAMES, ',') .. ' for '
.. parsed_url.scheme .. '; ' .. parsed_url.scheme .. '://'
.. parsed_url.host .. ' requested.'
end
return ENV_FULL_URI
else
return nil, 'Environment variable AWS_CONTAINER_CREDENTIALS_RELATIVE_URI or '
.. 'AWS_CONTAINER_CREDENTIALS_FULL_URI must be set to use AWS.RemoteCredentials.'
end
end
local err
ECSFullUri, err = getECSFullUri()
if not ECSFullUri then
ngx.log(ngx.ERR, LOG_PREFIX, "Failed to construct IAM url: ", err)
end
end
end
local function fetchCredentials()
local client = http.new()
client:set_timeout(DEFAULT_SERVICE_REQUEST_TIMEOUT)
local parsed_url = url.parse(ECSFullUri)
local ok, err = client:connect(parsed_url.host, parsed_url.port)
if not ok then
return nil, "Could not connect to metadata service: " .. tostring(err)
end
local response, err = client:request {
method = "GET",
path = parsed_url.path,
}
if not response then
return nil, "Failed to request IAM credentials request returned error: " .. tostring(err)
end
if response.status ~= 200 then
return nil, "Unable to request IAM credentials request returned status code " ..
response.status .. " " .. tostring(response:read_body())
end
local credentials = json.decode(response:read_body())
ngx.log(ngx.DEBUG, LOG_PREFIX, "Received temporary IAM credential from ECS metadata " ..
"service with session token: ", credentials.Token)
return {
access_key = credentials.AccessKeyId,
secret_key = credentials.SecretAccessKey,
session_token = credentials.Token,
expiration = parse_date(credentials.Expiration):timestamp()
}
end
local function fetchCredentialsLogged()
-- wrapper to log any errors
local creds, err = fetchCredentials()
if creds then
return creds
end
ngx.log(ngx.ERR, err)
end
local M = setmetatable({
configured = not not ECSFullUri, -- force to boolean
fetchCredentials = fetchCredentialsLogged,
}, {
__call = function(self, ...)
return self.fetchCredentials(...)
end
})
return M
|
-- This code is reverse engineered from the original AWS sdk. Specifically:
-- https://github.com/aws/aws-sdk-js/blob/c175cb2b89576f01c08ebf39b232584e4fa2c0e0/lib/credentials/remote_credentials.js
local function makeset(t)
for i = 1, #t do
t[t[i]] = true
end
return t
end
local plugin_name = ({...})[1]:match("^kong%.plugins%.([^%.]+)")
local LOG_PREFIX = "[" .. plugin_name .. " ecs] "
local ENV_RELATIVE_URI = os.getenv 'AWS_CONTAINER_CREDENTIALS_RELATIVE_URI'
local ENV_FULL_URI = os.getenv 'AWS_CONTAINER_CREDENTIALS_FULL_URI'
local FULL_URI_UNRESTRICTED_PROTOCOLS = makeset { "https" }
local FULL_URI_ALLOWED_PROTOCOLS = makeset { "http", "https" }
local FULL_URI_ALLOWED_HOSTNAMES = makeset { "localhost", "127.0.0.1" }
local RELATIVE_URI_HOST = '169.254.170.2'
local DEFAULT_SERVICE_REQUEST_TIMEOUT = 5000
local url = require "socket.url"
local http = require "resty.http"
local json = require "cjson"
local parse_date = require("luatz").parse.rfc_3339
local ECSFullUri
do
if not (ENV_RELATIVE_URI or ENV_FULL_URI) then
-- No variables found, so we're not running on ECS containers
ngx.log(ngx.NOTICE, LOG_PREFIX, "No ECS environment variables found for IAM")
else
-- construct the URL
local function getECSFullUri()
if ENV_RELATIVE_URI then
return 'http://' .. RELATIVE_URI_HOST .. ENV_RELATIVE_URI
elseif ENV_FULL_URI then
local parsed_url = url.parse(ENV_FULL_URI)
if not FULL_URI_ALLOWED_PROTOCOLS[parsed_url.scheme] then
return nil, 'Unsupported protocol: AWS.RemoteCredentials supports '
.. table.concat(FULL_URI_ALLOWED_PROTOCOLS, ',') .. ' only; '
.. parsed_url.scheme .. ' requested.'
end
if (not FULL_URI_UNRESTRICTED_PROTOCOLS[parsed_url.scheme]) and
(not FULL_URI_ALLOWED_HOSTNAMES[parsed_url.hostname]) then
return nil, 'Unsupported hostname: AWS.RemoteCredentials only supports '
.. table.concat(FULL_URI_ALLOWED_HOSTNAMES, ',') .. ' for '
.. parsed_url.scheme .. '; ' .. parsed_url.scheme .. '://'
.. parsed_url.host .. ' requested.'
end
return ENV_FULL_URI
else
return nil, 'Environment variable AWS_CONTAINER_CREDENTIALS_RELATIVE_URI or '
.. 'AWS_CONTAINER_CREDENTIALS_FULL_URI must be set to use AWS.RemoteCredentials.'
end
end
local err
ECSFullUri, err = getECSFullUri()
if not ECSFullUri then
ngx.log(ngx.ERR, LOG_PREFIX, "Failed to construct IAM url: ", err)
else
-- parse it and set a default port if omitted
ECSFullUri = url.parse(ECSFullUri)
ECSFullUri.port = ECSFullUri.port or
({ http = 80, https = 443 })[ECSFullUri.scheme]
end
end
end
local function fetchCredentials()
local client = http.new()
client:set_timeout(DEFAULT_SERVICE_REQUEST_TIMEOUT)
local ok, err = client:connect(ECSFullUri.host, ECSFullUri.port)
if not ok then
return nil, "Could not connect to metadata service: " .. tostring(err)
end
local response, err = client:request {
method = "GET",
path = ECSFullUri.path,
}
if not response then
return nil, "Failed to request IAM credentials request returned error: " .. tostring(err)
end
if response.status ~= 200 then
return nil, "Unable to request IAM credentials request returned status code " ..
response.status .. " " .. tostring(response:read_body())
end
local credentials = json.decode(response:read_body())
ngx.log(ngx.DEBUG, LOG_PREFIX, "Received temporary IAM credential from ECS metadata " ..
"service with session token: ", credentials.Token)
return {
access_key = credentials.AccessKeyId,
secret_key = credentials.SecretAccessKey,
session_token = credentials.Token,
expiration = parse_date(credentials.Expiration):timestamp()
}
end
local function fetchCredentialsLogged()
-- wrapper to log any errors
local creds, err = fetchCredentials()
if creds then
return creds
end
ngx.log(ngx.ERR, err)
end
local M = setmetatable({
configured = not not ECSFullUri, -- force to boolean
fetchCredentials = fetchCredentialsLogged,
}, {
__call = function(self, ...)
return self.fetchCredentials(...)
end
})
return M
|
fix(aws-lambda) force a port if omitted from the url
|
fix(aws-lambda) force a port if omitted from the url
If no port is provided, a default port, 80 or 443 is used based
on the scheme of the url.
|
Lua
|
apache-2.0
|
Kong/kong,Kong/kong,Kong/kong
|
f3dc7cbfa9eb89f2649976c46abf1eae7d185fb5
|
protocols/core/luasrc/model/cbi/admin_network/proto_dhcp.lua
|
protocols/core/luasrc/model/cbi/admin_network/proto_dhcp.lua
|
--[[
LuCI - Lua Configuration Interface
Copyright 2011-2012 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 map, section, net = ...
local ifc = net:get_interface()
local hostname, accept_ra, send_rs
local bcast, no_gw, peerdns, dns, metric, clientid, vendorclass
hostname = section:taboption("general", Value, "hostname",
translate("Hostname to send when requesting DHCP"))
hostname.placeholder = luci.sys.hostname()
hostname.datatype = "hostname"
if luci.model.network:has_ipv6() then
accept_ra = s:taboption("general", Flag, "accept_ra", translate("Accept router advertisements"))
accept_ra.default = accept_ra.enabled
send_rs = s:taboption("general", Flag, "send_rs", translate("Send router solicitations"))
send_rs.default = send_rs.disabled
send_rs:depends("accept_ra", "")
end
bcast = section:taboption("advanced", Flag, "broadcast",
translate("Use broadcast flag"),
translate("Required for certain ISPs, e.g. Charter with DOCSIS 3"))
bcast.default = bcast.disabled
no_gw = section:taboption("advanced", Flag, "gateway",
translate("Use default gateway"),
translate("If unchecked, no default route is configured"))
no_gw.default = no_gw.enabled
function no_gw.cfgvalue(...)
return Flag.cfgvalue(...) == "0.0.0.0" and "0" or "1"
end
function no_gw.write(self, section, value)
if value == "1" then
m:set(section, "gateway", nil)
else
m:set(section, "gateway", "0.0.0.0")
end
end
peerdns = section:taboption("advanced", Flag, "peerdns",
translate("Use DNS servers advertised by peer"),
translate("If unchecked, the advertised DNS server addresses are ignored"))
peerdns.default = peerdns.enabled
dns = section:taboption("advanced", DynamicList, "dns",
translate("Use custom DNS servers"))
dns:depends("peerdns", "")
dns.datatype = "ipaddr"
dns.cast = "string"
metric = section:taboption("advanced", Value, "metric",
translate("Use gateway metric"))
metric.placeholder = "0"
metric.datatype = "uinteger"
metric:depends("gateway", "1")
clientid = section:taboption("advanced", Value, "clientid",
translate("Client ID to send when requesting DHCP"))
vendorclass = section:taboption("advanced", Value, "vendorid",
translate("Vendor Class to send when requesting DHCP"))
macaddr = section:taboption("advanced", Value, "macaddr", translate("Override MAC address"))
macaddr.placeholder = ifc and ifc:mac() or "00:00:00:00:00:00"
macaddr.datatype = "macaddr"
mtu = section:taboption("advanced", Value, "mtu", translate("Override MTU"))
mtu.placeholder = "1500"
mtu.datatype = "max(1500)"
|
--[[
LuCI - Lua Configuration Interface
Copyright 2011-2012 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 map, section, net = ...
local ifc = net:get_interface()
local hostname, accept_ra, send_rs
local bcast, defaultroute, peerdns, dns, metric, clientid, vendorclass
hostname = section:taboption("general", Value, "hostname",
translate("Hostname to send when requesting DHCP"))
hostname.placeholder = luci.sys.hostname()
hostname.datatype = "hostname"
if luci.model.network:has_ipv6() then
accept_ra = s:taboption("general", Flag, "accept_ra", translate("Accept router advertisements"))
accept_ra.default = accept_ra.enabled
send_rs = s:taboption("general", Flag, "send_rs", translate("Send router solicitations"))
send_rs.default = send_rs.disabled
send_rs:depends("accept_ra", "")
end
bcast = section:taboption("advanced", Flag, "broadcast",
translate("Use broadcast flag"),
translate("Required for certain ISPs, e.g. Charter with DOCSIS 3"))
bcast.default = bcast.disabled
defaultroute = section:taboption("advanced", Flag, "gateway",
translate("Use default gateway"),
translate("If unchecked, no default route is configured"))
defaultroute.default = defaultroute.enabled
peerdns = section:taboption("advanced", Flag, "peerdns",
translate("Use DNS servers advertised by peer"),
translate("If unchecked, the advertised DNS server addresses are ignored"))
peerdns.default = peerdns.enabled
dns = section:taboption("advanced", DynamicList, "dns",
translate("Use custom DNS servers"))
dns:depends("peerdns", "")
dns.datatype = "ipaddr"
dns.cast = "string"
metric = section:taboption("advanced", Value, "metric",
translate("Use gateway metric"))
metric.placeholder = "0"
metric.datatype = "uinteger"
metric:depends("gateway", "1")
clientid = section:taboption("advanced", Value, "clientid",
translate("Client ID to send when requesting DHCP"))
vendorclass = section:taboption("advanced", Value, "vendorid",
translate("Vendor Class to send when requesting DHCP"))
macaddr = section:taboption("advanced", Value, "macaddr", translate("Override MAC address"))
macaddr.placeholder = ifc and ifc:mac() or "00:00:00:00:00:00"
macaddr.datatype = "macaddr"
mtu = section:taboption("advanced", Value, "mtu", translate("Override MTU"))
mtu.placeholder = "1500"
mtu.datatype = "max(1500)"
|
protocols/core: fix defaultroute setting for DHCP interfaces
|
protocols/core: fix defaultroute setting for DHCP interfaces
git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@8702 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
|
6e799cf4f7339731d561385ec868914a043b711a
|
pages/community/guilds/view/get.lua
|
pages/community/guilds/view/get.lua
|
function get()
local data = {}
local cache = false
data.guild, cache = db:singleQuery("SELECT a.id, a.ownerid, a.name as guildname, a.creationdata, a.motd, b.name, (SELECT COUNT(1) FROM guild_membership WHERE a.id = guild_id) AS members, (SELECT COUNT(1) FROM guild_membership c, players_online d WHERE c.player_id = d.player_id AND c.guild_id = a.id) AS onl, (SELECT MAX(f.level) FROM guild_membership e, players f WHERE f.id = e.player_id AND e.guild_id = a.id) as top, (SELECT MIN(f.level) FROM guild_membership e, players f WHERE f.id = e.player_id AND e.guild_id = a.id) as low FROM guilds a, players b WHERE a.ownerid = b.id AND a.name = ?", url:decode(http.getValues["name"]), true)
if data.guild == nil then
http:redirect("/subtopic/community/guilds/list")
return
end
local characters = db:query("SELECT id FROM players WHERE account_id = ?", session:loggedAccount().ID)
data.owner = false
if characters ~= nil then
for _, val in pairs(characters) do
if val.id == tonumber(data.guild.ownerid) then
data.owner = true
break
end
end
end
if not cache then
data.guild.created = time:parseUnix(tonumber(data.guild.creationdata))
end
data.memberlist = db:query("SELECT a.name, a.level, c.name as rank FROM guild_membership b, players a, guild_ranks c WHERE c.id = b.rank_id AND b.player_id = a.id AND b.guild_id = ? ORDER BY c.level DESC", data.guild.id)
data.success = session:getFlash("success")
data.validationError = session:getFlash("validationError")
if data.owner then
data.ranks = db:query("SELECT name, level FROM guild_ranks WHERE guild_id = ? ORDER BY level DESC", data.guild.id)
end
data.invitations = db:query("SELECT a.id, a.name FROM players a, guild_invites b WHERE b.guild_id = ? AND b.player_id = a.id", data.guild.id)
if data.invitations ~= nil then
for _, v in pairs(data.invitations) do
for _, p in pairs(characters) do
if p.id == v.id then
v.m = true
end
end
end
end
http:render("viewguild.html", data)
end
|
function get()
local data = {}
local cache = false
data.guild, cache = db:singleQuery("SELECT a.id, a.ownerid, a.name as guildname, a.creationdata, a.motd, b.name, (SELECT COUNT(1) FROM guild_membership WHERE a.id = guild_id) AS members, (SELECT COUNT(1) FROM guild_membership c, players_online d WHERE c.player_id = d.player_id AND c.guild_id = a.id) AS onl, (SELECT MAX(f.level) FROM guild_membership e, players f WHERE f.id = e.player_id AND e.guild_id = a.id) as top, (SELECT MIN(f.level) FROM guild_membership e, players f WHERE f.id = e.player_id AND e.guild_id = a.id) as low FROM guilds a, players b WHERE a.ownerid = b.id AND a.name = ?", url:decode(http.getValues["name"]), true)
if data.guild == nil then
http:redirect("/subtopic/community/guilds/list")
return
end
if session:isLogged() then
local characters = db:query("SELECT id FROM players WHERE account_id = ?", session:loggedAccount().ID)
end
data.owner = false
if characters ~= nil then
for _, val in pairs(characters) do
if val.id == tonumber(data.guild.ownerid) then
data.owner = true
break
end
end
end
if not cache then
data.guild.created = time:parseUnix(tonumber(data.guild.creationdata))
end
data.memberlist = db:query("SELECT a.name, a.level, c.name as rank FROM guild_membership b, players a, guild_ranks c WHERE c.id = b.rank_id AND b.player_id = a.id AND b.guild_id = ? ORDER BY c.level DESC", data.guild.id)
data.success = session:getFlash("success")
data.validationError = session:getFlash("validationError")
if data.owner then
data.ranks = db:query("SELECT name, level FROM guild_ranks WHERE guild_id = ? ORDER BY level DESC", data.guild.id)
end
data.invitations = db:query("SELECT a.id, a.name FROM players a, guild_invites b WHERE b.guild_id = ? AND b.player_id = a.id", data.guild.id)
if session:isLogged() then
if data.invitations ~= nil then
for _, v in pairs(data.invitations) do
for _, p in pairs(characters) do
if p.id == v.id then
v.m = true
end
end
end
end
end
http:render("viewguild.html", data)
end
|
Fix guild view if not logged in
|
Fix guild view if not logged in
|
Lua
|
mit
|
Raggaer/castro,Raggaer/castro,Raggaer/castro
|
72c40002a30640b98590c7d09ffc13feb3432c78
|
lib/switchboard_modules/lua_script_debugger/premade_scripts/Advanced_Scripts/Task-Scheduler_1.0.lua
|
lib/switchboard_modules/lua_script_debugger/premade_scripts/Advanced_Scripts/Task-Scheduler_1.0.lua
|
print("LabJack Lua Task Scheduler Example. Version 1.0")
-- Requires Firmware 1.0199 or higher
-- This script demonstrates a simple task scheduler used to execute multiple tasks
-- at regular intervals to 1ms resolution.
-- Note: Increase scheduler resolution to reduce CPU load on the T7 processor.
-- Directions:
-- 1. Define user functions as required.
-- 2. Build scheduler table for each function that is executed at regular
-- intervals. Each row int the scheduler table corresponds to one function.
-- 3. Define function parameters in the scheduler table as required
-- [n][0] - Function name (string)
-- [n][1] - Initial execution delay time. Set to nonzero value to delay
-- initial function execution. Function will execute at regular
-- internals after the initial delay has elapsed.
-- [n][2] - Function period in milliseconds.
-- [n][3] - Optional parameters to pass to the function if necessary.
-- Pass array if multiple parameters are required.
NumFuncs = 2 -- Number of functions being executed in scheduler. Must equal number of fuction defined in the scheduler table.
MsgThresh = 1 -- Allowable number of scheduler tics beyond function period before posting a warning.
IntvlCnt = 0
SchTbl = {} -- Empty table
SchTbl[0] = {} -- New row (1 row per function)
SchTbl[1] = {} -- New row (1 row per function)
SchTbl[0][0] = "Func1" -- Function1 name
SchTbl[0][1] = 10 -- Function1 counter. Function will execute when this value equals zero. Set to positive nonzero number to set delay before first execution.
SchTbl[0][2] = 50 -- Function1 period
SchTbl[0][3] = {} -- Function1 parameters (if required)
SchTbl[1][0] = "Func2" -- Function2 name
SchTbl[1][1] = 10 -- Function2 counter. Function will execute when this value equals zero. Set to positive nonzero number to set delay before first execution.
SchTbl[1][2] = 500 -- Function2 period
SchTbl[1][3] = {} -- Function2 parameters (if required)
LJ.IntervalConfig(0, 1) --Define scheduler resolution (1 ms). Increase if necessary.
Test = 0
--==============================================================================
-- Task function definitions
-- Define tasks to run as individual functions. Task functions must be defined
-- in the task table and executed by the task scheduler.
--==============================================================================
Func1 = function (args)
print("Function1 Executed --")
-- Add functional code here. Parameters may be passed thorugh the args
-- variable as an array.
return 0
end
Func2 = function (args)
print("Function2 Executed !!")
-- Add functional code here. Parameters may be passed thorugh the args
-- variable as an array.
return 0
end
--==============================================================================
--==============================================================================
-- Task Scheduler
-- Note: No need to modify the scheduler main loop. Scheduler will exeute
-- any number of tasks, defined in the task table.
--==============================================================================
while true do
IntvlCnt = LJ.CheckInterval(0) -- Save interval count to catch missed interval servicing.
if (IntvlCnt) then
-- Decrement function counters and determine if a function needs to run.
for i=0,NumFuncs-1,1 do
-- Decrement function counter variable. LJ.CheckINterval returns the number
-- of elapsed intervals since last check. In most cases Intvlcnt will normally
-- equal 1, unless some delay causes script to go multiple intervals between
-- checks. Adjust function counter accordingly to maintain function timing.
SchTbl[i][1] = SchTbl[i][1] - IntvlCnt
-- Call function when counter reaches zero.
if(SchTbl[i][1] <= 0) then
-- Post a message if we see the function execution time was delayed too long
if (IntvlCnt > 1) then
print("Warning: Function", i, "delayed too long", IntvlCnt, "ms")
end
-- Execute Task
--_G["Func1"](params{})
_G[SchTbl[i][0]](SchTbl[1][3]) -- Call function from the global namespace
SchTbl[i][1] = SchTbl[i][2] -- Reset function counter
end
end
end
end
--==============================================================================
|
print("LabJack Lua Task Scheduler Example. Version 1.0")
-- Requires Firmware 1.0199 or higher
-- This script demonstrates a simple task scheduler used to execute multiple tasks
-- at regular intervals to 1ms resolution.
-- Note: Increase scheduler resolution to reduce CPU load on the T7 processor.
-- Directions:
-- 1. Define user functions as required.
-- 2. Build scheduler table for each function that is executed at regular
-- intervals. Each row int the scheduler table corresponds to one function.
-- 3. Define function parameters in the scheduler table as required
-- [n][0] - Function name (string)
-- [n][1] - Initial execution delay time. Set to nonzero value to delay
-- initial function execution. Function will execute at regular
-- internals after the initial delay has elapsed.
-- [n][2] - Function period in milliseconds.
-- [n][3] - Optional parameters to pass to the function if necessary.
-- Pass array if multiple parameters are required.
NumFuncs = 2 -- Number of functions being executed in scheduler. Must equal number of fuction defined in the scheduler table.
MsgThresh = 1 -- Allowable number of scheduler tics beyond function period before posting a warning.
IntvlCnt = 0
SchTbl = {} -- Empty table
SchTbl[0] = {} -- New row (1 row per function)
SchTbl[1] = {} -- New row (1 row per function)
SchTbl[0][0] = "Func1" -- Function1 name
SchTbl[0][1] = 10 -- Function1 counter. Function will execute when this value equals zero. Set to positive nonzero number to set delay before first execution.
SchTbl[0][2] = 50 -- Function1 period
SchTbl[0][3] = {} -- Function1 parameters (if required)
SchTbl[1][0] = "Func2" -- Function2 name
SchTbl[1][1] = 10 -- Function2 counter. Function will execute when this value equals zero. Set to positive nonzero number to set delay before first execution.
SchTbl[1][2] = 500 -- Function2 period
SchTbl[1][3] = {} -- Function2 parameters (if required)
LJ.IntervalConfig(0, 1) --Define scheduler resolution (1 ms). Increase if necessary.
Test = 0
--==============================================================================
-- Task function definitions
-- Define tasks to run as individual functions. Task functions must be defined
-- in the task table and executed by the task scheduler.
--==============================================================================
Func1 = function (args)
print("Function1 Executed --")
-- Add functional code here. Parameters may be passed thorugh the args
-- variable as an array.
return 0
end
Func2 = function (args)
print("Function2 Executed !!")
-- Add functional code here. Parameters may be passed thorugh the args
-- variable as an array.
return 0
end
--==============================================================================
--==============================================================================
-- Task Scheduler
-- Note: No need to modify the scheduler main loop. Scheduler will exeute
-- any number of tasks, defined in the task table.
--==============================================================================
while true do
IntvlCnt = LJ.CheckInterval(0) -- Save interval count to catch missed interval servicing.
if (IntvlCnt) then
-- Decrement function counters and determine if a function needs to run.
for i=0,NumFuncs-1,1 do
-- Decrement function counter variable. LJ.CheckINterval returns the number
-- of elapsed intervals since last check. In most cases Intvlcnt will normally
-- equal 1, unless some delay causes script to go multiple intervals between
-- checks. Adjust function counter accordingly to maintain function timing.
delay = IntvlCnt - SchTbl[i][1]
SchTbl[i][1] = SchTbl[i][1] - IntvlCnt
-- Call function when counter reaches zero.
if(SchTbl[i][1] <= 0) then
-- Post a message if we see the function execution time was delayed too long
if (SchTbl[i][1] < 0) then
print("Warning: Function", i, "delayed by", delay, "ms")
end
-- Execute Task
--_G["Func1"](params{})
_G[SchTbl[i][0]](SchTbl[1][3]) -- Call function from the global namespace
SchTbl[i][1] = SchTbl[i][2] -- Reset function counter
end
end
end
end
--==============================================================================
|
Fixing delay message
|
Fixing delay message
The task is not necessarily delayed when IntvlCnt is greater than 1. For example, if the task had 2 ms left before it was supposed to be scheduled and IntvlCnt is 2, the task will be (serendipitously) initiated right on time.
|
Lua
|
mit
|
chrisJohn404/ljswitchboard-module_manager,chrisJohn404/ljswitchboard-module_manager,chrisJohn404/ljswitchboard-module_manager
|
8ca9c6f6f4f6acfcf8b593290deaa858a069e6c7
|
third_party/spirv-tools.lua
|
third_party/spirv-tools.lua
|
group("third_party")
project("spirv-tools")
uuid("621512da-bb50-40f2-85ba-ae615ff13e68")
kind("StaticLib")
language("C++")
links({
})
defines({
"_LIB",
})
includedirs({
"spirv-tools/external/include",
"spirv-tools/include",
})
files({
"spirv-tools/external/include/headers/GLSL.std.450.h",
"spirv-tools/external/include/headers/OpenCL.std.h",
"spirv-tools/external/include/headers/spirv.h",
"spirv-tools/include/spirv-tools/libspirv.h",
"spirv-tools/source/assembly_grammar.cpp",
"spirv-tools/source/assembly_grammar.h",
"spirv-tools/source/binary.cpp",
"spirv-tools/source/binary.h",
"spirv-tools/source/diagnostic.cpp",
"spirv-tools/source/diagnostic.h",
"spirv-tools/source/disassemble.cpp",
"spirv-tools/source/ext_inst.cpp",
"spirv-tools/source/ext_inst.h",
"spirv-tools/source/instruction.cpp",
"spirv-tools/source/instruction.h",
"spirv-tools/source/opcode.cpp",
"spirv-tools/source/opcode.h",
"spirv-tools/source/opcode.inc",
"spirv-tools/source/opencl_std_ext_inst.inc",
"spirv-tools/source/operand.cpp",
"spirv-tools/source/operand.h",
"spirv-tools/source/print.cpp",
"spirv-tools/source/print.h",
"spirv-tools/source/spirv_constant.h",
"spirv-tools/source/spirv_definition.h",
"spirv-tools/source/spirv_endian.cpp",
"spirv-tools/source/spirv_endian.h",
"spirv-tools/source/spirv_operands.h",
"spirv-tools/source/table.cpp",
"spirv-tools/source/table.h",
"spirv-tools/source/text.cpp",
"spirv-tools/source/text.h",
"spirv-tools/source/text_handler.cpp",
"spirv-tools/source/text_handler.h",
"spirv-tools/source/validate.cpp",
"spirv-tools/source/validate.h",
"spirv-tools/source/validate_cfg.cpp",
"spirv-tools/source/validate_id.cpp",
"spirv-tools/source/validate_instruction.cpp",
"spirv-tools/source/validate_layout.cpp",
"spirv-tools/source/validate_passes.h",
"spirv-tools/source/validate_ssa.cpp",
"spirv-tools/source/validate_types.cpp",
"spirv-tools/source/util/bitutils.h",
"spirv-tools/source/util/hex_float.h",
})
|
group("third_party")
project("spirv-tools")
uuid("621512da-bb50-40f2-85ba-ae615ff13e68")
kind("StaticLib")
language("C++")
links({
})
defines({
"_LIB",
})
includedirs({
"spirv-tools/external/include",
"spirv-tools/include",
})
files({
"spirv-tools/include/spirv/GLSL.std.450.h",
"spirv-tools/include/spirv/OpenCL.std.h",
"spirv-tools/include/spirv/spirv.h",
"spirv-tools/include/spirv-tools/libspirv.h",
"spirv-tools/source/assembly_grammar.cpp",
"spirv-tools/source/assembly_grammar.h",
"spirv-tools/source/binary.cpp",
"spirv-tools/source/binary.h",
"spirv-tools/source/diagnostic.cpp",
"spirv-tools/source/diagnostic.h",
"spirv-tools/source/disassemble.cpp",
"spirv-tools/source/ext_inst.cpp",
"spirv-tools/source/ext_inst.h",
"spirv-tools/source/instruction.cpp",
"spirv-tools/source/instruction.h",
"spirv-tools/source/opcode.cpp",
"spirv-tools/source/opcode.h",
"spirv-tools/source/opcode.inc",
"spirv-tools/source/opencl_std_ext_inst.inc",
"spirv-tools/source/operand.cpp",
"spirv-tools/source/operand.h",
"spirv-tools/source/print.cpp",
"spirv-tools/source/print.h",
"spirv-tools/source/spirv_constant.h",
"spirv-tools/source/spirv_definition.h",
"spirv-tools/source/spirv_endian.cpp",
"spirv-tools/source/spirv_endian.h",
"spirv-tools/source/spirv_operands.h",
"spirv-tools/source/table.cpp",
"spirv-tools/source/table.h",
"spirv-tools/source/text.cpp",
"spirv-tools/source/text.h",
"spirv-tools/source/text_handler.cpp",
"spirv-tools/source/text_handler.h",
"spirv-tools/source/validate.cpp",
"spirv-tools/source/validate.h",
"spirv-tools/source/validate_cfg.cpp",
"spirv-tools/source/validate_id.cpp",
"spirv-tools/source/validate_instruction.cpp",
"spirv-tools/source/validate_layout.cpp",
"spirv-tools/source/validate_passes.h",
"spirv-tools/source/validate_ssa.cpp",
"spirv-tools/source/validate_types.cpp",
"spirv-tools/source/util/bitutils.h",
"spirv-tools/source/util/hex_float.h",
})
|
Fix spirv-tools incorrect includes
|
Fix spirv-tools incorrect includes
|
Lua
|
bsd-3-clause
|
sabretooth/xenia,ObsidianGuardian/xenia,sephiroth99/xenia,sephiroth99/xenia,sabretooth/xenia,maxton/xenia,maxton/xenia,sabretooth/xenia,ObsidianGuardian/xenia,maxton/xenia,sephiroth99/xenia,ObsidianGuardian/xenia
|
2cbe2d29338d701b8baaa1cafb39d2f9ffeaeb30
|
applications/luci-statistics/src/model/cbi/admin_statistics/iptables.lua
|
applications/luci-statistics/src/model/cbi/admin_statistics/iptables.lua
|
--[[
Luci configuration model for statistics - collectd iptables plugin configuration
(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$
]]--
require("ffluci.sys.iptparser")
ip = ffluci.sys.iptparser.IptParser()
chains = { }
targets = { }
for i, rule in ipairs( ip:find() ) do
chains[rule.chain] = true
targets[rule.target] = true
end
m = Map("luci_statistics", "Iptables Plugin",
[[Das Iptables-Plugin ermöglicht die Überwachung bestimmter Firewallregeln um
Werte wie die Anzahl der verarbeiteten Pakete oder die insgesamt erfasste Datenmenge
zu speichern.]])
-- collectd_iptables config section
s = m:section( NamedSection, "collectd_iptables", "luci_statistics", "Pluginkonfiguration" )
-- collectd_iptables.enable
enable = s:option( Flag, "enable", "Plugin aktivieren" )
enable.default = 0
-- collectd_iptables_match config section (Chain directives)
rule = m:section( TypedSection, "collectd_iptables_match", "Regel hinzufügen",
[[Hier werden die Kriterien festgelegt, nach welchen die Firewall-Regeln zur Überwachung
ausgewählt werden.]])
rule.addremove = true
rule.anonymous = true
-- collectd_iptables_match.name
rule_table = rule:option( Value, "name", "Name der Regel", "wird im Diagram verwendet" )
-- collectd_iptables_match.table
rule_table = rule:option( ListValue, "table", "Firewall-Tabelle" )
rule_table.default = "filter"
rule_table.rmempty = true
rule_table.optional = true
rule_table:value("")
rule_table:value("filter")
rule_table:value("nat")
rule_table:value("mangle")
-- collectd_iptables_match.chain
rule_chain = rule:option( ListValue, "chain", "Firewall-Kette (Chain)" )
rule_chain.rmempty = true
rule_chain.optional = true
rule_chain:value("")
for chain, void in pairs( chains ) do
rule_chain:value( chain )
end
-- collectd_iptables_match.target
rule_target = rule:option( ListValue, "target", "Firewall-Aktion (Target)" )
rule_target.rmempty = true
rule_target.optional = true
rule_target:value("")
for target, void in pairs( targets ) do
rule_target:value( target )
end
-- collectd_iptables_match.protocol
rule_protocol = rule:option( ListValue, "protocol", "Netzwerkprotokoll" )
rule_protocol.rmempty = true
rule_protocol.optional = true
rule_protocol:value("")
rule_protocol:value("tcp")
rule_protocol:value("udp")
rule_protocol:value("icmp")
-- collectd_iptables_match.source
rule_source = rule:option( Value, "source", "Quell-IP-Bereich", "Bereich in CIDR Notation" )
rule_source.default = "0.0.0.0/0"
rule_source.rmempty = true
rule_source.optional = true
-- collectd_iptables_match.destination
rule_destination = rule:option( Value, "destination", "Ziel-IP-Bereich", "Bereich in CIDR Notation" )
rule_destination.default = "0.0.0.0/0"
rule_destination.rmempty = true
rule_destination.optional = true
-- collectd_iptables_match.inputif
rule_inputif = rule:option( Value, "inputif", "eingehende Schnittstelle", "z.B. eth0.0" )
rule_inputif.default = "0.0.0.0/0"
rule_inputif.rmempty = true
rule_inputif.optional = true
-- collectd_iptables_match.outputif
rule_outputif = rule:option( Value, "outputif", "ausgehende Schnittstelle", "z.B. eth0.1" )
rule_outputif.default = "0.0.0.0/0"
rule_outputif.rmempty = true
rule_outputif.optional = true
-- collectd_iptables_match.options
rule_options = rule:option( Value, "options", "Optionen", "z.B. reject-with tcp-reset" )
rule_options.default = "0.0.0.0/0"
rule_options.rmempty = true
rule_options.optional = true
return m
|
--[[
Luci configuration model for statistics - collectd iptables plugin configuration
(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$
]]--
require("ffluci.sys.iptparser")
ip = ffluci.sys.iptparser.IptParser()
chains = { }
targets = { }
for i, rule in ipairs( ip:find() ) do
chains[rule.chain] = true
targets[rule.target] = true
end
m = Map("luci_statistics", "Iptables Plugin",
[[Das Iptables-Plugin ermöglicht die Überwachung bestimmter Firewallregeln um
Werte wie die Anzahl der verarbeiteten Pakete oder die insgesamt erfasste Datenmenge
zu speichern.]])
-- collectd_iptables config section
s = m:section( NamedSection, "collectd_iptables", "luci_statistics", "Pluginkonfiguration" )
-- collectd_iptables.enable
enable = s:option( Flag, "enable", "Plugin aktivieren" )
enable.default = 0
-- collectd_iptables_match config section (Chain directives)
rule = m:section( TypedSection, "collectd_iptables_match", "Regel hinzufügen",
[[Hier werden die Kriterien festgelegt, nach welchen die Firewall-Regeln zur Überwachung
ausgewählt werden.]])
rule.addremove = true
rule.anonymous = true
-- collectd_iptables_match.name
rule_table = rule:option( Value, "name", "Name der Regel", "wird im Diagram verwendet" )
-- collectd_iptables_match.table
rule_table = rule:option( ListValue, "table", "Firewall-Tabelle" )
rule_table.default = "filter"
rule_table.rmempty = true
rule_table.optional = true
rule_table:value("")
rule_table:value("filter")
rule_table:value("nat")
rule_table:value("mangle")
-- collectd_iptables_match.chain
rule_chain = rule:option( ListValue, "chain", "Firewall-Kette (Chain)" )
rule_chain.rmempty = true
rule_chain.optional = true
rule_chain:value("")
for chain, void in pairs( chains ) do
rule_chain:value( chain )
end
-- collectd_iptables_match.target
rule_target = rule:option( ListValue, "target", "Firewall-Aktion (Target)" )
rule_target.rmempty = true
rule_target.optional = true
rule_target:value("")
for target, void in pairs( targets ) do
rule_target:value( target )
end
-- collectd_iptables_match.protocol
rule_protocol = rule:option( ListValue, "protocol", "Netzwerkprotokoll" )
rule_protocol.rmempty = true
rule_protocol.optional = true
rule_protocol:value("")
rule_protocol:value("tcp")
rule_protocol:value("udp")
rule_protocol:value("icmp")
-- collectd_iptables_match.source
rule_source = rule:option( Value, "source", "Quell-IP-Bereich", "Bereich in CIDR Notation" )
rule_source.default = "0.0.0.0/0"
rule_source.rmempty = true
rule_source.optional = true
-- collectd_iptables_match.destination
rule_destination = rule:option( Value, "destination", "Ziel-IP-Bereich", "Bereich in CIDR Notation" )
rule_destination.default = "0.0.0.0/0"
rule_destination.rmempty = true
rule_destination.optional = true
-- collectd_iptables_match.inputif
rule_inputif = rule:option( Value, "inputif", "eingehende Schnittstelle", "z.B. eth0.0" )
rule_inputif.rmempty = true
rule_inputif.optional = true
-- collectd_iptables_match.outputif
rule_outputif = rule:option( Value, "outputif", "ausgehende Schnittstelle", "z.B. eth0.1" )
rule_outputif.rmempty = true
rule_outputif.optional = true
-- collectd_iptables_match.options
rule_options = rule:option( Value, "options", "Optionen", "z.B. reject-with tcp-reset" )
rule_options.rmempty = true
rule_options.optional = true
return m
|
* ffluci/statistics: fix c'n'p errors in iptables cbi model
|
* ffluci/statistics: fix c'n'p errors in iptables cbi model
|
Lua
|
apache-2.0
|
joaofvieira/luci,tcatm/luci,keyidadi/luci,jorgifumi/luci,mumuqz/luci,fkooman/luci,dwmw2/luci,thesabbir/luci,NeoRaider/luci,bright-things/ionic-luci,remakeelectric/luci,Noltari/luci,RuiChen1113/luci,marcel-sch/luci,LazyZhu/openwrt-luci-trunk-mod,teslamint/luci,david-xiao/luci,LazyZhu/openwrt-luci-trunk-mod,sujeet14108/luci,Wedmer/luci,nmav/luci,981213/luci-1,shangjiyu/luci-with-extra,bright-things/ionic-luci,fkooman/luci,db260179/openwrt-bpi-r1-luci,oyido/luci,jorgifumi/luci,slayerrensky/luci,ollie27/openwrt_luci,deepak78/new-luci,bright-things/ionic-luci,bittorf/luci,RedSnake64/openwrt-luci-packages,Hostle/luci,harveyhu2012/luci,marcel-sch/luci,nwf/openwrt-luci,zhaoxx063/luci,david-xiao/luci,db260179/openwrt-bpi-r1-luci,cappiewu/luci,aircross/OpenWrt-Firefly-LuCI,bittorf/luci,ollie27/openwrt_luci,ollie27/openwrt_luci,fkooman/luci,urueedi/luci,nmav/luci,wongsyrone/luci-1,Sakura-Winkey/LuCI,wongsyrone/luci-1,opentechinstitute/luci,wongsyrone/luci-1,harveyhu2012/luci,lcf258/openwrtcn,oyido/luci,LuttyYang/luci,nmav/luci,cshore/luci,teslamint/luci,opentechinstitute/luci,kuoruan/luci,nmav/luci,nmav/luci,LazyZhu/openwrt-luci-trunk-mod,male-puppies/luci,keyidadi/luci,nmav/luci,NeoRaider/luci,dwmw2/luci,ReclaimYourPrivacy/cloak-luci,ReclaimYourPrivacy/cloak-luci,schidler/ionic-luci,Sakura-Winkey/LuCI,chris5560/openwrt-luci,shangjiyu/luci-with-extra,Noltari/luci,sujeet14108/luci,RedSnake64/openwrt-luci-packages,palmettos/cnLuCI,palmettos/test,teslamint/luci,kuoruan/lede-luci,shangjiyu/luci-with-extra,jlopenwrtluci/luci,lbthomsen/openwrt-luci,lbthomsen/openwrt-luci,tobiaswaldvogel/luci,bright-things/ionic-luci,joaofvieira/luci,jlopenwrtluci/luci,RedSnake64/openwrt-luci-packages,chris5560/openwrt-luci,dwmw2/luci,LuttyYang/luci,tobiaswaldvogel/luci,maxrio/luci981213,remakeelectric/luci,openwrt/luci,hnyman/luci,dwmw2/luci,slayerrensky/luci,schidler/ionic-luci,Wedmer/luci,dismantl/luci-0.12,thess/OpenWrt-luci,jchuang1977/luci-1,Noltari/luci,joaofvieira/luci,kuoruan/lede-luci,maxrio/luci981213,zhaoxx063/luci,obsy/luci,joaofvieira/luci,NeoRaider/luci,rogerpueyo/luci,lcf258/openwrtcn,dwmw2/luci,florian-shellfire/luci,dismantl/luci-0.12,joaofvieira/luci,male-puppies/luci,bright-things/ionic-luci,kuoruan/luci,forward619/luci,marcel-sch/luci,LuttyYang/luci,981213/luci-1,cshore-firmware/openwrt-luci,thess/OpenWrt-luci,Noltari/luci,remakeelectric/luci,db260179/openwrt-bpi-r1-luci,cshore-firmware/openwrt-luci,Hostle/luci,remakeelectric/luci,lcf258/openwrtcn,Kyklas/luci-proto-hso,aircross/OpenWrt-Firefly-LuCI,981213/luci-1,RuiChen1113/luci,Hostle/openwrt-luci-multi-user,florian-shellfire/luci,Hostle/luci,MinFu/luci,palmettos/test,MinFu/luci,jchuang1977/luci-1,fkooman/luci,palmettos/cnLuCI,marcel-sch/luci,openwrt/luci,LuttyYang/luci,artynet/luci,opentechinstitute/luci,remakeelectric/luci,MinFu/luci,florian-shellfire/luci,kuoruan/lede-luci,RuiChen1113/luci,forward619/luci,artynet/luci,thess/OpenWrt-luci,jchuang1977/luci-1,aa65535/luci,taiha/luci,Hostle/luci,joaofvieira/luci,hnyman/luci,schidler/ionic-luci,deepak78/new-luci,ollie27/openwrt_luci,cshore/luci,male-puppies/luci,jchuang1977/luci-1,teslamint/luci,db260179/openwrt-bpi-r1-luci,maxrio/luci981213,Kyklas/luci-proto-hso,kuoruan/luci,obsy/luci,marcel-sch/luci,david-xiao/luci,Kyklas/luci-proto-hso,Noltari/luci,jchuang1977/luci-1,RedSnake64/openwrt-luci-packages,cshore/luci,LazyZhu/openwrt-luci-trunk-mod,slayerrensky/luci,Hostle/openwrt-luci-multi-user,chris5560/openwrt-luci,kuoruan/lede-luci,dismantl/luci-0.12,male-puppies/luci,thess/OpenWrt-luci,slayerrensky/luci,thesabbir/luci,zhaoxx063/luci,NeoRaider/luci,ReclaimYourPrivacy/cloak-luci,tcatm/luci,cappiewu/luci,marcel-sch/luci,ff94315/luci-1,cshore/luci,RuiChen1113/luci,chris5560/openwrt-luci,zhaoxx063/luci,nwf/openwrt-luci,deepak78/new-luci,MinFu/luci,ollie27/openwrt_luci,tobiaswaldvogel/luci,oneru/luci,artynet/luci,lcf258/openwrtcn,Sakura-Winkey/LuCI,nmav/luci,MinFu/luci,cappiewu/luci,artynet/luci,opentechinstitute/luci,openwrt/luci,LuttyYang/luci,forward619/luci,Kyklas/luci-proto-hso,shangjiyu/luci-with-extra,urueedi/luci,chris5560/openwrt-luci,maxrio/luci981213,ollie27/openwrt_luci,openwrt/luci,lcf258/openwrtcn,bittorf/luci,david-xiao/luci,openwrt-es/openwrt-luci,openwrt-es/openwrt-luci,RedSnake64/openwrt-luci-packages,rogerpueyo/luci,kuoruan/luci,shangjiyu/luci-with-extra,jorgifumi/luci,LuttyYang/luci,keyidadi/luci,MinFu/luci,Wedmer/luci,shangjiyu/luci-with-extra,daofeng2015/luci,Wedmer/luci,jlopenwrtluci/luci,sujeet14108/luci,urueedi/luci,mumuqz/luci,thess/OpenWrt-luci,Hostle/openwrt-luci-multi-user,thesabbir/luci,aa65535/luci,ff94315/luci-1,wongsyrone/luci-1,dismantl/luci-0.12,aa65535/luci,bright-things/ionic-luci,male-puppies/luci,opentechinstitute/luci,bittorf/luci,oyido/luci,remakeelectric/luci,daofeng2015/luci,NeoRaider/luci,schidler/ionic-luci,ff94315/luci-1,david-xiao/luci,lbthomsen/openwrt-luci,aa65535/luci,harveyhu2012/luci,oneru/luci,tcatm/luci,male-puppies/luci,maxrio/luci981213,taiha/luci,harveyhu2012/luci,artynet/luci,Hostle/openwrt-luci-multi-user,hnyman/luci,openwrt-es/openwrt-luci,mumuqz/luci,oneru/luci,sujeet14108/luci,thess/OpenWrt-luci,taiha/luci,fkooman/luci,palmettos/cnLuCI,deepak78/new-luci,aircross/OpenWrt-Firefly-LuCI,remakeelectric/luci,nwf/openwrt-luci,chris5560/openwrt-luci,schidler/ionic-luci,daofeng2015/luci,deepak78/new-luci,RedSnake64/openwrt-luci-packages,oneru/luci,joaofvieira/luci,teslamint/luci,artynet/luci,male-puppies/luci,oyido/luci,palmettos/test,981213/luci-1,lbthomsen/openwrt-luci,ReclaimYourPrivacy/cloak-luci,cshore-firmware/openwrt-luci,florian-shellfire/luci,slayerrensky/luci,opentechinstitute/luci,obsy/luci,taiha/luci,oneru/luci,kuoruan/lede-luci,slayerrensky/luci,cappiewu/luci,cshore/luci,cappiewu/luci,daofeng2015/luci,RuiChen1113/luci,nwf/openwrt-luci,ff94315/luci-1,kuoruan/luci,zhaoxx063/luci,marcel-sch/luci,obsy/luci,maxrio/luci981213,db260179/openwrt-bpi-r1-luci,tcatm/luci,981213/luci-1,RuiChen1113/luci,Hostle/luci,david-xiao/luci,jchuang1977/luci-1,Sakura-Winkey/LuCI,dwmw2/luci,Sakura-Winkey/LuCI,wongsyrone/luci-1,forward619/luci,slayerrensky/luci,aa65535/luci,MinFu/luci,Noltari/luci,RuiChen1113/luci,LazyZhu/openwrt-luci-trunk-mod,NeoRaider/luci,deepak78/new-luci,Hostle/luci,kuoruan/lede-luci,bittorf/luci,rogerpueyo/luci,oneru/luci,kuoruan/lede-luci,MinFu/luci,male-puppies/luci,cshore-firmware/openwrt-luci,mumuqz/luci,Kyklas/luci-proto-hso,sujeet14108/luci,Wedmer/luci,bright-things/ionic-luci,mumuqz/luci,palmettos/cnLuCI,urueedi/luci,wongsyrone/luci-1,aa65535/luci,lcf258/openwrtcn,lcf258/openwrtcn,Wedmer/luci,kuoruan/luci,Kyklas/luci-proto-hso,jlopenwrtluci/luci,Noltari/luci,LazyZhu/openwrt-luci-trunk-mod,oyido/luci,taiha/luci,openwrt-es/openwrt-luci,teslamint/luci,rogerpueyo/luci,joaofvieira/luci,urueedi/luci,cshore/luci,keyidadi/luci,taiha/luci,opentechinstitute/luci,deepak78/new-luci,tobiaswaldvogel/luci,aircross/OpenWrt-Firefly-LuCI,jchuang1977/luci-1,db260179/openwrt-bpi-r1-luci,aircross/OpenWrt-Firefly-LuCI,forward619/luci,hnyman/luci,oyido/luci,jchuang1977/luci-1,jorgifumi/luci,nwf/openwrt-luci,Hostle/openwrt-luci-multi-user,ollie27/openwrt_luci,palmettos/cnLuCI,openwrt/luci,rogerpueyo/luci,hnyman/luci,Sakura-Winkey/LuCI,lbthomsen/openwrt-luci,harveyhu2012/luci,keyidadi/luci,obsy/luci,Hostle/openwrt-luci-multi-user,slayerrensky/luci,cshore/luci,bittorf/luci,aircross/OpenWrt-Firefly-LuCI,teslamint/luci,wongsyrone/luci-1,cshore-firmware/openwrt-luci,cappiewu/luci,palmettos/cnLuCI,RedSnake64/openwrt-luci-packages,kuoruan/luci,shangjiyu/luci-with-extra,schidler/ionic-luci,jlopenwrtluci/luci,lbthomsen/openwrt-luci,chris5560/openwrt-luci,oyido/luci,lcf258/openwrtcn,sujeet14108/luci,palmettos/test,rogerpueyo/luci,obsy/luci,marcel-sch/luci,deepak78/new-luci,nwf/openwrt-luci,oyido/luci,bright-things/ionic-luci,cshore/luci,Sakura-Winkey/LuCI,jorgifumi/luci,palmettos/cnLuCI,shangjiyu/luci-with-extra,jorgifumi/luci,thesabbir/luci,openwrt-es/openwrt-luci,openwrt/luci,keyidadi/luci,Hostle/openwrt-luci-multi-user,thesabbir/luci,ff94315/luci-1,cshore-firmware/openwrt-luci,LuttyYang/luci,chris5560/openwrt-luci,oneru/luci,Hostle/openwrt-luci-multi-user,kuoruan/lede-luci,urueedi/luci,fkooman/luci,jorgifumi/luci,aa65535/luci,ollie27/openwrt_luci,tobiaswaldvogel/luci,Sakura-Winkey/LuCI,981213/luci-1,obsy/luci,forward619/luci,981213/luci-1,openwrt-es/openwrt-luci,hnyman/luci,artynet/luci,Wedmer/luci,ReclaimYourPrivacy/cloak-luci,NeoRaider/luci,thesabbir/luci,tcatm/luci,harveyhu2012/luci,david-xiao/luci,nwf/openwrt-luci,zhaoxx063/luci,rogerpueyo/luci,taiha/luci,urueedi/luci,aircross/OpenWrt-Firefly-LuCI,forward619/luci,oneru/luci,hnyman/luci,thesabbir/luci,nmav/luci,ff94315/luci-1,Hostle/luci,ReclaimYourPrivacy/cloak-luci,florian-shellfire/luci,NeoRaider/luci,artynet/luci,sujeet14108/luci,mumuqz/luci,remakeelectric/luci,dwmw2/luci,thess/OpenWrt-luci,harveyhu2012/luci,keyidadi/luci,Kyklas/luci-proto-hso,keyidadi/luci,ff94315/luci-1,palmettos/test,palmettos/test,dismantl/luci-0.12,aa65535/luci,artynet/luci,jorgifumi/luci,lcf258/openwrtcn,dwmw2/luci,lcf258/openwrtcn,fkooman/luci,ff94315/luci-1,palmettos/test,zhaoxx063/luci,teslamint/luci,maxrio/luci981213,jlopenwrtluci/luci,thess/OpenWrt-luci,palmettos/cnLuCI,daofeng2015/luci,ReclaimYourPrivacy/cloak-luci,Wedmer/luci,openwrt-es/openwrt-luci,nmav/luci,tobiaswaldvogel/luci,daofeng2015/luci,florian-shellfire/luci,cappiewu/luci,bittorf/luci,daofeng2015/luci,tcatm/luci,sujeet14108/luci,RuiChen1113/luci,Hostle/luci,taiha/luci,tobiaswaldvogel/luci,obsy/luci,openwrt/luci,schidler/ionic-luci,dismantl/luci-0.12,bittorf/luci,LazyZhu/openwrt-luci-trunk-mod,cshore-firmware/openwrt-luci,lbthomsen/openwrt-luci,tobiaswaldvogel/luci,openwrt-es/openwrt-luci,mumuqz/luci,opentechinstitute/luci,openwrt/luci,florian-shellfire/luci,db260179/openwrt-bpi-r1-luci,nwf/openwrt-luci,mumuqz/luci,ReclaimYourPrivacy/cloak-luci,tcatm/luci,rogerpueyo/luci,daofeng2015/luci,dismantl/luci-0.12,cshore-firmware/openwrt-luci,jlopenwrtluci/luci,cappiewu/luci,urueedi/luci,Noltari/luci,jlopenwrtluci/luci,wongsyrone/luci-1,thesabbir/luci,kuoruan/luci,db260179/openwrt-bpi-r1-luci,LuttyYang/luci,david-xiao/luci,zhaoxx063/luci,LazyZhu/openwrt-luci-trunk-mod,maxrio/luci981213,palmettos/test,tcatm/luci,florian-shellfire/luci,lbthomsen/openwrt-luci,forward619/luci,fkooman/luci,hnyman/luci,Noltari/luci,schidler/ionic-luci
|
bd6009326fb468890ddabc16d6014916f08710ff
|
src/luarocks/cmd/build.lua
|
src/luarocks/cmd/build.lua
|
--- Module implementing the LuaRocks "build" command.
-- Builds a rock, compiling its C parts if any.
local cmd_build = {}
local dir = require("luarocks.dir")
local pack = require("luarocks.pack")
local path = require("luarocks.path")
local util = require("luarocks.util")
local fetch = require("luarocks.fetch")
local fs = require("luarocks.fs")
local deps = require("luarocks.deps")
local remove = require("luarocks.remove")
local cfg = require("luarocks.core.cfg")
local build = require("luarocks.build")
local writer = require("luarocks.manif.writer")
local search = require("luarocks.search")
local make = require("luarocks.cmd.make")
local cmd = require("luarocks.cmd")
function cmd_build.add_to_parser(parser)
local cmd = parser:command("build", "Build and install a rock, compiling its C parts if any.\n"..
"If no arguments are given, behaves as luarocks make.", util.see_also())
:summary("Build/compile a rock.")
cmd:argument("rock", "A rockspec file, a source rock file, or the name of "..
"a rock to be fetched from a repository.")
:args("?")
cmd:argument("version", "Rock version.")
:args("?")
cmd:flag("--only-deps", "Installs only the dependencies of the rock.")
make.cmd_options(cmd)
end
--- Build and install a rock.
-- @param rock_filename string: local or remote filename of a rock.
-- @param opts table: build options
-- @return boolean or (nil, string, [string]): True if build was successful,
-- or false and an error message and an optional error code.
local function build_rock(rock_filename, opts)
assert(type(rock_filename) == "string")
assert(opts:type() == "build.opts")
local ok, err, errcode
local unpack_dir
unpack_dir, err, errcode = fetch.fetch_and_unpack_rock(rock_filename, nil, opts.verify)
if not unpack_dir then
return nil, err, errcode
end
local rockspec_filename = path.rockspec_name_from_rock(rock_filename)
ok, err = fs.change_dir(unpack_dir)
if not ok then return nil, err end
local rockspec
rockspec, err, errcode = fetch.load_rockspec(rockspec_filename)
if not rockspec then
return nil, err, errcode
end
ok, err, errcode = build.build_rockspec(rockspec, opts)
fs.pop_dir()
return ok, err, errcode
end
local function do_build(ns_name, version, opts)
assert(type(ns_name) == "string")
assert(version == nil or type(version) == "string")
assert(opts:type() == "build.opts")
local url, err
if ns_name:match("%.rockspec$") or ns_name:match("%.rock$") then
url = ns_name
else
url, err = search.find_src_or_rockspec(ns_name, version, true)
if not url then
return nil, err
end
local _, namespace = util.split_namespace(ns_name)
opts.namespace = namespace
end
if url:match("%.rockspec$") then
local rockspec, err, errcode = fetch.load_rockspec(url, nil, opts.verify)
if not rockspec then
return nil, err, errcode
end
return build.build_rockspec(rockspec, opts)
end
if url:match("%.src%.rock$") then
opts.need_to_fetch = false
end
return build_rock(url, opts)
end
local function remove_doc_dir(name, version)
local install_dir = path.install_dir(name, version)
for _, f in ipairs(fs.list_dir(install_dir)) do
local doc_dirs = { "doc", "docs" }
for _, d in ipairs(doc_dirs) do
if f == d then
fs.delete(dir.path(install_dir, f))
end
end
end
end
--- Driver function for "build" command.
-- If a package name is given, forwards the request to "search" and,
-- if returned a result, installs the matching rock.
-- When passing a package name, a version number may also be given.
-- @return boolean or (nil, string, exitcode): True if build was successful; nil and an
-- error message otherwise. exitcode is optionally returned.
function cmd_build.command(args)
if not args.rock then
return make.command(args)
end
local name = util.adjust_name_and_namespace(args.rock, args)
local opts = build.opts({
need_to_fetch = true,
minimal_mode = false,
deps_mode = deps.get_deps_mode(args),
build_only_deps = not not args.only_deps,
namespace = args.namespace,
branch = not not args.branch,
verify = not not args.verify,
})
if args.sign and not args.pack_binary_rock then
return nil, "In the build command, --sign is meant to be used only with --pack-binary-rock"
end
if args.pack_binary_rock then
return pack.pack_binary_rock(name, args.version, args.sign, function()
opts.build_only_deps = false
local status, err, errcode = do_build(name, args.version, opts)
if status and args.no_doc then
remove_doc_dir(name, args.version)
end
return status, err, errcode
end)
end
local ok, err = fs.check_command_permissions(args)
if not ok then
return nil, err, cmd.errorcodes.PERMISSIONDENIED
end
ok, err = do_build(name, args.version, opts)
if not ok then return nil, err end
local version
name, version = ok, err
if args.no_doc then
remove_doc_dir(name, version)
end
if opts.build_only_deps then
util.printout("Stopping after installing dependencies for " ..name.." "..version)
util.printout()
else
if (not args.keep) and not cfg.keep_other_versions then
local ok, err = remove.remove_other_versions(name, version, args.force, args.force_fast)
if not ok then
util.printerr(err)
end
end
end
writer.check_dependencies(nil, deps.get_deps_mode(args))
return name, version
end
return cmd_build
|
--- Module implementing the LuaRocks "build" command.
-- Builds a rock, compiling its C parts if any.
local cmd_build = {}
local dir = require("luarocks.dir")
local pack = require("luarocks.pack")
local path = require("luarocks.path")
local util = require("luarocks.util")
local fetch = require("luarocks.fetch")
local fs = require("luarocks.fs")
local deps = require("luarocks.deps")
local remove = require("luarocks.remove")
local cfg = require("luarocks.core.cfg")
local build = require("luarocks.build")
local writer = require("luarocks.manif.writer")
local search = require("luarocks.search")
local make = require("luarocks.cmd.make")
local cmd = require("luarocks.cmd")
function cmd_build.add_to_parser(parser)
local cmd = parser:command("build", "Build and install a rock, compiling its C parts if any.\n"..
"If no arguments are given, behaves as luarocks make.", util.see_also())
:summary("Build/compile a rock.")
cmd:argument("rock", "A rockspec file, a source rock file, or the name of "..
"a rock to be fetched from a repository.")
:args("?")
cmd:argument("version", "Rock version.")
:args("?")
cmd:flag("--only-deps", "Installs only the dependencies of the rock.")
cmd:flag("--no-doc", "Installs the rock without its documentation.")
make.cmd_options(cmd)
end
--- Build and install a rock.
-- @param rock_filename string: local or remote filename of a rock.
-- @param opts table: build options
-- @return boolean or (nil, string, [string]): True if build was successful,
-- or false and an error message and an optional error code.
local function build_rock(rock_filename, opts)
assert(type(rock_filename) == "string")
assert(opts:type() == "build.opts")
local ok, err, errcode
local unpack_dir
unpack_dir, err, errcode = fetch.fetch_and_unpack_rock(rock_filename, nil, opts.verify)
if not unpack_dir then
return nil, err, errcode
end
local rockspec_filename = path.rockspec_name_from_rock(rock_filename)
ok, err = fs.change_dir(unpack_dir)
if not ok then return nil, err end
local rockspec
rockspec, err, errcode = fetch.load_rockspec(rockspec_filename)
if not rockspec then
return nil, err, errcode
end
ok, err, errcode = build.build_rockspec(rockspec, opts)
fs.pop_dir()
return ok, err, errcode
end
local function do_build(ns_name, version, opts)
assert(type(ns_name) == "string")
assert(version == nil or type(version) == "string")
assert(opts:type() == "build.opts")
local url, err
if ns_name:match("%.rockspec$") or ns_name:match("%.rock$") then
url = ns_name
else
url, err = search.find_src_or_rockspec(ns_name, version, true)
if not url then
return nil, err
end
local _, namespace = util.split_namespace(ns_name)
opts.namespace = namespace
end
if url:match("%.rockspec$") then
local rockspec, err, errcode = fetch.load_rockspec(url, nil, opts.verify)
if not rockspec then
return nil, err, errcode
end
return build.build_rockspec(rockspec, opts)
end
if url:match("%.src%.rock$") then
opts.need_to_fetch = false
end
return build_rock(url, opts)
end
local function remove_doc_dir(name, version)
local install_dir = path.install_dir(name, version)
for _, f in ipairs(fs.list_dir(install_dir)) do
local doc_dirs = { "doc", "docs" }
for _, d in ipairs(doc_dirs) do
if f == d then
fs.delete(dir.path(install_dir, f))
end
end
end
end
--- Driver function for "build" command.
-- If a package name is given, forwards the request to "search" and,
-- if returned a result, installs the matching rock.
-- When passing a package name, a version number may also be given.
-- @return boolean or (nil, string, exitcode): True if build was successful; nil and an
-- error message otherwise. exitcode is optionally returned.
function cmd_build.command(args)
if not args.rock then
return make.command(args)
end
local name = util.adjust_name_and_namespace(args.rock, args)
local opts = build.opts({
need_to_fetch = true,
minimal_mode = false,
deps_mode = deps.get_deps_mode(args),
build_only_deps = not not args.only_deps,
namespace = args.namespace,
branch = not not args.branch,
verify = not not args.verify,
})
if args.sign and not args.pack_binary_rock then
return nil, "In the build command, --sign is meant to be used only with --pack-binary-rock"
end
if args.pack_binary_rock then
return pack.pack_binary_rock(name, args.version, args.sign, function()
opts.build_only_deps = false
local status, err, errcode = do_build(name, args.version, opts)
if status and args.no_doc then
remove_doc_dir(name, args.version)
end
return status, err, errcode
end)
end
local ok, err = fs.check_command_permissions(args)
if not ok then
return nil, err, cmd.errorcodes.PERMISSIONDENIED
end
ok, err = do_build(name, args.version, opts)
if not ok then return nil, err end
local version
name, version = ok, err
if args.no_doc then
remove_doc_dir(name, version)
end
if opts.build_only_deps then
util.printout("Stopping after installing dependencies for " ..name.." "..version)
util.printout()
else
if (not args.keep) and not cfg.keep_other_versions then
local ok, err = remove.remove_other_versions(name, version, args.force, args.force_fast)
if not ok then
util.printerr(err)
end
end
end
writer.check_dependencies(nil, deps.get_deps_mode(args))
return name, version
end
return cmd_build
|
Fix build --no-doc
|
Fix build --no-doc
|
Lua
|
mit
|
luarocks/luarocks,keplerproject/luarocks,luarocks/luarocks,keplerproject/luarocks,keplerproject/luarocks,luarocks/luarocks,keplerproject/luarocks
|
54b33bd6a7853653f74d33e6cf3e22d5193bbb64
|
frontend/ui/device.lua
|
frontend/ui/device.lua
|
Device = {
screen_saver_mode = false,
charging_mode = false,
}
function Device:getModel()
local std_out = io.popen("grep 'MX' /proc/cpuinfo | cut -d':' -f2 | awk {'print $2'}", "r")
local cpu_mod = std_out:read()
if not cpu_mod then
return nil
end
if cpu_mod == "MX50" then
local f = lfs.attributes("/sys/devices/system/fl_tps6116x/fl_tps6116x0/fl_intensity")
if f then
return "KindlePaperWhite"
else
return "Kindle4"
end
elseif cpu_mod == "MX35" then
-- check if we are running on Kindle 3 (additional volume input)
local f = lfs.attributes("/dev/input/event2")
if f then
return "Kindle3"
else
return "KindleDXG"
end
elseif cpu_mod == "MX3" then
return "Kindle2"
else
return nil
end
end
function Device:isKindle4()
re_val = os.execute("cat /proc/cpuinfo | grep MX50")
if re_val == 0 then
return true
else
return false
end
end
function Device:isKindle3()
re_val = os.execute("cat /proc/cpuinfo | grep MX35")
if re_val == 0 then
return true
else
return false
end
end
function Device:isKindle2()
re_val = os.execute("cat /proc/cpuinfo | grep MX3")
if re_val == 0 then
return true
else
return false
end
end
function Device:intoScreenSaver()
--os.execute("echo 'screensaver in' >> /mnt/us/event_test.txt")
if self.charging_mode == false and self.screen_saver_mode == false then
Screen:saveCurrentBB()
msg = InfoMessage:new{"Going into screensaver... "}
UIManager:show(msg)
Screen.kpv_rotation_mode = Screen.cur_rotation_mode
Screen.fb:setOrientation(Screen.native_rotation_mode)
util.sleep(1)
os.execute("killall -cont cvm")
self.screen_saver_mode = true
UIManager:close(msg)
end
end
function Device:outofScreenSaver()
--os.execute("echo 'screensaver out' >> /mnt/us/event_test.txt")
if self.screen_saver_mode == true and self.charging_mode == false then
util.usleep(1500000)
os.execute("killall -stop cvm")
Screen.fb:setOrientation(Screen.kpv_rotation_mode)
Screen:restoreFromSavedBB()
Screen.fb:refresh(0)
end
self.screen_saver_mode = false
end
function Device:usbPlugIn()
--os.execute("echo 'usb in' >> /mnt/us/event_test.txt")
if self.charging_mode == false and self.screen_saver_mode == false then
Screen:saveCurrentBB()
Screen.kpv_rotation_mode = Screen.cur_rotation_mode
Screen.fb:setOrientation(Screen.native_rotation_mode)
msg = InfoMessage:new{"Going into USB mode... "}
UIManager:show(msg)
util.sleep(1)
UIManager:close(msg)
os.execute("killall -cont cvm")
end
self.charging_mode = true
end
function Device:usbPlugOut()
--os.execute("echo 'usb out' >> /mnt/us/event_test.txt")
if self.charging_mode == true and self.screen_saver_mode == false then
util.usleep(1500000)
os.execute("killall -stop cvm")
Screen.fb:setOrientation(Screen.kpv_rotation_mode)
Screen:restoreFromSavedBB()
Screen.fb:refresh(0)
end
--@TODO signal filemanager for file changes 13.06 2012 (houqp)
--FileChooser:setPath(FileChooser.path)
--FileChooser.pagedirty = true
self.charging_mode = false
end
|
Device = {
screen_saver_mode = false,
charging_mode = false,
}
function Device:getModel()
local std_out = io.popen("grep 'MX' /proc/cpuinfo | cut -d':' -f2 | awk {'print $2'}", "r")
local cpu_mod = std_out:read()
if not cpu_mod then
local ret = os.execute("grep 'Hardware : Mario Platform' /proc/cpuinfo", "r")
if ret ~= 0 then
return nil
else
return "KindleDXG"
end
end
if cpu_mod == "MX50" then
local f = lfs.attributes("/sys/devices/system/fl_tps6116x/fl_tps6116x0/fl_intensity")
if f then
return "KindlePaperWhite"
else
return "Kindle4"
end
elseif cpu_mod == "MX35" then
-- check if we are running on Kindle 3 (additional volume input)
return "Kindle3"
elseif cpu_mod == "MX3" then
return "Kindle2"
else
return nil
end
end
function Device:isKindle4()
re_val = os.execute("cat /proc/cpuinfo | grep MX50")
if re_val == 0 then
return true
else
return false
end
end
function Device:isKindle3()
re_val = os.execute("cat /proc/cpuinfo | grep MX35")
if re_val == 0 then
return true
else
return false
end
end
function Device:isKindle2()
re_val = os.execute("cat /proc/cpuinfo | grep MX3")
if re_val == 0 then
return true
else
return false
end
end
function Device:intoScreenSaver()
--os.execute("echo 'screensaver in' >> /mnt/us/event_test.txt")
if self.charging_mode == false and self.screen_saver_mode == false then
Screen:saveCurrentBB()
msg = InfoMessage:new{"Going into screensaver... "}
UIManager:show(msg)
Screen.kpv_rotation_mode = Screen.cur_rotation_mode
Screen.fb:setOrientation(Screen.native_rotation_mode)
util.sleep(1)
os.execute("killall -cont cvm")
self.screen_saver_mode = true
UIManager:close(msg)
end
end
function Device:outofScreenSaver()
--os.execute("echo 'screensaver out' >> /mnt/us/event_test.txt")
if self.screen_saver_mode == true and self.charging_mode == false then
util.usleep(1500000)
os.execute("killall -stop cvm")
Screen.fb:setOrientation(Screen.kpv_rotation_mode)
Screen:restoreFromSavedBB()
Screen.fb:refresh(0)
end
self.screen_saver_mode = false
end
function Device:usbPlugIn()
--os.execute("echo 'usb in' >> /mnt/us/event_test.txt")
if self.charging_mode == false and self.screen_saver_mode == false then
Screen:saveCurrentBB()
Screen.kpv_rotation_mode = Screen.cur_rotation_mode
Screen.fb:setOrientation(Screen.native_rotation_mode)
msg = InfoMessage:new{"Going into USB mode... "}
UIManager:show(msg)
util.sleep(1)
UIManager:close(msg)
os.execute("killall -cont cvm")
end
self.charging_mode = true
end
function Device:usbPlugOut()
--os.execute("echo 'usb out' >> /mnt/us/event_test.txt")
if self.charging_mode == true and self.screen_saver_mode == false then
util.usleep(1500000)
os.execute("killall -stop cvm")
Screen.fb:setOrientation(Screen.kpv_rotation_mode)
Screen:restoreFromSavedBB()
Screen.fb:refresh(0)
end
--@TODO signal filemanager for file changes 13.06 2012 (houqp)
--FileChooser:setPath(FileChooser.path)
--FileChooser.pagedirty = true
self.charging_mode = false
end
|
fix DXG detection
|
fix DXG detection
|
Lua
|
agpl-3.0
|
lgeek/koreader,Hzj-jie/koreader-base,Hzj-jie/koreader-base,poire-z/koreader,Hzj-jie/koreader-base,Frenzie/koreader-base,NiLuJe/koreader-base,houqp/koreader-base,houqp/koreader,ashhher3/koreader,Frenzie/koreader-base,NiLuJe/koreader-base,frankyifei/koreader-base,frankyifei/koreader-base,houqp/koreader-base,mihailim/koreader,poire-z/koreader,koreader/koreader,apletnev/koreader-base,koreader/koreader-base,houqp/koreader-base,Frenzie/koreader,apletnev/koreader-base,NiLuJe/koreader,Hzj-jie/koreader-base,NickSavage/koreader,frankyifei/koreader-base,ashang/koreader,noname007/koreader,apletnev/koreader,houqp/koreader-base,Hzj-jie/koreader,Frenzie/koreader-base,koreader/koreader-base,NiLuJe/koreader,Markismus/koreader,NiLuJe/koreader-base,chrox/koreader,koreader/koreader-base,pazos/koreader,robert00s/koreader,chihyang/koreader,frankyifei/koreader-base,frankyifei/koreader,mwoz123/koreader,Frenzie/koreader,NiLuJe/koreader-base,koreader/koreader-base,koreader/koreader,Frenzie/koreader-base,apletnev/koreader-base,apletnev/koreader-base
|
fc3ef2567cf97298b48f2fb12482d5eda670c083
|
lua/tests/expression.lua
|
lua/tests/expression.lua
|
-- Copyright (c) 2009 Incremental IP Limited
-- see license.txt for license information
local series = require("test.series")
local expression = require("rima.expression")
local scope = require("rima.scope")
local object = require("rima.object")
local rima = require("rima")
module(...)
-- Tests -----------------------------------------------------------------------
local function equal(T, expected, got)
local function prep(z)
if object.type(z) == "table" then
local e = z[1]
for i = 3, #z do
e = expression[z[i]](e, z[2])
end
return e
else
return z
end
end
local e, g = prep(expected), prep(got)
T:check_equal(g, e, nil, 1)
end
function test(show_passes)
local T = series:new(_M, show_passes)
-- local o = operators.operator:new()
-- T:expect_error(function() expression:new({}) end,
-- "rima.expression:new: expecting an operator, variable or number for 'operator', got 'table'")
-- T:expect_error(function() expression:new("a") end,
-- "expecting an operator, variable or number for 'operator', got 'string'")
-- T:expect_ok(function() expression:new(o) end)
-- T:test(isa(expression:new(o), expression), "isa(expression:new(), expression)")
-- T:check_equal(type(expression:new(o)), "expression", "type(expression:new() == 'expression'")
local S = scope.new()
-- literals
equal(T, "number(1)", {1, nil, "dump"})
equal(T, 1, {1, S, "eval"})
-- variables
local a = rima.R"a"
equal(T, "ref(a)", {a, nil, "dump"})
T:expect_ok(function() rima.E(a, S) end)
equal(T, "ref(a)", {a, S, "dump"})
equal(T, "a", {a, S, "eval"})
S.a = rima.free()
equal(T, "a", {a, S, "eval"})
equal(T, 5, {a, scope.spawn(S, { a=5 }), "eval"})
-- repr
T:check_equal(expression.dump(1), "number(1)")
-- eval
T:expect_ok(function() expression.eval(expression:new({}), {}) end)
T:check_equal(expression.eval(expression:new({}), {}), "table()")
-- tests with add, mul and pow
do
local a, b = rima.R"a, b"
local S = rima.scope.create{ ["a,b"]=rima.free() }
equal(T, "+(1*number(3), 4*ref(a))", {3 + 4 * a, S, "eval", "dump"})
equal(T, "3 - 4*a", {4 * -a + 3, S, "eval"})
equal(T, "+(1*number(3), 4**(ref(a)^1, ref(b)^1))", {3 + 4 * a * b, S, "eval", "dump"})
equal(T, "3 - 4*a*b", {3 - 4 * a * b, S, "eval"})
equal(T, "*(number(6)^1, ref(a)^1)", {3 * (a + a), S, "eval", "dump"})
equal(T, "6*a", {3 * (a + a), S, "eval"})
equal(T, "+(1*number(1), 6*ref(a))", {1 + 3 * (a + a), S, "eval", "dump"})
equal(T, "1 + 6*a", {1 + 3 * (a + a), S, "eval"})
equal(T, "*(number(1.5)^1, ref(a)^-1)", {3 / (a + a), S, "eval", "dump"})
equal(T, "1.5/a", {3 / (a + a), S, "eval"})
equal(T, "+(1*number(1), 1.5**(ref(a)^-1))", {1 + 3 / (a + a), S, "eval", "dump"})
equal(T, "1 + 1.5/a", {1 + 3 / (a + a), S, "eval"})
equal(T, "*(number(3)^1, ^(ref(a), number(2))^1)", {3 * a^2, nil, "dump"})
equal(T, "*(number(3)^1, ref(a)^2)", {3 * a^2, S, "eval", "dump"})
equal(T, "*(number(3)^1, +(1*number(1), 1*ref(a))^2)", {3 * (a+1)^2, S, "eval", "dump"})
end
-- tests with references to expressions
do
local a, b = rima.R"a,b"
local S = rima.scope.create{ a = rima.free(), b = 3 * (a + 1)^2 }
equal(T, {b, S, "eval", "dump"}, {3 * (a + 1)^2, S, "eval", "dump"})
equal(T, {5 * b, S, "eval", "dump"}, {5 * (3 * (a + 1)^2), S, "eval", "dump"} )
local c, d = rima.R"c,d"
S.d = 3 + (c * 5)^2
T:expect_ok(function() expression.eval(5 * d, S) end)
equal(T, "5*(3 + (5*c)^2)", {5 * d, S, "eval"})
end
-- references to functions
do
local f, x, y = rima.R"f, x, y"
local S = rima.scope.create{ x = 2, f = rima.F({y}, y + 5) }
T:check_equal(rima.E(f(x), S), 7)
end
-- Tagged expressions
do
local x, y = rima.R"x, y"
local e = x + y
expression.tag(e, { check = 1 })
T:check_equal(expression.tags(e).check, 1)
T:check_equal(expression.tags(rima.E(e, { x=1 })).check, 1)
T:check_equal(expression.tags(rima.E(e, { y=2 })).check, 1)
T:expect_ok(function() local a = expression.tags(rima.E(e, { x=1, y=2 })).check end)
T:check_equal(expression.tags(rima.E(e, { x=1, y=2 })).check, nil)
end
return T:close()
end
-- EOF -------------------------------------------------------------------------
|
-- Copyright (c) 2009 Incremental IP Limited
-- see license.txt for license information
local series = require("test.series")
local expression = require("rima.expression")
local scope = require("rima.scope")
local object = require("rima.object")
local rima = require("rima")
module(...)
-- Tests -----------------------------------------------------------------------
local function equal(T, expected, got)
local function prep(z)
if object.type(z) == "table" then
local e = z[1]
for i = 3, #z do
local arg = z[2]
arg = (arg ~= "" and arg) or nil
e = expression[z[i]](e, arg)
end
return e
else
return z
end
end
local e, g = prep(expected), prep(got)
T:check_equal(g, e, nil, 1)
end
function test(show_passes)
local T = series:new(_M, show_passes)
-- local o = operators.operator:new()
-- T:expect_error(function() expression:new({}) end,
-- "rima.expression:new: expecting an operator, variable or number for 'operator', got 'table'")
-- T:expect_error(function() expression:new("a") end,
-- "expecting an operator, variable or number for 'operator', got 'string'")
-- T:expect_ok(function() expression:new(o) end)
-- T:test(isa(expression:new(o), expression), "isa(expression:new(), expression)")
-- T:check_equal(type(expression:new(o)), "expression", "type(expression:new() == 'expression'")
local S = scope.new()
-- literals
equal(T, "number(1)", {1, "", "dump"})
equal(T, 1, {1, S, "eval"})
-- variables
local a = rima.R"a"
equal(T, "ref(a)", {a, "", "dump"})
T:expect_ok(function() rima.E(a, S) end)
equal(T, "ref(a)", {a, S, "dump"})
equal(T, "a", {a, S, "eval"})
S.a = rima.free()
equal(T, "a", {a, S, "eval"})
equal(T, 5, {a, scope.spawn(S, { a=5 }), "eval"})
-- repr
T:check_equal(expression.dump(1), "number(1)")
-- eval
T:expect_ok(function() expression.eval(expression:new({}), {}) end)
T:check_equal(expression.eval(expression:new({}), {}), "table()")
-- tests with add, mul and pow
do
local a, b = rima.R"a, b"
local S = rima.scope.create{ ["a,b"]=rima.free() }
equal(T, "+(1*number(3), 4*ref(a))", {3 + 4 * a, S, "eval", "dump"})
equal(T, "3 - 4*a", {4 * -a + 3, S, "eval"})
equal(T, "+(1*number(3), 4**(ref(a)^1, ref(b)^1))", {3 + 4 * a * b, S, "eval", "dump"})
equal(T, "3 - 4*a*b", {3 - 4 * a * b, S, "eval"})
equal(T, "*(number(6)^1, ref(a)^1)", {3 * (a + a), S, "eval", "dump"})
equal(T, "6*a", {3 * (a + a), S, "eval"})
equal(T, "+(1*number(1), 6*ref(a))", {1 + 3 * (a + a), S, "eval", "dump"})
equal(T, "1 + 6*a", {1 + 3 * (a + a), S, "eval"})
equal(T, "*(number(1.5)^1, ref(a)^-1)", {3 / (a + a), S, "eval", "dump"})
equal(T, "1.5/a", {3 / (a + a), S, "eval"})
equal(T, "+(1*number(1), 1.5**(ref(a)^-1))", {1 + 3 / (a + a), S, "eval", "dump"})
equal(T, "1 + 1.5/a", {1 + 3 / (a + a), S, "eval"})
equal(T, "*(number(3)^1, ^(ref(a), number(2))^1)", {3 * a^2, "", "dump"})
equal(T, "*(number(3)^1, ref(a)^2)", {3 * a^2, S, "eval", "dump"})
equal(T, "*(number(3)^1, +(1*number(1), 1*ref(a))^2)", {3 * (a+1)^2, S, "eval", "dump"})
end
-- tests with references to expressions
do
local a, b = rima.R"a,b"
local S = rima.scope.create{ a = rima.free(), b = 3 * (a + 1)^2 }
equal(T, {b, S, "eval", "dump"}, {3 * (a + 1)^2, S, "eval", "dump"})
equal(T, {5 * b, S, "eval", "dump"}, {5 * (3 * (a + 1)^2), S, "eval", "dump"} )
local c, d = rima.R"c,d"
S.d = 3 + (c * 5)^2
T:expect_ok(function() expression.eval(5 * d, S) end)
equal(T, "5*(3 + (5*c)^2)", {5 * d, S, "eval"})
end
-- references to functions
do
local f, x, y = rima.R"f, x, y"
local S = rima.scope.create{ x = 2, f = rima.F({y}, y + 5) }
T:check_equal(rima.E(f(x), S), 7)
end
-- Tagged expressions
do
local x, y = rima.R"x, y"
local e = x + y
expression.tag(e, { check = 1 })
T:check_equal(expression.tags(e).check, 1)
T:check_equal(expression.tags(rima.E(e, { x=1 })).check, 1)
T:check_equal(expression.tags(rima.E(e, { y=2 })).check, 1)
T:expect_ok(function() local a = expression.tags(rima.E(e, { x=1, y=2 })).check end)
T:check_equal(expression.tags(rima.E(e, { x=1, y=2 })).check, nil)
end
return T:close()
end
-- EOF -------------------------------------------------------------------------
|
fixed careless use of nil in tables in expression tests
|
fixed careless use of nil in tables in expression tests
|
Lua
|
mit
|
geoffleyland/rima,geoffleyland/rima,geoffleyland/rima
|
235a6cc256f2770889f8c493efa0aed037731a2b
|
premake5.lua
|
premake5.lua
|
solution "ponyc"
configurations { "Debug", "Release", "Profile" }
location( _OPTIONS["to"] )
flags {
"FatalWarnings",
"MultiProcessorCompile",
"ReleaseRuntime" --for all configs
}
configuration "Debug"
targetdir "bin/debug"
objdir "obj/debug"
defines "DEBUG"
flags { "Symbols" }
configuration "Release"
targetdir "bin/release"
objdir "obj/release"
configuration "Profile"
targetdir "bin/profile"
objdir "obj/profile"
configuration "Release or Profile"
defines "NDEBUG"
optimize "Speed"
--flags { "LinkTimeOptimization" }
if not os.is("windows") then
linkoptions {
"-flto",
"-fuse-ld=gold"
}
end
configuration { "Profile", "gmake" }
buildoptions "-pg"
linkoptions "-pg"
configuration { "Profile", "vs*" }
buildoptions "/PROFILE"
configuration "vs*"
debugdir "."
defines {
-- disables warnings for vsnprintf
"_CRT_SECURE_NO_WARNINGS"
}
configuration { "not windows" }
linkoptions {
"-pthread"
}
configuration { "macosx", "gmake" }
toolset "clang"
buildoptions "-Qunused-arguments"
linkoptions "-Qunused-arguments"
configuration "gmake"
buildoptions {
"-march=native"
}
configuration "vs*"
architecture "x64"
dofile("scripts/properties.lua")
dofile("scripts/llvm.lua")
dofile("scripts/helper.lua")
project "libponyc"
targetname "ponyc"
kind "StaticLib"
language "C"
includedirs {
llvm_config("--includedir"),
"src/common"
}
files {
"src/common/*.h",
"src/libponyc/**.c*",
"src/libponyc/**.h"
}
configuration "gmake"
buildoptions{
"-std=gnu11"
}
defines {
"__STDC_CONSTANT_MACROS",
"__STDC_FORMAT_MACROS",
"__STDC_LIMIT_MACROS"
}
excludes { "src/libponyc/**.cc" }
configuration "vs*"
defines {
"PONY_USE_BIGINT"
}
cppforce { "src/libponyc/**.c*" }
configuration "*"
project "libponyrt"
targetname "ponyrt"
kind "StaticLib"
language "C"
includedirs {
"src/common/",
"src/libponyrt/"
}
files {
"src/libponyrt/**.c",
"src/libponyrt/**.h"
}
configuration "gmake"
buildoptions {
"-std=gnu11"
}
configuration "vs*"
cppforce { "src/libponyrt/**.c" }
configuration "*"
project "ponyc"
kind "ConsoleApp"
language "C++"
includedirs {
"src/common/"
}
files {
"src/ponyc/**.h",
"src/ponyc/**.c"
}
configuration "gmake"
buildoptions "-std=gnu11"
configuration "vs*"
cppforce { "src/ponyc/**.c" }
configuration "*"
link_libponyc()
if ( _OPTIONS["with-tests"] or _OPTIONS["run-tests"] ) then
project "gtest"
targetname "gtest"
language "C++"
kind "StaticLib"
configuration "gmake"
buildoptions {
"-std=gnu++11"
}
configuration "*"
includedirs {
"utils/gtest"
}
files {
"utils/gtest/gtest-all.cc",
"utils/gtest/gtest_main.cc"
}
project "testc"
targetname "testc"
testsuite()
includedirs {
"utils/gtest",
"src/common",
"src/libponyc"
}
files {
"test/unit/ponyc/**.h",
"test/unit/ponyc/**.cc"
}
link_libponyc()
configuration "vs*"
defines { "PONY_USE_BIGINT" }
configuration "*"
project "testrt"
targetname "testrt"
testsuite()
links "libponyrt"
includedirs {
"utils/gtest",
"src/common",
"src/libponyrt"
}
files { "test/unit/ponyrt/**.cc" }
end
if _ACTION == "clean" then
--os.rmdir("bin") os.rmdir clears out the link targets of symbolic links...
--os.rmdir("obj")
end
-- Allow for out-of-source builds.
newoption {
trigger = "to",
value = "path",
description = "Set output location for generated files."
}
newoption {
trigger = "with-tests",
description = "Compile test suite for every build."
}
newoption {
trigger = "run-tests",
description = "Run the test suite on every successful build."
}
newoption {
trigger = "use-docsgen",
description = "Select a tool for generating the API documentation",
allowed = {
{ "sphinx", "Chooses Sphinx as documentation tool. (Default)" },
{ "doxygen", "Chooses Doxygen as documentation tool." }
}
}
dofile("scripts/release.lua")
-- Package release versions of ponyc for all supported platforms.
newaction {
trigger = "release",
description = "Prepare a new ponyc release.",
execute = dorelease
}
dofile("scripts/docs.lua")
newaction {
trigger = "docs",
value = "tool",
description = "Produce API documentation.",
execute = dodocs
}
|
local force_cpp = { }
function cppforce(inFiles)
for _, val in ipairs(inFiles) do
for _, fname in ipairs(os.matchfiles(val)) do
table.insert(force_cpp, path.getabsolute(fname))
end
end
end
-- gmake
premake.override(path, "iscfile", function(base, fname)
if table.contains(force_cpp, fname) then
return false
else
return base(fname)
end
end)
-- Visual Studio
premake.override(premake.vstudio.vc2010, "additionalCompileOptions", function(base, cfg, condition)
if cfg.abspath then
if table.contains(force_cpp, cfg.abspath) then
_p(3,'<CompileAs %s>CompileAsCpp</CompileAs>', condition)
end
end
return base(cfg, condition)
end)
function link_libponyc()
configuration "gmake"
linkoptions {
llvm_config("--ldflags")
}
configuration "vs*"
libdirs {
llvm_config("--libdir")
}
configuration "*"
links { "libponyc", "libponyrt" }
local output = llvm_config("--libs")
for lib in string.gmatch(output, "-l(%S+)") do
links { lib }
end
end
function llvm_config(opt)
--expect symlink of llvm-config to your config version (e.g llvm-config-3.4)
local stream = assert(io.popen("llvm-config " .. opt))
local output = ""
--llvm-config contains '\n'
while true do
local curr = stream:read("*l")
if curr == nil then
break
end
output = output .. curr
end
stream:close()
return output
end
function testsuite()
kind "ConsoleApp"
language "C++"
links "gtest"
configuration "gmake"
buildoptions { "-std=gnu++11" }
configuration "*"
if (_OPTIONS["run-tests"]) then
configuration "gmake"
postbuildcommands { "$(TARGET)" }
configuration "vs*"
postbuildcommands { "\"$(TargetPath)\"" }
configuration "*"
end
end
solution "ponyc"
configurations { "Debug", "Release", "Profile" }
location( _OPTIONS["to"] )
flags {
"FatalWarnings",
"MultiProcessorCompile",
"ReleaseRuntime" --for all configs
}
configuration "Debug"
targetdir "build/debug"
objdir "build/debug/obj"
defines "DEBUG"
flags { "Symbols" }
configuration "Release"
targetdir "build/release"
objdir "build/release/obj"
configuration "Profile"
targetdir "build/profile"
objdir "build/profile/obj"
configuration "Release or Profile"
defines "NDEBUG"
optimize "Speed"
--flags { "LinkTimeOptimization" }
if not os.is("windows") then
linkoptions {
"-flto",
"-fuse-ld=gold"
}
end
configuration { "Profile", "gmake" }
buildoptions "-pg"
linkoptions "-pg"
configuration { "Profile", "vs*" }
buildoptions "/PROFILE"
configuration "vs*"
debugdir "."
defines {
-- disables warnings for vsnprintf
"_CRT_SECURE_NO_WARNINGS"
}
configuration { "not windows" }
linkoptions {
"-pthread"
}
configuration { "macosx", "gmake" }
toolset "clang"
buildoptions "-Qunused-arguments"
linkoptions "-Qunused-arguments"
configuration "gmake"
buildoptions {
"-march=native"
}
configuration "vs*"
architecture "x64"
project "libponyc"
targetname "ponyc"
kind "StaticLib"
language "C"
includedirs {
llvm_config("--includedir"),
"src/common"
}
files {
"src/common/*.h",
"src/libponyc/**.c*",
"src/libponyc/**.h"
}
configuration "gmake"
buildoptions{
"-std=gnu11"
}
defines {
"__STDC_CONSTANT_MACROS",
"__STDC_FORMAT_MACROS",
"__STDC_LIMIT_MACROS"
}
excludes { "src/libponyc/**.cc" }
configuration "vs*"
defines {
"PONY_USE_BIGINT"
}
cppforce { "src/libponyc/**.c*" }
configuration "*"
project "libponyrt"
targetname "ponyrt"
kind "StaticLib"
language "C"
includedirs {
"src/common/",
"src/libponyrt/"
}
files {
"src/libponyrt/**.c",
"src/libponyrt/**.h"
}
configuration "gmake"
buildoptions {
"-std=gnu11"
}
configuration "vs*"
cppforce { "src/libponyrt/**.c" }
configuration "*"
project "ponyc"
kind "ConsoleApp"
language "C++"
includedirs {
"src/common/"
}
files {
"src/ponyc/**.h",
"src/ponyc/**.c"
}
configuration "gmake"
buildoptions "-std=gnu11"
configuration "vs*"
cppforce { "src/ponyc/**.c" }
configuration "*"
link_libponyc()
if ( _OPTIONS["with-tests"] or _OPTIONS["run-tests"] ) then
project "gtest"
targetname "gtest"
language "C++"
kind "StaticLib"
configuration "gmake"
buildoptions {
"-std=gnu++11"
}
configuration "*"
includedirs {
"utils/gtest"
}
files {
"lib/gtest/gtest-all.cc",
"lib/gtest/gtest_main.cc"
}
project "testc"
targetname "testc"
testsuite()
includedirs {
"utils/gtest",
"src/common",
"src/libponyc"
}
files {
"test/libponyc/**.h",
"test/libponyc/**.cc"
}
link_libponyc()
configuration "vs*"
defines { "PONY_USE_BIGINT" }
configuration "*"
project "testrt"
targetname "testrt"
testsuite()
links "libponyrt"
includedirs {
"lib/gtest",
"src/common",
"src/libponyrt"
}
files { "test/libponyrt/**.cc" }
end
if _ACTION == "clean" then
os.rmdir("build")
end
-- Allow for out-of-source builds.
newoption {
trigger = "to",
value = "path",
description = "Set output location for generated files."
}
newoption {
trigger = "with-tests",
description = "Compile test suite for every build."
}
newoption {
trigger = "run-tests",
description = "Run the test suite on every successful build."
}
|
fixed premake5.lua
|
fixed premake5.lua
|
Lua
|
bsd-2-clause
|
mkfifo/ponyc,sgebbie/ponyc,CausalityLtd/ponyc,jemc/ponyc,jemc/ponyc,Praetonus/ponyc,ryanai3/ponyc,boemmels/ponyc,dipinhora/ponyc,jupvfranco/ponyc,Perelandric/ponyc,jupvfranco/ponyc,jemc/ponyc,ryanai3/ponyc,gwelr/ponyc,cquinn/ponyc,pap/ponyc,kulibali/ponyc,darach/ponyc,dipinhora/ponyc,cquinn/ponyc,cquinn/ponyc,lukecheeseman/ponyta,Theodus/ponyc,Perelandric/ponyc,ponylang/ponyc,doublec/ponyc,dckc/ponyc,sgebbie/ponyc,kulibali/ponyc,mkfifo/ponyc,jupvfranco/ponyc,Praetonus/ponyc,darach/ponyc,mkfifo/ponyc,lukecheeseman/ponyta,ponylang/ponyc,Praetonus/ponyc,Perelandric/ponyc,shlomif/ponyc,kulibali/ponyc,sgebbie/ponyc,boemmels/ponyc,dckc/ponyc,jonas-l/ponyc,Perelandric/ponyc,Theodus/ponyc,boemmels/ponyc,Praetonus/ponyc,influx6/ponyc,shlomif/ponyc,malthe/ponyc,influx6/ponyc,dipinhora/ponyc,lukecheeseman/ponyta,jupvfranco/ponyc,mkfifo/ponyc,darach/ponyc,sgebbie/ponyc,pap/ponyc,sgebbie/ponyc,jupvfranco/ponyc,Theodus/ponyc,boemmels/ponyc,mkfifo/ponyc,doublec/ponyc,doublec/ponyc,malthe/ponyc,gwelr/ponyc,ponylang/ponyc,Theodus/ponyc,malthe/ponyc,jonas-l/ponyc,jonas-l/ponyc,CausalityLtd/ponyc,ryanai3/ponyc,pap/ponyc,CausalityLtd/ponyc,Theodus/ponyc,boemmels/ponyc,Perelandric/ponyc,malthe/ponyc,cquinn/ponyc,kulibali/ponyc
|
69b58cf189d4e49f33bea8912babfae3e2bac300
|
premake5.lua
|
premake5.lua
|
include("build_tools")
location(build_root)
targetdir(build_bin)
objdir(build_obj)
includedirs({
".",
"src",
"third_party",
})
defines({
"_UNICODE",
"UNICODE",
})
vectorextensions("AVX")
flags({
--"ExtraWarnings", -- Sets the compiler's maximum warning level.
"FatalWarnings", -- Treat warnings as errors.
"Unicode",
})
filter("kind:StaticLib")
defines({
"_LIB",
})
filter("configurations:Checked")
runtime("Debug")
defines({
"DEBUG",
})
runtime("Debug")
filter({"configurations:Checked", "platforms:Windows"})
buildoptions({
"/RTCsu", -- Full Run-Time Checks.
})
filter("configurations:Debug")
runtime("Debug")
defines({
"DEBUG",
"_NO_DEBUG_HEAP=1",
})
runtime("Release")
filter("configurations:Release")
runtime("Release")
defines({
"NDEBUG",
"_NO_DEBUG_HEAP=1",
})
optimize("On")
flags({
"LinkTimeOptimization",
})
runtime("Release")
filter("platforms:Linux")
system("linux")
toolset("clang")
buildoptions({
"-mlzcnt", -- Assume lzcnt supported.
})
filter({"platforms:Linux", "language:C++"})
buildoptions({
"-std=c++14",
})
filter("platforms:Windows")
system("windows")
toolset("msc")
buildoptions({
"/MP", -- Multiprocessor compilation.
"/wd4100", -- Unreferenced parameters are ok.
"/wd4201", -- Nameless struct/unions are ok.
"/wd4512", -- 'assignment operator was implicitly defined as deleted'.
"/wd4127", -- 'conditional expression is constant'.
"/wd4324", -- 'structure was padded due to alignment specifier'.
"/wd4189", -- 'local variable is initialized but not referenced'.
})
flags({
"NoMinimalRebuild", -- Required for /MP above.
"Symbols",
})
defines({
"_CRT_NONSTDC_NO_DEPRECATE",
"_CRT_SECURE_NO_WARNINGS",
"WIN32",
"_WIN64=1",
"_AMD64=1",
})
linkoptions({
"/ignore:4006", -- Ignores complaints about empty obj files.
"/ignore:4221",
"/NODEFAULTLIB:MSVCRTD"
})
links({
"ntdll",
"wsock32",
"ws2_32",
"xinput",
"xaudio2",
"glu32",
"opengl32",
"comctl32",
"shlwapi",
})
-- Create scratch/ path and dummy flags file if needed.
if not os.isdir("scratch") then
os.mkdir("scratch")
local flags_file = io.open("scratch/flags.txt", "w")
flags_file:write("# Put flags, one on each line.\n")
flags_file:write("# Launch executables with --flags_file=scratch/flags.txt\n")
flags_file:write("\n")
flags_file:write("--cpu=x64\n")
flags_file:write("#--enable_haswell_instructions=false\n")
flags_file:write("\n")
flags_file:write("--debug\n")
flags_file:write("#--protect_zero=false\n")
flags_file:write("\n")
flags_file:write("#--mute\n")
flags_file:write("\n")
flags_file:write("--fast_stdout\n")
flags_file:write("#--flush_stdout=false\n")
flags_file:write("\n")
flags_file:write("#--vsync=false\n")
flags_file:write("#--gl_debug\n")
flags_file:write("#--gl_debug_output\n")
flags_file:write("#--gl_debug_output_synchronous\n")
flags_file:write("#--trace_gpu_prefix=scratch/gpu/gpu_trace_\n")
flags_file:write("#--trace_gpu_stream\n")
flags_file:write("#--disable_framebuffer_readback\n")
flags_file:write("\n")
flags_file:close()
end
solution("xenia")
uuid("931ef4b0-6170-4f7a-aaf2-0fece7632747")
startproject("xenia-app")
architecture("x86_64")
if os.is("linux") then
platforms({"Linux"})
elseif os.is("windows") then
platforms({"Windows"})
end
configurations({"Checked", "Debug", "Release"})
-- Include third party files first so they don't have to deal with gflags.
include("third_party/capstone.lua")
include("third_party/elemental-forms")
include("third_party/glew.lua")
include("third_party/imgui.lua")
include("third_party/libav.lua")
include("third_party/xxhash.lua")
include("build_tools/third_party/gflags.lua")
include("src/xenia")
include("src/xenia/app")
include("src/xenia/apu")
include("src/xenia/apu/nop")
include("src/xenia/base")
include("src/xenia/cpu")
include("src/xenia/cpu/backend/x64")
include("src/xenia/debug")
include("src/xenia/debug/ui")
include("src/xenia/gpu")
include("src/xenia/gpu/gl4")
include("src/xenia/hid")
include("src/xenia/hid/nop")
include("src/xenia/kernel")
include("src/xenia/ui")
include("src/xenia/ui/gl")
include("src/xenia/vfs")
if os.is("windows") then
include("src/xenia/apu/xaudio2")
include("src/xenia/hid/winkey")
include("src/xenia/hid/xinput")
end
|
include("build_tools")
location(build_root)
targetdir(build_bin)
objdir(build_obj)
includedirs({
".",
"src",
"third_party",
})
defines({
"_UNICODE",
"UNICODE",
})
vectorextensions("AVX")
flags({
--"ExtraWarnings", -- Sets the compiler's maximum warning level.
"FatalWarnings", -- Treat warnings as errors.
"Unicode",
})
filter("kind:StaticLib")
defines({
"_LIB",
})
filter("configurations:Checked")
runtime("Debug")
defines({
"DEBUG",
})
runtime("Debug")
filter({"configurations:Checked", "platforms:Windows"})
buildoptions({
"/RTCsu", -- Full Run-Time Checks.
})
filter("configurations:Debug")
runtime("Debug")
defines({
"DEBUG",
"_NO_DEBUG_HEAP=1",
})
runtime("Release")
filter({"configurations:Debug", "platforms:Windows"})
linkoptions({
"/NODEFAULTLIB:MSVCRTD",
})
filter("configurations:Release")
runtime("Release")
defines({
"NDEBUG",
"_NO_DEBUG_HEAP=1",
})
optimize("On")
flags({
"LinkTimeOptimization",
})
runtime("Release")
filter({"configurations:Release", "platforms:Windows"})
linkoptions({
"/NODEFAULTLIB:MSVCRTD",
})
filter("platforms:Linux")
system("linux")
toolset("clang")
buildoptions({
"-mlzcnt", -- Assume lzcnt supported.
})
filter({"platforms:Linux", "language:C++"})
buildoptions({
"-std=c++14",
})
filter("platforms:Windows")
system("windows")
toolset("msc")
buildoptions({
"/MP", -- Multiprocessor compilation.
"/wd4100", -- Unreferenced parameters are ok.
"/wd4201", -- Nameless struct/unions are ok.
"/wd4512", -- 'assignment operator was implicitly defined as deleted'.
"/wd4127", -- 'conditional expression is constant'.
"/wd4324", -- 'structure was padded due to alignment specifier'.
"/wd4189", -- 'local variable is initialized but not referenced'.
})
flags({
"NoMinimalRebuild", -- Required for /MP above.
"Symbols",
})
defines({
"_CRT_NONSTDC_NO_DEPRECATE",
"_CRT_SECURE_NO_WARNINGS",
"WIN32",
"_WIN64=1",
"_AMD64=1",
})
linkoptions({
"/ignore:4006", -- Ignores complaints about empty obj files.
"/ignore:4221",
})
links({
"ntdll",
"wsock32",
"ws2_32",
"xinput",
"xaudio2",
"glu32",
"opengl32",
"comctl32",
"shlwapi",
})
-- Create scratch/ path and dummy flags file if needed.
if not os.isdir("scratch") then
os.mkdir("scratch")
local flags_file = io.open("scratch/flags.txt", "w")
flags_file:write("# Put flags, one on each line.\n")
flags_file:write("# Launch executables with --flags_file=scratch/flags.txt\n")
flags_file:write("\n")
flags_file:write("--cpu=x64\n")
flags_file:write("#--enable_haswell_instructions=false\n")
flags_file:write("\n")
flags_file:write("--debug\n")
flags_file:write("#--protect_zero=false\n")
flags_file:write("\n")
flags_file:write("#--mute\n")
flags_file:write("\n")
flags_file:write("--fast_stdout\n")
flags_file:write("#--flush_stdout=false\n")
flags_file:write("\n")
flags_file:write("#--vsync=false\n")
flags_file:write("#--gl_debug\n")
flags_file:write("#--gl_debug_output\n")
flags_file:write("#--gl_debug_output_synchronous\n")
flags_file:write("#--trace_gpu_prefix=scratch/gpu/gpu_trace_\n")
flags_file:write("#--trace_gpu_stream\n")
flags_file:write("#--disable_framebuffer_readback\n")
flags_file:write("\n")
flags_file:close()
end
solution("xenia")
uuid("931ef4b0-6170-4f7a-aaf2-0fece7632747")
startproject("xenia-app")
architecture("x86_64")
if os.is("linux") then
platforms({"Linux"})
elseif os.is("windows") then
platforms({"Windows"})
end
configurations({"Checked", "Debug", "Release"})
-- Include third party files first so they don't have to deal with gflags.
include("third_party/capstone.lua")
include("third_party/elemental-forms")
include("third_party/glew.lua")
include("third_party/imgui.lua")
include("third_party/libav.lua")
include("third_party/xxhash.lua")
include("build_tools/third_party/gflags.lua")
include("src/xenia")
include("src/xenia/app")
include("src/xenia/apu")
include("src/xenia/apu/nop")
include("src/xenia/base")
include("src/xenia/cpu")
include("src/xenia/cpu/backend/x64")
include("src/xenia/debug")
include("src/xenia/debug/ui")
include("src/xenia/gpu")
include("src/xenia/gpu/gl4")
include("src/xenia/hid")
include("src/xenia/hid/nop")
include("src/xenia/kernel")
include("src/xenia/ui")
include("src/xenia/ui/gl")
include("src/xenia/vfs")
if os.is("windows") then
include("src/xenia/apu/xaudio2")
include("src/xenia/hid/winkey")
include("src/xenia/hid/xinput")
end
|
Fixing checked build.
|
Fixing checked build.
|
Lua
|
bsd-3-clause
|
KitoHo/xenia,sephiroth99/xenia,sabretooth/xenia,galek/xenia,KitoHo/xenia,no1dead/xenia,no1dead/xenia,TRex22/xenia,ObsidianGuardian/xenia,maxton/xenia,ObsidianGuardian/xenia,TRex22/xenia,maxton/xenia,sephiroth99/xenia,KitoHo/xenia,galek/xenia,sephiroth99/xenia,TRex22/xenia,maxton/xenia,sabretooth/xenia,sabretooth/xenia,no1dead/xenia,KitoHo/xenia,ObsidianGuardian/xenia,no1dead/xenia,galek/xenia,galek/xenia
|
af5a25b187977199ba3326666f0c1f6508b7c5fd
|
config/nvim/lua/user/completion.lua
|
config/nvim/lua/user/completion.lua
|
local cmp_status_ok, cmp = pcall(require, "cmp")
if not cmp_status_ok then
return
end
local snip_status_ok, luasnip = pcall(require, "luasnip")
if not snip_status_ok then
return
end
require("luasnip/loaders/from_vscode").lazy_load()
local check_backspace = function()
local col = vim.fn.col "." - 1
return col == 0 or vim.fn.getline("."):sub(col, col):match "%s"
end
-- פּ ﯟ some other good icons
local kind_icons = {
Text = "",
Method = "m",
Function = "",
Constructor = "",
Field = "",
Variable = "",
Class = "",
Interface = "",
Module = "",
Property = "",
Unit = "",
Value = "",
Enum = "",
Keyword = "",
Snippet = "",
Color = "",
File = "",
Reference = "",
Folder = "",
EnumMember = "",
Constant = "",
Struct = "",
Event = "",
Operator = "",
TypeParameter = "",
}
-- find more here: https://www.nerdfonts.com/cheat-sheet
cmp.setup {
snippet = {
expand = function(args)
luasnip.lsp_expand(args.body) -- For `luasnip` users.
end,
},
mapping = {
["<C-b>"] = cmp.mapping(cmp.mapping.scroll_docs(-1), { "i", "c" }),
["<C-f>"] = cmp.mapping(cmp.mapping.scroll_docs(1), { "i", "c" }),
["<C-Space>"] = cmp.mapping(cmp.mapping.complete(), { "i", "c" }),
["<C-y>"] = cmp.config.disable, -- Specify `cmp.config.disable` if you want to remove the default `<C-y>` mapping.
["<C-e>"] = cmp.mapping {
i = cmp.mapping.abort(),
c = cmp.mapping.close(),
},
-- Accept currently selected item. If none selected, `select` first item.
-- Set `select` to `false` to only confirm explicitly selected items.
["<CR>"] = cmp.mapping.confirm { select = true },
["<Tab>"] = cmp.mapping(function(fallback)
if cmp.visible() then
cmp.select_next_item()
elseif luasnip.expandable() then
luasnip.expand()
elseif luasnip.expand_or_jumpable() then
luasnip.expand_or_jump()
elseif check_backspace() then
fallback()
else
fallback()
end
end, {
"i",
"s",
}),
["<S-Tab>"] = cmp.mapping(function(fallback)
if cmp.visible() then
cmp.select_prev_item()
elseif luasnip.jumpable(-1) then
luasnip.jump(-1)
else
fallback()
end
end, {
"i",
"s",
}),
},
formatting = {
fields = { "kind", "abbr", "menu" },
format = function(entry, vim_item)
-- Kind icons
vim_item.kind = string.format("%s", kind_icons[vim_item.kind])
-- vim_item.kind = string.format('%s %s', kind_icons[vim_item.kind], vim_item.kind) -- This concatonates the icons with the name of the item kind
vim_item.menu = ({
nvim_lsp = "[LSP]",
nvim_lua = "[Lua]",
luasnip = "[Snippet]",
buffer = "[Buffer]",
path = "[Path]",
crates = "[Crates]",
treesitter = "[Treesitter]",
zsh = "[ZSH]",
})[entry.source.name]
return vim_item
end,
},
sources = {
{ name = "nvim_lsp" },
{ name = "crates" },
{ name = "zsh" },
{ name = "treesitter" },
{ name = "nvim_lua" },
{ name = "luasnip" },
{ name = "buffer" },
{ name = "path" },
},
confirm_opts = {
behavior = cmp.ConfirmBehavior.Replace,
select = false,
},
documentation = {
border = { "╭", "─", "╮", "│", "╯", "─", "╰", "│" },
},
experimental = {
ghost_text = false,
native_menu = false,
},
}
|
local cmp_status_ok, cmp = pcall(require, "cmp")
if not cmp_status_ok then
return
end
local snip_status_ok, luasnip = pcall(require, "luasnip")
if not snip_status_ok then
return
end
require("luasnip/loaders/from_vscode").lazy_load()
local check_backspace = function()
local col = vim.fn.col "." - 1
return col == 0 or vim.fn.getline("."):sub(col, col):match "%s"
end
-- פּ ﯟ some other good icons
local kind_icons = {
Text = "",
Method = "m",
Function = "",
Constructor = "",
Field = "",
Variable = "",
Class = "",
Interface = "",
Module = "",
Property = "",
Unit = "",
Value = "",
Enum = "",
Keyword = "",
Snippet = "",
Color = "",
File = "",
Reference = "",
Folder = "",
EnumMember = "",
Constant = "",
Struct = "",
Event = "",
Operator = "",
TypeParameter = "",
}
-- find more here: https://www.nerdfonts.com/cheat-sheet
cmp.setup {
snippet = {
expand = function(args)
luasnip.lsp_expand(args.body) -- For `luasnip` users.
end,
},
mapping = {
["<C-b>"] = cmp.mapping(cmp.mapping.scroll_docs(-1), { "i", "c" }),
["<C-f>"] = cmp.mapping(cmp.mapping.scroll_docs(1), { "i", "c" }),
["<C-Space>"] = cmp.mapping(cmp.mapping.complete(), { "i", "c" }),
["<C-y>"] = cmp.config.disable, -- Specify `cmp.config.disable` if you want to remove the default `<C-y>` mapping.
["<C-e>"] = cmp.mapping {
i = cmp.mapping.abort(),
c = cmp.mapping.close(),
},
-- Accept currently selected item. If none selected, `select` first item.
-- Set `select` to `false` to only confirm explicitly selected items.
["<CR>"] = cmp.mapping.confirm { select = true },
["<Tab>"] = cmp.mapping(function(fallback)
if cmp.visible() then
cmp.select_next_item()
elseif luasnip.expandable() then
luasnip.expand()
elseif luasnip.expand_or_jumpable() then
luasnip.expand_or_jump()
elseif check_backspace() then
fallback()
else
fallback()
end
end, {
"i",
"s",
}),
["<S-Tab>"] = cmp.mapping(function(fallback)
if cmp.visible() then
cmp.select_prev_item()
elseif luasnip.jumpable(-1) then
luasnip.jump(-1)
else
fallback()
end
end, {
"i",
"s",
}),
},
formatting = {
fields = { "kind", "abbr", "menu" },
format = function(entry, vim_item)
-- Kind icons
vim_item.kind = string.format("%s", kind_icons[vim_item.kind])
-- vim_item.kind = string.format('%s %s', kind_icons[vim_item.kind], vim_item.kind) -- This concatonates the icons with the name of the item kind
vim_item.menu = ({
nvim_lsp = "[LSP]",
nvim_lua = "[Lua]",
luasnip = "[Snippet]",
buffer = "[Buffer]",
path = "[Path]",
crates = "[Crates]",
treesitter = "[Treesitter]",
zsh = "[ZSH]",
})[entry.source.name]
return vim_item
end,
},
sources = {
{ name = "nvim_lsp" },
{ name = "crates" },
{ name = "zsh" },
{ name = "treesitter" },
{ name = "nvim_lua" },
{ name = "luasnip" },
{ name = "buffer" },
{ name = "path" },
},
confirm_opts = {
behavior = cmp.ConfirmBehavior.Replace,
select = false,
},
window = {
documentation = "native"
},
experimental = {
ghost_text = false,
native_menu = false,
},
}
|
Updated packer. Bufferline: Remove/Install. nvim-cmp: Fixed obsolete param
|
Updated packer. Bufferline: Remove/Install. nvim-cmp: Fixed obsolete param
|
Lua
|
mit
|
hust921/dotfiles,hust921/dotfiles
|
2ed91da8910506535151dd083931035386bcaed2
|
player.lua
|
player.lua
|
local Player = class('Player', Base)
Player.static.SPEED = 200
local getUVs = require('getUVs')
local radius = 20
local function physicsCharacter(char)
char.body = love.physics.newBody(game.world, char.x, char.y, 'dynamic')
local shape = love.physics.newCircleShape(radius)
char.fixture = love.physics.newFixture(char.body, shape, 1)
function char:setPositionFromBody()
char.x = char.body:getX()
char.y = char.body:getY()
end
function char:setPosition(x, y)
char.body:setPosition(x, y)
char:setPositionFromBody()
end
function char:applyForce(fx, fy)
char.body:applyForce(fx, fy)
char:setPositionFromBody()
end
function char:setLinearVelocity(dx, dy)
char.body:setLinearVelocity(dx, dy)
char:setPositionFromBody()
end
return char
end
function Player:initialize()
Base.initialize(self)
self.joystick = love.joystick.getJoysticks()[1]
do
local sprite_name = 'robot1_gun'
local sprites = require('images.sprites')
local ua, va, ub, vb = getUVs(sprites, sprite_name)
self.mesh = g.newMesh({
{-radius, -radius, ua, va},
{-radius, radius, ua, vb},
{radius, radius, ub, vb},
{radius, -radius, ub, va},
}, 'fan', 'static')
self.mesh:setTexture(sprites.texture)
end
local ax, ay = game.map:gridToPixel(1, 1)
local dx, dy = game.map:gridToPixel(game.map.width, game.map.height)
self.attackers = {
physicsCharacter({
x = ax,
y = ay,
rotation = 0
})
}
self.defenders = {
physicsCharacter({
x = dx,
y = dy,
rotation = 0
})
}
end
function Player:update(dt)
for _,attacker in ipairs(self.attackers) do
local dx = self.joystick:getGamepadAxis("leftx")
local dy = self.joystick:getGamepadAxis("lefty")
local phi = math.atan2(dy, dx)
local dx, dy = dx * Player.SPEED, dy * Player.SPEED
attacker.rotation = phi
attacker:setLinearVelocity(dx, dy)
for _,defender in ipairs(self.defenders) do
defender.rotation = phi + math.pi
defender:setLinearVelocity(-dx, -dy)
end
end
end
function Player:draw()
for i,attacker in ipairs(self.attackers) do
g.draw(self.mesh, attacker.x, attacker.y, attacker.rotation)
end
for _,defender in ipairs(self.defenders) do
g.draw(self.mesh, defender.x, defender.y, defender.rotation)
end
end
return Player
|
local Player = class('Player', Base)
Player.static.SPEED = 200
local getUVs = require('getUVs')
local radius = 20
local function physicsCharacter(char)
char.body = love.physics.newBody(game.world, char.x, char.y, 'dynamic')
local shape = love.physics.newCircleShape(radius)
char.fixture = love.physics.newFixture(char.body, shape, 1)
function char:setPositionFromBody()
char.x = char.body:getX()
char.y = char.body:getY()
end
function char:setPosition(x, y)
char.body:setPosition(x, y)
char:setPositionFromBody()
end
function char:applyForce(fx, fy)
char.body:applyForce(fx, fy)
char:setPositionFromBody()
end
function char:setLinearVelocity(dx, dy)
char.body:setLinearVelocity(dx, dy)
char:setPositionFromBody()
end
return char
end
function Player:initialize()
Base.initialize(self)
self.joystick = love.joystick.getJoysticks()[1]
do
local sprite_name = 'robot1_gun'
local sprites = require('images.sprites')
local ua, va, ub, vb = getUVs(sprites, sprite_name)
self.mesh = g.newMesh({
{-radius, -radius, ua, va},
{-radius, radius, ua, vb},
{radius, radius, ub, vb},
{radius, -radius, ub, va},
}, 'fan', 'static')
self.mesh:setTexture(sprites.texture)
end
local ax, ay = game.map:gridToPixel(1, 1)
local dx, dy = game.map:gridToPixel(game.map.width, game.map.height)
self.attackers = {
physicsCharacter({
x = ax,
y = ay,
rotation = 0
})
}
self.defenders = {
physicsCharacter({
x = dx,
y = dy,
rotation = 0
})
}
end
function Player:update(dt)
for _,attacker in ipairs(self.attackers) do
local dx = self.joystick:getGamepadAxis("leftx")
local dy = self.joystick:getGamepadAxis("lefty")
if math.abs(dx) < 0.2 then dx = 0 end
if math.abs(dy) < 0.2 then dy = 0 end
local phi = math.atan2(dy, dx)
local dx, dy = dx * Player.SPEED, dy * Player.SPEED
if dx ~= 0 or dy ~= 0 then attacker.rotation = phi end
attacker:setLinearVelocity(dx, dy)
for _,defender in ipairs(self.defenders) do
if dx ~= 0 or dy ~= 0 then defender.rotation = phi + math.pi end
defender:setLinearVelocity(-dx, -dy)
end
end
end
function Player:draw()
for i,attacker in ipairs(self.attackers) do
g.draw(self.mesh, attacker.x, attacker.y, attacker.rotation)
end
for _,defender in ipairs(self.defenders) do
g.draw(self.mesh, defender.x, defender.y, defender.rotation)
end
end
return Player
|
fix player drift from non-zeroing controller
|
fix player drift from non-zeroing controller
|
Lua
|
mit
|
TannerRogalsky/GGJ2017
|
df09dda937e66ea788f78f1779e0de3aa5d76b2f
|
luasrc/mch/console.lua
|
luasrc/mch/console.lua
|
local utils = require("mch.util")
module('mch.console', package.seeall)
function getMembers(t, o)
local tp
for i, j in pairs(o) do
if type(i) == 'string' then
if type(j) == 'function' then
tp = true
else
tp = false
end
t[i] = tp
end
end
return t
end
function table2array(t, funcOnly)
local ret = {}
for k, v in pairs(t) do
if v then
table.insert(ret, k .. '(')
elseif funcOnly then
else
table.insert(ret, k)
end
end
return ret
end
function interact(host, port)
local sock = ngx.socket.tcp()
local ok, err
ok, err = sock:connect(host, port)
if not ok then
logger:error('Error while connecting back to %s:%d, %s', host, port, err)
return
end
logger:info('console socket connected.')
sock:settimeout(86400000)
while true do
local req = utils.read_jsonresponse(sock)
local res = {}
logger:info('console socket got request: %s', req)
if not req then break end
local res = {}
if req.cmd == 'code' then
local ok, chunk, ret, err
-- must come first
chunk, err = loadstring('return ' .. req.data, 'console')
if not chunk then
chunk, err = loadstring(req.data, 'console')
end
if err then
res.error = err
else
ok, ret = pcall(chunk)
if not ok then
res.error = ret
else
if ret ~= nil then
res.result = logger.tostring(ret)
end
end
end
elseif req.cmd == 'dir' then
local t = {}
local o
local chunk, ok, ret
chunk, _ = loadstring('return ' .. req.data, 'input')
if chunk then
ok, ret = pcall(chunk)
if ok then
o = ret
end
end
if o then
getMembers(t, o)
local meta = getmetatable(o) or {}
if type(meta.__index) == 'table' then
getMembers(t, meta.__index)
end
end
res.result = table2array(t, req.funcOnly)
else
res.error = 'unknown cmd: ' .. logger.tostring(req.cmd)
end
logger:info('reply: %s', res)
utils.write_jsonresponse(sock, res)
end
logger:info('console session ends.')
end
function start(req, res)
res.headers['Content-Type'] = 'text/plain'
local host = req.uri_args.host or ngx.var.remote_addr
local port = req.uri_args.port
res:defer(function()
interact(host, port)
end)
res:writeln("ok.")
end
|
local utils = require("mch.util")
module('mch.console', package.seeall)
function getMembers(t, o)
local tp
for i, j in pairs(o) do
if type(i) == 'string' then
if type(j) == 'function' then
tp = true
else
tp = false
end
t[i] = tp
end
end
return t
end
function table2array(t, funcOnly)
local ret = {}
for k, v in pairs(t) do
if v then
table.insert(ret, k .. '(')
elseif funcOnly then
else
table.insert(ret, k)
end
end
return ret
end
function interact(host, port)
local sock = ngx.socket.tcp()
local ok, err
ok, err = sock:connect(host, port)
if not ok then
logger:error('Error while connecting back to %s:%d, %s', host, port, err)
return
end
logger:debug('console socket connected.')
sock:settimeout(86400000)
while true do
local req = utils.read_jsonresponse(sock)
local res = {}
logger:debug('console socket got request: %s', req)
if not req then break end
local res = {}
if req.cmd == 'code' then
local ok, chunk, ret, err
-- must come first
chunk, err = loadstring('return ' .. req.data, 'console')
if not chunk then
chunk, err = loadstring(req.data, 'console')
end
if err then
res.error = err
else
ok, ret = pcall(chunk)
if not ok then
res.error = ret
else
if ret ~= nil then
res.result = logger.tostring(ret)
end
end
end
elseif req.cmd == 'dir' then
local t = {}
local o
local chunk, ok, ret
chunk, _ = loadstring('return ' .. req.data, 'input')
if chunk then
ok, ret = pcall(chunk)
if ok then
o = ret
end
end
if type(o) == 'table' then
getMembers(t, o)
local meta = getmetatable(o) or {}
if type(meta.__index) == 'table' then
getMembers(t, meta.__index)
end
res.result = table2array(t, req.funcOnly)
end
else
res.error = 'unknown cmd: ' .. logger.tostring(req.cmd)
end
logger:debug('reply: %s', res)
utils.write_jsonresponse(sock, res)
end
logger:debug('console session ends.')
end
function start(req, res)
res.headers['Content-Type'] = 'text/plain'
local host = req.uri_args.host or ngx.var.remote_addr
local port = req.uri_args.port
res:defer(function()
interact(host, port)
end)
res:writeln("ok.")
end
|
mch.console: fix a bug; use debug instead of info logging
|
mch.console: fix a bug; use debug instead of info logging
|
Lua
|
apache-2.0
|
lilien1010/moochine,lilien1010/moochine,appwilldev/moochine,lilien1010/moochine,appwilldev/moochine
|
2e59e6db2095ab31b867745480a2f1eb124de037
|
src/lib/yang/util.lua
|
src/lib/yang/util.lua
|
-- Use of this source code is governed by the Apache 2.0 license; see COPYING.
module(..., package.seeall)
local lib = require("core.lib")
local ffi = require("ffi")
local ipv4 = require("lib.protocol.ipv4")
ffi.cdef([[
unsigned long long strtoull (const char *nptr, const char **endptr, int base);
]])
function tointeger(str, what, min, max)
if not what then what = 'integer' end
local str = assert(str, 'missing value for '..what)
local start = 1
local is_negative
local base = 10
if str:match('^-') then start, is_negative = 2, true
elseif str:match('^+') then start = 2 end
if str:match('^0x', start) then base, start = 16, start + 2
elseif str:match('^0', start) then base = 8 end
str = str:lower()
if start > str:len() then
error('invalid numeric value for '..what..': '..str)
end
-- FIXME: check that res did not overflow the 64-bit number
local res = ffi.C.strtoull(str:sub(start), nil, base)
if is_negative then
res = ffi.new('int64_t[1]', -1*res)[0]
if res > 0 then
error('invalid numeric value for '..what..': '..str)
end
if min and not (min <= 0 and min <= res) then
error('invalid numeric value for '..what..': '..str)
end
else
-- Only compare min and res if both are positive, otherwise if min
-- is a negative int64_t then the comparison will treat it as a
-- large uint64_t.
if min and not (min <= 0 or min <= res) then
error('invalid numeric value for '..what..': '..str)
end
end
if max and res > max then
error('invalid numeric value for '..what..': '..str)
end
-- Only return Lua numbers for values within int32 + uint32 range.
-- The 0 <= res check is needed because res might be a uint64, in
-- which case comparing to a negative Lua number will cast that Lua
-- number to a uint64 :-((
if (0 <= res or -0x8000000 <= res) and res <= 0xffffffff then
return tonumber(res)
end
return res
end
function ffi_array(ptr, elt_t, count)
local mt = {}
local size = count or ffi.sizeof(ptr)/ffi.sizeof(elt_t)
function mt:__len() return size end
function mt:__index(idx)
assert(1 <= idx and idx <= size)
return ptr[idx-1]
end
function mt:__newindex(idx, val)
assert(1 <= idx and idx <= size)
ptr[idx-1] = val
end
function mt:__ipairs()
local idx = -1
return function()
idx = idx + 1
if idx >= size then return end
return idx+1, ptr[idx]
end
end
return ffi.metatype(ffi.typeof('struct { $* ptr; }', elt_t), mt)(ptr)
end
-- The yang modules represent IPv4 addresses as host-endian uint32
-- values in Lua. See https://github.com/snabbco/snabb/issues/1063.
function ipv4_pton(str)
return lib.ntohl(ffi.cast('uint32_t*', assert(ipv4:pton(str)))[0])
end
function ipv4_ntop(addr)
return ipv4:ntop(ffi.new('uint32_t[1]', lib.htonl(addr)))
end
ffi.cdef [[
void* malloc (size_t);
void free (void*);
]]
function memoize(f, max_occupancy)
local cache = {}
local occupancy = 0
local argc = 0
max_occupancy = max_occupancy or 10
return function(...)
local args = {...}
if #args == argc then
local walk = cache
for i=1,#args do
if walk == nil then break end
walk = walk[args[i]]
end
if walk ~= nil then return unpack(walk) end
else
cache, occupancy, argc = {}, 0, #args
end
local ret = {f(...)}
if occupancy >= max_occupancy then
cache = {}
occupancy = 0
end
local walk = cache
for i=1,#args-1 do
if not walk[args[i]] then walk[args[i]] = {} end
walk = walk[args[i]]
end
walk[args[#args]] = ret
occupancy = occupancy + 1
return unpack(ret)
end
end
function timezone ()
local now = os.time()
local utctime = os.date("!*t", now)
local localtime = os.date("*t", now)
-- Synchronize daylight-saving flags.
utctime.isdst = localtime.isdst
local timediff = os.difftime(os.time(localtime), os.time(utctime))
if timediff ~= 0 then
local sign = timediff > 0 and "+" or "-"
local time = os.date("!*t", math.abs(timediff))
return sign..("%.2d:%.2d"):format(time.hour, time.min)
end
end
function format_date_as_iso_8601 (time)
local ret = {}
time = time or os.time()
local utctime = os.date("!*t", time)
table.insert(ret, ("%.4d-%.2d-%.2dT%.2d:%.2d:%.2dZ"):format(
utctime.year, utctime.month, utctime.day, utctime.hour, utctime.min, utctime.sec))
table.insert(ret, timezone() or "")
return table.concat(ret, "")
end
-- XXX: ISO 8601 can be more complex. We asumme date is the format returned
-- by 'format_date_as_iso8601'.
function parse_date_as_iso_8601 (date)
assert(type(date) == 'string')
local gmtdate = "(%d%d%d%d)-(%d%d)-(%d%d)T(%d%d):(%d%d):(%d%d)Z"
local year, month, day, hour, min, sec = assert(date:match(gmtdate))
local tz_sign, tz_hour, tz_min = date:match("Z([+-]?)(%d%d):(%d%d)")
return {year=year, month=month, day=day, hour=hour, min=min, sec=sec, tz_sign=tz_sign, tz_hour=tz_hour, tz_min=tz_min}
end
function selftest()
print('selftest: lib.yang.util')
assert(tointeger('0') == 0)
assert(tointeger('-0') == 0)
assert(tointeger('10') == 10)
assert(tostring(tointeger('10')) == '10')
assert(tointeger('-10') == -10)
assert(tointeger('010') == 8)
assert(tointeger('-010') == -8)
assert(tointeger('0xffffffff') == 0xffffffff)
assert(tointeger('0xffffffffffffffff') == 0xffffffffffffffffULL)
assert(tointeger('0x7fffffffffffffff') == 0x7fffffffffffffffULL)
assert(tointeger('0xffffffffffffffff') == 0xffffffffffffffffULL)
assert(tointeger('-0x7fffffffffffffff') == -0x7fffffffffffffffLL)
assert(tointeger('-0x8000000000000000') == -0x8000000000000000LL)
assert(ipv4_pton('255.0.0.1') == 255 * 2^24 + 1)
assert(ipv4_ntop(ipv4_pton('255.0.0.1')) == '255.0.0.1')
print('selftest: ok')
end
|
-- Use of this source code is governed by the Apache 2.0 license; see COPYING.
module(..., package.seeall)
local lib = require("core.lib")
local ffi = require("ffi")
local ipv4 = require("lib.protocol.ipv4")
ffi.cdef([[
unsigned long long strtoull (const char *nptr, const char **endptr, int base);
]])
function tointeger(str, what, min, max)
if not what then what = 'integer' end
local str = assert(str, 'missing value for '..what)
local start = 1
local is_negative
local base = 10
if str:match('^-') then start, is_negative = 2, true
elseif str:match('^+') then start = 2 end
if str:match('^0x', start) then base, start = 16, start + 2
elseif str:match('^0', start) then base = 8 end
str = str:lower()
if start > str:len() then
error('invalid numeric value for '..what..': '..str)
end
-- FIXME: check that res did not overflow the 64-bit number
local res = ffi.C.strtoull(str:sub(start), nil, base)
if is_negative then
res = ffi.new('int64_t[1]', -1*res)[0]
if res > 0 then
error('invalid numeric value for '..what..': '..str)
end
if min and not (min <= 0 and min <= res) then
error('invalid numeric value for '..what..': '..str)
end
else
-- Only compare min and res if both are positive, otherwise if min
-- is a negative int64_t then the comparison will treat it as a
-- large uint64_t.
if min and not (min <= 0 or min <= res) then
error('invalid numeric value for '..what..': '..str)
end
end
if max and res > max then
error('invalid numeric value for '..what..': '..str)
end
-- Only return Lua numbers for values within int32 + uint32 range.
-- The 0 <= res check is needed because res might be a uint64, in
-- which case comparing to a negative Lua number will cast that Lua
-- number to a uint64 :-((
if (0 <= res or -0x8000000 <= res) and res <= 0xffffffff then
return tonumber(res)
end
return res
end
function ffi_array(ptr, elt_t, count)
local mt = {}
local size = count or ffi.sizeof(ptr)/ffi.sizeof(elt_t)
function mt:__len() return size end
function mt:__index(idx)
assert(1 <= idx and idx <= size)
return ptr[idx-1]
end
function mt:__newindex(idx, val)
assert(1 <= idx and idx <= size)
ptr[idx-1] = val
end
function mt:__ipairs()
local idx = -1
return function()
idx = idx + 1
if idx >= size then return end
return idx+1, ptr[idx]
end
end
return ffi.metatype(ffi.typeof('struct { $* ptr; }', elt_t), mt)(ptr)
end
-- The yang modules represent IPv4 addresses as host-endian uint32
-- values in Lua. See https://github.com/snabbco/snabb/issues/1063.
function ipv4_pton(str)
return lib.ntohl(ffi.cast('uint32_t*', assert(ipv4:pton(str)))[0])
end
function ipv4_ntop(addr)
return ipv4:ntop(ffi.new('uint32_t[1]', lib.htonl(addr)))
end
ffi.cdef [[
void* malloc (size_t);
void free (void*);
]]
function memoize(f, max_occupancy)
local cache = {}
local occupancy = 0
local argc = 0
max_occupancy = max_occupancy or 10
return function(...)
local args = {...}
if #args == argc then
local walk = cache
for i=1,#args do
if walk == nil then break end
walk = walk[args[i]]
end
if walk ~= nil then return unpack(walk) end
else
cache, occupancy, argc = {}, 0, #args
end
local ret = {f(...)}
if occupancy >= max_occupancy then
cache = {}
occupancy = 0
end
local walk = cache
for i=1,#args-1 do
if not walk[args[i]] then walk[args[i]] = {} end
walk = walk[args[i]]
end
walk[args[#args]] = ret
occupancy = occupancy + 1
return unpack(ret)
end
end
function timezone ()
local now = os.time()
local utctime = os.date("!*t", now)
local localtime = os.date("*t", now)
-- Synchronize daylight-saving flags.
utctime.isdst = localtime.isdst
local timediff = os.difftime(os.time(localtime), os.time(utctime))
if timediff ~= 0 then
local sign = timediff > 0 and "+" or "-"
local time = os.date("!*t", math.abs(timediff))
return sign..("%.2d:%.2d"):format(time.hour, time.min)
end
end
function format_date_as_iso_8601 (time)
local ret = {}
time = time or os.time()
local utctime = os.date("!*t", time)
table.insert(ret, ("%.4d-%.2d-%.2dT%.2d:%.2d:%.2dZ"):format(
utctime.year, utctime.month, utctime.day, utctime.hour, utctime.min, utctime.sec))
table.insert(ret, timezone() or "")
return table.concat(ret, "")
end
-- XXX: ISO 8601 can be more complex. We asumme date is the format returned
-- by 'format_date_as_iso8601'.
function parse_date_as_iso_8601 (date)
assert(type(date) == 'string')
local gmtdate = "(%d%d%d%d)-(%d%d)-(%d%d)T(%d%d):(%d%d):(%d%d)"
local year, month, day, hour, min, sec = assert(date:match(gmtdate))
local ret = {year=year, month=month, day=day, hour=hour, min=min, sec=sec}
if date:match("Z$") then
return ret
else
local tz_sign, tz_hour, tz_min = date:match("([+-]?)(%d%d):(%d%d)$")
ret.tz_sign = tz_sign
ret.tz_hour = tz_hour
ret.tz_min = tz_min
return ret
end
end
function selftest()
print('selftest: lib.yang.util')
assert(tointeger('0') == 0)
assert(tointeger('-0') == 0)
assert(tointeger('10') == 10)
assert(tostring(tointeger('10')) == '10')
assert(tointeger('-10') == -10)
assert(tointeger('010') == 8)
assert(tointeger('-010') == -8)
assert(tointeger('0xffffffff') == 0xffffffff)
assert(tointeger('0xffffffffffffffff') == 0xffffffffffffffffULL)
assert(tointeger('0x7fffffffffffffff') == 0x7fffffffffffffffULL)
assert(tointeger('0xffffffffffffffff') == 0xffffffffffffffffULL)
assert(tointeger('-0x7fffffffffffffff') == -0x7fffffffffffffffLL)
assert(tointeger('-0x8000000000000000') == -0x8000000000000000LL)
assert(ipv4_pton('255.0.0.1') == 255 * 2^24 + 1)
assert(ipv4_ntop(ipv4_pton('255.0.0.1')) == '255.0.0.1')
print('selftest: ok')
end
|
Fix parsing of ISO8601 date format
|
Fix parsing of ISO8601 date format
According to ISO8601 format, a Z is equivalent to zero timezone offset
(+00:00). If the timezone difference is higher or lower than zero,
there's no Z and timediff is encoded as [+-]XX:XX.
|
Lua
|
apache-2.0
|
SnabbCo/snabbswitch,Igalia/snabb,Igalia/snabbswitch,SnabbCo/snabbswitch,alexandergall/snabbswitch,snabbco/snabb,snabbco/snabb,Igalia/snabbswitch,alexandergall/snabbswitch,snabbco/snabb,alexandergall/snabbswitch,Igalia/snabbswitch,snabbco/snabb,Igalia/snabbswitch,eugeneia/snabb,eugeneia/snabb,SnabbCo/snabbswitch,alexandergall/snabbswitch,eugeneia/snabb,Igalia/snabb,alexandergall/snabbswitch,Igalia/snabb,eugeneia/snabb,Igalia/snabbswitch,snabbco/snabb,snabbco/snabb,eugeneia/snabb,eugeneia/snabb,alexandergall/snabbswitch,Igalia/snabb,alexandergall/snabbswitch,Igalia/snabb,eugeneia/snabb,eugeneia/snabb,Igalia/snabb,snabbco/snabb,alexandergall/snabbswitch,Igalia/snabb,snabbco/snabb,SnabbCo/snabbswitch,Igalia/snabb
|
5d131bdd6cea7abdad719f0826d15f31545f8ceb
|
hammerspoon/modules/homebrew.lua
|
hammerspoon/modules/homebrew.lua
|
-- Homebrew menubar
local Homebrew = {
menubar = hs.menubar.new(),
items = {},
disabled = false,
notified = false,
}
function Homebrew:loadOutdated()
self.items = {}
local pipe = io.popen('/usr/local/bin/brew outdated -1 --quiet', 'r')
for item in pipe:lines() do
table.insert(self.items, item)
end
pipe:close()
if next(self.items) == nil then
self.disabled = true
self.notified = false
self.menubar:removeFromMenuBar()
self.menubar:setTooltip("Homebrew")
else
local msg = string.format("%d updated formula%s available", #self.items, plural(self.items))
self.disabled = false
self.menubar:returnToMenuBar()
self.menubar:setTooltip(msg)
if not self.notified then
hs.notify.show('Homebrew', msg, table.concat(self.items, ', '))
self.notified = true
end
end
end
function Homebrew:getMenu()
local menu = {
{title=string.format("Update %s formula%s", #self.items, plural(self.items)), fn=function() self.disabled = true; hs.task.new('/usr/local/bin/brew', function() Homebrew:loadOutdated() end, {'upgrade', table.concat(self.items, ' ')}):start() end, disabled=self.disabled},
{title='-'},
}
for _, item in ipairs(self.items) do
table.insert(menu, {title=item, fn=function() self.disabled = true; hs.task.new('/usr/local/bin/brew', function() Homebrew:loadOutdated() end, {'upgrade', item}):start() end, disabled=self.disabled})
end
return menu
end
function Homebrew:update()
print('Updating Homebrew')
hs.task.new('/usr/local/bin/brew', function() Homebrew:loadOutdated() end, {'update'}):start()
end
function plural(a)
local suffix = ''
if #a > 1 then
suffix = 's'
end
return suffix
end
if Homebrew then
Homebrew.menubar:setTooltip('Homebrew')
Homebrew.menubar:setIcon('./assets/cask.pdf')
Homebrew.menubar:setMenu(function() return Homebrew:getMenu() end)
Homebrew.menubar:removeFromMenuBar()
Homebrew:update(); hs.timer.doEvery(3600, function() Homebrew:update() end)
end
|
-- Homebrew menubar
local Homebrew = {
menubar = hs.menubar.new(),
items = {},
disabled = false,
notified = false,
}
function Homebrew:loadOutdated()
self.items = {}
local pipe = io.popen('/usr/local/bin/brew outdated -1 --quiet', 'r')
for item in pipe:lines() do
table.insert(self.items, item)
end
pipe:close()
if next(self.items) == nil then
self.disabled = true
self.notified = false
self.menubar:removeFromMenuBar()
self.menubar:setTooltip("Homebrew")
else
local msg = string.format("%d updated formula%s available", #self.items, plural(self.items))
self.disabled = false
self.menubar:returnToMenuBar()
self.menubar:setTooltip(msg)
if not self.notified then
hs.notify.show('Homebrew', msg, table.concat(self.items, ', '))
self.notified = true
end
end
end
function Homebrew:getMenu()
local params = table.merge({'upgrade'}, self.items)
local menu = {
{title=string.format("Update %s formula%s", #self.items, plural(self.items)), fn=function() self.disabled = true; hs.task.new('/usr/local/bin/brew', function() Homebrew:loadOutdated() end, params):start() end, disabled=self.disabled},
{title='-'},
}
for _, item in ipairs(self.items) do
table.insert(menu, {title=item, fn=function() self.disabled = true; hs.task.new('/usr/local/bin/brew', function() Homebrew:loadOutdated() end, {'upgrade', item}):start() end, disabled=self.disabled})
end
return menu
end
function Homebrew:update()
print('Updating Homebrew')
hs.task.new('/usr/local/bin/brew', function() Homebrew:loadOutdated() end, {'update'}):start()
end
function table.merge(t1, t2)
for k,v in ipairs(t2) do
table.insert(t1, v)
end
return t1
end
function plural(a)
local suffix = ''
if #a > 1 then
suffix = 's'
end
return suffix
end
if Homebrew then
Homebrew.menubar:setTooltip('Homebrew')
Homebrew.menubar:setIcon('./assets/cask.pdf')
Homebrew.menubar:setMenu(function() return Homebrew:getMenu() end)
Homebrew.menubar:removeFromMenuBar()
Homebrew:update(); hs.timer.doEvery(3600, function() Homebrew:update() end)
end
|
hammerspoon: Fix homebrew menu
|
hammerspoon: Fix homebrew menu
|
Lua
|
mit
|
sebastianmarkow/dotfiles
|
2c3544204c73ae9d85c508207e67f3228bc2efe7
|
Normalize.lua
|
Normalize.lua
|
local Normalize, parent = torch.class('nn.Normalize', 'nn.Module')
function Normalize:__init(p,eps)
parent.__init(self)
assert(p,'p-norm not provided')
assert(p > 0, p..'-norm not supported')
self.p = p
self.eps = eps or 1e-10
end
function Normalize:updateOutput(input)
assert(input:dim() <= 2, 'only 1d layer supported')
local is_batch = true
if input:dim() == 1 then
input = input:view(1,-1)
is_batch = false
end
self.output:resizeAs(input)
self.norm = self.norm or input.new()
self.normp = self.normp or input.new()
self.buffer = self.buffer or input.new()
if self.p % 2 ~= 0 then
self.buffer:abs(input):pow(self.p)
else
self.buffer:pow(input,self.p)
end
self.normp:sum(self.buffer,2):add(self.eps)
self.norm:pow(self.normp,1/self.p)
self.output:cdiv(input,self.norm:view(-1,1):expandAs(self.output))
if not is_batch then
self.output = self.output[1]
end
return self.output
end
function Normalize:updateGradInput(input, gradOutput)
assert(input:dim() <= 2, 'only 1d layer supported')
assert(gradOutput:dim() <= 2, 'only 1d layer supported')
local is_batch = true
if input:dim() == 1 then
input = input:view(1,-1)
is_batch = false
end
local n = input:size(1) -- batch size
local d = input:size(2) -- dimensionality of vectors
-- compute diagonal term with gradOutput
self.gradInput:resize(n,d,1)
gradOutput = gradOutput:view(n,d,1)
self.gradInput:cmul(self.normp:view(n,1,1):expand(n,d,1),gradOutput)
-- compute cross term in two steps
self.cross = self.cross or input.new()
self.cross:resize(n,1,1)
self.buffer:abs(input):pow(self.p-2):cmul(input)
local b1 = self.buffer:view(n,d,1)
local b2 = input:view(n,1,d)
-- instead of having a huge temporary matrix (b1*b2),
-- do the computations as b1*(b2*gradOutput). This avoids redundant
-- computation and also a huge buffer of size n*d^2
self.cross:bmm(b2,gradOutput)
self.gradInput:baddbmm(-1,b1, self.cross)
-- reuse cross buffer for normalization
self.cross:cmul(self.normp,self.norm)
self.gradInput:cdiv(self.cross:view(n,1,1):expand(n,d,1))
self.gradInput = self.gradInput:view(n,d)
if not is_batch then
self.gradInput = self.gradInput[1]
end
return self.gradInput
end
function Normalize:__tostring__()
local s
-- different prints if the norm is integer
if self.p % 1 == 0 then
s = '%s(%d)'
else
s = '%s(%f)'
end
return string.format(s,torch.type(self),self.p)
end
|
local Normalize, parent = torch.class('nn.Normalize', 'nn.Module')
function Normalize:__init(p,eps)
parent.__init(self)
assert(p,'p-norm not provided')
assert(p > 0, p..'-norm not supported')
self.p = p
self.eps = eps or 1e-10
self._output = torch.Tensor()
self._gradInput = torch.Tensor()
end
function Normalize:updateOutput(input)
assert(input:dim() <= 2, 'only 1d layer supported')
local input_size = input:size()
if input:dim() == 1 then
input = input:view(1,-1)
end
self._output:resizeAs(input)
self.norm = self.norm or input.new()
self.normp = self.normp or input.new()
self.buffer = self.buffer or input.new()
if self.p % 2 ~= 0 then
self.buffer:abs(input):pow(self.p)
else
self.buffer:pow(input,self.p)
end
self.normp:sum(self.buffer,2):add(self.eps)
self.norm:pow(self.normp,1/self.p)
self._output:cdiv(input, self.norm:view(-1,1):expandAs(input))
self.output = self._output:view(input_size)
return self.output
end
function Normalize:updateGradInput(input, gradOutput)
assert(input:dim() <= 2, 'only 1d layer supported')
assert(gradOutput:dim() <= 2, 'only 1d layer supported')
local input_size = input:size()
if input:dim() == 1 then
input = input:view(1,-1)
end
local n = input:size(1) -- batch size
local d = input:size(2) -- dimensionality of vectors
-- compute diagonal term with gradOutput
self._gradInput:resize(n,d,1)
gradOutput = gradOutput:view(n,d,1)
self._gradInput:cmul(self.normp:view(n,1,1):expand(n,d,1), gradOutput)
-- compute cross term in two steps
self.cross = self.cross or input.new()
self.cross:resize(n,1,1)
self.buffer:abs(input):pow(self.p-2):cmul(input)
local b1 = self.buffer:view(n,d,1)
local b2 = input:view(n,1,d)
-- instead of having a huge temporary matrix (b1*b2),
-- do the computations as b1*(b2*gradOutput). This avoids redundant
-- computation and also a huge buffer of size n*d^2
self.cross:bmm(b2, gradOutput)
self._gradInput:baddbmm(-1, b1, self.cross)
-- reuse cross buffer for normalization
self.cross:cmul(self.normp, self.norm)
self._gradInput:cdiv(self.cross:view(n,1,1):expand(n,d,1))
self._gradInput = self._gradInput:view(n,d)
self.gradInput = self._gradInput:view(input_size)
return self.gradInput
end
function Normalize:__tostring__()
local s
-- different prints if the norm is integer
if self.p % 1 == 0 then
s = '%s(%d)'
else
s = '%s(%f)'
end
return string.format(s,torch.type(self),self.p)
end
|
Fix modification of output in nn.Normalize
|
Fix modification of output in nn.Normalize
|
Lua
|
bsd-3-clause
|
apaszke/nn,andreaskoepf/nn,elbamos/nn,eriche2016/nn,kmul00/nn,rotmanmi/nn,clementfarabet/nn,PraveerSINGH/nn,jonathantompson/nn,Moodstocks/nn,nicholas-leonard/nn,colesbury/nn,caldweln/nn,sagarwaghmare69/nn,diz-vara/nn,vgire/nn,lukasc-ch/nn,jhjin/nn,eulerreich/nn,witgo/nn,mlosch/nn,xianjiec/nn,joeyhng/nn
|
f7610db744c172680354fa2558b73744fddd69e4
|
modules/title/post/pgolds.lua
|
modules/title/post/pgolds.lua
|
local os = require 'os'
local iconv = require'iconv'
local dbi = require 'DBI'
require'logging.console'
local log = logging.console()
-- Open connection to the postgresql database using DBI lib and ivar2 global config
local openDb = function()
-- TODO save/cache connection
local dbh = DBI.Connect('PostgreSQL', ivar2.config.dbname, ivar2.config.dbuser, ivar2.config.dbpass, ivar2.config.dbhost, ivar2.config.dbport)
return dbh
end
-- check for existing url
local checkOlds = function(dbh, source, destination, url)
-- create a select handle
local sth = assert(dbh:prepare([[
SELECT
date_trunc('second', time),
date_trunc('second', age(now(), date_trunc('second', time))),
nick
FROM urls
WHERE
url=?
AND
channel=?
ORDER BY time ASC
]]
))
-- execute select with a url bound to variable
log:info(string.format('conf %s %s', url, destination))
sth:execute(url, destination)
-- get list of column names in the result set
--local columns = sth:columns()
local count = 0
local nick
local when
-- iterate over the returned data
for row in sth:rows() do
count = count + 1
-- rows() with no arguments (or false) returns
-- the data as a numerically indexed table
-- passing it true returns a table indexed by
-- column names
if count == 1 then
when = row[1]
ago = row[2]
nick = row[3]
when = when .. ', ' .. ago .. ' ago'
end
end
if count > 0 then
return nick, count, ago
end
end
-- save url to db
local dbLogUrl = function(dbh, source, destination, msg, url)
local nick = source.nick
log:info(string.format('Inserting URL into db. %s,%s, %s, %s', nick, destination, msg, url))
-- check status of the connection
-- local alive = dbh:ping()
-- create a handle for an insert
local insert = dbh:prepare('INSERT INTO urls(nick,channel,url,message) values(?,?,?,?)')
-- execute the handle with bind parameters
local stmt, err = insert:execute(nick, destination, url, msg)
-- commit the transaction
dbh:commit()
--local ok = dbh:close()
end
do
return function(source, destination, queue)
local dbh = openDb()
local nick, count, ago = checkOlds(dbh, source, destination, queue.url)
dbLogUrl(dbh, source, destination, queue.url)
-- Check if this module is disabled and just stop here if it is
if not ivar2:IsModuleDisabled('olds', destination) then
local prepend
if(count > 1) then
prepend = string.format("Olds! %s times, first by %s %s", count, nick, ago)
else
prepend = string.format("Olds! Linked by %s %s ago", nick, ago)
end
if(queue.output) then
queue.output = string.format("%s - %s", prepend, queue.output)
else
queue.output = prepend
end
end
end
end
|
local os = require 'os'
local iconv = require'iconv'
local dbi = require 'DBI'
require'logging.console'
local log = logging.console()
-- Open connection to the postgresql database using DBI lib and ivar2 global config
local openDb = function()
-- TODO save/cache connection
local dbh = DBI.Connect('PostgreSQL', ivar2.config.dbname, ivar2.config.dbuser, ivar2.config.dbpass, ivar2.config.dbhost, ivar2.config.dbport)
return dbh
end
-- check for existing url
local checkOlds = function(dbh, source, destination, url)
-- create a select handle
local sth = assert(dbh:prepare([[
SELECT
date_trunc('second', time),
date_trunc('second', age(now(), date_trunc('second', time))),
nick
FROM urls
WHERE
url=?
AND
channel=?
ORDER BY time ASC
]]
))
-- execute select with a url bound to variable
sth:execute(url, destination)
-- get list of column names in the result set
--local columns = sth:columns()
local count = 0
local nick
local when
local ago
-- iterate over the returned data
for row in sth:rows() do
count = count + 1
-- rows() with no arguments (or false) returns
-- the data as a numerically indexed table
-- passing it true returns a table indexed by
-- column names
if count == 1 then
when = row[1]
ago = row[2]
nick = row[3]
when = when .. ', ' .. ago .. ' ago'
end
end
return nick, count, ago
end
-- save url to db
local dbLogUrl = function(dbh, source, destination, url, msg)
local nick = source.nick
log:info(string.format('Inserting URL into db. %s,%s, %s, %s', nick, destination, msg, url))
-- check status of the connection
-- local alive = dbh:ping()
-- create a handle for an insert
local insert = dbh:prepare('INSERT INTO urls(nick,channel,url,message) values(?,?,?,?)')
-- execute the handle with bind parameters
local stmt, err = insert:execute(nick, destination, url, msg)
-- commit the transaction
dbh:commit()
--local ok = dbh:close()
end
do
return function(source, destination, queue, msg)
local dbh = openDb()
local nick, count, ago = checkOlds(dbh, source, destination, queue.url)
dbLogUrl(dbh, source, destination, queue.url, msg)
if not count then return end
if count == 0 then return end
-- Check if this module is disabled and just stop here if it is
if not ivar2:IsModuleDisabled('olds', destination) then
local prepend
if(count > 1) then
prepend = string.format("Olds! %s times, first by %s %s", count, nick, ago)
else
prepend = string.format("Olds! Linked by %s %s ago", nick, ago)
end
if(queue.output) then
queue.output = string.format("%s - %s", prepend, queue.output)
else
queue.output = prepend
end
end
end
end
|
Fix the argument, fix count check
|
Fix the argument, fix count check
Former-commit-id: bc582db541b809b1e19ceaa1ffb28a7896a21539 [formerly 4f442204d02925d33225e7ac1a225d38b8cc5850]
Former-commit-id: 1adf22e7c2fc488da295340b283b015cbb137fa1
|
Lua
|
mit
|
torhve/ivar2,haste/ivar2,torhve/ivar2,torhve/ivar2
|
bdf7749fa709a427d99ba33f163d27d5f037cc81
|
core/storagemanager.lua
|
core/storagemanager.lua
|
local error, type = error, type;
local setmetatable = setmetatable;
local config = require "core.configmanager";
local datamanager = require "util.datamanager";
local modulemanager = require "core.modulemanager";
local multitable = require "util.multitable";
local hosts = hosts;
local log = require "util.logger".init("storagemanager");
local olddm = {}; -- maintain old datamanager, for backwards compatibility
for k,v in pairs(datamanager) do olddm[k] = v; end
module("storagemanager")
local default_driver_mt = { name = "internal" };
default_driver_mt.__index = default_driver_mt;
function default_driver_mt:open(store)
return setmetatable({ host = self.host, store = store }, default_driver_mt);
end
function default_driver_mt:get(user) return olddm.load(user, self.host, self.store); end
function default_driver_mt:set(user, data) return olddm.store(user, self.host, self.store, data); end
local stores_available = multitable.new();
function initialize_host(host)
host_session.events.add_handler("item-added/data-driver", function (event)
local item = event.item;
stores_available:set(host, item.name, item);
end);
host_session.events.add_handler("item-removed/data-driver", function (event)
local item = event.item;
stores_available:set(host, item.name, nil);
end);
end
local function load_driver(host, driver_name)
if not driver_name then
return;
end
local driver = stores_available:get(host, driver_name);
if not driver then
if driver_name ~= "internal" then
modulemanager.load(host, "storage_"..driver_name);
return stores_available:get(host, driver_name);
else
return setmetatable({host = host}, default_driver_mt);
end
end
end
function open(host, store, typ)
local storage = config.get(host, "core", "storage");
local driver_name;
local option_type = type(storage);
if option_type == "string" then
driver_name = storage;
elseif option_type == "table" then
driver_name = storage[store];
end
local driver = load_driver(host, driver_name);
if not driver then
driver_name = config.get(host, "core", "default_storage");
driver = load_driver(host, driver_name);
if not driver then
if storage or driver_name then
log("warn", "Falling back to default driver for %s storage on %s", store, host);
end
driver_name = "internal";
driver = load_driver(host, driver_name);
end
end
local ret, err = driver:open(store, typ);
if not ret then
if err == "unsupported-store" then
log("debug", "Storage driver %s does not support store %s (%s), falling back to internal driver",
driver_name, store, typ);
ret = setmetatable({ host = host, store = store }, default_driver_mt); -- default to default driver
err = nil;
end
end
return ret, err;
end
function datamanager.load(username, host, datastore)
return open(host, datastore):get(username);
end
function datamanager.store(username, host, datastore, data)
return open(host, datastore):set(username, data);
end
return _M;
|
local error, type = error, type;
local setmetatable = setmetatable;
local config = require "core.configmanager";
local datamanager = require "util.datamanager";
local modulemanager = require "core.modulemanager";
local multitable = require "util.multitable";
local hosts = hosts;
local log = require "util.logger".init("storagemanager");
local olddm = {}; -- maintain old datamanager, for backwards compatibility
for k,v in pairs(datamanager) do olddm[k] = v; end
module("storagemanager")
local default_driver_mt = { name = "internal" };
default_driver_mt.__index = default_driver_mt;
function default_driver_mt:open(store)
return setmetatable({ host = self.host, store = store }, default_driver_mt);
end
function default_driver_mt:get(user) return olddm.load(user, self.host, self.store); end
function default_driver_mt:set(user, data) return olddm.store(user, self.host, self.store, data); end
local stores_available = multitable.new();
function initialize_host(host)
local host_session = hosts[host];
host_session.events.add_handler("item-added/data-driver", function (event)
local item = event.item;
stores_available:set(host, item.name, item);
end);
host_session.events.add_handler("item-removed/data-driver", function (event)
local item = event.item;
stores_available:set(host, item.name, nil);
end);
end
local function load_driver(host, driver_name)
if not driver_name then
return;
end
local driver = stores_available:get(host, driver_name);
if not driver then
if driver_name ~= "internal" then
modulemanager.load(host, "storage_"..driver_name);
return stores_available:get(host, driver_name);
else
return setmetatable({host = host}, default_driver_mt);
end
end
end
function open(host, store, typ)
local storage = config.get(host, "core", "storage");
local driver_name;
local option_type = type(storage);
if option_type == "string" then
driver_name = storage;
elseif option_type == "table" then
driver_name = storage[store];
end
local driver = load_driver(host, driver_name);
if not driver then
driver_name = config.get(host, "core", "default_storage");
driver = load_driver(host, driver_name);
if not driver then
if storage or driver_name then
log("warn", "Falling back to default driver for %s storage on %s", store, host);
end
driver_name = "internal";
driver = load_driver(host, driver_name);
end
end
local ret, err = driver:open(store, typ);
if not ret then
if err == "unsupported-store" then
log("debug", "Storage driver %s does not support store %s (%s), falling back to internal driver",
driver_name, store, typ);
ret = setmetatable({ host = host, store = store }, default_driver_mt); -- default to default driver
err = nil;
end
end
return ret, err;
end
function datamanager.load(username, host, datastore)
return open(host, datastore):get(username);
end
function datamanager.store(username, host, datastore, data)
return open(host, datastore):set(username, data);
end
return _M;
|
storagemanager: Fixed a nil global access.
|
storagemanager: Fixed a nil global access.
|
Lua
|
mit
|
sarumjanuch/prosody,sarumjanuch/prosody
|
076e5672adba3a7c1dca3a9e6651d5a65092e426
|
applications/luci-app-nft-qos/luasrc/controller/nft-qos.lua
|
applications/luci-app-nft-qos/luasrc/controller/nft-qos.lua
|
-- Copyright 2018 Rosy Song <[email protected]>
-- Licensed to the public under the Apache License 2.0.
module("luci.controller.nft-qos", package.seeall)
function index()
if not nixio.fs.access("/etc/config/nft-qos") then
return
end
entry({"admin", "status", "realtime", "rate"},
template("nft-qos/rate"), _("Rate"), 5).leaf = true
entry({"admin", "status", "realtime", "rate_status"},
call("action_rate")).leaf = true
entry({"admin", "services", "nft-qos"}, cbi("nft-qos/nft-qos"),
_("Qos over Nftables"), 60)
end
function _action_rate(rv, n)
local c = io.popen("nft list chain inet nft-qos-monitor " .. n .. " 2>/dev/null")
if c then
for l in c:lines() do
local _, i, p, b = l:match('^%s+ip ([^%s]+) ([^%s]+) counter packets (%d+) bytes (%d+)')
if i and p and b then
-- handle expression
local r = {
rule = {
family = "inet",
table = "nft-qos-monitor",
chain = n,
handle = 0,
expr = {
{ match = { right = i } },
{ counter = { packets = p, bytes = b } }
}
}
}
rv[#rv + 1] = r
end
end
c:close()
end
end
function action_rate()
luci.http.prepare_content("application/json")
local data = { nftables = {} }
_action_rate(data.nftables, "upload")
_action_rate(data.nftables, "download")
luci.http.write_json(data)
end
|
-- Copyright 2018 Rosy Song <[email protected]>
-- Licensed to the public under the Apache License 2.0.
module("luci.controller.nft-qos", package.seeall)
function index()
if not nixio.fs.access("/etc/config/nft-qos") then
return
end
entry({"admin", "status", "realtime", "rate"},
template("nft-qos/rate"), _("Rate"), 5).leaf = true
entry({"admin", "status", "realtime", "rate_status"},
call("action_rate")).leaf = true
entry({"admin", "services", "nft-qos"}, cbi("nft-qos/nft-qos"),
_("Qos over Nftables"), 60)
end
function _action_rate(rv, n)
local has_ipv6 = nixio.fs.access("/proc/net/ipv6_route")
if has_ipv6 then
local c = io.popen("nft list chain inet nft-qos-monitor " .. n .. " 2>/dev/null")
else
local c = io.popen("nft list chain ip nft-qos-monitor " .. n .. " 2>/dev/null")
end
if c then
for l in c:lines() do
local _, i, p, b = l:match('^%s+ip ([^%s]+) ([^%s]+) counter packets (%d+) bytes (%d+)')
if i and p and b then
-- handle expression
local r = {
rule = {
family = "inet",
table = "nft-qos-monitor",
chain = n,
handle = 0,
expr = {
{ match = { right = i } },
{ counter = { packets = p, bytes = b } }
}
}
}
rv[#rv + 1] = r
end
end
c:close()
end
end
function action_rate()
luci.http.prepare_content("application/json")
local data = { nftables = {} }
_action_rate(data.nftables, "upload")
_action_rate(data.nftables, "download")
luci.http.write_json(data)
end
|
luci-app-nft-qos: fix monitor doesn't work when there no ipv6 support.
|
luci-app-nft-qos: fix monitor doesn't work when there no ipv6 support.
Signed-off-by: Rosy Song <[email protected]>
|
Lua
|
apache-2.0
|
hnyman/luci,openwrt/luci,hnyman/luci,rogerpueyo/luci,Noltari/luci,tobiaswaldvogel/luci,tobiaswaldvogel/luci,artynet/luci,artynet/luci,openwrt-es/openwrt-luci,artynet/luci,Noltari/luci,hnyman/luci,artynet/luci,nmav/luci,rogerpueyo/luci,openwrt-es/openwrt-luci,nmav/luci,hnyman/luci,nmav/luci,openwrt/luci,hnyman/luci,artynet/luci,nmav/luci,openwrt/luci,openwrt-es/openwrt-luci,hnyman/luci,lbthomsen/openwrt-luci,Noltari/luci,lbthomsen/openwrt-luci,lbthomsen/openwrt-luci,rogerpueyo/luci,openwrt/luci,openwrt-es/openwrt-luci,artynet/luci,lbthomsen/openwrt-luci,Noltari/luci,openwrt-es/openwrt-luci,Noltari/luci,artynet/luci,hnyman/luci,rogerpueyo/luci,openwrt-es/openwrt-luci,tobiaswaldvogel/luci,Noltari/luci,Noltari/luci,tobiaswaldvogel/luci,nmav/luci,lbthomsen/openwrt-luci,artynet/luci,rogerpueyo/luci,openwrt/luci,tobiaswaldvogel/luci,openwrt/luci,nmav/luci,artynet/luci,tobiaswaldvogel/luci,nmav/luci,openwrt-es/openwrt-luci,lbthomsen/openwrt-luci,nmav/luci,lbthomsen/openwrt-luci,tobiaswaldvogel/luci,rogerpueyo/luci,rogerpueyo/luci,tobiaswaldvogel/luci,lbthomsen/openwrt-luci,rogerpueyo/luci,openwrt/luci,nmav/luci,openwrt/luci,openwrt-es/openwrt-luci,hnyman/luci,Noltari/luci,Noltari/luci
|
808e76f30ac2dbafe49c228f184af44685b8b5f4
|
decode.lua
|
decode.lua
|
require 'torch'
require 'cudnn'
require 'src.Model'
require 'src.utilities'
require 'src.WidthBatcher'
local str2bool_table = {
['true'] = true, ['false'] = false,
['t'] = true, ['f'] = false,
['True'] = true, ['False'] = false,
['1'] = true, ['0'] = false,
['TRUE'] = true, ['FALSE'] = false
}
local argparse = require 'argparse'
local parser = argparse('decode.lua', '')
parser:argument('model', 'Path to the neural network model file')
parser:argument('data', 'Path to the dataset HDF5 file')
parser:option('-b --batch_size', 'Batch size', 16):convert(tonumber)
parser:option('--use_gpu',
'If true, perform computations on a GPU card supporintg CUDA',
'true'):convert(str2bool_table)
parser:option('--use_cudnn',
'If true, use NVIDIA cuDNN toolkit',
'true'):convert(str2bool_table)
local args = parser:parse()
if args.use_gpu then
require 'cutorch'
require 'cunn'
if args.use_cudnn then
require 'cudnn'
end
end
local model = torch.load(args.model)
model:remove() -- Remove last module (JoinTable)
if args.use_gpu then
model = model:cuda()
if use_cudnn then
cudnn.convert(model, cudnn)
end
end
model:evaluate()
local dv = WidthBatcher(args.data, true)
local n = 0
for batch=1,dv:numSamples(),args.batch_size do
-- Prepare batch
local batch_img, _, _, batch_ids = dv:next(args.batch_size)
if args.use_gpu then
batch_img = batch_img:cuda()
end
-- Forward through network
local output = model:forward(batch_img)
-- Prepare hypothesis
local hyps = {}
for t=1,#output do
local _, idx = torch.max(output[t], 2)
idx = torch.totable(idx - 1)
for i=1,args.batch_size do
if i <= #hyps then
table.insert(hyps[i], idx[i][1])
else
hyps[i] = idx[i]
end
end
end
for i=1,args.batch_size do
n = n + 1
if n > dv:numSamples() then
break
end
io.write(string.format('%s ', batch_ids[i]))
for t=1,#hyps[i] do
io.write(string.format(' %d', hyps[i][t]))
end
io.write('\n')
end
end
|
require 'torch'
require 'cudnn'
require 'src.Model'
require 'src.utilities'
require 'src.WidthBatcher'
local str2bool_table = {
['true'] = true, ['false'] = false,
['t'] = true, ['f'] = false,
['True'] = true, ['False'] = false,
['1'] = true, ['0'] = false,
['TRUE'] = true, ['FALSE'] = false
}
local argparse = require 'argparse'
local parser = argparse('decode.lua', '')
parser:argument('model', 'Path to the neural network model file')
parser:argument('data', 'Path to the dataset HDF5 file')
parser:option('-b --batch_size', 'Batch size', 16):convert(tonumber)
parser:option('--use_gpu',
'If true, perform computations on a GPU card supporting CUDA',
'true'):convert(str2bool_table)
parser:option('--use_cudnn',
'If true, use NVIDIA cuDNN toolkit',
'true'):convert(str2bool_table)
local args = parser:parse()
if args.use_gpu then
require 'cutorch'
require 'cunn'
if args.use_cudnn then
require 'cudnn'
end
end
local model = torch.load(args.model)
if args.use_gpu then
model = model:cuda()
if use_cudnn then
cudnn.convert(model, cudnn)
end
end
model:evaluate()
local dv = WidthBatcher(args.data, true)
local n = 0
for batch=1,dv:numSamples(),args.batch_size do
-- Prepare batch
local batch_img, _, _, batch_ids = dv:next(args.batch_size)
if args.use_gpu then
batch_img = batch_img:cuda()
end
-- Forward through network
local output = model:forward(batch_img)
local batch_decode = framewise_decode(args.batch_size, output)
for i=1, args.batch_size do
n = n + 1
if n > dv:numSamples() then
break
end
io.write(string.format('%s ', batch_ids[i]))
for t=1, #batch_decode[i] do
io.write(string.format(' %d', batch_decode[i][t]))
end
io.write('\n')
end
end
|
Fixed decoding
|
Fixed decoding
|
Lua
|
mit
|
jpuigcerver/Laia,jpuigcerver/Laia,jpuigcerver/Laia,jpuigcerver/Laia
|
512d5debdfad94f1e1f15857e8b0b5f80ecf69c1
|
lua/entities/gmod_wire_expression2/core/custom/remoteupload.lua
|
lua/entities/gmod_wire_expression2/core/custom/remoteupload.lua
|
E2Lib.RegisterExtension("remoteupload", false)
local antispam = {}
local function check(ply)
if antispam[ply] and antispam[ply] > CurTime() then
return false
else
antispam[ply] = CurTime() + 1
return true
end
end
umsg.PoolString("e2_remoteupload_request")
__e2setcost(1000)
e2function void entity:remoteUpload( string filepath )
if not this or not this:IsValid() or this:GetClass() ~= "gmod_wire_expression2" then return end
if not E2Lib.isOwner( self, this ) then return end
if not check(self.player) then return end
umsg.Start( "e2_remoteupload_request", self.player )
umsg.Entity( this )
umsg.String( filepath )
umsg.End()
end
__e2setcost(250)
e2function void entity:remoteSetCode( string code )
if not this or not this:IsValid() or this:GetClass() ~= "gmod_wire_expression2" then return end
if not E2Lib.isOwner( self, this ) then return end
if not check(self.player) then return end
this:Setup( code, {} )
end
e2function void entity:remoteSetCode( string main, table includes )
if not this or not this:IsValid() or this:GetClass() ~= "gmod_wire_expression2" then return end
if not E2Lib.isOwner( self, this ) then return end
if not check(self.player) then return end
local luatable = {}
for k,v in pairs( includes.s ) do
self.prf = self.prf + 0.3
if includes.stypes[k] == "s" then
luatable[k] = v
else
error( "Non-string value given to remoteSetCode", 2 )
end
end
this:Setup( main, luatable )
end
__e2setcost(20)
e2function string getCode()
local main, _ = self.entity:GetCode()
return main
end
e2function table getCodeIncludes()
local _, includes = self.entity:GetCode()
local e2table = {n={},ntypes={},s={},stypes={},size=0}
local size = 0
for k,v in pairs( includes ) do
size = size + 1
e2table.s[k] = v
e2table.stypes[k] = "s"
end
self.prf = self.prf + size * 0.3
e2table.size = size
return e2table
end
|
E2Lib.RegisterExtension("remoteupload", false)
local antispam = {}
local function check(ply)
if antispam[ply] and antispam[ply] > CurTime() then
return false
else
antispam[ply] = CurTime() + 1
return true
end
end
umsg.PoolString("e2_remoteupload_request")
__e2setcost(1000)
e2function void entity:remoteUpload( string filepath )
if not this or not this:IsValid() or this:GetClass() ~= "gmod_wire_expression2" then return end
if not E2Lib.isOwner( self, this ) then return end
if not check(self.player) then return end
umsg.Start( "e2_remoteupload_request", self.player )
umsg.Entity( this )
umsg.String( filepath )
umsg.End()
end
__e2setcost(250)
e2function void entity:remoteSetCode( string code )
if not this or not this:IsValid() or this:GetClass() ~= "gmod_wire_expression2" then return end
if not E2Lib.isOwner( self, this ) then return end
if not check(self.player) then return end
timer.Simple( 0, function()
this:Setup( code, {}, nil, nil, "remoteSetCode" )
end )
end
e2function void entity:remoteSetCode( string main, table includes )
if not this or not this:IsValid() or this:GetClass() ~= "gmod_wire_expression2" then return end
if not E2Lib.isOwner( self, this ) then return end
if not check(self.player) then return end
local luatable = {}
for k,v in pairs( includes.s ) do
self.prf = self.prf + 0.3
if includes.stypes[k] == "s" then
luatable[k] = v
else
error( "Non-string value given to remoteSetCode", 2 )
end
end
timer.Simple( 0, function()
this:Setup( main, luatable, nil, nil, "remoteSetCode" )
end )
end
__e2setcost(20)
e2function string getCode()
local main, _ = self.entity:GetCode()
return main
end
e2function table getCodeIncludes()
local _, includes = self.entity:GetCode()
local e2table = {n={},ntypes={},s={},stypes={},size=0}
local size = 0
for k,v in pairs( includes ) do
size = size + 1
e2table.s[k] = v
e2table.stypes[k] = "s"
end
self.prf = self.prf + size * 0.3
e2table.size = size
return e2table
end
|
Fixed remoteSetCode not working
|
Fixed remoteSetCode not working
TIMERS
SOLVE
EVERYTHING
Fixes #758
|
Lua
|
apache-2.0
|
plinkopenguin/wiremod,Python1320/wire,Grocel/wire,bigdogmat/wire,CaptainPRICE/wire,sammyt291/wire,rafradek/wire,wiremod/wire,dvdvideo1234/wire,notcake/wire,mitterdoo/wire,immibis/wiremod,thegrb93/wire,garrysmodlua/wire,NezzKryptic/Wire,mms92/wire
|
69649f2708c1c54c32645c6f9d83f86b0e835bc7
|
libs/core/luasrc/init.lua
|
libs/core/luasrc/init.lua
|
--[[
LuCI - Lua Configuration Interface
Description:
Main class
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.
]]--
local require = require
module "luci"
local v = require "luci.version"
__version__ = v.luciversion or "0.9"
__appname__ = v.luciname or "LuCI"
|
--[[
LuCI - Lua Configuration Interface
Description:
Main class
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.
]]--
local require = require
-- Make sure that bitlib is loaded
if not _G.bit then
_G.bit = require "bit"
end
module "luci"
local v = require "luci.version"
__version__ = v.luciversion or "0.9"
__appname__ = v.luciname or "LuCI"
|
libs/core: make sure that bitlib is loaded, fixes some sdk problems
|
libs/core: make sure that bitlib is loaded, fixes some sdk problems
git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@4537 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
|
6ff0d11af321545bef10aec99ea0158d83fc9de4
|
src/ngx-oauth/config.lua
|
src/ngx-oauth/config.lua
|
---------
-- Module for configuration loading.
local util = require 'ngx-oauth.util'
local contains = util.contains
local is_blank = util.is_blank
local map = util.map
local par = util.partial
local M = {}
local defaults = {
client_id = '',
client_secret = '',
scope = '',
redirect_path = '/_oauth/callback',
server_url = '', -- used only as a shorthand for setting these 3 below
authorization_url = '${server_url}/authorize',
token_url = '${server_url}/token',
userinfo_url = "${server_url}/userinfo",
success_path = '/',
cookie_path = '/',
max_age = 2592000, -- 30 days
aes_bits = 256,
debug = false
}
local load_from_ngx = par(map, function(default_value, key)
return util.default(ngx.var['oauth_'..key], default_value)
end, defaults)
--- Loads settings from nginx variables and ensure that all required
-- variables are set.
--
-- @treturn {[string]=any,...} Settings
-- @treturn nil|string Validation error, or `false` if no validation
-- error was found.
function M.load ()
local errors = {}
local conf = load_from_ngx()
local server_url = not is_blank(conf.server_url) and conf.server_url
if is_blank(conf.client_id) then
table.insert(errors, 'variable $oauth_client_id is not set')
end
if is_blank(conf.client_secret) then
table.insert(errors, 'variable $oauth_client_secret is not set')
end
if not contains(conf.aes_bits, {128, 192, 256}) then
table.insert(errors, '$oauth_aes_bits must be 128, 192, or 256')
end
if conf.client_secret:len() < conf.aes_bits / 8 then
table.insert(errors, '$oauth_client_secret is too short, it must be at least '..
(conf.aes_bits / 8)..' characters long for $oauth_aes_bits = '..conf.aes_bits)
end
for _, key in ipairs {'authorization_url', 'token_url', 'userinfo_url'} do
if not server_url and conf[key]:find('${server_url}', 1, true) then
table.insert(errors, 'neither variable $oauth_'..key..' nor $oauth_server_url is set')
elseif server_url then
conf[key] = conf[key]:gsub('${server_url}', server_url)
end
end
return conf, #errors ~= 0 and table.concat(errors, ', ')
end
return M
|
---------
-- Module for configuration loading.
local util = require 'ngx-oauth.util'
local contains = util.contains
local is_blank = util.is_blank
local map = util.map
local par = util.partial
local M = {}
local defaults = {
client_id = '',
client_secret = '',
scope = '',
redirect_path = '/_oauth/callback',
server_url = '', -- used only as a shorthand for setting these 3 below
authorization_url = '${server_url}/authorize',
token_url = '${server_url}/token',
userinfo_url = "${server_url}/userinfo",
success_path = '/',
cookie_path = '/',
max_age = 2592000, -- 30 days
aes_bits = 256,
debug = false
}
local load_from_ngx = par(map, function(default_value, key)
return util.default(ngx.var['oauth_'..key], default_value)
end, defaults)
--- Loads settings from nginx variables and ensure that all required
-- variables are set.
--
-- @treturn {[string]=any,...} Settings
-- @treturn nil|string Validation error, or `false` if no validation
-- error was found.
function M.load ()
local errors = {}
local conf = load_from_ngx()
local server_url = not is_blank(conf.server_url) and conf.server_url
if is_blank(conf.client_id) then
table.insert(errors, 'variable $oauth_client_id is not set')
end
if is_blank(conf.client_secret) then
table.insert(errors, 'variable $oauth_client_secret is not set')
end
if not contains(conf.aes_bits, {128, 192, 256}) then
table.insert(errors, '$oauth_aes_bits must be 128, 192, or 256')
end
if conf.client_secret:len() < conf.aes_bits / 8 then
table.insert(errors, ('$oauth_client_secret is too short, it must be at least %.0f'..
' characters long for $oauth_aes_bits = %.0f'):format(conf.aes_bits / 8, conf.aes_bits))
end
for _, key in ipairs {'authorization_url', 'token_url', 'userinfo_url'} do
if not server_url and conf[key]:find('${server_url}', 1, true) then
table.insert(errors, 'neither variable $oauth_'..key..' nor $oauth_server_url is set')
elseif server_url then
conf[key] = conf[key]:gsub('${server_url}', server_url)
end
end
return conf, #errors ~= 0 and table.concat(errors, ', ')
end
return M
|
Fix compatibility with Lua 5.3
|
Fix compatibility with Lua 5.3
|
Lua
|
mit
|
jirutka/ngx-oauth,jirutka/ngx-oauth
|
5281d65abddc7ff7a65e0683245e5db6a38e828c
|
libs/fs.lua
|
libs/fs.lua
|
local prev, pl, dirname, dir = ...
local glob = prev.require 'posix.glob'.glob
local romPath = pl.path.normpath(pl.path.join(dirname, 'cc'))
local function findRomFile(path)
return pl.path.normpath(pl.path.join(romPath, path))
end
local function betterifyPath(path)
local oldPath
while oldPath ~= path do
oldPath = path
if path:sub(1, 1) == '/' then
path = path:sub(2)
end
if path:sub(1, 2) == './' or path == '.' then
path = path:sub(2)
end
if path:sub(1, 3) == '../' or path == '..' then
path = path:sub(3)
end
if path:sub(-2) == '/.' then
path = path:sub(1, -3)
end
end
return path
end
dir = '/' .. betterifyPath(dir)
dirname = '/' .. betterifyPath(dirname)
romPath = '/' .. betterifyPath(pl.path.abspath(romPath))
local function findPath(path)
path = pl.path.normpath(path)
path = betterifyPath(path)
if path:sub(1, 3) == 'rom' then
return findRomFile(path)
end
return pl.path.normpath(pl.path.join(dir, path))
end
local function runRom(path, ...)
local fn, err = prev.loadfile(findRomFile(path), 't', _G)
if err then
error(err)
end
if setfenv then
setfenv(fn, _G)
end
return fn(...)
end
return {
isReadOnly = function(path)
return betterifyPath(path):sub(1, 3) == 'rom'
end;
delete = function(path)
path = findPath(path)
if pl.path.exists(findPath(path)) then
local ok, err = pl.file.delete(path)
if err then
error(err)
end
end
end;
move = function(src, dest)
src = findPath(src)
dest = findPath(dest)
if not pl.path.exists(src) then
error('No such file', 2)
end
if pl.path.exists(dest) then
error('File exists', 2)
end
pl.file.move(src, dest)
end;
copy = function(src, dest)
src = findPath(src)
dest = findPath(dest)
if not pl.path.exists(src) then
error('No such file', 2)
end
if pl.path.exists(dest) then
error('File exists', 2)
end
pl.file.copy(src, dest)
end;
list = function(path)
path = findPath(path)
if not pl.path.isdir(path) then
error('Not a directory', 2)
end
local files = {}
if path == dir then
files[#files + 1] = 'rom'
end
for file in pl.path.dir(path) do
if file ~= '.' and file ~= '..' then
files[#files + 1] = file
end
end
table.sort(files)
return files
end;
open = function(path, mode)
path = findPath(path)
if not pl.path.isfile(path) then return nil end
local file = prev.io.open(path, mode)
local h = {}
if mode == 'r' then
function h.readAll()
local data, err = file:read('*a')
if data then
data = data:gsub('\13', '\n')
-- prev.print('all', pl.pretty.write(data))
return data
else
if err then
error(err)
else
return ''
end
end
end
function h.readLine()
local line = file:read('*l')
if line then
line = line:gsub('[\13\n\r]*$', '')
end
-- prev.print('line', pl.pretty.write(line))
return line
end
elseif mode == 'w' or mode == 'a' then
function h.write(data)
file:write(data)
end
function h.writeLine(data)
file:write(data)
file:write('\n')
end
function h.flush()
file:flush()
end
end
function h.close()
file:close()
end
return h
end;
exists = function(path)
return pl.path.exists(findPath(path)) ~= false
end;
getDrive = function(path)
path = findPath(path)
if pl.path.exists(path) then
if path:find(romPath, 1, true) then
return 'rom'
else
return 'hdd'
end
end
end;
isDir = function(path)
return pl.path.isdir(findPath(path))
end;
combine = function(a, b)
local function doIt()
if a == '' then
a = '/'
end
if a:sub(1, 1) ~= '/' and a:sub(1, 2) ~= './' then
a = '/' .. a
end
if b == '.' then
return a
end
if a == '/' and b == '..' then
return '..'
end
if a:sub(-2) == '..' and b == '..' then
return a .. '/..'
end
return pl.path.normpath(pl.path.join(a, b))
end
local res = doIt()
if res:sub(1, 1) == '/' then
res = res:sub(2)
end
return res
end;
getName = function(path) return pl.path.basename(path) end;
getSize = function(path) return math.pow(2, 20) end;
find = function(pat)
pat = pl.path.normpath(pat or '')
pat = pat:gsub('%*%*', '*')
local results = {}
for _, path in ipairs(glob(findPath(pat)) or {}) do
results[#results + 1] = pl.path.relpath(path, dir)
end
for _, path in ipairs(glob(findRomFile(pat)) or {}) do
results[#results + 1] = pl.path.relpath(path, romPath)
end
return results
end;
makeDir = function(path)
path = findPath(path)
pl.path.mkdir(path)
end;
}, runRom
|
local prev, pl, dirname, dir = ...
local glob = prev.require 'posix.glob'.glob
local romPath = pl.path.normpath(pl.path.join(dirname, 'cc'))
local function findRomFile(path)
return pl.path.normpath(pl.path.join(romPath, path))
end
local function betterifyPath(path)
local oldPath
while oldPath ~= path do
oldPath = path
if path:sub(1, 1) == '/' then
path = path:sub(2)
end
if path:sub(1, 2) == './' or path == '.' then
path = path:sub(2)
end
if path:sub(1, 3) == '../' or path == '..' then
path = path:sub(3)
end
if path:sub(-2) == '/.' then
path = path:sub(1, -3)
end
end
return path
end
dir = '/' .. betterifyPath(dir)
dirname = '/' .. betterifyPath(dirname)
romPath = '/' .. betterifyPath(pl.path.abspath(romPath))
local function findPath(path)
path = pl.path.normpath(path)
path = betterifyPath(path)
if path:sub(1, 3) == 'rom' then
return findRomFile(path)
end
return pl.path.normpath(pl.path.join(dir, path))
end
local function runRom(path, ...)
local fn, err = prev.loadfile(findRomFile(path), 't', _G)
if err then
error(err)
end
if setfenv then
setfenv(fn, _G)
end
return fn(...)
end
return {
isReadOnly = function(path)
return betterifyPath(path):sub(1, 3) == 'rom'
end;
delete = function(path)
path = findPath(path)
if pl.path.exists(findPath(path)) then
local ok, err = pl.file.delete(path)
if err then
error(err)
end
end
end;
move = function(src, dest)
src = findPath(src)
dest = findPath(dest)
if not pl.path.exists(src) then
error('No such file', 2)
end
if pl.path.exists(dest) then
error('File exists', 2)
end
pl.file.move(src, dest)
end;
copy = function(src, dest)
src = findPath(src)
dest = findPath(dest)
if not pl.path.exists(src) then
error('No such file', 2)
end
if pl.path.exists(dest) then
error('File exists', 2)
end
pl.file.copy(src, dest)
end;
list = function(path)
path = findPath(path)
if not pl.path.isdir(path) then
error('Not a directory', 2)
end
local files = {}
if path == dir then
files[#files + 1] = 'rom'
end
for file in pl.path.dir(path) do
if file ~= '.' and file ~= '..' then
files[#files + 1] = file
end
end
table.sort(files)
return files
end;
open = function(path, mode)
path = findPath(path)
if not pl.path.isfile(path) and (mode == 'r' or mode == 'rb') then return nil end
local file
local h = {}
if mode == 'r' then
file = prev.io.open(path, 'r')
if not file then return end
function h.readAll()
local data, err = file:read('*a')
if data then
data = data:gsub('\13', '\n')
-- prev.print('all', pl.pretty.write(data))
return data
else
if err then
error(err)
else
return ''
end
end
end
function h.readLine()
local line = file:read('*l')
if line then
line = line:gsub('[\13\n\r]*$', '')
end
-- prev.print('line', pl.pretty.write(line))
return line
end
elseif mode == 'w' or mode == 'a' then
file = prev.io.open(path, mode)
function h.write(data)
file:write(data)
end
function h.writeLine(data)
file:write(data)
file:write('\n')
end
function h.flush()
file:flush()
end
end
local open = true
function h.close()
if open then
file:close()
end
open = false
end
return h
end;
exists = function(path)
return pl.path.exists(findPath(path)) ~= false
end;
getDrive = function(path)
path = findPath(path)
if pl.path.exists(path) then
if path:find(romPath, 1, true) then
return 'rom'
else
return 'hdd'
end
end
end;
isDir = function(path)
return pl.path.isdir(findPath(path))
end;
combine = function(a, b)
local function doIt()
if a == '' then
a = '/'
end
if a:sub(1, 1) ~= '/' and a:sub(1, 2) ~= './' then
a = '/' .. a
end
if b == '.' then
return a
end
if a == '/' and b == '..' then
return '..'
end
if a:sub(-2) == '..' and b == '..' then
return a .. '/..'
end
return pl.path.normpath(pl.path.join(a, b))
end
local res = doIt()
if res:sub(1, 1) == '/' then
res = res:sub(2)
end
return res
end;
getName = function(path) return pl.path.basename(path) end;
getSize = function(path) return math.pow(2, 20) end;
find = function(pat)
pat = pl.path.normpath(pat or '')
pat = pat:gsub('%*%*', '*')
local results = {}
for _, path in ipairs(glob(findPath(pat)) or {}) do
results[#results + 1] = pl.path.relpath(path, dir)
end
for _, path in ipairs(glob(findRomFile(pat)) or {}) do
results[#results + 1] = pl.path.relpath(path, romPath)
end
return results
end;
makeDir = function(path)
path = findPath(path)
pl.path.mkdir(path)
end;
}, runRom
|
Fix fs.open (creating files and closing files multiple times)
|
Fix fs.open (creating files and closing files multiple times)
|
Lua
|
mit
|
CoderPuppy/cc-emu,CoderPuppy/cc-emu,CoderPuppy/cc-emu
|
a82bafc63cdb41ca7266aef210fb8fddad87c31b
|
frontend/ui/rendertext.lua
|
frontend/ui/rendertext.lua
|
local Font = require("ui/font")
local Screen = require("device").screen
local Cache = require("cache")
local CacheItem = require("cacheitem")
local BlitBuffer = require("ffi/blitbuffer")
local DEBUG = require("dbg")
--[[
TODO: all these functions should probably be methods on Face objects
]]--
local RenderText = {}
local GlyphCache = Cache:new{
max_memsize = 512*1024,
current_memsize = 0,
cache = {},
-- this will hold the LRU order of the cache
cache_order = {}
}
-- iterator over UTF8 encoded characters in a string
local function utf8Chars(input)
local function read_next_glyph(input, pos)
if string.len(input) < pos then return nil end
local value = string.byte(input, pos)
if bit.band(value, 0x80) == 0 then
-- TODO: check valid ranges
return pos+1, value, string.sub(input, pos, pos)
elseif bit.band(value, 0xC0) == 0x80 -- invalid, continuation
or bit.band(value, 0xF8) == 0xF8 -- 5-or-more byte sequence, illegal due to RFC3629
then
return pos+1, 0xFFFD, "\xFF\xFD"
else
local glyph, bytes_left
if bit.band(value, 0xE0) == 0xC0 then
glyph = bit.band(value, 0x1F)
bytes_left = 1
elseif bit.band(value, 0xF0) == 0xE0 then
glyph = bit.band(value, 0x0F)
bytes_left = 2
elseif bit.band(value, 0xF8) == 0xF0 then
glyph = bit.band(value, 0x07)
bytes_left = 3
else
return pos+1, 0xFFFD, "\xFF\xFD"
end
if string.len(input) < (pos + bytes_left - 1) then
return pos+1, 0xFFFD, "\xFF\xFD"
end
for i = pos+1, pos + bytes_left do
value = string.byte(input, i)
if bit.band(value, 0xC0) == 0x80 then
glyph = bit.bor(bit.lshift(glyph, 6), bit.band(value, 0x3F))
else
return i+1, 0xFFFD, "\xFF\xFD"
end
end
-- TODO: check for valid ranges here!
return pos+bytes_left+1, glyph, string.sub(input, pos, pos+bytes_left)
end
end
return read_next_glyph, input, 1
end
function RenderText:getGlyph(face, charcode, bold)
local hash = "glyph|"..face.hash.."|"..charcode.."|"..(bold and 1 or 0)
local glyph = GlyphCache:check(hash)
if glyph then
-- cache hit
return glyph[1]
end
local rendered_glyph = face.ftface:renderGlyph(charcode, bold)
if face.ftface:checkGlyph(charcode) == 0 then
for index, font in pairs(Font.fallbacks) do
-- use original size before scaling by screen DPI
local fb_face = Font:getFace(font, face.orig_size)
if fb_face.ftface:checkGlyph(charcode) ~= 0 then
rendered_glyph = fb_face.ftface:renderGlyph(charcode, bold)
--DEBUG("fallback to font", font)
break
end
end
end
if not rendered_glyph then
DEBUG("error rendering glyph (charcode=", charcode, ") for face", face)
return
end
glyph = CacheItem:new{rendered_glyph}
glyph.size = glyph[1].bb:getWidth() * glyph[1].bb:getHeight() / 2 + 32
GlyphCache:insert(hash, glyph)
return rendered_glyph
end
function RenderText:getSubTextByWidth(text, face, width, kerning, bold)
local pen_x = 0
local prevcharcode = 0
local char_list = {}
for _, charcode, uchar in utf8Chars(text) do
if pen_x < width then
local glyph = self:getGlyph(face, charcode, bold)
if kerning and prevcharcode then
local kern = face.ftface:getKerning(prevcharcode, charcode)
pen_x = pen_x + kern
end
pen_x = pen_x + glyph.ax
if pen_x <= width then
prevcharcode = charcode
table.insert(char_list, uchar)
else
break
end
end
end
return table.concat(char_list)
end
function RenderText:sizeUtf8Text(x, width, face, text, kerning, bold)
if not text then
DEBUG("sizeUtf8Text called without text");
return
end
-- may still need more adaptive pen placement when kerning,
-- see: http://freetype.org/freetype2/docs/glyphs/glyphs-4.html
local pen_x = 0
local pen_y_top = 0
local pen_y_bottom = 0
local prevcharcode = 0
for _, charcode, uchar in utf8Chars(text) do
if pen_x < (width - x) then
local glyph = self:getGlyph(face, charcode, bold)
if kerning and (prevcharcode ~= 0) then
pen_x = pen_x + (face.ftface):getKerning(prevcharcode, charcode)
end
pen_x = pen_x + glyph.ax
pen_y_top = math.max(pen_y_top, glyph.t)
pen_y_bottom = math.max(pen_y_bottom, glyph.bb:getHeight() - glyph.t)
--DEBUG("ax:"..glyph.ax.." t:"..glyph.t.." r:"..glyph.r.." h:"..glyph.bb:getHeight().." w:"..glyph.bb:getWidth().." yt:"..pen_y_top.." yb:"..pen_y_bottom)
prevcharcode = charcode
end -- if pen_x < (width - x)
end
return { x = pen_x, y_top = pen_y_top, y_bottom = pen_y_bottom}
end
function RenderText:renderUtf8Text(buffer, x, y, face, text, kerning, bold, fgcolor, width)
if not text then
DEBUG("renderUtf8Text called without text");
return 0
end
if not fgcolor then
fgcolor = BlitBuffer.COLOR_BLACK
end
-- may still need more adaptive pen placement when kerning,
-- see: http://freetype.org/freetype2/docs/glyphs/glyphs-4.html
local pen_x = 0
local prevcharcode = 0
local text_width = buffer:getWidth() - x
if width and width < text_width then
text_width = width
end
for _, charcode, uchar in utf8Chars(text) do
if pen_x < text_width then
local glyph = self:getGlyph(face, charcode, bold)
if kerning and (prevcharcode ~= 0) then
pen_x = pen_x + face.ftface:getKerning(prevcharcode, charcode)
end
buffer:colorblitFrom(
glyph.bb,
x + pen_x + glyph.l, y - glyph.t,
0, 0,
glyph.bb:getWidth(), glyph.bb:getHeight(),
fgcolor)
pen_x = pen_x + glyph.ax
prevcharcode = charcode
end -- if pen_x < text_width
end
return pen_x
end
return RenderText
|
local Font = require("ui/font")
local Screen = require("device").screen
local Cache = require("cache")
local CacheItem = require("cacheitem")
local BlitBuffer = require("ffi/blitbuffer")
local DEBUG = require("dbg")
--[[
TODO: all these functions should probably be methods on Face objects
]]--
local RenderText = {}
local GlyphCache = Cache:new{
max_memsize = 512*1024,
current_memsize = 0,
cache = {},
-- this will hold the LRU order of the cache
cache_order = {}
}
-- iterator over UTF8 encoded characters in a string
local function utf8Chars(input)
local function read_next_glyph(input, pos)
if string.len(input) < pos then return nil end
local value = string.byte(input, pos)
if bit.band(value, 0x80) == 0 then
-- TODO: check valid ranges
return pos+1, value, string.sub(input, pos, pos)
elseif bit.band(value, 0xC0) == 0x80 -- invalid, continuation
or bit.band(value, 0xF8) == 0xF8 -- 5-or-more byte sequence, illegal due to RFC3629
then
return pos+1, 0xFFFD, "\xFF\xFD"
else
local glyph, bytes_left
if bit.band(value, 0xE0) == 0xC0 then
glyph = bit.band(value, 0x1F)
bytes_left = 1
elseif bit.band(value, 0xF0) == 0xE0 then
glyph = bit.band(value, 0x0F)
bytes_left = 2
elseif bit.band(value, 0xF8) == 0xF0 then
glyph = bit.band(value, 0x07)
bytes_left = 3
else
return pos+1, 0xFFFD, "\xFF\xFD"
end
if string.len(input) < (pos + bytes_left) then
return pos+1, 0xFFFD, "\xFF\xFD"
end
for i = pos+1, pos + bytes_left do
value = string.byte(input, i)
if bit.band(value, 0xC0) == 0x80 then
glyph = bit.bor(bit.lshift(glyph, 6), bit.band(value, 0x3F))
else
-- invalid UTF8 continuation - don't be greedy, just skip
-- the initial char of the sequence.
return pos+1, 0xFFFD, "\xFF\xFD"
end
end
-- TODO: check for valid ranges here!
return pos+bytes_left+1, glyph, string.sub(input, pos, pos+bytes_left)
end
end
return read_next_glyph, input, 1
end
function RenderText:getGlyph(face, charcode, bold)
local hash = "glyph|"..face.hash.."|"..charcode.."|"..(bold and 1 or 0)
local glyph = GlyphCache:check(hash)
if glyph then
-- cache hit
return glyph[1]
end
local rendered_glyph = face.ftface:renderGlyph(charcode, bold)
if face.ftface:checkGlyph(charcode) == 0 then
for index, font in pairs(Font.fallbacks) do
-- use original size before scaling by screen DPI
local fb_face = Font:getFace(font, face.orig_size)
if fb_face.ftface:checkGlyph(charcode) ~= 0 then
rendered_glyph = fb_face.ftface:renderGlyph(charcode, bold)
--DEBUG("fallback to font", font)
break
end
end
end
if not rendered_glyph then
DEBUG("error rendering glyph (charcode=", charcode, ") for face", face)
return
end
glyph = CacheItem:new{rendered_glyph}
glyph.size = glyph[1].bb:getWidth() * glyph[1].bb:getHeight() / 2 + 32
GlyphCache:insert(hash, glyph)
return rendered_glyph
end
function RenderText:getSubTextByWidth(text, face, width, kerning, bold)
local pen_x = 0
local prevcharcode = 0
local char_list = {}
for _, charcode, uchar in utf8Chars(text) do
if pen_x < width then
local glyph = self:getGlyph(face, charcode, bold)
if kerning and prevcharcode then
local kern = face.ftface:getKerning(prevcharcode, charcode)
pen_x = pen_x + kern
end
pen_x = pen_x + glyph.ax
if pen_x <= width then
prevcharcode = charcode
table.insert(char_list, uchar)
else
break
end
end
end
return table.concat(char_list)
end
function RenderText:sizeUtf8Text(x, width, face, text, kerning, bold)
if not text then
DEBUG("sizeUtf8Text called without text");
return
end
-- may still need more adaptive pen placement when kerning,
-- see: http://freetype.org/freetype2/docs/glyphs/glyphs-4.html
local pen_x = 0
local pen_y_top = 0
local pen_y_bottom = 0
local prevcharcode = 0
for _, charcode, uchar in utf8Chars(text) do
if pen_x < (width - x) then
local glyph = self:getGlyph(face, charcode, bold)
if kerning and (prevcharcode ~= 0) then
pen_x = pen_x + (face.ftface):getKerning(prevcharcode, charcode)
end
pen_x = pen_x + glyph.ax
pen_y_top = math.max(pen_y_top, glyph.t)
pen_y_bottom = math.max(pen_y_bottom, glyph.bb:getHeight() - glyph.t)
--DEBUG("ax:"..glyph.ax.." t:"..glyph.t.." r:"..glyph.r.." h:"..glyph.bb:getHeight().." w:"..glyph.bb:getWidth().." yt:"..pen_y_top.." yb:"..pen_y_bottom)
prevcharcode = charcode
end -- if pen_x < (width - x)
end
return { x = pen_x, y_top = pen_y_top, y_bottom = pen_y_bottom}
end
function RenderText:renderUtf8Text(buffer, x, y, face, text, kerning, bold, fgcolor, width)
if not text then
DEBUG("renderUtf8Text called without text");
return 0
end
if not fgcolor then
fgcolor = BlitBuffer.COLOR_BLACK
end
-- may still need more adaptive pen placement when kerning,
-- see: http://freetype.org/freetype2/docs/glyphs/glyphs-4.html
local pen_x = 0
local prevcharcode = 0
local text_width = buffer:getWidth() - x
if width and width < text_width then
text_width = width
end
for _, charcode, uchar in utf8Chars(text) do
if pen_x < text_width then
local glyph = self:getGlyph(face, charcode, bold)
if kerning and (prevcharcode ~= 0) then
pen_x = pen_x + face.ftface:getKerning(prevcharcode, charcode)
end
buffer:colorblitFrom(
glyph.bb,
x + pen_x + glyph.l, y - glyph.t,
0, 0,
glyph.bb:getWidth(), glyph.bb:getHeight(),
fgcolor)
pen_x = pen_x + glyph.ax
prevcharcode = charcode
end -- if pen_x < text_width
end
return pen_x
end
return RenderText
|
fix handling of invalid UTF8 sequences
|
fix handling of invalid UTF8 sequences
external data (and in bad cases our own) can contain invalid byte
sequences in UTF8 strings. A prominent example are file names.
There was a 1-off bug in calculating the allowed length for multibyte
chars, and the iterator was a bit too greedy when stumbling upon
invalid sequences, returning a single "invalid" char for a sequence
up to the point where it became invalid in calculation. Now, we present
one invalid char for the first byte of that sequence and then check
for a valid char starting with the next byte.
|
Lua
|
agpl-3.0
|
apletnev/koreader,ashhher3/koreader,Markismus/koreader,chrox/koreader,chihyang/koreader,Frenzie/koreader,NiLuJe/koreader,houqp/koreader,mwoz123/koreader,poire-z/koreader,robert00s/koreader,Frenzie/koreader,pazos/koreader,poire-z/koreader,ashang/koreader,frankyifei/koreader,koreader/koreader,mihailim/koreader,lgeek/koreader,noname007/koreader,koreader/koreader,NiLuJe/koreader,Hzj-jie/koreader,NickSavage/koreader
|
df3688f56a2d738d0065ab386ffc46e9bd7da2f5
|
src/actions/vstudio/vs2010_rules_xml.lua
|
src/actions/vstudio/vs2010_rules_xml.lua
|
---
-- vs2010_rules_xml.lua
-- Generate a Visual Studio 201x custom rules XML file.
-- Copyright (c) 2014 Jason Perkins and the Premake project
--
premake.vstudio.vs2010.rules.xml = {}
local m = premake.vstudio.vs2010.rules.xml
m.elements = {}
local p = premake
---
-- Entry point; generate the root <ProjectSchemaDefinitions> element.
---
m.elements.project = function(r)
return {
p.xmlUtf8,
m.projectSchemaDefinitions,
m.rule,
m.ruleItem,
m.fileExtension,
m.contentType,
}
end
function m.generate(r)
p.callArray(m.elements.project, r)
p.pop('</ProjectSchemaDefinitions>')
end
---
-- Generate the main <Rule> element.
---
m.elements.rule = function(r)
return {
m.dataSource,
m.categories,
m.inputs,
m.properties,
}
end
function m.rule(r)
p.push('<Rule')
p.w('Name="%s"', r.name)
p.w('PageTemplate="tool"')
p.w('DisplayName="%s"', r.description or r.name)
p.w('Order="200">')
p.callArray(m.elements.rule, r)
p.pop('</Rule>')
end
---
-- Generate the list of categories.
---
function m.categories(r)
local categories = {
[1] = { name="General" },
[2] = { name="Command Line", subtype="CommandLine" },
}
p.push('<Rule.Categories>')
for i = 1, #categories do
m.category(categories[i])
end
p.pop('</Rule.Categories>')
end
function m.category(cat)
local attribs = p.capture(function()
p.push()
p.w('Name="%s"', cat.name)
if cat.subtype then
p.w('Subtype="%s"', cat.subtype)
end
p.pop()
end)
p.push('<Category')
p.outln(attribs .. '>')
p.push('<Category.DisplayName>')
p.w('<sys:String>%s</sys:String>', cat.name)
p.pop('</Category.DisplayName>')
p.pop('</Category>')
end
---
-- Generate the list of property definitions.
---
function m.properties(r)
local defs = r.propertyDefinition
for i = 1, #defs do
local def = defs[i]
if def.kind == "list" then
m.stringListProperty(def)
elseif type(def.values) == "table" then
m.enumProperty(def)
else
m.stringProperty(def)
end
end
end
function m.baseProperty(def)
p.w('Name="%s"', def.name)
p.w('HelpContext="0"')
p.w('DisplayName="%s"', def.display or def.name)
p.w('Description="%s"', def.description or def.display or def.name)
end
function m.enumProperty(def)
p.push('<EnumProperty')
m.baseProperty(def)
local values = def.values
local switches = def.switch or {}
local keys = table.keys(def.values)
table.sort(keys)
for _, key in pairs(keys) do
p.push('<EnumValue')
p.w('Name="%d"', key)
p.w('DisplayName="%s"', values[key])
p.w('Switch="%s" />', switches[key] or values[key])
p.pop()
end
p.pop('</EnumProperty>')
end
function m.stringProperty(def)
p.push('<StringProperty')
m.baseProperty(def)
p.w('Switch="[value]" />')
p.pop()
end
function m.stringListProperty(def)
p.push('<StringListProperty')
m.baseProperty(def)
p.w('Switch="[value]" />')
p.pop()
end
---
-- Implementations of individual elements.
---
function m.contentType(r)
p.push('<ContentType')
p.w('Name="%s"', r.name)
p.w('DisplayName="%s"', r.name)
p.w('ItemType="%s" />', r.name)
p.pop()
end
function m.dataSource(r)
p.push('<Rule.DataSource>')
p.push('<DataSource')
p.w('Persistence="ProjectFile"')
p.w('ItemType="%s" />', r.name)
p.pop()
p.pop('</Rule.DataSource>')
end
function m.fileExtension(r)
p.push('<FileExtension')
p.w('Name="*.XYZ"')
p.w('ContentType="%s" />', r.name)
p.pop()
end
function m.inputs(r)
p.push('<StringListProperty')
p.w('Name="Inputs"')
p.w('Category="Command Line"')
p.w('IsRequired="true"')
p.w('Switch=" ">')
p.push('<StringListProperty.DataSource>')
p.push('<DataSource')
p.w('Persistence="ProjectFile"')
p.w('ItemType="%s"', r.name)
p.w('SourceType="Item" />')
p.pop()
p.pop('</StringListProperty.DataSource>')
p.pop('</StringListProperty>')
end
function m.ruleItem(r)
p.push('<ItemType')
p.w('Name="%s"', r.name)
p.w('DisplayName="%s" />', r.name)
p.pop()
end
function m.projectSchemaDefinitions(r)
p.push('<ProjectSchemaDefinitions xmlns="http://schemas.microsoft.com/build/2009/properties" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:sys="clr-namespace:System;assembly=mscorlib">')
end
|
---
-- vs2010_rules_xml.lua
-- Generate a Visual Studio 201x custom rules XML file.
-- Copyright (c) 2014 Jason Perkins and the Premake project
--
premake.vstudio.vs2010.rules.xml = {}
local m = premake.vstudio.vs2010.rules.xml
m.elements = {}
local p = premake
---
-- Entry point; generate the root <ProjectSchemaDefinitions> element.
---
m.elements.project = function(r)
return {
p.xmlUtf8,
m.projectSchemaDefinitions,
m.rule,
m.ruleItem,
m.fileExtension,
m.contentType,
}
end
function m.generate(r)
p.callArray(m.elements.project, r)
p.pop('</ProjectSchemaDefinitions>')
end
---
-- Generate the main <Rule> element.
---
m.elements.rule = function(r)
return {
m.dataSource,
m.categories,
m.inputs,
m.properties,
}
end
function m.rule(r)
p.push('<Rule')
p.w('Name="%s"', r.name)
p.w('PageTemplate="tool"')
p.w('DisplayName="%s"', r.display or r.name)
p.w('Order="200">')
p.callArray(m.elements.rule, r)
p.pop('</Rule>')
end
---
-- Generate the list of categories.
---
function m.categories(r)
local categories = {
[1] = { name="General" },
[2] = { name="Command Line", subtype="CommandLine" },
}
p.push('<Rule.Categories>')
for i = 1, #categories do
m.category(categories[i])
end
p.pop('</Rule.Categories>')
end
function m.category(cat)
local attribs = p.capture(function()
p.push()
p.w('Name="%s"', cat.name)
if cat.subtype then
p.w('Subtype="%s"', cat.subtype)
end
p.pop()
end)
p.push('<Category')
p.outln(attribs .. '>')
p.push('<Category.DisplayName>')
p.w('<sys:String>%s</sys:String>', cat.name)
p.pop('</Category.DisplayName>')
p.pop('</Category>')
end
---
-- Generate the list of property definitions.
---
function m.properties(r)
local defs = r.propertyDefinition
for i = 1, #defs do
local def = defs[i]
if def.kind == "boolean" then
m.boolProperty(def)
elseif def.kind == "list" then
m.stringListProperty(def)
elseif type(def.values) == "table" then
m.enumProperty(def)
else
m.stringProperty(def)
end
end
end
function m.baseProperty(def, close)
p.w('Name="%s"', def.name)
p.w('HelpContext="0"')
p.w('DisplayName="%s"', def.display or def.name)
p.w('Description="%s"%s', def.description or def.display or def.name, iif(close, ">", ""))
end
function m.boolProperty(def)
p.push('<BoolProperty')
m.baseProperty(def)
if def.switch then
p.w('Switch="%s" />', def.switch)
end
p.pop()
end
function m.enumProperty(def)
p.push('<EnumProperty')
m.baseProperty(def, true)
local values = def.values
local switches = def.switch or {}
local keys = table.keys(def.values)
table.sort(keys)
for _, key in pairs(keys) do
p.push('<EnumValue')
p.w('Name="%d"', key)
if switches[key] then
p.w('DisplayName="%s"', values[key])
p.w('Switch="%s" />', switches[key])
else
p.w('DisplayName="%s" />', values[key])
end
p.pop()
end
p.pop('</EnumProperty>')
end
function m.stringProperty(def)
p.push('<StringProperty')
m.baseProperty(def)
p.w('Switch="[value]" />')
p.pop()
end
function m.stringListProperty(def)
p.push('<StringListProperty')
m.baseProperty(def)
if def.separator then
p.w('Separator="%s"', def.separator)
end
p.w('Switch="[value]" />')
p.pop()
end
---
-- Implementations of individual elements.
---
function m.contentType(r)
p.push('<ContentType')
p.w('Name="%s"', r.name)
p.w('DisplayName="%s"', r.name)
p.w('ItemType="%s" />', r.name)
p.pop()
end
function m.dataSource(r)
p.push('<Rule.DataSource>')
p.push('<DataSource')
p.w('Persistence="ProjectFile"')
p.w('ItemType="%s" />', r.name)
p.pop()
p.pop('</Rule.DataSource>')
end
function m.fileExtension(r)
p.push('<FileExtension')
p.w('Name="*.XYZ"')
p.w('ContentType="%s" />', r.name)
p.pop()
end
function m.inputs(r)
p.push('<StringListProperty')
p.w('Name="Inputs"')
p.w('Category="Command Line"')
p.w('IsRequired="true"')
p.w('Switch=" ">')
p.push('<StringListProperty.DataSource>')
p.push('<DataSource')
p.w('Persistence="ProjectFile"')
p.w('ItemType="%s"', r.name)
p.w('SourceType="Item" />')
p.pop()
p.pop('</StringListProperty.DataSource>')
p.pop('</StringListProperty>')
end
function m.ruleItem(r)
p.push('<ItemType')
p.w('Name="%s"', r.name)
p.w('DisplayName="%s" />', r.name)
p.pop()
end
function m.projectSchemaDefinitions(r)
p.push('<ProjectSchemaDefinitions xmlns="http://schemas.microsoft.com/build/2009/properties" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:sys="clr-namespace:System;assembly=mscorlib">')
end
|
Basic support for boolean properties, some fixes
|
Basic support for boolean properties, some fixes
|
Lua
|
bsd-3-clause
|
LORgames/premake-core,xriss/premake-core,jstewart-amd/premake-core,saberhawk/premake-core,akaStiX/premake-core,resetnow/premake-core,aleksijuvani/premake-core,Tiger66639/premake-core,sleepingwit/premake-core,prapin/premake-core,dcourtois/premake-core,martin-traverse/premake-core,mendsley/premake-core,premake/premake-core,starkos/premake-core,xriss/premake-core,noresources/premake-core,Yhgenomics/premake-core,felipeprov/premake-core,TurkeyMan/premake-core,aleksijuvani/premake-core,Meoo/premake-core,PlexChat/premake-core,Zefiros-Software/premake-core,alarouche/premake-core,tvandijck/premake-core,xriss/premake-core,starkos/premake-core,martin-traverse/premake-core,Meoo/premake-core,dcourtois/premake-core,mandersan/premake-core,lizh06/premake-core,akaStiX/premake-core,bravnsgaard/premake-core,felipeprov/premake-core,TurkeyMan/premake-core,Blizzard/premake-core,jstewart-amd/premake-core,lizh06/premake-core,Zefiros-Software/premake-core,jsfdez/premake-core,alarouche/premake-core,lizh06/premake-core,aleksijuvani/premake-core,starkos/premake-core,tritao/premake-core,dcourtois/premake-core,dcourtois/premake-core,bravnsgaard/premake-core,martin-traverse/premake-core,jstewart-amd/premake-core,starkos/premake-core,grbd/premake-core,PlexChat/premake-core,TurkeyMan/premake-core,premake/premake-core,alarouche/premake-core,prapin/premake-core,mendsley/premake-core,Zefiros-Software/premake-core,tvandijck/premake-core,dcourtois/premake-core,premake/premake-core,noresources/premake-core,Tiger66639/premake-core,akaStiX/premake-core,Blizzard/premake-core,xriss/premake-core,starkos/premake-core,jsfdez/premake-core,xriss/premake-core,kankaristo/premake-core,mendsley/premake-core,akaStiX/premake-core,sleepingwit/premake-core,LORgames/premake-core,grbd/premake-core,mandersan/premake-core,TurkeyMan/premake-core,saberhawk/premake-core,mandersan/premake-core,starkos/premake-core,LORgames/premake-core,mandersan/premake-core,Yhgenomics/premake-core,jstewart-amd/premake-core,mendsley/premake-core,Meoo/premake-core,LORgames/premake-core,Yhgenomics/premake-core,prapin/premake-core,aleksijuvani/premake-core,noresources/premake-core,sleepingwit/premake-core,noresources/premake-core,saberhawk/premake-core,noresources/premake-core,premake/premake-core,prapin/premake-core,CodeAnxiety/premake-core,premake/premake-core,Tiger66639/premake-core,bravnsgaard/premake-core,dcourtois/premake-core,jsfdez/premake-core,tvandijck/premake-core,tvandijck/premake-core,dcourtois/premake-core,LORgames/premake-core,soundsrc/premake-core,CodeAnxiety/premake-core,felipeprov/premake-core,sleepingwit/premake-core,premake/premake-core,PlexChat/premake-core,felipeprov/premake-core,starkos/premake-core,premake/premake-core,martin-traverse/premake-core,bravnsgaard/premake-core,CodeAnxiety/premake-core,mandersan/premake-core,noresources/premake-core,soundsrc/premake-core,alarouche/premake-core,grbd/premake-core,Meoo/premake-core,grbd/premake-core,kankaristo/premake-core,soundsrc/premake-core,jstewart-amd/premake-core,Blizzard/premake-core,Zefiros-Software/premake-core,tvandijck/premake-core,jsfdez/premake-core,sleepingwit/premake-core,tritao/premake-core,soundsrc/premake-core,resetnow/premake-core,Blizzard/premake-core,Blizzard/premake-core,bravnsgaard/premake-core,resetnow/premake-core,CodeAnxiety/premake-core,PlexChat/premake-core,aleksijuvani/premake-core,resetnow/premake-core,mendsley/premake-core,lizh06/premake-core,resetnow/premake-core,Zefiros-Software/premake-core,tritao/premake-core,saberhawk/premake-core,noresources/premake-core,kankaristo/premake-core,CodeAnxiety/premake-core,Yhgenomics/premake-core,kankaristo/premake-core,Blizzard/premake-core,soundsrc/premake-core,tritao/premake-core,Tiger66639/premake-core,TurkeyMan/premake-core
|
d468e3e67b3b9a327a41fe5c1c71754a75dab7ef
|
new/types.lua
|
new/types.lua
|
local base_types = (...) or {}
local BaseType = function(s)
s = tostring(s)
return {
get = function(j)
return 'lua_to'..s..'(L, '..tostring(j)..')', 1
end,
push = function(j) -- must handle arguments (e.g. in virtual callbacks) and return values
return 'lua_push'..s..'(L, '..tostring(j)..')', 1
end,
}
end
local integer_type = {
get = function(j)
return 'lua_tointeger(L, '..tostring(j)..')', 1
end,
push = function(j) -- must handle arguments (e.g. in virtual callbacks) and return values
return 'lua_pushinteger(L, '..tostring(j)..')', 1
end,
test = function(j) -- must handle arguments (e.g. in virtual callbacks) and return values
return 'lqtL_isinteger(L, '..tostring(j)..')', 1
end,
}
local number_type = {
get = function(j)
return 'lua_tonumber(L, '..tostring(j)..')', 1
end,
push = function(j) -- must handle arguments (e.g. in virtual callbacks) and return values
return 'lua_pushnumber(L, '..tostring(j)..')', 1
end,
test = function(j) -- must handle arguments (e.g. in virtual callbacks) and return values
return 'lqtL_isnumber(L, '..tostring(j)..')', 1
end,
}
local integer_type = {
get = function(j)
return 'lua_tointeger(L, '..tostring(j)..')', 1
end,
push = function(j) -- must handle arguments (e.g. in virtual callbacks) and return values
return 'lua_pushinteger(L, '..tostring(j)..')', 1
end,
test = function(j) -- must handle arguments (e.g. in virtual callbacks) and return values
return 'lqtL_isinteger(L, '..tostring(j)..')', 1
end,
}
local bool_type = {
get = function(j)
return 'lua_toboolean(L, '..tostring(j)..')', 1
end,
push = function(j) -- must handle arguments (e.g. in virtual callbacks) and return values
return 'lua_pushboolean(L, '..tostring(j)..')', 1
end,
test = function(j) -- must handle arguments (e.g. in virtual callbacks) and return values
return 'lqtL_isboolean(L, '..tostring(j)..')', 1
end,
}
base_types['char const*'] = {
get = function(j)
return 'lua_tostring(L, '..tostring(j)..')', 1
end,
push = function(j) -- must handle arguments (e.g. in virtual callbacks) and return values
return 'lua_pushstring(L, '..tostring(j)..')', 1
end,
test = function(j)
return 'lqtL_isstring(L, '..tostring(j)..')', 1
end,
}
base_types['char'] = integer_type
base_types['unsigned char'] = integer_type
base_types['int'] = integer_type
base_types['unsigned int'] = integer_type
base_types['short'] = integer_type
base_types['short int'] = integer_type
base_types['unsigned short'] = integer_type
base_types['unsigned short int'] = integer_type
base_types['short unsigned int'] = integer_type
base_types['long'] = integer_type
base_types['unsigned long'] = integer_type
base_types['long int'] = integer_type
base_types['unsigned long int'] = integer_type
base_types['long unsigned int'] = integer_type
base_types['long long'] = integer_type
base_types['unsigned long long'] = integer_type
base_types['long long int'] = integer_type
base_types['unsigned long long int'] = integer_type
base_types['float'] = number_type
base_types['double'] = number_type
base_types['bool'] = bool_type
base_types['QSizeF'] = {
get = function(i) return 'QSizeF(lua_tonumber(L, '..i..'), lua_tonumber(L, '..i..'+1))', 2 end,
push = function(i) return 'lua_pushnumber(L, '..i..'.width()), lua_pushnumber(L, '..i..'.height())', 2 end,
test = function(i) return '(lqtL_isnumber(L, '..i..') && lqtL_isnumber(L, '..i..'+1))', 2 end,
}
base_types['QSizeF const&'] = base_types['QSizeF']
base_types['QSize'] = {
get = function(i) return 'QSize(lua_tointeger(L, '..i..'), lua_tointeger(L, '..i..'+1))', 2 end,
push = function(i) return 'lua_pushinteger(L, '..i..'.width()), lua_pushinteger(L, '..i..'.height())', 2 end,
test = function(i) return '(lqtL_isinteger(L, '..i..') && lqtL_isinteger(L, '..i..'+1))', 2 end,
}
base_types['QSize const&'] = base_types['QSize']
base_types['QPoint'] = {
get = function(i) return 'QPoint(lua_tointeger(L, '..i..'), lua_tointeger(L, '..i..'+1))', 2 end,
push = function(i) return 'lua_pushinteger(L, '..i..'.x()), lua_pushinteger(L, '..i..'.y())', 2 end,
test = function(i) return '(lqtL_isinteger(L, '..i..') && lqtL_isinteger(L, '..i..'+1))', 2 end,
}
base_types['QPoint const&'] = base_types['QPoint']
base_types['QPointF'] = {
get = function(i) return 'QPointF(lua_tointeger(L, '..i..'), lua_tointeger(L, '..i..'+1))', 2 end,
push = function(i) return 'lua_pushinteger(L, '..i..'.x()), lua_pushinteger(L, '..i..'.y())', 2 end,
test = function(i) return '(lqtL_isinteger(L, '..i..') && lqtL_isinteger(L, '..i..'+1))', 2 end,
}
base_types['QPointF const&'] = base_types['QPointF']
base_types['QRect'] = {
get = function(i) return 'QRect(lua_tointeger(L, '..i..'), lua_tointeger(L, '..i..'+1), lua_tointeger(L, '..i..'+2), lua_tointeger(L, '..i..'+3))', 4 end,
push = function(i) return 'lua_pushinteger(L, '..i..'.x()), lua_pushinteger(L, '..i..'.y()), lua_pushinteger(L, '..i..'.width()), lua_pushinteger(L, '..i..'.height())', 4 end,
test = function(i) return '(lqtL_isinteger(L, '..i..') && lqtL_isinteger(L, '..i..'+1) && lqtL_isinteger(L, '..i..'+2) && lqtL_isinteger(L, '..i..'+3))', 4 end,
}
base_types['QRect const&'] = base_types['QRect']
base_types['QRectF'] = {
get = function(i) return 'QRectF(lua_tointeger(L, '..i..'), lua_tointeger(L, '..i..'+1), lua_tointeger(L, '..i..'+2), lua_tointeger(L, '..i..'+3))', 4 end,
push = function(i) return 'lua_pushinteger(L, '..i..'.x()), lua_pushinteger(L, '..i..'.y()), lua_pushinteger(L, '..i..'.width()), lua_pushinteger(L, '..i..'.height())', 4 end,
test = function(i) return '(lqtL_isinteger(L, '..i..') && lqtL_isinteger(L, '..i..'+1) && lqtL_isinteger(L, '..i..'+2) && lqtL_isinteger(L, '..i..'+3))', 4 end,
}
base_types['QRectF const&'] = base_types['QRectF']
return base_types
|
local base_types = (...) or {}
local BaseType = function(s)
s = tostring(s)
return {
get = function(j)
return 'lua_to'..s..'(L, '..tostring(j)..')', 1
end,
push = function(j) -- must handle arguments (e.g. in virtual callbacks) and return values
return 'lua_push'..s..'(L, '..tostring(j)..')', 1
end,
}
end
local integer_type = {
get = function(j)
return 'lua_tointeger(L, '..tostring(j)..')', 1
end,
push = function(j) -- must handle arguments (e.g. in virtual callbacks) and return values
return 'lua_pushinteger(L, '..tostring(j)..')', 1
end,
test = function(j) -- must handle arguments (e.g. in virtual callbacks) and return values
return 'lqtL_isinteger(L, '..tostring(j)..')', 1
end,
}
local number_type = {
get = function(j)
return 'lua_tonumber(L, '..tostring(j)..')', 1
end,
push = function(j) -- must handle arguments (e.g. in virtual callbacks) and return values
return 'lua_pushnumber(L, '..tostring(j)..')', 1
end,
test = function(j) -- must handle arguments (e.g. in virtual callbacks) and return values
return 'lqtL_isnumber(L, '..tostring(j)..')', 1
end,
}
local integer_type = {
get = function(j)
return 'lua_tointeger(L, '..tostring(j)..')', 1
end,
push = function(j) -- must handle arguments (e.g. in virtual callbacks) and return values
return 'lua_pushinteger(L, '..tostring(j)..')', 1
end,
test = function(j) -- must handle arguments (e.g. in virtual callbacks) and return values
return 'lqtL_isinteger(L, '..tostring(j)..')', 1
end,
}
local bool_type = {
get = function(j)
return 'lua_toboolean(L, '..tostring(j)..')', 1
end,
push = function(j) -- must handle arguments (e.g. in virtual callbacks) and return values
return 'lua_pushboolean(L, '..tostring(j)..')', 1
end,
test = function(j) -- must handle arguments (e.g. in virtual callbacks) and return values
return 'lqtL_isboolean(L, '..tostring(j)..')', 1
end,
}
base_types['char const*'] = {
get = function(j)
return 'lua_tostring(L, '..tostring(j)..')', 1
end,
push = function(j) -- must handle arguments (e.g. in virtual callbacks) and return values
return 'lua_pushstring(L, '..tostring(j)..')', 1
end,
test = function(j)
return 'lqtL_isstring(L, '..tostring(j)..')', 1
end,
}
base_types['char'] = integer_type
base_types['unsigned char'] = integer_type
base_types['int'] = integer_type
base_types['unsigned int'] = integer_type
base_types['short'] = integer_type
base_types['short int'] = integer_type
base_types['unsigned short'] = integer_type
base_types['unsigned short int'] = integer_type
base_types['short unsigned int'] = integer_type
base_types['long'] = integer_type
base_types['unsigned long'] = integer_type
base_types['long int'] = integer_type
base_types['unsigned long int'] = integer_type
base_types['long unsigned int'] = integer_type
base_types['long long'] = integer_type
base_types['unsigned long long'] = integer_type
base_types['long long int'] = integer_type
base_types['unsigned long long int'] = integer_type
base_types['float'] = number_type
base_types['double'] = number_type
base_types['bool'] = bool_type
base_types['QSizeF'] = {
get = function(i) return 'QSizeF(lua_tonumber(L, '..i..'), lua_tonumber(L, '..i..'+1))', 2 end,
push = function(i) return 'lua_pushnumber(L, '..i..'.width()), lua_pushnumber(L, '..i..'.height())', 2 end,
test = function(i) return '(lqtL_isnumber(L, '..i..') && lqtL_isnumber(L, '..i..'+1))', 2 end,
}
base_types['QSizeF const&'] = base_types['QSizeF']
base_types['QSize'] = {
get = function(i) return 'QSize(lua_tointeger(L, '..i..'), lua_tointeger(L, '..i..'+1))', 2 end,
push = function(i) return 'lua_pushinteger(L, '..i..'.width()), lua_pushinteger(L, '..i..'.height())', 2 end,
test = function(i) return '(lqtL_isinteger(L, '..i..') && lqtL_isinteger(L, '..i..'+1))', 2 end,
}
base_types['QSize const&'] = base_types['QSize']
base_types['QPoint'] = {
get = function(i) return 'QPoint(lua_tointeger(L, '..i..'), lua_tointeger(L, '..i..'+1))', 2 end,
push = function(i) return 'lua_pushinteger(L, '..i..'.x()), lua_pushinteger(L, '..i..'.y())', 2 end,
test = function(i) return '(lqtL_isinteger(L, '..i..') && lqtL_isinteger(L, '..i..'+1))', 2 end,
}
base_types['QPoint const&'] = base_types['QPoint']
base_types['QPointF'] = {
get = function(i) return 'QPointF(lua_tonumber(L, '..i..'), lua_tonumber(L, '..i..'+1))', 2 end,
push = function(i) return 'lua_pushnumber(L, '..i..'.x()), lua_pushnumber(L, '..i..'.y())', 2 end,
test = function(i) return '(lqtL_isnumber(L, '..i..') && lqtL_isnumber(L, '..i..'+1))', 2 end,
}
base_types['QPointF const&'] = base_types['QPointF']
base_types['QRect'] = {
get = function(i) return 'QRect(lua_tointeger(L, '..i..'), lua_tointeger(L, '..i..'+1), lua_tointeger(L, '..i..'+2), lua_tointeger(L, '..i..'+3))', 4 end,
push = function(i) return 'lua_pushinteger(L, '..i..'.x()), lua_pushinteger(L, '..i..'.y()), lua_pushinteger(L, '..i..'.width()), lua_pushinteger(L, '..i..'.height())', 4 end,
test = function(i) return '(lqtL_isinteger(L, '..i..') && lqtL_isinteger(L, '..i..'+1) && lqtL_isinteger(L, '..i..'+2) && lqtL_isinteger(L, '..i..'+3))', 4 end,
}
base_types['QRect const&'] = base_types['QRect']
base_types['QRectF'] = {
get = function(i) return 'QRectF(lua_tonumber(L, '..i..'), lua_tonumber(L, '..i..'+1), lua_tonumber(L, '..i..'+2), lua_tonumber(L, '..i..'+3))', 4 end,
push = function(i) return 'lua_pushnumber(L, '..i..'.x()), lua_pushnumber(L, '..i..'.y()), lua_pushnumber(L, '..i..'.width()), lua_pushnumber(L, '..i..'.height())', 4 end,
test = function(i) return '(lqtL_isnumber(L, '..i..') && lqtL_isnumber(L, '..i..'+1) && lqtL_isnumber(L, '..i..'+2) && lqtL_isnumber(L, '..i..'+3))', 4 end,
}
base_types['QRectF const&'] = base_types['QRectF']
return base_types
|
fixed Q.*F to use numbers instead of doubles
|
fixed Q.*F to use numbers instead of doubles
|
Lua
|
mit
|
mkottman/lqt,mkottman/lqt
|
3fc0817a2d8f02ad14feead0b13435a27f000ef1
|
src/patch/ui/hooks/joiningroom_enablemods.lua
|
src/patch/ui/hooks/joiningroom_enablemods.lua
|
if _mpPatch and _mpPatch.loaded then
Modding = _mpPatch.hookTable(Modding, {ActivateAllowedDLC = function(...)
_mpPatch.overrideModsFromPreGame()
return Modding._super.ActivateAllowedDLC(...)
end})
local function enterLobby()
UIManager:QueuePopup(Controls.StagingRoomScreen, PopupPriority.StagingScreen)
UIManager:DequeuePopup(ContextPtr)
end
local function joinFailed(message)
Events.FrontEndPopup.CallImmediate(message)
g_joinFailed = true
Matchmaking.LeaveMultiplayerGame()
UIManager:DequeuePopup(ContextPtr)
end
function OnConnectionCompete()
if not Matchmaking.IsHost() then
if _mpPatch.isModding then
local missingModList = {}
_mpPatch.debugPrint("Enabled mods for room:")
for _, mod in ipairs(decodeModsList()) do
local missingText = ""
if not Modding.IsModInstalled(mod.ID, mod.Version) then
table.insert(missingModList, mod.Name)
missingText = " (is missing)"
end
_mpPatch.debugPrint("- "..mod.Name..missingText)
end
-- TODO: Check for
if #missingModList > 0 then
local messageTable = {Locale.Lookup("TXT_KEY_MPPATCH_MOD_MISSING")}
for _, name in ipairs(missingModList) do
table.insert(messageTable, "[ICON_BULLET]"..v.Name:gsub("%[", "("):gsub("%]", ")"))
end
joinFailed(table.concat(messageTable, "[NEWLINE]"))
return
end
_mpPatch.debugPrint("Activating mods and DLC...")
Modding.ActivateAllowedDLC()
end
enterLobby()
end
end
end
|
if _mpPatch and _mpPatch.loaded then
Modding = _mpPatch.hookTable(Modding, {ActivateAllowedDLC = function(...)
_mpPatch.overrideModsFromPreGame()
return Modding._super.ActivateAllowedDLC(...)
end})
local function enterLobby()
UIManager:QueuePopup(Controls.StagingRoomScreen, PopupPriority.StagingScreen)
UIManager:DequeuePopup(ContextPtr)
end
local function joinFailed(message)
Events.FrontEndPopup.CallImmediate(message)
g_joinFailed = true
Matchmaking.LeaveMultiplayerGame()
UIManager:DequeuePopup(ContextPtr)
end
function OnConnectionCompete()
if not Matchmaking.IsHost() then
if _mpPatch.isModding then
local missingModList = {}
_mpPatch.debugPrint("Enabled mods for room:")
for _, mod in ipairs(_mpPatch.decodeModsList()) do
local missingText = ""
if not Modding.IsModInstalled(mod.ID, mod.Version) then
table.insert(missingModList, mod.Name)
missingText = " (is missing)"
end
_mpPatch.debugPrint("- "..mod.Name..missingText)
end
-- TODO: Check for DLCs/mod compatibility
if #missingModList > 0 then
local messageTable = {Locale.Lookup("TXT_KEY_MPPATCH_MOD_MISSING")}
for _, name in ipairs(missingModList) do
table.insert(messageTable, "[ICON_BULLET]"..v.Name:gsub("%[", "("):gsub("%]", ")"))
end
joinFailed(table.concat(messageTable, "[NEWLINE]"))
return
end
_mpPatch.debugPrint("Activating mods and DLC...")
Modding.ActivateAllowedDLC()
end
enterLobby()
end
end
end
|
Fix joiningroom.
|
Fix joiningroom.
|
Lua
|
mit
|
Lymia/MPPatch,Lymia/MPPatch,Lymia/MultiverseModManager,Lymia/MPPatch,Lymia/MPPatch,Lymia/CivV_Mod2DLC,Lymia/MultiverseModManager
|
550ea7ca579b2b7d183bf84eab58ed57ce519af4
|
Peripherals/WEB/webthread.lua
|
Peripherals/WEB/webthread.lua
|
require("love.thread")
local to_channel = love.thread.getChannel("To_WebThread")
local from_channel = love.thread.getChannel("From_WebThread")
local request = require("Engine.luajit-request")
local json = require("Engine.JSON")
while true do
local req = to_channel:demand()
if type(req) == "table" then
local url = req[1]
local args = json:decode(req[2])
local out, errorcode, errorstr, errline = request.send(url,args)
from_channel:push(json:encode({ url, out, errorcode, errorstr, errline }))
end
end
|
require("love.thread")
local to_channel = love.thread.getChannel("To_WebThread")
local from_channel = love.thread.getChannel("From_WebThread")
local ok, request = pcall(require,"Engine.luajit-request")
print("Thread failed: "..tostring(request))
if not ok then return end
local json = require("Engine.JSON")
while true do
local req = to_channel:demand()
if type(req) == "table" then
local url = req[1]
local args = json:decode(req[2])
local out, errorcode, errorstr, errline = request.send(url,args)
from_channel:push(json:encode({ url, out, errorcode, errorstr, errline }))
end
end
|
Bugfix
|
Bugfix
|
Lua
|
mit
|
RamiLego4Game/LIKO-12
|
13929d2ce88cb72fe1aef0cbdc33aeb1019bd2ec
|
tests/lib_specs/inheritance.lua
|
tests/lib_specs/inheritance.lua
|
local Class = require '30log'
context('Derivation (Inheritance)',function()
local Window
before(function()
Window = Class { width = 100, height = 100 }
function Window:setSize(w,h) self.width, self.height = w,h end
end)
context('Class can be derived from a superclass',function()
test('Via "extends()" method',function()
local Frame = Window:extends()
assert_equal(type(Frame),'table')
end)
test('With extra-arguments passed to method "extends()" as a table',function()
local Frame = Window:extends {ID = 1}
assert_equal(Frame.ID,1)
assert_equal(Frame.width,100)
assert_equal(Frame.height,100)
end)
end)
context('A derived class still points to its superclass',function()
test('Via its "super" key',function()
local Frame = Window:extends()
assert_equal(Frame.super,Window)
end)
test('Via "getmetatable()" function',function()
local Frame = Window:extends()
assert_equal(getmetatable(Frame),Window)
end)
end)
context('A derived class',function()
test('can instantiate objects',function()
local Frame = Window:extends()
function Frame:setSize(size) self.width, self.height = size,size end
local app = Frame()
local app2 = Frame:new()
assert_equal(type(app),'table')
assert_equal(type(app2),'table')
end)
test('shares its superclass attributes',function()
local Frame = Window:extends()
assert_equal(Frame.width,100)
assert_equal(Frame.height,100)
end)
test('shares its superclass methods',function()
local Frame = Window:extends()
Frame:setSize(15,15)
assert_equal(type(Frame.setSize),'function')
assert_equal(Frame.width,15)
assert_equal(Frame.height,15)
end)
test('can reimplement its superclass methods',function()
local Frame = Window:extends()
function Frame:setSize(size) self.width, self.height = size,size end
Frame:setSize(30)
assert_equal(Frame.width,30)
assert_equal(Frame.height,30)
end)
test('Yet, it still has access to the original superclass method',function()
local Frame = Window:extends()
function Frame:setSize(size) self.width, self.height = size,size end
Frame.super.setSize(Frame,50,55)
assert_equal(Frame.width,50)
assert_equal(Frame.height,55)
end)
end)
context('In a single inheritance model', function()
local A, B, C, D
before(function()
A = Class()
function A.__init(instance,a)
instance.a = a
end
B = A:extends()
function B.__init(instance, a, b)
B.super.__init(instance, a)
instance.b = b
end
C = B:extends()
function C.__init(instance, a, b, c)
C.super.__init(instance,a, b)
instance.c = c
end
D = C:extends()
function D.__init(instance, a, b, c, d)
D.super.__init(instance,a, b, c)
instance.d = d
end
end)
test('__init() class constructor can chain', function()
local a = A(1)
local b = B(1,2)
local c = C(1,2,3)
local d = D(1,2,3,4)
assert_equal(a.a,1)
assert_equal(b.a,1)
assert_equal(b.b,2)
assert_equal(c.a,1)
assert_equal(c.b,2)
assert_equal(c.c,3)
assert_equal(d.a,1)
assert_equal(d.b,2)
assert_equal(d.c,3)
assert_equal(d.d,4)
end)
end)
end)
|
local Class = require '30log'
context('Derivation (Inheritance)',function()
local Window
before(function()
Window = Class { width = 100, height = 100 }
function Window:setSize(w,h) self.width, self.height = w,h end
end)
context('Class can be derived from a superclass',function()
test('Via "extends()" method',function()
local Frame = Window:extends()
assert_equal(type(Frame),'table')
end)
test('With extra-arguments passed to method "extends()" as a table',function()
local Frame = Window:extends {ID = 1}
assert_equal(Frame.ID,1)
assert_equal(Frame.width,100)
assert_equal(Frame.height,100)
end)
end)
context('A derived class still points to its superclass',function()
test('Via its "super" key',function()
local Frame = Window:extends()
assert_equal(Frame.super,Window)
end)
test('Via "getmetatable()" function',function()
local Frame = Window:extends()
assert_equal(getmetatable(Frame),Window)
end)
end)
context('A derived class',function()
test('can instantiate objects',function()
local Frame = Window:extends()
function Frame:setSize(size) self.width, self.height = size,size end
local app = Frame()
local app2 = Frame:new()
assert_equal(type(app),'table')
assert_equal(type(app2),'table')
end)
test('shares its superclass attributes',function()
local Frame = Window:extends()
assert_equal(Frame.width,100)
assert_equal(Frame.height,100)
end)
test('shares its superclass methods',function()
local Frame = Window:extends()
Frame:setSize(15,15)
assert_equal(type(Frame.setSize),'function')
assert_equal(Frame.width,15)
assert_equal(Frame.height,15)
end)
test('can reimplement its superclass methods',function()
local Frame = Window:extends()
function Frame:setSize(size) self.width, self.height = size,size end
Frame:setSize(30)
assert_equal(Frame.width,30)
assert_equal(Frame.height,30)
end)
test('Yet, it still has access to the original superclass method',function()
local Frame = Window:extends()
function Frame:setSize(size) self.width, self.height = size,size end
Frame.super.setSize(Frame,50,55)
assert_equal(Frame.width,50)
assert_equal(Frame.height,55)
end)
end)
context('In a single inheritance model', function()
local A, B, C, D
before(function()
A = Class()
function A:__init(a)
self.a = a
end
B = A:extends()
function B:__init(a, b)
B.super.__init(self, a)
self.b = b
end
C = B:extends()
function C:__init(a, b, c)
C.super.__init(self, a, b)
self.c = c
end
D = C:extends()
function D:__init(a, b, c, d)
D.super.__init(self, a, b, c)
self.d = d
end
end)
test('__init() class constructor can chain', function()
local a = A(1)
local b = B(1,2)
local c = C(1,2,3)
local d = D(1,2,3,4)
assert_equal(a.a,1)
assert_equal(b.a,1)
assert_equal(b.b,2)
assert_equal(c.a,1)
assert_equal(c.b,2)
assert_equal(c.c,3)
assert_equal(d.a,1)
assert_equal(d.b,2)
assert_equal(d.c,3)
assert_equal(d.d,4)
end)
end)
end)
|
Added call to methods inside initializer spec Fixed indentation to 2-whitespaces
|
Added call to methods inside initializer spec
Fixed indentation to 2-whitespaces
|
Lua
|
mit
|
tizzybec/30log,aubergine10/30log
|
505409a2284d82bd58b7f335fa91136e981ad670
|
entities/securitycam.lua
|
entities/securitycam.lua
|
local SECURITYCAM_REALIZE_TIME=4
local function newSecurityCam (x, y, radius)
local cam = {
x = x,
y = y,
alert = {},
alerted = false,
alertness = 0.,
testingfor = 1,
radius = radius,
drawradius = 200,
beep_timer = nil,
player_alert_start= {},
detectortype = "securitycam",
}
Signals.register ('win', function()
if cam.beep_timer ~= nil then
Timer.cancel (cam.beep_timer)
cam.beep_timer = nil
end
end)
function cam:update(dt, players, world)
if self.alerted then
self.alertness = math.min (1., self.alertness + dt * GVAR.alert_increase_rate)
else
self.alertness = math.max (0., self.alertness - dt * GVAR.alert_decrease_rate)
end
local function callback(fixture, x, y, xn, yn, fraction)
if (fixture:getUserData() == "chain") then -- you can't hide behind your chains
return -1
end
if (fixture:getUserData() == "player") then
return -1
end
-- we hit something bad
self.alert[self.testingfor] = false
return 0 -- immediately cancel the ray
end
for k,player in pairs(players) do
-- cast rays
local visible = ((player.body:getX()-self.x)^2+(player.body:getY()-self.y)^2 < (self.radius+player.radius)^2)
if visible then
self.alert[k] = true
self.testingfor = k
world:rayCast(self.x, self.y, player.body:getX(), player.body:getY(), callback)
visible = self.alert[k]
end
-- emit signals
if visible and not self.player_alert_start[player] then
Signals.emit ('alert-start', self, player)
self.player_alert_start[player] = love.timer.getTime()
self.beep_timer = Timer.addPeriodic (0.4, function ()
Sound.static.beep2:play()
end)
end
if not visible and self.player_alert_start[player] then
Signals.emit ('alert-stop', self, player)
self.player_alert_start[player] = nil
end
end
if next (self.player_alert_start) then
self.alerted = true
else
if self.beep_timer then
Timer.cancel (self.beep_timer)
end
self.alerted = false
end
end
function cam:draw()
love.graphics.setColor(255,(1. - self.alertness) * 255, 0, 128)
love.graphics.circle("fill", self.x, self.y, self.drawradius)
if self.alerted then
love.graphics.setColor (255, 0, 0, 128)
love.graphics.setLineWidth (10.)
love.graphics.circle("line", self.x, self.y, self.radius + math.sin(love.timer.getTime() * 10) * 10)
end
end
return cam
end
return newSecurityCam
|
local SECURITYCAM_REALIZE_TIME=4
local function newSecurityCam (x, y, radius)
local cam = {
x = x,
y = y,
alert = {},
alerted = false,
alertness = 0.,
testingfor = 1,
radius = radius,
drawradius = 200,
beep_timer = nil,
player_alert_start= {},
detectortype = "securitycam",
}
Signals.register ('win', function()
if cam.beep_timer ~= nil then
Timer.cancel (cam.beep_timer)
cam.beep_timer = nil
end
end)
function cam:update(dt, players, world)
if self.alerted then
self.alertness = math.min (1., self.alertness + dt * GVAR.alert_increase_rate)
else
self.alertness = math.max (0., self.alertness - dt * GVAR.alert_decrease_rate)
end
local function callback(fixture, x, y, xn, yn, fraction)
if (fixture:getUserData() == "chain") then -- you can't hide behind your chains
return -1
end
if (fixture:getUserData() == "player") then
return -1
end
-- we hit something bad
self.alert[self.testingfor] = false
return 0 -- immediately cancel the ray
end
for k,player in pairs(players) do
-- cast rays
local visible = ((player.body:getX()-self.x)^2+(player.body:getY()-self.y)^2 < (self.radius+player.radius)^2)
if visible then
self.alert[k] = true
self.testingfor = k
world:rayCast(self.x, self.y, player.body:getX(), player.body:getY(), callback)
visible = self.alert[k]
end
-- emit signals
if visible and not self.player_alert_start[player] then
Signals.emit ('alert-start', self, player)
self.player_alert_start[player] = love.timer.getTime()
if not self.beep_timer then
self.beep_timer = Timer.addPeriodic (0.4, function ()
Sound.static.beep2:play()
end)
end
end
if not visible and self.player_alert_start[player] then
Signals.emit ('alert-stop', self, player)
self.player_alert_start[player] = nil
end
end
if next (self.player_alert_start) then
self.alerted = true
else
self.alerted = false
if self.beep_timer then
Timer.cancel (self.beep_timer)
self.beep_timer = nil
end
end
end
function cam:draw()
love.graphics.setColor(255,(1. - self.alertness) * 255, 0, 128)
love.graphics.circle("fill", self.x, self.y, self.drawradius)
if self.alerted then
love.graphics.setColor (255, 0, 0, 128)
love.graphics.setLineWidth (10.)
love.graphics.circle("line", self.x, self.y, self.radius + math.sin(love.timer.getTime() * 10) * 10)
end
end
return cam
end
return newSecurityCam
|
fixed beep
|
fixed beep
|
Lua
|
apache-2.0
|
martinfelis/ggj15
|
084e01a6ac7961fa650aba9cdc06502e4bd88b2c
|
xmake/modules/detect/tools/nvcc/has_flags.lua
|
xmake/modules/detect/tools/nvcc/has_flags.lua
|
--!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-2020, TBOOX Open Source Group.
--
-- @author ruki
-- @file has_flags.lua
--
-- imports
import("lib.detect.cache")
import("core.language.language")
-- is linker?
function _islinker(flags, opt)
-- the flags is "-Wl,<arg>" or "-Xlinker <arg>"?
local flags_str = table.concat(flags, " ")
if flags_str:startswith("-Wl,") or flags_str:startswith("-Xlinker ") then
return true
end
-- the tool kind is ld or sh?
local toolkind = opt.toolkind or ""
return toolkind == "ld" or toolkind == "sh" or toolkind:endswith("-ld") or toolkind:endswith("-sh")
end
-- try running
function _try_running(...)
local argv = {...}
local errors = nil
return try { function () os.runv(unpack(argv)); return true end, catch { function (errs) errors = (errs or ""):trim() end }}, errors
end
-- attempt to check it from the argument list
function _check_from_arglist(flags, opt, islinker)
-- check for the builtin flags
local builtin_flags = {["-code"] = true,
["--gpu-code"] = true,
["-gencode"] = true,
["--generate-code"] = true,
["-arch"] = true,
["--gpu-architecture"] = true,
["-cudart=none"] = true,
["--cudart=none"] = true}
if builtin_flags[flags[1]] then
return true
end
-- check for the builtin flag=value
local cudart_flags = {none = true, shared = true, static = true}
local builtin_flags_pair = {["-cudart"] = cudart_flags,
["--cudart"] = cudart_flags}
if #flags > 1 and builtin_flags_pair[flags[1]] and builtin_flags_pair[flags[1]][flags[2]] then
return true
end
-- check from the `--help` menu, only for linker
if islinker or #flags > 1 then
return
end
-- make cache key
local key = "detect.tools.nvcc.has_flags"
-- make flags key
local flagskey = opt.program .. "_" .. (opt.programver or "")
-- load cache
local cacheinfo = cache.load(key)
-- get all flags from argument list
local allflags = cacheinfo[flagskey]
if not allflags then
-- get argument list
allflags = {}
local arglist = os.iorunv(opt.program, {"--help"})
if arglist then
for arg in arglist:gmatch("%s+(%-[%-%a%d]+)%s+") do
allflags[arg] = true
end
end
-- save cache
cacheinfo[flagskey] = allflags
cache.save(key, cacheinfo)
end
-- ok?
return allflags[flags[1]]
end
-- try running to check flags
function _check_try_running(flags, opt, islinker)
-- make an stub source file
local sourcefile = path.join(os.tmpdir(), "detect", "nvcc_has_flags.cu")
if not os.isfile(sourcefile) then
io.writefile(sourcefile, "int main(int argc, char** argv)\n{return 0;}")
end
local args = table.join("-o", os.nuldev(), sourcefile)
if not islinker then
table.insert(args, 1, "-c")
end
if flags[1] ~= "-allow-unsupported-compiler" then
local allow_unsupported_compiler = main({"-allow-unsupported-compiler"}, opt)
if allow_unsupported_compiler then
table.insert(args, 1, "-allow-unsupported-compiler")
end
end
-- check flags
return _try_running(opt.program, table.join(flags, args))
end
-- has_flags(flags)?
--
-- @param opt the argument options, e.g. {toolname = "", program = "", programver = "", toolkind = "cu"}
--
-- @return true or false
--
function main(flags, opt)
-- is linker?
local islinker = _islinker(flags, opt)
-- attempt to check it from the argument list
if _check_from_arglist(flags, opt, islinker) then
return true
end
-- try running to check it
return _check_try_running(flags, opt, islinker)
end
|
--!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-2020, TBOOX Open Source Group.
--
-- @author ruki
-- @file has_flags.lua
--
-- imports
import("lib.detect.cache")
import("core.language.language")
-- is linker?
function _islinker(flags, opt)
-- the flags is "-Wl,<arg>" or "-Xlinker <arg>"?
local flags_str = table.concat(flags, " ")
if flags_str:startswith("-Wl,") or flags_str:startswith("-Xlinker ") then
return true
end
-- the tool kind is ld or sh?
local toolkind = opt.toolkind or ""
return toolkind == "ld" or toolkind == "sh" or toolkind:endswith("-ld") or toolkind:endswith("-sh")
end
-- try running
function _try_running(...)
local argv = {...}
local errors = nil
return try { function () os.runv(unpack(argv)); return true end, catch { function (errs) errors = (errs or ""):trim() end }}, errors
end
-- attempt to check it from the argument list
function _check_from_arglist(flags, opt, islinker)
-- check for the builtin flags
local builtin_flags = {["-code"] = true,
["--gpu-code"] = true,
["-gencode"] = true,
["--generate-code"] = true,
["-arch"] = true,
["--gpu-architecture"] = true,
["-cudart=none"] = true,
["--cudart=none"] = true}
if builtin_flags[flags[1]] then
return true
end
-- check for the builtin flag=value
local cudart_flags = {none = true, shared = true, static = true}
local builtin_flags_pair = {["-cudart"] = cudart_flags,
["--cudart"] = cudart_flags}
if #flags > 1 and builtin_flags_pair[flags[1]] and builtin_flags_pair[flags[1]][flags[2]] then
return true
end
-- check from the `--help` menu, only for linker
if islinker or #flags > 1 then
return
end
-- make cache key
local key = "detect.tools.nvcc.has_flags"
-- make flags key
local flagskey = opt.program .. "_" .. (opt.programver or "")
-- load cache
local cacheinfo = cache.load(key)
-- get all flags from argument list
local allflags = cacheinfo[flagskey]
if not allflags then
-- get argument list
allflags = {}
local arglist = os.iorunv(opt.program, {"--help"})
if arglist then
for arg in arglist:gmatch("%s+(%-[%-%a%d]+)%s+") do
allflags[arg] = true
end
end
-- save cache
cacheinfo[flagskey] = allflags
cache.save(key, cacheinfo)
end
-- ok?
return allflags[flags[1]]
end
-- try running to check flags
function _check_try_running(flags, opt, islinker)
-- make an stub source file
local sourcefile = path.join(os.tmpdir(), "detect", "nvcc_has_flags.cu")
if not os.isfile(sourcefile) then
io.writefile(sourcefile, "int main(int argc, char** argv)\n{return 0;}")
end
local args = table.join("-o", os.nuldev(), sourcefile)
if not islinker then
table.insert(args, 1, "-c")
end
-- avoid recursion
if flags[1] ~= "-allow-unsupported-compiler" then
-- add -allow-unsupported-compiler if supported to suppress error of unsupported compiler,
-- which caused all checks failed.
local allow_unsupported_compiler = _has_flags({"-allow-unsupported-compiler"}, opt)
if allow_unsupported_compiler then
table.insert(args, 1, "-allow-unsupported-compiler")
end
end
-- check flags
return _try_running(opt.program, table.join(flags, args))
end
-- has_flags(flags)?
--
-- @param opt the argument options, e.g. {toolname = "", program = "", programver = "", toolkind = "cu"}
--
-- @return true or false
--
function _has_flags(flags, opt)
-- is linker?
local islinker = _islinker(flags, opt)
-- attempt to check it from the argument list
if _check_from_arglist(flags, opt, islinker) then
return true
end
-- try running to check it
return _check_try_running(flags, opt, islinker)
end
function main(...)
return _has_flags(...)
end
|
fix code style
|
fix code style
|
Lua
|
apache-2.0
|
waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake
|
addcea8e1d12bcec4188c8b6533180d23275e0f3
|
twitpic.lua
|
twitpic.lua
|
local url_count = 0
local tries = 0
local item_type = os.getenv('item_type')
local item_value = os.getenv('item_value')
read_file = function(file)
if file then
local f = assert(io.open(file))
local data = f:read("*all")
f:close()
return data
else
return ""
end
end
wget.callbacks.download_child_p = function(urlpos, parent, depth, start_url_parsed, iri, verdict, reason)
local url = urlpos["url"]["url"]
local ishtml = urlpos["link_expect_html"]
local parenturl = parent["url"]
-- Chfoo - Can I use "local html = nil" in "wget.callbacks.download_child_p"?
local html = nil
-- Skip redirect from mysite.verizon.net and members.bellatlantic.net
if item_type == "image" then
if string.match(url, "cloudfront%.net") or
string.match(url, "twimg%.com") or
string.match(url, "amazonaws%.com") then
return verdict
elseif string.match(url, "advertise%.twitpic%.com") then
return false
elseif string.match(url, "/[^:]+:[^/]+/") then
return false
elseif string.match(url, '/[^"]+"[^/]+/') then
return false
elseif not string.match(url, "twitpic%.com") then
if ishtml ~= 1 then
return verdict
end
elseif not string.match(url, item_value) then
return false
else
return false
end
elseif item_type == "user" then
if string.match(url, "cloudfront%.net") then
return true
elseif string.match(url, "twimg%.com") then
return true
elseif string.match(url, "amazonaws%.com") then
return true
elseif string.match(url, "advertise%.twitpic%.com") then
return false
elseif not string.match(url, "twitpic%.com") and
ishtml ~= 1 then
return true
elseif string.match(url, item_value) then
return true
else
return false
end
elseif item_type == "tag" then
if string.match(url, "cloudfront%.net") then
return true
elseif string.match(url, "twimg%.com") then
return true
elseif string.match(url, "amazonaws%.com") then
return true
elseif string.match(url, "advertise%.twitpic%.com") then
return false
-- Check if we are on the last page of a tag
elseif string.match(url, "twitpic%.com/tag/[^%?]+%?page=[0-9]+") then
if not html then
html = read_file(file)
end
if not string.match(url, '<div class="user%-photo%-content right">') then
return false
else
return true
end
elseif not string.match(url, "twitpic%.com") and
ishtml ~= 1 then
return true
elseif string.match(url, item_value) then
return true
else
return false
end
else
return verdict
end
end
wget.callbacks.httploop_result = function(url, err, http_stat)
-- NEW for 2014: Slightly more verbose messages because people keep
-- complaining that it's not moving or not working
local status_code = http_stat["statcode"]
url_count = url_count + 1
io.stdout:write(url_count .. "=" .. status_code .. " " .. url["url"] .. ". \r")
io.stdout:flush()
if status_code >= 500 or
(status_code >= 400 and status_code ~= 404 and status_code ~= 403) then
if string.match(url["host"], "twitpic%.com") or
string.match(url["host"], "cloudfront%.net") or
string.match(url["host"], "twimg%.com") or
string.match(url["host"], "amazonaws%.com") then
io.stdout:write("\nServer returned "..http_stat.statcode.." for " .. url["url"] .. ". Sleeping.\n")
io.stdout:flush()
os.execute("sleep 10")
tries = tries + 1
if tries >= 5 then
io.stdout:write("\nI give up...\n")
io.stdout:flush()
return wget.actions.NOTHING
else
return wget.actions.CONTINUE
end
else
io.stdout:write("\nServer returned "..http_stat.statcode.." for " .. url["url"] .. ". Sleeping.\n")
io.stdout:flush()
os.execute("sleep 10")
tries = tries + 1
if tries >= 5 then
io.stdout:write("\nI give up...\n")
io.stdout:flush()
return wget.actions.NOTHING
else
return wget.actions.CONTINUE
end
end
elseif status_code == 0 then
io.stdout:write("\nServer returned "..http_stat.statcode.." for " .. url["url"] .. ". Sleeping.\n")
io.stdout:flush()
os.execute("sleep 10")
tries = tries + 1
if tries >= 5 then
io.stdout:write("\nI give up...\n")
io.stdout:flush()
return wget.actions.ABORT
else
return wget.actions.CONTINUE
end
end
tries = 0
-- We're okay; sleep a bit (if we have to) and continue
-- local sleep_time = 0.1 * (math.random(1000, 2000) / 100.0)
local sleep_time = 0
-- if string.match(url["host"], "cdn") or string.match(url["host"], "media") then
-- -- We should be able to go fast on images since that's what a web browser does
-- sleep_time = 0
-- end
if sleep_time > 0.001 then
os.execute("sleep " .. sleep_time)
end
return wget.actions.NOTHING
end
|
local url_count = 0
local tries = 0
local item_type = os.getenv('item_type')
local item_value = os.getenv('item_value')
read_file = function(file)
if file then
local f = assert(io.open(file))
local data = f:read("*all")
f:close()
return data
else
return ""
end
end
wget.callbacks.download_child_p = function(urlpos, parent, depth, start_url_parsed, iri, verdict, reason)
local url = urlpos["url"]["url"]
local ishtml = urlpos["link_expect_html"]
local parenturl = parent["url"]
-- Chfoo - Can I use "local html = nil" in "wget.callbacks.download_child_p"?
local html = nil
-- Skip redirect from mysite.verizon.net and members.bellatlantic.net
if item_type == "image" then
if string.match(url, "cloudfront%.net") or
string.match(url, "twimg%.com") or
string.match(url, "amazonaws%.com") then
return verdict
elseif string.match(url, "advertise%.twitpic%.com") then
return false
elseif string.match(url, "/[^:]+:[^/]+/") then
return false
elseif string.match(url, '/[^"]+"[^/]+/') then
return false
elseif not string.match(url, "twitpic%.com") then
if ishtml ~= 1 then
return verdict
end
elseif not string.match(url, item_value) then
if ishtml == 1 then
return false
else
return true
end
else
return false
end
elseif item_type == "user" then
if string.match(url, "cloudfront%.net") then
return true
elseif string.match(url, "twimg%.com") then
return true
elseif string.match(url, "amazonaws%.com") then
return true
elseif string.match(url, "advertise%.twitpic%.com") then
return false
elseif not string.match(url, "twitpic%.com") and
ishtml ~= 1 then
return true
elseif string.match(url, item_value) then
return true
else
return false
end
elseif item_type == "tag" then
if string.match(url, "cloudfront%.net") then
return true
elseif string.match(url, "twimg%.com") then
return true
elseif string.match(url, "amazonaws%.com") then
return true
elseif string.match(url, "advertise%.twitpic%.com") then
return false
-- Check if we are on the last page of a tag
elseif string.match(url, "twitpic%.com/tag/[^%?]+%?page=[0-9]+") then
if not html then
html = read_file(file)
end
if not string.match(url, '<div class="user%-photo%-content right">') then
return false
else
return true
end
elseif not string.match(url, "twitpic%.com") and
ishtml ~= 1 then
return true
elseif string.match(url, item_value) then
return true
else
return false
end
else
return verdict
end
end
wget.callbacks.httploop_result = function(url, err, http_stat)
-- NEW for 2014: Slightly more verbose messages because people keep
-- complaining that it's not moving or not working
local status_code = http_stat["statcode"]
url_count = url_count + 1
io.stdout:write(url_count .. "=" .. status_code .. " " .. url["url"] .. ". \r")
io.stdout:flush()
if status_code >= 500 or
(status_code >= 400 and status_code ~= 404 and status_code ~= 403) then
if string.match(url["host"], "twitpic%.com") or
string.match(url["host"], "cloudfront%.net") or
string.match(url["host"], "twimg%.com") or
string.match(url["host"], "amazonaws%.com") then
io.stdout:write("\nServer returned "..http_stat.statcode.." for " .. url["url"] .. ". Sleeping.\n")
io.stdout:flush()
os.execute("sleep 10")
tries = tries + 1
if tries >= 5 then
io.stdout:write("\nI give up...\n")
io.stdout:flush()
return wget.actions.NOTHING
else
return wget.actions.CONTINUE
end
else
io.stdout:write("\nServer returned "..http_stat.statcode.." for " .. url["url"] .. ". Sleeping.\n")
io.stdout:flush()
os.execute("sleep 10")
tries = tries + 1
if tries >= 5 then
io.stdout:write("\nI give up...\n")
io.stdout:flush()
return wget.actions.NOTHING
else
return wget.actions.CONTINUE
end
end
elseif status_code == 0 then
io.stdout:write("\nServer returned "..http_stat.statcode.." for " .. url["url"] .. ". Sleeping.\n")
io.stdout:flush()
os.execute("sleep 10")
tries = tries + 1
if tries >= 5 then
io.stdout:write("\nI give up...\n")
io.stdout:flush()
return wget.actions.ABORT
else
return wget.actions.CONTINUE
end
end
tries = 0
-- We're okay; sleep a bit (if we have to) and continue
-- local sleep_time = 0.1 * (math.random(1000, 2000) / 100.0)
local sleep_time = 0
-- if string.match(url["host"], "cdn") or string.match(url["host"], "media") then
-- -- We should be able to go fast on images since that's what a web browser does
-- sleep_time = 0
-- end
if sleep_time > 0.001 then
os.execute("sleep " .. sleep_time)
end
return wget.actions.NOTHING
end
|
twitpic.lua: fix to download videos
|
twitpic.lua: fix to download videos
|
Lua
|
unlicense
|
ArchiveTeam/twitpic-grab,ArchiveTeam/twitpic-grab,ArchiveTeam/twitpic-grab
|
13ecd9088e5ee2364f89af93f711aad4bb9a23b2
|
core/modulemanager.lua
|
core/modulemanager.lua
|
-- Prosody IM v0.2
-- Copyright (C) 2008 Matthew Wild
-- Copyright (C) 2008 Waqas Hussain
--
-- This program is free software; you can redistribute it and/or
-- modify it under the terms of the GNU General Public License
-- as published by the Free Software Foundation; either version 2
-- of the License, or (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program; if not, write to the Free Software
-- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
--
local plugin_dir = CFG_PLUGINDIR or "./plugins/";
local logger = require "util.logger";
local log = logger.init("modulemanager");
local addDiscoInfoHandler = require "core.discomanager".addDiscoInfoHandler;
local eventmanager = require "core.eventmanager";
local config = require "core.configmanager";
local multitable_new = require "util.multitable".new;
local loadfile, pcall = loadfile, pcall;
local setmetatable, setfenv, getfenv = setmetatable, setfenv, getfenv;
local pairs, ipairs = pairs, ipairs;
local t_insert = table.insert;
local type = type;
local tostring, print = tostring, print;
-- We need this to let modules access the real global namespace
local _G = _G;
module "modulemanager"
local api = {}; -- Module API container
local modulemap = { ["*"] = {} };
local stanza_handlers = multitable_new();
local handler_info = {};
local modulehelpers = setmetatable({}, { __index = _G });
-- Load modules when a host is activated
function load_modules_for_host(host)
local modules_enabled = config.get(host, "core", "modules_enabled");
if modules_enabled then
for _, module in pairs(modules_enabled) do
load(host, module);
end
end
end
eventmanager.add_event_hook("host-activated", load_modules_for_host);
--
function load(host, module_name, config)
if not (host and module_name) then
return nil, "insufficient-parameters";
end
if not modulemap[host] then
modulemap[host] = {};
elseif modulemap[host][module_name] then
log("warn", "%s is already loaded for %s, so not loading again", module_name, host);
return nil, "module-already-loaded";
elseif modulemap["*"][module_name] then
return nil, "global-module-already-loaded";
end
local mod, err = loadfile(plugin_dir.."mod_"..module_name..".lua");
if not mod then
log("error", "Unable to load module '%s': %s", module_name or "nil", err or "nil");
return nil, err;
end
local _log = logger.init(host..":"..module_name);
local api_instance = setmetatable({ name = module_name, host = host, config = config, _log = _log, log = function (self, ...) return _log(...); end }, { __index = api });
local pluginenv = setmetatable({ module = api_instance }, { __index = _G });
setfenv(mod, pluginenv);
local success, ret = pcall(mod);
if not success then
log("error", "Error initialising module '%s': %s", name or "nil", ret or "nil");
return nil, ret;
end
-- Use modified host, if the module set one
modulemap[api_instance.host][module_name] = mod;
return true;
end
function is_loaded(host, name)
return modulemap[host] and modulemap[host][name] and true;
end
function unload(host, name, ...)
local mod = modulemap[host] and modulemap[host][name];
if not mod then return nil, "module-not-loaded"; end
if type(mod.unload) == "function" then
local ok, err = pcall(mod.unload, ...)
if (not ok) and err then
log("warn", "Non-fatal error unloading module '%s' from '%s': %s", name, host, err);
end
end
end
function handle_stanza(host, origin, stanza)
local name, xmlns, origin_type = stanza.name, stanza.attr.xmlns, origin.type;
if name == "iq" and xmlns == "jabber:client" then
if stanza.attr.type == "get" or stanza.attr.type == "set" then
xmlns = stanza.tags[1].attr.xmlns;
log("debug", "Stanza of type %s from %s has xmlns: %s", name, origin_type, xmlns);
else
log("debug", "Discarding %s from %s of type: %s", name, origin_type, stanza.attr.type);
return true;
end
end
local handlers = stanza_handlers:get(host, origin_type, name, xmlns);
if handlers then
log("debug", "Passing stanza to mod_%s", handler_info[handlers[1]].name);
(handlers[1])(origin, stanza);
return true;
else
log("debug", "Stanza unhandled by any modules, xmlns: %s", stanza.attr.xmlns); -- we didn't handle it
end
end
----- API functions exposed to modules -----------
-- Must all be in api.*
-- Returns the name of the current module
function api:get_name()
return self.name;
end
-- Returns the host that the current module is serving
function api:get_host()
return self.host;
end
local function _add_handler(module, origin_type, tag, xmlns, handler)
local handlers = stanza_handlers:get(module.host, origin_type, tag, xmlns);
local msg = (tag == "iq") and "namespace" or "payload namespace";
if not handlers then
stanza_handlers:add(module.host, origin_type, tag, xmlns, handler);
handler_info[handler] = module;
module:log("debug", "I now handle tag '%s' [%s] with %s '%s'", tag, origin_type, msg, xmlns);
else
module:log("warn", "I wanted to handle tag '%s' [%s] with %s '%s' but mod_%s already handles that", tag, origin_type, msg, xmlns, handler_info[handlers[1]].module.name);
end
end
function api:add_handler(origin_type, tag, xmlns, handler)
if not (origin_type and tag and xmlns and handler) then return false; end
if type(origin_type) == "table" then
for _, origin_type in ipairs(origin_type) do
_add_handler(self, origin_type, tag, xmlns, handler);
end
else
_add_handler(self, origin_type, tag, xmlns, handler);
end
end
function api:add_iq_handler(origin_type, xmlns, handler)
self:add_handler(origin_type, "iq", xmlns, handler);
end
function api:add_feature(xmlns)
addDiscoInfoHandler(self.host, function(reply, to, from, node)
if #node == 0 then
reply:tag("feature", {var = xmlns}):up();
return true;
end
end);
end
function api:add_event_hook (...) return eventmanager.add_event_hook(...); end
--------------------------------------------------------------------
return _M;
|
-- Prosody IM v0.2
-- Copyright (C) 2008 Matthew Wild
-- Copyright (C) 2008 Waqas Hussain
--
-- This program is free software; you can redistribute it and/or
-- modify it under the terms of the GNU General Public License
-- as published by the Free Software Foundation; either version 2
-- of the License, or (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program; if not, write to the Free Software
-- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
--
local plugin_dir = CFG_PLUGINDIR or "./plugins/";
local logger = require "util.logger";
local log = logger.init("modulemanager");
local addDiscoInfoHandler = require "core.discomanager".addDiscoInfoHandler;
local eventmanager = require "core.eventmanager";
local config = require "core.configmanager";
local multitable_new = require "util.multitable".new;
local loadfile, pcall = loadfile, pcall;
local setmetatable, setfenv, getfenv = setmetatable, setfenv, getfenv;
local pairs, ipairs = pairs, ipairs;
local t_insert = table.insert;
local type = type;
local tostring, print = tostring, print;
-- We need this to let modules access the real global namespace
local _G = _G;
module "modulemanager"
local api = {}; -- Module API container
local modulemap = { ["*"] = {} };
local stanza_handlers = multitable_new();
local handler_info = {};
local modulehelpers = setmetatable({}, { __index = _G });
-- Load modules when a host is activated
function load_modules_for_host(host)
-- Load modules from global section
local modules_enabled = config.get("*", "core", "modules_enabled");
local modules_disabled = config.get(host, "core", "modules_disabled");
local disabled_set = {};
if modules_enabled then
if modules_disabled then
for _, module in pairs(modules_disabled) do
disabled_set[module] = true;
end
end
for _, module in pairs(modules_enabled) do
if not disabled_set[module] then
load(host, module);
end
end
end
-- Load modules from just this host
local modules_enabled = config.get(host, "core", "modules_enabled");
if modules_enabled then
for _, module in pairs(modules_enabled) do
load(host, module);
end
end
end
eventmanager.add_event_hook("host-activated", load_modules_for_host);
--
function load(host, module_name, config)
if not (host and module_name) then
return nil, "insufficient-parameters";
end
if not modulemap[host] then
modulemap[host] = {};
elseif modulemap[host][module_name] then
log("warn", "%s is already loaded for %s, so not loading again", module_name, host);
return nil, "module-already-loaded";
elseif modulemap["*"][module_name] then
return nil, "global-module-already-loaded";
end
local mod, err = loadfile(plugin_dir.."mod_"..module_name..".lua");
if not mod then
log("error", "Unable to load module '%s': %s", module_name or "nil", err or "nil");
return nil, err;
end
local _log = logger.init(host..":"..module_name);
local api_instance = setmetatable({ name = module_name, host = host, config = config, _log = _log, log = function (self, ...) return _log(...); end }, { __index = api });
local pluginenv = setmetatable({ module = api_instance }, { __index = _G });
setfenv(mod, pluginenv);
local success, ret = pcall(mod);
if not success then
log("error", "Error initialising module '%s': %s", name or "nil", ret or "nil");
return nil, ret;
end
-- Use modified host, if the module set one
modulemap[api_instance.host][module_name] = mod;
return true;
end
function is_loaded(host, name)
return modulemap[host] and modulemap[host][name] and true;
end
function unload(host, name, ...)
local mod = modulemap[host] and modulemap[host][name];
if not mod then return nil, "module-not-loaded"; end
if type(mod.unload) == "function" then
local ok, err = pcall(mod.unload, ...)
if (not ok) and err then
log("warn", "Non-fatal error unloading module '%s' from '%s': %s", name, host, err);
end
end
end
function handle_stanza(host, origin, stanza)
local name, xmlns, origin_type = stanza.name, stanza.attr.xmlns, origin.type;
if name == "iq" and xmlns == "jabber:client" then
if stanza.attr.type == "get" or stanza.attr.type == "set" then
xmlns = stanza.tags[1].attr.xmlns;
log("debug", "Stanza of type %s from %s has xmlns: %s", name, origin_type, xmlns);
else
log("debug", "Discarding %s from %s of type: %s", name, origin_type, stanza.attr.type);
return true;
end
end
local handlers = stanza_handlers:get(host, origin_type, name, xmlns);
if handlers then
log("debug", "Passing stanza to mod_%s", handler_info[handlers[1]].name);
(handlers[1])(origin, stanza);
return true;
else
log("debug", "Stanza unhandled by any modules, xmlns: %s", stanza.attr.xmlns); -- we didn't handle it
end
end
----- API functions exposed to modules -----------
-- Must all be in api.*
-- Returns the name of the current module
function api:get_name()
return self.name;
end
-- Returns the host that the current module is serving
function api:get_host()
return self.host;
end
local function _add_handler(module, origin_type, tag, xmlns, handler)
local handlers = stanza_handlers:get(module.host, origin_type, tag, xmlns);
local msg = (tag == "iq") and "namespace" or "payload namespace";
if not handlers then
stanza_handlers:add(module.host, origin_type, tag, xmlns, handler);
handler_info[handler] = module;
module:log("debug", "I now handle tag '%s' [%s] with %s '%s'", tag, origin_type, msg, xmlns);
else
module:log("warn", "I wanted to handle tag '%s' [%s] with %s '%s' but mod_%s already handles that", tag, origin_type, msg, xmlns, handler_info[handlers[1]].module.name);
end
end
function api:add_handler(origin_type, tag, xmlns, handler)
if not (origin_type and tag and xmlns and handler) then return false; end
if type(origin_type) == "table" then
for _, origin_type in ipairs(origin_type) do
_add_handler(self, origin_type, tag, xmlns, handler);
end
else
_add_handler(self, origin_type, tag, xmlns, handler);
end
end
function api:add_iq_handler(origin_type, xmlns, handler)
self:add_handler(origin_type, "iq", xmlns, handler);
end
function api:add_feature(xmlns)
addDiscoInfoHandler(self.host, function(reply, to, from, node)
if #node == 0 then
reply:tag("feature", {var = xmlns}):up();
return true;
end
end);
end
function api:add_event_hook (...) return eventmanager.add_event_hook(...); end
--------------------------------------------------------------------
return _M;
|
Fix for not loading global modules when host-specific modules are specified in config
|
Fix for not loading global modules when host-specific modules are specified in config
|
Lua
|
mit
|
sarumjanuch/prosody,sarumjanuch/prosody
|
ef9ff6b1050cce8ddbacdde010fc929f375b2a39
|
mod_ircd/mod_ircd.lua
|
mod_ircd/mod_ircd.lua
|
local irc_listener = { default_port = 6667, default_mode = "*l" };
local sessions = {};
local commands = {};
local nicks = {};
local st = require "util.stanza";
local conference_server = module:get_option("conference_server") or "conference.jabber.org";
local function irc_close_session(session)
session.conn:close();
end
function irc_listener.onincoming(conn, data)
local session = sessions[conn];
if not session then
session = { conn = conn, host = module.host, reset_stream = function () end,
close = irc_close_session, log = logger.init("irc"..(conn.id or "1")),
roster = {} };
sessions[conn] = session;
function session.data(data)
module:log("debug", "Received: %s", data);
local command, args = data:match("^%s*([^ ]+) *(.*)%s*$");
if not command then
module:log("warn", "Invalid command: %s", data);
return;
end
command = command:upper();
module:log("debug", "Received command: %s", command);
if commands[command] then
local ret = commands[command](session, args);
if ret then
session.send(ret.."\r\n");
end
end
end
function session.send(data)
module:log("debug", "sending: %s", data);
return conn:write(data.."\r\n");
end
end
if data then
session.data(data);
end
end
function irc_listener.ondisconnect(conn, error)
module:log("debug", "Client disconnected");
sessions[conn] = nil;
end
function commands.NICK(session, nick)
nick = nick:match("^[%w_]+");
if nicks[nick] then
session.send(":"..session.host.." 433 * The nickname "..nick.." is already in use");
return;
end
nicks[nick] = session;
session.nick = nick;
session.full_jid = nick.."@"..module.host.."/ircd";
session.type = "c2s";
module:log("debug", "Client bound to %s", session.full_jid);
session.send(":"..session.host.." 001 "..session.nick.." :Welcome to XMPP via the "..session.host.." gateway "..session.nick);
end
local joined_mucs = {};
function commands.JOIN(session, channel)
if not joined_mucs[channel] then
joined_mucs[channel] = { occupants = {}, sessions = {} };
end
joined_mucs[channel].sessions[session] = true;
local join_stanza = st.presence({ from = session.full_jid, to = channel:gsub("^#", "").."@"..conference_server.."/"..session.nick });
core_process_stanza(session, join_stanza);
session.send(":"..session.nick.." JOIN :"..channel);
session.send(":"..session.host.." 332 "..session.nick.." "..channel.." :Connection in progress...");
local nicks = session.nick;
for nick in pairs(joined_mucs[channel].occupants) do
nicks = nicks.." "..nick;
end
session.send(":"..session.host.." 353 "..session.nick.." = "..channel.." :"..nicks);
session.send(":"..session.host.." 366 "..session.nick.." "..channel.." :End of /NAMES list.");
end
function commands.PART(session, channel)
local channel, part_message = channel:match("^([^:]+):?(.*)$");
channel = channel:match("^([%S]*)");
core_process_stanza(session, st.presence{ type = "unavailable", from = session.full_jid,
to = channel:gsub("^#", "").."@"..conference_server.."/"..session.nick }:tag("status"):text(part_message));
session.send(":"..session.nick.." PART :"..channel);
end
function commands.PRIVMSG(session, message)
local who, message = message:match("^(%S+) :(.+)$");
if joined_mucs[who] then
core_process_stanza(session, st.message{to=who:gsub("^#", "").."@"..conference_server, type="groupchat"}:tag("body"):text(message));
end
end
function commands.PING(session, server)
session.send(":"..session.host..": PONG "..server);
end
function commands.WHO(session, channel)
if joined_mucs[channel] then
for nick in pairs(joined_mucs[channel].occupants) do
--n=MattJ 91.85.191.50 irc.freenode.net MattJ H :0 Matthew Wild
session.send(":"..session.host.." 352 "..session.nick.." "..channel.." "..nick.." "..nick.." "..session.host.." "..nick.." H :0 "..nick);
end
session.send(":"..session.host.." 315 "..session.nick.." "..channel.. " :End of /WHO list");
end
end
function commands.MODE(session, channel)
session.send(":"..session.host.." 324 "..session.nick.." "..channel.." +J");
end
--- Component (handle stanzas from the server for IRC clients)
function irc_component(origin, stanza)
local from, from_bare = stanza.attr.from, jid.bare(stanza.attr.from);
local from_node = "#"..jid.split(stanza.attr.from);
if joined_mucs[from_node] and from_bare == from then
-- From room itself
local joined_muc = joined_mucs[from_node];
if stanza.name == "message" then
local subject = stanza:get_child("subject");
subject = subject and (subject:get_text() or "");
if subject then
for session in pairs(joined_muc.sessions) do
session.send(":"..session.host.." 332 "..session.nick.." "..from_node.." :"..subject);
end
end
end
elseif joined_mucs[from_node] then
-- From room occupant
local joined_muc = joined_mucs[from_node];
local nick = select(3, jid.split(from)):gsub(" ", "_");
if stanza.name == "presence" then
local what;
if not stanza.attr.type then
if joined_muc.occupants[nick] then
return;
end
joined_muc.occupants[nick] = true;
what = "JOIN";
else
joined_muc.occupants[nick] = nil;
what = "PART";
end
for session in pairs(joined_muc.sessions) do
if nick ~= session.nick then
session.send(":"..nick.."!"..nick.." "..what.." :"..from_node);
end
end
elseif stanza.name == "message" then
local body = stanza:get_child("body");
body = body and body:get_text() or "";
local hasdelay = stanza:get_child("delay", "urn:xmpp:delay");
if body ~= "" and nick then
for session in pairs(joined_muc.sessions) do
if nick ~= session.nick or hasdelay then
session.send(":"..nick.." PRIVMSG "..from_node.." :"..body);
end
end
end
if not nick then
module:log("error", "Invalid nick from JID: %s", from);
end
end
end
end
require "core.componentmanager".register_component(module.host, irc_component);
prosody.events.add_handler("server-stopping", function (shutdown)
module:log("debug", "Closing IRC connections prior to shutdown");
for channel, joined_muc in pairs(joined_mucs) do
for session in pairs(joined_muc.sessions) do
core_process_stanza(session,
st.presence{ type = "unavailable", from = session.full_jid,
to = channel:gsub("^#", "").."@"..conference_server.."/"..session.nick }
:tag("status")
:text("Connection closed: Server is shutting down"..(shutdown.reason and (": "..shutdown.reason) or "")));
session:close();
end
end
end);
require "net.connlisteners".register("irc", irc_listener);
require "net.connlisteners".start("irc", { port = module:get_option("port") });
|
local irc_listener = { default_port = 6667, default_mode = "*l" };
local sessions = {};
local commands = {};
local nicks = {};
local st = require "util.stanza";
local conference_server = module:get_option("conference_server") or "conference.jabber.org";
local function irc_close_session(session)
session.conn:close();
end
function irc_listener.onincoming(conn, data)
local session = sessions[conn];
if not session then
session = { conn = conn, host = module.host, reset_stream = function () end,
close = irc_close_session, log = logger.init("irc"..(conn.id or "1")),
roster = {} };
sessions[conn] = session;
function session.data(data)
module:log("debug", "Received: %s", data);
local command, args = data:match("^%s*([^ ]+) *(.*)%s*$");
if not command then
module:log("warn", "Invalid command: %s", data);
return;
end
command = command:upper();
module:log("debug", "Received command: %s", command);
if commands[command] then
local ret = commands[command](session, args);
if ret then
session.send(ret.."\r\n");
end
end
end
function session.send(data)
module:log("debug", "sending: %s", data);
return conn:write(data.."\r\n");
end
end
if data then
session.data(data);
end
end
function irc_listener.ondisconnect(conn, error)
module:log("debug", "Client disconnected");
sessions[conn] = nil;
end
function commands.NICK(session, nick)
nick = nick:match("^[%w_]+");
if nicks[nick] then
session.send(":"..session.host.." 433 * The nickname "..nick.." is already in use");
return;
end
nicks[nick] = session;
session.nick = nick;
session.full_jid = nick.."@"..module.host.."/ircd";
session.type = "c2s";
module:log("debug", "Client bound to %s", session.full_jid);
session.send(":"..session.host.." 001 "..session.nick.." :Welcome to XMPP via the "..session.host.." gateway "..session.nick);
end
local joined_mucs = {};
function commands.JOIN(session, channel)
if not joined_mucs[channel] then
joined_mucs[channel] = { occupants = {}, sessions = {} };
end
joined_mucs[channel].sessions[session] = true;
local join_stanza = st.presence({ from = session.full_jid, to = channel:gsub("^#", "").."@"..conference_server.."/"..session.nick });
core_process_stanza(session, join_stanza);
session.send(":"..session.nick.." JOIN :"..channel);
session.send(":"..session.host.." 332 "..session.nick.." "..channel.." :Connection in progress...");
local nicks = session.nick;
for nick in pairs(joined_mucs[channel].occupants) do
nicks = nicks.." "..nick;
end
session.send(":"..session.host.." 353 "..session.nick.." = "..channel.." :"..nicks);
session.send(":"..session.host.." 366 "..session.nick.." "..channel.." :End of /NAMES list.");
end
function commands.PART(session, channel)
local channel, part_message = channel:match("^([^:]+):?(.*)$");
channel = channel:match("^([%S]*)");
core_process_stanza(session, st.presence{ type = "unavailable", from = session.full_jid,
to = channel:gsub("^#", "").."@"..conference_server.."/"..session.nick }:tag("status"):text(part_message));
session.send(":"..session.nick.." PART :"..channel);
end
function commands.PRIVMSG(session, message)
local who, message = message:match("^(%S+) :(.+)$");
if joined_mucs[who] then
core_process_stanza(session, st.message{to=who:gsub("^#", "").."@"..conference_server, type="groupchat"}:tag("body"):text(message));
end
end
function commands.PING(session, server)
session.send(":"..session.host..": PONG "..server);
end
function commands.WHO(session, channel)
if joined_mucs[channel] then
for nick in pairs(joined_mucs[channel].occupants) do
--n=MattJ 91.85.191.50 irc.freenode.net MattJ H :0 Matthew Wild
session.send(":"..session.host.." 352 "..session.nick.." "..channel.." "..nick.." "..nick.." "..session.host.." "..nick.." H :0 "..nick);
end
session.send(":"..session.host.." 315 "..session.nick.." "..channel.. " :End of /WHO list");
end
end
function commands.MODE(session, channel)
session.send(":"..session.host.." 324 "..session.nick.." "..channel.." +J");
end
--- Component (handle stanzas from the server for IRC clients)
function irc_component(origin, stanza)
local from, from_bare = stanza.attr.from, jid.bare(stanza.attr.from);
local from_node = "#"..jid.split(stanza.attr.from);
if joined_mucs[from_node] and from_bare == from then
-- From room itself
local joined_muc = joined_mucs[from_node];
if stanza.name == "message" then
local subject = stanza:get_child("subject");
subject = subject and (subject:get_text() or "");
if subject then
for session in pairs(joined_muc.sessions) do
session.send(":"..session.host.." 332 "..session.nick.." "..from_node.." :"..subject);
end
end
end
elseif joined_mucs[from_node] then
-- From room occupant
local joined_muc = joined_mucs[from_node];
local nick = select(3, jid.split(from)):gsub(" ", "_");
if stanza.name == "presence" then
local what;
if not stanza.attr.type then
if joined_muc.occupants[nick] then
return;
end
joined_muc.occupants[nick] = true;
what = "JOIN";
else
joined_muc.occupants[nick] = nil;
what = "PART";
end
for session in pairs(joined_muc.sessions) do
if nick ~= session.nick then
session.send(":"..nick.."!"..nick.." "..what.." :"..from_node);
end
end
elseif stanza.name == "message" then
local body = stanza:get_child("body");
body = body and body:get_text() or "";
local hasdelay = stanza:get_child("delay", "urn:xmpp:delay");
if body ~= "" and nick then
local to_nick = jid.split(stanza.attr.to);
local session = nicks[to_nick];
if nick ~= session.nick or hasdelay then
session.send(":"..nick.." PRIVMSG "..from_node.." :"..body);
end
end
if not nick then
module:log("error", "Invalid nick from JID: %s", from);
end
end
end
end
require "core.componentmanager".register_component(module.host, irc_component);
prosody.events.add_handler("server-stopping", function (shutdown)
module:log("debug", "Closing IRC connections prior to shutdown");
for channel, joined_muc in pairs(joined_mucs) do
for session in pairs(joined_muc.sessions) do
core_process_stanza(session,
st.presence{ type = "unavailable", from = session.full_jid,
to = channel:gsub("^#", "").."@"..conference_server.."/"..session.nick }
:tag("status")
:text("Connection closed: Server is shutting down"..(shutdown.reason and (": "..shutdown.reason) or "")));
session:close();
end
end
end);
require "net.connlisteners".register("irc", irc_listener);
require "net.connlisteners".start("irc", { port = module:get_option("port") });
|
fixed broadcast PRIVMSG bug
|
fixed broadcast PRIVMSG bug
|
Lua
|
mit
|
Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules
|
1575824e17a59abcde6e46c696c25eeb19e02814
|
kong/api/routes/plugins.lua
|
kong/api/routes/plugins.lua
|
local crud = require "kong.api.crud_helpers"
local cjson = require "cjson"
local utils = require "kong.tools.utils"
local reports = require "kong.core.reports"
local singletons = require "kong.singletons"
-- Remove functions from a schema definition so that
-- cjson can encode the schema.
local function remove_functions(schema)
for k, v in pairs(schema) do
if type(v) == "function" then
schema[k] = "function"
end
if type(v) == "table" then
remove_functions(schema[k])
end
end
end
return {
["/plugins"] = {
GET = function(self, dao_factory)
crud.paginated_set(self, dao_factory.plugins)
end,
PUT = function(self, dao_factory)
crud.put(self.params, dao_factory.plugins)
end,
POST = function(self, dao_factory)
crud.post(self.params, dao_factory.plugins, function(data)
local r_data = utils.deep_copy(data)
r_data.config = nil
if data.service_id then
r_data.e = "s"
elseif data.route_id then
r_data.e = "r"
elseif data.api_id then
r_data.e = "a"
end
reports.send("api", r_data)
end)
end
},
["/plugins/schema/:name"] = {
GET = function(self, dao_factory, helpers)
local ok, plugin_schema = utils.load_module_if_exists("kong.plugins." .. self.params.name .. ".schema")
if not ok then
return helpers.responses.send_HTTP_NOT_FOUND("No plugin named '" .. self.params.name .. "'")
end
remove_functions(plugin_schema)
return helpers.responses.send_HTTP_OK(plugin_schema)
end
},
["/plugins/:id"] = {
before = function(self, dao_factory, helpers)
crud.find_plugin_by_filter(self, dao_factory, {
id = self.params.id
}, helpers)
end,
GET = function(self, dao_factory, helpers)
return helpers.responses.send_HTTP_OK(self.plugin)
end,
PATCH = function(self, dao_factory)
crud.patch(self.params, dao_factory.plugins, self.plugin)
end,
DELETE = function(self, dao_factory)
crud.delete(self.plugin, dao_factory.plugins)
end
},
["/plugins/enabled"] = {
GET = function(self, dao_factory, helpers)
local enabled_plugins = setmetatable({}, cjson.empty_array_mt)
for k in pairs(singletons.configuration.plugins) do
enabled_plugins[#enabled_plugins+1] = k
end
return helpers.responses.send_HTTP_OK {
enabled_plugins = enabled_plugins
}
end
}
}
|
local crud = require "kong.api.crud_helpers"
local cjson = require "cjson"
local utils = require "kong.tools.utils"
local reports = require "kong.core.reports"
local singletons = require "kong.singletons"
-- Remove functions from a schema definition so that
-- cjson can encode the schema.
local function remove_functions(schema)
local copy = {}
for k, v in pairs(schema) do
copy[k] = (type(v) == "function" and "function")
or (type(v) == "table" and remove_functions(schema[k]))
or v
end
return copy
end
return {
["/plugins"] = {
GET = function(self, dao_factory)
crud.paginated_set(self, dao_factory.plugins)
end,
PUT = function(self, dao_factory)
crud.put(self.params, dao_factory.plugins)
end,
POST = function(self, dao_factory)
crud.post(self.params, dao_factory.plugins, function(data)
local r_data = utils.deep_copy(data)
r_data.config = nil
if data.service_id then
r_data.e = "s"
elseif data.route_id then
r_data.e = "r"
elseif data.api_id then
r_data.e = "a"
end
reports.send("api", r_data)
end)
end
},
["/plugins/schema/:name"] = {
GET = function(self, dao_factory, helpers)
local ok, plugin_schema = utils.load_module_if_exists("kong.plugins." .. self.params.name .. ".schema")
if not ok then
return helpers.responses.send_HTTP_NOT_FOUND("No plugin named '" .. self.params.name .. "'")
end
local copy = remove_functions(plugin_schema)
return helpers.responses.send_HTTP_OK(copy)
end
},
["/plugins/:id"] = {
before = function(self, dao_factory, helpers)
crud.find_plugin_by_filter(self, dao_factory, {
id = self.params.id
}, helpers)
end,
GET = function(self, dao_factory, helpers)
return helpers.responses.send_HTTP_OK(self.plugin)
end,
PATCH = function(self, dao_factory)
crud.patch(self.params, dao_factory.plugins, self.plugin)
end,
DELETE = function(self, dao_factory)
crud.delete(self.plugin, dao_factory.plugins)
end
},
["/plugins/enabled"] = {
GET = function(self, dao_factory, helpers)
local enabled_plugins = setmetatable({}, cjson.empty_array_mt)
for k in pairs(singletons.configuration.plugins) do
enabled_plugins[#enabled_plugins+1] = k
end
return helpers.responses.send_HTTP_OK {
enabled_plugins = enabled_plugins
}
end
}
}
|
fix(admin) do not mutate plugins schema in /plugins/schema/:name
|
fix(admin) do not mutate plugins schema in /plugins/schema/:name
Make `remove_functions` produce a copy instead of modifying the plugin
schema table in-place.
Fix #3222
From #3348
|
Lua
|
apache-2.0
|
Mashape/kong,Kong/kong,Kong/kong,Kong/kong
|
093cad888c4f66571ec4d7845b9810ae51db5054
|
xmake/platforms/linux/xmake.lua
|
xmake/platforms/linux/xmake.lua
|
--!The Make-like Build Utility based on Lua
--
-- XMake is free software; you can redistribute it and/or modify
-- it under the terms of the GNU Lesser General Public License as published by
-- the Free Software Foundation; either version 2.1 of the License, or
-- (at your option) any later version.
--
-- XMake is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU Lesser General Public License for more details.
--
-- You should have received a copy of the GNU Lesser General Public License
-- along with XMake;
-- If not, see <a href="http://www.gnu.org/licenses/"> http://www.gnu.org/licenses/</a>
--
-- Copyright (C) 2015 - 2016, ruki All rights reserved.
--
-- @author ruki
-- @file xmake.lua
--
-- define platform
platform("linux")
-- set os
set_os("linux")
-- set hosts
set_hosts("macosx", "linux", "windows")
-- set archs
set_archs("i386", "x86_64")
-- set checker
set_checker("checker")
-- set installer
set_installer("installer")
-- set tooldirs
set_tooldirs("/usr/bin", "/usr/local/bin", "/opt/bin", "/opt/local/bin")
-- on load
on_load(function ()
-- imports
import("core.project.config")
-- init the file formats
_g.formats = {}
_g.formats.static = {"lib", ".a"}
_g.formats.object = {"", ".o"}
_g.formats.shared = {"lib", ".so"}
_g.formats.symbol = {"", ".sym"}
-- cross toolchains?
if config.get("cross") then
-- init linkdirs and includedirs
local sdkdir = config.get("sdk")
if sdkdir then
_g.includedirs = {path.join(sdkdir, "include")}
_g.linkdirs = {path.join(sdkdir, "lib")}
end
-- ok
return
end
-- init flags for architecture
local archflags = nil
local arch = config.get("arch")
if arch then
if arch == "x86_64" then archflags = "-m64"
elseif arch == "i386" then archflags = "-m32"
else archflags = "-arch " .. arch
end
end
_g.cxflags = { archflags }
_g.mxflags = { archflags }
_g.asflags = { archflags }
_g.ldflags = { archflags }
_g.shflags = { archflags }
-- init linkdirs and includedirs
_g.linkdirs = {"/usr/lib", "/usr/local/lib"}
_g.includedirs = {"/usr/include", "/usr/local/include"}
end)
|
--!The Make-like Build Utility based on Lua
--
-- XMake is free software; you can redistribute it and/or modify
-- it under the terms of the GNU Lesser General Public License as published by
-- the Free Software Foundation; either version 2.1 of the License, or
-- (at your option) any later version.
--
-- XMake is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU Lesser General Public License for more details.
--
-- You should have received a copy of the GNU Lesser General Public License
-- along with XMake;
-- If not, see <a href="http://www.gnu.org/licenses/"> http://www.gnu.org/licenses/</a>
--
-- Copyright (C) 2015 - 2016, ruki All rights reserved.
--
-- @author ruki
-- @file xmake.lua
--
-- define platform
platform("linux")
-- set os
set_os("linux")
-- set hosts
set_hosts("macosx", "linux", "windows")
-- set archs
set_archs("i386", "x86_64")
-- set checker
set_checker("checker")
-- set installer
set_installer("installer")
-- set tooldirs
set_tooldirs("/usr/bin", "/usr/local/bin", "/opt/bin", "/opt/local/bin")
-- on load
on_load(function ()
-- imports
import("core.project.config")
-- init the file formats
_g.formats = {}
_g.formats.static = {"lib", ".a"}
_g.formats.object = {"", ".o"}
_g.formats.shared = {"lib", ".so"}
_g.formats.symbol = {"", ".sym"}
-- cross toolchains?
if config.get("cross") or config.get("toolchains") or config.get("sdk") then
-- init linkdirs and includedirs
local sdkdir = config.get("sdk")
if sdkdir then
_g.includedirs = {path.join(sdkdir, "include")}
_g.linkdirs = {path.join(sdkdir, "lib")}
end
-- ok
return
end
-- init flags for architecture
local archflags = nil
local arch = config.get("arch")
if arch then
if arch == "x86_64" then archflags = "-m64"
elseif arch == "i386" then archflags = "-m32"
else archflags = "-arch " .. arch
end
end
_g.cxflags = { archflags }
_g.mxflags = { archflags }
_g.asflags = { archflags }
_g.ldflags = { archflags }
_g.shflags = { archflags }
-- init linkdirs and includedirs
_g.linkdirs = {"/usr/lib", "/usr/local/lib"}
_g.includedirs = {"/usr/include", "/usr/local/include"}
end)
|
fix toolchains checking
|
fix toolchains checking
|
Lua
|
apache-2.0
|
tboox/xmake,tboox/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,tboox/xmake,waruqi/xmake,tboox/xmake,waruqi/xmake,tboox/xmake,tboox/xmake,waruqi/xmake,waruqi/xmake,tboox/xmake
|
b07ca52a5e29648bed85e08a2431f2ce4438a463
|
nyagos.d/catalog/autocd.lua
|
nyagos.d/catalog/autocd.lua
|
share.org_autocd_argsfilter = nyagos.argsfilter
nyagos.argsfilter = function(args)
if share.org_autocd_argsfilter then
local args_ = share.org_autocd_argsfilter(args)
if args_ then
args = args_
end
end
local stat = nyagos.stat(args[0])
if not stat or not stat.isdir then
return
end
local newargs = {[0] = 'cd'}
for i = 0, #args do
newargs[#newargs + 1] = args[i]
end
return newargs
end
|
share.org_autocd_argsfilter = nyagos.argsfilter
nyagos.argsfilter = function(args)
if share.org_autocd_argsfilter then
local args_ = share.org_autocd_argsfilter(args)
if args_ then
args = args_
end
end
if nyagos.which(args[0]) then
return
end
local stat = nyagos.stat(args[0])
if not stat or not stat.isdir then
return
end
local newargs = {[0] = 'cd'}
for i = 0, #args do
newargs[#newargs + 1] = args[i]
end
return newargs
end
|
Fix: autocd.lua
|
Fix: autocd.lua
|
Lua
|
bsd-3-clause
|
zetamatta/nyagos,tsuyoshicho/nyagos,nocd5/nyagos,tyochiai/nyagos
|
9467eab6e117d4c51d0b25b68f74b4395a3e47a8
|
frontend/apps/reader/modules/readerdictionary.lua
|
frontend/apps/reader/modules/readerdictionary.lua
|
local EventListener = require("ui/widget/eventlistener")
local UIManager = require("ui/uimanager")
local DictQuickLookup = require("ui/widget/dictquicklookup")
local Geom = require("ui/geometry")
local Screen = require("ui/screen")
local JSON = require("JSON")
local DEBUG = require("dbg")
local _ = require("gettext")
local ReaderDictionary = EventListener:new{}
function ReaderDictionary:onLookupWord(word, box, highlight)
self.highlight = highlight
self:stardictLookup(word, box)
return true
end
function ReaderDictionary:stardictLookup(word, box)
DEBUG("lookup word:", word, box)
if word then
-- strip punctuation characters around selected word
word = string.gsub(word, "^%p+", '')
word = string.gsub(word, "%p+$", '')
DEBUG("stripped word:", word)
-- escape quotes and other funny characters in word
local std_out = io.popen("./sdcv --utf8-input --utf8-output -nj "..("%q"):format(word), "r")
local results_str = nil
if std_out then results_str = std_out:read("*all") end
--DEBUG("result str:", word, results_str)
local ok, results = pcall(JSON.decode, JSON, results_str)
if ok and results then
DEBUG("lookup result table:", word, results)
self:showDict(word, results, box)
else
-- dummy results
results = {
{
dict = "",
word = word,
definition = _("No definition found."),
}
}
DEBUG("dummy result table:", word, results)
self:showDict(word, results, box)
end
end
end
function ReaderDictionary:showDict(word, results, box)
if results and results[1] then
DEBUG("showing quick lookup window")
UIManager:show(DictQuickLookup:new{
ui = self.ui,
highlight = self.highlight,
dialog = self.dialog,
-- original lookup word
word = word,
results = results,
dictionary = self.default_dictionary,
width = Screen:getWidth() - Screen:scaleByDPI(80),
word_box = box,
-- differentiate between dict and wiki
wiki = self.wiki,
})
end
end
function ReaderDictionary:onUpdateDefaultDict(dict)
DEBUG("make default dictionary:", dict)
self.default_dictionary = dict
return true
end
function ReaderDictionary:onReadSettings(config)
self.default_dictionary = config:readSetting("default_dictionary")
end
function ReaderDictionary:onSaveSettings()
self.ui.doc_settings:saveSetting("default_dictionary", self.default_dictionary)
end
return ReaderDictionary
|
local EventListener = require("ui/widget/eventlistener")
local UIManager = require("ui/uimanager")
local DictQuickLookup = require("ui/widget/dictquicklookup")
local Geom = require("ui/geometry")
local Screen = require("ui/screen")
local JSON = require("JSON")
local DEBUG = require("dbg")
local _ = require("gettext")
local ReaderDictionary = EventListener:new{}
function ReaderDictionary:onLookupWord(word, box, highlight)
self.highlight = highlight
self:stardictLookup(word, box)
return true
end
function ReaderDictionary:stardictLookup(word, box)
DEBUG("lookup word:", word, box)
if word then
-- strip ASCII punctuation characters around selected word
-- and strip any generic punctuation (U+2000 - U+206F) in the word
word = word:gsub("\226[\128-\131][\128-\191]",''):gsub("^%p+",''):gsub("%p+$",'')
DEBUG("stripped word:", word)
-- escape quotes and other funny characters in word
local std_out = io.popen("./sdcv --utf8-input --utf8-output -nj "..("%q"):format(word), "r")
local results_str = nil
if std_out then results_str = std_out:read("*all") end
--DEBUG("result str:", word, results_str)
local ok, results = pcall(JSON.decode, JSON, results_str)
if ok and results then
DEBUG("lookup result table:", word, results)
self:showDict(word, results, box)
else
-- dummy results
results = {
{
dict = "",
word = word,
definition = _("No definition found."),
}
}
DEBUG("dummy result table:", word, results)
self:showDict(word, results, box)
end
end
end
function ReaderDictionary:showDict(word, results, box)
if results and results[1] then
DEBUG("showing quick lookup window")
UIManager:show(DictQuickLookup:new{
ui = self.ui,
highlight = self.highlight,
dialog = self.dialog,
-- original lookup word
word = word,
results = results,
dictionary = self.default_dictionary,
width = Screen:getWidth() - Screen:scaleByDPI(80),
word_box = box,
-- differentiate between dict and wiki
wiki = self.wiki,
})
end
end
function ReaderDictionary:onUpdateDefaultDict(dict)
DEBUG("make default dictionary:", dict)
self.default_dictionary = dict
return true
end
function ReaderDictionary:onReadSettings(config)
self.default_dictionary = config:readSetting("default_dictionary")
end
function ReaderDictionary:onSaveSettings()
self.ui.doc_settings:saveSetting("default_dictionary", self.default_dictionary)
end
return ReaderDictionary
|
strip generic punctuation (U+2000 - U+206F) in lookup word This should fix #921.
|
strip generic punctuation (U+2000 - U+206F) in lookup word
This should fix #921.
|
Lua
|
agpl-3.0
|
Frenzie/koreader,NiLuJe/koreader,houqp/koreader,ashhher3/koreader,robert00s/koreader,Markismus/koreader,Frenzie/koreader,mihailim/koreader,NickSavage/koreader,ashang/koreader,apletnev/koreader,lgeek/koreader,koreader/koreader,chihyang/koreader,poire-z/koreader,Hzj-jie/koreader,NiLuJe/koreader,koreader/koreader,poire-z/koreader,noname007/koreader,chrox/koreader,mwoz123/koreader,frankyifei/koreader,pazos/koreader
|
a409d092b48267aea8ee4c3ef634a6d140010adf
|
mod_auth_ldap/mod_auth_ldap.lua
|
mod_auth_ldap/mod_auth_ldap.lua
|
-- mod_auth_ldap
local new_sasl = require "util.sasl".new;
local lualdap = require "lualdap";
local function ldap_filter_escape(s) return (s:gsub("[*()\\%z]", function(c) return ("\\%02x"):format(c:byte()) end)); end
-- Config options
local ldap_server = module:get_option_string("ldap_server", "localhost");
local ldap_rootdn = module:get_option_string("ldap_rootdn", "");
local ldap_password = module:get_option_string("ldap_password", "");
local ldap_tls = module:get_option_boolean("ldap_tls");
local ldap_scope = module:get_option_string("ldap_scope", "onelevel");
local ldap_filter = module:get_option_string("ldap_filter", "(uid=$user)"):gsub("%%s", "$user", 1);
local ldap_base = assert(module:get_option_string("ldap_base"), "ldap_base is a required option for ldap");
local ldap_mode = module:get_option_string("ldap_mode", "bind");
local host = ldap_filter_escape(module:get_option_string("realm", module.host));
-- Initiate connection
local ld = nil;
module.unload = function() if ld then pcall(ld, ld.close); end end
function ldap_search_once(args)
if ld == nil then
local err;
ld, err = lualdap.open_simple(ldap_server, ldap_rootdn, ldap_password, ldap_tls);
if not ld then return nil, err, "reconnect"; end
end
local success, iterator, invariant, initial = pcall(ld.search, ld, args);
if not success then ld = nil; return nil, iterator, "search"; end
local success, dn, attr = pcall(iterator, invariant, initial);
if not success then ld = nil; return success, dn, "iter"; end
return dn, attr, "return";
end
function ldap_search(args, retry_count)
local dn, attr, where;
for i=1,1+retry_count do
dn, attr, where = ldap_search_once(args);
if dn or not(attr) then break; end -- nothing or something found
module:log("warn", "LDAP: %s %s (in %s)", tostring(dn), tostring(attr), where);
-- otherwise retry
end
if not dn and attr then
module:log("error", "LDAP: %s", tostring(attr));
end
return dn, attr;
end
local function get_user(username)
module:log("debug", "get_user(%q)", username);
for dn, attr in ldap_search({
base = ldap_base;
scope = ldap_scope;
sizelimit = 1;
filter = ldap_filter:gsub("%$(%a+)", {
user = ldap_filter_escape(username);
host = host;
});
}, 3) do return dn, attr; end
end
local provider = {};
function provider.create_user(username, password)
return nil, "Account creation not available with LDAP.";
end
function provider.user_exists(username)
return not not get_user(username);
end
function provider.set_password(username, password)
local dn, attr = get_user(username);
if not dn then return nil, attr end
if attr.userPassword == password then return true end
return ld:modify(dn, { '=', userPassword = password })();
end
if ldap_mode == "getpasswd" then
function provider.get_password(username)
local dn, attr = get_user(username);
if dn and attr then
return attr.userPassword;
end
end
function provider.test_password(username, password)
return provider.get_password(username) == password;
end
function provider.get_sasl_handler()
return new_sasl(module.host, {
plain = function(sasl, username)
local password = provider.get_password(username);
if not password then return "", nil; end
return password, true;
end
});
end
elseif ldap_mode == "bind" then
local function test_password(userdn, password)
return not not lualdap.open_simple(ldap_server, userdn, password, ldap_tls);
end
function provider.test_password(username, password)
local dn = get_user(username);
if not dn then return end
return test_password(dn, password)
end
function provider.get_sasl_handler()
return new_sasl(module.host, {
plain_test = function(sasl, username, password)
return provider.test_password(username, password), true;
end
});
end
else
module:log("error", "Unsupported ldap_mode %s", tostring(ldap_mode));
end
module:provides("auth", provider);
|
-- mod_auth_ldap
local new_sasl = require "util.sasl".new;
local lualdap = require "lualdap";
local function ldap_filter_escape(s) return (s:gsub("[*()\\%z]", function(c) return ("\\%02x"):format(c:byte()) end)); end
-- Config options
local ldap_server = module:get_option_string("ldap_server", "localhost");
local ldap_rootdn = module:get_option_string("ldap_rootdn", "");
local ldap_password = module:get_option_string("ldap_password", "");
local ldap_tls = module:get_option_boolean("ldap_tls");
local ldap_scope = module:get_option_string("ldap_scope", "onelevel");
local ldap_filter = module:get_option_string("ldap_filter", "(uid=$user)"):gsub("%%s", "$user", 1);
local ldap_base = assert(module:get_option_string("ldap_base"), "ldap_base is a required option for ldap");
local ldap_mode = module:get_option_string("ldap_mode", "bind");
local host = ldap_filter_escape(module:get_option_string("realm", module.host));
-- Initiate connection
local ld = nil;
module.unload = function() if ld then pcall(ld, ld.close); end end
function ldap_do_once(method, ...)
if ld == nil then
local err;
ld, err = lualdap.open_simple(ldap_server, ldap_rootdn, ldap_password, ldap_tls);
if not ld then return nil, err, "reconnect"; end
end
local success, iterator, invariant, initial = pcall(ld[method], ld, ...);
if not success then ld = nil; return nil, iterator, "search"; end
local success, dn, attr = pcall(iterator, invariant, initial);
if not success then ld = nil; return success, dn, "iter"; end
return dn, attr, "return";
end
function ldap_do(method, retry_count, ...)
local dn, attr, where;
for i=1,1+retry_count do
dn, attr, where = ldap_do_once(method, ...);
if dn or not(attr) then break; end -- nothing or something found
module:log("warn", "LDAP: %s %s (in %s)", tostring(dn), tostring(attr), where);
-- otherwise retry
end
if not dn and attr then
module:log("error", "LDAP: %s", tostring(attr));
end
return dn, attr;
end
local function get_user(username)
module:log("debug", "get_user(%q)", username);
return ldap_do("search", 2, {
base = ldap_base;
scope = ldap_scope;
sizelimit = 1;
filter = ldap_filter:gsub("%$(%a+)", {
user = ldap_filter_escape(username);
host = host;
});
});
end
local provider = {};
function provider.create_user(username, password)
return nil, "Account creation not available with LDAP.";
end
function provider.user_exists(username)
return not not get_user(username);
end
function provider.set_password(username, password)
local dn, attr = get_user(username);
if not dn then return nil, attr end
if attr.userPassword == password then return true end
return ldap_do("modify", 2, dn, { '=', userPassword = password });
end
if ldap_mode == "getpasswd" then
function provider.get_password(username)
local dn, attr = get_user(username);
if dn and attr then
return attr.userPassword;
end
end
function provider.test_password(username, password)
return provider.get_password(username) == password;
end
function provider.get_sasl_handler()
return new_sasl(module.host, {
plain = function(sasl, username)
local password = provider.get_password(username);
if not password then return "", nil; end
return password, true;
end
});
end
elseif ldap_mode == "bind" then
local function test_password(userdn, password)
return not not lualdap.open_simple(ldap_server, userdn, password, ldap_tls);
end
function provider.test_password(username, password)
local dn = get_user(username);
if not dn then return end
return test_password(dn, password)
end
function provider.get_sasl_handler()
return new_sasl(module.host, {
plain_test = function(sasl, username, password)
return provider.test_password(username, password), true;
end
});
end
else
module:log("error", "Unsupported ldap_mode %s", tostring(ldap_mode));
end
module:provides("auth", provider);
|
mod_auth_ldap: Fix use of ldap_search, and generalize it to support password modification as well.
|
mod_auth_ldap: Fix use of ldap_search, and generalize it to support password modification as well.
|
Lua
|
mit
|
cryptotoad/prosody-modules,vfedoroff/prosody-modules,heysion/prosody-modules,vfedoroff/prosody-modules,amenophis1er/prosody-modules,softer/prosody-modules,BurmistrovJ/prosody-modules,amenophis1er/prosody-modules,Craige/prosody-modules,olax/prosody-modules,jkprg/prosody-modules,Craige/prosody-modules,NSAKEY/prosody-modules,vince06fr/prosody-modules,dhotson/prosody-modules,heysion/prosody-modules,asdofindia/prosody-modules,Craige/prosody-modules,vfedoroff/prosody-modules,brahmi2/prosody-modules,NSAKEY/prosody-modules,either1/prosody-modules,guilhem/prosody-modules,iamliqiang/prosody-modules,joewalker/prosody-modules,guilhem/prosody-modules,crunchuser/prosody-modules,amenophis1er/prosody-modules,crunchuser/prosody-modules,crunchuser/prosody-modules,obelisk21/prosody-modules,jkprg/prosody-modules,either1/prosody-modules,mmusial/prosody-modules,LanceJenkinZA/prosody-modules,either1/prosody-modules,brahmi2/prosody-modules,syntafin/prosody-modules,brahmi2/prosody-modules,1st8/prosody-modules,mardraze/prosody-modules,prosody-modules/import,1st8/prosody-modules,dhotson/prosody-modules,obelisk21/prosody-modules,mardraze/prosody-modules,vfedoroff/prosody-modules,BurmistrovJ/prosody-modules,obelisk21/prosody-modules,jkprg/prosody-modules,vfedoroff/prosody-modules,olax/prosody-modules,stephen322/prosody-modules,vince06fr/prosody-modules,heysion/prosody-modules,joewalker/prosody-modules,cryptotoad/prosody-modules,vince06fr/prosody-modules,asdofindia/prosody-modules,prosody-modules/import,BurmistrovJ/prosody-modules,apung/prosody-modules,brahmi2/prosody-modules,joewalker/prosody-modules,olax/prosody-modules,olax/prosody-modules,drdownload/prosody-modules,obelisk21/prosody-modules,LanceJenkinZA/prosody-modules,prosody-modules/import,drdownload/prosody-modules,stephen322/prosody-modules,drdownload/prosody-modules,iamliqiang/prosody-modules,apung/prosody-modules,softer/prosody-modules,iamliqiang/prosody-modules,joewalker/prosody-modules,NSAKEY/prosody-modules,LanceJenkinZA/prosody-modules,crunchuser/prosody-modules,mmusial/prosody-modules,syntafin/prosody-modules,amenophis1er/prosody-modules,LanceJenkinZA/prosody-modules,LanceJenkinZA/prosody-modules,1st8/prosody-modules,drdownload/prosody-modules,Craige/prosody-modules,BurmistrovJ/prosody-modules,vince06fr/prosody-modules,guilhem/prosody-modules,brahmi2/prosody-modules,syntafin/prosody-modules,either1/prosody-modules,mmusial/prosody-modules,Craige/prosody-modules,jkprg/prosody-modules,cryptotoad/prosody-modules,apung/prosody-modules,iamliqiang/prosody-modules,crunchuser/prosody-modules,dhotson/prosody-modules,mardraze/prosody-modules,olax/prosody-modules,heysion/prosody-modules,BurmistrovJ/prosody-modules,mmusial/prosody-modules,1st8/prosody-modules,mardraze/prosody-modules,vince06fr/prosody-modules,syntafin/prosody-modules,asdofindia/prosody-modules,stephen322/prosody-modules,dhotson/prosody-modules,stephen322/prosody-modules,asdofindia/prosody-modules,prosody-modules/import,amenophis1er/prosody-modules,syntafin/prosody-modules,guilhem/prosody-modules,dhotson/prosody-modules,guilhem/prosody-modules,NSAKEY/prosody-modules,mardraze/prosody-modules,stephen322/prosody-modules,iamliqiang/prosody-modules,1st8/prosody-modules,cryptotoad/prosody-modules,softer/prosody-modules,mmusial/prosody-modules,softer/prosody-modules,asdofindia/prosody-modules,softer/prosody-modules,drdownload/prosody-modules,prosody-modules/import,either1/prosody-modules,obelisk21/prosody-modules,apung/prosody-modules,jkprg/prosody-modules,heysion/prosody-modules,cryptotoad/prosody-modules,apung/prosody-modules,joewalker/prosody-modules,NSAKEY/prosody-modules
|
5c225ba5801fbaf0bfa10bb5c3b29dfd7e737803
|
extensions/osascript/test_javascript.lua
|
extensions/osascript/test_javascript.lua
|
hs.osascript = require("hs.osascript")
function testJavaScriptParseError()
local js = "2 +"
local status, object, descriptor = hs.osascript.javascript(js)
assertFalse(status)
assertIsEqual(descriptor.OSAScriptErrorBriefMessageKey, "Error on line 1: SyntaxError: Unexpected end of script")
return success()
end
function testJavaScriptAddition()
local js = "2+2"
local status, object, descriptor = hs.osascript.javascript(js)
assertTrue(status)
assertIsEqual(object, 4)
return success()
end
function testJavaScriptDestructuring()
local js = [[
var obj = { cat: 1, dog: 2 };
var { cat, dog } = obj;
cat + dog;
]]
local status, object, descriptor = hs.osascript.javascript(js)
assertTrue(status)
assertIsEqual(object, 3)
return success()
end
function testJavaScriptString()
local js = [[
var str1 = "Hello", str2 = "World";
str1 + ", " + str2 + "!";
]]
local status, object, descriptor = hs.osascript.javascript(js)
assertTrue(status)
assertIsEqual(object, "Hello, World!")
return success()
end
function testJavaScriptArray()
local js = [[
[1, "a", 3.14, "b", null, false]
]]
local status, object, descriptor = hs.osascript.javascript(js)
assertTrue(status)
assertIsEqual(object[1], 1)
assertIsEqual(object[2], "a")
assertIsEqual(object[3], 3.14)
assertIsEqual(object[4], "b")
assertIsEqual(object[5], false)
return success()
end
function testJavaScriptJsonStringify()
local js = [[
var obj = {
a: 1,
"b": "two",
"c": true
};
json = JSON.stringify(obj);
json;
]]
local status, object, descriptor = hs.osascript.javascript(js)
assertTrue(status)
assertIsEqual(object, '{"a":1,"b":"two","c":true}')
return success()
end
function testJavaScriptJsonParse()
local js = [[
var json = '{"a":1, "b": "two", "c": true}';
obj = JSON.parse(json);
obj;
]]
local status, object, descriptor = hs.osascript.javascript(js)
assertIsEqual(status, true)
assertIsEqual(object.a, 1)
assertIsEqual(object.b, "two")
assertIsEqual(object.c, true)
return success()
end
function testJavaScriptJsonParseError()
local js = [[
var json = '{"a":1, "b": "two", c: true}';
obj = JSON.parse(json);
obj;
]]
local status, object, descriptor = hs.osascript.javascript(js)
assertFalse(status)
assertIsEqual(descriptor.OSAScriptErrorBriefMessageKey, "Error on line 2: SyntaxError: JSON Parse error: Property name must be a string literal")
return success()
end
|
hs.osascript = require("hs.osascript")
function testJavaScriptParseError()
local js = "2 +"
local status, object, descriptor = hs.osascript.javascript(js)
assertFalse(status)
assertIsEqual(descriptor.OSAScriptErrorBriefMessageKey, "Error on line 1: SyntaxError: Unexpected end of script")
return success()
end
function testJavaScriptAddition()
local js = "2+2"
local status, object, descriptor = hs.osascript.javascript(js)
assertTrue(status)
assertIsEqual(object, 4)
return success()
end
function testJavaScriptDestructuring()
local js = [[
var obj = { cat: 1, dog: 2 };
var { cat, dog } = obj;
cat + dog;
]]
local status, object, descriptor = hs.osascript.javascript(js)
assertTrue(status)
assertIsEqual(object, 3)
return success()
end
function testJavaScriptString()
local js = [[
var str1 = "Hello", str2 = "World";
str1 + ", " + str2 + "!";
]]
local status, object, descriptor = hs.osascript.javascript(js)
assertTrue(status)
assertIsEqual(object, "Hello, World!")
return success()
end
function testJavaScriptArray()
local js = [[
[1, "a", 3.14, "b", null, false]
]]
local status, object, descriptor = hs.osascript.javascript(js)
assertTrue(status)
assertIsEqual(object[1], 1)
assertIsEqual(object[2], "a")
assertIsEqual(object[3], 3.14)
assertIsEqual(object[4], "b")
assertIsEqual(object[5], false)
return success()
end
function testJavaScriptJsonStringify()
local js = [[
var obj = {
a: 1,
"b": "two",
"c": true
};
json = JSON.stringify(obj);
json;
]]
local status, object, descriptor = hs.osascript.javascript(js)
assertTrue(status)
assertIsEqual(object, '{"a":1,"b":"two","c":true}')
return success()
end
function testJavaScriptJsonParse()
local js = [[
var json = '{"a":1, "b": "two", "c": true}';
obj = JSON.parse(json);
obj;
]]
local status, object, descriptor = hs.osascript.javascript(js)
assertIsEqual(status, true)
assertIsEqual(object.a, 1)
assertIsEqual(object.b, "two")
assertIsEqual(object.c, true)
return success()
end
function testJavaScriptJsonParseError()
local js = [[
var json = '{"a":1, "b": "two", c: true}';
obj = JSON.parse(json);
obj;
]]
local status, object, descriptor = hs.osascript.javascript(js)
assertFalse(status)
assertIsEqual("Error: SyntaxError: JSON Parse error: Property name must be a string literal", descriptor.OSAScriptErrorBriefMessageKey)
return success()
end
|
Fix an hs.osascript test: it had assertIsEqual() arguments backwards, and the error message it was looking for, seems to have changed
|
Fix an hs.osascript test: it had assertIsEqual() arguments backwards, and the error message it was looking for, seems to have changed
|
Lua
|
mit
|
latenitefilms/hammerspoon,cmsj/hammerspoon,Habbie/hammerspoon,cmsj/hammerspoon,CommandPost/CommandPost-App,Habbie/hammerspoon,CommandPost/CommandPost-App,asmagill/hammerspoon,cmsj/hammerspoon,asmagill/hammerspoon,latenitefilms/hammerspoon,asmagill/hammerspoon,latenitefilms/hammerspoon,CommandPost/CommandPost-App,Hammerspoon/hammerspoon,asmagill/hammerspoon,Habbie/hammerspoon,Habbie/hammerspoon,Hammerspoon/hammerspoon,Habbie/hammerspoon,CommandPost/CommandPost-App,cmsj/hammerspoon,cmsj/hammerspoon,CommandPost/CommandPost-App,CommandPost/CommandPost-App,cmsj/hammerspoon,Hammerspoon/hammerspoon,latenitefilms/hammerspoon,asmagill/hammerspoon,asmagill/hammerspoon,Hammerspoon/hammerspoon,latenitefilms/hammerspoon,Habbie/hammerspoon,Hammerspoon/hammerspoon,latenitefilms/hammerspoon,Hammerspoon/hammerspoon
|
8992a6e549f398bd6edd44e8c055025887b53d76
|
share/lua/playlist/cue.lua
|
share/lua/playlist/cue.lua
|
--[[
Parse CUE files
$Id$
Copyright (C) 2009 Laurent Aimar
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.
--]]
-- Probe function.
function probe()
if( not string.match( string.upper( vlc.path ), ".CUE$" ) ) then
return false
end
header = vlc.peek( 2048 )
return string.match( header, "FILE.*WAVE%s*[\r\n]+" ) or
string.match( header, "FILE.*AIFF%s*[\r\n]+" ) or
string.match( header, "FILE.*MP3%s*[\r\n]+" )
end
-- Helpers
function cue_string( src )
local sub = string.match( src, "^\"(.*)\".*$" );
if( sub ) then
return sub
end
return string.match( src, "^(%S+).*$" )
end
function cue_path( src )
if( string.match( src, "^/" ) or
string.match( src, "^\\" ) or
string.match( src, "^[%l%u]:\\" ) ) then
return vlc.strings.make_uri(src)
end
local slash = string.find( string.reverse( vlc.path ), '/' )
local prefix = vlc.access .. "://" .. string.sub( vlc.path, 1, -slash )
-- FIXME: postfix may not be encoded correctly (esp. slashes)
local postfix = vlc.strings.encode_uri_component(src)
return prefix .. postfix
end
function cue_track( global, track )
if( track.index01 == nil ) then
return nil
end
t = {}
t.path = cue_path( track.file or global.file )
t.title = track.title
t.album = global.title
t.artist = track.performer or global.performer
t.genre = track.genre or global.genre
t.date = track.date or global.date
t.description = global.comment
t.tracknum = track.num
t.options = { ":start-time=" .. math.floor(track.index01) }
return t
end
function cue_append( tracks, global, track )
local t = cue_track( global, track )
if( t ~= nil ) then
if( #tracks > 0 ) then
local prev = tracks[#tracks]
table.insert( prev.options, ":stop-time=" .. math.floor(track.index01) )
end
table.insert( tracks, t )
end
end
-- Parse function.
function parse()
p = {}
global_data = nil
data = {}
file = nil
while true
do
line = vlc.readline()
if not line then break end
cmd, arg = string.match( line, "^%s*(%S+)%s*(.*)$" )
if( cmd == "REM" and arg ) then
subcmd, value = string.match( arg, "^(%S+)%s*(.*)$" )
if( subcmd == "GENRE" and value ) then
data.genre = cue_string( value )
elseif( subcmd == "DATE" and value ) then
data.date = cue_string( value )
elseif( subcmd == "COMMENT" and value ) then
data.comment = cue_string( value )
end
elseif( cmd == "PERFORMER" and arg ) then
data.performer = cue_string( arg )
elseif( cmd == "TITLE" and arg ) then
data.title = cue_string( arg )
elseif( cmd == "FILE" ) then
file = cue_string( arg )
elseif( cmd == "TRACK" ) then
if( not global_data ) then
global_data = data
else
cue_append( p, global_data, data )
end
data = { file = file, num = string.match( arg, "^(%d+)" ) }
elseif( cmd == "INDEX" ) then
local idx, m, s, f = string.match( arg, "(%d+)%s+(%d+):(%d+):(%d+)" )
if( idx == "01" and m ~= nil and s ~= nil and f ~= nil ) then
data.index01 = m * 60 + s + f / 75
end
end
end
cue_append( p, global_data, data )
return p
end
|
--[[
Parse CUE files
$Id$
Copyright (C) 2009 Laurent Aimar
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.
--]]
-- Probe function.
function probe()
if( not string.match( string.upper( vlc.path ), ".CUE$" ) ) then
return false
end
header = vlc.peek( 2048 )
return string.match( header, "FILE.*WAVE%s*[\r\n]+" ) or
string.match( header, "FILE.*AIFF%s*[\r\n]+" ) or
string.match( header, "FILE.*MP3%s*[\r\n]+" )
end
-- Helpers
function is_utf8( src )
return vlc.strings.from_charset( "UTF-8", src ) == src
end
function cue_string( src )
if not is_utf8( src ) then
-- Convert to UTF-8 since it's probably Latin1
src = vlc.strings.from_charset( "ISO_8859-1", src )
end
local sub = string.match( src, "^\"(.*)\".*$" );
if( sub ) then
return sub
end
return string.match( src, "^(%S+).*$" )
end
function cue_path( src )
if( string.match( src, "^/" ) or
string.match( src, "^\\" ) or
string.match( src, "^[%l%u]:\\" ) ) then
return vlc.strings.make_uri(src)
end
local slash = string.find( string.reverse( vlc.path ), '/' )
local prefix = vlc.access .. "://" .. string.sub( vlc.path, 1, -slash )
-- FIXME: postfix may not be encoded correctly (esp. slashes)
local postfix = vlc.strings.encode_uri_component(src)
return prefix .. postfix
end
function cue_track( global, track )
if( track.index01 == nil ) then
return nil
end
t = {}
t.path = cue_path( track.file or global.file )
t.title = track.title
t.album = global.title
t.artist = track.performer or global.performer
t.genre = track.genre or global.genre
t.date = track.date or global.date
t.description = global.comment
t.tracknum = track.num
t.options = { ":start-time=" .. math.floor(track.index01) }
return t
end
function cue_append( tracks, global, track )
local t = cue_track( global, track )
if( t ~= nil ) then
if( #tracks > 0 ) then
local prev = tracks[#tracks]
table.insert( prev.options, ":stop-time=" .. math.floor(track.index01) )
end
table.insert( tracks, t )
end
end
-- Parse function.
function parse()
p = {}
global_data = nil
data = {}
file = nil
while true
do
line = vlc.readline()
if not line then break end
cmd, arg = string.match( line, "^%s*(%S+)%s*(.*)$" )
if( cmd == "REM" and arg ) then
subcmd, value = string.match( arg, "^(%S+)%s*(.*)$" )
if( subcmd == "GENRE" and value ) then
data.genre = cue_string( value )
elseif( subcmd == "DATE" and value ) then
data.date = cue_string( value )
elseif( subcmd == "COMMENT" and value ) then
data.comment = cue_string( value )
end
elseif( cmd == "PERFORMER" and arg ) then
data.performer = cue_string( arg )
elseif( cmd == "TITLE" and arg ) then
data.title = cue_string( arg )
elseif( cmd == "FILE" ) then
file = cue_string( arg )
elseif( cmd == "TRACK" ) then
if( not global_data ) then
global_data = data
else
cue_append( p, global_data, data )
end
data = { file = file, num = string.match( arg, "^(%d+)" ) }
elseif( cmd == "INDEX" ) then
local idx, m, s, f = string.match( arg, "(%d+)%s+(%d+):(%d+):(%d+)" )
if( idx == "01" and m ~= nil and s ~= nil and f ~= nil ) then
data.index01 = m * 60 + s + f / 75
end
end
end
cue_append( p, global_data, data )
return p
end
|
cue: support Latin1 cue files (fix #9238)
|
cue: support Latin1 cue files (fix #9238)
(cherry picked from commit 3e43d99c32e4367dcd1908551c1a4f50bb2dbccd)
Signed-off-by: Jean-Baptiste Kempf <[email protected]>
|
Lua
|
lgpl-2.1
|
vlc-mirror/vlc-2.1,vlc-mirror/vlc-2.1,vlc-mirror/vlc-2.1,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.1,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.1,jomanmuk/vlc-2.1,jomanmuk/vlc-2.1,jomanmuk/vlc-2.1,jomanmuk/vlc-2.1,vlc-mirror/vlc-2.1,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.1
|
8cb56e3105bb44eb785aa767df828fec61e28a52
|
share/lua/intf/hotkeys.lua
|
share/lua/intf/hotkeys.lua
|
--[==========================================================================[
hotkeys.lua: hotkey handling for VLC
--[==========================================================================[
Copyright (C) 2007 the VideoLAN team
$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.
--]==========================================================================]
--[==========================================================================[
This is meant to replace modules/control/hotkeys.c
(which will require some changes in the VLC core hotkeys stuff)
--]==========================================================================]
require("common")
--common.table_print(vlc,"vlc.\t")
bindings = {
["Ctrl-q"] = "quit",
["Space"] = "play-pause",
[113] --[[q]] = "quit",
[119] --[[w]] = "demo",
[120] --[[x]] = "demo2",
}
function quit()
print("Bye-bye!")
vlc.quit()
end
function demo()
vlc.osd.icon("speaker")
end
function demo2()
if not channel1 then
channel1 = vlc.osd.channel_register()
channel2 = vlc.osd.channel_register()
end
vlc.osd.message("Hey!",channel1)
vlc.osd.slider( 10, "horizontal", channel2 )
end
function action(func,delta)
return { func = func, delta = delta or 0, last = 0, times = 0 }
end
actions = {
["quit"] = action(quit),
["play-pause"] = action(play_pause),
["demo"] = action(demo),
["demo2"] = action(demo2),
}
action = nil
queue = {}
function action_trigger( action )
print("action_trigger:",tostring(action))
local a = actions[action]
if a then
local date = vlc.misc.mdate()
if a.delta and date > a.last + a.delta then
a.times = 0
else
a.times = a.times + 1
end
a.last = date
table.insert(queue,action)
vlc.misc.signal()
else
vlc.msg.err("Key `"..key.."' points to unknown action `"..bindings[key].."'.")
end
end
function key_press( var, old, new, data )
local key = new
print("key_press:",tostring(key))
if bindings[key] then
action_trigger(bindings[key])
else
vlc.msg.err("Key `"..key.."' isn't bound to any action.")
end
end
vlc.var.add_callback( vlc.object.libvlc(), "key-pressed", key_press )
--vlc.var.add_callback( vlc.object.libvlc(), "action-triggered", action_trigger )
while not die do
if #queue ~= 0 then
local action = actions[queue[1]]
local ok, msg = pcall( action.func )
if not ok then
vlc.msg.err("Error while executing action `"..queue[1].."': "..msg)
end
table.remove(queue,1)
else
die = vlc.misc.lock_and_wait()
end
end
-- Clean up
vlc.var.del_callback( vlc.object.libvlc(), "key-pressed", key_press )
--vlc.var.del_callback( vlc.object.libvlc(), "action-triggered", action_trigger )
|
--[==========================================================================[
hotkeys.lua: hotkey handling for VLC
--[==========================================================================[
Copyright (C) 2007 the VideoLAN team
$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.
--]==========================================================================]
--[==========================================================================[
This is meant to replace modules/control/hotkeys.c
(which will require some changes in the VLC core hotkeys stuff)
--]==========================================================================]
require("common")
--common.table_print(vlc,"vlc.\t")
bindings = {
["Ctrl-q"] = "quit",
["Space"] = "play-pause",
[113] --[[q]] = "quit",
[119] --[[w]] = "demo",
[120] --[[x]] = "demo2",
}
function quit()
print("Bye-bye!")
vlc.misc.quit()
end
function demo()
vlc.osd.icon("speaker")
end
function demo2()
if not channel1 then
channel1 = vlc.osd.channel_register()
channel2 = vlc.osd.channel_register()
end
vlc.osd.message("Hey!",channel1)
vlc.osd.slider( 10, "horizontal", channel2 )
end
function action(func,delta)
return { func = func, delta = delta or 0, last = 0, times = 0 }
end
actions = {
["quit"] = action(quit),
["play-pause"] = action(play_pause),
["demo"] = action(demo),
["demo2"] = action(demo2),
}
action = nil
queue = {}
function action_trigger( action )
print("action_trigger:",tostring(action))
local a = actions[action]
if a then
local ok, msg = pcall( a.func )
if not ok then
vlc.msg.err("Error while executing action `".. tostring(action) .."': "..msg)
end
else
vlc.msg.err("Key `"..key.."' points to unknown action `"..bindings[key].."'.")
end
end
function key_press( var, old, key, data )
print("key_press:",tostring(key))
if bindings[key] then
action_trigger(bindings[key])
else
vlc.msg.err("Key `"..key.."' isn't bound to any action.")
end
end
vlc.var.add_callback( vlc.object.libvlc(), "key-pressed", key_press )
--vlc.var.add_callback( vlc.object.libvlc(), "action-triggered", action_trigger )
while not vlc.misc.lock_and_wait() do
end
-- Clean up
vlc.var.del_callback( vlc.object.libvlc(), "key-pressed", key_press )
--vlc.var.del_callback( vlc.object.libvlc(), "action-triggered", action_trigger )
|
lua: fix hotkeys demo file.
|
lua: fix hotkeys demo file.
|
Lua
|
lgpl-2.1
|
jomanmuk/vlc-2.1,vlc-mirror/vlc,krichter722/vlc,jomanmuk/vlc-2.1,vlc-mirror/vlc-2.1,vlc-mirror/vlc,vlc-mirror/vlc,vlc-mirror/vlc,shyamalschandra/vlc,krichter722/vlc,jomanmuk/vlc-2.2,jomanmuk/vlc-2.2,krichter722/vlc,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.1,jomanmuk/vlc-2.1,vlc-mirror/vlc-2.1,shyamalschandra/vlc,shyamalschandra/vlc,xkfz007/vlc,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.2,shyamalschandra/vlc,jomanmuk/vlc-2.2,jomanmuk/vlc-2.1,shyamalschandra/vlc,shyamalschandra/vlc,krichter722/vlc,xkfz007/vlc,jomanmuk/vlc-2.2,jomanmuk/vlc-2.1,xkfz007/vlc,vlc-mirror/vlc-2.1,xkfz007/vlc,vlc-mirror/vlc,jomanmuk/vlc-2.2,krichter722/vlc,jomanmuk/vlc-2.2,xkfz007/vlc,shyamalschandra/vlc,xkfz007/vlc,vlc-mirror/vlc,vlc-mirror/vlc,vlc-mirror/vlc-2.1,krichter722/vlc,jomanmuk/vlc-2.1,krichter722/vlc,vlc-mirror/vlc-2.1,xkfz007/vlc
|
f5cbd0dd90a6afaa4ef67b4414df602ce8bf6ec9
|
share/lua/website/tcmag.lua
|
share/lua/website/tcmag.lua
|
-- libquvi-scripts
-- Copyright (C) 2011 quvi project
--
-- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>.
--
-- This library is free software; you can redistribute it and/or
-- modify it under the terms of the GNU Lesser General Public
-- License as published by the Free Software Foundation; either
-- version 2.1 of the License, or (at your option) any later version.
--
-- This library is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-- Lesser General Public License for more details.
--
-- You should have received a copy of the GNU Lesser General Public
-- License along with this library; if not, write to the Free Software
-- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
-- 02110-1301 USA
--
-- Identify the script.
function ident (self)
package.path = self.script_dir .. '/?.lua'
local C = require 'quvi/const'
local r = {}
r.domain = "tcmag%.com"
r.formats = "default"
r.categories = C.proto_http
local U = require 'quvi/util'
r.handles = U.handles(self.page_url, {r.domain}, {"/magazine/.+"})
return r
end
-- Query available formats.
function query_formats(self)
self.formats = 'default'
return self
end
-- Parse media URL.
function parse (self)
self.host_id = "tcmag"
local page = quvi.fetch(self.page_url)
local _,_,s = page:find('<article id="article">(.-)</article>')
local article = s or error ("no match: article")
local _,_,s = article:find('http://.*youtube.com/embed/([^/]-)"')
if s then
-- Hand over to youtube.lua
self.redirect_url = 'http://youtube.com/watch?v=' .. s
return self
end
local _,_,s = article:find('http://.*vimeo.com/video/([0-9]+)')
if s then
-- Hand over to vimeo.lua
self.redirect_url = 'http://vimeo.com/video/' .. s
return self
end
local _,_,s = article:find("'file': '(.-)',")
self.url = {s or error ("no match: media url")}
local url = s
local _,_,s = article:find('<h1>(.-)</h1>')
self.title = s or error ("no match: media title")
local _,_,s = url:find("/(.-)/sizes/")
self.id = s or error ("no match: media id")
return self
end
-- vim: set ts=4 sw=4 tw=72 expandtab:
|
-- libquvi-scripts
-- Copyright (C) 2011 quvi project
--
-- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>.
--
-- This library is free software; you can redistribute it and/or
-- modify it under the terms of the GNU Lesser General Public
-- License as published by the Free Software Foundation; either
-- version 2.1 of the License, or (at your option) any later version.
--
-- This library is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-- Lesser General Public License for more details.
--
-- You should have received a copy of the GNU Lesser General Public
-- License along with this library; if not, write to the Free Software
-- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
-- 02110-1301 USA
--
local TCMag = {} -- Utility functions specific to this script
-- Identify the script.
function ident(self)
package.path = self.script_dir .. '/?.lua'
local C = require 'quvi/const'
local r = {}
r.domain = "tcmag%.com"
r.formats = "default"
r.categories = C.proto_http
local U = require 'quvi/util'
r.handles = U.handles(self.page_url, {r.domain}, {"/magazine/.+"})
return r
end
-- Query available formats.
function query_formats(self)
self.formats = 'default'
return TCMag.check_external_content(self)
end
-- Parse media URL.
function parse(self)
self.host_id = "tcmag"
return TCMag.check_external_content(self)
end
--
-- Utility functions
--
function TCMag.check_external_content(self)
local page = quvi.fetch(self.page_url)
local article = page:match('<article id="article">(.-)</article>')
or error("no match: article")
local s = article:match('http://.*youtube.com/embed/([^/]-)"')
if s then -- Hand over to youtube.lua
self.redirect_url = 'http://youtube.com/watch?v=' .. s
return self
end
local s = article:match('http://.*vimeo.com/video/([0-9]+)')
if s then -- Hand over to vimeo.lua
self.redirect_url = 'http://vimeo.com/video/' .. s
return self
end
local s = article:match('http://.*liveleak.com/e/([%w_]+)')
if s then -- Hand over to liveleak.lua
self.redirect_url = 'http://liveleak.com/e/' .. s
return self
end
self.title = article:match('<h1>(.-)</h1>')
or error ("no match: media title")
self.url = {article:match("'file': '(.-)',")
or error("no match: media url")}
self.id = self.url[1]:match("/%d+/%d+/(.-)/sizes/")
or error ("no match: media id")
return self
end
-- vim: set ts=4 sw=4 tw=72 expandtab:
|
tcmag.lua: Make query_formats work with external content
|
tcmag.lua: Make query_formats work with external content
Additional changes
* Check for liveleak content
* Fix self.id pattern
|
Lua
|
agpl-3.0
|
alech/libquvi-scripts,DangerCove/libquvi-scripts,legatvs/libquvi-scripts,alech/libquvi-scripts,hadess/libquvi-scripts-iplayer,DangerCove/libquvi-scripts,legatvs/libquvi-scripts,hadess/libquvi-scripts-iplayer
|
0e8712177e7ff072d7ae5ffba5f9857e3dd27c0e
|
OvaleCooldown.lua
|
OvaleCooldown.lua
|
--[[--------------------------------------------------------------------
Ovale Spell Priority
Copyright (C) 2012 Sidoine
Copyright (C) 2012, 2013 Johnny C. Lam
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License in the LICENSE
file accompanying this program.
--]]--------------------------------------------------------------------
local _, Ovale = ...
local OvaleCooldown = Ovale:NewModule("OvaleCooldown")
Ovale.OvaleCooldown = OvaleCooldown
--<private-static-properties>
local OvaleData = Ovale.OvaleData
local OvalePaperDoll = Ovale.OvalePaperDoll
local OvaleStance = Ovale.OvaleStance
local OvaleState = Ovale.OvaleState
local API_UnitHealth = UnitHealth
local API_UnitHealthMax = UnitHealthMax
local API_UnitClass = UnitClass
-- Player's class.
local self_class = select(2, API_UnitClass("player"))
--</private-static-properties>
--<public-static-methods>
function OvaleCooldown:OnEnable()
OvaleState:RegisterState(self, self.statePrototype)
end
function OvaleCooldown:OnDisable()
OvaleState:UnregisterState(self)
end
-- Return the GCD after the given spellId is cast.
-- If no spellId is given, then returns the GCD after a "yellow-hit" ability has been cast.
function OvaleCooldown:GetGCD(spellId)
-- Base global cooldown.
local isCaster = false
if self_class == "DEATHKNIGHT" then
cd = 1.0
elseif self_class == "DRUID" and OvaleStance:IsStance("druid_cat_form") then
cd = 1.0
elseif self_class == "MONK" then
cd = 1.0
elseif self_class == "ROGUE" then
cd = 1.0
else
isCaster = true
cd = 1.5
end
-- Use SpellInfo() information if available.
if spellId and OvaleData.spellInfo[spellId] then
local si = OvaleData.spellInfo[spellId]
if si.gcd then
cd = si.gcd
end
if si.haste then
if si.haste == "melee" then
cd = cd / OvalePaperDoll:GetMeleeHasteMultiplier()
elseif si.haste == "spell" then
cd = cd / OvalePaperDoll:GetSpellHasteMultiplier()
end
end
elseif isCaster then
cd = cd / OvalePaperDoll:GetSpellHasteMultiplier()
end
-- Clamp GCD at 1s.
cd = (cd > 1) and cd or 1
return cd
end
--</public-static-methods>
--[[----------------------------------------------------------------------------
State machine for simulator.
--]]----------------------------------------------------------------------------
--<public-static-properties>
OvaleCooldown.statePrototype = {
cd = nil,
}
--</public-static-properties>
--<public-static-methods>
-- Initialize the state.
function OvaleCooldown:InitializeState(state)
state.cd = {}
end
-- Reset the state to the current conditions.
function OvaleCooldown:ResetState(state)
for _, cd in pairs(state.cd) do
cd.start = nil
cd.duration = nil
cd.enable = 0
cd.toggled = nil
end
end
-- Apply the effects of the spell on the player's state, assuming the spellcast completes.
function OvaleCooldown:ApplySpellOnPlayer(state, spellId, startCast, endCast, nextCast, nocd, targetGUID, spellcast)
-- If the spellcast has already ended, then the effects on the player have already occurred.
if endCast <= OvaleState.now then
return
end
local si = OvaleData.spellInfo[spellId]
if si then
local cd = state:GetCD(spellId)
if cd then
cd.start = startCast
cd.duration = si.cd or 0
-- Test for no cooldown.
if nocd then
cd.duration = 0
else
-- There is no cooldown if the buff named by "buffnocd" parameter is present.
if si.buffnocd then
local start, ending, stacks = state:GetAura("player", si.buffnocd)
if start and stacks and stacks > 0 then
Ovale:Logf("buffnocd stacks = %s, start = %s, ending = %s, startCast = %f", stacks, start, ending, startCast)
-- XXX Shouldn't this be (not ending or ending > endCast)?
-- XXX The spellcast needs to finish before the buff expires.
if start <= startCast and (not ending or ending > startCast) then
cd.duration = 0
end
end
end
-- There is no cooldown if the target's health percent is below what's specified
-- with the "targetlifenocd" parameter.
if si.targetlifenocd then
local healthPercent = API_UnitHealth("target") / API_UnitHealthMax("target") * 100
if healthPercent < si.targetlifenocd then
cd.duration = 0
end
end
end
-- Adjust cooldown duration if it is affected by haste: "cd_haste=melee" or "cd_haste=spell".
if cd.duration > 0 and si.cd_haste then
if si.cd_haste == "melee" then
cd.duration = cd.duration / OvalePaperDoll:GetMeleeHasteMultiplier()
elseif si.cd_haste == "spell" then
cd.duration = cd.duration / OvalePaperDoll:GetSpellHasteMultiplier()
end
end
cd.enable = 1
if si.toggle then
cd.toggled = 1
end
Ovale:Logf("Spell %d cooldown info: start=%f, duration=%f", spellId, cd.start, cd.duration)
end
end
end
--</public-static-methods>
-- Mix-in methods for simulator state.
do
local statePrototype = OvaleCooldown.statePrototype
-- Return the table holding the simulator's cooldown information for the given spell.
function statePrototype:GetCD(spellId)
local state = self
if spellId then
local si = OvaleData.spellInfo[spellId]
if si and si.cd then
local cdname = si.sharedcd and si.sharedcd or spellId
if not state.cd[cdname] then
state.cd[cdname] = {}
end
return state.cd[cdname]
end
end
return nil
end
-- Return the cooldown for the spell in the simulator.
function statePrototype:GetSpellCooldown(spellId)
local state = self
local start, duration, enable
local cd = state:GetCD(spellId)
if cd and cd.start then
start = cd.start
duration = cd.duration
enable = cd.enable
else
start, duration, enable = OvaleData:GetSpellCooldown(spellId)
end
return start, duration, enable
end
-- Force the cooldown of a spell to reset at the specified time.
function statePrototype:ResetSpellCooldown(spellId, atTime)
local state = self
if atTime >= OvaleState.currentTime then
local cd = state:GetCD(spellId)
cd.start = OvaleState.currentTime
cd.duration = atTime - OvaleState.currentTime
cd.enable = 1
end
end
end
|
--[[--------------------------------------------------------------------
Ovale Spell Priority
Copyright (C) 2012 Sidoine
Copyright (C) 2012, 2013 Johnny C. Lam
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License in the LICENSE
file accompanying this program.
--]]--------------------------------------------------------------------
local _, Ovale = ...
local OvaleCooldown = Ovale:NewModule("OvaleCooldown")
Ovale.OvaleCooldown = OvaleCooldown
--<private-static-properties>
local OvaleData = Ovale.OvaleData
local OvaleGUID = Ovale.OvaleGUID
local OvalePaperDoll = Ovale.OvalePaperDoll
local OvaleStance = Ovale.OvaleStance
local OvaleState = Ovale.OvaleState
local API_UnitHealth = UnitHealth
local API_UnitHealthMax = UnitHealthMax
local API_UnitClass = UnitClass
-- Player's class.
local self_class = select(2, API_UnitClass("player"))
--</private-static-properties>
--<public-static-methods>
function OvaleCooldown:OnEnable()
OvaleState:RegisterState(self, self.statePrototype)
end
function OvaleCooldown:OnDisable()
OvaleState:UnregisterState(self)
end
-- Return the GCD after the given spellId is cast.
-- If no spellId is given, then returns the GCD after a "yellow-hit" ability has been cast.
function OvaleCooldown:GetGCD(spellId)
-- Base global cooldown.
local isCaster = false
if self_class == "DEATHKNIGHT" then
cd = 1.0
elseif self_class == "DRUID" and OvaleStance:IsStance("druid_cat_form") then
cd = 1.0
elseif self_class == "MONK" then
cd = 1.0
elseif self_class == "ROGUE" then
cd = 1.0
else
isCaster = true
cd = 1.5
end
-- Use SpellInfo() information if available.
if spellId and OvaleData.spellInfo[spellId] then
local si = OvaleData.spellInfo[spellId]
if si.gcd then
cd = si.gcd
end
if si.haste then
if si.haste == "melee" then
cd = cd / OvalePaperDoll:GetMeleeHasteMultiplier()
elseif si.haste == "spell" then
cd = cd / OvalePaperDoll:GetSpellHasteMultiplier()
end
end
elseif isCaster then
cd = cd / OvalePaperDoll:GetSpellHasteMultiplier()
end
-- Clamp GCD at 1s.
cd = (cd > 1) and cd or 1
return cd
end
--</public-static-methods>
--[[----------------------------------------------------------------------------
State machine for simulator.
--]]----------------------------------------------------------------------------
--<public-static-properties>
OvaleCooldown.statePrototype = {
cd = nil,
}
--</public-static-properties>
--<public-static-methods>
-- Initialize the state.
function OvaleCooldown:InitializeState(state)
state.cd = {}
end
-- Reset the state to the current conditions.
function OvaleCooldown:ResetState(state)
for _, cd in pairs(state.cd) do
cd.start = nil
cd.duration = nil
cd.enable = 0
cd.toggled = nil
end
end
-- Apply the effects of the spell on the player's state, assuming the spellcast completes.
function OvaleCooldown:ApplySpellOnPlayer(state, spellId, startCast, endCast, nextCast, nocd, targetGUID, spellcast)
-- If the spellcast has already ended, then the effects on the player have already occurred.
if endCast <= OvaleState.now then
return
end
local si = OvaleData.spellInfo[spellId]
if si then
local cd = state:GetCD(spellId)
if cd then
cd.start = startCast
cd.duration = si.cd or 0
-- Test for no cooldown.
if nocd then
cd.duration = 0
else
-- There is no cooldown if the buff named by "buffnocd" parameter is present.
if si.buffnocd then
local start, ending, stacks = state:GetAura("player", si.buffnocd)
if start and stacks and stacks > 0 then
Ovale:Logf("buffnocd stacks = %s, start = %s, ending = %s, startCast = %f", stacks, start, ending, startCast)
-- XXX Shouldn't this be (not ending or ending > endCast)?
-- XXX The spellcast needs to finish before the buff expires.
if start <= startCast and (not ending or ending > startCast) then
cd.duration = 0
end
end
end
-- There is no cooldown if the target's health percent is below what's specified
-- with the "targetlifenocd" parameter.
local target = OvaleGUID:GetUnitId(targetGUID)
if target and si.targetlifenocd then
local healthPercent = API_UnitHealth(target) / API_UnitHealthMax(target) * 100
if healthPercent < si.targetlifenocd then
cd.duration = 0
end
end
end
-- Adjust cooldown duration if it is affected by haste: "cd_haste=melee" or "cd_haste=spell".
if cd.duration > 0 and si.cd_haste then
if si.cd_haste == "melee" then
cd.duration = cd.duration / OvalePaperDoll:GetMeleeHasteMultiplier()
elseif si.cd_haste == "spell" then
cd.duration = cd.duration / OvalePaperDoll:GetSpellHasteMultiplier()
end
end
cd.enable = 1
if si.toggle then
cd.toggled = 1
end
Ovale:Logf("Spell %d cooldown info: start=%f, duration=%f", spellId, cd.start, cd.duration)
end
end
end
--</public-static-methods>
-- Mix-in methods for simulator state.
do
local statePrototype = OvaleCooldown.statePrototype
-- Return the table holding the simulator's cooldown information for the given spell.
function statePrototype:GetCD(spellId)
local state = self
if spellId then
local si = OvaleData.spellInfo[spellId]
if si and si.cd then
local cdname = si.sharedcd and si.sharedcd or spellId
if not state.cd[cdname] then
state.cd[cdname] = {}
end
return state.cd[cdname]
end
end
return nil
end
-- Return the cooldown for the spell in the simulator.
function statePrototype:GetSpellCooldown(spellId)
local state = self
local start, duration, enable
local cd = state:GetCD(spellId)
if cd and cd.start then
start = cd.start
duration = cd.duration
enable = cd.enable
else
start, duration, enable = OvaleData:GetSpellCooldown(spellId)
end
return start, duration, enable
end
-- Force the cooldown of a spell to reset at the specified time.
function statePrototype:ResetSpellCooldown(spellId, atTime)
local state = self
if atTime >= OvaleState.currentTime then
local cd = state:GetCD(spellId)
cd.start = OvaleState.currentTime
cd.duration = atTime - OvaleState.currentTime
cd.enable = 1
end
end
end
|
Fix target used in "targetlifenocd" computation for spell cooldowns.
|
Fix target used in "targetlifenocd" computation for spell cooldowns.
git-svn-id: b2bb544abab4b09d60f88077ac82407cb244c9c9@1163 d5049fe3-3747-40f7-a4b5-f36d6801af5f
|
Lua
|
mit
|
ultijlam/ovale,ultijlam/ovale,eXhausted/Ovale,ultijlam/ovale,Xeltor/ovale,eXhausted/Ovale,eXhausted/Ovale
|
3424536e9d1075d325bd55e750ddc1879e55421b
|
kong/templates/nginx_kong.lua
|
kong/templates/nginx_kong.lua
|
return [[
charset UTF-8;
error_log logs/error.log ${{LOG_LEVEL}};
> if anonymous_reports then
${{SYSLOG_REPORTS}}
> end
> if nginx_optimizations then
>-- send_timeout 60s; # default value
>-- keepalive_timeout 75s; # default value
>-- client_body_timeout 60s; # default value
>-- client_header_timeout 60s; # default value
>-- tcp_nopush on; # disabled until benchmarked
>-- proxy_buffer_size 128k; # disabled until benchmarked
>-- proxy_buffers 4 256k; # disabled until benchmarked
>-- proxy_busy_buffers_size 256k; # disabled until benchmarked
>-- reset_timedout_connection on; # disabled until benchmarked
> end
client_max_body_size 0;
proxy_ssl_server_name on;
underscores_in_headers on;
real_ip_header X-Forwarded-For;
set_real_ip_from 0.0.0.0/0;
real_ip_recursive on;
lua_package_path '${{LUA_PACKAGE_PATH}};;';
lua_package_cpath '${{LUA_PACKAGE_CPATH}};;';
lua_code_cache ${{LUA_CODE_CACHE}};
lua_socket_pool_size ${{LUA_SOCKET_POOL_SIZE}};
lua_max_running_timers 4096;
lua_max_pending_timers 16384;
lua_shared_dict kong 4m;
lua_shared_dict cache ${{MEM_CACHE_SIZE}};
lua_shared_dict cache_locks 100k;
lua_shared_dict process_events 1m;
lua_shared_dict cassandra 5m;
lua_socket_log_errors off;
> if lua_ssl_trusted_certificate then
lua_ssl_trusted_certificate '${{LUA_SSL_TRUSTED_CERTIFICATE}}';
lua_ssl_verify_depth ${{LUA_SSL_VERIFY_DEPTH}};
> end
init_by_lua_block {
require 'resty.core'
kong = require 'kong'
kong.init()
}
init_worker_by_lua_block {
kong.init_worker()
}
proxy_next_upstream_tries 999;
upstream kong_upstream {
server 0.0.0.1;
balancer_by_lua_block {
kong.balancer()
}
keepalive ${{UPSTREAM_KEEPALIVE}};
}
map $http_upgrade $upstream_connection {
default keep-alive;
websocket upgrade;
}
map $http_upgrade $upstream_upgrade {
default '';
websocket websocket;
}
server {
server_name kong;
listen ${{PROXY_LISTEN}};
error_page 404 408 411 412 413 414 417 /kong_error_handler;
error_page 500 502 503 504 /kong_error_handler;
access_log logs/access.log;
> if ssl then
listen ${{PROXY_LISTEN_SSL}} ssl;
ssl_certificate ${{SSL_CERT}};
ssl_certificate_key ${{SSL_CERT_KEY}};
ssl_protocols TLSv1.1 TLSv1.2;
ssl_certificate_by_lua_block {
kong.ssl_certificate()
}
> end
location / {
set $upstream_host nil;
set $upstream_scheme nil;
access_by_lua_block {
kong.access()
}
proxy_http_version 1.1;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Host $upstream_host;
proxy_set_header Upgrade $upstream_upgrade;
proxy_set_header Connection $upstream_connection;
proxy_pass_header Server;
proxy_pass $upstream_scheme://kong_upstream;
header_filter_by_lua_block {
kong.header_filter()
}
body_filter_by_lua_block {
kong.body_filter()
}
log_by_lua_block {
kong.log()
}
}
location = /kong_error_handler {
internal;
content_by_lua_block {
require('kong.core.error_handlers')(ngx)
}
}
}
server {
server_name kong_admin;
listen ${{ADMIN_LISTEN}};
access_log logs/admin_access.log;
client_max_body_size 10m;
client_body_buffer_size 10m;
> if admin_ssl then
listen ${{ADMIN_LISTEN_SSL}} ssl;
ssl_certificate ${{ADMIN_SSL_CERT}};
ssl_certificate_key ${{ADMIN_SSL_CERT_KEY}};
ssl_protocols TLSv1.1 TLSv1.2;
> end
location / {
default_type application/json;
content_by_lua_block {
ngx.header['Access-Control-Allow-Origin'] = '*'
ngx.header['Access-Control-Allow-Credentials'] = 'false'
if ngx.req.get_method() == 'OPTIONS' then
ngx.header['Access-Control-Allow-Methods'] = 'GET,HEAD,PUT,PATCH,POST,DELETE'
ngx.header['Access-Control-Allow-Headers'] = 'Content-Type'
ngx.exit(204)
end
require('lapis').serve('kong.api')
}
}
location /nginx_status {
internal;
access_log off;
stub_status;
}
location /robots.txt {
return 200 'User-agent: *\nDisallow: /';
}
}
]]
|
return [[
charset UTF-8;
error_log logs/error.log ${{LOG_LEVEL}};
> if anonymous_reports then
${{SYSLOG_REPORTS}}
> end
> if nginx_optimizations then
>-- send_timeout 60s; # default value
>-- keepalive_timeout 75s; # default value
>-- client_body_timeout 60s; # default value
>-- client_header_timeout 60s; # default value
>-- tcp_nopush on; # disabled until benchmarked
>-- proxy_buffer_size 128k; # disabled until benchmarked
>-- proxy_buffers 4 256k; # disabled until benchmarked
>-- proxy_busy_buffers_size 256k; # disabled until benchmarked
>-- reset_timedout_connection on; # disabled until benchmarked
> end
client_max_body_size 0;
proxy_ssl_server_name on;
underscores_in_headers on;
real_ip_header X-Forwarded-For;
set_real_ip_from 0.0.0.0/0;
real_ip_recursive on;
lua_package_path '${{LUA_PACKAGE_PATH}};;';
lua_package_cpath '${{LUA_PACKAGE_CPATH}};;';
lua_code_cache ${{LUA_CODE_CACHE}};
lua_socket_pool_size ${{LUA_SOCKET_POOL_SIZE}};
lua_max_running_timers 4096;
lua_max_pending_timers 16384;
lua_shared_dict kong 4m;
lua_shared_dict cache ${{MEM_CACHE_SIZE}};
lua_shared_dict cache_locks 100k;
lua_shared_dict process_events 1m;
lua_shared_dict cassandra 5m;
lua_socket_log_errors off;
> if lua_ssl_trusted_certificate then
lua_ssl_trusted_certificate '${{LUA_SSL_TRUSTED_CERTIFICATE}}';
lua_ssl_verify_depth ${{LUA_SSL_VERIFY_DEPTH}};
> end
init_by_lua_block {
require 'resty.core'
kong = require 'kong'
kong.init()
}
init_worker_by_lua_block {
kong.init_worker()
}
proxy_next_upstream_tries 999;
upstream kong_upstream {
server 0.0.0.1;
balancer_by_lua_block {
kong.balancer()
}
keepalive ${{UPSTREAM_KEEPALIVE}};
}
map $http_upgrade $upstream_connection {
default keep-alive;
websocket upgrade;
}
map $http_upgrade $upstream_upgrade {
default '';
websocket websocket;
}
server {
server_name kong;
listen ${{PROXY_LISTEN}};
error_page 404 408 411 412 413 414 417 /kong_error_handler;
error_page 500 502 503 504 /kong_error_handler;
access_log logs/access.log;
> if ssl then
listen ${{PROXY_LISTEN_SSL}} ssl;
ssl_certificate ${{SSL_CERT}};
ssl_certificate_key ${{SSL_CERT_KEY}};
ssl_protocols TLSv1.1 TLSv1.2;
ssl_certificate_by_lua_block {
kong.ssl_certificate()
}
> end
location / {
set $upstream_host nil;
set $upstream_scheme nil;
access_by_lua_block {
kong.access()
}
proxy_http_version 1.1;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Host $upstream_host;
proxy_set_header Upgrade $upstream_upgrade;
proxy_set_header Connection $upstream_connection;
proxy_pass_header Server;
proxy_pass $upstream_scheme://kong_upstream;
header_filter_by_lua_block {
kong.header_filter()
}
body_filter_by_lua_block {
kong.body_filter()
}
log_by_lua_block {
kong.log()
}
}
location = /kong_error_handler {
internal;
content_by_lua_block {
require('kong.core.error_handlers')(ngx)
}
}
}
server {
server_name kong_admin;
listen ${{ADMIN_LISTEN}};
access_log logs/admin_access.log;
client_max_body_size 10m;
client_body_buffer_size 10m;
> if admin_ssl then
listen ${{ADMIN_LISTEN_SSL}} ssl;
ssl_certificate ${{ADMIN_SSL_CERT}};
ssl_certificate_key ${{ADMIN_SSL_CERT_KEY}};
ssl_protocols TLSv1.1 TLSv1.2;
> end
location / {
default_type application/json;
content_by_lua_block {
ngx.header['Access-Control-Allow-Origin'] = '*'
if ngx.req.get_method() == 'OPTIONS' then
ngx.header['Access-Control-Allow-Methods'] = 'GET,HEAD,PUT,PATCH,POST,DELETE'
ngx.header['Access-Control-Allow-Headers'] = 'Content-Type'
ngx.exit(204)
end
require('lapis').serve('kong.api')
}
}
location /nginx_status {
internal;
access_log off;
stub_status;
}
location /robots.txt {
return 200 'User-agent: *\nDisallow: /';
}
}
]]
|
fix(admin) CORS ACAC header cannot receive false
|
fix(admin) CORS ACAC header cannot receive false
Remove the ACAC header set to `false` in the Admin API.
This raises an interesting concern about the Admin API: we do not allow
requests with credentials to be made to it (since ACAC is not sent with
`true`). This might warrant an update and some testing in the future.
|
Lua
|
apache-2.0
|
salazar/kong,jebenexer/kong,Mashape/kong,Kong/kong,shiprabehera/kong,icyxp/kong,akh00/kong,Kong/kong,Kong/kong
|
12fae8966fa6e64c3cae4c25ccc67a6d00e5d65e
|
OvaleState.lua
|
OvaleState.lua
|
--[[--------------------------------------------------------------------
Copyright (C) 2012 Sidoine De Wispelaere.
Copyright (C) 2012, 2013, 2014 Johnny C. Lam.
See the file LICENSE.txt for copying permission.
--]]--------------------------------------------------------------------
--[[
This addon is the core of the state machine for the simulator.
--]]
local OVALE, Ovale = ...
local OvaleState = Ovale:NewModule("OvaleState")
Ovale.OvaleState = OvaleState
--<private-static-properties>
local L = Ovale.L
local OvaleDebug = Ovale.OvaleDebug
local OvaleQueue = Ovale.OvaleQueue
local pairs = pairs
local OVALE_STATE_DEBUG = "state"
do
OvaleDebug:RegisterDebugOption(OVALE_STATE_DEBUG, L["State machine"], L["Debug state machine"])
end
--</private-static-properties>
--<public-static-properties>
-- Registered state prototypes from which mix-in methods are added to state machines.
OvaleState.statePrototype = {}
OvaleState.stateAddons = OvaleQueue:NewQueue("OvaleState_stateAddons")
-- The state for the simulator.
OvaleState.state = {}
--</public-static-properties>
--<public-static-methods>
function OvaleState:OnEnable()
self:RegisterState(self, self.statePrototype)
end
function OvaleState:OnDisable()
self:UnregisterState(self)
end
function OvaleState:RegisterState(stateAddon, statePrototype)
self.stateAddons:Insert(stateAddon)
self.statePrototype[stateAddon] = statePrototype
-- Mix-in addon's state prototype into OvaleState.state.
for k, v in pairs(statePrototype) do
self.state[k] = v
end
end
function OvaleState:UnregisterState(stateAddon)
local stateModules = OvaleQueue:NewQueue("OvaleState_stateModules")
while self.stateAddons:Size() > 0 do
local addon = self.stateAddons:Remove()
if stateAddon ~= addon then
stateModules:Insert(addon)
end
end
self.stateAddons = stateModules
-- Release resources used by the state machine managed by the addon.
if stateAddon.CleanState then
stateAddon:CleanState(self.state)
end
-- Remove mix-in methods from addon's state prototype.
local statePrototype = self.statePrototype[stateAddon]
if statePrototype then
for k in pairs(statePrototype) do
self.state[k] = nil
end
end
self.statePrototype[stateAddon] = nil
end
function OvaleState:InvokeMethod(methodName, ...)
for _, addon in self.stateAddons:Iterator() do
if addon[methodName] then
addon[methodName](addon, ...)
end
end
end
--</public-static-methods>
--[[----------------------------------------------------------------------------
State machine for simulator.
--]]----------------------------------------------------------------------------
--<public-static-properties>
OvaleState.statePrototype = {}
--</public-static-properties>
--<private-static-properties>
local statePrototype = OvaleState.statePrototype
--</private-static-properties>
--<state-properties>
-- Whether the state of the simulator has been initialized.
statePrototype.isInitialized = nil
-- Table of state variables added by scripts that is reset on every refresh.
statePrototype.futureVariable = nil
-- Table of state variables added by scripts that is reset only when out of combat.
statePrototype.variable = nil
--</state-properties>
--<public-static-methods>
-- Initialize the state.
function OvaleState:InitializeState(state)
state.futureVariable = {}
state.variable = {}
end
-- Reset the state to the current conditions.
function OvaleState:ResetState(state)
for k in pairs(state.futureVariable) do
state.futureVariable[k] = nil
end
-- TODO: What conditions should trigger resetting state variables?
-- For now, reset/remove all state variables if out of combat.
if not Ovale.enCombat then
for k in pairs(state.variable) do
Ovale:DebugPrintf(OVALE_STATE_DEBUG, "Resetting state variable '%s'.", k)
state.variable[k] = nil
end
end
end
-- Release state resources prior to removing from the simulator.
function OvaleState:CleanState(state)
for k in pairs(state.futureVariable) do
state.futureVariable[k] = nil
end
for k in pairs(state.variable) do
state.variable[k] = nil
end
end
--</public-static-methods>
--<state-methods>
statePrototype.Initialize = function(state)
if not state.isInitialized then
OvaleState:InvokeMethod("InitializeState", state)
state.isInitialized = true
end
end
statePrototype.Reset = function(state)
OvaleState:InvokeMethod("ResetState", state)
end
-- Get the value of the named state variable. If missing, then return 0.
statePrototype.GetState = function(state, name)
return state.futureVariable[name] or state.variable[name] or 0
end
-- Put a value into the named state variable.
statePrototype.PutState = function(state, name, value, isFuture)
if isFuture then
Ovale:Logf("Setting future state: %s = %s.", name, value)
state.futureVariable[name] = value
else
Ovale:DebugPrintf(OVALE_STATE_DEBUG, "Advancing combat state: %s = %s.", name, value)
Ovale:Logf("Advancing combat state: %s = %s.", name, value)
state.variable[name] = value
end
end
--</state-methods>
|
--[[--------------------------------------------------------------------
Copyright (C) 2012 Sidoine De Wispelaere.
Copyright (C) 2012, 2013, 2014 Johnny C. Lam.
See the file LICENSE.txt for copying permission.
--]]--------------------------------------------------------------------
--[[
This addon is the core of the state machine for the simulator.
--]]
local OVALE, Ovale = ...
local OvaleState = Ovale:NewModule("OvaleState")
Ovale.OvaleState = OvaleState
--<private-static-properties>
local L = Ovale.L
local OvaleDebug = Ovale.OvaleDebug
local OvaleQueue = Ovale.OvaleQueue
local pairs = pairs
-- Registered state prototypes from which mix-in methods are added to state machines.
local self_statePrototype = {}
local self_stateAddons = OvaleQueue:NewQueue("OvaleState_stateAddons")
local OVALE_STATE_DEBUG = "state"
do
OvaleDebug:RegisterDebugOption(OVALE_STATE_DEBUG, L["State machine"], L["Debug state machine"])
end
--</private-static-properties>
--<public-static-properties>
-- The state for the simulator.
OvaleState.state = {}
--</public-static-properties>
--<public-static-methods>
function OvaleState:OnEnable()
self:RegisterState(self, self.statePrototype)
end
function OvaleState:OnDisable()
self:UnregisterState(self)
end
function OvaleState:RegisterState(stateAddon, statePrototype)
self_stateAddons:Insert(stateAddon)
self_statePrototype[stateAddon] = statePrototype
-- Mix-in addon's state prototype into OvaleState.state.
for k, v in pairs(statePrototype) do
self.state[k] = v
end
end
function OvaleState:UnregisterState(stateAddon)
local stateModules = OvaleQueue:NewQueue("OvaleState_stateModules")
while self_stateAddons:Size() > 0 do
local addon = self_stateAddons:Remove()
if stateAddon ~= addon then
stateModules:Insert(addon)
end
end
self_stateAddons = stateModules
-- Release resources used by the state machine managed by the addon.
if stateAddon.CleanState then
stateAddon:CleanState(self.state)
end
-- Remove mix-in methods from addon's state prototype.
local statePrototype = self_statePrototype[stateAddon]
if statePrototype then
for k in pairs(statePrototype) do
self.state[k] = nil
end
end
self_statePrototype[stateAddon] = nil
end
function OvaleState:InvokeMethod(methodName, ...)
for _, addon in self_stateAddons:Iterator() do
if addon[methodName] then
addon[methodName](addon, ...)
end
end
end
--</public-static-methods>
--[[----------------------------------------------------------------------------
State machine for simulator.
--]]----------------------------------------------------------------------------
--<public-static-properties>
OvaleState.statePrototype = {}
--</public-static-properties>
--<private-static-properties>
local statePrototype = OvaleState.statePrototype
--</private-static-properties>
--<state-properties>
-- Whether the state of the simulator has been initialized.
statePrototype.isInitialized = nil
-- Table of state variables added by scripts that is reset on every refresh.
statePrototype.futureVariable = nil
-- Table of state variables added by scripts that is reset only when out of combat.
statePrototype.variable = nil
--</state-properties>
--<public-static-methods>
-- Initialize the state.
function OvaleState:InitializeState(state)
state.futureVariable = {}
state.variable = {}
end
-- Reset the state to the current conditions.
function OvaleState:ResetState(state)
for k in pairs(state.futureVariable) do
state.futureVariable[k] = nil
end
-- TODO: What conditions should trigger resetting state variables?
-- For now, reset/remove all state variables if out of combat.
if not Ovale.enCombat then
for k in pairs(state.variable) do
Ovale:DebugPrintf(OVALE_STATE_DEBUG, "Resetting state variable '%s'.", k)
state.variable[k] = nil
end
end
end
-- Release state resources prior to removing from the simulator.
function OvaleState:CleanState(state)
for k in pairs(state.futureVariable) do
state.futureVariable[k] = nil
end
for k in pairs(state.variable) do
state.variable[k] = nil
end
end
--</public-static-methods>
--<state-methods>
statePrototype.Initialize = function(state)
if not state.isInitialized then
OvaleState:InvokeMethod("InitializeState", state)
state.isInitialized = true
end
end
statePrototype.Reset = function(state)
OvaleState:InvokeMethod("ResetState", state)
end
-- Get the value of the named state variable. If missing, then return 0.
statePrototype.GetState = function(state, name)
return state.futureVariable[name] or state.variable[name] or 0
end
-- Put a value into the named state variable.
statePrototype.PutState = function(state, name, value, isFuture)
if isFuture then
Ovale:Logf("Setting future state: %s = %s.", name, value)
state.futureVariable[name] = value
else
Ovale:DebugPrintf(OVALE_STATE_DEBUG, "Advancing combat state: %s = %s.", name, value)
Ovale:Logf("Advancing combat state: %s = %s.", name, value)
state.variable[name] = value
end
end
--</state-methods>
|
Fix misuse of OvaleState.statePrototype.
|
Fix misuse of OvaleState.statePrototype.
The public property was being misused for two different functions. Make a
private property for the mapping and keep the public property for the true
state prototype registered with OvaleState.
|
Lua
|
mit
|
ultijlam/ovale,Xeltor/ovale,ultijlam/ovale,eXhausted/Ovale,eXhausted/Ovale,ultijlam/ovale,eXhausted/Ovale
|
c6462ccc09d557dcd0ae74827b6f67b0f53bccc5
|
bin/process/IntFile2PoolRelationsTorch.lua
|
bin/process/IntFile2PoolRelationsTorch.lua
|
--
-- User: pat
-- Date: 8/10/15
--
require 'torch'
require 'nn'
-- note : in data is assumed to be 0 indexed but all output is 1 indxed
local cmd = torch.CmdLine()
cmd:option('-inFile', '', 'input file')
cmd:option('-outFile', '', 'out file')
cmd:option('-delim', ' ', 'delimiter to split lines on')
cmd:option('-maxSeq', 50, 'throw away sequences longer than this')
cmd:option('-maxCount', 10000, 'throw away eps with more than this many relations')
local params = cmd:parse(arg)
print(params)
local max_ep = 0
local max_token = 0
local num_rows = 0
local ep_rels = {}
print('Seperating relations by ep')
for line in io.lines(params.inFile) do
num_rows = num_rows + 1
local e1, e2, ep, rel, token_str, label = string.match(line, "([^\t]+)\t([^\t]+)\t([^\t]+)\t([^\t]+)\t([^\t]+)\t([^\t]+)")
local tokens = {}
for token in string.gmatch(token_str, "[^" .. params.delim .. "]+") do
token = tonumber(token)
table.insert(tokens, token)
local ep_num = tonumber(ep)
max_token = math.max(token, max_token)
max_ep = math.max(ep_num, max_ep)
end
if #tokens <= params.maxSeq then
ep_rels[ep] = ep_rels[ep] or {}
-- zero pad for now
for i = #tokens, params.maxSeq-1 do table.insert(tokens, 0) end
table.insert(ep_rels[ep], torch.Tensor(tokens):view(1, #tokens))
end
if (num_rows % 10000 == 0) then io.write('\rProcessing line number : '..num_rows); io.flush() end
end
print('\nJoining tensors')
local join = nn.JoinTable(1)
local rel_counts = {}
local ep_counts = {}
local max_count = 0
local ep_num = 0
for ep, rel_table in pairs(ep_rels) do
max_count = math.max(max_count, #rel_table)
local rel_tensor = join(rel_table):clone()
rel_counts[#rel_table] = rel_counts[#rel_table] or {}
ep_counts[#rel_table] = ep_counts[#rel_table] or {}
table.insert(rel_counts[#rel_table], rel_tensor:view(1, rel_tensor:size(1), rel_tensor:size(2)))
table.insert(ep_counts[#rel_table], ep)
ep_num = ep_num+1
if (ep_num % 100 == 0) then io.write('\rProcessing ep number : '..ep_num); io.flush() end
end
ep_rels = nil
local data = { num_eps = max_ep, num_tokens = max_token+2, max_length = params.max_count }
for i = 1, math.min(params.maxCount, max_count) do
if rel_counts[i] then
local epTensor = torch.Tensor(ep_counts[i])
local seqTensor = join(rel_counts[i]):clone()
-- set pad token to last index
seqTensor = seqTensor:add(seqTensor:eq(0):double():mul(max_token+1))
data[i] = { ep = epTensor, seq = seqTensor, count = 0, num_eps = max_ep, num_tokens = max_token+2 }
end
end
ep_counts = nil; rel_counts = nil;
print('\nSaving data')
torch.save(params.outFile, data)
print(string.format('num rows = %d\t num unique tokens = %d', num_rows, max_token))
|
--
-- User: pat
-- Date: 8/10/15
--
require 'torch'
require 'nn'
-- note : in data is assumed to be 0 indexed but all output is 1 indxed
local cmd = torch.CmdLine()
cmd:option('-inFile', '', 'input file')
cmd:option('-outFile', '', 'out file')
cmd:option('-delim', ' ', 'delimiter to split lines on')
cmd:option('-maxSeq', 50, 'throw away sequences longer than this')
cmd:option('-maxCount', 10000, 'throw away eps with more than this many relations')
cmd:option('-minCount', 1, 'throw away tokens seen less than this many times')
local params = cmd:parse(arg)
print(params)
local max_ep = 0
local max_token = 0
local num_rows = 0
local ep_rels = {}
print('Seperating relations by ep')
for line in io.lines(params.inFile) do
num_rows = num_rows + 1
local e1, e2, ep, rel, token_str, label = string.match(line, "([^\t]+)\t([^\t]+)\t([^\t]+)\t([^\t]+)\t([^\t]+)\t([^\t]+)")
local tokens = {}
for token in string.gmatch(token_str, "[^" .. params.delim .. "]+") do
token = tonumber(token)
table.insert(tokens, token)
local ep_num = tonumber(ep)
max_token = math.max(token, max_token)
max_ep = math.max(ep_num, max_ep)
end
if #tokens <= params.maxSeq then
ep_rels[ep] = ep_rels[ep] or {}
-- zero pad for now
for i = #tokens, params.maxSeq-1 do table.insert(tokens, 0) end
table.insert(ep_rels[ep], torch.Tensor(tokens):view(1, #tokens))
end
if (num_rows % 10000 == 0) then io.write('\rProcessing line number : '..num_rows); io.flush() end
end
print('\nJoining tensors')
local join = nn.JoinTable(1)
local rel_counts = {}
local ep_counts = {}
local max_count = 0
local ep_num = 0
for ep, rel_table in pairs(ep_rels) do
max_count = math.max(max_count, #rel_table)
local rel_tensor = join(rel_table):clone()
rel_counts[#rel_table] = rel_counts[#rel_table] or {}
ep_counts[#rel_table] = ep_counts[#rel_table] or {}
table.insert(rel_counts[#rel_table], rel_tensor:view(1, rel_tensor:size(1), rel_tensor:size(2)))
table.insert(ep_counts[#rel_table], ep)
ep_num = ep_num+1
if (ep_num % 100 == 0) then io.write('\rProcessing ep number : '..ep_num); io.flush() end
end
ep_rels = nil
local data = { num_eps = max_ep, num_tokens = max_token+2, max_length = params.max_count }
for i = 1, math.min(params.maxCount, max_count) do
if rel_counts[i] then
local epTensor = torch.Tensor(ep_counts[i])
local seqTensor = join(rel_counts[i]):clone()
-- set pad token to last index
seqTensor = seqTensor:add(seqTensor:eq(0):double():mul(max_token+1))
data[i] = { ep = epTensor, seq = seqTensor, count = 0, num_eps = max_ep, num_tokens = max_token+2 }
end
end
ep_counts = nil; rel_counts = nil;
print('\nSaving data')
torch.save(params.outFile, data)
print(string.format('num rows = %d\t num unique tokens = %d', num_rows, max_token))
|
fix bug
|
fix bug
|
Lua
|
mit
|
patverga/torch-relation-extraction,patverga/torch-relation-extraction,patverga/torch-relation-extraction
|
f46abf4520e7f6bcbb095da88c4fc21b8ae44db0
|
mod_pastebin/mod_pastebin.lua
|
mod_pastebin/mod_pastebin.lua
|
local st = require "util.stanza";
local httpserver = require "net.httpserver";
local uuid_new = require "util.uuid".generate;
local os_time = os.time;
local t_insert, t_remove = table.insert, table.remove;
local add_task = require "util.timer".add_task;
local utf8_pattern = "[\194-\244][\128-\191]*$";
local function drop_invalid_utf8(seq)
local start = seq:byte();
module:log("utf8: %d, %d", start, #seq);
if (start <= 223 and #seq < 2)
or (start >= 224 and start <= 239 and #seq < 3)
or (start >= 240 and start <= 244 and #seq < 4)
or (start > 244) then
return "";
end
return seq;
end
local function utf8_length(str)
local _, count = string.gsub(str, "[^\128-\193]", "");
return count;
end
local pastebin_private_messages = module:get_option_boolean("pastebin_private_messages", hosts[module.host].type ~= "component");
local length_threshold = module:get_option_number("pastebin_threshold", 500);
local line_threshold = module:get_option_number("pastebin_line_threshold", 4);
local max_summary_length = module:get_option_number("pastebin_summary_length", 150);
local html_preview = module:get_option_boolean("pastebin_html_preview", true);
local base_url = module:get_option_string("pastebin_url");
-- Seconds a paste should live for in seconds (config is in hours), default 24 hours
local expire_after = math.floor(module:get_option_number("pastebin_expire_after", 24) * 3600);
local trigger_string = module:get_option_string("pastebin_trigger");
trigger_string = (trigger_string and trigger_string .. " ");
local pastes = {};
local default_headers = { ["Content-Type"] = "text/plain; charset=utf-8" };
local xmlns_xhtmlim = "http://jabber.org/protocol/xhtml-im";
local xmlns_xhtml = "http://www.w3.org/1999/xhtml";
if expire_after == 0 then
local dm = require "util.datamanager";
setmetatable(pastes, {
__index = function (pastes, id)
if type(id) == "string" then
return dm.load(id, module.host, "pastebin");
end
end;
__newindex = function (pastes, id, data)
if type(id) == "string" then
dm.store(id, module.host, "pastebin", data);
end
end;
});
else
setmetatable(pastes, nil);
end
function pastebin_text(text)
local uuid = uuid_new();
pastes[uuid] = { body = text, time = os_time(), headers = default_headers };
pastes[#pastes+1] = uuid;
if not pastes[2] then -- No other pastes, give the timer a kick
add_task(expire_after, expire_pastes);
end
return base_url..uuid;
end
function handle_request(method, body, request)
local pasteid = request.url.path:match("[^/]+$");
if not pasteid or not pastes[pasteid] then
return "Invalid paste id, perhaps it expired?";
end
--module:log("debug", "Received request, replying: %s", pastes[pasteid].text);
return pastes[pasteid];
end
function check_message(data)
local origin, stanza = data.origin, data.stanza;
local body, bodyindex, htmlindex;
for k,v in ipairs(stanza) do
if v.name == "body" then
body, bodyindex = v, k;
elseif v.name == "html" and v.attr.xmlns == xmlns_xhtmlim then
htmlindex = k;
end
end
if not body then return; end
body = body:get_text();
--module:log("debug", "Body(%s) length: %d", type(body), #(body or ""));
if body and (
((#body > length_threshold)
and (utf8_length(body) > length_threshold)) or
(trigger_string and body:find(trigger_string, 1, true) == 1) or
(select(2, body:gsub("\n", "%0")) >= line_threshold)
) then
if trigger_string then
body = body:gsub("^" .. trigger_string, "", 1);
end
local url = pastebin_text(body);
module:log("debug", "Pasted message as %s", url);
--module:log("debug", " stanza[bodyindex] = %q", tostring( stanza[bodyindex]));
local summary = (body:sub(1, max_summary_length):gsub(utf8_pattern, drop_invalid_utf8) or ""):match("[^\n]+") or "";
summary = summary:match("^%s*(.-)%s*$");
local summary_prefixed = summary:match("[,:]$");
stanza[bodyindex][1] = (summary_prefixed and (summary.." ") or "")..url;
if html_preview then
local line_count = select(2, body:gsub("\n", "%0")) + 1;
local link_text = ("[view %spaste (%d line%s)]"):format(summary_prefixed and "" or "rest of ", line_count, line_count == 1 and "" or "s");
local html = st.stanza("html", { xmlns = xmlns_xhtmlim }):tag("body", { xmlns = xmlns_xhtml });
html:tag("p"):text(summary.." "):up();
html:tag("a", { href = url }):text(link_text):up();
stanza[htmlindex or #stanza+1] = html;
end
end
end
module:hook("message/bare", check_message);
if pastebin_private_messages then
module:hook("message/full", check_message);
end
function expire_pastes(time)
time = time or os_time(); -- COMPAT with 0.5
if pastes[1] then
pastes[pastes[1]] = nil;
t_remove(pastes, 1);
if pastes[1] then
return (expire_after - (time - pastes[pastes[1]].time)) + 1;
end
end
end
local ports = module:get_option("pastebin_ports", { 5280 });
for _, options in ipairs(ports) do
local port, base, ssl, interface = 5280, "pastebin", false, nil;
if type(options) == "number" then
port = options;
elseif type(options) == "table" then
port, base, ssl, interface = options.port or 5280, options.path or "pastebin", options.ssl or false, options.interface;
elseif type(options) == "string" then
base = options;
end
base_url = base_url or ("http://"..module:get_host()..(port ~= 80 and (":"..port) or "").."/"..base.."/");
httpserver.new{ port = port, base = base, handler = handle_request, ssl = ssl }
end
function module.save()
return { pastes = pastes };
end
function module.restore(data)
pastes = data.pastes or pastes;
end
|
local st = require "util.stanza";
local httpserver = require "net.httpserver";
local uuid_new = require "util.uuid".generate;
local os_time = os.time;
local t_insert, t_remove = table.insert, table.remove;
local add_task = require "util.timer".add_task;
local utf8_pattern = "[\194-\244][\128-\191]*$";
local function drop_invalid_utf8(seq)
local start = seq:byte();
module:log("utf8: %d, %d", start, #seq);
if (start <= 223 and #seq < 2)
or (start >= 224 and start <= 239 and #seq < 3)
or (start >= 240 and start <= 244 and #seq < 4)
or (start > 244) then
return "";
end
return seq;
end
local function utf8_length(str)
local _, count = string.gsub(str, "[^\128-\193]", "");
return count;
end
local pastebin_private_messages = module:get_option_boolean("pastebin_private_messages", hosts[module.host].type ~= "component");
local length_threshold = module:get_option_number("pastebin_threshold", 500);
local line_threshold = module:get_option_number("pastebin_line_threshold", 4);
local max_summary_length = module:get_option_number("pastebin_summary_length", 150);
local html_preview = module:get_option_boolean("pastebin_html_preview", true);
local base_url = module:get_option_string("pastebin_url");
-- Seconds a paste should live for in seconds (config is in hours), default 24 hours
local expire_after = math.floor(module:get_option_number("pastebin_expire_after", 24) * 3600);
local trigger_string = module:get_option_string("pastebin_trigger");
trigger_string = (trigger_string and trigger_string .. " ");
local pastes = {};
local default_headers = { ["Content-Type"] = "text/plain; charset=utf-8" };
local xmlns_xhtmlim = "http://jabber.org/protocol/xhtml-im";
local xmlns_xhtml = "http://www.w3.org/1999/xhtml";
function pastebin_text(text)
local uuid = uuid_new();
pastes[uuid] = { body = text, time = os_time(), headers = default_headers };
pastes[#pastes+1] = uuid;
if not pastes[2] then -- No other pastes, give the timer a kick
add_task(expire_after, expire_pastes);
end
return base_url..uuid;
end
function handle_request(method, body, request)
local pasteid = request.url.path:match("[^/]+$");
if not pasteid or not pastes[pasteid] then
return "Invalid paste id, perhaps it expired?";
end
--module:log("debug", "Received request, replying: %s", pastes[pasteid].text);
return pastes[pasteid];
end
function check_message(data)
local origin, stanza = data.origin, data.stanza;
local body, bodyindex, htmlindex;
for k,v in ipairs(stanza) do
if v.name == "body" then
body, bodyindex = v, k;
elseif v.name == "html" and v.attr.xmlns == xmlns_xhtmlim then
htmlindex = k;
end
end
if not body then return; end
body = body:get_text();
--module:log("debug", "Body(%s) length: %d", type(body), #(body or ""));
if body and (
((#body > length_threshold)
and (utf8_length(body) > length_threshold)) or
(trigger_string and body:find(trigger_string, 1, true) == 1) or
(select(2, body:gsub("\n", "%0")) >= line_threshold)
) then
if trigger_string then
body = body:gsub("^" .. trigger_string, "", 1);
end
local url = pastebin_text(body);
module:log("debug", "Pasted message as %s", url);
--module:log("debug", " stanza[bodyindex] = %q", tostring( stanza[bodyindex]));
local summary = (body:sub(1, max_summary_length):gsub(utf8_pattern, drop_invalid_utf8) or ""):match("[^\n]+") or "";
summary = summary:match("^%s*(.-)%s*$");
local summary_prefixed = summary:match("[,:]$");
stanza[bodyindex][1] = (summary_prefixed and (summary.." ") or "")..url;
if html_preview then
local line_count = select(2, body:gsub("\n", "%0")) + 1;
local link_text = ("[view %spaste (%d line%s)]"):format(summary_prefixed and "" or "rest of ", line_count, line_count == 1 and "" or "s");
local html = st.stanza("html", { xmlns = xmlns_xhtmlim }):tag("body", { xmlns = xmlns_xhtml });
html:tag("p"):text(summary.." "):up();
html:tag("a", { href = url }):text(link_text):up();
stanza[htmlindex or #stanza+1] = html;
end
end
end
module:hook("message/bare", check_message);
if pastebin_private_messages then
module:hook("message/full", check_message);
end
function expire_pastes(time)
time = time or os_time(); -- COMPAT with 0.5
if pastes[1] then
pastes[pastes[1]] = nil;
t_remove(pastes, 1);
if pastes[1] then
return (expire_after - (time - pastes[pastes[1]].time)) + 1;
end
end
end
local ports = module:get_option("pastebin_ports", { 5280 });
for _, options in ipairs(ports) do
local port, base, ssl, interface = 5280, "pastebin", false, nil;
if type(options) == "number" then
port = options;
elseif type(options) == "table" then
port, base, ssl, interface = options.port or 5280, options.path or "pastebin", options.ssl or false, options.interface;
elseif type(options) == "string" then
base = options;
end
base_url = base_url or ("http://"..module:get_host()..(port ~= 80 and (":"..port) or "").."/"..base.."/");
httpserver.new{ port = port, base = base, handler = handle_request, ssl = ssl }
end
function module.load()
if expire_after == 0 then
local dm = require "util.datamanager";
setmetatable(pastes, {
__index = function (pastes, id)
if type(id) == "string" then
return dm.load(id, module.host, "pastebin");
end
end;
__newindex = function (pastes, id, data)
if type(id) == "string" then
dm.store(id, module.host, "pastebin", data);
end
end;
});
else
setmetatable(pastes, nil);
end
end
function module.save()
return { pastes = pastes };
end
function module.restore(data)
pastes = data.pastes or pastes;
end
|
mod_pastebin: Fix issue with metatable not being set when a reload changes expires_after to 0
|
mod_pastebin: Fix issue with metatable not being set when a reload changes expires_after to 0
|
Lua
|
mit
|
prosody-modules/import,1st8/prosody-modules,brahmi2/prosody-modules,1st8/prosody-modules,crunchuser/prosody-modules,apung/prosody-modules,drdownload/prosody-modules,guilhem/prosody-modules,BurmistrovJ/prosody-modules,heysion/prosody-modules,syntafin/prosody-modules,drdownload/prosody-modules,jkprg/prosody-modules,jkprg/prosody-modules,syntafin/prosody-modules,iamliqiang/prosody-modules,NSAKEY/prosody-modules,vfedoroff/prosody-modules,drdownload/prosody-modules,prosody-modules/import,1st8/prosody-modules,jkprg/prosody-modules,vfedoroff/prosody-modules,apung/prosody-modules,1st8/prosody-modules,iamliqiang/prosody-modules,mmusial/prosody-modules,syntafin/prosody-modules,obelisk21/prosody-modules,vince06fr/prosody-modules,joewalker/prosody-modules,jkprg/prosody-modules,drdownload/prosody-modules,vince06fr/prosody-modules,asdofindia/prosody-modules,vfedoroff/prosody-modules,dhotson/prosody-modules,NSAKEY/prosody-modules,prosody-modules/import,LanceJenkinZA/prosody-modules,olax/prosody-modules,crunchuser/prosody-modules,crunchuser/prosody-modules,syntafin/prosody-modules,LanceJenkinZA/prosody-modules,amenophis1er/prosody-modules,joewalker/prosody-modules,crunchuser/prosody-modules,dhotson/prosody-modules,vince06fr/prosody-modules,olax/prosody-modules,amenophis1er/prosody-modules,guilhem/prosody-modules,stephen322/prosody-modules,Craige/prosody-modules,guilhem/prosody-modules,mardraze/prosody-modules,heysion/prosody-modules,obelisk21/prosody-modules,asdofindia/prosody-modules,asdofindia/prosody-modules,LanceJenkinZA/prosody-modules,joewalker/prosody-modules,prosody-modules/import,cryptotoad/prosody-modules,dhotson/prosody-modules,cryptotoad/prosody-modules,olax/prosody-modules,guilhem/prosody-modules,softer/prosody-modules,NSAKEY/prosody-modules,vince06fr/prosody-modules,asdofindia/prosody-modules,brahmi2/prosody-modules,either1/prosody-modules,stephen322/prosody-modules,stephen322/prosody-modules,BurmistrovJ/prosody-modules,jkprg/prosody-modules,vince06fr/prosody-modules,Craige/prosody-modules,syntafin/prosody-modules,Craige/prosody-modules,crunchuser/prosody-modules,stephen322/prosody-modules,apung/prosody-modules,obelisk21/prosody-modules,mardraze/prosody-modules,BurmistrovJ/prosody-modules,1st8/prosody-modules,apung/prosody-modules,prosody-modules/import,softer/prosody-modules,mardraze/prosody-modules,mardraze/prosody-modules,cryptotoad/prosody-modules,obelisk21/prosody-modules,mmusial/prosody-modules,iamliqiang/prosody-modules,brahmi2/prosody-modules,BurmistrovJ/prosody-modules,iamliqiang/prosody-modules,asdofindia/prosody-modules,softer/prosody-modules,amenophis1er/prosody-modules,LanceJenkinZA/prosody-modules,stephen322/prosody-modules,heysion/prosody-modules,either1/prosody-modules,amenophis1er/prosody-modules,NSAKEY/prosody-modules,BurmistrovJ/prosody-modules,cryptotoad/prosody-modules,either1/prosody-modules,NSAKEY/prosody-modules,mmusial/prosody-modules,vfedoroff/prosody-modules,brahmi2/prosody-modules,cryptotoad/prosody-modules,mmusial/prosody-modules,either1/prosody-modules,olax/prosody-modules,obelisk21/prosody-modules,mardraze/prosody-modules,iamliqiang/prosody-modules,drdownload/prosody-modules,joewalker/prosody-modules,heysion/prosody-modules,guilhem/prosody-modules,dhotson/prosody-modules,apung/prosody-modules,dhotson/prosody-modules,brahmi2/prosody-modules,amenophis1er/prosody-modules,either1/prosody-modules,softer/prosody-modules,olax/prosody-modules,joewalker/prosody-modules,heysion/prosody-modules,Craige/prosody-modules,mmusial/prosody-modules,LanceJenkinZA/prosody-modules,vfedoroff/prosody-modules,Craige/prosody-modules,softer/prosody-modules
|
98bc0b8143053f79f6f5ac896da078097472852b
|
build/scripts/Utils.lua
|
build/scripts/Utils.lua
|
function string.is_empty(s)
return not s or s == ''
end
function cat(file)
local file = assert(io.open(file, "r"))
local output = file:read('*all')
file:close()
return output
end
function execute(cmd, quiet)
print(cmd)
if not quiet then
return os.execute(cmd)
else
local file = assert(io.popen(cmd .. " 2>&1", "r"))
local output = file:read('*all')
file:close()
return output
end
end
function execute_or_die(cmd, quiet)
local res = execute(cmd, quiet)
if res > 0 then
error("Error executing shell command, aborting...")
end
return res
end
function sudo(cmd)
return os.execute("sudo " .. cmd)
end
function is_vagrant()
return os.isdir("/home/vagrant")
end
git = {}
-- Remove once https://github.com/premake/premake-core/pull/307 is merged.
local sep = os.is("windows") and "\\" or "/"
function git.clone(dir, url, target)
local cmd = "git clone " .. url .. " " .. path.translate(dir, sep)
if target ~= nil then
cmd = cmd .. " " .. target
end
return execute_or_die(cmd)
end
function git.pull_rebase(dir)
local cmd = "git -C " .. path.translate(dir, sep) .. " pull --rebase"
return execute_or_die(cmd)
end
function git.reset_hard(dir, rev)
local cmd = "git -C " .. path.translate(dir, sep) .. " reset --hard " .. rev
return execute_or_die(cmd)
end
function git.checkout(dir, rev)
local cmd = "git -C " .. path.translate(dir, sep) .. " checkout " .. rev
return execute_or_die(cmd)
end
function git.rev_parse(dir, rev)
local cmd = "git -C " .. path.translate(dir, sep) .. " rev-parse " .. rev
return os.outputof(cmd)
end
function http.progress (total, curr)
local ratio = curr / total;
ratio = math.floor(math.min(math.max(ratio, 0), 1));
local percent = ratio * 100;
print("Download progress (" .. percent .. "%/100%)")
end
function download(url, file)
print("Downloading: " .. url)
local res = http.download(url, file, http.progress)
if res ~= "OK" then
os.remove(file)
error(res)
end
return res
end
--
-- Allows copying directories.
-- It uses the premake patterns (**=recursive match, *=file match)
-- NOTE: It won't copy empty directories!
-- Example: we have a file: src/test.h
-- os.copydir("src", "include") simple copy, makes include/test.h
-- os.copydir("src", "include", "*.h") makes include/test.h
-- os.copydir(".", "include", "src/*.h") makes include/src/test.h
-- os.copydir(".", "include", "**.h") makes include/src/test.h
-- os.copydir(".", "include", "**.h", true) will force it to include dir, makes include/test.h
--
-- @param src_dir
-- Source directory, which will be copied to dst_dir.
-- @param dst_dir
-- Destination directory.
-- @param filter
-- Optional, defaults to "**". Only filter matches will be copied. It can contain **(recursive) and *(filename).
-- @param single_dst_dir
-- Optional, defaults to false. Allows putting all files to dst_dir without subdirectories.
-- Only useful with recursive (**) filter.
-- @returns
-- True if successful, otherwise nil.
--
function os.copydir(src_dir, dst_dir, filter, single_dst_dir)
filter = filter or "**"
src_dir = src_dir .. "/"
print('copy "' .. path.getabsolute(src_dir) .. filter .. '" to "' .. dst_dir .. '".')
if not os.isdir(src_dir) then error(src_dir .. " is not an existing directory!") end
dst_dir = dst_dir .. "/"
local dir = path.rebase(".",path.getabsolute("."), src_dir) -- root dir, relative from src_dir
os.chdir( src_dir ) -- change current directory to src_dir
local matches = os.matchfiles(filter)
os.chdir( dir ) -- change current directory back to root
local counter = 0
for k, v in ipairs(matches) do
local target = iif(single_dst_dir, path.getname(v), v)
--make sure, that directory exists or os.copyfile() fails
os.mkdir( path.getdirectory(dst_dir .. target))
if os.copyfile( src_dir .. v, dst_dir .. target) then
counter = counter + 1
end
end
if counter == #matches then
print( counter .. " files copied.")
return true
else
print( "Error: " .. counter .. "/" .. #matches .. " files copied.")
return nil
end
end
--
-- Allows removing files from directories.
-- It uses the premake patterns (**=recursive match, *=file match)
--
-- @param src_dir
-- Source directory, which will be copied to dst_dir.
-- @param filter
-- Optional, defaults to "**". Only filter matches will be copied. It can contain **(recursive) and *(filename).
-- @returns
-- True if successful, otherwise nil.
--
function os.rmfiles(src_dir, filter)
filter = filter or "**"
src_dir = src_dir .. "/"
print('rm "' .. path.getabsolute(src_dir) .. filter)
if not os.isdir(src_dir) then error(src_dir .. " is not an existing directory!") end
local dir = path.rebase(".",path.getabsolute("."), src_dir) -- root dir, relative from src_dir
os.chdir( src_dir ) -- change current directory to src_dir
local matches = os.matchfiles(filter)
os.chdir( dir ) -- change current directory back to root
local counter = 0
for k, v in ipairs(matches) do
if os.remove( src_dir .. v) then
counter = counter + 1
end
end
if counter == #matches then
print( counter .. " files removed.")
return true
else
print( "Error: " .. counter .. "/" .. #matches .. " files removed.")
return nil
end
end
|
function string.is_empty(s)
return not s or s == ''
end
function cat(file)
local file = assert(io.open(file, "r"))
local output = file:read('*all')
file:close()
return output
end
function execute(cmd, quiet)
print(cmd)
if not quiet then
return os.execute(cmd)
else
local file = assert(io.popen(cmd .. " 2>&1", "r"))
local output = file:read('*all')
file:close()
-- FIXME: Lua 5.2 returns the process exit code from close()
-- Update this once Premake upgrades from Lua 5.1
return 0
end
end
function execute_or_die(cmd, quiet)
local res = execute(cmd, quiet)
if res > 0 then
error("Error executing shell command, aborting...")
end
return res
end
function sudo(cmd)
return os.execute("sudo " .. cmd)
end
function is_vagrant()
return os.isdir("/home/vagrant")
end
git = {}
-- Remove once https://github.com/premake/premake-core/pull/307 is merged.
local sep = os.is("windows") and "\\" or "/"
function git.clone(dir, url, target)
local cmd = "git clone " .. url .. " " .. path.translate(dir, sep)
if target ~= nil then
cmd = cmd .. " " .. target
end
return execute_or_die(cmd)
end
function git.pull_rebase(dir)
local cmd = "git -C " .. path.translate(dir, sep) .. " pull --rebase"
return execute_or_die(cmd)
end
function git.reset_hard(dir, rev)
local cmd = "git -C " .. path.translate(dir, sep) .. " reset --hard " .. rev
return execute_or_die(cmd)
end
function git.checkout(dir, rev)
local cmd = "git -C " .. path.translate(dir, sep) .. " checkout " .. rev
return execute_or_die(cmd)
end
function git.rev_parse(dir, rev)
local cmd = "git -C " .. path.translate(dir, sep) .. " rev-parse " .. rev
return os.outputof(cmd)
end
function http.progress (total, curr)
local ratio = curr / total;
ratio = math.floor(math.min(math.max(ratio, 0), 1));
local percent = ratio * 100;
print("Download progress (" .. percent .. "%/100%)")
end
function download(url, file)
print("Downloading: " .. url)
local res = http.download(url, file, http.progress)
if res ~= "OK" then
os.remove(file)
error(res)
end
return res
end
--
-- Allows copying directories.
-- It uses the premake patterns (**=recursive match, *=file match)
-- NOTE: It won't copy empty directories!
-- Example: we have a file: src/test.h
-- os.copydir("src", "include") simple copy, makes include/test.h
-- os.copydir("src", "include", "*.h") makes include/test.h
-- os.copydir(".", "include", "src/*.h") makes include/src/test.h
-- os.copydir(".", "include", "**.h") makes include/src/test.h
-- os.copydir(".", "include", "**.h", true) will force it to include dir, makes include/test.h
--
-- @param src_dir
-- Source directory, which will be copied to dst_dir.
-- @param dst_dir
-- Destination directory.
-- @param filter
-- Optional, defaults to "**". Only filter matches will be copied. It can contain **(recursive) and *(filename).
-- @param single_dst_dir
-- Optional, defaults to false. Allows putting all files to dst_dir without subdirectories.
-- Only useful with recursive (**) filter.
-- @returns
-- True if successful, otherwise nil.
--
function os.copydir(src_dir, dst_dir, filter, single_dst_dir)
filter = filter or "**"
src_dir = src_dir .. "/"
print('copy "' .. path.getabsolute(src_dir) .. filter .. '" to "' .. dst_dir .. '".')
if not os.isdir(src_dir) then error(src_dir .. " is not an existing directory!") end
dst_dir = dst_dir .. "/"
local dir = path.rebase(".",path.getabsolute("."), src_dir) -- root dir, relative from src_dir
os.chdir( src_dir ) -- change current directory to src_dir
local matches = os.matchfiles(filter)
os.chdir( dir ) -- change current directory back to root
local counter = 0
for k, v in ipairs(matches) do
local target = iif(single_dst_dir, path.getname(v), v)
--make sure, that directory exists or os.copyfile() fails
os.mkdir( path.getdirectory(dst_dir .. target))
if os.copyfile( src_dir .. v, dst_dir .. target) then
counter = counter + 1
end
end
if counter == #matches then
print( counter .. " files copied.")
return true
else
print( "Error: " .. counter .. "/" .. #matches .. " files copied.")
return nil
end
end
--
-- Allows removing files from directories.
-- It uses the premake patterns (**=recursive match, *=file match)
--
-- @param src_dir
-- Source directory, which will be copied to dst_dir.
-- @param filter
-- Optional, defaults to "**". Only filter matches will be copied. It can contain **(recursive) and *(filename).
-- @returns
-- True if successful, otherwise nil.
--
function os.rmfiles(src_dir, filter)
filter = filter or "**"
src_dir = src_dir .. "/"
print('rm "' .. path.getabsolute(src_dir) .. filter)
if not os.isdir(src_dir) then error(src_dir .. " is not an existing directory!") end
local dir = path.rebase(".",path.getabsolute("."), src_dir) -- root dir, relative from src_dir
os.chdir( src_dir ) -- change current directory to src_dir
local matches = os.matchfiles(filter)
os.chdir( dir ) -- change current directory back to root
local counter = 0
for k, v in ipairs(matches) do
if os.remove( src_dir .. v) then
counter = counter + 1
end
end
if counter == #matches then
print( counter .. " files removed.")
return true
else
print( "Error: " .. counter .. "/" .. #matches .. " files removed.")
return nil
end
end
|
Return a process exit code from execute.
|
Return a process exit code from execute.
Should fix the build.
|
Lua
|
mit
|
mono/CppSharp,genuinelucifer/CppSharp,zillemarco/CppSharp,inordertotest/CppSharp,genuinelucifer/CppSharp,ktopouzi/CppSharp,genuinelucifer/CppSharp,ktopouzi/CppSharp,zillemarco/CppSharp,inordertotest/CppSharp,u255436/CppSharp,inordertotest/CppSharp,u255436/CppSharp,mohtamohit/CppSharp,ktopouzi/CppSharp,mohtamohit/CppSharp,ktopouzi/CppSharp,genuinelucifer/CppSharp,u255436/CppSharp,ddobrev/CppSharp,ktopouzi/CppSharp,inordertotest/CppSharp,mohtamohit/CppSharp,ddobrev/CppSharp,inordertotest/CppSharp,mono/CppSharp,u255436/CppSharp,mono/CppSharp,mohtamohit/CppSharp,mono/CppSharp,mono/CppSharp,ddobrev/CppSharp,u255436/CppSharp,ddobrev/CppSharp,mono/CppSharp,zillemarco/CppSharp,ddobrev/CppSharp,genuinelucifer/CppSharp,zillemarco/CppSharp,zillemarco/CppSharp,mohtamohit/CppSharp
|
b7e416337df64aa413cd827990819c0952b34999
|
share/lua/playlist/googlevideo.lua
|
share/lua/playlist/googlevideo.lua
|
--[[
$Id$
Copyright © 2007 the VideoLAN team
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.
--]]
-- Probe function.
function probe()
return vlc.access == "http"
and string.match( vlc.path, "video.google.com" )
and string.match( vlc.path, "videoplay" )
end
-- Parse function.
function parse()
while true
do
line = vlc.readline()
if not line then break end
if string.match( line, "^<title>" ) then
title = string.gsub( line, "<title>([^<]*).*", "%1" )
end
if string.match( line, "src=\"/googleplayer.swf" ) then
url = string.gsub( line, ".*videoUrl=([^&]*).*" ,"%1" )
arturl = string.gsub( line, ".*thumbnailUrl=([^\"]*).*", "%1" )
return { { path = vlc.strings.decode_uri(url), title = title, arturl = vlc.strings.decode_uri(arturl) } }
end
end
end
|
--[[
$Id$
Copyright © 2007 the VideoLAN team
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.
--]]
function get_url_param( url, name )
return string.gsub( url, "^.*[&?]"..name.."=([^&]*).*$", "%1" )
end
-- Probe function.
function probe()
return vlc.access == "http"
and string.match( vlc.path, "video.google.com" )
and ( string.match( vlc.path, "videoplay" )
or string.match( vlc.path, "videofeed" ) )
end
function get_arg( line, arg )
return string.gsub( line, "^.*"..arg.."=\"(.-)\".*$", "%1" )
end
-- Parse function.
function parse()
local docid = get_url_param( vlc.path, "docid" )
if string.match( vlc.path, "videoplay" ) then
return { { path = "http://video.google.com/videofeed?docid=" .. docid } }
elseif string.match( vlc.path, "videofeed" ) then
local path = nil
local arturl
local duration
local name
local description
while true
do
local line = vlc.readline()
if not line then break end
if string.match( line, "media:content.*flv" )
then
local s = string.gsub( line, "^.*<media:content(.-)/>.*$", "%1" )
path = vlc.strings.resolve_xml_special_chars(get_arg( s, "url" ))
duration = get_arg( s, "duration" )
end
if string.match( line, "media:thumbnail" )
then
local s = string.gsub( line, "^.*<media:thumbnail(.-)/>.*$", "%1" )
arturl = vlc.strings.resolve_xml_special_chars(get_arg( s, "url" ))
vlc.msg.err( tostring(arturl))
end
if string.match( line, "media:title" )
then
name = string.gsub( line, "^.*<media:title>(.-)</media:title>.*$", "%1" )
end
if string.match( line, "media:description" )
then
description = string.gsub( line, "^.*<media:description>(.-)</media:description>.*$", "%1" )
end
end
return { { path = path; name = name; arturl = arturl; duration = duration; description = description } }
end
end
|
Fix google video playlist script.
|
Fix google video playlist script.
|
Lua
|
lgpl-2.1
|
krichter722/vlc,shyamalschandra/vlc,jomanmuk/vlc-2.1,jomanmuk/vlc-2.1,xkfz007/vlc,vlc-mirror/vlc-2.1,krichter722/vlc,shyamalschandra/vlc,vlc-mirror/vlc-2.1,shyamalschandra/vlc,jomanmuk/vlc-2.2,vlc-mirror/vlc,vlc-mirror/vlc-2.1,xkfz007/vlc,xkfz007/vlc,shyamalschandra/vlc,jomanmuk/vlc-2.1,xkfz007/vlc,krichter722/vlc,vlc-mirror/vlc-2.1,vlc-mirror/vlc-2.1,vlc-mirror/vlc,jomanmuk/vlc-2.2,jomanmuk/vlc-2.2,shyamalschandra/vlc,jomanmuk/vlc-2.1,jomanmuk/vlc-2.1,krichter722/vlc,vlc-mirror/vlc,vlc-mirror/vlc,xkfz007/vlc,jomanmuk/vlc-2.2,shyamalschandra/vlc,jomanmuk/vlc-2.1,jomanmuk/vlc-2.2,vlc-mirror/vlc,jomanmuk/vlc-2.2,vlc-mirror/vlc-2.1,shyamalschandra/vlc,krichter722/vlc,vlc-mirror/vlc,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.2,krichter722/vlc,xkfz007/vlc,vlc-mirror/vlc,xkfz007/vlc,jomanmuk/vlc-2.1,krichter722/vlc
|
8bb0baa842727bd2b8cb22775b18f7a5c3dad57e
|
lib/tolua++/src/bin/lua/_driver.lua
|
lib/tolua++/src/bin/lua/_driver.lua
|
-- Allow debugging by ZBS, if run under the IDE:
local mobdebugfound, mobdebug = pcall(require, "mobdebug")
if mobdebugfound then mobdebug.start() end
-- The list of valid arguments that the ToLua scripts can process:
local KnownArgs = {
['v'] = true,
['h'] = true,
['p'] = true,
['P'] = true,
['o'] = true,
['n'] = true,
['H'] = true,
['S'] = true,
['1'] = true,
['L'] = true,
['D'] = true,
['W'] = true,
['C'] = true,
['E'] = true,
['t'] = true,
['q'] = true,
}
-- The flags table used by ToLua scripts, to be filled from the cmdline params:
flags = {}
-- Te extra parameters used by ToLua scripts:
_extra_parameters = {}
-- ToLua version required by the scripts:
TOLUA_VERSION = "tolua++-1.0.92"
-- Lua version used by ToLua, required by the scripts:
TOLUA_LUA_VERSION = "Lua 5.1"
-- Process the cmdline params into the flags table:
local args = arg or {}
local argc = #args
local i = 1
while (i <= argc) do
local argv = args[i]
if (argv:sub(1, 1) == "-") then
if (KnownArgs[argv:sub(2)]) then
print("Setting flag \"" .. argv:sub(2) .. "\" to \"" .. args[i + 1] .. "\".")
flags[argv:sub(2)] = args[i + 1]
i = i + 1
else
print("Unknown option (" .. i .. "): " .. argv)
print("Aborting.")
os.exit(1)
end
else
print("Setting flag \"f\" to \"" .. argv .. "\".")
flags['f'] = argv
break
end
i = i + 1
end
-- Get the path where the scripts are located:
path = args[0] or ""
local index = path:find("/[^/]*$")
if (index == nil) then
index = path:find("\\[^\\]*$")
end
if (index ~= nil) then
path = path:sub(1, index)
end
print("path is set to \"" .. path .. "\".")
-- Call the ToLua processor:
dofile(path .. "all.lua")
|
-- Allow debugging by ZBS, if run under the IDE:
local mobdebugfound, mobdebug = pcall(require, "mobdebug")
if mobdebugfound then mobdebug.start() end
-- The list of valid arguments that the ToLua scripts can process:
local KnownArgs = {
['v'] = true,
['h'] = true,
['p'] = true,
['P'] = true,
['o'] = true,
['n'] = true,
['H'] = true,
['S'] = true,
['1'] = true,
['L'] = true,
['D'] = true,
['W'] = true,
['C'] = true,
['E'] = true,
['t'] = true,
['q'] = true,
}
-- The flags table used by ToLua scripts, to be filled from the cmdline params:
flags = {}
-- Te extra parameters used by ToLua scripts:
_extra_parameters = {}
-- ToLua version required by the scripts:
TOLUA_VERSION = "tolua++-1.0.92"
-- Lua version used by ToLua, required by the scripts:
TOLUA_LUA_VERSION = "Lua 5.1"
-- Process the cmdline params into the flags table:
local args = arg or {}
local argc = #args
local i = 1
while (i <= argc) do
local argv = args[i]
if (argv:sub(1, 1) == "-") then
if (KnownArgs[argv:sub(2)]) then
print("Setting flag \"" .. argv:sub(2) .. "\" to \"" .. args[i + 1] .. "\".")
flags[argv:sub(2)] = args[i + 1]
i = i + 1
else
print("Unknown option (" .. i .. "): " .. argv)
print("Aborting.")
os.exit(1)
end
else
print("Setting flag \"f\" to \"" .. argv .. "\".")
flags['f'] = argv
break
end
i = i + 1
end
-- Get the path where the scripts are located:
path = args[0] or ""
local index = path:find("/[^/]*$")
if (index == nil) then
index = path:find("\\[^\\]*$")
end
if (index ~= nil) then
path = path:sub(1, index)
end
print("path is set to \"" .. path .. "\".")
-- Call the ToLua processor:
dofile(path .. "all.lua")
|
Tolua driver: Fixed wrong indentation.
|
Tolua driver: Fixed wrong indentation.
|
Lua
|
apache-2.0
|
mmdk95/cuberite,electromatter/cuberite,Frownigami1/cuberite,bendl/cuberite,birkett/MCServer,marvinkopf/cuberite,guijun/MCServer,Altenius/cuberite,Howaner/MCServer,kevinr/cuberite,Fighter19/cuberite,nounoursheureux/MCServer,QUSpilPrgm/cuberite,zackp30/cuberite,QUSpilPrgm/cuberite,SamOatesPlugins/cuberite,mc-server/MCServer,Schwertspize/cuberite,guijun/MCServer,johnsoch/cuberite,birkett/cuberite,birkett/cuberite,johnsoch/cuberite,nichwall/cuberite,tonibm19/cuberite,birkett/MCServer,Altenius/cuberite,mjssw/cuberite,jammet/MCServer,Haxi52/cuberite,mc-server/MCServer,SamOatesPlugins/cuberite,mjssw/cuberite,nichwall/cuberite,linnemannr/MCServer,Tri125/MCServer,kevinr/cuberite,mmdk95/cuberite,jammet/MCServer,birkett/MCServer,mc-server/MCServer,birkett/cuberite,mjssw/cuberite,nounoursheureux/MCServer,thetaeo/cuberite,nicodinh/cuberite,HelenaKitty/EbooMC,linnemannr/MCServer,bendl/cuberite,ionux/MCServer,thetaeo/cuberite,tonibm19/cuberite,nichwall/cuberite,zackp30/cuberite,mjssw/cuberite,nicodinh/cuberite,zackp30/cuberite,QUSpilPrgm/cuberite,electromatter/cuberite,Haxi52/cuberite,nichwall/cuberite,tonibm19/cuberite,Howaner/MCServer,jammet/MCServer,kevinr/cuberite,nichwall/cuberite,Haxi52/cuberite,nevercast/cuberite,mmdk95/cuberite,linnemannr/MCServer,Schwertspize/cuberite,nicodinh/cuberite,electromatter/cuberite,Fighter19/cuberite,nicodinh/cuberite,thetaeo/cuberite,johnsoch/cuberite,Howaner/MCServer,guijun/MCServer,nichwall/cuberite,mmdk95/cuberite,Howaner/MCServer,tonibm19/cuberite,ionux/MCServer,nicodinh/cuberite,HelenaKitty/EbooMC,nevercast/cuberite,Fighter19/cuberite,bendl/cuberite,Haxi52/cuberite,Tri125/MCServer,marvinkopf/cuberite,mmdk95/cuberite,birkett/MCServer,QUSpilPrgm/cuberite,Altenius/cuberite,nevercast/cuberite,Frownigami1/cuberite,jammet/MCServer,SamOatesPlugins/cuberite,Altenius/cuberite,guijun/MCServer,mc-server/MCServer,Howaner/MCServer,johnsoch/cuberite,birkett/cuberite,Fighter19/cuberite,marvinkopf/cuberite,birkett/cuberite,ionux/MCServer,QUSpilPrgm/cuberite,tonibm19/cuberite,guijun/MCServer,electromatter/cuberite,Tri125/MCServer,birkett/cuberite,jammet/MCServer,Altenius/cuberite,kevinr/cuberite,HelenaKitty/EbooMC,nicodinh/cuberite,bendl/cuberite,nounoursheureux/MCServer,HelenaKitty/EbooMC,Howaner/MCServer,Schwertspize/cuberite,thetaeo/cuberite,Fighter19/cuberite,Frownigami1/cuberite,linnemannr/MCServer,Haxi52/cuberite,thetaeo/cuberite,linnemannr/MCServer,nevercast/cuberite,Fighter19/cuberite,nevercast/cuberite,marvinkopf/cuberite,birkett/MCServer,electromatter/cuberite,jammet/MCServer,zackp30/cuberite,bendl/cuberite,johnsoch/cuberite,mc-server/MCServer,mmdk95/cuberite,birkett/MCServer,ionux/MCServer,HelenaKitty/EbooMC,Schwertspize/cuberite,Schwertspize/cuberite,mjssw/cuberite,ionux/MCServer,zackp30/cuberite,tonibm19/cuberite,Frownigami1/cuberite,SamOatesPlugins/cuberite,linnemannr/MCServer,nounoursheureux/MCServer,nounoursheureux/MCServer,Haxi52/cuberite,Tri125/MCServer,QUSpilPrgm/cuberite,zackp30/cuberite,mc-server/MCServer,mjssw/cuberite,marvinkopf/cuberite,electromatter/cuberite,thetaeo/cuberite,nevercast/cuberite,marvinkopf/cuberite,Tri125/MCServer,Frownigami1/cuberite,guijun/MCServer,SamOatesPlugins/cuberite,kevinr/cuberite,Tri125/MCServer,kevinr/cuberite,ionux/MCServer,nounoursheureux/MCServer
|
4f3c67df4103c00c764d58b76cd95468fad5a738
|
applications/luci-uvc_streamer/luasrc/model/cbi/uvc_streamer.lua
|
applications/luci-uvc_streamer/luasrc/model/cbi/uvc_streamer.lua
|
--[[
LuCI UVC Streamer
(c) 2008 Yanira <[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$
]]--
-- find current lan address and port of first uvc_streamer config section
local uci = luci.model.uci.cursor_state()
local addr = uci:get("network", "lan", "ipaddr")
local port
uci:foreach( "uvc_streamer", "uvc_streamer",
function(section) port = port or tonumber(section.port) end )
m = Map("uvc_streamer", translate("uvc_streamer"),
translatef("uvc_streamer_desc", nil, addr, port, addr, port))
s = m:section(TypedSection, "uvc_streamer", translate("settings"))
s.addremove = false
s.anonymous = true
s:option(Flag, "enabled", translate("enabled", "Enable"))
s:option(Value, "device", translate("device")).rmempty = true
nm = s:option(Value, "resolution", translate("resolution"))
nm:value("640x480")
nm:value("320x240")
nm:value("160x120")
s:option(Value, "framespersecond", translate("framespersecond")).rmempty = true
s:option(Value, "port", translate("port", "Port")).rmempty = true
return m
|
--[[
LuCI UVC Streamer
(c) 2008 Yanira <[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$
]]--
-- find current lan address and port of first uvc_streamer config section
local uci = luci.model.uci.cursor_state()
local addr = uci:get("network", "lan", "ipaddr")
local port
uci:foreach( "uvc_streamer", "uvc_streamer",
function(section) port = port or tonumber(section.port) end )
addr = addr or "192.168.1.1"
port = port or 8080
m = Map("uvc_streamer", translate("uvc_streamer"),
translatef("uvc_streamer_desc", nil, addr, port, addr, port))
s = m:section(TypedSection, "uvc_streamer", translate("settings"))
s.addremove = false
s.anonymous = true
s:option(Flag, "enabled", translate("enabled", "Enable"))
s:option(Value, "device", translate("device")).rmempty = true
nm = s:option(Value, "resolution", translate("resolution"))
nm:value("640x480")
nm:value("320x240")
nm:value("160x120")
s:option(Value, "framespersecond", translate("framespersecond")).rmempty = true
s:option(Value, "port", translate("port", "Port")).rmempty = true
return m
|
* luci/applications/uvc-streamer: fix possible crash when no uvc_streamer sections is defined in config
|
* luci/applications/uvc-streamer: fix possible crash when no uvc_streamer sections is defined in config
|
Lua
|
apache-2.0
|
dismantl/luci-0.12,tcatm/luci,joaofvieira/luci,maxrio/luci981213,palmettos/test,maxrio/luci981213,keyidadi/luci,artynet/luci,urueedi/luci,thesabbir/luci,RuiChen1113/luci,schidler/ionic-luci,tobiaswaldvogel/luci,aa65535/luci,remakeelectric/luci,obsy/luci,thesabbir/luci,fkooman/luci,nwf/openwrt-luci,RuiChen1113/luci,kuoruan/luci,palmettos/test,david-xiao/luci,RedSnake64/openwrt-luci-packages,florian-shellfire/luci,cshore-firmware/openwrt-luci,sujeet14108/luci,Wedmer/luci,Hostle/luci,lbthomsen/openwrt-luci,ff94315/luci-1,palmettos/cnLuCI,shangjiyu/luci-with-extra,sujeet14108/luci,Hostle/openwrt-luci-multi-user,RuiChen1113/luci,forward619/luci,jchuang1977/luci-1,taiha/luci,joaofvieira/luci,jchuang1977/luci-1,tobiaswaldvogel/luci,forward619/luci,shangjiyu/luci-with-extra,lbthomsen/openwrt-luci,openwrt-es/openwrt-luci,jlopenwrtluci/luci,aa65535/luci,openwrt/luci,dismantl/luci-0.12,MinFu/luci,bittorf/luci,db260179/openwrt-bpi-r1-luci,981213/luci-1,keyidadi/luci,hnyman/luci,ReclaimYourPrivacy/cloak-luci,981213/luci-1,hnyman/luci,forward619/luci,thess/OpenWrt-luci,schidler/ionic-luci,aa65535/luci,schidler/ionic-luci,openwrt/luci,oneru/luci,obsy/luci,wongsyrone/luci-1,lcf258/openwrtcn,aircross/OpenWrt-Firefly-LuCI,fkooman/luci,maxrio/luci981213,aa65535/luci,david-xiao/luci,cshore/luci,thess/OpenWrt-luci,hnyman/luci,harveyhu2012/luci,cappiewu/luci,MinFu/luci,cshore-firmware/openwrt-luci,RuiChen1113/luci,kuoruan/lede-luci,deepak78/new-luci,male-puppies/luci,lbthomsen/openwrt-luci,aircross/OpenWrt-Firefly-LuCI,palmettos/cnLuCI,florian-shellfire/luci,dismantl/luci-0.12,jorgifumi/luci,rogerpueyo/luci,jorgifumi/luci,bittorf/luci,forward619/luci,Wedmer/luci,marcel-sch/luci,taiha/luci,schidler/ionic-luci,fkooman/luci,taiha/luci,tcatm/luci,sujeet14108/luci,florian-shellfire/luci,deepak78/new-luci,RuiChen1113/luci,Hostle/luci,lbthomsen/openwrt-luci,remakeelectric/luci,ReclaimYourPrivacy/cloak-luci,Kyklas/luci-proto-hso,zhaoxx063/luci,marcel-sch/luci,aa65535/luci,ff94315/luci-1,palmettos/test,wongsyrone/luci-1,ollie27/openwrt_luci,maxrio/luci981213,kuoruan/luci,deepak78/new-luci,Kyklas/luci-proto-hso,urueedi/luci,mumuqz/luci,teslamint/luci,daofeng2015/luci,bright-things/ionic-luci,chris5560/openwrt-luci,dwmw2/luci,jchuang1977/luci-1,oyido/luci,jchuang1977/luci-1,jchuang1977/luci-1,ollie27/openwrt_luci,bright-things/ionic-luci,artynet/luci,dwmw2/luci,opentechinstitute/luci,teslamint/luci,kuoruan/lede-luci,male-puppies/luci,fkooman/luci,Hostle/luci,palmettos/test,oneru/luci,LazyZhu/openwrt-luci-trunk-mod,palmettos/cnLuCI,obsy/luci,male-puppies/luci,keyidadi/luci,dwmw2/luci,sujeet14108/luci,nwf/openwrt-luci,maxrio/luci981213,florian-shellfire/luci,aircross/OpenWrt-Firefly-LuCI,sujeet14108/luci,thesabbir/luci,oneru/luci,hnyman/luci,LazyZhu/openwrt-luci-trunk-mod,thesabbir/luci,Sakura-Winkey/LuCI,rogerpueyo/luci,thess/OpenWrt-luci,bright-things/ionic-luci,slayerrensky/luci,Hostle/luci,joaofvieira/luci,harveyhu2012/luci,maxrio/luci981213,thess/OpenWrt-luci,kuoruan/lede-luci,obsy/luci,thesabbir/luci,aircross/OpenWrt-Firefly-LuCI,keyidadi/luci,teslamint/luci,RuiChen1113/luci,db260179/openwrt-bpi-r1-luci,NeoRaider/luci,jlopenwrtluci/luci,cappiewu/luci,marcel-sch/luci,artynet/luci,RedSnake64/openwrt-luci-packages,shangjiyu/luci-with-extra,Sakura-Winkey/LuCI,daofeng2015/luci,bright-things/ionic-luci,openwrt-es/openwrt-luci,daofeng2015/luci,obsy/luci,ReclaimYourPrivacy/cloak-luci,openwrt/luci,kuoruan/lede-luci,MinFu/luci,deepak78/new-luci,tcatm/luci,schidler/ionic-luci,chris5560/openwrt-luci,cappiewu/luci,oneru/luci,db260179/openwrt-bpi-r1-luci,urueedi/luci,NeoRaider/luci,LuttyYang/luci,Hostle/luci,obsy/luci,nwf/openwrt-luci,bittorf/luci,tcatm/luci,teslamint/luci,thesabbir/luci,deepak78/new-luci,RedSnake64/openwrt-luci-packages,schidler/ionic-luci,teslamint/luci,NeoRaider/luci,lcf258/openwrtcn,daofeng2015/luci,shangjiyu/luci-with-extra,LazyZhu/openwrt-luci-trunk-mod,Hostle/openwrt-luci-multi-user,keyidadi/luci,cshore/luci,Sakura-Winkey/LuCI,thess/OpenWrt-luci,Sakura-Winkey/LuCI,sujeet14108/luci,Noltari/luci,Noltari/luci,remakeelectric/luci,db260179/openwrt-bpi-r1-luci,MinFu/luci,thesabbir/luci,aa65535/luci,Sakura-Winkey/LuCI,Wedmer/luci,tcatm/luci,981213/luci-1,dwmw2/luci,deepak78/new-luci,remakeelectric/luci,palmettos/test,Hostle/openwrt-luci-multi-user,thess/OpenWrt-luci,tobiaswaldvogel/luci,openwrt-es/openwrt-luci,ollie27/openwrt_luci,slayerrensky/luci,remakeelectric/luci,oneru/luci,chris5560/openwrt-luci,palmettos/cnLuCI,bright-things/ionic-luci,hnyman/luci,Kyklas/luci-proto-hso,bittorf/luci,nmav/luci,lbthomsen/openwrt-luci,artynet/luci,hnyman/luci,openwrt/luci,LuttyYang/luci,shangjiyu/luci-with-extra,Hostle/openwrt-luci-multi-user,cshore/luci,jorgifumi/luci,jlopenwrtluci/luci,daofeng2015/luci,florian-shellfire/luci,oneru/luci,male-puppies/luci,harveyhu2012/luci,obsy/luci,cshore-firmware/openwrt-luci,rogerpueyo/luci,Sakura-Winkey/LuCI,nmav/luci,lcf258/openwrtcn,male-puppies/luci,wongsyrone/luci-1,oyido/luci,thess/OpenWrt-luci,nmav/luci,cshore/luci,rogerpueyo/luci,opentechinstitute/luci,dwmw2/luci,lcf258/openwrtcn,981213/luci-1,rogerpueyo/luci,nwf/openwrt-luci,artynet/luci,david-xiao/luci,ff94315/luci-1,artynet/luci,mumuqz/luci,kuoruan/luci,jlopenwrtluci/luci,LuttyYang/luci,slayerrensky/luci,chris5560/openwrt-luci,joaofvieira/luci,forward619/luci,keyidadi/luci,daofeng2015/luci,fkooman/luci,kuoruan/luci,db260179/openwrt-bpi-r1-luci,opentechinstitute/luci,lbthomsen/openwrt-luci,opentechinstitute/luci,LuttyYang/luci,LuttyYang/luci,Noltari/luci,schidler/ionic-luci,keyidadi/luci,thess/OpenWrt-luci,jorgifumi/luci,palmettos/cnLuCI,openwrt-es/openwrt-luci,urueedi/luci,cshore-firmware/openwrt-luci,cshore/luci,harveyhu2012/luci,teslamint/luci,cappiewu/luci,joaofvieira/luci,kuoruan/luci,ff94315/luci-1,marcel-sch/luci,mumuqz/luci,ff94315/luci-1,Hostle/openwrt-luci-multi-user,aa65535/luci,florian-shellfire/luci,cshore/luci,david-xiao/luci,jorgifumi/luci,zhaoxx063/luci,cshore-firmware/openwrt-luci,jlopenwrtluci/luci,ReclaimYourPrivacy/cloak-luci,Hostle/luci,zhaoxx063/luci,florian-shellfire/luci,tobiaswaldvogel/luci,shangjiyu/luci-with-extra,hnyman/luci,bittorf/luci,aircross/OpenWrt-Firefly-LuCI,kuoruan/lede-luci,tcatm/luci,tcatm/luci,oyido/luci,remakeelectric/luci,opentechinstitute/luci,Hostle/openwrt-luci-multi-user,cshore/luci,LuttyYang/luci,Wedmer/luci,zhaoxx063/luci,kuoruan/luci,oyido/luci,NeoRaider/luci,zhaoxx063/luci,fkooman/luci,david-xiao/luci,tobiaswaldvogel/luci,Hostle/luci,RuiChen1113/luci,chris5560/openwrt-luci,hnyman/luci,palmettos/cnLuCI,lcf258/openwrtcn,oneru/luci,Noltari/luci,Wedmer/luci,daofeng2015/luci,taiha/luci,cshore-firmware/openwrt-luci,oyido/luci,kuoruan/lede-luci,oyido/luci,jchuang1977/luci-1,urueedi/luci,Kyklas/luci-proto-hso,artynet/luci,zhaoxx063/luci,dismantl/luci-0.12,jlopenwrtluci/luci,rogerpueyo/luci,aircross/OpenWrt-Firefly-LuCI,nmav/luci,Noltari/luci,MinFu/luci,ollie27/openwrt_luci,joaofvieira/luci,fkooman/luci,cshore-firmware/openwrt-luci,LuttyYang/luci,jchuang1977/luci-1,mumuqz/luci,cshore-firmware/openwrt-luci,daofeng2015/luci,nmav/luci,artynet/luci,lcf258/openwrtcn,Wedmer/luci,LuttyYang/luci,deepak78/new-luci,sujeet14108/luci,RedSnake64/openwrt-luci-packages,lbthomsen/openwrt-luci,LazyZhu/openwrt-luci-trunk-mod,marcel-sch/luci,taiha/luci,MinFu/luci,RuiChen1113/luci,urueedi/luci,remakeelectric/luci,slayerrensky/luci,david-xiao/luci,zhaoxx063/luci,opentechinstitute/luci,cappiewu/luci,oneru/luci,NeoRaider/luci,Noltari/luci,NeoRaider/luci,palmettos/test,kuoruan/lede-luci,jorgifumi/luci,mumuqz/luci,Hostle/luci,chris5560/openwrt-luci,bright-things/ionic-luci,Kyklas/luci-proto-hso,RedSnake64/openwrt-luci-packages,florian-shellfire/luci,jchuang1977/luci-1,cshore/luci,LazyZhu/openwrt-luci-trunk-mod,cappiewu/luci,NeoRaider/luci,db260179/openwrt-bpi-r1-luci,slayerrensky/luci,opentechinstitute/luci,forward619/luci,taiha/luci,rogerpueyo/luci,openwrt/luci,chris5560/openwrt-luci,mumuqz/luci,ollie27/openwrt_luci,forward619/luci,dismantl/luci-0.12,dwmw2/luci,kuoruan/lede-luci,nwf/openwrt-luci,openwrt/luci,kuoruan/luci,shangjiyu/luci-with-extra,ReclaimYourPrivacy/cloak-luci,sujeet14108/luci,obsy/luci,Hostle/openwrt-luci-multi-user,openwrt/luci,chris5560/openwrt-luci,forward619/luci,lbthomsen/openwrt-luci,thesabbir/luci,RedSnake64/openwrt-luci-packages,LazyZhu/openwrt-luci-trunk-mod,kuoruan/luci,jorgifumi/luci,cappiewu/luci,ff94315/luci-1,oyido/luci,marcel-sch/luci,lcf258/openwrtcn,remakeelectric/luci,981213/luci-1,nmav/luci,nwf/openwrt-luci,ollie27/openwrt_luci,marcel-sch/luci,teslamint/luci,LazyZhu/openwrt-luci-trunk-mod,Noltari/luci,jlopenwrtluci/luci,wongsyrone/luci-1,Sakura-Winkey/LuCI,urueedi/luci,Kyklas/luci-proto-hso,Noltari/luci,palmettos/cnLuCI,dwmw2/luci,rogerpueyo/luci,981213/luci-1,981213/luci-1,david-xiao/luci,tobiaswaldvogel/luci,slayerrensky/luci,Noltari/luci,teslamint/luci,wongsyrone/luci-1,artynet/luci,joaofvieira/luci,openwrt-es/openwrt-luci,tcatm/luci,MinFu/luci,Kyklas/luci-proto-hso,dismantl/luci-0.12,tobiaswaldvogel/luci,harveyhu2012/luci,NeoRaider/luci,joaofvieira/luci,ReclaimYourPrivacy/cloak-luci,openwrt-es/openwrt-luci,bittorf/luci,lcf258/openwrtcn,tobiaswaldvogel/luci,lcf258/openwrtcn,RedSnake64/openwrt-luci-packages,maxrio/luci981213,cappiewu/luci,aircross/OpenWrt-Firefly-LuCI,dismantl/luci-0.12,openwrt/luci,nmav/luci,Sakura-Winkey/LuCI,keyidadi/luci,maxrio/luci981213,shangjiyu/luci-with-extra,slayerrensky/luci,wongsyrone/luci-1,oyido/luci,palmettos/test,palmettos/cnLuCI,ff94315/luci-1,Hostle/openwrt-luci-multi-user,jorgifumi/luci,dwmw2/luci,harveyhu2012/luci,LazyZhu/openwrt-luci-trunk-mod,ReclaimYourPrivacy/cloak-luci,nmav/luci,taiha/luci,nmav/luci,taiha/luci,bright-things/ionic-luci,openwrt-es/openwrt-luci,schidler/ionic-luci,ollie27/openwrt_luci,aa65535/luci,bittorf/luci,palmettos/test,deepak78/new-luci,slayerrensky/luci,david-xiao/luci,fkooman/luci,wongsyrone/luci-1,urueedi/luci,nwf/openwrt-luci,lcf258/openwrtcn,Wedmer/luci,male-puppies/luci,harveyhu2012/luci,bright-things/ionic-luci,mumuqz/luci,ReclaimYourPrivacy/cloak-luci,MinFu/luci,Wedmer/luci,wongsyrone/luci-1,jlopenwrtluci/luci,openwrt-es/openwrt-luci,male-puppies/luci,ollie27/openwrt_luci,mumuqz/luci,ff94315/luci-1,marcel-sch/luci,db260179/openwrt-bpi-r1-luci,db260179/openwrt-bpi-r1-luci,male-puppies/luci,nwf/openwrt-luci,bittorf/luci,zhaoxx063/luci,opentechinstitute/luci
|
ed28d42b4dfeb27553f4abdf199de07c072856ff
|
build/scripts/LLVM.lua
|
build/scripts/LLVM.lua
|
require "Build"
require "Utils"
require "../Helpers"
local llvm = basedir .. "/../deps/llvm"
-- If we are inside vagrant then clone and build LLVM outside the shared folder,
-- otherwise file I/O performance will be terrible.
if is_vagrant() then
llvm = "~/llvm"
end
local llvm_build = llvm .. "/" .. os.get()
function get_llvm_rev()
return cat(basedir .. "/LLVM-commit")
end
function get_clang_rev()
return cat(basedir .. "/Clang-commit")
end
function clone_llvm()
local llvm_release = get_llvm_rev()
print("LLVM release: " .. llvm_release)
local clang_release = get_clang_rev()
print("Clang release: " .. clang_release)
if os.isdir(llvm) and not os.isdir(llvm .. "/.git") then
error("LLVM directory is not a git repository.")
end
if not os.isdir(llvm) then
git.clone(llvm, "http://llvm.org/git/llvm.git")
else
git.reset_hard(llvm, "HEAD")
git.pull_rebase(llvm)
end
local clang = llvm .. "/tools/clang"
if not os.isdir(clang) then
git.clone(clang, "http://llvm.org/git/clang.git")
else
git.reset_hard(clang, "HEAD")
git.pull_rebase(clang)
end
git.reset_hard(llvm, llvm_release)
git.reset_hard(clang, clang_release)
end
function get_llvm_package_name(rev, conf)
if not rev then
rev = get_llvm_rev()
end
if not conf then
conf = get_llvm_configuration_name()
end
rev = string.sub(rev, 0, 6)
return table.concat({"llvm", rev, os.get(), conf}, "-")
end
function get_llvm_configuration_name()
return os.is("windows") and "RelWithDebInfo" or "Release"
end
function extract_7z(archive, dest_dir)
return execute(string.format("7z x %s -o%s -y", archive, dest_dir), true)
end
function download_llvm()
local base = "https://dl.dropboxusercontent.com/u/194502/CppSharp/llvm/"
local pkg_name = get_llvm_package_name()
local archive = pkg_name .. ".7z"
-- check if we already have the file downloaded
if not os.isfile(archive) then
download(base .. archive, archive)
end
-- extract the package
if not os.isdir(pkg_name) then
extract_7z(archive, pkg_name)
end
end
function cmake(gen, conf)
local cwd = os.getcwd()
os.chdir(llvm_build)
local cmd = "cmake -G " .. '"' .. gen .. '"'
.. ' -DCLANG_BUILD_EXAMPLES=false -DCLANG_INCLUDE_DOCS=false -DCLANG_INCLUDE_TESTS=false'
.. ' -DCLANG_ENABLE_ARCMT=false -DCLANG_ENABLE_REWRITER=false -DCLANG_ENABLE_STATIC_ANALYZER=false'
.. ' -DLLVM_INCLUDE_EXAMPLES=false -DLLVM_INCLUDE_DOCS=false -DLLVM_INCLUDE_TESTS=false'
.. ' -DLLVM_TARGETS_TO_BUILD="X86"'
.. ' -DCMAKE_BUILD_TYPE=' .. conf .. ' ..'
execute(cmd)
os.chdir(cwd)
end
function clean_llvm(llvm_build)
if os.isdir(llvm_build) then os.rmdir(llvm_build) end
os.mkdir(llvm_build)
end
function build_llvm(llvm_build)
local conf = get_llvm_configuration_name()
if os.is("windows") then
cmake("Visual Studio 12 2013", conf)
local llvm_sln = path.join(llvm_build, "LLVM.sln")
msbuild(llvm_sln, conf)
else
cmake("Ninja", conf)
ninja(llvm_build)
ninja(llvm_build, "clang-headers")
end
end
function package_llvm(conf, llvm, llvm_build)
local rev = git.rev_parse(llvm, "HEAD")
local out = get_llvm_package_name(rev, conf)
if os.isdir(out) then os.rmdir(out) end
os.mkdir(out)
os.copydir(llvm .. "/include", out .. "/include")
os.copydir(llvm_build .. "/include", out .. "/build/include")
local lib_dir = os.is("windows") and "/" .. conf .. "/lib" or "/lib"
local llvm_build_libdir = llvm_build .. lib_dir
if os.is("windows") then
os.copydir(llvm_build_libdir, out .. "/build" .. lib_dir, "*.lib")
else
os.copydir(llvm_build_libdir, out .. "/build/lib", "*.a")
end
os.copydir(llvm .. "/tools/clang/include", out .. "/tools/clang/include")
os.copydir(llvm_build .. "/tools/clang/include", out .. "/build/tools/clang/include")
os.copydir(llvm .. "/tools/clang/lib/CodeGen", out .. "/tools/clang/lib/CodeGen", "*.h")
os.copydir(llvm .. "/tools/clang/lib/Driver", out .. "/tools/clang/lib/Driver", "*.h")
local out_lib_dir = out .. "/build" .. lib_dir
if os.is("windows") then
os.rmfiles(out_lib_dir, "LLVM*ObjCARCOpts*.lib")
os.rmfiles(out_lib_dir, "clang*ARC*.lib")
os.rmfiles(out_lib_dir, "clang*Matchers*.lib")
os.rmfiles(out_lib_dir, "clang*Rewrite*.lib")
os.rmfiles(out_lib_dir, "clang*StaticAnalyzer*.lib")
os.rmfiles(out_lib_dir, "clang*Tooling*.lib")
else
os.rmfiles(out_lib_dir, "libllvm*ObjCARCOpts*.a")
os.rmfiles(out_lib_dir, "libclang*ARC*.a")
os.rmfiles(out_lib_dir, "libclang*Matchers*.a")
os.rmfiles(out_lib_dir, "libclang*Rewrite*.a")
os.rmfiles(out_lib_dir, "libclang*StaticAnalyzer*.a")
os.rmfiles(out_lib_dir, "libclang*Tooling*.a")
end
return out
end
function archive_llvm(dir)
execute("7z a " .. dir .. ".7z " .. "./" .. dir .. "/*")
end
if _ACTION == "clone_llvm" then
clone_llvm()
os.exit()
end
if _ACTION == "build_llvm" then
clean_llvm(llvm_build)
build_llvm(llvm_build)
os.exit()
end
if _ACTION == "package_llvm" then
local conf = get_llvm_configuration_name()
local pkg = package_llvm(conf, llvm, llvm_build)
archive_llvm(pkg)
os.exit()
end
if _ACTION == "download_llvm" then
download_llvm()
os.exit()
end
|
require "Build"
require "Utils"
require "../Helpers"
local llvm = basedir .. "/../deps/llvm"
-- If we are inside vagrant then clone and build LLVM outside the shared folder,
-- otherwise file I/O performance will be terrible.
if is_vagrant() then
llvm = "~/llvm"
end
local llvm_build = llvm .. "/" .. os.get()
function get_llvm_rev()
return cat(basedir .. "/LLVM-commit")
end
function get_clang_rev()
return cat(basedir .. "/Clang-commit")
end
function clone_llvm()
local llvm_release = get_llvm_rev()
print("LLVM release: " .. llvm_release)
local clang_release = get_clang_rev()
print("Clang release: " .. clang_release)
if os.isdir(llvm) and not os.isdir(llvm .. "/.git") then
error("LLVM directory is not a git repository.")
end
if not os.isdir(llvm) then
git.clone(llvm, "http://llvm.org/git/llvm.git")
else
git.reset_hard(llvm, "HEAD")
git.pull_rebase(llvm)
end
local clang = llvm .. "/tools/clang"
if not os.isdir(clang) then
git.clone(clang, "http://llvm.org/git/clang.git")
else
git.reset_hard(clang, "HEAD")
git.pull_rebase(clang)
end
git.reset_hard(llvm, llvm_release)
git.reset_hard(clang, clang_release)
end
function get_llvm_package_name(rev, conf)
if not rev then
rev = get_llvm_rev()
end
if not conf then
conf = get_llvm_configuration_name()
end
rev = string.sub(rev, 0, 6)
return table.concat({"llvm", rev, os.get(), conf}, "-")
end
function get_llvm_configuration_name()
return os.is("windows") and "RelWithDebInfo" or "Release"
end
function extract_7z(archive, dest_dir)
return execute(string.format("7z x %s -o%s -y", archive, dest_dir), true)
end
function download_llvm()
local base = "https://dl.dropboxusercontent.com/u/194502/CppSharp/llvm/"
local pkg_name = get_llvm_package_name()
local archive = pkg_name .. ".7z"
-- check if we already have the file downloaded
if not os.isfile(archive) then
download(base .. archive, archive)
end
-- extract the package
if not os.isdir(pkg_name) then
extract_7z(archive, pkg_name)
end
end
function cmake(gen, conf)
local cwd = os.getcwd()
os.chdir(llvm_build)
local cmd = "cmake -G " .. '"' .. gen .. '"'
.. ' -DCLANG_BUILD_EXAMPLES=false -DCLANG_INCLUDE_DOCS=false -DCLANG_INCLUDE_TESTS=false'
.. ' -DCLANG_ENABLE_ARCMT=false -DCLANG_ENABLE_REWRITER=false -DCLANG_ENABLE_STATIC_ANALYZER=false'
.. ' -DLLVM_INCLUDE_EXAMPLES=false -DLLVM_INCLUDE_DOCS=false -DLLVM_INCLUDE_TESTS=false'
.. ' -DLLVM_TARGETS_TO_BUILD="X86"'
.. ' -DCMAKE_BUILD_TYPE=' .. conf .. ' ..'
execute(cmd)
os.chdir(cwd)
end
function clean_llvm(llvm_build)
if os.isdir(llvm_build) then os.rmdir(llvm_build) end
os.mkdir(llvm_build)
end
function build_llvm(llvm_build)
local conf = get_llvm_configuration_name()
local use_msbuild = false
if os.is("windows") and use_msbuild then
cmake("Visual Studio 12 2013", conf)
local llvm_sln = path.join(llvm_build, "LLVM.sln")
msbuild(llvm_sln, conf)
else
cmake("Ninja", conf)
ninja(llvm_build)
ninja(llvm_build, "clang-headers")
end
end
function package_llvm(conf, llvm, llvm_build)
local rev = git.rev_parse(llvm, "HEAD")
if string.is_empty(rev) then
rev = get_llvm_rev()
end
local out = get_llvm_package_name(rev, conf)
if os.isdir(out) then os.rmdir(out) end
os.mkdir(out)
os.copydir(llvm .. "/include", out .. "/include")
os.copydir(llvm_build .. "/include", out .. "/build/include")
local llvm_msbuild_libdir = "/" .. conf .. "/lib"
local lib_dir = os.is("windows") and os.isdir(llvm_msbuild_libdir)
and llvm_msbuild_libdir or "/lib"
local llvm_build_libdir = llvm_build .. lib_dir
if os.is("windows") and os.isdir(llvm_build_libdir) then
os.copydir(llvm_build_libdir, out .. "/build" .. lib_dir, "*.lib")
else
os.copydir(llvm_build_libdir, out .. "/build/lib", "*.a")
end
os.copydir(llvm .. "/tools/clang/include", out .. "/tools/clang/include")
os.copydir(llvm_build .. "/tools/clang/include", out .. "/build/tools/clang/include")
os.copydir(llvm .. "/tools/clang/lib/CodeGen", out .. "/tools/clang/lib/CodeGen", "*.h")
os.copydir(llvm .. "/tools/clang/lib/Driver", out .. "/tools/clang/lib/Driver", "*.h")
local out_lib_dir = out .. "/build" .. lib_dir
if os.is("windows") then
os.rmfiles(out_lib_dir, "LLVM*ObjCARCOpts*.lib")
os.rmfiles(out_lib_dir, "clang*ARC*.lib")
os.rmfiles(out_lib_dir, "clang*Matchers*.lib")
os.rmfiles(out_lib_dir, "clang*Rewrite*.lib")
os.rmfiles(out_lib_dir, "clang*StaticAnalyzer*.lib")
os.rmfiles(out_lib_dir, "clang*Tooling*.lib")
else
os.rmfiles(out_lib_dir, "libllvm*ObjCARCOpts*.a")
os.rmfiles(out_lib_dir, "libclang*ARC*.a")
os.rmfiles(out_lib_dir, "libclang*Matchers*.a")
os.rmfiles(out_lib_dir, "libclang*Rewrite*.a")
os.rmfiles(out_lib_dir, "libclang*StaticAnalyzer*.a")
os.rmfiles(out_lib_dir, "libclang*Tooling*.a")
end
return out
end
function archive_llvm(dir)
execute("7z a " .. dir .. ".7z " .. "./" .. dir .. "/*")
end
if _ACTION == "clone_llvm" then
clone_llvm()
os.exit()
end
if _ACTION == "build_llvm" then
clean_llvm(llvm_build)
build_llvm(llvm_build)
os.exit()
end
if _ACTION == "package_llvm" then
local conf = get_llvm_configuration_name()
local pkg = package_llvm(conf, llvm, llvm_build)
archive_llvm(pkg)
os.exit()
end
if _ACTION == "download_llvm" then
download_llvm()
os.exit()
end
|
Build and packaging fixes for LLVM on Windows using Ninja.
|
Build and packaging fixes for LLVM on Windows using Ninja.
|
Lua
|
mit
|
u255436/CppSharp,genuinelucifer/CppSharp,inordertotest/CppSharp,u255436/CppSharp,zillemarco/CppSharp,mono/CppSharp,mono/CppSharp,mono/CppSharp,ddobrev/CppSharp,genuinelucifer/CppSharp,u255436/CppSharp,ddobrev/CppSharp,zillemarco/CppSharp,ktopouzi/CppSharp,mohtamohit/CppSharp,zillemarco/CppSharp,inordertotest/CppSharp,ktopouzi/CppSharp,mono/CppSharp,u255436/CppSharp,mohtamohit/CppSharp,ddobrev/CppSharp,genuinelucifer/CppSharp,mohtamohit/CppSharp,genuinelucifer/CppSharp,genuinelucifer/CppSharp,mohtamohit/CppSharp,mono/CppSharp,inordertotest/CppSharp,ddobrev/CppSharp,mohtamohit/CppSharp,inordertotest/CppSharp,zillemarco/CppSharp,ddobrev/CppSharp,u255436/CppSharp,mono/CppSharp,ktopouzi/CppSharp,zillemarco/CppSharp,ktopouzi/CppSharp,ktopouzi/CppSharp,inordertotest/CppSharp
|
146c46289b84459e62f6039aff4794eddf58cab8
|
defaut/Chevalier.lua
|
defaut/Chevalier.lua
|
Ovale.defaut["DEATHKNIGHT"] = [[
#Abilities
Define(ARMYOFTHEDEAD 42650)
SpellInfo(ARMYOFTHEDEAD cd=600)
Define(BLOODBOIL 48721)
Define(BLOODPRESENCE 48263)
Define(BLOODSTRIKE 45902)
SpellInfo(BLOODSTRIKE blood=-1)
Define(BLOODTAP 45529)
Define(BONESHIELD 49222) #blood
SpellAddBuff(BONESHIELD BONESHIELD=300)
Define(DANCINGRUNEWEAPON 49028) #blood
Define(DARKTRANSFORMATION 63560) #unholy
Define(DEATHANDECAY 43265)
Define(DEATHCOIL 47541)
Define(DEATHSTRIKE 49998)
SpellInfo(DEATHSTRIKE unholy=-1 frost=-1)
Define(EMPOWERRUNEWEAPON 47568)
Define(FESTERINGSTRIKE 85948) #1 frost 1 blood
Define(FROSTPRESENCE 48266)
Define(FROSTSTRIKE 49143) #frost
SpellInfo(FROSTSTRIKE mana=40)
Define(HEARTSTRIKE 55050) #blood
SpellInfo(HEARTSTRIKE blood=-1)
Define(HORNOFWINTER 57330)
SpellInfo(HORNOFWINTER cd=20)
Define(HOWLINGBLAST 49184) #frost
SpellInfo(HOWLINGBLAST frost=-1 cd=8)
SpellAddTargetDebuff(HOWLINGBLAST FROSTFEVER=15 glyph=GLYPHHOWLINGBLAST)
Define(ICEBOUNDFORTITUDE 48792)
SpellAddBuff(ICEBOUNDFORTITUDE ICEBOUNDFORTITUDE=18)
Define(ICYTOUCH 45477)
SpellInfo(ICYTOUCH frost=-1)
SpellAddTargetDebuff(ICYTOUCH FROSTFEVER=15)
Define(OBLITERATE 49020)
SpellInfo(OBLITERATE unholy=-1 frost=-1)
Define(OUTBREAK 77575)
Define(PESTILENCE 50842)
Define(PILLAROFFROST 51271) #frost
Define(PLAGUESTRIKE 45462)
SpellInfo(PLAGUESTRIKE unholy=-1)
SpellAddTargetDebuff(PLAGUESTRIKE BLOODPLAGUE=15)
Define(RAISEDEAD 46584)
Define(RUNESTRIKE 56815)
SpellInfo(RUNESTRIKE mana=20)
Define(RUNETAP 48982) #blood
SpellInfo(RUNETAP blood=-1)
Define(SCOURGESTRIKE 55090) #unholy
SpellInfo(SCOURGESTRIKE unholy=-1)
Define(SUMMONGARGOYLE 49206) #unholy
SpellInfo(SUMMONGARGOYLE cd=180)
Define(UNHOLYBLIGHT 49194)
Define(UNHOLYFRENZY 49016)
SpellInfo(UNHOLYFRENZY cd=300)
Define(UNHOLYPRESENCE 48265)
Define(VAMPIRICBLOOD 55233) #blood
SpellInfo(VAMPIRICBLOOD blood=-1)
#Talents
#Define(TALENTDEATSTRIKE 2259)
#Define(TALENTFROSTSTRIKE 1975)
#Define(TALENTHEARTSTRIKE 1957)
#Define(TALENTBLOODYSTRIKES 2015)
#Glyphs
Define(GLYPHHOWLINGBLAST 63335)
#Buffs and debuffs
Define(BLOODPLAGUE 59879)
Define(FROSTFEVER 59921)
Define(KILLINGMACHINE 51124)
Define(SHADOWINFUSION 49572)
Define(SUDDENDOOM 49530)
AddCheckBox(horn SpellName(HORNOFWINTER))
ScoreSpells(HOWLINGBLAST HEARTSTRIKE BLOODSTRIKE DEATHSTRIKE SCOURGESTRIKE OBLITERATE HEARTSTRIKE
PESTILENCE ICYTOUCH PLAGUESTRIKE FROSTSTRIKE DEATHCOIL)
AddIcon help=main mastery=1
{
Spell(DANCINGRUNEWEAPON usable=1)
if BuffExpires(strengthagility 2) and CheckBoxOn(horn) Spell(HORNOFWINTER)
if TargetDebuffPresent(FROSTFEVER mine=1) and TargetDebuffPresent(BLOODPLAGUE mine=1)
{
if Runes(blood 1) and {CheckBoxOff(rolldes) or Runes(blood 2)} Spell(HEARTSTRIKE)
if Runes(unholy 1 nodeath=1) and Runes(frost 1 nodeath=1) Spell(DEATHSTRIKE)
}
if TargetDebuffExpires(FROSTFEVER 0 mine=1) and Runes(frost 1) Spell(ICYTOUCH)
if TargetDebuffExpires(BLOODPLAGUE 0 mine=1) and Runes(unholy 1) Spell(PLAGUESTRIKE)
if PetPresent(no) Spell(RAISEDEAD)
Spell(RUNESTRIKE usable=1)
if Mana(more 39) Spell(DEATHCOIL usable=1)
if CheckBoxOn(horn) Spell(HORNOFWINTER priority=2)
}
AddIcon help=main mastery=2
{
if BuffExpires(strengthagility 2) and CheckBoxOn(horn) Spell(HORNOFWINTER)
if BuffPresent(KILLINGMACHINE) Spell(FROSTSTRIKE usable=1)
if TargetDebuffPresent(FROSTFEVER mine=1) and TargetDebuffPresent(BLOODPLAGUE mine=1)
{
if Runes(unholy 1 nodeath=1) and Runes(frost 1 nodeath=1) Spell(OBLITERATE)
if Runes(blood 1) and {CheckBoxOff(rolldes) or Runes(blood 2)} Spell(BLOODSTRIKE)
}
if TargetDebuffExpires(FROSTFEVER 0 mine=1) and Runes(frost 1)
{
if Glyph(GLYPHHOWLINGBLAST) Spell(HOWLINGBLAST)
unless Glyph(GLYPHHOWLINGBLAST) Spell(ICYTOUCH)
}
if TargetDebuffExpires(BLOODPLAGUE 0 mine=1) and Runes(unholy 1) Spell(PLAGUESTRIKE)
Spell(FROSTSTRIKE usable=1)
if PetPresent(no) Spell(RAISEDEAD)
if CheckBoxOn(horn) Spell(HORNOFWINTER priority=2)
unless Runes(frost 1) and Runes(unholy 1) Spell(BLOODTAP)
if Runes(blood 2 nodeath=1)
{
Spell(HEARTSTRIKE priority=2)
Spell(BLOODSTRIKE priority=2)
}
}
AddIcon help=main mastery=3
{
if BuffExpires(strengthagility 2) and CheckBoxOn(horn) Spell(HORNOFWINTER)
if TargetDebuffPresent(FROSTFEVER mine=1) and TargetDebuffPresent(BLOODPLAGUE mine=1)
{
if TargetBuffPresent(SHADOWINFUSION stacks=5 target=pet) Spell(DARKTRANSFORMATION)
if BuffPresent(SUDDENDOOM mine=1) Spell(DEATHCOIL usable=1)
if Mana(more 90) Spell(DEATHCOIL usable=1)
if Runes(unholy 1) Spell(SCOURGESTRIKE)
if Runes(blood 1 nodeath=1) and Runes(frost 1 nodeath=1) Spell(FESTERINGSTRIKE)
}
if TargetDebuffExpires(FROSTFEVER 0 mine=1) and Runes(frost 1) Spell(ICYTOUCH)
if TargetDebuffExpires(BLOODPLAGUE 0 mine=1) and Runes(unholy 1) Spell(PLAGUESTRIKE)
if PetPresent(no) Spell(RAISEDEAD)
if Mana(more 34) Spell(DEATHCOIL usable=1)
if CheckBoxOn(horn) Spell(HORNOFWINTER priority=2)
}
AddIcon help=aoe
{
if Runes(unholy 1) and Runes(frost 1) Spell(HOWLINGBLAST)
if TargetDebuffPresent(BLOODPLAGUE) or TargetDebuffPresent(FROSTFEVER)
Spell(PESTILENCE usable=1)
Spell(DEATHANDECAY usable=1)
Spell(BLOODBOIL usable=1)
}
AddIcon help=cd
{
unless BuffPresent(BONESHIELD) Spell(BONESHIELD)
if BuffPresent(BLOODPRESENCE)
{
Spell(VAMPIRICBLOOD)
Spell(RUNETAP)
Spell(UNBREAKABLEARMOR)
Spell(ICEBOUNDFORTITUDE)
}
Spell(SUMMONGARGOYLE)
Item(Trinket0Slot usable=1)
Item(Trinket1Slot usable=1)
Spell(ARMYOFTHEDEAD)
}
]]
|
Ovale.defaut["DEATHKNIGHT"] = [[
#Abilities
Define(ARMYOFTHEDEAD 42650)
SpellInfo(ARMYOFTHEDEAD cd=600)
Define(BLOODBOIL 48721)
Define(BLOODPRESENCE 48263)
Define(BLOODSTRIKE 45902)
SpellInfo(BLOODSTRIKE blood=-1)
Define(BLOODTAP 45529)
Define(BONESHIELD 49222) #blood
SpellAddBuff(BONESHIELD BONESHIELD=300)
Define(DANCINGRUNEWEAPON 49028) #blood
Define(DARKTRANSFORMATION 63560) #unholy
Define(DEATHANDECAY 43265)
Define(DEATHCOIL 47541)
Define(DEATHSTRIKE 49998)
SpellInfo(DEATHSTRIKE unholy=-1 frost=-1)
Define(EMPOWERRUNEWEAPON 47568)
Define(FESTERINGSTRIKE 85948) #1 frost 1 blood
Define(FROSTPRESENCE 48266)
Define(FROSTSTRIKE 49143) #frost
SpellInfo(FROSTSTRIKE mana=40)
Define(HEARTSTRIKE 55050) #blood
SpellInfo(HEARTSTRIKE blood=-1)
Define(HORNOFWINTER 57330)
SpellInfo(HORNOFWINTER cd=20)
Define(HOWLINGBLAST 49184) #frost
SpellInfo(HOWLINGBLAST frost=-1 cd=8)
SpellAddTargetDebuff(HOWLINGBLAST FROSTFEVER=15 glyph=GLYPHHOWLINGBLAST)
Define(ICEBOUNDFORTITUDE 48792)
SpellAddBuff(ICEBOUNDFORTITUDE ICEBOUNDFORTITUDE=18)
Define(ICYTOUCH 45477)
SpellInfo(ICYTOUCH frost=-1)
SpellAddTargetDebuff(ICYTOUCH FROSTFEVER=15)
Define(OBLITERATE 49020)
SpellInfo(OBLITERATE unholy=-1 frost=-1)
Define(OUTBREAK 77575)
Define(PESTILENCE 50842)
Define(PILLAROFFROST 51271) #frost
Define(PLAGUESTRIKE 45462)
SpellInfo(PLAGUESTRIKE unholy=-1)
SpellAddTargetDebuff(PLAGUESTRIKE BLOODPLAGUE=15)
Define(RAISEDEAD 46584)
Define(RUNESTRIKE 56815)
SpellInfo(RUNESTRIKE mana=20)
Define(RUNETAP 48982) #blood
SpellInfo(RUNETAP blood=-1)
Define(SCOURGESTRIKE 55090) #unholy
SpellInfo(SCOURGESTRIKE unholy=-1)
Define(SUMMONGARGOYLE 49206) #unholy
SpellInfo(SUMMONGARGOYLE cd=180)
Define(UNHOLYBLIGHT 49194)
Define(UNHOLYFRENZY 49016)
SpellInfo(UNHOLYFRENZY cd=300)
Define(UNHOLYPRESENCE 48265)
Define(VAMPIRICBLOOD 55233) #blood
SpellInfo(VAMPIRICBLOOD blood=-1)
#Talents
#Define(TALENTDEATSTRIKE 2259)
#Define(TALENTFROSTSTRIKE 1975)
#Define(TALENTHEARTSTRIKE 1957)
#Define(TALENTBLOODYSTRIKES 2015)
#Glyphs
Define(GLYPHHOWLINGBLAST 63335)
#Buffs and debuffs
Define(BLOODPLAGUE 55078)
Define(FROSTFEVER 55095)
Define(KILLINGMACHINE 51124)
Define(SHADOWINFUSION 91342)
Define(SUDDENDOOM 81340)
AddCheckBox(horn SpellName(HORNOFWINTER))
ScoreSpells(HOWLINGBLAST HEARTSTRIKE BLOODSTRIKE DEATHSTRIKE SCOURGESTRIKE OBLITERATE HEARTSTRIKE
PESTILENCE ICYTOUCH PLAGUESTRIKE FROSTSTRIKE DEATHCOIL)
AddIcon help=main mastery=1
{
Spell(DANCINGRUNEWEAPON usable=1)
if BuffExpires(strengthagility 2) and CheckBoxOn(horn) Spell(HORNOFWINTER)
if TargetDebuffPresent(FROSTFEVER mine=1) and TargetDebuffPresent(BLOODPLAGUE mine=1)
{
if Runes(blood 1) and {CheckBoxOff(rolldes) or Runes(blood 2)} Spell(HEARTSTRIKE)
if Runes(unholy 1 nodeath=1) and Runes(frost 1 nodeath=1) Spell(DEATHSTRIKE)
}
if TargetDebuffExpires(FROSTFEVER 0 mine=1) and Runes(frost 1) Spell(ICYTOUCH)
if TargetDebuffExpires(BLOODPLAGUE 0 mine=1) and Runes(unholy 1) Spell(PLAGUESTRIKE)
if PetPresent(no) Spell(RAISEDEAD)
Spell(RUNESTRIKE usable=1)
if Mana(more 39) Spell(DEATHCOIL usable=1)
if CheckBoxOn(horn) Spell(HORNOFWINTER priority=2)
}
AddIcon help=main mastery=2
{
if BuffExpires(strengthagility 2) and CheckBoxOn(horn) Spell(HORNOFWINTER)
if BuffPresent(KILLINGMACHINE) Spell(FROSTSTRIKE usable=1)
if TargetDebuffPresent(FROSTFEVER mine=1) and TargetDebuffPresent(BLOODPLAGUE mine=1)
{
if Runes(unholy 1 nodeath=1) and Runes(frost 1 nodeath=1) Spell(OBLITERATE)
if Runes(blood 1) and {CheckBoxOff(rolldes) or Runes(blood 2)} Spell(BLOODSTRIKE)
}
if TargetDebuffExpires(FROSTFEVER 0 mine=1) and Runes(frost 1)
{
if Glyph(GLYPHHOWLINGBLAST) Spell(HOWLINGBLAST)
unless Glyph(GLYPHHOWLINGBLAST) Spell(ICYTOUCH)
}
if TargetDebuffExpires(BLOODPLAGUE 0 mine=1) and Runes(unholy 1) Spell(PLAGUESTRIKE)
Spell(FROSTSTRIKE usable=1)
if PetPresent(no) Spell(RAISEDEAD)
if CheckBoxOn(horn) Spell(HORNOFWINTER priority=2)
unless Runes(frost 1) and Runes(unholy 1) Spell(BLOODTAP)
if Runes(blood 2 nodeath=1)
{
Spell(HEARTSTRIKE priority=2)
Spell(BLOODSTRIKE priority=2)
}
}
AddIcon help=main mastery=3
{
if BuffExpires(strengthagility 2) and CheckBoxOn(horn) Spell(HORNOFWINTER)
if TargetDebuffPresent(FROSTFEVER mine=1) and TargetDebuffPresent(BLOODPLAGUE mine=1)
{
if Runes(unholy 1) and TargetBuffPresent(SHADOWINFUSION stacks=5 target=pet) Spell(DARKTRANSFORMATION)
if BuffPresent(SUDDENDOOM mine=1) Spell(DEATHCOIL usable=1)
if Mana(more 90) Spell(DEATHCOIL usable=1)
if Runes(unholy 1) Spell(SCOURGESTRIKE)
if Runes(blood 1 nodeath=1) and Runes(frost 1 nodeath=1) Spell(FESTERINGSTRIKE)
}
if TargetDebuffExpires(FROSTFEVER 0 mine=1) and Runes(frost 1) Spell(ICYTOUCH)
if TargetDebuffExpires(BLOODPLAGUE 0 mine=1) and Runes(unholy 1) Spell(PLAGUESTRIKE)
if PetPresent(no) Spell(RAISEDEAD)
if Mana(more 34) Spell(DEATHCOIL usable=1)
if CheckBoxOn(horn) Spell(HORNOFWINTER priority=2)
}
AddIcon help=aoe
{
if Runes(unholy 1) and Runes(frost 1) Spell(HOWLINGBLAST)
if TargetDebuffPresent(BLOODPLAGUE) or TargetDebuffPresent(FROSTFEVER)
Spell(PESTILENCE usable=1)
Spell(DEATHANDECAY usable=1)
Spell(BLOODBOIL usable=1)
}
AddIcon help=cd
{
unless BuffPresent(BONESHIELD) Spell(BONESHIELD)
if BuffPresent(BLOODPRESENCE)
{
Spell(VAMPIRICBLOOD)
Spell(RUNETAP)
Spell(UNBREAKABLEARMOR)
Spell(ICEBOUNDFORTITUDE)
}
Spell(SUMMONGARGOYLE)
Item(Trinket0Slot usable=1)
Item(Trinket1Slot usable=1)
Spell(ARMYOFTHEDEAD)
}
]]
|
deathknight: bug fixes
|
deathknight: bug fixes
git-svn-id: b2bb544abab4b09d60f88077ac82407cb244c9c9@287 d5049fe3-3747-40f7-a4b5-f36d6801af5f
|
Lua
|
mit
|
eXhausted/Ovale,Xeltor/ovale,ultijlam/ovale,eXhausted/Ovale,ultijlam/ovale,ultijlam/ovale,eXhausted/Ovale
|
2bcad8aac7cfe3a10ee000e03d733bf33805d0de
|
lib/resty/auto-ssl/ssl_providers/lets_encrypt.lua
|
lib/resty/auto-ssl/ssl_providers/lets_encrypt.lua
|
local _M = {}
local shell_execute = require "resty.auto-ssl.utils.shell_execute"
function _M.issue_cert(auto_ssl_instance, domain)
local package_root = auto_ssl_instance.package_root
local base_dir = auto_ssl_instance:get("dir")
-- Run dehydrated for this domain, using our custom hooks to handle the
-- domain validation and the issued certificates.
local command = "env HOOK_SECRET=" .. ngx.shared.auto_ssl:get("hook_server:secret") .. " " ..
package_root .. "/auto-ssl/vendor/dehydrated " ..
"--cron " ..
"--domain " .. domain .. " " ..
"--challenge http-01 " ..
"--config " .. base_dir .. "/letsencrypt/config " ..
"--hook " .. package_root .. "/auto-ssl/shell/letsencrypt_hooks"
local status, out, err = shell_execute(command)
if status ~= 0 then
ngx.log(ngx.ERR, "auto-ssl: dehydrated failed: ", command, " status: ", status, " out: ", out, " err: ", err)
return nil, nil, "dehydrated failure"
end
ngx.log(ngx.DEBUG, "auto-ssl: dehydrated output: " .. out)
-- The result of running that command should result in the certs being
-- populated in our storage (due to the deploy_cert hook triggering).
local storage = auto_ssl_instance:get("storage")
local fullchain_pem, privkey_pem = storage:get_cert(domain)
-- If dehydrated said it succeeded, but we still don't have any certs in
-- storage, the issue is likely that the certs have been deleted out of our
-- storage, but still exist in dehydrated's certs directory. If this
-- occurs, try to manually fire the deploy_cert hook again to populate our
-- storage with dehydrated's local copies.
if not fullchain_pem or not privkey_pem then
ngx.log(ngx.WARN, "auto-ssl: dehydrated succeeded, but certs still missing from storage - trying to manually copy - domain: " .. domain)
command = "env HOOK_SECRET=" .. ngx.shared.auto_ssl:get("hook_server:secret") .. " " ..
package_root .. "/auto-ssl/shell/letsencrypt_hooks " ..
"deploy_cert " ..
domain .. " " ..
base_dir .. "/letsencrypt/certs/" .. domain .. "/privkey.pem " ..
base_dir .. "/letsencrypt/certs/" .. domain .. "/cert.pem " ..
base_dir .. "/letsencrypt/certs/" .. domain .. "/fullchain.pem " ..
base_dir .. "/letsencrypt/certs/" .. domain .. "/chain.pem " ..
math.floor(ngx.now())
status, out, err = shell_execute(command)
if status ~= 0 then
ngx.log(ngx.ERR, "auto-ssl: dehydrated manual hook.sh failed: ", command, " status: ", status, " out: ", out, " err: ", err)
return nil, nil, "dehydrated failure"
end
-- Try fetching again.
fullchain_pem, privkey_pem = storage:get_cert(domain)
end
-- Return error if things are still unexpectedly missing.
if not fullchain_pem or not privkey_pem then
return nil, nil, "dehydrated succeeded, but no certs present"
end
return fullchain_pem, privkey_pem
end
return _M
|
local _M = {}
local shell_execute = require "resty.auto-ssl.utils.shell_execute"
function _M.issue_cert(auto_ssl_instance, domain)
local package_root = auto_ssl_instance.package_root
local base_dir = auto_ssl_instance:get("dir")
-- Run dehydrated for this domain, using our custom hooks to handle the
-- domain validation and the issued certificates.
--
-- Disable dehydrated's locking, since we perform our own domain-specific
-- locking using the storage adapter.
local command = "env HOOK_SECRET=" .. ngx.shared.auto_ssl:get("hook_server:secret") .. " " ..
package_root .. "/auto-ssl/vendor/dehydrated " ..
"--cron " ..
"--no-lock " ..
"--domain " .. domain .. " " ..
"--challenge http-01 " ..
"--config " .. base_dir .. "/letsencrypt/config " ..
"--hook " .. package_root .. "/auto-ssl/shell/letsencrypt_hooks"
local status, out, err = shell_execute(command)
if status ~= 0 then
ngx.log(ngx.ERR, "auto-ssl: dehydrated failed: ", command, " status: ", status, " out: ", out, " err: ", err)
return nil, nil, "dehydrated failure"
end
ngx.log(ngx.DEBUG, "auto-ssl: dehydrated output: " .. out)
-- The result of running that command should result in the certs being
-- populated in our storage (due to the deploy_cert hook triggering).
local storage = auto_ssl_instance:get("storage")
local fullchain_pem, privkey_pem = storage:get_cert(domain)
-- If dehydrated said it succeeded, but we still don't have any certs in
-- storage, the issue is likely that the certs have been deleted out of our
-- storage, but still exist in dehydrated's certs directory. If this
-- occurs, try to manually fire the deploy_cert hook again to populate our
-- storage with dehydrated's local copies.
if not fullchain_pem or not privkey_pem then
ngx.log(ngx.WARN, "auto-ssl: dehydrated succeeded, but certs still missing from storage - trying to manually copy - domain: " .. domain)
command = "env HOOK_SECRET=" .. ngx.shared.auto_ssl:get("hook_server:secret") .. " " ..
package_root .. "/auto-ssl/shell/letsencrypt_hooks " ..
"deploy_cert " ..
domain .. " " ..
base_dir .. "/letsencrypt/certs/" .. domain .. "/privkey.pem " ..
base_dir .. "/letsencrypt/certs/" .. domain .. "/cert.pem " ..
base_dir .. "/letsencrypt/certs/" .. domain .. "/fullchain.pem " ..
base_dir .. "/letsencrypt/certs/" .. domain .. "/chain.pem " ..
math.floor(ngx.now())
status, out, err = shell_execute(command)
if status ~= 0 then
ngx.log(ngx.ERR, "auto-ssl: dehydrated manual hook.sh failed: ", command, " status: ", status, " out: ", out, " err: ", err)
return nil, nil, "dehydrated failure"
end
-- Try fetching again.
fullchain_pem, privkey_pem = storage:get_cert(domain)
end
-- Return error if things are still unexpectedly missing.
if not fullchain_pem or not privkey_pem then
return nil, nil, "dehydrated succeeded, but no certs present"
end
return fullchain_pem, privkey_pem
end
return _M
|
Fix concurrent request creation for different domains.
|
Fix concurrent request creation for different domains.
dehydrated's internal locking was redundant to our own locking
mechanism, but also prevented different domains from being registered at
the same time (which our own locking should allow).
Fixes https://github.com/GUI/lua-resty-auto-ssl/issues/24
|
Lua
|
mit
|
UseFedora/lua-resty-auto-ssl,GUI/lua-resty-auto-ssl,UseFedora/lua-resty-auto-ssl
|
31d2fb6ff20e628315399468fdb8c54899b34c7c
|
test/test.lua
|
test/test.lua
|
local M = {}
local pb = require("luapbintf")
function script_path()
local str = debug.getinfo(2, "S").source:sub(2)
return str:match("(.*/)")
end
pb.add_proto_path(script_path())
-- test.proto imports common.proto
pb.import_proto_file("test.proto")
function M.test_rpc()
assert(pb.get_rpc_input_name("test.Test", "Foo") == "test.TestMsg")
assert(pb.get_rpc_output_name("test.Test", "Foo") == "test.CommonMsg")
end -- test_rpc()
function M.test_encode_decode()
local msg = { uid = 12345 }
local s = pb.encode("test.TestMsg", msg)
local msg2 = pb.decode("test.TestMsg", s)
assert(msg2.uid == 12345)
end -- test_encode_decode()
function M.test_repeated()
local msg = { names = {"n1", "n2", "n3"} }
local s = pb.encode("test.TestMsg", msg)
local msg2 = pb.decode("test.TestMsg", s)
assert(#msg2.names == 3)
assert("n3" == msg2.names[3]) -- Maybe reordered.
end -- test_repeated()
-- Array table will ignore other index.
function M.test_repeated_ignore()
local msg = { names = {"n1", "n2", "n3", [0] = "n1", [100] = "n100"} }
local s = pb.encode("test.TestMsg", msg)
local msg2 = pb.decode("test.TestMsg", s)
assert(#msg2.names == 3)
end -- test_repeated_ignore()
function M.test_default_value()
local msg2 = assert(pb.decode("test.TestMsg", ""))
assert(nil == msg2.common_msg)
assert(0 == msg2.cmd)
assert(#msg2.names == 0)
end
function M.test_type_convertion_s2n()
local msg = { uid = "12345" }
local s = pb.encode("test.TestMsg", msg)
assert(pb.decode("test.TestMsg", s).uid == 12345)
end -- test_type_convertion_s2n()
function M.test_type_convertion_n2s()
local msg = { name = 12345 }
local s = pb.encode("test.TestMsg", msg)
assert(pb.decode("test.TestMsg", s).name == "12345")
end -- test_type_convertion_n2s()
function M.test_type_convertion_n2n()
local msg = { n32 = 4294967296 + 123 }
assert(msg.n32 == 4294967296 + 123)
local s = pb.encode("test.TestMsg", msg)
local msg2 = pb.decode("test.TestMsg", s)
assert(msg2.n32 == 123)
end -- test_type_convertion_n2n()
function M.test_type_convertion_s2d()
local msg = { d = "12345e-67" }
local s = pb.encode("test.TestMsg", msg)
assert(pb.decode("test.TestMsg", s).d == 12345e-67)
end -- test_type_convertion_s2d()
function M.test_type_convertion_f2n()
local msg = { n32 = 1.0 }
local s = pb.encode("test.TestMsg", msg)
assert(pb.decode("test.TestMsg", s).d == 12345e-67)
end -- test_type_convertion_s2d()
function M.test_string_enum()
local msg = { cmd = "CMD_TYPE_CHECK" }
local s = pb.encode("test.TestMsg", msg)
assert(pb.decode("test.TestMsg", s).cmd == 2)
end -- test_string_enum()
function M.test_s1234_enum()
local msg = { cmd = "1234" }
local s = pb.encode("test.TestMsg", msg)
assert(pb.decode("test.TestMsg", s).cmd == 1234)
end -- test_string_enum()
function M.test_many_fields()
local msg = {
uid = 12345,
param = 9876,
name = "Jin Qing",
names = {"n1", "n2", "n3"},
cmd = 10,
common_msg = {},
}
local s = pb.encode("test.TestMsg", msg)
local msg2 = pb.decode("test.TestMsg", s)
assert(msg2.name == "Jin Qing")
assert(#msg2.names == 3)
local n3 = msg2.names[3]
-- Maybe reordered.
assert(n3 == "n1" or n3 == "n2" or n3 == "n3")
assert(10 == msg2.cmd)
assert(msg2.common_msg)
end -- test_encode_decode()
function M.test_packed()
local msg = { samples = {1,2,3} }
local s = pb.encode("test.TestMsg", msg)
local msg2 = pb.decode("test.TestMsg", s)
assert(#msg2.samples == 3)
end -- test.packed()
function M.test_map()
local msgs = {}
msgs["k1"] = {}
msgs["k2"] = {}
local msg = { msgs = msgs }
local s = pb.encode("test.TestMsg", msg)
local msg2 = pb.decode("test.TestMsg", s)
assert(msg2.msgs["k1"])
assert(msg2.msgs["k2"])
end -- test_map()
function M.test_map_index_convert()
local msg = { msgs = { {}, {}, ["key"] = {} } }
local s = pb.encode("test.TestMsg", msg)
local msg2 = pb.decode("test.TestMsg", s)
-- key 1,2 is converted to "1", "2"
assert(msg2.msgs[1] == nil)
assert(msg2.msgs["1"])
assert(msg2.msgs["2"])
assert(msg2.msgs["key"])
end -- test_map_index_convert()
function M.test_oneof_name()
local msg = { name2 = "Jin Qing" }
local s = pb.encode("test.TestMsg", msg)
local msg2 = pb.decode("test.TestMsg", s)
assert(msg2.name2 == "Jin Qing")
assert(msg2.msg2 == nil)
end -- test.oneof_name()
function M.test_oneof_msg()
local msg = { msg2 = {} }
local s = pb.encode("test.TestMsg", msg)
local msg2 = pb.decode("test.TestMsg", s)
assert(msg2.name == "")
assert(msg2.name2 == nil)
assert(msg2.msg2)
end -- test.oneof_msg()
function M.test_oneof_none()
local s = pb.encode("test.TestMsg", {})
local msg2 = pb.decode("test.TestMsg", s)
assert(msg2.name2 == nil)
assert(msg2.msg2 == nil)
end -- test.oneof_none()
function M.test_oneof_both()
local msg = { name2 = "abc", msg2 = {} }
local s = pb.encode("test.TestMsg", msg)
local msg2 = pb.decode("test.TestMsg", s)
assert(msg2.name2 or msg2.msg2)
assert(msg2.name2 == nil or msg2.msg2 == nil)
end -- test.oneof_both()
function M.test_oneof_default_value()
local msg = { name2 = "" }
local s = pb.encode("test.TestMsg", msg)
local msg2 = pb.decode("test.TestMsg", s)
assert(msg2.name2 == "")
end -- test_oneof_default_value()
function M.test_decode_return_nil()
assert(nil == pb.decode("test.TestMsg", "IllegalData"))
end -- test_decode_return_nil()
function M.test_all()
M.test_rpc()
M.test_encode_decode()
M.test_repeated()
M.test_repeated_ignore()
M.test_default_value()
M.test_type_convertion_s2n()
M.test_type_convertion_n2s()
M.test_type_convertion_n2n()
M.test_type_convertion_s2d()
M.test_string_enum()
M.test_s1234_enum()
M.test_many_fields()
M.test_packed()
M.test_map()
M.test_map_index_convert()
M.test_oneof_name()
M.test_oneof_msg()
M.test_oneof_none()
M.test_oneof_both()
M.test_oneof_default_value()
M.test_decode_return_nil()
print("Test OK!")
end -- test_all
M.test_all()
return M
|
local M = {}
local pb = require("luapbintf")
local function script_path()
local source = debug.getinfo(2, "S").source
return source:match("@(.*/)") or ""
end
pb.add_proto_path(script_path())
-- test.proto imports common.proto
pb.import_proto_file("test.proto")
function M.test_rpc()
assert(pb.get_rpc_input_name("test.Test", "Foo") == "test.TestMsg")
assert(pb.get_rpc_output_name("test.Test", "Foo") == "test.CommonMsg")
end -- test_rpc()
function M.test_encode_decode()
local msg = { uid = 12345 }
local s = pb.encode("test.TestMsg", msg)
local msg2 = pb.decode("test.TestMsg", s)
assert(msg2.uid == 12345)
end -- test_encode_decode()
function M.test_repeated()
local msg = { names = {"n1", "n2", "n3"} }
local s = pb.encode("test.TestMsg", msg)
local msg2 = pb.decode("test.TestMsg", s)
assert(#msg2.names == 3)
assert("n3" == msg2.names[3]) -- Maybe reordered.
end -- test_repeated()
-- Array table will ignore other index.
function M.test_repeated_ignore()
local msg = { names = {"n1", "n2", "n3", [0] = "n1", [100] = "n100"} }
local s = pb.encode("test.TestMsg", msg)
local msg2 = pb.decode("test.TestMsg", s)
assert(#msg2.names == 3)
end -- test_repeated_ignore()
function M.test_default_value()
local msg2 = assert(pb.decode("test.TestMsg", ""))
assert(nil == msg2.common_msg)
assert(0 == msg2.cmd)
assert(#msg2.names == 0)
end
function M.test_type_convertion_s2n()
local msg = { uid = "12345" }
local s = pb.encode("test.TestMsg", msg)
assert(pb.decode("test.TestMsg", s).uid == 12345)
end -- test_type_convertion_s2n()
function M.test_type_convertion_n2s()
local msg = { name = 12345 }
local s = pb.encode("test.TestMsg", msg)
assert(pb.decode("test.TestMsg", s).name == "12345")
end -- test_type_convertion_n2s()
function M.test_type_convertion_n2n()
local msg = { n32 = 4294967296 + 123 }
assert(msg.n32 == 4294967296 + 123)
local s = pb.encode("test.TestMsg", msg)
local msg2 = pb.decode("test.TestMsg", s)
assert(msg2.n32 == 123)
end -- test_type_convertion_n2n()
function M.test_type_convertion_s2d()
local msg = { d = "12345e-67" }
local s = pb.encode("test.TestMsg", msg)
assert(pb.decode("test.TestMsg", s).d == 12345e-67)
end -- test_type_convertion_s2d()
function M.test_type_convertion_f2n()
local msg = { n32 = 1.0 }
local s = pb.encode("test.TestMsg", msg)
assert(pb.decode("test.TestMsg", s).d == 12345e-67)
end -- test_type_convertion_s2d()
function M.test_string_enum()
local msg = { cmd = "CMD_TYPE_CHECK" }
local s = pb.encode("test.TestMsg", msg)
assert(pb.decode("test.TestMsg", s).cmd == 2)
end -- test_string_enum()
function M.test_s1234_enum()
local msg = { cmd = "1234" }
local s = pb.encode("test.TestMsg", msg)
assert(pb.decode("test.TestMsg", s).cmd == 1234)
end -- test_string_enum()
function M.test_many_fields()
local msg = {
uid = 12345,
param = 9876,
name = "Jin Qing",
names = {"n1", "n2", "n3"},
cmd = 10,
common_msg = {},
}
local s = pb.encode("test.TestMsg", msg)
local msg2 = pb.decode("test.TestMsg", s)
assert(msg2.name == "Jin Qing")
assert(#msg2.names == 3)
local n3 = msg2.names[3]
-- Maybe reordered.
assert(n3 == "n1" or n3 == "n2" or n3 == "n3")
assert(10 == msg2.cmd)
assert(msg2.common_msg)
end -- test_encode_decode()
function M.test_packed()
local msg = { samples = {1,2,3} }
local s = pb.encode("test.TestMsg", msg)
local msg2 = pb.decode("test.TestMsg", s)
assert(#msg2.samples == 3)
end -- test.packed()
function M.test_map()
local msgs = {}
msgs["k1"] = {}
msgs["k2"] = {}
local msg = { msgs = msgs }
local s = pb.encode("test.TestMsg", msg)
local msg2 = pb.decode("test.TestMsg", s)
assert(msg2.msgs["k1"])
assert(msg2.msgs["k2"])
end -- test_map()
function M.test_map_index_convert()
local msg = { msgs = { {}, {}, ["key"] = {} } }
local s = pb.encode("test.TestMsg", msg)
local msg2 = pb.decode("test.TestMsg", s)
-- key 1,2 is converted to "1", "2"
assert(msg2.msgs[1] == nil)
assert(msg2.msgs["1"])
assert(msg2.msgs["2"])
assert(msg2.msgs["key"])
end -- test_map_index_convert()
function M.test_oneof_name()
local msg = { name2 = "Jin Qing" }
local s = pb.encode("test.TestMsg", msg)
local msg2 = pb.decode("test.TestMsg", s)
assert(msg2.name2 == "Jin Qing")
assert(msg2.msg2 == nil)
end -- test.oneof_name()
function M.test_oneof_msg()
local msg = { msg2 = {} }
local s = pb.encode("test.TestMsg", msg)
local msg2 = pb.decode("test.TestMsg", s)
assert(msg2.name == "")
assert(msg2.name2 == nil)
assert(msg2.msg2)
end -- test.oneof_msg()
function M.test_oneof_none()
local s = pb.encode("test.TestMsg", {})
local msg2 = pb.decode("test.TestMsg", s)
assert(msg2.name2 == nil)
assert(msg2.msg2 == nil)
end -- test.oneof_none()
function M.test_oneof_both()
local msg = { name2 = "abc", msg2 = {} }
local s = pb.encode("test.TestMsg", msg)
local msg2 = pb.decode("test.TestMsg", s)
assert(msg2.name2 or msg2.msg2)
assert(msg2.name2 == nil or msg2.msg2 == nil)
end -- test.oneof_both()
function M.test_oneof_default_value()
local msg = { name2 = "" }
local s = pb.encode("test.TestMsg", msg)
local msg2 = pb.decode("test.TestMsg", s)
assert(msg2.name2 == "")
end -- test_oneof_default_value()
function M.test_decode_return_nil()
assert(nil == pb.decode("test.TestMsg", "IllegalData"))
end -- test_decode_return_nil()
function M.test_all()
M.test_rpc()
M.test_encode_decode()
M.test_repeated()
M.test_repeated_ignore()
M.test_default_value()
M.test_type_convertion_s2n()
M.test_type_convertion_n2s()
M.test_type_convertion_n2n()
M.test_type_convertion_s2d()
M.test_string_enum()
M.test_s1234_enum()
M.test_many_fields()
M.test_packed()
M.test_map()
M.test_map_index_convert()
M.test_oneof_name()
M.test_oneof_msg()
M.test_oneof_none()
M.test_oneof_both()
M.test_oneof_default_value()
M.test_decode_return_nil()
print("Test OK!")
end -- test_all
M.test_all()
return M
|
Fix test.
|
Fix test.
E:\Git\Lua\LuaPbIntf\test>lua53pp test.lua
lua53pp: test.lua:10: bad argument #1 to 'add_proto_path' (string expected, got
nil)
stack traceback:
[C]: in function 'luapbintf.add_proto_path'
test.lua:10: in main chunk
[C]: in ?
|
Lua
|
mit
|
jinq0123/LuaPbIntf,jinq0123/LuaPbIntf,jinq0123/LuaPbIntf
|
7c46e06d59fdbd1a09125e081aba5a47c927637b
|
OS/DiskOS/Programs/edit.lua
|
OS/DiskOS/Programs/edit.lua
|
--Text editor--
print("")
local args = {...} --Get the arguments passed to this program
if #args < 1 then color(9) print("Must provide the path to the file") return end
local tar = table.concat(args," ") --The path may include whitespaces
local term = require("C://terminal")
tar = term.parsePath(tar)
if fs.isDirectory(tar) then color(9) print("Can't edit directories !") return end
local eapi = require("C://Editors")
local edit = {}
edit.editorsheet = eapi.editorsheet
edit.flavor = eapi.flavor
edit.flavorBack = eapi.flavorBack
edit.background = eapi.background
local swidth, sheight = screenSize()
local sid --Selected option id
function edit:drawBottomBar()
rect(1,sheight-7,swidth,8,false,self.flavor)
end
local controlID = 11
local controlNum = 3 --The number of the control buttons at the top right corner of the editor.
local controlGrid = {swidth-8*controlNum+1,1, 8*controlNum,8, controlNum,1}
function edit:drawTopBar()
rect(1,1,swidth,8,false,self.flavor)
SpriteGroup(55, 1,1, 4,1, 1,1, false, self.editorsheet) --The LIKO12 Logo
SpriteGroup(controlID, controlGrid[1],controlGrid[2], controlGrid[5],controlGrid[6], 1,1, false, self.editorsheet)
if sid then
SpriteGroup(controlID+24+sid, controlGrid[1]+sid*8,controlGrid[2], 1,1, 1,1, false, self.editorsheet)
end
end
function edit:drawUI()
clear(self.background) --Clear the screen
self:drawTopBar() --Draw the top bar
self:drawBottomBar() --Draw the bottom bar
end
local ok, texteditor = assert(pcall(assert(fs.load("C://Editors/code.lua")),edit))
if tar:sub(-4,-1) ~= ".lua" then texteditor.colorize = false end
local screen = screenshot()
local px,py,pc = printCursor()
cursor("normal")
if fs.exists(tar) then texteditor:import(fs.read(tar)) end
texteditor:entered()
local eflag = false
local hflag = false --hover flag
local controls = {
function() --Reload
texteditor:leaved()
if fs.exists(tar) then texteditor:import(fs.read(tar)) end
texteditor:entered()
end,
function() --Save
local data = texteditor:export()
fs.write(tar,data)
end,
function() --Exit
texteditor:leaved()
return true
end
}
for event, a,b,c,d,e,f in pullEvent do
if event == "keypressed" then
if a == "escape" then
--[[texteditor:leaved()
break]]
eflag = not eflag
if eflag then
cursor("none")
sid = 1
else
cursor("normal")
sid = false
end
edit:drawTopBar()
elseif eflag then
if a == "left" then
sid = sid - 1
if sid < 0 then sid = 2 end
edit:drawTopBar()
elseif a == "right" then
sid = sid + 1
if sid > 2 then sid = 0 end
edit:drawTopBar()
elseif a == "return" then
if controls[sid+1]() then break end
sid, eflag = false, false
edit:drawTopBar()
end
else
local key, sc = a, b
if(isKDown("lalt", "ralt")) then
key = "alt-" .. key
sc = "alt-" .. sc
end
if(isKDown("lctrl", "rctrl", "capslock")) then
key = "ctrl-" .. key
sc = "ctrl-" .. sc
end
if(isKDown("lshift", "rshift")) then
key = "shift-" .. key
sc = "shift-" .. sc
end
if texteditor.keymap and texteditor.keymap[key] then texteditor.keymap[key](texteditor,c)
elseif texteditor.keymap and texteditor.keymap[sc] then texteditor.keymap[sc](texteditor,c) end
if texteditor[event] then texteditor[event](texteditor,a,b,c,d,e,f) end
end
elseif event == "mousepressed" and not eflag then
local cx, cy = whereInGrid(a,b,controlGrid)
if cx then
cursor("handpress")
hflag = "d"
sid = cx-1
edit:drawTopBar()
else
if texteditor[event] then texteditor[event](texteditor,a,b,c,d,e,f) end
end
elseif event == "mousemoved" and not eflag then
local cx, cy = whereInGrid(a,b,controlGrid)
if cx then
if hflag and hflag == "d" then
sid = cx-1
edit:drawTopBar()
elseif not hflag then
cursor("handrelease")
hflag = "h"
end
else
if hflag and hflag == "h" then
hflag = false
cursor("normal")
end
if texteditor[event] then texteditor[event](texteditor,a,b,c,d,e,f) end
end
elseif event == "mousereleased" and not eflag then
local cx, cy = whereInGrid(a,b,controlGrid)
if cx then
if hflag and hflag == "d" then
cursor("handrelease")
if controls[sid+1]() then break end
sid, hflag = false, false
edit:drawTopBar()
elseif not hflag then
hflag = "h"
cursor("handrelease")
end
else
if hflag then
if hflag == "d" then
sid = false
edit:drawTopBar()
end
cursor("normal")
hflag = nil
end
if texteditor[event] then texteditor[event](texteditor,a,b,c,d,e,f) end
end
elseif eflag then
if event == "touchpressed" then textinput(true) end
else
if texteditor[event] then texteditor[event](texteditor,a,b,c,d,e,f) end
end
end
clear(1)
screen:image():draw(1,1)
printCursor(px,py,pc)
|
--Text editor--
print("")
local args = {...} --Get the arguments passed to this program
if #args < 1 then color(9) print("Must provide the path to the file") return end
local tar = table.concat(args," ") --The path may include whitespaces
local term = require("C://terminal")
tar = term.parsePath(tar)
if fs.exists(tar) and fs.isDirectory(tar) then color(9) print("Can't edit directories !") return end
local eapi = require("C://Editors")
local edit = {}
edit.editorsheet = eapi.editorsheet
edit.flavor = eapi.flavor
edit.flavorBack = eapi.flavorBack
edit.background = eapi.background
local swidth, sheight = screenSize()
local sid --Selected option id
function edit:drawBottomBar()
rect(1,sheight-7,swidth,8,false,self.flavor)
end
local controlID = 11
local controlNum = 3 --The number of the control buttons at the top right corner of the editor.
local controlGrid = {swidth-8*controlNum+1,1, 8*controlNum,8, controlNum,1}
function edit:drawTopBar()
rect(1,1,swidth,8,false,self.flavor)
SpriteGroup(55, 1,1, 4,1, 1,1, false, self.editorsheet) --The LIKO12 Logo
SpriteGroup(controlID, controlGrid[1],controlGrid[2], controlGrid[5],controlGrid[6], 1,1, false, self.editorsheet)
if sid then
SpriteGroup(controlID+24+sid, controlGrid[1]+sid*8,controlGrid[2], 1,1, 1,1, false, self.editorsheet)
end
end
function edit:drawUI()
clear(self.background) --Clear the screen
self:drawTopBar() --Draw the top bar
self:drawBottomBar() --Draw the bottom bar
end
local ok, texteditor = assert(pcall(assert(fs.load("C://Editors/code.lua")),edit))
if tar:sub(-4,-1) ~= ".lua" then texteditor.colorize = false end
local screen = screenshot()
local px,py,pc = printCursor()
cursor("normal")
if fs.exists(tar) then texteditor:import(fs.read(tar)) end
texteditor:entered()
local eflag = false
local hflag = false --hover flag
local controls = {
function() --Reload
texteditor:leaved()
if fs.exists(tar) then texteditor:import(fs.read(tar)) end
texteditor:entered()
end,
function() --Save
local data = texteditor:export()
fs.write(tar,data)
end,
function() --Exit
texteditor:leaved()
return true
end
}
for event, a,b,c,d,e,f in pullEvent do
if event == "keypressed" then
if a == "escape" then
--[[texteditor:leaved()
break]]
eflag = not eflag
if eflag then
cursor("none")
sid = 1
else
cursor("normal")
sid = false
end
pushMatrix() cam() edit:drawTopBar() popMatrix()
elseif eflag then
if a == "left" then
sid = sid - 1
if sid < 0 then sid = 2 end
pushMatrix() cam() edit:drawTopBar() popMatrix()
elseif a == "right" then
sid = sid + 1
if sid > 2 then sid = 0 end
pushMatrix() cam() edit:drawTopBar() popMatrix()
elseif a == "return" then
if controls[sid+1]() then break end
sid, eflag = false, false
pushMatrix() cam() edit:drawTopBar() popMatrix()
end
else
local key, sc = a, b
if(isKDown("lalt", "ralt")) then
key = "alt-" .. key
sc = "alt-" .. sc
end
if(isKDown("lctrl", "rctrl", "capslock")) then
key = "ctrl-" .. key
sc = "ctrl-" .. sc
end
if(isKDown("lshift", "rshift")) then
key = "shift-" .. key
sc = "shift-" .. sc
end
if texteditor.keymap and texteditor.keymap[key] then texteditor.keymap[key](texteditor,c)
elseif texteditor.keymap and texteditor.keymap[sc] then texteditor.keymap[sc](texteditor,c) end
if texteditor[event] then texteditor[event](texteditor,a,b,c,d,e,f) end
end
elseif event == "mousepressed" and not eflag then
local cx, cy = whereInGrid(a,b,controlGrid)
if cx then
cursor("handpress")
hflag = "d"
sid = cx-1
pushMatrix() cam() edit:drawTopBar() popMatrix()
else
if texteditor[event] then texteditor[event](texteditor,a,b,c,d,e,f) end
end
elseif event == "mousemoved" and not eflag then
local cx, cy = whereInGrid(a,b,controlGrid)
if cx then
if hflag and hflag == "d" then
sid = cx-1
pushMatrix() cam() edit:drawTopBar() popMatrix()
elseif not hflag then
cursor("handrelease")
hflag = "h"
end
else
if hflag and hflag == "h" then
hflag = false
cursor("normal")
end
if texteditor[event] then texteditor[event](texteditor,a,b,c,d,e,f) end
end
elseif event == "mousereleased" and not eflag then
local cx, cy = whereInGrid(a,b,controlGrid)
if cx then
if hflag and hflag == "d" then
cursor("handrelease")
if controls[sid+1]() then break end
sid, hflag = false, false
pushMatrix() cam() edit:drawTopBar() popMatrix()
elseif not hflag then
hflag = "h"
cursor("handrelease")
end
else
if hflag then
if hflag == "d" then
sid = false
pushMatrix() cam() edit:drawTopBar() popMatrix()
end
cursor("normal")
hflag = nil
end
if texteditor[event] then texteditor[event](texteditor,a,b,c,d,e,f) end
end
elseif eflag then
if event == "touchpressed" then textinput(true) end
else
if texteditor[event] then texteditor[event](texteditor,a,b,c,d,e,f) end
end
end
clear(1)
screen:image():draw(1,1)
printCursor(px,py,pc)
|
Bugfixes
|
Bugfixes
|
Lua
|
mit
|
RamiLego4Game/LIKO-12
|
1afc8830294967905abbd930aca2dff12e52c396
|
applications/luci-app-cpulimit/luasrc/model/cbi/cpulimit.lua
|
applications/luci-app-cpulimit/luasrc/model/cbi/cpulimit.lua
|
m = Map("cpulimit", translate("cpulimit"),translate("Use cpulimit to restrict app's cpu usage."))
s = m:section(TypedSection, "list", translate("Settings"))
s.template = "cbi/tblsection"
s.anonymous = true
s.addremove = true
enable = s:option(Flag, "enabled", translate("enable", "enable"))
enable.optional = false
enable.rmempty = false
-- pick 3rd part;delete 1st line;sort and unique;delete lines started with '[' and '{';delete basic command using extend regexp;pick the last part divided by '/'
-- hope this works and make sure your sed command has '-r' or '-E' option
local pscmd="ps | awk '{print $3}' | sed '1d' | sort | uniq | sed '/^\[/d' | sed '/^{/d' | sed -E '/(sed|awk|hostapd|pppd|mwan3|sleep|sort|uniq|ps)/d' | awk -F'/' '{print $NF}'"
local shellpipe = io.popen(pscmd,"r")
exename = s:option(Value, "exename", translate("Executable Name"), translate("Name of the executable program file. Should NOT Be a Path!"))
exename.optional = false
exename.rmempty = false
exename.default = "vsftpd"
for psvalue in shellpipe:lines() do
exename:value(psvalue)
end
limit = s:option(Value, "limit", translate("Usage restrictions"))
limit.optional = false
limit.rmempty = false
limit.default = "50"
limit:value("100","100%")
limit:value("90","90%")
limit:value("80","80%")
limit:value("70","70%")
limit:value("60","60%")
limit:value("50","50%")
limit:value("40","40%")
limit:value("30","30%")
limit:value("20","20%")
limit:value("10","10%")
return m
|
m = Map("cpulimit", translate("cpulimit"),translate("Use cpulimit to restrict app's cpu usage."))
s = m:section(TypedSection, "list", translate("Settings"))
s.template = "cbi/tblsection"
s.anonymous = true
s.addremove = true
enable = s:option(Flag, "enabled", translate("enable", "enable"))
enable.optional = false
enable.rmempty = false
-- pick 3rd part;delete 1st line;delete lines started with '[' and '{';delete basic command using extend regexp;pick the last part divided by '/';sort the list
-- make sure your sed command has '-r' or '-E' option
local pscmd="ps | awk '{print $3}' | sed '1d' | sed '/^\\[/d' | sed '/^{/d' | sed -E '/(-ash|sh|sed|awk|hostapd|pppd|mwan3|sleep|sort|uniq|ps|insmod|rmmod|odhcp6c)/d' | awk -F'/' '{print $NF}' | sort -u"
local shellpipe = io.popen(pscmd,"r")
exename = s:option(Value, "exename", translate("Executable Name"), translate("Name of the executable program file. Should NOT Be a Path!"))
exename.optional = false
exename.rmempty = false
exename.default = "dnsmasq"
for psvalue in shellpipe:lines() do
exename:value(psvalue)
end
limit = s:option(Value, "limit", translate("Usage restrictions"))
limit.optional = false
limit.rmempty = false
limit.default = "50"
limit:value("100","100%")
limit:value("90","90%")
limit:value("80","80%")
limit:value("70","70%")
limit:value("60","60%")
limit:value("50","50%")
limit:value("40","40%")
limit:value("30","30%")
limit:value("20","20%")
limit:value("10","10%")
return m
|
luci-app-cpulimit: my bad (#8)
|
luci-app-cpulimit: my bad (#8)
fix some issues
|
Lua
|
apache-2.0
|
wongsyrone/luci-1,wongsyrone/luci-1,wongsyrone/luci-1,wongsyrone/luci-1,wongsyrone/luci-1,wongsyrone/luci-1,wongsyrone/luci-1,wongsyrone/luci-1
|
c4e2e923ee037ddbb2422c5d450a0f8202cb3037
|
test_scripts/Polices/build_options/ATF_P_timeout_countdown_start_PROPRIETARY.lua
|
test_scripts/Polices/build_options/ATF_P_timeout_countdown_start_PROPRIETARY.lua
|
-- Requirements summary:
-- [PolicyTableUpdate] "timeout" countdown start
--
-- Description:
-- SDL must forward OnSystemRequest(request_type=PROPRIETARY, url, appID) with encrypted PTS
-- snapshot as a hybrid data to mobile application with <appID> value. "fileType" must be
-- assigned as "JSON" in mobile app notification.
-- 1. Used preconditions
-- SDL is built with "-DEXTENDED_POLICY: PROPRIETARY" flag
-- Application is registered.
-- PTU is requested.
-- SDL->HMI: SDL.OnStatusUpdate(UPDATE_NEEDED)
-- SDL->HMI:SDL.PolicyUpdate(file, timeout, retry[])
-- HMI -> SDL: SDL.GetURLs (<service>)
-- HMI->SDL: BasicCommunication.OnSystemRequest ('url', requestType:PROPRIETARY, appID="default")
-- SDL->app: OnSystemRequest ('url', requestType:PROPRIETARY, fileType="JSON", appID)
-- 2. Performed steps
-- Do not send SystemRequest from <app_ID>
--
-- Expected result:
-- SDL waits for SystemRequest response from <app ID> within 'timeout' value, if no obtained,
-- it starts retry sequence
---------------------------------------------------------------------------------------------
--[[ General configuration parameters ]]
config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0"
--[[ Required Shared libraries ]]
local commonSteps = require('user_modules/shared_testcases/commonSteps')
local commonFunctions = require('user_modules/shared_testcases/commonFunctions')
local commonTestCases = require('user_modules/shared_testcases/commonTestCases')
local testCasesForPolicyTable = require('user_modules/shared_testcases/testCasesForPolicyTable')
local testCasesForPolicyTableSnapshot = require('user_modules/shared_testcases/testCasesForPolicyTableSnapshot')
--[[ Local Functions ]]
local function timestamp()
local f = io.popen("date +%s")
local o = f:read("*all")
f:close()
return (o:gsub("\n", ""))
end
--[[ General Precondition before ATF start ]]
commonSteps:DeleteLogsFileAndPolicyTable()
--ToDo: shall be removed when issue: "ATF does not stop HB timers by closing session and connection" is fixed
config.defaultProtocolVersion = 2
--[[ General Settings for configuration ]]
Test = require('connecttest')
require('cardinalities')
require('user_modules/AppTypes')
--[[ Preconditions ]]
commonFunctions:newTestCasesGroup("Preconditions")
function Test:Precondition_trigger_getting_device_consent()
testCasesForPolicyTable:trigger_getting_device_consent(self, config.application1.registerAppInterfaceParams.appName, config.deviceMAC)
end
--[[ Test ]]
commonFunctions:newTestCasesGroup("Test")
function Test:TestStep_Sending_PTS_to_mobile_application()
local time_update_needed = {}
local time_system_request = {}
local endpoints = {}
local is_test_fail = false
local SystemFilesPath = commonFunctions:read_parameter_from_smart_device_link_ini("SystemFilesPath")
local PathToSnapshot = commonFunctions:read_parameter_from_smart_device_link_ini("PathToSnapshot")
local file_pts = SystemFilesPath.."/"..PathToSnapshot
for i = 1, #testCasesForPolicyTableSnapshot.pts_endpoints do
if (testCasesForPolicyTableSnapshot.pts_endpoints[i].service == "0x07") then
endpoints[#endpoints + 1] = { url = testCasesForPolicyTableSnapshot.pts_endpoints[i].value, appID = nil}
end
if (testCasesForPolicyTableSnapshot.pts_endpoints[i].service == "app1") then
endpoints[#endpoints + 1] = { url = testCasesForPolicyTableSnapshot.pts_endpoints[i].value, appID = testCasesForPolicyTableSnapshot.pts_endpoints[i].appID}
end
end
local RequestId_GetUrls = self.hmiConnection:SendRequest("SDL.GetURLS", { service = 7 })
EXPECT_HMIRESPONSE(RequestId_GetUrls)
:Do(function(_,_)
self.hmiConnection:SendNotification("BasicCommunication.OnSystemRequest",{ requestType = "PROPRIETARY", fileName = "PolicyTableUpdate" })
--first retry sequence
local seconds_between_retries = {}
local timeout_pts = testCasesForPolicyTableSnapshot:get_data_from_PTS("module_config.timeout_after_x_seconds")
for i = 1, #testCasesForPolicyTableSnapshot.pts_seconds_between_retries do
seconds_between_retries[i] = testCasesForPolicyTableSnapshot.pts_seconds_between_retries[i].value
end
local time_wait = (timeout_pts*seconds_between_retries[1]*1000 + 10000)
commonTestCases:DelayedExp(time_wait) -- tolerance 10 sec
local function verify_retry_sequence()
--time_update_needed[#time_update_needed + 1] = testCasesForPolicyTable.time_trigger
time_update_needed[#time_update_needed + 1] = timestamp()
local time_1 = time_update_needed[#time_update_needed]
local time_2 = time_system_request[#time_system_request]
local timeout = (time_1 - time_2)
if( ( timeout > (timeout_pts*1000 + 2000) ) or ( timeout < (timeout_pts*1000 - 2000) )) then
is_test_fail = true
commonFunctions:printError("ERROR: timeout for first retry sequence is not as expected: "..timeout_pts.."msec(5sec tolerance). real: "..timeout.."ms")
else
print("timeout is as expected: "..timeout_pts.."ms. real: "..timeout)
end
end
EXPECT_NOTIFICATION("OnSystemRequest", { requestType = "PROPRIETARY", fileType = "JSON"})
:Do(function(_,_) time_system_request[#time_system_request + 1] = timestamp() end)
EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate", {status = "UPDATE_NEEDED"})
EXPECT_HMICALL("BasicCommunication.PolicyUpdate", { file = file_pts, timeout = timeout_pts, retry = seconds_between_retries})
:Do(function(exp_pu,data)
if(exp_pu.occurences > 1) then
is_test_fail = true
commonFunctions:printError("ERROR: PTU sequence is restarted again!")
end
verify_retry_sequence()
self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", {})
end)
end)
if(is_test_fail == true) then
self:FailTestCase("Test is FAILED. See prints.")
end
end
--[[ Postconditions ]]
commonFunctions:newTestCasesGroup("Postconditions")
function Test:Postcondition_Force_Stop_SDL()
commonFunctions:SDLForceStop(self)
end
return Test
|
-- Requirements summary:
-- [PolicyTableUpdate] "timeout" countdown start
--
-- Description:
-- SDL must forward OnSystemRequest(request_type=PROPRIETARY, url, appID) with encrypted PTS
-- snapshot as a hybrid data to mobile application with <appID> value. "fileType" must be
-- assigned as "JSON" in mobile app notification.
-- 1. Used preconditions
-- SDL is built with "-DEXTENDED_POLICY: PROPRIETARY" flag
-- Application is registered.
-- PTU is requested.
-- SDL->HMI: SDL.OnStatusUpdate(UPDATE_NEEDED)
-- SDL->HMI:SDL.PolicyUpdate(file, timeout, retry[])
-- HMI -> SDL: SDL.GetURLs (<service>)
-- HMI->SDL: BasicCommunication.OnSystemRequest ('url', requestType:PROPRIETARY, appID="default")
-- SDL->app: OnSystemRequest ('url', requestType:PROPRIETARY, fileType="JSON", appID)
-- 2. Performed steps
-- Do not send SystemRequest from <app_ID>
--
-- Expected result:
-- SDL waits for SystemRequest response from <app ID> within 'timeout' value, if no obtained,
-- it starts retry sequence
---------------------------------------------------------------------------------------------
--[[ General configuration parameters ]]
config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0"
--[[ Required Shared libraries ]]
local commonSteps = require('user_modules/shared_testcases/commonSteps')
local commonFunctions = require('user_modules/shared_testcases/commonFunctions')
local testCasesForPolicyTableSnapshot = require('user_modules/shared_testcases/testCasesForPolicyTableSnapshot')
--[[ Local Functions ]]
local function timestamp()
local f = io.popen("date +%s")
local o = f:read("*all")
f:close()
return (o:gsub("\n", ""))
end
--[[ General Precondition before ATF start ]]
commonFunctions:SDLForceStop()
commonSteps:DeleteLogsFileAndPolicyTable()
--ToDo: shall be removed when issue: "ATF does not stop HB timers by closing session and connection" is fixed
config.defaultProtocolVersion = 2
--[[ General Settings for configuration ]]
Test = require('connecttest')
require('cardinalities')
require('user_modules/AppTypes')
--[[ Test ]]
commonFunctions:newTestCasesGroup("Test")
function Test:TestStep_Sending_PTS_to_mobile_application()
local time_system_request = {}
local is_test_fail = false
local RequestId_GetUrls = self.hmiConnection:SendRequest("SDL.GetURLS", { service = 7 })
EXPECT_HMIRESPONSE(RequestId_GetUrls)
:Do(function()
self.hmiConnection:SendNotification("BasicCommunication.OnSystemRequest",{ requestType = "PROPRIETARY", fileName = "PolicyTableUpdate" })
--first retry sequence
local seconds_between_retries = {}
local timeout_pts = testCasesForPolicyTableSnapshot:get_data_from_PTS("module_config.timeout_after_x_seconds")
for i = 1, #testCasesForPolicyTableSnapshot.pts_seconds_between_retries do
seconds_between_retries[i] = testCasesForPolicyTableSnapshot.pts_seconds_between_retries[i].value
end
local time_wait = (timeout_pts*seconds_between_retries[1]*1000 + 10000)
local function verify_retry_sequence()
local time_1 = timestamp() -- time PolicyUpdate
local time_2 = time_system_request[#time_system_request]
local timeout = (time_1 - time_2)
if( ( timeout > (timeout_pts + 2) ) or ( timeout < (timeout_pts - 2) )) then
is_test_fail = true
commonFunctions:printError("ERROR: timeout for first retry sequence is not as expected: "..timeout_pts.." sec (5 sec tolerance). real: "..timeout.." sec")
else
print("timeout is as expected: "..timeout_pts.." sec. real: "..timeout)
end
end
EXPECT_NOTIFICATION("OnSystemRequest", { requestType = "PROPRIETARY", fileType = "JSON"})
:Do(function() time_system_request[#time_system_request + 1] = timestamp() end)
EXPECT_HMICALL("BasicCommunication.PolicyUpdate")
:Do(function(exp,data)
if(exp.occurences > 1) then
is_test_fail = true
commonFunctions:printError("ERROR: PTU sequence is restarted again!")
end
verify_retry_sequence()
self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", {})
end)
:Timeout(time_wait)
end)
if(is_test_fail == true) then
self:FailTestCase("Test is FAILED. See prints.")
end
end
--[[ Postconditions ]]
commonFunctions:newTestCasesGroup("Postconditions")
function Test.Postcondition_Force_Stop_SDL()
StopSDL()
end
return Test
|
Fix issues
|
Fix issues
|
Lua
|
bsd-3-clause
|
smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts
|
73aee7d6dd8d5637ad60733ab41c4908e93cbebd
|
src/dbmt.lua
|
src/dbmt.lua
|
local mod_name = (...):match ( "^(.*)%..-$" )
local misc = require ( mod_name .. ".misc" )
local attachpairs_start = misc.attachpairs_start
local colmt = require ( mod_name .. ".colmt" )
local gridfs = require ( mod_name .. ".gridfs" )
local dbmethods = { }
local dbmt = { __index = dbmethods }
function dbmethods:cmd(q)
local collection = "$cmd"
local col = self:get_col(collection)
local c_id , r , t = col:query(q)
if t.QueryFailure then
return nil, "Query Failure"
elseif not r[1] then
return nil, "No results returned"
elseif r[1].ok == 0 then -- Failure
return nil , r[1].errmsg , r[1] , t
else
return r[1]
end
end
function dbmethods:listcollections ( )
local col = self:get_col("system.namespaces")
return col:find( { } )
end
function dbmethods:dropDatabase ( )
local r, err = self:cmd({ dropDatabase = true })
if not r then
return nil, err
end
return 1
end
local function pass_digest ( username , password )
return ngx.md5(username .. ":mongo:" .. password)
end
function dbmethods:add_user ( username , password )
local digest = pass_digest ( username , password )
return self:update ( "system.users" , { user = username } , { ["$set"] = { pwd = password } } , true )
end
function dbmethods:auth(username, password)
local r, err = self:cmd({ getnonce = true })
if not r then
return nil, err
end
local digest = ngx.md5( r.nonce .. username .. pass_digest ( username , password ) )
r, err = self:cmd(attachpairs_start({
authenticate = true ;
user = username ;
nonce = r.nonce ;
key = digest ;
} , "authenticate" ) )
if not r then
return nil, err
end
return 1
end
function dbmethods:get_col(collection)
if not collection then
return nil, "collection needed"
end
return setmetatable ( {
conn = self.conn;
db_obj = self;
db = self.db ;
col = collection;
} , colmt )
end
function dbmethods:get_gridfs(fs, files_col, chunks_col)
if not fs then
return nil, "fs name needed"
end
files_col = files_col or "files"
chunks_col = chunks_col or "chunks"
return setmetatable({
conn = self.conn;
db_obj = self;
db = self.db;
file_col = self:get_col(fs.."."..files_col);
chunk_col = self:get_col(fs.."."..chunks_col);
} , gridfs)
end
return dbmt
|
local mod_name = (...):match ( "^(.*)%..-$" )
local misc = require ( mod_name .. ".misc" )
local attachpairs_start = misc.attachpairs_start
local colmt = require ( mod_name .. ".colmt" )
local gridfs = require ( mod_name .. ".gridfs" )
local dbmethods = { }
local dbmt = { __index = dbmethods }
function dbmethods:cmd(q)
local collection = "$cmd"
local col = self:get_col(collection)
local c_id , r , t = col:query(q)
if t.QueryFailure then
return nil, "Query Failure"
elseif not r[1] then
return nil, "No results returned"
elseif r[1].ok == 0 then -- Failure
return nil , r[1].errmsg , r[1] , t
else
return r[1]
end
end
function dbmethods:listcollections ( )
local col = self:get_col("system.namespaces")
return col:find( { } )
end
function dbmethods:dropDatabase ( )
local r, err = self:cmd({ dropDatabase = true })
if not r then
return nil, err
end
return 1
end
local function pass_digest ( username , password )
return ngx.md5(username .. ":mongo:" .. password)
end
function dbmethods:add_user ( username , password )
local digest = pass_digest ( username , password )
return self:update ( "system.users" , { user = username } , { ["$set"] = { pwd = password } } , true )
end
function dbmethods:auth(username, password)
local r, err = self:cmd({ getnonce = true })
if not r then
return nil, err
end
local digest = ngx.md5( r.nonce .. username .. pass_digest ( username , password ) )
local oldpairs = pairs
pairs = function(t)
local mt = getmetatable(t)
if mt and mt.__pairs then
return mt.__pairs(t)
else
return oldpairs(t)
end
end
r, err = self:cmd(attachpairs_start({
authenticate = 1 ;
user = username ;
nonce = r.nonce ;
key = digest ;
} , "authenticate" ) )
pairs = oldpairs
if not r then
error(err)
return nil, err
end
return 1
end
function dbmethods:get_col(collection)
if not collection then
return nil, "collection needed"
end
return setmetatable ( {
conn = self.conn;
db_obj = self;
db = self.db ;
col = collection;
} , colmt )
end
function dbmethods:get_gridfs(fs, files_col, chunks_col)
if not fs then
return nil, "fs name needed"
end
files_col = files_col or "files"
chunks_col = chunks_col or "chunks"
return setmetatable({
conn = self.conn;
db_obj = self;
db = self.db;
file_col = self:get_col(fs.."."..files_col);
chunk_col = self:get_col(fs.."."..chunks_col);
} , gridfs)
end
return dbmt
|
fixed auth
|
fixed auth
|
Lua
|
mit
|
Olivine-Labs/resty-mongol
|
6f3ae374c0acf32ae4b257ce5c6f8d306a3e1039
|
src/main.lua
|
src/main.lua
|
-- This comment enforces unit-test coverage for this file:
-- coverage: 0
http = require 'summit.http'
menu = require 'summit.menu'
speech = require 'summit.speech'
json = require 'json'
inspect = require "inspect"
function get_abstract(arg)
channel.say(arg.abstract)
get_link_menu(arg.url)
end
function invalid()
channel.say("Not a valid selection")
end
function select_category(cat)
selected_category = cat
end
function send_article(selection)
local url = selection
sms = require "summit.sms"
to = "+16306244913"
-- to = "+1" .. channel.data.ani
from = "+1" .. channel.data.dnis
message = "You have saved " .. url .. " for later."
ok, err = sms.send(to, from, message)
get_main_menu()
end
function hangup()
channel.say("Goodbye, bitches!")
channel.hangup()
end
function get_user_info()
-- phone_number = channel.data.ani
phone_number = '6039690489'
user_url = "https://getnewspeak.herokuapp.com/api/v1/users/" .. phone_number
res, err = http.get(user_url)
if err then
get_main_menu()
end
user_info = json:decode(res.content)
channel.say("Welcome to Newspeak, " .. user_info.name)
end
-- Main menu
function get_main_menu()
selected_category = ""
category_names = { 'u.s.', 'world', 'sports', 'business', 'technology', 'science', 'health' }
cat_counter = 1
main_menu = menu()
main_menu.intro("Select a news topic.")
for index, category in ipairs(category_names) do
main_menu.add(tostring(index), "For " .. category .. ", press " .. tostring(index), function() select_category(category) end)
end
main_menu.run()
channel.say("Selected Category: " .. selected_category)
get_category_menu()
end
-- API Call
function get_category_menu()
url = "http://getnewspeak.herokuapp.com/headlines?categories=" .. selected_category
res, err = http.get(url)
if err then
channel.say('Unable to contact news service, goodbye.')
channel.hangup()
end
news_content = json:decode(res.content)
-- Category Menu
category_menu = menu()
category_menu.add(tostring(1), "Press " .. tostring(1) .. " for " .. news_content[1].title, function() get_abstract(news_content[1]) end)
category_menu.add(tostring(2), "Press " .. tostring(2) .. " for " .. news_content[2].title, function() get_abstract(news_content[2]) end)
category_menu.add(tostring(3), "Press " .. tostring(3) .. " for " .. news_content[3].title, function() get_abstract(news_content[3]) end)
category_menu.add(tostring(4), "Press " .. tostring(4) .. " for " .. news_content[4].title, function() get_abstract(news_content[4]) end)
category_menu.add(tostring(5), "Press " .. tostring(5) .. " for " .. news_content[5].title, function() get_abstract(news_content[5]) end)
category_menu.default(invalid)
category_menu.intro("Make your selection, please")
category_menu.run()
get_link_menu()
end
-- Link Menu
function get_link_menu(selection)
link_menu = menu()
link_menu.add(tostring(1), "To receive a link to the full article, press 1", function() send_article(selection) end)
link_menu.add(tostring(2), "To continue browsing, press 2", get_main_menu)
link_menu.add(tostring(3), "To close Newspeak, press 3", hangup)
link_menu.default(invalid)
link_menu.intro("Make your selection, please")
link_menu.run()
end
-- Welcome
channel.answer()
get_user_info()
get_main_menu()
|
-- This comment enforces unit-test coverage for this file:
-- coverage: 0
http = require 'summit.http'
menu = require 'summit.menu'
speech = require 'summit.speech'
json = require 'json'
inspect = require "inspect"
category_names = { 'u.s.', 'world', 'sports', 'business', 'technology', 'science', 'health' }
function get_abstract(arg)
channel.say(arg.abstract)
get_link_menu(arg.url)
end
function invalid()
channel.say("Not a valid selection")
end
function send_article(selection)
local url = selection
sms = require "summit.sms"
to = "+1" .. channel.data.ani
from = "+1" .. channel.data.dnis
message = "You have saved " .. url .. " for later."
ok, err = sms.send(to, from, message)
get_main_menu()
end
function select_category(cat)
selected_category = cat
end
function hangup()
channel.say("Goodbye, bitches!")
channel.hangup()
end
function get_user_info()
-- phone_number = '6039690489'
phone_number = channel.data.ani
user_url = "https://getnewspeak.herokuapp.com/api/v1/users/" .. phone_number
res, err = http.get(user_url)
if err or res.data == '' then
get_main_menu()
end
user_info = json:decode(res.content)
if user_info.categories[1] then
category_names = {}
for index, category in ipairs(user_info.categories) do
category_names[index] = category.abbreviation
end
end
channel.say("Welcome to Newspeak, " .. user_info.name)
end
-- Main menu
function get_main_menu()
selected_category = ""
cat_counter = 1
main_menu = menu()
main_menu.intro("Select a news topic.")
for index, category in ipairs(category_names) do
main_menu.add(tostring(index), "For " .. category .. ", press " .. tostring(index), function() select_category(category) end)
end
main_menu.run()
channel.say("Selected Category: " .. selected_category)
get_category_menu()
end
-- API Call
function get_category_menu()
url = "http://getnewspeak.herokuapp.com/headlines?categories=" .. selected_category
res, err = http.get(url)
if err then
channel.say('Unable to contact news service, goodbye.')
channel.hangup()
end
news_content = json:decode(res.content)
-- Category Menu
category_menu = menu()
category_menu.add(tostring(1), "Press " .. tostring(1) .. " for " .. news_content[1].title, function() get_abstract(news_content[1]) end)
category_menu.add(tostring(2), "Press " .. tostring(2) .. " for " .. news_content[2].title, function() get_abstract(news_content[2]) end)
category_menu.add(tostring(3), "Press " .. tostring(3) .. " for " .. news_content[3].title, function() get_abstract(news_content[3]) end)
category_menu.add(tostring(4), "Press " .. tostring(4) .. " for " .. news_content[4].title, function() get_abstract(news_content[4]) end)
category_menu.add(tostring(5), "Press " .. tostring(5) .. " for " .. news_content[5].title, function() get_abstract(news_content[5]) end)
category_menu.default(invalid)
category_menu.intro("Make your selection, please")
category_menu.run()
get_link_menu()
end
-- Link Menu
function get_link_menu(selection)
link_menu = menu()
link_menu.add(tostring(1), "To receive a link to the full article, press 1", function() send_article(selection) end)
link_menu.add(tostring(2), "To continue browsing, press 2", get_main_menu)
link_menu.add(tostring(3), "To close Newspeak, press 3", hangup)
link_menu.default(invalid)
link_menu.intro("Make your selection, please")
link_menu.run()
end
-- Welcome
channel.answer()
get_user_info()
get_main_menu()
|
Fix user categories
|
Fix user categories
|
Lua
|
mit
|
rfleury2/newspeak-phone-corvisa
|
b66d91ad466ab64b37d5300dae05eadc67dd41f8
|
sslobby/gamemode/minigames/base/init.lua
|
sslobby/gamemode/minigames/base/init.lua
|
MINIGAME.Time = 60
---------------------------------------------------------
--
---------------------------------------------------------
function MINIGAME:Initialize()
self.players = {}
self.spawnPoints = {}
local spawnPoints = ents.FindByClass("info_player_spawn")
for k, entity in pairs(spawnPoints) do
if (entity.minigames) then
if (entity.team) then
for k2, unique in pairs(entity.minigames) do
if (unique == self.Unique) then
self.spawnPoints.team = self.spawnPoints.team or {}
local teamID
if (entity.team == "blue") then
teamID = TEAM_BLUE
elseif (entity.team == "red") then
teamID = TEAM_RED
elseif (entity.team == "green") then
teamID = TEAM_GREEN
elseif (entity.team == "orange") then
teamID = TEAM_ORANGE
end
self.spawnPoints.team[teamID] = self.spawnPoints.team[teamID] or {}
table.insert(self.spawnPoints.team[teamID], entity)
end
end
else
for k2, unique in pairs(entity.minigames) do
if (unique == self.Unique) then
table.insert(self.spawnPoints, entity)
end
end
end
end
end
end
---------------------------------------------------------
--
---------------------------------------------------------
function MINIGAME:Start()
for k, player in pairs(self.players) do
player:ChatPrint(self.Name .. " - " .. self.Description)
end
end
---------------------------------------------------------
--
---------------------------------------------------------
function MINIGAME:Finish(timeLimit)
local players = self:GetPlayers()
self.players = {}
for k, player in pairs(player.GetAll()) do
player:SetNetworkedBool("ss.playingminigame", false)
player.minigame = nil
end
for k, player in pairs(players) do
self:RespawnPlayer(player)
end
if (!timeLimit) then
SS.Lobby.Minigame:FinishGame()
end
end
---------------------------------------------------------
--
---------------------------------------------------------
function MINIGAME:RemovePlayer(player, noRespawn)
for k, v in pairs(self.players) do
if (v == player) then
self.players[k] = nil
v:SetNetworkedBool("ss.playingminigame", false)
v.minigame = nil
if (!noRespawn) then
self:RespawnPlayer(player)
end
end
end
end
---------------------------------------------------------
--
---------------------------------------------------------
function MINIGAME:RespawnPlayer(player)
local spawnPoint = hook.Run("PlayerSelectSpawn", player)
player:SetNetworkedBool("ss.playingminigame", false)
player.minigame = nil
player:Spawn()
player:SetPos(spawnPoint:GetPos())
player:SetEyeAngles(spawnPoint:GetAngles())
if (player:IsBot()) then
player:Freeze(true)
end
end
---------------------------------------------------------
--
---------------------------------------------------------
function MINIGAME:Think()
end
---------------------------------------------------------
--
---------------------------------------------------------
function MINIGAME:KeyPress(player, key)
end
---------------------------------------------------------
--
---------------------------------------------------------
function MINIGAME:DoPlayerDeath(victim, inflictor, dmginfo)
end
---------------------------------------------------------
--
---------------------------------------------------------
function MINIGAME:CanPlayerSlap(player, target, nextSlap)
end
---------------------------------------------------------
--
---------------------------------------------------------
function MINIGAME:PlayerSlap(player, target, nextSlap)
return nextSlap
end
---------------------------------------------------------
--
---------------------------------------------------------
function MINIGAME:CanPlayerSuicide(player)
return true
end
---------------------------------------------------------
--
---------------------------------------------------------
function MINIGAME:PlayerLoadout(player)
end
---------------------------------------------------------
--
---------------------------------------------------------
function MINIGAME:HasRequirements(players, teams)
return true
end
---------------------------------------------------------
--
---------------------------------------------------------
function MINIGAME:GetPlayers()
return self.players
end
---------------------------------------------------------
--
---------------------------------------------------------
function MINIGAME:HasPlayer(player)
local players = self:GetPlayers()
for k, v in pairs(players) do
if (v == player) then
return true
end
end
end
---------------------------------------------------------
--
---------------------------------------------------------
function MINIGAME:GetSpawnPoints(player)
if (self.spawnPoints.team) then
local teamID = player:Team()
return self.spawnPoints.team[teamID]
else
return self.spawnPoints
end
end
---------------------------------------------------------
--
---------------------------------------------------------
function MINIGAME:AnnounceWin(player)
if (IsValid(player)) then
local teamID = player:Team()
if (teamID > TEAM_READY) then
local nick = player:Nick()
local teamName = team.GetName(teamID)
SS.Lobby.Minigame:AddScore(teamID, 1)
util.PrintAll("[MINIGAME] " .. nick .. " has won the game for the " .. teamName .. " team!")
end
else
local teams = {}
for k, player in pairs(self.players) do
if (IsValid(player)) then
local id = player:Team()
local exists = false
for i = 1, #teams do
if (teams[i].id == id) then
exists = true
break
end
end
if (!exists) then
table.insert(teams, {id = id, players = {}})
end
for i = 1, #teams do
if (teams[i].id == id) then
table.insert(teams[i].players, player)
end
end
end
end
if (#teams == 1) then
local players = teams[1].players
local teamName = team.GetName(teams[1].id)
if (#players > 1) then
util.PrintAll("[MINIGAME] The " .. teamName .. " team has won the game!")
else
local nick = players[1]:Nick()
util.PrintAll("[MINIGAME] " .. nick .. " has won the game for the " .. teamName .. " team!")
end
SS.Lobby.Minigame:AddScore(teams[1].id, 1)
return true
end
return false
end
end
|
MINIGAME.Time = 60
---------------------------------------------------------
--
---------------------------------------------------------
function MINIGAME:Initialize()
self.players = {}
self.spawnPoints = {}
local spawnPoints = ents.FindByClass("info_player_spawn")
for k, entity in pairs(spawnPoints) do
if (entity.minigames) then
if (entity.team) then
for k2, unique in pairs(entity.minigames) do
if (unique == self.Unique) then
self.spawnPoints.team = self.spawnPoints.team or {}
local teamID
if (entity.team == "blue") then
teamID = TEAM_BLUE
elseif (entity.team == "red") then
teamID = TEAM_RED
elseif (entity.team == "green") then
teamID = TEAM_GREEN
elseif (entity.team == "orange") then
teamID = TEAM_ORANGE
end
self.spawnPoints.team[teamID] = self.spawnPoints.team[teamID] or {}
table.insert(self.spawnPoints.team[teamID], entity)
end
end
else
for k2, unique in pairs(entity.minigames) do
if (unique == self.Unique) then
table.insert(self.spawnPoints, entity)
end
end
end
end
end
end
---------------------------------------------------------
--
---------------------------------------------------------
function MINIGAME:Start()
local String = self.Name.." - "..self.Description
for k, player in pairs(self.players) do
player:ChatPrint(String)
end
end
---------------------------------------------------------
--
---------------------------------------------------------
function MINIGAME:Finish(timeLimit)
local players = self:GetPlayers()
self.players = {}
for k, player in pairs(player.GetAll()) do
player:SetNetworkedBool("ss.playingminigame", false)
player.minigame = nil
end
for k, player in pairs(players) do
self:RespawnPlayer(player)
end
if (!timeLimit) then
SS.Lobby.Minigame:FinishGame()
end
end
---------------------------------------------------------
--
---------------------------------------------------------
function MINIGAME:RemovePlayer(player, noRespawn)
for k, v in pairs(self.players) do
if (v == player) then
self.players[k] = nil
v:SetNetworkedBool("ss.playingminigame", false)
v.minigame = nil
if (!noRespawn) then
self:RespawnPlayer(player)
end
end
end
end
---------------------------------------------------------
--
---------------------------------------------------------
function MINIGAME:RespawnPlayer(player)
local spawnPoint = hook.Run("PlayerSelectSpawn", player)
player:SetNetworkedBool("ss.playingminigame", false)
player.minigame = nil
player:Spawn()
player:SetPos(spawnPoint:GetPos())
player:SetEyeAngles(spawnPoint:GetAngles())
if (player:IsBot()) then
player:Freeze(true)
end
end
---------------------------------------------------------
--
---------------------------------------------------------
function MINIGAME:Think()
end
---------------------------------------------------------
--
---------------------------------------------------------
function MINIGAME:KeyPress(player, key)
end
---------------------------------------------------------
--
---------------------------------------------------------
function MINIGAME:DoPlayerDeath(victim, inflictor, dmginfo)
end
---------------------------------------------------------
--
---------------------------------------------------------
function MINIGAME:CanPlayerSlap(player, target, nextSlap)
end
---------------------------------------------------------
--
---------------------------------------------------------
function MINIGAME:PlayerSlap(player, target, nextSlap)
return nextSlap
end
---------------------------------------------------------
--
---------------------------------------------------------
function MINIGAME:CanPlayerSuicide(player)
return true
end
---------------------------------------------------------
--
---------------------------------------------------------
function MINIGAME:PlayerLoadout(player)
end
---------------------------------------------------------
--
---------------------------------------------------------
function MINIGAME:HasRequirements(players, teams)
return true
end
---------------------------------------------------------
--
---------------------------------------------------------
function MINIGAME:GetPlayers()
return self.players
end
---------------------------------------------------------
--
---------------------------------------------------------
function MINIGAME:HasPlayer(player)
local players = self:GetPlayers()
for k, v in pairs(players) do
if (v == player) then
return true
end
end
end
---------------------------------------------------------
--
---------------------------------------------------------
function MINIGAME:GetSpawnPoints(player)
if (self.spawnPoints.team) then
local teamID = player:Team()
return self.spawnPoints.team[teamID]
else
return self.spawnPoints
end
end
---------------------------------------------------------
--
---------------------------------------------------------
function MINIGAME:AnnounceWin(player)
if (IsValid(player)) then
local teamID = player:Team()
if (teamID > TEAM_READY) then
local nick = player:Nick()
local teamName = team.GetName(teamID)
SS.Lobby.Minigame:AddScore(teamID, 1)
util.PrintAll("[MINIGAME] " .. nick .. " has won the game for the " .. teamName .. " team!")
end
else
local teams = {}
for k, player in pairs(self.players) do
if (IsValid(player)) then
local id = player:Team()
local exists = false
for i = 1, #teams do
if (teams[i].id == id) then
exists = true
break
end
end
if (!exists) then
table.insert(teams, {id = id, players = {}})
end
for i = 1, #teams do
if (teams[i].id == id) then
table.insert(teams[i].players, player)
end
end
end
end
if (#teams == 1) then
local players = teams[1].players
local teamName = team.GetName(teams[1].id)
if (#players > 1) then
util.PrintAll("[MINIGAME] The " .. teamName .. " team has won the game!")
else
local nick = players[1]:Nick()
util.PrintAll("[MINIGAME] " .. nick .. " has won the game for the " .. teamName .. " team!")
end
SS.Lobby.Minigame:AddScore(teams[1].id, 1)
return true
end
return false
end
end
|
This is a shot in the dark fix, lets hope it works.
|
This is a shot in the dark fix, lets hope it works.
|
Lua
|
bsd-3-clause
|
T3hArco/skeyler-gamemodes
|
00e274760fa8f7f738bf3b05d0525cf2c2a1f3c7
|
spec/daemon_spec.lua
|
spec/daemon_spec.lua
|
require'busted'
package.path = package.path..'../'
local ev = require'ev'
local jetdaemon = require'jet.daemon'
local loop = ev.Loop.default
local port = os.getenv('JET_PORT') or 33326
describe(
'A daemon',
function()
local daemon
before(
function()
daemon = jetdaemon.new
{
port = port
}
end)
it(
'provides the correct interface',
function()
assert.is_true(type(daemon) == 'table')
assert.is_true(type(daemon.start) == 'function')
assert.is_true(type(daemon.stop) == 'function')
end)
it(
'can be started',
function()
assert.has_not_error(
function()
daemon:start()
end)
end)
it(
'can be stopped',
function()
assert.has_not_error(
function()
daemon:stop()
end)
end)
describe(
'once started',
function()
before(
function()
daemon:start()
end)
after(
function()
daemon:stop()
end)
it(
'listens on specified port',
async,
function(done)
local sock = socket.connect('127.0.0.1',port)
assert.is_truthy(sock)
sock:settimeout(0)
ev.IO.new(
continue(
function(loop,io)
io:stop(loop)
assert.is_true(true)
done()
end),sock:getfd(),ev.WRITE):start(loop)
end)
end)
end)
return function()
loop:loop()
end
|
require'busted'
package.path = package.path..'../'
local ev = require'ev'
local jetdaemon = require'jet.daemon'
local loop = ev.Loop.default
local port = os.getenv('JET_PORT') or 33326
describe(
'A daemon',
function()
local daemon
before(
function()
daemon = jetdaemon.new
{
port = port
}
end)
it(
'provides the correct interface',
function()
assert.is_true(type(daemon) == 'table')
assert.is_true(type(daemon.start) == 'function')
assert.is_true(type(daemon.stop) == 'function')
end)
it(
'can be started',
function()
assert.has_not_error(
function()
daemon:start()
end)
end)
it(
'can be stopped',
function()
assert.has_not_error(
function()
daemon:stop()
end)
end)
describe(
'once started',
function()
before(
function()
daemon:start()
end)
after(
function()
daemon:stop()
end)
it(
'listens on specified port',
async,
function(done)
local sock = socket.tcp()
sock:settimeout(0)
assert.is_truthy(sock)
ev.IO.new(
continue(
function(loop,io)
io:stop(loop)
assert.is_true(true)
sock:shutdown()
sock:close()
done()
end),sock:getfd(),ev.WRITE):start(loop)
sock:connect('127.0.0.1',port)
end)
end)
end)
return function()
loop:loop()
end
|
fix async connect test
|
fix async connect test
|
Lua
|
mit
|
lipp/lua-jet
|
5218d1212f5ffc10f6345046a576d694bba4d4bd
|
Sandboxer/sandboxer.post.lua
|
Sandboxer/sandboxer.post.lua
|
assert(config.profile~="dbus" and
config.profile~="pulse" and
config.profile~="profile" and
config.profile~="loader" and
config.profile~="config" and
config.profile~="defaults" and
config.profile~="tunables" and
config.profile~="control",
"cannot use service table name as profile: "..config.profile)
assert(type(defaults.basedir)=="string" and defaults.basedir~="", "defaults.basedir param incorrect")
-- load profile
profile=loadstring("return " .. config.profile)()
-- sandbox table verification
assert(type(sandbox)=="table", "sandbox param incorrect")
-- features table
assert(type(sandbox.features)=="nil" or type(sandbox.features)=="table", "sandbox.features param incorrect")
if type(sandbox.features)=="nil" then sandbox.features={} end
if type(sandbox.features)=="table" then
for index,field in ipairs(sandbox.features) do
assert(type(field)=="string", "sandbox.features[".. index .."] value is incorrect (must be a string)")
assert(string.match(field,'^[0-9a-z_]*$')==field, "sandbox.features[".. index .."] value contain invalid characters")
end
end
-- setup table
assert(type(sandbox.setup)=="table", "sandbox.setup param incorrect")
assert(type(sandbox.setup.static_executor)=="nil" or type(sandbox.setup.static_executor)=="boolean", "sandbox.setup.static_executor param incorrect")
if type(sandbox.setup.static_executor)=="nil" then sandbox.setup.static_executor=false end
assert(type(sandbox.setup.security_key)=="nil" or type(sandbox.setup.security_key)=="number", "sandbox.setup.security_key param incorrect")
if type(sandbox.setup.security_key)=="nil" then sandbox.setup.security_key=42 end
assert(type(sandbox.setup.chroot)=="nil" or type(sandbox.setup.chroot)=="table", "sandbox.setup.chroot param incorrect")
function loader.check_one_level_string_list(target, name)
assert(type(target)=="nil" or type(target)=="table", name.." table is incorrect")
if type(target)=="table" then
for index,field in ipairs(target) do
assert(type(field)=="string", name.."[".. index .."] value is incorrect")
end
end
end
function loader.check_two_level_string_list(target, name)
assert(type(target)=="nil" or type(target)=="table", name.." table is incorrect")
if type(target)=="table" then
for index,field in ipairs(target) do
assert(type(field)=="table", name.."[" .. index .. "] subtable is incorrect")
for mi,mf in ipairs(field) do
assert(type(mf)=="string", name.."["..index.."]["..mi.."] value is incorrect")
end
end
end
end
function loader.check_two_level_env_set_list(target, name)
assert(type(target)=="nil" or type(target)=="table", name.." table is incorrect")
if type(target)=="table" then
for index,field in ipairs(target) do
assert(type(field)=="table", name.."["..index.."] subtable is incorrect")
for mi,mf in ipairs(field) do
assert(type(mf)=="table", name.."["..index.."]["..mi.."] value is incorrect (it should be a table)")
local env_idx=0
for vi,vf in ipairs(mf) do
assert(vi<3, name.."["..index.."]["..mi.."] has incorrect strings count")
assert(type(vf)=="string", name.."["..index.."]["..mi.."]["..vi.."] value is incorrect")
env_idx=env_idx+1
end
assert(env_idx==2 or env_idx==0, name.."["..index.."]["..mi.."] has incorrect strings count")
end
end
end
end
function loader.check_one_level_env_set_list(target, name)
assert(type(target)=="nil" or type(target)=="table", name.." table is incorrect")
if type(target)=="table" then
for index,field in ipairs(target) do
assert(type(field)=="table", name.."["..index.."] subtable is incorrect")
local env_idx=0
for mi,mf in ipairs(field) do
assert(mi<3, name.."["..index.."] has incorrect strings count")
assert(type(mf)=="string", name.."["..index.."]["..mi.."] value is incorrect")
env_idx=env_idx+1
end
assert(env_idx==2 or env_idx==0, name.."["..index.."] has incorrect strings count")
end
end
end
-- custom command table
loader.check_two_level_string_list(sandbox.setup.commands,"sandbox.setup.commands")
-- env tables
loader.check_two_level_string_list(sandbox.setup.env_blacklist,"sandbox.setup.env_blacklist")
loader.check_two_level_string_list(sandbox.setup.env_whitelist,"sandbox.setup.env_whitelist")
loader.check_two_level_env_set_list(sandbox.setup.env_set,"sandbox.setup.env_set")
-- bwrap table
assert(type(sandbox.bwrap)=="table", "sandbox.bwrap param incorrect")
for index,field in ipairs(sandbox.bwrap) do
assert(type(field)=="table", "sandbox.bwrap[" .. index .. "] value is incorrect")
for mi,mf in ipairs(field) do
if mi==1 then
assert(type(mf)=="string", "sandbox.bwrap["..index.."]["..mi.."] value is incorrect")
else
assert(type(mf)~="table" and type(mf)~="function" and type(mf)~="nil", "sandbox.bwrap["..index.."]["..mi.."] value is incorrect")
end
end
end
-- check profile
function loader.check_profile(profile, name)
assert(type(profile)=="table", name.." profile is incorrect")
assert(type(profile.exec)=="string", name..".exec value is incorrect or missing")
assert(type(profile.path)=="string" or type(profile.path)=="nil", name..".path value is incorrect or missing")
loader.check_one_level_string_list(profile.args, name..".args")
loader.check_one_level_string_list(profile.env_unset, name..".env_unset")
loader.check_one_level_env_set_list(profile.env_set, name..".env_set")
assert(type(profile.term_signal)=="number" or type(profile.term_signal)=="nil", name..".term_signal value is incorrect or missing")
assert(type(profile.attach)=="boolean" or type(profile.attach)=="nil", name..".attach value is incorrect or missing")
if type(profile.attach)=="nil" then profile.attach=false end
assert(type(profile.pty)=="boolean" or type(profile.pty)=="nil", name..".pty value is incorrect or missing")
if type(profile.pty)=="nil" then profile.pty=false end
assert(type(profile.exclusive)=="boolean" or type(profile.exclusive)=="nil", name..".exclusive value is incorrect or missing")
if type(profile.exclusive)=="nil" then profile.exclusive=false end
-- start command opcode
if profile.attach==true and profile.pty==false then
profile.start_opcode=100
elseif profile.attach==false and profile.pty==false then
profile.start_opcode=101
elseif profile.attach==true and profile.pty==true then
profile.start_opcode=200
elseif profile.attach==false and profile.pty==true then
profile.start_opcode=201
end
end
loader.check_profile(profile,config.profile)
loader.check_profile(dbus,"dbus")
loader.check_profile(pulse,"pulse")
|
assert(config.profile~="dbus" and
config.profile~="pulse" and
config.profile~="profile" and
config.profile~="loader" and
config.profile~="config" and
config.profile~="defaults" and
config.profile~="control",
"cannot use service table name as profile: "..config.profile)
assert(type(defaults.basedir)=="string" and defaults.basedir~="", "defaults.basedir param incorrect")
-- load profile
profile=loadstring("return " .. config.profile)()
-- sandbox table verification
assert(type(sandbox)=="table", "sandbox param incorrect")
-- features table
assert(type(sandbox.features)=="nil" or type(sandbox.features)=="table", "sandbox.features param incorrect")
if type(sandbox.features)=="nil" then sandbox.features={} end
if type(sandbox.features)=="table" then
for index,field in ipairs(sandbox.features) do
assert(type(field)=="string", "sandbox.features[".. index .."] value is incorrect (must be a string)")
assert(string.match(field,'^[0-9a-z_]*$')==field, "sandbox.features[".. index .."] value contain invalid characters")
end
end
-- setup table
assert(type(sandbox.setup)=="table", "sandbox.setup param incorrect")
assert(type(sandbox.setup.static_executor)=="nil" or type(sandbox.setup.static_executor)=="boolean", "sandbox.setup.static_executor param incorrect")
if type(sandbox.setup.static_executor)=="nil" then sandbox.setup.static_executor=false end
assert(type(sandbox.setup.security_key)=="nil" or type(sandbox.setup.security_key)=="number", "sandbox.setup.security_key param incorrect")
if type(sandbox.setup.security_key)=="nil" then sandbox.setup.security_key=42 end
assert(type(sandbox.setup.chroot)=="nil" or type(sandbox.setup.chroot)=="table", "sandbox.setup.chroot param incorrect")
function loader.check_one_level_string_list(target, name)
assert(type(target)=="nil" or type(target)=="table", name.." table is incorrect")
if type(target)=="table" then
for index,field in ipairs(target) do
assert(type(field)=="string", name.."[".. index .."] value is incorrect")
end
end
end
function loader.check_two_level_string_list(target, name)
assert(type(target)=="nil" or type(target)=="table", name.." table is incorrect")
if type(target)=="table" then
for index,field in ipairs(target) do
assert(type(field)=="table", name.."[" .. index .. "] subtable is incorrect")
for mi,mf in ipairs(field) do
assert(type(mf)=="string", name.."["..index.."]["..mi.."] value is incorrect")
end
end
end
end
function loader.check_two_level_env_set_list(target, name)
assert(type(target)=="nil" or type(target)=="table", name.." table is incorrect")
if type(target)=="table" then
for index,field in ipairs(target) do
assert(type(field)=="table", name.."["..index.."] subtable is incorrect")
for mi,mf in ipairs(field) do
assert(type(mf)=="table", name.."["..index.."]["..mi.."] value is incorrect (it should be a table)")
local env_idx=0
for vi,vf in ipairs(mf) do
assert(vi<3, name.."["..index.."]["..mi.."] has incorrect strings count")
assert(type(vf)=="string", name.."["..index.."]["..mi.."]["..vi.."] value is incorrect")
env_idx=env_idx+1
end
assert(env_idx==2 or env_idx==0, name.."["..index.."]["..mi.."] has incorrect strings count")
end
end
end
end
function loader.check_one_level_env_set_list(target, name)
assert(type(target)=="nil" or type(target)=="table", name.." table is incorrect")
if type(target)=="table" then
for index,field in ipairs(target) do
assert(type(field)=="table", name.."["..index.."] subtable is incorrect")
local env_idx=0
for mi,mf in ipairs(field) do
assert(mi<3, name.."["..index.."] has incorrect strings count")
assert(type(mf)=="string", name.."["..index.."]["..mi.."] value is incorrect")
env_idx=env_idx+1
end
assert(env_idx==2 or env_idx==0, name.."["..index.."] has incorrect strings count")
end
end
end
-- custom command table
loader.check_two_level_string_list(sandbox.setup.commands,"sandbox.setup.commands")
-- env tables
loader.check_two_level_string_list(sandbox.setup.env_blacklist,"sandbox.setup.env_blacklist")
loader.check_two_level_string_list(sandbox.setup.env_whitelist,"sandbox.setup.env_whitelist")
loader.check_two_level_env_set_list(sandbox.setup.env_set,"sandbox.setup.env_set")
-- bwrap table
assert(type(sandbox.bwrap)=="table", "sandbox.bwrap param incorrect")
for index,field in ipairs(sandbox.bwrap) do
assert(type(field)=="table", "sandbox.bwrap[" .. index .. "] value is incorrect")
for mi,mf in ipairs(field) do
if mi==1 then
assert(type(mf)=="string", "sandbox.bwrap["..index.."]["..mi.."] value is incorrect")
else
assert(type(mf)~="table" and type(mf)~="function" and type(mf)~="nil", "sandbox.bwrap["..index.."]["..mi.."] value is incorrect")
end
end
end
-- check profile
function loader.check_profile(profile, name)
assert(type(profile)=="table", name.." profile is incorrect")
assert(type(profile.exec)=="string", name..".exec value is incorrect or missing")
assert(type(profile.path)=="string" or type(profile.path)=="nil", name..".path value is incorrect or missing")
loader.check_one_level_string_list(profile.args, name..".args")
loader.check_one_level_string_list(profile.env_unset, name..".env_unset")
loader.check_one_level_env_set_list(profile.env_set, name..".env_set")
assert(type(profile.term_signal)=="number" or type(profile.term_signal)=="nil", name..".term_signal value is incorrect or missing")
assert(type(profile.attach)=="boolean" or type(profile.attach)=="nil", name..".attach value is incorrect or missing")
if type(profile.attach)=="nil" then profile.attach=false end
assert(type(profile.pty)=="boolean" or type(profile.pty)=="nil", name..".pty value is incorrect or missing")
if type(profile.pty)=="nil" then profile.pty=false end
assert(type(profile.exclusive)=="boolean" or type(profile.exclusive)=="nil", name..".exclusive value is incorrect or missing")
if type(profile.exclusive)=="nil" then profile.exclusive=false end
-- start command opcode
if profile.attach==true and profile.pty==false then
profile.start_opcode=100
elseif profile.attach==false and profile.pty==false then
profile.start_opcode=101
elseif profile.attach==true and profile.pty==true then
profile.start_opcode=200
elseif profile.attach==false and profile.pty==true then
profile.start_opcode=201
end
end
loader.check_profile(profile,config.profile)
loader.check_profile(dbus,"dbus")
loader.check_profile(pulse,"pulse")
|
sandboxer.post.lua: minor fix
|
sandboxer.post.lua: minor fix
|
Lua
|
mit
|
DarkCaster/Sandboxer,DarkCaster/Sandboxer
|
63a7069671cbd550d93d8601d72013a7e5d51757
|
worldedit_commands/wand.lua
|
worldedit_commands/wand.lua
|
local function above_or_under(placer, pointed_thing)
if placer:get_player_control().sneak then
return pointed_thing.above
else
return pointed_thing.under
end
end
local punched_air_time = {}
minetest.register_tool(":worldedit:wand", {
description = "WorldEdit Wand tool\nLeft-click to set 1st position, right-click to set 2nd",
inventory_image = "worldedit_wand.png",
stack_max = 1, -- there is no need to have more than one
liquids_pointable = true, -- ground with only water on can be selected as well
on_use = function(itemstack, placer, pointed_thing)
if placer == nil or pointed_thing == nil then return itemstack end
local name = placer:get_player_name()
if pointed_thing.type == "node" then
-- set and mark pos1
worldedit.pos1[name] = above_or_under(placer, pointed_thing)
worldedit.mark_pos1(name)
elseif pointed_thing.type == "nothing" then
local now = minetest.get_us_time()
if now - (punched_air_time[name] or 0) < 1000 * 1000 then
-- reset markers
minetest.registered_chatcommands["/reset"].func(name, "")
end
punched_air_time[name] = now
end
return itemstack -- nothing consumed, nothing changed
end,
on_place = function(itemstack, placer, pointed_thing)
if placer ~= nil and pointed_thing ~= nil and pointed_thing.type == "node" then
-- set and mark pos2
local name = placer:get_player_name()
worldedit.pos2[name] = above_or_under(placer, pointed_thing)
worldedit.mark_pos2(name)
end
return itemstack -- nothing consumed, nothing changed
end,
})
|
local function above_or_under(placer, pointed_thing)
if placer:get_player_control().sneak then
return pointed_thing.above
else
return pointed_thing.under
end
end
local punched_air_time = {}
minetest.register_tool(":worldedit:wand", {
description = "WorldEdit Wand tool\nLeft-click to set 1st position, right-click to set 2nd",
inventory_image = "worldedit_wand.png",
stack_max = 1, -- there is no need to have more than one
liquids_pointable = true, -- ground with only water on can be selected as well
on_use = function(itemstack, placer, pointed_thing)
if placer == nil or pointed_thing == nil then return itemstack end
local name = placer:get_player_name()
if pointed_thing.type == "node" then
-- set and mark pos1
worldedit.pos1[name] = above_or_under(placer, pointed_thing)
worldedit.mark_pos1(name)
elseif pointed_thing.type == "nothing" then
local now = minetest.get_us_time()
if now - (punched_air_time[name] or 0) < 1000 * 1000 then
-- reset markers
minetest.registered_chatcommands["/reset"].func(name, "")
end
punched_air_time[name] = now
elseif pointed_thing.type == "object" then
local entity = pointed_thing.ref:get_luaentity()
if entity and entity.name == "worldedit:pos2" then
-- set pos1 = pos2
worldedit.pos1[name] = worldedit.pos2[name]
worldedit.mark_pos1(name)
end
end
return itemstack -- nothing consumed, nothing changed
end,
on_place = function(itemstack, placer, pointed_thing)
if placer == nil or pointed_thing == nil then return itemstack end
local name = placer:get_player_name()
if pointed_thing.type == "node" then
-- set and mark pos2
worldedit.pos2[name] = above_or_under(placer, pointed_thing)
worldedit.mark_pos2(name)
elseif pointed_thing.type == "object" then
local entity = pointed_thing.ref:get_luaentity()
if entity and entity.name == "worldedit:pos1" then
-- set pos2 = pos1
worldedit.pos2[name] = worldedit.pos1[name]
worldedit.mark_pos2(name)
end
end
return itemstack -- nothing consumed, nothing changed
end,
})
|
Allow easily setting pos1 + 2 to the same node using the wand
|
Allow easily setting pos1 + 2 to the same node using the wand
Though right-click currently doesn't work due to an engine bug.
|
Lua
|
agpl-3.0
|
Uberi/Minetest-WorldEdit
|
4809d0f75dd5108ea7551ed42c5beced3e3439de
|
test_scripts/Polices/Policy_Table_Update/004_ATF_P_TC_PTU_DeviceConsent_from_User.lua
|
test_scripts/Polices/Policy_Table_Update/004_ATF_P_TC_PTU_DeviceConsent_from_User.lua
|
---------------------------------------------------------------------------------------------
-- Requirements summary:
-- [PolicyTableUpdate] PoliciesManager must initiate PTU in case getting 'device consent' from the user
--
-- Description:
-- SDL should request PTU in case gets 'device consent' from the user
-- 1. Used preconditions
-- SDL is built with "-DEXTENDED_POLICY: EXTERNAL_PROPRIETARY" flag
-- Connect mobile phone.
-- Register new application.
-- 2. Performed steps
-- Activate application.
-- User consent device
--
-- Expected result:
-- PTU is requested. PTS is created.
-- SDL->HMI: SDL.OnStatusUpdate(UPDATE_NEEDED)
---------------------------------------------------------------------------------------------
--[[ General configuration parameters ]]
config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0"
--[[ Required Shared libraries ]]
local commonSteps = require('user_modules/shared_testcases/commonSteps')
local commonFunctions = require('user_modules/shared_testcases/commonFunctions')
local testCasesForPolicyTableSnapshot = require('user_modules/shared_testcases/testCasesForPolicyTableSnapshot')
local testCasesForPolicyTable = require('user_modules/shared_testcases/testCasesForPolicyTable')
--[[ General Precondition before ATF start ]]
commonSteps:DeleteLogsFileAndPolicyTable()
testCasesForPolicyTable.Delete_Policy_table_snapshot()
--[[ General Settings for configuration ]]
Test = require('connecttest')
require('cardinalities')
require('user_modules/AppTypes')
--[[ Test ]]
commonFunctions:newTestCasesGroup("Test")
function Test:TestStep_PTU_DeviceConsent_from_User()
local is_test_failed = false
local ServerAddress = commonFunctions:read_parameter_from_smart_device_link_ini("ServerAddress")
local RequestId = self.hmiConnection:SendRequest("SDL.ActivateApp", { appID = self.applications[config.application1.registerAppInterfaceParams.appName]})
EXPECT_HMIRESPONSE(RequestId)
:Do(function(_,_)
local hmi_app1_id = self.applications[config.application1.registerAppInterfaceParams.appName]
--EXPECT_HMICALL("SDL.OnSDLConsentNeeded", { device = { name = ServerAddress, id = config.deviceMAC, isSDLAllowed = false } })
local RequestId_GetUsrFrMsg = self.hmiConnection:SendRequest("SDL.GetUserFriendlyMessage", {language = "EN-US", messageCodes = {"DataConsent"}})
EXPECT_HMIRESPONSE( RequestId_GetUsrFrMsg, {result = {code = 0, method = "SDL.GetUserFriendlyMessage"}})
:Do(function(_,_)
self.hmiConnection:SendNotification("SDL.OnAllowSDLFunctionality",
{allowed = true, source = "GUI", device = {id = config.deviceMAC, name = ServerAddress, isSDLAllowed = true}})
EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate", { status = "UPDATE_NEEDED" })
EXPECT_HMICALL("BasicCommunication.PolicyUpdate", {file = "/tmp/fs/mp/images/ivsu_cache/sdl_snapshot.json"})
:Do(function(_,_data1)
testCasesForPolicyTableSnapshot:verify_PTS(true,
{config.application1.registerAppInterfaceParams.appID},
{config.deviceMAC},
{hmi_app1_id})
local timeout_after_x_seconds = testCasesForPolicyTableSnapshot:get_data_from_PTS("module_config.timeout_after_x_seconds")
local seconds_between_retries = {}
for i = 1, #testCasesForPolicyTableSnapshot.pts_seconds_between_retries do
seconds_between_retries[i] = testCasesForPolicyTableSnapshot.pts_seconds_between_retries[i].value
if(seconds_between_retries[i] ~= _data1.params.retry[i]) then
commonFunctions:printError("Error: data.params.retry["..i.."]: ".._data1.params.retry[i] .."ms. Expected: "..seconds_between_retries[i].."ms")
is_test_failed = true
end
end
if(_data1.params.timeout ~= timeout_after_x_seconds) then
commonFunctions:printError("Error: data.params.timeout = ".._data1.params.timeout.."ms. Expected: "..timeout_after_x_seconds.."ms.")
is_test_failed = true
end
if(is_test_failed == true) then
self:FailTestCase("Test is FAILED. See prints.")
end
self.hmiConnection:SendResponse(_data1.id, _data1.method, "SUCCESS", {})
end)
end)
EXPECT_HMICALL("BasicCommunication.ActivateApp")
:Do(function(_,data)
self.hmiConnection:SendResponse(data.id,"BasicCommunication.ActivateApp", "SUCCESS", {})
end):Times(1)
end)
EXPECT_NOTIFICATION("OnHMIStatus", {hmiLevel = "FULL", systemContext = "MAIN"})
if(is_test_failed == true) then self:FailTestCase("Test is FAILED. See prints.") end
end
--[[ Postconditions ]]
commonFunctions:newTestCasesGroup("Postconditions")
function Test.Postcondition_Stop()
StopSDL()
end
return Test
|
---------------------------------------------------------------------------------------------
-- Requirements summary:
-- [PolicyTableUpdate] PoliciesManager must initiate PTU in case getting 'device consent' from the user
--
-- Description:
-- SDL should request PTU in case gets 'device consent' from the user
-- 1. Used preconditions
-- SDL is built with "-DEXTENDED_POLICY: EXTERNAL_PROPRIETARY" flag
-- Connect mobile phone.
-- Register new application.
-- 2. Performed steps
-- Activate application.
-- User consent device
--
-- Expected result:
-- PTU is requested. PTS is created.
-- SDL->HMI: SDL.OnStatusUpdate(UPDATE_NEEDED)
---------------------------------------------------------------------------------------------
--[[ General configuration parameters ]]
config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0"
--[[ Required Shared libraries ]]
local commonSteps = require('user_modules/shared_testcases/commonSteps')
local commonFunctions = require('user_modules/shared_testcases/commonFunctions')
local testCasesForPolicyTable = require('user_modules/shared_testcases/testCasesForPolicyTable')
--[[ Local Functions ]]
local function check_file_exists(name)
local f = io.open(name, "r")
if f ~= nil then
io.close(f)
return true
else
return false
end
end
--[[ General Precondition before ATF start ]]
commonSteps:DeleteLogsFileAndPolicyTable()
testCasesForPolicyTable.Delete_Policy_table_snapshot()
--[[ General Settings for configuration ]]
Test = require('connecttest')
require('cardinalities')
require('user_modules/AppTypes')
--[[ Test ]]
commonFunctions:newTestCasesGroup("Test")
function Test:ActivateApp()
local requestId1 = self.hmiConnection:SendRequest("SDL.ActivateApp", { appID = self.applications["Test Application"] })
EXPECT_HMIRESPONSE(requestId1)
:Do(function(_, data1)
if data1.result.isSDLAllowed ~= true then
local requestId2 = self.hmiConnection:SendRequest("SDL.GetUserFriendlyMessage",
{ language = "EN-US", messageCodes = { "DataConsent" } })
EXPECT_HMIRESPONSE(requestId2)
:Do(function(_, _)
self.hmiConnection:SendNotification("SDL.OnAllowSDLFunctionality",
{ allowed = true, source = "GUI", device = { id = config.deviceMAC, name = "127.0.0.1" } })
EXPECT_HMICALL("BasicCommunication.ActivateApp")
:Do(function(_, data2)
self.hmiConnection:SendResponse(data2.id,"BasicCommunication.ActivateApp", "SUCCESS", { })
end)
:Times(1)
end)
end
end)
EXPECT_HMICALL("BasicCommunication.PolicyUpdate")
end
function Test:ValidateSnapshot()
local system_file_path = commonFunctions:read_parameter_from_smart_device_link_ini("SystemFilesPath")
if not check_file_exists(system_file_path .. "/sdl_snapshot.json") then
self:FailTestCase("PTS file is NOT created")
end
end
--[[ Postconditions ]]
commonFunctions:newTestCasesGroup("Postconditions")
function Test.Postcondition_Stop()
StopSDL()
end
return Test
|
Fix issues in script
|
Fix issues in script
|
Lua
|
bsd-3-clause
|
smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts
|
4a803f0be3c286c48c4cb7b49cc4e152b8985f8e
|
bin/data/scripts/console.lua
|
bin/data/scripts/console.lua
|
Console = {
cursor = 0,
string = '',
offset = 0,
prompt = '> ',
-- Output log. Commands log in iLua console history
history = {},
}
Console.__index = Console
Console.iLua = require('data/scripts/ilua')
require('data/scripts/consolekeys')
function Console:widget()
if self.console == nil then
local console = Interface.getWidgetByName("console")
if console == nil then
console = Interface.createWidget("widget_console", constants.wtText)
console:load({ name = "console",
align = bit.bor(constants.waLEFT, constants.waTOP),
height = 200, width = 300, depth = 2, bgcolor = {0, 0, 0, 127},
text = {
x = 5, y = -5, size = 18, color = {255,255,255},
face = "./LiberationSerif-Regular.ttf", lineheight = 0.75,
align = bit.bor(constants.waLEFT, constants.waTOP),
}
})
console:resize(configs:getById('windows_width', 'config_general') - 1, 300)
console:toggle()
end
self.console = console
self.lines = console:Lines()
end
return self.console
end
function Console:toggle()
if self:widget():toggle() then
self.old_bindings = Input.getName()
Input.set("bindings_console")
Input.setReciever( function(keynum, down, char)
if down == 1 then self:process(keynum, char) end
end
)
self:widget():CursorVisible(true)
else
Input.set( self.old_bindings )
Input.setReciever(nil)
end
end
function keyname_by_code(keynum)
for k,v in pairs(keys) do
if v == keynum then
return k
end
end
end
function Console:process(keynum, char)
local keyname = keyname_by_code(keynum)
local func = nil
if keyname ~= nil then
func = self["key_" .. keyname]
end
if type(func) == "function" then
func(self, char)
else
if char ~= "" then
self.cursor = self.cursor + 1
local start = self.string:sub(0, self.cursor - 1)
local send = self.string:sub(self.cursor)
self.string = start .. char .. send
end
end
-- Print lines of log
local out = ''
local count = table.getn(self.history)
if count > 0 then
-- Start line
local number = 0
if count > self.lines then
number = count - self.lines
end
for line = number - self.offset, number + self.lines - self.offset do
if line < count then
out = out .. self.history[line + 1]
end
end
end
if self.cursor < 0 then self.cursor = 0 end
if self.cursor > self.string:len() then
self.cursor = self.string:len()
end
self:widget():WidgetText(out .. self.prompt .. self.string .. ' ')
self:widget():Cursor(out:len() + self.prompt:len() + self.cursor)
end
|
Console = {
cursor = 0,
string = '',
offset = 0,
prompt = '> ',
-- Output log. Commands log in iLua console history
history = {},
}
Console.__index = Console
Console.iLua = require('data/scripts/ilua')
require('data/scripts/consolekeys')
function Console:widget()
if self.console == nil then
local console = Interface.getWidgetByName("console")
if console == nil then
console = Interface.createWidget("widget_console", constants.wtText)
console:load({ name = "console",
align = bit.bor(constants.waLEFT, constants.waTOP),
height = 200, width = 300, depth = 2, bgcolor = {0, 0, 0, 127},
text = {
x = 5, y = -5, size = 18, color = {255,255,255},
face = "./LiberationSerif-Regular.ttf", lineheight = 0.75,
align = bit.bor(constants.waLEFT, constants.waTOP),
}
})
local conf_video = configs:get( 'video', 'config_general', 'config' )
console:resize(conf_video['window_width'] - 1, 300)
console:toggle()
end
self.console = console
self.lines = console:Lines()
end
return self.console
end
function Console:toggle()
if self:widget():toggle() then
self.old_bindings = Input.getName()
Input.set("bindings_console")
Input.setReciever( function(keynum, down, char)
if down == 1 then self:process(keynum, char) end
end
)
self:widget():CursorVisible(true)
else
Input.set( self.old_bindings )
Input.setReciever(nil)
end
end
function keyname_by_code(keynum)
for k,v in pairs(keys) do
if v == keynum then
return k
end
end
end
function Console:process(keynum, char)
local keyname = keyname_by_code(keynum)
local func = nil
if keyname ~= nil then
func = self["key_" .. keyname]
end
if type(func) == "function" then
func(self, char)
else
if char ~= "" then
self.cursor = self.cursor + 1
local start = self.string:sub(0, self.cursor - 1)
local send = self.string:sub(self.cursor)
self.string = start .. char .. send
end
end
-- Print lines of log
local out = ''
local count = table.getn(self.history)
if count > 0 then
-- Start line
local number = 0
if count > self.lines then
number = count - self.lines
end
for line = number - self.offset, number + self.lines - self.offset do
if line < count then
out = out .. self.history[line + 1]
end
end
end
if self.cursor < 0 then self.cursor = 0 end
if self.cursor > self.string:len() then
self.cursor = self.string:len()
end
self:widget():WidgetText(out .. self.prompt .. self.string .. ' ')
self:widget():Cursor(out:len() + self.prompt:len() + self.cursor)
end
|
Fix console.
|
Fix console.
|
Lua
|
mit
|
Yukkurigame/Yukkuri,Yukkurigame/Yukkuri,Yukkurigame/Yukkuri
|
5a02dda4ea266497786835ce9b764c88d657c022
|
src/cli/utils/start.lua
|
src/cli/utils/start.lua
|
local IO = require "kong.tools.io"
local cutils = require "kong.cli.utils"
local constants = require "kong.constants"
local _M = {}
local function is_openresty(path_to_check)
local cmd = tostring(path_to_check).." -v 2>&1"
local handle = io.popen(cmd)
local out = handle:read()
handle:close()
local matched = out:match("^nginx version: ngx_openresty/") or out:match("^nginx version: openresty/")
if matched then
return path_to_check
end
end
local function find_nginx()
local nginx_bin = "nginx"
local nginx_search_paths = {
"/usr/local/openresty/nginx/sbin/",
"/usr/local/opt/openresty/bin/",
"/usr/local/bin/",
"/usr/sbin/",
""
}
for i = 1, #nginx_search_paths do
local prefix = nginx_search_paths[i]
local to_check = tostring(prefix)..tostring(nginx_bin)
if is_openresty(to_check) then
return to_check
end
end
end
local function prepare_nginx_working_dir(kong_config)
if kong_config.send_anonymous_reports then
kong_config.nginx = "error_log syslog:server=kong-hf.mashape.com:61828 error;\n"..kong_config.nginx
end
-- Create nginx folder if needed
local _, err = IO.path:mkdir(IO.path:join(kong_config.nginx_working_dir, "logs"))
if err then
cutils.logger:error_exit(err)
end
os.execute("touch "..IO.path:join(kong_config.nginx_working_dir, "logs", "error.log"))
os.execute("touch "..IO.path:join(kong_config.nginx_working_dir, "logs", "access.log"))
-- Extract nginx config to nginx folder
local ok, err = IO.write_to_file(IO.path:join(kong_config.nginx_working_dir, constants.CLI.NGINX_CONFIG), kong_config.nginx)
if not ok then
error(err)
end
return kong_config.nginx_working_dir
end
function _M.start(args_config)
-- Make sure nginx is there and is openresty
local nginx_path = find_nginx()
if not nginx_path then
cutils.logger:error_exit("can't find nginx")
end
-- Get configuration from default or given path
local config_path = cutils.get_kong_config_path(args_config)
local config, dao_factory = IO.load_configuration_and_dao(config_path)
-- Migrate the DB if needed and possible
local keyspace, err = dao_factory:get_migrations()
if err then
cutils.logger:error_exit(err)
elseif keyspace == nil then
cutils.logger:log("Database not initialized. Running migrations...")
local migrations = require("kong.tools.migrations")(dao_factory, cutils.get_luarocks_install_dir())
migrations:migrate(function(migration, err)
if err then
cutils.logger:error_exit(err)
elseif migration then
cutils.logger:success("Migrated up to: "..cutils.colors.yellow(migration.name))
end
end)
end
-- Prepare nginx --prefix dir
local nginx_working_dir = prepare_nginx_working_dir(config)
-- Build nginx start command
local cmd = string.format("KONG_CONF=%s %s -p %s -c %s -g 'pid %s;'",
config_path,
nginx_path,
nginx_working_dir,
constants.CLI.NGINX_CONFIG,
constants.CLI.NGINX_PID)
if os.execute(cmd) == 0 then
cutils.logger:success("Started")
else
cutils.logger:error_exit("Could not start Kong")
end
end
return _M.start
|
local IO = require "kong.tools.io"
local cutils = require "kong.cli.utils"
local constants = require "kong.constants"
local _M = {}
local KONG_SYSLOG = "kong-hf.mashape.com"
local function is_openresty(path_to_check)
local cmd = tostring(path_to_check).." -v 2>&1"
local handle = io.popen(cmd)
local out = handle:read()
handle:close()
local matched = out:match("^nginx version: ngx_openresty/") or out:match("^nginx version: openresty/")
if matched then
return path_to_check
end
end
local function find_nginx()
local nginx_bin = "nginx"
local nginx_search_paths = {
"/usr/local/openresty/nginx/sbin/",
"/usr/local/opt/openresty/bin/",
"/usr/local/bin/",
"/usr/sbin/",
""
}
for i = 1, #nginx_search_paths do
local prefix = nginx_search_paths[i]
local to_check = tostring(prefix)..tostring(nginx_bin)
if is_openresty(to_check) then
return to_check
end
end
end
local function prepare_nginx_working_dir(kong_config)
if kong_config.send_anonymous_reports then
-- If there is no internet connection, disable this feature
if os.execute("dig +time=2 +tries=2 "..KONG_SYSLOG.. "> /dev/null") == 0 then
kong_config.nginx = "error_log syslog:server="..KONG_SYSLOG..":61828 error;\n"..kong_config.nginx
else
cutils.logger:warn("The internet connection might not be available, cannot resolve "..KONG_SYSLOG)
end
end
-- Create nginx folder if needed
local _, err = IO.path:mkdir(IO.path:join(kong_config.nginx_working_dir, "logs"))
if err then
cutils.logger:error_exit(err)
end
os.execute("touch "..IO.path:join(kong_config.nginx_working_dir, "logs", "error.log"))
os.execute("touch "..IO.path:join(kong_config.nginx_working_dir, "logs", "access.log"))
-- Extract nginx config to nginx folder
local ok, err = IO.write_to_file(IO.path:join(kong_config.nginx_working_dir, constants.CLI.NGINX_CONFIG), kong_config.nginx)
if not ok then
error(err)
end
return kong_config.nginx_working_dir
end
function _M.start(args_config)
-- Make sure nginx is there and is openresty
local nginx_path = find_nginx()
if not nginx_path then
cutils.logger:error_exit("can't find nginx")
end
-- Get configuration from default or given path
local config_path = cutils.get_kong_config_path(args_config)
local config, dao_factory = IO.load_configuration_and_dao(config_path)
-- Migrate the DB if needed and possible
local keyspace, err = dao_factory:get_migrations()
if err then
cutils.logger:error_exit(err)
elseif keyspace == nil then
cutils.logger:log("Database not initialized. Running migrations...")
local migrations = require("kong.tools.migrations")(dao_factory, cutils.get_luarocks_install_dir())
migrations:migrate(function(migration, err)
if err then
cutils.logger:error_exit(err)
elseif migration then
cutils.logger:success("Migrated up to: "..cutils.colors.yellow(migration.name))
end
end)
end
-- Prepare nginx --prefix dir
local nginx_working_dir = prepare_nginx_working_dir(config)
-- Build nginx start command
local cmd = string.format("KONG_CONF=%s %s -p %s -c %s -g 'pid %s;'",
config_path,
nginx_path,
nginx_working_dir,
constants.CLI.NGINX_CONFIG,
constants.CLI.NGINX_PID)
if os.execute(cmd) == 0 then
cutils.logger:success("Started")
else
cutils.logger:error_exit("Could not start Kong")
end
end
return _M.start
|
Fixes #111
|
Fixes #111
|
Lua
|
apache-2.0
|
sbuettner/kong,peterayeni/kong,AnsonSmith/kong,paritoshmmmec/kong,Skyscanner/kong,ChristopherBiscardi/kong,bbalu/kong,chourobin/kong,wakermahmud/kong,puug/kong,ropik/kong,vmercierfr/kong,skynet/kong
|
3853f776a3fdcc52fb4aa804b4b2cf9350516861
|
share/lua/playlist/vimeo.lua
|
share/lua/playlist/vimeo.lua
|
--[[
$Id$
Copyright © 2009 the VideoLAN team
Authors: Konstantin Pavlov ([email protected])
François Revol ([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 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.
--]]
function get_prefres()
local prefres = -1
if vlc.var and vlc.var.inherit then
prefres = vlc.var.inherit(nil, "preferred-resolution")
if prefres == nil then
prefres = -1
end
end
return prefres
end
-- Probe function.
function probe()
return vlc.access == "http"
and string.match( vlc.path, "vimeo.com/%d+$" )
-- do not match other addresses,
-- else we'll also try to decode the actual video url
end
-- Parse function.
function parse()
_,_,id = string.find( vlc.path, "vimeo.com/([0-9]*)")
prefres = get_prefres()
ishd = false
quality = "sd"
codec = nil
while true do
line = vlc.readline()
if not line then break end
-- Try to find the video's title
if string.match( line, "<meta property=\"og:title\"" ) then
_,_,name = string.find (line, "content=\"(.*)\">" )
end
if string.match( line, "{config:.*\"title\":\"" ) then
_,_,name = string.find (line, "\"title\":\"([^\"]*)\"," )
end
-- Try to find image for thumbnail
if string.match( line, "<meta property=\"og:image\"" ) then
_,_,arturl = string.find (line, "content=\"(.*)\">" )
end
if string.match( line, "<meta itemprop=\"thumbnailUrl\"" ) then
_,_,arturl = string.find (line, "content=\"(.*)\">" )
end
-- Try to find duration
if string.match( line, "{config:.*\"duration\":" ) then
_,_,duration = string.find (line, "\"duration\":([0-9]*)," )
end
-- Try to find request signature (needed to construct video url)
if string.match( line, "{config:.*\"signature\":" ) then
_,_,rsig = string.find (line, "\"signature\":\"([0-9a-f]*)\"," )
end
-- Try to find request signature time (needed to construct video url)
if string.match( line, "{config:.*\"timestamp\":" ) then
_,_,tstamp = string.find (line, "\"timestamp\":([0-9]*)," )
end
-- Try to find the available codecs
if string.match( line, "{config:.*,\"files\":{\"vp6\":" ) then
codec = "vp6"
end
if string.match( line, "{config:.*,\"files\":{\"vp8\":" ) then
codec = "vp8"
end
if string.match( line, "{config:.*,\"files\":{\"h264\":" ) then
codec = "h264"
end
-- Try to find whether video is HD actually
if string.match( line, "{config:.*,\"hd\":1" ) then
ishd = true
end
if string.match( line, "{config:.*\"height\":" ) then
_,_,height = string.find (line, "\"height\":([0-9]*)," )
end
end
if not codec then
vlc.msg.err("unable to find codec info")
return {}
end
if ishd and ( not height or prefres < 0 or prefres >= tonumber(height) ) then
quality = "hd"
end
path = "http://player.vimeo.com/play_redirect?quality="..quality.."&codecs="..codec.."&clip_id="..id.."&time="..tstamp.."&sig="..rsig.."&type=html5_desktop_local"
return { { path = path; name = name; arturl = arturl; duration = duration } }
end
|
--[[
$Id$
Copyright © 2009 the VideoLAN team
Authors: Konstantin Pavlov ([email protected])
François Revol ([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 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.
--]]
function get_prefres()
local prefres = -1
if vlc.var and vlc.var.inherit then
prefres = vlc.var.inherit(nil, "preferred-resolution")
if prefres == nil then
prefres = -1
end
end
return prefres
end
-- Probe function.
function probe()
return vlc.access == "http"
and string.match( vlc.path, "vimeo.com/%d+$" )
-- do not match other addresses,
-- else we'll also try to decode the actual video url
end
-- Parse function.
function parse()
_,_,id = string.find( vlc.path, "vimeo.com/([0-9]*)")
prefres = get_prefres()
ishd = false
quality = "sd"
codec = nil
line2 = ""
while true do
line = vlc.readline()
if not line then break end
if string.match( line, "{config:.*") then
line2 = line;
while not string.match( line2, "}};") do
line2 = vlc.readline()
if not line2 then break end
line = line .. line2;
end
end
-- Try to find the video's title
if string.match( line, "<meta property=\"og:title\"" ) then
_,_,name = string.find (line, "content=\"(.*)\">" )
end
if string.match( line, "{config:.*\"title\":\"" ) then
_,_,name = string.find (line, "\"title\":\"([^\"]*)\"," )
end
-- Try to find image for thumbnail
if string.match( line, "<meta property=\"og:image\"" ) then
_,_,arturl = string.find (line, "content=\"(.*)\">" )
end
if string.match( line, "<meta itemprop=\"thumbnailUrl\"" ) then
_,_,arturl = string.find (line, "content=\"(.*)\">" )
end
-- Try to find duration
if string.match( line, "{config:.*\"duration\":" ) then
_,_,duration = string.find (line, "\"duration\":([0-9]*)," )
end
-- Try to find request signature (needed to construct video url)
if string.match( line, "{config:.*\"signature\":" ) then
_,_,rsig = string.find (line, "\"signature\":\"([0-9a-f]*)\"," )
end
-- Try to find request signature time (needed to construct video url)
if string.match( line, "{config:.*\"timestamp\":" ) then
_,_,tstamp = string.find (line, "\"timestamp\":([0-9]*)," )
end
-- Try to find the available codecs
if string.match( line, "{config:.*,\"files\":{\"vp6\":" ) then
codec = "vp6"
end
if string.match( line, "{config:.*,\"files\":{\"vp8\":" ) then
codec = "vp8"
end
if string.match( line, "{config:.*,\"files\":{\"h264\":" ) then
codec = "h264"
end
-- Try to find whether video is HD actually
if string.match( line, "{config:.*,\"hd\":1" ) then
ishd = true
end
if string.match( line, "{config:.*\"height\":" ) then
_,_,height = string.find (line, "\"height\":([0-9]*)," )
end
if not line2 then break end
end
if not codec then
vlc.msg.err("unable to find codec info")
return {}
end
if ishd and ( not height or prefres < 0 or prefres >= tonumber(height) ) then
quality = "hd"
end
path = "http://player.vimeo.com/play_redirect?quality="..quality.."&codecs="..codec.."&clip_id="..id.."&time="..tstamp.."&sig="..rsig.."&type=html5_desktop_local"
return { { path = path; name = name; arturl = arturl; duration = duration } }
end
|
Fix for vimeo parser to handle multi-line data block
|
Fix for vimeo parser to handle multi-line data block
Added code to vimeo.lua parser to handle data block consisting of
multiple lines. Code now concatenates those lines together.
Note when testing: vimeo doesn't like VLC; you must use :http-user-agent
flag to impersonate browser.
Close #7148
Signed-off-by: Jean-Baptiste Kempf <[email protected]>
|
Lua
|
lgpl-2.1
|
xkfz007/vlc,jomanmuk/vlc-2.1,jomanmuk/vlc-2.2,xkfz007/vlc,vlc-mirror/vlc-2.1,shyamalschandra/vlc,krichter722/vlc,xkfz007/vlc,krichter722/vlc,krichter722/vlc,krichter722/vlc,vlc-mirror/vlc,vlc-mirror/vlc,xkfz007/vlc,shyamalschandra/vlc,shyamalschandra/vlc,krichter722/vlc,jomanmuk/vlc-2.2,jomanmuk/vlc-2.1,jomanmuk/vlc-2.2,vlc-mirror/vlc,xkfz007/vlc,vlc-mirror/vlc-2.1,vlc-mirror/vlc,vlc-mirror/vlc,jomanmuk/vlc-2.1,vlc-mirror/vlc-2.1,krichter722/vlc,vlc-mirror/vlc,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.2,jomanmuk/vlc-2.1,jomanmuk/vlc-2.1,jomanmuk/vlc-2.2,jomanmuk/vlc-2.2,vlc-mirror/vlc,krichter722/vlc,vlc-mirror/vlc-2.1,xkfz007/vlc,jomanmuk/vlc-2.2,xkfz007/vlc,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.1,vlc-mirror/vlc-2.1,shyamalschandra/vlc,jomanmuk/vlc-2.1,shyamalschandra/vlc,shyamalschandra/vlc,shyamalschandra/vlc
|
d419749eb20cbbf41a541dccfb3814f984db5b53
|
swift/tools/tracing-config.lua
|
swift/tools/tracing-config.lua
|
function RegisterExtractorPack(id)
local extractorDirectory = GetPlatformToolsDirectory()
local relativeSwiftExtractor = extractorDirectory .. 'extractor'
local swiftExtractor = AbsolutifyExtractorPath(id, relativeSwiftExtractor)
function indexOf(array, value)
for i, v in ipairs(array) do
if v == value then
return i
end
end
return nil
end
-- removes unsupported CLI arg including the following how_many args
function strip_unsupported_arg(args, arg, how_many)
local index = indexOf(args, arg)
if index then
table.remove(args, index)
while (how_many > 0)
do
table.remove(args, index)
how_many = how_many - 1
end
end
end
function strip_unsupported_args(args)
strip_unsupported_arg(args, '-emit-localized-strings', 0)
strip_unsupported_arg(args, '-emit-localized-strings-path', 1)
strip_unsupported_arg(args, '-stack-check', 0)
end
-- xcodebuild does not always specify the -resource-dir in which case the compiler falls back
-- to a resource-dir based on its path
-- here we mimic this behavior externally
-- without a proper -resource-dir compiler-specific headers cannot be found which leads to
-- broken extraction
function insert_resource_dir_if_needed(compilerPath, args)
local resource_dir_index = indexOf(args, '-resource-dir')
if resource_dir_index then
return
end
-- derive -resource-dir based on the compilerPath
-- e.g.: /usr/bin/swift-frontend -> /usr/bin/../lib/swift
local last_slash_index = string.find(compilerPath, "/[^/]*$")
local compiler_dir = string.sub(compilerPath, 1, last_slash_index)
local resource_dir = compiler_dir .. '../lib/swift'
table.insert(args, '-resource-dir')
table.insert(args, resource_dir)
end
function SwiftMatcher(compilerName, compilerPath, compilerArguments, lang)
-- Only match binaries names `swift-frontend`
if compilerName ~= 'swift-frontend' then return nil end
-- Skip the invocation in case it's not called in `-frontend` mode
if compilerArguments.argv[1] ~= '-frontend' then return nil end
-- Drop the `-frontend` argument
table.remove(compilerArguments.argv, 1)
-- Skip "info" queries in case there is nothing to extract
if compilerArguments.argv[1] == '-print-target-info' then
return nil
end
if compilerArguments.argv[1] == '-emit-supported-features' then
return nil
end
strip_unsupported_args(compilerArguments.argv)
insert_resource_dir_if_needed(compilerPath, compilerArguments.argv)
return {
trace = true,
replace = false,
order = ORDER_AFTER,
invocation = {path = swiftExtractor, arguments = compilerArguments}
}
end
return {SwiftMatcher}
end
-- Return a list of minimum supported versions of the configuration file format
-- return one entry per supported major version.
function GetCompatibleVersions() return {'1.0.0'} end
|
function RegisterExtractorPack(id)
local extractorDirectory = GetPlatformToolsDirectory()
local relativeSwiftExtractor = extractorDirectory .. 'extractor'
local swiftExtractor = AbsolutifyExtractorPath(id, relativeSwiftExtractor)
function indexOf(array, value)
for i, v in ipairs(array) do
if v == value then
return i
end
end
return nil
end
-- removes unsupported CLI arg including the following how_many args
function strip_unsupported_arg(args, arg, how_many)
local index = indexOf(args, arg)
if index then
table.remove(args, index)
while (how_many > 0)
do
table.remove(args, index)
how_many = how_many - 1
end
end
end
function strip_unsupported_args(args)
strip_unsupported_arg(args, '-emit-localized-strings', 0)
strip_unsupported_arg(args, '-emit-localized-strings-path', 1)
strip_unsupported_arg(args, '-stack-check', 0)
strip_unsupported_arg(args, '-experimental-skip-non-inlinable-function-bodies-without-types', 0)
end
-- xcodebuild does not always specify the -resource-dir in which case the compiler falls back
-- to a resource-dir based on its path
-- here we mimic this behavior externally
-- without a proper -resource-dir compiler-specific headers cannot be found which leads to
-- broken extraction
function insert_resource_dir_if_needed(compilerPath, args)
local resource_dir_index = indexOf(args, '-resource-dir')
if resource_dir_index then
return
end
-- derive -resource-dir based on the compilerPath
-- e.g.: /usr/bin/swift-frontend -> /usr/bin/../lib/swift
local last_slash_index = string.find(compilerPath, "/[^/]*$")
local compiler_dir = string.sub(compilerPath, 1, last_slash_index)
local resource_dir = compiler_dir .. '../lib/swift'
table.insert(args, '-resource-dir')
table.insert(args, resource_dir)
end
function SwiftMatcher(compilerName, compilerPath, compilerArguments, lang)
-- Only match binaries names `swift-frontend`
if compilerName ~= 'swift-frontend' then return nil end
-- Skip the invocation in case it's not called in `-frontend` mode
if compilerArguments.argv[1] ~= '-frontend' then return nil end
-- Drop the `-frontend` argument
table.remove(compilerArguments.argv, 1)
-- Skip "info" queries in case there is nothing to extract
if compilerArguments.argv[1] == '-print-target-info' then
return nil
end
if compilerArguments.argv[1] == '-emit-supported-features' then
return nil
end
strip_unsupported_args(compilerArguments.argv)
insert_resource_dir_if_needed(compilerPath, compilerArguments.argv)
return {
trace = true,
replace = false,
order = ORDER_AFTER,
invocation = {path = swiftExtractor, arguments = compilerArguments}
}
end
return {SwiftMatcher}
end
-- Return a list of minimum supported versions of the configuration file format
-- return one entry per supported major version.
function GetCompatibleVersions() return {'1.0.0'} end
|
Swift: fix missing extraction of function bodies in SPM builds
|
Swift: fix missing extraction of function bodies in SPM builds
For some reason `-experimental-skip-non-inlinable-function-bodies-without-types`
is passed to the frontend, which will skip extraction of most bodies.
By suppressing that option the problem goes away.
|
Lua
|
mit
|
github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql
|
e8d656fefcec253425469d23354afdf505f368b9
|
UCDadmin/permissions/permissions.lua
|
UCDadmin/permissions/permissions.lua
|
-- Numbers are for GUI buttons
-- If a number is not there, it means it is false
-- Permissions are inherited from the rank below
local permissions = {
[1] = {
[1] = true, -- warp to player
[2] = true, -- punish
[3] = true, -- spectate
[4] = true, -- warp player to
[5] = true, -- reconnect
[6] = true, -- kick
[7] = true, -- freeze
[9] = true, -- slap
[10] = true, -- rename
[11] = true, -- view punishments
[12] = true, -- screenshot
[17] = true, -- dimension
[18] = true, -- interior
[21] = true, -- destroy vehicle
[25] = true, -- view weapons
[29] = true, -- freeze vehicle
["mute"] = true,
["admin jail"] = true,
},
[2] = {
[8] = true, -- shout
[13] = true, -- set model
[15] = true, -- set health
[16] = true, -- set armour
[20] = true, -- eject
[22] = true, -- disable vehicle
[23] = true, -- set job
},
[3] = {
["ban"] = true,
[27] = true, -- last logins
},
[4] = {
},
[5] = {
},
[1337] = {
},
}
function canAdminDoAction(plr, action)
if (not isPlayerAdmin(plr) or not getPlayerAdminRank(plr)) then return end
return getRankPerms(getPlayerAdminRank(plr))[action] or false
end
function getRankPerms(rank)
if (not rank) then return end
local temp = {}
for ind, ent in pairs(permissions) do
if (ind <= rank) then
for k, v in pairs(ent) do
temp[k] = v
end
end
end
if (rank == 1337) then
temp[-1] = true
end
return temp
end
function sendPermissions(plr)
if (not isPlayerAdmin(plr)) then return end
local rank = getPlayerAdminRank(plr)
triggerClientEvent(plr, "UCDadmin.onReceivedPermissions", plr, getRankPerms(rank))
end
addEvent("UCDadmin.getPermissions", true)
addEventHandler("UCDadmin.getPermissions", root,
function ()
sendPermissions(client)
end
)
addEventHandler("onPlayerLogin", root,
function ()
if (source.account.name ~= "guest" and adminTable[source.account.name]) then
sendPermissions(plr)
end
end
)
|
-- Numbers are for GUI buttons
-- If a number is not there, it means it is false
-- Permissions are inherited from the rank below
local permissions = {
[1] = {
[1] = true, -- warp to player
[2] = true, -- punish
[3] = true, -- spectate
[4] = true, -- warp player to
[5] = true, -- reconnect
[6] = true, -- kick
[7] = true, -- freeze
[9] = true, -- slap
[10] = true, -- rename
[11] = true, -- view punishments
[12] = true, -- screenshot
[17] = true, -- dimension
[18] = true, -- interior
[21] = true, -- destroy vehicle
[25] = true, -- view weapons
[29] = true, -- freeze vehicle
["mute"] = true,
["admin jail"] = true,
},
[2] = {
[8] = true, -- shout
[13] = true, -- set model
[15] = true, -- set health
[16] = true, -- set armour
[20] = true, -- eject
[22] = true, -- disable vehicle
[23] = true, -- set job
},
[3] = {
["ban"] = true,
[27] = true, -- last logins
},
[4] = {
},
[5] = {
},
[1337] = {
},
}
function canAdminDoAction(plr, action)
if (not isPlayerAdmin(plr) or not getPlayerAdminRank(plr)) then return end
return getRankPerms(getPlayerAdminRank(plr))[action] or false
end
function getRankPerms(rank)
if (not rank) then return end
local temp = {}
for ind, ent in pairs(permissions) do
if (ind <= rank) then
for k, v in pairs(ent) do
temp[k] = v
end
end
end
if (rank == 1337) then
temp[-1] = true
end
return temp
end
function sendPermissions(plr)
if (not isPlayerAdmin(plr)) then return end
local rank = getPlayerAdminRank(plr)
triggerClientEvent(plr, "UCDadmin.onReceivedPermissions", plr, getRankPerms(rank))
end
addEvent("UCDadmin.getPermissions", true)
addEventHandler("UCDadmin.getPermissions", root,
function ()
sendPermissions(client)
end
)
addEventHandler("onPlayerLogin", root,
function ()
--if (source.account.name ~= "guest" and adminTable[source.account.name]) then
if (isPlayerAdmin(source))
sendPermissions(source)
end
end
)
|
UCDadmin
|
UCDadmin
- Hopefully fixed table sync once and for all
|
Lua
|
mit
|
nokizorque/ucd,nokizorque/ucd
|
a2784867f6629ca24913eba779df125f588d90ac
|
src/luarocks/install.lua
|
src/luarocks/install.lua
|
--- Module implementing the LuaRocks "install" command.
-- Installs binary rocks.
module("luarocks.install", package.seeall)
local path = require("luarocks.path")
local rep = require("luarocks.rep")
local fetch = require("luarocks.fetch")
local util = require("luarocks.util")
local fs = require("luarocks.fs")
local deps = require("luarocks.deps")
local manif = require("luarocks.manif")
local cfg = require("luarocks.cfg")
help_summary = "Install a rock."
help_arguments = "{<rock>|<name> [<version>]}"
help = [[
Argument may be the name of a rock to be fetched from a repository
or a filename of a locally available rock.
]]
--- Install a binary rock.
-- @param rock_file string: local or remote filename of a rock.
-- @return boolean or (nil, string, [string]): True if succeeded or
-- nil and an error message and an optional error code.
function install_binary_rock(rock_file)
assert(type(rock_file) == "string")
local name, version, arch = path.parse_rock_name(rock_file)
if not name then
return nil, "Filename "..rock_file.." does not match format 'name-version-revision.arch.rock'."
end
if arch ~= "all" and arch ~= cfg.arch then
return nil, "Incompatible architecture "..arch, "arch"
end
if rep.is_installed(name, version) then
rep.delete_version(name, version)
end
local rollback = util.schedule_function(function()
fs.delete(path.install_dir(name, version))
fs.remove_dir_if_empty(path.versions_dir(name))
end)
local ok, err, errcode = fetch.fetch_and_unpack_rock(rock_file, path.install_dir(name, version))
if not ok then return nil, err, errcode end
local rockspec, err, errcode = fetch.load_rockspec(path.rockspec_file(name, version))
if err then
return nil, "Failed loading rockspec for installed package: "..err, errcode
end
ok, err, errcode = deps.check_external_deps(rockspec, "install")
if err then return nil, err, errcode end
ok, err, errcode = deps.fulfill_dependencies(rockspec)
if err then return nil, err, errcode end
-- For compatibility with .rock files built with LuaRocks 1
if not fs.exists(path.rock_manifest_file(name, version)) then
ok, err = manif.make_rock_manifest(name, version)
if err then return nil, err end
end
ok, err = rep.deploy_files(name, version)
if err then return nil, err end
util.remove_scheduled_function(rollback)
rollback = util.schedule_function(function()
rep.delete_version(name, version)
end)
ok, err = rep.run_hook(rockspec, "post_install")
if err then return nil, err end
ok, err = manif.update_manifest(name, version)
if err then return nil, err end
util.remove_scheduled_function(rollback)
return true
end
--- Driver function for the "install" command.
-- @param name string: name of a binary rock. If an URL or pathname
-- to a binary rock is given, fetches and installs it. If a rockspec or a
-- source rock is given, forwards the request to the "build" command.
-- If a package name is given, forwards the request to "search" and,
-- if returned a result, installs the matching rock.
-- @param version string: When passing a package name, a version number
-- may also be given.
-- @return boolean or (nil, string): True if installation was
-- successful, nil and an error message otherwise.
function run(...)
local flags, name, version = util.parse_flags(...)
if type(name) ~= "string" then
return nil, "Argument missing, see help."
end
if name:match("%.rockspec$") or name:match("%.src%.rock$") then
local build = require("luarocks.build")
return build.run(name)
elseif name:match("%.rock$") then
return install_binary_rock(name)
else
local search = require("luarocks.search")
local results, err = search.find_suitable_rock(search.make_query(name, version))
if err then
return nil, err
elseif type(results) == "string" then
local url = results
print("Installing "..url.."...")
return run(url)
else
print()
print("Could not determine which rock to install.")
print()
print("Search results:")
print("---------------")
search.print_results(results)
return nil, (next(results) and "Please narrow your query." or "No results found.")
end
end
end
|
--- Module implementing the LuaRocks "install" command.
-- Installs binary rocks.
module("luarocks.install", package.seeall)
local path = require("luarocks.path")
local rep = require("luarocks.rep")
local fetch = require("luarocks.fetch")
local util = require("luarocks.util")
local fs = require("luarocks.fs")
local deps = require("luarocks.deps")
local manif = require("luarocks.manif")
local cfg = require("luarocks.cfg")
help_summary = "Install a rock."
help_arguments = "{<rock>|<name> [<version>]}"
help = [[
Argument may be the name of a rock to be fetched from a repository
or a filename of a locally available rock.
]]
--- Install a binary rock.
-- @param rock_file string: local or remote filename of a rock.
-- @return boolean or (nil, string, [string]): True if succeeded or
-- nil and an error message and an optional error code.
function install_binary_rock(rock_file)
assert(type(rock_file) == "string")
local name, version, arch = path.parse_rock_name(rock_file)
if not name then
return nil, "Filename "..rock_file.." does not match format 'name-version-revision.arch.rock'."
end
if arch ~= "all" and arch ~= cfg.arch then
return nil, "Incompatible architecture "..arch, "arch"
end
if rep.is_installed(name, version) then
rep.delete_version(name, version)
end
local rollback = util.schedule_function(function()
fs.delete(path.install_dir(name, version))
fs.remove_dir_if_empty(path.versions_dir(name))
end)
local ok, err, errcode = fetch.fetch_and_unpack_rock(rock_file, path.install_dir(name, version))
if not ok then return nil, err, errcode end
local rockspec, err, errcode = fetch.load_rockspec(path.rockspec_file(name, version))
if err then
return nil, "Failed loading rockspec for installed package: "..err, errcode
end
ok, err, errcode = deps.check_external_deps(rockspec, "install")
if err then return nil, err, errcode end
-- For compatibility with .rock files built with LuaRocks 1
if not fs.exists(path.rock_manifest_file(name, version)) then
ok, err = manif.make_rock_manifest(name, version)
if err then return nil, err end
end
ok, err, errcode = deps.fulfill_dependencies(rockspec)
if err then return nil, err, errcode end
ok, err = rep.deploy_files(name, version)
if err then return nil, err end
util.remove_scheduled_function(rollback)
rollback = util.schedule_function(function()
rep.delete_version(name, version)
end)
ok, err = rep.run_hook(rockspec, "post_install")
if err then return nil, err end
ok, err = manif.update_manifest(name, version)
if err then return nil, err end
util.remove_scheduled_function(rollback)
return true
end
--- Driver function for the "install" command.
-- @param name string: name of a binary rock. If an URL or pathname
-- to a binary rock is given, fetches and installs it. If a rockspec or a
-- source rock is given, forwards the request to the "build" command.
-- If a package name is given, forwards the request to "search" and,
-- if returned a result, installs the matching rock.
-- @param version string: When passing a package name, a version number
-- may also be given.
-- @return boolean or (nil, string): True if installation was
-- successful, nil and an error message otherwise.
function run(...)
local flags, name, version = util.parse_flags(...)
if type(name) ~= "string" then
return nil, "Argument missing, see help."
end
if name:match("%.rockspec$") or name:match("%.src%.rock$") then
local build = require("luarocks.build")
return build.run(name)
elseif name:match("%.rock$") then
return install_binary_rock(name)
else
local search = require("luarocks.search")
local results, err = search.find_suitable_rock(search.make_query(name, version))
if err then
return nil, err
elseif type(results) == "string" then
local url = results
print("Installing "..url.."...")
return run(url)
else
print()
print("Could not determine which rock to install.")
print()
print("Search results:")
print("---------------")
search.print_results(results)
return nil, (next(results) and "Please narrow your query." or "No results found.")
end
end
end
|
fix compatibility with LR1 packages. Bug reported by Graham Wakefield.
|
fix compatibility with LR1 packages. Bug reported by Graham Wakefield.
git-svn-id: b90ab2797f6146e3ba3e3d8b20782c4c2887e809@104 9ca3f7c1-7366-0410-b1a3-b5c78f85698c
|
Lua
|
mit
|
xpol/luainstaller,robooo/luarocks,keplerproject/luarocks,keplerproject/luarocks,xpol/luavm,leafo/luarocks,xpol/luainstaller,usstwxy/luarocks,starius/luarocks,xpol/luarocks,xpol/luavm,lxbgit/luarocks,tst2005/luarocks,aryajur/luarocks,robooo/luarocks,lxbgit/luarocks,tst2005/luarocks,tst2005/luarocks,starius/luarocks,ignacio/luarocks,usstwxy/luarocks,usstwxy/luarocks,coderstudy/luarocks,xpol/luavm,rrthomas/luarocks,tarantool/luarocks,tarantool/luarocks,leafo/luarocks,rrthomas/luarocks,xiaq/luarocks,tarantool/luarocks,luarocks/luarocks,keplerproject/luarocks,robooo/luarocks,luarocks/luarocks,lxbgit/luarocks,robooo/luarocks,aryajur/luarocks,ignacio/luarocks,luarocks/luarocks,rrthomas/luarocks,xpol/luavm,starius/luarocks,aryajur/luarocks,ignacio/luarocks,coderstudy/luarocks,xpol/luarocks,keplerproject/luarocks,aryajur/luarocks,tst2005/luarocks,xiaq/luarocks,starius/luarocks,ignacio/luarocks,xiaq/luarocks,xpol/luainstaller,xpol/luarocks,xpol/luarocks,usstwxy/luarocks,xpol/luavm,xiaq/luarocks,coderstudy/luarocks,lxbgit/luarocks,leafo/luarocks,xpol/luainstaller,coderstudy/luarocks,rrthomas/luarocks
|
e78c4ca80c15dac0bfd836feb36cf92585c093f2
|
src/nodes/trampoline.lua
|
src/nodes/trampoline.lua
|
local sound = require 'vendor/TEsound'
local Gamestate = require 'vendor/gamestate'
local window = require 'window'
local Trampoline = {}
Trampoline.__index = Trampoline
function Trampoline.new(node, collider)
local tramp = {}
setmetatable(tramp, Trampoline)
tramp.bb = collider:addRectangle(node.x, node.y, node.width, node.height)
tramp.node = node
tramp.bb.node = tramp
tramp.bval = node.properties.bval and -(tonumber(node.properties.bval)) or -800
tramp.dbadd = node.properties.dbadd and -(tonumber(node.properties.dbadd)) or -150
tramp.lastBounce = tramp.bval
tramp.blurHeight = 200
tramp.player = nil
tramp.width = 312
tramp.height = 144
tramp.x = node.x
tramp.y = node.y
tramp.whiteout = 0
tramp.foreground = true
collider:setPassive(tramp.bb)
return tramp
end
function Trampoline:collide(player, dt, mtv_x, mtv_y)
if player.character then self.player = player end
if player.position.y + player.height > self.node.y + self.node.height then
sound.playSfx('trampoline_bounce')
player.fall_damage = 0
if self.double_bounce then
player.velocity.y = self.lastBounce + self.dbadd
else
player.velocity.y = self.bval
end
self.lastBounce = player.velocity.y
end
end
function Trampoline:leave()
if not self.player then return end
local player = self.player
player.blur = false
player.freeze = false
self.whiteout = 0
end
function Trampoline:update(dt)
if not self.player then return end
local player = self.player
if player.position.y < -200 then
--transition
player.lives = player.lives + 1
Gamestate.switch('greendale-exterior')
elseif player.position.y < self.blurHeight then
self.whiteout = self.whiteout + 1
player.blur = true
player.freeze = true
player.position.y = player.position.y - 1.3
else
player.blur = false
end
end
function Trampoline:keypressed( button )
if button == 'B' then
self.double_bounce = true
end
end
function Trampoline:collide_end()
self.bounced = false
self.double_bounce = false
end
function Trampoline:draw()
if self.whiteout > 0 then
love.graphics.setColor( 255, 255, 255, math.min( self.whiteout, 255 ) )
love.graphics.rectangle( 'fill', 0, 0, window.width, window.height * 2 )
love.graphics.setColor( 255, 255, 255, 255 )
end
end
return Trampoline
|
local sound = require 'vendor/TEsound'
local Gamestate = require 'vendor/gamestate'
local window = require 'window'
local Trampoline = {}
Trampoline.__index = Trampoline
function Trampoline.new(node, collider)
local tramp = {}
setmetatable(tramp, Trampoline)
tramp.bb = collider:addRectangle(node.x, node.y, node.width, node.height)
tramp.node = node
tramp.bb.node = tramp
tramp.bval = node.properties.bval and -(tonumber(node.properties.bval)) or -800
tramp.dbadd = node.properties.dbadd and -(tonumber(node.properties.dbadd)) or -150
tramp.lastBounce = tramp.bval
tramp.blurHeight = 200
tramp.player = nil
tramp.width = 312
tramp.height = 144
tramp.x = node.x
tramp.y = node.y
tramp.whiteout = 0
tramp.foreground = true
collider:setPassive(tramp.bb)
return tramp
end
function Trampoline:collide(player, dt, mtv_x, mtv_y)
if not player.isPlayer then return end
if player.character then self.player = player end
if player.position.y + player.height > self.node.y + self.node.height then
sound.playSfx('trampoline_bounce')
player.fall_damage = 0
if self.double_bounce then
player.velocity.y = self.lastBounce + self.dbadd
else
player.velocity.y = self.bval
end
self.lastBounce = player.velocity.y
end
end
function Trampoline:leave()
if not self.player then return end
local player = self.player
player.blur = false
player.freeze = false
self.whiteout = 0
end
function Trampoline:update(dt)
if not self.player then return end
local player = self.player
if player.position.y < -200 then
--transition
player.lives = player.lives + 1
Gamestate.switch('greendale-exterior')
elseif player.position.y < self.blurHeight then
self.whiteout = self.whiteout + 1
player.blur = true
player.freeze = true
player.position.y = player.position.y - 1.3
else
player.blur = false
end
end
function Trampoline:keypressed( button )
if button == 'B' then
self.double_bounce = true
end
end
function Trampoline:collide_end()
self.bounced = false
self.double_bounce = false
end
function Trampoline:draw()
if self.whiteout > 0 then
love.graphics.setColor( 255, 255, 255, math.min( self.whiteout, 255 ) )
love.graphics.rectangle( 'fill', 0, 0, window.width, window.height * 2 )
love.graphics.setColor( 255, 255, 255, 255 )
end
end
return Trampoline
|
fix trampoline collision error with nonplayer
|
fix trampoline collision error with nonplayer
|
Lua
|
mit
|
hawkthorne/hawkthorne-client-lua,hawkthorne/hawkthorne-server-lua,hawkthorne/hawkthorne-server-lua,hawkthorne/hawkthorne-client-lua
|
2d926177773f72f4bf3d87b87ac8535ad45341ad
|
aspects/nvim/files/.config/nvim/lua/wincent/cmp/handles.lua
|
aspects/nvim/files/.config/nvim/lua/wincent/cmp/handles.lua
|
-- Custom nvim-cmp source for GitHub handles.
local handles = {}
local registered = false
handles.setup = function()
if registered then
return
end
registered = true
local has_cmp, cmp = pcall(require, 'cmp')
if not has_cmp then
return
end
local config = vim.fn.expand('~/.github-handles.json')
if vim.fn.filereadable(config) == 0 then
return
end
local addresses = vim.fn.json_decode(vim.fn.readfile(config))
local source = {}
source.new = function()
return setmetatable({}, {__index = source})
end
source.get_trigger_characters = function()
return { '@' }
end
source.complete = function(self, request, callback)
local input = string.sub(request.context.cursor_before_line, request.offset - 1)
local prefix = string.sub(request.context.cursor_before_line, 1, request.offset - 1)
if vim.startswith(input, '@') and (prefix == '@' or vim.endswith(prefix, ' @')) then
local items = {}
for handle, address in pairs(addresses) do
table.insert(items, {
filterText = handle .. ' ' .. address,
label = address,
textEdit = {
newText = address,
range = {
start = {
line = request.context.cursor.row - 1,
character = request.context.cursor.col - 1 - #input,
},
['end'] = {
line = request.context.cursor.row - 1,
character = request.context.cursor.col - 1,
},
},
},
}
)
end
callback {
items = items,
isIncomplete = true,
}
else
callback({isIncomplete = true})
end
end
cmp.register_source('handles', source.new())
cmp.setup.filetype('gitcommit', {
sources = cmp.config.sources({
{ name = 'luasnip' },
{ name = 'buffer' },
{ name = 'calc' },
{ name = 'emoji' },
{ name = 'path' },
-- My custom sources.
{ name = 'handles' }, -- GitHub handles; eg. @wincent → Greg Hurrell <[email protected]>
}),
})
end
return handles
|
-- Custom nvim-cmp source for GitHub handles.
local handles = {}
local registered = false
handles.setup = function()
if registered then
return
end
registered = true
local has_cmp, cmp = pcall(require, 'cmp')
if not has_cmp then
return
end
local config = vim.fn.expand('~/.github-handles.json')
if vim.fn.filereadable(config) == 0 then
return
end
local addresses = vim.fn.json_decode(vim.fn.readfile(config))
local source = {}
source.new = function()
return setmetatable({}, {__index = source})
end
source.get_trigger_characters = function()
return { '@' }
end
source.get_keyword_pattern = function()
-- Add dot to existing keyword characters (\k).
return [[\%(\k\|\.\)\+]]
end
source.complete = function(self, request, callback)
local input = string.sub(request.context.cursor_before_line, request.offset - 1)
local prefix = string.sub(request.context.cursor_before_line, 1, request.offset - 1)
if vim.startswith(input, '@') and (prefix == '@' or vim.endswith(prefix, ' @')) then
local items = {}
for handle, address in pairs(addresses) do
table.insert(items, {
filterText = handle .. ' ' .. address,
label = address,
textEdit = {
newText = address,
range = {
start = {
line = request.context.cursor.row - 1,
character = request.context.cursor.col - 1 - #input,
},
['end'] = {
line = request.context.cursor.row - 1,
character = request.context.cursor.col - 1,
},
},
},
}
)
end
callback {
items = items,
isIncomplete = true,
}
else
callback({isIncomplete = true})
end
end
cmp.register_source('handles', source.new())
cmp.setup.filetype('gitcommit', {
sources = cmp.config.sources({
{ name = 'luasnip' },
{ name = 'buffer' },
{ name = 'calc' },
{ name = 'emoji' },
{ name = 'path' },
-- My custom sources.
{ name = 'handles' }, -- GitHub handles; eg. @wincent → Greg Hurrell <[email protected]>
}),
})
end
return handles
|
fix(nvim): add "." to nvim-cmp keyword characters for handle source
|
fix(nvim): add "." to nvim-cmp keyword characters for handle source
So I can type a "." in something like "github.com" without interrupting
autocompletion.
For some reason, this function is _super_ fussy about the exact format
it wants things in. I tried expressing this in a bunch of ways that I
think should be equivalent, but only this one worked (and it was about
the tenth that I tried).
Breaking it down:
[[ Lua: opening string delimiter (ignores escapes).
\%( Vim: start non-capturing group.
\k Vim: keyword character.
\| Vim: alternate operator.
\. Vim: literal dot.
\) Vim: end non-capturing group.
\+ Vim: one-or-more quantifier.
]] Lua: closing string delimiter.
Note that in the `gitcommit` filetype `'iskeyword'` has the default
value of:
iskeyword=@,48-57,_,192-255
(48-57 correspond to 0-9; not sure what 192-255 correspond to.)
|
Lua
|
unlicense
|
wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent
|
68d2a25c225613713bcee83061206387d52c3a94
|
stdlib/area/position.lua
|
stdlib/area/position.lua
|
--- Position module
-- @module position
Position = {}
--- Creates a position that is offset by x,y coordinate pair
-- @param pos the position to offset
-- @param x the amount to offset the position in the x direction
-- @param y the amount to offset the position in the y direction
-- @return a new position, offset by the x,y coordinates
function Position.offset(pos, x, y)
if #pos == 2 then
return { x = pos[1] + x, y = pos[2] + y }
else
return { x = pos.x + x, y = pos.y + y }
end
end
--- Adds 2 positions
-- @param pos1 the first position
-- @param pos2 the second position
-- @return a new position
function Position.add(pos1,pos2)
if #pos1 == 2 then
pos1 = { x = pos1[1], y = pos1[2] }
end
if #pos2 == 2 then
pos2 = { x = pos2[1], y = pos2[2] }
end
return { x = pos1.x + pos2.x, y = pos1.y + pos2.y}
end
--- Subtracts 2 positions
-- @param pos1 the first position
-- @param pos2 the second position
-- @return a new position
function Position.subtract(pos1,pos2)
if #pos1 == 2 then
pos1 = { x = pos1[1], y = pos1[2] }
end
if #pos2 == 2 then
pos2 = { x = pos2[1], y = pos2[2] }
end
return { x = pos1.x - pos2.x, y = pos1.y - pos2.y }
end
--- Translates a position in the given direction
-- @param pos the position to translate
-- @param direction in which direction to translate (see defines.direction)
-- @param distance distance of the translation
-- @return the translated position
function Position.translate(pos, direction, distance)
if direction == defines.direction.north then
return { x = pos.x, y = pos.y - distance }
elseif direction == defines.direction.northeast then
return { x = pos.x + distance, y = pos.y - distance }
elseif direction == defines.direction.east then
return { x = pos.x + distance, y = pos.y }
elseif direction == defines.direction.southeast then
return { x = pos.x + distance, y = pos.y + distance }
elseif direction == defines.direction.south then
return { x = pos.x, y = pos.y + distance }
elseif direction == defines.direction.southwest then
return { x = pos.x - distance, y = pos.y + distance }
elseif direction == defines.direction.west then
return { x = pos.x - distance, y = pos.y }
elseif direction == defines.direction.northwest then
return { x = pos.x - distance, y = pos.y - distance }
end
end
--- Expands a position to a square area usable in surface.find_entities*
-- @param pos the position to expand into an area
-- @param radius half the side length of the area
-- @return a bounding box
function Position.expand_to_area(pos, radius)
if #pos == 2 then
return { left_top = { pos[1] - radius, pos[2] - radius }, right_bottom = { pos[1] + radius, pos[2] + radius } }
end
return { left_top = {pos.x - radius, pos.y - radius}, right_bottom = { pos.x + radius, pos.y + radius } }
end
--- Converts a position to a string
-- @param pos the position to convert
-- @return string representation of pos
function Position.tostring(pos)
if #pos == 2 then
return util.positiontostr({x = pos[1], y = pos[2] })
else
return util.positiontostr(pos)
end
end
|
--- Position module
-- @module position
Position = {}
--- Creates a position that is offset by x,y coordinate pair
-- @param pos the position to offset
-- @param x the amount to offset the position in the x direction
-- @param y the amount to offset the position in the y direction
-- @return a new position, offset by the x,y coordinates
function Position.offset(pos, x, y)
if #pos == 2 then
return { x = pos[1] + x, y = pos[2] + y }
else
return { x = pos.x + x, y = pos.y + y }
end
end
--- Adds 2 positions
-- @param pos1 the first position
-- @param pos2 the second position
-- @return a new position
function Position.add(pos1, pos2)
if #pos1 == 2 then pos1 = Position.to_table(pos1) end
if #pos2 == 2 then pos2 = Position.to_table(pos2) end
return { x = pos1.x + pos2.x, y = pos1.y + pos2.y}
end
--- Subtracts 2 positions
-- @param pos1 the first position
-- @param pos2 the second position
-- @return a new position
function Position.subtract(pos1, pos2)
if #pos1 == 2 then pos1 = Position.to_table(pos1) end
if #pos2 == 2 then pos2 = Position.to_table(pos2) end
return { x = pos1.x - pos2.x, y = pos1.y - pos2.y }
end
--- Translates a position in the given direction
-- @param pos the position to translate
-- @param direction in which direction to translate (see defines.direction)
-- @param distance distance of the translation
-- @return the translated position
function Position.translate(pos, direction, distance)
if #pos == 2 then pos = Position.to_table(pos) end
if direction == defines.direction.north then
return { x = pos.x, y = pos.y - distance }
elseif direction == defines.direction.northeast then
return { x = pos.x + distance, y = pos.y - distance }
elseif direction == defines.direction.east then
return { x = pos.x + distance, y = pos.y }
elseif direction == defines.direction.southeast then
return { x = pos.x + distance, y = pos.y + distance }
elseif direction == defines.direction.south then
return { x = pos.x, y = pos.y + distance }
elseif direction == defines.direction.southwest then
return { x = pos.x - distance, y = pos.y + distance }
elseif direction == defines.direction.west then
return { x = pos.x - distance, y = pos.y }
elseif direction == defines.direction.northwest then
return { x = pos.x - distance, y = pos.y - distance }
end
end
--- Expands a position to a square area
-- @param pos the position to expand into an area
-- @param radius half the side length of the area
-- @return a bounding box
function Position.expand_to_area(pos, radius)
if #pos == 2 then
return { left_top = { pos[1] - radius, pos[2] - radius }, right_bottom = { pos[1] + radius, pos[2] + radius } }
end
return { left_top = {pos.x - radius, pos.y - radius}, right_bottom = { pos.x + radius, pos.y + radius } }
end
--- Converts a position in the array format to a position in the table format
-- @param pos_arr the position to convert
-- @return a converted position, { x = pos_arr[1], y = pos_arr[2] }
function Position.to_table(pos_arr)
return { x = pos_arr[1], y = pos_arr[2] }
end
--- Converts a position to a string
-- @param pos the position to convert
-- @return string representation of pos
function Position.tostring(pos)
if #pos == 2 then
return "Position {x = " .. pos[1] .. ", y = " .. pos[2] .. "}"
else
return "Position {x = " .. pos.x .. ", y = " .. pos.y .. "}"
end
end
|
A bit of cleanup and fix the tostring function
|
A bit of cleanup and fix the tostring function
|
Lua
|
isc
|
Afforess/Factorio-Stdlib
|
6e761a183e520636653d9c2c549e78618f05299c
|
prototype/luamake/example.lua
|
prototype/luamake/example.lua
|
-- Fundamental moss concepts:
-- Artifact: a completed build output (definition vs product)
-- Build Pipeline: a series of build functions that transform definition into product
-- Tool: build function that translats source files or forms products
-- Spore: collection of artifact definitions and build functions
require("lambda")
local clang_debug_tools = lambda { cflags = append("-g") }
local clang_release_tools = lambda { cflags = append("-O3") }
local clang_with_fpu = lambda { cflags = append("-ffpu") }
local debug = lambda { cflags = append("-DDEBUG") }
local fast = lambda { cflags = append("-DLOG_NONE") }
local verbose = lambda { cflags = append("-DLOG_VERBOSE") }
local directory = lambda { forms = append("DIR") }
local staticlib = lambda { forms = append("LIB") }
local executable = lambda { forms = append("EXE") }
local zipfile = lambda { forms = append("ZIP") }
-- Debug build pipeline
local debug_build = build(clang_debug_tools, debug, verbose)
-- Release build pipeline
local release_build = build(clang_release_tools, fast)
math_lib = build(staticlib) {
name = "fastmath.lib";
source = {"math1.c", "math2.c"};
};
main_image = build(executable) {
name = "main.exe";
source = "main.c";
-- main_image requires math_lib within its build
libs = "fastmath";
};
local output = build(directory) {
name = "output";
build(directory, debug_build) {
name = "debug";
math_lib;
main_image;
};
build(directory, release_build) {
name = "release";
main_image;
build(clang_with_fpu)(math_lib);
};
-- In-place build artifact
build(zipfile) {
name = "release.zip";
files = {
-- We can refer to artifacts directly by path
"release/main.exe",
"debug/main.exe",
"help.doc",
"release-notes.txt"
};
};
};
dumpbuild(output)
|
-- Fundamental moss concepts:
-- Artifact: a completed build output (definition vs product)
-- Build Pipeline: a series of build functions that transform definition into product
-- Tool: build function that translats source files or forms products
-- Spore: collection of artifact definitions and build functions
require("lambda")
local clang_debug_tools = lambda { cflags = append("-g") }
local clang_release_tools = lambda { cflags = append("-O3") }
local clang_with_fpu = lambda { cflags = append("-ffpu") }
local debug = lambda { cflags = append("-DDEBUG") }
local fast = lambda { cflags = append("-DLOG_NONE") }
local verbose = lambda { cflags = append("-DLOG_VERBOSE") }
local directory = lambda { forms = append("DIR") }
local staticlib = lambda { forms = append("LIB") }
local executable = lambda { forms = append("EXE") }
local zipfile = lambda { forms = append("ZIP") }
local directory = function(path)
return lambda { name = addprefix(path .. "/") }
end
-- Debug build pipeline
local debug_build = build(clang_debug_tools, debug, verbose)
-- Release build pipeline
local release_build = build(clang_release_tools, fast)
math_lib = build(staticlib) {
name = "fastmath.lib";
source = {"math1.c", "math2.c"};
};
main_image = build(executable) {
name = "main.exe";
source = "main.c";
-- main_image requires math_lib within its build
libs = "fastmath";
};
local output = build(directory("output")) {
build(directory("debug"), debug_build) {
math_lib;
main_image;
};
build(directory("release"), release_build) {
main_image;
build(clang_with_fpu)(math_lib);
};
-- In-place build artifact
build(zipfile) {
name = "release.zip";
files = {
-- We can refer to artifacts directly by path
"release/main.exe",
"debug/main.exe",
"help.doc",
"release-notes.txt"
};
};
};
dumpbuild(output)
|
Implement directory lambda as prefix to name
|
Implement directory lambda as prefix to name
|
Lua
|
mit
|
sjanhunen/moss,sjanhunen/gnumake-molds,sjanhunen/moss
|
b186701be768fafcfd14ae0afd58581086182a38
|
public/lua/oc/commandLoop.lua
|
public/lua/oc/commandLoop.lua
|
function loadPackages()
tcp = require('tcp');
orient = require('trackOrientation');
pos = require('trackPosition');
sendScan = require('sendScan');
scanDirection = require('scanDirection');
mas = require('moveAndScan');
robot = require('robot');
dl = require('downloadCode');
adj = require('adjacent');
dta = require('doToArea');
int = require('interact');
craft = require('craft');
computer = require('computer');
config = require('config');
raw = config.get(config.path).components.raw;
rawBool = (raw == "true" or raw == true) and true or false;
end
loadPackages();
local commandMap = require('commandMap');
function runInTerminal(commandText)
local file = assert(io.popen(commandText, 'r'));
local output = file:read('*all');
file:close();
return output;
end
-- wait until a command exists, grab it, execute it, and send result back
function executeCommand()
local data = tcp.read();
local result = commandMap[data['name']](unpack(data['parameters']));
tcp.write({['command result']={result, result}});
tcp.write({['power level']=computer.energy()/computer.maxEnergy()});
-- for k, v in pairs(data) do
-- if k == 'message' then
-- print(v);
-- end
-- if k == 'command' or k == 'raw command' and rawBool then
-- local command = load(v, nil, 't', _ENV);
-- print(v);
-- local status, result = pcall(command);
-- print(status, result);
-- tcp.write({['command result']={status, result}});
-- tcp.write({['power level']=computer.energy()/computer.maxEnergy()});
-- end
-- end
end
continueLoop = true;
while continueLoop do
if not pcall(executeCommand) then
-- unloading 'computer' breaks stuff, it can't be required again for some reason
-- really we don't need to reload every one of these, but this is easiest
local loadedPackages = {'tcp', 'trackOrientation', 'trackPosition', 'sendScan', 'scanDirection', 'moveAndScan', 'robot', 'downloadCode', 'adjacent', 'doToArea', 'interact', 'craft', 'config'};
for index, p in pairs(loadedPackages) do
package.loaded[p] = nil;
end
-- wait for server to come back up
os.sleep(5);
-- reconnect to server
loadPackages();
end
end
|
function loadPackages()
tcp = require('tcp');
orient = require('trackOrientation');
pos = require('trackPosition');
sendScan = require('sendScan');
scanDirection = require('scanDirection');
mas = require('moveAndScan');
robot = require('robot');
dl = require('downloadCode');
adj = require('adjacent');
dta = require('doToArea');
int = require('interact');
craft = require('craft');
computer = require('computer');
config = require('config');
raw = config.get(config.path).components.raw;
rawBool = (raw == "true" or raw == true) and true or false;
end
loadPackages();
local commandMap = require('commandMap');
function runInTerminal(commandText)
local file = assert(io.popen(commandText, 'r'));
local output = file:read('*all');
file:close();
return output;
end
function unpack (t, i)
i = i or 1;
if t[i] ~= nil then
return t[i], unpack(t, i + 1);
end
end
-- wait until a command exists, grab it, execute it, and send result back
function executeCommand()
local data = tcp.read();
local result = commandMap[data['name']](unpack(data['parameters']));
tcp.write({['command result']={result, result}});
tcp.write({['power level']=computer.energy()/computer.maxEnergy()});
-- for k, v in pairs(data) do
-- if k == 'message' then
-- print(v);
-- end
-- if k == 'command' or k == 'raw command' and rawBool then
-- local command = load(v, nil, 't', _ENV);
-- print(v);
-- local status, result = pcall(command);
-- print(status, result);
-- tcp.write({['command result']={status, result}});
-- tcp.write({['power level']=computer.energy()/computer.maxEnergy()});
-- end
-- end
end
continueLoop = true;
while continueLoop do
if not pcall(executeCommand) then
-- unloading 'computer' breaks stuff, it can't be required again for some reason
-- really we don't need to reload every one of these, but this is easiest
local loadedPackages = {'tcp', 'trackOrientation', 'trackPosition', 'sendScan', 'scanDirection', 'moveAndScan', 'robot', 'downloadCode', 'adjacent', 'doToArea', 'interact', 'craft', 'config'};
for index, p in pairs(loadedPackages) do
package.loaded[p] = nil;
end
-- wait for server to come back up
os.sleep(5);
-- reconnect to server
loadPackages();
end
end
|
apparently this environment doesn't include unpack
|
apparently this environment doesn't include unpack
this should fix the continuous reconnecting problems
|
Lua
|
mit
|
dunstad/roboserver,dunstad/roboserver
|
eed9ccc3836ae19baef59e7b6ed060d760b4f43f
|
Framework/BuildTools/protoc.lua
|
Framework/BuildTools/protoc.lua
|
-- as found on http://lua-users.org/wiki/SplitJoin
local function split(str, delim, maxNb)
-- Eliminate bad cases...
if string.find(str, delim) == nil then
return { str }
end
if maxNb == nil or maxNb < 1 then
maxNb = 0 -- No limit
end
local result = {}
local pat = "(.-)" .. delim .. "()"
local nb = 0
local lastPos
for part, pos in string.gfind(str, pat) do
nb = nb + 1
result[nb] = part
lastPos = pos
if nb == maxNb then break end
end
-- Handle the last field
if nb ~= maxNb then
result[nb + 1] = string.sub(str, lastPos)
end
return result
end
local function getShadowFile(file)
name = path.getname(file)
dir = path.getdirectory(file)
return dir .. "/." .. name .. ".lastCompile~"
end
local function checkRecompileNeeded(file)
file_info = os.stat(file)
shadow_info = os.stat(getShadowFile(file))
if(shadow_info == nil or (file_info ~= nil and file_info.mtime > shadow_info.mtime)) then
print ("INFO: " .. file .. " was changed")
return true
end
return false
end
local function touchShadow(file, time)
local shadowFile = getShadowFile(file)
io.output(shadowFile)
io.write(time)
io.close()
end
local function protocCompile(inputFiles, cppOut, javaOut, pythonOut, ipaths)
-- get the protobuf compiler from the EXTERN_PATH
compiler = "protoc"
if(os.host("windows")) then
compiler = "protoc.exe"
end
-- TODO: should we search on additional locations?
compilerPath = os.pathsearch(compiler, EXTERN_PATH .. "/bin/")
if compilerPath == nil then
compilerPath = os.pathsearch(compiler, EXTERN_PATH_NATIVE .. "/bin/")
end
if compilerPath == nil then
print ("ERROR: could not find protoc compiler executable in \"" .. EXTERN_PATH .. "/bin/" .. "\"")
return false
end
local args = ""
-- hack
args = args .. "--python_out=\"" .. pythonOut .. "\" " -- always mind the space at the end
if(cppOut ~= nil) then
args = args .. "--cpp_out=\"" .. cppOut .. "\" " -- always mind the space at the end
end
if(javaOut ~= nil) then
args = args .. "--java_out=\"" .. javaOut .. "\" " -- always mind the space at the end
end
if(ipaths ~= nil) then
for i=1,#ipaths do
args = args .. "--proto_path=\"" .. ipaths[i] .. "\" " -- always mind the space at the end
end
end
args = args .. table.concat(inputFiles, " ")
local cmd = compilerPath .. "/" .. compiler .. " " .. args
-- HACK: create the output directories if needed
os.mkdir(cppOut)
os.mkdir(javaOut)
-- generate the message files
print("INFO: executing " .. cmd)
local succ, status, returnCode = os.execute(cmd)
if returnCode == 0 then
-- add few lines to suppress the conversion warnings to each of the generated *.cc files
add_gcc_ignore_pragmas(os.matchfiles(cppOut .. "**.pb.cc"))
add_gcc_ignore_pragmas(os.matchfiles(cppOut .. "**.pb.h"))
end
return returnCode == 0
end
function add_gcc_ignore_pragmas(files)
-- add gcc pragma to suppress the conversion warnings to each of the generated *.cc files
-- NOTE: we assume GCC version >= 4.9
local prefix = "// added by NaoTH \n" ..
"#if defined(__GNUC__)\n" ..
"#pragma GCC diagnostic push\n" ..
"#pragma GCC diagnostic ignored \"-Wconversion\"\n" ..
"#pragma GCC diagnostic ignored \"-Wunused-parameter\"\n" ..
"#endif\n\n"
-- restore the previous state at the end
local suffix = "\n\n// added by NaoTH \n" ..
"#if defined(__GNUC__)\n" ..
"#pragma GCC diagnostic pop\n" ..
"#endif\n\n"
for i,v in ipairs(files) do
local f = io.open(v, "r")
if (f == nil) then
print ("ERROR: could not open file \"" .. v)
end
local content = f:read("*all")
f:close()
local f = io.open(v, "w+")
f:write(prefix);
f:write(content);
f:write(suffix);
f:close()
end
end
function invokeprotoc(inputFiles, cppOut, javaOut, pythonOut, ipaths)
-- check if protobuf compile is explicitely requested
local compile = (_OPTIONS["protoc"] ~= nil)
-- iterate over all files to check if any of them was changed
for i = 1, #inputFiles do
if(checkRecompileNeeded(inputFiles[i])) then
compile = true
break
end
end
if(compile) then
-- execute compile process for each file
local time = os.time()
-- do the recompilation
if( protocCompile(inputFiles, cppOut, javaOut, pythonOut, ipaths)) then
-- if successfull touch the shadow files
for i = 1, #inputFiles do
-- touch shadow file in order to remember this build date
touchShadow(inputFiles[i], time)
end -- end for each file to compile
else
print ("ERROR: protoc not successful")
end
end -- end if compile
end
newoption {
trigger = "protoc",
description = "Force to recompile the protbuf messages"
}
newoption {
trigger = "protoc-ipath",
value = "INCLUDE-DIRS",
description = "Include paths seperated by a \":\""
}
newoption {
trigger = "protoc-cpp",
value = "OUT-DIR",
description = "Output directory for the C++ classes generated by protoc"
}
newoption {
trigger = "protoc-java",
value = "OUT-DIR",
description = "Output directory for the Java classes generated by protoc"
}
newoption {
trigger = "protoc-python",
value = "OUT-DIR",
description = "Output directory for the Python classes generated by protoc"
}
-- the action protoc takes the files to compile as argument
-- see also the "protoc-cpp" and "protoc-java" arguments for specifying what kind of file
-- to generate and where to generate them
newaction {
trigger = "protoc",
description = "Compile premake4 messages given as argument",
execute = function ()
invokeprotoc(_ARGS, _OPTIONS["protoc-cpp"], _OPTIONS["protoc-java"], _OPTIONS["protoc-python"], split(_OPTIONS["protoc-ipath"], ":") )
end
}
|
-- as found on http://lua-users.org/wiki/SplitJoin
local function split(str, delim, maxNb)
-- Eliminate bad cases...
if string.find(str, delim) == nil then
return { str }
end
if maxNb == nil or maxNb < 1 then
maxNb = 0 -- No limit
end
local result = {}
local pat = "(.-)" .. delim .. "()"
local nb = 0
local lastPos
for part, pos in string.gfind(str, pat) do
nb = nb + 1
result[nb] = part
lastPos = pos
if nb == maxNb then break end
end
-- Handle the last field
if nb ~= maxNb then
result[nb + 1] = string.sub(str, lastPos)
end
return result
end
local function getShadowFile(file)
name = path.getname(file)
dir = path.getdirectory(file)
return dir .. "/." .. name .. ".lastCompile~"
end
local function checkRecompileNeeded(file)
file_info = os.stat(file)
shadow_info = os.stat(getShadowFile(file))
if(shadow_info == nil or (file_info ~= nil and file_info.mtime > shadow_info.mtime)) then
print ("INFO: " .. file .. " was changed")
return true
end
return false
end
local function touchShadow(file, time)
local shadowFile = getShadowFile(file)
io.output(shadowFile)
io.write(time)
io.close()
end
local function protocCompile(inputFiles, cppOut, javaOut, pythonOut, ipaths)
-- get the protobuf compiler from the EXTERN_PATH
compiler = os.ishost("windows") and "protoc.exe" or "protoc"
-- TODO: should we search on additional locations?
compilerPath = os.pathsearch(compiler, EXTERN_PATH .. "/bin/") or os.pathsearch(compiler, EXTERN_PATH_NATIVE .. "/bin/")
if compilerPath == nil then
print ("ERROR: could not find protoc compiler executable in \"" .. EXTERN_PATH .. "/bin/" .. "\"")
return false
end
local args = ""
-- hack
args = args .. "--python_out=\"" .. pythonOut .. "\" " -- always mind the space at the end
if(cppOut ~= nil) then
args = args .. "--cpp_out=\"" .. cppOut .. "\" " -- always mind the space at the end
end
if(javaOut ~= nil) then
args = args .. "--java_out=\"" .. javaOut .. "\" " -- always mind the space at the end
end
if(ipaths ~= nil) then
for i=1,#ipaths do
args = args .. "--proto_path=\"" .. ipaths[i] .. "\" " -- always mind the space at the end
end
end
args = args .. table.concat(inputFiles, " ")
local cmd = compilerPath .. "/" .. compiler .. " " .. args
-- HACK: create the output directories if needed
os.mkdir(cppOut)
os.mkdir(javaOut)
-- generate the message files
print("INFO: executing " .. cmd)
local succ, status, returnCode = os.execute(cmd)
if returnCode == 0 then
-- add few lines to suppress the conversion warnings to each of the generated *.cc files
add_gcc_ignore_pragmas(os.matchfiles(cppOut .. "**.pb.cc"))
add_gcc_ignore_pragmas(os.matchfiles(cppOut .. "**.pb.h"))
end
return returnCode == 0
end
function add_gcc_ignore_pragmas(files)
-- add gcc pragma to suppress the conversion warnings to each of the generated *.cc files
-- NOTE: we assume GCC version >= 4.9
local prefix = "// added by NaoTH \n" ..
"#if defined(__GNUC__)\n" ..
"#pragma GCC diagnostic push\n" ..
"#pragma GCC diagnostic ignored \"-Wconversion\"\n" ..
"#pragma GCC diagnostic ignored \"-Wunused-parameter\"\n" ..
"#endif\n\n"
-- restore the previous state at the end
local suffix = "\n\n// added by NaoTH \n" ..
"#if defined(__GNUC__)\n" ..
"#pragma GCC diagnostic pop\n" ..
"#endif\n\n"
for i,v in ipairs(files) do
local f = io.open(v, "r")
if (f == nil) then
print ("ERROR: could not open file \"" .. v)
end
local content = f:read("*all")
f:close()
local f = io.open(v, "w+")
f:write(prefix);
f:write(content);
f:write(suffix);
f:close()
end
end
function invokeprotoc(inputFiles, cppOut, javaOut, pythonOut, ipaths)
-- check if protobuf compile is explicitely requested
local compile = (_OPTIONS["protoc"] ~= nil)
-- iterate over all files to check if any of them was changed
for i = 1, #inputFiles do
if(checkRecompileNeeded(inputFiles[i])) then
compile = true
break
end
end
if(compile) then
-- execute compile process for each file
local time = os.time()
-- do the recompilation
if( protocCompile(inputFiles, cppOut, javaOut, pythonOut, ipaths)) then
-- if successfull touch the shadow files
for i = 1, #inputFiles do
-- touch shadow file in order to remember this build date
touchShadow(inputFiles[i], time)
end -- end for each file to compile
else
print ("ERROR: protoc not successful")
end
end -- end if compile
end
newoption {
trigger = "protoc",
description = "Force to recompile the protbuf messages"
}
newoption {
trigger = "protoc-ipath",
value = "INCLUDE-DIRS",
description = "Include paths seperated by a \":\""
}
newoption {
trigger = "protoc-cpp",
value = "OUT-DIR",
description = "Output directory for the C++ classes generated by protoc"
}
newoption {
trigger = "protoc-java",
value = "OUT-DIR",
description = "Output directory for the Java classes generated by protoc"
}
newoption {
trigger = "protoc-python",
value = "OUT-DIR",
description = "Output directory for the Python classes generated by protoc"
}
-- the action protoc takes the files to compile as argument
-- see also the "protoc-cpp" and "protoc-java" arguments for specifying what kind of file
-- to generate and where to generate them
newaction {
trigger = "protoc",
description = "Compile premake5 messages given as argument",
execute = function ()
invokeprotoc(_ARGS, _OPTIONS["protoc-cpp"], _OPTIONS["protoc-java"], _OPTIONS["protoc-python"], split(_OPTIONS["protoc-ipath"], ":") )
end
}
|
small fix does work for linux
|
small fix
does work for linux
|
Lua
|
apache-2.0
|
BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH
|
93547ac94797cdea6670b0d458e838bcdb578f77
|
src/lua-factory/sources/grl-radiofrance.lua
|
src/lua-factory/sources/grl-radiofrance.lua
|
--[[
* Copyright (C) 2014 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
*
--]]
local stations = { 'franceinter', 'franceinfo', 'franceculture', 'francemusique', 'fipradio', 'lemouv' }
---------------------------
-- Source initialization --
---------------------------
source = {
id = "grl-radiofrance-lua",
name = "Radio France",
description = "A source for browsing Radio France radio stations",
supported_keys = { "id", "thumbnail", "title", "url", "mime-type" },
icon = 'resource:///org/gnome/grilo/plugins/radiofrance/radiofrance.png',
supported_media = 'audio',
tags = { 'radio', 'country:fr', 'net:internet', 'net:plaintext' }
}
------------------
-- Source utils --
------------------
function grl_source_browse(media_id)
if grl.get_options("skip") > 0 then
grl.callback()
else
local urls = {}
for index, item in pairs(stations) do
local url = 'http://www.' .. item .. '.fr/player'
table.insert(urls, url)
end
grl.fetch(urls, "radiofrance_now_fetch_cb")
end
end
------------------------
-- Callback functions --
------------------------
-- return all the media found
function radiofrance_now_fetch_cb(results)
for index, result in pairs(results) do
local media = create_media(stations[index], result)
grl.callback(media, -1)
end
grl.callback()
end
-------------
-- Helpers --
-------------
function get_thumbnail(id)
local images = {}
images['franceinter'] = 'http://www.franceinter.fr/sites/all/themes/franceinter/logo.png'
images['franceinfo'] = 'http://www.franceinfo.fr/sites/all/themes/custom/france_info/logo.png'
images['franceculture'] = 'http://www.franceculture.fr/sites/all/themes/franceculture/images/logo.png'
images['francemusique'] = 'http://www.francemusique.fr/sites/all/themes/custom/france_musique/logo.png'
images['fipradio'] = 'http://www.fipradio.fr/sites/all/themes/custom/fip/logo.png'
images['lemouv'] = 'http://www.lemouv.fr/sites/all/themes/mouv/images/logo_119x119.png'
return images[id]
end
function get_title(id)
local names = {}
names['franceinter'] = 'France Inter'
names['franceinfo'] = 'France Info'
names['franceculture'] = 'France Culture'
names['francemusique'] = 'France Musique'
names['fipradio'] = 'Fip Radio'
names['lemouv'] = "Le Mouv'"
return names[id]
end
function create_media(id, result)
local media = {}
media.type = "audio"
media.mime_type = "audio/mpeg"
media.id = id
if media.id == 'fipradio' then
media.id = 'fip'
end
media.url = result:match("liveUrl: '(.-)',")
if not media.url then
media.url = result:match('"player" href="(http.-%.mp3)')
end
media.title = get_title(id)
media.thumbnail = get_thumbnail(id)
-- FIXME Add metadata about the currently playing tracks
-- Available in 'http://www.' .. item .. '.fr/api/now&full=true'
return media
end
|
--[[
* Copyright (C) 2014 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
*
--]]
local stations = { 'franceinter', 'franceinfo', 'franceculture', 'francemusique', 'fipradio', 'lemouv' }
---------------------------
-- Source initialization --
---------------------------
source = {
id = "grl-radiofrance-lua",
name = "Radio France",
description = "A source for browsing Radio France radio stations",
supported_keys = { "id", "thumbnail", "title", "url", "mime-type" },
icon = 'resource:///org/gnome/grilo/plugins/radiofrance/radiofrance.png',
supported_media = 'audio',
tags = { 'radio', 'country:fr', 'net:internet', 'net:plaintext' }
}
------------------
-- Source utils --
------------------
function grl_source_browse(media, options, callback)
if options.skip > 0 then
callback()
else
local urls = {}
for index, item in pairs(stations) do
local url = 'http://www.' .. item .. '.fr/player'
table.insert(urls, url)
end
grl.fetch(urls, radiofrance_now_fetch_cb, callback)
end
end
------------------------
-- Callback functions --
------------------------
-- return all the media found
function radiofrance_now_fetch_cb(results, callback)
for index, result in pairs(results) do
local media = create_media(stations[index], result)
callback(media, -1)
end
callback()
end
-------------
-- Helpers --
-------------
function get_thumbnail(id)
local images = {}
images['franceinter'] = 'http://www.franceinter.fr/sites/all/themes/franceinter/logo.png'
images['franceinfo'] = 'http://www.franceinfo.fr/sites/all/themes/custom/france_info/logo.png'
images['franceculture'] = 'http://www.franceculture.fr/sites/all/themes/franceculture/images/logo.png'
images['francemusique'] = 'http://www.francemusique.fr/sites/all/themes/custom/france_musique/logo.png'
images['fipradio'] = 'http://www.fipradio.fr/sites/all/themes/custom/fip/logo.png'
images['lemouv'] = 'http://www.lemouv.fr/sites/all/themes/mouv/images/logo_119x119.png'
return images[id]
end
function get_title(id)
local names = {}
names['franceinter'] = 'France Inter'
names['franceinfo'] = 'France Info'
names['franceculture'] = 'France Culture'
names['francemusique'] = 'France Musique'
names['fipradio'] = 'Fip Radio'
names['lemouv'] = "Le Mouv'"
return names[id]
end
function create_media(id, result)
local media = {}
media.type = "audio"
media.mime_type = "audio/mpeg"
media.id = id
if media.id == 'fipradio' then
media.id = 'fip'
end
media.url = result:match("liveUrl: '(.-)',")
if not media.url then
media.url = result:match('"player" href="(http.-%.mp3)')
end
media.title = get_title(id)
media.thumbnail = get_thumbnail(id)
-- FIXME Add metadata about the currently playing tracks
-- Available in 'http://www.' .. item .. '.fr/api/now&full=true'
return media
end
|
lua-factory: port grl-radiofrance.lua to the new lua system
|
lua-factory: port grl-radiofrance.lua to the new lua system
https://bugzilla.gnome.org/show_bug.cgi?id=753141
Acked-by: Victor Toso <[email protected]>
|
Lua
|
lgpl-2.1
|
MikePetullo/grilo-plugins,MikePetullo/grilo-plugins,grilofw/grilo-plugins,MikePetullo/grilo-plugins,jasuarez/grilo-plugins,GNOME/grilo-plugins,grilofw/grilo-plugins,GNOME/grilo-plugins,jasuarez/grilo-plugins
|
7009e98ee801bbe7a389f38f30ef937dd567a08b
|
frontend/device/pocketbook/device.lua
|
frontend/device/pocketbook/device.lua
|
local Generic = require("device/generic/device") -- <= look at this file!
local logger = require("logger")
-- luacheck: push
-- luacheck: ignore
local EVT_INIT = 21
local EVT_EXIT = 22
local EVT_SHOW = 23
local EVT_REPAINT = 23
local EVT_HIDE = 24
local EVT_KEYDOWN = 25
local EVT_KEYPRESS = 25
local EVT_KEYUP = 26
local EVT_KEYRELEASE = 26
local EVT_KEYREPEAT = 28
local EVT_FOREGROUND = 151
local EVT_BACKGROUND = 152
local KEY_POWER = 0x01
local KEY_DELETE = 0x08
local KEY_OK = 0x0a
local KEY_UP = 0x11
local KEY_DOWN = 0x12
local KEY_LEFT = 0x13
local KEY_RIGHT = 0x14
local KEY_MINUS = 0x15
local KEY_PLUS = 0x16
local KEY_MENU = 0x17
local KEY_PREV = 0x18
local KEY_NEXT = 0x19
local KEY_HOME = 0x1a
local KEY_BACK = 0x1b
local KEY_PREV2 = 0x1c
local KEY_NEXT2 = 0x1d
local KEY_COVEROPEN = 0x02
local KEY_COVERCLOSE = 0x03
-- luacheck: pop
local function yes() return true end
local function pocketbookEnableWifi(toggle)
os.execute("/ebrmain/bin/netagent " .. (toggle == 1 and "connect" or "disconnect"))
end
local PocketBook = Generic:new{
model = "PocketBook",
isPocketBook = yes,
isInBackGround = false,
}
function PocketBook:init()
self.input:registerEventAdjustHook(function(_input, ev)
if ev.type == EVT_KEYDOWN or ev.type == EVT_KEYUP then
ev.code = ev.code
ev.value = ev.type == EVT_KEYDOWN and 1 or 0
ev.type = 1 -- EV_KEY
elseif ev.type == EVT_BACKGROUND then
self.isInBackGround = true
self:onPowerEvent("Power")
elseif self.isInBackGround and ev.type == EVT_FOREGROUND then
self.isInBackGround = false
self:onPowerEvent("Power")
elseif ev.type == EVT_EXIT then
-- auto shutdown event from inkview framework, gracefully close
-- everything and let the framework shutdown the device
require("ui/uimanager"):broadcastEvent(
require("ui/event"):new("Close"))
elseif not self.isInBackGround and ev.type == EVT_FOREGROUND then
self.screen:refreshPartial()
end
end)
os.remove(self.emu_events_dev)
os.execute("mkfifo " .. self.emu_events_dev)
self.input.open(self.emu_events_dev, 1)
Generic.init(self)
end
function PocketBook: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("date -s '%d-%d-%d %d:%d:%d'", year, month, day, hour, min, sec)
else
command = string.format("date -s '%d:%d'",hour, min)
end
if os.execute(command) == 0 then
os.execute('hwclock -u -w')
return true
else
return false
end
end
function PocketBook:initNetworkManager(NetworkMgr)
NetworkMgr.turnOnWifi = function()
pocketbookEnableWifi(1)
end
NetworkMgr.turnOffWifi = function()
pocketbookEnableWifi(0)
end
end
local PocketBook840 = PocketBook:new{
isTouchDevice = yes,
hasKeys = yes,
hasFrontlight = yes,
display_dpi = 250,
emu_events_dev = "/var/dev/shm/emu_events",
}
function PocketBook840:init()
self.screen = require("ffi/framebuffer_mxcfb"):new{device = self, debug = logger.dbg}
self.powerd = require("device/pocketbook/powerd"):new{device = self}
self.input = require("device/input"):new{
device = self,
event_map = {
[24] = "LPgBack",
[25] = "LPgFwd",
[1002] = "Power",
}
}
PocketBook.init(self)
end
-- should check device model before return to support other PocketBook models
return PocketBook840
|
local Generic = require("device/generic/device") -- <= look at this file!
local logger = require("logger")
local ffi = require("ffi")
local inkview = ffi.load("inkview")
-- luacheck: push
-- luacheck: ignore
local EVT_INIT = 21
local EVT_EXIT = 22
local EVT_SHOW = 23
local EVT_REPAINT = 23
local EVT_HIDE = 24
local EVT_KEYDOWN = 25
local EVT_KEYPRESS = 25
local EVT_KEYUP = 26
local EVT_KEYRELEASE = 26
local EVT_KEYREPEAT = 28
local EVT_FOREGROUND = 151
local EVT_BACKGROUND = 152
local KEY_POWER = 0x01
local KEY_DELETE = 0x08
local KEY_OK = 0x0a
local KEY_UP = 0x11
local KEY_DOWN = 0x12
local KEY_LEFT = 0x13
local KEY_RIGHT = 0x14
local KEY_MINUS = 0x15
local KEY_PLUS = 0x16
local KEY_MENU = 0x17
local KEY_PREV = 0x18
local KEY_NEXT = 0x19
local KEY_HOME = 0x1a
local KEY_BACK = 0x1b
local KEY_PREV2 = 0x1c
local KEY_NEXT2 = 0x1d
local KEY_COVEROPEN = 0x02
local KEY_COVERCLOSE = 0x03
-- luacheck: pop
ffi.cdef[[
char *GetSoftwareVersion(void);
char *GetDeviceModel(void);
]]
local function yes() return true end
local function pocketbookEnableWifi(toggle)
os.execute("/ebrmain/bin/netagent " .. (toggle == 1 and "connect" or "disconnect"))
end
local PocketBook = Generic:new{
model = "PocketBook",
isPocketBook = yes,
isInBackGround = false,
}
function PocketBook:init()
self.input:registerEventAdjustHook(function(_input, ev)
if ev.type == EVT_KEYDOWN or ev.type == EVT_KEYUP then
ev.code = ev.code
ev.value = ev.type == EVT_KEYDOWN and 1 or 0
ev.type = 1 -- EV_KEY
elseif ev.type == EVT_BACKGROUND then
self.isInBackGround = true
self:onPowerEvent("Power")
elseif self.isInBackGround and ev.type == EVT_FOREGROUND then
self.isInBackGround = false
self:onPowerEvent("Power")
elseif ev.type == EVT_EXIT then
-- auto shutdown event from inkview framework, gracefully close
-- everything and let the framework shutdown the device
require("ui/uimanager"):broadcastEvent(
require("ui/event"):new("Close"))
elseif not self.isInBackGround and ev.type == EVT_FOREGROUND then
self.screen:refreshPartial()
end
end)
os.remove(self.emu_events_dev)
os.execute("mkfifo " .. self.emu_events_dev)
self.input.open(self.emu_events_dev, 1)
Generic.init(self)
end
function PocketBook: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("date -s '%d-%d-%d %d:%d:%d'", year, month, day, hour, min, sec)
else
command = string.format("date -s '%d:%d'",hour, min)
end
if os.execute(command) == 0 then
os.execute('hwclock -u -w')
return true
else
return false
end
end
function PocketBook:initNetworkManager(NetworkMgr)
NetworkMgr.turnOnWifi = function()
pocketbookEnableWifi(1)
end
NetworkMgr.turnOffWifi = function()
pocketbookEnableWifi(0)
end
end
function PocketBook:getSoftwareVersion()
return ffi.string(inkview.GetSoftwareVersion())
end
function PocketBook:getDeviceModel()
return ffi.string(inkview.GetDeviceModel())
end
-- PocketBook InkPad
local PocketBook840 = PocketBook:new{
isTouchDevice = yes,
hasKeys = yes,
hasFrontlight = yes,
display_dpi = 250,
emu_events_dev = "/var/dev/shm/emu_events",
}
-- PocketBook HD Touch
local PocketBook631 = PocketBook:new{
isTouchDevice = yes,
hasKeys = yes,
hasFrontlight = yes,
display_dpi = 300,
emu_events_dev = "/dev/shm/emu_events",
}
function PocketBook840:init()
self.screen = require("ffi/framebuffer_mxcfb"):new{device = self, debug = logger.dbg}
self.powerd = require("device/pocketbook/powerd"):new{device = self}
self.input = require("device/input"):new{
device = self,
event_map = {
[24] = "LPgBack",
[25] = "LPgFwd",
[1002] = "Power",
}
}
PocketBook.init(self)
end
function PocketBook631:init()
self.screen = require("ffi/framebuffer_mxcfb"):new{device = self, debug = logger.dbg}
self.powerd = require("device/pocketbook/powerd"):new{device = self}
self.input = require("device/input"):new{
device = self,
event_map = {
[23] = "Menu",
[24] = "LPgBack",
[25] = "LPgFwd",
[1002] = "Power",
}
}
PocketBook.init(self)
end
logger.info('SoftwareVersion: ', PocketBook:getSoftwareVersion())
local codename = PocketBook:getDeviceModel()
if codename == "PocketBook 840" then
return PocketBook840
elseif codename == "PB631" then
return PocketBook631
else
error("unrecognized PocketBook model " .. codename)
end
|
PocketBook: Basic device-detection / PocketBook631 (Touch HD) support (#3403)
|
PocketBook: Basic device-detection / PocketBook631 (Touch HD) support (#3403)
Add basic device-detection via libinkview, support PocketBook631. Fixes https://github.com/koreader/koreader/issues/3312
|
Lua
|
agpl-3.0
|
mwoz123/koreader,koreader/koreader,houqp/koreader,NiLuJe/koreader,mihailim/koreader,pazos/koreader,koreader/koreader,poire-z/koreader,poire-z/koreader,NiLuJe/koreader,lgeek/koreader,Frenzie/koreader,apletnev/koreader,Frenzie/koreader,Hzj-jie/koreader,Markismus/koreader
|
5bd288e378584e51bc88d859b72621b59b72e9f7
|
spec/unit/readerview_spec.lua
|
spec/unit/readerview_spec.lua
|
describe("Readerview module", function()
local DocumentRegistry, Blitbuffer, ReaderUI, UIManager, Event
setup(function()
require("commonrequire")
package.unloadAll()
DocumentRegistry = require("document/documentregistry")
Blitbuffer = require("ffi/blitbuffer")
ReaderUI = require("apps/reader/readerui")
UIManager = require("ui/uimanager")
Event = require("ui/event")
end)
it("should stop hinting on document close event", function()
local sample_epub = "spec/front/unit/data/leaves.epub"
local readerui = ReaderUI:new{
document = DocumentRegistry:openDocument(sample_epub),
}
for i = #UIManager._task_queue, 1, -1 do
local task = UIManager._task_queue[i]
if task.action == readerui.view.emitHintPageEvent then
error("UIManager's task queue should be emtpy.")
end
end
local bb = Blitbuffer.new(1000, 1000)
readerui.view:drawSinglePage(bb, 0, 0)
local found = false
for i = #UIManager._task_queue, 1, -1 do
local task = UIManager._task_queue[i]
if task.action == readerui.view.emitHintPageEvent then
found = true
end
end
assert.is.truthy(found)
readerui:onClose()
assert.is.falsy(readerui.view.hinting)
for i = #UIManager._task_queue, 1, -1 do
local task = UIManager._task_queue[i]
if task.action == readerui.view.emitHintPageEvent then
error("UIManager's task queue should be emtpy.")
end
end
end)
it("should return and restore view context in page mode", function()
local sample_pdf = "spec/front/unit/data/2col.pdf"
local readerui = ReaderUI:new{
document = DocumentRegistry:openDocument(sample_pdf),
}
readerui:handleEvent(Event:new("SetScrollMode", false))
readerui.zooming:setZoomMode("page")
local view = readerui.view
local ctx = view:getViewContext()
local zoom = ctx[1].zoom
ctx[1].zoom = nil
local saved_ctx = {
{
page = 1,
pos = 0,
gamma = 1,
offset = {
x = 17, y = 0,
h = 0, w = 0,
},
rotation = 0,
},
-- visible_area
{
x = 0, y = 0,
h = 800, w = 566,
},
-- page_area
{
x = 0, y = 0,
h = 800, w = 566,
},
}
assert.are.same(saved_ctx, ctx)
assertAlmostEquals(zoom, 0.95011876484561, 0.0001)
assert.is.same(view.state.page, 1)
assert.is.same(view.visible_area.x, 0)
assert.is.same(view.visible_area.y, 0)
saved_ctx[1].page = 2
saved_ctx[1].zoom = zoom
saved_ctx[2].y = 10
view:restoreViewContext(saved_ctx)
assert.is.same(view.state.page, 2)
assert.is.same(view.visible_area.x, 0)
assert.is.same(view.visible_area.y, 10)
end)
it("should return and restore view context in scroll mode", function()
local sample_pdf = "spec/front/unit/data/2col.pdf"
local readerui = ReaderUI:new{
document = DocumentRegistry:openDocument(sample_pdf),
}
readerui:handleEvent(Event:new("SetScrollMode", true))
readerui.zooming:setZoomMode("page")
local view = readerui.view
local ctx = view:getViewContext()
local zoom = ctx[1].zoom
ctx[1].zoom = nil
local saved_ctx = {
{
gamma = 1,
offset = {x = 17, y = 0},
page = 1,
page_area = {
h = 800,
w = 566,
x = 0,
y = 0,
},
rotation = 0,
visible_area = {
h = 800,
w = 566,
x = 0,
y = 0,
},
},
}
assert.are.same(saved_ctx, ctx)
assertAlmostEquals(zoom, 0.95011876484561, 0.0001)
assert.is.same(view.state.page, 1)
assert.is.same(view.visible_area.x, 0)
assert.is.same(view.visible_area.y, 0)
saved_ctx[1].page = 2
saved_ctx[1].zoom = zoom
saved_ctx[1].visible_area.y = 10
view:restoreViewContext(saved_ctx)
assert.is.same(#view.page_states, 1)
assert.is.same(view.page_states[1].page, 2)
assert.is.same(view.page_states[1].visible_area.x, 0)
assert.is.same(view.page_states[1].visible_area.y, 10)
end)
end)
|
describe("Readerview module", function()
local DocumentRegistry, Blitbuffer, ReaderUI, UIManager, Event
setup(function()
require("commonrequire")
package.unloadAll()
DocumentRegistry = require("document/documentregistry")
Blitbuffer = require("ffi/blitbuffer")
ReaderUI = require("apps/reader/readerui")
UIManager = require("ui/uimanager")
Event = require("ui/event")
end)
it("should stop hinting on document close event", function()
local sample_epub = "spec/front/unit/data/leaves.epub"
local readerui = ReaderUI:new{
document = DocumentRegistry:openDocument(sample_epub),
}
for i = #UIManager._task_queue, 1, -1 do
local task = UIManager._task_queue[i]
if task.action == readerui.view.emitHintPageEvent then
error("UIManager's task queue should be emtpy.")
end
end
local bb = Blitbuffer.new(1000, 1000)
readerui.view:drawSinglePage(bb, 0, 0)
local found = false
for i = #UIManager._task_queue, 1, -1 do
local task = UIManager._task_queue[i]
if task.action == readerui.view.emitHintPageEvent then
found = true
end
end
assert.is.truthy(found)
readerui:onClose()
assert.is.falsy(readerui.view.hinting)
for i = #UIManager._task_queue, 1, -1 do
local task = UIManager._task_queue[i]
if task.action == readerui.view.emitHintPageEvent then
error("UIManager's task queue should be emtpy.")
end
end
end)
-- TODO FIX THESE TESTS THEY'RE BROKEN!!!
it("should return and restore view context in page mode #notest", function()
local sample_pdf = "spec/front/unit/data/2col.pdf"
local readerui = ReaderUI:new{
document = DocumentRegistry:openDocument(sample_pdf),
}
readerui:handleEvent(Event:new("SetScrollMode", false))
readerui.zooming:setZoomMode("page")
local view = readerui.view
local ctx = view:getViewContext()
local zoom = ctx[1].zoom
ctx[1].zoom = nil
local saved_ctx = {
{
page = 1,
pos = 0,
gamma = 1,
offset = {
x = 17, y = 0,
h = 0, w = 0,
},
rotation = 0,
},
-- visible_area
{
x = 0, y = 0,
h = 800, w = 566,
},
-- page_area
{
x = 0, y = 0,
h = 800, w = 566,
},
}
assert.are.same(saved_ctx, ctx)
assertAlmostEquals(zoom, 0.95011876484561, 0.0001)
assert.is.same(view.state.page, 1)
assert.is.same(view.visible_area.x, 0)
assert.is.same(view.visible_area.y, 0)
saved_ctx[1].page = 2
saved_ctx[1].zoom = zoom
saved_ctx[2].y = 10
view:restoreViewContext(saved_ctx)
assert.is.same(view.state.page, 2)
assert.is.same(view.visible_area.x, 0)
assert.is.same(view.visible_area.y, 10)
end)
it("should return and restore view context in scroll mode #notest", function()
local sample_pdf = "spec/front/unit/data/2col.pdf"
local readerui = ReaderUI:new{
document = DocumentRegistry:openDocument(sample_pdf),
}
readerui:handleEvent(Event:new("SetScrollMode", true))
readerui.zooming:setZoomMode("page")
local view = readerui.view
local ctx = view:getViewContext()
local zoom = ctx[1].zoom
ctx[1].zoom = nil
local saved_ctx = {
{
gamma = 1,
offset = {x = 17, y = 0},
page = 1,
page_area = {
h = 800,
w = 566,
x = 0,
y = 0,
},
rotation = 0,
visible_area = {
h = 800,
w = 566,
x = 0,
y = 0,
},
},
}
assert.are.same(saved_ctx, ctx)
assertAlmostEquals(zoom, 0.95011876484561, 0.0001)
assert.is.same(view.state.page, 1)
assert.is.same(view.visible_area.x, 0)
assert.is.same(view.visible_area.y, 0)
saved_ctx[1].page = 2
saved_ctx[1].zoom = zoom
saved_ctx[1].visible_area.y = 10
view:restoreViewContext(saved_ctx)
assert.is.same(#view.page_states, 1)
assert.is.same(view.page_states[1].page, 2)
assert.is.same(view.page_states[1].visible_area.x, 0)
assert.is.same(view.page_states[1].visible_area.y, 10)
end)
end)
|
[fix] #nocov on broken scroll mode tests
|
[fix] #nocov on broken scroll mode tests
|
Lua
|
agpl-3.0
|
Frenzie/koreader,mwoz123/koreader,poire-z/koreader,mihailim/koreader,Frenzie/koreader,pazos/koreader,apletnev/koreader,lgeek/koreader,Hzj-jie/koreader,NiLuJe/koreader,koreader/koreader,Markismus/koreader,koreader/koreader,poire-z/koreader,houqp/koreader,NiLuJe/koreader
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.